Search in sources :

Example 11 with CommandSource

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

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

the class QueryHandler method handleFullStats.

private void handleFullStats(ChannelHandlerContext ctx, DatagramPacket packet, int sessionId) {
    final LanternGame game = this.queryServer.getGame();
    final LanternServer server = game.getServer();
    final Platform platform = game.getPlatform();
    final PluginContainer api = platform.getContainer(Platform.Component.API);
    final PluginContainer impl = platform.getContainer(Platform.Component.IMPLEMENTATION);
    final PluginContainer mc = platform.getContainer(Platform.Component.GAME);
    final StringBuilder plugins = new StringBuilder().append(impl.getName()).append(" ").append(impl.getVersion()).append(" on ").append(api.getName()).append(" ").append(api.getVersion());
    if (this.showPlugins) {
        final List<PluginContainer> containers = new ArrayList<>(game.getPluginManager().getPlugins());
        containers.remove(api);
        containers.remove(impl);
        containers.remove(mc);
        char delim = ':';
        for (PluginContainer plugin : containers) {
            plugins.append(delim).append(' ').append(plugin.getName());
            delim = ';';
        }
    }
    final List<String> playerNames = server.getOnlinePlayers().stream().map(CommandSource::getName).collect(Collectors.toList());
    final Cause cause = Cause.of(EventContext.empty(), new SimpleRemoteConnection((InetSocketAddress) ctx.channel().remoteAddress(), null));
    final QueryServerEvent.Full event = SpongeEventFactory.createQueryServerEventFull(cause, (InetSocketAddress) ctx.channel().localAddress(), new HashMap<>(), "MINECRAFT", "SMP", getWorldName(), server.getMotd().toPlain(), playerNames, plugins.toString(), mc.getVersion().orElse("unknown"), server.getMaxPlayers(), Integer.MAX_VALUE, playerNames.size(), 0);
    final InetSocketAddress address = event.getAddress();
    final Map<String, Object> data = new LinkedHashMap<>();
    data.put("hostname", event.getMotd());
    data.put("gametype", event.getGameType());
    data.put("game_id", event.getGameId());
    data.put("version", event.getVersion());
    data.put("plugins", event.getPlugins());
    data.put("map", event.getMap());
    data.put("numplayers", event.getPlayerCount());
    data.put("maxplayers", event.getMaxPlayerCount());
    data.put("hostport", address.getPort());
    data.put("hostip", address.getHostString());
    event.getCustomValuesMap().entrySet().stream().filter(entry -> !data.containsKey(entry.getKey())).forEach(entry -> data.put(entry.getKey(), entry.getValue()));
    final ByteBuf buf = ctx.alloc().buffer();
    buf.writeByte(ACTION_STATS);
    buf.writeInt(sessionId);
    // constant: splitnum\x00\x80\x00
    buf.writeBytes(new byte[] { 0x73, 0x70, 0x6C, 0x69, 0x74, 0x6E, 0x75, 0x6D, 0x00, (byte) 0x80, 0x00 });
    for (Entry<String, Object> e : data.entrySet()) {
        writeString(buf, e.getKey());
        writeString(buf, String.valueOf(e.getValue()));
    }
    buf.writeByte(0);
    // constant: \x01player_\x00\x00
    buf.writeBytes(new byte[] { 0x01, 0x70, 0x6C, 0x61, 0x79, 0x65, 0x72, 0x5F, 0x00, 0x00 });
    for (Player player : game.getServer().getOnlinePlayers()) {
        writeString(buf, player.getName());
    }
    buf.writeByte(0);
    ctx.write(new DatagramPacket(buf, packet.sender()));
}
Also used : HashMap(java.util.HashMap) Platform(org.spongepowered.api.Platform) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) ChannelHandlerContext(io.netty.channel.ChannelHandlerContext) ByteBuf(io.netty.buffer.ByteBuf) Map(java.util.Map) DatagramPacket(io.netty.channel.socket.DatagramPacket) PluginContainer(org.spongepowered.api.plugin.PluginContainer) SimpleRemoteConnection(org.lanternpowered.server.network.SimpleRemoteConnection) LanternServer(org.lanternpowered.server.LanternServer) CommandSource(org.spongepowered.api.command.CommandSource) SpongeEventFactory(org.spongepowered.api.event.SpongeEventFactory) Collection(java.util.Collection) Sponge(org.spongepowered.api.Sponge) InetSocketAddress(java.net.InetSocketAddress) Collectors(java.util.stream.Collectors) LanternGame(org.lanternpowered.server.game.LanternGame) StandardCharsets(java.nio.charset.StandardCharsets) Cause(org.spongepowered.api.event.cause.Cause) List(java.util.List) QueryServerEvent(org.spongepowered.api.event.server.query.QueryServerEvent) SimpleChannelInboundHandler(io.netty.channel.SimpleChannelInboundHandler) World(org.spongepowered.api.world.World) Entry(java.util.Map.Entry) Player(org.spongepowered.api.entity.living.player.Player) EventContext(org.spongepowered.api.event.cause.EventContext) Player(org.spongepowered.api.entity.living.player.Player) PluginContainer(org.spongepowered.api.plugin.PluginContainer) Platform(org.spongepowered.api.Platform) SimpleRemoteConnection(org.lanternpowered.server.network.SimpleRemoteConnection) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) QueryServerEvent(org.spongepowered.api.event.server.query.QueryServerEvent) ByteBuf(io.netty.buffer.ByteBuf) LanternGame(org.lanternpowered.server.game.LanternGame) LinkedHashMap(java.util.LinkedHashMap) LanternServer(org.lanternpowered.server.LanternServer) Cause(org.spongepowered.api.event.cause.Cause) DatagramPacket(io.netty.channel.socket.DatagramPacket)

Example 13 with CommandSource

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

the class LanternContextCalculator method accumulateContexts.

@Override
public void accumulateContexts(Subject subject, Set<Context> accumulator) {
    final Optional<CommandSource> subjSource = subject.getCommandSource();
    if (subjSource.isPresent()) {
        final CommandSource source = subjSource.get();
        if (source instanceof Locatable) {
            final World currentExt = ((Locatable) source).getWorld();
            accumulator.add(currentExt.getContext());
            accumulator.add((currentExt.getDimension().getContext()));
        }
        if (source instanceof RemoteSource) {
            final RemoteSource rem = (RemoteSource) source;
            accumulator.addAll(this.remoteIpCache.get(rem));
            accumulator.addAll(this.localIpCache.get(rem));
            accumulator.add(new Context(Context.LOCAL_PORT_KEY, String.valueOf(rem.getConnection().getVirtualHost().getPort())));
            accumulator.add(new Context(Context.LOCAL_HOST_KEY, rem.getConnection().getVirtualHost().getHostName()));
        }
    }
}
Also used : Context(org.spongepowered.api.service.context.Context) RemoteSource(org.spongepowered.api.command.source.RemoteSource) CommandSource(org.spongepowered.api.command.CommandSource) World(org.spongepowered.api.world.World) Locatable(org.spongepowered.api.world.Locatable)

Example 14 with CommandSource

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

the class CommandGameRule method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    final Collection<String> defaultRules = Sponge.getRegistry().getDefaultGameRules();
    final ThreadLocal<RuleType<?>> currentRule = new ThreadLocal<>();
    specBuilder.arguments(GenericArguments.flags().valueFlag(GenericArguments.world(CommandHelper.WORLD_KEY), "-world", "w").buildWith(GenericArguments.none()), new CommandElement(Text.of("rule")) {

        @Nullable
        @Override
        protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
            RuleType<?> ruleType = RuleType.getOrCreate(args.next(), RuleDataTypes.STRING, "");
            currentRule.set(ruleType);
            return ruleType;
        }

        @Override
        public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
            final String prefix = args.nextIfPresent().orElse("");
            return defaultRules.stream().filter(new StartsWithPredicate(prefix)).collect(ImmutableList.toImmutableList());
        }
    }, new CommandElement(Text.of("value")) {

        private final List<String> booleanRuleSuggestions = ImmutableList.of("true", "false");

        @Nullable
        @Override
        protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
            RuleType<?> ruleType = currentRule.get();
            currentRule.remove();
            try {
                return ruleType.getDataType().parse(args.next());
            } catch (IllegalArgumentException e) {
                throw args.createError(t(e.getMessage()));
            }
        }

        @Override
        public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
            RuleType<?> ruleType = context.<RuleType<?>>getOne("rule").get();
            if (ruleType.getDataType() == RuleDataTypes.BOOLEAN) {
                // match the first part of the string
                return this.booleanRuleSuggestions;
            }
            return Collections.emptyList();
        }
    }).executor((src, args) -> {
        WorldProperties world = CommandHelper.getWorldProperties(src, args);
        Object value = args.getOne("value").get();
        RuleType ruleType = args.<RuleType>getOne("rule").get();
        ((LanternWorldProperties) world).getRules().getOrCreateRule(ruleType).setValue(value);
        src.sendMessage(t("commands.gamerule.success", ruleType.getName(), ruleType.getDataType().serialize(value)));
        return CommandResult.success();
    });
}
Also used : CommandArgs(org.spongepowered.api.command.args.CommandArgs) CommandContext(org.spongepowered.api.command.args.CommandContext) RuleType(org.lanternpowered.server.world.rules.RuleType) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) CommandSource(org.spongepowered.api.command.CommandSource) CommandElement(org.spongepowered.api.command.args.CommandElement) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) LanternWorldProperties(org.lanternpowered.server.world.LanternWorldProperties) LanternWorldProperties(org.lanternpowered.server.world.LanternWorldProperties) WorldProperties(org.spongepowered.api.world.storage.WorldProperties)

Example 15 with CommandSource

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

Aggregations

CommandSource (org.spongepowered.api.command.CommandSource)93 Text (org.spongepowered.api.text.Text)61 CommandResult (org.spongepowered.api.command.CommandResult)49 List (java.util.List)47 CommandContext (org.spongepowered.api.command.args.CommandContext)45 Collectors (java.util.stream.Collectors)39 Optional (java.util.Optional)37 Sponge (org.spongepowered.api.Sponge)37 Player (org.spongepowered.api.entity.living.player.Player)36 TextColors (org.spongepowered.api.text.format.TextColors)30 CommandElement (org.spongepowered.api.command.args.CommandElement)27 TextActions (org.spongepowered.api.text.action.TextActions)27 GenericArguments (org.spongepowered.api.command.args.GenericArguments)25 NonnullByDefault (org.spongepowered.api.util.annotation.NonnullByDefault)25 AbstractCommand (io.github.nucleuspowered.nucleus.internal.command.AbstractCommand)24 Permissions (io.github.nucleuspowered.nucleus.internal.annotations.command.Permissions)23 RegisterCommand (io.github.nucleuspowered.nucleus.internal.annotations.command.RegisterCommand)23 Util (io.github.nucleuspowered.nucleus.Util)20 Nullable (javax.annotation.Nullable)20 World (org.spongepowered.api.world.World)20