Search in sources :

Example 6 with CommandElement

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

the class CommandListBans method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    specBuilder.arguments(GenericArguments.optional(new CommandElement(Text.of("ips")) {

        private final List<String> choices = Arrays.asList("ips", "players");

        @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 start = args.nextIfPresent().orElse("").toLowerCase();
            return this.choices.stream().filter(new StartsWithPredicate(start)).collect(Collectors.toList());
        }
    })).executor((src, args) -> {
        final boolean showIpBans = "ips".equalsIgnoreCase(args.<String>getOne("ips").orElse(null));
        final BanService banService = Lantern.getGame().getServiceManager().provideUnchecked(BanService.class);
        List<String> entries;
        if (showIpBans) {
            entries = banService.getIpBans().stream().map(ban -> ban.getAddress().getHostAddress()).collect(Collectors.toList());
            src.sendMessage(t("commands.banlist.ips", entries.size()));
        } else {
            entries = banService.getProfileBans().stream().map(ban -> ban.getProfile().getName().orElse(ban.getProfile().getUniqueId().toString())).collect(Collectors.toList());
            src.sendMessage(t("commands.banlist.players", entries.size()));
        }
        src.sendMessage(Text.of(Joiner.on(", ").join(entries)));
        return CommandResult.success();
    });
}
Also used : CommandArgs(org.spongepowered.api.command.args.CommandArgs) CommandContext(org.spongepowered.api.command.args.CommandContext) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) CommandSource(org.spongepowered.api.command.CommandSource) CommandElement(org.spongepowered.api.command.args.CommandElement) List(java.util.List) BanService(org.spongepowered.api.service.ban.BanService) Nullable(javax.annotation.Nullable)

Example 7 with CommandElement

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

the class CommandParticle method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    specBuilder.arguments(new PatternMatchingCommandElement(Text.of("type")) {

        @Override
        protected Iterable<String> getChoices(CommandSource source) {
            return Sponge.getGame().getRegistry().getAllOf(ParticleType.class).stream().filter(type -> ((LanternParticleType) type).getInternalType().isPresent()).map(CatalogType::getId).collect(Collectors.toList());
        }

        @Override
        protected Object getValue(String choice) throws IllegalArgumentException {
            final Optional<ParticleType> ret = Sponge.getGame().getRegistry().getType(ParticleType.class, choice);
            if (!ret.isPresent() || !((LanternParticleType) ret.get()).getInternalType().isPresent()) {
                throw new IllegalArgumentException("Invalid input " + choice + " was found");
            }
            return ret.get();
        }
    }, GenericArguments2.targetedVector3d(Text.of("position")), // The default value should be 0 for x, y and z
    GenericArguments2.vector3d(Text.of("offset"), Vector3d.ZERO), GenericArguments2.doubleNum(Text.of("speed"), 1.0), GenericArguments.optional(GenericArguments2.integer(Text.of("count"), 1)), GenericArguments.optional(new CommandElement(Text.of("mode")) {

        @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) {
            Optional<String> arg = args.nextIfPresent();
            if (arg.isPresent()) {
                return Stream.of("normal", "force").filter(new StartsWithPredicate(arg.get())).collect(Collectors.toList());
            }
            return Collections.emptyList();
        }
    }), GenericArguments.optional(GenericArguments.player(Text.of("player"))), GenericArguments.optional(new CommandElement(Text.of("params")) {

        @Nullable
        @Override
        protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
            List<Integer> params = new ArrayList<>();
            while (args.hasNext()) {
                String arg = args.next();
                try {
                    params.add(Integer.parseInt(arg));
                } catch (NumberFormatException e) {
                    throw args.createError(t("Expected an integer, but input '%s' was not", arg));
                }
            }
            return params.stream().mapToInt(i -> i).toArray();
        }

        @Override
        public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
            return Collections.emptyList();
        }
    })).executor((src, args) -> {
        final LanternParticleType particleType = args.<LanternParticleType>getOne("type").get();
        final int particleId = particleType.getInternalType().getAsInt();
        final Vector3f position = args.<Vector3d>getOne("position").get().toFloat();
        final Vector3f offset = args.<Vector3d>getOne("offset").get().toFloat();
        final float speed = args.<Double>getOne("speed").get().floatValue();
        final int count = args.<Integer>getOne("count").orElse(1);
        final boolean longDistance = args.<String>getOne("mode").map(mode -> mode.equalsIgnoreCase("force")).orElse(false);
        final int[] params = args.<int[]>getOne("params").orElse(new int[0]);
        final LanternWorld world = CommandHelper.getWorld(src, args);
        final int dataLength;
        if (particleType == ParticleTypes.BLOCK_CRACK || particleType == ParticleTypes.BLOCK_DUST || particleType == ParticleTypes.FALLING_DUST) {
            dataLength = 1;
        } else if (particleType == ParticleTypes.ITEM_CRACK) {
            dataLength = 2;
        } else {
            dataLength = 0;
        }
        if (params.length != dataLength) {
            throw new CommandException(t("Invalid parameters (%s), length mismatch (got %s, expected %s) for the particle type %s", Arrays.toString(params), params.length, dataLength, particleType.getId()));
        }
        final MessagePlayOutSpawnParticle message = new MessagePlayOutSpawnParticle(particleId, position, offset, speed, count, params, longDistance);
        if (args.hasAny("player")) {
            args.<LanternPlayer>getOne("player").get().getConnection().send(message);
        } else {
            for (LanternPlayer player : world.getRawPlayers()) {
                player.getConnection().send(message);
            }
        }
        src.sendMessage(t("commands.particle.success", particleType.getName(), count));
        return CommandResult.success();
    });
}
Also used : Arrays(java.util.Arrays) MessagePlayOutSpawnParticle(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutSpawnParticle) Vector3d(com.flowpowered.math.vector.Vector3d) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) CommandArgs(org.spongepowered.api.command.args.CommandArgs) LanternParticleType(org.lanternpowered.server.effect.particle.LanternParticleType) GenericArguments(org.spongepowered.api.command.args.GenericArguments) ArrayList(java.util.ArrayList) ParticleType(org.spongepowered.api.effect.particle.ParticleType) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) ParticleTypes(org.spongepowered.api.effect.particle.ParticleTypes) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) GenericArguments2(org.lanternpowered.server.command.element.GenericArguments2) LanternWorld(org.lanternpowered.server.world.LanternWorld) PluginContainer(org.spongepowered.api.plugin.PluginContainer) Nullable(javax.annotation.Nullable) CommandResult(org.spongepowered.api.command.CommandResult) TranslationHelper.t(org.lanternpowered.server.text.translation.TranslationHelper.t) CommandSource(org.spongepowered.api.command.CommandSource) CatalogType(org.spongepowered.api.CatalogType) Sponge(org.spongepowered.api.Sponge) 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) Stream(java.util.stream.Stream) Vector3f(com.flowpowered.math.vector.Vector3f) LanternPlayer(org.lanternpowered.server.entity.living.player.LanternPlayer) Optional(java.util.Optional) PatternMatchingCommandElement(org.spongepowered.api.command.args.PatternMatchingCommandElement) Collections(java.util.Collections) CommandContext(org.spongepowered.api.command.args.CommandContext) LanternParticleType(org.lanternpowered.server.effect.particle.LanternParticleType) ParticleType(org.spongepowered.api.effect.particle.ParticleType) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) LanternWorld(org.lanternpowered.server.world.LanternWorld) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) ArrayList(java.util.ArrayList) List(java.util.List) CommandArgs(org.spongepowered.api.command.args.CommandArgs) Optional(java.util.Optional) MessagePlayOutSpawnParticle(org.lanternpowered.server.network.vanilla.message.type.play.MessagePlayOutSpawnParticle) CommandException(org.spongepowered.api.command.CommandException) CommandSource(org.spongepowered.api.command.CommandSource) Vector3d(com.flowpowered.math.vector.Vector3d) PatternMatchingCommandElement(org.spongepowered.api.command.args.PatternMatchingCommandElement) Vector3f(com.flowpowered.math.vector.Vector3f) LanternParticleType(org.lanternpowered.server.effect.particle.LanternParticleType) CommandElement(org.spongepowered.api.command.args.CommandElement) PatternMatchingCommandElement(org.spongepowered.api.command.args.PatternMatchingCommandElement) Nullable(javax.annotation.Nullable) LanternPlayer(org.lanternpowered.server.entity.living.player.LanternPlayer)

Example 8 with CommandElement

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

the class CommandSetData method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    final ThreadLocal<Key<?>> currentKey = new ThreadLocal<>();
    specBuilder.arguments(GenericArguments.playerOrSource(Text.of("player")), new PatternMatchingCommandElement(Text.of("key")) {

        @Override
        protected Iterable<String> getChoices(CommandSource source) {
            return Sponge.getGame().getRegistry().getAllOf(Key.class).stream().map(Key::getId).collect(Collectors.toList());
        }

        @Override
        protected Object getValue(String choice) throws IllegalArgumentException {
            final Optional<Key> ret = Sponge.getGame().getRegistry().getType(Key.class, choice);
            if (!ret.isPresent()) {
                throw new IllegalArgumentException("Invalid input " + choice + " was found");
            }
            currentKey.set(ret.get());
            return ret.get();
        }
    }, new CommandElement(Text.of("data")) {

        @Nullable
        @Override
        protected Object parseValue(CommandSource source, CommandArgs args) throws ArgumentParseException {
            args.next();
            final String content = args.getRaw().substring(args.getRawPosition()).trim();
            while (args.hasNext()) {
                args.next();
            }
            final Object data;
            try {
                // Don't be too strict
                data = JsonDataFormat.read(content, true).orElse(null);
            } catch (IOException e) {
                throw args.createError(t("Invalid json data: %s\nError: %s", content, e.getMessage()));
            }
            final Key key = currentKey.get();
            final TypeToken<?> typeToken = key.getElementToken();
            if (content.isEmpty()) {
                return null;
            }
            final DataTypeSerializer dataTypeSerializer = Lantern.getGame().getDataManager().getTypeSerializer(typeToken).orElse(null);
            if (dataTypeSerializer == null) {
                throw args.createError(Text.of("Unable to deserialize the data key value: {}, " + "no supported deserializer exists.", key.getId()));
            } else {
                final DataTypeSerializerContext context = Lantern.getGame().getDataManager().getTypeSerializerContext();
                try {
                    // Put it in a holder object, the command element separates iterable objects
                    return new ValueHolder(dataTypeSerializer.deserialize(typeToken, context, data));
                } catch (InvalidDataException e) {
                    throw args.createError(t("Invalid data: %s", e.getMessage()));
                }
            }
        }

        @Override
        public List<String> complete(CommandSource src, CommandArgs args, CommandContext context) {
            return new ArrayList<>();
        }
    }).executor((src, args) -> {
        final Player target = args.<Player>getOne("player").get();
        final Key key = args.<Key>getOne("key").get();
        final Object data = args.<ValueHolder>getOne("data").get().data;
        target.offer(key, data);
        src.sendMessage(t("Successfully offered the data for the key %s to the player %s", key.getId(), target.getName()));
        return CommandResult.success();
    });
}
Also used : CommandArgs(org.spongepowered.api.command.args.CommandArgs) Player(org.spongepowered.api.entity.living.player.Player) CommandContext(org.spongepowered.api.command.args.CommandContext) DataTypeSerializerContext(org.lanternpowered.server.data.persistence.DataTypeSerializerContext) ArrayList(java.util.ArrayList) IOException(java.io.IOException) CommandSource(org.spongepowered.api.command.CommandSource) PatternMatchingCommandElement(org.spongepowered.api.command.args.PatternMatchingCommandElement) InvalidDataException(org.spongepowered.api.data.persistence.InvalidDataException) CommandElement(org.spongepowered.api.command.args.CommandElement) PatternMatchingCommandElement(org.spongepowered.api.command.args.PatternMatchingCommandElement) DataTypeSerializer(org.lanternpowered.server.data.persistence.DataTypeSerializer) Key(org.spongepowered.api.data.key.Key)

Example 9 with CommandElement

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

the class CommandOp method completeSpec.

@Override
public void completeSpec(PluginContainer pluginContainer, CommandSpec.Builder specBuilder) {
    specBuilder.arguments(new CommandElement(Text.of("player")) {

        @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 prefix = args.nextIfPresent().orElse("");
            final UserConfig<OpsEntry> config = Lantern.getGame().getOpsConfig();
            return Lantern.getGame().getGameProfileManager().getCache().getProfiles().stream().filter(p -> p.getName().isPresent() && !config.getEntryByUUID(p.getUniqueId()).isPresent()).map(p -> p.getName().get()).filter(new StartsWithPredicate(prefix)).collect(ImmutableList.toImmutableList());
        }
    }, GenericArguments.optional(GenericArguments.integer(Text.of("level")))).executor((src, args) -> {
        String playerName = args.<String>getOne("player").get();
        UserConfig<OpsEntry> config = Lantern.getGame().getOpsConfig();
        if (!(src instanceof ConsoleSource) && args.hasAny("level")) {
            throw new CommandException(Text.of("Only the console may specify the op level."));
        }
        int opLevel = args.<Integer>getOne("level").orElse(Lantern.getGame().getGlobalConfig().getDefaultOpPermissionLevel());
        Lantern.getGame().getGameProfileManager().get(playerName).whenComplete((profile, error) -> {
            if (error != null) {
                src.sendMessage(t("commands.op.failed", playerName));
            } else {
                src.sendMessage(t("commands.op.success", playerName));
                config.addEntry(new OpsEntry(((LanternGameProfile) profile).withoutProperties(), opLevel));
            }
        });
        return CommandResult.success();
    });
}
Also used : CommandArgs(org.spongepowered.api.command.args.CommandArgs) CommandResult(org.spongepowered.api.command.CommandResult) ConsoleSource(org.spongepowered.api.command.source.ConsoleSource) TranslationHelper.t(org.lanternpowered.server.text.translation.TranslationHelper.t) CommandSource(org.spongepowered.api.command.CommandSource) OpsEntry(org.lanternpowered.server.config.user.OpsEntry) ArgumentParseException(org.spongepowered.api.command.args.ArgumentParseException) CommandArgs(org.spongepowered.api.command.args.CommandArgs) CommandElement(org.spongepowered.api.command.args.CommandElement) GenericArguments(org.spongepowered.api.command.args.GenericArguments) LanternGameProfile(org.lanternpowered.server.profile.LanternGameProfile) CommandSpec(org.spongepowered.api.command.spec.CommandSpec) CommandException(org.spongepowered.api.command.CommandException) UserConfig(org.lanternpowered.server.config.user.UserConfig) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) CommandContext(org.spongepowered.api.command.args.CommandContext) Text(org.spongepowered.api.text.Text) Lantern(org.lanternpowered.server.game.Lantern) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) PluginContainer(org.spongepowered.api.plugin.PluginContainer) Nullable(javax.annotation.Nullable) CommandContext(org.spongepowered.api.command.args.CommandContext) LanternGameProfile(org.lanternpowered.server.profile.LanternGameProfile) StartsWithPredicate(org.spongepowered.api.util.StartsWithPredicate) CommandException(org.spongepowered.api.command.CommandException) CommandSource(org.spongepowered.api.command.CommandSource) OpsEntry(org.lanternpowered.server.config.user.OpsEntry) CommandElement(org.spongepowered.api.command.args.CommandElement) ConsoleSource(org.spongepowered.api.command.source.ConsoleSource)

Aggregations

CommandSource (org.spongepowered.api.command.CommandSource)9 CommandArgs (org.spongepowered.api.command.args.CommandArgs)9 CommandContext (org.spongepowered.api.command.args.CommandContext)9 CommandElement (org.spongepowered.api.command.args.CommandElement)9 List (java.util.List)8 StartsWithPredicate (org.spongepowered.api.util.StartsWithPredicate)8 Nullable (javax.annotation.Nullable)7 ArgumentParseException (org.spongepowered.api.command.args.ArgumentParseException)7 CommandResult (org.spongepowered.api.command.CommandResult)6 CommandSpec (org.spongepowered.api.command.spec.CommandSpec)6 Text (org.spongepowered.api.text.Text)6 ImmutableList (com.google.common.collect.ImmutableList)5 TranslationHelper.t (org.lanternpowered.server.text.translation.TranslationHelper.t)5 Optional (java.util.Optional)4 GenericArguments (org.spongepowered.api.command.args.GenericArguments)4 PluginContainer (org.spongepowered.api.plugin.PluginContainer)4 Map (java.util.Map)3 Lantern (org.lanternpowered.server.game.Lantern)3 Sponge (org.spongepowered.api.Sponge)3 CommandException (org.spongepowered.api.command.CommandException)3