Search in sources :

Example 1 with ComponentLike

use of net.kyori.adventure.text.ComponentLike in project LuckPerms by lucko.

the class VerboseListener method sendNotification.

private void sendNotification(VerboseEvent event) {
    // form a text component from the check trace
    Component component;
    if (event instanceof PermissionCheckEvent) {
        PermissionCheckEvent permissionEvent = (PermissionCheckEvent) event;
        component = Message.VERBOSE_LOG_PERMISSION.build(permissionEvent.getCheckTarget().describe(), permissionEvent.getPermission(), permissionEvent.getResult().result());
    } else if (event instanceof MetaCheckEvent) {
        MetaCheckEvent metaEvent = (MetaCheckEvent) event;
        component = Message.VERBOSE_LOG_META.build(metaEvent.getCheckTarget().describe(), metaEvent.getKey(), String.valueOf(metaEvent.getResult().result()));
    } else {
        throw new IllegalArgumentException("Unknown event type: " + event);
    }
    // just send as a raw message
    if (this.notifiedSender.isConsole()) {
        this.notifiedSender.sendMessage(component);
        return;
    }
    // build the hover text
    List<ComponentLike> hover = new ArrayList<>();
    hover.add(Message.VERBOSE_LOG_HOVER_TYPE.build(event.getType().toString()));
    hover.add(Message.VERBOSE_LOG_HOVER_ORIGIN.build(event.getOrigin().name()));
    Result<?, ?> result = event.getResult();
    if (result instanceof TristateResult) {
        TristateResult tristateResult = (TristateResult) result;
        if (tristateResult.processorClass() != null) {
            hover.add(Message.VERBOSE_LOG_HOVER_PROCESSOR.build(tristateResult.processorClassFriendly()));
        }
    }
    Node node = result.node();
    if (node != null) {
        if (node instanceof MetaNode) {
            hover.add(Message.VERBOSE_LOG_HOVER_CAUSE_META.build((MetaNode) node));
        } else {
            hover.add(Message.VERBOSE_LOG_HOVER_CAUSE.build(node));
        }
    }
    if (event.getCheckQueryOptions().mode() == QueryMode.CONTEXTUAL) {
        hover.add(Message.VERBOSE_LOG_HOVER_CONTEXT.build(event.getCheckQueryOptions().context()));
    }
    hover.add(Message.VERBOSE_LOG_HOVER_THREAD.build(event.getCheckThread()));
    hover.add(Message.VERBOSE_LOG_HOVER_TRACE_TITLE.build());
    Consumer<StackTraceElement> printer = StackTracePrinter.elementToString(str -> hover.add(Message.VERBOSE_LOG_HOVER_TRACE_CONTENT.build(str)));
    int overflow;
    if (shouldFilterStackTrace(event)) {
        overflow = CHAT_FILTERED_PRINTER.process(event.getCheckTrace(), printer);
    } else {
        overflow = CHAT_UNFILTERED_PRINTER.process(event.getCheckTrace(), printer);
    }
    if (overflow != 0) {
        hover.add(Message.VERBOSE_LOG_HOVER_TRACE_OVERFLOW.build(overflow));
    }
    // send the message
    HoverEvent<Component> hoverEvent = HoverEvent.showText(Component.join(Component.newline(), hover));
    this.notifiedSender.sendMessage(component.hoverEvent(hoverEvent));
}
Also used : PermissionCheckEvent(me.lucko.luckperms.common.verbose.event.PermissionCheckEvent) ComponentLike(net.kyori.adventure.text.ComponentLike) Node(net.luckperms.api.node.Node) MetaNode(net.luckperms.api.node.types.MetaNode) ArrayList(java.util.ArrayList) MetaNode(net.luckperms.api.node.types.MetaNode) MetaCheckEvent(me.lucko.luckperms.common.verbose.event.MetaCheckEvent) Component(net.kyori.adventure.text.Component) TristateResult(me.lucko.luckperms.common.cacheddata.result.TristateResult)

Example 2 with ComponentLike

use of net.kyori.adventure.text.ComponentLike in project Nucleus by NucleusPowered.

the class MessageHandler method sendMessage.

@Override
public boolean sendMessage(final MessageTarget sender, final MessageTarget receiver, final String message) {
    // Message is about to be sent. Send the event out. If canceled, then that's that.
    boolean isBlocked = false;
    this.checkValid(sender);
    this.checkValid(receiver);
    try (final CauseStackManager.StackFrame frame = Sponge.server().causeStackManager().pushCauseFrame()) {
        @Nullable final ServerPlayer senderAsPlayer = sender instanceof UserMessageTarget ? Sponge.server().player(((UserMessageTarget) sender).getUserUUID()).orElseThrow(() -> new IllegalArgumentException("Sender" + " is not online")) : null;
        if (sender instanceof AbstractMessageTarget) {
            ((AbstractMessageTarget) sender).pushCauseToFrame(frame);
        } else {
            frame.pushCause(sender);
        }
        boolean isCancelled = Sponge.eventManager().post(new InternalNucleusMessageEvent(frame.currentCause(), sender, receiver, message));
        if (isCancelled) {
            sender.getRepresentedAudience().ifPresent(x -> this.serviceCollection.messageProvider().sendMessageTo(x, "message.cancel"));
            // Only continue to show Social Spy messages if the subject is muted.
            if (!this.messageConfig.isShowMessagesInSocialSpyWhileMuted()) {
                return false;
            }
        }
        // Cancel message if the receiver has message toggle false
        if (!sender.isAvailableForMessages() && !receiver.canBypassMessageToggle()) {
            isCancelled = true;
            isBlocked = true;
            sender.getRepresentedAudience().ifPresent(x -> this.serviceCollection.messageProvider().sendMessageTo(x, "message.blocked", receiver.getDisplayName()));
            if (!this.messageConfig.isShowMessagesInSocialSpyWhileMuted()) {
                return false;
            }
        }
        // Social Spies.
        final UUID uuidSender = this.getUUID(sender);
        final UUID uuidReceiver = this.getUUID(receiver);
        // Create the tokens.
        final Map<String, Function<Object, Optional<ComponentLike>>> tokens = new HashMap<>();
        tokens.put("from", cs -> Optional.of(Component.text(sender.getName())));
        tokens.put("to", cs -> Optional.of(Component.text(receiver.getName())));
        tokens.put("fromdisplay", cs -> Optional.of(sender.getDisplayName()));
        tokens.put("todisplay", cs -> Optional.of(receiver.getDisplayName()));
        final Component tm = this.useMessage(senderAsPlayer, message);
        final INucleusTextTemplateFactory textTemplateFactory = this.serviceCollection.textTemplateFactory();
        if (!isCancelled) {
            sender.getRepresentedAudience().ifPresent(x -> x.sendMessage(this.constructMessage(sender, tm, this.messageConfig.getMessageSenderPrefix(textTemplateFactory), tokens)));
            receiver.receiveMessageFrom(sender, this.constructMessage(sender, tm, this.messageConfig.getMessageReceiverPrefix(textTemplateFactory), tokens));
        }
        NucleusTextTemplateImpl prefix = this.messageConfig.getMessageSocialSpyPrefix(textTemplateFactory);
        if (isBlocked) {
            prefix = textTemplateFactory.createFromAmpersandString(this.messageConfig.getBlockedTag() + prefix.asComponent());
        }
        if (isCancelled) {
            prefix = textTemplateFactory.createFromAmpersandString(this.messageConfig.getMutedTag() + prefix.asComponent());
        }
        final MessageConfig.Targets targets = this.messageConfig.spyOn();
        if (sender instanceof PlayerMessageTarget && targets.isPlayer() || sender instanceof SystemMessageTarget && targets.isServer() || targets.isCustom()) {
            final Set<UUID> lm = this.onlinePlayersCanSpyOn(!uuidSender.equals(Util.CONSOLE_FAKE_UUID) && !uuidReceiver.equals(Util.CONSOLE_FAKE_UUID), sender, receiver);
            if (!lm.isEmpty()) {
                final Component socialSpyToSend = this.constructMessage(sender, tm, prefix, tokens);
                for (final UUID uuid : lm) {
                    Sponge.server().player(uuid).ifPresent(x -> x.sendMessage(socialSpyToSend));
                }
            }
        }
        return !isCancelled;
    }
}
Also used : NucleusTextTemplateImpl(io.github.nucleuspowered.nucleus.core.services.impl.texttemplatefactory.NucleusTextTemplateImpl) ComponentLike(net.kyori.adventure.text.ComponentLike) HashMap(java.util.HashMap) INucleusTextTemplateFactory(io.github.nucleuspowered.nucleus.core.services.interfaces.INucleusTextTemplateFactory) Function(java.util.function.Function) PlayerMessageTarget(io.github.nucleuspowered.nucleus.modules.message.services.target.PlayerMessageTarget) MessageConfig(io.github.nucleuspowered.nucleus.modules.message.config.MessageConfig) CauseStackManager(org.spongepowered.api.event.CauseStackManager) UserMessageTarget(io.github.nucleuspowered.nucleus.api.module.message.target.UserMessageTarget) ServerPlayer(org.spongepowered.api.entity.living.player.server.ServerPlayer) SystemMessageTarget(io.github.nucleuspowered.nucleus.api.module.message.target.SystemMessageTarget) UUID(java.util.UUID) Component(net.kyori.adventure.text.Component) AbstractMessageTarget(io.github.nucleuspowered.nucleus.modules.message.services.target.AbstractMessageTarget) Nullable(org.checkerframework.checker.nullness.qual.Nullable) InternalNucleusMessageEvent(io.github.nucleuspowered.nucleus.modules.message.events.InternalNucleusMessageEvent)

Example 3 with ComponentLike

use of net.kyori.adventure.text.ComponentLike in project Nucleus by NucleusPowered.

the class TemplateParser method createTextTemplateFragmentWithLinks.

public Optional<ITextStyleService.TextFormat> createTextTemplateFragmentWithLinks(final String message, final List<BiFunction<Object, Map<String, Function<Object, Optional<ComponentLike>>>, Component>> elements, final ITextStyleService.TextFormat format) {
    Objects.requireNonNull(message, "message");
    if (message.isEmpty()) {
        return Optional.of(format);
    }
    final Matcher m = this.enhancedUrlParser.matcher(message);
    final ITextStyleService textStyleService = this.serviceCollection.textStyleService();
    if (!m.find()) {
        final Component component = textStyleService.oldLegacy(message);
        elements.add((a, b) -> component);
        return Optional.of(textStyleService.getLastColourAndStyle(component, format));
    }
    String remaining = message;
    ITextStyleService.TextFormat st = format;
    do {
        // We found a URL. We split on the URL that we have.
        final String[] textArray = remaining.split(this.enhancedUrlParser.pattern(), 2);
        final Component first = Component.text().color(st.colour().orElse(null)).style(st.style()).append(textStyleService.oldLegacy(textArray[0])).build();
        // Add this text to the list regardless.
        elements.add((a, b) -> 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
        final String colourMatch = m.group("colour");
        st = textStyleService.getLastColourAndStyle(first, st);
        Style style = st.style();
        @Nullable TextColor colour = st.colour().orElse(null);
        if (colourMatch != null && !colourMatch.isEmpty()) {
            // If there is a reset, explicitly do it.
            if (m.group("reset") != null) {
                style = this.serviceCollection.textStyleService().getResetStyle();
                colour = NamedTextColor.WHITE;
            }
            for (int idx = 1; idx < colourMatch.length(); idx = idx + 2) {
                final String match = colourMatch.substring(idx, idx + 1);
                if (match.equals("r")) {
                    colour = NamedTextColor.WHITE;
                    style = this.serviceCollection.textStyleService().getResetStyle();
                }
                style = textStyleService.getTextStyleFromString(match).merge(style);
                colour = textStyleService.getColourFromString(match).orElse(colour);
            }
            st = new TextStyleService.TextFormatImpl(colour, style);
        }
        // Build the URL
        final String whiteSpace = m.group("first");
        final ITextStyleService.TextFormat tf = st;
        if (m.group("url") != null) {
            final String url = m.group("url");
            elements.add((a, b) -> this.getTextForUrl(url, url, whiteSpace, tf, m.group("options")));
        } else if (m.group("specialUrl") != null) {
            final String url = m.group("sUrl");
            final String msg = m.group("msg");
            elements.add((a, b) -> this.getTextForUrl(url, msg, whiteSpace, tf, m.group("optionssurl")));
        } else {
            // Must be commands.
            final String cmd = m.group("sCmd");
            final String msg = m.group("sMsg");
            final String optionList = m.group("optionsscmd");
            if (cmd.contains("{{subject}}")) {
                elements.add(new SubjectCommand(st.colour().orElse(null), st.style(), msg, cmd, optionList, whiteSpace));
            } else {
                final Style s = st.style();
                @Nullable final TextColor c = st.colour().orElse(null);
                elements.add((a, b) -> Component.text().color(c).style(s).append(this.getCmd(msg, cmd, optionList, whiteSpace)).build());
            }
        }
    } while (remaining != null && m.find());
    // Add the last bit.
    if (remaining != null) {
        final TextComponent.Builder tb = Component.text().color(st.colour().orElse(null)).style(st.style()).append(LegacyComponentSerializer.legacyAmpersand().deserialize(remaining));
        if (remaining.matches("^\\s+&r.*")) {
            tb.style(this.serviceCollection.textStyleService().getResetStyle());
        }
        final TextComponent t = tb.build();
        st = textStyleService.getLastColourAndStyle(t, st);
        elements.add((a, b) -> t);
    }
    return Optional.of(st);
}
Also used : NucleusJavaProperties(io.github.nucleuspowered.nucleus.core.NucleusJavaProperties) INucleusServiceCollection(io.github.nucleuspowered.nucleus.core.services.INucleusServiceCollection) URL(java.net.URL) Inject(com.google.inject.Inject) BiFunction(java.util.function.BiFunction) ClickEvent(net.kyori.adventure.text.event.ClickEvent) Function(java.util.function.Function) ComponentLike(net.kyori.adventure.text.ComponentLike) ArrayList(java.util.ArrayList) Style(net.kyori.adventure.text.format.Style) Matcher(java.util.regex.Matcher) Component(net.kyori.adventure.text.Component) Map(java.util.Map) TextStyleService(io.github.nucleuspowered.nucleus.core.services.impl.textstyle.TextStyleService) LegacyComponentSerializer(net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer) Nameable(org.spongepowered.api.util.Nameable) LinkedList(java.util.LinkedList) IMessageProviderService(io.github.nucleuspowered.nucleus.core.services.interfaces.IMessageProviderService) Nullable(org.checkerframework.checker.nullness.qual.Nullable) TextComponent(net.kyori.adventure.text.TextComponent) TextColor(net.kyori.adventure.text.format.TextColor) MalformedURLException(java.net.MalformedURLException) ITextStyleService(io.github.nucleuspowered.nucleus.core.services.interfaces.ITextStyleService) NamedTextColor(net.kyori.adventure.text.format.NamedTextColor) INucleusTextTemplateFactory(io.github.nucleuspowered.nucleus.core.services.interfaces.INucleusTextTemplateFactory) Objects(java.util.Objects) List(java.util.List) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) HoverEvent(net.kyori.adventure.text.event.HoverEvent) Collections(java.util.Collections) TextComponent(net.kyori.adventure.text.TextComponent) Matcher(java.util.regex.Matcher) ITextStyleService(io.github.nucleuspowered.nucleus.core.services.interfaces.ITextStyleService) TextStyleService(io.github.nucleuspowered.nucleus.core.services.impl.textstyle.TextStyleService) ITextStyleService(io.github.nucleuspowered.nucleus.core.services.interfaces.ITextStyleService) Style(net.kyori.adventure.text.format.Style) TextColor(net.kyori.adventure.text.format.TextColor) NamedTextColor(net.kyori.adventure.text.format.NamedTextColor) Component(net.kyori.adventure.text.Component) TextComponent(net.kyori.adventure.text.TextComponent) Nullable(org.checkerframework.checker.nullness.qual.Nullable)

Example 4 with ComponentLike

use of net.kyori.adventure.text.ComponentLike in project Nucleus by NucleusPowered.

the class TemplateParser method createFromAmpersandString.

@Override
public NucleusTextTemplateImpl createFromAmpersandString(@Nullable final String string, final Component prefix, final Component suffix) {
    if (string == null || string.isEmpty()) {
        return NucleusTextTemplateImpl.empty();
    }
    final Matcher mat = pattern.matcher(string);
    final List<String> map = new ArrayList<>();
    final List<String> s = new ArrayList<>();
    Collections.addAll(s, pattern.split(string));
    int index = 0;
    while (mat.find()) {
        if (mat.group("url") != null && mat.group("urltwo") != null) {
            String toUpdate = s.get(index);
            toUpdate = toUpdate + mat.group();
            if (s.size() < index + 1) {
                toUpdate += s.get(index + 1);
                s.remove(index + 1);
                s.set(index, toUpdate);
            }
        } else {
            String out = mat.group("url");
            if (out != null) {
                if (s.isEmpty()) {
                    s.add(out);
                } else {
                    s.set(index, s.get(index) + out);
                }
            }
            index++;
            out = mat.group("urltwo");
            if (out != null) {
                if (s.size() <= index) {
                    s.add(out);
                } else {
                    s.set(index, out + s.get(index));
                }
            }
            map.add(mat.group("name").toLowerCase());
        }
    }
    // Generic hell.
    final List<BiFunction<Object, Map<String, Function<Object, Optional<ComponentLike>>>, Component>> texts = new LinkedList<>();
    ITextStyleService.TextFormat textFormat = ITextStyleService.EMPTY;
    if (s.size() > 0) {
        textFormat = this.createTextTemplateFragmentWithLinks(s.get(0), texts, textFormat).orElse(textFormat);
    }
    for (int i = 0; i < map.size(); i++) {
        texts.add(new PlaceholderElement(textFormat.colour().orElse(null), textFormat.style(), map.get(i)));
        if (s.size() > i + 1) {
            textFormat = this.createTextTemplateFragmentWithLinks(s.get(i + 1), texts, textFormat).orElse(textFormat);
        }
    }
    return new NucleusTextTemplateImpl(this.serviceCollection, texts, prefix, suffix);
}
Also used : Matcher(java.util.regex.Matcher) ComponentLike(net.kyori.adventure.text.ComponentLike) ArrayList(java.util.ArrayList) LinkedList(java.util.LinkedList) ITextStyleService(io.github.nucleuspowered.nucleus.core.services.interfaces.ITextStyleService) BiFunction(java.util.function.BiFunction) Function(java.util.function.Function) BiFunction(java.util.function.BiFunction)

Aggregations

ComponentLike (net.kyori.adventure.text.ComponentLike)4 ArrayList (java.util.ArrayList)3 Function (java.util.function.Function)3 Component (net.kyori.adventure.text.Component)3 INucleusTextTemplateFactory (io.github.nucleuspowered.nucleus.core.services.interfaces.INucleusTextTemplateFactory)2 ITextStyleService (io.github.nucleuspowered.nucleus.core.services.interfaces.ITextStyleService)2 LinkedList (java.util.LinkedList)2 BiFunction (java.util.function.BiFunction)2 Matcher (java.util.regex.Matcher)2 Nullable (org.checkerframework.checker.nullness.qual.Nullable)2 Inject (com.google.inject.Inject)1 SystemMessageTarget (io.github.nucleuspowered.nucleus.api.module.message.target.SystemMessageTarget)1 UserMessageTarget (io.github.nucleuspowered.nucleus.api.module.message.target.UserMessageTarget)1 NucleusJavaProperties (io.github.nucleuspowered.nucleus.core.NucleusJavaProperties)1 INucleusServiceCollection (io.github.nucleuspowered.nucleus.core.services.INucleusServiceCollection)1 TextStyleService (io.github.nucleuspowered.nucleus.core.services.impl.textstyle.TextStyleService)1 NucleusTextTemplateImpl (io.github.nucleuspowered.nucleus.core.services.impl.texttemplatefactory.NucleusTextTemplateImpl)1 IMessageProviderService (io.github.nucleuspowered.nucleus.core.services.interfaces.IMessageProviderService)1 MessageConfig (io.github.nucleuspowered.nucleus.modules.message.config.MessageConfig)1 InternalNucleusMessageEvent (io.github.nucleuspowered.nucleus.modules.message.events.InternalNucleusMessageEvent)1