Search in sources :

Example 1 with PostPacketComponentProcessEvent

use of com.loohp.interactivechat.api.events.PostPacketComponentProcessEvent 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)

Aggregations

PacketType (com.comphenix.protocol.PacketType)1 ListenerPriority (com.comphenix.protocol.events.ListenerPriority)1 PacketAdapter (com.comphenix.protocol.events.PacketAdapter)1 PacketContainer (com.comphenix.protocol.events.PacketContainer)1 PacketEvent (com.comphenix.protocol.events.PacketEvent)1 ChatType (com.comphenix.protocol.wrappers.EnumWrappers.ChatType)1 WrappedChatComponent (com.comphenix.protocol.wrappers.WrappedChatComponent)1 InteractiveChat (com.loohp.interactivechat.InteractiveChat)1 PostPacketComponentProcessEvent (com.loohp.interactivechat.api.events.PostPacketComponentProcessEvent)1 PreChatPacketSendEvent (com.loohp.interactivechat.api.events.PreChatPacketSendEvent)1 PrePacketComponentProcessEvent (com.loohp.interactivechat.api.events.PrePacketComponentProcessEvent)1 PlayerData (com.loohp.interactivechat.data.PlayerDataManager.PlayerData)1 VentureChatInjection (com.loohp.interactivechat.hooks.venturechat.VentureChatInjection)1 CommandsDisplay (com.loohp.interactivechat.modules.CommandsDisplay)1 CustomPlaceholderDisplay (com.loohp.interactivechat.modules.CustomPlaceholderDisplay)1 EnderchestDisplay (com.loohp.interactivechat.modules.EnderchestDisplay)1 HoverableItemDisplay (com.loohp.interactivechat.modules.HoverableItemDisplay)1 InventoryDisplay (com.loohp.interactivechat.modules.InventoryDisplay)1 ItemDisplay (com.loohp.interactivechat.modules.ItemDisplay)1 MentionDisplay (com.loohp.interactivechat.modules.MentionDisplay)1