Search in sources :

Example 1 with SendCommandEvent

use of org.spongepowered.api.event.command.SendCommandEvent in project SpongeCommon by SpongePowered.

the class SpongeCommandManager method process.

@Override
public CommandResult process(CommandSource source, String commandLine) {
    final String[] argSplit = commandLine.split(" ", 2);
    Sponge.getCauseStackManager().pushCause(source);
    final SendCommandEvent event = SpongeEventFactory.createSendCommandEvent(Sponge.getCauseStackManager().getCurrentCause(), argSplit.length > 1 ? argSplit[1] : "", argSplit[0], CommandResult.empty());
    Sponge.getGame().getEventManager().post(event);
    Sponge.getCauseStackManager().popCause();
    if (event.isCancelled()) {
        return event.getResult();
    }
    // Only the first part of argSplit is used at the moment, do the other in the future if needed.
    argSplit[0] = event.getCommand();
    commandLine = event.getCommand();
    if (!event.getArguments().isEmpty()) {
        commandLine = commandLine + ' ' + event.getArguments();
    }
    try {
        try (StackFrame frame = Sponge.getCauseStackManager().pushCauseFrame();
            // Since we know we are in the main thread, this is safe to do without a thread check
            CommandPhaseContext context = GeneralPhase.State.COMMAND.createPhaseContext().source(source).addCaptures().addEntityDropCaptures().buildAndSwitch()) {
            if (source instanceof EntityPlayer) {
                // Enable player inventory capture
                ((IMixinInventoryPlayer) ((EntityPlayer) source).inventory).setCapture(true);
            }
            Sponge.getCauseStackManager().pushCause(source);
            final CommandResult result = this.dispatcher.process(source, commandLine);
            return result;
        } catch (InvocationCommandException ex) {
            if (ex.getCause() != null) {
                throw ex.getCause();
            }
        } catch (CommandPermissionException ex) {
            Text text = ex.getText();
            if (text != null) {
                source.sendMessage(error(text));
            }
        } catch (CommandException ex) {
            Text text = ex.getText();
            if (text != null) {
                source.sendMessage(error(text));
            }
            if (ex.shouldIncludeUsage()) {
                final Optional<CommandMapping> mapping = this.dispatcher.get(argSplit[0], source);
                if (mapping.isPresent()) {
                    Text usage;
                    if (ex instanceof ArgumentParseException.WithUsage) {
                        usage = ((ArgumentParseException.WithUsage) ex).getUsage();
                    } else {
                        usage = mapping.get().getCallable().getUsage(source);
                    }
                    source.sendMessage(error(t("Usage: /%s %s", argSplit[0], usage)));
                }
            }
        }
    } catch (Throwable thr) {
        Text.Builder excBuilder;
        if (thr instanceof TextMessageException) {
            Text text = ((TextMessageException) thr).getText();
            excBuilder = text == null ? Text.builder("null") : Text.builder();
        } else {
            excBuilder = Text.builder(String.valueOf(thr.getMessage()));
        }
        if (source.hasPermission("sponge.debug.hover-stacktrace")) {
            final StringWriter writer = new StringWriter();
            thr.printStackTrace(new PrintWriter(writer));
            excBuilder.onHover(TextActions.showText(Text.of(writer.toString().replace("\t", "    ").replace("\r\n", "\n").replace("\r", // I mean I guess somebody could be running this on like OS 9?
            "\n"))));
        }
        source.sendMessage(error(t("Error occurred while executing command: %s", excBuilder.build())));
        this.logger.error(TextSerializers.PLAIN.serialize(t("Error occurred while executing command '%s' for source %s: %s", commandLine, source.toString(), String.valueOf(thr.getMessage()))), thr);
    }
    return CommandResult.empty();
}
Also used : CommandPermissionException(org.spongepowered.api.command.CommandPermissionException) Optional(java.util.Optional) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) Text(org.spongepowered.api.text.Text) InvocationCommandException(org.spongepowered.api.command.InvocationCommandException) CommandException(org.spongepowered.api.command.CommandException) CommandResult(org.spongepowered.api.command.CommandResult) IMixinInventoryPlayer(org.spongepowered.common.interfaces.entity.player.IMixinInventoryPlayer) InvocationCommandException(org.spongepowered.api.command.InvocationCommandException) StringWriter(java.io.StringWriter) CommandPhaseContext(org.spongepowered.common.event.tracking.phase.general.CommandPhaseContext) StackFrame(org.spongepowered.api.event.CauseStackManager.StackFrame) SendCommandEvent(org.spongepowered.api.event.command.SendCommandEvent) EntityPlayer(net.minecraft.entity.player.EntityPlayer) TextMessageException(org.spongepowered.api.util.TextMessageException) PrintWriter(java.io.PrintWriter)

Example 2 with SendCommandEvent

use of org.spongepowered.api.event.command.SendCommandEvent in project LanternServer by LanternPowered.

the class LanternCommandManager method process.

@Override
public CommandResult process(CommandSource source, String commandLine) {
    checkNotNull(source, "source");
    final String[] argSplit = commandLine.split(" ", 2);
    final CauseStack causeStack = CauseStack.currentOrEmpty();
    try (CauseStack.Frame frame = causeStack.pushCauseFrame()) {
        frame.pushCause(source);
        final SendCommandEvent event = SpongeEventFactory.createSendCommandEvent(frame.getCurrentCause(), argSplit.length > 1 ? argSplit[1] : "", argSplit[0], CommandResult.empty());
        Sponge.getGame().getEventManager().post(event);
        if (event.isCancelled()) {
            return event.getResult();
        }
        // Only the first part of argSplit is used at the moment, do the other in the future if needed.
        argSplit[0] = event.getCommand();
        commandLine = event.getCommand();
        if (!event.getArguments().isEmpty()) {
            commandLine = commandLine + ' ' + event.getArguments();
        }
        try {
            return this.dispatcher.process(source, commandLine);
        } catch (InvocationCommandException ex) {
            if (ex.getCause() != null) {
                throw ex.getCause();
            }
        } catch (CommandPermissionException ex) {
            Text text = ex.getText();
            if (text != null) {
                source.sendMessage(error(text));
            }
        } catch (CommandException ex) {
            Text text = ex.getText();
            if (text != null) {
                source.sendMessage(error(text));
            }
            if (ex.shouldIncludeUsage()) {
                final Optional<CommandMapping> mapping = this.dispatcher.get(argSplit[0], source);
                mapping.ifPresent(commandMapping -> source.sendMessage(error(t("commands.generic.usage", t("/%s %s", argSplit[0], commandMapping.getCallable().getUsage(source))))));
            }
        }
    } catch (Throwable thr) {
        final Text.Builder excBuilder;
        if (thr instanceof TextMessageException) {
            final Text text = ((TextMessageException) thr).getText();
            excBuilder = text == null ? Text.builder("null") : Text.builder().append(text);
        } else {
            excBuilder = Text.builder(String.valueOf(thr.getMessage()));
        }
        if (source.hasPermission("sponge.debug.hover-stacktrace")) {
            final StringWriter writer = new StringWriter();
            thr.printStackTrace(new PrintWriter(writer));
            excBuilder.onHover(TextActions.showText(Text.of(writer.toString().replace("\t", "    ").replace("\r\n", "\n").replace("\r", // I mean I guess somebody could be running this on like OS 9?
            "\n"))));
        }
        source.sendMessage(error(t("Error occurred while executing command: %s", excBuilder.build())));
        this.logger.error(LanternTexts.toLegacy(t("Error occurred while executing command '%s' for source %s: %s", commandLine, source.toString(), String.valueOf(thr.getMessage()))), thr);
    }
    return CommandResult.empty();
}
Also used : Arrays(java.util.Arrays) Inject(com.google.inject.Inject) CommandCallable(org.spongepowered.api.command.CommandCallable) CommandMapping(org.spongepowered.api.command.CommandMapping) Multimap(com.google.common.collect.Multimap) LanternTexts(org.lanternpowered.server.text.LanternTexts) Function(java.util.function.Function) InvocationCommandException(org.spongepowered.api.command.InvocationCommandException) ArrayList(java.util.ArrayList) SpongeApiTranslationHelper.t(org.spongepowered.api.util.SpongeApiTranslationHelper.t) HashMultimap(com.google.common.collect.HashMultimap) CauseStack(org.lanternpowered.server.event.CauseStack) CommandPermissionException(org.spongepowered.api.command.CommandPermissionException) ImmutableList(com.google.common.collect.ImmutableList) Text(org.spongepowered.api.text.Text) Map(java.util.Map) TabCompleteEvent(org.spongepowered.api.event.command.TabCompleteEvent) PluginContainer(org.spongepowered.api.plugin.PluginContainer) Nullable(javax.annotation.Nullable) PrintWriter(java.io.PrintWriter) CommandResult(org.spongepowered.api.command.CommandResult) TextActions(org.spongepowered.api.text.action.TextActions) Location(org.spongepowered.api.world.Location) ImmutableSet(com.google.common.collect.ImmutableSet) Logger(org.slf4j.Logger) SimpleDispatcher(org.spongepowered.api.command.dispatcher.SimpleDispatcher) Iterator(java.util.Iterator) CommandSource(org.spongepowered.api.command.CommandSource) TextMessageException(org.spongepowered.api.util.TextMessageException) SpongeEventFactory(org.spongepowered.api.event.SpongeEventFactory) StringWriter(java.io.StringWriter) Collection(java.util.Collection) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Sponge(org.spongepowered.api.Sponge) Set(java.util.Set) CommandException(org.spongepowered.api.command.CommandException) List(java.util.List) World(org.spongepowered.api.world.World) CommandManager(org.spongepowered.api.command.CommandManager) Optional(java.util.Optional) SendCommandEvent(org.spongepowered.api.event.command.SendCommandEvent) CommandMessageFormatting.error(org.spongepowered.api.command.CommandMessageFormatting.error) Singleton(com.google.inject.Singleton) Disambiguator(org.spongepowered.api.command.dispatcher.Disambiguator) CauseStack(org.lanternpowered.server.event.CauseStack) CommandPermissionException(org.spongepowered.api.command.CommandPermissionException) Optional(java.util.Optional) Text(org.spongepowered.api.text.Text) InvocationCommandException(org.spongepowered.api.command.InvocationCommandException) CommandException(org.spongepowered.api.command.CommandException) InvocationCommandException(org.spongepowered.api.command.InvocationCommandException) StringWriter(java.io.StringWriter) SendCommandEvent(org.spongepowered.api.event.command.SendCommandEvent) TextMessageException(org.spongepowered.api.util.TextMessageException) PrintWriter(java.io.PrintWriter)

Example 3 with SendCommandEvent

use of org.spongepowered.api.event.command.SendCommandEvent in project Nucleus by NucleusPowered.

the class CommandSpyListener method onCommand.

@Listener(order = Order.LAST)
public void onCommand(SendCommandEvent event, @Root Player player) {
    if (!player.hasPermission(this.exemptTarget)) {
        boolean isInList = false;
        if (!this.listIsEmpty) {
            String command = event.getCommand().toLowerCase();
            Optional<? extends CommandMapping> oc = Sponge.getCommandManager().get(command, player);
            Set<String> cmd;
            // If the command exists, then get all aliases.
            cmd = oc.map(commandMapping -> commandMapping.getAllAliases().stream().map(String::toLowerCase).collect(Collectors.toSet())).orElseGet(() -> Sets.newHashSet(command));
            isInList = this.config.getCommands().stream().map(String::toLowerCase).anyMatch(cmd::contains);
        }
        // If the command is in the list, report it.
        if (isInList == this.config.isUseWhitelist()) {
            List<Player> playerList = Sponge.getServer().getOnlinePlayers().stream().filter(x -> !x.getUniqueId().equals(player.getUniqueId())).filter(x -> x.hasPermission(this.basePermission)).filter(x -> Nucleus.getNucleus().getUserDataManager().getUnchecked(x).get(CommandSpyUserDataModule.class).isCommandSpy()).collect(Collectors.toList());
            if (!playerList.isEmpty()) {
                Text prefix = this.config.getTemplate().getForCommandSource(player);
                TextParsingUtils.StyleTuple st = TextParsingUtils.getLastColourAndStyle(prefix, null);
                Text messageToSend = prefix.toBuilder().append(Text.of(st.colour, st.style, "/", event.getCommand(), Util.SPACE, event.getArguments())).build();
                playerList.forEach(x -> x.sendMessage(messageToSend));
            }
        }
    }
}
Also used : CommandPermissionHandler(io.github.nucleuspowered.nucleus.internal.CommandPermissionHandler) Nucleus(io.github.nucleuspowered.nucleus.Nucleus) CommandSpyConfig(io.github.nucleuspowered.nucleus.modules.commandspy.config.CommandSpyConfig) TextParsingUtils(io.github.nucleuspowered.nucleus.internal.text.TextParsingUtils) Sponge(org.spongepowered.api.Sponge) Set(java.util.Set) CommandMapping(org.spongepowered.api.command.CommandMapping) CommandSpyModule(io.github.nucleuspowered.nucleus.modules.commandspy.CommandSpyModule) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) Reloadable(io.github.nucleuspowered.nucleus.internal.interfaces.Reloadable) Root(org.spongepowered.api.event.filter.cause.Root) List(java.util.List) CommandSpyConfigAdapter(io.github.nucleuspowered.nucleus.modules.commandspy.config.CommandSpyConfigAdapter) Text(org.spongepowered.api.text.Text) Order(org.spongepowered.api.event.Order) Optional(java.util.Optional) ListenerBase(io.github.nucleuspowered.nucleus.internal.ListenerBase) CommandSpyCommand(io.github.nucleuspowered.nucleus.modules.commandspy.commands.CommandSpyCommand) Util(io.github.nucleuspowered.nucleus.Util) CommandSpyUserDataModule(io.github.nucleuspowered.nucleus.modules.commandspy.datamodules.CommandSpyUserDataModule) Player(org.spongepowered.api.entity.living.player.Player) Listener(org.spongepowered.api.event.Listener) SendCommandEvent(org.spongepowered.api.event.command.SendCommandEvent) Player(org.spongepowered.api.entity.living.player.Player) CommandSpyUserDataModule(io.github.nucleuspowered.nucleus.modules.commandspy.datamodules.CommandSpyUserDataModule) Text(org.spongepowered.api.text.Text) TextParsingUtils(io.github.nucleuspowered.nucleus.internal.text.TextParsingUtils) Listener(org.spongepowered.api.event.Listener)

Aggregations

Optional (java.util.Optional)3 SendCommandEvent (org.spongepowered.api.event.command.SendCommandEvent)3 Text (org.spongepowered.api.text.Text)3 PrintWriter (java.io.PrintWriter)2 StringWriter (java.io.StringWriter)2 List (java.util.List)2 Set (java.util.Set)2 Sponge (org.spongepowered.api.Sponge)2 CommandException (org.spongepowered.api.command.CommandException)2 CommandMapping (org.spongepowered.api.command.CommandMapping)2 CommandPermissionException (org.spongepowered.api.command.CommandPermissionException)2 CommandResult (org.spongepowered.api.command.CommandResult)2 InvocationCommandException (org.spongepowered.api.command.InvocationCommandException)2 TextMessageException (org.spongepowered.api.util.TextMessageException)2 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)1 HashMultimap (com.google.common.collect.HashMultimap)1 ImmutableList (com.google.common.collect.ImmutableList)1 ImmutableSet (com.google.common.collect.ImmutableSet)1 Multimap (com.google.common.collect.Multimap)1 Sets (com.google.common.collect.Sets)1