use of org.spongepowered.api.command.CommandSource 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();
});
}
use of org.spongepowered.api.command.CommandSource 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();
});
}
use of org.spongepowered.api.command.CommandSource in project LanternServer by LanternPowered.
the class HandlerPlayInTabComplete method handle.
@Override
public void handle(NetworkContext context, MessagePlayInTabComplete message) {
final String text = message.getText();
// The content with normalized spaces, the spaces are trimmed
// from the ends and there are never two spaces directly after eachother
final String textNormalized = StringUtils.normalizeSpace(text);
final Player player = context.getSession().getPlayer();
final Location<World> targetBlock = message.getBlockPosition().map(pos -> new Location<>(player.getWorld(), pos)).orElse(null);
final boolean hasPrefix = textNormalized.startsWith("/");
if (hasPrefix || message.getAssumeCommand()) {
String command = textNormalized;
// Don't include the '/'
if (hasPrefix) {
command = command.substring(1);
}
// Keep the last space, it must be there!
if (text.endsWith(" ")) {
command = command + " ";
}
// Get the suggestions
List<String> suggestions = ((LanternCommandManager) Sponge.getCommandManager()).getSuggestions(player, command, targetBlock, message.getAssumeCommand());
// If the suggestions are for the command and there was a prefix, then append the prefix
if (hasPrefix && command.split(" ").length == 1 && !command.endsWith(" ")) {
suggestions = suggestions.stream().map(suggestion -> '/' + suggestion).collect(ImmutableList.toImmutableList());
}
context.getSession().send(new MessagePlayOutTabComplete(suggestions));
} else {
// Vanilla mc will complete user names if
// no command is being completed
final int index = text.lastIndexOf(' ');
final String part;
if (index == -1) {
part = text;
} else {
part = text.substring(index + 1);
}
if (part.isEmpty()) {
return;
}
final String part1 = part.toLowerCase();
final List<String> suggestions = Sponge.getServer().getOnlinePlayers().stream().map(CommandSource::getName).filter(n -> n.toLowerCase().startsWith(part1)).collect(Collectors.toList());
final Cause cause = Cause.of(EventContext.empty(), context.getSession().getPlayer());
final TabCompleteEvent.Chat event = SpongeEventFactory.createTabCompleteEventChat(cause, ImmutableList.copyOf(suggestions), suggestions, text, Optional.ofNullable(targetBlock), false);
if (!Sponge.getEventManager().post(event)) {
context.getSession().send(new MessagePlayOutTabComplete(suggestions));
}
}
}
use of org.spongepowered.api.command.CommandSource in project UltimateChat by FabioZumbi12.
the class UCMessages method formatTags.
public static String formatTags(String tag, String text, Object cmdSender, Object receiver, String msg, UCChannel ch) {
if (receiver instanceof CommandSource && tag.equals("message")) {
text = text.replace("{message}", mention(cmdSender, receiver, msg));
if (UChat.get().getConfig().root().general.item_hand.enable) {
text = text.replace(UChat.get().getConfig().root().general.item_hand.placeholder, formatTags("", UCUtil.toColor(UChat.get().getConfig().root().general.item_hand.format), cmdSender, receiver, msg, ch));
}
} else {
text = text.replace("{message}", msg);
}
if (tag.equals("message") && !UChat.get().getConfig().root().general.enable_tags_on_messages) {
return text;
}
text = text.replace("{ch-color}", ch.getColor()).replace("{ch-name}", ch.getName()).replace("{ch-alias}", ch.getAlias());
if (UChat.get().getConfig().root().jedis.enable && ch.useJedis()) {
text = text.replace("{jedis-id}", UChat.get().getConfig().root().jedis.server_id);
}
if (cmdSender instanceof CommandSource) {
text = text.replace("{playername}", ((CommandSource) cmdSender).getName());
if (receiver instanceof CommandSource) {
text = text.replace("{receivername}", ((CommandSource) receiver).getName());
}
if (receiver instanceof String) {
text = text.replace("{receivername}", receiver.toString());
}
} else {
text = text.replace("{playername}", (String) cmdSender);
if (receiver instanceof CommandSource)
text = text.replace("{receivername}", ((CommandSource) receiver).getName());
if (receiver instanceof String)
text = text.replace("{receivername}", (String) receiver);
}
for (String repl : registeredReplacers.keySet()) {
if (registeredReplacers.get(repl).equals(repl)) {
text = text.replace(repl, "");
continue;
}
text = text.replace(repl, registeredReplacers.get(repl));
}
if (defFormat.length > 0) {
StringBuilder all = new StringBuilder();
for (int i = 0; i < defFormat.length; i++) {
if (i == 0)
text = text.replace("{chat_header}", defFormat[i]);
if (i == 1)
text = text.replace("{chat_body}", defFormat[i]);
if (i == 2)
text = text.replace("{chat_footer}", defFormat[i]);
all.append(defFormat[i]);
}
text = text.replace("{chat_all}", all.toString());
}
if (text.contains("{time-now}")) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
text = text.replace("{time-now}", sdf.format(cal.getTime()));
}
if (cmdSender instanceof Player) {
Player sender = (Player) cmdSender;
if (text.contains("{nickname}") && sender.get(Keys.DISPLAY_NAME).isPresent()) {
String nick = sender.get(Keys.DISPLAY_NAME).get().toPlain();
if (!nick.equals(sender.getName())) {
text = text.replace("{nickname}", nick);
text = text.replace("{nick-symbol}", UChat.get().getConfig().root().general.nick_symbol);
} else if (Sponge.getPluginManager().getPlugin("nucleus").isPresent() && NucleusAPI.getNicknameService().isPresent()) {
Optional<Text> opNick = NucleusAPI.getNicknameService().get().getNickname(sender);
if (opNick.isPresent()) {
nick = TextSerializers.FORMATTING_CODE.serialize(opNick.get());
text = text.replace("{nick-symbol}", UChat.get().getConfig().root().general.nick_symbol);
}
}
text = text.replace("{nickname}", nick);
}
// replace item hand
text = text.replace(UChat.get().getConfig().root().general.item_hand.placeholder, UCUtil.toColor(UChat.get().getConfig().root().general.item_hand.format));
ItemStack item = null;
if (sender.getItemInHand(HandTypes.MAIN_HAND).isPresent()) {
item = sender.getItemInHand(HandTypes.MAIN_HAND).get();
} else if (sender.getItemInHand(HandTypes.OFF_HAND).isPresent()) {
item = sender.getItemInHand(HandTypes.OFF_HAND).get();
}
if (text.contains("{hand-") && item != null) {
text = text.replace("{hand-durability}", item.get(Keys.ITEM_DURABILITY).isPresent() ? String.valueOf(item.get(Keys.ITEM_DURABILITY).get()) : "").replace("{hand-name}", item.getItem().getTranslation().get());
if (item.get(Keys.ITEM_LORE).isPresent()) {
StringBuilder lorestr = new StringBuilder();
for (Text line : item.get(Keys.ITEM_LORE).get()) {
lorestr.append("\n ").append(line.toPlain());
}
if (lorestr.length() >= 2) {
text = text.replace("{hand-lore}", lorestr.toString().substring(0, lorestr.length() - 1));
}
}
if (item.get(Keys.ITEM_ENCHANTMENTS).isPresent()) {
StringBuilder str = new StringBuilder();
str.append(UChat.get().getVHelper().getEnchantments(str, item));
if (str.length() >= 2) {
text = text.replace("{hand-enchants}", str.toString().substring(0, str.length() - 1));
}
}
text = text.replace("{hand-amount}", String.valueOf(item.getQuantity()));
text = text.replace("{hand-name}", item.getItem().getName());
text = text.replace("{hand-type}", item.getItem().getTranslation().get());
} else {
text = text.replace("{hand-name}", UChat.get().getLang().get("chat.emptyslot"));
text = text.replace("{hand-type}", "Air");
}
if (text.contains("{world}")) {
String world = sender.getWorld().getName();
text = text.replace("{world}", UChat.get().getConfig().root().general.world_names.getOrDefault(world, world));
}
if (text.contains("{balance}") && UChat.get().getEco() != null) {
UniqueAccount acc = UChat.get().getEco().getOrCreateAccount(sender.getUniqueId()).get();
text = text.replace("{balance}", "" + acc.getBalance(UChat.get().getEco().getDefaultCurrency()).intValue());
}
// parse permissions options
try {
// player options
Pattern pp = Pattern.compile("\\{player_option_(.+?)\\}");
Matcher pm = pp.matcher(text);
while (pm.find()) {
if (sender.getOption(pm.group(1)).isPresent() && !text.contains(sender.getOption(pm.group(1)).get())) {
text = text.replace("{player_option_" + pm.group(1) + "}", sender.getOption(pm.group(1)).get());
pm = pp.matcher(text);
}
}
// group options
Subject sub = UChat.get().getPerms().getGroupAndTag(sender);
if (sub != null) {
text = text.replace("{option_group}", UChat.get().getConfig().root().general.group_names.getOrDefault(sub.getIdentifier(), sub.getIdentifier()));
if (sub.getOption("display_name").isPresent()) {
text = text.replace("{option_display_name}", sub.getOption("display_name").get());
} else {
text = text.replace("{option_display_name}", UChat.get().getConfig().root().general.group_names.getOrDefault(sub.getIdentifier(), sub.getIdentifier()));
}
Pattern gp = Pattern.compile("\\{option_(.+?)\\}");
Matcher gm = gp.matcher(text);
while (gm.find()) {
if (sub.getOption(gm.group(1)).isPresent() && !text.contains(sub.getOption(gm.group(1)).get())) {
text = text.replace("{option_" + gm.group(1) + "}", sub.getOption(gm.group(1)).get());
gm = gp.matcher(text);
}
}
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
if (text.contains("{clan_") && UChat.get().getConfig().root().hooks.MCClans.enable) {
Optional<ClanService> clanServiceOpt = Sponge.getServiceManager().provide(ClanService.class);
if (clanServiceOpt.isPresent()) {
ClanService clan = clanServiceOpt.get();
ClanPlayer cp = clan.getClanPlayer(sender.getUniqueId());
if (cp != null && cp.isMemberOfAClan()) {
text = text.replace("{clan_name}", checkEmpty(cp.getClan().getName())).replace("{clan_tag}", cp.getClan().getTag()).replace("{clan_tag_color}", TextSerializers.FORMATTING_CODE.serialize(cp.getClan().getTagColored())).replace("{clan_kdr}", "" + cp.getClan().getKDR()).replace("{clan_player_rank}", checkEmpty(cp.getRank().getName())).replace("{clan_player_kdr}", "" + cp.getKillDeath().getKDR()).replace("{clan_player_ffprotected}", String.valueOf(cp.isFfProtected())).replace("{clan_player_isowner}", String.valueOf(cp.getClan().getOwner().equals(cp)));
}
}
}
if (Sponge.getPluginManager().getPlugin("placeholderapi").isPresent()) {
Optional<PlaceholderService> phapiOpt = Sponge.getServiceManager().provide(PlaceholderService.class);
Pattern p = Pattern.compile("\\%([^\\%]*)\\%");
if (phapiOpt.isPresent() && p.matcher(text).find()) {
PlaceholderService phapi = phapiOpt.get();
// fix last color from string
String lastcolor = text.length() > 1 ? text.substring(text.length() - 2, text.length()) : "";
if (!Pattern.compile("(&([A-Fa-fK-Ok-oRr0-9]))").matcher(lastcolor).find())
lastcolor = "";
text = TextSerializers.FORMATTING_CODE.serialize(phapi.replacePlaceholders(text, sender, receiver, p)) + lastcolor;
}
}
}
text = text.replace("{option_suffix}", "&r: ");
if (cmdSender instanceof CommandSource) {
text = text.replace("{nickname}", UChat.get().getConfig().root().general.console_tag.replace("{console}", ((CommandSource) cmdSender).getName()));
} else {
text = text.replace("{nickname}", UChat.get().getConfig().root().general.console_tag.replace("{console}", (String) cmdSender));
}
// remove blank items
text = text.replaceAll("\\{.*\\}", "");
if (!tag.equals("message")) {
for (String rpl : UChat.get().getConfig().root().general.remove_from_chat) {
text = text.replace(UCUtil.toColor(rpl), "");
}
}
if (text.equals(" ") || text.equals(" ")) {
return text = "";
}
return text;
}
use of org.spongepowered.api.command.CommandSource in project SpongeAPI by SpongePowered.
the class GenericArgumentsTest method testGettingSinglePlayer.
@Test
public void testGettingSinglePlayer() throws Exception {
CommandArgs args = new CommandArgs("test1", Lists.newArrayList(new SingleArg("test1", 0, 5)));
CommandContext context = new CommandContext();
CommandSource source = Mockito.mock(CommandSource.class);
getPlayerElement().parse(source, args, context);
assertEquals("test1", context.<Player>getOne(Text.of("player")).get().getName());
}
Aggregations