Search in sources :

Example 1 with TextRepresentable

use of org.spongepowered.api.text.TextRepresentable in project Nucleus by NucleusPowered.

the class TextParsingUtils method createTextTemplateFragmentWithLinks.

public Tuples.NullableTuple<List<TextRepresentable>, Map<String, Function<CommandSource, Text>>> createTextTemplateFragmentWithLinks(String message) {
    Preconditions.checkNotNull(message, "message");
    if (message.isEmpty()) {
        return new Tuples.NullableTuple<>(Lists.newArrayList(Text.EMPTY), null);
    }
    Matcher m = enhancedUrlParser.matcher(message);
    if (!m.find()) {
        return new Tuples.NullableTuple<>(Lists.newArrayList(oldLegacy(message)), null);
    }
    Map<String, Function<CommandSource, Text>> args = Maps.newHashMap();
    List<TextRepresentable> texts = Lists.newArrayList();
    String remaining = message;
    StyleTuple st = TextParsingUtils.EMPTY;
    do {
        // We found a URL. We split on the URL that we have.
        String[] textArray = remaining.split(enhancedUrlParser.pattern(), 2);
        TextRepresentable first = Text.builder().color(st.colour).style(st.style).append(oldLegacy(textArray[0])).build();
        // Add this text to the list regardless.
        texts.add(first);
        // If we have more to do, shove it into the "remaining" variable.
        if (textArray.length == 2) {
            remaining = textArray[1];
        } else {
            remaining = null;
        }
        // Get the last colour & styles
        String colourMatch = m.group("colour");
        if (colourMatch != null && !colourMatch.isEmpty()) {
            // If there is a reset, explicitly do it.
            TextStyle reset = TextStyles.NONE;
            if (m.group("reset") != null) {
                reset = TextStyles.RESET;
            }
            first = Text.of(reset, oldLegacy(m.group("colour")));
        }
        st = getLastColourAndStyle(first, st);
        // Build the URL
        String whiteSpace = m.group("first");
        if (m.group("url") != null) {
            String url = m.group("url");
            texts.add(getTextForUrl(url, url, whiteSpace, st, m.group("options")));
        } else if (m.group("specialUrl") != null) {
            String url = m.group("sUrl");
            String msg = m.group("msg");
            texts.add(getTextForUrl(url, msg, whiteSpace, st, m.group("optionssurl")));
        } else {
            // Must be commands.
            String cmd = m.group("sCmd");
            String msg = m.group("sMsg");
            String optionList = m.group("optionsscmd");
            if (cmd.contains("{{subject}}")) {
                String arg = UUID.randomUUID().toString();
                args.put(arg, cs -> {
                    String command = cmd.replace("{{subject}}", cs.getName());
                    return getCmd(msg, command, optionList, whiteSpace);
                });
                texts.add(TextTemplate.arg(arg).color(st.colour).style(st.style).build());
            } else {
                texts.add(Text.of(st.colour, st.style, getCmd(msg, cmd, optionList, whiteSpace)));
            }
        }
    } while (remaining != null && m.find());
    // Add the last bit.
    if (remaining != null) {
        Text.Builder tb = Text.builder().color(st.colour).style(st.style).append(TextSerializers.FORMATTING_CODE.deserialize(remaining));
        if (remaining.matches("^\\s+&r.*")) {
            tb.style(TextStyles.RESET);
        }
        texts.add(tb.build());
    }
    // Return the list.
    return new Tuples.NullableTuple<>(texts, args);
}
Also used : TextRepresentable(org.spongepowered.api.text.TextRepresentable) TextStyle(org.spongepowered.api.text.format.TextStyle) Arrays(java.util.Arrays) TextRepresentable(org.spongepowered.api.text.TextRepresentable) NucleusPlugin(io.github.nucleuspowered.nucleus.NucleusPlugin) URL(java.net.URL) TextTemplate(org.spongepowered.api.text.TextTemplate) NonnullByDefault(org.spongepowered.api.util.annotation.NonnullByDefault) Function(java.util.function.Function) CoreModule(io.github.nucleuspowered.nucleus.modules.core.CoreModule) CoreConfigAdapter(io.github.nucleuspowered.nucleus.modules.core.config.CoreConfigAdapter) Lists(com.google.common.collect.Lists) Matcher(java.util.regex.Matcher) Text(org.spongepowered.api.text.Text) TextColor(org.spongepowered.api.text.format.TextColor) Map(java.util.Map) HoverAction(org.spongepowered.api.text.action.HoverAction) TextColors(org.spongepowered.api.text.format.TextColors) Nullable(javax.annotation.Nullable) TextActions(org.spongepowered.api.text.action.TextActions) Nucleus(io.github.nucleuspowered.nucleus.Nucleus) User(org.spongepowered.api.entity.living.player.User) Iterator(java.util.Iterator) CommandSource(org.spongepowered.api.command.CommandSource) MalformedURLException(java.net.MalformedURLException) TextStyles(org.spongepowered.api.text.format.TextStyles) UUID(java.util.UUID) Maps(com.google.common.collect.Maps) Consumer(java.util.function.Consumer) TextSerializers(org.spongepowered.api.text.serializer.TextSerializers) List(java.util.List) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) Tuples(io.github.nucleuspowered.nucleus.util.Tuples) Player(org.spongepowered.api.entity.living.player.Player) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) Text(org.spongepowered.api.text.Text) Function(java.util.function.Function) TextStyle(org.spongepowered.api.text.format.TextStyle)

Example 2 with TextRepresentable

use of org.spongepowered.api.text.TextRepresentable in project LanternServer by LanternPowered.

the class JsonTextTranslatableSerializer method serialize.

@SuppressWarnings("deprecation")
@Override
public JsonElement serialize(TranslatableText src, Type typeOfSrc, JsonSerializationContext context) {
    final Translation translation = src.getTranslation();
    if (this.networkingFormat && !(translation instanceof MinecraftTranslation)) {
        final ImmutableList<Object> arguments = src.getArguments();
        final Object[] rawArguments = arguments.toArray(new Object[arguments.size()]);
        final Locale locale = currentLocale.get();
        for (int i = 0; i < rawArguments.length; i++) {
            Object object = rawArguments[i];
            if (object instanceof TextRepresentable) {
                if (!(object instanceof Text)) {
                    object = ((TextRepresentable) object).toText();
                }
                rawArguments[i] = ((LanternTextSerializer) TextSerializers.LEGACY_FORMATTING_CODE).serialize((Text) object, locale);
            } else {
                rawArguments[i] = object.toString();
            }
        }
        final String content = src.getTranslation().get(locale, rawArguments);
        return JsonTextLiteralSerializer.serializeLiteralText(src, content, context, this.removeComplexity);
    }
    final JsonObject obj = new JsonObject();
    obj.addProperty(TRANSLATABLE, src.getTranslation().getId());
    final ImmutableList<Object> arguments = src.getArguments();
    if (!arguments.isEmpty()) {
        final JsonArray argumentsArray = new JsonArray();
        for (Object object : arguments) {
            // so we need to convert the objects if possible
            if (object instanceof TextRepresentable) {
                if (!(object instanceof Text)) {
                    object = ((TextRepresentable) object).toText();
                }
                argumentsArray.add(context.serialize(object, Text.class));
            } else {
                argumentsArray.add(new JsonPrimitive(object.toString()));
            }
        }
        obj.add(TRANSLATABLE_ARGS, argumentsArray);
    }
    serialize(obj, src, context);
    return obj;
}
Also used : Locale(java.util.Locale) TextRepresentable(org.spongepowered.api.text.TextRepresentable) MinecraftTranslation(org.lanternpowered.server.text.translation.MinecraftTranslation) Translation(org.spongepowered.api.text.translation.Translation) JsonPrimitive(com.google.gson.JsonPrimitive) JsonObject(com.google.gson.JsonObject) Text(org.spongepowered.api.text.Text) TranslatableText(org.spongepowered.api.text.TranslatableText) JsonArray(com.google.gson.JsonArray) MinecraftTranslation(org.lanternpowered.server.text.translation.MinecraftTranslation) JsonObject(com.google.gson.JsonObject)

Example 3 with TextRepresentable

use of org.spongepowered.api.text.TextRepresentable in project LanternServer by LanternPowered.

the class LegacyTexts method toLegacy.

private static StringBuilder toLegacy(StringBuilder builder, Locale locale, Text text, char legacyChar, Style base, Style applied) {
    if (legacyChar != 0) {
        final TextFormat format = text.getFormat();
        final TextColor color = format.getColor();
        final TextStyle style = format.getStyle();
        // Create a new style object
        final Style newStyle = base.copyTo(new Style());
        base = newStyle;
        if (color != TextColors.NONE) {
            newStyle.color = color == TextColors.RESET ? null : color;
        }
        style.isBold().ifPresent(value -> newStyle.bold = value);
        style.isItalic().ifPresent(value -> newStyle.italic = value);
        style.isObfuscated().ifPresent(value -> newStyle.obfuscated = value);
        style.hasUnderline().ifPresent(value -> newStyle.underlined = value);
        style.hasStrikethrough().ifPresent(value -> newStyle.strikethrough = value);
        if ((applied.color != null && newStyle.color == null) || (applied.bold && !newStyle.bold) || (applied.italic && !newStyle.italic) || (applied.obfuscated && !newStyle.obfuscated) || (applied.underlined && !newStyle.underlined) || (applied.strikethrough && !newStyle.strikethrough)) {
            builder.append(legacyChar).append(TextConstants.RESET);
            if (newStyle.color != null) {
                builder.append(legacyChar).append(((FormattingCodeHolder) newStyle.color).getCode());
            }
            if (newStyle.bold) {
                builder.append(legacyChar).append(TextConstants.BOLD);
            }
            if (newStyle.italic) {
                builder.append(legacyChar).append(TextConstants.ITALIC);
            }
            if (newStyle.obfuscated) {
                builder.append(legacyChar).append(TextConstants.OBFUSCATED);
            }
            if (newStyle.underlined) {
                builder.append(legacyChar).append(TextConstants.UNDERLINE);
            }
            if (newStyle.strikethrough) {
                builder.append(legacyChar).append(TextConstants.STRIKETHROUGH);
            }
        } else {
            if (applied.color != newStyle.color) {
                builder.append(legacyChar).append(((FormattingCodeHolder) newStyle.color).getCode());
            }
            if (applied.bold != newStyle.bold) {
                builder.append(legacyChar).append(TextConstants.BOLD);
            }
            if (applied.italic != newStyle.italic) {
                builder.append(legacyChar).append(TextConstants.ITALIC);
            }
            if (applied.obfuscated != newStyle.obfuscated) {
                builder.append(legacyChar).append(TextConstants.OBFUSCATED);
            }
            if (applied.underlined != newStyle.underlined) {
                builder.append(legacyChar).append(TextConstants.UNDERLINE);
            }
            if (applied.strikethrough != newStyle.strikethrough) {
                builder.append(legacyChar).append(TextConstants.STRIKETHROUGH);
            }
        }
        newStyle.copyTo(applied);
    }
    if (text instanceof LiteralText) {
        builder.append(((LiteralText) text).getContent());
    } else if (text instanceof SelectorText) {
        builder.append(((SelectorText) text).getSelector().toPlain());
    } else if (text instanceof TranslatableText) {
        final TranslatableText text0 = (TranslatableText) text;
        final Translation translation = text0.getTranslation();
        final ImmutableList<Object> args = text0.getArguments();
        final Object[] args0 = new Object[args.size()];
        for (int i = 0; i < args0.length; i++) {
            Object object = args.get(i);
            if (object instanceof Text || object instanceof Text.Builder || object instanceof TextRepresentable) {
                if (object instanceof Text) {
                // Ignore
                } else if (object instanceof Text.Builder) {
                    object = ((Text.Builder) object).build();
                } else {
                    object = ((TextRepresentable) object).toText();
                }
                args0[i] = toLegacy(new StringBuilder(), locale, (Text) object, legacyChar, base, applied).toString();
            } else {
                args0[i] = object;
            }
        }
        builder.append(translation.get(locale, args0));
    } else if (text instanceof ScoreText) {
        final ScoreText text0 = (ScoreText) text;
        final Optional<String> override = text0.getOverride();
        if (override.isPresent()) {
            builder.append(override.get());
        } else {
            builder.append(text0.getScore().getScore());
        }
    }
    for (Text child : text.getChildren()) {
        toLegacy(builder, locale, child, legacyChar, base, applied);
    }
    return builder;
}
Also used : TranslatableText(org.spongepowered.api.text.TranslatableText) TextRepresentable(org.spongepowered.api.text.TextRepresentable) SelectorText(org.spongepowered.api.text.SelectorText) Translation(org.spongepowered.api.text.translation.Translation) Optional(java.util.Optional) ScoreText(org.spongepowered.api.text.ScoreText) LiteralText(org.spongepowered.api.text.LiteralText) ScoreText(org.spongepowered.api.text.ScoreText) SelectorText(org.spongepowered.api.text.SelectorText) Text(org.spongepowered.api.text.Text) TranslatableText(org.spongepowered.api.text.TranslatableText) TextStyle(org.spongepowered.api.text.format.TextStyle) TextFormat(org.spongepowered.api.text.format.TextFormat) TextStyle(org.spongepowered.api.text.format.TextStyle) TextColor(org.spongepowered.api.text.format.TextColor) LiteralText(org.spongepowered.api.text.LiteralText)

Example 4 with TextRepresentable

use of org.spongepowered.api.text.TextRepresentable in project Nucleus by NucleusPowered.

the class AFKHandler method onTick.

public void onTick() {
    synchronized (lock) {
        activity.forEach(u -> data.compute(u, ((uuid, afkData) -> afkData == null ? new AFKData(uuid) : updateActivity(uuid, afkData))));
        activity.clear();
    }
    List<UUID> uuidList = Sponge.getServer().getOnlinePlayers().stream().map(Player::getUniqueId).collect(Collectors.toList());
    // Remove all offline players.
    Set<Map.Entry<UUID, AFKData>> entries = data.entrySet();
    entries.removeIf(refactor -> !uuidList.contains(refactor.getKey()));
    entries.stream().filter(x -> !x.getValue().cacheValid).forEach(x -> x.getValue().updateFromPermissions());
    long now = System.currentTimeMillis();
    // Check AFK status.
    entries.stream().filter(x -> x.getValue().isKnownAfk && !x.getValue().willKick && x.getValue().timeToKick > 0).forEach(e -> {
        if (now - e.getValue().lastActivityTime > e.getValue().timeToKick) {
            // Kick them
            e.getValue().willKick = true;
            NucleusTextTemplateImpl message = config.getMessages().getKickMessage();
            TextRepresentable t;
            if (message == null || message.isEmpty()) {
                t = Nucleus.getNucleus().getMessageProvider().getTextMessageWithTextFormat("afk.kickreason");
            } else {
                t = message;
            }
            final NucleusTextTemplateImpl messageToServer = config.getMessages().getOnKick();
            Sponge.getServer().getPlayer(e.getKey()).ifPresent(player -> {
                MessageChannel mc;
                if (config.isBroadcastOnKick()) {
                    mc = MessageChannel.TO_ALL;
                } else {
                    mc = MessageChannel.permission(this.afkPermissionHandler.getPermissionWithSuffix("notify"));
                }
                AFKEvents.Kick events = new AFKEvents.Kick(player, messageToServer.getForCommandSource(player), mc);
                if (Sponge.getEventManager().post(events)) {
                    // Cancelled.
                    return;
                }
                Text toSend = t instanceof NucleusTextTemplateImpl ? ((NucleusTextTemplateImpl) t).getForCommandSource(player) : t.toText();
                Sponge.getScheduler().createSyncExecutor(Nucleus.getNucleus()).execute(() -> player.kick(toSend));
                events.getMessage().ifPresent(m -> events.getChannel().send(player, m, ChatTypes.SYSTEM));
            });
        }
    });
    // Check AFK status.
    entries.stream().filter(x -> !x.getValue().isKnownAfk && x.getValue().timeToAfk > 0).forEach(e -> {
        if (now - e.getValue().lastActivityTime > e.getValue().timeToAfk) {
            Sponge.getServer().getPlayer(e.getKey()).ifPresent(this::setAfk);
        }
    });
}
Also used : AFKConfig(io.github.nucleuspowered.nucleus.modules.afk.config.AFKConfig) ChatTypes(org.spongepowered.api.text.chat.ChatTypes) Keys(org.spongepowered.api.data.key.Keys) TextRepresentable(org.spongepowered.api.text.TextRepresentable) NoExceptionAutoClosable(io.github.nucleuspowered.nucleus.api.util.NoExceptionAutoClosable) NucleusPlugin(io.github.nucleuspowered.nucleus.NucleusPlugin) Multimap(com.google.common.collect.Multimap) HashMultimap(com.google.common.collect.HashMultimap) Lists(com.google.common.collect.Lists) Text(org.spongepowered.api.text.Text) Duration(java.time.Duration) Map(java.util.Map) Task(org.spongepowered.api.scheduler.Task) Util(io.github.nucleuspowered.nucleus.Util) NucleusAFKService(io.github.nucleuspowered.nucleus.api.service.NucleusAFKService) ServiceChangeListener(io.github.nucleuspowered.nucleus.internal.permissions.ServiceChangeListener) PluginContainer(org.spongepowered.api.plugin.PluginContainer) AFKConfigAdapter(io.github.nucleuspowered.nucleus.modules.afk.config.AFKConfigAdapter) CommandPermissionHandler(io.github.nucleuspowered.nucleus.internal.CommandPermissionHandler) Nucleus(io.github.nucleuspowered.nucleus.Nucleus) User(org.spongepowered.api.entity.living.player.User) CauseStackHelper(io.github.nucleuspowered.nucleus.util.CauseStackHelper) Sponge(org.spongepowered.api.Sponge) Set(java.util.Set) Tuple(org.spongepowered.api.util.Tuple) UUID(java.util.UUID) Instant(java.time.Instant) GuardedBy(javax.annotation.concurrent.GuardedBy) Maps(com.google.common.collect.Maps) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) AFKCommand(io.github.nucleuspowered.nucleus.modules.afk.commands.AFKCommand) Reloadable(io.github.nucleuspowered.nucleus.internal.interfaces.Reloadable) Cause(org.spongepowered.api.event.cause.Cause) List(java.util.List) MessageChannel(org.spongepowered.api.text.channel.MessageChannel) Optional(java.util.Optional) Preconditions(com.google.common.base.Preconditions) Player(org.spongepowered.api.entity.living.player.Player) NucleusTextTemplateImpl(io.github.nucleuspowered.nucleus.internal.text.NucleusTextTemplateImpl) AFKEvents(io.github.nucleuspowered.nucleus.modules.afk.events.AFKEvents) TextRepresentable(org.spongepowered.api.text.TextRepresentable) NucleusTextTemplateImpl(io.github.nucleuspowered.nucleus.internal.text.NucleusTextTemplateImpl) Text(org.spongepowered.api.text.Text) AFKEvents(io.github.nucleuspowered.nucleus.modules.afk.events.AFKEvents) MessageChannel(org.spongepowered.api.text.channel.MessageChannel) UUID(java.util.UUID)

Aggregations

Text (org.spongepowered.api.text.Text)4 TextRepresentable (org.spongepowered.api.text.TextRepresentable)4 Optional (java.util.Optional)3 Preconditions (com.google.common.base.Preconditions)2 Lists (com.google.common.collect.Lists)2 Maps (com.google.common.collect.Maps)2 Nucleus (io.github.nucleuspowered.nucleus.Nucleus)2 NucleusPlugin (io.github.nucleuspowered.nucleus.NucleusPlugin)2 List (java.util.List)2 Map (java.util.Map)2 UUID (java.util.UUID)2 TranslatableText (org.spongepowered.api.text.TranslatableText)2 Translation (org.spongepowered.api.text.translation.Translation)2 HashMultimap (com.google.common.collect.HashMultimap)1 Multimap (com.google.common.collect.Multimap)1 Sets (com.google.common.collect.Sets)1 JsonArray (com.google.gson.JsonArray)1 JsonObject (com.google.gson.JsonObject)1 JsonPrimitive (com.google.gson.JsonPrimitive)1 Util (io.github.nucleuspowered.nucleus.Util)1