Search in sources :

Example 61 with CommandSource

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

the class BanEntry method getBanCommandSource.

@SuppressWarnings("deprecation")
@Override
public Optional<CommandSource> getBanCommandSource() {
    if (this.source == null) {
        return Optional.empty();
    }
    CommandSource source;
    if (this.commandSource != null && (source = this.commandSource.get()) != null) {
        return Optional.of(source);
    }
    String plainSource = LanternTexts.toLegacy(this.source);
    if (plainSource.equals(LanternConsoleSource.NAME)) {
        source = Sponge.getServer().getConsole();
    } else {
        source = Sponge.getServer().getPlayer(plainSource).orElse(null);
    }
    if (source != null) {
        this.commandSource = new WeakReference<>(source);
    }
    return Optional.ofNullable(source);
}
Also used : CommandSource(org.spongepowered.api.command.CommandSource)

Example 62 with CommandSource

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

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

Example 64 with CommandSource

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

the class UCMessages method mention.

private static String mention(Object sender, Object receiver, String msg) {
    if (UChat.get().getConfig().root().mention.enable) {
        for (Player p : Sponge.getServer().getOnlinePlayers()) {
            if (!sender.equals(p) && Arrays.stream(msg.split(" ")).anyMatch(p.getName()::equalsIgnoreCase)) {
                if (receiver instanceof Player && receiver.equals(p)) {
                    String mentionc = UChat.get().getConfig().root().mention.color_template.replace("{mentioned-player}", p.getName());
                    mentionc = formatTags("", mentionc, sender, p, "", new UCChannel("mention"));
                    if (msg.contains(mentionc) || sender instanceof CommandSource && !UChat.get().getPerms().hasPerm((CommandSource) sender, "chat.mention")) {
                        msg = msg.replaceAll("(?i)\\b" + p.getName() + "\\b", p.getName());
                        continue;
                    }
                    Optional<SoundType> sound = Sponge.getRegistry().getType(SoundType.class, UChat.get().getConfig().root().mention.playsound);
                    if (sound.isPresent() && !msg.contains(mentionc)) {
                        p.playSound(sound.get(), p.getLocation().getPosition(), 1, 1);
                    }
                    msg = msg.replace(mentionc, p.getName());
                    msg = msg.replaceAll("(?i)\\b" + p.getName() + "\\b", mentionc);
                } else {
                    msg = msg.replaceAll("(?i)\\b" + p.getName() + "\\b", p.getName());
                }
            }
        }
    }
    return msg;
}
Also used : SoundType(org.spongepowered.api.effect.sound.SoundType) Player(org.spongepowered.api.entity.living.player.Player) ClanPlayer(nl.riebie.mcclans.api.ClanPlayer) CommandSource(org.spongepowered.api.command.CommandSource)

Example 65 with CommandSource

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

the class UCMessages method sendFancyMessage.

static MutableMessageChannel sendFancyMessage(String[] format, Text msg, UCChannel channel, CommandSource sender, CommandSource tellReceiver) {
    // Execute listener:
    HashMap<String, String> tags = new HashMap<>();
    for (String str : UChat.get().getConfig().root().general.custom_tags) {
        tags.put(str, str);
    }
    SendChannelMessageEvent event = new SendChannelMessageEvent(tags, format, sender, channel, msg, true);
    Sponge.getEventManager().post(event);
    if (event.isCancelled()) {
        return null;
    }
    registeredReplacers = event.getResgisteredTags();
    defFormat = event.getDefFormat();
    String evmsg = event.getMessage().toPlain();
    // send to event
    MutableMessageChannel msgCh = MessageChannel.TO_CONSOLE.asMutable();
    evmsg = UCChatProtection.filterChatMessage(sender, evmsg, event.getChannel());
    if (evmsg == null) {
        return null;
    }
    HashMap<CommandSource, Text> msgPlayers = new HashMap<>();
    evmsg = composeColor(sender, evmsg);
    Text srcText = Text.builder(event.getMessage(), evmsg).build();
    if (event.getChannel() != null) {
        UCChannel ch = event.getChannel();
        if (sender instanceof Player && !ch.availableWorlds().isEmpty() && !ch.availableInWorld(((Player) sender).getWorld())) {
            UChat.get().getLang().sendMessage(sender, UChat.get().getLang().get("channel.notavailable").replace("{channel}", ch.getName()));
            return null;
        }
        if (!UChat.get().getPerms().channelWritePerm(sender, ch)) {
            UChat.get().getLang().sendMessage(sender, UChat.get().getLang().get("channel.nopermission").replace("{channel}", ch.getName()));
            return null;
        }
        if (!UChat.get().getPerms().hasPerm(sender, "bypass.cost") && UChat.get().getEco() != null && sender instanceof Player && ch.getCost() > 0) {
            UniqueAccount acc = UChat.get().getEco().getOrCreateAccount(((Player) sender).getUniqueId()).get();
            if (acc.getBalance(UChat.get().getEco().getDefaultCurrency()).doubleValue() < ch.getCost()) {
                sender.sendMessage(UCUtil.toText(UChat.get().getLang().get("channel.cost").replace("{value}", "" + ch.getCost())));
                return null;
            } else {
                acc.withdraw(UChat.get().getEco().getDefaultCurrency(), BigDecimal.valueOf(ch.getCost()), UChat.get().getVHelper().getCause(UChat.get().instance()));
            }
        }
        int noWorldReceived = 0;
        int vanish = 0;
        List<Player> receivers = new ArrayList<>();
        // put sender
        msgPlayers.put(sender, sendMessage(sender, sender, srcText, ch, false));
        msgCh.addMember(sender);
        if (ch.getDistance() > 0 && sender instanceof Player) {
            for (Player play : ((Player) sender).getNearbyEntities(ch.getDistance()).stream().filter(ent -> ent instanceof Player).map(p -> (Player) p).collect(Collectors.toList())) {
                if (UChat.get().getPerms().channelReadPerm(play, ch)) {
                    if (sender.equals(play)) {
                        continue;
                    }
                    if (!ch.availableWorlds().isEmpty() && !ch.availableInWorld(play.getWorld())) {
                        continue;
                    }
                    if (ch.isIgnoring(play.getName())) {
                        continue;
                    }
                    if (isIgnoringPlayers(play.getName(), sender.getName())) {
                        noWorldReceived++;
                        continue;
                    }
                    if (!((Player) sender).canSee(play)) {
                        vanish++;
                    }
                    if (!ch.neeFocus() || ch.isMember(play)) {
                        msgPlayers.put(play, sendMessage(sender, play, srcText, ch, false));
                        receivers.add(play);
                        msgCh.addMember(play);
                    }
                }
            }
        } else {
            for (Player receiver : Sponge.getServer().getOnlinePlayers()) {
                if (receiver.equals(sender) || !UChat.get().getPerms().channelReadPerm(receiver, ch) || (!ch.crossWorlds() && (sender instanceof Player && !receiver.getWorld().equals(((Player) sender).getWorld())))) {
                    continue;
                }
                if (!ch.availableWorlds().isEmpty() && !ch.availableInWorld(receiver.getWorld())) {
                    continue;
                }
                if (ch.isIgnoring(receiver.getName())) {
                    continue;
                }
                if (isIgnoringPlayers(receiver.getName(), sender.getName())) {
                    noWorldReceived++;
                    continue;
                }
                if (sender instanceof Player && !((Player) sender).canSee(receiver)) {
                    vanish++;
                } else {
                    noWorldReceived++;
                }
                if (!ch.neeFocus() || ch.isMember(receiver)) {
                    msgPlayers.put(receiver, sendMessage(sender, receiver, srcText, ch, false));
                    receivers.add(receiver);
                    msgCh.addMember(receiver);
                }
            }
        }
        // chat spy
        if (!sender.hasPermission("uchat.chat-spy.bypass")) {
            for (Player receiver : Sponge.getServer().getOnlinePlayers()) {
                if (!receiver.equals(sender) && !receivers.contains(receiver) && !receivers.contains(sender) && UChat.get().isSpy.contains(receiver.getName()) && UChat.get().getPerms().hasSpyPerm(receiver, ch.getName())) {
                    String spyformat = UChat.get().getConfig().root().general.spy_format;
                    spyformat = spyformat.replace("{output}", UCUtil.stripColor(sendMessage(sender, receiver, srcText, ch, true).toPlain()));
                    receiver.sendMessage(UCUtil.toText(spyformat));
                }
            }
        }
        if (ch.getDistance() == 0 && noWorldReceived <= 0) {
            if (ch.getReceiversMsg()) {
                UChat.get().getLang().sendMessage(sender, "channel.noplayer.world");
            }
        }
        if ((receivers.size() - vanish) <= 0) {
            if (ch.getReceiversMsg()) {
                UChat.get().getLang().sendMessage(sender, "channel.noplayer.near");
            }
        }
    } else {
        if (UChat.get().msgTogglePlayers.contains(tellReceiver.getName()) && !sender.hasPermission("uchat.msgtoggle.exempt")) {
            UChat.get().getLang().sendMessage(sender, "cmd.msgtoggle.msgdisabled");
            return null;
        }
        channel = new UCChannel("tell");
        // send spy
        if (!sender.hasPermission("uchat.chat-spy.bypass")) {
            for (Player receiver : Sponge.getServer().getOnlinePlayers()) {
                if (!receiver.equals(tellReceiver) && !receiver.equals(sender) && UChat.get().isSpy.contains(receiver.getName()) && UChat.get().getPerms().hasSpyPerm(receiver, "private")) {
                    String spyformat = UChat.get().getConfig().root().general.spy_format;
                    if (isIgnoringPlayers(tellReceiver.getName(), sender.getName())) {
                        spyformat = UChat.get().getLang().get("chat.ignored") + spyformat;
                    }
                    spyformat = spyformat.replace("{output}", UCUtil.stripColor(sendMessage(sender, tellReceiver, srcText, channel, true).toPlain()));
                    receiver.sendMessage(UCUtil.toText(spyformat));
                }
            }
        }
        Text to = sendMessage(sender, tellReceiver, srcText, channel, false);
        msgPlayers.put(tellReceiver, to);
        msgPlayers.put(sender, to);
        if (isIgnoringPlayers(tellReceiver.getName(), sender.getName())) {
            to = Text.of(UCUtil.toText(UChat.get().getLang().get("chat.ignored")), to);
        }
        msgPlayers.put(Sponge.getServer().getConsole(), to);
    }
    if (!msgPlayers.keySet().contains(Sponge.getServer().getConsole())) {
        msgPlayers.put(Sponge.getServer().getConsole(), msgPlayers.values().stream().findAny().get());
    }
    PostFormatChatMessageEvent postEvent = new PostFormatChatMessageEvent(sender, msgPlayers, channel);
    Sponge.getEventManager().post(postEvent);
    if (postEvent.isCancelled()) {
        return null;
    }
    msgPlayers.forEach((send, text) -> {
        UChat.get().getLogger().timings(timingType.END, "UCMessages#send()|before send");
        send.sendMessage(text);
        UChat.get().getLogger().timings(timingType.END, "UCMessages#send()|after send");
    });
    // send to jedis
    if (channel != null && !channel.isTell() && UChat.get().getJedis() != null) {
        UChat.get().getJedis().sendMessage(channel.getName().toLowerCase(), msgPlayers.get(sender));
    }
    // send to jda
    if (channel != null && UChat.get().getUCJDA() != null) {
        if (channel.isTell()) {
            UChat.get().getUCJDA().sendTellToDiscord(msgPlayers.get(sender).toPlain());
        } else {
            UChat.get().getUCJDA().sendToDiscord(sender, evmsg, channel);
        }
    }
    return msgCh;
}
Also used : java.util(java.util) Keys(org.spongepowered.api.data.key.Keys) URL(java.net.URL) TextTemplate(org.spongepowered.api.text.TextTemplate) ItemTypes(org.spongepowered.api.item.ItemTypes) SimpleDateFormat(java.text.SimpleDateFormat) StringUtils(org.apache.commons.lang3.StringUtils) BigDecimal(java.math.BigDecimal) ItemStack(org.spongepowered.api.item.inventory.ItemStack) Matcher(java.util.regex.Matcher) Text(org.spongepowered.api.text.Text) Subject(org.spongepowered.api.service.permission.Subject) UCLogger.timingType(br.net.fabiozumbi12.UltimateChat.Sponge.UCLogger.timingType) TextUtils(me.rojo8399.placeholderapi.impl.utils.TextUtils) MutableMessageChannel(org.spongepowered.api.text.channel.MutableMessageChannel) PlaceholderService(me.rojo8399.placeholderapi.PlaceholderService) TextActions(org.spongepowered.api.text.action.TextActions) SendChannelMessageEvent(br.net.fabiozumbi12.UltimateChat.Sponge.API.SendChannelMessageEvent) CommandSource(org.spongepowered.api.command.CommandSource) MalformedURLException(java.net.MalformedURLException) SoundType(org.spongepowered.api.effect.sound.SoundType) Builder(org.spongepowered.api.text.Text.Builder) Sponge(org.spongepowered.api.Sponge) PostFormatChatMessageEvent(br.net.fabiozumbi12.UltimateChat.Sponge.API.PostFormatChatMessageEvent) Entity(org.spongepowered.api.entity.Entity) Collectors(java.util.stream.Collectors) ExecutionException(java.util.concurrent.ExecutionException) TextSerializers(org.spongepowered.api.text.serializer.TextSerializers) ClanService(nl.riebie.mcclans.api.ClanService) NucleusAPI(io.github.nucleuspowered.nucleus.api.NucleusAPI) HandTypes(org.spongepowered.api.data.type.HandTypes) MessageChannel(org.spongepowered.api.text.channel.MessageChannel) Player(org.spongepowered.api.entity.living.player.Player) Pattern(java.util.regex.Pattern) ClanPlayer(nl.riebie.mcclans.api.ClanPlayer) UniqueAccount(org.spongepowered.api.service.economy.account.UniqueAccount) Player(org.spongepowered.api.entity.living.player.Player) ClanPlayer(nl.riebie.mcclans.api.ClanPlayer) UniqueAccount(org.spongepowered.api.service.economy.account.UniqueAccount) Text(org.spongepowered.api.text.Text) CommandSource(org.spongepowered.api.command.CommandSource) PostFormatChatMessageEvent(br.net.fabiozumbi12.UltimateChat.Sponge.API.PostFormatChatMessageEvent) SendChannelMessageEvent(br.net.fabiozumbi12.UltimateChat.Sponge.API.SendChannelMessageEvent) MutableMessageChannel(org.spongepowered.api.text.channel.MutableMessageChannel)

Aggregations

CommandSource (org.spongepowered.api.command.CommandSource)91 Text (org.spongepowered.api.text.Text)60 CommandResult (org.spongepowered.api.command.CommandResult)48 List (java.util.List)47 CommandContext (org.spongepowered.api.command.args.CommandContext)45 Collectors (java.util.stream.Collectors)37 Sponge (org.spongepowered.api.Sponge)37 Player (org.spongepowered.api.entity.living.player.Player)36 Optional (java.util.Optional)35 TextColors (org.spongepowered.api.text.format.TextColors)30 CommandElement (org.spongepowered.api.command.args.CommandElement)27 TextActions (org.spongepowered.api.text.action.TextActions)27 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 GenericArguments (org.spongepowered.api.command.args.GenericArguments)23 Util (io.github.nucleuspowered.nucleus.Util)20 Nullable (javax.annotation.Nullable)20 Map (java.util.Map)19