Search in sources :

Example 1 with ResourcePackInfo

use of com.loohp.interactivechatdiscordsrvaddon.resources.ResourcePackInfo in project InteractiveChat-DiscordSRV-Addon by LOOHP.

the class MinecraftFontRenderer method loadResources.

public void loadResources() {
    try {
        if (!resourceLock.tryLock(0, TimeUnit.MILLISECONDS)) {
            return;
        }
    } catch (InterruptedException e) {
    }
    reloadResourcesButton.setEnabled(false);
    resourceBar.setValue(0);
    resourceBar.setVisible(true);
    textAreaResources.setText("Loading Resources...");
    updateTextAreaInputSize();
    List<String> resourceOrder;
    int valuePerPack;
    try {
        YamlConfiguration yaml = new YamlConfiguration(new FileInputStream("InteractiveChatDiscordSrvAddon/config.yml"));
        resourceOrder = yaml.getStringList("Resources.Order");
        Collections.reverse(resourceOrder);
        valuePerPack = (int) ((1.0 / (double) (resourceOrder.size() + 1)) * 10000);
    } catch (IOException e) {
        Toolkit.getDefaultToolkit().beep();
        JOptionPane.showMessageDialog(null, GUIMain.createLabel("There is an error while loading from config:\n" + e.getMessage(), 13, Color.RED), title, JOptionPane.ERROR_MESSAGE);
        return;
    }
    if (resourceManager != null) {
        resourceManager.close();
    }
    PrintStream original = System.err;
    try {
        resourceManager = new ResourceManager();
        resourceManager.loadResources(new File("InteractiveChatDiscordSrvAddon/built-in", "Default"));
        resourceBar.setValue(valuePerPack);
        for (String resourceName : resourceOrder) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            System.setErr(new PrintStream(baos));
            try {
                File resourcePackFile = new File("InteractiveChatDiscordSrvAddon/resourcepacks/" + resourceName);
                ResourcePackInfo info = resourceManager.loadResources(resourcePackFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
            String error = baos.toString();
            if (!error.isEmpty()) {
                ForkJoinPool.commonPool().execute(() -> JOptionPane.showMessageDialog(null, GUIMain.createLabel("There are errors while loading \"" + resourceName + "\":\n" + error, 13, Color.RED), title, JOptionPane.ERROR_MESSAGE));
            }
            resourceBar.setValue(resourceBar.getValue() + valuePerPack);
        }
    } catch (Throwable e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        Toolkit.getDefaultToolkit().beep();
        JOptionPane.showMessageDialog(null, GUIMain.createLabel("An error occurred!\n" + sw, 13, Color.RED), title, JOptionPane.ERROR_MESSAGE);
    }
    System.setErr(original);
    textAreaResources.setText("Loaded Resources:\n");
    for (ResourcePackInfo info : resourceManager.getResourcePackInfo()) {
        textAreaResources.append(" - " + info.getName());
        if (!info.getStatus()) {
            textAreaResources.append(" (Failed)");
        }
        textAreaResources.append("\n");
    }
    List<LanguageData> languages = getAllLanguageData(resourceManager.getLanguageManager());
    String lastSelected = comboBoxLanguages.getSelectedItem() == null ? null : ((LanguageData) comboBoxLanguages.getSelectedItem()).getLanguage();
    comboBoxLanguages.removeAllItems();
    for (LanguageData language : languages) {
        comboBoxLanguages.addItem(language);
    }
    Optional<LanguageData> optLanguage = languages.stream().filter(each -> each.getLanguage().equalsIgnoreCase(lastSelected == null ? "en_us" : lastSelected)).findFirst();
    if (optLanguage.isPresent()) {
        comboBoxLanguages.setSelectedItem(optLanguage.get());
    } else {
        comboBoxLanguages.setSelectedIndex(0);
    }
    reloadResourcesButton.setEnabled(true);
    resourceBar.setVisible(false);
    updateTextAreaInputSize();
    resourceLock.unlock();
}
Also used : Color(java.awt.Color) YamlConfiguration(com.loohp.interactivechat.libs.com.loohp.yamlconfiguration.YamlConfiguration) URLClassLoaderAccess(com.loohp.interactivechatdiscordsrvaddon.libs.URLClassLoaderAccess) ResourcePackInfo(com.loohp.interactivechatdiscordsrvaddon.resources.ResourcePackInfo) RenderingHints(java.awt.RenderingHints) TextureAnimation(com.loohp.interactivechatdiscordsrvaddon.resources.textures.TextureAnimation) URLClassLoader(java.net.URLClassLoader) ImageIO(javax.imageio.ImageIO) MouseAdapter(java.awt.event.MouseAdapter) TextureResource(com.loohp.interactivechatdiscordsrvaddon.resources.textures.TextureResource) JFileChooser(javax.swing.JFileChooser) JComboBox(javax.swing.JComboBox) JFrame(javax.swing.JFrame) BorderLayout(java.awt.BorderLayout) Clipboard(java.awt.datatransfer.Clipboard) PrintWriter(java.io.PrintWriter) BufferedImage(java.awt.image.BufferedImage) BorderFactory(javax.swing.BorderFactory) Icon(javax.swing.Icon) LanguageManager(com.loohp.interactivechatdiscordsrvaddon.resources.languages.LanguageManager) ComponentEvent(java.awt.event.ComponentEvent) KeyEvent(java.awt.event.KeyEvent) Collectors(java.util.stream.Collectors) Executors(java.util.concurrent.Executors) Objects(java.util.Objects) Dimension(java.awt.Dimension) List(java.util.List) GridConstraints(com.loohp.interactivechat.libs.com.intellij.uiDesigner.core.GridConstraints) JCheckBox(javax.swing.JCheckBox) Graphics(java.awt.Graphics) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) JPanel(javax.swing.JPanel) WindowConstants(javax.swing.WindowConstants) Toolkit(java.awt.Toolkit) Insets(java.awt.Insets) ImageUtils(com.loohp.interactivechatdiscordsrvaddon.graphics.ImageUtils) ByteArrayOutputStream(java.io.ByteArrayOutputStream) JTextField(javax.swing.JTextField) ResourceManager(com.loohp.interactivechatdiscordsrvaddon.resources.ResourceManager) SpinnerNumberModel(javax.swing.SpinnerNumberModel) CompletableFuture(java.util.concurrent.CompletableFuture) KeyAdapter(java.awt.event.KeyAdapter) AtomicReference(java.util.concurrent.atomic.AtomicReference) ComponentStyling(com.loohp.interactivechat.utils.ComponentStyling) ArrayList(java.util.ArrayList) GridLayout(java.awt.GridLayout) SwingUtilities(javax.swing.SwingUtilities) FocusAdapter(java.awt.event.FocusAdapter) ResourceDownloadManager(com.loohp.interactivechatdiscordsrvaddon.resources.ResourceDownloadManager) PlainTextComponentSerializer(com.loohp.interactivechat.libs.net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer) JMenuItem(javax.swing.JMenuItem) Graphics2D(java.awt.Graphics2D) JProgressBar(javax.swing.JProgressBar) ExecutorService(java.util.concurrent.ExecutorService) GsonComponentSerializer(com.loohp.interactivechat.libs.net.kyori.adventure.text.serializer.gson.GsonComponentSerializer) JComponent(javax.swing.JComponent) PrintStream(java.io.PrintStream) JButton(javax.swing.JButton) JSpinner(javax.swing.JSpinner) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Component(com.loohp.interactivechat.libs.net.kyori.adventure.text.Component) ResourceRegistry(com.loohp.interactivechatdiscordsrvaddon.registry.ResourceRegistry) JPopupMenu(javax.swing.JPopupMenu) StringWriter(java.io.StringWriter) Spacer(com.loohp.interactivechat.libs.com.intellij.uiDesigner.core.Spacer) TextureMeta(com.loohp.interactivechatdiscordsrvaddon.resources.textures.TextureMeta) IOException(java.io.IOException) FileInputStream(java.io.FileInputStream) JOptionPane(javax.swing.JOptionPane) MouseEvent(java.awt.event.MouseEvent) File(java.io.File) JScrollPane(javax.swing.JScrollPane) ComponentAdapter(java.awt.event.ComponentAdapter) TimeUnit(java.util.concurrent.TimeUnit) GridLayoutManager(com.loohp.interactivechat.libs.com.intellij.uiDesigner.core.GridLayoutManager) JLabel(javax.swing.JLabel) FocusEvent(java.awt.event.FocusEvent) ForkJoinPool(java.util.concurrent.ForkJoinPool) ChatColorUtils(com.loohp.interactivechat.utils.ChatColorUtils) TextureProperties(com.loohp.interactivechatdiscordsrvaddon.resources.textures.TextureProperties) JTextArea(javax.swing.JTextArea) NamedTextColor(com.loohp.interactivechat.libs.net.kyori.adventure.text.format.NamedTextColor) Collections(java.util.Collections) LegacyComponentSerializer(com.loohp.interactivechat.libs.net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer) PrintStream(java.io.PrintStream) IOException(java.io.IOException) ResourceManager(com.loohp.interactivechatdiscordsrvaddon.resources.ResourceManager) ByteArrayOutputStream(java.io.ByteArrayOutputStream) YamlConfiguration(com.loohp.interactivechat.libs.com.loohp.yamlconfiguration.YamlConfiguration) FileInputStream(java.io.FileInputStream) ResourcePackInfo(com.loohp.interactivechatdiscordsrvaddon.resources.ResourcePackInfo) IOException(java.io.IOException) StringWriter(java.io.StringWriter) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 2 with ResourcePackInfo

use of com.loohp.interactivechatdiscordsrvaddon.resources.ResourcePackInfo in project InteractiveChat-DiscordSRV-Addon by LOOHP.

the class BlockModelRenderer method loadResources.

public void loadResources() {
    try {
        if (!lock.tryLock(0, TimeUnit.MILLISECONDS)) {
            return;
        }
    } catch (InterruptedException e) {
    }
    renderModelButton.setEnabled(false);
    reloadResourcesButton.setEnabled(false);
    resourceBar.setValue(0);
    resourceBar.setVisible(true);
    textAreaResources.setText("Loading Resources...");
    List<String> resourceOrder;
    int valuePerPack;
    try {
        YamlConfiguration yaml = new YamlConfiguration(new FileInputStream("InteractiveChatDiscordSrvAddon/config.yml"));
        resourceOrder = yaml.getStringList("Resources.Order");
        Collections.reverse(resourceOrder);
        valuePerPack = (int) ((1.0 / (double) (resourceOrder.size() + 1)) * 10000);
    } catch (IOException e) {
        Toolkit.getDefaultToolkit().beep();
        JOptionPane.showMessageDialog(null, GUIMain.createLabel("There is an error while loading from config:\n" + e.getMessage(), 13, Color.RED), title, JOptionPane.ERROR_MESSAGE);
        return;
    }
    if (resourceManager != null) {
        resourceManager.close();
    }
    PrintStream original = System.err;
    try {
        resourceManager = new ResourceManager();
        resourceManager.loadResources(new File("InteractiveChatDiscordSrvAddon/built-in", "Default"));
        resourceBar.setValue(valuePerPack);
        for (String resourceName : resourceOrder) {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            System.setErr(new PrintStream(baos));
            try {
                File resourcePackFile = new File("InteractiveChatDiscordSrvAddon/resourcepacks/" + resourceName);
                ResourcePackInfo info = resourceManager.loadResources(resourcePackFile);
            } catch (Exception e) {
                e.printStackTrace();
            }
            String error = baos.toString();
            if (!error.isEmpty()) {
                ForkJoinPool.commonPool().execute(() -> JOptionPane.showMessageDialog(null, GUIMain.createLabel("There are errors while loading \"" + resourceName + "\":\n" + error, 13, Color.RED), title, JOptionPane.ERROR_MESSAGE));
            }
            resourceBar.setValue(resourceBar.getValue() + valuePerPack);
        }
    } catch (Throwable e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        Toolkit.getDefaultToolkit().beep();
        JOptionPane.showMessageDialog(null, GUIMain.createLabel("An error occurred!\n" + sw, 13, Color.RED), title, JOptionPane.ERROR_MESSAGE);
    }
    System.setErr(original);
    textAreaResources.setText("Loaded Resources:\n");
    for (ResourcePackInfo info : resourceManager.getResourcePackInfo()) {
        textAreaResources.append(" - " + info.getName());
        if (!info.getStatus()) {
            textAreaResources.append(" (Failed)");
        }
        textAreaResources.append("\n");
    }
    renderModelButton.setEnabled(true);
    reloadResourcesButton.setEnabled(true);
    resourceBar.setVisible(false);
    lock.unlock();
}
Also used : PrintStream(java.io.PrintStream) IOException(java.io.IOException) ResourceManager(com.loohp.interactivechatdiscordsrvaddon.resources.ResourceManager) ByteArrayOutputStream(java.io.ByteArrayOutputStream) YamlConfiguration(com.loohp.interactivechat.libs.com.loohp.yamlconfiguration.YamlConfiguration) FileInputStream(java.io.FileInputStream) ResourcePackInfo(com.loohp.interactivechatdiscordsrvaddon.resources.ResourcePackInfo) IOException(java.io.IOException) StringWriter(java.io.StringWriter) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 3 with ResourcePackInfo

use of com.loohp.interactivechatdiscordsrvaddon.resources.ResourcePackInfo in project InteractiveChat-DiscordSRV-Addon by LOOHP.

the class InteractiveChatDiscordSrvAddon method reloadTextures.

public void reloadTextures(boolean redownload, boolean clean, CommandSender... receivers) {
    CommandSender[] senders;
    if (Stream.of(receivers).noneMatch(each -> each.equals(Bukkit.getConsoleSender()))) {
        senders = new CommandSender[receivers.length + 1];
        System.arraycopy(receivers, 0, senders, 0, receivers.length);
        senders[senders.length - 1] = Bukkit.getConsoleSender();
    } else {
        senders = receivers;
    }
    Bukkit.getScheduler().runTaskAsynchronously(this, () -> {
        try {
            if (!resourceReloadLock.tryLock(0, TimeUnit.MILLISECONDS)) {
                sendMessage(ChatColor.YELLOW + "Resource reloading already in progress!", senders);
                return;
            }
            isReady = false;
            if (InteractiveChatDiscordSrvAddon.plugin.resourceManager != null) {
                Bukkit.getScheduler().callSyncMethod(plugin, () -> {
                    InteractiveChatDiscordSrvAddon.plugin.resourceManager.close();
                    return null;
                }).get();
            }
            try {
                AssetsDownloader.loadAssets(getDataFolder(), redownload, clean, receivers);
            } catch (Exception e) {
                e.printStackTrace();
            }
            List<String> resourceList = new ArrayList<>();
            resourceList.add("Default");
            resourceList.addAll(resourceOrder);
            sendMessage(ChatColor.AQUA + "[ICDiscordSrvAddon] Reloading ResourceManager: " + ChatColor.YELLOW + String.join(", ", resourceList), senders);
            ResourceManager resourceManager = new ResourceManager();
            resourceManager.getLanguageManager().setTranslateFunction((translateKey, language) -> LanguageUtils.getTranslation(translateKey, language));
            resourceManager.getLanguageManager().setAvailableLanguagesSupplier(() -> LanguageUtils.getLoadedLanguages());
            resourceManager.getLanguageManager().registerReloadListener(e -> {
                LanguageUtils.clearPluginTranslations(InteractiveChatDiscordSrvAddon.plugin);
                for (Entry<String, Map<String, String>> entry : e.getTranslations().entrySet()) {
                    LanguageUtils.loadPluginTranslations(InteractiveChatDiscordSrvAddon.plugin, entry.getKey(), entry.getValue());
                }
            });
            Bukkit.getConsoleSender().sendMessage(ChatColor.AQUA + "[ICDiscordSrvAddon] Loading \"Default\" resources...");
            resourceManager.loadResources(new File(getDataFolder() + "/built-in", "Default"));
            for (String resourceName : resourceOrder) {
                try {
                    Bukkit.getConsoleSender().sendMessage(ChatColor.AQUA + "[ICDiscordSrvAddon] Loading \"" + resourceName + "\" resources...");
                    File resourcePackFile = new File(getDataFolder(), "resourcepacks/" + resourceName);
                    ResourcePackInfo info = resourceManager.loadResources(resourcePackFile);
                    if (info.getStatus()) {
                        if (info.comparePackFormat() > 0) {
                            sendMessage(ChatColor.YELLOW + "[ICDiscordSrvAddon] Warning: \"" + resourceName + "\" was made for a newer version of Minecraft!", senders);
                        } else if (info.comparePackFormat() < 0) {
                            sendMessage(ChatColor.YELLOW + "[ICDiscordSrvAddon] Warning: \"" + resourceName + "\" was made for an older version of Minecraft!", senders);
                        }
                    } else {
                        if (info.getRejectedReason() == null) {
                            sendMessage(ChatColor.RED + "[ICDiscordSrvAddon] Unable to load \"" + resourceName + "\"", senders);
                        } else {
                            sendMessage(ChatColor.RED + "[ICDiscordSrvAddon] Unable to load \"" + resourceName + "\", Reason: " + info.getRejectedReason(), senders);
                        }
                    }
                } catch (Exception e) {
                    sendMessage(ChatColor.RED + "[ICDiscordSrvAddon] Unable to load \"" + resourceName + "\"", senders);
                    e.printStackTrace();
                }
            }
            Bukkit.getScheduler().callSyncMethod(plugin, () -> {
                InteractiveChatDiscordSrvAddon.plugin.resourceManager = resourceManager;
                Cache.clearAllCache();
                if (resourceManager.getResourcePackInfo().stream().allMatch(each -> each.getStatus())) {
                    sendMessage(ChatColor.AQUA + "[ICDiscordSrvAddon] Loaded all resources!", senders);
                    isReady = true;
                } else {
                    sendMessage(ChatColor.RED + "[ICDiscordSrvAddon] There is a problem while loading resources.", senders);
                }
                return null;
            }).get();
            resourceReloadLock.unlock();
        } catch (InterruptedException | ExecutionException e) {
            e.printStackTrace();
        }
    });
}
Also used : Color(java.awt.Color) Charts(com.loohp.interactivechatdiscordsrvaddon.metrics.Charts) Arrays(java.util.Arrays) FontTextureResource(com.loohp.interactivechatdiscordsrvaddon.resources.fonts.FontTextureResource) ListIterator(java.util.ListIterator) ResourcePackInfo(com.loohp.interactivechatdiscordsrvaddon.resources.ResourcePackInfo) JSONParser(com.loohp.interactivechat.libs.org.json.simple.parser.JSONParser) EventHandler(org.bukkit.event.EventHandler) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) Map(java.util.Map) ThreadFactory(java.util.concurrent.ThreadFactory) PlaceholderCooldownManager(com.loohp.interactivechat.objectholders.PlaceholderCooldownManager) Debug(com.loohp.interactivechatdiscordsrvaddon.debug.Debug) Bukkit(org.bukkit.Bukkit) InboundToGameEvents(com.loohp.interactivechatdiscordsrvaddon.listeners.InboundToGameEvents) PlayerJoinEvent(org.bukkit.event.player.PlayerJoinEvent) CommandSender(org.bukkit.command.CommandSender) BufferedImage(java.awt.image.BufferedImage) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) UUID(java.util.UUID) Executors(java.util.concurrent.Executors) InteractiveChat(com.loohp.interactivechat.InteractiveChat) JavaPlugin(org.bukkit.plugin.java.JavaPlugin) ImageGeneration(com.loohp.interactivechatdiscordsrvaddon.graphics.ImageGeneration) List(java.util.List) Stream(java.util.stream.Stream) Entry(java.util.Map.Entry) Queue(java.util.Queue) Permission(github.scarsz.discordsrv.dependencies.jda.api.Permission) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) DiscordReadyEvents(com.loohp.interactivechatdiscordsrvaddon.listeners.DiscordReadyEvents) ImageUtils(com.loohp.interactivechatdiscordsrvaddon.graphics.ImageUtils) ResourceManager(com.loohp.interactivechatdiscordsrvaddon.resources.ResourceManager) Registry(com.loohp.interactivechat.registry.Registry) Config(com.loohp.interactivechat.config.Config) ModelRenderer(com.loohp.interactivechatdiscordsrvaddon.resources.ModelRenderer) SkinUtils(com.loohp.interactivechat.utils.SkinUtils) StandardCopyOption(java.nio.file.StandardCopyOption) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) DiscordSRV(github.scarsz.discordsrv.DiscordSRV) LanguageUtils(com.loohp.interactivechat.utils.LanguageUtils) InteractiveChatRegistry(com.loohp.interactivechatdiscordsrvaddon.registry.InteractiveChatRegistry) Metrics(com.loohp.interactivechatdiscordsrvaddon.metrics.Metrics) JSONObject(com.loohp.interactivechat.libs.org.json.simple.JSONObject) OutboundToDiscordEvents(com.loohp.interactivechatdiscordsrvaddon.listeners.OutboundToDiscordEvents) ExecutorService(java.util.concurrent.ExecutorService) ChatColor(net.md_5.bungee.api.ChatColor) Listener(org.bukkit.event.Listener) ColorUtils(com.loohp.interactivechat.utils.ColorUtils) ReentrantLock(java.util.concurrent.locks.ReentrantLock) Files(java.nio.file.Files) IOException(java.io.IOException) ICPlayerEvents(com.loohp.interactivechatdiscordsrvaddon.listeners.ICPlayerEvents) File(java.io.File) ExecutionException(java.util.concurrent.ExecutionException) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) ICPlayerFactory(com.loohp.interactivechat.objectholders.ICPlayerFactory) ChatColorUtils(com.loohp.interactivechat.utils.ChatColorUtils) Collections(java.util.Collections) Updater(com.loohp.interactivechatdiscordsrvaddon.updater.Updater) ArrayList(java.util.ArrayList) ResourceManager(com.loohp.interactivechatdiscordsrvaddon.resources.ResourceManager) IOException(java.io.IOException) ExecutionException(java.util.concurrent.ExecutionException) ResourcePackInfo(com.loohp.interactivechatdiscordsrvaddon.resources.ResourcePackInfo) CommandSender(org.bukkit.command.CommandSender) ExecutionException(java.util.concurrent.ExecutionException) Map(java.util.Map) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) File(java.io.File)

Example 4 with ResourcePackInfo

use of com.loohp.interactivechatdiscordsrvaddon.resources.ResourcePackInfo in project InteractiveChat-DiscordSRV-Addon by LOOHP.

the class Commands method onCommand.

@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    if (!label.equalsIgnoreCase("interactivechatdiscordsrv") && !label.equalsIgnoreCase("icd")) {
        return true;
    }
    if (args.length == 0) {
        sender.sendMessage(ChatColor.AQUA + "InteractiveChat DiscordSRV Addon written by LOOHP!");
        sender.sendMessage(ChatColor.GOLD + "You are running ICDiscordSRVAddon version: " + InteractiveChatDiscordSrvAddon.plugin.getDescription().getVersion());
        return true;
    }
    if (args[0].equalsIgnoreCase("status")) {
        if (sender.hasPermission("interactivechatdiscordsrv.status")) {
            sender.sendMessage(InteractiveChatDiscordSrvAddon.plugin.defaultResourceHashLang.replaceFirst("%s", InteractiveChatDiscordSrvAddon.plugin.defaultResourceHash + " (" + InteractiveChat.exactMinecraftVersion + ")"));
            sender.sendMessage(InteractiveChatDiscordSrvAddon.plugin.loadedResourcesLang);
            for (ResourcePackInfo info : InteractiveChatDiscordSrvAddon.plugin.resourceManager.getResourcePackInfo()) {
                String name = info.getName();
                if (info.getStatus()) {
                    Component component = Component.text(" - " + name).color(info.comparePackFormat() == 0 ? NamedTextColor.GREEN : NamedTextColor.YELLOW);
                    Component hoverComponent = info.getDescription();
                    if (info.comparePackFormat() > 0) {
                        hoverComponent = hoverComponent.append(LegacyComponentSerializer.legacySection().deserialize("\n" + ChatColor.YELLOW + LanguageUtils.getTranslation(TranslationKeyUtils.getNewIncompatiblePack(), InteractiveChatDiscordSrvAddon.plugin.language)));
                    } else if (info.comparePackFormat() < 0) {
                        hoverComponent = hoverComponent.append(LegacyComponentSerializer.legacySection().deserialize("\n" + ChatColor.YELLOW + LanguageUtils.getTranslation(TranslationKeyUtils.getOldIncompatiblePack(), InteractiveChatDiscordSrvAddon.plugin.language)));
                    }
                    component = component.hoverEvent(HoverEvent.showText(hoverComponent));
                    InteractiveChatAPI.sendMessage(sender, component);
                    if (!(sender instanceof Player)) {
                        for (Component each : ComponentStyling.splitAtLineBreaks(info.getDescription())) {
                            InteractiveChatAPI.sendMessage(sender, Component.text("   - ").color(NamedTextColor.GRAY).append(each));
                            if (info.comparePackFormat() > 0) {
                                sender.sendMessage(ChatColor.YELLOW + "     " + LanguageUtils.getTranslation(TranslationKeyUtils.getNewIncompatiblePack(), InteractiveChatDiscordSrvAddon.plugin.language));
                            } else if (info.comparePackFormat() < 0) {
                                sender.sendMessage(ChatColor.YELLOW + "     " + LanguageUtils.getTranslation(TranslationKeyUtils.getOldIncompatiblePack(), InteractiveChatDiscordSrvAddon.plugin.language));
                            }
                        }
                    }
                } else {
                    Component component = Component.text(" - " + name).color(NamedTextColor.RED);
                    if (info.getRejectedReason() != null) {
                        component = component.hoverEvent(HoverEvent.showText(Component.text(info.getRejectedReason()).color(NamedTextColor.RED)));
                    }
                    InteractiveChatAPI.sendMessage(sender, component);
                    if (!(sender instanceof Player)) {
                        InteractiveChatAPI.sendMessage(sender, Component.text("   - ").append(Component.text(info.getRejectedReason()).color(NamedTextColor.RED)).color(NamedTextColor.RED));
                    }
                }
            }
        } else {
            sender.sendMessage(InteractiveChat.noPermissionMessage);
        }
        return true;
    }
    if (args[0].equalsIgnoreCase("reloadconfig")) {
        if (sender.hasPermission("interactivechatdiscordsrv.reloadconfig")) {
            try {
                if (InteractiveChatDiscordSrvAddon.plugin.resourceReloadLock.tryLock(0, TimeUnit.MILLISECONDS)) {
                    try {
                        InteractiveChatDiscordSrvAddon.plugin.reloadConfig();
                        Bukkit.getPluginManager().callEvent(new InteractiveChatDiscordSRVConfigReloadEvent());
                        sender.sendMessage(InteractiveChatDiscordSrvAddon.plugin.reloadConfigMessage);
                    } catch (Throwable e) {
                        e.printStackTrace();
                    }
                    InteractiveChatDiscordSrvAddon.plugin.resourceReloadLock.unlock();
                } else {
                    sender.sendMessage(ChatColor.YELLOW + "Resource reloading in progress, please wait!");
                }
            } catch (IllegalStateException | InterruptedException e) {
            }
        } else {
            sender.sendMessage(InteractiveChat.noPermissionMessage);
        }
        return true;
    }
    if (args[0].equalsIgnoreCase("reloadtexture")) {
        List<String> argList = Arrays.asList(args);
        boolean clean = argList.contains("--reset");
        boolean redownload = argList.contains("--redownload") || clean;
        if (sender.hasPermission("interactivechatdiscordsrv.reloadtexture")) {
            sender.sendMessage(InteractiveChatDiscordSrvAddon.plugin.reloadTextureMessage);
            InteractiveChatDiscordSrvAddon.plugin.reloadTextures(redownload, clean, sender);
        } else {
            sender.sendMessage(InteractiveChat.noPermissionMessage);
        }
        return true;
    }
    if (args[0].equalsIgnoreCase("update")) {
        if (sender.hasPermission("interactivechatdiscordsrv.update")) {
            sender.sendMessage(ChatColor.AQUA + "[ICDiscordSrvAddon] InteractiveChat DiscordSRV Addon written by LOOHP!");
            sender.sendMessage(ChatColor.GOLD + "[ICDiscordSrvAddon] You are running ICDiscordSRVAddon version: " + InteractiveChatDiscordSrvAddon.plugin.getDescription().getVersion());
            Bukkit.getScheduler().runTaskAsynchronously(InteractiveChatDiscordSrvAddon.plugin, () -> {
                UpdaterResponse version = Updater.checkUpdate();
                if (version.getResult().equals("latest")) {
                    if (version.isDevBuildLatest()) {
                        sender.sendMessage(ChatColor.GREEN + "[ICDiscordSrvAddon] You are running the latest version!");
                    } else {
                        Updater.sendUpdateMessage(sender, version.getResult(), version.getSpigotPluginId(), true);
                    }
                } else {
                    Updater.sendUpdateMessage(sender, version.getResult(), version.getSpigotPluginId());
                }
            });
        } else {
            sender.sendMessage(InteractiveChat.noPermissionMessage);
        }
        return true;
    }
    if (args[0].equalsIgnoreCase("imagemap")) {
        if (args.length > 1 && sender instanceof Player) {
            try {
                DiscordAttachmentData data = InboundToGameEvents.DATA.get(UUID.fromString(args[1]));
                if (data != null && (data.isImage() || data.isVideo())) {
                    GraphicsToPacketMapWrapper imageMap = data.getImageMap();
                    if (imageMap.futureCancelled()) {
                        sender.sendMessage(InteractiveChatDiscordSrvAddon.plugin.linkExpired);
                    } else if (imageMap.futureCompleted()) {
                        imageMap.show((Player) sender);
                    } else {
                        sender.sendMessage(InteractiveChatDiscordSrvAddon.plugin.previewLoading);
                    }
                } else {
                    sender.sendMessage(InteractiveChatDiscordSrvAddon.plugin.linkExpired);
                }
            } catch (Exception e) {
                sender.sendMessage(InteractiveChatDiscordSrvAddon.plugin.linkExpired);
            }
        }
        return true;
    }
    sender.sendMessage(ChatColorUtils.translateAlternateColorCodes('&', Bukkit.spigot().getConfig().getString("messages.unknown-command")));
    return true;
}
Also used : Player(org.bukkit.entity.Player) DiscordAttachmentData(com.loohp.interactivechatdiscordsrvaddon.listeners.InboundToGameEvents.DiscordAttachmentData) UpdaterResponse(com.loohp.interactivechatdiscordsrvaddon.updater.Updater.UpdaterResponse) ResourcePackInfo(com.loohp.interactivechatdiscordsrvaddon.resources.ResourcePackInfo) InteractiveChatDiscordSRVConfigReloadEvent(com.loohp.interactivechatdiscordsrvaddon.api.events.InteractiveChatDiscordSRVConfigReloadEvent) Component(com.loohp.interactivechat.libs.net.kyori.adventure.text.Component) GraphicsToPacketMapWrapper(com.loohp.interactivechatdiscordsrvaddon.wrappers.GraphicsToPacketMapWrapper)

Example 5 with ResourcePackInfo

use of com.loohp.interactivechatdiscordsrvaddon.resources.ResourcePackInfo 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

ResourcePackInfo (com.loohp.interactivechatdiscordsrvaddon.resources.ResourcePackInfo)5 IOException (java.io.IOException)4 Component (com.loohp.interactivechat.libs.net.kyori.adventure.text.Component)3 ChatColorUtils (com.loohp.interactivechat.utils.ChatColorUtils)3 ImageUtils (com.loohp.interactivechatdiscordsrvaddon.graphics.ImageUtils)3 Color (java.awt.Color)3 InteractiveChat (com.loohp.interactivechat.InteractiveChat)2 YamlConfiguration (com.loohp.interactivechat.libs.com.loohp.yamlconfiguration.YamlConfiguration)2 ICPlayer (com.loohp.interactivechat.objectholders.ICPlayer)2 ICPlayerFactory (com.loohp.interactivechat.objectholders.ICPlayerFactory)2 ColorUtils (com.loohp.interactivechat.utils.ColorUtils)2 LanguageUtils (com.loohp.interactivechat.utils.LanguageUtils)2 SkinUtils (com.loohp.interactivechat.utils.SkinUtils)2 InteractiveChatDiscordSRVConfigReloadEvent (com.loohp.interactivechatdiscordsrvaddon.api.events.InteractiveChatDiscordSRVConfigReloadEvent)2 ImageGeneration (com.loohp.interactivechatdiscordsrvaddon.graphics.ImageGeneration)2 ResourceManager (com.loohp.interactivechatdiscordsrvaddon.resources.ResourceManager)2 DiscordSRV (github.scarsz.discordsrv.DiscordSRV)2 BufferedImage (java.awt.image.BufferedImage)2 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 File (java.io.File)2