Search in sources :

Example 21 with ICPlayer

use of com.loohp.interactivechat.objectholders.ICPlayer 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 22 with ICPlayer

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

the class DiscordCommands method onSlashCommand.

@Override
public void onSlashCommand(SlashCommandEvent event) {
    if (!(event.getChannel() instanceof TextChannel)) {
        return;
    }
    TextChannel channel = (TextChannel) event.getChannel();
    String label = event.getName();
    if (InteractiveChatDiscordSrvAddon.plugin.resourcepackCommandEnabled && label.equalsIgnoreCase(RESOURCEPACK_LABEL)) {
        if (InteractiveChatDiscordSrvAddon.plugin.resourcepackCommandIsMainServer) {
            event.deferReply().setEphemeral(true).queue();
            List<MessageEmbed> messageEmbeds = new ArrayList<>();
            Map<String, byte[]> attachments = new HashMap<>();
            int i = 0;
            for (ResourcePackInfo packInfo : InteractiveChatDiscordSrvAddon.plugin.resourceManager.getResourcePackInfo()) {
                i++;
                String packName = packInfo.getName();
                Component description = packInfo.getDescription();
                EmbedBuilder builder = new EmbedBuilder().setAuthor(packName).setThumbnail("attachment://" + i + ".png");
                if (packInfo.getStatus()) {
                    builder.setDescription(PlainTextComponentSerializer.plainText().serialize(description));
                    ChatColor firstColor = ChatColorUtils.getColor(LegacyComponentSerializer.builder().useUnusualXRepeatedCharacterHexFormat().character(ChatColorUtils.COLOR_CHAR).build().serialize(description));
                    Color color = ColorUtils.getColor(firstColor);
                    if (color == null) {
                        color = new Color(0xAAAAAA);
                    } else if (color.equals(Color.WHITE)) {
                        color = new Color(0xFFFFFE);
                    }
                    builder.setColor(color);
                    if (packInfo.comparePackFormat() > 0) {
                        builder.setFooter(LanguageUtils.getTranslation(TranslationKeyUtils.getNewIncompatiblePack(), InteractiveChatDiscordSrvAddon.plugin.language));
                    } else if (packInfo.comparePackFormat() < 0) {
                        builder.setFooter(LanguageUtils.getTranslation(TranslationKeyUtils.getOldIncompatiblePack(), InteractiveChatDiscordSrvAddon.plugin.language));
                    }
                } else {
                    builder.setColor(0xFF0000).setDescription(packInfo.getRejectedReason());
                }
                messageEmbeds.add(builder.build());
                try {
                    attachments.put(i + ".png", ImageUtils.toArray(ImageUtils.resizeImageAbs(packInfo.getIcon(), 128, 128)));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            WebhookMessageUpdateAction<Message> action = event.getHook().setEphemeral(true).editOriginal("**" + LanguageUtils.getTranslation(TranslationKeyUtils.getServerResourcePack(), InteractiveChatDiscordSrvAddon.plugin.language) + "**").setEmbeds(messageEmbeds);
            for (Entry<String, byte[]> entry : attachments.entrySet()) {
                action = action.addFile(entry.getValue(), entry.getKey());
            }
            action.queue();
        }
    } else if (InteractiveChatDiscordSrvAddon.plugin.playerlistCommandEnabled && label.equalsIgnoreCase(PLAYERLIST_LABEL)) {
        String minecraftChannel = discordsrv.getChannels().entrySet().stream().filter(entry -> channel.getId().equals(entry.getValue())).map(Map.Entry::getKey).findFirst().orElse(null);
        if (minecraftChannel == null) {
            if (InteractiveChatDiscordSrvAddon.plugin.respondToCommandsInInvalidChannels && InteractiveChatDiscordSrvAddon.plugin.playerlistCommandIsMainServer) {
                event.reply(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.invalidDiscordChannel)).setEphemeral(true).queue();
            }
            return;
        }
        AtomicBoolean deleted = new AtomicBoolean(false);
        event.deferReply().queue(hook -> {
            if (InteractiveChatDiscordSrvAddon.plugin.playerlistCommandDeleteAfter > 0) {
                Bukkit.getScheduler().runTaskLaterAsynchronously(InteractiveChatDiscordSrvAddon.plugin, () -> {
                    if (!deleted.get()) {
                        hook.deleteOriginal().queue();
                    }
                }, InteractiveChatDiscordSrvAddon.plugin.playerlistCommandDeleteAfter * 20L);
            }
        });
        Map<OfflinePlayer, Integer> players;
        if (InteractiveChat.bungeecordMode && InteractiveChatDiscordSrvAddon.plugin.playerlistCommandBungeecord && !Bukkit.getOnlinePlayers().isEmpty()) {
            try {
                List<ValueTrios<UUID, String, Integer>> bungeePlayers = InteractiveChatAPI.getBungeecordPlayerList().get();
                players = new LinkedHashMap<>(bungeePlayers.size());
                for (ValueTrios<UUID, String, Integer> playerinfo : bungeePlayers) {
                    if (!VanishUtils.isVanished(playerinfo.getFirst())) {
                        players.put(Bukkit.getOfflinePlayer(playerinfo.getFirst()), playerinfo.getThird());
                    }
                }
            } catch (InterruptedException | ExecutionException e) {
                e.printStackTrace();
                event.getHook().editOriginal(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.unableToRetrieveData) + " (-1)").queue();
                return;
            }
        } else {
            players = Bukkit.getOnlinePlayers().stream().filter(each -> !VanishUtils.isVanished(each.getUniqueId())).collect(Collectors.toMap(each -> each, each -> PlayerUtils.getPing(each)));
        }
        if (players.isEmpty()) {
            event.getHook().editOriginal(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.playerlistCommandEmptyServer)).queue();
        } else {
            int errorCode = -2;
            try {
                String[] groups = getGroups();
                List<ValueTrios<UUID, Component, Integer>> player = new ArrayList<>();
                Map<UUID, Integer> playerGroups = new HashMap<>();
                for (Entry<OfflinePlayer, Integer> entry : players.entrySet()) {
                    OfflinePlayer bukkitOfflinePlayer = entry.getKey();
                    @SuppressWarnings("deprecation") OfflineICPlayer offlinePlayer = ICPlayerFactory.getUnsafe().getOfflineICPPlayerWithoutInitialization(bukkitOfflinePlayer.getUniqueId());
                    playerGroups.put(offlinePlayer.getUniqueId(), getPlayerGroupOrder(groups, bukkitOfflinePlayer));
                    player.add(new ValueTrios<>(offlinePlayer.getUniqueId(), LegacyComponentSerializer.legacySection().deserialize(ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(offlinePlayer, InteractiveChatDiscordSrvAddon.plugin.playerlistCommandPlayerFormat))), entry.getValue()));
                }
                errorCode--;
                player.sort(Comparator.comparing(each -> playerGroups.getOrDefault(((ValueTrios<UUID, Component, Integer>) each).getFirst(), Integer.MIN_VALUE)).thenComparing(each -> ((ValueTrios<UUID, Component, Integer>) each).getFirst()));
                errorCode--;
                @SuppressWarnings("deprecation") OfflineICPlayer firstPlayer = ICPlayerFactory.getUnsafe().getOfflineICPPlayerWithoutInitialization(players.keySet().iterator().next().getUniqueId());
                List<Component> header = new ArrayList<>();
                if (!InteractiveChatDiscordSrvAddon.plugin.playerlistCommandHeader.isEmpty()) {
                    header = ComponentStyling.splitAtLineBreaks(LegacyComponentSerializer.legacySection().deserialize(ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(firstPlayer, InteractiveChatDiscordSrvAddon.plugin.playerlistCommandHeader.replace("{OnlinePlayers}", players.size() + "")))));
                }
                errorCode--;
                List<Component> footer = new ArrayList<>();
                if (!InteractiveChatDiscordSrvAddon.plugin.playerlistCommandFooter.isEmpty()) {
                    footer = ComponentStyling.splitAtLineBreaks(LegacyComponentSerializer.legacySection().deserialize(ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(firstPlayer, InteractiveChatDiscordSrvAddon.plugin.playerlistCommandFooter.replace("{OnlinePlayers}", players.size() + "")))));
                }
                errorCode--;
                BufferedImage image = ImageGeneration.getTabListImage(header, footer, player, InteractiveChatDiscordSrvAddon.plugin.playerlistCommandAvatar, InteractiveChatDiscordSrvAddon.plugin.playerlistCommandPing);
                errorCode--;
                byte[] data = ImageUtils.toArray(image);
                errorCode--;
                event.getHook().editOriginalEmbeds(new EmbedBuilder().setImage("attachment://Tablist.png").setColor(InteractiveChatDiscordSrvAddon.plugin.playerlistCommandColor).build()).addFile(data, "Tablist.png").queue(success -> {
                    if (InteractiveChatDiscordSrvAddon.plugin.playerlistCommandDeleteAfter > 0) {
                        deleted.set(true);
                        success.delete().queueAfter(InteractiveChatDiscordSrvAddon.plugin.playerlistCommandDeleteAfter, TimeUnit.SECONDS);
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
                event.getHook().editOriginal(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.unableToRetrieveData) + " (" + errorCode + ")").queue();
                return;
            }
        }
    } else if (InteractiveChatDiscordSrvAddon.plugin.shareItemCommandEnabled && (label.equalsIgnoreCase(ITEM_LABEL) || label.equalsIgnoreCase(ITEM_OTHER_LABEL))) {
        String minecraftChannel = discordsrv.getChannels().entrySet().stream().filter(entry -> channel.getId().equals(entry.getValue())).map(Map.Entry::getKey).findFirst().orElse(null);
        if (minecraftChannel == null) {
            if (InteractiveChatDiscordSrvAddon.plugin.respondToCommandsInInvalidChannels && InteractiveChatDiscordSrvAddon.plugin.shareInvCommandIsMainServer) {
                event.reply(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.invalidDiscordChannel)).setEphemeral(true).queue();
            }
            return;
        }
        String discordUserId = event.getUser().getId();
        List<OptionMapping> options = event.getOptionsByType(OptionType.USER);
        if (options.size() > 0) {
            discordUserId = options.get(0).getAsUser().getId();
        }
        UUID uuid = discordsrv.getAccountLinkManager().getUuid(discordUserId);
        if (uuid == null) {
            if (InteractiveChatDiscordSrvAddon.plugin.shareItemCommandIsMainServer) {
                event.reply(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.accountNotLinked)).setEphemeral(true).queue();
            }
            return;
        }
        int errorCode = -1;
        try {
            OfflineICPlayer offlineICPlayer = ICPlayerFactory.getOfflineICPlayer(uuid);
            if (offlineICPlayer == null) {
                if (InteractiveChatDiscordSrvAddon.plugin.shareItemCommandIsMainServer) {
                    event.reply(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.unableToRetrieveData) + " (" + errorCode + ")").setEphemeral(true).queue();
                }
                return;
            }
            errorCode--;
            if (InteractiveChatDiscordSrvAddon.plugin.shareItemCommandIsMainServer) {
                event.deferReply().queue();
            }
            errorCode--;
            ICPlayer icplayer = offlineICPlayer.getPlayer();
            if (InteractiveChat.bungeecordMode && icplayer != null) {
                if (icplayer.isLocal()) {
                    ItemStack[] equipment;
                    if (InteractiveChat.version.isOld()) {
                        // noinspection deprecation
                        equipment = new ItemStack[] { icplayer.getEquipment().getHelmet(), icplayer.getEquipment().getChestplate(), icplayer.getEquipment().getLeggings(), icplayer.getEquipment().getBoots(), icplayer.getEquipment().getItemInHand() };
                    } else {
                        equipment = new ItemStack[] { icplayer.getEquipment().getHelmet(), icplayer.getEquipment().getChestplate(), icplayer.getEquipment().getLeggings(), icplayer.getEquipment().getBoots(), icplayer.getEquipment().getItemInMainHand(), icplayer.getEquipment().getItemInOffHand() };
                    }
                    try {
                        BungeeMessageSender.forwardEquipment(System.currentTimeMillis(), icplayer.getUniqueId(), icplayer.isRightHanded(), icplayer.getSelectedSlot(), icplayer.getExperienceLevel(), equipment);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                } else {
                    TimeUnit.MILLISECONDS.sleep(InteractiveChat.remoteDelay);
                }
            }
            errorCode--;
            ItemStack itemStack = resolveItemStack(event, offlineICPlayer);
            if (itemStack == null) {
                itemStack = new ItemStack(Material.AIR);
            }
            errorCode--;
            BufferedImage itemImage = ImageGeneration.getItemStackImage(itemStack, offlineICPlayer, true);
            errorCode--;
            String title = ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.shareItemCommandTitle.replace("{Player}", offlineICPlayer.getName()));
            errorCode--;
            Component itemTag = ItemDisplay.createItemDisplay(offlineICPlayer, itemStack, title, true, null);
            Component resolvedItemTag = ComponentStringUtils.convertTranslatables(ComponentModernizing.modernize(itemTag), InteractiveChatDiscordSrvAddon.plugin.resourceManager.getLanguageManager().getTranslateFunction().ofLanguage(InteractiveChatDiscordSrvAddon.plugin.language));
            Component component = LegacyComponentSerializer.legacySection().deserialize(InteractiveChatDiscordSrvAddon.plugin.shareItemCommandInGameMessageText.replace("{Player}", offlineICPlayer.getName())).replaceText(TextReplacementConfig.builder().matchLiteral("{ItemTag}").replacement(itemTag).build());
            Component resolvedComponent = LegacyComponentSerializer.legacySection().deserialize(InteractiveChatDiscordSrvAddon.plugin.shareItemCommandInGameMessageText.replace("{Player}", offlineICPlayer.getName())).replaceText(TextReplacementConfig.builder().matchLiteral("{ItemTag}").replacement(resolvedItemTag).build());
            errorCode--;
            String key = "<DiscordShare=" + UUID.randomUUID() + ">";
            components.put(key, component);
            Bukkit.getScheduler().runTaskLater(InteractiveChatDiscordSrvAddon.plugin, () -> components.remove(key), 100);
            errorCode--;
            discordsrv.broadcastMessageToMinecraftServer(minecraftChannel, ComponentStringUtils.toDiscordSRVComponent(Component.text(key)), event.getUser());
            if (InteractiveChatDiscordSrvAddon.plugin.shareItemCommandIsMainServer) {
                errorCode--;
                Player bukkitPlayer = icplayer == null || !icplayer.isLocal() ? null : icplayer.getLocalPlayer();
                DiscordDescription description = DiscordItemStackUtils.getDiscordDescription(itemStack, bukkitPlayer);
                errorCode--;
                Color color = DiscordItemStackUtils.getDiscordColor(itemStack);
                if (color == null || color.equals(Color.WHITE)) {
                    color = new Color(0xFFFFFE);
                }
                EmbedBuilder embedBuilder = new EmbedBuilder().setAuthor(description.getName(), null, "attachment://Item.png").setColor(color);
                WebhookMessageUpdateAction<Message> action = event.getHook().editOriginal(PlainTextComponentSerializer.plainText().serialize(resolvedComponent));
                errorCode--;
                byte[] data = ImageUtils.toArray(itemImage);
                action.addFile(data, "Item.png");
                errorCode--;
                if (InteractiveChatDiscordSrvAddon.plugin.itemUseTooltipImage) {
                    DiscordToolTip discordToolTip = DiscordItemStackUtils.getToolTip(itemStack, bukkitPlayer);
                    if (!discordToolTip.isBaseItem() || InteractiveChatDiscordSrvAddon.plugin.itemUseTooltipImageOnBaseItem) {
                        BufferedImage tooltip = ImageGeneration.getToolTipImage(discordToolTip.getComponents());
                        byte[] tooltipData = ImageUtils.toArray(tooltip);
                        action.addFile(tooltipData, "ToolTip.png");
                        embedBuilder.setImage("attachment://ToolTip.png");
                    } else {
                        embedBuilder.setDescription(description.getDescription().orElse(null));
                    }
                } else {
                    embedBuilder.setDescription(description.getDescription().orElse(null));
                }
                errorCode--;
                action.setEmbeds(embedBuilder.build()).queue();
            }
        } catch (Exception e) {
            e.printStackTrace();
            event.getHook().editOriginal(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.unableToRetrieveData) + " (" + errorCode + ")").queue();
            return;
        }
    } else if (InteractiveChatDiscordSrvAddon.plugin.shareInvCommandEnabled && (label.equalsIgnoreCase(INVENTORY_LABEL) || label.equalsIgnoreCase(INVENTORY_OTHER_LABEL))) {
        String minecraftChannel = discordsrv.getChannels().entrySet().stream().filter(entry -> channel.getId().equals(entry.getValue())).map(Map.Entry::getKey).findFirst().orElse(null);
        if (minecraftChannel == null) {
            if (InteractiveChatDiscordSrvAddon.plugin.respondToCommandsInInvalidChannels && InteractiveChatDiscordSrvAddon.plugin.shareInvCommandIsMainServer) {
                event.reply(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.invalidDiscordChannel)).setEphemeral(true).queue();
            }
            return;
        }
        String discordUserId = event.getUser().getId();
        List<OptionMapping> options = event.getOptionsByType(OptionType.USER);
        if (options.size() > 0) {
            discordUserId = options.get(0).getAsUser().getId();
        }
        UUID uuid = discordsrv.getAccountLinkManager().getUuid(discordUserId);
        if (uuid == null) {
            if (InteractiveChatDiscordSrvAddon.plugin.shareInvCommandIsMainServer) {
                event.reply(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.accountNotLinked)).setEphemeral(true).queue();
            }
            return;
        }
        int errorCode = -1;
        try {
            OfflineICPlayer offlineICPlayer = ICPlayerFactory.getOfflineICPlayer(uuid);
            if (offlineICPlayer == null) {
                if (InteractiveChatDiscordSrvAddon.plugin.shareInvCommandIsMainServer) {
                    event.reply(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.unableToRetrieveData) + " (" + errorCode + ")").setEphemeral(true).queue();
                }
                return;
            }
            errorCode--;
            if (InteractiveChatDiscordSrvAddon.plugin.shareInvCommandIsMainServer) {
                event.deferReply().queue();
            }
            errorCode--;
            ICPlayer icplayer = offlineICPlayer.getPlayer();
            if (InteractiveChat.bungeecordMode && icplayer != null) {
                if (icplayer.isLocal()) {
                    BungeeMessageSender.forwardInventory(System.currentTimeMillis(), uuid, icplayer.isRightHanded(), icplayer.getSelectedSlot(), icplayer.getExperienceLevel(), null, icplayer.getInventory());
                } else {
                    TimeUnit.MILLISECONDS.sleep(InteractiveChat.remoteDelay);
                }
            }
            errorCode--;
            BufferedImage image = InteractiveChatDiscordSrvAddon.plugin.usePlayerInvView ? ImageGeneration.getPlayerInventoryImage(offlineICPlayer.getInventory(), offlineICPlayer) : ImageGeneration.getInventoryImage(offlineICPlayer.getInventory(), Component.translatable(TranslationKeyUtils.getDefaultContainerTitle()), offlineICPlayer);
            errorCode--;
            Component component = LegacyComponentSerializer.legacySection().deserialize(InteractiveChatDiscordSrvAddon.plugin.shareInvCommandInGameMessageText.replace("{Player}", offlineICPlayer.getName()));
            errorCode--;
            String title = ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.shareInvCommandTitle.replace("{Player}", offlineICPlayer.getName()));
            errorCode--;
            String sha1 = HashUtils.createSha1(true, offlineICPlayer.getSelectedSlot(), offlineICPlayer.getExperienceLevel(), title, offlineICPlayer.getInventory());
            errorCode--;
            layout0(offlineICPlayer, sha1, title);
            errorCode--;
            layout1(offlineICPlayer, sha1, title);
            errorCode--;
            component = component.hoverEvent(HoverEvent.showText(LegacyComponentSerializer.legacySection().deserialize(InteractiveChatDiscordSrvAddon.plugin.shareInvCommandInGameMessageHover)));
            component = component.clickEvent(ClickEvent.runCommand("/interactivechat viewinv " + sha1));
            errorCode--;
            String key = "<DiscordShare=" + UUID.randomUUID() + ">";
            components.put(key, component);
            Bukkit.getScheduler().runTaskLater(InteractiveChatDiscordSrvAddon.plugin, () -> components.remove(key), 100);
            errorCode--;
            discordsrv.broadcastMessageToMinecraftServer(minecraftChannel, ComponentStringUtils.toDiscordSRVComponent(Component.text(key)), event.getUser());
            if (InteractiveChatDiscordSrvAddon.plugin.shareInvCommandIsMainServer) {
                errorCode--;
                EmbedBuilder embedBuilder = new EmbedBuilder().setAuthor(title).setImage("attachment://Inventory.png").setColor(InteractiveChatDiscordSrvAddon.plugin.invColor);
                WebhookMessageUpdateAction<Message> action = event.getHook().editOriginal(PlainTextComponentSerializer.plainText().serialize(component));
                errorCode--;
                byte[] data = ImageUtils.toArray(image);
                action.addFile(data, "Inventory.png");
                errorCode--;
                if (InteractiveChatDiscordSrvAddon.plugin.invShowLevel) {
                    int level = offlineICPlayer.getExperienceLevel();
                    byte[] bottleData = ImageUtils.toArray(InteractiveChatDiscordSrvAddon.plugin.modelRenderer.render(32, 32, InteractiveChatDiscordSrvAddon.plugin.resourceManager, InteractiveChat.version.isOld(), "minecraft:item/experience_bottle", ModelDisplayPosition.GUI, false).getImage());
                    embedBuilder.setFooter(LanguageUtils.getTranslation(TranslationKeyUtils.getLevelTranslation(level), InteractiveChatDiscordSrvAddon.plugin.language).replaceFirst("%s|%d", level + ""), "attachment://Level.png");
                    action.addFile(bottleData, "Level.png");
                }
                errorCode--;
                action.setEmbeds(embedBuilder.build()).queue();
            }
        } catch (Exception e) {
            e.printStackTrace();
            event.getHook().editOriginal(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.unableToRetrieveData) + " (" + errorCode + ")").queue();
            return;
        }
    } else if (InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandEnabled && (label.equals(ENDERCHEST_LABEL) || label.equals(ENDERCHEST_OTHER_LABEL))) {
        String minecraftChannel = discordsrv.getChannels().entrySet().stream().filter(entry -> channel.getId().equals(entry.getValue())).map(Map.Entry::getKey).findFirst().orElse(null);
        if (minecraftChannel == null) {
            if (InteractiveChatDiscordSrvAddon.plugin.respondToCommandsInInvalidChannels && InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandIsMainServer) {
                event.reply(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.invalidDiscordChannel)).setEphemeral(true).queue();
            }
            return;
        }
        String discordUserId = event.getUser().getId();
        List<OptionMapping> options = event.getOptionsByType(OptionType.USER);
        if (options.size() > 0) {
            discordUserId = options.get(0).getAsUser().getId();
        }
        UUID uuid = discordsrv.getAccountLinkManager().getUuid(discordUserId);
        if (uuid == null) {
            if (InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandIsMainServer) {
                event.reply(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.accountNotLinked)).setEphemeral(true).queue();
            }
            return;
        }
        int errorCode = -1;
        try {
            OfflineICPlayer offlineICPlayer = ICPlayerFactory.getOfflineICPlayer(uuid);
            if (offlineICPlayer == null) {
                if (InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandIsMainServer) {
                    event.reply(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.unableToRetrieveData) + " (" + errorCode + ")").setEphemeral(true).queue();
                }
                return;
            }
            errorCode--;
            if (InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandIsMainServer) {
                event.deferReply().queue();
            }
            errorCode--;
            ICPlayer icplayer = offlineICPlayer.getPlayer();
            if (InteractiveChat.bungeecordMode && icplayer != null) {
                if (icplayer.isLocal()) {
                    BungeeMessageSender.forwardEnderchest(System.currentTimeMillis(), uuid, icplayer.isRightHanded(), icplayer.getSelectedSlot(), icplayer.getExperienceLevel(), null, icplayer.getEnderChest());
                } else {
                    TimeUnit.MILLISECONDS.sleep(InteractiveChat.remoteDelay);
                }
            }
            errorCode--;
            BufferedImage image = ImageGeneration.getInventoryImage(offlineICPlayer.getEnderChest(), Component.translatable(TranslationKeyUtils.getEnderChestContainerTitle()), offlineICPlayer);
            errorCode--;
            Component component = LegacyComponentSerializer.legacySection().deserialize(InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandInGameMessageText.replace("{Player}", offlineICPlayer.getName()));
            errorCode--;
            String title = ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandTitle.replace("{Player}", offlineICPlayer.getName()));
            errorCode--;
            String sha1 = HashUtils.createSha1(true, offlineICPlayer.getSelectedSlot(), offlineICPlayer.getExperienceLevel(), title, offlineICPlayer.getEnderChest());
            errorCode--;
            ender(offlineICPlayer, sha1, title);
            errorCode--;
            component = component.hoverEvent(HoverEvent.showText(LegacyComponentSerializer.legacySection().deserialize(InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandInGameMessageHover)));
            component = component.clickEvent(ClickEvent.runCommand("/interactivechat viewender " + sha1));
            errorCode--;
            String key = "<DiscordShare=" + UUID.randomUUID() + ">";
            components.put(key, component);
            Bukkit.getScheduler().runTaskLater(InteractiveChatDiscordSrvAddon.plugin, () -> components.remove(key), 100);
            errorCode--;
            discordsrv.broadcastMessageToMinecraftServer(minecraftChannel, ComponentStringUtils.toDiscordSRVComponent(Component.text(key)), event.getUser());
            if (InteractiveChatDiscordSrvAddon.plugin.shareEnderCommandIsMainServer) {
                errorCode--;
                byte[] data = ImageUtils.toArray(image);
                errorCode--;
                event.getHook().editOriginal(PlainTextComponentSerializer.plainText().serialize(component)).setEmbeds(new EmbedBuilder().setAuthor(title).setImage("attachment://Inventory.png").setColor(InteractiveChatDiscordSrvAddon.plugin.enderColor).build()).addFile(data, "Inventory.png").queue();
            }
        } catch (Exception e) {
            e.printStackTrace();
            event.getHook().editOriginal(ChatColorUtils.stripColor(InteractiveChatDiscordSrvAddon.plugin.unableToRetrieveData) + " (" + errorCode + ")").queue();
            return;
        }
    }
}
Also used : Color(java.awt.Color) Arrays(java.util.Arrays) InventoryUtils(com.loohp.interactivechat.utils.InventoryUtils) PlayerUtils(com.loohp.interactivechat.utils.PlayerUtils) ResourcePackInfo(com.loohp.interactivechatdiscordsrvaddon.resources.ResourcePackInfo) TextChannel(github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) Map(java.util.Map) ComponentStringUtils(com.loohp.interactivechatdiscordsrvaddon.utils.ComponentStringUtils) Material(org.bukkit.Material) EquipmentSlot(org.bukkit.inventory.EquipmentSlot) DiscordToolTip(com.loohp.interactivechatdiscordsrvaddon.utils.DiscordItemStackUtils.DiscordToolTip) Message(github.scarsz.discordsrv.dependencies.jda.api.entities.Message) Guild(github.scarsz.discordsrv.dependencies.jda.api.entities.Guild) Set(java.util.Set) OfflinePlayer(org.bukkit.OfflinePlayer) 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) OptionData(github.scarsz.discordsrv.dependencies.jda.api.interactions.commands.build.OptionData) Chat(net.milkbowl.vault.chat.Chat) EmbedBuilder(github.scarsz.discordsrv.dependencies.jda.api.EmbedBuilder) ImageUtils(com.loohp.interactivechatdiscordsrvaddon.graphics.ImageUtils) BungeeMessageSender(com.loohp.interactivechat.bungeemessaging.BungeeMessageSender) MCVersion(com.loohp.interactivechat.utils.MCVersion) HoverEvent(com.loohp.interactivechat.libs.net.kyori.adventure.text.event.HoverEvent) PostPacketComponentProcessEvent(com.loohp.interactivechat.api.events.PostPacketComponentProcessEvent) ArrayList(java.util.ArrayList) LinkedHashMap(java.util.LinkedHashMap) LanguageUtils(com.loohp.interactivechat.utils.LanguageUtils) ColorUtils(com.loohp.interactivechat.utils.ColorUtils) InteractiveChatDiscordSRVConfigReloadEvent(com.loohp.interactivechatdiscordsrvaddon.api.events.InteractiveChatDiscordSRVConfigReloadEvent) OptionType(github.scarsz.discordsrv.dependencies.jda.api.interactions.commands.OptionType) Component(com.loohp.interactivechat.libs.net.kyori.adventure.text.Component) DiscordDescription(com.loohp.interactivechatdiscordsrvaddon.utils.DiscordItemStackUtils.DiscordDescription) IOException(java.io.IOException) WebhookMessageUpdateAction(github.scarsz.discordsrv.dependencies.jda.api.requests.restaction.WebhookMessageUpdateAction) Field(java.lang.reflect.Field) ExecutionException(java.util.concurrent.ExecutionException) ValueTrios(com.loohp.interactivechat.objectholders.ValueTrios) TextReplacementConfig(com.loohp.interactivechat.libs.net.kyori.adventure.text.TextReplacementConfig) PlaceholderParser(com.loohp.interactivechat.utils.PlaceholderParser) RegisteredServiceProvider(org.bukkit.plugin.RegisteredServiceProvider) LegacyComponentSerializer(com.loohp.interactivechat.libs.net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer) DiscordItemStackUtils(com.loohp.interactivechatdiscordsrvaddon.utils.DiscordItemStackUtils) VanishUtils(com.loohp.interactivechat.utils.VanishUtils) ComponentReplacing(com.loohp.interactivechat.utils.ComponentReplacing) InteractiveChatAPI(com.loohp.interactivechat.api.InteractiveChatAPI) ListenerAdapter(github.scarsz.discordsrv.dependencies.jda.api.hooks.ListenerAdapter) Player(org.bukkit.entity.Player) Inventory(org.bukkit.inventory.Inventory) ComponentModernizing(com.loohp.interactivechat.utils.ComponentModernizing) EventHandler(org.bukkit.event.EventHandler) InteractiveChatComponentSerializer(com.loohp.interactivechat.utils.InteractiveChatComponentSerializer) SlashCommandEvent(github.scarsz.discordsrv.dependencies.jda.api.events.interaction.SlashCommandEvent) OptionMapping(github.scarsz.discordsrv.dependencies.jda.api.interactions.commands.OptionMapping) InventoryDisplay(com.loohp.interactivechat.modules.InventoryDisplay) TranslatableComponent(com.loohp.interactivechat.libs.net.kyori.adventure.text.TranslatableComponent) XMaterial(com.loohp.interactivechat.libs.com.cryptomorin.xseries.XMaterial) Bukkit(org.bukkit.Bukkit) BufferedImage(java.awt.image.BufferedImage) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) ClickEvent(com.loohp.interactivechat.libs.net.kyori.adventure.text.event.ClickEvent) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) ImageGeneration(com.loohp.interactivechatdiscordsrvaddon.graphics.ImageGeneration) List(java.util.List) ErrorResponseException(github.scarsz.discordsrv.dependencies.jda.api.exceptions.ErrorResponseException) SubcommandData(github.scarsz.discordsrv.dependencies.jda.api.interactions.commands.build.SubcommandData) TextDecoration(com.loohp.interactivechat.libs.net.kyori.adventure.text.format.TextDecoration) JDAUtils(com.loohp.interactivechatdiscordsrvaddon.utils.JDAUtils) Entry(java.util.Map.Entry) Optional(java.util.Optional) NBTEditor(com.loohp.interactivechat.libs.io.github.bananapuncher714.nbteditor.NBTEditor) ArrayUtils(com.loohp.interactivechat.libs.org.apache.commons.lang3.ArrayUtils) Permission(net.milkbowl.vault.permission.Permission) ItemMeta(org.bukkit.inventory.meta.ItemMeta) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) HashMap(java.util.HashMap) InteractiveChatDiscordSrvAddon(com.loohp.interactivechatdiscordsrvaddon.InteractiveChatDiscordSrvAddon) SkinUtils(com.loohp.interactivechat.utils.SkinUtils) ComponentStyling(com.loohp.interactivechat.utils.ComponentStyling) HashSet(java.util.HashSet) PlainTextComponentSerializer(com.loohp.interactivechat.libs.net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer) DiscordSRV(github.scarsz.discordsrv.DiscordSRV) SharedType(com.loohp.interactivechat.api.InteractiveChatAPI.SharedType) ICPlaceholder(com.loohp.interactivechat.objectholders.ICPlaceholder) OfflineICPlayer(com.loohp.interactivechat.objectholders.OfflineICPlayer) ChatColor(net.md_5.bungee.api.ChatColor) Listener(org.bukkit.event.Listener) ItemDisplay(com.loohp.interactivechat.modules.ItemDisplay) TimeUnit(java.util.concurrent.TimeUnit) ICPlayerFactory(com.loohp.interactivechat.objectholders.ICPlayerFactory) ChatColorUtils(com.loohp.interactivechat.utils.ChatColorUtils) TranslationKeyUtils(com.loohp.interactivechatdiscordsrvaddon.utils.TranslationKeyUtils) NamedTextColor(com.loohp.interactivechat.libs.net.kyori.adventure.text.format.NamedTextColor) Comparator(java.util.Comparator) HashUtils(com.loohp.interactivechat.utils.HashUtils) ModelDisplayPosition(com.loohp.interactivechatdiscordsrvaddon.resources.models.ModelDisplay.ModelDisplayPosition) Collections(java.util.Collections) OptionMapping(github.scarsz.discordsrv.dependencies.jda.api.interactions.commands.OptionMapping) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) OfflineICPlayer(com.loohp.interactivechat.objectholders.OfflineICPlayer) MessageEmbed(github.scarsz.discordsrv.dependencies.jda.api.entities.MessageEmbed) DiscordDescription(com.loohp.interactivechatdiscordsrvaddon.utils.DiscordItemStackUtils.DiscordDescription) Message(github.scarsz.discordsrv.dependencies.jda.api.entities.Message) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) WebhookMessageUpdateAction(github.scarsz.discordsrv.dependencies.jda.api.requests.restaction.WebhookMessageUpdateAction) DiscordToolTip(com.loohp.interactivechatdiscordsrvaddon.utils.DiscordItemStackUtils.DiscordToolTip) ArrayList(java.util.ArrayList) ResourcePackInfo(com.loohp.interactivechatdiscordsrvaddon.resources.ResourcePackInfo) BufferedImage(java.awt.image.BufferedImage) LinkedHashMap(java.util.LinkedHashMap) TextChannel(github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel) Entry(java.util.Map.Entry) OfflinePlayer(org.bukkit.OfflinePlayer) ArrayList(java.util.ArrayList) List(java.util.List) Component(com.loohp.interactivechat.libs.net.kyori.adventure.text.Component) TranslatableComponent(com.loohp.interactivechat.libs.net.kyori.adventure.text.TranslatableComponent) UUID(java.util.UUID) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) OfflinePlayer(org.bukkit.OfflinePlayer) Player(org.bukkit.entity.Player) OfflineICPlayer(com.loohp.interactivechat.objectholders.OfflineICPlayer) Color(java.awt.Color) ChatColor(net.md_5.bungee.api.ChatColor) NamedTextColor(com.loohp.interactivechat.libs.net.kyori.adventure.text.format.NamedTextColor) IOException(java.io.IOException) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ErrorResponseException(github.scarsz.discordsrv.dependencies.jda.api.exceptions.ErrorResponseException) OfflineICPlayer(com.loohp.interactivechat.objectholders.OfflineICPlayer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) EmbedBuilder(github.scarsz.discordsrv.dependencies.jda.api.EmbedBuilder) ItemStack(org.bukkit.inventory.ItemStack) ChatColor(net.md_5.bungee.api.ChatColor) Map(java.util.Map) LinkedHashMap(java.util.LinkedHashMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) ValueTrios(com.loohp.interactivechat.objectholders.ValueTrios)

Aggregations

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