Search in sources :

Example 6 with ICPlayer

use of com.loohp.interactivechat.objectholders.ICPlayer in project InteractiveChat by LOOHP.

the class OutChatPacket method processPacket.

private static void processPacket(Player receiver, PacketContainer packet, UUID messageUUID, boolean isFiltered) {
    PacketContainer originalPacket = packet.deepClone();
    try {
        Component component = null;
        ChatComponentType type = null;
        int field = -1;
        search: for (ChatComponentType t : ChatComponentType.byPriority()) {
            for (int i = 0; i < packet.getModifier().size(); i++) {
                if (!CustomArrayUtils.allNull(packet.getModifier().read(i)) && packet.getModifier().getField(i).getType().getName().matches(t.getMatchingRegex())) {
                    try {
                        component = t.convertFrom(packet.getModifier().read(i));
                    } catch (Throwable e) {
                        System.err.println(t.toString(packet.getModifier().read(i)));
                        e.printStackTrace();
                        service.send(packet, receiver, messageUUID);
                        return;
                    }
                    field = i;
                    type = t;
                    break search;
                }
            }
        }
        if (field < 0 || type == null || component == null) {
            service.send(packet, receiver, messageUUID);
            return;
        }
        String legacyText = LegacyComponentSerializer.legacySection().serializeOr(component, "");
        try {
            if (legacyText.equals("") || InteractiveChat.messageToIgnore.stream().anyMatch(each -> legacyText.matches(each))) {
                service.send(packet, receiver, messageUUID);
                return;
            }
        } catch (Exception e) {
            service.send(packet, receiver, messageUUID);
            return;
        }
        if (InteractiveChat.version.isOld() && JsonUtils.containsKey(InteractiveChatComponentSerializer.gson().serialize(component), "translate")) {
            service.send(packet, receiver, messageUUID);
            return;
        }
        boolean isCommand = false;
        boolean isChat = false;
        Optional<ICPlayer> sender = Optional.empty();
        String rawMessageKey = PlainTextComponentSerializer.plainText().serializeOr(component, "");
        InteractiveChat.keyTime.putIfAbsent(rawMessageKey, System.currentTimeMillis());
        Long timeKey = InteractiveChat.keyTime.get(rawMessageKey);
        long unix = timeKey == null ? System.currentTimeMillis() : timeKey;
        ProcessSenderResult commandSender = ProcessCommands.process(component);
        if (commandSender.getSender() != null) {
            ICPlayer icplayer = ICPlayerFactory.getICPlayer(commandSender.getSender());
            if (icplayer != null) {
                sender = Optional.of(icplayer);
                // noinspection UnusedAssignment
                isCommand = true;
            }
        }
        ProcessSenderResult chatSender = null;
        if (!sender.isPresent()) {
            if (InteractiveChat.useAccurateSenderFinder) {
                chatSender = ProcessAccurateSender.process(component);
                if (chatSender.getSender() != null) {
                    ICPlayer icplayer = ICPlayerFactory.getICPlayer(chatSender.getSender());
                    if (icplayer != null) {
                        sender = Optional.of(icplayer);
                        // noinspection UnusedAssignment
                        isChat = true;
                    }
                }
            }
        }
        if (!sender.isPresent() && !InteractiveChat.useAccurateSenderFinder) {
            sender = SenderFinder.getSender(component, rawMessageKey);
        }
        if (sender.isPresent() && !sender.get().isLocal()) {
            if (isFiltered) {
                Bukkit.getScheduler().runTaskLaterAsynchronously(InteractiveChat.plugin, () -> {
                    service.execute(() -> {
                        processPacket(receiver, packet, messageUUID, false);
                    }, receiver, messageUUID);
                }, (int) Math.ceil((double) InteractiveChat.remoteDelay / 50));
                return;
            }
        }
        component = commandSender.getComponent();
        if (chatSender != null) {
            component = chatSender.getComponent();
        }
        if (sender.isPresent()) {
            InteractiveChat.keyPlayer.put(rawMessageKey, sender.get());
        }
        component = ComponentModernizing.modernize(component);
        component = component.replaceText(TextReplacementConfig.builder().match(Registry.ID_PATTERN).replacement("").build());
        UUID preEventSenderUUID = sender.isPresent() ? sender.get().getUniqueId() : null;
        PrePacketComponentProcessEvent preEvent = new PrePacketComponentProcessEvent(true, receiver, component, preEventSenderUUID);
        Bukkit.getPluginManager().callEvent(preEvent);
        if (preEvent.getSender() != null) {
            Player newsender = Bukkit.getPlayer(preEvent.getSender());
            if (newsender != null) {
                sender = Optional.of(ICPlayerFactory.getICPlayer(newsender));
            }
        }
        component = preEvent.getComponent();
        if (InteractiveChat.translateHoverableItems && InteractiveChat.itemGUI) {
            component = HoverableItemDisplay.process(component, receiver);
        }
        if (InteractiveChat.usePlayerName) {
            component = PlayernameDisplay.process(component, sender, receiver, unix);
        }
        if (InteractiveChat.allowMention && sender.isPresent()) {
            PlayerData data = InteractiveChat.playerDataManager.getPlayerData(receiver);
            if (data == null || !data.isMentionDisabled()) {
                component = MentionDisplay.process(component, receiver, sender.get(), unix, true);
            }
        }
        component = ComponentReplacing.replace(component, Registry.MENTION_TAG_CONVERTER.getReversePattern().pattern(), true, (result, components) -> {
            return LegacyComponentSerializer.legacySection().deserialize(result.group(2));
        });
        component = CustomPlaceholderDisplay.process(component, sender, receiver, InteractiveChat.placeholderList.values(), unix);
        if (InteractiveChat.useItem) {
            component = ItemDisplay.process(component, sender, receiver, unix);
        }
        if (InteractiveChat.useInventory) {
            component = InventoryDisplay.process(component, sender, receiver, unix);
        }
        if (InteractiveChat.useEnder) {
            component = EnderchestDisplay.process(component, sender, receiver, unix);
        }
        if (InteractiveChat.clickableCommands) {
            component = CommandsDisplay.process(component);
        }
        if (InteractiveChat.version.isNewerOrEqualTo(MCVersion.V1_16) && InteractiveChat.fontTags) {
            if (!sender.isPresent() || (sender.isPresent() && PlayerUtils.hasPermission(sender.get().getUniqueId(), "interactivechat.customfont.translate", true, 250))) {
                component = ComponentFont.parseFont(component);
            }
        }
        if (PlayerUtils.getColorSettings(receiver).equals(ColorSettings.OFF)) {
            component = ComponentStyling.stripColor(component);
        }
        PostPacketComponentProcessEvent postEvent = new PostPacketComponentProcessEvent(true, receiver, component, preEventSenderUUID);
        Bukkit.getPluginManager().callEvent(postEvent);
        component = postEvent.getComponent();
        boolean legacyRGB = InteractiveChat.version.isLegacyRGB();
        String json = legacyRGB ? InteractiveChatComponentSerializer.legacyGson().serialize(component) : InteractiveChatComponentSerializer.gson().serialize(component);
        boolean longerThanMaxLength = InteractiveChat.sendOriginalIfTooLong && json.length() > InteractiveChat.packetStringMaxLength;
        try {
            packet.getModifier().write(field, type.convertTo(component, legacyRGB));
        } catch (Throwable e) {
            for (int i = 0; i < chatFieldsSize; i++) {
                packet.getModifier().write(i, null);
            }
            packet.getChatComponents().write(0, WrappedChatComponent.fromJson(json));
        }
        UUID postEventSenderUUID = sender.isPresent() ? sender.get().getUniqueId() : new UUID(0, 0);
        if (packet.getUUIDs().size() > 0) {
            packet.getUUIDs().write(0, postEventSenderUUID);
        }
        PreChatPacketSendEvent sendEvent = new PreChatPacketSendEvent(true, receiver, packet, postEventSenderUUID, originalPacket, InteractiveChat.sendOriginalIfTooLong, longerThanMaxLength);
        Bukkit.getPluginManager().callEvent(sendEvent);
        Bukkit.getScheduler().runTaskLater(InteractiveChat.plugin, () -> {
            InteractiveChat.keyTime.remove(rawMessageKey);
            InteractiveChat.keyPlayer.remove(rawMessageKey);
        }, 10);
        if (sendEvent.isCancelled()) {
            if (sendEvent.sendOriginalIfCancelled()) {
                if (longerThanMaxLength && InteractiveChat.cancelledMessage) {
                    Bukkit.getConsoleSender().sendMessage(ChatColor.YELLOW + "[InteractiveChat] " + ChatColor.RED + "Cancelled a chat packet bounded to " + receiver.getName() + " that is " + json.length() + " characters long (Longer than maximum allowed in a chat packet), sending original unmodified message instead! [THIS IS NOT A BUG]");
                }
                PacketContainer originalPacketModified = sendEvent.getOriginal();
                service.send(originalPacketModified, receiver, messageUUID);
                return;
            }
            if (longerThanMaxLength && InteractiveChat.cancelledMessage) {
                Bukkit.getConsoleSender().sendMessage(ChatColor.YELLOW + "[InteractiveChat] " + ChatColor.RED + "Cancelled a chat packet bounded to " + receiver.getName() + " that is " + json.length() + " characters long (Longer than maximum allowed in a chat packet) [THIS IS NOT A BUG]");
            }
            service.discard(receiver.getUniqueId(), messageUUID);
            return;
        }
        service.send(packet, receiver, messageUUID);
    } catch (Exception e) {
        e.printStackTrace();
        service.send(originalPacket, receiver, messageUUID);
    }
}
Also used : ComponentReplacing(com.loohp.interactivechat.utils.ComponentReplacing) PlayerUtils(com.loohp.interactivechat.utils.PlayerUtils) PlayerData(com.loohp.interactivechat.data.PlayerDataManager.PlayerData) Player(org.bukkit.entity.Player) PreChatPacketSendEvent(com.loohp.interactivechat.api.events.PreChatPacketSendEvent) ComponentModernizing(com.loohp.interactivechat.utils.ComponentModernizing) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) ComponentFont(com.loohp.interactivechat.utils.ComponentFont) InteractiveChatComponentSerializer(com.loohp.interactivechat.utils.InteractiveChatComponentSerializer) HoverableItemDisplay(com.loohp.interactivechat.modules.HoverableItemDisplay) InventoryDisplay(com.loohp.interactivechat.modules.InventoryDisplay) Bukkit(org.bukkit.Bukkit) ProcessAccurateSender(com.loohp.interactivechat.modules.ProcessAccurateSender) CustomArrayUtils(com.loohp.interactivechat.utils.CustomArrayUtils) CustomPlaceholderDisplay(com.loohp.interactivechat.modules.CustomPlaceholderDisplay) ListenerPriority(com.comphenix.protocol.events.ListenerPriority) UUID(java.util.UUID) PacketType(com.comphenix.protocol.PacketType) Collectors(java.util.stream.Collectors) InteractiveChat(com.loohp.interactivechat.InteractiveChat) PacketContainer(com.comphenix.protocol.events.PacketContainer) List(java.util.List) AsyncChatSendingExecutor(com.loohp.interactivechat.objectholders.AsyncChatSendingExecutor) CommandsDisplay(com.loohp.interactivechat.modules.CommandsDisplay) TextReplacementConfig(net.kyori.adventure.text.TextReplacementConfig) PrePacketComponentProcessEvent(com.loohp.interactivechat.api.events.PrePacketComponentProcessEvent) ColorSettings(com.loohp.interactivechat.utils.PlayerUtils.ColorSettings) Optional(java.util.Optional) ProcessSenderResult(com.loohp.interactivechat.objectholders.ProcessSenderResult) WrappedChatComponent(com.comphenix.protocol.wrappers.WrappedChatComponent) MCVersion(com.loohp.interactivechat.utils.MCVersion) Registry(com.loohp.interactivechat.registry.Registry) MentionDisplay(com.loohp.interactivechat.modules.MentionDisplay) JsonUtils(com.loohp.interactivechat.utils.JsonUtils) PostPacketComponentProcessEvent(com.loohp.interactivechat.api.events.PostPacketComponentProcessEvent) ComponentStyling(com.loohp.interactivechat.utils.ComponentStyling) PacketAdapter(com.comphenix.protocol.events.PacketAdapter) Component(net.kyori.adventure.text.Component) LegacyComponentSerializer(net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer) VentureChatInjection(com.loohp.interactivechat.hooks.venturechat.VentureChatInjection) ChatColor(net.md_5.bungee.api.ChatColor) Listener(org.bukkit.event.Listener) PacketEvent(com.comphenix.protocol.events.PacketEvent) ChatComponentType(com.loohp.interactivechat.utils.ChatComponentType) ProcessCommands(com.loohp.interactivechat.modules.ProcessCommands) ItemDisplay(com.loohp.interactivechat.modules.ItemDisplay) EnderchestDisplay(com.loohp.interactivechat.modules.EnderchestDisplay) ChatType(com.comphenix.protocol.wrappers.EnumWrappers.ChatType) PlayernameDisplay(com.loohp.interactivechat.modules.PlayernameDisplay) PlainTextComponentSerializer(net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer) ICPlayerFactory(com.loohp.interactivechat.objectholders.ICPlayerFactory) SenderFinder(com.loohp.interactivechat.modules.SenderFinder) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) ProcessSenderResult(com.loohp.interactivechat.objectholders.ProcessSenderResult) PacketContainer(com.comphenix.protocol.events.PacketContainer) PrePacketComponentProcessEvent(com.loohp.interactivechat.api.events.PrePacketComponentProcessEvent) Player(org.bukkit.entity.Player) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) ChatComponentType(com.loohp.interactivechat.utils.ChatComponentType) PostPacketComponentProcessEvent(com.loohp.interactivechat.api.events.PostPacketComponentProcessEvent) PreChatPacketSendEvent(com.loohp.interactivechat.api.events.PreChatPacketSendEvent) WrappedChatComponent(com.comphenix.protocol.wrappers.WrappedChatComponent) Component(net.kyori.adventure.text.Component) UUID(java.util.UUID) PlayerData(com.loohp.interactivechat.data.PlayerDataManager.PlayerData)

Example 7 with ICPlayer

use of com.loohp.interactivechat.objectholders.ICPlayer in project InteractiveChat by LOOHP.

the class OutTabCompletePacket method tabCompleteListener.

public static void tabCompleteListener() {
    Bukkit.getScheduler().runTaskTimerAsynchronously(InteractiveChat.plugin, () -> {
        if (InteractiveChat.useTooltipOnTab) {
            Map<String, UUID> playernames = new HashMap<>();
            for (ICPlayer player : ICPlayerFactory.getOnlineICPlayers()) {
                playernames.put(ChatColorUtils.stripColor(player.getName()), player.getUniqueId());
                if (!player.getName().equals(player.getDisplayName())) {
                    playernames.put(ChatColorUtils.stripColor(player.getDisplayName()), player.getUniqueId());
                }
                List<String> names = InteractiveChatAPI.getNicknames(player.getUniqueId());
                for (String name : names) {
                    playernames.put(ChatColorUtils.stripColor(name), player.getUniqueId());
                }
            }
            Bukkit.getScheduler().runTask(InteractiveChat.plugin, () -> OutTabCompletePacket.playernames = playernames);
        }
    }, 0, 100);
    InteractiveChat.protocolManager.addPacketListener(new PacketAdapter(PacketAdapter.params().optionAsync().plugin(InteractiveChat.plugin).listenerPriority(ListenerPriority.HIGHEST).types(PacketType.Play.Server.TAB_COMPLETE)) {

        @Override
        public void onPacketSending(PacketEvent event) {
            if (!event.isFiltered() || event.isCancelled() || !event.getPacketType().equals(PacketType.Play.Server.TAB_COMPLETE) || event.isPlayerTemporary()) {
                return;
            }
            PacketContainer packet = event.getPacket();
            Player tabCompleter = event.getPlayer();
            Suggestions suggestions = (Suggestions) packet.getModifier().read(1);
            StringRange range = suggestions.getRange();
            List<Suggestion> matches = suggestions.getList();
            List<Suggestion> newMatches = new ArrayList<>();
            for (Suggestion suggestion : matches) {
                String text = suggestion.getText();
                int pos = text.indexOf("\0");
                if (pos < 0) {
                    if (InteractiveChat.useTooltipOnTab) {
                        ICPlayer icplayer = null;
                        for (Entry<String, UUID> entry : playernames.entrySet()) {
                            if (entry.getKey().equalsIgnoreCase(text)) {
                                icplayer = ICPlayerFactory.getICPlayer(entry.getValue());
                                if (icplayer == null) {
                                    newMatches.add(suggestion);
                                    continue;
                                }
                                break;
                            }
                        }
                        if (icplayer != null) {
                            Component component = LegacyComponentSerializer.legacySection().deserialize(ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(icplayer, InteractiveChat.tabTooltip)));
                            if (PlayerUtils.getColorSettings(tabCompleter).equals(ColorSettings.OFF)) {
                                component = ComponentStyling.stripColor(component);
                            }
                            String json = InteractiveChat.version.isLegacyRGB() ? InteractiveChatComponentSerializer.legacyGson().serialize(component) : InteractiveChatComponentSerializer.gson().serialize(component);
                            newMatches.add(new Suggestion(range, text, (Message) WrappedChatComponent.fromJson(json).getHandle()));
                        } else {
                            newMatches.add(suggestion);
                        }
                    } else {
                        newMatches.add(suggestion);
                    }
                } else {
                    String tooltip = text.substring(pos + 1);
                    text = text.substring(0, pos);
                    newMatches.add(new Suggestion(range, text, (Message) WrappedChatComponent.fromJson(tooltip).getHandle()));
                }
            }
            packet.getModifier().write(1, new Suggestions(range, newMatches));
        }
    });
}
Also used : ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) PacketContainer(com.comphenix.protocol.events.PacketContainer) Player(org.bukkit.entity.Player) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) HashMap(java.util.HashMap) StringRange(com.mojang.brigadier.context.StringRange) Suggestions(com.mojang.brigadier.suggestion.Suggestions) Suggestion(com.mojang.brigadier.suggestion.Suggestion) Entry(java.util.Map.Entry) PacketAdapter(com.comphenix.protocol.events.PacketAdapter) PacketEvent(com.comphenix.protocol.events.PacketEvent) ArrayList(java.util.ArrayList) List(java.util.List) UUID(java.util.UUID) WrappedChatComponent(com.comphenix.protocol.wrappers.WrappedChatComponent) Component(net.kyori.adventure.text.Component)

Example 8 with ICPlayer

use of com.loohp.interactivechat.objectholders.ICPlayer in project InteractiveChat by LOOHP.

the class EnderchestDisplay method process.

public static Component process(Component component, Optional<ICPlayer> optplayer, Player reciever, long unix) throws Exception {
    String plain = InteractiveChatComponentSerializer.plainText().serialize(component);
    if (InteractiveChat.enderPlaceholder.matcher(plain).find()) {
        String regex = InteractiveChat.enderPlaceholder.pattern();
        if (optplayer.isPresent()) {
            ICPlayer player = optplayer.get();
            if (PlayerUtils.hasPermission(player.getUniqueId(), "interactivechat.module.enderchest", true, 5)) {
                String replaceText = InteractiveChat.enderReplaceText;
                String title = ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(player, InteractiveChat.enderTitle));
                String sha1 = HashUtils.createSha1(title, player.getEnderChest());
                if (!InteractiveChat.enderDisplay.containsKey(sha1)) {
                    int size = player.getEnderChest().getSize();
                    Inventory inv = Bukkit.createInventory(null, InventoryUtils.toMultipleOf9(size), title);
                    for (int j = 0; j < size; j++) {
                        if (player.getEnderChest().getItem(j) != null) {
                            if (!player.getEnderChest().getItem(j).getType().equals(Material.AIR)) {
                                inv.setItem(j, player.getEnderChest().getItem(j).clone());
                            }
                        }
                    }
                    InventoryPlaceholderEvent event = new InventoryPlaceholderEvent(player, reciever, component, unix, inv, InventoryPlaceholderType.ENDERCHEST);
                    Bukkit.getPluginManager().callEvent(event);
                    inv = event.getInventory();
                    InteractiveChatAPI.addInventoryToItemShareList(SharedType.ENDERCHEST, sha1, inv);
                    if (InteractiveChat.bungeecordMode) {
                        if (player.isLocal()) {
                            try {
                                BungeeMessageSender.forwardEnderchest(unix, player.getUniqueId(), player.isRightHanded(), player.getSelectedSlot(), player.getExperienceLevel(), null, inv);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
                String componentText = ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(player, replaceText));
                List<String> hoverList = ConfigManager.getConfig().getStringList("ItemDisplay.EnderChest.HoverMessage");
                String hoverText = ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(player, String.join("\n", hoverList)));
                String command = "/interactivechat viewender " + sha1;
                Component enderComponent = LegacyComponentSerializer.legacySection().deserialize(componentText);
                enderComponent = enderComponent.hoverEvent(HoverEvent.showText(LegacyComponentSerializer.legacySection().deserialize(hoverText)));
                enderComponent = enderComponent.clickEvent(ClickEvent.runCommand(command));
                component = ComponentReplacing.replace(component, regex, true, enderComponent);
            }
        } else {
            Component message;
            if (InteractiveChat.playerNotFoundReplaceEnable) {
                message = LegacyComponentSerializer.legacySection().deserialize(InteractiveChat.playerNotFoundReplaceText.replace("{Placeholder}", InteractiveChat.enderName));
            } else {
                message = Component.text(InteractiveChat.enderName);
            }
            if (InteractiveChat.playerNotFoundHoverEnable) {
                message = message.hoverEvent(HoverEvent.showText(LegacyComponentSerializer.legacySection().deserialize(InteractiveChat.playerNotFoundHoverText.replace("{Placeholder}", InteractiveChat.enderName))));
            }
            if (InteractiveChat.playerNotFoundClickEnable) {
                String clickValue = ChatColorUtils.translateAlternateColorCodes('&', InteractiveChat.playerNotFoundClickValue.replace("{Placeholder}", InteractiveChat.enderName));
                message = message.clickEvent(ClickEvent.clickEvent(ClickEvent.Action.valueOf(InteractiveChat.playerNotFoundClickAction), clickValue));
            }
            component = ComponentReplacing.replace(component, regex, true, message);
        }
        return component;
    } else {
        return component;
    }
}
Also used : ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) InventoryPlaceholderEvent(com.loohp.interactivechat.api.events.InventoryPlaceholderEvent) IOException(java.io.IOException) Component(net.kyori.adventure.text.Component) Inventory(org.bukkit.inventory.Inventory)

Example 9 with ICPlayer

use of com.loohp.interactivechat.objectholders.ICPlayer in project InteractiveChat by LOOHP.

the class InventoryDisplay method process.

public static Component process(Component component, Optional<ICPlayer> optplayer, Player reciever, long unix) throws Exception {
    String plain = InteractiveChatComponentSerializer.plainText().serialize(component);
    if (InteractiveChat.invPlaceholder.matcher(plain).find()) {
        String regex = InteractiveChat.invPlaceholder.pattern();
        if (optplayer.isPresent()) {
            ICPlayer player = optplayer.get();
            if (PlayerUtils.hasPermission(player.getUniqueId(), "interactivechat.module.inventory", true, 5)) {
                String replaceText = InteractiveChat.invReplaceText;
                String title = ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(player, InteractiveChat.invTitle));
                String sha1 = HashUtils.createSha1(player.isRightHanded(), player.getSelectedSlot(), player.getExperienceLevel(), title, player.getInventory());
                if (!InteractiveChat.inventoryDisplay.containsKey(sha1)) {
                    layout0(player, sha1, title, reciever, component, unix);
                    layout1(player, sha1, title, reciever, component, unix);
                }
                String componentText = ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(player, replaceText));
                List<String> hoverList = ConfigManager.getConfig().getStringList("ItemDisplay.Inventory.HoverMessage");
                String hoverText = ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(player, String.join("\n", hoverList)));
                String command = "/interactivechat viewinv " + sha1;
                Component invComponent = LegacyComponentSerializer.legacySection().deserialize(componentText);
                invComponent = invComponent.hoverEvent(HoverEvent.showText(LegacyComponentSerializer.legacySection().deserialize(hoverText)));
                invComponent = invComponent.clickEvent(ClickEvent.runCommand(command));
                component = ComponentReplacing.replace(component, regex, true, invComponent);
            }
        } else {
            Component message;
            if (InteractiveChat.playerNotFoundReplaceEnable) {
                message = LegacyComponentSerializer.legacySection().deserialize(InteractiveChat.playerNotFoundReplaceText.replace("{Placeholder}", InteractiveChat.invName));
            } else {
                message = Component.text(InteractiveChat.invName);
            }
            if (InteractiveChat.playerNotFoundHoverEnable) {
                message = message.hoverEvent(HoverEvent.showText(LegacyComponentSerializer.legacySection().deserialize(InteractiveChat.playerNotFoundHoverText.replace("{Placeholder}", InteractiveChat.invName))));
            }
            if (InteractiveChat.playerNotFoundClickEnable) {
                String clickValue = ChatColorUtils.translateAlternateColorCodes('&', InteractiveChat.playerNotFoundClickValue.replace("{Placeholder}", InteractiveChat.invName));
                message = message.clickEvent(ClickEvent.clickEvent(ClickEvent.Action.valueOf(InteractiveChat.playerNotFoundClickAction), clickValue));
            }
            component = ComponentReplacing.replace(component, regex, true, message);
        }
        return component;
    } else {
        return component;
    }
}
Also used : ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) TranslatableComponent(net.kyori.adventure.text.TranslatableComponent) Component(net.kyori.adventure.text.Component)

Example 10 with ICPlayer

use of com.loohp.interactivechat.objectholders.ICPlayer in project InteractiveChat by LOOHP.

the class ProcessExternalMessage method processWithoutReceiver0.

@SuppressWarnings("deprecation")
public String processWithoutReceiver0(String message) {
    UUID senderUUID = ProcessAccurateSender.find(message);
    ICPlayer sender;
    if (senderUUID == null) {
        sender = null;
    } else {
        sender = ICPlayerFactory.getICPlayer(senderUUID);
    }
    message = message.replaceAll(ProcessCommands.COLOR_IGNORE_PATTERN_0.pattern(), "").replaceAll(ProcessCommands.COLOR_IGNORE_PATTERN_1.pattern(), "").replaceAll(ProcessAccurateSender.COLOR_IGNORE_PATTERN.pattern(), "");
    message = message.replaceAll(ProcessAccurateSender.PATTERN_0.pattern(), "$2");
    Matcher matcher = ProcessAccurateSender.PATTERN_0.matcher(message);
    StringBuffer sb = new StringBuffer();
    while (matcher.find()) {
        String replacement = Registry.ID_UNESCAPE_PATTERN.matcher(matcher.group(2)).replaceAll(">");
        matcher.appendReplacement(sb, replacement);
    }
    matcher.appendTail(sb);
    message = sb.toString();
    message = Registry.MENTION_TAG_CONVERTER.revertTags(message);
    if (sender == null) {
        return message;
    }
    long now = System.currentTimeMillis();
    long uniCooldown = InteractiveChatAPI.getPlayerUniversalCooldown(sender.getUniqueId()) - now;
    if (!(uniCooldown < 0 || uniCooldown + 100 > InteractiveChat.universalCooldown)) {
        return message;
    }
    if (InteractiveChat.rgbTags) {
        message = CustomStringUtils.clearPluginRGBTags(message);
    }
    if (InteractiveChat.fontTags) {
        message = CustomStringUtils.clearPluginFontTags(message);
    }
    Component component = LegacyComponentSerializer.legacySection().deserialize(message);
    for (ICPlaceholder placeholder : InteractiveChatAPI.getICPlaceholderList()) {
        if (!placeholder.isBuildIn()) {
            CustomPlaceholder customP = (CustomPlaceholder) placeholder;
            if (!InteractiveChat.useCustomPlaceholderPermissions || (InteractiveChat.useCustomPlaceholderPermissions && PlayerUtils.hasPermission(sender.getUniqueId(), customP.getPermission(), true, 250))) {
                if (customP.getKeyword().matcher(message).find()) {
                    if (customP.getReplace().isEnabled()) {
                        String replace = ChatColor.WHITE + ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(sender, customP.getReplace().getReplaceText()));
                        component = ComponentReplacing.replace(component, customP.getKeyword().pattern(), true, result -> {
                            String replaceString = CustomStringUtils.applyReplacementRegex(replace, result, 1);
                            return LegacyComponentSerializer.legacySection().deserialize(replaceString);
                        });
                    }
                }
            }
        }
    }
    if (InteractiveChat.t && WebData.getInstance() != null) {
        for (CustomPlaceholder customP : WebData.getInstance().getSpecialPlaceholders()) {
            if (customP.getKeyword().matcher(message).find()) {
                if (customP.getReplace().isEnabled()) {
                    String replace = ChatColor.WHITE + ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(sender, customP.getReplace().getReplaceText()));
                    component = ComponentReplacing.replace(component, customP.getKeyword().pattern(), true, result -> {
                        String replaceString = CustomStringUtils.applyReplacementRegex(replace, result, 1);
                        return LegacyComponentSerializer.legacySection().deserialize(replaceString);
                    });
                }
            }
        }
    }
    if (InteractiveChat.useItem && PlayerUtils.hasPermission(sender.getUniqueId(), "interactivechat.module.item", true, 250)) {
        Pattern placeholder = InteractiveChat.itemPlaceholder;
        if (placeholder.matcher(message).find()) {
            ItemStack item = sender.getEquipment().getItemInHand();
            if (item == null) {
                item = new ItemStack(Material.AIR);
            }
            String itemStr = InteractiveChatComponentSerializer.bungeecordApiLegacy().serialize(ItemStackUtils.getDisplayName(item), InteractiveChat.language);
            int amount = item.getAmount();
            if (item == null || item.getType().equals(Material.AIR)) {
                amount = 1;
            }
            itemStr = RarityUtils.getRarityColor(item) + itemStr;
            String replaceText;
            if (amount == 1) {
                replaceText = PlaceholderParser.parse(sender, InteractiveChat.itemSingularReplaceText.replace("{Item}", itemStr));
            } else {
                replaceText = PlaceholderParser.parse(sender, InteractiveChat.itemReplaceText.replace("{Amount}", String.valueOf(amount)).replace("{Item}", itemStr));
            }
            component = ComponentReplacing.replace(component, placeholder.pattern(), true, LegacyComponentSerializer.legacySection().deserialize(replaceText));
        }
    }
    if (InteractiveChat.useInventory && PlayerUtils.hasPermission(sender.getUniqueId(), "interactivechat.module.inventory", true, 250)) {
        Pattern placeholder = InteractiveChat.invPlaceholder;
        if (placeholder.matcher(message).find()) {
            String replaceText = PlaceholderParser.parse(sender, InteractiveChat.invReplaceText);
            component = ComponentReplacing.replace(component, placeholder.pattern(), true, LegacyComponentSerializer.legacySection().deserialize(replaceText));
        }
    }
    if (InteractiveChat.useEnder && PlayerUtils.hasPermission(sender.getUniqueId(), "interactivechat.module.enderchest", true, 250)) {
        Pattern placeholder = InteractiveChat.enderPlaceholder;
        if (placeholder.matcher(message).find()) {
            String replaceText = PlaceholderParser.parse(sender, InteractiveChat.enderReplaceText);
            component = ComponentReplacing.replace(component, placeholder.pattern(), true, LegacyComponentSerializer.legacySection().deserialize(replaceText));
        }
    }
    return LegacyComponentSerializer.builder().character(ChatColorUtils.COLOR_CHAR).hexColors().useUnusualXRepeatedCharacterHexFormat().build().serialize(component);
}
Also used : Plugin(org.bukkit.plugin.Plugin) ComponentReplacing(com.loohp.interactivechat.utils.ComponentReplacing) MCVersion(com.loohp.interactivechat.utils.MCVersion) PlayerUtils(com.loohp.interactivechat.utils.PlayerUtils) CustomPlaceholder(com.loohp.interactivechat.objectholders.CustomPlaceholder) InteractiveChatAPI(com.loohp.interactivechat.api.InteractiveChatAPI) PlayerData(com.loohp.interactivechat.data.PlayerDataManager.PlayerData) WebData(com.loohp.interactivechat.objectholders.WebData) Registry(com.loohp.interactivechat.registry.Registry) JsonUtils(com.loohp.interactivechat.utils.JsonUtils) Player(org.bukkit.entity.Player) ComponentModernizing(com.loohp.interactivechat.utils.ComponentModernizing) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) ComponentFont(com.loohp.interactivechat.utils.ComponentFont) InteractiveChatComponentSerializer(com.loohp.interactivechat.utils.InteractiveChatComponentSerializer) Matcher(java.util.regex.Matcher) Component(net.kyori.adventure.text.Component) ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) LegacyComponentSerializer(net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer) Method(java.lang.reflect.Method) ItemStackUtils(com.loohp.interactivechat.utils.ItemStackUtils) Material(org.bukkit.Material) ChatColor(net.md_5.bungee.api.ChatColor) Bukkit(org.bukkit.Bukkit) Collection(java.util.Collection) RarityUtils(com.loohp.interactivechat.utils.RarityUtils) UUID(java.util.UUID) Field(java.lang.reflect.Field) ItemStack(org.bukkit.inventory.ItemStack) InteractiveChat(com.loohp.interactivechat.InteractiveChat) TimeUnit(java.util.concurrent.TimeUnit) ICPlayerFactory(com.loohp.interactivechat.objectholders.ICPlayerFactory) ChatColorUtils(com.loohp.interactivechat.utils.ChatColorUtils) CustomStringUtils(com.loohp.interactivechat.utils.CustomStringUtils) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) PlaceholderParser(com.loohp.interactivechat.utils.PlaceholderParser) ProcessSenderResult(com.loohp.interactivechat.objectholders.ProcessSenderResult) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) CustomPlaceholder(com.loohp.interactivechat.objectholders.CustomPlaceholder) UUID(java.util.UUID) Component(net.kyori.adventure.text.Component) ItemStack(org.bukkit.inventory.ItemStack)

Aggregations

ICPlayer (com.loohp.interactivechat.objectholders.ICPlayer)22 Player (org.bukkit.entity.Player)11 UUID (java.util.UUID)10 Component (net.kyori.adventure.text.Component)10 InteractiveChat (com.loohp.interactivechat.InteractiveChat)9 ICPlayerFactory (com.loohp.interactivechat.objectholders.ICPlayerFactory)9 ArrayList (java.util.ArrayList)9 List (java.util.List)9 Bukkit (org.bukkit.Bukkit)9 ICPlaceholder (com.loohp.interactivechat.objectholders.ICPlaceholder)7 ChatColorUtils (com.loohp.interactivechat.utils.ChatColorUtils)7 ComponentReplacing (com.loohp.interactivechat.utils.ComponentReplacing)7 InteractiveChatComponentSerializer (com.loohp.interactivechat.utils.InteractiveChatComponentSerializer)7 PlaceholderParser (com.loohp.interactivechat.utils.PlaceholderParser)7 HashMap (java.util.HashMap)7 Optional (java.util.Optional)7 ItemStack (org.bukkit.inventory.ItemStack)7 InteractiveChatAPI (com.loohp.interactivechat.api.InteractiveChatAPI)6 CustomStringUtils (com.loohp.interactivechat.utils.CustomStringUtils)6 IOException (java.io.IOException)6