Search in sources :

Example 1 with PlayerData

use of com.loohp.interactivechat.data.PlayerDataManager.PlayerData in project InteractiveChat by LOOHP.

the class Commands method onCommand.

@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    if (!label.equalsIgnoreCase("interactivechat") && !label.equalsIgnoreCase("ic")) {
        return true;
    }
    if (args.length == 0) {
        sender.sendMessage(ChatColor.AQUA + "InteractiveChat written by LOOHP!");
        sender.sendMessage(ChatColor.GOLD + "You are running InteractiveChat version: " + InteractiveChat.plugin.getDescription().getVersion());
        return true;
    }
    if (args[0].equalsIgnoreCase("reload")) {
        if (sender.hasPermission("interactivechat.reload")) {
            InteractiveChat.closeSharedInventoryViews();
            ConfigManager.reloadConfig();
            InteractiveChat.placeholderCooldownManager.reloadPlaceholders();
            PlayerUtils.resetAllPermissionCache();
            Bukkit.getScheduler().runTaskAsynchronously(InteractiveChat.plugin, () -> InteractiveChat.playerDataManager.reload());
            if (InteractiveChat.bungeecordMode) {
                try {
                    BungeeMessageSender.reloadBungeeConfig(System.currentTimeMillis());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            sender.sendMessage(InteractiveChat.reloadPluginMessage);
        } else {
            sender.sendMessage(InteractiveChat.noPermissionMessage);
        }
        return true;
    }
    if (args[0].equalsIgnoreCase("update")) {
        if (sender.hasPermission("interactivechat.update")) {
            sender.sendMessage(ChatColor.AQUA + "[InteractiveChat] InteractiveChat written by LOOHP!");
            sender.sendMessage(ChatColor.GOLD + "[InteractiveChat] You are running InteractiveChat version: " + InteractiveChat.plugin.getDescription().getVersion());
            Bukkit.getScheduler().runTaskAsynchronously(InteractiveChat.plugin, () -> {
                UpdaterResponse version = Updater.checkUpdate();
                if (version.getResult().equals("latest")) {
                    if (version.isDevBuildLatest()) {
                        sender.sendMessage(ChatColor.GREEN + "[InteractiveChat] You are running the latest version!");
                    } else {
                        Updater.sendUpdateMessage(sender, version.getResult(), version.getSpigotPluginId(), true);
                    }
                } else {
                    Updater.sendUpdateMessage(sender, version.getResult(), version.getSpigotPluginId());
                }
            });
        } else {
            sender.sendMessage(InteractiveChat.noPermissionMessage);
        }
        return true;
    }
    if (args[0].equalsIgnoreCase("mentiontoggle")) {
        if (sender.hasPermission("interactivechat.mention.toggle")) {
            if (args.length == 1) {
                if (sender instanceof Player) {
                    Player player = (Player) sender;
                    PlayerData pd = InteractiveChat.playerDataManager.getPlayerData(player);
                    if (pd.isMentionDisabled()) {
                        pd.setMentionDisabled(false);
                        Bukkit.getScheduler().runTaskAsynchronously(InteractiveChat.plugin, () -> pd.save());
                        sender.sendMessage(InteractiveChat.mentionEnable);
                    } else {
                        pd.setMentionDisabled(true);
                        Bukkit.getScheduler().runTaskAsynchronously(InteractiveChat.plugin, () -> pd.save());
                        sender.sendMessage(InteractiveChat.mentionDisable);
                    }
                    if (InteractiveChat.bungeecordMode) {
                        try {
                            BungeeMessageSender.signalPlayerDataReload(System.currentTimeMillis(), player.getUniqueId());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                } else {
                    sender.sendMessage(InteractiveChat.noConsoleMessage);
                }
            } else {
                if (sender.hasPermission("interactivechat.mention.toggle.others")) {
                    Player player = Bukkit.getPlayer(args[1]);
                    if (player != null) {
                        PlayerData pd = InteractiveChat.playerDataManager.getPlayerData(player);
                        if (pd.isMentionDisabled()) {
                            pd.setMentionDisabled(false);
                            Bukkit.getScheduler().runTaskAsynchronously(InteractiveChat.plugin, () -> pd.save());
                            sender.sendMessage(InteractiveChat.mentionEnable);
                        } else {
                            pd.setMentionDisabled(true);
                            Bukkit.getScheduler().runTaskAsynchronously(InteractiveChat.plugin, () -> pd.save());
                            sender.sendMessage(InteractiveChat.mentionDisable);
                        }
                        if (InteractiveChat.bungeecordMode) {
                            try {
                                BungeeMessageSender.signalPlayerDataReload(System.currentTimeMillis(), player.getUniqueId());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        sender.sendMessage(InteractiveChat.invalidPlayerMessage);
                    }
                } else {
                    sender.sendMessage(InteractiveChat.noPermissionMessage);
                }
            }
        } else {
            sender.sendMessage(InteractiveChat.noPermissionMessage);
        }
        return true;
    }
    if (args[0].equalsIgnoreCase("setinvdisplaylayout")) {
        if (sender.hasPermission("interactivechat.module.inventory.setlayout")) {
            try {
                if (args.length == 1) {
                    sender.sendMessage(InteractiveChat.notEnoughArgs);
                } else if (args.length == 2) {
                    if (sender instanceof Player) {
                        int layout = Integer.parseInt(args[1]);
                        if (!InventoryDisplay.LAYOUTS.contains(layout)) {
                            throw new NumberFormatException();
                        }
                        Player player = (Player) sender;
                        PlayerData pd = InteractiveChat.playerDataManager.getPlayerData(player);
                        pd.setInventoryDisplayLayout(layout);
                        Bukkit.getScheduler().runTaskAsynchronously(InteractiveChat.plugin, () -> pd.save());
                        sender.sendMessage(InteractiveChat.setInvDisplayLayout.replace("{Layout}", layout + ""));
                        if (InteractiveChat.bungeecordMode) {
                            try {
                                BungeeMessageSender.signalPlayerDataReload(System.currentTimeMillis(), player.getUniqueId());
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    } else {
                        sender.sendMessage(InteractiveChat.noConsoleMessage);
                    }
                } else {
                    if (sender.hasPermission("interactivechat.module.inventory.setlayout.others")) {
                        Player player = Bukkit.getPlayer(args[2]);
                        if (player != null) {
                            int layout = Integer.parseInt(args[1]);
                            if (!InventoryDisplay.LAYOUTS.contains(layout)) {
                                throw new NumberFormatException();
                            }
                            PlayerData pd = InteractiveChat.playerDataManager.getPlayerData(player);
                            pd.setInventoryDisplayLayout(layout);
                            Bukkit.getScheduler().runTaskAsynchronously(InteractiveChat.plugin, () -> pd.save());
                            sender.sendMessage(InteractiveChat.setInvDisplayLayout.replace("{Layout}", layout + ""));
                            if (InteractiveChat.bungeecordMode) {
                                try {
                                    BungeeMessageSender.signalPlayerDataReload(System.currentTimeMillis(), player.getUniqueId());
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        } else {
                            sender.sendMessage(InteractiveChat.invalidPlayerMessage);
                        }
                    } else {
                        sender.sendMessage(InteractiveChat.noPermissionMessage);
                    }
                }
            } catch (NumberFormatException e) {
                sender.sendMessage(InteractiveChat.invalidArgs);
            }
        } else {
            sender.sendMessage(InteractiveChat.noPermissionMessage);
        }
        return true;
    }
    if (args[0].equalsIgnoreCase("list")) {
        try {
            if (sender.hasPermission("interactivechat.list")) {
                int start = 0;
                int end = InteractiveChat.placeholderList.size();
                if (args.length > 1) {
                    start = Integer.parseInt(args[1]) - 1;
                    if (start < 0) {
                        start = 0;
                    }
                }
                if (args.length > 2) {
                    end = Integer.parseInt(args[2]);
                    if (end < 0) {
                        end = InteractiveChat.placeholderList.size();
                    }
                }
                InteractiveChatAPI.sendMessageUnprocessed(sender, LegacyComponentSerializer.legacySection().deserialize(InteractiveChat.listPlaceholderHeader));
                String body = InteractiveChat.listPlaceholderBody;
                List<Component> items = new ArrayList<>();
                if (sender.hasPermission("interactivechat.list.all")) {
                    int i = 0;
                    for (ICPlaceholder placeholder : InteractiveChat.placeholderList.values()) {
                        i++;
                        String text = body.replace("{Order}", i + "").replace("{Keyword}", placeholder.getName()).replace("{Description}", placeholder.getDescription());
                        items.add(LegacyComponentSerializer.legacySection().deserialize(text));
                    }
                } else {
                    int i = 0;
                    for (ICPlaceholder placeholder : InteractiveChat.placeholderList.values()) {
                        if ((placeholder.isBuildIn() && sender.hasPermission(placeholder.getPermission())) || (!placeholder.isBuildIn() && (sender.hasPermission(placeholder.getPermission()) || !InteractiveChat.useCustomPlaceholderPermissions))) {
                            i++;
                            String text = body.replace("{Order}", i + "").replace("{Keyword}", placeholder.getName()).replace("{Description}", placeholder.getDescription());
                            items.add(LegacyComponentSerializer.legacySection().deserialize(text));
                        }
                    }
                }
                for (int i = start; i < end && i < items.size(); i++) {
                    InteractiveChatAPI.sendMessageUnprocessed(sender, items.get(i));
                }
            } else {
                sender.sendMessage(InteractiveChat.noPermissionMessage);
            }
        } catch (Exception e) {
            sender.sendMessage(InteractiveChat.invalidArgs);
        }
        return true;
    }
    if (args[0].equalsIgnoreCase("parse")) {
        if (sender.hasPermission("interactivechat.parse")) {
            if (sender instanceof Player) {
                String str = String.join(" ", Arrays.copyOfRange(args, 1, args.length));
                Player player = (Player) sender;
                Optional<ICPlayer> icplayer = Optional.of(ICPlayerFactory.getICPlayer(player));
                Bukkit.getScheduler().runTaskAsynchronously(InteractiveChat.plugin, () -> {
                    String text = str;
                    try {
                        long unix = System.currentTimeMillis();
                        if (InteractiveChat.chatAltColorCode.isPresent() && player.hasPermission("interactivechat.chatcolor.translate")) {
                            text = ChatColorUtils.translateAlternateColorCodes(InteractiveChat.chatAltColorCode.get(), str);
                        }
                        Component component = Component.text(text);
                        if (InteractiveChat.usePlayerName) {
                            component = PlayernameDisplay.process(component, icplayer, player, unix);
                        }
                        if (InteractiveChat.useItem) {
                            component = ItemDisplay.process(component, icplayer, player, unix);
                        }
                        if (InteractiveChat.useInventory) {
                            component = InventoryDisplay.process(component, icplayer, player, unix);
                        }
                        if (InteractiveChat.useEnder) {
                            component = EnderchestDisplay.process(component, icplayer, player, unix);
                        }
                        component = CustomPlaceholderDisplay.process(component, icplayer, player, InteractiveChat.placeholderList.values(), unix);
                        if (InteractiveChat.clickableCommands) {
                            component = CommandsDisplay.process(component);
                        }
                        if (InteractiveChat.version.isNewerOrEqualTo(MCVersion.V1_16) && InteractiveChat.fontTags) {
                            if (PlayerUtils.hasPermission(player.getUniqueId(), "interactivechat.customfont.translate", true, 250)) {
                                component = ComponentFont.parseFont(component);
                            }
                        }
                        String json = InteractiveChatComponentSerializer.gson().serialize(component);
                        if (json.length() > InteractiveChat.packetStringMaxLength) {
                            InteractiveChatAPI.sendMessageUnprocessed(sender, Component.text(text));
                        } else {
                            InteractiveChatAPI.sendMessageUnprocessed(sender, component);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
            } else {
                sender.sendMessage(String.join(" ", Arrays.copyOfRange(args, 1, args.length)));
            }
        } else {
            sender.sendMessage(InteractiveChat.noPermissionMessage);
        }
        return true;
    }
    if (args[0].equalsIgnoreCase("chat")) {
        if (sender.hasPermission("interactivechat.chat")) {
            if (args.length > 1) {
                if (sender instanceof Player) {
                    String message = String.join(" ", Arrays.copyOfRange(args, 1, args.length));
                    PacketContainer packet = InteractiveChat.protocolManager.createPacket(PacketType.Play.Client.CHAT);
                    packet.getStrings().write(0, message);
                    try {
                        InteractiveChat.protocolManager.recieveClientPacket((Player) sender, packet);
                    } catch (IllegalAccessException | InvocationTargetException e) {
                        e.printStackTrace();
                    }
                } else {
                    sender.sendMessage(InteractiveChat.noConsoleMessage);
                }
            }
        } else {
            sender.sendMessage(InteractiveChat.noPermissionMessage);
        }
        return true;
    }
    if (sender instanceof Player && args.length > 1) {
        Player player = (Player) sender;
        switch(args[0].toLowerCase()) {
            case "viewinv":
                {
                    PlayerData data = InteractiveChat.playerDataManager.getPlayerData(player);
                    String hash = args[1];
                    if (data == null || data.getInventoryDisplayLayout() == 0) {
                        Inventory inv = InteractiveChat.inventoryDisplay.get(hash);
                        if (inv != null) {
                            Bukkit.getScheduler().runTask(InteractiveChat.plugin, () -> player.openInventory(inv));
                        } else {
                            player.sendMessage(PlaceholderAPI.setPlaceholders(player, InteractiveChat.invExpiredMessage));
                        }
                    } else {
                        Inventory inv = InteractiveChat.inventoryDisplay1Upper.get(hash);
                        Inventory inv2 = InteractiveChat.inventoryDisplay1Lower.get(hash);
                        if (inv != null && inv2 != null) {
                            Bukkit.getScheduler().runTask(InteractiveChat.plugin, () -> {
                                player.openInventory(inv);
                                InventoryUtils.sendFakePlayerInventory(player, inv2, true, false);
                                InteractiveChat.viewingInv1.put(player.getUniqueId(), hash);
                            });
                        } else {
                            player.sendMessage(PlaceholderAPI.setPlaceholders(player, InteractiveChat.invExpiredMessage));
                        }
                    }
                    break;
                }
            case "viewender":
                {
                    Inventory inv = InteractiveChat.enderDisplay.get(args[1]);
                    if (inv != null) {
                        Bukkit.getScheduler().runTask(InteractiveChat.plugin, () -> player.openInventory(inv));
                    } else {
                        player.sendMessage(PlaceholderAPI.setPlaceholders(player, InteractiveChat.invExpiredMessage));
                    }
                    break;
                }
            case "viewitem":
                {
                    Inventory inv = InteractiveChat.itemDisplay.get(args[1]);
                    if (inv != null) {
                        Bukkit.getScheduler().runTask(InteractiveChat.plugin, () -> player.openInventory(inv));
                    } else {
                        player.sendMessage(PlaceholderAPI.setPlaceholders(player, InteractiveChat.invExpiredMessage));
                    }
                    break;
                }
            case "viewmap":
                ItemStack map = InteractiveChat.mapDisplay.get(args[1]);
                if (map != null) {
                    Bukkit.getScheduler().runTask(InteractiveChat.plugin, () -> MapViewer.showMap(player, map));
                } else {
                    player.sendMessage(PlaceholderAPI.setPlaceholders(player, InteractiveChat.invExpiredMessage));
                }
                break;
        }
        return true;
    }
    sender.sendMessage(ChatColorUtils.translateAlternateColorCodes('&', Bukkit.spigot().getConfig().getString("messages.unknown-command")));
    return true;
}
Also used : ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) Player(org.bukkit.entity.Player) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) PacketContainer(com.comphenix.protocol.events.PacketContainer) ArrayList(java.util.ArrayList) UpdaterResponse(com.loohp.interactivechat.updater.Updater.UpdaterResponse) InvocationTargetException(java.lang.reflect.InvocationTargetException) InvocationTargetException(java.lang.reflect.InvocationTargetException) ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) Component(net.kyori.adventure.text.Component) ItemStack(org.bukkit.inventory.ItemStack) PlayerData(com.loohp.interactivechat.data.PlayerDataManager.PlayerData) Inventory(org.bukkit.inventory.Inventory)

Example 2 with PlayerData

use of com.loohp.interactivechat.data.PlayerDataManager.PlayerData in project InteractiveChat by LOOHP.

the class ChatEvents method checkMention.

private String checkMention(AsyncPlayerChatEvent event) {
    Player sender = event.getPlayer();
    String message = event.getMessage();
    PlayerData data = InteractiveChat.playerDataManager.getPlayerData(sender);
    if (InteractiveChat.allowMention && (data == null || !data.isMentionDisabled())) {
        String processedMessage;
        if (!InteractiveChat.disableEveryone && (processedMessage = checkMentionEveryone("chat", message, sender)) != null) {
            return processedMessage;
        }
        if (!InteractiveChat.disableHere && (processedMessage = checkMentionHere("chat", message, sender)) != null) {
            return processedMessage;
        }
        if ((processedMessage = checkMentionPlayers("chat", message, sender)) != null) {
            return processedMessage;
        }
    }
    return message;
}
Also used : Player(org.bukkit.entity.Player) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) PlayerData(com.loohp.interactivechat.data.PlayerDataManager.PlayerData)

Example 3 with PlayerData

use of com.loohp.interactivechat.data.PlayerDataManager.PlayerData 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 4 with PlayerData

use of com.loohp.interactivechat.data.PlayerDataManager.PlayerData in project InteractiveChat by LOOHP.

the class Placeholders method onRequest.

@Override
public String onRequest(OfflinePlayer offlineplayer, String identifier) {
    if (identifier.equals("mentiontoggle")) {
        PlayerData pd;
        if (offlineplayer.isOnline()) {
            Player player = offlineplayer.getPlayer();
            pd = InteractiveChat.playerDataManager.getPlayerData(player);
        } else {
            pd = InteractiveChat.database.getPlayerInfo(offlineplayer.getUniqueId());
        }
        return pd == null ? "enabled" : (pd.isMentionDisabled() ? "disabled" : "enabled");
    }
    if (identifier.equals("invdisplaylayout")) {
        PlayerData pd;
        if (offlineplayer.isOnline()) {
            Player player = offlineplayer.getPlayer();
            pd = InteractiveChat.playerDataManager.getPlayerData(player);
        } else {
            pd = InteractiveChat.database.getPlayerInfo(offlineplayer.getUniqueId());
        }
        return (pd == null ? InteractiveChat.invDisplayLayout : pd.getInventoryDisplayLayout()) + "";
    }
    return null;
}
Also used : Player(org.bukkit.entity.Player) OfflinePlayer(org.bukkit.OfflinePlayer) PlayerData(com.loohp.interactivechat.data.PlayerDataManager.PlayerData)

Example 5 with PlayerData

use of com.loohp.interactivechat.data.PlayerDataManager.PlayerData in project InteractiveChat by LOOHP.

the class ProcessExternalMessage method processAndRespond0.

public String processAndRespond0(Player receiver, String json) throws Exception {
    Component component = InteractiveChatComponentSerializer.gson().deserialize(json);
    Component originalComponent = component;
    try {
        if (LegacyComponentSerializer.legacySection().serialize(component).isEmpty()) {
            return json;
        }
    } catch (Exception e) {
        return json;
    }
    if ((InteractiveChat.version.isOld()) && JsonUtils.containsKey(InteractiveChatComponentSerializer.gson().serialize(component), "translate")) {
        return json;
    }
    Optional<ICPlayer> sender = Optional.empty();
    String rawMessageKey = InteractiveChatComponentSerializer.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) {
        sender = Optional.ofNullable(ICPlayerFactory.getICPlayer(commandSender.getSender()));
    }
    ProcessSenderResult chatSender = null;
    if (!sender.isPresent()) {
        if (InteractiveChat.useAccurateSenderFinder) {
            chatSender = ProcessAccurateSender.process(component);
            if (chatSender.getSender() != null) {
                sender = Optional.ofNullable(ICPlayerFactory.getICPlayer(chatSender.getSender()));
            }
        }
    }
    if (!sender.isPresent() && !InteractiveChat.useAccurateSenderFinder) {
        sender = SenderFinder.getSender(component, rawMessageKey);
    }
    component = commandSender.getComponent();
    if (chatSender != null) {
        component = chatSender.getComponent();
    }
    String text = LegacyComponentSerializer.legacySection().serialize(component);
    if (InteractiveChat.messageToIgnore.stream().anyMatch(each -> text.matches(each))) {
        return json;
    }
    if (sender.isPresent()) {
        InteractiveChat.keyPlayer.put(rawMessageKey, sender.get());
    }
    String server;
    if (sender.isPresent() && !sender.get().isLocal()) {
        try {
            TimeUnit.MILLISECONDS.sleep(InteractiveChat.remoteDelay);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        server = sender.get().getServer();
    } else {
        server = ICPlayer.LOCAL_SERVER_REPRESENTATION;
    }
    component = ComponentModernizing.modernize(component);
    component = ComponentReplacing.replace(component, Registry.ID_PATTERN.pattern(), Component.empty());
    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, !Bukkit.isPrimaryThread());
        }
    }
    component = ComponentReplacing.replace(component, Registry.MENTION_TAG_CONVERTER.getReversePattern().pattern(), true, (result, components) -> {
        return LegacyComponentSerializer.legacySection().deserialize(result.group(2));
    });
    Collection<ICPlaceholder> serverPlaceholderList = InteractiveChat.remotePlaceholderList.get(server);
    if (server.equals(ICPlayer.LOCAL_SERVER_REPRESENTATION) || serverPlaceholderList == null) {
        serverPlaceholderList = InteractiveChat.placeholderList.values();
    }
    component = CustomPlaceholderDisplay.process(component, sender, receiver, serverPlaceholderList, 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, 5))) {
            component = ComponentFont.parseFont(component);
        }
    }
    Bukkit.getScheduler().runTaskLater(InteractiveChat.plugin, () -> {
        InteractiveChat.keyTime.remove(rawMessageKey);
        InteractiveChat.keyPlayer.remove(rawMessageKey);
    }, 5);
    String newJson = InteractiveChatComponentSerializer.gson().serialize(component);
    if (InteractiveChat.sendOriginalIfTooLong && newJson.length() > InteractiveChat.packetStringMaxLength) {
        String originalJson = InteractiveChatComponentSerializer.gson().serialize(originalComponent);
        if (originalJson.length() > InteractiveChat.packetStringMaxLength) {
            return "{\"text\":\"\"}";
        } else {
            return originalJson;
        }
    }
    return newJson;
}
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) ProcessSenderResult(com.loohp.interactivechat.objectholders.ProcessSenderResult) ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) Component(net.kyori.adventure.text.Component) PlayerData(com.loohp.interactivechat.data.PlayerDataManager.PlayerData)

Aggregations

PlayerData (com.loohp.interactivechat.data.PlayerDataManager.PlayerData)6 Player (org.bukkit.entity.Player)6 ICPlayer (com.loohp.interactivechat.objectholders.ICPlayer)5 InteractiveChat (com.loohp.interactivechat.InteractiveChat)3 ICPlaceholder (com.loohp.interactivechat.objectholders.ICPlaceholder)3 ICPlayerFactory (com.loohp.interactivechat.objectholders.ICPlayerFactory)3 PacketContainer (com.comphenix.protocol.events.PacketContainer)2 InteractiveChatAPI (com.loohp.interactivechat.api.InteractiveChatAPI)2 CustomPlaceholder (com.loohp.interactivechat.objectholders.CustomPlaceholder)2 ProcessSenderResult (com.loohp.interactivechat.objectholders.ProcessSenderResult)2 Registry (com.loohp.interactivechat.registry.Registry)2 ComponentFont (com.loohp.interactivechat.utils.ComponentFont)2 ComponentModernizing (com.loohp.interactivechat.utils.ComponentModernizing)2 ComponentReplacing (com.loohp.interactivechat.utils.ComponentReplacing)2 InteractiveChatComponentSerializer (com.loohp.interactivechat.utils.InteractiveChatComponentSerializer)2 PlaceholderParser (com.loohp.interactivechat.utils.PlaceholderParser)2 Optional (java.util.Optional)2 UUID (java.util.UUID)2 Pattern (java.util.regex.Pattern)2 Component (net.kyori.adventure.text.Component)2