Search in sources :

Example 6 with XMaterial

use of com.loohp.interactivechat.libs.com.cryptomorin.xseries.XMaterial 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 7 with XMaterial

use of com.loohp.interactivechat.libs.com.cryptomorin.xseries.XMaterial in project InteractiveChat-DiscordSRV-Addon by LOOHP.

the class DiscordItemStackUtils method getDiscordDescription.

public static DiscordDescription getDiscordDescription(ItemStack item, Player player) throws Exception {
    String language = InteractiveChatDiscordSrvAddon.plugin.language;
    if (!item.getType().equals(Material.AIR) && InteractiveChat.ecoHook) {
        item = EcoHook.setEcoLores(item, player);
    }
    if (item == null) {
        item = new ItemStack(Material.AIR);
    }
    XMaterial xMaterial = XMaterialUtils.matchXMaterial(item);
    String name = PlainTextComponentSerializer.plainText().serialize(LegacyComponentSerializer.legacySection().deserialize(InteractiveChatComponentSerializer.bungeecordApiLegacy().serialize(ItemStackUtils.getDisplayName(item), language)));
    if (item.getAmount() == 1 || item == null || item.getType().equals(Material.AIR)) {
        name = InteractiveChatDiscordSrvAddon.plugin.itemDisplaySingle.replace("{Item}", ComponentStringUtils.stripColorAndConvertMagic(name)).replace("{Amount}", String.valueOf(item.getAmount()));
    } else {
        name = InteractiveChatDiscordSrvAddon.plugin.itemDisplayMultiple.replace("{Item}", ComponentStringUtils.stripColorAndConvertMagic(name)).replace("{Amount}", String.valueOf(item.getAmount()));
    }
    boolean hasMeta = item.hasItemMeta();
    StringBuilder description = new StringBuilder();
    if (xMaterial.equals(XMaterial.WRITTEN_BOOK) && hasMeta && item.getItemMeta() instanceof BookMeta) {
        BookMeta meta = (BookMeta) item.getItemMeta();
        String author = meta.getAuthor();
        if (author != null) {
            description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getBookAuthor(), language).replaceFirst("%1\\$s", ChatColorUtils.stripColor(author))).append("\n");
        }
        Generation generation = meta.getGeneration();
        if (generation == null) {
            generation = Generation.ORIGINAL;
        }
        description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getBookGeneration(generation), language)).append("\n");
        description.append("\n");
    }
    if (xMaterial.equals(XMaterial.SHIELD) && (!hasMeta || (hasMeta && !item.getItemMeta().hasItemFlag(ItemFlag.HIDE_POTION_EFFECTS)))) {
        if (NBTEditor.contains(item, "BlockEntityTag")) {
            List<Pattern> patterns = Collections.emptyList();
            if (!(item.getItemMeta() instanceof BannerMeta)) {
                if (item.getItemMeta() instanceof BlockStateMeta) {
                    BlockStateMeta bmeta = (BlockStateMeta) item.getItemMeta();
                    if (bmeta.hasBlockState()) {
                        Banner bannerBlockMeta = (Banner) bmeta.getBlockState();
                        patterns = bannerBlockMeta.getPatterns();
                    }
                }
            } else {
                BannerMeta meta = (BannerMeta) item.getItemMeta();
                patterns = meta.getPatterns();
            }
            for (Pattern pattern : patterns) {
                PatternTypeWrapper type = PatternTypeWrapper.fromPatternType(pattern.getPattern());
                description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getBannerPatternName(type, pattern.getColor()), language)).append("\n");
            }
        }
    }
    if (xMaterial.isOneOf(Arrays.asList("CONTAINS:Banner")) && (!hasMeta || (hasMeta && !item.getItemMeta().hasItemFlag(ItemFlag.HIDE_POTION_EFFECTS)))) {
        List<Pattern> patterns = Collections.emptyList();
        if (!(item.getItemMeta() instanceof BannerMeta)) {
            if (item.getItemMeta() instanceof BlockStateMeta) {
                BlockStateMeta bmeta = (BlockStateMeta) item.getItemMeta();
                Banner bannerBlockMeta = (Banner) bmeta.getBlockState();
                patterns = bannerBlockMeta.getPatterns();
            }
        } else {
            BannerMeta meta = (BannerMeta) item.getItemMeta();
            patterns = meta.getPatterns();
        }
        for (Pattern pattern : patterns) {
            PatternTypeWrapper type = PatternTypeWrapper.fromPatternType(pattern.getPattern());
            description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getBannerPatternName(type, pattern.getColor()), language)).append("\n");
        }
    }
    if (xMaterial.equals(XMaterial.TROPICAL_FISH_BUCKET)) {
        List<String> translations = TranslationKeyUtils.getTropicalFishBucketName(item);
        if (translations.size() > 0) {
            description.append(LanguageUtils.getTranslation(translations.get(0), language)).append("\n");
            if (translations.size() > 1) {
                description.append(translations.stream().skip(1).map(each -> LanguageUtils.getTranslation(each, language)).collect(Collectors.joining(", "))).append("\n");
            }
            description.append("\n");
        }
    }
    if (xMaterial.isOneOf(Arrays.asList("CONTAINS:Music_Disc"))) {
        description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getMusicDiscName(item), language)).append("\n");
    }
    if (xMaterial.equals(XMaterial.FIREWORK_ROCKET)) {
        if (InteractiveChat.version.isNewerOrEqualTo(MCVersion.V1_12) && NBTEditor.contains(item, "Fireworks", "Flight")) {
            int flight = NBTEditor.getByte(item, "Fireworks", "Flight");
            description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getRocketFlightDuration(), language)).append(" ").append(flight).append("\n");
        }
    }
    if (xMaterial.equals(XMaterial.CROSSBOW)) {
        CrossbowMeta meta = (CrossbowMeta) item.getItemMeta();
        List<ItemStack> charged = meta.getChargedProjectiles();
        if (charged != null && !charged.isEmpty()) {
            ItemStack charge = charged.get(0);
            String chargeItemName = getDiscordDescription(charge, player).getName();
            description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getCrossbowProjectile(), language)).append(" [**").append(chargeItemName).append("**]\n\n");
        }
    }
    if (InteractiveChat.version.isNewerOrEqualTo(MCVersion.V1_12) && FilledMapUtils.isFilledMap(item)) {
        MapMeta map = (MapMeta) item.getItemMeta();
        MapView mapView;
        int id;
        if (InteractiveChat.version.isNewerOrEqualTo(MCVersion.V1_13_1)) {
            mapView = map.getMapView();
            id = mapView.getId();
        } else if (InteractiveChat.version.equals(MCVersion.V1_13)) {
            short shortId = (short) bukkitMapViewClassGetIdMethod.invoke(map);
            mapView = (MapView) bukkitBukkitClassGetMapShortMethod.invoke(null, shortId);
            id = shortId;
        } else {
            short shortId = item.getDurability();
            mapView = (MapView) bukkitBukkitClassGetMapShortMethod.invoke(null, shortId);
            id = shortId;
        }
        int scale = mapView.getScale().getValue();
        if (!InteractiveChat.version.isLegacy()) {
            description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getFilledMapId(), language).replaceFirst("%s", id + "")).append("\n");
        } else {
            name += " (#" + id + ")";
        }
        description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getFilledMapScale(), language).replaceFirst("%s", (int) Math.pow(2, scale) + "")).append("\n");
        description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getFilledMapLevel(), language).replaceFirst("%s", scale + "").replaceFirst("%s", "4")).append("\n");
        description.append("\n");
    }
    if (InteractiveChat.version.isNewerOrEqualTo(MCVersion.V1_12) && !hasMeta || (hasMeta && !item.getItemMeta().hasItemFlag(ItemFlag.HIDE_POTION_EFFECTS))) {
        if (item.getItemMeta() instanceof PotionMeta) {
            PotionMeta meta = (PotionMeta) item.getItemMeta();
            List<PotionEffect> effects = new ArrayList<>();
            List<PotionEffect> base = PotionUtils.getBasePotionEffect(item);
            if (base != null) {
                effects.addAll(base);
            }
            effects.addAll(meta.getCustomEffects());
            if (effects.isEmpty()) {
                description.append("**").append(LanguageUtils.getTranslation(TranslationKeyUtils.getNoEffect(), language)).append("**\n");
            } else {
                for (PotionEffect effect : effects) {
                    String key = TranslationKeyUtils.getEffect(effect.getType());
                    String translation = LanguageUtils.getTranslation(key, language);
                    if (key.equals(translation)) {
                        description.append("**").append(WordUtils.capitalize(effect.getType().getName().toLowerCase().replace("_", " ")));
                    } else {
                        description.append("**").append(translation);
                    }
                    int amplifier = effect.getAmplifier();
                    String effectLevelTranslation = LanguageUtils.getTranslation(TranslationKeyUtils.getEffectLevel(amplifier), language);
                    if (effectLevelTranslation.length() > 0) {
                        description.append(" ").append(effectLevelTranslation);
                    }
                    if (!effect.getType().isInstant()) {
                        if (xMaterial.equals(XMaterial.LINGERING_POTION)) {
                            description.append(" (").append(TimeUtils.getReadableTimeBetween(0, effect.getDuration() / 4 * 50L, ":", ChronoUnit.MINUTES, ChronoUnit.SECONDS, true)).append(")");
                        } else {
                            description.append(" (").append(TimeUtils.getReadableTimeBetween(0, effect.getDuration() * 50L, ":", ChronoUnit.MINUTES, ChronoUnit.SECONDS, true)).append(")");
                        }
                    }
                    description.append("**\n");
                }
            }
            if (!description.toString().equals("")) {
                description.append("\n");
            }
        }
    }
    if (!hasMeta || (hasMeta && !item.getItemMeta().hasItemFlag(ItemFlag.HIDE_ENCHANTS))) {
        if (hasMeta && item.getItemMeta() instanceof EnchantmentStorageMeta) {
            for (Entry<Enchantment, Integer> entry : CustomMapUtils.sortMapByValue(((EnchantmentStorageMeta) item.getItemMeta()).getStoredEnchants()).entrySet()) {
                Enchantment ench = entry.getKey();
                int level = entry.getValue();
                String key = TranslationKeyUtils.getEnchantment(ench);
                String translation = LanguageUtils.getTranslation(key, language);
                String enchName;
                if (key.equals(translation)) {
                    enchName = WordUtils.capitalize(ench.getName().toLowerCase().replace("_", " "));
                } else {
                    enchName = translation;
                }
                if (enchName != null) {
                    description.append("**").append(enchName).append(ench.getMaxLevel() == 1 && level == 1 ? "" : " " + LanguageUtils.getTranslation(TranslationKeyUtils.getEnchantmentLevel(level), language)).append("**\n");
                }
            }
        } else {
            for (Entry<Enchantment, Integer> entry : CustomMapUtils.sortMapByValue(item.getEnchantments()).entrySet()) {
                Enchantment ench = entry.getKey();
                int level = entry.getValue();
                String key = TranslationKeyUtils.getEnchantment(ench);
                String translation = LanguageUtils.getTranslation(key, language);
                String enchName;
                if (key.equals(translation)) {
                    enchName = WordUtils.capitalize(ench.getName().toLowerCase().replace("_", " "));
                } else {
                    enchName = translation;
                }
                if (enchName != null) {
                    description.append("**").append(enchName).append(ench.getMaxLevel() == 1 && level == 1 ? "" : " " + LanguageUtils.getTranslation(TranslationKeyUtils.getEnchantmentLevel(level), language)).append("**\n");
                }
            }
        }
    }
    if (hasMeta && item.getItemMeta() instanceof LeatherArmorMeta && !item.getItemMeta().hasItemFlag(ItemFlag.HIDE_DYE)) {
        LeatherArmorMeta meta = (LeatherArmorMeta) item.getItemMeta();
        if (NBTEditor.contains(item, "display", "color")) {
            if (!description.toString().equals("")) {
                description.append("\n");
            }
            Color color = new Color(meta.getColor().asRGB());
            String hex = ColorUtils.rgb2Hex(color).toUpperCase();
            description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getDyeColor(), language).replaceFirst("%s", hex)).append("\n");
        }
    }
    if (hasMeta) {
        ItemMeta meta = item.getItemMeta();
        if (meta.hasLore()) {
            if (!description.toString().equals("")) {
                description.append("\n");
            }
            String lore = String.join("\n", meta.getLore());
            if (DiscordSRV.config().getBoolean("Experiment_MCDiscordReserializer_ToDiscord")) {
                if (InteractiveChatDiscordSrvAddon.plugin.escapeDiscordMarkdownInItems) {
                    lore = lore.replaceAll(DiscordDataRegistry.getMarkdownSpecialPattern(), "\\\\$1");
                }
                lore = DiscordSerializer.INSTANCE.serialize(ComponentStringUtils.toDiscordSRVComponent(LEGACY_SERIALIZER.deserialize(lore)));
            } else {
                lore = ComponentStringUtils.stripColorAndConvertMagic(String.join("\n", meta.getLore()));
                if (InteractiveChatDiscordSrvAddon.plugin.escapeDiscordMarkdownInItems) {
                    lore = lore.replaceAll(DiscordDataRegistry.getMarkdownSpecialPattern(), "\\\\$1");
                }
            }
            description.append(lore).append("\n");
        }
    }
    if (InteractiveChat.version.isNewerOrEqualTo(MCVersion.V1_12) && hasMeta && NBTEditor.contains(item, "AttributeModifiers") && NBTEditor.getSize(item, "AttributeModifiers") > 0 && !item.getItemMeta().hasItemFlag(ItemFlag.HIDE_ATTRIBUTES)) {
        boolean useMainHand = false;
        List<String> mainHand = new LinkedList<>();
        boolean useOffhand = false;
        List<String> offHand = new LinkedList<>();
        boolean useFeet = false;
        List<String> feet = new LinkedList<>();
        boolean useLegs = false;
        List<String> legs = new LinkedList<>();
        boolean useChest = false;
        List<String> chest = new LinkedList<>();
        boolean useHead = false;
        List<String> head = new LinkedList<>();
        ListTag<CompoundTag> attributeList = (ListTag<CompoundTag>) new SNBTDeserializer().fromString(NBTEditor.getNBTCompound(item, "tag", "AttributeModifiers").toJson());
        for (CompoundTag attributeTag : attributeList) {
            String attributeName = attributeTag.getString("AttributeName").replace("minecraft:", "");
            double amount = attributeTag.getDouble("Amount");
            int operation = attributeTag.containsKey("Operation") ? attributeTag.getInt("Operation") : 0;
            String attributeComponent = LanguageUtils.getTranslation(TranslationKeyUtils.getAttributeModifierKey(amount, operation), language).replaceFirst("%s", ATTRIBUTE_FORMAT.format(Math.abs(amount)) + "").replaceFirst("%s", LanguageUtils.getTranslation(TranslationKeyUtils.getAttributeKey(attributeName), language)).replace("%%", "%");
            if (attributeTag.containsKey("Slot")) {
                String slot = attributeTag.getString("Slot");
                switch(slot) {
                    case "mainhand":
                        if (amount != 0) {
                            mainHand.add(attributeComponent);
                        }
                        useMainHand = true;
                        break;
                    case "offhand":
                        if (amount != 0) {
                            offHand.add(attributeComponent);
                        }
                        useOffhand = true;
                        break;
                    case "feet":
                        if (amount != 0) {
                            feet.add(attributeComponent);
                        }
                        useFeet = true;
                        break;
                    case "legs":
                        if (amount != 0) {
                            legs.add(attributeComponent);
                        }
                        useLegs = true;
                        break;
                    case "chest":
                        if (amount != 0) {
                            chest.add(attributeComponent);
                        }
                        useChest = true;
                        break;
                    case "head":
                        if (amount != 0) {
                            head.add(attributeComponent);
                        }
                        useHead = true;
                        break;
                }
            } else {
                if (amount != 0) {
                    mainHand.add(attributeComponent);
                    offHand.add(attributeComponent);
                    feet.add(attributeComponent);
                    legs.add(attributeComponent);
                    chest.add(attributeComponent);
                    head.add(attributeComponent);
                }
                useMainHand = true;
                useOffhand = true;
                useFeet = true;
                useLegs = true;
                useChest = true;
                useHead = true;
            }
        }
        if (useMainHand) {
            description.append("\n");
            description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getModifierSlotKey(EquipmentSlot.HAND), language)).append("\n");
            for (String each : mainHand) {
                description.append(each).append("\n");
            }
        }
        if (useOffhand) {
            description.append("\n");
            description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getModifierSlotKey(EquipmentSlot.OFF_HAND), language)).append("\n");
            for (String each : offHand) {
                description.append(each).append("\n");
            }
        }
        if (useFeet) {
            description.append("\n");
            description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getModifierSlotKey(EquipmentSlot.FEET), language)).append("\n");
            for (String each : feet) {
                description.append(each).append("\n");
            }
        }
        if (useLegs) {
            description.append("\n");
            description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getModifierSlotKey(EquipmentSlot.LEGS), language)).append("\n");
            for (String each : legs) {
                description.append(each).append("\n");
            }
        }
        if (useChest) {
            description.append("\n");
            description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getModifierSlotKey(EquipmentSlot.CHEST), language)).append("\n");
            for (String each : chest) {
                description.append(each).append("\n");
            }
        }
        if (useHead) {
            description.append("\n");
            description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getModifierSlotKey(EquipmentSlot.HEAD), language)).append("\n");
            for (String each : head) {
                description.append(each).append("\n");
            }
        }
    }
    if (hasMeta && isUnbreakable(item) && !item.getItemMeta().hasItemFlag(ItemFlag.HIDE_UNBREAKABLE)) {
        if (!description.toString().equals("")) {
            description.append("\n");
        }
        description.append("**").append(LanguageUtils.getTranslation(TranslationKeyUtils.getUnbreakable(), language)).append("**\n");
    }
    if (InteractiveChat.version.isNewerOrEqualTo(MCVersion.V1_12) && hasMeta && !item.getItemMeta().hasItemFlag(ItemFlag.HIDE_DESTROYS)) {
        if (NBTEditor.contains(item, "CanDestroy") && NBTEditor.getSize(item, "CanDestroy") > 0) {
            description.append("\n");
            description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getCanDestroy(), language)).append("\n");
            ListTag<StringTag> materialList = (ListTag<StringTag>) new SNBTDeserializer().fromString(NBTEditor.getNBTCompound(item, "tag", "CanDestroy").toJson());
            for (StringTag materialTag : materialList) {
                XMaterial parsedXMaterial = XMaterialUtils.matchXMaterial(materialTag.getValue().replace("minecraft:", "").toUpperCase());
                if (parsedXMaterial == null) {
                    description.append(WordUtils.capitalizeFully(materialTag.getValue().replace("_", " ").toLowerCase())).append("\n");
                } else {
                    description.append(LanguageUtils.getTranslation(LanguageUtils.getTranslationKey(parsedXMaterial.parseItem()), language)).append("\n");
                }
            }
        }
    }
    if (InteractiveChat.version.isNewerOrEqualTo(MCVersion.V1_12) && hasMeta && !item.getItemMeta().hasItemFlag(ItemFlag.HIDE_PLACED_ON)) {
        if (NBTEditor.contains(item, "CanPlaceOn") && NBTEditor.getSize(item, "CanPlaceOn") > 0) {
            description.append("\n");
            description.append(LanguageUtils.getTranslation(TranslationKeyUtils.getCanPlace(), language)).append("\n");
            ListTag<StringTag> materialList = (ListTag<StringTag>) new SNBTDeserializer().fromString(NBTEditor.getNBTCompound(item, "tag", "CanPlaceOn").toJson());
            for (StringTag materialTag : materialList) {
                XMaterial parsedXMaterial = XMaterialUtils.matchXMaterial(materialTag.getValue().replace("minecraft:", "").toUpperCase());
                if (parsedXMaterial == null) {
                    description.append(WordUtils.capitalizeFully(materialTag.getValue().replace("_", " ").toLowerCase())).append("\n");
                } else {
                    description.append(LanguageUtils.getTranslation(LanguageUtils.getTranslationKey(parsedXMaterial.parseItem()), language)).append("\n");
                }
            }
        }
    }
    if (item.getType().getMaxDurability() > 0) {
        int durability = item.getType().getMaxDurability() - (InteractiveChat.version.isLegacy() ? item.getDurability() : ((Damageable) item.getItemMeta()).getDamage());
        int maxDur = item.getType().getMaxDurability();
        if (durability < maxDur) {
            if (!description.toString().equals("")) {
                description.append("\n");
            }
            description.append("**").append(LanguageUtils.getTranslation(TranslationKeyUtils.getDurability(), language).replaceFirst("%s", String.valueOf(durability)).replaceFirst("%s", String.valueOf(maxDur))).append("**\n");
        }
    }
    return new DiscordDescription(name, description.toString().trim().isEmpty() ? null : description.toString());
}
Also used : ItemFlag(org.bukkit.inventory.ItemFlag) Color(java.awt.Color) Arrays(java.util.Arrays) Enchantment(org.bukkit.enchantments.Enchantment) Player(org.bukkit.entity.Player) InteractiveChatComponentSerializer(com.loohp.interactivechat.utils.InteractiveChatComponentSerializer) SNBTDeserializer(com.loohp.interactivechat.libs.net.querz.nbt.io.SNBTDeserializer) Method(java.lang.reflect.Method) XMaterial(com.loohp.interactivechat.libs.com.cryptomorin.xseries.XMaterial) Material(org.bukkit.Material) EquipmentSlot(org.bukkit.inventory.EquipmentSlot) BlockStateMeta(org.bukkit.inventory.meta.BlockStateMeta) Bukkit(org.bukkit.Bukkit) MapMeta(org.bukkit.inventory.meta.MapMeta) XMaterialUtils(com.loohp.interactivechat.utils.XMaterialUtils) PatternTypeWrapper(com.loohp.interactivechatdiscordsrvaddon.wrappers.PatternTypeWrapper) Collectors(java.util.stream.Collectors) ItemStack(org.bukkit.inventory.ItemStack) InteractiveChat(com.loohp.interactivechat.InteractiveChat) DiscordSerializer(github.scarsz.discordsrv.dependencies.mcdiscordreserializer.discord.DiscordSerializer) Damageable(org.bukkit.inventory.meta.Damageable) List(java.util.List) CompoundTag(com.loohp.interactivechat.libs.net.querz.nbt.tag.CompoundTag) ListTag(com.loohp.interactivechat.libs.net.querz.nbt.tag.ListTag) Stream(java.util.stream.Stream) LeatherArmorMeta(org.bukkit.inventory.meta.LeatherArmorMeta) Entry(java.util.Map.Entry) Optional(java.util.Optional) NBTEditor(com.loohp.interactivechat.libs.io.github.bananapuncher714.nbteditor.NBTEditor) CrossbowMeta(org.bukkit.inventory.meta.CrossbowMeta) EnchantmentStorageMeta(org.bukkit.inventory.meta.EnchantmentStorageMeta) FilledMapUtils(com.loohp.interactivechat.utils.FilledMapUtils) MCVersion(com.loohp.interactivechat.utils.MCVersion) ItemMeta(org.bukkit.inventory.meta.ItemMeta) Pattern(org.bukkit.block.banner.Pattern) BookMeta(org.bukkit.inventory.meta.BookMeta) StringTag(com.loohp.interactivechat.libs.net.querz.nbt.tag.StringTag) BannerMeta(org.bukkit.inventory.meta.BannerMeta) Generation(org.bukkit.inventory.meta.BookMeta.Generation) InteractiveChatDiscordSrvAddon(com.loohp.interactivechatdiscordsrvaddon.InteractiveChatDiscordSrvAddon) ArrayList(java.util.ArrayList) PlainTextComponentSerializer(com.loohp.interactivechat.libs.net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer) DiscordSRV(github.scarsz.discordsrv.DiscordSRV) Banner(org.bukkit.block.Banner) WordUtils(com.loohp.interactivechat.libs.org.apache.commons.text.WordUtils) LanguageUtils(com.loohp.interactivechat.utils.LanguageUtils) PotionMeta(org.bukkit.inventory.meta.PotionMeta) MapView(org.bukkit.map.MapView) LinkedList(java.util.LinkedList) ItemStackUtils(com.loohp.interactivechat.utils.ItemStackUtils) ChatColor(net.md_5.bungee.api.ChatColor) ColorUtils(com.loohp.interactivechat.utils.ColorUtils) Component(com.loohp.interactivechat.libs.net.kyori.adventure.text.Component) DecimalFormat(java.text.DecimalFormat) RarityUtils(com.loohp.interactivechat.utils.RarityUtils) EcoHook(com.loohp.interactivechat.hooks.ecoenchants.EcoHook) PotionEffect(org.bukkit.potion.PotionEffect) DiscordDataRegistry(com.loohp.interactivechatdiscordsrvaddon.registry.DiscordDataRegistry) ChronoUnit(java.time.temporal.ChronoUnit) ChatColorUtils(com.loohp.interactivechat.utils.ChatColorUtils) Collections(java.util.Collections) LegacyComponentSerializer(com.loohp.interactivechat.libs.net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer) StringTag(com.loohp.interactivechat.libs.net.querz.nbt.tag.StringTag) PotionEffect(org.bukkit.potion.PotionEffect) ArrayList(java.util.ArrayList) MapView(org.bukkit.map.MapView) CrossbowMeta(org.bukkit.inventory.meta.CrossbowMeta) ItemMeta(org.bukkit.inventory.meta.ItemMeta) CompoundTag(com.loohp.interactivechat.libs.net.querz.nbt.tag.CompoundTag) Pattern(org.bukkit.block.banner.Pattern) BannerMeta(org.bukkit.inventory.meta.BannerMeta) Banner(org.bukkit.block.Banner) Color(java.awt.Color) ChatColor(net.md_5.bungee.api.ChatColor) PatternTypeWrapper(com.loohp.interactivechatdiscordsrvaddon.wrappers.PatternTypeWrapper) PotionMeta(org.bukkit.inventory.meta.PotionMeta) XMaterial(com.loohp.interactivechat.libs.com.cryptomorin.xseries.XMaterial) ListTag(com.loohp.interactivechat.libs.net.querz.nbt.tag.ListTag) LinkedList(java.util.LinkedList) BlockStateMeta(org.bukkit.inventory.meta.BlockStateMeta) Generation(org.bukkit.inventory.meta.BookMeta.Generation) EnchantmentStorageMeta(org.bukkit.inventory.meta.EnchantmentStorageMeta) MapMeta(org.bukkit.inventory.meta.MapMeta) SNBTDeserializer(com.loohp.interactivechat.libs.net.querz.nbt.io.SNBTDeserializer) LeatherArmorMeta(org.bukkit.inventory.meta.LeatherArmorMeta) ItemStack(org.bukkit.inventory.ItemStack) Enchantment(org.bukkit.enchantments.Enchantment) BookMeta(org.bukkit.inventory.meta.BookMeta)

Aggregations

XMaterial (com.loohp.interactivechat.libs.com.cryptomorin.xseries.XMaterial)7 Color (java.awt.Color)7 BufferedImage (java.awt.image.BufferedImage)5 ItemStack (org.bukkit.inventory.ItemStack)5 Component (com.loohp.interactivechat.libs.net.kyori.adventure.text.Component)4 BlockStateMeta (org.bukkit.inventory.meta.BlockStateMeta)4 LeatherArmorMeta (org.bukkit.inventory.meta.LeatherArmorMeta)4 ICPlayer (com.loohp.interactivechat.objectholders.ICPlayer)3 ModelOverrideType (com.loohp.interactivechatdiscordsrvaddon.resources.models.ModelOverride.ModelOverrideType)3 GeneratedTextureResource (com.loohp.interactivechatdiscordsrvaddon.resources.textures.GeneratedTextureResource)3 TextureResource (com.loohp.interactivechatdiscordsrvaddon.resources.textures.TextureResource)3 TintIndexData (com.loohp.interactivechatdiscordsrvaddon.utils.TintUtils.TintIndexData)3 PatternTypeWrapper (com.loohp.interactivechatdiscordsrvaddon.wrappers.PatternTypeWrapper)3 Graphics2D (java.awt.Graphics2D)3 ArrayList (java.util.ArrayList)3 LinkedList (java.util.LinkedList)3 List (java.util.List)3 InteractiveChat (com.loohp.interactivechat.InteractiveChat)2 LegacyComponentSerializer (com.loohp.interactivechat.libs.net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer)2 PlainTextComponentSerializer (com.loohp.interactivechat.libs.net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer)2