Search in sources :

Example 1 with ConsoleSource

use of org.spongepowered.api.command.source.ConsoleSource 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 2 with ConsoleSource

use of org.spongepowered.api.command.source.ConsoleSource in project UltimateChat by FabioZumbi12.

the class UCCommands method registerTellAliases.

private void registerTellAliases() {
    // register tell aliases
    for (String tell : UChat.get().getConfig().getTellAliases()) {
        unregisterCmd(tell);
        if (tell.equals("r")) {
            manager.register(UChat.get().instance(), CommandSpec.builder().arguments(new remainJoinedStringsWithTab(Text.of("message"))).permission("uchat.cmd.tell").description(Text.of("Respond to the private messages of other players.")).executor((src, args) -> {
                {
                    if (src instanceof Player) {
                        Player p = (Player) src;
                        if (UChat.get().respondTell.containsKey(p.getName())) {
                            String recStr = UChat.get().respondTell.get(p.getName());
                            Text msg = Text.of(args.<String>getOne("message").get());
                            if (recStr.equals("CONSOLE")) {
                                UChat.get().respondTell.put("CONSOLE", p.getName());
                                UChat.get().command.add(p.getName());
                                sendPreTell(p, Sponge.getServer().getConsole(), msg);
                            } else {
                                Optional<Player> optRec = Sponge.getServer().getPlayer(recStr);
                                if (!optRec.isPresent()) {
                                    throw new CommandException(UChat.get().getLang().getText("cmd.tell.nonetorespond"));
                                } else {
                                    Player receiver = optRec.get();
                                    UChat.get().respondTell.put(receiver.getName(), p.getName());
                                    UChat.get().command.add(p.getName());
                                    sendPreTell(p, receiver, msg);
                                }
                            }
                            return CommandResult.success();
                        } else {
                            throw new CommandException(UChat.get().getLang().getText("cmd.tell.nonetorespond"));
                        }
                    }
                    return CommandResult.success();
                }
            }).build(), tell);
        } else {
            manager.register(UChat.get().instance(), CommandSpec.builder().arguments(GenericArguments.optional(GenericArguments.firstParsing(GenericArguments.player(Text.of("receiver")), GenericArguments.string(Text.of("receiver")))), GenericArguments.optional(new remainJoinedStringsWithTab(Text.of("message")))).description(Text.of("Lock your chat with a player or send private messages.")).permission("uchat.cmd.tell").executor((src, args) -> {
                {
                    if (!args.hasAny("receiver")) {
                        if (UChat.get().tellPlayers.containsKey(src.getName())) {
                            String tp = UChat.get().tellPlayers.get(src.getName());
                            UChat.get().tellPlayers.remove(src.getName());
                            UChat.get().getLang().sendMessage(src, UChat.get().getLang().get("cmd.tell.unlocked").replace("{player}", tp));
                            return CommandResult.success();
                        }
                    } else {
                        Object recObj = args.getOne("receiver").get();
                        if (src instanceof Player) {
                            Player p = (Player) src;
                            if (args.<String>getOne("message").isPresent()) {
                                Text msg = Text.of(args.<String>getOne("message").get());
                                // receiver as player
                                if (recObj instanceof Player) {
                                    Player receiver = (Player) recObj;
                                    if (receiver.equals(p)) {
                                        throw new CommandException(UChat.get().getLang().getText("cmd.tell.self"), true);
                                    }
                                    if (!receiver.isOnline() || !p.canSee(receiver)) {
                                        UChat.get().getLang().sendMessage(p, "listener.invalidplayer");
                                        return CommandResult.success();
                                    }
                                    if (!p.canSee(receiver)) {
                                        UChat.get().getLang().sendMessage(p, "listener.invalidplayer");
                                        return CommandResult.success();
                                    }
                                    UChat.get().tempTellPlayers.put(p.getName(), receiver.getName());
                                    UChat.get().command.add(p.getName());
                                    sendPreTell(p, receiver, msg);
                                } else // if receiver as console
                                if (recObj.toString().equalsIgnoreCase("console")) {
                                    UChat.get().tempTellPlayers.put(p.getName(), "CONSOLE");
                                    UChat.get().command.add(p.getName());
                                    sendPreTell(p, Sponge.getServer().getConsole(), msg);
                                } else // send to jedis
                                if (UChat.get().getJedis() != null) {
                                    UChat.get().getJedis().sendTellMessage(p, recObj.toString(), msg);
                                    return CommandResult.success();
                                } else // not found
                                {
                                    UChat.get().getLang().sendMessage(p, "listener.invalidplayer");
                                }
                                return CommandResult.success();
                            } else // lock tell
                            if (recObj instanceof Player) {
                                Player receiver = (Player) recObj;
                                if (!receiver.isOnline() || !p.canSee(receiver)) {
                                    throw new CommandException(UChat.get().getLang().getText("listener.invalidplayer"), true);
                                }
                                if (receiver.equals(p)) {
                                    throw new CommandException(UChat.get().getLang().getText("cmd.tell.self"), true);
                                }
                                if (UChat.get().tellPlayers.containsKey(p.getName()) && UChat.get().tellPlayers.get(p.getName()).equals(receiver.getName())) {
                                    UChat.get().tellPlayers.remove(p.getName());
                                    UChat.get().getLang().sendMessage(p, UChat.get().getLang().get("cmd.tell.unlocked").replace("{player}", receiver.getName()));
                                } else {
                                    UChat.get().tellPlayers.put(p.getName(), receiver.getName());
                                    UChat.get().getLang().sendMessage(p, UChat.get().getLang().get("cmd.tell.locked").replace("{player}", receiver.getName()));
                                }
                                return CommandResult.success();
                            }
                        } else // console to player
                        if (src instanceof ConsoleSource && recObj instanceof Player && args.<String>getOne("message").isPresent()) {
                            String msg = args.<String>getOne("message").get();
                            Player receiver = (Player) recObj;
                            if (!receiver.isOnline()) {
                                UChat.get().getLang().sendMessage(Sponge.getServer().getConsole(), "listener.invalidplayer");
                                return CommandResult.success();
                            }
                            UChat.get().tempTellPlayers.put("CONSOLE", receiver.getName());
                            UChat.get().command.add("CONSOLE");
                            sendPreTell(Sponge.getServer().getConsole(), receiver, Text.of(msg));
                            return CommandResult.success();
                        }
                    }
                    sendTellHelp(src);
                    return CommandResult.success();
                }
            }).build(), tell);
        }
    }
}
Also used : Player(org.spongepowered.api.entity.living.player.Player) Text(org.spongepowered.api.text.Text) ConsoleSource(org.spongepowered.api.command.source.ConsoleSource)

Example 3 with ConsoleSource

use of org.spongepowered.api.command.source.ConsoleSource in project Nucleus by NucleusPowered.

the class CloneWorldCommand method executeCommand.

@Override
protected CommandResult executeCommand(CommandSource src, CommandContext args) throws Exception {
    WorldProperties worldToCopy = args.<WorldProperties>getOne(this.worldKey).get();
    final String oldName = worldToCopy.getWorldName();
    final String newName = args.<String>getOne(this.newKey).get();
    if (Sponge.getServer().getWorldProperties(newName).isPresent()) {
        throw ReturnMessageException.fromKey("command.world.clone.alreadyexists", newName);
    }
    Text message = Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.world.clone.starting", oldName, newName);
    src.sendMessage(message);
    if (!(src instanceof ConsoleSource)) {
        Sponge.getServer().getConsole().sendMessage(message);
    }
    // Well, you never know, the player might die or disconnect - we have to be vigilant.
    final Supplier<MessageReceiver> mr;
    if (src instanceof Player) {
        UUID uuid = ((Player) src).getUniqueId();
        mr = () -> Sponge.getServer().getPlayer(uuid).map(x -> (MessageReceiver) x).orElseGet(() -> new MessageReceiver() {

            @Override
            public void sendMessage(Text message) {
            }

            @Override
            public MessageChannel getMessageChannel() {
                return MessageChannel.TO_NONE;
            }

            @Override
            public void setMessageChannel(MessageChannel channel) {
            }
        });
    } else {
        mr = () -> src;
    }
    Sponge.getServer().copyWorld(worldToCopy, newName).handle((result, ex) -> {
        MessageReceiver m = mr.get();
        Text msg;
        if (ex == null && result.isPresent()) {
            msg = Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.world.clone.success", oldName, newName);
        } else {
            msg = Nucleus.getNucleus().getMessageProvider().getTextMessageWithFormat("command.world.clone.failed", oldName, newName);
        }
        m.sendMessage(msg);
        if (!(m instanceof ConsoleSource)) {
            Sponge.getServer().getConsole().sendMessage(msg);
        }
        return result;
    });
    return CommandResult.success();
}
Also used : Player(org.spongepowered.api.entity.living.player.Player) MessageChannel(org.spongepowered.api.text.channel.MessageChannel) MessageReceiver(org.spongepowered.api.text.channel.MessageReceiver) Text(org.spongepowered.api.text.Text) ConsoleSource(org.spongepowered.api.command.source.ConsoleSource) UUID(java.util.UUID) WorldProperties(org.spongepowered.api.world.storage.WorldProperties)

Example 4 with ConsoleSource

use of org.spongepowered.api.command.source.ConsoleSource in project Nucleus by NucleusPowered.

the class WorldCorrector method worldCheck.

public static void worldCheck() throws IOException, ObjectMappingException {
    final Map<String, UUID> m = get();
    // Now get the file out.
    Path path = Nucleus.getNucleus().getDataPath().resolve("worlduuids.json");
    ConfigurationLoader<ConfigurationNode> cl = GsonConfigurationLoader.builder().setPath(path).build();
    Map<String, UUID> ms = cl.load().getValue(new TypeToken<Map<String, UUID>>() {
    }, Maps.newHashMap());
    final Map<UUID, UUID> fromToConverter = Maps.newHashMap();
    for (String r : ms.keySet()) {
        UUID oldUuid = ms.get(r);
        @Nullable UUID newUuid = m.get(r);
        if (newUuid != null && !oldUuid.equals(newUuid)) {
            fromToConverter.put(newUuid, oldUuid);
        }
    }
    cl.save(cl.createEmptyNode().setValue(new TypeToken<Map<String, UUID>>() {
    }, m));
    if (fromToConverter.isEmpty()) {
        return;
    }
    MessageProvider mp = Nucleus.getNucleus().getMessageProvider();
    ConsoleSource cs = Sponge.getServer().getConsole();
    List<Text> msg = Lists.newArrayList();
    Nucleus.getNucleus().addX(msg, 0);
    msg.forEach(cs::sendMessage);
    cs.sendMessage(Text.of(TextColors.RED, "--------------------"));
    cs.sendMessage(mp.getTextMessageWithFormat("worldrepair.detected"));
    for (Map.Entry<UUID, UUID> u : fromToConverter.entrySet()) {
        cs.sendMessage(mp.getTextMessageWithFormat("worldrepair.worldlist", Sponge.getServer().getWorldProperties(u.getKey()).get().getWorldName(), u.getValue().toString(), u.getKey().toString()));
    }
    Method method;
    try {
        method = Sponge.getServer().getDefaultWorld().get().getClass().getDeclaredMethod("setUniqueId", UUID.class);
        method.setAccessible(true);
    } catch (NoSuchMethodException e) {
        cs.sendMessage(mp.getTextMessageWithFormat("worldrepair.whitelist.nocmd"));
        return;
    }
    cs.sendMessage(mp.getTextMessageWithFormat("worldrepair.whitelist.cmd"));
    cs.sendMessage(Text.of(TextColors.RED, "--------------------"));
    cs.sendMessage(mp.getTextMessageWithFormat("worldrepair.whitelist.cmd2"));
    Sponge.getServer().setHasWhitelist(true);
    Sponge.getCommandManager().register(Nucleus.getNucleus(), CommandSpec.builder().executor((s, a) -> {
        MessageProvider mpr = Nucleus.getNucleus().getMessageProvider();
        if (s instanceof ConsoleSource) {
            cs.sendMessage(mpr.getTextMessageWithFormat("worldrepair.repair.start"));
            Sponge.getEventManager().registerListener(Nucleus.getNucleus(), GameStoppedServerEvent.class, event -> {
                for (Map.Entry<UUID, UUID> meuu : fromToConverter.entrySet()) {
                    // Magic!
                    WorldProperties wp = Sponge.getServer().getWorldProperties(meuu.getKey()).orElseThrow(() -> new NoSuchElementException(mpr.getMessageWithFormat("worldrepair.repair.nouuid", meuu.getKey().toString())));
                    final String name = wp.getWorldName();
                    try {
                        cs.sendMessage(mpr.getTextMessageWithFormat("worldrepair.repair.try", name));
                        method.invoke(wp, meuu.getValue());
                        Sponge.getServer().saveWorldProperties(wp);
                        cs.sendMessage(mpr.getTextMessageWithFormat("worldrepair.repair.success", name));
                    } catch (Exception e) {
                        cs.sendMessage(mpr.getTextMessageWithFormat("worldrepair.repair.fail", name));
                        e.printStackTrace();
                    }
                }
                try {
                    cl.save(cl.createEmptyNode().setValue(new TypeToken<Map<String, UUID>>() {
                    }, get()));
                } catch (IOException | ObjectMappingException e) {
                    e.printStackTrace();
                }
            });
            Sponge.getServer().shutdown();
            return CommandResult.success();
        } else {
            s.sendMessage(mpr.getTextMessageWithFormat("command.consoleonly"));
            return CommandResult.empty();
        }
    }).build(), "repairuuids");
}
Also used : UUID(java.util.UUID) ObjectMappingException(ninja.leaping.configurate.objectmapping.ObjectMappingException) Path(java.nio.file.Path) MessageProvider(io.github.nucleuspowered.nucleus.internal.messages.MessageProvider) Text(org.spongepowered.api.text.Text) Method(java.lang.reflect.Method) IOException(java.io.IOException) NoSuchElementException(java.util.NoSuchElementException) IOException(java.io.IOException) ObjectMappingException(ninja.leaping.configurate.objectmapping.ObjectMappingException) ConfigurationNode(ninja.leaping.configurate.ConfigurationNode) TypeToken(com.google.common.reflect.TypeToken) ConsoleSource(org.spongepowered.api.command.source.ConsoleSource) Map(java.util.Map) Nullable(javax.annotation.Nullable) WorldProperties(org.spongepowered.api.world.storage.WorldProperties) NoSuchElementException(java.util.NoSuchElementException)

Example 5 with ConsoleSource

use of org.spongepowered.api.command.source.ConsoleSource in project Nucleus by NucleusPowered.

the class NucleusPlugin method onGameStarted.

@Listener
public void onGameStarted(GameStartedServerEvent event) {
    if (!this.isServer) {
        // on client, disable whitelist
        try {
            Sponge.getServer().setHasWhitelist(false);
        } catch (Throwable e) {
        // ignored
        }
    }
    if (isErrored == null) {
        try {
            getInternalServiceManager().getServiceUnchecked(UUIDChangeService.class).setStateAndReload();
            // for migration purposes
            this.generalService.loadInternal();
            // Save any additions.
            moduleContainer.refreshSystemConfig();
            fireReloadables();
        } catch (Throwable e) {
            isErrored = e;
            disable();
            errorOnStartup();
            return;
        }
        this.hasStarted = true;
        Sponge.getScheduler().createSyncExecutor(this).submit(() -> this.gameStartedTime = Instant.now());
        // What about perms and econ?
        List<Text> lt = Lists.newArrayList();
        if (ServiceChangeListener.isOpOnly()) {
            addTri(lt, 0);
            lt.add(messageProvider.getTextMessageWithFormat("standard.line"));
            lt.add(messageProvider.getTextMessageWithFormat("standard.nopermplugin"));
            lt.add(messageProvider.getTextMessageWithFormat("standard.nopermplugin2"));
        }
        if (!Sponge.getServiceManager().isRegistered(EconomyService.class)) {
            if (lt.isEmpty()) {
                addTri(lt, 0);
            }
            lt.add(messageProvider.getTextMessageWithFormat("standard.line"));
            lt.add(messageProvider.getTextMessageWithFormat("standard.noeconplugin"));
            lt.add(messageProvider.getTextMessageWithFormat("standard.noeconplugin2"));
        }
        if (!lt.isEmpty()) {
            lt.add(messageProvider.getTextMessageWithFormat("standard.line"));
            lt.add(messageProvider.getTextMessageWithFormat("standard.seesuggested"));
        }
        if (!this.startupMessages.isEmpty()) {
            if (lt.isEmpty()) {
                addTri(lt, 0);
            }
            lt.add(messageProvider.getTextMessageWithFormat("standard.line"));
            lt.addAll(this.startupMessages);
            this.startupMessages.clear();
        }
        if (!lt.isEmpty()) {
            lt.add(messageProvider.getTextMessageWithFormat("standard.line"));
            ConsoleSource c = Sponge.getServer().getConsole();
            lt.forEach(c::sendMessage);
        }
    }
}
Also used : UUIDChangeService(io.github.nucleuspowered.nucleus.modules.core.service.UUIDChangeService) EconomyService(org.spongepowered.api.service.economy.EconomyService) Text(org.spongepowered.api.text.Text) ConsoleSource(org.spongepowered.api.command.source.ConsoleSource) ServiceChangeListener(io.github.nucleuspowered.nucleus.internal.permissions.ServiceChangeListener) Listener(org.spongepowered.api.event.Listener)

Aggregations

ConsoleSource (org.spongepowered.api.command.source.ConsoleSource)10 Text (org.spongepowered.api.text.Text)8 UUID (java.util.UUID)3 Nullable (javax.annotation.Nullable)3 CommandSource (org.spongepowered.api.command.CommandSource)3 Player (org.spongepowered.api.entity.living.player.Player)3 WorldProperties (org.spongepowered.api.world.storage.WorldProperties)3 IOException (java.io.IOException)2 List (java.util.List)2 Lantern (org.lanternpowered.server.game.Lantern)2 TranslationHelper.t (org.lanternpowered.server.text.translation.TranslationHelper.t)2 CommandException (org.spongepowered.api.command.CommandException)2 CommandResult (org.spongepowered.api.command.CommandResult)2 ArgumentParseException (org.spongepowered.api.command.args.ArgumentParseException)2 CommandArgs (org.spongepowered.api.command.args.CommandArgs)2 CommandContext (org.spongepowered.api.command.args.CommandContext)2 CommandElement (org.spongepowered.api.command.args.CommandElement)2 GenericArguments (org.spongepowered.api.command.args.GenericArguments)2 CommandSpec (org.spongepowered.api.command.spec.CommandSpec)2 Vector3d (com.flowpowered.math.vector.Vector3d)1