Search in sources :

Example 21 with ICPlaceholder

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

the class PluginMessageSendingBungee method forwardPlaceholderList.

@SuppressWarnings("deprecation")
public static void forwardPlaceholderList(List<ICPlaceholder> serverPlaceholderList, ServerInfo serverFrom) throws IOException {
    ByteArrayDataOutput output = ByteStreams.newDataOutput();
    DataTypeIO.writeString(output, serverFrom.getName(), StandardCharsets.UTF_8);
    output.writeInt(serverPlaceholderList.size());
    for (ICPlaceholder placeholder : serverPlaceholderList) {
        boolean isBuiltIn = placeholder.isBuildIn();
        output.writeBoolean(isBuiltIn);
        if (isBuiltIn) {
            DataTypeIO.writeString(output, placeholder.getKeyword().pattern(), StandardCharsets.UTF_8);
            DataTypeIO.writeString(output, placeholder.getName(), StandardCharsets.UTF_8);
            DataTypeIO.writeString(output, placeholder.getDescription(), StandardCharsets.UTF_8);
            DataTypeIO.writeString(output, placeholder.getPermission(), StandardCharsets.UTF_8);
            output.writeLong(placeholder.getCooldown());
        } else {
            CustomPlaceholder customPlaceholder = (CustomPlaceholder) placeholder;
            output.writeInt(customPlaceholder.getPosition());
            output.writeByte(customPlaceholder.getParsePlayer().getOrder());
            DataTypeIO.writeString(output, customPlaceholder.getKeyword().pattern(), StandardCharsets.UTF_8);
            output.writeBoolean(customPlaceholder.getParseKeyword());
            output.writeLong(customPlaceholder.getCooldown());
            CustomPlaceholderHoverEvent hover = customPlaceholder.getHover();
            output.writeBoolean(hover.isEnabled());
            DataTypeIO.writeString(output, hover.getText(), StandardCharsets.UTF_8);
            CustomPlaceholderClickEvent click = customPlaceholder.getClick();
            output.writeBoolean(click.isEnabled());
            DataTypeIO.writeString(output, click.getAction() == null ? "" : click.getAction().name(), StandardCharsets.UTF_8);
            DataTypeIO.writeString(output, click.getValue(), StandardCharsets.UTF_8);
            CustomPlaceholderReplaceText replace = customPlaceholder.getReplace();
            output.writeBoolean(replace.isEnabled());
            DataTypeIO.writeString(output, replace.getReplaceText(), StandardCharsets.UTF_8);
            DataTypeIO.writeString(output, placeholder.getName(), StandardCharsets.UTF_8);
            DataTypeIO.writeString(output, placeholder.getDescription(), StandardCharsets.UTF_8);
        }
    }
    int packetNumber = InteractiveChatBungee.random.nextInt();
    int packetId = 0x09;
    byte[] data = output.toByteArray();
    byte[][] dataArray = CustomArrayUtils.divideArray(data, 32700);
    for (int i = 0; i < dataArray.length; i++) {
        byte[] chunk = dataArray[i];
        ByteArrayDataOutput out = ByteStreams.newDataOutput();
        out.writeInt(packetNumber);
        out.writeShort(packetId);
        out.writeBoolean(i == (dataArray.length - 1));
        out.write(chunk);
        for (ServerInfo server : ProxyServer.getInstance().getServers().values()) {
            if (!server.getName().equals(serverFrom.getName())) {
                server.sendData("interchat:main", out.toByteArray());
                InteractiveChatBungee.pluginMessagesCounter.incrementAndGet();
            }
        }
    }
}
Also used : ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) ServerInfo(net.md_5.bungee.api.config.ServerInfo) ByteArrayDataOutput(com.google.common.io.ByteArrayDataOutput) CustomPlaceholder(com.loohp.interactivechat.objectholders.CustomPlaceholder) CustomPlaceholderHoverEvent(com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderHoverEvent) CustomPlaceholderClickEvent(com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderClickEvent) CustomPlaceholderReplaceText(com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderReplaceText)

Example 22 with ICPlaceholder

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

the class BungeeMessageListener method onPluginMessageReceived.

@SuppressWarnings("deprecation")
@Override
public void onPluginMessageReceived(String channel, Player pluginMessagingPlayer, byte[] bytes) {
    if (!channel.equals("interchat:main")) {
        return;
    }
    ByteArrayDataInput in = ByteStreams.newDataInput(bytes);
    int packetNumber = in.readInt();
    int packetId = in.readShort();
    boolean isEnding = in.readBoolean();
    byte[] data = new byte[bytes.length - 7];
    in.readFully(data);
    byte[] chain = incoming.remove(packetNumber);
    if (chain != null) {
        ByteBuffer buff = ByteBuffer.allocate(chain.length + data.length);
        buff.put(chain);
        buff.put(data);
        data = buff.array();
    }
    if (!isEnding) {
        incoming.put(packetNumber, data);
        return;
    }
    try {
        ByteArrayDataInput input = ByteStreams.newDataInput(data);
        switch(packetId) {
            case 0x00:
                int playerAmount = input.readInt();
                Set<UUID> localUUID = Bukkit.getOnlinePlayers().stream().map(each -> each.getUniqueId()).collect(Collectors.toSet());
                Set<UUID> current = new HashSet<>(ICPlayerFactory.getRemoteUUIDs());
                Set<UUID> newSet = new HashSet<>();
                for (int i = 0; i < playerAmount; i++) {
                    String server = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                    UUID uuid = DataTypeIO.readUUID(input);
                    String name = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                    ICPlayer player = ICPlayerFactory.getICPlayer(uuid);
                    if (player != null) {
                        if (!player.getRemoteServer().equals(server)) {
                            player.setRemoteServer(server);
                        }
                    }
                    if (!localUUID.contains(uuid) && !ICPlayerFactory.getRemoteUUIDs().contains(uuid)) {
                        ICPlayerFactory.createOrUpdateRemoteICPlayer(server, name, uuid, true, 0, 0, Bukkit.createInventory(null, 45), Bukkit.createInventory(null, 36));
                    }
                    newSet.add(uuid);
                }
                current.removeAll(newSet);
                for (UUID uuid : current) {
                    ICPlayerFactory.removeRemoteICPlayer(uuid);
                }
                for (UUID uuid : localUUID) {
                    ICPlayerFactory.removeRemoteICPlayer(uuid);
                }
                break;
            case 0x01:
                int delay = input.readInt();
                short itemStackScheme = input.readShort();
                short inventoryScheme = input.readShort();
                InteractiveChat.remoteDelay = delay;
                BungeeMessageSender.itemStackScheme = itemStackScheme;
                BungeeMessageSender.inventoryScheme = inventoryScheme;
                break;
            case 0x02:
                UUID sender = DataTypeIO.readUUID(input);
                UUID receiver = DataTypeIO.readUUID(input);
                InteractiveChat.mentionPair.add(new MentionPair(sender, receiver));
                break;
            case 0x03:
                UUID uuid = DataTypeIO.readUUID(input);
                ICPlayer player = ICPlayerFactory.getICPlayer(uuid);
                if (player == null) {
                    break;
                }
                boolean rightHanded = input.readBoolean();
                player.setRemoteRightHanded(rightHanded);
                int selectedSlot = input.readByte();
                player.setRemoteSelectedSlot(selectedSlot);
                int level = input.readInt();
                player.setRemoteExperienceLevel(level);
                int size = input.readByte();
                ItemStack[] equipment = new ItemStack[size];
                for (int i = 0; i < equipment.length; i++) {
                    equipment[i] = DataTypeIO.readItemStack(input, StandardCharsets.UTF_8);
                }
                player.getEquipment().setHelmet(equipment[0]);
                player.getEquipment().setChestplate(equipment[1]);
                player.getEquipment().setLeggings(equipment[2]);
                player.getEquipment().setBoots(equipment[3]);
                if (InteractiveChat.version.isOld()) {
                    player.getEquipment().setItemInHand(equipment[4]);
                } else {
                    player.getEquipment().setItemInMainHand(equipment[4]);
                    player.getEquipment().setItemInOffHand(equipment[5]);
                }
                break;
            case 0x04:
                UUID uuid1 = DataTypeIO.readUUID(input);
                ICPlayer player1 = ICPlayerFactory.getICPlayer(uuid1);
                if (player1 == null) {
                    break;
                }
                boolean rightHanded1 = input.readBoolean();
                player1.setRemoteRightHanded(rightHanded1);
                int selectedSlot1 = input.readByte();
                player1.setRemoteSelectedSlot(selectedSlot1);
                int level1 = input.readInt();
                player1.setRemoteExperienceLevel(level1);
                int type = input.readByte();
                if (type == 0) {
                    player1.setRemoteInventory(DataTypeIO.readInventory(input, StandardCharsets.UTF_8));
                } else {
                    player1.setRemoteEnderChest(DataTypeIO.readInventory(input, StandardCharsets.UTF_8));
                }
                break;
            case 0x05:
                UUID uuid2 = DataTypeIO.readUUID(input);
                ICPlayer player2 = ICPlayerFactory.getICPlayer(uuid2);
                if (player2 == null) {
                    break;
                }
                int size1 = input.readInt();
                for (int i = 0; i < size1; i++) {
                    String placeholder = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                    String text = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                    player2.getRemotePlaceholdersMapping().put(placeholder, text);
                }
                break;
            case 0x06:
                String message = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                UUID uuid3 = DataTypeIO.readUUID(input);
                ICPlayer player3 = ICPlayerFactory.getICPlayer(uuid3);
                if (player3 == null) {
                    break;
                }
                InteractiveChat.messages.put(message, uuid3);
                Bukkit.getScheduler().runTaskLater(InteractiveChat.plugin, () -> InteractiveChat.messages.remove(message), 60);
                break;
            case 0x07:
                int cooldownType = input.readByte();
                switch(cooldownType) {
                    case 0:
                        UUID uuid4 = DataTypeIO.readUUID(input);
                        long time = input.readLong();
                        InteractiveChat.placeholderCooldownManager.setPlayerUniversalLastTimestampRaw(uuid4, time);
                        break;
                    case 1:
                        uuid4 = DataTypeIO.readUUID(input);
                        UUID internalId = DataTypeIO.readUUID(input);
                        time = input.readLong();
                        Optional<ICPlaceholder> optPlaceholder = InteractiveChat.placeholderList.values().stream().filter(each -> each.getInternalId().equals(internalId)).findFirst();
                        if (optPlaceholder.isPresent()) {
                            InteractiveChat.placeholderCooldownManager.setPlayerPlaceholderLastTimestampRaw(uuid4, optPlaceholder.get(), time);
                        }
                        break;
                }
                break;
            case 0x08:
                UUID messageId = DataTypeIO.readUUID(input);
                UUID uuid5 = DataTypeIO.readUUID(input);
                Player bukkitplayer1 = Bukkit.getPlayer(uuid5);
                if (bukkitplayer1 == null) {
                    break;
                }
                String component = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                Bukkit.getScheduler().runTaskAsynchronously(InteractiveChat.plugin, () -> {
                    try {
                        String processed = ProcessExternalMessage.processAndRespond(bukkitplayer1, component);
                        BungeeMessageSender.respondProcessedMessage(System.currentTimeMillis(), processed, messageId);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                });
                break;
            case 0x09:
                String server = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                int size2 = input.readInt();
                List<ICPlaceholder> list = new ArrayList<>(size2);
                for (int i = 0; i < size2; i++) {
                    boolean isBulitIn = input.readBoolean();
                    if (isBulitIn) {
                        String keyword = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                        String name = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                        String description = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                        String permission = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                        long cooldown = input.readLong();
                        list.add(new BuiltInPlaceholder(Pattern.compile(keyword), name, description, permission, cooldown));
                    } else {
                        int customNo = input.readInt();
                        ParsePlayer parseplayer = ParsePlayer.fromOrder(input.readByte());
                        String placeholder = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                        boolean parseKeyword = input.readBoolean();
                        long cooldown = input.readLong();
                        boolean hoverEnabled = input.readBoolean();
                        String hoverText = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                        boolean clickEnabled = input.readBoolean();
                        String clickAction = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                        String clickValue = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                        boolean replaceEnabled = input.readBoolean();
                        String replaceText = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                        String name = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                        String description = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                        list.add(new CustomPlaceholder(customNo, parseplayer, Pattern.compile(placeholder), parseKeyword, cooldown, new CustomPlaceholderHoverEvent(hoverEnabled, hoverText), new CustomPlaceholderClickEvent(clickEnabled, clickEnabled ? ClickEventAction.valueOf(clickAction) : null, clickValue), new CustomPlaceholderReplaceText(replaceEnabled, replaceText), name, description));
                    }
                }
                InteractiveChat.remotePlaceholderList.put(server, list);
                break;
            case 0x0A:
                BungeeMessageSender.resetAndForwardPlaceholderList(System.currentTimeMillis(), InteractiveChat.placeholderList.values());
                break;
            case 0x0B:
                int id = input.readInt();
                UUID playerUUID = DataTypeIO.readUUID(input);
                String permission = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                Player player5 = Bukkit.getPlayer(playerUUID);
                BungeeMessageSender.permissionCheckResponse(System.currentTimeMillis(), id, player5 != null && player5.hasPermission(permission));
                break;
            case 0x0D:
                UUID playerUUID1 = DataTypeIO.readUUID(input);
                PlayerData pd = InteractiveChat.playerDataManager.getPlayerData(playerUUID1);
                if (pd != null) {
                    pd.reload();
                }
                break;
            case 0x0E:
                SharedType sharedType = SharedType.fromValue(input.readByte());
                String sha1 = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                Inventory inventory = DataTypeIO.readInventory(input, StandardCharsets.UTF_8);
                InteractiveChatAPI.addInventoryToItemShareList(sharedType, sha1, inventory);
                break;
            case 0x0F:
                int requestType = input.readByte();
                UUID playerUUID2 = DataTypeIO.readUUID(input);
                Player player6 = Bukkit.getPlayer(playerUUID2);
                if (player6 != null) {
                    ICPlayer player7 = ICPlayerFactory.getICPlayer(player6);
                    switch(requestType) {
                        case 0:
                            BungeeMessageSender.forwardInventory(System.currentTimeMillis(), player7.getUniqueId(), player7.isRightHanded(), player7.getSelectedSlot(), player7.getExperienceLevel(), null, player7.getInventory());
                            break;
                        case 1:
                            BungeeMessageSender.forwardEnderchest(System.currentTimeMillis(), player7.getUniqueId(), player7.isRightHanded(), player7.getSelectedSlot(), player7.getExperienceLevel(), null, player7.getEnderChest());
                            break;
                    }
                }
                break;
            case 0x10:
                UUID requestUUID = DataTypeIO.readUUID(input);
                int requestType2 = input.readByte();
                // noinspection SwitchStatementWithTooFewBranches
                switch(requestType2) {
                    case 0:
                        List<ValueTrios<UUID, String, Integer>> playerlist = new ArrayList<>();
                        int playerListSize = input.readInt();
                        for (int i = 0; i < playerListSize; i++) {
                            playerlist.add(new ValueTrios<>(DataTypeIO.readUUID(input), DataTypeIO.readString(input, StandardCharsets.UTF_8), input.readInt()));
                        }
                        @SuppressWarnings("unchecked") CompletableFuture<List<ValueTrios<UUID, String, Integer>>> future = (CompletableFuture<List<ValueTrios<UUID, String, Integer>>>) toComplete.remove(requestUUID);
                        if (future != null) {
                            future.complete(playerlist);
                        }
                        break;
                    default:
                        break;
                }
                break;
            case 0x11:
                UUID playerUUID3 = DataTypeIO.readUUID(input);
                int nicknameSize = input.readInt();
                Set<String> remoteNicknames = new HashSet<>();
                for (int i = 0; i < nicknameSize; i++) {
                    remoteNicknames.add(DataTypeIO.readString(input, StandardCharsets.UTF_8));
                }
                ICPlayer icPlayer = ICPlayerFactory.getICPlayer(playerUUID3);
                if (icPlayer != null) {
                    icPlayer.setRemoteNicknames(remoteNicknames);
                }
                break;
            case 0x12:
                UUID playerUUID4 = DataTypeIO.readUUID(input);
                String placeholders = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                ICPlayer icPlayer1 = ICPlayerFactory.getICPlayer(playerUUID4);
                if (icPlayer1 != null && icPlayer1.isLocal()) {
                    PlaceholderParser.parse(icPlayer1, placeholders);
                }
                break;
            case 0xFF:
                String customChannel = DataTypeIO.readString(input, StandardCharsets.UTF_8);
                int dataLength = input.readInt();
                byte[] customData = new byte[dataLength];
                input.readFully(customData);
                ProxyCustomDataRecievedEvent dataEvent = new ProxyCustomDataRecievedEvent(customChannel, customData);
                Bukkit.getPluginManager().callEvent(dataEvent);
                break;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
}
Also used : CustomPlaceholder(com.loohp.interactivechat.objectholders.CustomPlaceholder) InteractiveChatAPI(com.loohp.interactivechat.api.InteractiveChatAPI) PlayerData(com.loohp.interactivechat.data.PlayerDataManager.PlayerData) DataTypeIO(com.loohp.interactivechat.utils.DataTypeIO) TimeoutException(java.util.concurrent.TimeoutException) HashMap(java.util.HashMap) CompletableFuture(java.util.concurrent.CompletableFuture) BuiltInPlaceholder(com.loohp.interactivechat.objectholders.BuiltInPlaceholder) Player(org.bukkit.entity.Player) ParsePlayer(com.loohp.interactivechat.objectholders.CustomPlaceholder.ParsePlayer) Inventory(org.bukkit.inventory.Inventory) ByteBuffer(java.nio.ByteBuffer) CustomPlaceholderReplaceText(com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderReplaceText) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) PluginMessageListener(org.bukkit.plugin.messaging.PluginMessageListener) ProcessExternalMessage(com.loohp.interactivechat.modules.ProcessExternalMessage) Map(java.util.Map) ByteArrayDataInput(com.google.common.io.ByteArrayDataInput) MentionPair(com.loohp.interactivechat.objectholders.MentionPair) SharedType(com.loohp.interactivechat.api.InteractiveChatAPI.SharedType) ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) Bukkit(org.bukkit.Bukkit) ProxyCustomDataRecievedEvent(com.loohp.interactivechat.api.events.ProxyCustomDataRecievedEvent) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) StandardCharsets(java.nio.charset.StandardCharsets) ItemStack(org.bukkit.inventory.ItemStack) InteractiveChat(com.loohp.interactivechat.InteractiveChat) List(java.util.List) ValueTrios(com.loohp.interactivechat.objectholders.ValueTrios) ClickEventAction(com.loohp.interactivechat.objectholders.CustomPlaceholder.ClickEventAction) CustomPlaceholderHoverEvent(com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderHoverEvent) ICPlayerFactory(com.loohp.interactivechat.objectholders.ICPlayerFactory) ByteStreams(com.google.common.io.ByteStreams) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) CustomPlaceholderClickEvent(com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderClickEvent) PlaceholderParser(com.loohp.interactivechat.utils.PlaceholderParser) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) CustomPlaceholderHoverEvent(com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderHoverEvent) ArrayList(java.util.ArrayList) CustomPlaceholderReplaceText(com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderReplaceText) CompletableFuture(java.util.concurrent.CompletableFuture) ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) CustomPlaceholder(com.loohp.interactivechat.objectholders.CustomPlaceholder) ArrayList(java.util.ArrayList) List(java.util.List) UUID(java.util.UUID) HashSet(java.util.HashSet) Player(org.bukkit.entity.Player) ParsePlayer(com.loohp.interactivechat.objectholders.CustomPlaceholder.ParsePlayer) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) ProxyCustomDataRecievedEvent(com.loohp.interactivechat.api.events.ProxyCustomDataRecievedEvent) SharedType(com.loohp.interactivechat.api.InteractiveChatAPI.SharedType) CustomPlaceholderClickEvent(com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderClickEvent) ByteArrayDataInput(com.google.common.io.ByteArrayDataInput) ByteBuffer(java.nio.ByteBuffer) TimeoutException(java.util.concurrent.TimeoutException) ParsePlayer(com.loohp.interactivechat.objectholders.CustomPlaceholder.ParsePlayer) BuiltInPlaceholder(com.loohp.interactivechat.objectholders.BuiltInPlaceholder) MentionPair(com.loohp.interactivechat.objectholders.MentionPair) ItemStack(org.bukkit.inventory.ItemStack) PlayerData(com.loohp.interactivechat.data.PlayerDataManager.PlayerData) Inventory(org.bukkit.inventory.Inventory) ValueTrios(com.loohp.interactivechat.objectholders.ValueTrios)

Example 23 with ICPlaceholder

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

the class BungeeMessageSender method resetAndForwardPlaceholderList.

@SuppressWarnings("deprecation")
public static boolean resetAndForwardPlaceholderList(long time, Collection<ICPlaceholder> placeholderList) throws Exception {
    ByteArrayDataOutput out = ByteStreams.newDataOutput();
    out.writeInt(placeholderList.size());
    for (ICPlaceholder placeholder : placeholderList) {
        boolean isBuiltIn = placeholder.isBuildIn();
        out.writeBoolean(isBuiltIn);
        if (isBuiltIn) {
            DataTypeIO.writeString(out, placeholder.getKeyword().pattern(), StandardCharsets.UTF_8);
            DataTypeIO.writeString(out, placeholder.getName(), StandardCharsets.UTF_8);
            DataTypeIO.writeString(out, placeholder.getDescription(), StandardCharsets.UTF_8);
            DataTypeIO.writeString(out, placeholder.getPermission(), StandardCharsets.UTF_8);
            out.writeLong(placeholder.getCooldown());
        } else {
            CustomPlaceholder customPlaceholder = (CustomPlaceholder) placeholder;
            out.writeInt(customPlaceholder.getPosition());
            out.writeByte(customPlaceholder.getParsePlayer().getOrder());
            DataTypeIO.writeString(out, customPlaceholder.getKeyword().pattern(), StandardCharsets.UTF_8);
            out.writeBoolean(customPlaceholder.getParseKeyword());
            out.writeLong(customPlaceholder.getCooldown());
            CustomPlaceholderHoverEvent hover = customPlaceholder.getHover();
            out.writeBoolean(hover.isEnabled());
            DataTypeIO.writeString(out, hover.getText(), StandardCharsets.UTF_8);
            CustomPlaceholderClickEvent click = customPlaceholder.getClick();
            out.writeBoolean(click.isEnabled());
            DataTypeIO.writeString(out, click.getAction() == null ? "" : click.getAction().name(), StandardCharsets.UTF_8);
            DataTypeIO.writeString(out, click.getValue(), StandardCharsets.UTF_8);
            CustomPlaceholderReplaceText replace = customPlaceholder.getReplace();
            out.writeBoolean(replace.isEnabled());
            DataTypeIO.writeString(out, replace.getReplaceText(), StandardCharsets.UTF_8);
            DataTypeIO.writeString(out, placeholder.getName(), StandardCharsets.UTF_8);
            DataTypeIO.writeString(out, placeholder.getDescription(), StandardCharsets.UTF_8);
        }
    }
    return forwardData(time, 0x0C, out.toByteArray());
}
Also used : ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) ByteArrayDataOutput(com.google.common.io.ByteArrayDataOutput) CustomPlaceholder(com.loohp.interactivechat.objectholders.CustomPlaceholder) CustomPlaceholderHoverEvent(com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderHoverEvent) CustomPlaceholderClickEvent(com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderClickEvent) CustomPlaceholderReplaceText(com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderReplaceText)

Example 24 with ICPlaceholder

use of com.loohp.interactivechat.objectholders.ICPlaceholder in project InteractiveChat-DiscordSRV-Addon by LOOHP.

the class OutboundToDiscordEvents method processGameMessage.

@SuppressWarnings("deprecation")
public Component processGameMessage(ICPlayer icSender, Component component) {
    boolean reserializer = DiscordSRV.config().getBoolean("Experiment_MCDiscordReserializer_ToDiscord");
    PlaceholderCooldownManager cooldownManager = InteractiveChatDiscordSrvAddon.plugin.placeholderCooldownManager;
    long now = cooldownManager.checkMessage(icSender.getUniqueId(), PlainTextComponentSerializer.plainText().serialize(component)).getTimeNow();
    GameMessagePreProcessEvent gameMessagePreProcessEvent = new GameMessagePreProcessEvent(icSender, component, false);
    Bukkit.getPluginManager().callEvent(gameMessagePreProcessEvent);
    if (gameMessagePreProcessEvent.isCancelled()) {
        return null;
    }
    component = ComponentFlattening.flatten(gameMessagePreProcessEvent.getComponent());
    String plain = InteractiveChatComponentSerializer.plainText().serialize(component);
    if (InteractiveChat.useItem && PlayerUtils.hasPermission(icSender.getUniqueId(), "interactivechat.module.item", true, 200)) {
        Debug.debug("onGameToDiscord processing item display");
        if (!cooldownManager.isPlaceholderOnCooldownAt(icSender.getUniqueId(), InteractiveChat.placeholderList.values().stream().filter(each -> each.getKeyword().equals(InteractiveChat.itemPlaceholder)).findFirst().get(), now)) {
            Matcher matcher = InteractiveChat.itemPlaceholder.matcher(plain);
            if (matcher.find()) {
                ItemStack item = PlayerUtils.getHeldItem(icSender);
                boolean isAir = item.getType().equals(Material.AIR);
                XMaterial xMaterial = XMaterialUtils.matchXMaterial(item);
                String itemStr = PlainTextComponentSerializer.plainText().serialize(ComponentStringUtils.convertTranslatables(ComponentModernizing.modernize(ItemStackUtils.getDisplayName(item)), InteractiveChatDiscordSrvAddon.plugin.resourceManager.getLanguageManager().getTranslateFunction().ofLanguage(InteractiveChatDiscordSrvAddon.plugin.language)));
                itemStr = ComponentStringUtils.stripColorAndConvertMagic(itemStr);
                int amount = item.getAmount();
                if (isAir) {
                    amount = 1;
                }
                String replaceText = PlaceholderParser.parse(icSender, (amount == 1 ? ComponentStringUtils.stripColorAndConvertMagic(InteractiveChat.itemSingularReplaceText) : ComponentStringUtils.stripColorAndConvertMagic(InteractiveChat.itemReplaceText).replace("{Amount}", String.valueOf(amount))).replace("{Item}", itemStr));
                if (reserializer) {
                    replaceText = MessageUtil.reserializeToDiscord(github.scarsz.discordsrv.dependencies.kyori.adventure.text.Component.text(replaceText));
                }
                AtomicBoolean replaced = new AtomicBoolean(false);
                Component replaceComponent = LegacyComponentSerializer.legacySection().deserialize(replaceText);
                component = ComponentReplacing.replace(component, InteractiveChat.itemPlaceholder.pattern(), true, (groups) -> {
                    replaced.set(true);
                    return replaceComponent;
                });
                if (replaced.get() && InteractiveChatDiscordSrvAddon.plugin.itemImage) {
                    int inventoryId = DATA_ID_PROVIDER.getNext();
                    int position = matcher.start();
                    String title = PlaceholderParser.parse(icSender, ComponentStringUtils.stripColorAndConvertMagic(InteractiveChat.itemTitle));
                    Inventory inv = null;
                    if (item.hasItemMeta() && item.getItemMeta() instanceof BlockStateMeta) {
                        BlockState bsm = ((BlockStateMeta) item.getItemMeta()).getBlockState();
                        if (bsm instanceof InventoryHolder) {
                            Inventory container = ((InventoryHolder) bsm).getInventory();
                            if (!container.isEmpty()) {
                                inv = Bukkit.createInventory(null, InventoryUtils.toMultipleOf9(container.getSize()));
                                for (int j = 0; j < container.getSize(); j++) {
                                    if (container.getItem(j) != null) {
                                        if (!container.getItem(j).getType().equals(Material.AIR)) {
                                            inv.setItem(j, container.getItem(j).clone());
                                        }
                                    }
                                }
                            }
                        }
                    }
                    GameMessageProcessItemEvent gameMessageProcessItemEvent = new GameMessageProcessItemEvent(icSender, title, component, false, inventoryId, item.clone(), inv);
                    Bukkit.getPluginManager().callEvent(gameMessageProcessItemEvent);
                    if (!gameMessageProcessItemEvent.isCancelled()) {
                        component = gameMessageProcessItemEvent.getComponent();
                        title = gameMessageProcessItemEvent.getTitle();
                        if (gameMessageProcessItemEvent.hasInventory()) {
                            DATA.put(inventoryId, new ImageDisplayData(icSender, position, title, ImageDisplayType.ITEM_CONTAINER, gameMessageProcessItemEvent.getItemStack().clone(), new TitledInventoryWrapper(ItemStackUtils.getDisplayName(item, null), gameMessageProcessItemEvent.getInventory())));
                        } else {
                            DATA.put(inventoryId, new ImageDisplayData(icSender, position, title, ImageDisplayType.ITEM, gameMessageProcessItemEvent.getItemStack().clone()));
                        }
                    }
                    component = component.append(Component.text("<ICD=" + inventoryId + ">"));
                }
            }
        }
    }
    if (InteractiveChat.useInventory && PlayerUtils.hasPermission(icSender.getUniqueId(), "interactivechat.module.inventory", true, 200)) {
        Debug.debug("onGameToDiscord processing inventory display");
        if (!cooldownManager.isPlaceholderOnCooldownAt(icSender.getUniqueId(), InteractiveChat.placeholderList.values().stream().filter(each -> each.getKeyword().equals(InteractiveChat.invPlaceholder)).findFirst().get(), now)) {
            Matcher matcher = InteractiveChat.invPlaceholder.matcher(plain);
            if (matcher.find()) {
                String replaceText = PlaceholderParser.parse(icSender, ComponentStringUtils.stripColorAndConvertMagic(InteractiveChat.invReplaceText));
                if (reserializer) {
                    replaceText = MessageUtil.reserializeToDiscord(github.scarsz.discordsrv.dependencies.kyori.adventure.text.Component.text(replaceText));
                }
                AtomicBoolean replaced = new AtomicBoolean(false);
                Component replaceComponent = LegacyComponentSerializer.legacySection().deserialize(replaceText);
                component = ComponentReplacing.replace(component, InteractiveChat.invPlaceholder.pattern(), true, (groups) -> {
                    replaced.set(true);
                    return replaceComponent;
                });
                if (replaced.get() && InteractiveChatDiscordSrvAddon.plugin.invImage) {
                    int inventoryId = DATA_ID_PROVIDER.getNext();
                    int position = matcher.start();
                    Inventory inv = Bukkit.createInventory(null, 45);
                    for (int j = 0; j < icSender.getInventory().getSize(); j++) {
                        if (icSender.getInventory().getItem(j) != null) {
                            if (!icSender.getInventory().getItem(j).getType().equals(Material.AIR)) {
                                inv.setItem(j, icSender.getInventory().getItem(j).clone());
                            }
                        }
                    }
                    String title = PlaceholderParser.parse(icSender, ComponentStringUtils.stripColorAndConvertMagic(InteractiveChat.invTitle));
                    GameMessageProcessPlayerInventoryEvent gameMessageProcessPlayerInventoryEvent = new GameMessageProcessPlayerInventoryEvent(icSender, title, component, false, inventoryId, inv);
                    Bukkit.getPluginManager().callEvent(gameMessageProcessPlayerInventoryEvent);
                    if (!gameMessageProcessPlayerInventoryEvent.isCancelled()) {
                        component = gameMessageProcessPlayerInventoryEvent.getComponent();
                        title = gameMessageProcessPlayerInventoryEvent.getTitle();
                        DATA.put(inventoryId, new ImageDisplayData(icSender, position, title, ImageDisplayType.INVENTORY, true, new TitledInventoryWrapper(Component.translatable(TranslationKeyUtils.getDefaultContainerTitle()), gameMessageProcessPlayerInventoryEvent.getInventory())));
                    }
                    component = component.append(Component.text("<ICD=" + inventoryId + ">"));
                }
            }
        }
    }
    if (InteractiveChat.useEnder && PlayerUtils.hasPermission(icSender.getUniqueId(), "interactivechat.module.enderchest", true, 200)) {
        Debug.debug("onGameToDiscord processing enderchest display");
        if (!cooldownManager.isPlaceholderOnCooldownAt(icSender.getUniqueId(), InteractiveChat.placeholderList.values().stream().filter(each -> each.getKeyword().equals(InteractiveChat.enderPlaceholder)).findFirst().get(), now)) {
            Matcher matcher = InteractiveChat.enderPlaceholder.matcher(plain);
            if (matcher.find()) {
                String replaceText = PlaceholderParser.parse(icSender, ComponentStringUtils.stripColorAndConvertMagic(InteractiveChat.enderReplaceText));
                if (reserializer) {
                    replaceText = MessageUtil.reserializeToDiscord(github.scarsz.discordsrv.dependencies.kyori.adventure.text.Component.text(replaceText));
                }
                AtomicBoolean replaced = new AtomicBoolean(false);
                Component replaceComponent = LegacyComponentSerializer.legacySection().deserialize(replaceText);
                component = ComponentReplacing.replace(component, InteractiveChat.enderPlaceholder.pattern(), true, (groups) -> {
                    replaced.set(true);
                    return replaceComponent;
                });
                if (replaced.get() && InteractiveChatDiscordSrvAddon.plugin.enderImage) {
                    int inventoryId = DATA_ID_PROVIDER.getNext();
                    int position = matcher.start();
                    Inventory inv = Bukkit.createInventory(null, InventoryUtils.toMultipleOf9(icSender.getEnderChest().getSize()));
                    for (int j = 0; j < icSender.getEnderChest().getSize(); j++) {
                        if (icSender.getEnderChest().getItem(j) != null) {
                            if (!icSender.getEnderChest().getItem(j).getType().equals(Material.AIR)) {
                                inv.setItem(j, icSender.getEnderChest().getItem(j).clone());
                            }
                        }
                    }
                    String title = PlaceholderParser.parse(icSender, ComponentStringUtils.stripColorAndConvertMagic(InteractiveChat.enderTitle));
                    GameMessageProcessInventoryEvent gameMessageProcessInventoryEvent = new GameMessageProcessInventoryEvent(icSender, title, component, false, inventoryId, inv);
                    Bukkit.getPluginManager().callEvent(gameMessageProcessInventoryEvent);
                    if (!gameMessageProcessInventoryEvent.isCancelled()) {
                        component = gameMessageProcessInventoryEvent.getComponent();
                        title = gameMessageProcessInventoryEvent.getTitle();
                        DATA.put(inventoryId, new ImageDisplayData(icSender, position, title, ImageDisplayType.ENDERCHEST, new TitledInventoryWrapper(Component.translatable(TranslationKeyUtils.getEnderChestContainerTitle()), gameMessageProcessInventoryEvent.getInventory())));
                    }
                    component = component.append(Component.text("<ICD=" + inventoryId + ">"));
                }
            }
        }
    }
    Debug.debug("onGameToDiscord processing custom placeholders");
    for (ICPlaceholder placeholder : InteractiveChatAPI.getICPlaceholderList()) {
        if (!placeholder.isBuildIn()) {
            CustomPlaceholder customP = (CustomPlaceholder) placeholder;
            if (!InteractiveChat.useCustomPlaceholderPermissions || (InteractiveChat.useCustomPlaceholderPermissions && PlayerUtils.hasPermission(icSender.getUniqueId(), customP.getPermission(), true, 200))) {
                boolean onCooldown = cooldownManager.isPlaceholderOnCooldownAt(icSender.getUniqueId(), customP, now);
                Matcher matcher = customP.getKeyword().matcher(plain);
                if (matcher.find() && !onCooldown) {
                    String replaceText;
                    if (customP.getReplace().isEnabled()) {
                        replaceText = ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(icSender, customP.getReplace().getReplaceText()));
                    } else {
                        replaceText = null;
                    }
                    List<Component> toAppend = new LinkedList<>();
                    Set<String> shown = new HashSet<>();
                    component = ComponentReplacing.replace(component, customP.getKeyword().pattern(), true, (result, matchedComponents) -> {
                        String replaceString = replaceText == null ? result.group() : CustomStringUtils.applyReplacementRegex(replaceText, result, 1);
                        if (!shown.contains(replaceString)) {
                            shown.add(replaceString);
                            int position = result.start();
                            if (InteractiveChatDiscordSrvAddon.plugin.hoverEnabled && !InteractiveChatDiscordSrvAddon.plugin.hoverIgnore.contains(customP.getPosition())) {
                                HoverClickDisplayData.Builder hoverClick = new HoverClickDisplayData.Builder().player(icSender).postion(position).color(DiscordDataRegistry.DISCORD_HOVER_COLOR).displayText(ChatColorUtils.stripColor(replaceString));
                                boolean usingHoverClick = false;
                                if (customP.getHover().isEnabled()) {
                                    usingHoverClick = true;
                                    String hoverText = ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(icSender, CustomStringUtils.applyReplacementRegex(customP.getHover().getText(), result, 1)));
                                    Color color = ColorUtils.getFirstColor(hoverText);
                                    hoverClick.hoverText(LegacyComponentSerializer.legacySection().deserialize(hoverText));
                                    if (color != null) {
                                        hoverClick.color(color);
                                    }
                                }
                                if (customP.getClick().isEnabled()) {
                                    usingHoverClick = true;
                                    hoverClick.clickAction(customP.getClick().getAction()).clickValue(CustomStringUtils.applyReplacementRegex(customP.getClick().getValue(), result, 1));
                                }
                                if (usingHoverClick) {
                                    int hoverId = DATA_ID_PROVIDER.getNext();
                                    DATA.put(hoverId, hoverClick.build());
                                    toAppend.add(Component.text("<ICD=" + hoverId + ">"));
                                }
                            }
                        }
                        return replaceText == null ? Component.empty().children(matchedComponents) : LegacyComponentSerializer.legacySection().deserialize(replaceString);
                    });
                    for (Component componentToAppend : toAppend) {
                        component = component.append(componentToAppend);
                    }
                }
            }
        }
    }
    if (InteractiveChat.t && WebData.getInstance() != null) {
        for (CustomPlaceholder customP : WebData.getInstance().getSpecialPlaceholders()) {
            boolean onCooldown = cooldownManager.isPlaceholderOnCooldownAt(icSender.getUniqueId(), customP, now);
            Matcher matcher = customP.getKeyword().matcher(plain);
            if (matcher.find() && !onCooldown) {
                String replaceText;
                if (customP.getReplace().isEnabled()) {
                    replaceText = ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(icSender, customP.getReplace().getReplaceText()));
                } else {
                    replaceText = null;
                }
                List<Component> toAppend = new LinkedList<>();
                Set<String> shown = new HashSet<>();
                component = ComponentReplacing.replace(component, customP.getKeyword().pattern(), true, (result, matchedComponents) -> {
                    String replaceString = replaceText == null ? result.group() : CustomStringUtils.applyReplacementRegex(replaceText, result, 1);
                    if (!shown.contains(replaceString)) {
                        shown.add(replaceString);
                        int position = result.start();
                        if (InteractiveChatDiscordSrvAddon.plugin.hoverEnabled && !InteractiveChatDiscordSrvAddon.plugin.hoverIgnore.contains(customP.getPosition())) {
                            HoverClickDisplayData.Builder hoverClick = new HoverClickDisplayData.Builder().player(icSender).postion(position).color(DiscordDataRegistry.DISCORD_HOVER_COLOR).displayText(ChatColorUtils.stripColor(replaceString));
                            boolean usingHoverClick = false;
                            if (customP.getHover().isEnabled()) {
                                usingHoverClick = true;
                                String hoverText = ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(icSender, CustomStringUtils.applyReplacementRegex(customP.getHover().getText(), result, 1)));
                                Color color = ColorUtils.getFirstColor(hoverText);
                                hoverClick.hoverText(LegacyComponentSerializer.legacySection().deserialize(hoverText));
                                if (color != null) {
                                    hoverClick.color(color);
                                }
                            }
                            if (customP.getClick().isEnabled()) {
                                usingHoverClick = true;
                                hoverClick.clickAction(customP.getClick().getAction()).clickValue(CustomStringUtils.applyReplacementRegex(customP.getClick().getValue(), result, 1));
                            }
                            if (usingHoverClick) {
                                int hoverId = DATA_ID_PROVIDER.getNext();
                                DATA.put(hoverId, hoverClick.build());
                                toAppend.add(Component.text("<ICD=" + hoverId + ">"));
                            }
                        }
                    }
                    return replaceText == null ? Component.empty().children(matchedComponents) : LegacyComponentSerializer.legacySection().deserialize(replaceString);
                });
                for (Component componentToAppend : toAppend) {
                    component = component.append(componentToAppend);
                }
            }
        }
    }
    DiscordSRV srv = InteractiveChatDiscordSrvAddon.discordsrv;
    if (InteractiveChatDiscordSrvAddon.plugin.translateMentions) {
        Debug.debug("onGameToDiscord processing mentions");
        List<MentionPair> distinctMentionPairs = new ArrayList<>();
        Set<UUID> processedReceivers = new HashSet<>();
        synchronized (InteractiveChat.mentionPair) {
            for (MentionPair pair : InteractiveChat.mentionPair) {
                if (!processedReceivers.contains(pair.getReciever())) {
                    distinctMentionPairs.add(pair);
                    processedReceivers.add(pair.getReciever());
                }
            }
        }
        for (MentionPair pair : distinctMentionPairs) {
            if (pair.getSender().equals(icSender.getUniqueId())) {
                UUID receiverUUID = pair.getReciever();
                Set<String> names = new HashSet<>();
                ICPlayer receiver = ICPlayerFactory.getICPlayer(receiverUUID);
                if (receiver != null) {
                    names.add(ChatColorUtils.stripColor(receiver.getName()));
                    List<String> list = InteractiveChatAPI.getNicknames(receiver.getUniqueId());
                    for (String name : list) {
                        names.add(ChatColorUtils.stripColor(name));
                    }
                }
                String userId = srv.getAccountLinkManager().getDiscordId(receiverUUID);
                if (userId != null) {
                    User user = srv.getJda().getUserById(userId);
                    if (user != null) {
                        String discordMention = user.getAsMention();
                        for (String name : names) {
                            component = ComponentReplacing.replace(component, CustomStringUtils.escapeMetaCharacters(Registry.MENTION_TAG_CONVERTER.getTagStyle(InteractiveChat.mentionPrefix + name)), true, LegacyComponentSerializer.legacySection().deserialize(discordMention));
                        }
                    }
                }
            }
        }
    }
    GameMessagePostProcessEvent gameMessagePostProcessEvent = new GameMessagePostProcessEvent(icSender, component, false);
    Bukkit.getPluginManager().callEvent(gameMessagePostProcessEvent);
    if (gameMessagePostProcessEvent.isCancelled()) {
        return null;
    }
    component = gameMessagePostProcessEvent.getComponent();
    return component;
}
Also used : GameMessageProcessPlayerInventoryEvent(com.loohp.interactivechatdiscordsrvaddon.api.events.GameMessageProcessPlayerInventoryEvent) Color(java.awt.Color) AchievementMessagePreProcessEvent(github.scarsz.discordsrv.api.events.AchievementMessagePreProcessEvent) InventoryUtils(com.loohp.interactivechat.utils.InventoryUtils) PlayerUtils(com.loohp.interactivechat.utils.PlayerUtils) HoverClickDisplayData(com.loohp.interactivechatdiscordsrvaddon.objectholders.HoverClickDisplayData) TextChannel(github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel) Event(org.bukkit.event.Event) DeathMessagePostProcessEvent(github.scarsz.discordsrv.api.events.DeathMessagePostProcessEvent) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) Matcher(java.util.regex.Matcher) AttachmentData(com.loohp.interactivechatdiscordsrvaddon.objectholders.AttachmentData) ImageDisplayData(com.loohp.interactivechatdiscordsrvaddon.objectholders.ImageDisplayData) AchievementUtils(com.loohp.interactivechatdiscordsrvaddon.utils.AchievementUtils) Map(java.util.Map) ComponentStringUtils(com.loohp.interactivechatdiscordsrvaddon.utils.ComponentStringUtils) Material(org.bukkit.Material) BlockStateMeta(org.bukkit.inventory.meta.BlockStateMeta) Debug(com.loohp.interactivechatdiscordsrvaddon.debug.Debug) DiscordToolTip(com.loohp.interactivechatdiscordsrvaddon.utils.DiscordItemStackUtils.DiscordToolTip) WebhookMessageBuilder(club.minnced.discord.webhook.send.WebhookMessageBuilder) Message(github.scarsz.discordsrv.dependencies.jda.api.entities.Message) Set(java.util.Set) ItemStack(org.bukkit.inventory.ItemStack) InteractiveChat(com.loohp.interactivechat.InteractiveChat) MessageEmbed(github.scarsz.discordsrv.dependencies.jda.api.entities.MessageEmbed) CustomStringUtils(com.loohp.interactivechat.utils.CustomStringUtils) GameMessageProcessItemEvent(com.loohp.interactivechatdiscordsrvaddon.api.events.GameMessageProcessItemEvent) ImageUtils(com.loohp.interactivechatdiscordsrvaddon.graphics.ImageUtils) WebhookClient(club.minnced.discord.webhook.WebhookClient) DiscordMessageContent(com.loohp.interactivechatdiscordsrvaddon.objectholders.DiscordMessageContent) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) AchievementMessagePostProcessEvent(github.scarsz.discordsrv.api.events.AchievementMessagePostProcessEvent) LanguageUtils(com.loohp.interactivechat.utils.LanguageUtils) VentureChatMessagePreProcessEvent(github.scarsz.discordsrv.api.events.VentureChatMessagePreProcessEvent) ItemStackUtils(com.loohp.interactivechat.utils.ItemStackUtils) LinkedHashSet(java.util.LinkedHashSet) ColorUtils(com.loohp.interactivechat.utils.ColorUtils) User(github.scarsz.discordsrv.dependencies.jda.api.entities.User) ComponentFlattening(com.loohp.interactivechat.utils.ComponentFlattening) Component(com.loohp.interactivechat.libs.net.kyori.adventure.text.Component) GameChatMessagePreProcessEvent(github.scarsz.discordsrv.api.events.GameChatMessagePreProcessEvent) WebhookUtil(github.scarsz.discordsrv.util.WebhookUtil) DiscordDescription(com.loohp.interactivechatdiscordsrvaddon.utils.DiscordItemStackUtils.DiscordDescription) AdvancementData(com.loohp.interactivechatdiscordsrvaddon.objectholders.AdvancementData) IOException(java.io.IOException) DiscordDisplayData(com.loohp.interactivechatdiscordsrvaddon.objectholders.DiscordDisplayData) InventoryHolder(org.bukkit.inventory.InventoryHolder) DiscordDataRegistry(com.loohp.interactivechatdiscordsrvaddon.registry.DiscordDataRegistry) EventPriority(org.bukkit.event.EventPriority) PlaceholderParser(com.loohp.interactivechat.utils.PlaceholderParser) LegacyComponentSerializer(com.loohp.interactivechat.libs.net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer) DiscordItemStackUtils(com.loohp.interactivechatdiscordsrvaddon.utils.DiscordItemStackUtils) ComponentReplacing(com.loohp.interactivechat.utils.ComponentReplacing) InteractiveChatAPI(com.loohp.interactivechat.api.InteractiveChatAPI) WebData(com.loohp.interactivechat.objectholders.WebData) ListenerAdapter(github.scarsz.discordsrv.dependencies.jda.api.hooks.ListenerAdapter) Player(org.bukkit.entity.Player) ImageDisplayType(com.loohp.interactivechatdiscordsrvaddon.objectholders.ImageDisplayType) Inventory(org.bukkit.inventory.Inventory) ComponentModernizing(com.loohp.interactivechat.utils.ComponentModernizing) EventHandler(org.bukkit.event.EventHandler) InteractiveChatComponentSerializer(com.loohp.interactivechat.utils.InteractiveChatComponentSerializer) MentionPair(com.loohp.interactivechat.objectholders.MentionPair) XMaterial(com.loohp.interactivechat.libs.com.cryptomorin.xseries.XMaterial) PlaceholderCooldownManager(com.loohp.interactivechat.objectholders.PlaceholderCooldownManager) Bukkit(org.bukkit.Bukkit) BufferedImage(java.awt.image.BufferedImage) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) XMaterialUtils(com.loohp.interactivechat.utils.XMaterialUtils) UUID(java.util.UUID) ChannelType(github.scarsz.discordsrv.dependencies.jda.api.entities.ChannelType) Subscribe(github.scarsz.discordsrv.api.Subscribe) ImageGeneration(com.loohp.interactivechatdiscordsrvaddon.graphics.ImageGeneration) PlayerDeathEvent(org.bukkit.event.entity.PlayerDeathEvent) List(java.util.List) ListenerPriority(github.scarsz.discordsrv.api.ListenerPriority) Entry(java.util.Map.Entry) GameMessagePostProcessEvent(com.loohp.interactivechatdiscordsrvaddon.api.events.GameMessagePostProcessEvent) DiscordGuildMessagePostProcessEvent(github.scarsz.discordsrv.api.events.DiscordGuildMessagePostProcessEvent) DeathMessageUtils(com.loohp.interactivechatdiscordsrvaddon.utils.DeathMessageUtils) MessageFormat(github.scarsz.discordsrv.objects.MessageFormat) ItemMeta(org.bukkit.inventory.meta.ItemMeta) CustomPlaceholder(com.loohp.interactivechat.objectholders.CustomPlaceholder) Registry(com.loohp.interactivechat.registry.Registry) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) GameMessagePreProcessEvent(com.loohp.interactivechatdiscordsrvaddon.api.events.GameMessagePreProcessEvent) InteractiveChatDiscordSrvAddon(com.loohp.interactivechatdiscordsrvaddon.InteractiveChatDiscordSrvAddon) MessageUtil(github.scarsz.discordsrv.util.MessageUtil) HashSet(java.util.HashSet) AdvancementType(com.loohp.interactivechatdiscordsrvaddon.objectholders.AdvancementType) PlainTextComponentSerializer(com.loohp.interactivechat.libs.net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer) DiscordSRV(github.scarsz.discordsrv.DiscordSRV) DiscordImageEvent(com.loohp.interactivechatdiscordsrvaddon.api.events.DiscordImageEvent) MessageAction(github.scarsz.discordsrv.dependencies.jda.api.requests.restaction.MessageAction) ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) LinkedList(java.util.LinkedList) Listener(org.bukkit.event.Listener) IDProvider(com.loohp.interactivechatdiscordsrvaddon.objectholders.IDProvider) DiscordGuildMessageSentEvent(github.scarsz.discordsrv.api.events.DiscordGuildMessageSentEvent) ResourceRegistry(com.loohp.interactivechatdiscordsrvaddon.registry.ResourceRegistry) BlockState(org.bukkit.block.BlockState) URLRequestUtils(com.loohp.interactivechatdiscordsrvaddon.utils.URLRequestUtils) MineverseChatPlayer(mineverse.Aust1n46.chat.api.MineverseChatPlayer) AdvancementUtils(com.loohp.interactivechatdiscordsrvaddon.utils.AdvancementUtils) TitledInventoryWrapper(com.loohp.interactivechatdiscordsrvaddon.wrappers.TitledInventoryWrapper) ICPlayerFactory(com.loohp.interactivechat.objectholders.ICPlayerFactory) ChatColorUtils(com.loohp.interactivechat.utils.ChatColorUtils) TranslationKeyUtils(com.loohp.interactivechatdiscordsrvaddon.utils.TranslationKeyUtils) Comparator(java.util.Comparator) ModelDisplayPosition(com.loohp.interactivechatdiscordsrvaddon.resources.models.ModelDisplay.ModelDisplayPosition) MessageReceivedEvent(github.scarsz.discordsrv.dependencies.jda.api.events.message.MessageReceivedEvent) Collections(java.util.Collections) GameMessageProcessInventoryEvent(com.loohp.interactivechatdiscordsrvaddon.api.events.GameMessageProcessInventoryEvent) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) User(github.scarsz.discordsrv.dependencies.jda.api.entities.User) Matcher(java.util.regex.Matcher) WebhookMessageBuilder(club.minnced.discord.webhook.send.WebhookMessageBuilder) ArrayList(java.util.ArrayList) GameMessageProcessPlayerInventoryEvent(com.loohp.interactivechatdiscordsrvaddon.api.events.GameMessageProcessPlayerInventoryEvent) ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) CustomPlaceholder(com.loohp.interactivechat.objectholders.CustomPlaceholder) GameMessageProcessInventoryEvent(com.loohp.interactivechatdiscordsrvaddon.api.events.GameMessageProcessInventoryEvent) Component(com.loohp.interactivechat.libs.net.kyori.adventure.text.Component) UUID(java.util.UUID) InventoryHolder(org.bukkit.inventory.InventoryHolder) LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) GameMessagePostProcessEvent(com.loohp.interactivechatdiscordsrvaddon.api.events.GameMessagePostProcessEvent) GameMessagePreProcessEvent(com.loohp.interactivechatdiscordsrvaddon.api.events.GameMessagePreProcessEvent) Color(java.awt.Color) DiscordSRV(github.scarsz.discordsrv.DiscordSRV) XMaterial(com.loohp.interactivechat.libs.com.cryptomorin.xseries.XMaterial) LinkedList(java.util.LinkedList) BlockStateMeta(org.bukkit.inventory.meta.BlockStateMeta) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TitledInventoryWrapper(com.loohp.interactivechatdiscordsrvaddon.wrappers.TitledInventoryWrapper) BlockState(org.bukkit.block.BlockState) GameMessageProcessItemEvent(com.loohp.interactivechatdiscordsrvaddon.api.events.GameMessageProcessItemEvent) MentionPair(com.loohp.interactivechat.objectholders.MentionPair) ItemStack(org.bukkit.inventory.ItemStack) PlaceholderCooldownManager(com.loohp.interactivechat.objectholders.PlaceholderCooldownManager) ImageDisplayData(com.loohp.interactivechatdiscordsrvaddon.objectholders.ImageDisplayData) Inventory(org.bukkit.inventory.Inventory) HoverClickDisplayData(com.loohp.interactivechatdiscordsrvaddon.objectholders.HoverClickDisplayData)

Example 25 with ICPlaceholder

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

the class InteractiveChatVelocity method onSwitch.

@Subscribe
public void onSwitch(ServerConnectedEvent event) {
    RegisteredServer to = event.getServer();
    Player player = event.getPlayer();
    UUID uuid = player.getUniqueId();
    if (!placeholderList.containsKey(to.getServerInfo().getName())) {
        try {
            PluginMessageSendingVelocity.requestPlaceholderList(to);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    try {
        PluginMessageSendingVelocity.sendPlayerListData();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    long universalTime = playerCooldownManager.getPlayerUniversalLastTimestamp(uuid);
    if (universalTime >= 0) {
        try {
            PluginMessageSendingVelocity.sendPlayerUniversalCooldown(to, uuid, universalTime);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    List<ICPlaceholder> placeholders = placeholderList.get(to.getServerInfo().getName());
    if (placeholders != null) {
        for (ICPlaceholder placeholder : placeholders) {
            long placeholderTime = playerCooldownManager.getPlayerPlaceholderLastTimestamp(uuid, placeholder.getInternalId());
            if (placeholderTime >= 0) {
                try {
                    PluginMessageSendingVelocity.sendPlayerPlaceholderCooldown(to, uuid, placeholder, placeholderTime);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    proxyServer.getScheduler().buildTask(plugin, () -> {
        try {
            PluginMessageSendingVelocity.sendDelayAndScheme();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }).schedule();
    proxyServer.getScheduler().buildTask(plugin, () -> {
        if (event.getPlayer().getUsername().equals("LOOHP") || event.getPlayer().getUsername().equals("AppLEskakE")) {
            sendMessage(event.getPlayer(), Component.text(TextColor.GOLD + "InteractiveChat (Velocity) " + getDescription().getVersion() + " is running!"));
        }
    }).delay(100, TimeUnit.MILLISECONDS).schedule();
}
Also used : ConnectedPlayer(com.velocitypowered.proxy.connection.client.ConnectedPlayer) ParsePlayer(com.loohp.interactivechat.objectholders.CustomPlaceholder.ParsePlayer) Player(com.velocitypowered.api.proxy.Player) ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) RegisteredServer(com.velocitypowered.api.proxy.server.RegisteredServer) IOException(java.io.IOException) UUID(java.util.UUID) Subscribe(com.velocitypowered.api.event.Subscribe)

Aggregations

ICPlaceholder (com.loohp.interactivechat.objectholders.ICPlaceholder)26 UUID (java.util.UUID)15 Pattern (java.util.regex.Pattern)13 IOException (java.io.IOException)12 Matcher (java.util.regex.Matcher)12 CustomPlaceholder (com.loohp.interactivechat.objectholders.CustomPlaceholder)11 ArrayList (java.util.ArrayList)11 List (java.util.List)10 ICPlayer (com.loohp.interactivechat.objectholders.ICPlayer)9 ParsePlayer (com.loohp.interactivechat.objectholders.CustomPlaceholder.ParsePlayer)8 Component (net.kyori.adventure.text.Component)8 Player (org.bukkit.entity.Player)8 InteractiveChat (com.loohp.interactivechat.InteractiveChat)7 ItemStack (org.bukkit.inventory.ItemStack)7 CustomPlaceholderClickEvent (com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderClickEvent)6 CustomPlaceholderHoverEvent (com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderHoverEvent)6 CustomPlaceholderReplaceText (com.loohp.interactivechat.objectholders.CustomPlaceholder.CustomPlaceholderReplaceText)6 BackendInteractiveChatData (com.loohp.interactivechat.proxy.objectholders.BackendInteractiveChatData)6 ChatColorUtils (com.loohp.interactivechat.utils.ChatColorUtils)6 Field (java.lang.reflect.Field)6