use of com.loohp.interactivechatdiscordsrvaddon.wrappers.GraphicsToPacketMapWrapper in project InteractiveChat-DiscordSRV-Addon by LOOHP.
the class InteractiveChatDiscordSrvAddonAPI method getDiscordImageWrapperByUUID.
/**
* Get the preview image map by the assigned uuid
*
* @param uuid the uuid of the image wrapper
* @return The image preview map (Could be null)
*/
public static GraphicsToPacketMapWrapper getDiscordImageWrapperByUUID(UUID uuid) {
Optional<DiscordAttachmentData> opt = InboundToGameEvents.DATA.values().stream().filter(each -> each.getUniqueId().equals(uuid)).findFirst();
DiscordAttachmentData data;
if (opt.isPresent() && (data = opt.get()).isImage()) {
return data.getImageMap();
} else {
return null;
}
}
use of com.loohp.interactivechatdiscordsrvaddon.wrappers.GraphicsToPacketMapWrapper 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;
}
use of com.loohp.interactivechatdiscordsrvaddon.wrappers.GraphicsToPacketMapWrapper 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();
}
}
}
}
}
}
Aggregations