Search in sources :

Example 1 with ICPlayer

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

the class InteractiveChatDiscordSrvAddon method onEnable.

@Override
public void onEnable() {
    plugin = this;
    interactivechat = InteractiveChat.plugin;
    discordsrv = DiscordSRV.getPlugin();
    if (!getDataFolder().exists()) {
        getDataFolder().mkdirs();
    }
    AssetsDownloader.loadLibraries(getDataFolder());
    try {
        Config.loadConfig(CONFIG_ID, new File(getDataFolder(), "config.yml"), getClass().getClassLoader().getResourceAsStream("config.yml"), getClass().getClassLoader().getResourceAsStream("config.yml"), true);
    } catch (IOException e) {
        e.printStackTrace();
        getServer().getPluginManager().disablePlugin(this);
        return;
    }
    reloadConfig();
    metrics = new Metrics(this, BSTATS_PLUGIN_ID);
    Charts.setup(metrics);
    DiscordSRV.api.subscribe(new DiscordReadyEvents());
    DiscordSRV.api.subscribe(new OutboundToDiscordEvents());
    DiscordSRV.api.subscribe(new InboundToGameEvents());
    getServer().getPluginManager().registerEvents(this, this);
    getServer().getPluginManager().registerEvents(new InboundToGameEvents(), this);
    getServer().getPluginManager().registerEvents(new OutboundToDiscordEvents(), this);
    getServer().getPluginManager().registerEvents(new ICPlayerEvents(), this);
    getServer().getPluginManager().registerEvents(new Debug(), this);
    getServer().getPluginManager().registerEvents(new Updater(), this);
    getCommand("interactivechatdiscordsrv").setExecutor(new Commands());
    File resourcepacks = new File(getDataFolder(), "resourcepacks");
    if (!resourcepacks.exists()) {
        File resources = new File(getDataFolder(), "resources");
        if (resources.exists() && resources.isDirectory()) {
            try {
                Files.move(resources.toPath(), resourcepacks.toPath(), StandardCopyOption.ATOMIC_MOVE);
            } catch (IOException e) {
                getServer().getConsoleSender().sendMessage(ChatColor.RED + "[ICDiscordSrvAddon] Unable to move folder, are any files opened?");
                e.printStackTrace();
                getServer().getPluginManager().disablePlugin(this);
                return;
            }
        } else {
            resourcepacks.mkdirs();
        }
    }
    if (!compatible()) {
        for (int i = 0; i < 10; i++) {
            getServer().getConsoleSender().sendMessage(ChatColor.RED + "[ICDiscordSrvAddon] VERSION NOT COMPATIBLE WITH INSTALLED INTERACTIVECHAT VERSION, PLEASE UPDATE BOTH TO LATEST!!!!");
        }
        getServer().getPluginManager().disablePlugin(this);
        return;
    } else {
        getServer().getConsoleSender().sendMessage(ChatColor.GREEN + "[ICDiscordSrvAddon] InteractiveChat DiscordSRV Addon has been Enabled!");
    }
    reloadTextures(false, false);
    modelRenderer = new ModelRenderer(str -> new ThreadFactoryBuilder().setNameFormat(str).build(), () -> InteractiveChatDiscordSrvAddon.plugin.cacheTimeout, image -> ImageGeneration.getEnchantedImage(image), image -> ImageGeneration.getRawEnchantedImage(image), () -> 8, () -> Runtime.getRuntime().availableProcessors());
    ThreadFactory factory = new ThreadFactoryBuilder().setNameFormat("InteractiveChatDiscordSRVAddon Async Media Reading Thread #%d").build();
    mediaReadingService = Executors.newFixedThreadPool(4, factory);
    Bukkit.getScheduler().runTaskTimerAsynchronously(this, () -> {
        for (ICPlayer player : ICPlayerFactory.getOnlineICPlayers()) {
            cachePlayerSkin(player);
        }
        AssetsDownloader.loadExtras();
    }, 600, 6000);
}
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) ThreadFactory(java.util.concurrent.ThreadFactory) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) DiscordReadyEvents(com.loohp.interactivechatdiscordsrvaddon.listeners.DiscordReadyEvents) OutboundToDiscordEvents(com.loohp.interactivechatdiscordsrvaddon.listeners.OutboundToDiscordEvents) ICPlayerEvents(com.loohp.interactivechatdiscordsrvaddon.listeners.ICPlayerEvents) IOException(java.io.IOException) InboundToGameEvents(com.loohp.interactivechatdiscordsrvaddon.listeners.InboundToGameEvents) Metrics(com.loohp.interactivechatdiscordsrvaddon.metrics.Metrics) ModelRenderer(com.loohp.interactivechatdiscordsrvaddon.resources.ModelRenderer) Updater(com.loohp.interactivechatdiscordsrvaddon.updater.Updater) ThreadFactoryBuilder(com.google.common.util.concurrent.ThreadFactoryBuilder) File(java.io.File) Debug(com.loohp.interactivechatdiscordsrvaddon.debug.Debug)

Example 2 with ICPlayer

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

the class OutboundToDiscordEvents method onVentureChatHookToDiscord.

@Subscribe(priority = ListenerPriority.HIGHEST)
public void onVentureChatHookToDiscord(VentureChatMessagePreProcessEvent event) {
    ICPlayer icSender = null;
    MineverseChatPlayer mcPlayer = event.getVentureChatEvent().getMineverseChatPlayer();
    if (mcPlayer != null) {
        icSender = ICPlayerFactory.getICPlayer(mcPlayer.getUUID());
    } else {
        icSender = ICPlayerFactory.getICPlayerExact(event.getVentureChatEvent().getUsername());
    }
    if (icSender == null) {
        return;
    }
    Component message = ComponentStringUtils.toRegularComponent(event.getMessageComponent());
    message = processGameMessage(icSender, message);
    event.setMessageComponent(ComponentStringUtils.toDiscordSRVComponent(message));
}
Also used : ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) MineverseChatPlayer(mineverse.Aust1n46.chat.api.MineverseChatPlayer) Component(com.loohp.interactivechat.libs.net.kyori.adventure.text.Component) Subscribe(github.scarsz.discordsrv.api.Subscribe)

Example 3 with ICPlayer

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

the class PlayernameDisplay method processPlayer.

private static Component processPlayer(String placeholder, ICPlayer player, Optional<ICPlayer> sender, Player receiver, Component component, long unix) {
    String plain = InteractiveChatComponentSerializer.plainText().serialize(component);
    if (InteractiveChat.usePlayerNameCaseSensitive) {
        if (!plain.contains(placeholder)) {
            return component;
        }
    } else {
        if (!plain.toLowerCase().contains(placeholder.toLowerCase())) {
            return component;
        }
    }
    HoverEvent<?> hoverEvent;
    ClickEvent clickEvent;
    if (InteractiveChat.usePlayerNameHoverEnable) {
        String playertext = ChatColorUtils.translateAlternateColorCodes('&', PlaceholderParser.parse(player, InteractiveChat.usePlayerNameHoverText));
        hoverEvent = HoverEvent.showText(LegacyComponentSerializer.legacySection().deserialize(playertext));
    } else {
        hoverEvent = null;
    }
    if (InteractiveChat.usePlayerNameClickEnable) {
        String playertext = PlaceholderParser.parse(player, InteractiveChat.usePlayerNameClickValue);
        clickEvent = ClickEvent.clickEvent(ClickEvent.Action.valueOf(InteractiveChat.usePlayerNameClickAction), playertext);
    } else {
        clickEvent = null;
    }
    String regex = InteractiveChat.usePlayerNameCaseSensitive ? CustomStringUtils.escapeMetaCharacters(placeholder) : "(?i)" + CustomStringUtils.escapeMetaCharacters(placeholder);
    component = ComponentReplacing.replace(component, regex, true, (result, replaced) -> {
        List<Component> children = new ArrayList<>();
        for (Component c : replaced) {
            Component edited = c;
            if (hoverEvent != null && (InteractiveChat.usePlayerNameOverrideHover || edited.hoverEvent() == null)) {
                edited = edited.hoverEvent(hoverEvent);
            }
            if (clickEvent != null && (InteractiveChat.usePlayerNameOverrideClick || edited.clickEvent() == null)) {
                edited = edited.clickEvent(clickEvent);
            }
            children.add(edited);
        }
        return Component.empty().children(children);
    });
    List<Component> children = new ArrayList<>(component.children());
    for (int i = 0; i < children.size(); i++) {
        Component child = children.get(i);
        if (child instanceof TranslatableComponent) {
            TranslatableComponent trans = (TranslatableComponent) child;
            List<Component> withs = new ArrayList<>(trans.args());
            for (int u = 0; u < withs.size(); u++) {
                Component with = withs.get(u);
                withs.set(u, processPlayer(placeholder, player, sender, receiver, with, unix));
            }
            trans = trans.args(withs);
            children.set(i, trans);
        }
    }
    return ComponentCompacting.optimize(component.children(children));
}
Also used : VanishUtils(com.loohp.interactivechat.utils.VanishUtils) ComponentReplacing(com.loohp.interactivechat.utils.ComponentReplacing) ComponentCompacting(com.loohp.interactivechat.utils.ComponentCompacting) ReplaceTextBundle(com.loohp.interactivechat.objectholders.ReplaceTextBundle) InteractiveChatAPI(com.loohp.interactivechat.api.InteractiveChatAPI) Random(java.util.Random) ClickEvent(net.kyori.adventure.text.event.ClickEvent) Player(org.bukkit.entity.Player) TranslatableComponent(net.kyori.adventure.text.TranslatableComponent) ArrayList(java.util.ArrayList) EventHandler(org.bukkit.event.EventHandler) ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) InteractiveChatComponentSerializer(com.loohp.interactivechat.utils.InteractiveChatComponentSerializer) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Component(net.kyori.adventure.text.Component) CollectionUtils(com.loohp.interactivechat.utils.CollectionUtils) LegacyComponentSerializer(net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer) LinkedHashSet(java.util.LinkedHashSet) Bukkit(org.bukkit.Bukkit) Listener(org.bukkit.event.Listener) PlayerLoginEvent(org.bukkit.event.player.PlayerLoginEvent) Collection(java.util.Collection) InteractiveChat(com.loohp.interactivechat.InteractiveChat) List(java.util.List) EventPriority(org.bukkit.event.EventPriority) ICPlayerFactory(com.loohp.interactivechat.objectholders.ICPlayerFactory) ChatColorUtils(com.loohp.interactivechat.utils.ChatColorUtils) PlayerQuitEvent(org.bukkit.event.player.PlayerQuitEvent) CustomStringUtils(com.loohp.interactivechat.utils.CustomStringUtils) Optional(java.util.Optional) PlaceholderParser(com.loohp.interactivechat.utils.PlaceholderParser) HoverEvent(net.kyori.adventure.text.event.HoverEvent) Collections(java.util.Collections) TranslatableComponent(net.kyori.adventure.text.TranslatableComponent) ClickEvent(net.kyori.adventure.text.event.ClickEvent) ArrayList(java.util.ArrayList) ArrayList(java.util.ArrayList) List(java.util.List) TranslatableComponent(net.kyori.adventure.text.TranslatableComponent) Component(net.kyori.adventure.text.Component)

Example 4 with ICPlayer

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

the class Commands method onCommand.

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

Example 5 with ICPlayer

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

the class ChatEvents method checkMentionPlayers.

private String checkMentionPlayers(String senderTagType, String message, Player sender) {
    boolean senderTagged = Registry.ID_PATTERN.matcher(message).find();
    if (PlayerUtils.hasPermission(sender.getUniqueId(), "interactivechat.mention.player", false, 200)) {
        Map<String, UUID> playernames = new HashMap<>();
        for (ICPlayer player : ICPlayerFactory.getOnlineICPlayers()) {
            playernames.put(ChatColorUtils.stripColor(player.getName()), player.getUniqueId());
            if (InteractiveChat.useBukkitDisplayName && !ChatColorUtils.stripColor(player.getName()).equals(ChatColorUtils.stripColor(player.getDisplayName()))) {
                playernames.put(ChatColorUtils.stripColor(player.getDisplayName()), player.getUniqueId());
            }
            List<String> names = InteractiveChatAPI.getNicknames(player.getUniqueId());
            for (String name : names) {
                playernames.put(ChatColorUtils.stripColor(name), player.getUniqueId());
            }
        }
        for (Entry<String, UUID> entry : playernames.entrySet()) {
            String name = InteractiveChat.mentionPrefix + entry.getKey();
            UUID uuid = entry.getValue();
            int index = message.toLowerCase().indexOf(name.toLowerCase());
            if (index >= 0) {
                if (senderTagged) {
                    message = Registry.MENTION_TAG_CONVERTER.convertToTag(name, message);
                } else {
                    String tagStyle = Registry.MENTION_TAG_CONVERTER.getTagStyle(name);
                    String uuidmatch = "<" + senderTagType + "=" + sender.getUniqueId() + ":" + Registry.ID_ESCAPE_PATTERN.matcher(tagStyle).replaceAll("\\>") + ":>";
                    message = message.replace(name, uuidmatch);
                }
                if (!uuid.equals(sender.getUniqueId())) {
                    InteractiveChat.mentionPair.add(new MentionPair(sender.getUniqueId(), uuid));
                    if (InteractiveChat.bungeecordMode) {
                        try {
                            BungeeMessageSender.forwardMentionPair(System.currentTimeMillis(), sender.getUniqueId(), uuid);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
                return message;
            }
        }
    }
    return null;
}
Also used : ICPlayer(com.loohp.interactivechat.objectholders.ICPlayer) HashMap(java.util.HashMap) MentionPair(com.loohp.interactivechat.objectholders.MentionPair) UUID(java.util.UUID)

Aggregations

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