file_name
stringlengths
6
86
file_path
stringlengths
45
249
content
stringlengths
47
6.26M
file_size
int64
47
6.26M
language
stringclasses
1 value
extension
stringclasses
1 value
repo_name
stringclasses
767 values
repo_stars
int64
8
14.4k
repo_forks
int64
0
1.17k
repo_open_issues
int64
0
788
repo_created_at
stringclasses
767 values
repo_pushed_at
stringclasses
767 values
MinecraftToDiscordChatModule.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/messageforwarding/game/minecrafttodiscord/MinecraftToDiscordChatModule.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.messageforwarding.game.minecrafttodiscord; import com.discordsrv.api.channel.GameChannel; import com.discordsrv.api.discord.entity.channel.DiscordGuildMessageChannel; import com.discordsrv.api.discord.entity.guild.DiscordGuild; import com.discordsrv.api.discord.entity.message.AllowedMention; import com.discordsrv.api.discord.entity.message.ReceivedDiscordMessage; import com.discordsrv.api.discord.entity.message.ReceivedDiscordMessageCluster; import com.discordsrv.api.discord.entity.message.SendableDiscordMessage; import com.discordsrv.api.discord.util.DiscordFormattingUtil; import com.discordsrv.api.event.bus.EventPriority; import com.discordsrv.api.event.bus.Subscribe; import com.discordsrv.api.event.events.message.forward.game.GameChatMessageForwardedEvent; import com.discordsrv.api.event.events.message.receive.game.GameChatMessageReceiveEvent; import com.discordsrv.api.placeholder.FormattedText; import com.discordsrv.api.placeholder.util.Placeholders; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.component.util.ComponentUtil; import com.discordsrv.common.config.main.channels.MinecraftToDiscordChatConfig; import com.discordsrv.common.config.main.channels.base.BaseChannelConfig; import com.discordsrv.common.future.util.CompletableFutureUtil; import com.discordsrv.common.messageforwarding.game.AbstractGameMessageModule; import com.discordsrv.common.permission.Permission; import com.discordsrv.common.player.IPlayer; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Role; import net.kyori.adventure.text.Component; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; public class MinecraftToDiscordChatModule extends AbstractGameMessageModule<MinecraftToDiscordChatConfig, GameChatMessageReceiveEvent> { public MinecraftToDiscordChatModule(DiscordSRV discordSRV) { super(discordSRV, "MINECRAFT_TO_DISCORD"); } @Subscribe(priority = EventPriority.LAST) public void onChatReceive(GameChatMessageReceiveEvent event) { if (checkProcessor(event) || checkCancellation(event) || !discordSRV.isReady()) { return; } GameChannel gameChannel = event.getGameChannel(); process(event, event.getPlayer(), gameChannel); event.markAsProcessed(); } @Override public MinecraftToDiscordChatConfig mapConfig(BaseChannelConfig channelConfig) { return channelConfig.minecraftToDiscord; } @Override public void postClusterToEventBus(ReceivedDiscordMessageCluster cluster) { discordSRV.eventBus().publish(new GameChatMessageForwardedEvent(cluster)); } @Override public Map<CompletableFuture<ReceivedDiscordMessage>, DiscordGuildMessageChannel> sendMessageToChannels( MinecraftToDiscordChatConfig config, IPlayer player, SendableDiscordMessage.Builder format, Collection<DiscordGuildMessageChannel> channels, GameChatMessageReceiveEvent event, Object... context ) { Map<DiscordGuild, Set<DiscordGuildMessageChannel>> channelMap = new LinkedHashMap<>(); for (DiscordGuildMessageChannel channel : channels) { DiscordGuild guild = channel.getGuild(); channelMap.computeIfAbsent(guild, key -> new LinkedHashSet<>()) .add(channel); } Component message = ComponentUtil.fromAPI(event.getMessage()); Map<CompletableFuture<ReceivedDiscordMessage>, DiscordGuildMessageChannel> futures = new LinkedHashMap<>(); // Format messages per-Guild for (Map.Entry<DiscordGuild, Set<DiscordGuildMessageChannel>> entry : channelMap.entrySet()) { Guild guild = entry.getKey().asJDA(); CompletableFuture<SendableDiscordMessage> messageFuture = getMessageForGuild(config, format, guild, message, player, context); for (DiscordGuildMessageChannel channel : entry.getValue()) { futures.put(messageFuture.thenCompose(channel::sendMessage), channel); } } return futures; } @Override public void setPlaceholders(MinecraftToDiscordChatConfig config, GameChatMessageReceiveEvent event, SendableDiscordMessage.Formatter formatter) {} private final Pattern MENTION_PATTERN = Pattern.compile("@\\S+"); private CompletableFuture<SendableDiscordMessage> getMessageForGuild( MinecraftToDiscordChatConfig config, SendableDiscordMessage.Builder format, Guild guild, Component message, IPlayer player, Object[] context ) { MinecraftToDiscordChatConfig.Mentions mentionConfig = config.mentions; MentionCachingModule mentionCaching = discordSRV.getModule(MentionCachingModule.class); if (mentionCaching != null && mentionConfig.users && mentionConfig.uncachedUsers && player.hasPermission(Permission.MENTION_USER_LOOKUP)) { List<CompletableFuture<List<MentionCachingModule.CachedMention>>> futures = new ArrayList<>(); String messageContent = discordSRV.componentFactory().plainSerializer().serialize(message); Matcher matcher = MENTION_PATTERN.matcher(messageContent); while (matcher.find()) { futures.add(mentionCaching.lookupMemberMentions(guild, matcher.group())); } if (!futures.isEmpty()) { return CompletableFutureUtil.combine(futures).thenApply(values -> { Set<MentionCachingModule.CachedMention> mentions = new LinkedHashSet<>(); for (List<MentionCachingModule.CachedMention> value : values) { mentions.addAll(value); } return getMessageForGuildWithMentions(config, format, guild, message, player, context, mentions); }); } } return CompletableFuture.completedFuture(getMessageForGuildWithMentions(config, format, guild, message, player, context, null)); } private SendableDiscordMessage getMessageForGuildWithMentions( MinecraftToDiscordChatConfig config, SendableDiscordMessage.Builder format, Guild guild, Component message, IPlayer player, Object[] context, Set<MentionCachingModule.CachedMention> memberMentions ) { MinecraftToDiscordChatConfig.Mentions mentionConfig = config.mentions; Set<MentionCachingModule.CachedMention> mentions = new LinkedHashSet<>(); if (memberMentions != null) { mentions.addAll(memberMentions); } MentionCachingModule mentionCaching = discordSRV.getModule(MentionCachingModule.class); if (mentionCaching != null) { if (mentionConfig.roles) { mentions.addAll(mentionCaching.getRoleMentions(guild).values()); } if (mentionConfig.channels) { mentions.addAll(mentionCaching.getChannelMentions(guild).values()); } if (mentionConfig.users) { mentions.addAll(mentionCaching.getMemberMentions(guild).values()); } } List<MentionCachingModule.CachedMention> orderedMentions = mentions.stream() .sorted(Comparator.comparingInt(mention -> ((MentionCachingModule.CachedMention) mention).searchLength()).reversed()) .collect(Collectors.toList()); List<AllowedMention> allowedMentions = new ArrayList<>(); if (mentionConfig.users && player.hasPermission(Permission.MENTION_USER)) { allowedMentions.add(AllowedMention.ALL_USERS); } if (mentionConfig.roles) { if (player.hasPermission(Permission.MENTION_ROLE_MENTIONABLE)) { for (Role role : guild.getRoles()) { if (role.isMentionable()) { allowedMentions.add(AllowedMention.role(role.getIdLong())); } } } if (player.hasPermission(Permission.MENTION_ROLE_ALL)) { allowedMentions.add(AllowedMention.ALL_ROLES); } } boolean everyone = mentionConfig.everyone && player.hasPermission(Permission.MENTION_EVERYONE); if (everyone) { allowedMentions.add(AllowedMention.EVERYONE); } return format.setAllowedMentions(allowedMentions) .toFormatter() .addContext(context) .addPlaceholder("message", () -> { String convertedComponent = convertComponent(config, message); Placeholders channelMessagePlaceholders = new Placeholders( DiscordFormattingUtil.escapeMentions(convertedComponent)); // From longest to shortest orderedMentions.forEach(mention -> channelMessagePlaceholders.replaceAll(mention.search(), mention.mention())); String finalMessage = channelMessagePlaceholders.toString(); return new FormattedText(preventEveryoneMentions(everyone, finalMessage)); }) .applyPlaceholderService() .build(); } public String convertComponent(MinecraftToDiscordChatConfig config, Component component) { String content = discordSRV.placeholderService().getResultAsPlain(component).toString(); Placeholders messagePlaceholders = new Placeholders(content); config.contentRegexFilters.forEach(messagePlaceholders::replaceAll); return messagePlaceholders.toString(); } private String preventEveryoneMentions(boolean everyoneAllowed, String message) { if (everyoneAllowed) { // Nothing to do return message; } message = message .replace("@everyone", "\\@\u200Beveryone") // zero-width-space .replace("@here", "\\@\u200Bhere"); // zero-width-space if (message.contains("@everyone") || message.contains("@here")) { throw new IllegalStateException("@everyone or @here blocking unsuccessful"); } return message; } }
11,249
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
MentionCachingModule.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/messageforwarding/game/minecrafttodiscord/MentionCachingModule.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.messageforwarding.game.minecrafttodiscord; import com.discordsrv.api.event.bus.Subscribe; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.config.main.channels.MinecraftToDiscordChatConfig; import com.discordsrv.common.config.main.channels.base.BaseChannelConfig; import com.discordsrv.common.module.type.AbstractModule; import com.github.benmanes.caffeine.cache.Cache; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel; import net.dv8tion.jda.api.events.channel.ChannelCreateEvent; import net.dv8tion.jda.api.events.channel.ChannelDeleteEvent; import net.dv8tion.jda.api.events.channel.update.ChannelUpdateNameEvent; import net.dv8tion.jda.api.events.guild.GuildLeaveEvent; import net.dv8tion.jda.api.events.guild.member.GuildMemberJoinEvent; import net.dv8tion.jda.api.events.guild.member.GuildMemberRemoveEvent; import net.dv8tion.jda.api.events.guild.member.update.GuildMemberUpdateNicknameEvent; import net.dv8tion.jda.api.events.role.RoleCreateEvent; import net.dv8tion.jda.api.events.role.RoleDeleteEvent; import net.dv8tion.jda.api.events.role.update.RoleUpdateNameEvent; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.regex.Pattern; public class MentionCachingModule extends AbstractModule<DiscordSRV> { private final Map<Long, Map<Long, CachedMention>> memberMentions = new ConcurrentHashMap<>(); private final Map<Long, Cache<Long, CachedMention>> memberMentionsCache = new ConcurrentHashMap<>(); private final Map<Long, Map<Long, CachedMention>> roleMentions = new ConcurrentHashMap<>(); private final Map<Long, Map<Long, CachedMention>> channelMentions = new ConcurrentHashMap<>(); public MentionCachingModule(DiscordSRV discordSRV) { super(discordSRV); } @Override public boolean isEnabled() { for (BaseChannelConfig channel : discordSRV.channelConfig().getAllChannels()) { MinecraftToDiscordChatConfig config = channel.minecraftToDiscord; if (!config.enabled) { continue; } MinecraftToDiscordChatConfig.Mentions mentions = config.mentions; if (mentions.roles || mentions.users || mentions.channels) { return true; } } return false; } @Override public void disable() { memberMentions.clear(); roleMentions.clear(); channelMentions.clear(); } @Subscribe public void onGuildDelete(GuildLeaveEvent event) { long guildId = event.getGuild().getIdLong(); memberMentions.remove(guildId); roleMentions.remove(guildId); channelMentions.remove(guildId); } // // Member // public CompletableFuture<List<CachedMention>> lookupMemberMentions(Guild guild, String mention) { CompletableFuture<List<Member>> memberFuture = new CompletableFuture<>(); guild.retrieveMembersByPrefix(mention.substring(1), 100) .onSuccess(memberFuture::complete).onError(memberFuture::completeExceptionally); Cache<Long, CachedMention> cache = memberMentionsCache.computeIfAbsent(guild.getIdLong(), key -> discordSRV.caffeineBuilder() .expireAfterAccess(10, TimeUnit.MINUTES) .build() ); return memberFuture.thenApply(members -> { List<CachedMention> cachedMentions = new ArrayList<>(); for (Member member : members) { CachedMention cachedMention = cache.get(member.getIdLong(), k -> convertMember(member)); cachedMentions.add(cachedMention); } return cachedMentions; }); } public Map<Long, CachedMention> getMemberMentions(Guild guild) { return memberMentions.computeIfAbsent(guild.getIdLong(), key -> { Map<Long, CachedMention> mentions = new LinkedHashMap<>(); for (Member member : guild.getMembers()) { mentions.put(member.getIdLong(), convertMember(member)); } return mentions; }); } private CachedMention convertMember(Member member) { return new CachedMention( "@" + member.getEffectiveName(), member.getAsMention(), member.getIdLong() ); } @Subscribe public void onMemberAdd(GuildMemberJoinEvent event) { Member member = event.getMember(); if (member.getGuild().getMemberCache().getElementById(member.getIdLong()) == null) { // Member is not cached return; } getMemberMentions(event.getGuild()).put(member.getIdLong(), convertMember(member)); } @Subscribe public void onMemberUpdate(GuildMemberUpdateNicknameEvent event) { Member member = event.getMember(); getMemberMentions(event.getGuild()).replace(member.getIdLong(), convertMember(member)); } @Subscribe public void onMemberDelete(GuildMemberRemoveEvent event) { Member member = event.getMember(); if (member == null) { return; } getMemberMentions(event.getGuild()).remove(member.getIdLong()); } // // Role // public Map<Long, CachedMention> getRoleMentions(Guild guild) { return roleMentions.computeIfAbsent(guild.getIdLong(), key -> { Map<Long, CachedMention> mentions = new LinkedHashMap<>(); for (Role role : guild.getRoles()) { mentions.put(role.getIdLong(), convertRole(role)); } return mentions; }); } private CachedMention convertRole(Role role) { return new CachedMention( "@" + role.getName(), role.getAsMention(), role.getIdLong() ); } @Subscribe public void onRoleCreate(RoleCreateEvent event) { Role role = event.getRole(); getRoleMentions(event.getGuild()).put(role.getIdLong(), convertRole(role)); } @Subscribe public void onRoleUpdate(RoleUpdateNameEvent event) { Role role = event.getRole(); getRoleMentions(event.getGuild()).put(role.getIdLong(), convertRole(role)); } @Subscribe public void onRoleDelete(RoleDeleteEvent event) { Role role = event.getRole(); getRoleMentions(event.getGuild()).remove(role.getIdLong()); } // // Channel // public Map<Long, CachedMention> getChannelMentions(Guild guild) { return channelMentions.computeIfAbsent(guild.getIdLong(), key -> { Map<Long, CachedMention> mentions = new LinkedHashMap<>(); for (GuildChannel channel : guild.getChannels()) { mentions.put(channel.getIdLong(), convertChannel(channel)); } return mentions; }); } private CachedMention convertChannel(GuildChannel channel) { return new CachedMention( "#" + channel.getName(), channel.getAsMention(), channel.getIdLong() ); } @Subscribe public void onChannelCreate(ChannelCreateEvent event) { if (!event.getChannelType().isGuild()) { return; } GuildChannel channel = (GuildChannel) event.getChannel(); getChannelMentions(event.getGuild()).put(channel.getIdLong(), convertChannel(channel)); } @Subscribe public void onChannelUpdate(ChannelUpdateNameEvent event) { if (!event.getChannelType().isGuild()) { return; } GuildChannel channel = (GuildChannel) event.getChannel(); getChannelMentions(event.getGuild()).put(channel.getIdLong(), convertChannel(channel)); } @Subscribe public void onChannelDelete(ChannelDeleteEvent event) { if (!event.getChannelType().isGuild()) { return; } GuildChannel channel = (GuildChannel) event.getChannel(); getChannelMentions(event.getGuild()).remove(channel.getIdLong()); } public static class CachedMention { private final Pattern search; private final int searchLength; private final String mention; private final long id; public CachedMention(String search, String mention, long id) { this.search = Pattern.compile(search, Pattern.LITERAL); this.searchLength = search.length(); this.mention = mention; this.id = id; } public Pattern search() { return search; } public int searchLength() { return searchLength; } public String mention() { return mention; } public long id() { return id; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; CachedMention that = (CachedMention) o; return id == that.id; } @Override public int hashCode() { return Objects.hash(id); } @Override public String toString() { return "CachedMention{pattern=" + search.pattern() + ",mention=" + mention + "}"; } } }
10,374
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordMessageMirroringModule.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/messageforwarding/discord/DiscordMessageMirroringModule.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.messageforwarding.discord; import com.discordsrv.api.channel.GameChannel; import com.discordsrv.api.discord.connection.details.DiscordGatewayIntent; import com.discordsrv.api.discord.entity.DiscordUser; import com.discordsrv.api.discord.entity.channel.DiscordGuildMessageChannel; import com.discordsrv.api.discord.entity.channel.DiscordMessageChannel; import com.discordsrv.api.discord.entity.channel.DiscordTextChannel; import com.discordsrv.api.discord.entity.channel.DiscordThreadChannel; import com.discordsrv.api.discord.entity.guild.DiscordGuildMember; import com.discordsrv.api.discord.entity.message.DiscordMessageEmbed; import com.discordsrv.api.discord.entity.message.ReceivedDiscordMessage; import com.discordsrv.api.discord.entity.message.SendableDiscordMessage; import com.discordsrv.api.event.bus.Subscribe; import com.discordsrv.api.event.events.discord.message.DiscordMessageDeleteEvent; import com.discordsrv.api.event.events.discord.message.DiscordMessageUpdateEvent; import com.discordsrv.api.event.events.message.forward.game.AbstractGameMessageForwardedEvent; import com.discordsrv.api.event.events.message.receive.discord.DiscordChatMessageReceiveEvent; import com.discordsrv.api.placeholder.PlainPlaceholderFormat; import com.discordsrv.api.placeholder.provider.SinglePlaceholder; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.config.main.channels.MirroringConfig; import com.discordsrv.common.config.main.channels.base.BaseChannelConfig; import com.discordsrv.common.config.main.channels.base.IChannelConfig; import com.discordsrv.common.config.main.generic.DiscordIgnoresConfig; import com.discordsrv.common.future.util.CompletableFutureUtil; import com.discordsrv.common.logging.NamedLogger; import com.discordsrv.common.module.type.AbstractModule; import com.github.benmanes.caffeine.cache.Cache; import net.dv8tion.jda.api.entities.Message; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; public class DiscordMessageMirroringModule extends AbstractModule<DiscordSRV> { private final Cache<Long, Cache<Long, Sync>> mapping; public DiscordMessageMirroringModule(DiscordSRV discordSRV) { super(discordSRV, new NamedLogger(discordSRV, "DISCORD_MIRRORING")); this.mapping = discordSRV.caffeineBuilder() .expireAfterWrite(60, TimeUnit.MINUTES) .expireAfterAccess(30, TimeUnit.MINUTES) .build(); } @Override public boolean isEnabled() { for (BaseChannelConfig config : discordSRV.channelConfig().getAllChannels()) { if (config.mirroring.enabled) { return true; } } return false; } @Override public @NotNull Collection<DiscordGatewayIntent> requiredIntents() { return Arrays.asList(DiscordGatewayIntent.GUILD_MESSAGES, DiscordGatewayIntent.MESSAGE_CONTENT); } @SuppressWarnings("unchecked") // Wacky generics @Subscribe public <CC extends BaseChannelConfig & IChannelConfig> void onDiscordChatMessageProcessing(DiscordChatMessageReceiveEvent event) { if (checkCancellation(event)) { return; } Map<GameChannel, BaseChannelConfig> channels = discordSRV.channelConfig().resolve(event.getChannel()); if (channels == null || channels.isEmpty()) { return; } ReceivedDiscordMessage message = event.getMessage(); List<CompletableFuture<MirrorOperation>> futures = new ArrayList<>(); Map<ReceivedDiscordMessage.Attachment, byte[]> attachments = new LinkedHashMap<>(); DiscordMessageEmbed.Builder attachmentEmbed = DiscordMessageEmbed.builder().setDescription("Attachments"); for (Map.Entry<GameChannel, BaseChannelConfig> entry : channels.entrySet()) { BaseChannelConfig baseChannelConfig = entry.getValue(); MirroringConfig config = baseChannelConfig.mirroring; if (!config.enabled) { continue; } DiscordIgnoresConfig ignores = config.ignores; if (ignores != null && ignores.shouldBeIgnored(message.isWebhookMessage(), message.getAuthor(), message.getMember())) { continue; } CC channelConfig = baseChannelConfig instanceof IChannelConfig ? (CC) baseChannelConfig : null; if (channelConfig == null) { continue; } MirroringConfig.AttachmentConfig attachmentConfig = config.attachments; int maxSize = attachmentConfig.maximumSizeKb * 1000; boolean embedAttachments = attachmentConfig.embedAttachments; if (maxSize >= 0 || embedAttachments) { for (ReceivedDiscordMessage.Attachment attachment : message.getAttachments()) { if (attachments.containsKey(attachment)) { continue; } if (maxSize == 0 || attachment.sizeBytes() <= maxSize) { Request request = new Request.Builder() .url(attachment.url()) .get() .addHeader("Accept", "*/*") .build(); byte[] bytes = null; try (Response response = discordSRV.httpClient().newCall(request).execute()) { ResponseBody body = response.body(); if (body != null) { bytes = body.bytes(); } } catch (IOException e) { logger().error("Failed to download attachment for mirroring", e); } attachments.put(attachment, bytes); continue; } if (!embedAttachments) { continue; } attachments.put(attachment, null); attachmentEmbed.addField(attachment.fileName(), "[link](" + attachment.url() + ")", true); } } futures.add( discordSRV.discordAPI().findOrCreateDestinations(channelConfig, true, true) .thenApply(messageChannels -> { List<MirrorTarget> targets = new ArrayList<>(); for (DiscordGuildMessageChannel messageChannel : messageChannels) { targets.add(new MirrorTarget(messageChannel, config)); } return new MirrorOperation(message, config, targets); }) ); } CompletableFutureUtil.combine(futures).whenComplete((lists, t) -> { Set<Long> channelIdsHandled = new HashSet<>(); for (MirrorOperation operation : lists) { List<CompletableFuture<MirroredMessage>> mirrorFutures = new ArrayList<>(); for (MirrorTarget target : operation.targets) { DiscordGuildMessageChannel mirrorChannel = target.targetChannel; long channelId = mirrorChannel.getId(); if (channelId == event.getChannel().getId() || channelIdsHandled.contains(channelId)) { continue; } channelIdsHandled.add(channelId); MirroringConfig config = target.config; MirroringConfig.AttachmentConfig attachmentConfig = config.attachments; SendableDiscordMessage.Builder messageBuilder = convert(event.getMessage(), mirrorChannel, config); if (!attachmentEmbed.getFields().isEmpty() && attachmentConfig.embedAttachments) { messageBuilder.addEmbed(attachmentEmbed.build()); } int maxSize = attachmentConfig.maximumSizeKb * 1000; List<InputStream> streams = new ArrayList<>(); if (!attachments.isEmpty() && maxSize >= 0) { attachments.forEach((attachment, bytes) -> { if (bytes != null && (maxSize == 0 || attachment.sizeBytes() <= maxSize)) { InputStream stream = new ByteArrayInputStream(bytes); streams.add(stream); messageBuilder.addAttachment(stream, attachment.fileName()); } }); } if (messageBuilder.isEmpty()) { logger().debug("Nothing to mirror to " + mirrorChannel + ", skipping"); for (InputStream stream : streams) { try { stream.close(); } catch (IOException ignored) {} } return; } CompletableFuture<MirroredMessage> future = mirrorChannel.sendMessage(messageBuilder.build()) .thenApply(msg -> new MirroredMessage(msg, config)); mirrorFutures.add(future); future.exceptionally(t2 -> { logger().error("Failed to mirror message to " + mirrorChannel, t2); for (InputStream stream : streams) { try { stream.close(); } catch (IOException ignored) {} } return null; }); } CompletableFutureUtil.combine(mirrorFutures).whenComplete((messages, t2) -> { MessageReference reference = getReference(operation.originalMessage, operation.configForOriginalMessage); Map<ReceivedDiscordMessage, MessageReference> references = new LinkedHashMap<>(); references.put(message, reference); for (MirroredMessage mirroredMessage : messages) { references.put(mirroredMessage.message, getReference(mirroredMessage)); } putIntoCache(reference, references); }); } }).exceptionally(t -> { logger().error("Failed to mirror message", t); return null; }); } @Subscribe public void onDiscordMessageUpdate(DiscordMessageUpdateEvent event) { Cache<Long, Sync> syncs = mapping.getIfPresent(event.getChannel().getId()); if (syncs == null) { return; } ReceivedDiscordMessage message = event.getMessage(); Sync sync = syncs.getIfPresent(message.getId()); if (sync == null || sync.original == null || !sync.original.isMatching(message)) { return; } for (MessageReference reference : sync.mirrors) { DiscordGuildMessageChannel channel = reference.getMessageChannel(discordSRV); if (channel == null) { continue; } SendableDiscordMessage sendableMessage = convert(message, channel, reference.config).build(); channel.editMessageById(reference.messageId, sendableMessage).exceptionally(t -> { logger().error("Failed to update mirrored message in " + channel); return null; }); } } @Subscribe public void onDiscordMessageDelete(DiscordMessageDeleteEvent event) { Cache<Long, Sync> syncs = mapping.getIfPresent(event.getChannel().getId()); if (syncs == null) { return; } Sync sync = syncs.getIfPresent(event.getMessageId()); if (sync == null || sync.original == null || !sync.original.isMatching(event.getChannel()) || sync.original.messageId != event.getMessageId()) { return; } for (MessageReference reference : sync.mirrors) { DiscordMessageChannel channel = reference.getMessageChannel(discordSRV); if (channel == null) { continue; } channel.deleteMessageById(reference.messageId, reference.webhookMessage).exceptionally(t -> { logger().error("Failed to delete mirrored message in " + channel); return null; }); } } @Subscribe public void onGameMessageForwarded(AbstractGameMessageForwardedEvent event) { Set<? extends ReceivedDiscordMessage> messages = event.getDiscordMessage().getMessages(); Map<ReceivedDiscordMessage, MessageReference> references = new LinkedHashMap<>(); for (ReceivedDiscordMessage message : messages) { DiscordMessageChannel channel = message.getChannel(); MirroringConfig config = discordSRV.channelConfig().resolve(channel).values().iterator().next().mirroring; // TODO: add channel to event MessageReference reference = getReference(message, config); references.put(message, reference); } putIntoCache(null, references); } @SuppressWarnings("DataFlowIssue") // Supplier always returns a non-null value @NotNull private Cache<Long, Sync> getCache(long channelId) { return mapping.get( channelId, k -> discordSRV.caffeineBuilder() .expireAfterWrite(30, TimeUnit.MINUTES) .expireAfterAccess(10, TimeUnit.MINUTES) .build() ); } private void putIntoCache(@Nullable MessageReference original, Map<ReceivedDiscordMessage, MessageReference> references) { if (original == null && references.size() <= 1) { return; } for (Map.Entry<ReceivedDiscordMessage, MessageReference> entry : references.entrySet()) { ReceivedDiscordMessage message = entry.getKey(); MessageReference reference = entry.getValue(); List<MessageReference> refs = new ArrayList<>(); for (MessageReference ref : references.values()) { if (ref == reference) { continue; } refs.add(ref); } getCache(message.getChannel().getId()).put(message.getId(), new Sync(original, refs)); } } /** * Converts a given received message to a sendable message. */ private SendableDiscordMessage.Builder convert( ReceivedDiscordMessage message, DiscordGuildMessageChannel destinationChannel, MirroringConfig config ) { DiscordGuildMember member = message.getMember(); DiscordUser user = message.getAuthor(); String username = discordSRV.placeholderService().replacePlaceholders(config.usernameFormat, member, user); if (username.length() > 32) { username = username.substring(0, 32); } ReceivedDiscordMessage replyMessage = message.getReplyingTo(); String content = Objects.requireNonNull(message.getContent()) .replace("[", "\\["); // Block markdown urls String finalContent; if (replyMessage != null) { MessageReference matchingReference = null; Cache<Long, Sync> syncs = mapping.getIfPresent(replyMessage.getChannel().getId()); if (syncs != null) { Sync sync = syncs.getIfPresent(replyMessage.getId()); if (sync != null) { matchingReference = sync.getForChannel(destinationChannel); } } String jumpUrl = matchingReference != null ? String.format( Message.JUMP_URL, Long.toUnsignedString(destinationChannel.getGuild().getId()), Long.toUnsignedString(destinationChannel.getId()), Long.toUnsignedString(matchingReference.messageId) ) : replyMessage.getJumpUrl(); finalContent = PlainPlaceholderFormat.supplyWith( PlainPlaceholderFormat.Formatting.DISCORD, () -> discordSRV.placeholderService() .replacePlaceholders( config.replyFormat, replyMessage.getMember(), replyMessage.getAuthor(), new SinglePlaceholder("message_jump_url", jumpUrl), new SinglePlaceholder("message", content) ) ); } else { finalContent = content; } SendableDiscordMessage.Builder builder = SendableDiscordMessage.builder() .setAllowedMentions(Collections.emptyList()) .setContent(finalContent.substring(0, Math.min(finalContent.length(), Message.MAX_CONTENT_LENGTH))) .setWebhookUsername(username) .setWebhookAvatarUrl( member != null ? member.getEffectiveServerAvatarUrl() : user.getEffectiveAvatarUrl() ); for (DiscordMessageEmbed embed : message.getEmbeds()) { builder.addEmbed(embed); } return builder; } private MessageReference getReference(MirroredMessage message) { return getReference(message.message, message.config); } private MessageReference getReference(ReceivedDiscordMessage message, MirroringConfig config) { return getReference(message.getChannel(), message.getId(), message.isWebhookMessage(), config); } private MessageReference getReference( DiscordMessageChannel channel, long messageId, boolean webhookMessage, MirroringConfig config ) { if (channel instanceof DiscordTextChannel) { DiscordTextChannel textChannel = (DiscordTextChannel) channel; return new MessageReference(textChannel, messageId, webhookMessage, config); } else if (channel instanceof DiscordThreadChannel) { DiscordThreadChannel threadChannel = (DiscordThreadChannel) channel; return new MessageReference(threadChannel, messageId, webhookMessage, config); } throw new IllegalStateException("Unexpected channel type: " + channel.getClass().getName()); } private static class MirrorOperation { private final ReceivedDiscordMessage originalMessage; private final MirroringConfig configForOriginalMessage; private final List<MirrorTarget> targets; public MirrorOperation(ReceivedDiscordMessage originalMessage, MirroringConfig configForOriginalMessage, List<MirrorTarget> targets) { this.originalMessage = originalMessage; this.configForOriginalMessage = configForOriginalMessage; this.targets = targets; } } private static class MirrorTarget { private final DiscordGuildMessageChannel targetChannel; private final MirroringConfig config; public MirrorTarget(DiscordGuildMessageChannel targetChannel, MirroringConfig config) { this.targetChannel = targetChannel; this.config = config; } } private static class MirroredMessage { private final ReceivedDiscordMessage message; private final MirroringConfig config; public MirroredMessage(ReceivedDiscordMessage message, MirroringConfig config) { this.message = message; this.config = config; } } private static class Sync { private final MessageReference original; private final List<MessageReference> mirrors; public Sync(MessageReference original, List<MessageReference> mirrors) { this.original = original; this.mirrors = mirrors; } public MessageReference getForChannel(DiscordGuildMessageChannel channel) { for (MessageReference mirror : mirrors) { if (mirror.isMatching(channel)) { return mirror; } } return null; } } private static class MessageReference { private final long channelId; private final long threadId; private final long messageId; private final boolean webhookMessage; private final MirroringConfig config; public MessageReference( DiscordTextChannel textChannel, long messageId, boolean webhookMessage, MirroringConfig config ) { this(textChannel.getId(), -1L, messageId, webhookMessage, config); } public MessageReference( DiscordThreadChannel threadChannel, long messageId, boolean webhookMessage, MirroringConfig config ) { this(threadChannel.getParentChannel().getId(), threadChannel.getId(), messageId, webhookMessage, config); } public MessageReference( long channelId, long threadId, long messageId, boolean webhookMessage, MirroringConfig config ) { this.channelId = channelId; this.threadId = threadId; this.messageId = messageId; this.webhookMessage = webhookMessage; this.config = config; } public DiscordGuildMessageChannel getMessageChannel(DiscordSRV discordSRV) { DiscordTextChannel textChannel = discordSRV.discordAPI().getTextChannelById(channelId); if (textChannel == null) { return null; } else if (threadId == -1) { return textChannel; } for (DiscordThreadChannel activeThread : textChannel.getActiveThreads()) { if (activeThread.getId() == threadId) { return activeThread; } } return null; } public boolean isMatching(DiscordMessageChannel channel) { return channel instanceof DiscordThreadChannel ? channel.getId() == threadId && ((DiscordThreadChannel) channel).getParentChannel().getId() == channelId : channel.getId() == channelId; } public boolean isMatching(ReceivedDiscordMessage message) { return isMatching(message.getChannel()) && messageId == message.getId(); } } }
24,159
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordChatMessageModule.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/messageforwarding/discord/DiscordChatMessageModule.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.messageforwarding.discord; import com.discordsrv.api.channel.GameChannel; import com.discordsrv.api.component.GameTextBuilder; import com.discordsrv.api.component.MinecraftComponent; import com.discordsrv.api.discord.connection.details.DiscordGatewayIntent; import com.discordsrv.api.discord.entity.DiscordUser; import com.discordsrv.api.discord.entity.channel.DiscordMessageChannel; import com.discordsrv.api.discord.entity.guild.DiscordGuild; import com.discordsrv.api.discord.entity.guild.DiscordGuildMember; import com.discordsrv.api.discord.entity.message.ReceivedDiscordMessage; import com.discordsrv.api.event.bus.Subscribe; import com.discordsrv.api.event.events.discord.message.DiscordMessageDeleteEvent; import com.discordsrv.api.event.events.discord.message.DiscordMessageReceiveEvent; import com.discordsrv.api.event.events.discord.message.DiscordMessageUpdateEvent; import com.discordsrv.api.event.events.message.forward.discord.DiscordChatMessageForwardedEvent; import com.discordsrv.api.event.events.message.process.discord.DiscordChatMessageProcessEvent; import com.discordsrv.api.event.events.message.receive.discord.DiscordChatMessageReceiveEvent; import com.discordsrv.api.placeholder.util.Placeholders; import com.discordsrv.api.player.DiscordSRVPlayer; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.component.renderer.DiscordSRVMinecraftRenderer; import com.discordsrv.common.component.util.ComponentUtil; import com.discordsrv.common.config.main.channels.DiscordToMinecraftChatConfig; import com.discordsrv.common.config.main.channels.base.BaseChannelConfig; import com.discordsrv.common.config.main.generic.DiscordIgnoresConfig; import com.discordsrv.common.logging.NamedLogger; import com.discordsrv.common.module.type.AbstractModule; import net.kyori.adventure.text.Component; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import java.time.Duration; import java.util.Arrays; import java.util.Collection; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ScheduledFuture; import java.util.regex.Pattern; public class DiscordChatMessageModule extends AbstractModule<DiscordSRV> { // Filter for ASCII control characters which have no use being displayed, but might be misinterpreted somewhere // Notably this excludes, 0x09 HT (\t), 0x0A LF (\n), 0x0B VT (\v) and 0x0D CR (\r) (which may be used for text formatting) private static final Pattern ASCII_CONTROL_FILTER = Pattern.compile("[\\u0000-\\u0008\\u000C\\u000E-\\u001F\\u007F]"); // A regex filter matching the unicode regular expression character category "Other Symbol" // https://unicode.org/reports/tr18/#General_Category_Property private static final Pattern EMOJI_FILTER = Pattern.compile("\\p{So}"); private final Map<String, MessageSend> sends = new ConcurrentHashMap<>(); public DiscordChatMessageModule(DiscordSRV discordSRV) { super(discordSRV, new NamedLogger(discordSRV, "DISCORD_TO_MINECRAFT")); } public String getKey(ReceivedDiscordMessage message) { return getKey(message.getChannel(), message.getId()); } public String getKey(DiscordMessageChannel channel, long messageId) { return Long.toUnsignedString(channel.getId()) + "-" + Long.toUnsignedString(messageId); } @Override public boolean isEnabled() { for (BaseChannelConfig config : discordSRV.channelConfig().getAllChannels()) { if (config.discordToMinecraft.enabled) { return true; } } return false; } @Override public @NotNull Collection<DiscordGatewayIntent> requiredIntents() { return Arrays.asList(DiscordGatewayIntent.GUILD_MESSAGES, DiscordGatewayIntent.MESSAGE_CONTENT); } @Subscribe public void onDiscordMessageReceived(DiscordMessageReceiveEvent event) { if (!discordSRV.isReady() || event.getMessage().isFromSelf() || !(event.getTextChannel() != null || event.getThreadChannel() != null)) { return; } discordSRV.eventBus().publish(new DiscordChatMessageReceiveEvent(event.getMessage(), event.getChannel())); } @Subscribe public void onDiscordChatMessageReceive(DiscordChatMessageReceiveEvent event) { if (checkCancellation(event)) { return; } Map<GameChannel, BaseChannelConfig> channels = discordSRV.channelConfig().resolve(event.getChannel()); if (channels == null || channels.isEmpty()) { return; } ReceivedDiscordMessage message = event.getMessage(); for (Map.Entry<GameChannel, BaseChannelConfig> entry : channels.entrySet()) { GameChannel gameChannel = entry.getKey(); BaseChannelConfig config = entry.getValue(); if (!config.discordToMinecraft.enabled) { continue; } long delayMillis = config.discordToMinecraft.delayMillis; if (delayMillis == 0) { process(message, gameChannel, config); return; } String key = getKey(message); MessageSend send = new MessageSend(message, gameChannel, config); sends.put(key, send); send.setFuture(discordSRV.scheduler().runLater(() -> processSend(key), Duration.ofMillis(delayMillis))); } } private void processSend(String key) { MessageSend send = sends.remove(key); if (send != null) { process(send.getMessage(), send.getGameChannel(), send.getConfig()); } } @Subscribe public void onDiscordMessageUpdate(DiscordMessageUpdateEvent event) { ReceivedDiscordMessage message = event.getMessage(); MessageSend send = sends.get(getKey(message)); if (send != null) { send.setMessage(message); } } @Subscribe public void onDiscordMessageDelete(DiscordMessageDeleteEvent event) { MessageSend send = sends.remove(getKey(event.getChannel(), event.getMessageId())); if (send != null) { send.getFuture().cancel(false); } } private void process(ReceivedDiscordMessage discordMessage, GameChannel gameChannel, BaseChannelConfig channelConfig) { DiscordChatMessageProcessEvent event = new DiscordChatMessageProcessEvent(discordMessage.getChannel(), discordMessage, gameChannel); discordSRV.eventBus().publish(event); if (checkCancellation(event) || checkProcessor(event)) { return; } DiscordToMinecraftChatConfig chatConfig = channelConfig.discordToMinecraft; if (!chatConfig.enabled) { return; } DiscordGuild guild = discordMessage.getGuild(); DiscordMessageChannel channel = discordMessage.getChannel(); DiscordUser author = discordMessage.getAuthor(); DiscordGuildMember member = discordMessage.getMember(); boolean webhookMessage = discordMessage.isWebhookMessage(); DiscordIgnoresConfig ignores = chatConfig.ignores; if (ignores != null && ignores.shouldBeIgnored(webhookMessage, author, member)) { // TODO: response for humans return; } String format = webhookMessage ? chatConfig.webhookFormat : chatConfig.format; if (StringUtils.isBlank(format)) { return; } Placeholders message = new Placeholders(event.getContent()); message.replaceAll(ASCII_CONTROL_FILTER, ""); if (chatConfig.unicodeEmojiBehaviour == DiscordToMinecraftChatConfig.EmojiBehaviour.HIDE) { message.replaceAll(EMOJI_FILTER, ""); } chatConfig.contentRegexFilters.forEach(message::replaceAll); boolean attachments = !discordMessage.getAttachments().isEmpty() && format.contains("message_attachments"); String finalMessage = message.toString(); if (finalMessage.trim().isEmpty() && !attachments) { // No sending empty messages return; } Component messageComponent = DiscordSRVMinecraftRenderer.getWithContext(guild, chatConfig, () -> discordSRV.componentFactory().minecraftSerializer().serialize(finalMessage)); if (discordSRV.componentFactory().plainSerializer().serialize(messageComponent).trim().isEmpty() && !attachments) { // Check empty-ness again after rendering return; } GameTextBuilder componentBuilder = discordSRV.componentFactory() .textBuilder(format) .addContext(discordMessage, author, member, channel, channelConfig) .applyPlaceholderService() .addPlaceholder("message", messageComponent); MinecraftComponent component = DiscordSRVMinecraftRenderer.getWithContext(guild, chatConfig, componentBuilder::build); if (ComponentUtil.isEmpty(component)) { // Empty return; } gameChannel.sendMessage(component); Collection<? extends DiscordSRVPlayer> players = gameChannel.getRecipients(); for (DiscordSRVPlayer player : players) { gameChannel.sendMessageToPlayer(player, component); } discordSRV.eventBus().publish(new DiscordChatMessageForwardedEvent(component, gameChannel)); } public static class MessageSend { private ReceivedDiscordMessage message; private final GameChannel gameChannel; private final BaseChannelConfig config; private ScheduledFuture<?> future; public MessageSend(ReceivedDiscordMessage message, GameChannel gameChannel, BaseChannelConfig config) { this.message = message; this.gameChannel = gameChannel; this.config = config; } public ReceivedDiscordMessage getMessage() { return message; } public void setMessage(ReceivedDiscordMessage message) { this.message = message; } public GameChannel getGameChannel() { return gameChannel; } public BaseChannelConfig getConfig() { return config; } public ScheduledFuture<?> getFuture() { return future; } public void setFuture(ScheduledFuture<?> future) { this.future = future; } } }
11,318
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ApiInstanceUtil.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/api/util/ApiInstanceUtil.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.api.util; import com.discordsrv.api.DiscordSRVApi; import com.discordsrv.common.DiscordSRV; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; @ApiStatus.Internal public final class ApiInstanceUtil { private ApiInstanceUtil() {} @ApiStatus.Internal public static void setInstance(@NotNull DiscordSRV discordSRV) { // Avoids illegal access try { Class<?> apiProviderClass = Class.forName("com.discordsrv.api.DiscordSRVApi$InstanceHolder"); Method provideMethod = apiProviderClass.getDeclaredMethod("provide", DiscordSRVApi.class); provideMethod.setAccessible(true); provideMethod.invoke(null, discordSRV); } catch (ClassNotFoundException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) { discordSRV.logger().error("Failed to set API instance", e); } } }
1,878
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ChannelConfigHelper.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/channel/ChannelConfigHelper.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.channel; import com.discordsrv.api.channel.GameChannel; import com.discordsrv.api.discord.entity.channel.DiscordMessageChannel; import com.discordsrv.api.discord.entity.channel.DiscordTextChannel; import com.discordsrv.api.discord.entity.channel.DiscordThreadChannel; import com.discordsrv.api.event.events.channel.GameChannelLookupEvent; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.config.configurate.manager.MainConfigManager; import com.discordsrv.common.config.main.channels.base.BaseChannelConfig; import com.discordsrv.common.config.main.channels.base.ChannelConfig; import com.discordsrv.common.config.main.channels.base.IChannelConfig; import com.discordsrv.common.config.main.generic.DestinationConfig; import com.discordsrv.common.config.main.generic.ThreadConfig; import com.github.benmanes.caffeine.cache.CacheLoader; import com.github.benmanes.caffeine.cache.LoadingCache; import org.apache.commons.lang3.tuple.Pair; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.spongepowered.configurate.CommentedConfigurationNode; import org.spongepowered.configurate.objectmapping.ObjectMapper; import org.spongepowered.configurate.serialize.SerializationException; import java.util.*; import java.util.concurrent.TimeUnit; public class ChannelConfigHelper { private final DiscordSRV discordSRV; // game channel name eg. "global" -> game channel ("discordsrv:global") private final LoadingCache<String, GameChannel> nameToChannelCache; // game channel name -> config private final Map<String, BaseChannelConfig> configs; // caches for Discord channel -> config private final Map<Long, Map<String, BaseChannelConfig>> textChannelToConfigMap; private final Map<Pair<Long, String>, Map<String, BaseChannelConfig>> threadToConfigMap; public ChannelConfigHelper(DiscordSRV discordSRV) { this.discordSRV = discordSRV; this.nameToChannelCache = discordSRV.caffeineBuilder() .expireAfterWrite(60, TimeUnit.SECONDS) .expireAfterAccess(30, TimeUnit.SECONDS) .refreshAfterWrite(10, TimeUnit.SECONDS) .build(new CacheLoader<String, GameChannel>() { @Override public @Nullable GameChannel load(@NonNull String channelName) { GameChannelLookupEvent event = new GameChannelLookupEvent(null, channelName); discordSRV.eventBus().publish(event); if (!event.isProcessed()) { return null; } return event.getChannelFromProcessing(); } }); this.configs = new HashMap<>(); this.textChannelToConfigMap = new HashMap<>(); this.threadToConfigMap = new LinkedHashMap<>(); } @SuppressWarnings("unchecked") private BaseChannelConfig map(BaseChannelConfig defaultConfig, BaseChannelConfig config) throws SerializationException { MainConfigManager<?> configManager = discordSRV.configManager(); CommentedConfigurationNode defaultNode = CommentedConfigurationNode.root(configManager.nodeOptions(true)); CommentedConfigurationNode target = CommentedConfigurationNode.root(configManager.nodeOptions(true)); configManager.objectMapper() .get((Class<BaseChannelConfig>) defaultConfig.getClass()) .save(defaultConfig, defaultNode); ObjectMapper<BaseChannelConfig> mapper = configManager.objectMapper() .get((Class<BaseChannelConfig>) config.getClass()); mapper.save(config, target); target.mergeFrom(defaultNode); return mapper.load(target); } public void reload() throws SerializationException { Map<String, BaseChannelConfig> configChannels = discordSRV.config().channels; BaseChannelConfig defaultConfig = configChannels.computeIfAbsent(ChannelConfig.DEFAULT_KEY, key -> discordSRV.config().createDefaultBaseChannel()); Map<String, BaseChannelConfig> configs = new HashMap<>(); for (Map.Entry<String, BaseChannelConfig> entry : configChannels.entrySet()) { if (Objects.equals(entry.getKey(), ChannelConfig.DEFAULT_KEY)) { continue; } BaseChannelConfig mapped = map(defaultConfig, entry.getValue()); configs.put(entry.getKey(), mapped); } synchronized (this.configs) { this.configs.clear(); this.configs.putAll(configs); } Map<Long, Map<String, BaseChannelConfig>> text = new HashMap<>(); Map<Pair<Long, String>, Map<String, BaseChannelConfig>> thread = new HashMap<>(); for (Map.Entry<String, BaseChannelConfig> entry : channels().entrySet()) { String channelName = entry.getKey(); BaseChannelConfig value = entry.getValue(); if (value instanceof IChannelConfig) { DestinationConfig destination = ((IChannelConfig) value).destination(); List<Long> channelIds = destination.channelIds; if (channelIds != null) { for (long channelId : channelIds) { text.computeIfAbsent(channelId, key -> new LinkedHashMap<>()) .put(channelName, value); } } List<ThreadConfig> threads = destination.threads; if (threads != null) { for (ThreadConfig threadConfig : threads) { Pair<Long, String> pair = Pair.of( threadConfig.channelId, threadConfig.threadName.toLowerCase(Locale.ROOT) ); thread.computeIfAbsent(pair, key -> new LinkedHashMap<>()) .put(channelName, value); } } } } synchronized (textChannelToConfigMap) { textChannelToConfigMap.clear(); textChannelToConfigMap.putAll(text); } synchronized (threadToConfigMap) { threadToConfigMap.clear(); threadToConfigMap.putAll(thread); } } private Map<String, BaseChannelConfig> channels() { synchronized (configs) { return configs; } } private BaseChannelConfig findChannel(String key) { Map<String, BaseChannelConfig> channels = channels(); BaseChannelConfig byExact = channels.get(key); if (byExact != null) { return byExact; } for (Map.Entry<String, BaseChannelConfig> entry : channels.entrySet()) { if (entry.getKey().equalsIgnoreCase(key)) { return entry.getValue(); } } return null; } public Set<String> getKeys() { Set<String> keys = new LinkedHashSet<>(channels().keySet()); keys.remove(ChannelConfig.DEFAULT_KEY); return keys; } public Set<BaseChannelConfig> getAllChannels() { Set<BaseChannelConfig> channelConfigs = new HashSet<>(); for (Map.Entry<String, BaseChannelConfig> entry : channels().entrySet()) { if (entry.getKey().equals(ChannelConfig.DEFAULT_KEY)) { continue; } channelConfigs.add(entry.getValue()); } return channelConfigs; } public BaseChannelConfig get(GameChannel gameChannel) { return resolve(gameChannel.getOwnerName(), gameChannel.getChannelName()); } public BaseChannelConfig resolve(String ownerName, String channelName) { if (ownerName != null) { ownerName = ownerName.toLowerCase(Locale.ROOT); // Check if there is a channel defined like this: "owner:channel" BaseChannelConfig config = findChannel(ownerName + ":" + channelName); if (config != null) { return config; } // Check if this owner has the highest priority for this channel name GameChannel gameChannel = nameToChannelCache.get(channelName); if (gameChannel != null && gameChannel.getOwnerName().equalsIgnoreCase(ownerName)) { config = findChannel(channelName); return config; } return null; } // Get the highest priority owner for this channel name and relookup GameChannel gameChannel = nameToChannelCache.get(channelName); return gameChannel != null ? get(gameChannel) : null; } public Map<GameChannel, BaseChannelConfig> resolve(DiscordMessageChannel channel) { Map<String, BaseChannelConfig> pairs = get(channel); if (pairs == null || pairs.isEmpty()) { return Collections.emptyMap(); } Map<GameChannel, BaseChannelConfig> channels = new LinkedHashMap<>(); for (Map.Entry<String, BaseChannelConfig> entry : pairs.entrySet()) { GameChannel gameChannel = nameToChannelCache.get(entry.getKey()); if (gameChannel == null) { continue; } channels.put(gameChannel, entry.getValue()); } return channels; } private Map<String, BaseChannelConfig> get(DiscordMessageChannel channel) { Map<String, BaseChannelConfig> pairs = null; if (channel instanceof DiscordTextChannel) { pairs = getByTextChannel((DiscordTextChannel) channel); } else if (channel instanceof DiscordThreadChannel) { pairs = getByThreadChannel((DiscordThreadChannel) channel); } return pairs; } private Map<String, BaseChannelConfig> getByTextChannel(DiscordTextChannel channel) { synchronized (textChannelToConfigMap) { return textChannelToConfigMap.get(channel.getId()); } } private Map<String, BaseChannelConfig> getByThreadChannel(DiscordThreadChannel channel) { Pair<Long, String> pair = Pair.of( channel.getParentChannel().getId(), channel.getName().toLowerCase(Locale.ROOT) ); synchronized (threadToConfigMap) { return threadToConfigMap.get(pair); } } }
11,303
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
TimedUpdaterModule.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/channel/TimedUpdaterModule.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.channel; import com.discordsrv.api.DiscordSRVApi; import com.discordsrv.api.discord.connection.jda.errorresponse.ErrorCallbackContext; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.ServerDiscordSRV; import com.discordsrv.common.config.main.TimedUpdaterConfig; import com.discordsrv.common.logging.NamedLogger; import com.discordsrv.common.module.type.AbstractModule; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel; import net.dv8tion.jda.api.managers.channel.ChannelManager; import net.dv8tion.jda.api.managers.channel.concrete.TextChannelManager; import org.apache.commons.lang3.StringUtils; import java.time.Duration; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; public class TimedUpdaterModule extends AbstractModule<DiscordSRV> { private final Set<ScheduledFuture<?>> futures = new LinkedHashSet<>(); private boolean firstReload = true; public TimedUpdaterModule(DiscordSRV discordSRV) { super(discordSRV, new NamedLogger(discordSRV, "CHANNEL_UPDATER")); } @Override public boolean isEnabled() { boolean any = false; TimedUpdaterConfig config = discordSRV.config().timedUpdater; for (TimedUpdaterConfig.UpdaterConfig updaterConfig : config.getConfigs()) { if (updaterConfig.any()) { any = true; break; } } if (!any) { return false; } return super.isEnabled() && discordSRV.isReady() && (!(discordSRV instanceof ServerDiscordSRV) || ((ServerDiscordSRV<?, ?, ?, ?>) discordSRV).isServerStarted()); } @Override public void reload(Consumer<DiscordSRVApi.ReloadResult> resultConsumer) { futures.forEach(future -> future.cancel(false)); futures.clear(); TimedUpdaterConfig config = discordSRV.config().timedUpdater; for (TimedUpdaterConfig.UpdaterConfig updaterConfig : config.getConfigs()) { long time = Math.max(updaterConfig.timeSeconds(), updaterConfig.minimumSeconds()); futures.add(discordSRV.scheduler().runAtFixedRate( () -> update(updaterConfig), firstReload ? Duration.ZERO : Duration.ofSeconds(time), Duration.ofSeconds(time) )); } firstReload = false; } public void update(TimedUpdaterConfig.UpdaterConfig config) { JDA jda = discordSRV.jda(); if (jda == null) { return; } if (config instanceof TimedUpdaterConfig.VoiceChannelConfig) { updateChannel( jda, ((TimedUpdaterConfig.VoiceChannelConfig) config).channelIds, ((TimedUpdaterConfig.VoiceChannelConfig) config).nameFormat, null ); } else if (config instanceof TimedUpdaterConfig.TextChannelConfig) { updateChannel( jda, ((TimedUpdaterConfig.TextChannelConfig) config).channelIds, ((TimedUpdaterConfig.TextChannelConfig) config).nameFormat, ((TimedUpdaterConfig.TextChannelConfig) config).topicFormat ); } } private void updateChannel(JDA jda, List<Long> channelIds, String nameFormat, String topicFormat) { if (topicFormat != null) { topicFormat = discordSRV.placeholderService().replacePlaceholders(topicFormat); } if (nameFormat != null) { nameFormat = discordSRV.placeholderService().replacePlaceholders(nameFormat); } for (Long channelId : channelIds) { GuildChannel channel = jda.getGuildChannelById(channelId); if (channel == null) { continue; } try { ChannelManager<?, ?> manager = channel.getManager(); boolean anythingChanged = false; if (manager instanceof TextChannelManager && channel instanceof TextChannel && StringUtils.isNotEmpty(topicFormat) && !topicFormat.equals(((TextChannel) channel).getTopic())) { anythingChanged = true; manager = ((TextChannelManager) manager).setTopic(topicFormat); } if (StringUtils.isNotEmpty(nameFormat) && !nameFormat.equals(channel.getName())) { anythingChanged = true; manager = manager.setName(nameFormat); } if (!anythingChanged) { logger().debug("Skipping updating channel " + channel + ": nothing changed"); continue; } manager.timeout(30, TimeUnit.SECONDS).queue( null, ErrorCallbackContext.context("Failed to update channel " + channel) ); } catch (Throwable t) { discordSRV.logger().error("Failed to update channel " + channel, t); } } } }
6,225
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ChannelLockingModule.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/channel/ChannelLockingModule.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.channel; import com.discordsrv.api.discord.entity.channel.DiscordGuildMessageChannel; import com.discordsrv.api.discord.entity.channel.DiscordThreadChannel; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.config.main.channels.ChannelLockingConfig; import com.discordsrv.common.config.main.channels.base.BaseChannelConfig; import com.discordsrv.common.config.main.channels.base.IChannelConfig; import com.discordsrv.common.module.type.AbstractModule; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.IPermissionHolder; import net.dv8tion.jda.api.entities.Role; import net.dv8tion.jda.api.entities.channel.attribute.IPermissionContainer; import net.dv8tion.jda.api.entities.channel.middleman.GuildMessageChannel; import net.dv8tion.jda.api.requests.restaction.PermissionOverrideAction; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.function.BiConsumer; public class ChannelLockingModule extends AbstractModule<DiscordSRV> { public ChannelLockingModule(DiscordSRV discordSRV) { super(discordSRV); } @Override public int shutdownOrder() { return Integer.MIN_VALUE; } @Override public void enable() { doForAllChannels((config, channelConfig) -> { ChannelLockingConfig shutdownConfig = config.channelLocking; ChannelLockingConfig.Channels channels = shutdownConfig.channels; ChannelLockingConfig.Threads threads = shutdownConfig.threads; discordSRV.discordAPI() .findOrCreateDestinations((BaseChannelConfig & IChannelConfig) config, threads.unarchive, true) .whenComplete((destinations, t) -> { if (channels.everyone || !channels.roleIds.isEmpty()) { for (DiscordGuildMessageChannel destination : destinations) { channelPermissions(channels, destination, true); } } }); }); } @Override public void disable() { doForAllChannels((config, channelConfig) -> { if (!(config instanceof IChannelConfig)) { return; } ChannelLockingConfig shutdownConfig = config.channelLocking; ChannelLockingConfig.Channels channels = shutdownConfig.channels; ChannelLockingConfig.Threads threads = shutdownConfig.threads; boolean archive = threads.archive; boolean isChannels = channels.everyone || !channels.roleIds.isEmpty(); if (!threads.archive && !isChannels) { return; } Collection<DiscordGuildMessageChannel> destinations = discordSRV.discordAPI() .findDestinations((BaseChannelConfig & IChannelConfig) config, true); for (DiscordGuildMessageChannel destination : destinations) { if (archive && destination instanceof DiscordThreadChannel) { ((DiscordThreadChannel) destination).asJDA().getManager() .setArchived(true) .reason("DiscordSRV channel locking") .queue(); } if (isChannels) { channelPermissions(channels, destination, false); } } }); } private void channelPermissions( ChannelLockingConfig.Channels shutdownConfig, DiscordGuildMessageChannel channel, boolean state ) { boolean everyone = shutdownConfig.everyone; List<Long> roleIds = shutdownConfig.roleIds; if (!everyone && roleIds.isEmpty()) { return; } List<Permission> permissions = new ArrayList<>(); if (shutdownConfig.read) { permissions.add(Permission.VIEW_CHANNEL); } if (shutdownConfig.write) { permissions.add(Permission.MESSAGE_SEND); } if (shutdownConfig.addReactions) { permissions.add(Permission.MESSAGE_ADD_REACTION); } GuildMessageChannel messageChannel = (GuildMessageChannel) channel.getAsJDAMessageChannel(); if (!(messageChannel instanceof IPermissionContainer)) { return; } Guild guild = messageChannel.getGuild(); if (!guild.getSelfMember().hasPermission(messageChannel, Permission.MANAGE_PERMISSIONS)) { logger().error("Cannot change permissions of " + channel + ": lacking \"Manage Permissions\" permission"); return; } if (everyone) { setPermission((IPermissionContainer) messageChannel, guild.getPublicRole(), permissions, state); } for (Long roleId : roleIds) { Role role = guild.getRoleById(roleId); if (role == null) { continue; } setPermission((IPermissionContainer) messageChannel, role, permissions, state); } } private void setPermission(IPermissionContainer channel, IPermissionHolder holder, List<Permission> permissions, boolean state) { PermissionOverrideAction action = channel.upsertPermissionOverride(holder); if ((state ? action.getAllowedPermissions() : action.getDeniedPermissions()).containsAll(permissions)) { // Already correct return; } if (state) { action = action.grant(permissions); } else { action = action.deny(permissions); } action.reason("DiscordSRV channel locking").queue(); } private void doForAllChannels(BiConsumer<BaseChannelConfig, IChannelConfig> channelConsumer) { for (BaseChannelConfig config : discordSRV.channelConfig().getAllChannels()) { IChannelConfig channelConfig = config instanceof IChannelConfig ? (IChannelConfig) config : null; if (channelConfig == null) { continue; } channelConsumer.accept(config, channelConfig); } } }
7,060
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
GlobalChannelLookupModule.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/channel/GlobalChannelLookupModule.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.channel; import com.discordsrv.api.event.bus.EventPriority; import com.discordsrv.api.event.bus.Subscribe; import com.discordsrv.api.event.events.channel.GameChannelLookupEvent; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.module.type.AbstractModule; public class GlobalChannelLookupModule extends AbstractModule<DiscordSRV> { public GlobalChannelLookupModule(DiscordSRV discordSRV) { super(discordSRV); } @Subscribe(priority = EventPriority.LATE) public void onGameChannelLookup(GameChannelLookupEvent event) { if (event.getChannelName().equalsIgnoreCase("global")) { if (checkProcessor(event)) { return; } event.process(new GlobalChannel(discordSRV)); } } }
1,646
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
GlobalChannel.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/channel/GlobalChannel.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.channel; import com.discordsrv.api.channel.GameChannel; import com.discordsrv.api.player.DiscordSRVPlayer; import com.discordsrv.common.DiscordSRV; import org.jetbrains.annotations.NotNull; import java.util.Collection; public class GlobalChannel implements GameChannel { private final DiscordSRV discordSRV; public GlobalChannel(DiscordSRV discordSRV) { this.discordSRV = discordSRV; } @Override public @NotNull String getOwnerName() { return "DiscordSRV"; } @Override public @NotNull String getChannelName() { return "global"; } @Override public boolean isChat() { return true; } @Override public @NotNull Collection<? extends DiscordSRVPlayer> getRecipients() { return discordSRV.playerProvider().allPlayers(); } }
1,686
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
UUIDUtil.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/uuid/util/UUIDUtil.java
package com.discordsrv.common.uuid.util; import com.discordsrv.api.placeholder.annotation.Placeholder; import com.discordsrv.api.placeholder.annotation.PlaceholderPrefix; import org.jetbrains.annotations.NotNull; import java.util.UUID; @PlaceholderPrefix("uuid_") public final class UUIDUtil { private UUIDUtil() {} public static UUID fromShortOrFull(@NotNull String uuidString) { int length = uuidString.length(); if (length == 32) { return fromShort(uuidString); } else if (length == 36) { return UUID.fromString(uuidString); } throw new IllegalArgumentException("Not a valid 36 or 32 character long UUID"); } public static UUID fromShort(@NotNull String shortUUID) { if (shortUUID.length() != 32) { throw new IllegalArgumentException("Short uuids are 32 characters long"); } String fullLengthUUID = shortUUID.substring(0, 8) + "-" + shortUUID.substring(8, 12) + "-" + shortUUID.substring(12, 16) + "-" + shortUUID.substring(16, 20) + "-" + shortUUID.substring(20); return UUID.fromString(fullLengthUUID); } @Placeholder("short") public static String toShort(@NotNull UUID uuid) { return uuid.toString().replace("-", ""); } }
1,348
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
PluginManager.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/plugin/PluginManager.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.plugin; import java.util.List; public interface PluginManager { boolean isPluginEnabled(String pluginIdentifier); List<Plugin> getPlugins(); }
1,015
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
Plugin.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/plugin/Plugin.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.plugin; import com.fasterxml.jackson.annotation.JsonProperty; import java.util.List; public class Plugin { @JsonProperty("identifier") private final String identifier; @JsonProperty("name") private final String name; @JsonProperty("version") private final String version; @JsonProperty("authors") private final List<String> authors; public Plugin(String name, String version, List<String> authors) { this(name, name, version, authors); } public Plugin(String identifier, String name, String version, List<String> authors) { this.identifier = identifier; this.name = name; this.version = version; this.authors = authors; } public String identifier() { return identifier; } public String name() { return name; } public String version() { return version; } public List<String> authors() { return authors; } }
1,828
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
TestHelper.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/testing/TestHelper.java
package com.discordsrv.common.testing; import java.util.function.Consumer; public final class TestHelper { private static final ThreadLocal<Consumer<Throwable>> error = new ThreadLocal<>(); public static void fail(Throwable throwable) { Consumer<Throwable> handler = error.get(); if (handler != null) { handler.accept(throwable); } } public static void set(Consumer<Throwable> handler) { error.set(handler); } }
481
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DebugReport.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/debug/DebugReport.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.debug; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.config.configurate.manager.MessagesConfigSingleManager; import com.discordsrv.common.config.configurate.manager.abstraction.ConfigurateConfigManager; import com.discordsrv.common.config.connection.ConnectionConfig; import com.discordsrv.common.config.connection.StorageConfig; import com.discordsrv.common.config.messages.MessagesConfig; import com.discordsrv.common.debug.file.DebugFile; import com.discordsrv.common.debug.file.KeyValueDebugFile; import com.discordsrv.common.debug.file.TextDebugFile; import com.discordsrv.common.exception.ConfigException; import com.discordsrv.common.paste.Paste; import com.discordsrv.common.paste.PasteService; import com.discordsrv.common.plugin.Plugin; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import net.dv8tion.jda.api.JDA; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.spongepowered.configurate.CommentedConfigurationNode; import org.spongepowered.configurate.loader.AbstractConfigurationLoader; import java.io.BufferedWriter; import java.io.IOException; import java.io.StringWriter; import java.nio.charset.StandardCharsets; import java.nio.file.FileStore; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.*; import java.util.stream.Collectors; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class DebugReport { private static final int BIG_FILE_SPLIT_SIZE = 50000; private final List<DebugFile> files = new ArrayList<>(); private final DiscordSRV discordSRV; public DebugReport(DiscordSRV discordSRV) { this.discordSRV = discordSRV; } public void generate() { discordSRV.eventBus().publish(new DebugGenerateEvent(this)); addFile(environment()); // 100 addFile(plugins()); // 90 for (Path debugLog : discordSRV.logger().getDebugLogs()) { addFile(readFile(80, debugLog, null)); } addFile(config(79, discordSRV.configManager(), null)); addFile(rawConfig(79, discordSRV.configManager(), null)); Locale defaultLocale = discordSRV.defaultLocale(); for (MessagesConfigSingleManager<? extends MessagesConfig> manager : discordSRV.messagesConfigManager().getAllManagers().values()) { if (manager.locale() == defaultLocale) { addFile(config(78, manager, "parsed_messages.yaml")); addFile(rawConfig(78, manager, "messages.yaml")); } else { addFile(config(78, manager, "parsed_" + manager.locale() + "_messages.yaml")); addFile(rawConfig(78, manager, manager.locale() + "_messages.yaml")); } } addFile(activeLimitedConnectionsConfig()); // 77 } public Paste upload(PasteService service) throws Throwable { files.sort(Comparator.comparing(DebugFile::order).reversed()); ArrayNode files = discordSRV.json().createArrayNode(); for (DebugFile file : this.files) { int length = file.content().length(); if (length >= BIG_FILE_SPLIT_SIZE) { ObjectNode node = discordSRV.json().createObjectNode(); node.put("name", file.name()); try { Paste paste = service.uploadFile(convertToJson(file).toString().getBytes(StandardCharsets.UTF_8)); node.put("url", paste.url()); node.put("decryption_key", new String(Base64.getUrlEncoder().encode(paste.decryptionKey()), StandardCharsets.UTF_8)); node.put("length", length); } catch (Throwable e) { node.put("content", "Failed to upload file\n\n" + ExceptionUtils.getStackTrace(e)); } files.add(node); continue; } files.add(convertToJson(file)); } return service.uploadFile(files.toString().getBytes(StandardCharsets.UTF_8)); } public Path zip() throws Throwable { Path zipPath = discordSRV.dataDirectory().resolve("debug-" + System.currentTimeMillis() + ".zip"); try (ZipOutputStream zipOutputStream = new ZipOutputStream(Files.newOutputStream(zipPath))) { for (DebugFile file : files) { zipOutputStream.putNextEntry(new ZipEntry(file.name())); byte[] data = file.content().getBytes(StandardCharsets.UTF_8); zipOutputStream.write(data, 0, data.length); zipOutputStream.closeEntry(); } } return zipPath; } private ObjectNode convertToJson(DebugFile file) { ObjectNode node = discordSRV.json().createObjectNode(); node.put("name", file.name()); node.put("content", file.content()); return node; } public void addFile(DebugFile file) { if (file != null) { files.add(file); } } private DebugFile environment() { Map<String, Object> values = new LinkedHashMap<>(); values.put("discordSRV", discordSRV.getClass().getName()); values.put("version", discordSRV.versionInfo().version()); values.put("gitRevision", discordSRV.versionInfo().gitRevision()); values.put("gitBranch", discordSRV.versionInfo().gitBranch()); values.put("buildTime", discordSRV.versionInfo().buildTime()); values.put("status", discordSRV.status().name()); JDA jda = discordSRV.jda(); values.put("jdaStatus", jda != null ? jda.getStatus().name() : "JDA null"); values.put("platformLogger", discordSRV.platformLogger().getClass().getName()); values.put("onlineMode", discordSRV.onlineMode().name()); values.put("offlineModeUuid", discordSRV.playerProvider().isAnyOffline()); values.put("javaVersion", System.getProperty("java.version")); values.put("javaVendor", System.getProperty("java.vendor") + " (" + System.getProperty("java.vendor.url") + ")"); values.put("operatingSystem", System.getProperty("os.name") + " (" + System.getProperty("os.arch") + ")"); values.put("operatingSystemVersion", System.getProperty("os.version")); Runtime runtime = Runtime.getRuntime(); values.put("cores", runtime.availableProcessors()); values.put("freeMemory", runtime.freeMemory()); values.put("totalMemory", runtime.totalMemory()); long maxMemory = runtime.maxMemory(); values.put("maxMemory", maxMemory == Long.MAX_VALUE ? -1 : maxMemory); try { FileStore store = Files.getFileStore(discordSRV.dataDirectory()); values.put("usableSpace", store.getUsableSpace()); values.put("totalSpace", store.getTotalSpace()); } catch (IOException ignored) {} boolean docker = false; try { docker = Files.readAllLines(Paths.get("/proc/1/cgroup")) .stream().anyMatch(str -> str.contains("/docker/")); } catch (IOException ignored) {} values.put("docker", docker); return new KeyValueDebugFile(100, "environment.json", values); } private DebugFile plugins() { List<Plugin> plugins = discordSRV.pluginManager().getPlugins() .stream() .sorted(Comparator.comparing(plugin -> plugin.name().toLowerCase(Locale.ROOT))) .collect(Collectors.toList()); int order = 90; String fileName = "plugins.json"; try { String json = discordSRV.json().writeValueAsString(plugins); return new TextDebugFile(order, fileName, json); } catch (JsonProcessingException e) { return exception(order, fileName, e); } } private DebugFile config(int order, ConfigurateConfigManager<?, ?> manager, String overrideFileName) { String fileName = overrideFileName != null ? overrideFileName : "parsed_" + manager.fileName(); try (StringWriter writer = new StringWriter()) { AbstractConfigurationLoader<CommentedConfigurationNode> loader = manager .createLoader(manager.filePath(), manager.nodeOptions(true)) .sink(() -> new BufferedWriter(writer)) .build(); manager.save(loader); return new TextDebugFile(order, fileName, writer.toString()); } catch (IOException | ConfigException e) { return exception(order, fileName, e); } } private DebugFile rawConfig(int order, ConfigurateConfigManager<?, ?> manager, String overwriteFileName) { return readFile(order, manager.filePath(), overwriteFileName); } private DebugFile activeLimitedConnectionsConfig() { ConnectionConfig config = discordSRV.connectionConfig(); StorageConfig.Pool poolConfig = config.storage.remote.poolOptions; Map<String, Object> values = new LinkedHashMap<>(); values.put("minecraft-auth.allow", config.minecraftAuth.allow); values.put("minecraft-auth.token_set", StringUtils.isNotBlank(config.minecraftAuth.token)); values.put("storage.backend", config.storage.backend); values.put("storage.sql-table-prefix", config.storage.sqlTablePrefix); values.put("storage.remote.pool-options.keepalive-time", poolConfig.keepaliveTime); values.put("storage.remote.pool-options.maxiumum-lifetime", poolConfig.maximumLifetime); values.put("storage.remote.pool-options.maximum-pool-size", poolConfig.maximumPoolSize); values.put("storage.remote.pool-options.minimum-pool-size", poolConfig.minimumPoolSize); values.put("update.notification-enabled", config.update.notificationEnabled); values.put("update.notification-in-game", config.update.notificationInGame); values.put("update.first-party-notification", config.update.firstPartyNotification); values.put("update.github.enabled", config.update.github.enabled); values.put("update.github.api-token_set", StringUtils.isNotBlank(config.update.github.apiToken)); values.put("update.security.enabled", config.update.security.enabled); values.put("update.security.force", config.update.security.force); return new KeyValueDebugFile(77, "connections.json", values, true); } private DebugFile readFile(int order, Path file, String overwriteFileName) { String fileName = overwriteFileName != null ? overwriteFileName : file.getFileName().toString(); if (!Files.exists(file)) { return new TextDebugFile(order, fileName, "File does not exist"); } try { List<String> lines = Files.readAllLines(file, StandardCharsets.UTF_8); return new TextDebugFile(order, fileName, String.join("\n", lines)); } catch (IOException e) { return exception(order, fileName, e); } } private DebugFile exception(int order, String fileName, Throwable throwable) { return new TextDebugFile(order, fileName, ExceptionUtils.getStackTrace(throwable)); } }
12,211
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DebugGenerateEvent.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/debug/DebugGenerateEvent.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.debug; import com.discordsrv.api.event.events.Event; import com.discordsrv.common.debug.file.DebugFile; public class DebugGenerateEvent implements Event { private final DebugReport report; public DebugGenerateEvent(DebugReport report) { this.report = report; } public void addFile(DebugFile file) { report.addFile(file); } }
1,226
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
OnlineMode.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/debug/data/OnlineMode.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.debug.data; public enum OnlineMode { ONLINE(true), OFFLINE(false), BUNGEE(true), VELOCITY(true); private final boolean online; OnlineMode(boolean online) { this.online = online; } public boolean isOnline() { return online; } public static OnlineMode of(boolean onlineMode) { return onlineMode ? OnlineMode.ONLINE : OnlineMode.OFFLINE; } }
1,274
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
VersionInfo.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/debug/data/VersionInfo.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.debug.data; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class VersionInfo { private final String version; private final String gitRevision; private final String gitBranch; private final String buildTime; public VersionInfo(String version, String gitRevision, String gitBranch, String buildTime) { this.version = version; this.gitRevision = gitRevision; this.gitBranch = gitBranch; this.buildTime = buildTime; } @NotNull public String version() { return version; } public boolean isSnapshot() { return version.endsWith("-SNAPSHOT"); } @Nullable public String gitRevision() { return gitRevision; } @Nullable public String gitBranch() { return gitBranch; } @NotNull public String buildTime() { return buildTime; } }
1,782
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
KeyValueDebugFile.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/debug/file/KeyValueDebugFile.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.debug.file; import com.fasterxml.jackson.databind.ObjectMapper; import org.apache.commons.lang3.exception.ExceptionUtils; import java.io.IOException; import java.util.Map; public class KeyValueDebugFile implements DebugFile { private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); private final int order; private final String name; private final Map<String, Object> values; private final boolean prettyPrint; public KeyValueDebugFile(int order, String name, Map<String, Object> values) { this(order, name, values, false); } public KeyValueDebugFile(int order, String name, Map<String, Object> values, boolean prettyPrint) { this.order = order; this.name = name; this.values = values; this.prettyPrint = prettyPrint; } @Override public int order() { return order; } @Override public String name() { return name; } @Override public String content() { try { if (prettyPrint) { return OBJECT_MAPPER.writerWithDefaultPrettyPrinter().writeValueAsString(values); } else { return OBJECT_MAPPER.writeValueAsString(values); } } catch (IOException e) { return ExceptionUtils.getStackTrace(e); } } }
2,206
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
TextDebugFile.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/debug/file/TextDebugFile.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.debug.file; public class TextDebugFile implements DebugFile { private final int order; private final String name; private final String content; public TextDebugFile(String name, CharSequence content) { this(0, name, content); } public TextDebugFile(int order, String name, CharSequence content) { this.order = order; this.name = name; this.content = content.toString(); } public int order() { return order; } public String name() { return name; } public String content() { return content; } }
1,469
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DebugFile.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/debug/file/DebugFile.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.debug.file; public interface DebugFile { int order(); String name(); String content(); }
963
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
Console.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/console/Console.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.console; import com.discordsrv.common.command.game.executor.CommandExecutorProvider; import com.discordsrv.common.command.game.sender.ICommandSender; import com.discordsrv.common.logging.backend.LoggingBackend; public interface Console extends ICommandSender { /** * Gets the logging backend for the server/proxy. * @return the {@link LoggingBackend} */ LoggingBackend loggingBackend(); CommandExecutorProvider commandExecutorProvider(); }
1,331
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
SingleConsoleHandler.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/console/SingleConsoleHandler.java
package com.discordsrv.common.console; import com.discordsrv.api.discord.entity.DiscordUser; import com.discordsrv.api.discord.entity.channel.DiscordGuildChannel; import com.discordsrv.api.discord.entity.channel.DiscordGuildMessageChannel; import com.discordsrv.api.discord.entity.channel.DiscordMessageChannel; import com.discordsrv.api.discord.entity.channel.DiscordThreadChannel; import com.discordsrv.api.discord.entity.guild.DiscordGuildMember; import com.discordsrv.api.discord.entity.message.ReceivedDiscordMessage; import com.discordsrv.api.discord.entity.message.SendableDiscordMessage; import com.discordsrv.api.discord.util.DiscordFormattingUtil; import com.discordsrv.api.event.bus.Subscribe; import com.discordsrv.api.event.events.discord.message.DiscordMessageReceiveEvent; import com.discordsrv.api.placeholder.PlainPlaceholderFormat; import com.discordsrv.api.placeholder.provider.SinglePlaceholder; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.command.game.GameCommandExecutionHelper; import com.discordsrv.common.config.main.ConsoleConfig; import com.discordsrv.common.config.main.generic.DestinationConfig; import com.discordsrv.common.config.main.generic.GameCommandExecutionConditionConfig; import com.discordsrv.common.console.entry.LogEntry; import com.discordsrv.common.console.entry.LogMessage; import com.discordsrv.common.console.message.ConsoleMessage; import com.discordsrv.common.logging.LogLevel; import com.discordsrv.common.logging.Logger; import net.dv8tion.jda.api.entities.Message; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import java.time.Duration; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; /** * The log appending and command handling for a single console channel. */ public class SingleConsoleHandler { private static final int MESSAGE_MAX_LENGTH = Message.MAX_CONTENT_LENGTH; private final DiscordSRV discordSRV; private final Logger logger; private final ConsoleConfig config; private final Queue<LogEntry> queue; private Future<?> queueProcessingFuture; private boolean shutdown = false; // Editing private final List<LogMessage> messageCache; private Long mostRecentMessageId; // Preventing concurrent sends private final Object sendLock = new Object(); private CompletableFuture<?> sendFuture; // Don't annoy console users twice about using / private final Set<Long> warnedSlashUsageUserIds = new HashSet<>(); public SingleConsoleHandler(DiscordSRV discordSRV, Logger logger, ConsoleConfig config) { this.discordSRV = discordSRV; this.logger = logger; this.config = config; this.queue = config.appender.outputMode != ConsoleConfig.OutputMode.OFF ? new LinkedBlockingQueue<>() : null; this.messageCache = config.appender.useEditing ? new ArrayList<>() : null; timeQueueProcess(); discordSRV.eventBus().subscribe(this); } @Subscribe public void onDiscordMessageReceived(DiscordMessageReceiveEvent event) { DiscordMessageChannel messageChannel = event.getChannel(); DiscordGuildChannel channel = messageChannel instanceof DiscordGuildChannel ? (DiscordGuildChannel) messageChannel : null; if (channel == null) { return; } ReceivedDiscordMessage message = event.getMessage(); if (message.isFromSelf()) { return; } String command = event.getMessage().getContent(); if (command == null) { return; } DestinationConfig.Single destination = config.channel; String threadName = destination.threadName; DiscordGuildChannel checkChannel; if (StringUtils.isNotEmpty(threadName)) { if (!(channel instanceof DiscordThreadChannel)) { return; } if (!channel.getName().equals(threadName)) { return; } checkChannel = ((DiscordThreadChannel) channel).getParentChannel(); } else { checkChannel = channel; } if (checkChannel.getId() != destination.channelId) { return; } DiscordUser user = message.getAuthor(); DiscordGuildMember member = message.getMember(); GameCommandExecutionHelper helper = discordSRV.executeHelper(); if (command.startsWith("/") && config.commandExecution.enableSlashWarning) { long userId = user.getId(); boolean newUser; synchronized (warnedSlashUsageUserIds) { newUser = !warnedSlashUsageUserIds.contains(userId); if (newUser) { warnedSlashUsageUserIds.add(userId); } } if (newUser) { // TODO: translation message.reply( SendableDiscordMessage.builder() .setContent("Your command was prefixed with `/`, but normally commands in the Minecraft server console should **not** begin with `/`") .build() ); } } boolean pass = false; for (GameCommandExecutionConditionConfig filter : config.commandExecution.executionConditions) { if (filter.isAcceptableCommand(member, user, command, false, helper)) { pass = true; break; } } if (!pass) { if (!user.isBot()) { // TODO: translation message.reply( SendableDiscordMessage.builder() .setContent("You are not allowed to run that command") .build() ); } return; } // Split message when editing if (messageCache != null) { messageCache.clear(); } mostRecentMessageId = null; // Run the command discordSRV.console().runCommandWithLogging(discordSRV, user, command); } public void queue(LogEntry entry) { if (queue == null) { return; } queue.offer(entry); } @SuppressWarnings("SynchronizeOnNonFinalField") public void shutdown() { shutdown = true; discordSRV.eventBus().unsubscribe(this); queueProcessingFuture.cancel(false); try { synchronized (queueProcessingFuture) { queueProcessingFuture.wait(TimeUnit.SECONDS.toMillis(3)); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } queue.clear(); if (messageCache != null) { messageCache.clear(); } mostRecentMessageId = null; } private void timeQueueProcess() { if (shutdown) { return; } if (config.appender.outputMode == ConsoleConfig.OutputMode.OFF) { return; } this.queueProcessingFuture = discordSRV.scheduler().runLater(this::processQueue, Duration.ofSeconds(2)); } private void processQueue() { try { ConsoleConfig.Appender appenderConfig = config.appender; ConsoleConfig.OutputMode outputMode = appenderConfig.outputMode; Queue<LogMessage> currentBuffer = new LinkedBlockingQueue<>(); LogEntry entry; while ((entry = queue.poll()) != null) { String level = entry.level().name(); if (appenderConfig.levels.levels.contains(level) == appenderConfig.levels.blacklist) { // Ignored level continue; } String loggerName = entry.loggerName(); if (StringUtils.isEmpty(loggerName)) loggerName = "NONE"; if (appenderConfig.loggers.loggers.contains(loggerName) == appenderConfig.loggers.blacklist) { // Ignored logger continue; } List<String> messages = formatEntry(entry, outputMode, config.appender.diffExceptions); if (messages.size() == 1) { LogMessage message = new LogMessage(entry, messages.get(0)); currentBuffer.add(message); } else { clearBuffer(currentBuffer, outputMode); for (String message : messages) { send(message, true, outputMode); } } } clearBuffer(currentBuffer, outputMode); } catch (Exception ex) { logger.error("Failed to process console lines", ex); } if (sendFuture != null) { sendFuture.whenComplete((__, ___) -> { sendFuture = null; timeQueueProcess(); }); } else { timeQueueProcess(); } } private void clearBuffer(Queue<LogMessage> currentBuffer, ConsoleConfig.OutputMode outputMode) { if (currentBuffer.isEmpty()) { return; } int blockLength = outputMode.blockLength(); StringBuilder builder = new StringBuilder(); if (messageCache != null) { for (LogMessage logMessage : messageCache) { builder.append(logMessage.formatted()); } } LogMessage current; while ((current = currentBuffer.poll()) != null) { String formatted = current.formatted(); if (formatted.length() + builder.length() + blockLength > MESSAGE_MAX_LENGTH) { send(builder.toString(), true, outputMode); builder.setLength(0); if (messageCache != null) { messageCache.clear(); } } builder.append(formatted); if (messageCache != null) { messageCache.add(current); } } if (builder.length() > 0) { send(builder.toString(), false, outputMode); } } private void send(String message, boolean isFull, ConsoleConfig.OutputMode outputMode) { SendableDiscordMessage sendableMessage = SendableDiscordMessage.builder() .setContent(outputMode.prefix() + message + outputMode.suffix()) .setSuppressedNotifications(config.appender.silentMessages) .setSuppressedEmbeds(config.appender.disableLinkEmbeds) .build(); synchronized (sendLock) { CompletableFuture<?> future = sendFuture != null ? sendFuture : CompletableFuture.completedFuture(null); sendFuture = future .thenCompose(__ -> discordSRV.discordAPI() .findOrCreateDestinations(config.channel.asDestination(), true, true, true) ) .thenApply(channels -> { if (channels.isEmpty()) { // Nowhere to send to return null; } DiscordGuildMessageChannel channel = channels.iterator().next(); if (mostRecentMessageId != null) { long messageId = mostRecentMessageId; if (isFull) { mostRecentMessageId = null; } return channel.editMessageById(messageId, sendableMessage); } return channel.sendMessage(sendableMessage) .whenComplete((receivedMessage, t) -> { if (receivedMessage != null && messageCache != null) { mostRecentMessageId = receivedMessage.getId(); } }); }).exceptionally(ex -> { String error = "Failed to send message to console channel"; if (message.contains(error)) { // Prevent infinite loop of the same error return null; } logger.error(error, ex); return null; }); } } private List<String> formatEntry(LogEntry entry, ConsoleConfig.OutputMode outputMode, boolean diffExceptions) { int blockLength = outputMode.blockLength(); int maximumPart = MESSAGE_MAX_LENGTH - blockLength - "\n".length(); // Escape content String plainMessage = entry.message(); if (outputMode != ConsoleConfig.OutputMode.MARKDOWN) { if (outputMode == ConsoleConfig.OutputMode.PLAIN_CONTENT) { plainMessage = DiscordFormattingUtil.escapeContent(plainMessage); } else { plainMessage = plainMessage.replace("``", "`\u200B`"); // zero-width-space } } String parsedMessage; ConsoleMessage consoleMessage = new ConsoleMessage(discordSRV, plainMessage); switch (outputMode) { case ANSI: parsedMessage = consoleMessage.asAnsi(); break; case MARKDOWN: parsedMessage = consoleMessage.asMarkdown(); break; default: parsedMessage = consoleMessage.asPlain(); break; } String message = PlainPlaceholderFormat.supplyWith( outputMode == ConsoleConfig.OutputMode.PLAIN_CONTENT ? PlainPlaceholderFormat.Formatting.DISCORD : PlainPlaceholderFormat.Formatting.PLAIN, () -> discordSRV.placeholderService().replacePlaceholders( config.appender.lineFormat, entry, new SinglePlaceholder("message", parsedMessage) ) ); Throwable thrown = entry.throwable(); String throwable = thrown != null ? ExceptionUtils.getStackTrace(thrown) : StringUtils.EMPTY; if (outputMode == ConsoleConfig.OutputMode.DIFF) { String diff = getLogLevelDiffCharacter(entry.level()); if (!message.isEmpty()) { message = diff + message.replace("\n", "\n" + diff); } String exceptionCharacter = diffExceptions ? diff : ""; if (!throwable.isEmpty()) { throwable = exceptionCharacter + throwable.replace("\n", "\n" + exceptionCharacter); } } if (!message.isEmpty()) { message += "\n"; } if (!throwable.isEmpty()) { throwable += "\n"; } List<String> formatted = new ArrayList<>(); // Handle message being longer than a message if (message.length() > MESSAGE_MAX_LENGTH) { message = chopOnNewlines(message, blockLength, maximumPart, formatted); } // Handle log entry being longer than a message int totalLength = blockLength + throwable.length() + message.length(); if (totalLength > MESSAGE_MAX_LENGTH) { String remainingPart = chopOnNewlines(message, blockLength, maximumPart, formatted); formatted.add(remainingPart); } else { formatted.add(message + throwable); } return formatted; } private String chopOnNewlines(String input, int blockLength, int maximumPart, List<String> formatted) { if (!input.contains("\n")) { return cutToSizeIfNeeded(input, blockLength, maximumPart, formatted); } StringBuilder builder = new StringBuilder(); for (String line : input.split("\n")) { line += "\n"; line = cutToSizeIfNeeded(line, blockLength, maximumPart, formatted); if (blockLength + line.length() + builder.length() > MESSAGE_MAX_LENGTH) { formatted.add(builder.toString()); builder.setLength(0); } builder.append(line); } return builder.toString(); } private String cutToSizeIfNeeded( String content, int blockLength, int maximumPart, List<String> formatted ) { while (content.length() + blockLength > MESSAGE_MAX_LENGTH) { String cutToSize = content.substring(0, maximumPart) + "\n"; if (cutToSize.endsWith("\n\n")) { // maximumPart excludes the newline at the end of message/line cutToSize = cutToSize.substring(0, cutToSize.length() - 1); } formatted.add(cutToSize); content = content.substring(maximumPart); } return content; } private String getLogLevelDiffCharacter(LogLevel level) { if (level == LogLevel.StandardLogLevel.WARNING) { return "+ "; } else if (level == LogLevel.StandardLogLevel.ERROR) { return "- "; } return " "; } }
17,537
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ConsoleModule.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/console/ConsoleModule.java
package com.discordsrv.common.console; import com.discordsrv.api.DiscordSRVApi; import com.discordsrv.api.discord.connection.details.DiscordGatewayIntent; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.config.main.ConsoleConfig; import com.discordsrv.common.config.main.generic.DestinationConfig; import com.discordsrv.common.console.entry.LogEntry; import com.discordsrv.common.logging.LogAppender; import com.discordsrv.common.logging.LogLevel; import com.discordsrv.common.logging.NamedLogger; import com.discordsrv.common.logging.backend.LoggingBackend; import com.discordsrv.common.module.type.AbstractModule; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.function.Consumer; public class ConsoleModule extends AbstractModule<DiscordSRV> implements LogAppender { private LoggingBackend backend; private final List<SingleConsoleHandler> handlers = new ArrayList<>(); public ConsoleModule(DiscordSRV discordSRV) { super(discordSRV, new NamedLogger(discordSRV, "CONSOLE")); } @Override public @NotNull Collection<DiscordGatewayIntent> requiredIntents() { return Collections.singletonList(DiscordGatewayIntent.MESSAGE_CONTENT); } @Override public void enable() { backend = discordSRV.console().loggingBackend(); backend.addAppender(this); } @Override public void reload(Consumer<DiscordSRVApi.ReloadResult> resultConsumer) { for (SingleConsoleHandler handler : handlers) { handler.shutdown(); } handlers.clear(); List<ConsoleConfig> configs = discordSRV.config().console; for (ConsoleConfig config : configs) { DestinationConfig.Single destination = config.channel; if (destination.channelId == 0L && StringUtils.isEmpty(destination.threadName)) { logger().debug("Skipping a console handler due to lack of channel"); continue; } if (config.appender.outputMode == ConsoleConfig.OutputMode.OFF && !config.commandExecution.enabled) { logger().debug("Skipping console handler because output mode is OFF and command execution is disabled"); continue; } handlers.add(new SingleConsoleHandler(discordSRV, logger(), config)); } } @Override public void disable() { if (backend != null) { backend.removeAppender(this); } } @Override public void append( @Nullable String loggerName, @NotNull LogLevel logLevel, @Nullable String message, @Nullable Throwable throwable ) { LogEntry entry = new LogEntry(loggerName, logLevel, message, throwable); for (SingleConsoleHandler handler : handlers) { handler.queue(entry); } } }
3,075
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
LogMessage.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/console/entry/LogMessage.java
package com.discordsrv.common.console.entry; /** * A {@link LogEntry} with formatting. */ public class LogMessage { private final LogEntry entry; private final String formatted; public LogMessage(LogEntry entry, String formatted) { this.entry = entry; this.formatted = formatted; } public LogEntry entry() { return entry; } public String formatted() { return formatted; } }
445
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
LogEntry.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/console/entry/LogEntry.java
package com.discordsrv.common.console.entry; import com.discordsrv.api.placeholder.annotation.Placeholder; import com.discordsrv.common.logging.LogLevel; import java.time.ZonedDateTime; /** * A raw log entry from a platform logger. May be parsed to become a {@link LogMessage}. */ public class LogEntry { private final String loggerName; private final LogLevel level; private final String message; private final Throwable throwable; private final ZonedDateTime logTime; public LogEntry(String loggerName, LogLevel level, String message, Throwable throwable) { this.loggerName = loggerName; this.level = level; this.message = message; this.throwable = throwable; this.logTime = ZonedDateTime.now(); } @Placeholder("logger_name") public String loggerName() { return loggerName; } @Placeholder("log_level") public LogLevel level() { return level; } public String message() { return message; } public Throwable throwable() { return throwable; } @Placeholder(value = "log_time", relookup = "date") public ZonedDateTime logTime() { return logTime; } }
1,219
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ConsoleMessage.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/console/message/ConsoleMessage.java
package com.discordsrv.common.console.message; import com.discordsrv.common.DiscordSRV; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.format.*; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Helper class for parsing raw console messages into markdown, ansi or plain content for forwarding to Discord. */ public class ConsoleMessage { private static final String ANSI_ESCAPE = "\u001B"; // Paper uses 007F as an intermediary private static final String SECTION = "[§\u007F]"; // Regex pattern for matching ANSI + Legacy private static final Pattern PATTERN = Pattern.compile( // ANSI ANSI_ESCAPE + "\\[" + "(?<ansi>[0-9]{1,3}" + "(;[0-9]{1,3}" + "(;[0-9]{1,3}" + "(?:(?:;[0-9]{1,3}){2})?" + ")?" + ")?" + ")" + "m" + "|" + "(?<legacy>" // Legacy color/formatting + "(?:" + SECTION + "[0-9a-fk-or])" + "|" // Bungee/Spigot legacy + "(?:" + SECTION + "x(?:" + SECTION + "[0-9a-f]){6})" + ")" ); private final TextComponent.Builder builder = Component.text(); private final DiscordSRV discordSRV; public ConsoleMessage(DiscordSRV discordSRV, String input) { this.discordSRV = discordSRV; parse(input); } public String asMarkdown() { Component component = builder.build(); return discordSRV.componentFactory().discordSerializer().serialize(component); } public String asAnsi() { Component component = builder.build(); return discordSRV.componentFactory().ansiSerializer().serialize(component) + (ANSI_ESCAPE + "[0m"); } public String asPlain() { Component component = builder.build(); return discordSRV.componentFactory().plainSerializer().serialize(component); } private void parse(String input) { Matcher matcher = PATTERN.matcher(input); Style.Builder style = Style.style(); int lastMatchEnd = 0; while (matcher.find()) { int start = matcher.start(); int end = matcher.end(); if (start != lastMatchEnd) { builder.append(Component.text(input.substring(lastMatchEnd, start), style.build())); } String ansi = matcher.group("ansi"); if (ansi != null) { parseAnsi(ansi, style); } String legacy = matcher.group("legacy"); if (legacy != null) { parseLegacy(legacy, style); } lastMatchEnd = end; } int length = input.length(); if (lastMatchEnd != length) { builder.append(Component.text(input.substring(lastMatchEnd, length), style.build())); } } private void parseAnsi(String ansiEscape, Style.Builder style) { String[] ansiParts = ansiEscape.split(";"); int amount = ansiParts.length; if (amount == 1 || amount == 2) { int number = Integer.parseInt(ansiParts[0]); if ((number >= 30 && number <= 37) || (number >= 90 && number <= 97)) { style.color(fourBitAnsiColor(number)); return; } switch (number) { case 0: style.color(null).decorations(EnumSet.allOf(TextDecoration.class), false); break; case 1: style.decoration(TextDecoration.BOLD, true); break; case 3: style.decoration(TextDecoration.ITALIC, true); break; case 4: style.decoration(TextDecoration.UNDERLINED, true); break; case 8: style.decoration(TextDecoration.OBFUSCATED, true); break; case 9: style.decoration(TextDecoration.STRIKETHROUGH, true); break; case 22: style.decoration(TextDecoration.BOLD, false); break; case 23: style.decoration(TextDecoration.ITALIC, false); break; case 24: style.decoration(TextDecoration.UNDERLINED, false); break; case 28: style.decoration(TextDecoration.OBFUSCATED, false); break; case 29: style.decoration(TextDecoration.STRIKETHROUGH, false); break; case 39: style.color(null); break; } } else if (amount == 3 || amount == 5) { if (Integer.parseInt(ansiParts[0]) != 36 || Integer.parseInt(ansiParts[1]) != 5) { return; } if (amount == 5) { int red = Integer.parseInt(ansiParts[2]); int green = Integer.parseInt(ansiParts[3]); int blue = Integer.parseInt(ansiParts[4]); style.color(TextColor.color(red, green, blue)); return; } int number = Integer.parseInt(ansiParts[2]); style.color(eightBitAnsiColor(number)); } } private enum FourBitColor { BLACK(30, TextColor.color(0, 0, 0)), RED(31, TextColor.color(170, 0, 0)), GREEN(32, TextColor.color(0, 170, 0)), YELLOW(33, TextColor.color(170, 85, 0)), BLUE(34, TextColor.color(0, 0, 170)), MAGENTA(35, TextColor.color(170, 0, 170)), CYAN(36, TextColor.color(0, 170, 170)), WHITE(37, TextColor.color(170, 170, 170)), BRIGHT_BLACK(90, TextColor.color(85, 85, 85)), BRIGHT_RED(91, TextColor.color(255, 85, 85)), BRIGHT_GREEN(92, TextColor.color(85, 255, 85)), BRIGHT_YELLOW(93, TextColor.color(255, 255, 85)), BRIGHT_BLUE(94, TextColor.color(85, 85, 255)), BRIGHT_MAGENTA(95, TextColor.color(255, 85, 255)), BRIGHT_CYAN(96, TextColor.color(85, 255, 255)), BRIGHT_WHITE(97, TextColor.color(255, 255, 255)); private static final Map<Integer, FourBitColor> byFG = new HashMap<>(); static { for (FourBitColor value : values()) { byFG.put(value.fg, value); } } public static FourBitColor getByFG(int fg) { return byFG.get(fg); } private final int fg; private final TextColor color; FourBitColor(int fg, TextColor color) { this.fg = fg; this.color = color; } public TextColor color() { return color; } } private TextColor fourBitAnsiColor(int color) { FourBitColor fourBitColor = FourBitColor.getByFG(color); return fourBitColor != null ? fourBitColor.color() : null; } private TextColor[] colors; private TextColor eightBitAnsiColor(int color) { if (colors == null) { TextColor[] colors = new TextColor[256]; FourBitColor[] fourBitColors = FourBitColor.values(); for (int i = 0; i < fourBitColors.length; i++) { colors[i] = fourBitColors[i].color(); } // https://gitlab.gnome.org/GNOME/vte/-/blob/19acc51708d9e75ef2b314aa026467570e0bd8ee/src/vte.cc#L2485 for (int i = 16; i < 232; i++) { int j = i - 16; int red = j / 36; int green = (j / 6) % 6; int blue = j % 6; red = red == 0 ? 0 : red * 40 + 55; green = green == 0 ? 0 : green * 40 + 55; blue = blue == 0 ? 0 : blue * 40 + 55; colors[i] = TextColor.color( red | red << 8, green | green << 8, blue | blue << 8 ); } for (int i = 232; i < 256; i++) { int shade = 8 + (i - 232) * 10; colors[i] = TextColor.color(shade, shade, shade); } this.colors = colors; } return color <= colors.length && color >= 0 ? colors[color] : null; } private void parseLegacy(String legacy, Style.Builder style) { if (legacy.length() == 2) { char character = legacy.toCharArray()[1]; if (character == 'r') { style.color(null).decorations(EnumSet.allOf(TextDecoration.class), false); } else { TextFormat format = getFormat(character); if (format instanceof TextColor) { style.color((TextColor) format); } else if (format instanceof TextDecoration) { style.decorate((TextDecoration) format); } } } else { char[] characters = legacy.toCharArray(); StringBuilder hex = new StringBuilder(7).append(TextColor.HEX_PREFIX); for (int i = 2; i < characters.length; i += 2) { hex.append(characters[i]); } style.color(TextColor.fromHexString(hex.toString())); } } private TextFormat getFormat(char character) { switch (character) { case '0': return NamedTextColor.BLACK; case '1': return NamedTextColor.DARK_BLUE; case '2': return NamedTextColor.DARK_GREEN; case '3': return NamedTextColor.DARK_AQUA; case '4': return NamedTextColor.DARK_RED; case '5': return NamedTextColor.DARK_PURPLE; case '6': return NamedTextColor.GOLD; case '7': return NamedTextColor.GRAY; case '8': return NamedTextColor.DARK_GRAY; case '9': return NamedTextColor.BLUE; case 'a': return NamedTextColor.GREEN; case 'b': return NamedTextColor.AQUA; case 'c': return NamedTextColor.RED; case 'd': return NamedTextColor.LIGHT_PURPLE; case 'e': return NamedTextColor.YELLOW; case 'f': return NamedTextColor.WHITE; case 'k': return TextDecoration.OBFUSCATED; case 'l': return TextDecoration.BOLD; case 'm': return TextDecoration.STRIKETHROUGH; case 'n': return TextDecoration.UNDERLINED; case 'o': return TextDecoration.ITALIC; default: return null; } } }
10,947
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
Timeout.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/time/util/Timeout.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.time.util; import org.jetbrains.annotations.NotNull; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicLong; /** * Helper class to track of time since something was done last, to avoid repeating tasks within a short timespan. */ public class Timeout { private final AtomicLong last = new AtomicLong(0); private final long timeoutMS; public Timeout(long time, @NotNull TimeUnit unit) { this(unit.toMillis(time)); } public Timeout(long timeoutMS) { this.timeoutMS = timeoutMS; } /** * Checks if the last invocation of this method was not within the timeout period, * if true updates the time to the current time. * @return if the last time this was invoked was outside the timeout period */ public boolean checkAndUpdate() { long currentTime = System.currentTimeMillis(); synchronized (last) { long time = last.get(); if (time + timeoutMS < currentTime) { last.set(currentTime); return true; } } return false; } }
1,982
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
IBootstrap.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/bootstrap/IBootstrap.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.bootstrap; import com.discordsrv.common.logging.Logger; import dev.vankka.dependencydownload.classpath.ClasspathAppender; import java.nio.file.Path; public interface IBootstrap { Logger logger(); ClasspathAppender classpathAppender(); ClassLoader classLoader(); LifecycleManager lifecycleManager(); Path dataDirectory(); }
1,208
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
LifecycleManager.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/bootstrap/LifecycleManager.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.bootstrap; import com.discordsrv.api.DiscordSRVApi; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.dependency.DependencyLoader; import com.discordsrv.common.logging.Logger; import dev.vankka.dependencydownload.classpath.ClasspathAppender; import java.io.IOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.function.Supplier; public class LifecycleManager { private final Logger logger; private final ExecutorService taskPool; private final DependencyLoader dependencyLoader; private final CompletableFuture<?> completableFuture; public LifecycleManager( Logger logger, Path dataDirectory, String[] dependencyResources, ClasspathAppender classpathAppender ) throws IOException { this.logger = logger; this.taskPool = Executors.newSingleThreadExecutor(runnable -> new Thread(runnable, "DiscordSRV Initialization")); List<String> resourcePaths = new ArrayList<>(Collections.singletonList( "dependencies/runtimeDownload-common.txt" )); resourcePaths.addAll(Arrays.asList(dependencyResources)); this.dependencyLoader = new DependencyLoader( dataDirectory, taskPool, classpathAppender, resourcePaths.toArray(new String[0]) ); this.completableFuture = dependencyLoader.download(); completableFuture.whenComplete((v, t) -> taskPool.shutdown()); } public void loadAndEnable(Supplier<DiscordSRV> discordSRVSupplier) { if (load()) { enable(discordSRVSupplier); } } private boolean load() { try { completableFuture.get(); return true; } catch (InterruptedException ignored) { Thread.currentThread().interrupt(); } catch (ExecutionException e) { logger.error("Failed to download dependencies", e.getCause()); } return false; } private void enable(Supplier<DiscordSRV> discordSRVSupplier) { discordSRVSupplier.get().runEnable(); } public void reload(DiscordSRV discordSRV) { if (discordSRV == null) { return; } discordSRV.runReload(DiscordSRVApi.ReloadFlag.DEFAULT_FLAGS, false); } public void disable(DiscordSRV discordSRV) { if (!completableFuture.isDone()) { completableFuture.cancel(true); return; } if (discordSRV == null) { return; } try { discordSRV.invokeDisable().get(/*15, TimeUnit.SECONDS*/); } catch (InterruptedException/* | TimeoutException*/ e) { logger.warning("Timed out/interrupted shutting down DiscordSRV"); } catch (ExecutionException e) { logger.error("Failed to disable", e.getCause()); } } public DependencyLoader getDependencyLoader() { return dependencyLoader; } }
4,146
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ModuleManager.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/module/ModuleManager.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.module; import com.discordsrv.api.DiscordSRVApi; import com.discordsrv.api.discord.connection.details.DiscordCacheFlag; import com.discordsrv.api.discord.connection.details.DiscordGatewayIntent; import com.discordsrv.api.discord.connection.details.DiscordMemberCachePolicy; import com.discordsrv.api.event.bus.EventPriority; import com.discordsrv.api.event.bus.Subscribe; import com.discordsrv.api.event.events.lifecycle.DiscordSRVReadyEvent; import com.discordsrv.api.event.events.lifecycle.DiscordSRVShuttingDownEvent; import com.discordsrv.api.module.Module; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.command.game.commands.subcommand.reload.ReloadResults; import com.discordsrv.common.debug.DebugGenerateEvent; import com.discordsrv.common.debug.file.TextDebugFile; import com.discordsrv.common.discord.connection.jda.JDAConnectionManager; import com.discordsrv.common.function.CheckedFunction; import com.discordsrv.common.logging.Logger; import com.discordsrv.common.logging.NamedLogger; import com.discordsrv.common.module.type.AbstractModule; import com.discordsrv.common.module.type.ModuleDelegate; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.function.BiConsumer; import java.util.function.Function; public class ModuleManager { private final Set<Module> modules = new CopyOnWriteArraySet<>(); private final Map<String, Module> moduleLookupTable = new ConcurrentHashMap<>(); private final Map<Module, AbstractModule<?>> delegates = new ConcurrentHashMap<>(); private final DiscordSRV discordSRV; private final Logger logger; public ModuleManager(DiscordSRV discordSRV) { this.discordSRV = discordSRV; this.logger = new NamedLogger(discordSRV, "MODULE_MANAGER"); discordSRV.eventBus().subscribe(this); } public Logger logger() { return logger; } private <T> Set<T> getModuleDetails(Function<Module, Collection<T>> detailFunction, BiConsumer<AbstractModule<?>, Collection<T>> setRequested) { Set<T> details = new HashSet<>(); for (Module module : modules) { try { if (!module.isEnabled()) { continue; } Collection<T> values = detailFunction.apply(module); details.addAll(values); setRequested.accept(getAbstract(module), values); } catch (Throwable t) { logger.debug("Failed to get details from " + module.getClass(), t); } } return details; } public Set<DiscordGatewayIntent> requiredIntents() { return getModuleDetails(Module::requiredIntents, AbstractModule::setRequestedIntents); } public Set<DiscordCacheFlag> requiredCacheFlags() { return getModuleDetails(Module::requiredCacheFlags, AbstractModule::setRequestedCacheFlags); } public Set<DiscordMemberCachePolicy> requiredMemberCachePolicies() { return getModuleDetails(Module::requiredMemberCachingPolicies, (mod, result) -> mod.setRequestedMemberCachePolicies(result.size())); } @SuppressWarnings("unchecked") public <T extends Module> T getModule(Class<T> moduleType) { return (T) moduleLookupTable.computeIfAbsent(moduleType.getName(), key -> { Module bestCandidate = null; int bestCandidatePriority = Integer.MIN_VALUE; for (Module module : modules) { if (!module.isEnabled()) { continue; } int priority; if (moduleType.isAssignableFrom(module.getClass()) && ((priority = module.priority(moduleType)) > bestCandidatePriority)) { bestCandidate = module; bestCandidatePriority = priority; } } return bestCandidate; }); } private AbstractModule<?> getAbstract(Module module) { return module instanceof AbstractModule ? (AbstractModule<?>) module : delegates.computeIfAbsent(module, mod -> new ModuleDelegate(discordSRV, mod)); } public <DT extends DiscordSRV> void registerModule(DT discordSRV, CheckedFunction<DT, AbstractModule<?>> function) { try { register(function.apply(discordSRV)); } catch (Throwable t) { logger.debug("Module initialization failed", t); } } public void register(Module module) { if (module instanceof ModuleDelegate) { throw new IllegalArgumentException("Cannot register a delegate"); } this.modules.add(module); this.moduleLookupTable.put(module.getClass().getName(), module); logger.debug(module + " registered"); if (discordSRV.isReady()) { // Check if Discord connection is ready, if it is already we'll enable the module enable(getAbstract(module)); } } public void unregister(Module module) { if (module instanceof ModuleDelegate) { throw new IllegalArgumentException("Cannot unregister a delegate"); } // Disable if needed disable(getAbstract(module)); this.modules.remove(module); this.moduleLookupTable.values().removeIf(mod -> mod == module); this.delegates.remove(module); logger.debug(module + " unregistered"); } private void enable(AbstractModule<?> module) { try { if (module.enableModule()) { logger.debug(module + " enabled"); } } catch (Throwable t) { discordSRV.logger().error("Failed to enable " + module.getClass().getSimpleName(), t); } } private void disable(AbstractModule<?> module) { try { if (module.disableModule()) { logger.debug(module + " disabled"); } } catch (Throwable t) { discordSRV.logger().error("Failed to disable " + module.getClass().getSimpleName(), t); } } @Subscribe(priority = EventPriority.EARLY) public void onShuttingDown(DiscordSRVShuttingDownEvent event) { modules.stream() .sorted((m1, m2) -> Integer.compare(m2.shutdownOrder(), m1.shutdownOrder())) .forEachOrdered(module -> disable(getAbstract(module))); } @Subscribe public void onDiscordSRVReady(DiscordSRVReadyEvent event) { reload(); } public List<DiscordSRV.ReloadResult> reload() { JDAConnectionManager connectionManager = discordSRV.discordConnectionManager(); Set<DiscordSRVApi.ReloadResult> reloadResults = new HashSet<>(); for (Module module : modules) { AbstractModule<?> abstractModule = getAbstract(module); boolean fail = false; if (abstractModule.isEnabled()) { for (DiscordGatewayIntent requiredIntent : abstractModule.getRequestedIntents()) { if (!connectionManager.getIntents().contains(requiredIntent)) { fail = true; logger().warning("Missing gateway intent " + requiredIntent.name() + " for module " + module.getClass().getSimpleName()); } } for (DiscordCacheFlag requiredCacheFlag : abstractModule.getRequestedCacheFlags()) { if (!connectionManager.getCacheFlags().contains(requiredCacheFlag)) { fail = true; logger().warning("Missing cache flag " + requiredCacheFlag.name() + " for module " + module.getClass().getSimpleName()); } } } if (fail) { reloadResults.add(ReloadResults.DISCORD_CONNECTION_RELOAD_REQUIRED); } // Check if the module needs to be enabled or disabled if (!fail) { enable(abstractModule); } if (!abstractModule.isEnabled()) { disable(abstractModule); continue; } try { abstractModule.reload(result -> { if (result == null) { throw new NullPointerException("null result supplied to resultConsumer"); } reloadResults.add(result); }); } catch (Throwable t) { discordSRV.logger().error("Failed to reload " + module.getClass().getSimpleName(), t); } } List<DiscordSRVApi.ReloadResult> results = new ArrayList<>(); List<DiscordSRV.ReloadResult> validResults = Arrays.asList(DiscordSRVApi.ReloadResult.DefaultConstants.values()); for (DiscordSRVApi.ReloadResult reloadResult : reloadResults) { if (validResults.contains(reloadResult)) { results.add(reloadResult); } } return results; } @Subscribe public void onDebugGenerate(DebugGenerateEvent event) { StringBuilder builder = new StringBuilder(); builder.append("Enabled modules:"); List<Module> disabled = new ArrayList<>(); for (Module module : modules) { if (!getAbstract(module).isEnabled()) { disabled.add(module); continue; } appendModule(builder, module, true); } builder.append("\n\nDisabled modules:"); for (Module module : disabled) { appendModule(builder, module, false); } event.addFile(new TextDebugFile("modules.txt", builder)); } private void appendModule(StringBuilder builder, Module module, boolean extra) { builder.append('\n').append(module.getClass().getName()); if (!extra) { return; } AbstractModule<?> mod = getAbstract(module); List<DiscordGatewayIntent> intents = mod.getRequestedIntents(); if (!intents.isEmpty()) { builder.append("\n Intents: ").append(intents); } List<DiscordCacheFlag> cacheFlags = mod.getRequestedCacheFlags(); if (!cacheFlags.isEmpty()) { builder.append("\n Cache Flags: ").append(cacheFlags); } int memberCachePolicies = mod.getRequestedMemberCachePolicies(); if (memberCachePolicies != 0) { builder.append("\n Member Cache Policies: ").append(memberCachePolicies); } } }
11,431
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
AbstractModule.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/module/type/AbstractModule.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.module.type; import com.discordsrv.api.discord.connection.details.DiscordCacheFlag; import com.discordsrv.api.discord.connection.details.DiscordGatewayIntent; import com.discordsrv.api.event.events.Cancellable; import com.discordsrv.api.event.events.Processable; import com.discordsrv.api.module.Module; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.event.util.EventUtil; import com.discordsrv.common.logging.Logger; import java.util.ArrayList; import java.util.Collection; import java.util.List; public abstract class AbstractModule<DT extends DiscordSRV> implements Module { protected final DT discordSRV; private final Logger logger; private boolean hasBeenEnabled = false; private final List<DiscordGatewayIntent> requestedIntents = new ArrayList<>(); private final List<DiscordCacheFlag> requestedCacheFlags = new ArrayList<>(); private int requestedMemberCachePolicies = 0; public AbstractModule(DT discordSRV) { this(discordSRV, discordSRV.logger()); } public AbstractModule(DT discordSRV, Logger logger) { this.discordSRV = discordSRV; this.logger = logger; } @Override public String toString() { return getClass().getName(); } // Utility public final Logger logger() { return logger; } protected final boolean checkProcessor(Processable event) { return EventUtil.checkProcessor(discordSRV, event, logger()); } protected final boolean checkCancellation(Cancellable event) { return EventUtil.checkCancellation(discordSRV, event, logger()); } // Internal public final boolean enableModule() { if (hasBeenEnabled || !isEnabled()) { return false; } hasBeenEnabled = true; enable(); try { discordSRV.eventBus().subscribe(this); // Ignore not having listener methods exception } catch (IllegalArgumentException ignored) {} return true; } public final boolean disableModule() { if (!hasBeenEnabled) { return false; } disable(); hasBeenEnabled = false; try { discordSRV.eventBus().unsubscribe(this); // Ignore not having listener methods exception } catch (IllegalArgumentException ignored) {} return true; } public final void setRequestedIntents(Collection<DiscordGatewayIntent> intents) { this.requestedIntents.clear(); this.requestedIntents.addAll(intents); } public final List<DiscordGatewayIntent> getRequestedIntents() { return requestedIntents; } public final void setRequestedCacheFlags(Collection<DiscordCacheFlag> cacheFlags) { this.requestedCacheFlags.clear(); this.requestedCacheFlags.addAll(cacheFlags); } public final List<DiscordCacheFlag> getRequestedCacheFlags() { return requestedCacheFlags; } public final void setRequestedMemberCachePolicies(int amount) { this.requestedMemberCachePolicies = amount; } public final int getRequestedMemberCachePolicies() { return requestedMemberCachePolicies; } }
4,077
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
PluginIntegration.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/module/type/PluginIntegration.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.module.type; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.logging.Logger; import org.jetbrains.annotations.NotNull; import javax.annotation.OverridingMethodsMustInvokeSuper; public abstract class PluginIntegration<DT extends DiscordSRV> extends AbstractModule<DT> { public PluginIntegration(DT discordSRV) { super(discordSRV); } public PluginIntegration(DT discordSRV, Logger logger) { super(discordSRV, logger); } /** * The id/name of the plugin/mod this integration is for. * @return the id (when available) or name of the plugin or mod */ @NotNull public abstract String getIntegrationName(); @Override @OverridingMethodsMustInvokeSuper public boolean isEnabled() { if (discordSRV.config().integrations().disabledIntegrations.contains(getIntegrationName())) { return false; } return super.isEnabled(); } }
1,812
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ModuleDelegate.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/module/type/ModuleDelegate.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.module.type; import com.discordsrv.api.DiscordSRVApi; import com.discordsrv.api.discord.connection.details.DiscordCacheFlag; import com.discordsrv.api.discord.connection.details.DiscordGatewayIntent; import com.discordsrv.api.discord.connection.details.DiscordMemberCachePolicy; import com.discordsrv.api.module.Module; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.logging.NamedLogger; import org.jetbrains.annotations.NotNull; import java.util.Collection; import java.util.function.Consumer; public class ModuleDelegate extends AbstractModule<DiscordSRV> { private final Module module; public ModuleDelegate(DiscordSRV discordSRV, Module module) { super(discordSRV, new NamedLogger(discordSRV, module.getClass().getName())); this.module = module; } @Override public boolean isEnabled() { return module.isEnabled(); } @Override public @NotNull Collection<DiscordGatewayIntent> requiredIntents() { return module.requiredIntents(); } @Override public @NotNull Collection<DiscordCacheFlag> requiredCacheFlags() { return module.requiredCacheFlags(); } @Override public @NotNull Collection<DiscordMemberCachePolicy> requiredMemberCachingPolicies() { return module.requiredMemberCachingPolicies(); } @Override public int priority(Class<?> type) { return module.priority(type); } @Override public int shutdownOrder() { return module.shutdownOrder(); } @Override public void enable() { module.enable(); } @Override public void reload(Consumer<DiscordSRVApi.ReloadResult> resultConsumer) { module.reload(resultConsumer); } @Override public void disable() { module.disable(); } @Override public String toString() { return super.toString() + "{module=" + module.getClass().getName() + "(" + module + ")}"; } }
2,827
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ProfileManager.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/profile/ProfileManager.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.profile; import com.discordsrv.api.profile.IProfileManager; import com.discordsrv.common.DiscordSRV; import org.jetbrains.annotations.Blocking; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Map; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; public class ProfileManager implements IProfileManager { private final DiscordSRV discordSRV; private final Map<UUID, Profile> profiles = new ConcurrentHashMap<>(); private final Map<Long, Profile> discordUserMap = new ConcurrentHashMap<>(); public ProfileManager(DiscordSRV discordSRV) { this.discordSRV = discordSRV; } @Blocking public void loadProfile(UUID playerUUID) { Profile profile = lookupProfile(playerUUID).join(); profiles.put(playerUUID, profile); if (profile.isLinked()) { discordUserMap.put(profile.userId(), profile); } } public void unloadProfile(UUID playerUUID) { Profile profile = profiles.remove(playerUUID); if (profile == null) { return; } if (profile.isLinked()) { discordUserMap.remove(profile.userId()); } } @Override public @NotNull CompletableFuture<Profile> lookupProfile(UUID playerUUID) { return discordSRV.linkProvider().getUserId(playerUUID) .thenApply(opt -> new Profile(playerUUID, opt.orElse(null))); } @Override public @Nullable Profile getProfile(UUID playerUUID) { return profiles.get(playerUUID); } @Override public @NotNull CompletableFuture<Profile> lookupProfile(long userId) { return discordSRV.linkProvider().getPlayerUUID(userId) .thenApply(opt -> new Profile(opt.orElse(null), userId)); } @Override public @Nullable Profile getProfile(long userId) { return discordUserMap.get(userId); } }
2,844
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
Profile.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/profile/Profile.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.profile; import com.discordsrv.api.profile.IProfile; import org.jetbrains.annotations.Nullable; import java.util.UUID; public class Profile implements IProfile { private final UUID playerUUID; private final Long userId; public Profile(UUID playerUUID, Long userId) { this.playerUUID = playerUUID; this.userId = userId; } @Override public @Nullable UUID playerUUID() { return playerUUID; } @Override public @Nullable Long userId() { return userId; } }
1,390
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ServerScheduler.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/scheduler/ServerScheduler.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.scheduler; import org.jetbrains.annotations.ApiStatus; import java.util.concurrent.TimeUnit; @SuppressWarnings("unused") // API public interface ServerScheduler extends Scheduler { int TICKS_PER_SECOND = 20; long MILLISECONDS_PER_TICK = (1000L / TICKS_PER_SECOND); static long timeToTicks(long time, TimeUnit unit) { return millisToTicks(unit.toMillis(time)); } static long millisToTicks(long milliseconds) { return milliseconds / MILLISECONDS_PER_TICK; } static long ticksToMillis(long ticks) { return ticks * MILLISECONDS_PER_TICK; } /** * Runs the provided task on the server's main thread as soon as possible. * @param task the task */ void runOnMainThread(Runnable task); /** * Runs the provided task in on the server's main thread in the provided amount of ticks. * @param task the task * @param ticks the time in ticks * @see #TICKS_PER_SECOND * @see #timeToTicks(long, TimeUnit) */ void runOnMainThreadLaterInTicks(Runnable task, int ticks); /** * Runs the task on the server's main thread continuously at provided rate in ticks. * * @param task the task * @param rateTicks the rate in ticks */ @ApiStatus.NonExtendable default void runOnMainThreadAtFixedRateInTicks(Runnable task, int rateTicks) { runOnMainThreadAtFixedRateInTicks(task, 0, rateTicks); } /** * Runs the task on the server's main thread continuously at provided rate in ticks after the initial delay in ticks. * * @param task the task * @param initialTicks the initial delay in ticks * @param rateTicks the rate in ticks */ void runOnMainThreadAtFixedRateInTicks(Runnable task, int initialTicks, int rateTicks); }
2,666
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
StandardScheduler.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/scheduler/StandardScheduler.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.scheduler; import com.discordsrv.api.event.bus.EventPriority; import com.discordsrv.api.event.bus.Subscribe; import com.discordsrv.api.event.events.lifecycle.DiscordSRVShuttingDownEvent; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.scheduler.executor.DynamicCachingThreadPoolExecutor; import com.discordsrv.common.scheduler.threadfactory.CountingForkJoinWorkerThreadFactory; import com.discordsrv.common.scheduler.threadfactory.CountingThreadFactory; import org.jetbrains.annotations.NotNull; import java.time.Duration; import java.util.concurrent.*; public class StandardScheduler implements Scheduler { private final DiscordSRV discordSRV; private final ThreadPoolExecutor executorService; private final ScheduledThreadPoolExecutor scheduledExecutorService; private final ForkJoinPool forkJoinPool; private final ExceptionHandlingExecutor executor = new ExceptionHandlingExecutor(); public StandardScheduler(DiscordSRV discordSRV) { this( discordSRV, new DynamicCachingThreadPoolExecutor( /* Core pool size */ 1, /* Max pool size: cpu cores - 2 or at least 4 */ Math.max(4, Runtime.getRuntime().availableProcessors() - 2), /* Timeout */ 60, TimeUnit.SECONDS, new LinkedBlockingQueue<>(), new CountingThreadFactory(Scheduler.THREAD_NAME_PREFIX + "Executor #%s") ), new ScheduledThreadPoolExecutor( 1, /* Core pool size */ new CountingThreadFactory(Scheduler.THREAD_NAME_PREFIX + "Scheduled Executor #%s") ), new ForkJoinPool( /* parallelism */ Math.min( /* max of 10 */ 10, /* cpu cores / 2 or at least 1 */ Math.max(1, Runtime.getRuntime().availableProcessors() - 1) ), new CountingForkJoinWorkerThreadFactory(Scheduler.THREAD_NAME_PREFIX + "ForkJoinPool Worker #%s"), null, false /* async mode -> FIFO */ ) ); } private StandardScheduler( DiscordSRV discordSRV, ThreadPoolExecutor executorService, ScheduledThreadPoolExecutor scheduledExecutorService, ForkJoinPool forkJoinPool ) { this.discordSRV = discordSRV; this.executorService = executorService; this.scheduledExecutorService = scheduledExecutorService; this.forkJoinPool = forkJoinPool; } @Subscribe(priority = EventPriority.LAST) public void onShuttingDown(DiscordSRVShuttingDownEvent event) { executorService.shutdownNow(); scheduledExecutorService.shutdownNow(); forkJoinPool.shutdownNow(); } private Runnable wrap(Runnable runnable) { return () -> { try { runnable.run(); } catch (Throwable t) { discordSRV.logger().error(Thread.currentThread().getName() + " ran into an exception", t); } }; } @Override public Executor executor() { return executor; } @Override public ExecutorService executorService() { return executorService; } @Override public ScheduledExecutorService scheduledExecutorService() { return scheduledExecutorService; } @Override public ForkJoinPool forkJoinPool() { return forkJoinPool; } @Override public Future<?> run(@NotNull Runnable task) { return executorService.submit(wrap(task)); } @Override public ScheduledFuture<?> runLater(Runnable task, Duration delay) { return scheduledExecutorService.schedule(wrap(task), delay.toMillis(), TimeUnit.MILLISECONDS); } @Override public ScheduledFuture<?> runAtFixedRate(@NotNull Runnable task, Duration initialDelay, Duration rate) { return scheduledExecutorService.scheduleAtFixedRate(wrap(task), initialDelay.toMillis(), rate.toMillis(), TimeUnit.MILLISECONDS); } public class ExceptionHandlingExecutor implements Executor { @Override public void execute(@NotNull Runnable command) { run(command); } } }
5,409
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
Scheduler.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/scheduler/Scheduler.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.scheduler; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import java.time.Duration; import java.util.concurrent.*; @SuppressWarnings({"UnusedReturnValue", "unused"}) // API public interface Scheduler { /** * The thread name prefix for all DiscordSRV executors. */ String THREAD_NAME_PREFIX = "DiscordSRV Async "; /** * An executor that will actually catch exceptions. * @return the {@link Executor} */ Executor executor(); /** * Returns the {@link ExecutorService} being used. * @return the {@link ExecutorService} */ ExecutorService executorService(); /** * Returns the {@link ScheduledExecutorService} being used. * @return the {@link ScheduledExecutorService} */ ScheduledExecutorService scheduledExecutorService(); /** * Returns the {@link ForkJoinPool} being used. * @return the {@link ForkJoinPool} */ ForkJoinPool forkJoinPool(); /** * Runs the provided task as soon as possible. * * @param task the task */ Future<?> run(@NotNull Runnable task); /** * Schedules the given task after the provided amount of milliseconds. * * @param task the task * @param delay the delay before executing the task */ ScheduledFuture<?> runLater(Runnable task, Duration delay); /** * Schedules the given task at the given rate. * * @param task the task * @param rate the rate in the given unit */ @ApiStatus.NonExtendable default ScheduledFuture<?> runAtFixedRate(@NotNull Runnable task, Duration rate) { return runAtFixedRate(task, rate, rate); } /** * Schedules a task to run at the given rate after the initial delay. * * @param task the task * @param initialDelay the initial delay in the provided unit * @param rate the rate to run the task at in the given unit */ @ApiStatus.NonExtendable ScheduledFuture<?> runAtFixedRate(@NotNull Runnable task, Duration initialDelay, Duration rate); }
2,958
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
CountingForkJoinWorkerThreadFactory.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/scheduler/threadfactory/CountingForkJoinWorkerThreadFactory.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.scheduler.threadfactory; import java.util.concurrent.ForkJoinPool; import java.util.concurrent.ForkJoinWorkerThread; public class CountingForkJoinWorkerThreadFactory extends CountingFactory implements ForkJoinPool.ForkJoinWorkerThreadFactory { public CountingForkJoinWorkerThreadFactory(String format) { super(format); } @Override public ForkJoinWorkerThread newThread(ForkJoinPool pool) { ForkJoinWorkerThread worker = ForkJoinPool.defaultForkJoinWorkerThreadFactory.newThread(pool); worker.setName(nextName()); return worker; } }
1,448
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
CountingFactory.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/scheduler/threadfactory/CountingFactory.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.scheduler.threadfactory; import java.util.concurrent.atomic.AtomicInteger; public abstract class CountingFactory { private final AtomicInteger count = new AtomicInteger(0); private final String format; public CountingFactory(String format) { this.format = format; } protected String nextName() { return String.format(format, count.incrementAndGet()); } }
1,261
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
CountingThreadFactory.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/scheduler/threadfactory/CountingThreadFactory.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.scheduler.threadfactory; import org.jetbrains.annotations.NotNull; import java.util.concurrent.ThreadFactory; public class CountingThreadFactory extends CountingFactory implements ThreadFactory { public CountingThreadFactory(String format) { super(format); } @Override public Thread newThread(@NotNull Runnable task) { return new Thread(task, nextName()); } }
1,261
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DynamicCachingThreadPoolExecutor.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/scheduler/executor/DynamicCachingThreadPoolExecutor.java
package com.discordsrv.common.scheduler.executor; import org.jetbrains.annotations.NotNull; import java.util.concurrent.*; /** * A {@link ThreadPoolExecutor} that acts like a {@link Executors#newCachedThreadPool()} with a max pool size while allowing queueing tasks. */ public class DynamicCachingThreadPoolExecutor extends ThreadPoolExecutor { private int corePoolSize; public DynamicCachingThreadPoolExecutor( int corePoolSize, int maximumPoolSize, long keepAliveTime, @NotNull TimeUnit unit, @NotNull BlockingQueue<Runnable> workQueue, @NotNull ThreadFactory threadFactory ) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory); this.corePoolSize = corePoolSize; } @Override public int getCorePoolSize() { return corePoolSize; } @Override public void setCorePoolSize(int corePoolSize) { this.corePoolSize = corePoolSize; super.setCorePoolSize(this.corePoolSize); } @Override public synchronized void execute(@NotNull Runnable command) { super.setCorePoolSize(getMaximumPoolSize()); super.execute(command); super.setCorePoolSize(this.corePoolSize); } }
1,286
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ConfigException.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/exception/ConfigException.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.exception; public class ConfigException extends Exception { public ConfigException(String message) { super(message); } public ConfigException(String message, Throwable cause) { super(message, cause); } public ConfigException(Throwable cause) { super(cause); } }
1,174
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
StorageException.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/exception/StorageException.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.exception; import com.discordsrv.common.DiscordSRV; public class StorageException extends RuntimeException { public StorageException(Throwable cause) { super(null, cause); } public StorageException(String message) { super(message); } public void log(DiscordSRV discordSRV) { String baseMessage = "Failed to initialize storage"; Throwable cause = getCause(); String message = getMessage(); if (cause != null && message != null) { discordSRV.logger().error(baseMessage, this); } else if (message != null) { discordSRV.logger().error(baseMessage + ": " + message); } else if (cause != null) { discordSRV.logger().error(baseMessage, cause); } } }
1,640
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
MessageException.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/exception/MessageException.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.exception; import com.discordsrv.common.exception.util.ExceptionUtil; public class MessageException extends RuntimeException { @SuppressWarnings("ThrowableNotThrown") public MessageException(String message) { super(message); ExceptionUtil.minifyException(this); } }
1,157
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
InvalidListenerMethodException.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/exception/InvalidListenerMethodException.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.exception; public class InvalidListenerMethodException extends RuntimeException { public InvalidListenerMethodException(String message) { super(message); } }
1,036
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ExceptionUtil.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/exception/util/ExceptionUtil.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.exception.util; public final class ExceptionUtil { private ExceptionUtil() {} /** * Removes the stacktrace from the given {@link Throwable}. * * @param throwable the throwable * @return the same throwable with the stacktrace removed */ public static Throwable minifyException(Throwable throwable) { throwable.setStackTrace(new StackTraceElement[0]); return throwable; } }
1,292
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
CheckedFunction.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/function/CheckedFunction.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.function; @FunctionalInterface public interface CheckedFunction<I, O> { O apply(I input) throws Throwable; }
975
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
CheckedConsumer.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/function/CheckedConsumer.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.function; @FunctionalInterface public interface CheckedConsumer<I> { void accept(I input) throws Throwable; }
976
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
CheckedSupplier.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/function/CheckedSupplier.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.function; @FunctionalInterface public interface CheckedSupplier<O> { O get() throws Throwable; }
963
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
CheckedRunnable.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/function/CheckedRunnable.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.function; @FunctionalInterface public interface CheckedRunnable<T> { T run() throws Throwable; }
963
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
Permission.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/permission/Permission.java
package com.discordsrv.common.permission; public enum Permission { // Commands // Admin COMMAND_DEBUG("command.admin.debug"), COMMAND_RELOAD("command.admin.reload"), COMMAND_BROADCAST("command.admin.broadcast"), COMMAND_RESYNC("command.admin.resync"), COMMAND_VERSION("command.admin.version"), COMMAND_LINK_OTHER("command.admin.link.other"), COMMAND_LINKED_OTHER("command.admin.linked.other"), COMMAND_UNLINK_OTHER("command.admin.linked.other"), // Player COMMAND_ROOT("command.player.root"), COMMAND_LINK("command.player.link"), COMMAND_LINKED("command.player.linked"), COMMAND_UNLINK("command.player.unlink"), // Mentions MENTION_USER("mention.user.base"), MENTION_USER_LOOKUP("mention.user.lookup"), MENTION_ROLE_MENTIONABLE("mention.role.mentionable"), MENTION_ROLE_ALL("mention.role.all"), MENTION_EVERYONE("mention.everyone"), // Misc UPDATE_NOTIFICATION("updatenotification"), SILENT_JOIN("silentjoin"), SILENT_QUIT("silentquit"), ; private final String permission; Permission(String permission) { this.permission = permission; } public String permission() { return "discordsrv." + permission; } }
1,252
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
PermissionUtil.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/permission/util/PermissionUtil.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.permission.util; import com.discordsrv.api.module.type.PermissionModule; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.exception.MessageException; import net.kyori.adventure.text.Component; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.function.Function; public final class PermissionUtil { public static final String PREFIX_META_KEY = "discordsrv_prefix"; public static final String SUFFIX_META_KEY = "discordsrv_suffix"; private PermissionUtil() {} public static Component getMetaPrefix(DiscordSRV discordSRV, UUID uuid) { return getMeta(discordSRV, uuid, PREFIX_META_KEY); } public static Component getMetaSuffix(DiscordSRV discordSRV, UUID uuid) { return getMeta(discordSRV, uuid, SUFFIX_META_KEY); } public static Component getPrefix(DiscordSRV discordSRV, UUID uuid) { return getLegacy(discordSRV, "prefix", perm -> perm.getPrefix(uuid)); } public static Component getSuffix(DiscordSRV discordSRV, UUID uuid) { return getLegacy(discordSRV, "suffix", perm -> perm.getSuffix(uuid)); } private static Component getMeta(DiscordSRV discordSRV, UUID uuid, String metaKey) { PermissionModule.Meta meta = discordSRV.getModule(PermissionModule.Meta.class); if (meta == null) { return null; } String data = meta.getMeta(uuid, metaKey).join(); return translate(discordSRV, data); } private static Component getLegacy( DiscordSRV discordSRV, String what, Function<PermissionModule.PrefixAndSuffix, CompletableFuture<String>> legacy ) { PermissionModule.PrefixAndSuffix permission = discordSRV.getModule(PermissionModule.PrefixAndSuffix.class); if (permission == null) { return null; } String data = null; try { data = legacy.apply(permission).get(); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } catch (ExecutionException e) { Throwable cause = e.getCause(); if (cause instanceof MessageException) { discordSRV.logger().debug("Failed to lookup " + what + ": " + cause.getMessage()); } else { discordSRV.logger().debug("Failed to lookup " + what, cause); } } return translate(discordSRV, data); } private static Component translate(DiscordSRV discordSRV, String data) { return data != null ? discordSRV.componentFactory().parse(data) : null; } }
3,540
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ComponentFactory.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/component/ComponentFactory.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.component; import com.discordsrv.api.component.GameTextBuilder; import com.discordsrv.api.component.MinecraftComponent; import com.discordsrv.api.component.MinecraftComponentFactory; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.component.renderer.DiscordSRVMinecraftRenderer; import com.discordsrv.common.component.translation.Translation; import com.discordsrv.common.component.translation.TranslationRegistry; import dev.vankka.enhancedlegacytext.EnhancedLegacyText; import dev.vankka.mcdiscordreserializer.discord.DiscordSerializer; import dev.vankka.mcdiscordreserializer.discord.DiscordSerializerOptions; import dev.vankka.mcdiscordreserializer.minecraft.MinecraftSerializer; import dev.vankka.mcdiscordreserializer.minecraft.MinecraftSerializerOptions; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.TranslatableComponent; import net.kyori.adventure.text.flattener.ComponentFlattener; import net.kyori.adventure.text.serializer.ansi.ANSIComponentSerializer; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; import net.kyori.ansi.ColorLevel; import org.jetbrains.annotations.NotNull; public class ComponentFactory implements MinecraftComponentFactory { public static final Class<?> UNRELOCATED_ADVENTURE_COMPONENT; static { Class<?> clazz = null; try { clazz = Class.forName("net.kyo".concat("ri.adventure.text.Component")); } catch (ClassNotFoundException ignored) {} UNRELOCATED_ADVENTURE_COMPONENT = clazz; } private final DiscordSRV discordSRV; private final MinecraftSerializer minecraftSerializer; private final DiscordSerializer discordSerializer; private final PlainTextComponentSerializer plainSerializer; private final ANSIComponentSerializer ansiSerializer; // Not the same as Adventure's TranslationRegistry private final TranslationRegistry translationRegistry = new TranslationRegistry(); public ComponentFactory(DiscordSRV discordSRV) { this.discordSRV = discordSRV; this.minecraftSerializer = new MinecraftSerializer( MinecraftSerializerOptions.defaults() .addRenderer(new DiscordSRVMinecraftRenderer(discordSRV)) ); ComponentFlattener flattener = ComponentFlattener.basic().toBuilder() .mapper(TranslatableComponent.class, this::provideTranslation) .build(); this.discordSerializer = new DiscordSerializer( DiscordSerializerOptions.defaults() .withFlattener(flattener) ); this.plainSerializer = PlainTextComponentSerializer.builder() .flattener(flattener) .build(); this.ansiSerializer = ANSIComponentSerializer.builder() .colorLevel(ColorLevel.INDEXED_8) .flattener(flattener) .build(); } private String provideTranslation(TranslatableComponent component) { Translation translation = translationRegistry.lookup(discordSRV.defaultLocale(), component.key()); if (translation == null) { return null; } return translation.translate( component.args() .stream() .map(discordSerializer::serialize) .map(str -> (Object) str) .toArray(Object[]::new) ); } @Override public @NotNull MinecraftComponent empty() { return MinecraftComponentImpl.empty(); } @Override public @NotNull GameTextBuilder textBuilder(@NotNull String enhancedLegacyText) { return new EnhancedTextBuilderImpl(discordSRV, enhancedLegacyText); } public @NotNull Component parse(@NotNull String textInput) { if (textInput.contains(String.valueOf(LegacyComponentSerializer.SECTION_CHAR))) { return LegacyComponentSerializer.legacySection().deserialize(textInput); } return EnhancedLegacyText.get().parse(textInput); } public MinecraftSerializer minecraftSerializer() { return minecraftSerializer; } public DiscordSerializer discordSerializer() { return discordSerializer; } public PlainTextComponentSerializer plainSerializer() { return plainSerializer; } public ANSIComponentSerializer ansiSerializer() { return ansiSerializer; } public TranslationRegistry translationRegistry() { return translationRegistry; } }
5,517
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
EnhancedTextBuilderImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/component/EnhancedTextBuilderImpl.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.component; import com.discordsrv.api.color.Color; import com.discordsrv.api.component.GameTextBuilder; import com.discordsrv.api.component.MinecraftComponent; import com.discordsrv.api.placeholder.PlaceholderService; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.component.util.ComponentUtil; import dev.vankka.enhancedlegacytext.EnhancedComponentBuilder; import dev.vankka.enhancedlegacytext.EnhancedLegacyText; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.TextColor; import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; public class EnhancedTextBuilderImpl implements GameTextBuilder { private final Set<Object> context = new HashSet<>(); private final Map<Pattern, Function<Matcher, Object>> replacements = new LinkedHashMap<>(); private final DiscordSRV discordSRV; private final String enhancedFormat; public EnhancedTextBuilderImpl(DiscordSRV discordSRV, String enhancedFormat) { this.discordSRV = discordSRV; this.enhancedFormat = enhancedFormat; } @Override public @NotNull GameTextBuilder addContext(Object... context) { for (Object o : context) { if (o == null) { continue; } this.context.add(o); } return this; } @Override public @NotNull GameTextBuilder addReplacement(Pattern target, Function<Matcher, Object> replacement) { this.replacements.put(target, wrapFunction(replacement)); return this; } @Override public @NotNull GameTextBuilder applyPlaceholderService() { this.replacements.put(PlaceholderService.PATTERN, wrapFunction( matcher -> discordSRV.placeholderService().getResult(matcher, context))); return this; } private Function<Matcher, Object> wrapFunction(Function<Matcher, Object> function) { return matcher -> { Object result = function.apply(matcher); if (result instanceof Color) { // Convert Color to something it'll understand return TextColor.color(((Color) result).rgb()); } else if (result instanceof MinecraftComponent) { // Convert to adventure component from API return ComponentUtil.fromAPI((MinecraftComponent) result); } return result; }; } @Override public @NotNull MinecraftComponent build() { EnhancedComponentBuilder builder = EnhancedLegacyText.get() .buildComponent(enhancedFormat); replacements.forEach(builder::replaceAll); Component component = builder.build(); return ComponentUtil.toAPI(component); } }
3,705
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
MinecraftComponentImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/component/MinecraftComponentImpl.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.component; import com.discordsrv.api.component.MinecraftComponent; import com.discordsrv.api.component.MinecraftComponentAdapter; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; import org.jetbrains.annotations.NotNull; import java.lang.reflect.InvocationTargetException; public class MinecraftComponentImpl implements MinecraftComponent { private String json; private Component component; public static MinecraftComponentImpl empty() { return new MinecraftComponentImpl("{text:\"\"}"); } public MinecraftComponentImpl(String json) { setJson(json); } public MinecraftComponentImpl(Component component) { setComponent(component); } public Component getComponent() { return component; } public void setComponent(Component component) { this.component = component; this.json = GsonComponentSerializer.gson().serialize(component); } @Override public @NotNull String asJson() { return json; } @Override public void setJson(@NotNull String json) throws IllegalArgumentException { Component component; try { component = GsonComponentSerializer.gson().deserialize(json); } catch (Throwable t) { throw new IllegalArgumentException("Provided json is not valid: " + json, t); } this.component = component; this.json = json; } @Override public @NotNull String asPlainString() { return PlainTextComponentSerializer.plainText().serialize(component); } @Override public <T> MinecraftComponent.@NotNull Adapter<T> adventureAdapter( @NotNull Class<?> gsonSerializerClass, @NotNull Class<T> componentClass ) { return new Adapter<>(gsonSerializerClass, componentClass); } @Override public <T> MinecraftComponent.@NotNull Adapter<T> adventureAdapter(@NotNull MinecraftComponentAdapter<T> adapter) { return new Adapter<>(adapter); } @SuppressWarnings("unchecked") public class Adapter<T> implements MinecraftComponent.Adapter<T> { private final MinecraftComponentAdapter<T> adapter; private Adapter(Class<?> gsonSerializerClass, Class<T> componentClass) { this(MinecraftComponentAdapter.create(gsonSerializerClass, componentClass)); } private Adapter(MinecraftComponentAdapter<T> adapter) { this.adapter = adapter; } @Override public @NotNull T getComponent() { try { return (T) adapter.deserializeMethod() .invoke( adapter.serializerInstance(), json ); } catch (IllegalAccessException | InvocationTargetException e) { throw new RuntimeException("Failed to convert to adventure component", e); } } @Override public void setComponent(@NotNull Object adventureComponent) { try { setJson( (String) adapter.serializeMethod() .invoke( adapter.serializerInstance(), adventureComponent ) ); } catch (InvocationTargetException e) { throw new IllegalArgumentException("The provided class is not a Component for the GsonComponentSerializer " + adapter.serializerClass().getName(), e); } catch (IllegalAccessException e) { throw new RuntimeException("Failed to convert from adventure component", e); } } } }
4,763
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordSRVMinecraftRenderer.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/component/renderer/DiscordSRVMinecraftRenderer.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.component.renderer; import com.discordsrv.api.component.GameTextBuilder; import com.discordsrv.api.discord.entity.DiscordUser; import com.discordsrv.api.discord.entity.guild.DiscordCustomEmoji; import com.discordsrv.api.discord.entity.guild.DiscordGuild; import com.discordsrv.api.discord.entity.guild.DiscordGuildMember; import com.discordsrv.api.discord.entity.guild.DiscordRole; import com.discordsrv.api.event.events.message.process.discord.DiscordChatMessageCustomEmojiRenderEvent; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.component.util.ComponentUtil; import com.discordsrv.common.config.main.channels.DiscordToMinecraftChatConfig; import com.discordsrv.common.config.main.generic.MentionsConfig; import dev.vankka.mcdiscordreserializer.renderer.implementation.DefaultMinecraftRenderer; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel; import net.dv8tion.jda.api.utils.MiscUtil; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.event.ClickEvent; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; public class DiscordSRVMinecraftRenderer extends DefaultMinecraftRenderer { private static final Pattern MESSAGE_URL_PATTERN = Pattern.compile("https://(?:(?:ptb|canary)\\.)?discord\\.com/channels/[0-9]{16,20}/([0-9]{16,20})/[0-9]{16,20}"); private static final ThreadLocal<Context> CONTEXT = new ThreadLocal<>(); private final DiscordSRV discordSRV; public DiscordSRVMinecraftRenderer(DiscordSRV discordSRV) { this.discordSRV = discordSRV; } public static void runInContext( DiscordGuild guild, DiscordToMinecraftChatConfig config, Runnable runnable ) { getWithContext(guild, config, () -> { runnable.run(); return null; }); } public static <T> T getWithContext( DiscordGuild guild, DiscordToMinecraftChatConfig config, Supplier<T> supplier ) { Context oldValue = CONTEXT.get(); CONTEXT.set(new Context(guild, config)); T output = supplier.get(); CONTEXT.set(oldValue); return output; } @Override public Component appendLink(@NotNull Component part, String link) { Component messageLink = makeMessageLink(link); if (messageLink == null) { return super.appendLink(part, link); } return part.append(messageLink); } public Component makeMessageLink(String link) { JDA jda = discordSRV.jda(); if (jda == null) { return null; } Matcher matcher = MESSAGE_URL_PATTERN.matcher(link); if (!matcher.matches()) { return null; } String channel = matcher.group(1); GuildChannel guildChannel = jda.getGuildChannelById(channel); Context context = CONTEXT.get(); String format = context != null ? context.config.mentions.messageUrl : null; if (format == null || guildChannel == null) { return null; } return Component.text() .clickEvent(ClickEvent.openUrl(link)) .append( ComponentUtil.fromAPI( discordSRV.componentFactory() .textBuilder(format) .addContext(guildChannel) .addPlaceholder("jump_url", link) .applyPlaceholderService() .build() ) ) .build(); } @Override public @NotNull Component appendChannelMention(@NotNull Component component, @NotNull String id) { Context context = CONTEXT.get(); MentionsConfig.Format format = context != null ? context.config.mentions.channel : null; if (format == null) { return component.append(Component.text("<#" + id + ">")); } Component mention = makeChannelMention(MiscUtil.parseLong(id), format); if (mention == null) { return component; } return component.append(mention); } @Nullable public Component makeChannelMention(long id, MentionsConfig.Format format) { JDA jda = discordSRV.jda(); if (jda == null) { return null; } GuildChannel guildChannel = jda.getGuildChannelById(id); return ComponentUtil.fromAPI( discordSRV.componentFactory() .textBuilder(guildChannel != null ? format.format : format.unknownFormat) .addContext(guildChannel) .applyPlaceholderService() .build() ); } @Override public @NotNull Component appendUserMention(@NotNull Component component, @NotNull String id) { Context context = CONTEXT.get(); MentionsConfig.Format format = context != null ? context.config.mentions.user : null; DiscordGuild guild = context != null ? context.guild : null; if (format == null || guild == null) { return component.append(Component.text("<@" + id + ">")); } long userId = MiscUtil.parseLong(id); return component.append(makeUserMention(userId, format, guild)); } @NotNull public Component makeUserMention(long id, MentionsConfig.Format format, DiscordGuild guild) { DiscordUser user = discordSRV.discordAPI().getUserById(id); DiscordGuildMember member = guild.getMemberById(id); return ComponentUtil.fromAPI( discordSRV.componentFactory() .textBuilder(user != null ? format.format : format.unknownFormat) .addContext(user, member) .applyPlaceholderService() .build() ); } @Override public @NotNull Component appendRoleMention(@NotNull Component component, @NotNull String id) { Context context = CONTEXT.get(); MentionsConfig.Format format = context != null ? context.config.mentions.role : null; if (format == null) { return component.append(Component.text("<#" + id + ">")); } long roleId = MiscUtil.parseLong(id); return component.append(makeRoleMention(roleId, format)); } public Component makeRoleMention(long id, MentionsConfig.Format format) { DiscordRole role = discordSRV.discordAPI().getRoleById(id); return ComponentUtil.fromAPI( discordSRV.componentFactory() .textBuilder(role != null ? format.format : format.unknownFormat) .addContext(role) .applyPlaceholderService() .build() ); } @Override public @NotNull Component appendEmoteMention( @NotNull Component component, @NotNull String name, @NotNull String id ) { Context context = CONTEXT.get(); MentionsConfig.EmoteBehaviour behaviour = context != null ? context.config.mentions.customEmojiBehaviour : null; if (behaviour == null || behaviour == MentionsConfig.EmoteBehaviour.HIDE) { return component; } long emojiId = MiscUtil.parseLong(id); Component emoteMention = makeEmoteMention(emojiId, behaviour); if (emoteMention == null) { return component; } return component.append(emoteMention); } public Component makeEmoteMention(long id, MentionsConfig.EmoteBehaviour behaviour) { DiscordCustomEmoji emoji = discordSRV.discordAPI().getEmojiById(id); if (emoji == null) { return null; } DiscordChatMessageCustomEmojiRenderEvent event = new DiscordChatMessageCustomEmojiRenderEvent(emoji); discordSRV.eventBus().publish(event); if (event.isProcessed()) { return ComponentUtil.fromAPI(event.getRenderedEmojiFromProcessing()); } switch (behaviour) { case NAME: return Component.text(":" + emoji.getName() + ":"); case BLANK: default: return null; } } private static class Context { private final DiscordGuild guild; private final DiscordToMinecraftChatConfig config; public Context(DiscordGuild guild, DiscordToMinecraftChatConfig config) { this.guild = guild; this.config = config; } } }
9,704
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
StringFormatTranslation.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/component/translation/StringFormatTranslation.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.component.translation; public class StringFormatTranslation implements Translation { private final String format; public StringFormatTranslation(String format) { this.format = format; } @Override public String translate(Object[] arguments) { return String.format(format, arguments); } }
1,191
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
TranslationRegistry.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/component/translation/TranslationRegistry.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.component.translation; import org.jetbrains.annotations.Nullable; import java.util.Collections; import java.util.LinkedHashMap; import java.util.Locale; import java.util.Map; /** * Our own simple class that stores abstract {@link Translation}s instead of MessageFormats, * to be more flexible, and support Minecraft's own language files. */ public class TranslationRegistry { private static final Locale DEFAULT_LOCALE = Locale.US; private final Map<Locale, Map<String, Translation>> translations = new LinkedHashMap<>(); public TranslationRegistry() {} public void register(Locale locale, Map<String, Translation> translations) { synchronized (this.translations) { this.translations.computeIfAbsent(locale, key -> new LinkedHashMap<>()).putAll(translations); } } @Nullable public Translation lookup(Locale locale, String key) { synchronized (translations) { return translations.getOrDefault( locale, // Try the suggested locale first translations.getOrDefault( DEFAULT_LOCALE, // Then try the default locale Collections.emptyMap() // Then fail ) ).get(key); } } public void clear() { translations.clear(); } }
2,215
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
Translation.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/component/translation/Translation.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.component.translation; @FunctionalInterface public interface Translation { static Translation stringFormat(String format) { return new StringFormatTranslation(format); } String translate(Object[] arguments); }
1,093
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ComponentUtil.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/component/util/ComponentUtil.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.component.util; import com.discordsrv.api.component.MinecraftComponent; import com.discordsrv.api.component.MinecraftComponentAdapter; import com.discordsrv.common.component.MinecraftComponentImpl; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.ComponentLike; import net.kyori.adventure.text.TextComponent; import net.kyori.adventure.text.serializer.gson.GsonComponentSerializer; import net.kyori.adventure.text.serializer.plain.PlainTextComponentSerializer; import java.util.Collection; /** * An util class for {@link Component}s and {@link MinecraftComponent}s. */ public final class ComponentUtil { private static MinecraftComponentAdapter<Component> ADAPTER; private static MinecraftComponentAdapter<Component> getAdapter() { return ADAPTER != null ? ADAPTER : (ADAPTER = MinecraftComponentAdapter.create(GsonComponentSerializer.class, Component.class)); } private ComponentUtil() {} public static boolean isEmpty(Component component) { return PlainTextComponentSerializer.plainText().serialize(component).isEmpty(); } public static boolean isEmpty(MinecraftComponent component) { return component.asPlainString().isEmpty(); } public static MinecraftComponent toAPI(Component component) { return new MinecraftComponentImpl(component); } public static Component fromAPI(MinecraftComponent component) { if (component instanceof MinecraftComponentImpl) { return ((MinecraftComponentImpl) component).getComponent(); } else { return component.adventureAdapter(getAdapter()).getComponent(); } } public static void set(MinecraftComponent minecraftComponent, Component component) { if (component instanceof MinecraftComponentImpl) { ((MinecraftComponentImpl) component).setComponent(component); } else { minecraftComponent.adventureAdapter(getAdapter()).setComponent(component); } } public static MinecraftComponent fromUnrelocated(Object unrelocatedAdventure) { MinecraftComponentImpl component = MinecraftComponentImpl.empty(); MinecraftComponent.Adapter<Object> adapter = component.unrelocatedAdapter(); if (adapter == null) { throw new IllegalStateException("Could not get unrelocated adventure gson serializer"); } adapter.setComponent(unrelocatedAdventure); return component; } public static Component join(Component delimiter, Collection<? extends ComponentLike> components) { return join(delimiter, components.toArray(new ComponentLike[0])); } public static Component join(Component delimiter, ComponentLike[] components) { TextComponent.Builder builder = Component.text(); for (int i = 0; i < components.length; i++) { builder.append(components[i]); if (i < components.length - 1) { builder.append(delimiter); } } return builder.build(); } }
3,911
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
GroupSyncModule.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/groupsync/GroupSyncModule.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.groupsync; import com.discordsrv.api.DiscordSRVApi; import com.discordsrv.api.discord.entity.guild.DiscordRole; import com.discordsrv.api.event.bus.Subscribe; import com.discordsrv.api.event.events.discord.member.role.DiscordMemberRoleAddEvent; import com.discordsrv.api.event.events.discord.member.role.DiscordMemberRoleRemoveEvent; import com.discordsrv.api.module.type.PermissionModule; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.config.main.GroupSyncConfig; import com.discordsrv.common.debug.DebugGenerateEvent; import com.discordsrv.common.debug.file.TextDebugFile; import com.discordsrv.common.event.events.player.PlayerConnectedEvent; import com.discordsrv.common.future.util.CompletableFutureUtil; import com.discordsrv.common.groupsync.enums.GroupSyncCause; import com.discordsrv.common.groupsync.enums.GroupSyncDirection; import com.discordsrv.common.groupsync.enums.GroupSyncResult; import com.discordsrv.common.groupsync.enums.GroupSyncSide; import com.discordsrv.common.logging.NamedLogger; import com.discordsrv.common.module.type.AbstractModule; import com.discordsrv.common.player.IPlayer; import com.discordsrv.common.profile.Profile; import com.github.benmanes.caffeine.cache.Cache; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.Nullable; import java.time.Duration; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; public class GroupSyncModule extends AbstractModule<DiscordSRV> { private final Map<GroupSyncConfig.PairConfig, Future<?>> pairs = new LinkedHashMap<>(); private final Map<String, List<GroupSyncConfig.PairConfig>> groupsToPairs = new ConcurrentHashMap<>(); private final Map<Long, List<GroupSyncConfig.PairConfig>> rolesToPairs = new ConcurrentHashMap<>(); private final Cache<Long, Map<Long, Boolean>> expectedDiscordChanges; private final Cache<UUID, Map<String, Boolean>> expectedMinecraftChanges; public GroupSyncModule(DiscordSRV discordSRV) { super(discordSRV, new NamedLogger(discordSRV, "GROUP_SYNC")); this.expectedDiscordChanges = discordSRV.caffeineBuilder() .expireAfterWrite(30, TimeUnit.SECONDS) .build(); this.expectedMinecraftChanges = discordSRV.caffeineBuilder() .expireAfterWrite(30, TimeUnit.SECONDS) .build(); } @Override public boolean isEnabled() { boolean any = false; for (GroupSyncConfig.PairConfig pair : discordSRV.config().groupSync.pairs) { if (pair.roleId != 0 && StringUtils.isNotEmpty(pair.groupName)) { any = true; break; } } if (!any) { return false; } return super.isEnabled(); } @Override public void reload(Consumer<DiscordSRVApi.ReloadResult> resultConsumer) { synchronized (pairs) { pairs.values().forEach(future -> { if (future != null) { future.cancel(false); } }); pairs.clear(); groupsToPairs.clear(); rolesToPairs.clear(); GroupSyncConfig config = discordSRV.config().groupSync; for (GroupSyncConfig.PairConfig pair : config.pairs) { String groupName = pair.groupName; long roleId = pair.roleId; if (StringUtils.isEmpty(groupName) || roleId == 0) { continue; } if (!pair.validate(discordSRV)) { continue; } boolean failed = false; for (GroupSyncConfig.PairConfig pairConfig : config.pairs) { if (pairConfig != pair && pair.isTheSameAs(pairConfig)) { failed = true; break; } } if (failed) { discordSRV.logger().error("Duplicate group synchronization pair: " + groupName + " to " + roleId); continue; } Future<?> future = null; GroupSyncConfig.PairConfig.TimerConfig timer = pair.timer; if (timer != null && timer.enabled) { int cycleTime = timer.cycleTime; future = discordSRV.scheduler().runAtFixedRate( () -> resyncPair(pair, GroupSyncCause.TIMER), Duration.ofMinutes(cycleTime), Duration.ofMinutes(cycleTime) ); } pairs.put(pair, future); groupsToPairs.computeIfAbsent(groupName, key -> new ArrayList<>()).add(pair); rolesToPairs.computeIfAbsent(roleId, key -> new ArrayList<>()).add(pair); } } } // Debug @Subscribe public void onDebugGenerate(DebugGenerateEvent event) { StringBuilder builder = new StringBuilder("Active pairs:"); for (Map.Entry<GroupSyncConfig.PairConfig, Future<?>> entry : pairs.entrySet()) { GroupSyncConfig.PairConfig pair = entry.getKey(); builder.append("\n- ").append(pair) .append(" (tie-breaker: ").append(pair.tieBreaker) .append(", direction: ").append(pair.direction) .append(", server context: ").append(pair.serverContext).append(")"); if (entry.getValue() != null) { builder.append(" [Timed]"); } } PermissionModule.Groups groups = getPermissionProvider(); if (groups != null) { builder.append("\n\nAvailable groups (").append(groups.getClass().getName()).append("):"); for (String group : groups.getGroups()) { builder.append("\n- ").append(group); } } else { builder.append("\n\nNo permission provider available"); } event.addFile(new TextDebugFile("group-sync.txt", builder)); } private void logSummary( UUID player, GroupSyncCause cause, Map<GroupSyncConfig.PairConfig, CompletableFuture<GroupSyncResult>> pairs ) { CompletableFutureUtil.combine(pairs.values()).whenComplete((v, t) -> { SynchronizationSummary summary = new SynchronizationSummary(player, cause); for (Map.Entry<GroupSyncConfig.PairConfig, CompletableFuture<GroupSyncResult>> entry : pairs.entrySet()) { summary.add(entry.getKey(), entry.getValue().join()); } String finalSummary = summary.toString(); logger().debug(finalSummary); if (summary.anySuccess()) { // If anything was changed as a result of synchronization, log to file discordSRV.logger().writeLogForCurrentDay("groupsync", finalSummary); } }); } // Linked account helper methods private CompletableFuture<Long> lookupLinkedAccount(UUID player) { return discordSRV.profileManager().lookupProfile(player) .thenApply(Profile::userId); } private CompletableFuture<UUID> lookupLinkedAccount(long userId) { return discordSRV.profileManager().lookupProfile(userId) .thenApply(Profile::playerUUID); } // Permission data helper methods private PermissionModule.Groups getPermissionProvider() { PermissionModule.GroupsContext groupsContext = discordSRV.getModule(PermissionModule.GroupsContext.class); return groupsContext == null ? discordSRV.getModule(PermissionModule.Groups.class) : groupsContext; } public boolean noPermissionProvider() { PermissionModule.Groups groups = getPermissionProvider(); return groups == null || !groups.isEnabled(); } private boolean supportsOffline() { return getPermissionProvider().supportsOffline(); } private CompletableFuture<Boolean> hasGroup( UUID player, String groupName, @Nullable String serverContext ) { PermissionModule.Groups permissionProvider = getPermissionProvider(); if (permissionProvider instanceof PermissionModule.GroupsContext) { return ((PermissionModule.GroupsContext) permissionProvider) .hasGroup(player, groupName, false, serverContext != null ? Collections.singleton(serverContext) : null); } else { return permissionProvider.hasGroup(player, groupName, false); } } private CompletableFuture<Void> addGroup( UUID player, String groupName, @Nullable String serverContext ) { PermissionModule.Groups permissionProvider = getPermissionProvider(); if (permissionProvider instanceof PermissionModule.GroupsContext) { return ((PermissionModule.GroupsContext) permissionProvider) .addGroup(player, groupName, Collections.singleton(serverContext)); } else { return permissionProvider.addGroup(player, groupName); } } private CompletableFuture<Void> removeGroup( UUID player, String groupName, @Nullable String serverContext ) { PermissionModule.Groups permissionProvider = getPermissionProvider(); if (permissionProvider instanceof PermissionModule.GroupsContext) { return ((PermissionModule.GroupsContext) permissionProvider) .removeGroup(player, groupName, Collections.singleton(serverContext)); } else { return permissionProvider.removeGroup(player, groupName); } } // Resync user public CompletableFuture<List<GroupSyncResult>> resync(UUID player, GroupSyncCause cause) { return lookupLinkedAccount(player).thenCompose(userId -> { if (userId == null) { return CompletableFuture.completedFuture(Collections.emptyList()); } return CompletableFutureUtil.combine(resync(player, userId, cause)); }); } public CompletableFuture<List<GroupSyncResult>> resync(long userId, GroupSyncCause cause) { return lookupLinkedAccount(userId).thenCompose(player -> { if (player == null) { return CompletableFuture.completedFuture(Collections.emptyList()); } return CompletableFutureUtil.combine(resync(player, userId, cause)); }); } public Collection<CompletableFuture<GroupSyncResult>> resync(UUID player, long userId, GroupSyncCause cause) { if (noPermissionProvider()) { return Collections.singletonList(CompletableFuture.completedFuture(GroupSyncResult.NO_PERMISSION_PROVIDER)); } else if (discordSRV.playerProvider().player(player) == null && !supportsOffline()) { return Collections.singletonList(CompletableFuture.completedFuture(GroupSyncResult.PERMISSION_PROVIDER_NO_OFFLINE_SUPPORT)); } Map<GroupSyncConfig.PairConfig, CompletableFuture<GroupSyncResult>> futures = new LinkedHashMap<>(); for (GroupSyncConfig.PairConfig pair : pairs.keySet()) { futures.put(pair, resyncPair(pair, player, userId)); } logSummary(player, cause, futures); return futures.values(); } private void resyncPair(GroupSyncConfig.PairConfig pair, GroupSyncCause cause) { if (noPermissionProvider()) { return; } for (IPlayer player : discordSRV.playerProvider().allPlayers()) { UUID uuid = player.uniqueId(); lookupLinkedAccount(uuid).whenComplete((userId, t) -> { if (userId == null) { return; } resyncPair(pair, uuid, userId).whenComplete((result, t2) -> logger().debug( new SynchronizationSummary(uuid, cause, pair, result).toString() )); }); } } private CompletableFuture<GroupSyncResult> resyncPair(GroupSyncConfig.PairConfig pair, UUID player, long userId) { DiscordRole role = discordSRV.discordAPI().getRoleById(pair.roleId); if (role == null) { return CompletableFuture.completedFuture(GroupSyncResult.ROLE_DOESNT_EXIST); } if (!role.getGuild().getSelfMember().canInteract(role)) { return CompletableFuture.completedFuture(GroupSyncResult.ROLE_CANNOT_INTERACT); } return role.getGuild().retrieveMemberById(userId).thenCompose(member -> { if (member == null) { return CompletableFuture.completedFuture(GroupSyncResult.NOT_A_GUILD_MEMBER); } boolean hasRole = member.hasRole(role); String groupName = pair.groupName; CompletableFuture<GroupSyncResult> resultFuture = new CompletableFuture<>(); hasGroup(player, groupName, pair.serverContext).whenComplete((hasGroup, t) -> { if (t != null) { discordSRV.logger().error("Failed to check if player " + player + " has group " + groupName, t); resultFuture.complete(GroupSyncResult.PERMISSION_BACKEND_FAIL_CHECK); return; } if (hasRole == hasGroup) { resultFuture.complete(hasRole ? GroupSyncResult.BOTH_TRUE : GroupSyncResult.BOTH_FALSE); // We're all good return; } GroupSyncSide side = pair.tieBreaker; GroupSyncDirection direction = pair.direction; CompletableFuture<Void> future; GroupSyncResult result; if (hasRole) { if (side == GroupSyncSide.DISCORD) { // Has role, add group if (direction == GroupSyncDirection.MINECRAFT_TO_DISCORD) { resultFuture.complete(GroupSyncResult.WRONG_DIRECTION); return; } result = GroupSyncResult.ADD_GROUP; future = addGroup(player, groupName, pair.serverContext); } else { // Doesn't have group, remove role if (direction == GroupSyncDirection.DISCORD_TO_MINECRAFT) { resultFuture.complete(GroupSyncResult.WRONG_DIRECTION); return; } result = GroupSyncResult.REMOVE_ROLE; future = member.removeRole(role); } } else { if (side == GroupSyncSide.DISCORD) { // Doesn't have role, remove group if (direction == GroupSyncDirection.MINECRAFT_TO_DISCORD) { resultFuture.complete(GroupSyncResult.WRONG_DIRECTION); return; } result = GroupSyncResult.REMOVE_GROUP; future = removeGroup(player, groupName, pair.serverContext); } else { // Has group, add role if (direction == GroupSyncDirection.DISCORD_TO_MINECRAFT) { resultFuture.complete(GroupSyncResult.WRONG_DIRECTION); return; } result = GroupSyncResult.ADD_ROLE; future = member.addRole(role); } } future.whenComplete((v, t2) -> { if (t2 != null) { discordSRV.logger().error("Failed to " + result + " to " + player + "/" + Long.toUnsignedString(userId), t2); resultFuture.complete(GroupSyncResult.UPDATE_FAILED); return; } resultFuture.complete(result); }); }); return resultFuture; }); } // Listeners & methods to indicate something changed @Subscribe public void onPlayerConnected(PlayerConnectedEvent event) { resync(event.player().uniqueId(), GroupSyncCause.GAME_JOIN); } @Subscribe public void onDiscordMemberRoleAdd(DiscordMemberRoleAddEvent event) { event.getRoles().forEach(role -> roleChanged(event.getMember().getUser().getId(), role.getId(), false)); } @Subscribe public void onDiscordMemberRoleRemove(DiscordMemberRoleRemoveEvent event) { event.getRoles().forEach(role -> roleChanged(event.getMember().getUser().getId(), role.getId(), true)); } public void groupAdded(UUID player, String groupName, @Nullable Set<String> serverContext, GroupSyncCause cause) { groupChanged(player, groupName, serverContext, cause, false); } public void groupRemoved(UUID player, String groupName, @Nullable Set<String> serverContext, GroupSyncCause cause) { groupChanged(player, groupName, serverContext, cause, true); } // Internal handling of changes private <T, R> boolean checkExpectation(Cache<T, Map<R, Boolean>> expectations, T key, R mapKey, boolean remove) { // Check if we were expecting the change (when we add/remove something due to synchronization), // if we did expect the change, we won't trigger a synchronization since we just synchronized what was needed Map<R, Boolean> expected = expectations.getIfPresent(key); if (expected != null && Objects.equals(expected.get(mapKey), remove)) { expected.remove(mapKey); return true; } return false; } private void roleChanged(long userId, long roleId, boolean remove) { if (noPermissionProvider()) { return; } if (checkExpectation(expectedDiscordChanges, userId, roleId, remove)) { return; } lookupLinkedAccount(userId).whenComplete((player, t) -> { if (player == null) { return; } roleChanged(userId, player, roleId, remove); }); } private void roleChanged(long userId, UUID player, long roleId, boolean remove) { List<GroupSyncConfig.PairConfig> pairs = rolesToPairs.get(roleId); if (pairs == null) { return; } PermissionModule.Groups permissionProvider = getPermissionProvider(); if (permissionProvider == null) { discordSRV.logger().warning("No supported permission plugin available to perform group sync"); return; } Map<GroupSyncConfig.PairConfig, CompletableFuture<GroupSyncResult>> futures = new LinkedHashMap<>(); for (GroupSyncConfig.PairConfig pair : pairs) { GroupSyncDirection direction = pair.direction; if (direction == GroupSyncDirection.MINECRAFT_TO_DISCORD) { // Not going Discord -> Minecraft futures.put(pair, CompletableFuture.completedFuture(GroupSyncResult.WRONG_DIRECTION)); continue; } futures.put(pair, modifyGroupState(player, pair, remove)); // If the sync is bidirectional, also add/remove any other roles that are linked to this group if (direction == GroupSyncDirection.DISCORD_TO_MINECRAFT) { continue; } List<GroupSyncConfig.PairConfig> groupPairs = groupsToPairs.get(pair.groupName); if (groupPairs == null) { continue; } for (GroupSyncConfig.PairConfig groupPair : groupPairs) { if (groupPair.roleId == roleId) { continue; } futures.put(groupPair, modifyRoleState(userId, groupPair, remove)); } } logSummary(player, GroupSyncCause.DISCORD_ROLE_CHANGE, futures); } private void groupChanged( UUID player, String groupName, @Nullable Set<String> serverContext, GroupSyncCause cause, boolean remove ) { if (noPermissionProvider()) { return; } if (cause.isDiscordSRVCanCause() && checkExpectation(expectedMinecraftChanges, player, groupName, remove)) { return; } lookupLinkedAccount(player).whenComplete((userId, t) -> { if (userId == null) { return; } groupChanged(player, userId, groupName, serverContext, cause, remove); }); } private void groupChanged( UUID player, long userId, String groupName, @Nullable Set<String> serverContext, GroupSyncCause cause, boolean remove ) { List<GroupSyncConfig.PairConfig> pairs = groupsToPairs.get(groupName); if (pairs == null) { return; } PermissionModule.Groups permissionProvider = getPermissionProvider(); Map<GroupSyncConfig.PairConfig, CompletableFuture<GroupSyncResult>> futures = new LinkedHashMap<>(); for (GroupSyncConfig.PairConfig pair : pairs) { GroupSyncDirection direction = pair.direction; if (direction == GroupSyncDirection.DISCORD_TO_MINECRAFT) { // Not going Minecraft -> Discord futures.put(pair, CompletableFuture.completedFuture(GroupSyncResult.WRONG_DIRECTION)); continue; } // Check if we're in the right context String context = pair.serverContext; if (permissionProvider instanceof PermissionModule.GroupsContext) { if (StringUtils.isEmpty(context)) { // Use the default server context of the server Set<String> defaultValues = ((PermissionModule.GroupsContext) permissionProvider) .getDefaultServerContext(); if (!Objects.equals(serverContext, defaultValues)) { continue; } } else if (context.equals("global")) { // No server context if (serverContext != null && !serverContext.isEmpty()) { continue; } } else { // Server context has to match the specified if (serverContext == null || serverContext.size() != 1 || !serverContext.iterator().next().equals(context)) { continue; } } } futures.put(pair, modifyRoleState(userId, pair, remove)); // If the sync is bidirectional, also add/remove any other groups that are linked to this role if (direction == GroupSyncDirection.MINECRAFT_TO_DISCORD) { continue; } long roleId = pair.roleId; List<GroupSyncConfig.PairConfig> rolePairs = rolesToPairs.get(roleId); if (rolePairs == null || rolePairs.isEmpty()) { continue; } for (GroupSyncConfig.PairConfig rolePair : rolePairs) { if (rolePair.groupName.equals(groupName)) { continue; } futures.put(rolePair, modifyGroupState(player, rolePair, remove)); } } logSummary(player, cause, futures); } private CompletableFuture<GroupSyncResult> modifyGroupState(UUID player, GroupSyncConfig.PairConfig config, boolean remove) { String groupName = config.groupName; Map<String, Boolean> expected = expectedMinecraftChanges.get(player, key -> new ConcurrentHashMap<>()); if (expected != null) { expected.put(groupName, remove); } CompletableFuture<GroupSyncResult> future = new CompletableFuture<>(); String serverContext = config.serverContext; hasGroup(player, groupName, serverContext).thenCompose(hasGroup -> { if (remove && hasGroup) { return removeGroup(player, groupName, serverContext).thenApply(v -> GroupSyncResult.REMOVE_GROUP); } else if (!remove && !hasGroup) { return addGroup(player, groupName, serverContext).thenApply(v -> GroupSyncResult.ADD_GROUP); } else { // Nothing to do return CompletableFuture.completedFuture(GroupSyncResult.ALREADY_IN_SYNC); } }).whenComplete((result, t) -> { if (t != null) { if (expected != null) { // Failed, remove expectation expected.remove(groupName); } future.complete(GroupSyncResult.UPDATE_FAILED); discordSRV.logger().error("Failed to add group " + groupName + " to " + player, t); return; } future.complete(result); }); return future; } private CompletableFuture<GroupSyncResult> modifyRoleState(long userId, GroupSyncConfig.PairConfig config, boolean remove) { long roleId = config.roleId; DiscordRole role = discordSRV.discordAPI().getRoleById(roleId); if (role == null) { return CompletableFuture.completedFuture(GroupSyncResult.ROLE_DOESNT_EXIST); } if (!role.getGuild().getSelfMember().canInteract(role)) { return CompletableFuture.completedFuture(GroupSyncResult.ROLE_CANNOT_INTERACT); } return role.getGuild().retrieveMemberById(userId).thenCompose(member -> { if (member == null) { return CompletableFuture.completedFuture(GroupSyncResult.NOT_A_GUILD_MEMBER); } Map<Long, Boolean> expected = expectedDiscordChanges.get(userId, key -> new ConcurrentHashMap<>()); if (expected != null) { expected.put(roleId, remove); } boolean hasRole = member.hasRole(role); CompletableFuture<GroupSyncResult> future; if (remove && hasRole) { future = member.removeRole(role).thenApply(v -> GroupSyncResult.REMOVE_ROLE); } else if (!remove && !hasRole) { future = member.addRole(role).thenApply(v -> GroupSyncResult.ADD_ROLE); } else { if (expected != null) { // Nothing needed to be changed, remove expectation expected.remove(roleId); } return CompletableFuture.completedFuture(GroupSyncResult.ALREADY_IN_SYNC); } CompletableFuture<GroupSyncResult> resultFuture = new CompletableFuture<>(); future.whenComplete((result, t) -> { if (t != null) { if (expected != null) { // Failed, remove expectation expected.remove(roleId); } resultFuture.complete(GroupSyncResult.UPDATE_FAILED); discordSRV.logger().error("Failed to give/take role " + role + " to/from " + member, t); return; } resultFuture.complete(result); }); return resultFuture; }); } }
28,706
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
SynchronizationSummary.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/groupsync/SynchronizationSummary.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.groupsync; import com.discordsrv.common.config.main.GroupSyncConfig; import com.discordsrv.common.groupsync.enums.GroupSyncCause; import com.discordsrv.common.groupsync.enums.GroupSyncResult; import java.util.*; public class SynchronizationSummary { private final EnumMap<GroupSyncResult, Set<GroupSyncConfig.PairConfig>> pairs = new EnumMap<>(GroupSyncResult.class); private final UUID player; private final GroupSyncCause cause; public SynchronizationSummary(UUID player, GroupSyncCause cause, GroupSyncConfig.PairConfig config, GroupSyncResult result) { this(player, cause); add(config, result); } public SynchronizationSummary(UUID player, GroupSyncCause cause) { this.player = player; this.cause = cause; } public void add(GroupSyncConfig.PairConfig config, GroupSyncResult result) { pairs.computeIfAbsent(result, key -> new LinkedHashSet<>()).add(config); } public boolean anySuccess() { for (GroupSyncResult result : pairs.keySet()) { if (result.isSuccess()) { return true; } } return false; } @Override public String toString() { int count = pairs.size(); StringBuilder message = new StringBuilder( "Group synchronization (of " + count + " pair" + (count == 1 ? "" : "s") + ") for " + player + " (" + cause + ")"); for (Map.Entry<GroupSyncResult, Set<GroupSyncConfig.PairConfig>> entry : pairs.entrySet()) { message.append(count == 1 ? ": " : "\n") .append(entry.getKey().toString()) .append(": ") .append(entry.getValue().toString()); } return message.toString(); } }
2,635
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
GroupSyncSide.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/groupsync/enums/GroupSyncSide.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.groupsync.enums; public enum GroupSyncSide { MINECRAFT, DISCORD }
937
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
GroupSyncDirection.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/groupsync/enums/GroupSyncDirection.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.groupsync.enums; public enum GroupSyncDirection { MINECRAFT_TO_DISCORD, DISCORD_TO_MINECRAFT, BIDIRECTIONAL }
985
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
GroupSyncResult.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/groupsync/enums/GroupSyncResult.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.groupsync.enums; public enum GroupSyncResult { // Something happened ADD_GROUP("Success (group add)", true), REMOVE_GROUP("Success (group remove)", true), ADD_ROLE("Success (role add)", true), REMOVE_ROLE("Success (role remove)", true), // Nothing done ALREADY_IN_SYNC("Already in sync"), WRONG_DIRECTION("Wrong direction"), BOTH_TRUE("Both sides true"), BOTH_FALSE("Both sides false"), // Errors ROLE_DOESNT_EXIST("Role doesn't exist"), ROLE_CANNOT_INTERACT("Bot doesn't have a role above the synced role (cannot interact)"), NOT_A_GUILD_MEMBER("User is not part of the server the role is in"), PERMISSION_BACKEND_FAIL_CHECK("Failed to check group status, error printed"), UPDATE_FAILED("Failed to modify role/group, error printed"), NO_PERMISSION_PROVIDER("No permission provider"), PERMISSION_PROVIDER_NO_OFFLINE_SUPPORT("Permission provider doesn't support offline players"), ; final String prettyResult; final boolean success; GroupSyncResult(String prettyResult) { this(prettyResult, false); } GroupSyncResult(String prettyResult, boolean success) { this.prettyResult = prettyResult; this.success = success; } public boolean isSuccess() { return success; } @Override public String toString() { return prettyResult; } }
2,255
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
GroupSyncCause.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/groupsync/enums/GroupSyncCause.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.groupsync.enums; public enum GroupSyncCause { API("API"), COMMAND("Command"), GAME_JOIN("Joined game"), LINK("Linked account"), TIMER("Timed synchronization"), DISCORD_ROLE_CHANGE("Discord role changed", true), LUCKPERMS_NODE_CHANGE("LuckPerms node changed", true), LUCKPERMS_TRACK("LuckPerms track promotion/demotion"), ; private final String prettyCause; private final boolean discordSRVCanCause; GroupSyncCause(String prettyCause) { this(prettyCause, false); } GroupSyncCause(String prettyCause, boolean discordSRVCanCause) { this.prettyCause = prettyCause; this.discordSRVCanCause = discordSRVCanCause; } public boolean isDiscordSRVCanCause() { return discordSRVCanCause; } @Override public String toString() { return prettyCause; } }
1,726
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
UpdateChecker.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/update/UpdateChecker.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.update; import com.discordsrv.api.event.bus.Subscribe; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.config.connection.ConnectionConfig; import com.discordsrv.common.config.connection.UpdateConfig; import com.discordsrv.common.debug.data.VersionInfo; import com.discordsrv.common.event.events.player.PlayerConnectedEvent; import com.discordsrv.common.exception.MessageException; import com.discordsrv.common.http.util.HttpUtil; import com.discordsrv.common.logging.NamedLogger; import com.discordsrv.common.permission.Permission; import com.discordsrv.common.player.IPlayer; import com.discordsrv.common.update.github.GitHubCompareResponse; import com.discordsrv.common.update.github.GithubRelease; import com.fasterxml.jackson.core.type.TypeReference; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.event.ClickEvent; import net.kyori.adventure.text.format.NamedTextColor; import okhttp3.Request; import okhttp3.Response; import okhttp3.ResponseBody; import org.apache.commons.lang3.StringUtils; import java.io.IOException; import java.util.ArrayList; import java.util.List; public class UpdateChecker { private static final String USER_DOWNLOAD_URL = "-";// DiscordSRV.WEBSITE + "/download"; public static final String GITHUB_REPOSITORY = "DiscordSRV/Ascension"; private static final String GITHUB_DEV_BRANCH = "main"; public static final String DOWNLOAD_SERVICE_DOMAIN = "download.discordsrv.com"; private static final String DOWNLOAD_SERVICE_HOST = "https://" + DOWNLOAD_SERVICE_DOMAIN; private static final String DOWNLOAD_SERVICE_SNAPSHOT_CHANNEL = "testing"; private static final String DOWNLOAD_SERVICE_RELEASE_CHANNEL = null; public static final String GITHUB_API_DOMAIN = "api.github.com"; private static final String GITHUB_API_HOST = "https://" + GITHUB_API_DOMAIN; private final DiscordSRV discordSRV; private final NamedLogger logger; private boolean securityFailed = false; private VersionCheck latestCheck; private VersionCheck loggedCheck; public UpdateChecker(DiscordSRV discordSRV) { this.discordSRV = discordSRV; this.logger = new NamedLogger(discordSRV, "UPDATES"); discordSRV.eventBus().subscribe(this); } public boolean isSecurityFailed() { return securityFailed; } /** * @return if enabling is permitted */ public boolean check(boolean logUpToDate) { UpdateConfig config = discordSRV.connectionConfig().update; boolean isSnapshot = discordSRV.versionInfo().isSnapshot(); boolean isSecurity = config.security.enabled; boolean isFirstPartyNotification = config.firstPartyNotification; boolean isNotification = config.notificationEnabled; if (!isSecurity && !isNotification) { // Nothing to do return true; } if (isFirstPartyNotification || isSecurity) { VersionCheck check = null; try { check = checkFirstParty(isSnapshot); if (check == null && isSecurity) { securityFailed = true; return false; } } catch (Throwable t) { List<String> failedThings = new ArrayList<>(2); if (isSecurity) { failedThings.add("perform version security check"); } if (isFirstPartyNotification) { failedThings.add("check for updates"); } logger.warning("Failed to " + String.join(" and ", failedThings) + " from the first party API", t); if (config.security.force) { logger.error("Security check is required (as configured in " + ConnectionConfig.FILE_NAME + ")" + ", startup will be cancelled."); securityFailed = true; return false; } } if (isNotification && isFirstPartyNotification && check != null && check.status != VersionCheck.Status.UNKNOWN) { latestCheck = check; log(check, logUpToDate); return true; } } if (isNotification && config.github.enabled) { VersionCheck check = null; try { check = checkGitHub(isSnapshot); } catch (Throwable t) { logger.warning("Failed to check for updates from GitHub", t); } if (check != null && check.status != VersionCheck.Status.UNKNOWN) { latestCheck = check; log(check, logUpToDate); return true; } else { logger.error("Update check" + (isFirstPartyNotification ? "s" : "") + " failed: unknown version"); } } return true; } /** * @return {@code null} for preventing shutdown */ private VersionCheck checkFirstParty(boolean isSnapshot) throws IOException { VersionInfo versionInfo = discordSRV.versionInfo(); Request request = new Request.Builder() .url(DOWNLOAD_SERVICE_HOST + "/v2/" + GITHUB_REPOSITORY + "/" + (isSnapshot ? DOWNLOAD_SERVICE_SNAPSHOT_CHANNEL : DOWNLOAD_SERVICE_RELEASE_CHANNEL) + "/version-check/" + (isSnapshot ? versionInfo.gitRevision() : versionInfo.version())) .get().build(); String responseString; try (Response response = discordSRV.httpClient().newCall(request).execute()) { ResponseBody responseBody = HttpUtil.checkIfResponseSuccessful(request, response); responseString = responseBody.string(); } VersionCheck versionCheck = discordSRV.json().readValue(responseString, VersionCheck.class); if (versionCheck == null) { throw new MessageException("Failed to parse " + request.url() + " response body: " + StringUtils.substring(responseString, 0, 500)); } boolean insecure = versionCheck.insecure; List<String> securityIssues = versionCheck.securityIssues; if (insecure) { logger.error("This version of DiscordSRV is insecure, security issues are listed below, startup will be cancelled."); for (String securityIssue : versionCheck.securityIssues) { logger.error(securityIssue); } // Block startup return null; } else if (securityIssues != null && !securityIssues.isEmpty()) { logger.warning("There are security warnings for this version of DiscordSRV, listed below"); for (String securityIssue : versionCheck.securityIssues) { logger.warning(securityIssue); } } return versionCheck; } private VersionCheck checkGitHub(boolean isSnapshot) throws IOException { VersionInfo versionInfo = discordSRV.versionInfo(); if (isSnapshot) { Request request = new Request.Builder() .url(GITHUB_API_HOST + "/repos/" + GITHUB_REPOSITORY + "/compare/" + GITHUB_DEV_BRANCH + "..." + versionInfo.gitRevision() + "?per_page=0") .get().build(); try (Response response = discordSRV.httpClient().newCall(request).execute()) { ResponseBody responseBody = HttpUtil.checkIfResponseSuccessful(request, response); GitHubCompareResponse compare = discordSRV.json().readValue(responseBody.byteStream(), GitHubCompareResponse.class); VersionCheck versionCheck = new VersionCheck(); versionCheck.amount = compare.behind_by; versionCheck.amountType = (compare.behind_by == 1 ? "commit" : "commits"); versionCheck.amountSource = VersionCheck.AmountSource.GITHUB; if ("behind".equals(compare.status)) { versionCheck.status = VersionCheck.Status.OUTDATED; } else if ("identical".equals(compare.status)) { versionCheck.status = VersionCheck.Status.UP_TO_DATE; } else { versionCheck.status = VersionCheck.Status.UNKNOWN; } return versionCheck; } } String version = versionInfo.version(); int versionsBehind = 0; boolean found = false; int perPage = 100; int page = 0; for (int i = 0; i < 3 /* max 3 loops */; i++) { Request request = new Request.Builder() .url(GITHUB_API_HOST + "/repos/" + GITHUB_REPOSITORY + "/releases?per_page=" + perPage + "&page=" + page) .get().build(); try (Response response = discordSRV.httpClient().newCall(request).execute()) { ResponseBody responseBody = HttpUtil.checkIfResponseSuccessful(request, response); List<GithubRelease> releases = discordSRV.json().readValue(responseBody.byteStream(), new TypeReference<List<GithubRelease>>() {}); for (GithubRelease release : releases) { if (version.equals(release.tag_name)) { found = true; break; } versionsBehind++; } if (found || releases.size() < perPage) { break; } } } VersionCheck versionCheck = new VersionCheck(); versionCheck.amountSource = VersionCheck.AmountSource.GITHUB; versionCheck.amountType = (versionsBehind == 1 ? "release" : "releases"); if (!found) { versionCheck.status = VersionCheck.Status.UNKNOWN; versionCheck.amount = -1; } else { versionCheck.status = versionsBehind == 0 ? VersionCheck.Status.UP_TO_DATE : VersionCheck.Status.OUTDATED; versionCheck.amount = versionsBehind; } return versionCheck; } private void log(VersionCheck versionCheck, boolean logUpToDate) { switch (versionCheck.status) { case UP_TO_DATE: { if (logUpToDate) { logger.info("DiscordSRV is up-to-date."); loggedCheck = versionCheck; } break; } case OUTDATED: { // only log if there is new information if (loggedCheck == null || loggedCheck.amount != versionCheck.amount) { logger.warning( "DiscordSRV is outdated by " + versionCheck.amount + " " + versionCheck.amountType + ". Get the latest version from " + USER_DOWNLOAD_URL); loggedCheck = versionCheck; } break; } default: throw new IllegalStateException("Unexpected version check status: " + versionCheck.status.name()); } } @Subscribe public void onPlayerConnected(PlayerConnectedEvent event) { UpdateConfig config = discordSRV.connectionConfig().update; if (!config.notificationEnabled || !config.notificationInGame) { return; } if (latestCheck == null || latestCheck.status != VersionCheck.Status.OUTDATED) { return; } IPlayer player = event.player(); if (!player.hasPermission(Permission.UPDATE_NOTIFICATION)) { return; } player.sendMessage( Component.text("There is a new version of DiscordSRV available, ", NamedTextColor.AQUA) .append(Component.text() .content("click here to download it") .clickEvent(ClickEvent.openUrl(USER_DOWNLOAD_URL))) ); } }
13,035
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
VersionCheck.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/update/VersionCheck.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.update; import java.util.List; public class VersionCheck { public Status status; public int amount; public AmountSource amountSource; public String amountType; public boolean insecure; public List<String> securityIssues; public enum Status { UP_TO_DATE, OUTDATED, UNKNOWN } public enum AmountSource { GITHUB } }
1,251
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
GithubRelease.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/update/github/GithubRelease.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.update.github; public class GithubRelease { public String tag_name; }
936
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
GitHubCompareResponse.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/update/github/GitHubCompareResponse.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.update.github; public class GitHubCompareResponse { public String status; public int behind_by; }
969
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
IOfflinePlayer.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/player/IOfflinePlayer.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.player; import com.discordsrv.api.placeholder.annotation.Placeholder; import com.discordsrv.api.placeholder.annotation.PlaceholderPrefix; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.player.provider.model.SkinInfo; import com.discordsrv.common.profile.Profile; import net.kyori.adventure.identity.Identified; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.UUID; import java.util.concurrent.CompletableFuture; @PlaceholderPrefix("player_") public interface IOfflinePlayer extends Identified { DiscordSRV discordSRV(); @ApiStatus.NonExtendable default CompletableFuture<Profile> lookupProfile() { return discordSRV().profileManager().lookupProfile(uniqueId()); } @Placeholder("name") @Nullable String username(); @ApiStatus.NonExtendable @Placeholder(value = "uuid", relookup = "uuid") @NotNull default UUID uniqueId() { return identity().uuid(); } @Nullable SkinInfo skinInfo(); @Placeholder("skin_texture_id") @Nullable default String skinTextureId() { SkinInfo info = skinInfo(); return info != null ? info.textureId() : null; } @Placeholder("skin_model") @Nullable default String skinModel() { SkinInfo info = skinInfo(); return info != null ? info.model() : null; } }
2,301
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
OfflinePlayer.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/player/OfflinePlayer.java
package com.discordsrv.common.player; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.player.provider.model.SkinInfo; import net.kyori.adventure.identity.Identity; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.UUID; public class OfflinePlayer implements IOfflinePlayer { private final DiscordSRV discordSRV; private final String username; private final Identity identity; private final SkinInfo skinInfo; public OfflinePlayer(DiscordSRV discordSRV, String username, UUID uuid, SkinInfo skinInfo) { this.discordSRV = discordSRV; this.username = username; this.identity = Identity.identity(uuid); this.skinInfo = skinInfo; } @Override public DiscordSRV discordSRV() { return discordSRV; } @Override public @Nullable String username() { return username; } @Override public @NotNull Identity identity() { return identity; } @Override public @Nullable SkinInfo skinInfo() { return skinInfo; } }
1,113
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
IPlayer.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/player/IPlayer.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.player; import com.discordsrv.api.component.MinecraftComponent; import com.discordsrv.api.placeholder.annotation.Placeholder; import com.discordsrv.api.placeholder.annotation.PlaceholderPrefix; import com.discordsrv.api.player.DiscordSRVPlayer; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.command.game.sender.ICommandSender; import com.discordsrv.common.component.util.ComponentUtil; import com.discordsrv.common.config.main.AvatarProviderConfig; import com.discordsrv.common.permission.util.PermissionUtil; import com.discordsrv.common.profile.Profile; import net.kyori.adventure.text.Component; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.UUID; @PlaceholderPrefix("player_") public interface IPlayer extends DiscordSRVPlayer, IOfflinePlayer, ICommandSender { @Override default void sendMessage(@NotNull MinecraftComponent component) { sendMessage(ComponentUtil.fromAPI(component)); } @Override DiscordSRV discordSRV(); @ApiStatus.NonExtendable default Profile profile() { Profile profile = discordSRV().profileManager().getProfile(uniqueId()); if (profile == null) { throw new IllegalStateException("Profile does not exist"); } return profile; } @NotNull @Placeholder("name") String username(); @Override @ApiStatus.NonExtendable @Placeholder(value = "uuid", relookup = "uuid") default @NotNull UUID uniqueId() { return identity().uuid(); } @NotNull @Placeholder("display_name") Component displayName(); @Nullable @ApiStatus.NonExtendable @Placeholder("avatar_url") default String getAvatarUrl() { AvatarProviderConfig avatarConfig = discordSRV().config().avatarProvider; String avatarUrlTemplate = avatarConfig.avatarUrlTemplate; if (avatarConfig.autoDecideAvatarUrl) { // Offline mode if (uniqueId().version() == 3) avatarUrlTemplate = "https://cravatar.eu/helmavatar/%player_name%/128.png#%player_skin_texture_id%"; // Bedrock else if (uniqueId().getLeastSignificantBits() == 0) avatarUrlTemplate = "https://api.tydiumcraft.net/skin?uuid=%player_uuid_short%&type=avatar&size=128"; } if (avatarUrlTemplate == null) { return null; } return discordSRV().placeholderService().replacePlaceholders(avatarUrlTemplate, this); } @Nullable @ApiStatus.NonExtendable @Placeholder("meta_prefix") default Component getMetaPrefix() { return PermissionUtil.getMetaPrefix(discordSRV(), uniqueId()); } @Nullable @ApiStatus.NonExtendable @Placeholder("meta_suffix") default Component getMetaSuffix() { return PermissionUtil.getMetaSuffix(discordSRV(), uniqueId()); } @Nullable @ApiStatus.NonExtendable @Placeholder("prefix") default Component getPrefix() { return PermissionUtil.getPrefix(discordSRV(), uniqueId()); } @Nullable @ApiStatus.NonExtendable @Placeholder("suffix") default Component getSuffix() { return PermissionUtil.getSuffix(discordSRV(), uniqueId()); } }
4,147
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
AbstractPlayerProvider.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/player/provider/AbstractPlayerProvider.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.player.provider; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.event.events.player.PlayerConnectedEvent; import com.discordsrv.common.event.events.player.PlayerDisconnectedEvent; import com.discordsrv.common.http.util.HttpUtil; import com.discordsrv.common.player.IOfflinePlayer; import com.discordsrv.common.player.IPlayer; import com.discordsrv.common.player.OfflinePlayer; import com.discordsrv.common.player.provider.model.GameProfileResponse; import com.discordsrv.common.player.provider.model.SkinInfo; import com.discordsrv.common.player.provider.model.Textures; import com.discordsrv.common.player.provider.model.UUIDResponse; import com.discordsrv.common.uuid.util.UUIDUtil; import okhttp3.Request; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.concurrent.atomic.AtomicBoolean; public abstract class AbstractPlayerProvider<T extends IPlayer, DT extends DiscordSRV> implements PlayerProvider<T> { private static final String MOJANG_API_URL = "https://api.mojang.com"; private static final String USERNAME_TO_UUID_URL = MOJANG_API_URL + "/users/profiles/minecraft/%s"; private static final String UUID_TO_PROFILE_URL = MOJANG_API_URL + "/session/minecraft/profile/%s"; private final Map<UUID, T> players = new ConcurrentHashMap<>(); private final List<T> allPlayers = new CopyOnWriteArrayList<>(); protected final DT discordSRV; private final AtomicBoolean anyOffline = new AtomicBoolean(false); public AbstractPlayerProvider(DT discordSRV) { this.discordSRV = discordSRV; } public boolean isAnyOffline() { return anyOffline.get(); } public abstract void subscribe(); protected void addPlayer(UUID uuid, T player, boolean initial) { this.players.put(uuid, player); this.allPlayers.add(player); discordSRV.scheduler().run(() -> discordSRV.eventBus().publish(new PlayerConnectedEvent(player, initial))); if (uuid.getLeastSignificantBits() != 0 /* Not Geyser */ && uuid.version() == 3 /* Offline */) { anyOffline.set(true); } } protected void removePlayer(UUID uuid) { T player = this.players.remove(uuid); if (player != null) { allPlayers.remove(player); discordSRV.scheduler().run(() -> discordSRV.eventBus().publish(new PlayerDisconnectedEvent(player))); } } @Override public final @Nullable T player(@NotNull UUID uuid) { return players.get(uuid); } @Override public final @Nullable T player(@NotNull String username) { for (T value : allPlayers) { if (value.username().equalsIgnoreCase(username)) { return value; } } return null; } @Override public @NotNull Collection<T> allPlayers() { return allPlayers; } @Override public CompletableFuture<UUID> lookupUUIDForUsername(String username) { IPlayer player = player(username); if (player != null) { return CompletableFuture.completedFuture(player.uniqueId()); } Request request = new Request.Builder() .url(String.format(USERNAME_TO_UUID_URL, username)) .get() .build(); return HttpUtil.readJson(discordSRV, request, UUIDResponse.class) .thenApply(response -> UUIDUtil.fromShort(response.id)); } @Override public CompletableFuture<IOfflinePlayer> lookupOfflinePlayer(UUID uuid) { IPlayer player = player(uuid); if (player != null) { return CompletableFuture.completedFuture(player); } Request request = new Request.Builder() .url(String.format(UUID_TO_PROFILE_URL, uuid)) .get() .build(); return HttpUtil.readJson(discordSRV, request, GameProfileResponse.class).thenApply(response -> { SkinInfo skinInfo = null; for (GameProfileResponse.Property property : response.properties) { if (!Textures.KEY.equals(property.name)) { continue; } Textures textures = Textures.getFromBase64(discordSRV, property.value); skinInfo = textures.getSkinInfo(); } return new OfflinePlayer(discordSRV, response.name, uuid, skinInfo); }); } }
5,573
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
PlayerProvider.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/player/provider/PlayerProvider.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.player.provider; import com.discordsrv.api.player.DiscordSRVPlayer; import com.discordsrv.api.player.IPlayerProvider; import com.discordsrv.common.player.IOfflinePlayer; import com.discordsrv.common.player.IPlayer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Collection; import java.util.UUID; import java.util.concurrent.CompletableFuture; public interface PlayerProvider<T extends IPlayer> extends IPlayerProvider { /** * Gets an online player by {@link UUID}. * * @param uuid the uuid of the Player */ @Nullable DiscordSRVPlayer player(@NotNull UUID uuid); /** * Gets an online player by username. * * @param username case-insensitive username for the player */ @Nullable DiscordSRVPlayer player(@NotNull String username); /** * Gets all online players. * @return all players that are currently online */ @NotNull Collection<T> allPlayers(); CompletableFuture<UUID> lookupUUIDForUsername(String username); default CompletableFuture<IOfflinePlayer> lookupOfflinePlayer(String username) { return lookupUUIDForUsername(username).thenCompose(this::lookupOfflinePlayer); } CompletableFuture<IOfflinePlayer> lookupOfflinePlayer(UUID uuid); }
2,180
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ServerPlayerProvider.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/player/provider/ServerPlayerProvider.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.player.provider; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.player.IOfflinePlayer; import com.discordsrv.common.player.IPlayer; import java.util.UUID; import java.util.concurrent.CompletableFuture; public abstract class ServerPlayerProvider<T extends IPlayer, DT extends DiscordSRV> extends AbstractPlayerProvider<T, DT> { public ServerPlayerProvider(DT discordSRV) { super(discordSRV); } @Override public CompletableFuture<UUID> lookupUUIDForUsername(String username) { return lookupOfflinePlayer(username).thenApply(IOfflinePlayer::uniqueId); } @Override public abstract CompletableFuture<IOfflinePlayer> lookupOfflinePlayer(String username); @Override public abstract CompletableFuture<IOfflinePlayer> lookupOfflinePlayer(UUID uuid); }
1,685
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
UUIDResponse.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/player/provider/model/UUIDResponse.java
package com.discordsrv.common.player.provider.model; public class UUIDResponse { public String name; public String id; }
131
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
GameProfileResponse.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/player/provider/model/GameProfileResponse.java
package com.discordsrv.common.player.provider.model; import java.util.List; public class GameProfileResponse { public String id; public String name; public List<Property> properties; public static class Property { public String name; public String value; } }
299
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
SkinInfo.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/player/provider/model/SkinInfo.java
package com.discordsrv.common.player.provider.model; public class SkinInfo { private final String textureId; private final String model; public SkinInfo(String textureId, String model) { this.textureId = textureId; this.model = model; } public String textureId() { return textureId; } public String model() { return model; } }
396
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
Textures.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/player/provider/model/Textures.java
package com.discordsrv.common.player.provider.model; import com.discordsrv.common.DiscordSRV; import java.io.IOException; import java.io.UncheckedIOException; import java.util.Base64; import java.util.Map; public class Textures { public static String KEY = "textures"; public String profileId; public String profileName; public boolean signatureRequired; public Map<String, Texture> textures; public static class Texture { public String url; public Map<String, Object> metadata; } public SkinInfo getSkinInfo() { Textures.Texture texture = textures.get("SKIN"); if (texture == null) { return null; } String url = texture.url; Map<String, Object> metadata = texture.metadata; String textureId = url.substring(url.lastIndexOf("/") + 1); return new SkinInfo(textureId, metadata != null ? (String) metadata.get("model") : null); } public static Textures getFromBase64(DiscordSRV discordSRV, String base64) { byte[] bytes = Base64.getDecoder().decode(base64); Textures textures; try { textures = discordSRV.json().readValue(bytes, Textures.class); } catch (IOException e) { throw new UncheckedIOException(e); } return textures; } }
1,336
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
PasteService.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/paste/PasteService.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.paste; public interface PasteService { Paste uploadFile(byte[] fileContent) throws Throwable; }
963
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
Paste.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/paste/Paste.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.paste; public class Paste { private final String id; private final String url; private final byte[] decryptionKey; public Paste(String id, String url, byte[] decryptionKey) { this.id = id; this.url = url; this.decryptionKey = decryptionKey; } public String id() { return id; } public String url() { return url; } public byte[] decryptionKey() { return decryptionKey; } public Paste withDecryptionKey(byte[] decryptionKey) { return new Paste(id, url, decryptionKey); } }
1,445
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
AESEncryptedPasteService.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/paste/service/AESEncryptedPasteService.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.paste.service; import com.discordsrv.common.paste.Paste; import com.discordsrv.common.paste.PasteService; import org.apache.commons.lang3.ArrayUtils; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import java.security.GeneralSecurityException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.Base64; public class AESEncryptedPasteService implements PasteService { private final PasteService service; private final int keySize; private final SecureRandom RANDOM = new SecureRandom(); public AESEncryptedPasteService(PasteService service, int keySize) { this.service = service; this.keySize = keySize; } @Override public Paste uploadFile(byte[] fileContent) throws Throwable { byte[] iv = new byte[16]; RANDOM.nextBytes(iv); SecretKey secretKey = generateKey(); byte[] encrypted = encrypt(secretKey, fileContent, iv); Paste paste = service.uploadFile(Base64.getEncoder().encode(ArrayUtils.addAll(iv, encrypted))); return paste.withDecryptionKey(secretKey.getEncoded()); } private SecretKey generateKey() throws NoSuchAlgorithmException { KeyGenerator keyGenerator = KeyGenerator.getInstance("AES"); keyGenerator.init(keySize); return keyGenerator.generateKey(); } private byte[] encrypt(SecretKey key, byte[] content, byte[] iv) throws GeneralSecurityException { Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING"); cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(iv)); return cipher.doFinal(content); } }
2,591
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
BytebinPasteService.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/paste/service/BytebinPasteService.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.paste.service; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.paste.Paste; import com.discordsrv.common.paste.PasteService; import com.fasterxml.jackson.databind.JsonNode; import okhttp3.*; public class BytebinPasteService implements PasteService { private final DiscordSRV discordSRV; private final String bytebinUrl; public BytebinPasteService(DiscordSRV discordSRV, String bytebinUrl) { this.discordSRV = discordSRV; this.bytebinUrl = bytebinUrl; } @Override public Paste uploadFile(byte[] fileContent) throws Throwable { Request request = new Request.Builder() .url(bytebinUrl + "/post") //.header("Content-Encoding", "gzip") .post(RequestBody.create(fileContent, MediaType.get("application/octet-stream"))) .build(); try (Response response = discordSRV.httpClient().newCall(request).execute()) { ResponseBody responseBody = response.body(); if (responseBody == null) { return null; } JsonNode responseNode = discordSRV.json().readTree(responseBody.string()); String key = responseNode.get("key").asText(); return new Paste(key, bytebinUrl + "/" + key, null); } } }
2,180
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
BinPasteService.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/paste/service/BinPasteService.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.paste.service; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.paste.Paste; import com.discordsrv.common.paste.PasteService; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; import okhttp3.*; import java.io.IOException; import java.nio.charset.StandardCharsets; import java.util.Base64; public class BinPasteService implements PasteService { private final DiscordSRV discordSRV; private final String binUrl; public BinPasteService(DiscordSRV discordSRV, String binUrl) { this.discordSRV = discordSRV; this.binUrl = binUrl; } @Override public Paste uploadFile(byte[] fileContent) throws IOException { ObjectNode json = discordSRV.json().createObjectNode(); ArrayNode files = json.putArray("files"); ObjectNode file = files.addObject(); // "File name must be divisible by 16" not that I care about the file name... file.put("name", new String(Base64.getEncoder().encode(new byte[16]))); file.put("content", new String(fileContent, StandardCharsets.UTF_8)); Request request = new Request.Builder() .url(binUrl + "/v1/post") .post(RequestBody.create(json.toString(), MediaType.get("application/json"))) .build(); try (Response response = discordSRV.httpClient().newCall(request).execute()) { ResponseBody responseBody = response.body(); if (responseBody == null) { return null; } JsonNode responseNode = discordSRV.json().readTree(responseBody.string()); String binId = responseNode.get("bin").asText(); return new Paste(binId, binUrl + "/v1/" + binId + ".json", null); } } }
2,725
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
EventListenerImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/event/bus/EventListenerImpl.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.event.bus; import com.discordsrv.api.event.bus.EventListener; import com.discordsrv.api.event.bus.EventPriority; import com.discordsrv.api.event.bus.Subscribe; import org.jetbrains.annotations.NotNull; import java.lang.reflect.Method; public class EventListenerImpl implements EventListener { private final Object listener; private final Class<?> listenerClass; private final Subscribe annotation; private final Class<?> eventClass; private final Method method; public EventListenerImpl(Object listener, Class<?> listenerClass, Subscribe annotation, Class<?> eventClass, Method method) { this.listener = listener; this.listenerClass = listenerClass; this.annotation = annotation; this.eventClass = eventClass; this.method = method; } public boolean isIgnoringCancelled() { return annotation.ignoreCancelled(); } public EventPriority priority() { return annotation.priority(); } public Object listener() { return listener; } public Class<?> eventClass() { return eventClass; } public Method method() { return method; } @Override public @NotNull String className() { return listenerClass.getName(); } @Override public @NotNull String methodName() { return method.getName(); } @Override public String toString() { return "EventListenerImpl{" + className() + "#" + methodName() + "}"; } }
2,366
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
EventBusImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/event/bus/EventBusImpl.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.event.bus; import com.discordsrv.api.event.bus.EventBus; import com.discordsrv.api.event.bus.EventListener; import com.discordsrv.api.event.bus.EventPriority; import com.discordsrv.api.event.bus.Subscribe; import com.discordsrv.api.event.bus.internal.EventStateHolder; import com.discordsrv.api.event.events.Cancellable; import com.discordsrv.api.event.events.Event; import com.discordsrv.api.event.events.Processable; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.debug.DebugGenerateEvent; import com.discordsrv.common.debug.file.TextDebugFile; import com.discordsrv.common.exception.InvalidListenerMethodException; import com.discordsrv.common.logging.Logger; import com.discordsrv.common.logging.NamedLogger; import com.discordsrv.common.testing.TestHelper; import net.dv8tion.jda.api.events.GenericEvent; import org.apache.commons.lang3.tuple.Pair; import org.jetbrains.annotations.NotNull; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Function; import java.util.stream.Collectors; import static com.discordsrv.common.exception.util.ExceptionUtil.minifyException; public class EventBusImpl implements EventBus { private static final List<Pair<Function<Object, Boolean>, ThreadLocal<EventListener>>> STATES = Arrays.asList( Pair.of(event -> event instanceof Cancellable && ((Cancellable) event).isCancelled(), EventStateHolder.CANCELLED), Pair.of(event -> event instanceof Processable && ((Processable) event).isProcessed(), EventStateHolder.PROCESSED) ); private final Map<Object, List<EventListenerImpl>> listeners = new ConcurrentHashMap<>(); private final List<EventListenerImpl> allListeners = new CopyOnWriteArrayList<>(); private final Logger logger; public EventBusImpl(DiscordSRV discordSRV) { this.logger = new NamedLogger(discordSRV, "EVENT_BUS"); subscribe(this); } public void shutdown() { listeners.clear(); allListeners.clear(); } @Override public void subscribe(@NotNull Object eventListener) { if (listeners.containsKey(eventListener)) { throw new IllegalArgumentException("Listener is already registered"); } Class<?> listenerClass = eventListener.getClass(); List<Throwable> suppressedMethods = new ArrayList<>(); List<EventListenerImpl> methods = new ArrayList<>(); Class<?> currentClass = listenerClass; do { for (Method method : currentClass.getDeclaredMethods()) { checkMethod(eventListener, listenerClass, method, suppressedMethods, methods); } } while ((currentClass = currentClass.getSuperclass()) != null); if (methods.isEmpty() || !suppressedMethods.isEmpty()) { IllegalArgumentException exception = new IllegalArgumentException(listenerClass.getName() + " doesn't have valid listener methods that are annotated with " + Subscribe.class.getName()); suppressedMethods.forEach(exception::addSuppressed); throw exception; } listeners.put(eventListener, methods); allListeners.addAll(methods); logger.debug("Listener " + eventListener.getClass().getName() + " subscribed"); } private void checkMethod(Object eventListener, Class<?> listenerClass, Method method, List<Throwable> suppressedMethods, List<EventListenerImpl> methods) { Subscribe annotation = method.getAnnotation(Subscribe.class); if (annotation == null) { return; } Class<?>[] parameterTypes = method.getParameterTypes(); int parameters = parameterTypes.length; List<Throwable> suppressed = new ArrayList<>(); if (Void.class.isAssignableFrom(method.getReturnType())) { suppressed.add(createReasonException("Must return void")); } int modifiers = method.getModifiers(); if (Modifier.isAbstract(modifiers)) { suppressed.add(createReasonException("Cannot be abstract")); } if (Modifier.isStatic(modifiers)) { suppressed.add(createReasonException("Cannot be static")); } if (!Modifier.isPublic(modifiers)) { suppressed.add(createReasonException("Needs to be public")); } if (parameters != 1) { suppressed.add(createReasonException("Must have exactly 1 parameter")); } Class<?> firstParameter = null; if (parameters > 0) { firstParameter = parameterTypes[0]; if (!Event.class.isAssignableFrom(firstParameter) && !GenericEvent.class.isAssignableFrom(firstParameter)) { suppressed.add(createReasonException("#1 argument must be a DiscordSRV or JDA event")); } } if (!suppressed.isEmpty()) { Exception methodException = new InvalidListenerMethodException("Method " + method.getName() + "(" + (parameters > 0 ? Arrays.stream(method.getParameterTypes()) .map(Class::getName).collect(Collectors.joining(", ")) : "") + ") is invalid"); suppressed.forEach(methodException::addSuppressed); suppressedMethods.add(minifyException(methodException)); return; } EventListenerImpl listener = new EventListenerImpl(eventListener, listenerClass, annotation, firstParameter, method); methods.add(listener); } private Throwable createReasonException(String message) { InvalidListenerMethodException exception = new InvalidListenerMethodException(message); return minifyException(exception); } @Override public void unsubscribe(@NotNull Object eventListener) { List<EventListenerImpl> removed = listeners.remove(eventListener); if (removed != null) { allListeners.removeAll(removed); logger.debug("Listener " + eventListener.getClass().getName() + " unsubscribed"); } } @Override public void publish(@NotNull Event event) { publishEvent(event); } @Override public void publish(@NotNull GenericEvent event) { publishEvent(event); } private void publishEvent(Object event) { List<Boolean> states = new ArrayList<>(STATES.size()); for (Pair<Function<Object, Boolean>, ThreadLocal<EventListener>> entry : STATES) { if (entry.getKey().apply(event)) { // If the state is already set before listeners, we mark it as being changed by a 'unknown' event listener states.add(true); entry.getValue().set(EventStateHolder.UNKNOWN_LISTENER); continue; } states.add(false); } Class<?> eventClass = event.getClass(); for (EventPriority priority : EventPriority.values()) { for (EventListenerImpl eventListener : allListeners) { if (eventListener.isIgnoringCancelled() && event instanceof Cancellable && ((Cancellable) event).isCancelled()) { continue; } if (eventListener.priority() != priority) { continue; } if (!eventListener.eventClass().isAssignableFrom(eventClass)) { continue; } long startTime = System.currentTimeMillis(); try { Object listener = eventListener.listener(); eventListener.method().invoke(listener, event); } catch (IllegalAccessException e) { logger.error("Failed to access listener method: " + eventListener.methodName() + " in " + eventListener.className(), e); TestHelper.fail(e); } catch (InvocationTargetException e) { String eventClassName = eventClass.getName(); Throwable cause = e.getCause(); if (eventListener.className().startsWith("com.discordsrv")) { logger.error("Failed to pass " + eventClassName + " to " + eventListener, cause); } else { e.getCause().printStackTrace(); } TestHelper.fail(cause); } long timeTaken = System.currentTimeMillis() - startTime; logger.trace(eventListener + " took " + timeTaken + "ms to execute"); for (int index = 0; index < STATES.size(); index++) { Pair<Function<Object, Boolean>, ThreadLocal<EventListener>> state = STATES.get(index); boolean current = states.get(index); boolean updated = state.getKey().apply(event); states.set(index, updated); ThreadLocal<EventListener> stateHolder = state.getValue(); if (current != updated) { if (updated) { stateHolder.set(eventListener); } else { stateHolder.remove(); } } } } } // Clear the states for (Pair<Function<Object, Boolean>, ThreadLocal<EventListener>> state : STATES) { state.getValue().remove(); } } @Subscribe public void onDebugGenerate(DebugGenerateEvent event) { StringBuilder builder = new StringBuilder("Registered listeners (" + listeners.size() + "/" + allListeners.size() + "):\n"); for (Map.Entry<Object, List<EventListenerImpl>> entry : listeners.entrySet()) { Object listener = entry.getKey(); List<EventListenerImpl> eventListeners = entry.getValue(); builder.append('\n') .append(listener) .append(" (") .append(listener.getClass().getName()) .append(") [") .append(eventListeners.size()) .append("]\n"); for (EventListenerImpl eventListener : eventListeners) { builder.append(" - ") .append(eventListener.eventClass().getName()) .append(": ") .append(eventListener.methodName()) .append(" @ ") .append(eventListener.priority().name()) .append('\n'); } } event.addFile(new TextDebugFile("event-bus.txt", builder)); } }
11,848
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordMessageContextInteractionEventImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/event/events/discord/interaction/command/DiscordMessageContextInteractionEventImpl.java
package com.discordsrv.common.event.events.discord.interaction.command; import com.discordsrv.api.discord.entity.DiscordUser; import com.discordsrv.api.discord.entity.channel.DiscordMessageChannel; import com.discordsrv.api.discord.entity.guild.DiscordGuildMember; import com.discordsrv.api.discord.entity.interaction.DiscordInteractionHook; import com.discordsrv.api.discord.entity.interaction.component.ComponentIdentifier; import com.discordsrv.api.discord.entity.message.SendableDiscordMessage; import com.discordsrv.api.event.events.discord.interaction.command.DiscordMessageContextInteractionEvent; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.discord.api.entity.component.DiscordInteractionHookImpl; import com.discordsrv.common.discord.api.entity.message.util.SendableDiscordMessageUtil; import net.dv8tion.jda.api.events.interaction.command.MessageContextInteractionEvent; import java.util.concurrent.CompletableFuture; public class DiscordMessageContextInteractionEventImpl extends DiscordMessageContextInteractionEvent { private final DiscordSRV discordSRV; public DiscordMessageContextInteractionEventImpl( DiscordSRV discordSRV, MessageContextInteractionEvent jdaEvent, ComponentIdentifier identifier, DiscordUser user, DiscordGuildMember member, DiscordMessageChannel channel, DiscordInteractionHook interaction) { super(jdaEvent, identifier, user, member, channel, interaction); this.discordSRV = discordSRV; } @Override public CompletableFuture<DiscordInteractionHook> reply(SendableDiscordMessage message, boolean ephemeral) { return discordSRV.discordAPI().mapExceptions( () -> jdaEvent.reply(SendableDiscordMessageUtil.toJDASend(message)).setEphemeral(ephemeral).submit() .thenApply(ih -> new DiscordInteractionHookImpl(discordSRV, ih)) ); } }
1,962
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordChatInputInteractionEventImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/event/events/discord/interaction/command/DiscordChatInputInteractionEventImpl.java
package com.discordsrv.common.event.events.discord.interaction.command; import com.discordsrv.api.discord.entity.DiscordUser; import com.discordsrv.api.discord.entity.channel.DiscordMessageChannel; import com.discordsrv.api.discord.entity.guild.DiscordGuildMember; import com.discordsrv.api.discord.entity.interaction.DiscordInteractionHook; import com.discordsrv.api.discord.entity.interaction.component.ComponentIdentifier; import com.discordsrv.api.discord.entity.message.SendableDiscordMessage; import com.discordsrv.api.event.events.discord.interaction.command.DiscordChatInputInteractionEvent; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.discord.api.entity.component.DiscordInteractionHookImpl; import com.discordsrv.common.discord.api.entity.message.util.SendableDiscordMessageUtil; import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent; import java.util.concurrent.CompletableFuture; public class DiscordChatInputInteractionEventImpl extends DiscordChatInputInteractionEvent { private final DiscordSRV discordSRV; public DiscordChatInputInteractionEventImpl( DiscordSRV discordSRV, SlashCommandInteractionEvent jdaEvent, ComponentIdentifier identifier, DiscordUser user, DiscordGuildMember member, DiscordMessageChannel channel, DiscordInteractionHook interaction) { super(jdaEvent, identifier, user, member, channel, interaction); this.discordSRV = discordSRV; } @Override public CompletableFuture<DiscordInteractionHook> reply(SendableDiscordMessage message, boolean ephemeral) { return discordSRV.discordAPI().mapExceptions( () -> jdaEvent.reply(SendableDiscordMessageUtil.toJDASend(message)).setEphemeral(ephemeral).submit() .thenApply(ih -> new DiscordInteractionHookImpl(discordSRV, ih)) ); } }
1,938
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordUserContextInteractionEventImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/event/events/discord/interaction/command/DiscordUserContextInteractionEventImpl.java
package com.discordsrv.common.event.events.discord.interaction.command; import com.discordsrv.api.discord.entity.DiscordUser; import com.discordsrv.api.discord.entity.channel.DiscordMessageChannel; import com.discordsrv.api.discord.entity.guild.DiscordGuildMember; import com.discordsrv.api.discord.entity.interaction.DiscordInteractionHook; import com.discordsrv.api.discord.entity.interaction.component.ComponentIdentifier; import com.discordsrv.api.discord.entity.message.SendableDiscordMessage; import com.discordsrv.api.event.events.discord.interaction.command.DiscordUserContextInteractionEvent; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.discord.api.entity.component.DiscordInteractionHookImpl; import com.discordsrv.common.discord.api.entity.message.util.SendableDiscordMessageUtil; import net.dv8tion.jda.api.events.interaction.command.UserContextInteractionEvent; import java.util.concurrent.CompletableFuture; public class DiscordUserContextInteractionEventImpl extends DiscordUserContextInteractionEvent { private final DiscordSRV discordSRV; public DiscordUserContextInteractionEventImpl( DiscordSRV discordSRV, UserContextInteractionEvent jdaEvent, ComponentIdentifier identifier, DiscordUser user, DiscordGuildMember member, DiscordMessageChannel channel, DiscordInteractionHook interaction) { super(jdaEvent, identifier, user, member, channel, interaction); this.discordSRV = discordSRV; } @Override public CompletableFuture<DiscordInteractionHook> reply(SendableDiscordMessage message, boolean ephemeral) { return discordSRV.discordAPI().mapExceptions( () -> jdaEvent.reply(SendableDiscordMessageUtil.toJDASend(message)).setEphemeral(ephemeral).submit() .thenApply(ih -> new DiscordInteractionHookImpl(discordSRV, ih)) ); } }
1,944
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
PlayerDisconnectedEvent.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/event/events/player/PlayerDisconnectedEvent.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.event.events.player; import com.discordsrv.api.event.events.Event; import com.discordsrv.common.player.IPlayer; public class PlayerDisconnectedEvent implements Event { private final IPlayer player; public PlayerDisconnectedEvent(IPlayer player) { this.player = player; } public IPlayer player() { return player; } }
1,217
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
PlayerConnectedEvent.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/event/events/player/PlayerConnectedEvent.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.event.events.player; import com.discordsrv.api.event.events.Event; import com.discordsrv.common.player.IPlayer; public class PlayerConnectedEvent implements Event { private final IPlayer player; private final boolean joinedBeforeInitialization; public PlayerConnectedEvent(IPlayer player, boolean joinedBeforeInitialization) { this.player = player; this.joinedBeforeInitialization = joinedBeforeInitialization; } public IPlayer player() { return player; } /** * If this player joined before DiscordSRV initialized. * @return {@code true} if the player joined before DiscordSRV enabled */ public boolean joinedBeforeInitialization() { return joinedBeforeInitialization; } }
1,622
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
EventUtil.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/event/util/EventUtil.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package com.discordsrv.common.event.util; import com.discordsrv.api.event.bus.EventListener; import com.discordsrv.api.event.events.Cancellable; import com.discordsrv.api.event.events.Processable; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.logging.Logger; public final class EventUtil { private EventUtil() {} public static boolean checkProcessor(DiscordSRV discordSRV, Processable event, Logger logger) { if (!event.isProcessed()) { return false; } EventListener processor = event.whoProcessed(); String whoProcessed = processor != null ? processor.className() : "Unknown"; if (!whoProcessed.startsWith("com.discordsrv")) { logger.debug(event + " was handled by non-DiscordSRV handler: " + whoProcessed); } return true; } public static boolean checkCancellation(DiscordSRV discordSRV, Cancellable event, Logger logger) { if (!event.isCancelled()) { return false; } EventListener canceller = event.whoCancelled(); String whoCancelled = canceller != null ? canceller.className() : "Unknown"; logger.debug(event + " was cancelled by " + whoCancelled); return true; } }
2,091
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
package-info.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/api/src/main/java/org/slf4j/impl/package-info.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ /** * DiscordSRV's own implementation of SLF4J (relocated during runtime) that forwards log messages to the server's logger. */ package org.slf4j.impl;
984
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordSRVLoggerFactory.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/api/src/main/java/org/slf4j/impl/DiscordSRVLoggerFactory.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package org.slf4j.impl; import com.discordsrv.common.logging.adapter.DependencyLoggerAdapter; import org.slf4j.ILoggerFactory; import org.slf4j.Logger; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; public class DiscordSRVLoggerFactory implements ILoggerFactory { private final ConcurrentMap<String, DependencyLoggerAdapter> loggerMap = new ConcurrentHashMap<>(); @Override public Logger getLogger(String s) { return loggerMap.computeIfAbsent(s, DependencyLoggerAdapter::new); } }
1,383
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
StaticLoggerBinder.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/api/src/main/java/org/slf4j/impl/StaticLoggerBinder.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package org.slf4j.impl; import org.slf4j.ILoggerFactory; import org.slf4j.spi.LoggerFactoryBinder; @SuppressWarnings("unused") public class StaticLoggerBinder implements LoggerFactoryBinder { private static final StaticLoggerBinder SINGLETON = new StaticLoggerBinder(); public static StaticLoggerBinder getSingleton() { return SINGLETON; } // to avoid constant folding by the compiler, this field must *not* be final public static String REQUESTED_API_VERSION = "1.6.99"; // !final private static final String loggerFactoryClassStr = DiscordSRVLoggerFactory.class.getName(); private final ILoggerFactory loggerFactory; private StaticLoggerBinder() { loggerFactory = new DiscordSRVLoggerFactory(); } public ILoggerFactory getLoggerFactory() { return loggerFactory; } public String getLoggerFactoryClassStr() { return loggerFactoryClassStr; } }
1,767
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
StaticMDCBinder.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/api/src/main/java/org/slf4j/impl/StaticMDCBinder.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package org.slf4j.impl; import org.slf4j.helpers.BasicMDCAdapter; import org.slf4j.spi.MDCAdapter; @SuppressWarnings("unused") public class StaticMDCBinder { public static final StaticMDCBinder SINGLETON = new StaticMDCBinder(); private StaticMDCBinder() {} public static StaticMDCBinder getSingleton() { return SINGLETON; } public MDCAdapter getMDCA() { return new BasicMDCAdapter(); } public String getMDCAdapterClassStr() { return BasicMDCAdapter.class.getName(); } }
1,364
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
StaticMarkerBinder.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/api/src/main/java/org/slf4j/impl/StaticMarkerBinder.java
/* * This file is part of DiscordSRV, licensed under the GPLv3 License * Copyright (c) 2016-2023 Austin "Scarsz" Shapiro, Henri "Vankka" Schubin and DiscordSRV contributors * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <https://www.gnu.org/licenses/>. */ package org.slf4j.impl; import org.slf4j.IMarkerFactory; import org.slf4j.helpers.BasicMarkerFactory; import org.slf4j.spi.MarkerFactoryBinder; @SuppressWarnings("unused") public class StaticMarkerBinder implements MarkerFactoryBinder { public static final StaticMarkerBinder SINGLETON = new StaticMarkerBinder(); final IMarkerFactory markerFactory = new BasicMarkerFactory(); private StaticMarkerBinder() {} public static StaticMarkerBinder getSingleton() { return SINGLETON; } public IMarkerFactory getMarkerFactory() { return markerFactory; } public String getMarkerFactoryClassStr() { return BasicMarkerFactory.class.getName(); } }
1,535
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z