Search in sources :

Example 6 with CommandMapping

use of org.spongepowered.api.command.CommandMapping in project core by CubeEngine.

the class CubeCommandManager method addCommand.

@Override
public boolean addCommand(CommandBase command) {
    if (command instanceof AliasCommand) {
        Set<CommandBase> cmds = commands.computeIfAbsent(((AliasCommand) command).getTarget(), k -> new HashSet<>());
        cmds.add(command);
    }
    if (command.getDescriptor() instanceof CubeDescriptor) {
        CubeDescriptor descriptor = (CubeDescriptor) command.getDescriptor();
        String name = mm.getModuleName(descriptor.getOwner()).orElse(descriptor.getOwner().getSimpleName());
        Permission parent = pm.register(descriptor.getOwner(), "command", "Allows using all commands of " + name, null);
        descriptor.registerPermission(pm, parent);
    }
    boolean b = super.addCommand(command);
    if (!(command instanceof AliasCommand) || ((AliasDescriptor) command.getDescriptor()).mainDescriptor().getDispatcher() != this) {
        Optional<CommandMapping> mapping = registerSpongeCommand(command.getDescriptor());
        if (mapping.isPresent()) {
            mappings.put(command, mapping.get());
            commandLogger.debug("Registered command: " + mapping.get().getPrimaryAlias());
            return b;
        }
        commandLogger.warn("Command was not registered successfully!");
    }
    return b;
}
Also used : AliasCommand(org.cubeengine.butler.alias.AliasCommand) CommandBase(org.cubeengine.butler.CommandBase) CommandMapping(org.spongepowered.api.command.CommandMapping) Permission(org.cubeengine.libcube.service.permission.Permission)

Example 7 with CommandMapping

use of org.spongepowered.api.command.CommandMapping 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 8 with CommandMapping

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

the class CommandHelp method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    final Comparator<CommandMapping> comparator = Comparator.comparing(CommandMapping::getPrimaryAlias);
    specBuilder.arguments(GenericArguments.optional(new CommandElement(Text.of("command")) {

        @Nullable
        @Override
        protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
            return args.next();
        }

        @Override
        public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
            final String nextArg = args.nextIfPresent().orElse("");
            return Lantern.getGame().getCommandManager().getAliases().stream().filter(new StartsWithPredicate(nextArg)).collect(Collectors.toList());
        }
    })).description(Text.of("View a list of all commands")).extendedDescription(Text.of("View a list of all commands. Hover over\n" + " a command to view its description. Click\n" + " a command to insert it into your chat bar.")).executor((src, args) -> {
        Optional<String> command = args.getOne("command");
        if (command.isPresent()) {
            Optional<? extends CommandMapping> mapping = Sponge.getCommandManager().get(command.get());
            if (mapping.isPresent()) {
                CommandCallable callable = mapping.get().getCallable();
                Optional<? extends Text> desc;
                // command name in the usage message
                if (callable instanceof CommandSpec) {
                    Text.Builder builder = Text.builder();
                    callable.getShortDescription(src).ifPresent(des -> builder.append(des, Text.NEW_LINE));
                    builder.append(t("commands.generic.usage", t("/%s %s", command.get(), callable.getUsage(src))));
                    Text extendedDescription;
                    try {
                        // TODO: Why is there no method :(
                        extendedDescription = (Text) extendedDescriptionField.get(callable);
                    } catch (IllegalAccessException e) {
                        throw new RuntimeException(e);
                    }
                    if (extendedDescription != null) {
                        builder.append(Text.NEW_LINE, extendedDescription);
                    }
                    src.sendMessage(builder.build());
                } else if ((desc = callable.getHelp(src)).isPresent()) {
                    src.sendMessage(desc.get());
                } else {
                    src.sendMessage(t("commands.generic.usage", t("/%s %s", command.get(), callable.getUsage(src))));
                }
                return CommandResult.success();
            }
            throw new CommandException(Text.of("No such command: ", command.get()));
        }
        Lantern.getGame().getScheduler().submitAsyncTask(() -> {
            TreeSet<CommandMapping> commands = new TreeSet<>(comparator);
            commands.addAll(Collections2.filter(Sponge.getCommandManager().getAll().values(), input -> input.getCallable().testPermission(src)));
            final Text title = Text.builder("Available commands:").color(TextColors.DARK_GREEN).build();
            final List<Text> lines = commands.stream().map(c -> getDescription(src, c)).collect(Collectors.toList());
            // Console sources cannot see/use the pagination
            if (!(src instanceof ConsoleSource)) {
                Sponge.getGame().getServiceManager().provide(PaginationService.class).get().builder().title(title).padding(Text.of(TextColors.DARK_GREEN, "=")).contents(lines).sendTo(src);
            } else {
                src.sendMessage(title);
                src.sendMessages(lines);
            }
            return null;
        });
        return CommandResult.success();
    });
}
Also used : ConsoleSource(org.spongepowered.api.command.source.ConsoleSource) CommandCallable(org.spongepowered.api.command.CommandCallable) CommandMapping(org.spongepowered.api.command.CommandMapping) Collections2(com.google.common.collect.Collections2) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) CommandArgs(org.spongepowered.api.command.args.CommandArgs) GenericArguments(org.spongepowered.api.command.args.GenericArguments) TreeSet(java.util.TreeSet) PaginationList(org.spongepowered.api.service.pagination.PaginationList) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) PluginContainer(org.spongepowered.api.plugin.PluginContainer) TextColors(org.spongepowered.api.text.format.TextColors) Nullable(javax.annotation.Nullable) CommandResult(org.spongepowered.api.command.CommandResult) TextActions(org.spongepowered.api.text.action.TextActions) TranslationHelper.t(org.lanternpowered.server.text.translation.TranslationHelper.t) CommandSource(org.spongepowered.api.command.CommandSource) TextStyles(org.spongepowered.api.text.format.TextStyles) Collection(java.util.Collection) Sponge(org.spongepowered.api.Sponge) PaginationService(org.spongepowered.api.service.pagination.PaginationService) Field(java.lang.reflect.Field) CommandElement(org.spongepowered.api.command.args.CommandElement) Collectors(java.util.stream.Collectors) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) CommandException(org.spongepowered.api.command.CommandException) List(java.util.List) Lantern(org.lanternpowered.server.game.Lantern) Optional(java.util.Optional) Comparator(java.util.Comparator) CommandContext(org.spongepowered.api.command.args.CommandContext) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) CommandCallable(org.spongepowered.api.command.CommandCallable) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) TreeSet(java.util.TreeSet) CommandMapping(org.spongepowered.api.command.CommandMapping) PaginationList(org.spongepowered.api.service.pagination.PaginationList) List(java.util.List) CommandArgs(org.spongepowered.api.command.args.CommandArgs) Text(org.spongepowered.api.text.Text) CommandException(org.spongepowered.api.command.CommandException) CommandSource(org.spongepowered.api.command.CommandSource) CommandElement(org.spongepowered.api.command.args.CommandElement) ConsoleSource(org.spongepowered.api.command.source.ConsoleSource) Nullable(javax.annotation.Nullable)

Example 9 with CommandMapping

use of org.spongepowered.api.command.CommandMapping 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)

Example 10 with CommandMapping

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

the class CommandPermissions method populateMinecraftPermissions.

public static void populateMinecraftPermissions(ICommandSender sender, MemorySubjectData data) {
    // ICommandSenders have a *very* basic understanding of permissions, so
    // get what we can.
    populateNonCommandPermissions(data, sender::canUseCommand);
    for (CommandMapping command : SpongeImpl.getGame().getCommandManager().getCommands()) {
        if (command.getCallable() instanceof MinecraftCommandWrapper) {
            MinecraftCommandWrapper wrapper = (MinecraftCommandWrapper) command.getCallable();
            data.setPermission(SubjectData.GLOBAL_CONTEXT, wrapper.getCommandPermission(), Tristate.fromBoolean(wrapper.command.checkPermission(sender.getServer(), sender)));
        }
    }
}
Also used : CommandMapping(org.spongepowered.api.command.CommandMapping)

Aggregations

CommandMapping (org.spongepowered.api.command.CommandMapping)14 CommandException (org.spongepowered.api.command.CommandException)5 PluginContainer (org.spongepowered.api.plugin.PluginContainer)5 Text (org.spongepowered.api.text.Text)5 ImmutableCommandMapping (org.spongepowered.api.command.ImmutableCommandMapping)4 CommandSpec (org.spongepowered.api.command.spec.CommandSpec)4 ArrayList (java.util.ArrayList)3 List (java.util.List)3 Optional (java.util.Optional)3 Sponge (org.spongepowered.api.Sponge)3 CommandCallable (org.spongepowered.api.command.CommandCallable)3 Collection (java.util.Collection)2 Set (java.util.Set)2 Collectors (java.util.stream.Collectors)2 Nullable (javax.annotation.Nullable)2 CommandResult (org.spongepowered.api.command.CommandResult)2 CommandSource (org.spongepowered.api.command.CommandSource)2 SendCommandEvent (org.spongepowered.api.event.command.SendCommandEvent)2 TextActions (org.spongepowered.api.text.action.TextActions)2 StartsWithPredicate (org.spongepowered.api.util.StartsWithPredicate)2