Search in sources :

Example 1 with ThrowingSupplier

use of com.loohp.interactivechatdiscordsrvaddon.utils.ThrowingSupplier in project InteractiveChat-DiscordSRV-Addon by LOOHP.

the class InboundToGameEvents method onReceiveMessageFromDiscordPost.

@Subscribe(priority = ListenerPriority.HIGH)
public void onReceiveMessageFromDiscordPost(DiscordGuildMessagePostProcessEvent event) {
    Debug.debug("Triggering onReceiveMessageFromDiscordPost");
    Message message = event.getMessage();
    github.scarsz.discordsrv.dependencies.kyori.adventure.text.Component component = event.getMinecraftMessage();
    DiscordSRV srv = InteractiveChatDiscordSrvAddon.discordsrv;
    User author = message.getAuthor();
    if (InteractiveChatDiscordSrvAddon.plugin.translateMentions) {
        Debug.debug("onReceiveMessageFromDiscordPost translating mentions");
        Set<UUID> mentionTitleSent = new HashSet<>();
        Map<Member, UUID> channelMembers = new HashMap<>();
        TextChannel channel = event.getChannel();
        Guild guild = channel.getGuild();
        Member authorAsMember = guild.getMember(author);
        String senderDiscordName = authorAsMember == null ? author.getName() : authorAsMember.getEffectiveName();
        UUID senderUUID = srv.getAccountLinkManager().getUuid(author.getId());
        for (Entry<UUID, String> entry : srv.getAccountLinkManager().getManyDiscordIds(Bukkit.getOnlinePlayers().stream().map(each -> each.getUniqueId()).collect(Collectors.toSet())).entrySet()) {
            Member member = guild.getMemberById(entry.getValue());
            if (member != null && member.hasAccess(channel)) {
                channelMembers.put(member, entry.getKey());
            }
        }
        if (message.mentionsEveryone()) {
            // github.scarsz.discordsrv.dependencies.kyori.adventure.text.event.HoverEvent<Component> hover = Component.text(InteractiveChatDiscordSrvAddon.plugin.mentionHover.replace("{DiscordUser}", senderDiscordName).replace("{TextChannel}", "#" + channel.getName()).replace("{Guild}", guild.getName())).asHoverEvent();
            component = component.replaceText(github.scarsz.discordsrv.dependencies.kyori.adventure.text.TextReplacementConfig.builder().matchLiteral("@here").replacement(github.scarsz.discordsrv.dependencies.kyori.adventure.text.Component.text(InteractiveChatDiscordSrvAddon.plugin.mentionHighlight.replace("{DiscordMention}", "@here"))).build()).replaceText(github.scarsz.discordsrv.dependencies.kyori.adventure.text.TextReplacementConfig.builder().matchLiteral("@everyone").replacement(github.scarsz.discordsrv.dependencies.kyori.adventure.text.Component.text(InteractiveChatDiscordSrvAddon.plugin.mentionHighlight.replace("{DiscordMention}", "@everyone"))).build());
            for (UUID uuid : channelMembers.values()) {
                mentionTitleSent.add(uuid);
                Player player = Bukkit.getPlayer(uuid);
                if (player != null) {
                    DiscordToGameMention.playTitleScreen(senderDiscordName, channel.getName(), guild.getName(), player);
                }
            }
        }
        List<Role> mentionedRoles = message.getMentionedRoles();
        for (Role role : mentionedRoles) {
            // github.scarsz.discordsrv.dependencies.kyori.adventure.text.event.HoverEvent<Component> hover = Component.text(InteractiveChatDiscordSrvAddon.plugin.mentionHover.replace("{DiscordUser}", senderDiscordName).replace("{TextChannel}", "#" + channel.getName()).replace("{Guild}", guild.getName())).asHoverEvent();
            component = component.replaceText(github.scarsz.discordsrv.dependencies.kyori.adventure.text.TextReplacementConfig.builder().matchLiteral("@" + role.getName()).replacement(github.scarsz.discordsrv.dependencies.kyori.adventure.text.Component.text(InteractiveChatDiscordSrvAddon.plugin.mentionHighlight.replace("{DiscordMention}", "@" + role.getName()))).build());
            for (Entry<Member, UUID> entry : channelMembers.entrySet()) {
                UUID uuid = entry.getValue();
                if (!mentionTitleSent.contains(uuid) && entry.getKey().getRoles().contains(role)) {
                    mentionTitleSent.add(uuid);
                    Player player = Bukkit.getPlayer(uuid);
                    if (player != null) {
                        DiscordToGameMention.playTitleScreen(senderDiscordName, channel.getName(), guild.getName(), player);
                    }
                }
            }
        }
        List<User> mentionedUsers = message.getMentionedUsers();
        if (!mentionedUsers.isEmpty()) {
            for (User user : mentionedUsers) {
                // github.scarsz.discordsrv.dependencies.kyori.adventure.text.event.HoverEvent<Component> hover = Component.text(InteractiveChatDiscordSrvAddon.plugin.mentionHover.replace("{DiscordUser}", senderDiscordName).replace("{TextChannel}", "#" + channel.getName()).replace("{Guild}", guild.getName())).asHoverEvent();
                component = component.replaceText(github.scarsz.discordsrv.dependencies.kyori.adventure.text.TextReplacementConfig.builder().matchLiteral("@" + user.getName()).replacement(github.scarsz.discordsrv.dependencies.kyori.adventure.text.Component.text(InteractiveChatDiscordSrvAddon.plugin.mentionHighlight.replace("{DiscordMention}", "@" + user.getName()))).build());
                Member member = guild.getMember(user);
                if (member != null) {
                    UUID uuid = channelMembers.get(member);
                    if (uuid != null && !mentionTitleSent.contains(uuid) && (senderUUID == null || !senderUUID.equals(uuid))) {
                        mentionTitleSent.add(uuid);
                        Player player = Bukkit.getPlayer(uuid);
                        if (player != null) {
                            DiscordToGameMention.playTitleScreen(senderDiscordName, channel.getName(), guild.getName(), player);
                        }
                    }
                }
            }
        }
        event.setMinecraftMessage(component);
    }
    String processedMessage = MessageUtil.toLegacy(component);
    if (InteractiveChatDiscordSrvAddon.plugin.convertDiscordAttachments) {
        Debug.debug("onReceiveMessageFromDiscordPre converting discord attachments");
        Set<String> processedUrl = new HashSet<>();
        for (Attachment attachment : message.getAttachments()) {
            InteractiveChatDiscordSrvAddon.plugin.attachmentCounter.incrementAndGet();
            String url = attachment.getUrl();
            if (processedMessage.contains(url)) {
                processedUrl.add(url);
                if ((attachment.isImage() || attachment.isVideo()) && attachment.getSize() <= InteractiveChatDiscordSrvAddon.plugin.discordAttachmentsPreviewLimit) {
                    InteractiveChatDiscordSrvAddon.plugin.attachmentImageCounter.incrementAndGet();
                    List<ThrowingSupplier<InputStream>> methods = new ArrayList<>();
                    methods.add(() -> attachment.retrieveInputStream().get());
                    if (URLRequestUtils.isAllowed(attachment.getUrl())) {
                        methods.add(() -> URLRequestUtils.getInputStream0(attachment.getUrl()));
                    }
                    if (URLRequestUtils.isAllowed(attachment.getProxyUrl())) {
                        methods.add(() -> URLRequestUtils.getInputStream0(attachment.getProxyUrl()));
                    }
                    try (InputStream stream = URLRequestUtils.retrieveInputStreamUntilSuccessful(methods)) {
                        GraphicsToPacketMapWrapper map;
                        boolean isVideo = false;
                        if (url.toLowerCase().endsWith(".gif")) {
                            map = new GraphicsToPacketMapWrapper(InteractiveChatDiscordSrvAddon.plugin.playbackBarEnabled, InteractiveChatDiscordSrvAddon.plugin.discordAttachmentsMapBackgroundColor);
                            GifReader.readGif(stream, InteractiveChatDiscordSrvAddon.plugin.mediaReadingService, (frames, e) -> {
                                if (e != null) {
                                    e.printStackTrace();
                                    map.completeFuture(null);
                                } else {
                                    map.completeFuture(frames);
                                }
                            });
                        } else {
                            BufferedImage image = ImageIO.read(stream);
                            map = new GraphicsToPacketMapWrapper(image, InteractiveChatDiscordSrvAddon.plugin.discordAttachmentsMapBackgroundColor);
                        }
                        DiscordAttachmentData data = new DiscordAttachmentData(attachment.getFileName(), url, map, isVideo);
                        DiscordAttachmentConversionEvent dace = new DiscordAttachmentConversionEvent(url, data);
                        Bukkit.getPluginManager().callEvent(dace);
                        DATA.put(data.getUniqueId(), data);
                        Bukkit.getScheduler().runTaskLater(InteractiveChatDiscordSrvAddon.plugin, () -> DATA.remove(data.getUniqueId()), InteractiveChatDiscordSrvAddon.plugin.discordAttachmentTimeout);
                    } catch (IOException e) {
                        e.printStackTrace();
                        DiscordAttachmentData data = new DiscordAttachmentData(attachment.getFileName(), url);
                        DiscordAttachmentConversionEvent dace = new DiscordAttachmentConversionEvent(url, data);
                        Bukkit.getPluginManager().callEvent(dace);
                        DATA.put(data.getUniqueId(), data);
                        Bukkit.getScheduler().runTaskLater(InteractiveChatDiscordSrvAddon.plugin, () -> DATA.remove(data.getUniqueId()), InteractiveChatDiscordSrvAddon.plugin.discordAttachmentTimeout);
                    }
                } else {
                    DiscordAttachmentData data = new DiscordAttachmentData(attachment.getFileName(), url);
                    DiscordAttachmentConversionEvent dace = new DiscordAttachmentConversionEvent(url, data);
                    Bukkit.getPluginManager().callEvent(dace);
                    DATA.put(data.getUniqueId(), data);
                    Bukkit.getScheduler().runTaskLater(InteractiveChatDiscordSrvAddon.plugin, () -> DATA.remove(data.getUniqueId()), InteractiveChatDiscordSrvAddon.plugin.discordAttachmentTimeout);
                }
            }
        }
        Matcher matcher = URLRequestUtils.IMAGE_URL_PATTERN.matcher(message.getContentRaw());
        while (matcher.find()) {
            String url = matcher.group();
            String extension = matcher.group(1);
            if (!processedUrl.contains(url) && URLRequestUtils.isAllowed(url)) {
                long size = HTTPRequestUtils.getContentSize(url);
                if (size >= 0 && size <= InteractiveChatDiscordSrvAddon.plugin.discordAttachmentsPreviewLimit) {
                    InteractiveChatDiscordSrvAddon.plugin.attachmentImageCounter.incrementAndGet();
                    try (InputStream stream = URLRequestUtils.getInputStream(url)) {
                        GraphicsToPacketMapWrapper map;
                        boolean isVideo = false;
                        if (extension.equals("gif")) {
                            map = new GraphicsToPacketMapWrapper(InteractiveChatDiscordSrvAddon.plugin.playbackBarEnabled, InteractiveChatDiscordSrvAddon.plugin.discordAttachmentsMapBackgroundColor);
                            GifReader.readGif(stream, InteractiveChatDiscordSrvAddon.plugin.mediaReadingService, (frames, e) -> {
                                if (e != null) {
                                    e.printStackTrace();
                                    map.completeFuture(null);
                                } else {
                                    map.completeFuture(frames);
                                }
                            });
                        } else {
                            BufferedImage image = ImageIO.read(stream);
                            map = new GraphicsToPacketMapWrapper(image, InteractiveChatDiscordSrvAddon.plugin.discordAttachmentsMapBackgroundColor);
                        }
                        int end = matcher.end(1);
                        String name = url.lastIndexOf("/") < 0 ? url.substring(0, end) : url.substring(url.lastIndexOf("/") + 1, end);
                        DiscordAttachmentData data = new DiscordAttachmentData(name, url, map, isVideo);
                        DiscordAttachmentConversionEvent dace = new DiscordAttachmentConversionEvent(url, data);
                        Bukkit.getPluginManager().callEvent(dace);
                        DATA.put(data.getUniqueId(), data);
                        Bukkit.getScheduler().runTaskLater(InteractiveChatDiscordSrvAddon.plugin, () -> DATA.remove(data.getUniqueId()), InteractiveChatDiscordSrvAddon.plugin.discordAttachmentTimeout);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
Also used : ComponentReplacing(com.loohp.interactivechat.utils.ComponentReplacing) TextChannel(github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel) GifReader(com.loohp.interactivechatdiscordsrvaddon.graphics.GifReader) Player(org.bukkit.entity.Player) EventHandler(org.bukkit.event.EventHandler) Matcher(java.util.regex.Matcher) Map(java.util.Map) ImageIO(javax.imageio.ImageIO) ThrowingSupplier(com.loohp.interactivechatdiscordsrvaddon.utils.ThrowingSupplier) EntityDamageByEntityEvent(org.bukkit.event.entity.EntityDamageByEntityEvent) Debug(com.loohp.interactivechatdiscordsrvaddon.debug.Debug) Bukkit(org.bukkit.Bukkit) Message(github.scarsz.discordsrv.dependencies.jda.api.entities.Message) Guild(github.scarsz.discordsrv.dependencies.jda.api.entities.Guild) Entity(org.bukkit.entity.Entity) BufferedImage(java.awt.image.BufferedImage) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) InventoryClickEvent(org.bukkit.event.inventory.InventoryClickEvent) Set(java.util.Set) ClickEvent(com.loohp.interactivechat.libs.net.kyori.adventure.text.event.ClickEvent) DiscordAttachmentConversionEvent(com.loohp.interactivechatdiscordsrvaddon.api.events.DiscordAttachmentConversionEvent) Attachment(github.scarsz.discordsrv.dependencies.jda.api.entities.Message.Attachment) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) ItemStack(org.bukkit.inventory.ItemStack) Subscribe(github.scarsz.discordsrv.api.Subscribe) List(java.util.List) HTTPRequestUtils(com.loohp.interactivechat.utils.HTTPRequestUtils) InventoryOpenEvent(org.bukkit.event.inventory.InventoryOpenEvent) ListenerPriority(github.scarsz.discordsrv.api.ListenerPriority) PlayerQuitEvent(org.bukkit.event.player.PlayerQuitEvent) CustomStringUtils(com.loohp.interactivechat.utils.CustomStringUtils) Entry(java.util.Map.Entry) PrePacketComponentProcessEvent(com.loohp.interactivechat.api.events.PrePacketComponentProcessEvent) Pattern(java.util.regex.Pattern) GraphicsToPacketMapWrapper(com.loohp.interactivechatdiscordsrvaddon.wrappers.GraphicsToPacketMapWrapper) DiscordGuildMessagePostProcessEvent(github.scarsz.discordsrv.api.events.DiscordGuildMessagePostProcessEvent) DiscordGuildMessagePreProcessEvent(github.scarsz.discordsrv.api.events.DiscordGuildMessagePreProcessEvent) HoverEvent(com.loohp.interactivechat.libs.net.kyori.adventure.text.event.HoverEvent) HashMap(java.util.HashMap) Action(org.bukkit.event.block.Action) InteractiveChatDiscordSrvAddon(com.loohp.interactivechatdiscordsrvaddon.InteractiveChatDiscordSrvAddon) MessageUtil(github.scarsz.discordsrv.util.MessageUtil) ArrayList(java.util.ArrayList) InventoryCreativeEvent(org.bukkit.event.inventory.InventoryCreativeEvent) HashSet(java.util.HashSet) GameMode(org.bukkit.GameMode) DiscordSRV(github.scarsz.discordsrv.DiscordSRV) DiscordToGameMention(com.loohp.interactivechatdiscordsrvaddon.modules.DiscordToGameMention) PlayerInteractEvent(org.bukkit.event.player.PlayerInteractEvent) Listener(org.bukkit.event.Listener) User(github.scarsz.discordsrv.dependencies.jda.api.entities.User) Component(com.loohp.interactivechat.libs.net.kyori.adventure.text.Component) IOException(java.io.IOException) PlayerItemHeldEvent(org.bukkit.event.player.PlayerItemHeldEvent) URLRequestUtils(com.loohp.interactivechatdiscordsrvaddon.utils.URLRequestUtils) Role(github.scarsz.discordsrv.dependencies.jda.api.entities.Role) Member(github.scarsz.discordsrv.dependencies.jda.api.entities.Member) LegacyComponentSerializer(com.loohp.interactivechat.libs.net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer) InputStream(java.io.InputStream) User(github.scarsz.discordsrv.dependencies.jda.api.entities.User) Message(github.scarsz.discordsrv.dependencies.jda.api.entities.Message) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) Attachment(github.scarsz.discordsrv.dependencies.jda.api.entities.Message.Attachment) ThrowingSupplier(com.loohp.interactivechatdiscordsrvaddon.utils.ThrowingSupplier) Guild(github.scarsz.discordsrv.dependencies.jda.api.entities.Guild) BufferedImage(java.awt.image.BufferedImage) TextChannel(github.scarsz.discordsrv.dependencies.jda.api.entities.TextChannel) UUID(java.util.UUID) Member(github.scarsz.discordsrv.dependencies.jda.api.entities.Member) HashSet(java.util.HashSet) Player(org.bukkit.entity.Player) InputStream(java.io.InputStream) DiscordSRV(github.scarsz.discordsrv.DiscordSRV) IOException(java.io.IOException) Role(github.scarsz.discordsrv.dependencies.jda.api.entities.Role) DiscordAttachmentConversionEvent(com.loohp.interactivechatdiscordsrvaddon.api.events.DiscordAttachmentConversionEvent) GraphicsToPacketMapWrapper(com.loohp.interactivechatdiscordsrvaddon.wrappers.GraphicsToPacketMapWrapper) Subscribe(github.scarsz.discordsrv.api.Subscribe)

Aggregations

PrePacketComponentProcessEvent (com.loohp.interactivechat.api.events.PrePacketComponentProcessEvent)1 Component (com.loohp.interactivechat.libs.net.kyori.adventure.text.Component)1 ClickEvent (com.loohp.interactivechat.libs.net.kyori.adventure.text.event.ClickEvent)1 HoverEvent (com.loohp.interactivechat.libs.net.kyori.adventure.text.event.HoverEvent)1 LegacyComponentSerializer (com.loohp.interactivechat.libs.net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer)1 ComponentReplacing (com.loohp.interactivechat.utils.ComponentReplacing)1 CustomStringUtils (com.loohp.interactivechat.utils.CustomStringUtils)1 HTTPRequestUtils (com.loohp.interactivechat.utils.HTTPRequestUtils)1 InteractiveChatDiscordSrvAddon (com.loohp.interactivechatdiscordsrvaddon.InteractiveChatDiscordSrvAddon)1 DiscordAttachmentConversionEvent (com.loohp.interactivechatdiscordsrvaddon.api.events.DiscordAttachmentConversionEvent)1 Debug (com.loohp.interactivechatdiscordsrvaddon.debug.Debug)1 GifReader (com.loohp.interactivechatdiscordsrvaddon.graphics.GifReader)1 DiscordToGameMention (com.loohp.interactivechatdiscordsrvaddon.modules.DiscordToGameMention)1 ThrowingSupplier (com.loohp.interactivechatdiscordsrvaddon.utils.ThrowingSupplier)1 URLRequestUtils (com.loohp.interactivechatdiscordsrvaddon.utils.URLRequestUtils)1 GraphicsToPacketMapWrapper (com.loohp.interactivechatdiscordsrvaddon.wrappers.GraphicsToPacketMapWrapper)1 DiscordSRV (github.scarsz.discordsrv.DiscordSRV)1 ListenerPriority (github.scarsz.discordsrv.api.ListenerPriority)1 Subscribe (github.scarsz.discordsrv.api.Subscribe)1 DiscordGuildMessagePostProcessEvent (github.scarsz.discordsrv.api.events.DiscordGuildMessagePostProcessEvent)1