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
VelocityPlayerProvider.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/velocity/src/main/java/com/discordsrv/velocity/player/VelocityPlayerProvider.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.velocity.player; import com.discordsrv.common.player.provider.AbstractPlayerProvider; import com.discordsrv.velocity.VelocityDiscordSRV; import com.velocitypowered.api.event.PostOrder; import com.velocitypowered.api.event.Subscribe; import com.velocitypowered.api.event.connection.DisconnectEvent; import com.velocitypowered.api.event.connection.PostLoginEvent; import com.velocitypowered.api.proxy.Player; public class VelocityPlayerProvider extends AbstractPlayerProvider<VelocityPlayer, VelocityDiscordSRV> { public VelocityPlayerProvider(VelocityDiscordSRV discordSRV) { super(discordSRV); } @Override public void subscribe() { discordSRV.proxy().getEventManager().register(discordSRV.plugin(), this); // Add players that are already connected for (Player player : discordSRV.proxy().getAllPlayers()) { addPlayer(player, true); } } @Subscribe(order = PostOrder.FIRST) public void onPostLogin(PostLoginEvent event) { addPlayer(event.getPlayer(), false); } private void addPlayer(Player player, boolean initial) { addPlayer(player.getUniqueId(), new VelocityPlayer(discordSRV, player), initial); } @Subscribe(order = PostOrder.LAST) public void onDisconnect(DisconnectEvent event) { removePlayer(event.getPlayer().getUniqueId()); } public VelocityPlayer player(Player player) { VelocityPlayer srvPlayer = player(player.getUniqueId()); if (srvPlayer == null) { throw new IllegalStateException("Player not available"); } return srvPlayer; } }
2,485
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
FullBootExtension.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/test/java/com/discordsrv/common/FullBootExtension.java
package com.discordsrv.common; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assumptions; import org.junit.jupiter.api.extension.BeforeAllCallback; import org.junit.jupiter.api.extension.ExtensionContext; public class FullBootExtension implements BeforeAllCallback, ExtensionContext.Store.CloseableResource { public static String BOT_TOKEN = System.getenv("DISCORDSRV_AUTOTEST_BOT_TOKEN"); public static String TEST_CHANNEL_ID = System.getenv("DISCORDSRV_AUTOTEST_CHANNEL_ID"); public boolean started = false; @Override public void beforeAll(ExtensionContext context) { Assumptions.assumeTrue(BOT_TOKEN != null, "Automated testing bot token"); Assumptions.assumeTrue(TEST_CHANNEL_ID != null, "Automated testing channel id"); if (started) return; started = true; context.getRoot().getStore(ExtensionContext.Namespace.GLOBAL).put("Full boot extension", this); try { System.out.println("Enabling..."); MockDiscordSRV.INSTANCE.enable(); System.out.println("Enabled successfully"); } catch (Throwable e) { Assertions.fail(e); } } @Override public void close() { System.out.println("Disabling..."); MockDiscordSRV.INSTANCE.disable(); System.out.println("Disabled successfully"); } }
1,381
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
MockDiscordSRV.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/test/java/com/discordsrv/common/MockDiscordSRV.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; import com.discordsrv.api.channel.GameChannel; import com.discordsrv.common.bootstrap.IBootstrap; import com.discordsrv.common.bootstrap.LifecycleManager; import com.discordsrv.common.command.game.handler.ICommandHandler; import com.discordsrv.common.config.configurate.manager.ConnectionConfigManager; import com.discordsrv.common.config.configurate.manager.MainConfigManager; import com.discordsrv.common.config.configurate.manager.MessagesConfigManager; import com.discordsrv.common.config.configurate.manager.abstraction.ServerConfigManager; import com.discordsrv.common.config.connection.ConnectionConfig; import com.discordsrv.common.config.main.MainConfig; import com.discordsrv.common.config.main.PluginIntegrationConfig; import com.discordsrv.common.config.main.channels.base.ChannelConfig; import com.discordsrv.common.config.main.generic.DestinationConfig; import com.discordsrv.common.config.main.generic.ThreadConfig; import com.discordsrv.common.config.messages.MessagesConfig; import com.discordsrv.common.console.Console; import com.discordsrv.common.debug.data.OnlineMode; import com.discordsrv.common.debug.data.VersionInfo; import com.discordsrv.common.exception.ConfigException; import com.discordsrv.common.logging.Logger; import com.discordsrv.common.logging.backend.impl.JavaLoggerImpl; import com.discordsrv.common.messageforwarding.game.minecrafttodiscord.MinecraftToDiscordChatModule; import com.discordsrv.common.player.IPlayer; import com.discordsrv.common.player.provider.AbstractPlayerProvider; import com.discordsrv.common.plugin.PluginManager; import com.discordsrv.common.scheduler.Scheduler; import com.discordsrv.common.scheduler.StandardScheduler; import com.discordsrv.common.storage.impl.MemoryStorage; import dev.vankka.dependencydownload.classpath.ClasspathAppender; import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.util.List; @SuppressWarnings("ConstantConditions") public class MockDiscordSRV extends AbstractDiscordSRV<IBootstrap, MainConfig, ConnectionConfig, MessagesConfig> { public static final MockDiscordSRV INSTANCE = new MockDiscordSRV(); public boolean configLoaded = false; public boolean connectionConfigLoaded = false; public boolean messagesConfigLoaded = false; public boolean playerProviderSubscribed = false; private final Scheduler scheduler = new StandardScheduler(this); private Path path; public static void main(String[] args) { new MockDiscordSRV(); } public MockDiscordSRV() { super(new IBootstrap() { @Override public Logger logger() { return JavaLoggerImpl.getRoot(); } @Override public ClasspathAppender classpathAppender() { return null; } @Override public ClassLoader classLoader() { return MockDiscordSRV.class.getClassLoader(); } @Override public LifecycleManager lifecycleManager() { return null; } @Override public Path dataDirectory() { return null; } }); load(); versionInfo = new VersionInfo("JUnit", "JUnit", "JUnit", "JUnit"); } @Override public Path dataDirectory() { if (this.path == null) { Path path = Paths.get("/tmp/discordsrv-test"); try { path = Files.createTempDirectory("discordsrv-test"); } catch (IOException ignored) {} this.path = path; } return path; } @Override public Scheduler scheduler() { return scheduler; } @Override public Console console() { return null; } @Override public PluginManager pluginManager() { return null; } @Override public OnlineMode onlineMode() { return OnlineMode.ONLINE; } @Override public ICommandHandler commandHandler() { return null; } @Override public @NotNull AbstractPlayerProvider<?, ?> playerProvider() { return new AbstractPlayerProvider<IPlayer, DiscordSRV>(this) { @Override public void subscribe() { playerProviderSubscribed = true; } }; } @Override public ConnectionConfigManager<ConnectionConfig> connectionConfigManager() { return new ConnectionConfigManager<ConnectionConfig>(this) { @Override public ConnectionConfig createConfiguration() { return connectionConfig(); } @Override public void load() { connectionConfigLoaded = true; } }; } @Override public ConnectionConfig connectionConfig() { ConnectionConfig config = new ConnectionConfig(); config.bot.token = FullBootExtension.BOT_TOKEN; config.storage.backend = MemoryStorage.IDENTIFIER; config.minecraftAuth.allow = false; config.update.firstPartyNotification = false; config.update.security.enabled = false; config.update.github.enabled = false; return config; } @Override public MainConfigManager<MainConfig> configManager() { return new ServerConfigManager<MainConfig>(this) { @Override public MainConfig createConfiguration() { return config(); } @Override public void load() { configLoaded = true; } }; } @Override protected void enable() throws Throwable { super.enable(); registerModule(MinecraftToDiscordChatModule::new); } @Override public MainConfig config() { MainConfig config = new MainConfig() { @Override public PluginIntegrationConfig integrations() { return null; } }; if (StringUtils.isNotEmpty(FullBootExtension.TEST_CHANNEL_ID)) { ChannelConfig global = (ChannelConfig) config.channels.get(GameChannel.DEFAULT_NAME); DestinationConfig destination = global.destination = new DestinationConfig(); long channelId = Long.parseLong(FullBootExtension.TEST_CHANNEL_ID); List<Long> channelIds = destination.channelIds; channelIds.clear(); channelIds.add(channelId); List<ThreadConfig> threadConfigs = destination.threads; threadConfigs.clear(); ThreadConfig thread = new ThreadConfig(); thread.channelId = channelId; threadConfigs.add(thread); } return config; } @Override public MessagesConfigManager<MessagesConfig> messagesConfigManager() { return new MessagesConfigManager<MessagesConfig>(null) { @Override public MessagesConfig createConfiguration() { return null; } @Override public void load() throws ConfigException { messagesConfigLoaded = true; } }; } }
8,190
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
PlaceholderServiceTest.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/test/java/com/discordsrv/common/placeholder/PlaceholderServiceTest.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.placeholder; import com.discordsrv.api.placeholder.PlaceholderService; import com.discordsrv.api.placeholder.annotation.Placeholder; import com.discordsrv.api.placeholder.annotation.PlaceholderPrefix; import com.discordsrv.common.MockDiscordSRV; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertEquals; public class PlaceholderServiceTest { private final PlaceholderService service = MockDiscordSRV.INSTANCE.placeholderService(); @Test public void staticFieldTest() { assertEquals("a", service.replacePlaceholders("%static_field%", PlaceholderContext.class)); } @Test public void staticMethodTest() { assertEquals("b", service.replacePlaceholders("%static_method%", PlaceholderContext.class)); } @Test public void objectFieldTest() { assertEquals("c", service.replacePlaceholders("%object_field%", new PlaceholderContext())); } @Test public void objectMethodTest() { assertEquals("d", service.replacePlaceholders("%object_method%", new PlaceholderContext())); } @Test public void staticMethodWithContextTest() { assertEquals("e", service.replacePlaceholders("%static_method_with_context%", PlaceholderContext.class, "e")); } @Test public void orPrimaryTest() { assertEquals("a", service.replacePlaceholders("%static_field|static_method%", PlaceholderContext.class)); } @Test public void orSecondaryTest() { assertEquals("b", service.replacePlaceholders("%invalid|static_method%", PlaceholderContext.class)); } @Test public void orEmptyTest() { assertEquals("b", service.replacePlaceholders("%empty|static_method%", PlaceholderContext.class)); } @Test public void prefixFailTest() { assertEquals("%placeholder%", service.replacePlaceholders("%placeholder%", PrefixContext.class)); } @Test public void prefixTest() { assertEquals("value", service.replacePlaceholders("%prefix_placeholder%", PrefixContext.class)); } @Test public void prefixInheritFailTest() { assertEquals("%prefix_noprefix%", service.replacePlaceholders("%prefix_noprefix%", PrefixInheritanceContext.class)); } @Test public void prefixInheritTest() { assertEquals("value", service.replacePlaceholders("%noprefix%", PrefixInheritanceContext.class)); } public static class PlaceholderContext { @Placeholder("static_field") public static String STATIC_FIELD = "a"; @Placeholder("static_method") public static String staticMethod() { return "b"; } @Placeholder("empty") public static String EMPTY = ""; @Placeholder("object_field") public String localField = "c"; @Placeholder("object_method") public String objectMethod() { return "d"; } @Placeholder("static_method_with_context") public static String objectMethodWithContext(String output) { return output; } } @PlaceholderPrefix("prefix_") public static class PrefixContext { @Placeholder("placeholder") public static String placeholder = "value"; } public static class PrefixInheritanceContext extends PrefixContext { @Placeholder("noprefix") public static String noPrefix = "value"; } }
4,289
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
RequirementParserTest.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/test/java/com/discordsrv/common/linking/requirement/parser/RequirementParserTest.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.linking.requirement.parser; import com.discordsrv.common.linking.requirelinking.requirement.Requirement; import com.discordsrv.common.linking.requirelinking.requirement.parser.RequirementParser; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.function.Executable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.UUID; import java.util.concurrent.CompletableFuture; import static org.junit.jupiter.api.Assertions.*; public class RequirementParserTest { private final RequirementParser requirementParser = RequirementParser.getInstance(); private final List<Requirement<?>> requirements = Arrays.asList( new Requirement<Boolean>() { @Override public String name() { return "F"; } @Override public Boolean parse(String input) { return Boolean.parseBoolean(input); } @Override public CompletableFuture<Boolean> isMet(Boolean value, UUID player, long userId) { return CompletableFuture.completedFuture(value); } }, new Requirement<Object>() { @Override public String name() { return "AlwaysError"; } @Override public Object parse(String input) { return null; } @Override public CompletableFuture<Boolean> isMet(Object value, UUID player, long userId) { return null; } } ); private boolean parse(String input) { return requirementParser.parse(input, requirements, new ArrayList<>()).apply(null, 0L).join(); } @Test public void differentCase() { assertFalse(parse("f(false) || F(false)")); } @Test public void orFail() { assertFalse(parse("F(false) || F(false)")); } @Test public void orPass() { assertTrue(parse("F(true) || F(false)")); } @Test public void andFail() { assertFalse(parse("F(true) && F(false)")); } @Test public void andPass() { assertTrue(parse("F(true) && F(true)")); } @Test public void complexFail() { assertFalse(parse("F(true) && (F(false) && F(true))")); } @Test public void complexPass() { assertTrue(parse("F(true) && (F(false) || F(true))")); } private void assertExceptionMessageStartsWith(String exceptionMessage, Executable executable) { try { executable.execute(); } catch (Throwable e) { if (!e.getMessage().startsWith(exceptionMessage)) { fail("Exception message did not start with: " + exceptionMessage + " Actually: " + e.getMessage()); } } } @Test public void noConditionError() { assertExceptionMessageStartsWith("No condition", () -> parse("&&")); } @Test public void operatorLengthError() { assertExceptionMessageStartsWith("Operators must be exactly two of the same character", () -> parse("F(true) & F(true)")); } @Test public void danglingOperatorError() { assertExceptionMessageStartsWith("Dangling operator", () -> parse("F(true) &&")); } @Test public void emptyBracketsError() { assertExceptionMessageStartsWith("Empty brackets", () -> parse("()")); } @Test public void unacceptableValueError() { assertExceptionMessageStartsWith("Unacceptable function value for", () -> parse("AlwaysError()")); } }
4,590
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ConfigsLoadOnEnableTest.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/test/java/com/discordsrv/common/config/ConfigsLoadOnEnableTest.java
package com.discordsrv.common.config; import com.discordsrv.common.FullBootExtension; import com.discordsrv.common.MockDiscordSRV; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @ExtendWith(FullBootExtension.class) public class ConfigsLoadOnEnableTest { @Test public void configsLoaded() { Assertions.assertTrue(MockDiscordSRV.INSTANCE.configLoaded, "Config loaded"); Assertions.assertTrue(MockDiscordSRV.INSTANCE.connectionConfigLoaded, "Connection config loaded"); Assertions.assertTrue(MockDiscordSRV.INSTANCE.messagesConfigLoaded, "Messages config loaded"); } }
685
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
GameCommandFilterTest.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/test/java/com/discordsrv/common/command/game/GameCommandFilterTest.java
package com.discordsrv.common.command.game; import com.discordsrv.common.config.main.generic.GameCommandExecutionConditionConfig; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.CompletableFuture; public class GameCommandFilterTest { private final ExecutionHelper helper = new ExecutionHelper(); @Test public void test1() { Assertions.assertTrue(GameCommandExecutionConditionConfig.isCommandMatch("test", "test", false, helper)); } @Test public void test2() { Assertions.assertFalse(GameCommandExecutionConditionConfig.isCommandMatch("test", "tester", false, helper)); } @Test public void argumentTest() { Assertions.assertTrue(GameCommandExecutionConditionConfig.isCommandMatch("test arg", "test arg", false, helper)); } @Test public void suggestTest() { Assertions.assertTrue(GameCommandExecutionConditionConfig.isCommandMatch("test arg", "test", true, helper)); } @Test public void extraTest() { Assertions.assertTrue( GameCommandExecutionConditionConfig.isCommandMatch("test arg", "test arg extra arguments after that", false, helper)); } @Test public void argumentOverflowTest1() { Assertions.assertFalse( GameCommandExecutionConditionConfig.isCommandMatch("test arg", "test argument", false, helper)); } @Test public void sameCommandTest1() { Assertions.assertFalse(GameCommandExecutionConditionConfig.isCommandMatch("plugin1:test", "test", false, helper)); } @Test public void sameCommandTest2() { Assertions.assertTrue(GameCommandExecutionConditionConfig.isCommandMatch("plugin2:test", "test", false, helper)); } @Test public void regexTest1() { Assertions.assertTrue(GameCommandExecutionConditionConfig.isCommandMatch("/test/", "test", false, helper)); } @Test public void regexTest2() { Assertions.assertFalse(GameCommandExecutionConditionConfig.isCommandMatch("/test/", "test extra", false, helper)); } @Test public void regexTest3() { Assertions.assertTrue( GameCommandExecutionConditionConfig.isCommandMatch("/test( argument)?/", "test argument", false, helper)); } @Test public void regexTest4() { Assertions.assertFalse( GameCommandExecutionConditionConfig.isCommandMatch("/test( argument)?/", "test fail", false, helper)); } @Test public void regexTest5() { Assertions.assertTrue( GameCommandExecutionConditionConfig.isCommandMatch("/test( argument)?/", "test", true, helper)); } public static class ExecutionHelper implements GameCommandExecutionHelper { private final List<String> TEST1_USED = Collections.singletonList("plugin1:test"); private final List<String> TEST1 = Arrays.asList("test", "plugin1:test"); private final List<String> TEST2 = Arrays.asList("test", "plugin2:test"); private final List<String> TESTER = Arrays.asList("tester", "plugin2:tester"); @Override public CompletableFuture<List<String>> suggestCommands(List<String> parts) { return null; } @Override public List<String> getAliases(String command) { if (TEST1_USED.contains(command)) { return TEST1; } else if (TEST2.contains(command)) { return TEST2; } else if (TESTER.contains(command)) { return TESTER; } return Collections.emptyList(); } @Override public boolean isSameCommand(String command1, String command2) { return getAliases(command1) == getAliases(command2); } } }
3,913
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
MinecraftToDiscordChatMessageTest.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/test/java/com/discordsrv/common/messageforwarding/game/MinecraftToDiscordChatMessageTest.java
package com.discordsrv.common.messageforwarding.game; 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.message.ReceivedDiscordMessage; import com.discordsrv.api.event.bus.EventBus; 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.common.DiscordSRV; import com.discordsrv.common.FullBootExtension; import com.discordsrv.common.MockDiscordSRV; import com.discordsrv.common.channel.GlobalChannel; import com.discordsrv.common.component.util.ComponentUtil; import com.discordsrv.common.player.IPlayer; import com.discordsrv.common.player.provider.model.SkinInfo; import com.discordsrv.common.testing.TestHelper; import net.kyori.adventure.audience.Audience; import net.kyori.adventure.identity.Identity; import net.kyori.adventure.text.Component; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import java.util.Locale; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; @ExtendWith(FullBootExtension.class) public class MinecraftToDiscordChatMessageTest { @Test public void runTest() throws InterruptedException { DiscordSRV discordSRV = MockDiscordSRV.INSTANCE; EventBus bus = discordSRV.eventBus(); String testMessage = UUID.randomUUID().toString(); CompletableFuture<Boolean> future = new CompletableFuture<>(); Listener listener = new Listener(testMessage, future); bus.subscribe(listener); try { TestHelper.set(future::completeExceptionally); MockDiscordSRV.INSTANCE.eventBus().publish( new GameChatMessageReceiveEvent( null, new IPlayer() { @Override public @NotNull Identity identity() { return Identity.identity(UUID.fromString("6c983d46-0631-48b8-9baf-5e33eb5ffec4")); } @Override public @NotNull Audience audience() { return Audience.empty(); } @Override public DiscordSRV discordSRV() { return MockDiscordSRV.INSTANCE; } @Override public @NotNull String username() { return "Vankka"; } @Override public @Nullable SkinInfo skinInfo() { return null; } @Override public @Nullable Locale locale() { return Locale.getDefault(); } @Override public @NotNull Component displayName() { return Component.text("Vankka"); } @Override public boolean hasPermission(String permission) { return true; } @Override public void runCommand(String command) {} }, ComponentUtil.toAPI(Component.text(testMessage)), new GlobalChannel(MockDiscordSRV.INSTANCE), false )); try { Boolean success = future.get(40, TimeUnit.SECONDS); if (success == null) { Assertions.fail("Null amount returned by listener"); return; } Assertions.assertTrue(success, "Correct amount of messages received in the right channel types from listener"); } catch (ExecutionException e) { Assertions.fail(e.getCause()); } catch (TimeoutException e) { Assertions.fail("Failed to round trip message in 40 seconds", e); } } finally { TestHelper.set(null); } } public static class Listener { private final String lookFor; private final CompletableFuture<Boolean> success; public Listener(String lookFor, CompletableFuture<Boolean> success) { this.lookFor = lookFor; this.success = success; } @Subscribe public void onForwarded(GameChatMessageForwardedEvent event) { int text = 0; int thread = 0; for (ReceivedDiscordMessage message : event.getDiscordMessage().getMessages()) { String content = message.getContent(); if (content != null && content.contains(lookFor)) { DiscordMessageChannel channel = message.getChannel(); if (channel instanceof DiscordTextChannel) { text++; } else if (channel instanceof DiscordThreadChannel) { thread++; } } } success.complete(text == 1 && thread == 1); } } }
6,144
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
PlayerProviderBootTest.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/test/java/com/discordsrv/common/player/provider/PlayerProviderBootTest.java
package com.discordsrv.common.player.provider; import com.discordsrv.common.FullBootExtension; import com.discordsrv.common.MockDiscordSRV; import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @ExtendWith(FullBootExtension.class) public class PlayerProviderBootTest { @Test public void subscribed() { Assertions.assertTrue(MockDiscordSRV.INSTANCE.playerProviderSubscribed, "Player provider subscribed"); } }
505
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
EventBusTest.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/test/java/com/discordsrv/common/event/bus/EventBusTest.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.Subscribe; import com.discordsrv.api.event.events.Event; import com.discordsrv.common.MockDiscordSRV; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.assertTrue; public class EventBusTest { private static final Listener listener = new Listener(); private static final EventBus eventBus = MockDiscordSRV.INSTANCE.eventBus(); @BeforeAll public static void subscribe() { eventBus.subscribe(listener); } @AfterAll public static void unsubscribe() { eventBus.unsubscribe(listener); } @Test public void publishTest() { eventBus.publish(new Event() {}); assertTrue(listener.reached); } public static class Listener { public boolean reached = false; @Subscribe public void onEvent(Event event) { reached = true; } } }
1,914
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordSRV.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/DiscordSRV.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; import com.discordsrv.api.DiscordSRVApi; import com.discordsrv.api.module.Module; import com.discordsrv.api.placeholder.PlainPlaceholderFormat; import com.discordsrv.common.bootstrap.IBootstrap; import com.discordsrv.common.channel.ChannelConfigHelper; import com.discordsrv.common.command.game.GameCommandExecutionHelper; import com.discordsrv.common.command.game.handler.ICommandHandler; import com.discordsrv.common.command.game.sender.ICommandSender; import com.discordsrv.common.component.ComponentFactory; import com.discordsrv.common.config.configurate.manager.ConnectionConfigManager; import com.discordsrv.common.config.configurate.manager.MainConfigManager; import com.discordsrv.common.config.configurate.manager.MessagesConfigManager; import com.discordsrv.common.config.connection.ConnectionConfig; import com.discordsrv.common.config.main.MainConfig; import com.discordsrv.common.config.messages.MessagesConfig; import com.discordsrv.common.console.Console; import com.discordsrv.common.debug.data.OnlineMode; import com.discordsrv.common.debug.data.VersionInfo; import com.discordsrv.common.dependency.DiscordSRVDependencyManager; import com.discordsrv.common.discord.api.DiscordAPIImpl; import com.discordsrv.common.discord.connection.details.DiscordConnectionDetailsImpl; import com.discordsrv.common.discord.connection.jda.JDAConnectionManager; import com.discordsrv.common.linking.LinkProvider; import com.discordsrv.common.logging.Logger; import com.discordsrv.common.logging.impl.DiscordSRVLogger; import com.discordsrv.common.module.ModuleManager; import com.discordsrv.common.module.type.AbstractModule; import com.discordsrv.common.placeholder.PlaceholderServiceImpl; import com.discordsrv.common.player.IPlayer; import com.discordsrv.common.player.provider.AbstractPlayerProvider; import com.discordsrv.common.plugin.PluginManager; import com.discordsrv.common.profile.ProfileManager; import com.discordsrv.common.scheduler.Scheduler; import com.discordsrv.common.storage.Storage; import com.fasterxml.jackson.databind.ObjectMapper; import com.github.benmanes.caffeine.cache.Caffeine; import okhttp3.OkHttpClient; import org.jetbrains.annotations.ApiStatus; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.nio.file.Path; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; public interface DiscordSRV extends DiscordSRVApi { String WEBSITE = "https://discordsrv.vankka.dev"; // Platform IBootstrap bootstrap(); Logger platformLogger(); Path dataDirectory(); Scheduler scheduler(); Console console(); PluginManager pluginManager(); OnlineMode onlineMode(); DiscordSRVDependencyManager dependencyManager(); ICommandHandler commandHandler(); @NotNull AbstractPlayerProvider<?, ?> playerProvider(); // DiscordSRVApi @Override @NotNull ComponentFactory componentFactory(); @Override @NotNull ProfileManager profileManager(); @Override @NotNull PlaceholderServiceImpl placeholderService(); @Override @NotNull PlainPlaceholderFormat discordPlaceholders(); @Override @NotNull DiscordAPIImpl discordAPI(); // Logger DiscordSRVLogger logger(); // Storage Storage storage(); // Link Provider LinkProvider linkProvider(); // Version @NotNull VersionInfo versionInfo(); // Config ConnectionConfigManager<? extends ConnectionConfig> connectionConfigManager(); ConnectionConfig connectionConfig(); MainConfigManager<? extends MainConfig> configManager(); MainConfig config(); MessagesConfigManager<? extends MessagesConfig> messagesConfigManager(); default MessagesConfig messagesConfig() { return messagesConfig((Locale) null); } default MessagesConfig.Minecraft messagesConfig(@Nullable ICommandSender sender) { return sender instanceof IPlayer ? messagesConfig((IPlayer) sender) : messagesConfig((Locale) null).minecraft; } default MessagesConfig.Minecraft messagesConfig(@Nullable IPlayer player) { return messagesConfig(player != null ? player.locale() : null).minecraft; } MessagesConfig messagesConfig(@Nullable Locale locale); // Config helper ChannelConfigHelper channelConfig(); // Internal JDAConnectionManager discordConnectionManager(); @NotNull DiscordConnectionDetailsImpl discordConnectionDetails(); // Modules @Nullable <T extends Module> T getModule(Class<T> moduleType); void registerModule(AbstractModule<?> module); void unregisterModule(AbstractModule<?> module); ModuleManager moduleManager(); Locale defaultLocale(); // Status void setStatus(Status status); default void waitForStatus(Status status) throws InterruptedException { waitForStatus(status, -1, TimeUnit.MILLISECONDS); } void waitForStatus(Status status, long time, TimeUnit unit) throws InterruptedException; @SuppressWarnings("unchecked") @ApiStatus.NonExtendable default <K, V> Caffeine<K, V> caffeineBuilder() { return (Caffeine<K, V>) Caffeine.newBuilder() .executor(scheduler().executorService()); } OkHttpClient httpClient(); ObjectMapper json(); // Lifecycle void runEnable(); List<ReloadResult> runReload(Set<ReloadFlag> flags, boolean silent); CompletableFuture<Void> invokeDisable(); @Nullable default GameCommandExecutionHelper executeHelper() { return null; } }
6,492
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ProxyDiscordSRV.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/ProxyDiscordSRV.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; import com.discordsrv.common.bootstrap.IBootstrap; import com.discordsrv.common.config.connection.ConnectionConfig; import com.discordsrv.common.config.main.MainConfig; import com.discordsrv.common.config.messages.MessagesConfig; import com.discordsrv.common.messageforwarding.game.ServerSwitchMessageModule; public abstract class ProxyDiscordSRV< B extends IBootstrap, C extends MainConfig, CC extends ConnectionConfig, MC extends MessagesConfig > extends AbstractDiscordSRV<B, C, CC, MC> { public ProxyDiscordSRV(B bootstrap) { super(bootstrap); } @Override protected void enable() throws Throwable { super.enable(); registerModule(ServerSwitchMessageModule::new); startedMessage(); } }
1,640
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ServerDiscordSRV.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/ServerDiscordSRV.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; import com.discordsrv.common.bootstrap.IBootstrap; import com.discordsrv.common.config.connection.ConnectionConfig; import com.discordsrv.common.config.main.MainConfig; import com.discordsrv.common.config.messages.MessagesConfig; import com.discordsrv.common.messageforwarding.game.AwardMessageModule; import com.discordsrv.common.messageforwarding.game.DeathMessageModule; import com.discordsrv.common.player.provider.ServerPlayerProvider; import com.discordsrv.common.scheduler.ServerScheduler; import org.jetbrains.annotations.NotNull; import javax.annotation.OverridingMethodsMustInvokeSuper; import java.util.concurrent.CompletableFuture; public abstract class ServerDiscordSRV< B extends IBootstrap, C extends MainConfig, CC extends ConnectionConfig, MC extends MessagesConfig > extends AbstractDiscordSRV<B, C, CC, MC> { private boolean serverStarted = false; public ServerDiscordSRV(B bootstrap) { super(bootstrap); } @Override public abstract ServerScheduler scheduler(); @Override public abstract @NotNull ServerPlayerProvider<?, ?> playerProvider(); @Override protected void enable() throws Throwable { super.enable(); registerModule(AwardMessageModule::new); registerModule(DeathMessageModule::new); } public final CompletableFuture<Void> invokeServerStarted() { return CompletableFuture.supplyAsync(() -> { if (status().isShutdown()) { // Already shutdown/shutting down, don't bother return null; } try { this.serverStarted(); } catch (Throwable t) { if (status().isShutdown() && t instanceof NoClassDefFoundError) { // Already shutdown, ignore errors for classes that already got unloaded return null; } setStatus(Status.FAILED_TO_START); disable(); logger().error("Failed to start", t); } return null; }, scheduler().executorService()); } @OverridingMethodsMustInvokeSuper protected void serverStarted() { serverStarted = true; moduleManager().reload(); startedMessage(); } public boolean isServerStarted() { return serverStarted; } }
3,243
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
AbstractDiscordSRV.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/AbstractDiscordSRV.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; import com.discordsrv.api.event.events.lifecycle.DiscordSRVConnectedEvent; import com.discordsrv.api.event.events.lifecycle.DiscordSRVReadyEvent; import com.discordsrv.api.event.events.lifecycle.DiscordSRVReloadedEvent; import com.discordsrv.api.event.events.lifecycle.DiscordSRVShuttingDownEvent; import com.discordsrv.api.module.Module; import com.discordsrv.common.api.util.ApiInstanceUtil; import com.discordsrv.common.bootstrap.IBootstrap; import com.discordsrv.common.channel.ChannelConfigHelper; import com.discordsrv.common.channel.ChannelLockingModule; import com.discordsrv.common.channel.GlobalChannelLookupModule; import com.discordsrv.common.channel.TimedUpdaterModule; import com.discordsrv.common.command.discord.DiscordCommandModule; import com.discordsrv.common.command.game.GameCommandModule; import com.discordsrv.common.command.game.commands.subcommand.reload.ReloadResults; import com.discordsrv.common.component.ComponentFactory; import com.discordsrv.common.config.configurate.manager.ConnectionConfigManager; import com.discordsrv.common.config.configurate.manager.MainConfigManager; import com.discordsrv.common.config.configurate.manager.MessagesConfigManager; import com.discordsrv.common.config.configurate.manager.MessagesConfigSingleManager; import com.discordsrv.common.config.connection.ConnectionConfig; import com.discordsrv.common.config.connection.UpdateConfig; import com.discordsrv.common.config.main.MainConfig; import com.discordsrv.common.config.main.linking.LinkedAccountConfig; import com.discordsrv.common.config.messages.MessagesConfig; import com.discordsrv.common.console.ConsoleModule; import com.discordsrv.common.debug.data.VersionInfo; import com.discordsrv.common.dependency.DiscordSRVDependencyManager; import com.discordsrv.common.discord.api.DiscordAPIEventModule; import com.discordsrv.common.discord.api.DiscordAPIImpl; import com.discordsrv.common.discord.connection.details.DiscordConnectionDetailsImpl; import com.discordsrv.common.discord.connection.jda.JDAConnectionManager; import com.discordsrv.common.event.bus.EventBusImpl; import com.discordsrv.common.exception.StorageException; import com.discordsrv.common.function.CheckedFunction; import com.discordsrv.common.groupsync.GroupSyncModule; import com.discordsrv.common.invite.DiscordInviteModule; import com.discordsrv.common.linking.LinkProvider; import com.discordsrv.common.linking.LinkingModule; import com.discordsrv.common.linking.impl.MinecraftAuthenticationLinker; import com.discordsrv.common.linking.impl.StorageLinker; import com.discordsrv.common.logging.Logger; import com.discordsrv.common.logging.adapter.DependencyLoggerAdapter; import com.discordsrv.common.logging.impl.DependencyLoggingHandler; import com.discordsrv.common.logging.impl.DiscordSRVLogger; import com.discordsrv.common.messageforwarding.discord.DiscordChatMessageModule; import com.discordsrv.common.messageforwarding.discord.DiscordMessageMirroringModule; import com.discordsrv.common.messageforwarding.game.JoinMessageModule; import com.discordsrv.common.messageforwarding.game.LeaveMessageModule; import com.discordsrv.common.messageforwarding.game.StartMessageModule; import com.discordsrv.common.messageforwarding.game.StopMessageModule; import com.discordsrv.common.messageforwarding.game.minecrafttodiscord.MentionCachingModule; import com.discordsrv.common.module.ModuleManager; import com.discordsrv.common.module.type.AbstractModule; import com.discordsrv.common.placeholder.DiscordPlaceholdersImpl; import com.discordsrv.common.placeholder.PlaceholderServiceImpl; import com.discordsrv.common.placeholder.context.GlobalDateFormattingContext; import com.discordsrv.common.placeholder.context.GlobalTextHandlingContext; import com.discordsrv.common.placeholder.result.ComponentResultStringifier; import com.discordsrv.common.profile.ProfileManager; import com.discordsrv.common.storage.Storage; import com.discordsrv.common.storage.StorageType; import com.discordsrv.common.storage.impl.MemoryStorage; import com.discordsrv.common.update.UpdateChecker; import com.discordsrv.common.uuid.util.UUIDUtil; import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDAInfo; import okhttp3.ConnectionPool; import okhttp3.Dispatcher; import okhttp3.OkHttpClient; import okhttp3.Request; import org.apache.commons.lang3.StringUtils; import org.intellij.lang.annotations.Language; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import javax.annotation.OverridingMethodsMustInvokeSuper; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Constructor; import java.net.URL; import java.net.URLClassLoader; import java.nio.file.Path; import java.time.Duration; import java.util.*; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.jar.Attributes; import java.util.jar.JarFile; import java.util.jar.Manifest; /** * DiscordSRV's implementation's common code. * Implementations of this class must call {@link #load()} at the end of their constructors. * @param <C> the config type * @param <CC> the connections config type */ public abstract class AbstractDiscordSRV< B extends IBootstrap, C extends MainConfig, CC extends ConnectionConfig, MC extends MessagesConfig > implements DiscordSRV { private final AtomicReference<Status> status = new AtomicReference<>(Status.INITIALIZED); private final AtomicReference<Boolean> beenReady = new AtomicReference<>(false); // DiscordSRVApi private EventBusImpl eventBus; private ProfileManager profileManager; private PlaceholderServiceImpl placeholderService; private DiscordPlaceholdersImpl discordPlaceholders; private ComponentFactory componentFactory; private DiscordAPIImpl discordAPI; private DiscordConnectionDetailsImpl discordConnectionDetails; // DiscordSRV protected final B bootstrap; private final Logger platformLogger; private final Path dataDirectory; private DiscordSRVDependencyManager dependencyManager; private DiscordSRVLogger logger; private ModuleManager moduleManager; private JDAConnectionManager discordConnectionManager; private ChannelConfigHelper channelConfig; private Storage storage; private LinkProvider linkProvider; // Version private UpdateChecker updateChecker; protected VersionInfo versionInfo; private OkHttpClient httpClient; private final ObjectMapper objectMapper = new ObjectMapper() .configure(DeserializationFeature.FAIL_ON_IGNORED_PROPERTIES, false) .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); public AbstractDiscordSRV(B bootstrap) { ApiInstanceUtil.setInstance(this); this.bootstrap = bootstrap; this.platformLogger = bootstrap.logger(); this.dataDirectory = bootstrap.dataDirectory(); } /** * Method that should be called at the end of implementors constructors. */ protected final void load() { this.dependencyManager = new DiscordSRVDependencyManager(this, bootstrap.lifecycleManager() != null ? bootstrap.lifecycleManager().getDependencyLoader() : null); this.logger = new DiscordSRVLogger(this); this.eventBus = new EventBusImpl(this); this.moduleManager = new ModuleManager(this); this.profileManager = new ProfileManager(this); this.placeholderService = new PlaceholderServiceImpl(this); this.discordPlaceholders = new DiscordPlaceholdersImpl(); this.componentFactory = new ComponentFactory(this); this.discordAPI = new DiscordAPIImpl(this); this.discordConnectionDetails = new DiscordConnectionDetailsImpl(this); this.discordConnectionManager = new JDAConnectionManager(this); this.channelConfig = new ChannelConfigHelper(this); this.updateChecker = new UpdateChecker(this); readManifest(); /////////////////////////////////////////////////////////////// logger.warning(""); logger.warning("+-----------------------------------------+"); logger.warning("This is a testing version of DiscordSRV"); logger.warning("Limited or no support will be provided"); logger.warning("EVERYTHING is subject to change."); logger.warning("+-----------------------------------------+"); logger.warning(""); /////////////////////////////////////////////////////////////// Dispatcher dispatcher = new Dispatcher(); dispatcher.setMaxRequests(20); // Set maximum amount of requests at a time (to something more reasonable than 64) dispatcher.setMaxRequestsPerHost(16); // Most requests are to discord.com ConnectionPool connectionPool = new ConnectionPool(5, 10, TimeUnit.SECONDS); this.httpClient = new OkHttpClient.Builder() .dispatcher(dispatcher) .connectionPool(connectionPool) .addInterceptor(chain -> { Request original = chain.request(); String host = original.url().host(); boolean isDiscord = host.matches("(.*\\.|^)(?:discord\\.(?:com|gg)|(discordapp\\.com))"); String userAgent = isDiscord ? "DiscordBot (https://github.com/DiscordSRV/DiscordSRV, " + versionInfo().version() + ")" + " (" + JDAInfo.GITHUB + ", " + JDAInfo.VERSION + ")" : "DiscordSRV/" + versionInfo().version(); return chain.proceed( original.newBuilder() .removeHeader("User-Agent") .addHeader("User-Agent", userAgent) .build() ); }) .connectTimeout(20, TimeUnit.SECONDS) .readTimeout(20, TimeUnit.SECONDS) .writeTimeout(20, TimeUnit.SECONDS) .build(); } protected URL getManifest() { ClassLoader classLoader = bootstrap.classLoader(); if (classLoader instanceof URLClassLoader) { return ((URLClassLoader) classLoader).findResource(JarFile.MANIFEST_NAME); } return classLoader.getResource(JarFile.MANIFEST_NAME); } private void readManifest() { String version = bootstrap.getClass().getPackage().getImplementationVersion(); String gitCommit = null, gitBranch = null, buildTime = null; try { URL url = getManifest(); if (url == null) { logger().error("Could not find manifest"); return; } try (InputStream inputStream = url.openStream()) { Manifest manifest = new Manifest(inputStream); Attributes attributes = manifest.getMainAttributes(); if (version == null) { version = readAttribute(attributes, "Implementation-Version"); if (version == null) { logger().error("Failed to get version from manifest"); } } gitCommit = readAttribute(attributes, "Git-Commit"); gitBranch = readAttribute(attributes, "Git-Branch"); buildTime = readAttribute(attributes, "Build-Time"); } } catch (IOException e) { logger().error("Failed to read manifest", e); } versionInfo = new VersionInfo(version, gitCommit, gitBranch, buildTime); } private String readAttribute(Attributes attributes, String key) { return attributes.getValue(key); } // DiscordSRVApi @Override public final @NotNull Status status() { return status.get(); } @Override public final @NotNull EventBusImpl eventBus() { return eventBus; } @Override public final @NotNull ProfileManager profileManager() { return profileManager; } @Override public final @NotNull PlaceholderServiceImpl placeholderService() { return placeholderService; } @Override public final @NotNull DiscordPlaceholdersImpl discordPlaceholders() { return discordPlaceholders; } @Override public final @NotNull ComponentFactory componentFactory() { return componentFactory; } @Override public final @NotNull DiscordAPIImpl discordAPI() { return discordAPI; } @Override public final @Nullable JDA jda() { if (discordConnectionManager == null) { return null; } return discordConnectionManager.instance(); } @Override public final @NotNull DiscordConnectionDetailsImpl discordConnectionDetails() { return discordConnectionDetails; } // DiscordSRV @Override public final IBootstrap bootstrap() { return bootstrap; } @Override public final Logger platformLogger() { return platformLogger; } @Override public final DiscordSRVDependencyManager dependencyManager() { return dependencyManager; } @Override public Path dataDirectory() { return dataDirectory; } @Override public final DiscordSRVLogger logger() { return logger; } @Override public final Storage storage() { return storage; } @Override public final LinkProvider linkProvider() { return linkProvider; } @Override public final @NotNull VersionInfo versionInfo() { return versionInfo; } @Override public final ChannelConfigHelper channelConfig() { return channelConfig; } @Override public final JDAConnectionManager discordConnectionManager() { return discordConnectionManager; } // Config @Override public abstract ConnectionConfigManager<CC> connectionConfigManager(); @Override public CC connectionConfig() { return connectionConfigManager().config(); } @Override public abstract MainConfigManager<C> configManager(); @Override public C config() { return configManager().config(); } @Override public abstract MessagesConfigManager<MC> messagesConfigManager(); @Override public MC messagesConfig(@Nullable Locale locale) { MessagesConfigSingleManager<MC> manager = locale != null ? messagesConfigManager().getManager(locale) : null; if (manager == null) { manager = messagesConfigManager().getManager(defaultLocale()); } if (manager == null) { manager = messagesConfigManager().getManager(Locale.US); } return manager.config(); } // Module @Override public <T extends Module> T getModule(Class<T> moduleType) { return moduleManager.getModule(moduleType); } @Override public void registerModule(AbstractModule<?> module) { moduleManager.register(module); } @SuppressWarnings("unchecked") protected final <T extends DiscordSRV> void registerModule(CheckedFunction<T, AbstractModule<?>> function) { moduleManager.registerModule((T) this, function); } /** * @param className a class which has a constructor with {@link DiscordSRV} (or implementation specific) as the only parameter. */ protected final void registerIntegration( @Language(value = "JAVA", prefix = "class X{static{Class.forName(\"", suffix = "\");}}") String className ) { Object module; try { Class<?> clazz = Class.forName(className); Constructor<?> constructor = clazz.getConstructors()[0]; module = constructor.newInstance(this); } catch (Throwable e) { String suffix = ""; if (e instanceof LinkageError || e instanceof ClassNotFoundException) { suffix = " (Integration likely not installed or using wrong version)"; } moduleManager.logger().debug("Failed to load integration: " + className + suffix, e); return; } moduleManager.registerModule(this, d -> (AbstractModule<?>) module); } @Override public void unregisterModule(AbstractModule<?> module) { moduleManager.unregister(module); } @Override public ModuleManager moduleManager() { return moduleManager; } @Override public Locale defaultLocale() { MainConfig config = config(); if (config != null) { String defaultLanguage = config.messages.defaultLanguage; if (StringUtils.isNotBlank(defaultLanguage)) { return Locale.forLanguageTag(defaultLanguage); } } return Locale.getDefault(); } // Status @Override public void setStatus(Status status) { synchronized (this.status) { this.status.set(status); this.status.notifyAll(); } if (status == Status.CONNECTED) { eventBus().publish(new DiscordSRVConnectedEvent()); synchronized (beenReady) { if (!beenReady.get()) { eventBus.publish(new DiscordSRVReadyEvent()); beenReady.set(true); } } } } @Override public void waitForStatus(Status statusToWaitFor, long time, TimeUnit unit) throws InterruptedException { long deadline = time > 0 ? System.currentTimeMillis() + unit.toMillis(time) : Long.MAX_VALUE; while (status().ordinal() < statusToWaitFor.ordinal()) { long currentTime = System.currentTimeMillis(); if (currentTime > deadline) { break; } synchronized (this.status) { if (time > 0) { this.status.wait(deadline - currentTime); } else { this.status.wait(); } } } } @Override public OkHttpClient httpClient() { return httpClient; } @Override public ObjectMapper json() { return objectMapper; } // Lifecycle @Override public final void runEnable() { try { this.enable(); } catch (Throwable t) { logger.error("Failed to enable", t); setStatus(Status.FAILED_TO_START); } } @Override public final CompletableFuture<Void> invokeDisable() { return CompletableFuture.runAsync(this::disable, scheduler().executorService()); } @Override public final List<ReloadResult> runReload(Set<ReloadFlag> flags, boolean silent) { try { return reload(flags, silent); } catch (Throwable e) { if (silent) { throw new RuntimeException(e); } else { logger.error("Failed to reload", e); } return Collections.singletonList(ReloadResults.FAILED); } } @OverridingMethodsMustInvokeSuper protected void enable() throws Throwable { if (eventBus == null) { // Error that should only occur with new platforms throw new IllegalStateException("AbstractDiscordSRV#load was not called from the end of " + getClass().getName() + " constructor"); } // Logging DependencyLoggerAdapter.setAppender(new DependencyLoggingHandler(this)); // Placeholder result stringifiers & global contexts placeholderService().addResultMapper(new ComponentResultStringifier(this)); placeholderService().addGlobalContext(new GlobalTextHandlingContext(this)); placeholderService().addGlobalContext(new GlobalDateFormattingContext(this)); placeholderService().addGlobalContext(UUIDUtil.class); // Modules registerModule(ConsoleModule::new); registerModule(ChannelLockingModule::new); registerModule(TimedUpdaterModule::new); registerModule(DiscordCommandModule::new); registerModule(GameCommandModule::new); registerModule(GlobalChannelLookupModule::new); registerModule(DiscordAPIEventModule::new); registerModule(GroupSyncModule::new); registerModule(DiscordChatMessageModule::new); registerModule(DiscordMessageMirroringModule::new); registerModule(JoinMessageModule::new); registerModule(LeaveMessageModule::new); registerModule(DiscordInviteModule::new); registerModule(MentionCachingModule::new); registerModule(LinkingModule::new); // Integrations registerIntegration("com.discordsrv.common.integration.LuckPermsIntegration"); // Initial load try { runReload(ReloadFlag.ALL, true); } catch (RuntimeException e) { throw e.getCause(); } // Register PlayerProvider listeners playerProvider().subscribe(); } protected final void startedMessage() { registerModule(StartMessageModule::new); registerModule(StopMessageModule::new); } private StorageType getStorageType() { String backend = connectionConfig().storage.backend; switch (backend.toLowerCase(Locale.ROOT)) { case "h2": return StorageType.H2; case "mysql": return StorageType.MYSQL; case "mariadb": return StorageType.MARIADB; } if (backend.equals(MemoryStorage.IDENTIFIER)) { return StorageType.MEMORY; } throw new StorageException("Unknown storage backend \"" + backend + "\""); } @OverridingMethodsMustInvokeSuper protected void disable() { Status status = this.status.get(); if (status == Status.INITIALIZED || status.isShutdown()) { // Hasn't started or already shutting down/shutdown return; } this.status.set(Status.SHUTTING_DOWN); eventBus().publish(new DiscordSRVShuttingDownEvent()); eventBus().shutdown(); try { if (storage != null) { storage.close(); } } catch (Throwable t) { logger().error("Failed to close storage connection", t); } this.status.set(Status.SHUTDOWN); } @OverridingMethodsMustInvokeSuper public List<ReloadResult> reload(Set<ReloadFlag> flags, boolean initial) throws Throwable { if (!initial) { logger().info("Reloading DiscordSRV..."); } if (flags.contains(ReloadFlag.CONFIG)) { try { connectionConfigManager().load(); configManager().load(); messagesConfigManager().load(); channelConfig().reload(); } catch (Throwable t) { if (initial) { setStatus(Status.FAILED_TO_LOAD_CONFIG); } throw t; } } // Update check UpdateConfig updateConfig = connectionConfig().update; if (updateConfig.security.enabled) { if (updateChecker.isSecurityFailed()) { // Security has already failed return Collections.singletonList(ReloadResults.SECURITY_FAILED); } if (initial && !updateChecker.check(true)) { // Security failed cancel startup & shutdown invokeDisable(); return Collections.singletonList(ReloadResults.SECURITY_FAILED); } } else if (initial) { // Not using security, run update check off thread scheduler().run(() -> updateChecker.check(true)); } if (initial) { scheduler().runAtFixedRate(() -> updateChecker.check(false), Duration.ofHours(6)); } if (flags.contains(ReloadFlag.LINKED_ACCOUNT_PROVIDER)) { LinkedAccountConfig linkedAccountConfig = config().linkedAccounts; if (linkedAccountConfig != null && linkedAccountConfig.enabled) { LinkedAccountConfig.Provider provider = linkedAccountConfig.provider; boolean permitMinecraftAuth = connectionConfig().minecraftAuth.allow; if (provider == LinkedAccountConfig.Provider.AUTO) { provider = permitMinecraftAuth && onlineMode().isOnline() ? LinkedAccountConfig.Provider.MINECRAFTAUTH : LinkedAccountConfig.Provider.STORAGE; } switch (provider) { case MINECRAFTAUTH: if (!permitMinecraftAuth) { linkProvider = null; logger().error("minecraftauth.me is disabled in the " + ConnectionConfig.FILE_NAME + ", " + "but linked-accounts.provider is set to \"minecraftauth\". Linked accounts will be disabled"); break; } dependencyManager.mcAuthLib().download().get(); linkProvider = new MinecraftAuthenticationLinker(this); logger().info("Using minecraftauth.me for linked accounts"); break; case STORAGE: linkProvider = new StorageLinker(this); logger().info("Using storage for linked accounts"); break; default: { linkProvider = null; logger().error("Unknown linked account provider: \"" + provider + "\", linked accounts will not be used"); break; } } } else { linkProvider = null; logger().info("Linked accounts are disabled"); } } if (flags.contains(ReloadFlag.STORAGE)) { if (storage != null) { storage.close(); } try { try { StorageType storageType = getStorageType(); logger().info("Using " + storageType.prettyName() + " as storage"); if (storageType == StorageType.MEMORY) { logger().warning("Using memory as storage backend."); logger().warning("Data will not persist across server restarts."); } if (storageType.hikari()) { dependencyManager().hikari().download().get(); } storage = storageType.storageFunction().apply(this); storage.initialize(); logger().info("Storage connection successfully established"); } catch (ExecutionException e) { throw new StorageException(e.getCause()); } catch (StorageException e) { throw e; } catch (Throwable t) { throw new StorageException(t); } } catch (StorageException e) { e.log(this); logger().error("Failed to connect to storage"); if (initial) { setStatus(Status.FAILED_TO_START); } return Collections.singletonList(ReloadResults.STORAGE_CONNECTION_FAILED); } } if (flags.contains(ReloadFlag.DISCORD_CONNECTION)) { try { if (discordConnectionManager.instance() != null) { discordConnectionManager.reconnect().get(); } else { discordConnectionManager.connect().get(); } if (!initial) { waitForStatus(Status.CONNECTED, 20, TimeUnit.SECONDS); if (status() != Status.CONNECTED) { return Collections.singletonList(ReloadResults.DISCORD_CONNECTION_FAILED); } } else { JDA jda = jda(); if (jda != null) { try { jda.awaitReady(); } catch (IllegalStateException ignored) { // JDA shutdown -> don't continue return Collections.singletonList(ReloadResults.DISCORD_CONNECTION_FAILED); } } } } catch (ExecutionException e) { throw e.getCause(); } } List<ReloadResult> results = new ArrayList<>(); if (flags.contains(ReloadFlag.MODULES)) { results.addAll(moduleManager.reload()); } if (flags.contains(ReloadFlag.DISCORD_COMMANDS)) { discordAPI().commandRegistry().registerCommandsFromEvent(); discordAPI().commandRegistry().registerCommandsToDiscord(); } if (!initial) { eventBus().publish(new DiscordSRVReloadedEvent(flags)); logger().info("Reload complete."); } results.add(ReloadResults.SUCCESS); return results; } }
30,538
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordPlaceholdersImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/placeholder/DiscordPlaceholdersImpl.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.placeholder; import com.discordsrv.api.placeholder.PlainPlaceholderFormat; import dev.vankka.mcdiscordreserializer.rules.DiscordMarkdownRules; import dev.vankka.simpleast.core.TextStyle; import dev.vankka.simpleast.core.node.Node; import dev.vankka.simpleast.core.node.StyleNode; import dev.vankka.simpleast.core.node.TextNode; import dev.vankka.simpleast.core.parser.Parser; import dev.vankka.simpleast.core.parser.Rule; import dev.vankka.simpleast.core.simple.SimpleMarkdownRules; import java.util.ArrayList; import java.util.List; import java.util.function.Function; public class DiscordPlaceholdersImpl implements PlainPlaceholderFormat { private final Parser<Object, Node<Object>, Object> parser; public DiscordPlaceholdersImpl() { List<Rule<Object, Node<Object>, Object>> rules = new ArrayList<>(); rules.add(SimpleMarkdownRules.createEscapeRule()); rules.add(SimpleMarkdownRules.createNewlineRule()); rules.add(DiscordMarkdownRules.createCodeBlockRule()); rules.add(DiscordMarkdownRules.createCodeStringRule()); rules.add(DiscordMarkdownRules.createSpecialTextRule()); this.parser = new Parser<>().addRules(rules); } @Override public String map(String input, Function<String, String> placeholders) { List<Node<Object>> nodes = parser.parse(input); StringBuilder finalText = new StringBuilder(); StringBuilder text = new StringBuilder(); for (Node<Object> node : nodes) { if (node instanceof TextNode) { text.append(((TextNode<Object>) node).getContent()); } else if (node instanceof StyleNode) { String content = text.toString(); text.setLength(0); PlainPlaceholderFormat.with(Formatting.DISCORD, () -> finalText.append(placeholders.apply(content))); for (Object style : ((StyleNode<?, ?>) node).getStyles()) { if (!(style instanceof TextStyle)) { continue; } TextStyle textStyle = (TextStyle) style; String childText = ((TextNode<?>) node.getChildren().get(0)).getContent(); if (textStyle.getType() == TextStyle.Type.CODE_STRING) { finalText.append("`").append(placeholders.apply(childText)).append("`"); } else if (textStyle.getType() == TextStyle.Type.CODE_BLOCK) { String language = textStyle.getExtra().get("language"); if (language != null && language.equals("ansi")) { PlainPlaceholderFormat.with(Formatting.ANSI, () -> finalText .append("```ansi\n") .append(placeholders.apply(childText)) .append("```") ); } else { finalText .append("```") .append(language != null ? language : "") .append("\n") .append(placeholders.apply(childText)) .append("```"); } } } } } finalText.append(placeholders.apply(text.toString())); return finalText.toString(); } }
4,362
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
PlaceholderServiceImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/placeholder/PlaceholderServiceImpl.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.placeholder; import com.discordsrv.api.event.events.placeholder.PlaceholderLookupEvent; import com.discordsrv.api.placeholder.PlaceholderLookupResult; import com.discordsrv.api.placeholder.PlaceholderService; import com.discordsrv.api.placeholder.annotation.Placeholder; import com.discordsrv.api.placeholder.annotation.PlaceholderPrefix; import com.discordsrv.api.placeholder.annotation.PlaceholderRemainder; import com.discordsrv.api.placeholder.mapper.PlaceholderResultMapper; import com.discordsrv.api.placeholder.provider.PlaceholderProvider; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.logging.Logger; import com.discordsrv.common.logging.NamedLogger; import com.discordsrv.common.placeholder.provider.AnnotationPlaceholderProvider; import com.github.benmanes.caffeine.cache.CacheLoader; import com.github.benmanes.caffeine.cache.LoadingCache; import org.apache.commons.lang3.StringUtils; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; import org.jetbrains.annotations.NotNull; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.Parameter; import java.util.*; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PlaceholderServiceImpl implements PlaceholderService { private final DiscordSRV discordSRV; private final Logger logger; private final LoadingCache<Class<?>, Set<PlaceholderProvider>> classProviders; private final Set<PlaceholderResultMapper> mappers = new CopyOnWriteArraySet<>(); private final Set<Object> globalContext = new CopyOnWriteArraySet<>(); public PlaceholderServiceImpl(DiscordSRV discordSRV) { this.discordSRV = discordSRV; this.logger = new NamedLogger(discordSRV, "PLACEHOLDER_SERVICE"); this.classProviders = discordSRV.caffeineBuilder() .expireAfterAccess(10, TimeUnit.MINUTES) .expireAfterWrite(15, TimeUnit.MINUTES) .build(new ClassProviderLoader()); } public void addGlobalContext(@NotNull Object context) { globalContext.add(context); } public void removeGlobalContext(@NotNull Object context) { globalContext.remove(context); } private static Set<Object> getArrayAsSet(Object[] array) { return array.length == 0 ? Collections.emptySet() : new HashSet<>(Arrays.asList(array)); } @Override public PlaceholderLookupResult lookupPlaceholder(@NotNull String placeholder, Object... context) { return lookupPlaceholder(placeholder, getArrayAsSet(context)); } @Override public PlaceholderLookupResult lookupPlaceholder(@NotNull String placeholder, @NotNull Set<Object> lookupContexts) { Set<Object> contexts = new HashSet<>(lookupContexts); contexts.addAll(globalContext); contexts.removeIf(Objects::isNull); for (Object context : contexts) { if (context instanceof PlaceholderProvider) { PlaceholderLookupResult result = ((PlaceholderProvider) context).lookup(placeholder, contexts); if (result.getType() != PlaceholderLookupResult.Type.UNKNOWN_PLACEHOLDER) { return result; } } Set<PlaceholderProvider> providers = classProviders .get(context instanceof Class ? (Class<?>) context : context.getClass()); if (providers == null) { continue; } for (PlaceholderProvider provider : providers) { PlaceholderLookupResult result = provider.lookup(placeholder, contexts); if (result.getType() != PlaceholderLookupResult.Type.UNKNOWN_PLACEHOLDER) { return result; } } } // Only go through this if a placeholder couldn't be looked up from lookup/global contexts // API users are here as to not interfere with DiscordSRV's own placeholders PlaceholderLookupEvent lookupEvent = new PlaceholderLookupEvent(placeholder, contexts); discordSRV.eventBus().publish(lookupEvent); return lookupEvent.isProcessed() ? lookupEvent.getResultFromProcessing() : PlaceholderLookupResult.UNKNOWN_PLACEHOLDER; } @Override public String replacePlaceholders(@NotNull String input, Object... context) { return replacePlaceholders(input, getArrayAsSet(context)); } @Override public void addResultMapper(@NotNull PlaceholderResultMapper resultMapper) { mappers.add(resultMapper); } @Override public void removeResultMapper(@NotNull PlaceholderResultMapper resultMapper) { mappers.remove(resultMapper); } @Override public String replacePlaceholders(@NotNull String input, @NotNull Set<Object> context) { return getReplacement(PATTERN, input, context); } private String getReplacement(Pattern pattern, String input, Set<Object> context) { Matcher matcher = pattern.matcher(input); String output = input; while (matcher.find()) { String placeholder = getPlaceholder(matcher); List<PlaceholderLookupResult> results = resolve(placeholder, context); output = updateContent(results, placeholder, matcher, output); } return output; } @Override public Object getResult(@NotNull Matcher matcher, @NotNull Set<Object> context) { if (matcher.groupCount() < 3) { throw new IllegalStateException("Matcher must have at least 3 groups"); } String placeholder = getPlaceholder(matcher); List<PlaceholderLookupResult> results = resolve(placeholder, context); return getResultRepresentation(results, placeholder, matcher); } private String getPlaceholder(Matcher matcher) { String placeholder = matcher.group(2); Pattern pattern = matcher.pattern(); if (PATTERN.equals(pattern)) { // Remove escapes for % placeholder = placeholder.replace("\\%", "%"); } else if (RECURSIVE_PATTERN.equals(pattern)) { // Remove escapes for { and } placeholder = placeholder.replaceAll("\\\\([{}])", "$1"); } return placeholder; } @Override public @NotNull CharSequence getResultAsPlain(@NotNull Matcher matcher, @NotNull Set<Object> context) { Object result = getResult(matcher, context); return getResultAsPlain(result); } @Override public @NotNull CharSequence getResultAsPlain(@Nullable Object result) { if (result == null) { return ""; } else if (result instanceof CharSequence) { return (CharSequence) result; } Object output = null; for (PlaceholderResultMapper mapper : mappers) { output = mapper.convertResult(result); if (output != null) { break; } } return output instanceof CharSequence ? (CharSequence) output : String.valueOf(output != null ? output : result); } private List<PlaceholderLookupResult> resolve(String placeholder, Set<Object> context) { // Recursive placeholder = getReplacement(RECURSIVE_PATTERN, placeholder, context); List<PlaceholderLookupResult> results = new ArrayList<>(); for (String part : placeholder.split("(?<!\\\\)\\|")) { results.add(lookupPlaceholder(part, context)); } return results; } private String updateContent(List<PlaceholderLookupResult> results, String placeholder, Matcher matcher, String input) { Object representation = getResultRepresentation(results, placeholder, matcher); CharSequence output = getResultAsPlain(representation); return Pattern.compile( matcher.group(1) + placeholder + matcher.group(3), Pattern.LITERAL ) .matcher(input) .replaceFirst(Matcher.quoteReplacement(output.toString())); } private Object getResultRepresentation(List<PlaceholderLookupResult> results, String placeholder, Matcher matcher) { Map<String, AtomicInteger> preventInfiniteLoop = new HashMap<>(); Object best = null; for (PlaceholderLookupResult result : results) { while (result != null) { PlaceholderLookupResult.Type type = result.getType(); if (type == PlaceholderLookupResult.Type.UNKNOWN_PLACEHOLDER) { break; } boolean newLookup = false; Object replacement = null; switch (type) { case SUCCESS: replacement = result.getValue(); if (replacement == null) { replacement = getResultAsPlain(null); } if (StringUtils.isNotBlank(getResultAsPlain(replacement))) { return replacement; } break; case DATA_NOT_AVAILABLE: replacement = "Unavailable"; break; case LOOKUP_FAILED: logger.trace("Lookup failed", result.getError()); replacement = "Error"; break; case NEW_LOOKUP: String placeholderKey = (String) result.getValue(); AtomicInteger infiniteLoop = preventInfiniteLoop.computeIfAbsent(placeholderKey, key -> new AtomicInteger(0)); if (infiniteLoop.incrementAndGet() > 10) { replacement = "Infinite Loop"; break; } result = lookupPlaceholder(placeholderKey, result.getExtras()); newLookup = true; break; } if (replacement != null) { best = replacement; } if (!newLookup) { break; } } } return best != null ? best : matcher.group(1) + placeholder + matcher.group(3); } private static class ClassProviderLoader implements CacheLoader<Class<?>, Set<PlaceholderProvider>> { private Set<PlaceholderProvider> loadProviders(Class<?> clazz, PlaceholderPrefix prefix) { Set<PlaceholderProvider> providers = new LinkedHashSet<>(); Class<?> currentClass = clazz; while (currentClass != null) { PlaceholderPrefix currentPrefix = currentClass.getAnnotation(PlaceholderPrefix.class); if (currentPrefix != null && prefix == null) { prefix = currentPrefix; } PlaceholderPrefix usePrefix = (currentPrefix != null && currentPrefix.ignoreParents()) ? currentPrefix : prefix; for (Method method : clazz.getMethods()) { if (!method.getDeclaringClass().equals(currentClass)) { continue; } Placeholder annotation = method.getAnnotation(Placeholder.class); if (annotation == null) { continue; } PlaceholderRemainder remainder = null; for (Parameter parameter : method.getParameters()) { remainder = parameter.getAnnotation(PlaceholderRemainder.class); if (remainder != null) { break; } } boolean isStatic = Modifier.isStatic(method.getModifiers()); providers.add(new AnnotationPlaceholderProvider(annotation, usePrefix, remainder, isStatic ? null : clazz, method)); } for (Field field : clazz.getFields()) { if (!field.getDeclaringClass().equals(currentClass)) { continue; } Placeholder annotation = field.getAnnotation(Placeholder.class); if (annotation == null) { continue; } boolean isStatic = Modifier.isStatic(field.getModifiers()); providers.add(new AnnotationPlaceholderProvider(annotation, usePrefix, isStatic ? null : clazz, field)); } for (Class<?> anInterface : currentClass.getInterfaces()) { providers.addAll(loadProviders(anInterface, prefix)); } currentClass = currentClass.getSuperclass(); } return providers; } @Override public @Nullable Set<PlaceholderProvider> load(@NonNull Class<?> key) { return loadProviders(key, null); } } }
14,293
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
GlobalDateFormattingContext.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/placeholder/context/GlobalDateFormattingContext.java
package com.discordsrv.common.placeholder.context; import com.discordsrv.api.placeholder.annotation.Placeholder; import com.discordsrv.api.placeholder.annotation.PlaceholderRemainder; import com.discordsrv.common.DiscordSRV; import com.github.benmanes.caffeine.cache.LoadingCache; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.concurrent.TimeUnit; public class GlobalDateFormattingContext { private static final String TIMESTAMP_IDENTIFIER = "timestamp"; private final LoadingCache<String, DateTimeFormatter> cache; public GlobalDateFormattingContext(DiscordSRV discordSRV) { this.cache = discordSRV.caffeineBuilder() .expireAfterAccess(30, TimeUnit.SECONDS) .build(DateTimeFormatter::ofPattern); } @Placeholder("date") public String formatDate(ZonedDateTime time, @PlaceholderRemainder String format) { if (format.startsWith(TIMESTAMP_IDENTIFIER)) { String style = format.substring(TIMESTAMP_IDENTIFIER.length()); if (!style.isEmpty() && !style.startsWith(":")) { return null; } return "<t:" + time.toEpochSecond() + style + ">"; } DateTimeFormatter formatter = cache.get(format); if (formatter == null) { throw new IllegalStateException("Illegal state"); } return formatter.format(time); } }
1,442
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
GlobalTextHandlingContext.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/placeholder/context/GlobalTextHandlingContext.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.placeholder.context; import com.discordsrv.api.component.MinecraftComponent; import com.discordsrv.api.placeholder.annotation.Placeholder; import com.discordsrv.api.placeholder.annotation.PlaceholderRemainder; import com.discordsrv.common.DiscordSRV; public class GlobalTextHandlingContext { private final DiscordSRV discordSRV; public GlobalTextHandlingContext(DiscordSRV discordSRV) { this.discordSRV = discordSRV; } @Placeholder("text") public MinecraftComponent text(@PlaceholderRemainder String text) { return discordSRV.componentFactory().textBuilder(text).build(); } }
1,481
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ComponentResultStringifier.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/placeholder/result/ComponentResultStringifier.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.placeholder.result; import com.discordsrv.api.component.MinecraftComponent; import com.discordsrv.api.placeholder.FormattedText; import com.discordsrv.api.placeholder.PlainPlaceholderFormat; import com.discordsrv.api.placeholder.mapper.PlaceholderResultMapper; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.component.util.ComponentUtil; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.serializer.legacy.LegacyComponentSerializer; import org.jetbrains.annotations.NotNull; public class ComponentResultStringifier implements PlaceholderResultMapper { private final DiscordSRV discordSRV; public ComponentResultStringifier(DiscordSRV discordSRV) { this.discordSRV = discordSRV; } @Override public CharSequence convertResult(@NotNull Object result) { if (result instanceof MinecraftComponent) { result = ComponentUtil.fromAPI((MinecraftComponent) result); } if (result instanceof Component) { Component component = (Component) result; PlainPlaceholderFormat.Formatting mappingState = PlainPlaceholderFormat.FORMATTING.get(); switch (mappingState) { default: case PLAIN: return discordSRV.componentFactory().plainSerializer().serialize(component); case DISCORD: return new FormattedText(discordSRV.componentFactory().discordSerializer().serialize(component)); case ANSI: return discordSRV.componentFactory().ansiSerializer().serialize(component); case LEGACY: return LegacyComponentSerializer.legacySection().serialize(component); } } return null; } }
2,655
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
AnnotationPlaceholderProvider.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/placeholder/provider/AnnotationPlaceholderProvider.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.placeholder.provider; import com.discordsrv.api.placeholder.PlaceholderLookupResult; import com.discordsrv.api.placeholder.annotation.Placeholder; import com.discordsrv.api.placeholder.annotation.PlaceholderPrefix; import com.discordsrv.api.placeholder.annotation.PlaceholderRemainder; import com.discordsrv.api.placeholder.provider.PlaceholderProvider; import com.discordsrv.common.placeholder.provider.util.PlaceholderMethodUtil; import org.jetbrains.annotations.NotNull; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.HashSet; import java.util.Set; public class AnnotationPlaceholderProvider implements PlaceholderProvider { private final Placeholder annotation; private final PlaceholderPrefix prefixAnnotation; private final PlaceholderRemainder remainderAnnotation; private final Class<?> type; private final Method method; private final Field field; public AnnotationPlaceholderProvider(Placeholder annotation, PlaceholderPrefix prefixAnnotation, PlaceholderRemainder remainderAnnotation, Class<?> type, Method method) { this(annotation, prefixAnnotation, remainderAnnotation, type, method, null); } public AnnotationPlaceholderProvider(Placeholder annotation, PlaceholderPrefix prefixAnnotation, Class<?> type, Field field) { this(annotation, prefixAnnotation, null, type, null, field); } private AnnotationPlaceholderProvider(Placeholder annotation, PlaceholderPrefix prefixAnnotation, PlaceholderRemainder remainderAnnotation, Class<?> type, Method method, Field field) { this.annotation = annotation; this.prefixAnnotation = prefixAnnotation; this.remainderAnnotation = remainderAnnotation; this.type = type; this.method = method; this.field = field; } @Override public @NotNull PlaceholderLookupResult lookup(@NotNull String placeholder, @NotNull Set<Object> context) { String annotationPlaceholder = (prefixAnnotation != null ? prefixAnnotation.value() : "") + annotation.value(); String reLookup = annotation.relookup(); boolean startsWith = !reLookup.isEmpty() || remainderAnnotation != null; if (annotationPlaceholder.isEmpty() || !(startsWith ? placeholder.startsWith(annotationPlaceholder) : placeholder.equals(annotationPlaceholder)) || (type != null && context.isEmpty())) { return PlaceholderLookupResult.UNKNOWN_PLACEHOLDER; } Object instance = null; if (type != null) { for (Object o : context) { if (type.isAssignableFrom(o.getClass())) { instance = o; } } if (instance == null) { return PlaceholderLookupResult.UNKNOWN_PLACEHOLDER; } } String remainder = placeholder.substring(annotationPlaceholder.length()); Object result; try { if (field != null) { result = field.get(instance); } else { assert method != null; result = PlaceholderMethodUtil.lookup(method, instance, context, remainder); } } catch (Throwable t) { return PlaceholderLookupResult.lookupFailed(t); } if (reLookup.isEmpty() && remainderAnnotation == null) { reLookup = annotation.value(); } if (!reLookup.isEmpty() && !remainder.isEmpty()) { if (result == null) { return PlaceholderLookupResult.success(null); } Set<Object> newContext = new HashSet<>(context); newContext.add(result); String newPlaceholder = reLookup + remainder; return PlaceholderLookupResult.newLookup(newPlaceholder, newContext); } return result instanceof PlaceholderLookupResult ? (PlaceholderLookupResult) result : PlaceholderLookupResult.success(result); } }
4,889
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
PlaceholderMethodUtil.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/placeholder/provider/util/PlaceholderMethodUtil.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.placeholder.provider.util; import com.discordsrv.api.placeholder.annotation.PlaceholderRemainder; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Parameter; import java.util.Set; import java.util.function.BiConsumer; public final class PlaceholderMethodUtil { private PlaceholderMethodUtil() {} public static Object lookup(Method method, Object instance, Set<Object> context, String remainder) throws InvocationTargetException, IllegalAccessException { Parameter[] parameters = method.getParameters(); Object[] parameterValues = new Object[parameters.length]; apply(parameters, (parameter, i) -> { PlaceholderRemainder annotation = parameter.getAnnotation(PlaceholderRemainder.class); if (annotation != null) { parameters[i] = null; if (parameter.getType().isAssignableFrom(String.class)) { String suffix = remainder; if (suffix.startsWith(":")) { suffix = suffix.substring(1); } else if (!suffix.isEmpty()) { suffix = ""; } if (suffix.startsWith("'") && suffix.endsWith("'")) { suffix = suffix.substring(1, suffix.length() - 1); } parameterValues[i] = suffix; } else { parameterValues[i] = null; } } }); for (Object o : context) { Class<?> objectType = o.getClass(); apply(parameters, (parameter, i) -> { if (parameter.getType().isAssignableFrom(objectType)) { parameters[i] = null; parameterValues[i] = o; } }); } for (Object parameter : parameters) { if (parameter != null) { return null; } } return method.invoke(instance, parameterValues); } private static void apply(Parameter[] parameters, BiConsumer<Parameter, Integer> parameterProcessor) { for (int i = 0; i < parameters.length; i++) { Parameter parameter = parameters[i]; if (parameter == null) { continue; } parameterProcessor.accept(parameter, i); } } }
3,313
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
NamedLogger.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/logging/NamedLogger.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.logging; import com.discordsrv.common.DiscordSRV; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class NamedLogger implements Logger { private final DiscordSRV discordSRV; private final String name; public NamedLogger(DiscordSRV discordSRV, String name) { this.discordSRV = discordSRV; this.name = name; } @Override public void log(@Nullable String loggerName, @NotNull LogLevel logLevel, @Nullable String message, @Nullable Throwable throwable) { discordSRV.logger().log(name, logLevel, message, throwable); } }
1,475
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
Logger.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/logging/Logger.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.logging; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.PrintWriter; import java.io.StringWriter; public interface Logger { default void info(String message) { log(null, LogLevel.INFO, message, null); } default void warning(String message) { warning(message, null); } default void warning(Throwable throwable) { warning(null, throwable); } default void warning(String message, Throwable throwable) { log(null, LogLevel.WARNING, message, throwable); } default void error(String message) { error(message, null); } default void error(Throwable throwable) { error(null, throwable); } default void error(String message, Throwable throwable) { log(null, LogLevel.ERROR, message, throwable); } default void debug(String message) { debug(message, null); } default void debug(Throwable throwable) { debug(null, throwable); } default void debug(String message, Throwable throwable) { log(null, LogLevel.DEBUG, message, throwable); } default void trace(String message) { trace(message, null); } default void trace(Throwable throwable) { trace(null, throwable); } default void trace(String message, Throwable throwable) { log(null, LogLevel.TRACE, message, throwable); } void log(@Nullable String loggerName, @NotNull LogLevel logLevel, @Nullable String message, @Nullable Throwable throwable); default String getStackTrace(Throwable throwable) { final StringWriter stringWriter = new StringWriter(); final PrintWriter printWriter = new PrintWriter(stringWriter, true); throwable.printStackTrace(printWriter); return stringWriter.getBuffer().toString(); } }
2,726
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordSRVLogger.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/logging/impl/DiscordSRVLogger.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.logging.impl; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.config.main.DebugConfig; import com.discordsrv.common.config.main.MainConfig; import com.discordsrv.common.logging.LogLevel; import com.discordsrv.common.logging.Logger; import net.dv8tion.jda.api.Permission; import net.dv8tion.jda.api.exceptions.InsufficientPermissionException; import org.apache.commons.lang3.exception.ExceptionUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.charset.StandardCharsets; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardOpenOption; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.time.Duration; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Future; public class DiscordSRVLogger implements Logger { private static final DateFormat ROTATED_DATE_TIME_FORMATTER = new SimpleDateFormat("EEE HH:mm:ss z"); private static final DateFormat DAY_DATE_TIME_FORMATTER = new SimpleDateFormat("HH:mm:ss z"); private static final DateFormat DAY = new SimpleDateFormat("yyyy-MM-dd"); private static final String ROTATED_LOG_LINE_FORMAT = "[%s] [%s] %s"; private static final String DAY_LOG_LINE_FORMAT = "[%s] %s"; private static final String LOG_FILE_NAME_FORMAT = "%s-%s.log"; private static final List<String> DISABLE_DEBUG_BY_DEFAULT = Collections.singletonList("Hikari"); private final DiscordSRV discordSRV; // Files private final Path logsDirectory; private final List<Path> debugLogs; // File writing private final Queue<LogEntry> linesToWrite = new ConcurrentLinkedQueue<>(); private final Object lineProcessingLock = new Object(); private Future<?> lineProcessingFuture; public DiscordSRVLogger(DiscordSRV discordSRV) { this.discordSRV = discordSRV; this.logsDirectory = discordSRV.dataDirectory().resolve("logs"); if (!Files.exists(logsDirectory)) { try { Files.createDirectory(logsDirectory); } catch (IOException e) { throw new UncheckedIOException(e); } } this.debugLogs = rotateLog("debug", 3); } public List<Path> getDebugLogs() { return debugLogs; } public void writeLogForCurrentDay(String label, String message) { Path log = logsDirectory.resolve(label + "_" + DAY.format(System.currentTimeMillis()) + ".log"); scheduleWrite(new LogEntry(log, null, System.currentTimeMillis(), null, message, null)); } @SuppressWarnings("SameParameterValue") private List<Path> rotateLog(String label, int amount) { try { List<Path> logs = new ArrayList<>(amount); for (int i = amount; i > 0; i--) { Path log = logsDirectory.resolve(String.format(LOG_FILE_NAME_FORMAT, label, i)); logs.add(0, log); if (!Files.exists(log)) { continue; } if (i == amount) { Files.delete(log); continue; } Path to = logsDirectory.resolve(String.format(LOG_FILE_NAME_FORMAT, label, i + 1)); Files.move(log, to); } return logs; } catch (IOException e) { doLog("LOGGING", LogLevel.ERROR, "Failed to rotate log", e); return null; } } @Override public void log(@Nullable String loggerName, @NotNull LogLevel logLevel, @Nullable String message, @Nullable Throwable throwable) { if (throwable != null && throwable.getMessage() != null && (throwable.getStackTrace() == null || throwable.getStackTrace().length == 0)) { // Empty stack trace message = (message != null ? message + ": " : "") + throwable.getMessage(); throwable = null; } if (throwable instanceof InsufficientPermissionException) { Permission permission = ((InsufficientPermissionException) throwable).getPermission(); String msg = "The bot is missing the \"" + permission.getName() + "\" permission"; if (message == null) { message = msg; } else { message += ": " + msg; } doLog(loggerName, logLevel, message, null); doLog(loggerName, LogLevel.DEBUG, null, throwable); return; } doLog(loggerName, logLevel, message, throwable); } private void doLog(String loggerName, LogLevel logLevel, String message, Throwable throwable) { long time = System.currentTimeMillis(); MainConfig config = discordSRV.config(); DebugConfig debugConfig = config != null ? config.debug : null; if (logLevel == LogLevel.TRACE || (loggerName != null && logLevel == LogLevel.DEBUG && DISABLE_DEBUG_BY_DEFAULT.contains(loggerName))) { if (loggerName == null || debugConfig == null || debugConfig.additionalLevels == null || !debugConfig.additionalLevels.getOrDefault(loggerName, Collections.emptyList()).contains(logLevel.name())) { return; } } boolean debugOrTrace = logLevel == LogLevel.DEBUG || logLevel == LogLevel.TRACE; boolean logToConsole = debugConfig != null && debugConfig.logToConsole; if (!debugOrTrace || logToConsole) { String consoleMessage = message; LogLevel consoleLevel = logLevel; if (debugOrTrace) { // Normally DEBUG/TRACE logging isn't enabled, so we convert it to INFO and add the level consoleMessage = "[" + logLevel.name() + "]" + (message != null ? " " + message : ""); consoleLevel = LogLevel.INFO; } discordSRV.platformLogger().log(null, consoleLevel, consoleMessage, throwable); } Path debugLog = debugLogs.isEmpty() ? null : debugLogs.get(0); if (debugLog == null) { return; } scheduleWrite(new LogEntry(debugLog, loggerName, time, logLevel, message, throwable)); } private void scheduleWrite(LogEntry entry) { linesToWrite.add(entry); synchronized (lineProcessingLock) { if (lineProcessingFuture == null || lineProcessingFuture.isDone()) { lineProcessingFuture = discordSRV.scheduler().runLater(this::processLines, Duration.ofSeconds(2)); } } } private void processLines() { LogEntry entry; while ((entry = linesToWrite.poll()) != null) { writeToFile(entry.log(), entry.loggerName(), entry.time(), entry.logLevel(), entry.message(), entry.throwable()); } } private void writeToFile(Path path, String loggerName, long time, LogLevel logLevel, String message, Throwable throwable) { try { if (message == null) { message = ""; } if (loggerName != null) { message = "[" + loggerName + "] " + message; } String line; if (logLevel == null) { String timestamp = DAY_DATE_TIME_FORMATTER.format(time); line = String.format(DAY_LOG_LINE_FORMAT, timestamp, message) + "\n"; } else { String timestamp = ROTATED_DATE_TIME_FORMATTER.format(time); line = String.format(ROTATED_LOG_LINE_FORMAT, timestamp, logLevel.name(), message) + "\n"; } if (throwable != null) { line += ExceptionUtils.getStackTrace(throwable) + "\n"; } Path parent = path.getParent(); if (!Files.exists(parent)) { Files.createDirectories(parent); } if (!Files.exists(path)) { Files.createFile(path); } Files.write(path, line.getBytes(StandardCharsets.UTF_8), StandardOpenOption.APPEND); } catch (Throwable e) { try { // Prevent infinite loop if (discordSRV.status() == DiscordSRV.Status.SHUTDOWN) { return; } discordSRV.platformLogger().error("Failed to write to log", e); } catch (Throwable ignored) {} } } private static class LogEntry { private final Path log; private final String loggerName; private final long time; private final LogLevel logLevel; private final String message; private final Throwable throwable; public LogEntry(Path log, String loggerName, long time, LogLevel logLevel, String message, Throwable throwable) { this.log = log; this.loggerName = loggerName; this.time = time; this.logLevel = logLevel; this.message = message; this.throwable = throwable; } public Path log() { return log; } public String loggerName() { return loggerName; } public long time() { return time; } public LogLevel logLevel() { return logLevel; } public String message() { return message; } public Throwable throwable() { return throwable; } } }
10,556
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DependencyLoggingHandler.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/logging/impl/DependencyLoggingHandler.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.logging.impl; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.logging.LogAppender; import com.discordsrv.common.logging.LogLevel; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.concurrent.RejectedExecutionException; public class DependencyLoggingHandler implements LogAppender { private static final Map<String, List<String>> BLACKLISTED_MESSAGES = new HashMap<>(); private static final Map<String, String> LOGGER_MAPPINGS = new HashMap<>(); static { // Class names here will get relocated, which is fine LOGGER_MAPPINGS.put("net.dv8tion.jda", "JDA"); LOGGER_MAPPINGS.put("com.zaxxer.hikari", "Hikari"); BLACKLISTED_MESSAGES.put("net.dv8tion.jda", Arrays.asList( // We have our own more informative log messages for this "WebSocket connection was closed and cannot be recovered due to identification issues", // Failed JDA requests (handled with RestAction default failure) "There was an I/O error while executing a REST request: ", "There was an unexpected error while executing a REST request" )); BLACKLISTED_MESSAGES.put("com.zaxxer.hikari", Collections.singletonList( // This is fine, we don't need a warning about it "was not found, trying direct instantiation." // "Registered driver with driverClassName={} was not found, trying direct instantiation." )); } private final DiscordSRV discordSRV; public DependencyLoggingHandler(DiscordSRV discordSRV) { this.discordSRV = discordSRV; } @Override public void append(@Nullable String loggerName, @NotNull LogLevel logLevel, @Nullable String message, @Nullable Throwable throwable) { if (loggerName == null) { loggerName = "null"; } if (message != null) { List<String> blacklistedMessages = new ArrayList<>(); // Get blacklisted messages for the logger for (Map.Entry<String, List<String>> entry : BLACKLISTED_MESSAGES.entrySet()) { if (loggerName.startsWith(entry.getKey())) { blacklistedMessages.addAll(entry.getValue()); } } // Go through the blacklisted messages we gathered for (String blacklistedMessage : blacklistedMessages) { if (message.contains(blacklistedMessage)) { return; } } } // Prettify logger name, if possible String name = loggerName; for (Map.Entry<String, String> entry : LOGGER_MAPPINGS.entrySet()) { if (name.startsWith(entry.getKey())) { name = entry.getValue(); break; } } if (name.equals("JDA") && message != null && message.contains("Got an unexpected error. Please redirect the following message to the devs:") && throwable instanceof RejectedExecutionException && discordSRV.status().isShutdown()) { // Might happen if the server shuts down while JDA is starting return; } discordSRV.logger().log(null, logLevel, "[" + name + "]" + (message != null ? " " + message : ""), throwable); } }
4,299
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
LoggingBackend.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/logging/backend/LoggingBackend.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.logging.backend; import com.discordsrv.common.logging.LogAppender; public interface LoggingBackend { boolean addFilter(LogFilter filter); boolean removeFilter(LogFilter filter); boolean addAppender(LogAppender appender); boolean removeAppender(LogAppender appender); }
1,149
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
LogFilter.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/logging/backend/LogFilter.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.logging.backend; import com.discordsrv.common.logging.LogLevel; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; @FunctionalInterface public interface LogFilter { Result filter(@Nullable String loggerName, @NotNull LogLevel logLevel, @Nullable String message, @Nullable Throwable throwable); enum Result { ACCEPT, BLOCK, IGNORE } }
1,269
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
SLF4JLoggerImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/logging/backend/impl/SLF4JLoggerImpl.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.logging.backend.impl; import com.discordsrv.common.logging.LogLevel; import com.discordsrv.common.logging.Logger; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; public class SLF4JLoggerImpl implements Logger { private final com.discordsrv.unrelocate.org.slf4j.Logger logger; public SLF4JLoggerImpl(com.discordsrv.unrelocate.org.slf4j.Logger logger) { this.logger = logger; } @Override public void log(@Nullable String loggerName, @NotNull LogLevel level, @Nullable String message, @Nullable Throwable throwable) { if (!(level instanceof LogLevel.StandardLogLevel)) { return; } switch ((LogLevel.StandardLogLevel) level) { case INFO: { logger.info(message, throwable); return; } case WARNING: { logger.warn(message, throwable); return; } case ERROR: { logger.error(message, throwable); return; } case DEBUG: { logger.debug(message, throwable); return; } case TRACE: { logger.trace(message, throwable); return; } default: throw new IllegalStateException(level.name() + " was not specified"); } } }
2,267
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
JavaLoggerImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/logging/backend/impl/JavaLoggerImpl.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.logging.backend.impl; import com.discordsrv.common.logging.LogAppender; import com.discordsrv.common.logging.LogLevel; import com.discordsrv.common.logging.Logger; import com.discordsrv.common.logging.backend.LogFilter; import com.discordsrv.common.logging.backend.LoggingBackend; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.logging.Filter; import java.util.logging.Handler; import java.util.logging.Level; import java.util.logging.LogRecord; public class JavaLoggerImpl implements Logger, LoggingBackend { private static final Map<Level, LogLevel> LEVELS = new HashMap<>(); private static final Map<LogLevel, Level> LEVELS_REVERSE = new HashMap<>(); private static void put(Level level, LogLevel logLevel) { LEVELS.put(level, logLevel); LEVELS_REVERSE.put(logLevel, level); } static { put(Level.INFO, LogLevel.INFO); put(Level.WARNING, LogLevel.WARNING); put(Level.SEVERE, LogLevel.ERROR); } private final java.util.logging.Logger logger; private final Map<LogAppender, HandlerImpl> appenders = new HashMap<>(); private FilterProxy filterProxy; public static JavaLoggerImpl getRoot() { return new JavaLoggerImpl(java.util.logging.Logger.getLogger("")); } public JavaLoggerImpl(java.util.logging.Logger logger) { this.logger = logger; } @Override public void log(@Nullable String loggerName, @NotNull LogLevel level, @Nullable String message, @Nullable Throwable throwable) { Level logLevel = LEVELS_REVERSE.get(level); if (logLevel != null) { List<String> contents = new ArrayList<>(2); if (message != null) { contents.add(message); } if (throwable != null) { // Exceptions aren't always logged correctly by the logger itself contents.add(getStackTrace(throwable)); } logger.log(logLevel, String.join("\n", contents)); } } @Override public boolean addFilter(LogFilter filter) { if (filterProxy == null) { // The Java logger only allows for *one* filter, // so we're going to proxy it in case somebody else is using it filterProxy = new FilterProxy(logger.getFilter()); logger.setFilter(filterProxy); } return filterProxy.filters.add(filter); } @Override public boolean removeFilter(LogFilter filter) { if (filterProxy == null) { return false; } List<LogFilter> filters = filterProxy.filters; boolean success = filters.remove(filter); Filter currentFilter = logger.getFilter(); if (filters.isEmpty() && currentFilter == filterProxy) { // If we don't have any filters, and the current filter is our proxy, // change the filter back to what it was before & discard the proxy logger.setFilter(filterProxy.parent); filterProxy = null; } return success; } @Override public boolean addAppender(LogAppender appender) { HandlerImpl handler = new HandlerImpl(appender); appenders.put(appender, handler); logger.addHandler(handler); return true; } @Override public boolean removeAppender(LogAppender appender) { HandlerImpl handler = appenders.get(appender); if (handler != null) { logger.removeHandler(handler); return true; } return false; } private static class FilterProxy implements Filter { private final Filter parent; protected final List<LogFilter> filters = new ArrayList<>(); public FilterProxy(Filter parent) { this.parent = parent; } @Override public boolean isLoggable(LogRecord record) { if (filters.isEmpty()) { return true; } Level level = record.getLevel(); LogLevel logLevel = LEVELS.computeIfAbsent(level, key -> LogLevel.of(key.getName())); String message = record.getMessage(); Throwable throwable = record.getThrown(); for (LogFilter filter : filters) { LogFilter.Result result = filter.filter(record.getLoggerName(), logLevel, message, throwable); if (result == LogFilter.Result.BLOCK) { return false; } else if (result == LogFilter.Result.ACCEPT) { return true; } } return parent == null || parent.isLoggable(record); } } private static class HandlerImpl extends Handler { private final LogAppender appender; public HandlerImpl(LogAppender appender) { this.appender = appender; } @Override public void publish(LogRecord record) { Level level = record.getLevel(); LogLevel logLevel = LEVELS.computeIfAbsent(level, key -> LogLevel.of(key.getName())); appender.append(record.getLoggerName(), logLevel, record.getMessage(), record.getThrown()); } @Override public void flush() {} @Override public void close() throws SecurityException {} } }
6,336
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
Log4JLoggerImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/logging/backend/impl/Log4JLoggerImpl.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.logging.backend.impl; import com.discordsrv.common.logging.LogAppender; import com.discordsrv.common.logging.LogLevel; import com.discordsrv.common.logging.Logger; import com.discordsrv.common.logging.backend.LogFilter; import com.discordsrv.common.logging.backend.LoggingBackend; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Marker; import org.apache.logging.log4j.core.Appender; import org.apache.logging.log4j.core.Filter; import org.apache.logging.log4j.core.LogEvent; import org.apache.logging.log4j.core.appender.AbstractAppender; import org.apache.logging.log4j.message.Message; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.lang.reflect.Field; import java.util.HashMap; import java.util.Map; public class Log4JLoggerImpl implements Logger, LoggingBackend { private static final Map<Level, LogLevel> LEVELS = new HashMap<>(); private static final Map<LogLevel, Level> LEVELS_REVERSE = new HashMap<>(); private static void put(Level level, LogLevel logLevel) { LEVELS.put(level, logLevel); LEVELS_REVERSE.put(logLevel, level); } static { put(Level.INFO, LogLevel.INFO); put(Level.WARN, LogLevel.WARNING); put(Level.ERROR, LogLevel.ERROR); put(Level.DEBUG, LogLevel.DEBUG); put(Level.TRACE, LogLevel.TRACE); } private final org.apache.logging.log4j.Logger logger; private final Map<LogFilter, Filter> filters = new HashMap<>(); private final Map<LogAppender, Appender> appenders = new HashMap<>(); public static Log4JLoggerImpl getRoot() { return new Log4JLoggerImpl(LogManager.getRootLogger()); } public Log4JLoggerImpl(org.apache.logging.log4j.Logger logger) { this.logger = logger; } @Override public void log(@Nullable String loggerName, @NotNull LogLevel level, @Nullable String message, @Nullable Throwable throwable) { Level logLevel = LEVELS_REVERSE.get(level); logger.log(logLevel, message, throwable); } @Override public boolean addFilter(LogFilter filter) { if (logger instanceof org.apache.logging.log4j.core.Logger) { org.apache.logging.log4j.core.Logger loggerImpl = (org.apache.logging.log4j.core.Logger) logger; Log4jFilter log4jFilter = new Log4jFilter(filter); loggerImpl.addFilter(log4jFilter); filters.put(filter, log4jFilter); return true; } return false; } @Override public boolean removeFilter(LogFilter filter) { if (logger instanceof org.apache.logging.log4j.core.Logger) { // A simple little workaround for removing filters try { Field configField = null; Class<?> targetClass = logger.getClass(); // Get a field named config or privateConfig from the logger class or any of it's super classes while (targetClass != null) { try { configField = targetClass.getDeclaredField("config"); break; } catch (NoSuchFieldException ignored) {} try { configField = targetClass.getDeclaredField("privateConfig"); break; } catch (NoSuchFieldException ignored) {} targetClass = targetClass.getSuperclass(); } if (configField != null) { configField.setAccessible(true); Object config = configField.get(logger); Field configField2 = config.getClass().getDeclaredField("config"); configField2.setAccessible(true); Object config2 = configField2.get(config); if (config2 instanceof org.apache.logging.log4j.core.filter.Filterable) { Filter log4jFilter = filters.remove(filter); if (log4jFilter != null) { ((org.apache.logging.log4j.core.filter.Filterable) config2) .removeFilter(log4jFilter); return true; } } } } catch (Throwable t) { throw new RuntimeException("Failed to remove filter", t); } } return false; } @Override public boolean addAppender(LogAppender appender) { if (logger instanceof org.apache.logging.log4j.core.Logger) { org.apache.logging.log4j.core.Logger loggerImpl = (org.apache.logging.log4j.core.Logger) logger; Appender log4jAppender = new Log4jAppender(appender); loggerImpl.addAppender(log4jAppender); appenders.put(appender, log4jAppender); return true; } return false; } @Override public boolean removeAppender(LogAppender appender) { if (logger instanceof org.apache.logging.log4j.core.Logger) { org.apache.logging.log4j.core.Logger loggerImpl = (org.apache.logging.log4j.core.Logger) logger; Appender log4jAppender = appenders.remove(appender); loggerImpl.removeAppender(log4jAppender); return true; } return false; } private static class Log4jFilter implements Filter { private final LogFilter filter; public Log4jFilter(LogFilter filter) { this.filter = filter; } @Override public Result getOnMismatch() { return Result.NEUTRAL; } @Override public Result getOnMatch() { return Result.NEUTRAL; } @Override public Result filter(org.apache.logging.log4j.core.Logger logger, Level level, Marker marker, String msg, Object... params) { return filter( logger.getName(), level, msg, null ); } @Override public Result filter(org.apache.logging.log4j.core.Logger logger, Level level, Marker marker, Object msg, Throwable t) { return filter( logger.getName(), level, msg.toString(), t ); } @Override public Result filter(org.apache.logging.log4j.core.Logger logger, Level level, Marker marker, Message msg, Throwable t) { return filter( logger.getName(), level, msg.getFormattedMessage(), t ); } @Override public Result filter(LogEvent event) { return filter( event.getLoggerName(), event.getLevel(), event.getMessage().getFormattedMessage(), event.getThrown() ); } private Result filter(String loggerName, Level level, String message, Throwable throwable) { LogLevel logLevel = LEVELS.computeIfAbsent(level, key -> LogLevel.of(key.name())); LogFilter.Result result = filter.filter(loggerName, logLevel, message, throwable); switch (result) { case BLOCK: return Result.DENY; case ACCEPT: return Result.ACCEPT; default: case IGNORE: return Result.NEUTRAL; } } } private static class Log4jAppender extends AbstractAppender { private final LogAppender appender; protected Log4jAppender(LogAppender appender) { super("DiscordSRV Appender", null, null, false); this.appender = appender; } @Override public boolean isStarted() { return true; } @Override public void append(LogEvent event) { LogLevel level = LEVELS.computeIfAbsent(event.getLevel(), key -> LogLevel.of(key.name())); appender.append(event.getLoggerName(), level, event.getMessage().getFormattedMessage(), event.getThrown()); } } }
9,174
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordConnectionManager.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/connection/DiscordConnectionManager.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.discord.connection; import net.dv8tion.jda.api.JDA; import org.jetbrains.annotations.Nullable; import java.util.concurrent.CompletableFuture; import java.util.concurrent.TimeUnit; public interface DiscordConnectionManager { /** * The default amount of milliseconds to wait for shutdown before ending without completing rate limited requests. */ long DEFAULT_SHUTDOWN_TIMEOUT = TimeUnit.SECONDS.toMillis(10); /** * Gets the instance. * @return the jda instance, if connected */ @Nullable JDA instance(); /** * Attempts to connect to Discord. * @return a {@link CompletableFuture} */ CompletableFuture<Void> connect(); /** * Shuts down the Discord connection and connects again. * @return a {@link CompletableFuture} */ CompletableFuture<Void> reconnect(); /** * Shuts down the Discord connection after waiting for queued requests to complete. Blocks until shutdown is completed. * @return a {@link CompletableFuture} * @see #DEFAULT_SHUTDOWN_TIMEOUT */ default CompletableFuture<Void> shutdown() { return shutdown(DEFAULT_SHUTDOWN_TIMEOUT); } /** * Shuts down the Discord connection after waiting for queued requests to complete. * Waits the provided amount of milliseconds before running {@link #shutdownNow()}. * * @param timeoutMillis the maximum amount of milliseconds to wait for shut down * @return a {@link CompletableFuture} */ CompletableFuture<Void> shutdown(long timeoutMillis); /** * Shuts down the Discord connection without waiting for queued requests to be completed. */ void shutdownNow(); }
2,565
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordConnectionDetailsImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/connection/details/DiscordConnectionDetailsImpl.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.discord.connection.details; import com.discordsrv.api.discord.connection.details.DiscordCacheFlag; import com.discordsrv.api.discord.connection.details.DiscordConnectionDetails; import com.discordsrv.api.discord.connection.details.DiscordGatewayIntent; import com.discordsrv.api.discord.connection.details.DiscordMemberCachePolicy; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.exception.util.ExceptionUtil; import org.jetbrains.annotations.NotNull; import java.util.*; public class DiscordConnectionDetailsImpl implements DiscordConnectionDetails { private final DiscordSRV discordSRV; private final Set<DiscordGatewayIntent> gatewayIntents = new HashSet<>(); private final Set<DiscordCacheFlag> cacheFlags = new HashSet<>(); private final Set<DiscordMemberCachePolicy> memberCachePolicies = new HashSet<>(); public DiscordConnectionDetailsImpl(DiscordSRV discordSRV) { this.discordSRV = discordSRV; this.memberCachePolicies.add(DiscordMemberCachePolicy.OWNER); } private boolean isStatus() { return discordSRV.status() == DiscordSRV.Status.INITIALIZED || discordSRV.status() == DiscordSRV.Status.ATTEMPTING_TO_CONNECT; } public @NotNull Set<DiscordGatewayIntent> getGatewayIntents() { Set<DiscordGatewayIntent> intents = new HashSet<>(gatewayIntents); intents.addAll(discordSRV.moduleManager().requiredIntents()); return intents; } @Override public boolean requestGatewayIntent(@NotNull DiscordGatewayIntent gatewayIntent, DiscordGatewayIntent... gatewayIntents) { List<DiscordGatewayIntent> intents = new ArrayList<>(Collections.singleton(gatewayIntent)); intents.addAll(Arrays.asList(gatewayIntents)); this.gatewayIntents.addAll(intents); return isStatus(); } public @NotNull Set<DiscordCacheFlag> getCacheFlags() { Set<DiscordCacheFlag> flags = new HashSet<>(cacheFlags); flags.addAll(discordSRV.moduleManager().requiredCacheFlags()); return flags; } @Override public boolean requestCacheFlag(@NotNull DiscordCacheFlag cacheFlag, DiscordCacheFlag... cacheFlags) { List<DiscordCacheFlag> flags = new ArrayList<>(Collections.singleton(cacheFlag)); flags.addAll(Arrays.asList(cacheFlags)); List<Throwable> suppressed = new ArrayList<>(); for (DiscordCacheFlag flag : flags) { DiscordGatewayIntent requiredIntent = flag.requiredIntent(); if (requiredIntent != null && !gatewayIntents.contains(requiredIntent)) { suppressed.add(ExceptionUtil.minifyException(new IllegalArgumentException("CacheFlag " + requiredIntent.name() + " requires GatewayIntent " + requiredIntent.name()))); } } if (!suppressed.isEmpty()) { IllegalArgumentException exception = new IllegalArgumentException(); suppressed.forEach(exception::addSuppressed); throw exception; } this.cacheFlags.addAll(flags); return isStatus(); } public @NotNull Set<DiscordMemberCachePolicy> getMemberCachePolicies() { Set<DiscordMemberCachePolicy> policies = new HashSet<>(memberCachePolicies); policies.addAll(discordSRV.moduleManager().requiredMemberCachePolicies()); return policies; } @Override public boolean requestMemberCachePolicy(@NotNull DiscordMemberCachePolicy memberCachePolicy, @NotNull DiscordMemberCachePolicy... memberCachePolicies) { List<DiscordMemberCachePolicy> policies = new ArrayList<>(Collections.singleton(memberCachePolicy)); policies.addAll(Arrays.asList(memberCachePolicies)); this.memberCachePolicies.addAll(policies); return isStatus(); } }
4,680
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
JDAConnectionManager.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/connection/jda/JDAConnectionManager.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.discord.connection.jda; 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.discord.connection.jda.errorresponse.ErrorCallbackContext; import com.discordsrv.api.discord.entity.DiscordUser; import com.discordsrv.api.discord.entity.guild.DiscordGuildMember; 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.api.event.events.placeholder.PlaceholderLookupEvent; import com.discordsrv.api.placeholder.PlaceholderLookupResult; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.config.connection.BotConfig; import com.discordsrv.common.config.connection.ConnectionConfig; import com.discordsrv.common.config.documentation.DocumentationURLs; import com.discordsrv.common.config.main.MemberCachingConfig; import com.discordsrv.common.debug.DebugGenerateEvent; import com.discordsrv.common.debug.file.TextDebugFile; import com.discordsrv.common.discord.api.DiscordAPIImpl; import com.discordsrv.common.discord.api.entity.message.ReceivedDiscordMessageImpl; import com.discordsrv.common.discord.connection.DiscordConnectionManager; import com.discordsrv.common.discord.connection.details.DiscordConnectionDetailsImpl; import com.discordsrv.common.logging.Logger; import com.discordsrv.common.logging.NamedLogger; import com.discordsrv.common.scheduler.Scheduler; import com.discordsrv.common.scheduler.threadfactory.CountingThreadFactory; import com.discordsrv.common.time.util.Timeout; import com.neovisionaries.ws.client.WebSocketFactory; import com.neovisionaries.ws.client.WebSocketFrame; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.entities.*; import net.dv8tion.jda.api.entities.channel.concrete.*; import net.dv8tion.jda.api.events.StatusChangeEvent; import net.dv8tion.jda.api.events.session.SessionDisconnectEvent; import net.dv8tion.jda.api.events.session.ShutdownEvent; import net.dv8tion.jda.api.exceptions.ErrorResponseException; import net.dv8tion.jda.api.exceptions.InvalidTokenException; import net.dv8tion.jda.api.exceptions.RateLimitedException; import net.dv8tion.jda.api.requests.*; import net.dv8tion.jda.api.utils.ChunkingFilter; import net.dv8tion.jda.api.utils.cache.CacheFlag; import net.dv8tion.jda.api.utils.messages.MessageRequest; import net.dv8tion.jda.internal.entities.ReceivedMessage; import net.dv8tion.jda.internal.hooks.EventManagerProxy; import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.exception.ExceptionUtils; import org.jetbrains.annotations.NotNull; import java.io.InterruptedIOException; import java.time.Duration; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicReference; import java.util.function.Consumer; public class JDAConnectionManager implements DiscordConnectionManager { private final DiscordSRV discordSRV; private final FailureCallback failureCallback; private Future<?> failureCallbackFuture; private ScheduledExecutorService gatewayPool; private ScheduledExecutorService rateLimitSchedulerPool; private ExecutorService rateLimitElasticPool; private CompletableFuture<Void> connectionFuture; private JDA instance; // Currently used intents & cache flags private final Set<DiscordGatewayIntent> intents = new HashSet<>(); private final Set<DiscordCacheFlag> cacheFlags = new HashSet<>(); private final Set<DiscordMemberCachePolicy> memberCachePolicies = new HashSet<>(); // Bot owner details private final Timeout botOwnerTimeout = new Timeout(5, TimeUnit.MINUTES); private final AtomicReference<CompletableFuture<DiscordUser>> botOwnerRequest = new AtomicReference<>(); // Logging timeouts private final Timeout mfaTimeout = new Timeout(30, TimeUnit.SECONDS); private final Timeout serverErrorTimeout = new Timeout(20, TimeUnit.SECONDS); public JDAConnectionManager(DiscordSRV discordSRV) { this.discordSRV = discordSRV; this.failureCallback = new FailureCallback(new NamedLogger(discordSRV, "DISCORD_REQUESTS")); // Default failure callback RestAction.setDefaultFailure(failureCallback); // Disable all mentions by default for safety MessageRequest.setDefaultMentions(Collections.emptyList()); // Disable this warning (that doesn't even have a stacktrace) Message.suppressContentIntentWarning(); discordSRV.eventBus().subscribe(this); } public Set<DiscordGatewayIntent> getIntents() { return intents; } public Set<DiscordCacheFlag> getCacheFlags() { return cacheFlags; } public Set<DiscordMemberCachePolicy> getMemberCachePolicies() { return memberCachePolicies; } @Override public JDA instance() { return instance; } private void checkDefaultFailureCallback() { Consumer<? super Throwable> defaultFailure = RestAction.getDefaultFailure(); if (defaultFailure != failureCallback) { discordSRV.logger().error("RestAction DefaultFailure was set to " + defaultFailure.getClass().getName() + " (" + defaultFailure + ")"); discordSRV.logger().error("This is unsupported, please specify your own error handling on individual requests instead."); RestAction.setDefaultFailure(failureCallback); } } @Subscribe public void onStatusChange(StatusChangeEvent event) { DiscordSRV.Status currentStatus = discordSRV.status(); if (currentStatus.isShutdown() || currentStatus.isStartupError()) { // Don't change the status if it's shutdown or failed to start return; } JDA.Status status = event.getNewStatus(); int ordinal = status.ordinal(); DiscordSRV.Status newStatus; if (ordinal < JDA.Status.CONNECTED.ordinal()) { newStatus = DiscordSRV.Status.ATTEMPTING_TO_CONNECT; } else if (status == JDA.Status.DISCONNECTED || ordinal >= JDA.Status.SHUTTING_DOWN.ordinal()) { newStatus = DiscordSRV.Status.FAILED_TO_CONNECT; } else { newStatus = DiscordSRV.Status.CONNECTED; } discordSRV.setStatus(newStatus); } /** * Returns the bot owner as a {@link DiscordUser} or {@code null} within 10 seconds. * The owner will be cached for 5 minutes, if available it will be passed to the consumer instantly. * @param botOwnerConsumer the consumer that will be passed the bot owner or {@code null} */ private void withBotOwner(@NotNull Consumer<DiscordUser> botOwnerConsumer) { CompletableFuture<DiscordUser> request = botOwnerRequest.get(); if (request != null && !botOwnerTimeout.checkAndUpdate()) { request.whenComplete((user, t) -> botOwnerConsumer.accept(t != null ? null : user)); return; } CompletableFuture<DiscordUser> future = instance.retrieveApplicationInfo() .timeout(10, TimeUnit.SECONDS) .map(applicationInfo -> (DiscordUser) api().getUser(applicationInfo.getOwner())) .submit(); botOwnerRequest.set(future); future.whenComplete((user, t) -> botOwnerConsumer.accept(t != null ? null : user)); } private DiscordAPIImpl api() { return discordSRV.discordAPI(); } @Subscribe public void onDebugGenerate(DebugGenerateEvent event) { StringBuilder builder = new StringBuilder(); builder.append("Intents: ").append(intents); builder.append("\nCache Flags: ").append(cacheFlags); builder.append("\nMember Caching Policies: ").append(memberCachePolicies.size()); if (instance != null) { CompletableFuture<Long> restPingFuture = instance.getRestPing().timeout(5, TimeUnit.SECONDS).submit(); builder.append("\nGateway Ping: ").append(instance.getGatewayPing()).append("ms"); String restPing; try { restPing = restPingFuture.get() + "ms"; } catch (ExecutionException e) { if (e.getCause() instanceof TimeoutException) { restPing = ">5s"; } else { restPing = ExceptionUtils.getMessage(e); } } catch (Throwable t) { restPing = ExceptionUtils.getMessage(t); } builder.append("\nRest Ping: ").append(restPing); } event.addFile(new TextDebugFile("jda_connection_manager.txt", builder)); } @Subscribe(priority = EventPriority.EARLIEST) public void onPlaceholderLookup(PlaceholderLookupEvent event) { if (event.isProcessed()) { return; } // Map JDA objects to 1st party API objects Set<Object> newContext = new HashSet<>(); boolean anyConverted = false; for (Object o : event.getContexts()) { Object converted; boolean isConversion = true; if (o instanceof PrivateChannel) { converted = api().getDirectMessageChannel((PrivateChannel) o); } else if (o instanceof TextChannel) { converted = api().getTextChannel((TextChannel) o); } else if (o instanceof ThreadChannel) { converted = api().getThreadChannel((ThreadChannel) o); } else if (o instanceof VoiceChannel) { converted = api().getVoiceChannel((VoiceChannel) o); } else if (o instanceof StageChannel) { converted = api().getStageChannel((StageChannel) o); } else if (o instanceof Guild) { converted = api().getGuild((Guild) o); } else if (o instanceof Member) { converted = api().getGuildMember((Member) o); } else if (o instanceof Role) { converted = api().getRole((Role) o); } else if (o instanceof ReceivedMessage) { converted = ReceivedDiscordMessageImpl.fromJDA(discordSRV, (Message) o); } else if (o instanceof User) { converted = api().getUser((User) o); } else { converted = o; isConversion = false; } if (isConversion) { anyConverted = true; } newContext.add(converted); } // Prevent infinite recursion if (anyConverted) { event.process(PlaceholderLookupResult.newLookup(event.getPlaceholder(), newContext)); } } // // (Re)connecting & Shutting down // @Override public CompletableFuture<Void> connect() { if (connectionFuture != null && !connectionFuture.isDone()) { throw new IllegalStateException("Already connecting"); } else if (instance != null && instance.getStatus() != JDA.Status.SHUTDOWN) { throw new IllegalStateException("Cannot reconnect, still active"); } return connectionFuture = CompletableFuture.runAsync(this::connectInternal, discordSRV.scheduler().executor()); } private void connectInternal() { BotConfig botConfig = discordSRV.connectionConfig().bot; String token = botConfig.token; if (StringUtils.isBlank(token) || token.contains(" ")) { invalidToken(); return; } discordSRV.setStatus(DiscordSRVApi.Status.ATTEMPTING_TO_CONNECT); this.gatewayPool = new ScheduledThreadPoolExecutor( 1, r -> new Thread(r, Scheduler.THREAD_NAME_PREFIX + "JDA Gateway") ); this.rateLimitSchedulerPool = new ScheduledThreadPoolExecutor( 2, new CountingThreadFactory(Scheduler.THREAD_NAME_PREFIX + "JDA RateLimit Scheduler #%s") ); this.rateLimitElasticPool = new ThreadPoolExecutor( 0, 12, 60L, TimeUnit.SECONDS, new SynchronousQueue<>(), new CountingThreadFactory(Scheduler.THREAD_NAME_PREFIX + "JDA RateLimit Elastic #%s") ); this.failureCallbackFuture = discordSRV.scheduler().runAtFixedRate( this::checkDefaultFailureCallback, Duration.ofSeconds(30), Duration.ofSeconds(120) ); MemberCachingConfig memberCachingConfig = discordSRV.config().memberCaching; DiscordConnectionDetailsImpl connectionDetails = discordSRV.discordConnectionDetails(); this.intents.clear(); this.intents.addAll(connectionDetails.getGatewayIntents()); Set<CacheFlag> cacheFlags = new LinkedHashSet<>(); this.cacheFlags.clear(); this.cacheFlags.addAll(connectionDetails.getCacheFlags()); this.cacheFlags.forEach(flag -> { cacheFlags.add(flag.asJDA()); DiscordGatewayIntent intent = flag.requiredIntent(); if (intent != null) { this.intents.add(intent); } }); this.memberCachePolicies.clear(); this.memberCachePolicies.addAll(connectionDetails.getMemberCachePolicies()); if (memberCachingConfig.all || this.memberCachePolicies.contains(DiscordMemberCachePolicy.ALL)) { this.memberCachePolicies.clear(); this.memberCachePolicies.add(DiscordMemberCachePolicy.ALL); } else if (memberCachingConfig.linkedUsers) { this.memberCachePolicies.add(DiscordMemberCachePolicy.LINKED); } for (DiscordMemberCachePolicy policy : this.memberCachePolicies) { if (policy != DiscordMemberCachePolicy.OWNER && policy != DiscordMemberCachePolicy.VOICE) { this.intents.add(DiscordGatewayIntent.GUILD_MEMBERS); break; } } ChunkingFilter chunkingFilter; if (memberCachingConfig.chunk) { MemberCachingConfig.GuildFilter servers = memberCachingConfig.chunkingServerFilter; long[] ids = servers.ids.stream().mapToLong(l -> l).toArray(); if (servers.blacklist) { chunkingFilter = ChunkingFilter.exclude(ids); } else { chunkingFilter = ChunkingFilter.include(ids); } } else { chunkingFilter = ChunkingFilter.NONE; } Set<GatewayIntent> intents = new LinkedHashSet<>(); this.intents.forEach(intent -> intents.add(intent.asJDA())); // Start with everything disabled & enable stuff that we actually need JDABuilder jdaBuilder = JDABuilder.createLight(token, intents); jdaBuilder.enableCache(cacheFlags); jdaBuilder.setMemberCachePolicy(member -> { if (this.memberCachePolicies.isEmpty()) { return false; } DiscordGuildMember guildMember = api().getGuildMember(member); for (DiscordMemberCachePolicy memberCachePolicy : this.memberCachePolicies) { if (memberCachePolicy.isCached(guildMember)) { return true; } } return false; }); jdaBuilder.setChunkingFilter(chunkingFilter); // We shut down JDA ourselves. Doing it at the JVM's shutdown may cause errors due to classloading jdaBuilder.setEnableShutdownHook(false); // We don't use MDC jdaBuilder.setContextEnabled(false); // Custom event manager to forward to the DiscordSRV event bus & block using JDA's event listeners jdaBuilder.setEventManager(new EventManagerProxy(new JDAEventManager(discordSRV), discordSRV.scheduler().forkJoinPool())); // Our own (named) threads jdaBuilder.setCallbackPool(discordSRV.scheduler().forkJoinPool()); jdaBuilder.setGatewayPool(gatewayPool); jdaBuilder.setRateLimitScheduler(rateLimitSchedulerPool, true); jdaBuilder.setRateLimitElastic(rateLimitElasticPool); jdaBuilder.setHttpClient(discordSRV.httpClient()); WebSocketFactory webSocketFactory = new WebSocketFactory(); jdaBuilder.setWebsocketFactory(webSocketFactory); try { instance = jdaBuilder.build(); } catch (InvalidTokenException ignored) { invalidToken(); } catch (Throwable t) { discordSRV.logger().error("Could not create JDA instance due to an unknown error", t); } } @Override public CompletableFuture<Void> reconnect() { return CompletableFuture.runAsync(() -> { shutdown().join(); connect().join(); }, discordSRV.scheduler().executor()); } @Subscribe(priority = EventPriority.LATE) public void onDSRVShuttingDown(DiscordSRVShuttingDownEvent event) { // This has a timeout shutdown().join(); } @Override public CompletableFuture<Void> shutdown(long timeoutMillis) { return CompletableFuture.runAsync(() -> shutdownInternal(timeoutMillis), discordSRV.scheduler().executor()); } @SuppressWarnings("BusyWait") private void shutdownInternal(long timeoutMillis) { if (instance == null) { shutdownExecutors(); return; } instance.shutdown(); try { discordSRV.logger().info("Waiting up to " + TimeUnit.MILLISECONDS.toSeconds(timeoutMillis) + " seconds for JDA to shutdown..."); discordSRV.scheduler().run(() -> { try { while (instance != null && !rateLimitSchedulerPool.isShutdown()) { Thread.sleep(50); } } catch (InterruptedException ignored) {} }).get(timeoutMillis, TimeUnit.MILLISECONDS); instance = null; shutdownExecutors(); discordSRV.logger().info("JDA shutdown completed."); } catch (TimeoutException | ExecutionException e) { try { discordSRV.logger().info("JDA failed to shutdown within the timeout, cancelling any remaining requests"); shutdownNow(); } catch (Throwable t) { if (e instanceof ExecutionException) { t.addSuppressed(e.getCause()); } discordSRV.logger().error("Failed to shutdown JDA", t); } } catch (InterruptedException ignored) {} } @Override public void shutdownNow() { if (instance != null) { instance.shutdownNow(); instance = null; } shutdownExecutors(); discordSRV.logger().info("JDA shutdown completed."); } private void shutdownExecutors() { if (gatewayPool != null) { gatewayPool.shutdownNow(); } if (rateLimitSchedulerPool != null && !rateLimitSchedulerPool.isShutdown()) { rateLimitSchedulerPool.shutdownNow(); } if (rateLimitElasticPool != null) { rateLimitElasticPool.shutdownNow(); } if (failureCallbackFuture != null) { failureCallbackFuture.cancel(false); } } // // Logging // @Subscribe public void onShutdown(ShutdownEvent event) { checkCode(event.getCloseCode()); } @Subscribe public void onDisconnect(SessionDisconnectEvent event) { CloseCode closeCode = event.getCloseCode(); if (checkCode(closeCode)) { return; } boolean closedByServer = event.isClosedByServer(); WebSocketFrame frame = closedByServer ? event.getServiceCloseFrame() : event.getClientCloseFrame(); if (frame == null) { throw new IllegalStateException("Could not get the close frame for a disconnect"); } String message; if (closedByServer) { String closeReason = frame.getCloseReason(); message = "[JDA] [Server] Disconnected due to " + frame.getCloseCode() + ": " + (closeCode != null ? closeCode.getMeaning() : (closeReason != null ? closeReason : "(Unknown close reason)")); } else { message = "[JDA] [Client] Disconnected due to " + frame.getCloseCode() + ": " + frame.getCloseReason(); } if (closeCode != null && !closeCode.isReconnect()) { discordSRV.logger().error(message); } else { discordSRV.logger().debug(message); } } private boolean checkCode(CloseCode closeCode) { if (closeCode == null) { return false; } else if (closeCode == CloseCode.DISALLOWED_INTENTS) { discordSRV.logger().error("+-------------------------------------->"); discordSRV.logger().error("| Failed to connect to Discord:"); discordSRV.logger().error("|"); discordSRV.logger().error("| The Discord bot is lacking one or more"); discordSRV.logger().error("| privileged intents listed below"); discordSRV.logger().error("|"); for (DiscordGatewayIntent intent : intents) { if (!intent.privileged()) { continue; } String displayName = intent.portalName(); discordSRV.logger().error("| " + displayName); } discordSRV.logger().error("|"); discordSRV.logger().error("| Instructions for enabling privileged gateway intents:"); discordSRV.logger().error("| 1. Go to https://discord.com/developers/applications"); discordSRV.logger().error("| 2. Choose the bot you are using for DiscordSRV"); discordSRV.logger().error("| - Keep in mind it will only be visible to the "); discordSRV.logger().error("| Discord user who created the bot"); discordSRV.logger().error("| 3. Go to the \"Bot\" tab"); discordSRV.logger().error("| 4. Make sure the intents listed above are all enabled"); discordSRV.logger().error("| 5. Run the \"/discordsrv reload config discord_connection\" command"); discordSRV.logger().error("+-------------------------------------->"); discordSRV.setStatus(DiscordSRVApi.Status.FAILED_TO_CONNECT); return true; } else if (closeCode == CloseCode.AUTHENTICATION_FAILED) { invalidToken(); return true; } return false; } private void invalidToken() { discordSRV.logger().error("+------------------------------>"); discordSRV.logger().error("| Failed to connect to Discord:"); discordSRV.logger().error("|"); discordSRV.logger().error("| The token provided in the"); discordSRV.logger().error("| " + ConnectionConfig.FILE_NAME + " is invalid"); discordSRV.logger().error("|"); discordSRV.logger().error("| Haven't created a bot yet? Installing the plugin for the first time?"); discordSRV.logger().error("| See " + DocumentationURLs.CREATE_TOKEN); discordSRV.logger().error("|"); discordSRV.logger().error("| Already have a bot? You can get the token for your bot from:"); discordSRV.logger().error("| https://discord.com/developers/applications"); discordSRV.logger().error("| by selecting the application, going to the \"Bot\" tab"); discordSRV.logger().error("| and clicking on \"Reset Token\""); discordSRV.logger().error("| - Keep in mind the bot is only visible to"); discordSRV.logger().error("| the Discord user that created the bot"); discordSRV.logger().error("|"); discordSRV.logger().error("| Once the token is corrected in the " + ConnectionConfig.FILE_NAME); discordSRV.logger().error("| Run the \"/discordsrv reload config discord_connection\" command"); discordSRV.logger().error("+------------------------------>"); discordSRV.setStatus(DiscordSRVApi.Status.FAILED_TO_CONNECT); } private class FailureCallback implements Consumer<Throwable> { private final Logger logger; protected FailureCallback(Logger logger) { this.logger = logger; } @Override public void accept(Throwable t) { if (t instanceof ErrorCallbackContext.Exception) { accept(t.getMessage(), t.getCause()); } else { accept(null, t); } } public void accept(String context, Throwable t) { if ((t instanceof InterruptedIOException || t instanceof InterruptedException) && discordSRV.status().isShutdown()) { // Ignore interrupted exceptions when DiscordSRV is shutting down or shutdown return; } boolean cancelled; if ((cancelled = t instanceof CancellationException) || t instanceof TimeoutException) { // Cancelling/timing out requests is always intentional logger.debug("A request " + (cancelled ? "was cancelled" : "timed out"), t.getCause()); } else if (t instanceof RateLimitedException) { // Log route & retry after on warn & context on debug RateLimitedException exception = ((RateLimitedException) t); discordSRV.logger().warning("A request on route " + exception.getRateLimitedRoute() + " was rate-limited for " + exception.getRetryAfter() + "ms"); logger.debug(exception.getCause()); } else if (t instanceof ErrorResponseException) { ErrorResponseException exception = (ErrorResponseException) t; if (exception.getErrorCode() == Response.ERROR_CODE) { // There is no response due to a client error Throwable cause = exception.getCause(); if (cause != null) { // Run the cause through this method again accept(context, cause); } else { logger.error((context != null ? context + ": " : "") + "Failed to complete request for a unknown reason", exception); } return; } ErrorResponse response = exception.getErrorResponse(); switch (response) { case MFA_NOT_ENABLED: { if (!mfaTimeout.checkAndUpdate()) { return; } withBotOwner(user -> { discordSRV.logger().error("+----------------------------------------------->"); discordSRV.logger().error("| Failed to complete a request:"); discordSRV.logger().error("|"); discordSRV.logger().error("| The Discord bot's owner needs to enable 2FA"); discordSRV.logger().error("| on their Discord account due to a Discord"); discordSRV.logger().error("| server requiring 2FA for moderation actions"); if (user != null) { discordSRV.logger().error("|"); discordSRV.logger().error("| The Discord bot's owner is " + user.getUsername() + " (" + user.getId() + ")"); } discordSRV.logger().error("|"); discordSRV.logger().error("| You can view instructions for enabling 2FA here:"); discordSRV.logger().error("| https://support.discord.com/hc/en-us/articles/219576828-Setting-up-Two-Factor-Authentication"); discordSRV.logger().error("+----------------------------------------------->"); }); return; } case SERVER_ERROR: { if (serverErrorTimeout.checkAndUpdate()) { discordSRV.logger().error("+--------------------------------------------------------------->"); discordSRV.logger().error("| Failed to complete a request:"); discordSRV.logger().error("|"); discordSRV.logger().error("| Discord sent a server error (HTTP 500) as a response."); discordSRV.logger().error("| This is usually caused by a outage (https://discordstatus.com)"); discordSRV.logger().error("| and will stop happening once Discord stabilizes"); discordSRV.logger().error("+--------------------------------------------------------------->"); } else { // Log as debug as to not spam out the server console/log logger.debug("Failed to complete a request, Discord returned a server error (HTTP 500)"); } // Log context to find what made the request logger.debug(exception.getCause()); return; } default: break; } logger.error((context != null ? context : "Failed to complete a request") + ": " + response.getMeaning()); logger.debug(exception); } else { logger.error(context != null ? context : "Failed to complete a request due to unknown error", t); } } } }
31,075
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
JDAEventManager.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/connection/jda/JDAEventManager.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.discord.connection.jda; import com.discordsrv.common.DiscordSRV; import net.dv8tion.jda.api.events.GenericEvent; import net.dv8tion.jda.api.hooks.IEventManager; import org.jetbrains.annotations.NotNull; import java.util.List; public class JDAEventManager implements IEventManager { private final DiscordSRV discordSRV; public JDAEventManager(DiscordSRV discordSRV) { this.discordSRV = discordSRV; } @SuppressWarnings("UnusedReturnValue") private <T> T illegalUse() { throw new RuntimeException("The JDA event manager may not be used while using DiscordSRV. " + "Please use DiscordSRV's own event bus to listen for JDA events"); } @Override public void register(@NotNull Object listener) { illegalUse(); } @Override public void unregister(@NotNull Object listener) { illegalUse(); } @Override public void handle(@NotNull GenericEvent event) { discordSRV.eventBus().publish(event); } @NotNull @Override public List<Object> getRegisteredListeners() { return illegalUse(); } }
2,010
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ThreadChannelLookup.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/ThreadChannelLookup.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.discord.api; import com.discordsrv.api.discord.entity.channel.DiscordThreadChannel; import java.util.List; import java.util.concurrent.CompletableFuture; public class ThreadChannelLookup { private final long channelId; private final boolean privateThreads; private final CompletableFuture<List<DiscordThreadChannel>> future; private final CompletableFuture<DiscordThreadChannel> channelFuture = new CompletableFuture<>(); public ThreadChannelLookup(long channelId, boolean privateThreads, CompletableFuture<List<DiscordThreadChannel>> future) { this.channelId = channelId; this.privateThreads = privateThreads; this.future = future; } public long getChannelId() { return channelId; } public boolean isPrivateThreads() { return privateThreads; } public CompletableFuture<List<DiscordThreadChannel>> getFuture() { return future; } public CompletableFuture<DiscordThreadChannel> getChannelFuture() { return channelFuture; } }
1,904
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordCommandRegistry.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/DiscordCommandRegistry.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.discord.api; import com.discordsrv.api.discord.entity.JDAEntity; import com.discordsrv.api.discord.entity.interaction.command.CommandType; import com.discordsrv.api.discord.entity.interaction.command.DiscordCommand; import com.discordsrv.api.event.events.discord.interaction.command.CommandRegisterEvent; import com.discordsrv.common.DiscordSRV; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.requests.restaction.CommandListUpdateAction; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Predicate; import java.util.stream.Collectors; public class DiscordCommandRegistry { private static final Long GLOBAL_ID = -1L; private final Map<Long, Map<CommandType, Registry>> registries = new ConcurrentHashMap<>(); private final DiscordSRV discordSRV; public DiscordCommandRegistry(DiscordSRV discordSRV) { this.discordSRV = discordSRV; } public void registerCommandsFromEvent() { CommandRegisterEvent event = new CommandRegisterEvent(); discordSRV.eventBus().publish(event); List<DiscordCommand> commands = event.getCommands(); for (Map<CommandType, Registry> registryMap : registries.values()) { registryMap.values().forEach(registry -> registry.removeIf(reg -> reg.isTemporary() && !commands.contains(reg.getCommand()))); } commands.forEach(cmd -> register(cmd, true)); } public DiscordCommand.RegistrationResult register(DiscordCommand command, boolean temporary) { CommandType type = command.getType(); Long guildId = command.getGuildId(); Registry registry = registries .computeIfAbsent(guildId != null ? guildId : GLOBAL_ID, key -> new EnumMap<>(CommandType.class)) .computeIfAbsent(type, key -> new Registry()); if (registry.contains(command)) { return DiscordCommand.RegistrationResult.ALREADY_REGISTERED; } boolean first = registry.register(command, temporary); if (!first) { return DiscordCommand.RegistrationResult.NAME_ALREADY_IN_USE; } if (registry.getInTimeOrder().indexOf(command) >= type.getMaximumCount()) { return DiscordCommand.RegistrationResult.TOO_MANY_COMMANDS; } return DiscordCommand.RegistrationResult.REGISTERED; } public void unregister(DiscordCommand command) { Long guildId = command.getGuildId(); Registry registry = registries .computeIfAbsent(guildId != null ? guildId : GLOBAL_ID, key -> Collections.emptyMap()) .get(command.getType()); if (registry != null) { registry.unregister(command); } } @Nullable public DiscordCommand getActive(Long guildId, CommandType type, String name) { Registry registry = registries .computeIfAbsent(guildId != null ? guildId : GLOBAL_ID, key -> Collections.emptyMap()) .get(type); if (registry == null) { return null; } return registry.getActive(name); } public void registerCommandsToDiscord() { JDA jda = discordSRV.jda(); if (jda == null) { return; } List<Long> ids = new ArrayList<>(); ids.add(GLOBAL_ID); for (Guild guild : jda.getGuilds()) { ids.add(guild.getIdLong()); } for (long guildId : ids) { Map<CommandType, Registry> commandsByType = registries.getOrDefault(guildId, Collections.emptyMap()); Map<CommandType, Set<DiscordCommand>> commandsToRegister = new EnumMap<>(CommandType.class); boolean updateNeeded = false; for (Map.Entry<CommandType, Registry> entry : commandsByType.entrySet()) { Registry registry = entry.getValue(); List<DiscordCommand> commands = registry.getInTimeOrder(); Set<DiscordCommand> currentCommands = new LinkedHashSet<>(); int max = Math.min(commands.size(), entry.getKey().getMaximumCount()); for (int i = 0; i < max; i++) { DiscordCommand command = commands.get(i); currentCommands.add(command); } commandsToRegister.put(entry.getKey(), currentCommands); Collection<DiscordCommand> activeCommands = registry.activeCommands.values(); if (activeCommands.size() != currentCommands.size() || !currentCommands.containsAll(activeCommands)) { updateNeeded = true; } } if (updateNeeded) { CommandListUpdateAction action; if (Objects.equals(guildId, GLOBAL_ID)) { action = jda.updateCommands(); } else { Guild guild = jda.getGuildById(guildId); if (guild == null) { continue; } action = guild.updateCommands(); } List<DiscordCommand> allCommands = new ArrayList<>(); commandsToRegister.values().forEach(allCommands::addAll); action.addCommands(allCommands.stream().map(JDAEntity::asJDA).collect(Collectors.toList())) .queue(v -> { for (CommandType value : CommandType.values()) { Registry registry = commandsByType.get(value); if (registry != null) { registry.putActiveCommands(commandsToRegister.get(value)); } } }); } } } private static class Registry { private final Map<String, List<Registration>> registry = new ConcurrentHashMap<>(); private final Map<String, DiscordCommand> activeCommands = new HashMap<>(); public void removeIf(Predicate<Registration> commandPredicate) { List<String> removeKeys = new ArrayList<>(); for (Map.Entry<String, List<Registration>> entry : registry.entrySet()) { List<Registration> registrations = entry.getValue(); registrations.removeIf(commandPredicate); if (registrations.isEmpty()) { removeKeys.add(entry.getKey()); } } removeKeys.forEach(registry::remove); } public boolean contains(@NotNull DiscordCommand command) { List<Registration> commands = registry.get(command.getName()); if (commands == null) { return false; } return commands.stream().anyMatch(reg -> reg.getCommand() == command); } public boolean register(@NotNull DiscordCommand command, boolean temporary) { List<Registration> commands = registry.computeIfAbsent(command.getName(), key -> new CopyOnWriteArrayList<>()); boolean empty = commands.isEmpty(); commands.add(new Registration(command, temporary)); return empty; } public void unregister(@NotNull DiscordCommand command) { List<Registration> commands = registry.get(command.getName()); if (commands == null) { return; } commands.removeIf(reg -> reg.command == command); if (commands.isEmpty()) { registry.remove(command.getName()); } } public void putActiveCommands(Set<DiscordCommand> commands) { synchronized (activeCommands) { activeCommands.clear(); for (DiscordCommand command : commands) { activeCommands.put(command.getName(), command); } } } public List<DiscordCommand> getInTimeOrder() { List<Registration> registrations = registry.values().stream() .map(list -> list.get(0)) .collect(Collectors.toList()); return registrations.stream() .sorted(Comparator.comparingLong(Registration::getTime)) .map(Registration::getCommand) .collect(Collectors.toList()); } @Nullable public DiscordCommand getActive(String name) { synchronized (activeCommands) { return activeCommands.get(name); } } } private static class Registration { private final DiscordCommand command; private final long time; private final boolean temporary; public Registration(DiscordCommand command, boolean temporary) { this.command = command; this.time = System.currentTimeMillis(); this.temporary = temporary; } public DiscordCommand getCommand() { return command; } public long getTime() { return time; } public boolean isTemporary() { return temporary; } } }
10,257
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordAPIImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/DiscordAPIImpl.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.discord.api; import com.discordsrv.api.discord.DiscordAPI; import com.discordsrv.api.discord.connection.details.DiscordGatewayIntent; import com.discordsrv.api.discord.connection.jda.errorresponse.ErrorCallbackContext; import com.discordsrv.api.discord.entity.DiscordUser; import com.discordsrv.api.discord.entity.channel.*; import com.discordsrv.api.discord.entity.guild.DiscordCustomEmoji; import com.discordsrv.api.discord.entity.guild.DiscordGuild; import com.discordsrv.api.discord.entity.guild.DiscordRole; import com.discordsrv.api.discord.entity.interaction.command.CommandType; import com.discordsrv.api.discord.entity.interaction.command.DiscordCommand; import com.discordsrv.api.discord.exception.NotReadyException; import com.discordsrv.api.discord.exception.RestErrorResponseException; import com.discordsrv.common.DiscordSRV; 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.DestinationConfig; import com.discordsrv.common.config.main.generic.ThreadConfig; import com.discordsrv.common.discord.api.entity.DiscordUserImpl; import com.discordsrv.common.discord.api.entity.channel.*; import com.discordsrv.common.discord.api.entity.guild.DiscordCustomEmojiImpl; import com.discordsrv.common.discord.api.entity.guild.DiscordGuildImpl; import com.discordsrv.common.discord.api.entity.guild.DiscordGuildMemberImpl; import com.discordsrv.common.discord.api.entity.guild.DiscordRoleImpl; import com.discordsrv.common.function.CheckedSupplier; import com.discordsrv.common.future.util.CompletableFutureUtil; import com.github.benmanes.caffeine.cache.AsyncCacheLoader; import com.github.benmanes.caffeine.cache.AsyncLoadingCache; import com.github.benmanes.caffeine.cache.Expiry; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.entities.*; import net.dv8tion.jda.api.entities.channel.Channel; import net.dv8tion.jda.api.entities.channel.concrete.*; import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel; import net.dv8tion.jda.api.entities.emoji.CustomEmoji; import net.dv8tion.jda.api.exceptions.ErrorResponseException; import net.dv8tion.jda.api.requests.ErrorResponse; import org.checkerframework.checker.index.qual.NonNegative; import org.checkerframework.checker.nullness.qual.NonNull; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.concurrent.*; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.function.Function; public class DiscordAPIImpl implements DiscordAPI { private final DiscordSRV discordSRV; private final DiscordCommandRegistry commandRegistry; private final AsyncLoadingCache<Long, WebhookClient<Message>> cachedClients; private final List<ThreadChannelLookup> threadLookups = new CopyOnWriteArrayList<>(); public DiscordAPIImpl(DiscordSRV discordSRV) { this.discordSRV = discordSRV; this.commandRegistry = new DiscordCommandRegistry(discordSRV); this.cachedClients = discordSRV.caffeineBuilder() .expireAfter(new WebhookCacheExpiry()) .buildAsync(new WebhookCacheLoader()); } public CompletableFuture<WebhookClient<Message>> queryWebhookClient(long channelId) { return cachedClients.get(channelId); } public AsyncLoadingCache<Long, WebhookClient<Message>> getCachedClients() { return cachedClients; } public <T extends BaseChannelConfig & IChannelConfig> Collection<DiscordGuildMessageChannel> findDestinations( T config, boolean log ) { return findOrCreateDestinations(config, false, log).join(); } public <T extends BaseChannelConfig & IChannelConfig> CompletableFuture<Collection<DiscordGuildMessageChannel>> findOrCreateDestinations( T config, boolean create, boolean log ) { return findOrCreateDestinations(config.destination(), config.channelLocking.threads.unarchive, create, log); } public CompletableFuture<Collection<DiscordGuildMessageChannel>> findOrCreateDestinations( DestinationConfig destination, boolean unarchive, boolean create, boolean log ) { Set<DiscordGuildMessageChannel> channels = new HashSet<>(); for (Long channelId : destination.channelIds) { DiscordMessageChannel channel = getMessageChannelById(channelId); if (!(channel instanceof DiscordGuildMessageChannel)) { continue; } synchronized (channels) { channels.add((DiscordGuildMessageChannel) channel); } } List<CompletableFuture<Void>> threadFutures = new ArrayList<>(); List<ThreadConfig> threadConfigs = destination.threads; if (threadConfigs != null && !threadConfigs.isEmpty()) { for (ThreadConfig threadConfig : threadConfigs) { long channelId = threadConfig.channelId; DiscordThreadContainer channel = getTextChannelById(channelId); if (channel == null) { channel = getForumChannelById(channelId); } if (channel == null) { if (channelId > 0 && log) { discordSRV.logger().error("Unable to find channel with ID " + Long.toUnsignedString(channelId)); } continue; } // Check if a thread by the same name is still active DiscordThreadChannel thread = findThread(threadConfig, channel.getActiveThreads()); if (thread != null) { if (!thread.isArchived()) { synchronized (channels) { channels.add(thread); } continue; } } if (!create) { continue; } CompletableFuture<DiscordThreadChannel> future; if (thread != null) { // Unarchive the thread future = new CompletableFuture<>(); unarchiveOrCreateThread(threadConfig, channel, thread, future); } else { // Find or create the thread future = findOrCreateThread(unarchive, threadConfig, channel); } DiscordThreadContainer container = channel; threadFutures.add(future.handle((threadChannel, t) -> { if (t != null) { ErrorCallbackContext.context( "Failed to deliver message to thread \"" + threadConfig.threadName + "\" in channel " + container ).accept(t); throw new RuntimeException(); // Just here to fail the future } if (threadChannel != null) { synchronized (channels) { channels.add(threadChannel); } } return null; })); } } return CompletableFutureUtil.combine(threadFutures).thenApply(v -> channels); } private DiscordThreadChannel findThread(ThreadConfig config, List<DiscordThreadChannel> threads) { for (DiscordThreadChannel thread : threads) { if (thread.getName().equals(config.threadName)) { return thread; } } return null; } private CompletableFuture<DiscordThreadChannel> findOrCreateThread(boolean unarchive, ThreadConfig threadConfig, DiscordThreadContainer container) { if (!unarchive) { return container.createThread(threadConfig.threadName, threadConfig.privateThread); } CompletableFuture<DiscordThreadChannel> completableFuture = new CompletableFuture<>(); lookupThreads( container, threadConfig.privateThread, lookup -> findOrCreateThread(threadConfig, container, lookup, completableFuture), (thread, throwable) -> { if (throwable != null) { completableFuture.completeExceptionally(throwable); } else { completableFuture.complete(thread); } }); return completableFuture; } private void findOrCreateThread( ThreadConfig config, DiscordThreadContainer container, ThreadChannelLookup lookup, CompletableFuture<DiscordThreadChannel> completableFuture ) { completableFuture.whenComplete((threadChannel, throwable) -> { CompletableFuture<DiscordThreadChannel> future = lookup.getChannelFuture(); if (throwable != null) { future.completeExceptionally(throwable); } else { future.complete(threadChannel); } }); lookup.getFuture().whenComplete((channels, throwable) -> { if (throwable != null) { completableFuture.completeExceptionally(throwable); return; } DiscordThreadChannel thread = findThread(config, channels); unarchiveOrCreateThread(config, container, thread, completableFuture); }).exceptionally(t -> { if (t instanceof CompletionException) { completableFuture.completeExceptionally(t.getCause()); return null; } completableFuture.completeExceptionally(t); return null; }); } private void unarchiveOrCreateThread( ThreadConfig config, DiscordThreadContainer container, DiscordThreadChannel thread, CompletableFuture<DiscordThreadChannel> future ) { if (thread != null) { if (thread.isLocked() || thread.isArchived()) { try { thread.asJDA() .getManager() .setArchived(false) .reason("DiscordSRV Auto Unarchive") .queue(v -> future.complete(thread), future::completeExceptionally); } catch (Throwable t) { future.completeExceptionally(t); } } else { future.complete(thread); } return; } container.createThread(config.threadName, config.privateThread).whenComplete(((threadChannel, t) -> { if (t != null) { future.completeExceptionally(t); } else { future.complete(threadChannel); } })); } public void lookupThreads( DiscordThreadContainer container, boolean privateThreads, Consumer<ThreadChannelLookup> lookupConsumer, BiConsumer<DiscordThreadChannel, Throwable> channelConsumer ) { ThreadChannelLookup lookup; synchronized (threadLookups) { for (ThreadChannelLookup threadLookup : threadLookups) { if (threadLookup.isPrivateThreads() != privateThreads || threadLookup.getChannelId() != container.getId()) { continue; } threadLookup.getChannelFuture().whenComplete(channelConsumer); return; } lookup = new ThreadChannelLookup( container.getId(), privateThreads, privateThreads ? container.retrieveArchivedPrivateThreads() : container.retrieveArchivedPublicThreads() ); threadLookups.add(lookup); } lookup.getChannelFuture().whenComplete(channelConsumer); lookupConsumer.accept(lookup); lookup.getFuture().whenComplete((channel, t) -> threadLookups.remove(lookup)); } public <T> CompletableFuture<T> mapExceptions(CheckedSupplier<CompletableFuture<T>> futureSupplier) { try { return mapExceptions(futureSupplier.get()); } catch (Throwable t) { return CompletableFutureUtil.failed(t); } } public <T> CompletableFuture<T> mapExceptions(CompletableFuture<T> future) { return future.handle((response, t) -> { if (t instanceof ErrorResponseException) { ErrorResponseException exception = (ErrorResponseException) t; int code = exception.getErrorCode(); ErrorResponse errorResponse = exception.getErrorResponse(); throw new RestErrorResponseException(code, errorResponse != null ? errorResponse.getMeaning() : "Unknown", t); } else if (t != null) { throw (RuntimeException) t; } return response; }); } public <T> CompletableFuture<T> notReady() { return CompletableFutureUtil.failed(new NotReadyException()); } @Override public @Nullable DiscordMessageChannel getMessageChannelById(long id) { DiscordTextChannel textChannel = getTextChannelById(id); if (textChannel != null) { return textChannel; } DiscordThreadChannel threadChannel = getCachedThreadChannelById(id); if (threadChannel != null) { return threadChannel; } return getDirectMessageChannelById(id); } public DiscordChannel getChannel(Channel jda) { if (jda instanceof ForumChannel) { return getForumChannel((ForumChannel) jda); } else if (jda instanceof MessageChannel) { return getMessageChannel((MessageChannel) jda); } else { throw new IllegalArgumentException("Unmappable Channel type: " + jda.getClass().getName()); } } public AbstractDiscordMessageChannel<?> getMessageChannel(MessageChannel jda) { if (jda instanceof TextChannel) { return getTextChannel((TextChannel) jda); } else if (jda instanceof ThreadChannel) { return getThreadChannel((ThreadChannel) jda); } else if (jda instanceof PrivateChannel) { return getDirectMessageChannel((PrivateChannel) jda); } else if (jda instanceof NewsChannel) { return getNewsChannel((NewsChannel) jda); } else { throw new IllegalArgumentException("Unmappable MessageChannel type: " + jda.getClass().getName()); } } private <T, J> T mapJDAEntity(Function<JDA, J> get, Function<J, T> map) { JDA jda = discordSRV.jda(); if (jda == null) { return null; } J entity = get.apply(jda); if (entity == null) { return null; } return map.apply(entity); } @Override public @Nullable DiscordDMChannel getDirectMessageChannelById(long id) { return mapJDAEntity(jda -> jda.getPrivateChannelById(id), this::getDirectMessageChannel); } public DiscordDMChannelImpl getDirectMessageChannel(PrivateChannel jda) { return new DiscordDMChannelImpl(discordSRV, jda); } @Override public @Nullable DiscordNewsChannel getNewsChannelById(long id) { return null; } public DiscordNewsChannelImpl getNewsChannel(NewsChannel jda) { return new DiscordNewsChannelImpl(discordSRV, jda); } @Override public @Nullable DiscordTextChannel getTextChannelById(long id) { return mapJDAEntity(jda -> jda.getTextChannelById(id), this::getTextChannel); } public DiscordTextChannelImpl getTextChannel(TextChannel jda) { return new DiscordTextChannelImpl(discordSRV, jda); } @Override public @Nullable DiscordForumChannel getForumChannelById(long id) { return mapJDAEntity(jda -> jda.getForumChannelById(id), this::getForumChannel); } public DiscordForumChannelImpl getForumChannel(ForumChannel jda) { return new DiscordForumChannelImpl(discordSRV, jda); } @Override public @Nullable DiscordVoiceChannel getVoiceChannelById(long id) { return mapJDAEntity(jda -> jda.getVoiceChannelById(id), this::getVoiceChannel); } public DiscordVoiceChannelImpl getVoiceChannel(VoiceChannel jda) { return new DiscordVoiceChannelImpl(discordSRV, jda); } @Override public @Nullable DiscordStageChannel getStageChannelById(long id) { return mapJDAEntity(jda -> jda.getStageChannelById(id), this::getStageChannel); } public DiscordStageChannelImpl getStageChannel(StageChannel jda) { return new DiscordStageChannelImpl(discordSRV, jda); } @Override public @Nullable DiscordThreadChannel getCachedThreadChannelById(long id) { return mapJDAEntity(jda -> jda.getThreadChannelById(id), this::getThreadChannel); } public DiscordThreadChannelImpl getThreadChannel(ThreadChannel jda) { return new DiscordThreadChannelImpl(discordSRV, jda); } @Override public @Nullable DiscordGuild getGuildById(long id) { return mapJDAEntity(jda -> jda.getGuildById(id), this::getGuild); } public DiscordGuildImpl getGuild(Guild jda) { return new DiscordGuildImpl(discordSRV, jda); } public DiscordGuildMemberImpl getGuildMember(Member jda) { return new DiscordGuildMemberImpl(discordSRV, jda); } @Override public @Nullable DiscordUser getUserById(long id) { return mapJDAEntity(jda -> jda.getUserById(id), this::getUser); } public DiscordUserImpl getUser(User jda) { return new DiscordUserImpl(discordSRV, jda); } @Override public @NotNull CompletableFuture<DiscordUser> retrieveUserById(long id) { JDA jda = discordSRV.jda(); if (jda == null) { return notReady(); } return mapExceptions( jda.retrieveUserById(id) .submit() .thenApply(this::getUser) ); } @Override public boolean isUserCachingEnabled() { return discordSRV.discordConnectionManager().getIntents() .contains(DiscordGatewayIntent.GUILD_MEMBERS); } @Override public @Nullable DiscordRole getRoleById(long id) { return mapJDAEntity(jda -> jda.getRoleById(id), this::getRole); } public DiscordRoleImpl getRole(Role jda) { return new DiscordRoleImpl(discordSRV, jda); } @Override public DiscordCustomEmoji getEmojiById(long id) { return mapJDAEntity(jda -> jda.getEmojiById(id), this::getEmoji); } public DiscordCustomEmoji getEmoji(CustomEmoji jda) { return new DiscordCustomEmojiImpl(jda); } @Override public DiscordCommand.RegistrationResult registerCommand(DiscordCommand command) { return commandRegistry.register(command, false); } @Override public void unregisterCommand(DiscordCommand command) { commandRegistry.unregister(command); } public Optional<DiscordCommand> getActiveCommand(@Nullable Guild guild, CommandType type, String name) { return Optional.ofNullable(commandRegistry.getActive(guild != null ? guild.getIdLong() : null, type, name)); } public DiscordCommandRegistry commandRegistry() { return commandRegistry; } private class WebhookCacheLoader implements AsyncCacheLoader<Long, WebhookClient<Message>> { @Override public @NonNull CompletableFuture<WebhookClient<Message>> asyncLoad(@NonNull Long channelId, @NonNull Executor executor) { JDA jda = discordSRV.jda(); if (jda == null) { return notReady(); } TextChannel textChannel = jda.getTextChannelById(channelId); if (textChannel == null) { return CompletableFutureUtil.failed(new IllegalArgumentException("Channel could not be found")); } return textChannel.retrieveWebhooks().submit().thenApply(webhooks -> { Webhook hook = null; for (Webhook webhook : webhooks) { User user = webhook.getOwnerAsUser(); if (user == null || !user.getId().equals(jda.getSelfUser().getId()) || !webhook.getName().equals("DSRV")) { continue; } hook = webhook; break; } return hook; }).thenCompose(webhook -> { if (webhook != null) { return CompletableFuture.completedFuture(webhook); } return textChannel.createWebhook("DSRV").submit(); }).thenApply(webhook -> WebhookClient.createClient( webhook.getJDA(), webhook.getId(), Objects.requireNonNull(webhook.getToken()) ) ); } } private class WebhookCacheExpiry implements Expiry<Long, WebhookClient<Message>> { private boolean isConfiguredChannel(Long channelId) { for (BaseChannelConfig config : discordSRV.config().channels.values()) { DestinationConfig destination = config instanceof IChannelConfig ? ((IChannelConfig) config).destination() : null; if (destination == null) { continue; } if (destination.channelIds.contains(channelId)) { return true; } for (ThreadConfig thread : destination.threads) { if (Objects.equals(thread.channelId, channelId)) { return true; } } } return false; } private long expireAfterWrite(Long channelId) { return isConfiguredChannel(channelId) ? Long.MAX_VALUE : TimeUnit.MINUTES.toNanos(15); } @Override public long expireAfterCreate(@NonNull Long channelId, @NonNull WebhookClient webhookClient, long currentTime) { return expireAfterWrite(channelId); } @Override public long expireAfterUpdate(@NonNull Long channelId, @NonNull WebhookClient webhookClient, long currentTime, @NonNegative long currentDuration) { return expireAfterWrite(channelId); } @Override public long expireAfterRead(@NonNull Long channelId, @NonNull WebhookClient webhookClient, long currentTime, @NonNegative long currentDuration) { return isConfiguredChannel(channelId) ? Long.MAX_VALUE : TimeUnit.MINUTES.toNanos(10); } } }
24,086
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordAPIEventModule.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/DiscordAPIEventModule.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.discord.api; 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.command.CommandType; import com.discordsrv.api.discord.entity.interaction.command.DiscordCommand; import com.discordsrv.api.discord.entity.interaction.command.SubCommandGroup; import com.discordsrv.api.discord.entity.interaction.component.ComponentIdentifier; import com.discordsrv.api.event.bus.Subscribe; import com.discordsrv.api.event.events.Event; import com.discordsrv.api.event.events.discord.interaction.DiscordModalInteractionEvent; import com.discordsrv.api.event.events.discord.interaction.command.*; import com.discordsrv.api.event.events.discord.interaction.component.DiscordButtonInteractionEvent; import com.discordsrv.api.event.events.discord.interaction.component.DiscordSelectMenuInteractionEvent; import com.discordsrv.api.event.events.discord.member.role.DiscordMemberRoleAddEvent; import com.discordsrv.api.event.events.discord.member.role.DiscordMemberRoleRemoveEvent; 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.common.DiscordSRV; import com.discordsrv.common.discord.api.entity.component.DiscordInteractionHookImpl; import com.discordsrv.common.discord.api.entity.message.ReceivedDiscordMessageImpl; import com.discordsrv.common.event.events.discord.interaction.command.DiscordChatInputInteractionEventImpl; import com.discordsrv.common.event.events.discord.interaction.command.DiscordMessageContextInteractionEventImpl; import com.discordsrv.common.event.events.discord.interaction.command.DiscordUserContextInteractionEventImpl; import com.discordsrv.common.module.type.AbstractModule; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.events.guild.member.GuildMemberRoleAddEvent; import net.dv8tion.jda.api.events.guild.member.GuildMemberRoleRemoveEvent; import net.dv8tion.jda.api.events.interaction.GenericInteractionCreateEvent; import net.dv8tion.jda.api.events.interaction.ModalInteractionEvent; import net.dv8tion.jda.api.events.interaction.command.*; import net.dv8tion.jda.api.events.interaction.component.ButtonInteractionEvent; import net.dv8tion.jda.api.events.interaction.component.GenericComponentInteractionCreateEvent; import net.dv8tion.jda.api.events.interaction.component.GenericSelectMenuInteractionEvent; import net.dv8tion.jda.api.events.message.MessageDeleteEvent; import net.dv8tion.jda.api.events.message.MessageReceivedEvent; import net.dv8tion.jda.api.events.message.MessageUpdateEvent; import net.dv8tion.jda.api.interactions.callbacks.IDeferrableCallback; import net.dv8tion.jda.api.interactions.commands.Command; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.function.Consumer; import java.util.stream.Collectors; public class DiscordAPIEventModule extends AbstractModule<DiscordSRV> { public DiscordAPIEventModule(DiscordSRV discordSRV) { super(discordSRV); } private DiscordAPIImpl api() { return discordSRV.discordAPI(); } @Subscribe public void onMessageReceived(MessageReceivedEvent event) { discordSRV.eventBus().publish(new DiscordMessageReceiveEvent( event, api().getMessageChannel(event.getChannel()), ReceivedDiscordMessageImpl.fromJDA(discordSRV, event.getMessage()) )); } @Subscribe public void onMessageUpdate(MessageUpdateEvent event) { discordSRV.eventBus().publish(new DiscordMessageUpdateEvent( event, api().getMessageChannel(event.getChannel()), ReceivedDiscordMessageImpl.fromJDA(discordSRV, event.getMessage()) )); } @Subscribe public void onMessageDelete(MessageDeleteEvent event) { discordSRV.eventBus().publish(new DiscordMessageDeleteEvent( event, api().getMessageChannel(event.getChannel()), event.getMessageIdLong() )); } @Subscribe public void onGuildMemberRoleAdd(GuildMemberRoleAddEvent event) { discordSRV.eventBus().publish(new DiscordMemberRoleAddEvent( event, api().getGuildMember(event.getMember()), event.getRoles().stream().map(role -> api().getRole(role)).collect(Collectors.toList()) )); } @Subscribe public void onGuildMemberRoleRemove(GuildMemberRoleRemoveEvent event) { discordSRV.eventBus().publish(new DiscordMemberRoleRemoveEvent( event, api().getGuildMember(event.getMember()), event.getRoles().stream().map(role -> api().getRole(role)).collect(Collectors.toList()) )); } @Subscribe public void onGenericInteractionCreate(GenericInteractionCreateEvent event) { if (event.getChannel() == null || !event.getChannel().getType().isMessage() || (!(event instanceof CommandAutoCompleteInteractionEvent) && !(event instanceof IDeferrableCallback))) { return; } Member member = event.getMember(); DiscordUser user = api().getUser(event.getUser()); DiscordGuildMember guildMember = member != null ? api().getGuildMember(member) : null; DiscordMessageChannel channel = api().getMessageChannel(event.getMessageChannel()); if (event instanceof CommandAutoCompleteInteractionEvent) { DiscordCommand command = discordSRV.discordAPI().getActiveCommand( ((CommandAutoCompleteInteractionEvent) event).isGuildCommand() ? event.getGuild() : null, CommandType.CHAT_INPUT, ((CommandAutoCompleteInteractionEvent) event).getName() ).orElse(null); if (command == null) { return; } command = mapCommand( command, ((CommandAutoCompleteInteractionEvent) event).getSubcommandGroup(), ((CommandAutoCompleteInteractionEvent) event).getSubcommandName() ); DiscordCommandAutoCompleteInteractionEvent autoComplete = new DiscordCommandAutoCompleteInteractionEvent( (CommandAutoCompleteInteractionEvent) event, command.getId(), user, guildMember, channel); discordSRV.eventBus().publish(autoComplete); DiscordCommand.AutoCompleteHandler autoCompleteHandler = command.getAutoCompleteHandler(); if (autoCompleteHandler != null) { autoCompleteHandler.autoComplete(autoComplete); } List<Command.Choice> choices = new ArrayList<>(); for (Map.Entry<String, Object> entry : autoComplete.getChoices().entrySet()) { String name = entry.getKey(); Object value = entry.getValue(); if (value instanceof String) { choices.add(new Command.Choice(name, (String) value)); } else if (value instanceof Double || value instanceof Float) { choices.add(new Command.Choice(name, ((Number) value).doubleValue())); } else { choices.add(new Command.Choice(name, ((Number) value).longValue())); } } ((CommandAutoCompleteInteractionEvent) event).replyChoices(choices).queue(); return; } DiscordInteractionHook hook = new DiscordInteractionHookImpl(discordSRV, ((IDeferrableCallback) event).getHook()); Event newEvent = null; if (event instanceof GenericCommandInteractionEvent) { Guild guild = ((GenericCommandInteractionEvent) event).isGuildCommand() ? event.getGuild() : null; String name = ((GenericCommandInteractionEvent) event).getName(); if (event instanceof MessageContextInteractionEvent) { DiscordCommand command = discordSRV.discordAPI() .getActiveCommand(guild, CommandType.MESSAGE, name).orElse(null); if (command == null) { return; } DiscordMessageContextInteractionEvent interactionEvent = new DiscordMessageContextInteractionEventImpl( discordSRV, (MessageContextInteractionEvent) event, command.getId(), user, guildMember, channel, hook ); newEvent = interactionEvent; Consumer<AbstractCommandInteractionEvent<?>> eventHandler = command.getEventHandler(); if (eventHandler != null) { eventHandler.accept(interactionEvent); } } else if (event instanceof UserContextInteractionEvent) { DiscordCommand command = discordSRV.discordAPI() .getActiveCommand(guild, CommandType.USER, name).orElse(null); if (command == null) { return; } DiscordUserContextInteractionEvent interactionEvent = new DiscordUserContextInteractionEventImpl( discordSRV, (UserContextInteractionEvent) event, command.getId(), user, guildMember, channel, hook ); newEvent = interactionEvent; Consumer<AbstractCommandInteractionEvent<?>> eventHandler = command.getEventHandler(); if (eventHandler != null) { eventHandler.accept(interactionEvent); } } else if (event instanceof SlashCommandInteractionEvent) { DiscordCommand command = discordSRV.discordAPI() .getActiveCommand(guild, CommandType.CHAT_INPUT, name).orElse(null); if (command == null) { return; } command = mapCommand( command, ((SlashCommandInteractionEvent) event).getSubcommandGroup(), ((SlashCommandInteractionEvent) event).getSubcommandName() ); DiscordChatInputInteractionEvent interactionEvent = new DiscordChatInputInteractionEventImpl( discordSRV, (SlashCommandInteractionEvent) event, command.getId(), user, guildMember, channel, hook ); newEvent = interactionEvent; Consumer<AbstractCommandInteractionEvent<?>> eventHandler = command.getEventHandler(); if (eventHandler != null) { eventHandler.accept(interactionEvent); } } } else if (event instanceof GenericComponentInteractionCreateEvent) { ComponentIdentifier identifier = ComponentIdentifier.parseFromDiscord( ((GenericComponentInteractionCreateEvent) event).getComponentId()); if (identifier == null) { return; } if (event instanceof ButtonInteractionEvent) { newEvent = new DiscordButtonInteractionEvent( (ButtonInteractionEvent) event, identifier, user, guildMember, channel, hook); } else if (event instanceof GenericSelectMenuInteractionEvent) { newEvent = new DiscordSelectMenuInteractionEvent( (GenericSelectMenuInteractionEvent<?, ?>) event, identifier, user, guildMember, channel, hook); } } else if (event instanceof ModalInteractionEvent) { ComponentIdentifier identifier = ComponentIdentifier.parseFromDiscord( ((ModalInteractionEvent) event).getModalId()); if (identifier == null) { return; } newEvent = new DiscordModalInteractionEvent((ModalInteractionEvent) event, identifier, user, guildMember, channel, hook); } if (newEvent != null) { discordSRV.eventBus().publish(newEvent); } } private DiscordCommand mapCommand(DiscordCommand command, String subCommandGroupName, String subCommandName) { if (subCommandGroupName != null) { for (SubCommandGroup group : command.getSubCommandGroups()) { if (group.getName().equals(subCommandGroupName)) { for (DiscordCommand subCommand : group.getCommands()) { if (subCommand.getName().equals(subCommandName)) { command = subCommand; break; } } break; } } } else if (subCommandName != null) { for (DiscordCommand subCommand : command.getSubCommands()) { if (subCommandName.equals(subCommand.getName())) { command = subCommand; break; } } } return command; } }
14,661
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordUserImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/entity/DiscordUserImpl.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.discord.api.entity; import com.discordsrv.api.discord.entity.DiscordUser; import com.discordsrv.api.discord.entity.channel.DiscordDMChannel; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.discord.api.entity.channel.DiscordDMChannelImpl; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.entities.User; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.concurrent.CompletableFuture; public class DiscordUserImpl implements DiscordUser { protected final DiscordSRV discordSRV; protected final User user; protected final boolean self; public DiscordUserImpl(DiscordSRV discordSRV, User user) { this.discordSRV = discordSRV; this.user = user; this.self = user.getIdLong() == user.getJDA().getSelfUser().getIdLong(); } @Override public long getId() { return user.getIdLong(); } @Override public boolean isSelf() { return self; } @Override public boolean isBot() { return user.isBot(); } @Override public @NotNull String getUsername() { return user.getName(); } @Override public @NotNull String getEffectiveName() { return user.getEffectiveName(); } @SuppressWarnings("deprecation") @Override public @NotNull String getDiscriminator() { return user.getDiscriminator(); } @Override public @Nullable String getAvatarUrl() { return user.getAvatarUrl(); } @Override public @NotNull String getEffectiveAvatarUrl() { return user.getEffectiveAvatarUrl(); } @Override public CompletableFuture<DiscordDMChannel> openPrivateChannel() { JDA jda = discordSRV.jda(); if (jda == null) { return discordSRV.discordAPI().notReady(); } return discordSRV.discordAPI().mapExceptions( () -> jda.retrieveUserById(getId()) .submit() .thenCompose(user -> user.openPrivateChannel().submit()) .thenApply(privateChannel -> new DiscordDMChannelImpl(discordSRV, privateChannel)) ); } @Override public String getAsMention() { return user.getAsMention(); } @Override public String toString() { return "User:" + getUsername() + "(" + Long.toUnsignedString(getId()) + ")"; } @Override public User asJDA() { return user; } }
3,368
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordRoleImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/entity/guild/DiscordRoleImpl.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.discord.api.entity.guild; import com.discordsrv.api.color.Color; import com.discordsrv.api.discord.entity.guild.DiscordGuild; import com.discordsrv.api.discord.entity.guild.DiscordRole; import com.discordsrv.common.DiscordSRV; import net.dv8tion.jda.api.entities.Role; import org.jetbrains.annotations.NotNull; import java.util.Objects; public class DiscordRoleImpl implements DiscordRole { private final Role role; private final DiscordGuild guild; private final Color color; public DiscordRoleImpl(DiscordSRV discordSRV, Role role) { this.role = role; this.guild = discordSRV.discordAPI().getGuild(role.getGuild()); this.color = new Color(role.getColorRaw()); } @Override public long getId() { return role.getIdLong(); } @Override public @NotNull DiscordGuild getGuild() { return guild; } @Override public @NotNull String getName() { return role.getName(); } @Override public @NotNull Color getColor() { return color; } @Override public boolean isHoisted() { return role.isHoisted(); } @Override public String getAsMention() { return role.getAsMention(); } @Override public String toString() { return "ServerRole:" + getName() + "(" + Long.toUnsignedString(getId()) + ")"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DiscordRoleImpl that = (DiscordRoleImpl) o; return Objects.equals(role.getId(), that.role.getId()); } @Override public int hashCode() { return Objects.hash(role.getId()); } @Override public Role asJDA() { return role; } }
2,673
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordGuildMemberImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/entity/guild/DiscordGuildMemberImpl.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.discord.api.entity.guild; import com.discordsrv.api.color.Color; import com.discordsrv.api.discord.entity.DiscordUser; 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.placeholder.annotation.Placeholder; import com.discordsrv.api.placeholder.annotation.PlaceholderPrefix; import com.discordsrv.api.placeholder.annotation.PlaceholderRemainder; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.component.util.ComponentUtil; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Role; import net.kyori.adventure.text.Component; import net.kyori.adventure.text.format.TextColor; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.time.OffsetDateTime; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; @PlaceholderPrefix("user_") public class DiscordGuildMemberImpl implements DiscordGuildMember { private final DiscordSRV discordSRV; private final Member member; private final DiscordUser user; private final DiscordGuild guild; private final List<DiscordRole> roles; private final Color color; public DiscordGuildMemberImpl(DiscordSRV discordSRV, Member member) { this.discordSRV = discordSRV; this.member = member; this.user = discordSRV.discordAPI().getUser(member.getUser()); this.guild = discordSRV.discordAPI().getGuild(member.getGuild()); List<DiscordRole> roles = new ArrayList<>(); for (Role role : member.getRoles()) { roles.add(discordSRV.discordAPI().getRole(role)); } this.roles = roles; this.color = new Color(member.getColorRaw()); } @Override public @NotNull DiscordUser getUser() { return user; } @Override public @NotNull DiscordGuild getGuild() { return guild; } @Override public boolean isOwner() { return member.isOwner(); } @Override public @Nullable String getNickname() { return member.getNickname(); } @Override public @NotNull List<DiscordRole> getRoles() { return roles; } @Override public boolean hasRole(@NotNull DiscordRole role) { return roles.stream().anyMatch(role::equals); } @Override public boolean canInteract(@NotNull DiscordRole role) { return member.canInteract(role.asJDA()); } @Override public CompletableFuture<Void> addRole(@NotNull DiscordRole role) { return discordSRV.discordAPI().mapExceptions(() -> guild.asJDA().addRoleToMember(member, role.asJDA()).submit() ); } @Override public CompletableFuture<Void> removeRole(@NotNull DiscordRole role) { return discordSRV.discordAPI().mapExceptions(() -> guild.asJDA().removeRoleFromMember(member, role.asJDA()).submit() ); } @Override public @NotNull String getEffectiveServerAvatarUrl() { return member.getEffectiveAvatarUrl(); } @Override public Color getColor() { return color; } @Override public @NotNull OffsetDateTime getTimeJoined() { return member.getTimeJoined(); } @Override public @Nullable OffsetDateTime getTimeBoosted() { return member.getTimeBoosted(); } // // Placeholders // @Placeholder(value = "highest_role", relookup = "role") public DiscordRole _highestRole() { return !roles.isEmpty() ? roles.get(0) : null; } @Placeholder(value = "hoisted_role", relookup = "role") public DiscordRole _hoistedRole() { for (DiscordRole role : roles) { if (role.isHoisted()) { return role; } } return null; } @Placeholder("roles") public Component _allRoles(@PlaceholderRemainder String suffix) { List<Component> components = new ArrayList<>(); for (DiscordRole role : getRoles()) { components.add(Component.text(role.getName()).color(TextColor.color(role.getColor().rgb()))); } return ComponentUtil.join(Component.text(suffix), components); } @Override public String toString() { return "ServerMember:" + super.toString() + "/" + getGuild(); } @Override public String getAsMention() { return member.getAsMention(); } @Override public Member asJDA() { return member; } }
5,505
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordGuildImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/entity/guild/DiscordGuildImpl.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.discord.api.entity.guild; 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.common.DiscordSRV; import net.dv8tion.jda.api.entities.Guild; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Role; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; import java.util.concurrent.CompletableFuture; public class DiscordGuildImpl implements DiscordGuild { private final DiscordSRV discordSRV; private final Guild guild; public DiscordGuildImpl(DiscordSRV discordSRV, Guild guild) { this.discordSRV = discordSRV; this.guild = guild; } @Override public long getId() { return guild.getIdLong(); } @Override public @NotNull String getName() { return guild.getName(); } @Override public int getMemberCount() { return guild.getMemberCount(); } @Override public @NotNull DiscordGuildMember getSelfMember() { return discordSRV.discordAPI().getGuildMember(guild.getSelfMember()); } @Override public @NotNull CompletableFuture<DiscordGuildMember> retrieveMemberById(long id) { return discordSRV.discordAPI().mapExceptions(() -> guild.retrieveMemberById(id) .submit() .thenApply(member -> new DiscordGuildMemberImpl(discordSRV, member)) ); } @Override public @Nullable DiscordGuildMember getMemberById(long id) { Member member = guild.getMemberById(id); if (member == null) { return null; } return discordSRV.discordAPI().getGuildMember(member); } @Override public @NotNull Set<DiscordGuildMember> getCachedMembers() { Set<DiscordGuildMember> members = new HashSet<>(); for (Member member : guild.getMembers()) { members.add(discordSRV.discordAPI().getGuildMember(member)); } return members; } @Override public @Nullable DiscordRole getRoleById(long id) { Role role = guild.getRoleById(id); if (role == null) { return null; } return discordSRV.discordAPI().getRole(role); } @Override public @NotNull List<DiscordRole> getRoles() { List<DiscordRole> roles = new ArrayList<>(); for (Role role : guild.getRoles()) { roles.add(discordSRV.discordAPI().getRole(role)); } return roles; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DiscordGuildImpl that = (DiscordGuildImpl) o; return getId() == that.getId(); } @Override public int hashCode() { return Objects.hash(getId()); } @Override public String toString() { return "Guild:" + getName() + "(" + Long.toUnsignedString(getId()) + ")"; } @Override public Guild asJDA() { return guild; } }
4,027
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordCustomEmojiImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/entity/guild/DiscordCustomEmojiImpl.java
package com.discordsrv.common.discord.api.entity.guild; import com.discordsrv.api.discord.entity.guild.DiscordCustomEmoji; import net.dv8tion.jda.api.entities.emoji.CustomEmoji; public class DiscordCustomEmojiImpl implements DiscordCustomEmoji { private final CustomEmoji jda; public DiscordCustomEmojiImpl(CustomEmoji jda) { this.jda = jda; } @Override public CustomEmoji asJDA() { return jda; } @Override public long getId() { return jda.getIdLong(); } @Override public String getName() { return jda.getName(); } }
604
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ReceivedDiscordMessageClusterImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/entity/message/ReceivedDiscordMessageClusterImpl.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.discord.api.entity.message; 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.common.future.util.CompletableFutureUtil; import org.jetbrains.annotations.NotNull; import java.util.*; import java.util.concurrent.CompletableFuture; public class ReceivedDiscordMessageClusterImpl implements ReceivedDiscordMessageCluster { private final Set<ReceivedDiscordMessage> messages; public ReceivedDiscordMessageClusterImpl(Collection<ReceivedDiscordMessage> messages) { this.messages = new HashSet<>(messages); } @Override public @NotNull Set<ReceivedDiscordMessage> getMessages() { return messages; } @Override public @NotNull CompletableFuture<Void> deleteAll() { List<CompletableFuture<Void>> futures = new ArrayList<>(messages.size()); for (ReceivedDiscordMessage message : messages) { futures.add(message.delete()); } return CompletableFutureUtil.combine(futures).thenApply(v -> null); } @Override public @NotNull CompletableFuture<ReceivedDiscordMessageCluster> editAll(SendableDiscordMessage newMessage) { List<CompletableFuture<ReceivedDiscordMessage>> futures = new ArrayList<>(messages.size()); for (ReceivedDiscordMessage message : messages) { futures.add(message.edit(newMessage)); } return CompletableFutureUtil.combine(futures).thenApply(ReceivedDiscordMessageClusterImpl::new); } }
2,506
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ReceivedDiscordMessageImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/entity/message/ReceivedDiscordMessageImpl.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.discord.api.entity.message; import com.discordsrv.api.discord.entity.DiscordUser; import com.discordsrv.api.discord.entity.channel.DiscordDMChannel; 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.DiscordGuild; 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.discord.exception.RestErrorResponseException; import com.discordsrv.api.placeholder.annotation.Placeholder; import com.discordsrv.api.placeholder.annotation.PlaceholderPrefix; import com.discordsrv.api.placeholder.annotation.PlaceholderRemainder; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.component.util.ComponentUtil; import com.discordsrv.common.config.main.channels.base.BaseChannelConfig; import com.discordsrv.common.future.util.CompletableFutureUtil; import net.dv8tion.jda.api.entities.Member; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.entities.WebhookClient; import net.dv8tion.jda.api.requests.ErrorResponse; import net.kyori.adventure.text.Component; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.jetbrains.annotations.Unmodifiable; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; @PlaceholderPrefix("message_") public class ReceivedDiscordMessageImpl implements ReceivedDiscordMessage { public static ReceivedDiscordMessage fromJDA(DiscordSRV discordSRV, Message message) { List<DiscordMessageEmbed> mappedEmbeds = new ArrayList<>(); for (MessageEmbed embed : message.getEmbeds()) { mappedEmbeds.add(new DiscordMessageEmbed(embed)); } boolean webhookMessage = message.isWebhookMessage(); DiscordMessageChannel channel = discordSRV.discordAPI().getMessageChannel(message.getChannel()); DiscordUser user = discordSRV.discordAPI().getUser(message.getAuthor()); Member member = message.getMember(); DiscordGuildMember apiMember = member != null ? discordSRV.discordAPI().getGuildMember(member) : null; boolean self = false; if (webhookMessage) { CompletableFuture<WebhookClient<Message>> clientFuture = discordSRV.discordAPI() .getCachedClients() .getIfPresent(channel instanceof DiscordThreadChannel ? ((DiscordThreadChannel) channel).getParentChannel().getId() : channel.getId() ); if (clientFuture != null) { long clientId = clientFuture.join().getIdLong(); self = clientId == user.getId(); } } else { self = user.isSelf(); } List<Attachment> attachments = new ArrayList<>(); for (Message.Attachment attachment : message.getAttachments()) { attachments.add(new Attachment( attachment.getFileName(), attachment.getUrl(), attachment.getProxyUrl(), attachment.getSize() )); } Message referencedMessage = message.getReferencedMessage(); return new ReceivedDiscordMessageImpl( discordSRV, attachments, self, channel, referencedMessage != null ? fromJDA(discordSRV, referencedMessage) : null, apiMember, user, message.getChannel().getIdLong(), message.getIdLong(), message.getContentRaw(), mappedEmbeds, webhookMessage ); } private final DiscordSRV discordSRV; private final List<Attachment> attachments; private final boolean fromSelf; private final DiscordMessageChannel channel; private final ReceivedDiscordMessage replyingTo; private final DiscordGuildMember member; private final DiscordUser author; private final String content; private final List<DiscordMessageEmbed> embeds; private final boolean webhookMessage; private final long channelId; private final long id; private ReceivedDiscordMessageImpl( DiscordSRV discordSRV, List<Attachment> attachments, boolean fromSelf, DiscordMessageChannel channel, ReceivedDiscordMessage replyingTo, DiscordGuildMember member, DiscordUser author, long channelId, long id, String content, List<DiscordMessageEmbed> embeds, boolean webhookMessage ) { this.discordSRV = discordSRV; this.attachments = attachments; this.fromSelf = fromSelf; this.channel = channel; this.replyingTo = replyingTo; this.member = member; this.author = author; this.content = content; this.embeds = embeds; this.webhookMessage = webhookMessage; this.channelId = channelId; this.id = id; } @Override public long getId() { return id; } @Override public @NotNull String getContent() { return content; } @Override public @NotNull @Unmodifiable List<DiscordMessageEmbed> getEmbeds() { return embeds; } @Override public boolean isWebhookMessage() { return webhookMessage; } @Override public @NotNull String getJumpUrl() { DiscordGuild guild = getGuild(); return String.format( Message.JUMP_URL, guild != null ? Long.toUnsignedString(guild.getId()) : "@me", Long.toUnsignedString(getChannel().getId()), Long.toUnsignedString(id) ); } @Override public @NotNull List<Attachment> getAttachments() { return attachments; } @Override public boolean isFromSelf() { return fromSelf; } @Override public @Nullable DiscordTextChannel getTextChannel() { return channel instanceof DiscordTextChannel ? (DiscordTextChannel) channel : null; } @Override public @Nullable DiscordDMChannel getDMChannel() { return channel instanceof DiscordDMChannel ? (DiscordDMChannel) channel : null; } @Override public @Nullable DiscordGuildMember getMember() { return member; } @Override public @NotNull DiscordUser getAuthor() { return author; } @Override public @NotNull DiscordMessageChannel getChannel() { return channel; } @Override public @Nullable ReceivedDiscordMessage getReplyingTo() { return replyingTo; } @Override public @NotNull CompletableFuture<Void> delete() { DiscordMessageChannel messageChannel = discordSRV.discordAPI().getMessageChannelById(channelId); if (messageChannel == null) { return CompletableFutureUtil.failed(new RestErrorResponseException(ErrorResponse.UNKNOWN_CHANNEL)); } return messageChannel.deleteMessageById(getId(), fromSelf && webhookMessage); } @Override public @NotNull CompletableFuture<ReceivedDiscordMessage> edit( @NotNull SendableDiscordMessage message ) { if (!webhookMessage && message.isWebhookMessage()) { throw new IllegalArgumentException("Cannot edit a non-webhook message into a webhook message"); } DiscordMessageChannel messageChannel = discordSRV.discordAPI().getMessageChannelById(channelId); if (messageChannel == null) { return CompletableFutureUtil.failed(new RestErrorResponseException(ErrorResponse.UNKNOWN_CHANNEL)); } return messageChannel.editMessageById(getId(), message); } @Override public CompletableFuture<ReceivedDiscordMessage> reply(@NotNull SendableDiscordMessage message) { if (message.isWebhookMessage()) { throw new IllegalStateException("Webhook messages cannot be used as replies"); } DiscordMessageChannel messageChannel = discordSRV.discordAPI().getMessageChannelById(channelId); if (messageChannel == null) { return CompletableFutureUtil.failed(new RestErrorResponseException(ErrorResponse.UNKNOWN_CHANNEL)); } return messageChannel.sendMessage(message.withReplyingToMessageId(id)); } // // Placeholders // @Placeholder("reply") public Component _reply(BaseChannelConfig config) { if (replyingTo == null) { return null; } String content = replyingTo.getContent(); if (content == null) { return null; } Component component = discordSRV.componentFactory().minecraftSerializer().serialize(content); String replyFormat = config.discordToMinecraft.replyFormat; return ComponentUtil.fromAPI( discordSRV.componentFactory().textBuilder(replyFormat) .applyPlaceholderService() .addPlaceholder("message", component) .addContext(replyingTo.getMember(), replyingTo.getAuthor(), replyingTo) .build() ); } @Placeholder("attachments") public Component _attachments(BaseChannelConfig config, @PlaceholderRemainder String suffix) { String attachmentFormat = config.discordToMinecraft.attachmentFormat; List<Component> components = new ArrayList<>(); for (Attachment attachment : attachments) { components.add(ComponentUtil.fromAPI( discordSRV.componentFactory().textBuilder(attachmentFormat) .applyPlaceholderService() .addPlaceholder("file_name", attachment.fileName()) .addPlaceholder("file_url", attachment.url()) .build() )); } return ComponentUtil.join(Component.text(suffix), components); } @Override public String toString() { return "ReceivedMessage:" + Long.toUnsignedString(getId()) + "/" + getChannel(); } }
11,588
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
SendableDiscordMessageUtil.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/entity/message/util/SendableDiscordMessageUtil.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.discord.api.entity.message.util; import com.discordsrv.api.discord.entity.interaction.component.actionrow.MessageActionRow; import com.discordsrv.api.discord.entity.message.AllowedMention; import com.discordsrv.api.discord.entity.message.DiscordMessageEmbed; import com.discordsrv.api.discord.entity.message.SendableDiscordMessage; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.MessageEmbed; import net.dv8tion.jda.api.interactions.components.ActionRow; import net.dv8tion.jda.api.utils.FileUpload; import net.dv8tion.jda.api.utils.messages.*; import org.jetbrains.annotations.NotNull; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Set; public final class SendableDiscordMessageUtil { private SendableDiscordMessageUtil() {} @SuppressWarnings("unchecked") private static <T extends AbstractMessageBuilder<?, ?>> T jdaBuilder(@NotNull SendableDiscordMessage message, T builder) { List<Message.MentionType> allowedTypes = new ArrayList<>(); List<Long> allowedUsers = new ArrayList<>(); List<Long> allowedRoles = new ArrayList<>(); Set<AllowedMention> allowedMentions = message.getAllowedMentions(); for (AllowedMention allowedMention : allowedMentions) { if (allowedMention instanceof AllowedMention.Snowflake) { long id = ((AllowedMention.Snowflake) allowedMention).getId(); if (((AllowedMention.Snowflake) allowedMention).isUser()) { allowedUsers.add(id); } else { allowedRoles.add(id); } } else if (allowedMention instanceof AllowedMention.Standard) { allowedTypes.add(((AllowedMention.Standard) allowedMention).getMentionType()); } } List<MessageEmbed> embeds = new ArrayList<>(); for (DiscordMessageEmbed embed : message.getEmbeds()) { embeds.add(embed.toJDA()); } List<FileUpload> uploads = new ArrayList<>(); for (Map.Entry<InputStream, String> attachment : message.getAttachments().entrySet()) { uploads.add(FileUpload.fromData(attachment.getKey(), attachment.getValue())); } return (T) builder .setContent(message.getContent()) .setEmbeds(embeds) .setAllowedMentions(allowedTypes) .setSuppressEmbeds(message.isSuppressedEmbeds()) .mentionUsers(allowedUsers.stream().mapToLong(l -> l).toArray()) .mentionRoles(allowedRoles.stream().mapToLong(l -> l).toArray()) .setFiles(uploads); } public static MessageCreateData toJDASend(@NotNull SendableDiscordMessage message) { List<ActionRow> actionRows = new ArrayList<>(); for (MessageActionRow actionRow : message.getActionRows()) { actionRows.add(actionRow.asJDA()); } return jdaBuilder(message, new MessageCreateBuilder()) .addComponents(actionRows) .setSuppressedNotifications(message.isSuppressedNotifications()) .build(); } public static MessageEditData toJDAEdit(@NotNull SendableDiscordMessage message) { List<ActionRow> actionRows = new ArrayList<>(); for (MessageActionRow actionRow : message.getActionRows()) { actionRows.add(actionRow.asJDA()); } return jdaBuilder(message, new MessageEditBuilder()) .setComponents(actionRows) .build(); } }
4,478
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordStageChannelImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/entity/channel/DiscordStageChannelImpl.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.discord.api.entity.channel; import com.discordsrv.api.discord.entity.channel.DiscordStageChannel; import com.discordsrv.common.DiscordSRV; import net.dv8tion.jda.api.entities.channel.concrete.StageChannel; public class DiscordStageChannelImpl extends AbstractDiscordGuildMessageChannel<StageChannel> implements DiscordStageChannel { public DiscordStageChannelImpl(DiscordSRV discordSRV, StageChannel stageChannel) { super(discordSRV, stageChannel); } @Override public StageChannel asJDA() { return channel; } @Override public String toString() { return "StageChannel:" + getName() + "(" + Long.toUnsignedString(getId()) + ")"; } }
1,552
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordTextChannelImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/entity/channel/DiscordTextChannelImpl.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.discord.api.entity.channel; import com.discordsrv.api.discord.entity.channel.DiscordTextChannel; import com.discordsrv.common.DiscordSRV; import net.dv8tion.jda.api.entities.channel.concrete.TextChannel; import org.jetbrains.annotations.Nullable; public class DiscordTextChannelImpl extends AbstractDiscordThreadedGuildMessageChannel<TextChannel> implements DiscordTextChannel { public DiscordTextChannelImpl(DiscordSRV discordSRV, TextChannel textChannel) { super(discordSRV, textChannel); } @Override public @Nullable String getTopic() { return channel.getTopic(); } @Override public TextChannel asJDA() { return channel; } @Override public String toString() { return "TextChannel:" + getName() + "(" + Long.toUnsignedString(getId()) + ")"; } }
1,689
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordVoiceChannelImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/entity/channel/DiscordVoiceChannelImpl.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.discord.api.entity.channel; import com.discordsrv.api.discord.entity.channel.DiscordVoiceChannel; import com.discordsrv.common.DiscordSRV; import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel; public class DiscordVoiceChannelImpl extends AbstractDiscordGuildMessageChannel<VoiceChannel> implements DiscordVoiceChannel { public DiscordVoiceChannelImpl(DiscordSRV discordSRV, VoiceChannel voiceChannel) { super(discordSRV, voiceChannel); } @Override public VoiceChannel asJDA() { return channel; } @Override public String toString() { return "VoiceChannel:" + getName() + "(" + Long.toUnsignedString(getId()) + ")"; } }
1,552
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordThreadChannelImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/entity/channel/DiscordThreadChannelImpl.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.discord.api.entity.channel; import com.discordsrv.api.discord.entity.channel.DiscordChannelType; import com.discordsrv.api.discord.entity.channel.DiscordThreadChannel; import com.discordsrv.api.discord.entity.channel.DiscordThreadContainer; import com.discordsrv.api.discord.entity.guild.DiscordGuild; import com.discordsrv.common.DiscordSRV; import net.dv8tion.jda.api.JDA; import net.dv8tion.jda.api.JDABuilder; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.WebhookClient; import net.dv8tion.jda.api.entities.channel.ChannelType; import net.dv8tion.jda.api.entities.channel.attribute.IThreadContainer; import net.dv8tion.jda.api.entities.channel.concrete.ThreadChannel; import net.dv8tion.jda.api.requests.restaction.WebhookMessageCreateAction; import net.dv8tion.jda.api.requests.restaction.WebhookMessageDeleteAction; import net.dv8tion.jda.api.requests.restaction.WebhookMessageEditAction; import org.jetbrains.annotations.NotNull; import java.util.concurrent.CompletableFuture; public class DiscordThreadChannelImpl extends AbstractDiscordGuildMessageChannel<ThreadChannel> implements DiscordThreadChannel { private final DiscordThreadContainer threadContainer; private final DiscordGuild guild; public DiscordThreadChannelImpl(DiscordSRV discordSRV, ThreadChannel thread) { super(discordSRV, thread); IThreadContainer container = thread.getParentChannel(); this.threadContainer = (DiscordThreadContainer) discordSRV.discordAPI().getChannel(container); this.guild = discordSRV.discordAPI().getGuild(thread.getGuild()); } @Override public CompletableFuture<WebhookClient<Message>> queryWebhookClient() { return discordSRV.discordAPI() .queryWebhookClient(getParentChannel().getId()); } @Override protected <R> WebhookMessageCreateAction<R> mapAction(WebhookMessageCreateAction<R> action) { return super.mapAction(action).setThreadId(getId()); } @Override protected <R> WebhookMessageEditAction<R> mapAction(WebhookMessageEditAction<R> action) { return super.mapAction(action).setThreadId(getId()); } @Override protected WebhookMessageDeleteAction mapAction(WebhookMessageDeleteAction action) { return super.mapAction(action).setThreadId(getId()); } @Override public @NotNull DiscordGuild getGuild() { return guild; } @Override public @NotNull DiscordThreadContainer getParentChannel() { return threadContainer; } @Override public boolean isArchived() { return channel.isArchived(); } @Override public boolean isLocked() { return channel.isLocked(); } @Override public boolean isJoined() { return channel.isJoined(); } @Override public boolean isInvitable() { return channel.isInvitable(); } @Override public boolean isOwnedBySelfUser() { return channel.isOwner(); } @Override public boolean isPublic() { return channel.isPublic(); } @Override public String toString() { return "Thread:" + getName() + "(" + Long.toUnsignedString(getId()) + " in " + threadContainer + ")"; } @Override public ThreadChannel asJDA() { return channel; } public static void main(String[] args) { JDA jda = JDABuilder.createDefault("token").build(); WebhookClient.createClient(jda, "url").sendMessage("hello").setThreadId(1234567890L).queue(); } @Override public DiscordChannelType getType() { ChannelType type = channel.getType(); for (DiscordChannelType value : DiscordChannelType.values()) { if (value.asJDA() == type) { return value; } } throw new IllegalStateException("Unknown channel type"); } }
4,755
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
AbstractDiscordThreadedGuildMessageChannel.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/entity/channel/AbstractDiscordThreadedGuildMessageChannel.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.discord.api.entity.channel; import com.discordsrv.api.discord.entity.channel.DiscordGuildMessageChannel; import com.discordsrv.api.discord.entity.channel.DiscordThreadChannel; import com.discordsrv.api.discord.entity.channel.DiscordThreadContainer; import com.discordsrv.common.DiscordSRV; import net.dv8tion.jda.api.entities.channel.attribute.IThreadContainer; import net.dv8tion.jda.api.entities.channel.concrete.ThreadChannel; import net.dv8tion.jda.api.entities.channel.middleman.GuildMessageChannel; import net.dv8tion.jda.api.requests.restaction.ThreadChannelAction; import net.dv8tion.jda.api.requests.restaction.pagination.ThreadChannelPaginationAction; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.stream.Collectors; public abstract class AbstractDiscordThreadedGuildMessageChannel<T extends GuildMessageChannel & IThreadContainer> extends AbstractDiscordGuildMessageChannel<T> implements DiscordGuildMessageChannel, DiscordThreadContainer { public AbstractDiscordThreadedGuildMessageChannel(DiscordSRV discordSRV, T channel) { super(discordSRV, channel); } @Override public @NotNull List<DiscordThreadChannel> getActiveThreads() { List<ThreadChannel> threads = channel.getThreadChannels(); List<DiscordThreadChannel> threadChannels = new ArrayList<>(threads.size()); for (ThreadChannel thread : threads) { threadChannels.add(discordSRV.discordAPI().getThreadChannel(thread)); } return threadChannels; } @Override public CompletableFuture<List<DiscordThreadChannel>> retrieveArchivedPrivateThreads() { return threads(IThreadContainer::retrieveArchivedPrivateThreadChannels); } @Override public CompletableFuture<List<DiscordThreadChannel>> retrieveArchivedJoinedPrivateThreads() { return threads(IThreadContainer::retrieveArchivedPrivateJoinedThreadChannels); } @Override public CompletableFuture<List<DiscordThreadChannel>> retrieveArchivedPublicThreads() { return threads(IThreadContainer::retrieveArchivedPublicThreadChannels); } @SuppressWarnings("CodeBlock2Expr") private CompletableFuture<List<DiscordThreadChannel>> threads( Function<IThreadContainer, ThreadChannelPaginationAction> action) { return discordSRV.discordAPI().mapExceptions(() -> { return action.apply(channel) .submit() .thenApply(channels -> channels.stream() .map(channel -> discordSRV.discordAPI().getThreadChannel(channel)) .collect(Collectors.toList()) ); }); } @Override public CompletableFuture<DiscordThreadChannel> createThread(String name, boolean privateThread) { return thread(channel -> channel.createThreadChannel(name, privateThread)); } @Override public CompletableFuture<DiscordThreadChannel> createThread(String name, long messageId) { return thread(channel -> channel.createThreadChannel(name, messageId)); } @SuppressWarnings("CodeBlock2Expr") private CompletableFuture<DiscordThreadChannel> thread(Function<T, ThreadChannelAction> action) { return discordSRV.discordAPI().mapExceptions(() -> { return action.apply(channel) .submit() .thenApply(channel -> discordSRV.discordAPI().getThreadChannel(channel)); }); } }
4,488
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordForumChannelImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/entity/channel/DiscordForumChannelImpl.java
package com.discordsrv.common.discord.api.entity.channel; import com.discordsrv.api.discord.entity.channel.DiscordChannelType; import com.discordsrv.api.discord.entity.channel.DiscordForumChannel; import com.discordsrv.api.discord.entity.channel.DiscordThreadChannel; import com.discordsrv.api.discord.entity.guild.DiscordGuild; import com.discordsrv.common.DiscordSRV; import net.dv8tion.jda.api.entities.channel.attribute.IThreadContainer; import net.dv8tion.jda.api.entities.channel.concrete.ForumChannel; import net.dv8tion.jda.api.entities.channel.concrete.ThreadChannel; import net.dv8tion.jda.api.requests.restaction.ThreadChannelAction; import net.dv8tion.jda.api.requests.restaction.pagination.ThreadChannelPaginationAction; import org.jetbrains.annotations.NotNull; import java.util.ArrayList; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.function.Function; import java.util.stream.Collectors; public class DiscordForumChannelImpl implements DiscordForumChannel { private final DiscordSRV discordSRV; private final ForumChannel channel; private final DiscordGuild guild; public DiscordForumChannelImpl(DiscordSRV discordSRV, ForumChannel channel) { this.discordSRV = discordSRV; this.channel = channel; this.guild = discordSRV.discordAPI().getGuild(channel.getGuild()); } @Override public ForumChannel asJDA() { return channel; } @Override public long getId() { return channel.getIdLong(); } @Override public @NotNull String getName() { return channel.getName(); } @Override public @NotNull DiscordGuild getGuild() { return guild; } @Override public @NotNull String getJumpUrl() { return channel.getJumpUrl(); } @Override public @NotNull List<DiscordThreadChannel> getActiveThreads() { List<ThreadChannel> threads = channel.getThreadChannels(); List<DiscordThreadChannel> threadChannels = new ArrayList<>(threads.size()); for (ThreadChannel thread : threads) { threadChannels.add(discordSRV.discordAPI().getThreadChannel(thread)); } return threadChannels; } @Override public CompletableFuture<List<DiscordThreadChannel>> retrieveArchivedPrivateThreads() { return threads(IThreadContainer::retrieveArchivedPrivateThreadChannels); } @Override public CompletableFuture<List<DiscordThreadChannel>> retrieveArchivedJoinedPrivateThreads() { return threads(IThreadContainer::retrieveArchivedPrivateJoinedThreadChannels); } @Override public CompletableFuture<List<DiscordThreadChannel>> retrieveArchivedPublicThreads() { return threads(IThreadContainer::retrieveArchivedPublicThreadChannels); } @SuppressWarnings("CodeBlock2Expr") private CompletableFuture<List<DiscordThreadChannel>> threads( Function<IThreadContainer, ThreadChannelPaginationAction> action) { return discordSRV.discordAPI().mapExceptions(() -> { return action.apply(channel) .submit() .thenApply(channels -> channels.stream() .map(channel -> discordSRV.discordAPI().getThreadChannel(channel)) .collect(Collectors.toList()) ); }); } @Override public CompletableFuture<DiscordThreadChannel> createThread(String name, boolean privateThread) { return thread(channel -> channel.createThreadChannel(name, privateThread)); } @Override public CompletableFuture<DiscordThreadChannel> createThread(String name, long messageId) { return thread(channel -> channel.createThreadChannel(name, messageId)); } @SuppressWarnings("CodeBlock2Expr") private CompletableFuture<DiscordThreadChannel> thread(Function<ForumChannel, ThreadChannelAction> action) { return discordSRV.discordAPI().mapExceptions(() -> { return action.apply(channel) .submit() .thenApply(channel -> discordSRV.discordAPI().getThreadChannel(channel)); }); } @Override public DiscordChannelType getType() { return DiscordChannelType.FORUM; } }
4,303
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
AbstractDiscordGuildMessageChannel.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/entity/channel/AbstractDiscordGuildMessageChannel.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.discord.api.entity.channel; import com.discordsrv.api.discord.entity.channel.DiscordGuildMessageChannel; import com.discordsrv.api.discord.entity.guild.DiscordGuild; import com.discordsrv.api.discord.entity.message.ReceivedDiscordMessage; import com.discordsrv.api.discord.entity.message.SendableDiscordMessage; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.discord.api.entity.message.ReceivedDiscordMessageImpl; import com.discordsrv.common.discord.api.entity.message.util.SendableDiscordMessageUtil; import net.dv8tion.jda.api.entities.Message; import net.dv8tion.jda.api.entities.WebhookClient; import net.dv8tion.jda.api.entities.channel.middleman.GuildMessageChannel; import net.dv8tion.jda.api.requests.RestAction; import net.dv8tion.jda.api.requests.restaction.MessageCreateAction; import net.dv8tion.jda.api.requests.restaction.WebhookMessageCreateAction; import net.dv8tion.jda.api.requests.restaction.WebhookMessageDeleteAction; import net.dv8tion.jda.api.requests.restaction.WebhookMessageEditAction; import net.dv8tion.jda.api.utils.messages.MessageCreateData; import net.dv8tion.jda.api.utils.messages.MessageCreateRequest; import net.dv8tion.jda.api.utils.messages.MessageEditData; import net.dv8tion.jda.api.utils.messages.MessageEditRequest; import org.jetbrains.annotations.NotNull; import java.util.concurrent.CompletableFuture; public abstract class AbstractDiscordGuildMessageChannel<T extends GuildMessageChannel> extends AbstractDiscordMessageChannel<T> implements DiscordGuildMessageChannel { private final DiscordGuild guild; public AbstractDiscordGuildMessageChannel(DiscordSRV discordSRV, T channel) { super(discordSRV, channel); this.guild = discordSRV.discordAPI().getGuild(channel.getGuild()); } public CompletableFuture<WebhookClient<Message>> queryWebhookClient() { return discordSRV.discordAPI().queryWebhookClient(getId()); } @Override public @NotNull String getName() { return channel.getName(); } @Override public String getAsMention() { return channel.getAsMention(); } @Override public @NotNull String getJumpUrl() { return channel.getJumpUrl(); } @Override public @NotNull DiscordGuild getGuild() { return guild; } @Override public @NotNull CompletableFuture<ReceivedDiscordMessage> sendMessage(@NotNull SendableDiscordMessage message) { return sendInternal(message); } protected <R> WebhookMessageCreateAction<R> mapAction(WebhookMessageCreateAction<R> action) { return action; } @SuppressWarnings("unchecked") // Generics private <R extends MessageCreateRequest<? extends MessageCreateRequest<?>> & RestAction<Message>> CompletableFuture<ReceivedDiscordMessage> sendInternal(SendableDiscordMessage message) { MessageCreateData createData = SendableDiscordMessageUtil.toJDASend(message); CompletableFuture<R> createRequest; if (message.isWebhookMessage()) { createRequest = queryWebhookClient() .thenApply(client -> (R) mapAction(client.sendMessage(createData)) .setUsername(message.getWebhookUsername()) .setAvatarUrl(message.getWebhookAvatarUrl()) ); } else { MessageCreateAction action = channel.sendMessage(createData); Long referencedMessageId = message.getMessageIdToReplyTo(); if (referencedMessageId != null) { action = action.setMessageReference(referencedMessageId); } createRequest = CompletableFuture.completedFuture((R) action); } return createRequest .thenCompose(RestAction::submit) .thenApply(msg -> ReceivedDiscordMessageImpl.fromJDA(discordSRV, msg)); } @Override public @NotNull CompletableFuture<ReceivedDiscordMessage> editMessageById( long id, @NotNull SendableDiscordMessage message ) { return editInternal(id, message); } protected <R> WebhookMessageEditAction<R> mapAction(WebhookMessageEditAction<R> action) { return action; } @SuppressWarnings("unchecked") // Generics private <R extends MessageEditRequest<? extends MessageEditRequest<?>> & RestAction<Message>> CompletableFuture<ReceivedDiscordMessage> editInternal( long id, SendableDiscordMessage message ) { MessageEditData editData = SendableDiscordMessageUtil.toJDAEdit(message); CompletableFuture<R> editRequest; if (message.isWebhookMessage()) { editRequest = queryWebhookClient().thenApply(client -> (R) mapAction(client.editMessageById(id, editData))); } else { editRequest = CompletableFuture.completedFuture(((R) channel.editMessageById(id, editData))); } return editRequest .thenCompose(RestAction::submit) .thenApply(msg -> ReceivedDiscordMessageImpl.fromJDA(discordSRV, msg)); } protected WebhookMessageDeleteAction mapAction(WebhookMessageDeleteAction action) { return action; } @Override public CompletableFuture<Void> deleteMessageById(long id, boolean webhookMessage) { CompletableFuture<Void> future; if (webhookMessage) { future = queryWebhookClient().thenCompose(client -> mapAction(client.deleteMessageById(id)).submit()); } else { future = channel.deleteMessageById(id).submit(); } return discordSRV.discordAPI().mapExceptions(future); } }
6,541
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
AbstractDiscordMessageChannel.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/entity/channel/AbstractDiscordMessageChannel.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.discord.api.entity.channel; import com.discordsrv.api.discord.entity.channel.DiscordMessageChannel; import com.discordsrv.common.DiscordSRV; import net.dv8tion.jda.api.entities.channel.middleman.MessageChannel; import java.util.Objects; public abstract class AbstractDiscordMessageChannel<T extends MessageChannel> implements DiscordMessageChannel { protected final DiscordSRV discordSRV; protected final T channel; public AbstractDiscordMessageChannel(DiscordSRV discordSRV, T channel) { this.discordSRV = discordSRV; this.channel = channel; } @Override public long getId() { return channel.getIdLong(); } @Override public MessageChannel getAsJDAMessageChannel() { return channel; } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof DiscordMessageChannel)) return false; DiscordMessageChannel that = (DiscordMessageChannel) o; return Objects.equals(getId(), that.getId()); } @Override public int hashCode() { return Objects.hash(getId()); } }
1,990
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordDMChannelImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/entity/channel/DiscordDMChannelImpl.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.discord.api.entity.channel; import com.discordsrv.api.discord.entity.DiscordUser; import com.discordsrv.api.discord.entity.channel.DiscordDMChannel; import com.discordsrv.api.discord.entity.message.ReceivedDiscordMessage; import com.discordsrv.api.discord.entity.message.SendableDiscordMessage; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.discord.api.entity.message.ReceivedDiscordMessageImpl; import com.discordsrv.common.discord.api.entity.message.util.SendableDiscordMessageUtil; import net.dv8tion.jda.api.entities.User; import net.dv8tion.jda.api.entities.channel.concrete.PrivateChannel; import net.dv8tion.jda.api.requests.restaction.MessageCreateAction; import org.jetbrains.annotations.NotNull; import java.util.Objects; import java.util.concurrent.CompletableFuture; public class DiscordDMChannelImpl extends AbstractDiscordMessageChannel<PrivateChannel> implements DiscordDMChannel { private final DiscordUser user; public DiscordDMChannelImpl(DiscordSRV discordSRV, PrivateChannel privateChannel) { super(discordSRV, privateChannel); User user = privateChannel.getUser(); this.user = user != null ? discordSRV.discordAPI().getUser(user) : null; } @Override public DiscordUser getUser() { return user; } @Override public @NotNull CompletableFuture<ReceivedDiscordMessage> sendMessage(@NotNull SendableDiscordMessage message) { if (message.isWebhookMessage()) { throw new IllegalArgumentException("Cannot send webhook messages to DMChannels"); } MessageCreateAction action = channel.sendMessage(SendableDiscordMessageUtil.toJDASend(message)); Long referencedMessageId = message.getMessageIdToReplyTo(); if (referencedMessageId != null) { action = action.setMessageReference(referencedMessageId); } CompletableFuture<ReceivedDiscordMessage> future = action.submit() .thenApply(msg -> ReceivedDiscordMessageImpl.fromJDA(discordSRV, msg)); return discordSRV.discordAPI().mapExceptions(future); } @Override public CompletableFuture<Void> deleteMessageById(long id, boolean webhookMessage) { if (webhookMessage) { throw new IllegalArgumentException("DMChannels do not contain webhook messages"); } return discordSRV.discordAPI().mapExceptions(channel.deleteMessageById(id).submit()); } @Override public @NotNull CompletableFuture<ReceivedDiscordMessage> editMessageById( long id, @NotNull SendableDiscordMessage message ) { if (message.isWebhookMessage()) { throw new IllegalArgumentException("Cannot send webhook messages to DMChannels"); } CompletableFuture<ReceivedDiscordMessage> future = channel .editMessageById(id, SendableDiscordMessageUtil.toJDAEdit(message)) .submit() .thenApply(msg -> ReceivedDiscordMessageImpl.fromJDA(discordSRV, msg)); return discordSRV.discordAPI().mapExceptions(future); } @Override public String toString() { return "DMChannel:" + user + "(" + Long.toUnsignedString(getId()) + ")"; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; DiscordDMChannelImpl that = (DiscordDMChannelImpl) o; return Objects.equals(user.getId(), that.user.getId()); } @Override public int hashCode() { return Objects.hash(user.getId()); } @Override public PrivateChannel asJDA() { return channel; } }
4,560
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordNewsChannelImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/entity/channel/DiscordNewsChannelImpl.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.discord.api.entity.channel; import com.discordsrv.api.discord.entity.channel.DiscordNewsChannel; import com.discordsrv.common.DiscordSRV; import net.dv8tion.jda.api.entities.channel.concrete.NewsChannel; public class DiscordNewsChannelImpl extends AbstractDiscordThreadedGuildMessageChannel<NewsChannel> implements DiscordNewsChannel { public DiscordNewsChannelImpl(DiscordSRV discordSRV, NewsChannel channel) { super(discordSRV, channel); } @Override public NewsChannel asJDA() { return channel; } @Override public String toString() { return "NewsChannel:" + getName() + "(" + Long.toUnsignedString(getId()) + ")"; } }
1,541
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordInteractionHookImpl.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/discord/api/entity/component/DiscordInteractionHookImpl.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.discord.api.entity.component; import com.discordsrv.api.discord.entity.interaction.DiscordInteractionHook; import com.discordsrv.api.discord.entity.message.ReceivedDiscordMessage; import com.discordsrv.api.discord.entity.message.SendableDiscordMessage; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.discord.api.entity.message.ReceivedDiscordMessageImpl; import com.discordsrv.common.discord.api.entity.message.util.SendableDiscordMessageUtil; import net.dv8tion.jda.api.interactions.InteractionHook; import java.util.concurrent.CompletableFuture; public class DiscordInteractionHookImpl implements DiscordInteractionHook { private final DiscordSRV discordSRV; private final InteractionHook hook; public DiscordInteractionHookImpl(DiscordSRV discordSRV, InteractionHook hook) { this.discordSRV = discordSRV; this.hook = hook; } @Override public InteractionHook asJDA() { return hook; } @Override public long getExpiryTime() { return hook.getExpirationTimestamp(); } @Override public boolean isExpired() { return hook.isExpired(); } @Override public CompletableFuture<ReceivedDiscordMessage> editOriginal(SendableDiscordMessage message) { return hook.editOriginal(SendableDiscordMessageUtil.toJDAEdit(message)).submit() .thenApply(msg -> ReceivedDiscordMessageImpl.fromJDA(discordSRV, msg)); } @Override public CompletableFuture<ReceivedDiscordMessage> sendMessage(SendableDiscordMessage message, boolean ephemeral) { return hook.sendMessage(SendableDiscordMessageUtil.toJDASend(message)).setEphemeral(ephemeral).submit() .thenApply(msg -> ReceivedDiscordMessageImpl.fromJDA(discordSRV, msg)); } }
2,654
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
CompletableFutureUtil.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/future/util/CompletableFutureUtil.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.future.util; import com.discordsrv.common.DiscordSRV; import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.concurrent.CompletableFuture; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeoutException; public final class CompletableFutureUtil { private CompletableFutureUtil() {} /** * Same as {@link CompletableFuture#completedFuture(Object)} but for failing. */ public static <T> CompletableFuture<T> failed(Throwable throwable) { CompletableFuture<T> future = new CompletableFuture<>(); future.completeExceptionally(throwable); return future; } @SuppressWarnings("unchecked") public static <T> CompletableFuture<List<T>> combine(Collection<CompletableFuture<T>> futures) { return combine(futures.toArray(new CompletableFuture[0])); } @SafeVarargs public static <T> CompletableFuture<List<T>> combine(CompletableFuture<T>... futures) { CompletableFuture<List<T>> future = new CompletableFuture<>(); CompletableFuture.allOf(futures).whenComplete((v, t) -> { if (t != null) { future.completeExceptionally(t); return; } List<T> results = new ArrayList<>(); for (CompletableFuture<T> aFuture : futures) { results.add(aFuture.join()); } future.complete(results); }); return future; } public static <T> CompletableFuture<T> timeout(DiscordSRV discordSRV, CompletableFuture<T> future, Duration timeout) { ScheduledFuture<?> scheduledFuture = discordSRV.scheduler().runLater(() -> { if (!future.isDone()) { future.completeExceptionally(new TimeoutException()); } }, timeout); return future.whenComplete((__, t) -> { if (t == null) { scheduledFuture.cancel(false); } }); } }
2,888
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
LinkStore.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/linking/LinkStore.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.linking; import org.jetbrains.annotations.NotNull; import java.time.Duration; import java.util.UUID; import java.util.concurrent.CompletableFuture; public interface LinkStore extends LinkProvider { Duration LINKING_CODE_EXPIRY_TIME = Duration.ofMinutes(5); Duration LINKING_CODE_RATE_LIMIT = Duration.ofSeconds(5); CompletableFuture<Void> createLink(@NotNull UUID playerUUID, long userId); CompletableFuture<Void> removeLink(@NotNull UUID playerUUID, long userId); CompletableFuture<UUID> getCodeLinking(long userId, @NotNull String code); CompletableFuture<Void> removeLinkingCode(@NotNull String code); CompletableFuture<Void> removeLinkingCode(@NotNull UUID playerUUID); CompletableFuture<Integer> getLinkedAccountCount(); }
1,627
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
LinkProvider.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/linking/LinkProvider.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.linking; import com.discordsrv.api.component.MinecraftComponent; import com.discordsrv.common.player.IPlayer; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Locale; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; public interface LinkProvider { default CompletableFuture<Optional<Long>> queryUserId(@NotNull UUID playerUUID) { return queryUserId(playerUUID, false); } CompletableFuture<Optional<Long>> queryUserId(@NotNull UUID playerUUID, boolean canCauseLink); default CompletableFuture<Optional<Long>> getUserId(@NotNull UUID playerUUID) { Optional<Long> userId = getCachedUserId(playerUUID); if (userId.isPresent()) { return CompletableFuture.completedFuture(userId); } return queryUserId(playerUUID); } default Optional<Long> getCachedUserId(@NotNull UUID playerUUID) { return Optional.empty(); } default CompletableFuture<Optional<UUID>> queryPlayerUUID(long userId) { return queryPlayerUUID(userId, false); } CompletableFuture<Optional<UUID>> queryPlayerUUID(long userId, boolean canCauseLink); default CompletableFuture<Optional<UUID>> getPlayerUUID(long userId) { Optional<UUID> playerUUID = getCachedPlayerUUID(userId); if (playerUUID.isPresent()) { return CompletableFuture.completedFuture(playerUUID); } return queryPlayerUUID(userId); } default Optional<UUID> getCachedPlayerUUID(long userId) { return Optional.empty(); } default CompletableFuture<MinecraftComponent> getLinkingInstructions(@NotNull IPlayer player, @Nullable String requestReason) { return getLinkingInstructions(player.username(), player.uniqueId(), player.locale(), requestReason); } CompletableFuture<MinecraftComponent> getLinkingInstructions( String username, UUID playerUUID, @Nullable Locale locale, @Nullable String requestReason ); }
2,948
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
LinkingModule.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/linking/LinkingModule.java
package com.discordsrv.common.linking; import com.discordsrv.api.event.events.linking.AccountLinkedEvent; import com.discordsrv.api.event.events.linking.AccountUnlinkedEvent; import com.discordsrv.api.profile.IProfile; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.logging.NamedLogger; import com.discordsrv.common.module.type.AbstractModule; import java.util.UUID; public class LinkingModule extends AbstractModule<DiscordSRV> { public LinkingModule(DiscordSRV discordSRV) { super(discordSRV, new NamedLogger(discordSRV, "LINKING")); } public void linked(UUID playerUUID, long userId) { IProfile profile = discordSRV.profileManager().getProfile(playerUUID); if (profile == null || !profile.isLinked()) { throw new IllegalStateException("Notified that account linked, but profile is null or unlinked"); } discordSRV.eventBus().publish(new AccountLinkedEvent(profile)); } public void unlinked(UUID playerUUID, long userId) { discordSRV.eventBus().publish(new AccountUnlinkedEvent(playerUUID, userId)); } }
1,120
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ServerRequireLinkingModule.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/linking/requirelinking/ServerRequireLinkingModule.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.linking.requirelinking; import com.discordsrv.api.DiscordSRVApi; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.component.util.ComponentUtil; import com.discordsrv.common.config.main.linking.RequirementsConfig; import com.discordsrv.common.config.main.linking.ServerRequiredLinkingConfig; import com.discordsrv.common.future.util.CompletableFutureUtil; import com.discordsrv.common.linking.LinkProvider; import com.discordsrv.common.linking.requirelinking.requirement.MinecraftAuthRequirement; import net.kyori.adventure.text.Component; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Consumer; public abstract class ServerRequireLinkingModule<T extends DiscordSRV> extends RequiredLinkingModule<T> { private final List<CompiledRequirement> compiledRequirements = new CopyOnWriteArrayList<>(); public ServerRequireLinkingModule(T discordSRV) { super(discordSRV); } @Override public abstract ServerRequiredLinkingConfig config(); @Override public void reload(Consumer<DiscordSRVApi.ReloadResult> resultConsumer) { super.reload(resultConsumer); synchronized (compiledRequirements) { activeRequirementTypes.clear(); compiledRequirements.clear(); compiledRequirements.addAll(compile(config().requirements.requirements)); } } public List<MinecraftAuthRequirement.Type> getRequirementTypes() { return activeRequirementTypes; } public CompletableFuture<Component> getBlockReason(UUID playerUUID, String playerName, boolean join) { RequirementsConfig config = config().requirements; if (config.bypassUUIDs.contains(playerUUID.toString())) { // Bypasses: let them through logger().debug("Player " + playerName + " is bypassing required linking requirements"); return CompletableFuture.completedFuture(null); } LinkProvider linkProvider = discordSRV.linkProvider(); if (linkProvider == null) { // Link provider unavailable but required linking enabled: error message Component message = ComponentUtil.fromAPI( discordSRV.messagesConfig().minecraft.unableToCheckLinkingStatus.textBuilder().build() ); return CompletableFuture.completedFuture(message); } return linkProvider.queryUserId(playerUUID, true) .thenCompose(opt -> { if (!opt.isPresent()) { // User is not linked return linkProvider.getLinkingInstructions(playerName, playerUUID, null, join ? "join" : "freeze") .thenApply(ComponentUtil::fromAPI); } List<CompiledRequirement> requirements; synchronized (compiledRequirements) { requirements = compiledRequirements; } if (requirements.isEmpty()) { // No additional requirements: let them through return CompletableFuture.completedFuture(null); } CompletableFuture<Void> pass = new CompletableFuture<>(); List<CompletableFuture<Boolean>> all = new ArrayList<>(); long userId = opt.get(); for (CompiledRequirement requirement : requirements) { CompletableFuture<Boolean> future = requirement.function().apply(playerUUID, userId); all.add(future); future.whenComplete((val, t) -> { if (val != null && val) { pass.complete(null); } }).exceptionally(t -> { logger().debug("Check \"" + requirement.input() + "\" failed for " + playerName + " / " + Long.toUnsignedString(userId), t); return null; }); } // Complete when at least one passes or all of them completed return CompletableFuture.anyOf(pass, CompletableFutureUtil.combine(all)) .thenApply(v -> { if (pass.isDone()) { // One of the futures passed: let them through return null; } // None of the futures passed: requirements not met return Component.text("You did not pass requirements"); }); }); } }
5,769
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
RequiredLinkingModule.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/linking/requirelinking/RequiredLinkingModule.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.linking.requirelinking; import com.discordsrv.api.DiscordSRVApi; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.config.main.linking.RequiredLinkingConfig; import com.discordsrv.common.linking.impl.MinecraftAuthenticationLinker; import com.discordsrv.common.linking.requirelinking.requirement.*; import com.discordsrv.common.linking.requirelinking.requirement.parser.RequirementParser; import com.discordsrv.common.module.type.AbstractModule; import com.discordsrv.common.scheduler.Scheduler; import com.discordsrv.common.scheduler.executor.DynamicCachingThreadPoolExecutor; import com.discordsrv.common.scheduler.threadfactory.CountingThreadFactory; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.function.BiFunction; import java.util.function.Consumer; public abstract class RequiredLinkingModule<T extends DiscordSRV> extends AbstractModule<T> { private final List<Requirement<?>> availableRequirements = new ArrayList<>(); protected final List<MinecraftAuthRequirement.Type> activeRequirementTypes = new ArrayList<>(); private ThreadPoolExecutor executor; public RequiredLinkingModule(T discordSRV) { super(discordSRV); } public abstract RequiredLinkingConfig config(); @Override public boolean isEnabled() { return config().enabled; } @Override public void enable() { executor = new DynamicCachingThreadPoolExecutor( 1, Math.max(2, Runtime.getRuntime().availableProcessors() / 2), 10, TimeUnit.SECONDS, new SynchronousQueue<>(), new CountingThreadFactory(Scheduler.THREAD_NAME_PREFIX + "RequiredLinking #%s") ); super.enable(); } @Override public void disable() { if (executor != null) { executor.shutdown(); } } @Override public void reload(Consumer<DiscordSRVApi.ReloadResult> resultConsumer) { List<Requirement<?>> requirements = new ArrayList<>(); requirements.add(new DiscordRoleRequirement(discordSRV)); requirements.add(new DiscordServerRequirement(discordSRV)); requirements.add(new DiscordBoostingRequirement(discordSRV)); if (discordSRV.linkProvider() instanceof MinecraftAuthenticationLinker) { requirements.addAll(MinecraftAuthRequirement.createRequirements(discordSRV)); } synchronized (availableRequirements) { availableRequirements.clear(); availableRequirements.addAll(requirements); } } public List<MinecraftAuthRequirement.Type> getActiveRequirementTypes() { return activeRequirementTypes; } protected List<CompiledRequirement> compile(List<String> requirements) { List<CompiledRequirement> checks = new ArrayList<>(); for (String requirement : requirements) { BiFunction<UUID, Long, CompletableFuture<Boolean>> function = RequirementParser.getInstance().parse(requirement, availableRequirements, activeRequirementTypes); checks.add(new CompiledRequirement(requirement, function)); } return checks; } public static class CompiledRequirement { private final String input; private final BiFunction<UUID, Long, CompletableFuture<Boolean>> function; protected CompiledRequirement(String input, BiFunction<UUID, Long, CompletableFuture<Boolean>> function) { this.input = input; this.function = function; } public String input() { return input; } public BiFunction<UUID, Long, CompletableFuture<Boolean>> function() { return function; } } }
4,933
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordRoleRequirement.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/linking/requirelinking/requirement/DiscordRoleRequirement.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.linking.requirelinking.requirement; import com.discordsrv.api.discord.entity.guild.DiscordRole; import com.discordsrv.common.DiscordSRV; import java.util.UUID; import java.util.concurrent.CompletableFuture; public class DiscordRoleRequirement extends LongRequirement { private final DiscordSRV discordSRV; public DiscordRoleRequirement(DiscordSRV discordSRV) { this.discordSRV = discordSRV; } @Override public String name() { return "DiscordRole"; } @Override public CompletableFuture<Boolean> isMet(Long value, UUID player, long userId) { DiscordRole role = discordSRV.discordAPI().getRoleById(value); if (role == null) { return CompletableFuture.completedFuture(false); } return role.getGuild() .retrieveMemberById(userId) .thenApply(member -> member.getRoles().contains(role)); } }
1,781
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
LongRequirement.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/linking/requirelinking/requirement/LongRequirement.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.linking.requirelinking.requirement; public abstract class LongRequirement implements Requirement<Long> { @Override public Long parse(String input) { try { return Long.parseUnsignedLong(input); } catch (NumberFormatException ignored) {} return null; } }
1,163
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordServerRequirement.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/linking/requirelinking/requirement/DiscordServerRequirement.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.linking.requirelinking.requirement; import com.discordsrv.api.discord.entity.guild.DiscordGuild; import com.discordsrv.common.DiscordSRV; import java.util.Objects; import java.util.UUID; import java.util.concurrent.CompletableFuture; public class DiscordServerRequirement extends LongRequirement { private final DiscordSRV discordSRV; public DiscordServerRequirement(DiscordSRV discordSRV) { this.discordSRV = discordSRV; } @Override public String name() { return "DiscordServer"; } @Override public CompletableFuture<Boolean> isMet(Long value, UUID player, long userId) { DiscordGuild guild = discordSRV.discordAPI().getGuildById(value); if (guild == null) { return CompletableFuture.completedFuture(false); } return guild.retrieveMemberById(userId) .thenApply(Objects::nonNull); } }
1,765
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
Requirement.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/linking/requirelinking/requirement/Requirement.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.linking.requirelinking.requirement; import java.util.UUID; import java.util.concurrent.CompletableFuture; public interface Requirement<T> { String name(); T parse(String input); CompletableFuture<Boolean> isMet(T value, UUID player, long userId); }
1,127
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
MinecraftAuthRequirement.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/linking/requirelinking/requirement/MinecraftAuthRequirement.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.linking.requirelinking.requirement; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.function.CheckedSupplier; import me.minecraftauth.lib.AuthService; import me.minecraftauth.lib.account.platform.twitch.SubTier; import me.minecraftauth.lib.exception.LookupException; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.function.Function; public class MinecraftAuthRequirement<T> implements Requirement<MinecraftAuthRequirement.Reference<T>> { private static final Reference<?> NULL_VALUE = new Reference<>(null); public static List<Requirement<?>> createRequirements(DiscordSRV discordSRV) { List<Requirement<?>> requirements = new ArrayList<>(); // Patreon requirements.add(new MinecraftAuthRequirement<>( discordSRV, Type.PATREON, "PatreonSubscriber", AuthService::isSubscribedPatreon, AuthService::isSubscribedPatreon )); // Glimpse requirements.add(new MinecraftAuthRequirement<>( discordSRV, Type.GLIMPSE, "GlimpseSubscriber", AuthService::isSubscribedGlimpse, AuthService::isSubscribedGlimpse )); // Twitch requirements.add(new MinecraftAuthRequirement<>( discordSRV, Type.TWITCH, "TwitchFollower", AuthService::isFollowingTwitch )); requirements.add(new MinecraftAuthRequirement<>( discordSRV, Type.TWITCH, "TwitchSubscriber", AuthService::isSubscribedTwitch, AuthService::isSubscribedTwitch, string -> { try { int value = Integer.parseInt(string); return SubTier.level(value); } catch (NumberFormatException ignored) { return null; } } )); // YouTube requirements.add(new MinecraftAuthRequirement<>( discordSRV, Type.YOUTUBE, "YouTubeSubscriber", AuthService::isSubscribedYouTube )); requirements.add(new MinecraftAuthRequirement<>( discordSRV, Type.YOUTUBE, "YouTubeMember", AuthService::isMemberYouTube, AuthService::isMemberYouTube )); return requirements; } private final DiscordSRV discordSRV; private final Type type; private final String name; private final Test test; private final TestSpecific<T> testSpecific; private final Function<String, T> parse; public MinecraftAuthRequirement( DiscordSRV discordSRV, Type type, String name, Test test ) { this(discordSRV, type, name, test, null, null); } @SuppressWarnings("unchecked") public MinecraftAuthRequirement( DiscordSRV discordSRV, Type type, String name, Test test, TestSpecific<String> testSpecific ) { this(discordSRV, type, name, test, (TestSpecific<T>) testSpecific, t -> (T) t); } public MinecraftAuthRequirement( DiscordSRV discordSRV, Type type, String name, Test test, TestSpecific<T> testSpecific, Function<String, T> parse ) { this.discordSRV = discordSRV; this.type = type; this.name = name; this.test = test; this.testSpecific = testSpecific; this.parse = parse; } @Override public String name() { return name; } public Type getType() { return type; } @SuppressWarnings("unchecked") @Override public Reference<T> parse(String input) { if (StringUtils.isEmpty(input)) { return (Reference<T>) NULL_VALUE; } else if (parse != null) { return new Reference<>(parse.apply(input)); } else { return null; } } @Override public CompletableFuture<Boolean> isMet(Reference<T> atomicReference, UUID player, long userId) { String token = discordSRV.connectionConfig().minecraftAuth.token; T value = atomicReference.getValue(); if (value == null) { return supply(() -> test.test(token, player)); } else { return supply(() -> testSpecific.test(token, player, value)); } } private CompletableFuture<Boolean> supply(CheckedSupplier<Boolean> provider) { CompletableFuture<Boolean> completableFuture = new CompletableFuture<>(); discordSRV.scheduler().run(() -> { try { completableFuture.complete(provider.get()); } catch (Throwable t) { completableFuture.completeExceptionally(t); } }); return completableFuture; } @FunctionalInterface public interface Test { boolean test(String serverToken, UUID player) throws LookupException; } @FunctionalInterface public interface TestSpecific<T> { boolean test(String serverToken, UUID uuid, T specific) throws LookupException; } public static class Reference<T> { private final T value; public Reference(T value) { this.value = value; } public T getValue() { return value; } } public enum Type { PATREON('p'), GLIMPSE('g'), TWITCH('t'), YOUTUBE('y'); private final char character; Type(char character) { this.character = character; } public char character() { return character; } } }
6,925
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordBoostingRequirement.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/linking/requirelinking/requirement/DiscordBoostingRequirement.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.linking.requirelinking.requirement; import com.discordsrv.api.discord.entity.guild.DiscordGuild; import com.discordsrv.common.DiscordSRV; import java.util.UUID; import java.util.concurrent.CompletableFuture; public class DiscordBoostingRequirement extends LongRequirement { private final DiscordSRV discordSRV; public DiscordBoostingRequirement(DiscordSRV discordSRV) { this.discordSRV = discordSRV; } @Override public String name() { return "DiscordBoosting"; } @Override public CompletableFuture<Boolean> isMet(Long value, UUID player, long userId) { DiscordGuild guild = discordSRV.discordAPI().getGuildById(value); if (guild == null) { return CompletableFuture.completedFuture(false); } return guild.retrieveMemberById(userId) .thenApply(member -> member != null && member.isBoosting()); } }
1,776
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
RequirementParser.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/linking/requirelinking/requirement/parser/RequirementParser.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.linking.requirelinking.requirement.parser; import com.discordsrv.common.future.util.CompletableFutureUtil; import com.discordsrv.common.linking.requirelinking.requirement.MinecraftAuthRequirement; import com.discordsrv.common.linking.requirelinking.requirement.Requirement; import org.apache.commons.lang3.StringUtils; import java.util.ArrayList; import java.util.List; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.atomic.AtomicInteger; import java.util.function.BiFunction; import java.util.function.Function; public class RequirementParser { private static RequirementParser INSTANCE; public static RequirementParser getInstance() { return INSTANCE != null ? INSTANCE : (INSTANCE = new RequirementParser()); } private RequirementParser() {} @SuppressWarnings("unchecked") public <T> BiFunction<UUID, Long, CompletableFuture<Boolean>> parse(String input, List<Requirement<?>> requirements, List<MinecraftAuthRequirement.Type> types) { List<Requirement<T>> reqs = new ArrayList<>(requirements.size()); requirements.forEach(r -> reqs.add((Requirement<T>) r)); Func func = parse(input, new AtomicInteger(0), reqs, types); return func::test; } private <T> Func parse(String input, AtomicInteger iterator, List<Requirement<T>> requirements, List<MinecraftAuthRequirement.Type> types) { StringBuilder functionNameBuffer = new StringBuilder(); StringBuilder functionValueBuffer = new StringBuilder(); boolean isFunctionValue = false; Func func = null; Operator operator = null; boolean operatorSecond = false; Function<String, RuntimeException> error = text -> { int i = iterator.get(); return new IllegalArgumentException(text + "\n" + input + "\n" + StringUtils.leftPad("^", i)); }; char[] chars = input.toCharArray(); int i; for (; (i = iterator.get()) < chars.length; iterator.incrementAndGet()) { char c = chars[i]; if (c == '(' && functionNameBuffer.length() == 0) { iterator.incrementAndGet(); Func function = parse(input, iterator, requirements, types); if (function == null) { throw error.apply("Empty brackets"); } if (func != null) { if (operator == null) { throw error.apply("No operator"); } func = operator.function.apply(func, function); operator = null; } else { func = function; } continue; } if (c == ')' && functionNameBuffer.length() == 0) { return func; } if (c == '(' && functionNameBuffer.length() > 0) { if (isFunctionValue) { throw error.apply("Opening bracket inside function value"); } isFunctionValue = true; continue; } if (c == ')' && functionNameBuffer.length() > 0) { String functionName = functionNameBuffer.toString(); String value = functionValueBuffer.toString(); for (Requirement<T> requirement : requirements) { if (requirement.name().equalsIgnoreCase(functionName)) { if (requirement instanceof MinecraftAuthRequirement) { types.add(((MinecraftAuthRequirement<?>) requirement).getType()); } T requirementValue = requirement.parse(value); if (requirementValue == null) { throw error.apply("Unacceptable function value for " + functionName); } Func function = (player, user) -> requirement.isMet(requirementValue, player, user); if (func != null) { if (operator == null) { throw error.apply("No operator"); } func = operator.function.apply(func, function); operator = null; } else { func = function; } functionNameBuffer.setLength(0); functionValueBuffer.setLength(0); isFunctionValue = false; break; } } if (functionNameBuffer.length() != 0) { throw error.apply("Unknown function: " + functionName); } continue; } if (operator != null && !operatorSecond && c == operator.character) { operatorSecond = true; continue; } else if (operator == null && functionNameBuffer.length() == 0) { boolean found = false; for (Operator value : Operator.values()) { if (value.character == c) { if (func == null) { throw error.apply("No condition"); } operator = value; operatorSecond = false; found = true; break; } } if (found) { continue; } } if (operator != null && !operatorSecond) { throw error.apply("Operators must be exactly two of the same character"); } if (!Character.isSpaceChar(c)) { if (isFunctionValue) { functionValueBuffer.append(c); } else { functionNameBuffer.append(c); } } } if (operator != null) { throw error.apply("Dangling operator"); } return func; } @FunctionalInterface private interface Func { CompletableFuture<Boolean> test(UUID player, long user); } private enum Operator { AND('&', (one, two) -> apply(one, two, (o, t) -> o && t)), OR('|', (one, two) -> apply(one, two, (o, t) -> o || t)); private final char character; private final BiFunction<Func, Func, Func> function; Operator(char character, BiFunction<Func, Func, Func> function) { this.character = character; this.function = function; } private static Func apply(Func one, Func two, BiFunction<Boolean, Boolean, Boolean> function) { return (player, user) -> CompletableFutureUtil.combine(one.test(player, user), two.test(player, user)) .thenApply(bools -> function.apply(bools.get(0), bools.get(1))); } } }
7,962
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
CachedLinkProvider.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/linking/impl/CachedLinkProvider.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.linking.impl; import com.discordsrv.api.event.bus.Subscribe; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.event.events.player.PlayerConnectedEvent; import com.discordsrv.common.linking.LinkProvider; import com.github.benmanes.caffeine.cache.AsyncCacheLoader; import com.github.benmanes.caffeine.cache.AsyncLoadingCache; import com.github.benmanes.caffeine.cache.Cache; import com.github.benmanes.caffeine.cache.Expiry; import org.checkerframework.checker.index.qual.NonNegative; import org.checkerframework.checker.nullness.qual.NonNull; import org.jetbrains.annotations.NotNull; import java.util.Optional; import java.util.Set; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CopyOnWriteArraySet; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; public abstract class CachedLinkProvider implements LinkProvider { private static final long UNLINKED_USER = -1L; private static final UUID UNLINKED_UUID = new UUID(0, 0); protected final DiscordSRV discordSRV; private final Cache<Long, UUID> userToPlayer; private final AsyncLoadingCache<UUID, Long> playerToUser; private final Set<UUID> linkingAllowed = new CopyOnWriteArraySet<>(); public CachedLinkProvider(DiscordSRV discordSRV) { this.discordSRV = discordSRV; this.userToPlayer = discordSRV.caffeineBuilder().build(); this.playerToUser = discordSRV.caffeineBuilder() .expireAfter(new Expiry<UUID, Long>() { @Override public long expireAfterCreate(@NonNull UUID key, @NonNull Long value, long currentTime) { if (value == UNLINKED_USER) { return Long.MAX_VALUE; } return TimeUnit.MINUTES.toNanos(5); } @Override public long expireAfterUpdate( @NonNull UUID key, @NonNull Long value, long currentTime, @NonNegative long currentDuration ) { if (value == UNLINKED_USER) { return Long.MAX_VALUE; } return currentDuration; } @Override public long expireAfterRead( @NonNull UUID key, @NonNull Long value, long currentTime, @NonNegative long currentDuration ) { return currentDuration; } }) .removalListener((key, value, cause) -> { if (value != null) { userToPlayer.invalidate(value); } }) .buildAsync(new AsyncCacheLoader<UUID, Long>() { @Override public @NonNull CompletableFuture<Long> asyncLoad(@NonNull UUID key, @NonNull Executor executor) { return queryUserId(key, linkingAllowed.remove(key)).thenApply(opt -> opt.orElse(UNLINKED_USER)); } @Override public @NonNull CompletableFuture<Long> asyncReload( @NonNull UUID key, @NonNull Long oldValue, @NonNull Executor executor ) { if (discordSRV.playerProvider().player(key) == null) { // Don't keep players that aren't online in cache return CompletableFuture.completedFuture(null); } return asyncLoad(key, executor); } }); discordSRV.eventBus().subscribe(this); } @Override public CompletableFuture<Optional<Long>> getUserId(@NotNull UUID playerUUID) { return playerToUser.get(playerUUID).thenApply(value -> { if (value == UNLINKED_USER) { return Optional.empty(); } return Optional.of(value); }); } @Override public Optional<Long> getCachedUserId(@NotNull UUID player) { Long value = playerToUser.synchronous().getIfPresent(player); return Optional.ofNullable(value == null || value == UNLINKED_USER ? null : value); } @Override public CompletableFuture<Optional<UUID>> getPlayerUUID(long userId) { UUID player = userToPlayer.getIfPresent(userId); if (player != null) { return CompletableFuture.completedFuture(player == UNLINKED_UUID ? Optional.empty() : Optional.of(player)); } return queryPlayerUUID(userId).thenApply(optional -> { if (!optional.isPresent()) { userToPlayer.put(userId, UNLINKED_UUID); return optional; } UUID uuid = optional.get(); userToPlayer.put(userId, uuid); return optional; }); } @Override public Optional<UUID> getCachedPlayerUUID(long discordId) { UUID value = userToPlayer.getIfPresent(discordId); return Optional.ofNullable(value == null || value == UNLINKED_UUID ? null : value); } @Subscribe public void onPlayerConnected(PlayerConnectedEvent event) { // Cache logged in players UUID uuid = event.player().uniqueId(); linkingAllowed.add(uuid); playerToUser.get(uuid); linkingAllowed.remove(uuid); } }
6,626
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
MinecraftAuthenticationLinker.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/linking/impl/MinecraftAuthenticationLinker.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.linking.impl; import com.discordsrv.api.component.MinecraftComponent; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.function.CheckedSupplier; import com.discordsrv.common.future.util.CompletableFutureUtil; import com.discordsrv.common.linking.LinkProvider; import com.discordsrv.common.linking.LinkStore; import com.discordsrv.common.linking.LinkingModule; import com.discordsrv.common.linking.requirelinking.RequiredLinkingModule; import com.discordsrv.common.linking.requirelinking.requirement.MinecraftAuthRequirement; import com.discordsrv.common.logging.Logger; import com.discordsrv.common.logging.NamedLogger; import com.discordsrv.common.player.IPlayer; import me.minecraftauth.lib.AuthService; import me.minecraftauth.lib.account.AccountType; import me.minecraftauth.lib.account.platform.discord.DiscordAccount; import me.minecraftauth.lib.account.platform.minecraft.MinecraftAccount; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.Locale; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; import java.util.function.Consumer; import java.util.function.Supplier; public class MinecraftAuthenticationLinker extends CachedLinkProvider implements LinkProvider { public static final String BASE_LINK_URL = DiscordSRV.WEBSITE + "/link"; private final Logger logger; private final LinkStore linkStore; public MinecraftAuthenticationLinker(DiscordSRV discordSRV) { super(discordSRV); this.linkStore = new StorageLinker(discordSRV); this.logger = new NamedLogger(discordSRV, "MINECRAFTAUTH_LINKER"); } @Override public CompletableFuture<Optional<Long>> queryUserId(@NotNull UUID playerUUID, boolean canCauseLink) { return query( canCauseLink, () -> AuthService.lookup(AccountType.MINECRAFT, playerUUID.toString(), AccountType.DISCORD) .map(account -> (DiscordAccount) account) .map(discord -> Long.parseUnsignedLong(discord.getUserId())), () -> linkStore.getUserId(playerUUID), userId -> linked(playerUUID, userId), userId -> unlinked(playerUUID, userId) ).exceptionally(t -> { logger.error("Lookup for uuid " + playerUUID + " failed", t); return Optional.empty(); }); } @Override public CompletableFuture<Optional<UUID>> queryPlayerUUID(long userId, boolean canCauseLink) { return query( canCauseLink, () -> AuthService.lookup(AccountType.DISCORD, Long.toUnsignedString(userId), AccountType.MINECRAFT) .map(account -> (MinecraftAccount) account) .map(MinecraftAccount::getUUID), () -> linkStore.getPlayerUUID(userId), playerUUID -> linked(playerUUID, userId), playerUUID -> unlinked(playerUUID, userId) ).exceptionally(t -> { logger.error("Lookup for user id " + Long.toUnsignedString(userId) + " failed", t); return Optional.empty(); }); } @Override public CompletableFuture<MinecraftComponent> getLinkingInstructions(@NotNull IPlayer player, @Nullable String requestReason) { return getInstructions(player, requestReason); } @Override public CompletableFuture<MinecraftComponent> getLinkingInstructions(String username, UUID playerUUID, Locale locale, @Nullable String requestReason) { return getInstructions(null, requestReason); } private CompletableFuture<MinecraftComponent> getInstructions(@Nullable IPlayer player, @Nullable String requestReason) { String method = null; if (requestReason != null) { requestReason = requestReason.toLowerCase(Locale.ROOT); if (requestReason.startsWith("discord")) { method = "discord"; } else if (requestReason.startsWith("link")) { method = "link"; } else if (requestReason.startsWith("freeze")) { method = "freeze"; } } StringBuilder additionalParam = new StringBuilder(); RequiredLinkingModule<?> requiredLinkingModule = discordSRV.getModule(RequiredLinkingModule.class); if (requiredLinkingModule != null && requiredLinkingModule.isEnabled()) { for (MinecraftAuthRequirement.Type requirementType : requiredLinkingModule.getActiveRequirementTypes()) { additionalParam.append(requirementType.character()); } } String url = BASE_LINK_URL + (additionalParam.length() > 0 ? "/" + additionalParam : ""); String simple = url.substring(url.indexOf("://") + 3); // Remove protocol & don't include method query parameter MinecraftComponent component = discordSRV.messagesConfig(player).minecraftAuthLinking.textBuilder() .addContext(player) .addPlaceholder("minecraftauth_link", url + (method != null ? "?command=" + method : null)) .addPlaceholder("minecraftauth_link_simple", simple) .applyPlaceholderService() .build(); return CompletableFuture.completedFuture(component); } private void linked(UUID playerUUID, long userId) { logger.debug("New link: " + playerUUID + " & " + Long.toUnsignedString(userId)); linkStore.createLink(playerUUID, userId).whenComplete((v, t) -> { if (t != null) { logger.error("Failed to link player persistently", t); return; } module().linked(playerUUID, userId); }); } private void unlinked(UUID playerUUID, long userId) { logger.debug("Unlink: " + playerUUID + " & " + Long.toUnsignedString(userId)); linkStore.createLink(playerUUID, userId).whenComplete((v, t) -> { if (t != null) { logger.error("Failed to unlink player in persistent storage", t); return; } module().unlinked(playerUUID, userId); }); } private LinkingModule module() { LinkingModule module = discordSRV.getModule(LinkingModule.class); if (module == null) { throw new IllegalStateException("LinkingModule not available"); } return module; } private <T> CompletableFuture<Optional<T>> query( boolean canCauseLink, CheckedSupplier<Optional<T>> authSupplier, Supplier<CompletableFuture<Optional<T>>> storageSupplier, Consumer<T> linked, Consumer<T> unlinked ) { CompletableFuture<Optional<T>> authService = new CompletableFuture<>(); discordSRV.scheduler().run(() -> { try { authService.complete(authSupplier.get()); } catch (Throwable t) { authService.completeExceptionally(t); } }); if (!canCauseLink) { return authService; } CompletableFuture<Optional<T>> storageFuture = storageSupplier.get(); return CompletableFutureUtil.combine(authService, storageFuture).thenApply(results -> { Optional<T> auth = authService.join(); Optional<T> storage = storageFuture.join(); if (auth.isPresent() && !storage.isPresent()) { // new link linked.accept(auth.get()); } if (!auth.isPresent() && storage.isPresent()) { // unlink unlinked.accept(storage.get()); } if (auth.isPresent() && storage.isPresent() && !auth.get().equals(storage.get())) { // linked account changed unlinked.accept(storage.get()); linked.accept(auth.get()); } return auth; }); } }
8,859
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
StorageLinker.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/linking/impl/StorageLinker.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.linking.impl; import com.discordsrv.api.component.MinecraftComponent; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.component.util.ComponentUtil; import com.discordsrv.common.linking.LinkProvider; import com.discordsrv.common.linking.LinkStore; import net.kyori.adventure.text.Component; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.security.SecureRandom; import java.util.Locale; import java.util.Optional; import java.util.UUID; import java.util.concurrent.CompletableFuture; public class StorageLinker extends CachedLinkProvider implements LinkProvider, LinkStore { public StorageLinker(DiscordSRV discordSRV) { super(discordSRV); } @Override public CompletableFuture<Optional<Long>> queryUserId(@NotNull UUID playerUUID, boolean canCauseLink) { return CompletableFuture.supplyAsync(() -> { Long value = discordSRV.storage().getUserId(playerUUID); return Optional.ofNullable(value); }, discordSRV.scheduler().executor()); } @Override public CompletableFuture<Optional<UUID>> queryPlayerUUID(long userId, boolean canCauseLink) { return CompletableFuture.supplyAsync(() -> { UUID value = discordSRV.storage().getPlayerUUID(userId); return Optional.ofNullable(value); }, discordSRV.scheduler().executor()); } @Override public CompletableFuture<Void> createLink(@NotNull UUID playerUUID, long userId) { return CompletableFuture.runAsync( () -> discordSRV.storage().createLink(playerUUID, userId), discordSRV.scheduler().executor() ); } @Override public CompletableFuture<Void> removeLink(@NotNull UUID playerUUID, long userId) { return CompletableFuture.runAsync( () -> discordSRV.storage().removeLink(playerUUID, userId), discordSRV.scheduler().executor() ); } @Override public CompletableFuture<UUID> getCodeLinking(long userId, @NotNull String code) { return CompletableFuture.supplyAsync( () -> discordSRV.storage().getLinkingCode(code), discordSRV.scheduler().executor() ); } @Override public CompletableFuture<Void> removeLinkingCode(@NotNull String code) { return CompletableFuture.runAsync( () -> { UUID player = discordSRV.storage().getLinkingCode(code); discordSRV.storage().removeLinkingCode(player); }, discordSRV.scheduler().executor() ); } @Override public CompletableFuture<Void> removeLinkingCode(@NotNull UUID playerUUID) { return CompletableFuture.runAsync( () -> discordSRV.storage().removeLinkingCode(playerUUID), discordSRV.scheduler().executor() ); } @Override public CompletableFuture<Integer> getLinkedAccountCount() { return CompletableFuture.supplyAsync( () -> discordSRV.storage().getLinkedAccountCount(), discordSRV.scheduler().executor() ); } private final SecureRandom secureRandom = new SecureRandom(); @Override public CompletableFuture<MinecraftComponent> getLinkingInstructions(String username, UUID playerUUID, @Nullable Locale locale, @Nullable String requestReason) { return CompletableFuture.supplyAsync( () -> { String code = null; while (code == null || discordSRV.storage().getLinkingCode(code) != null) { code = String.valueOf(secureRandom.nextInt(1000000)); while (code.length() != 6) { code = "0" + code; } } discordSRV.storage().storeLinkingCode(playerUUID, code); return ComponentUtil.toAPI(Component.text(code)); }, discordSRV.scheduler().executor() ); } }
4,970
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
Config.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/Config.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.config; /** * Helper class to identify which file a given config instance belongs to. */ public interface Config { String getFileName(); }
1,007
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
MessagesMainConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/MessagesMainConfig.java
package com.discordsrv.common.config.main; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Comment; @ConfigSerializable public class MessagesMainConfig { @Comment("The language code for the default language, if left blank the system default will be used.\n" + "This should be in the ISO 639-1 format or ISO 639-1 (for example \"en\"), a underscore and a ISO 3166-1 country code to specify dialect (for example \"pt_BR\")") public String defaultLanguage = "en"; @Comment("If there should be a messages file per language (based on the player's or user's language), otherwise using the default") public boolean multiple = false; @Comment("If all languages provided with DiscordSRV should be loaded into the messages directory, only functions when \"multiple\" is set to true") public boolean loadAllDefaults = true; }
935
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
PluginIntegrationConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/PluginIntegrationConfig.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.config.main; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Comment; import java.util.ArrayList; import java.util.List; @ConfigSerializable public class PluginIntegrationConfig { @Comment("Plugin integrations that should be disabled. Specify the names or ids of plugins to disable integrations for") public List<String> disabledIntegrations = new ArrayList<>(); }
1,316
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordCommandConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/DiscordCommandConfig.java
package com.discordsrv.common.config.main; import com.discordsrv.common.config.configurate.annotation.Constants; import com.discordsrv.common.config.main.generic.GameCommandExecutionConditionConfig; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Comment; import java.util.ArrayList; import java.util.Arrays; import java.util.List; @ConfigSerializable public class DiscordCommandConfig { public ExecuteConfig execute = new ExecuteConfig(); @ConfigSerializable public static class ExecuteConfig { public ExecuteConfig() { executionConditions.add( new GameCommandExecutionConditionConfig( new ArrayList<>(), false, new ArrayList<>(Arrays.asList("say", "/gamemode(?: (?:survival|spectator)(?: .+)?)?/")) ) ); } public boolean enabled = true; @Comment("If the command output should only be visible to the user who ran the command") public boolean ephemeral = true; @Comment("The mode for the command output, available options are:\n" + "- markdown: Regular Discord markdown\n" + "- ansi: A colored ansi code block\n" + "- plain: Plain text\n" + "- code_block: Plain code block\n" + "- off: No command output") public OutputMode outputMode = OutputMode.MARKDOWN; @Comment("At least one condition has to match to allow execution") public List<GameCommandExecutionConditionConfig> executionConditions = new ArrayList<>(); @Comment("If commands should be suggested while typing\n" + "Suggestions go through the server's main thread (on servers with a main thread) to ensure compatability.") public boolean suggest = true; @Comment("If suggestions should be filtered based on the \"%1\" option") @Constants.Comment("filters") public boolean filterSuggestions = true; } public enum OutputMode { MARKDOWN, ANSI, PLAIN, CODEBLOCK, OFF } }
2,239
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
GroupSyncConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/GroupSyncConfig.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.config.main; import com.discordsrv.common.DiscordSRV; import com.discordsrv.common.config.configurate.annotation.Constants; import com.discordsrv.common.groupsync.enums.GroupSyncDirection; import com.discordsrv.common.groupsync.enums.GroupSyncSide; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Comment; import java.util.*; @ConfigSerializable public class GroupSyncConfig { @Comment("Group-Role pairs for group synchronization") public List<PairConfig> pairs = new ArrayList<>(Collections.singletonList(new PairConfig())); @ConfigSerializable public static class PairConfig { @Comment("The case-sensitive group name from your permissions plugin") public String groupName = ""; @Comment("The Discord role id") public Long roleId = 0L; @Comment("The direction this group-role pair will synchronize in.\n" + "Valid options: %1, %2, %3") @Constants.Comment({"bidirectional", "minecraft_to_discord", "discord_to_minecraft"}) public GroupSyncDirection direction = GroupSyncDirection.BIDIRECTIONAL; @Comment("Timed resynchronization.\n" + "This is required if you're not using LuckPerms and want to use Minecraft to Discord synchronization") public TimerConfig timer = new TimerConfig(); @ConfigSerializable public static class TimerConfig { @Comment("If timed synchronization of this group-role pair is enabled") public boolean enabled = true; @Comment("The amount of minutes between cycles") public int cycleTime = 5; } @Comment("Decides which side takes priority when using timed synchronization or the resync command\n" + "Valid options: %1, %2") @Constants.Comment({"minecraft", "discord"}) public GroupSyncSide tieBreaker = GroupSyncSide.MINECRAFT; @Comment("The LuckPerms \"%1\" context value, used when adding, removing and checking the groups of players.\n" + "Make this blank (\"\") to use the current server's value, or \"%2\" to not use the context") @Constants.Comment({"server", "global"}) public String serverContext = "global"; public boolean isTheSameAs(PairConfig config) { return groupName.equals(config.groupName) && Objects.equals(roleId, config.roleId); } public boolean validate(DiscordSRV discordSRV) { String label = "Group synchronization (" + groupName + ":" + Long.toUnsignedString(roleId) + ")"; boolean invalidTieBreaker, invalidDirection = false; if ((invalidTieBreaker = (tieBreaker == null)) || (invalidDirection = (direction == null))) { if (invalidTieBreaker) { discordSRV.logger().error(label + " has invalid tie-breaker: " + tieBreaker + ", should be one of " + Arrays.toString(GroupSyncSide.values())); } if (invalidDirection) { discordSRV.logger().error(label + " has invalid direction: " + direction + ", should be one of " + Arrays.toString(GroupSyncDirection.values())); } return false; } else if (direction != GroupSyncDirection.BIDIRECTIONAL) { boolean minecraft; if ((direction == GroupSyncDirection.MINECRAFT_TO_DISCORD) != (minecraft = (tieBreaker == GroupSyncSide.MINECRAFT))) { GroupSyncSide opposite = (minecraft ? GroupSyncSide.DISCORD : GroupSyncSide.MINECRAFT); discordSRV.logger().warning(label + " with direction " + direction + " with tie-breaker " + tieBreaker + " (should be " + opposite + ")"); tieBreaker = opposite; // Fix the config } } return true; } @Override public String toString() { String arrow; switch (direction) { default: case BIDIRECTIONAL: arrow = "<->"; break; case DISCORD_TO_MINECRAFT: arrow = "<-"; break; case MINECRAFT_TO_DISCORD: arrow = "->"; break; } return "PairConfig{" + groupName + arrow + roleId + '}'; } } }
5,547
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DebugConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/DebugConfig.java
package com.discordsrv.common.config.main; import com.discordsrv.common.config.configurate.annotation.Constants; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Comment; import java.util.HashMap; import java.util.List; import java.util.Map; @ConfigSerializable public class DebugConfig { @Comment("If debug messages should be logged into the config") public boolean logToConsole = false; @Comment("Additional levels to log\nExample value: %1") @Constants.Comment("{\"AWARD_LISTENER\":[\"TRACE\"]}") public Map<String, List<String>> additionalLevels = new HashMap<>(); }
675
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
MainConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/MainConfig.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.config.main; import com.discordsrv.api.channel.GameChannel; import com.discordsrv.common.config.Config; import com.discordsrv.common.config.configurate.annotation.Constants; import com.discordsrv.common.config.configurate.annotation.DefaultOnly; import com.discordsrv.common.config.configurate.annotation.Order; import com.discordsrv.common.config.connection.ConnectionConfig; import com.discordsrv.common.config.documentation.DocumentationURLs; import com.discordsrv.common.config.main.channels.base.BaseChannelConfig; import com.discordsrv.common.config.main.channels.base.ChannelConfig; import com.discordsrv.common.config.main.linking.LinkedAccountConfig; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Comment; import java.util.*; @ConfigSerializable public abstract class MainConfig implements Config { public static final String FILE_NAME = "config.yaml"; @Constants({DocumentationURLs.ELT_FORMAT, DocumentationURLs.DISCORD_MARKDOWN, DocumentationURLs.PLACEHOLDERS}) public static final String HEADER = String.join("\n", Arrays.asList( "Welcome to the DiscordSRV configuration file", "", "Looking for the \"BotToken\" option? It has been moved into the " + ConnectionConfig.FILE_NAME, "Need help with the format for Minecraft messages? %1", "Need help with Discord markdown? %2", "List of placeholders %3" )); @Override public final String getFileName() { return FILE_NAME; } public BaseChannelConfig createDefaultChannel() { return new ChannelConfig(); } public BaseChannelConfig createDefaultBaseChannel() { return new BaseChannelConfig(); } @DefaultOnly(ChannelConfig.DEFAULT_KEY) @Comment("Channels configuration\n\n" + "This is where everything related to in-game chat channels is configured.\n" + "The key of this option is the in-game channel name (the default keys are \"%1\" and \"%2\")\n" + "%3 and %4 can be configured for all channels except \"%2\"\n" + "\"%2\" is a special section which has the default values for all channels unless they are specified (overridden) under the channel's own section\n" + "So if you don't specify a certain option under a channel's own section, the option will take its value from the \"%2\" section") @Constants.Comment({GameChannel.DEFAULT_NAME, ChannelConfig.DEFAULT_KEY, "channel-ids", "threads"}) public Map<String, BaseChannelConfig> channels = new LinkedHashMap<String, BaseChannelConfig>() {{ put(GameChannel.DEFAULT_NAME, createDefaultChannel()); put(ChannelConfig.DEFAULT_KEY, createDefaultBaseChannel()); }}; public LinkedAccountConfig linkedAccounts = new LinkedAccountConfig(); public TimedUpdaterConfig timedUpdater = new TimedUpdaterConfig(); @Comment("Configuration options for group-role synchronization") public GroupSyncConfig groupSync = new GroupSyncConfig(); @Comment("In-game command configuration") public GameCommandConfig gameCommand = new GameCommandConfig(); @Comment("Discord command configuration") public DiscordCommandConfig discordCommand = new DiscordCommandConfig(); @Comment("Options for console channel(s) and/or thread(s)") public List<ConsoleConfig> console = new ArrayList<>(Collections.singleton(new ConsoleConfig())); @Comment("Configuration for the %1 placeholder. The below options will be attempted in the order they are in") @Constants.Comment("%discord_invite%") public DiscordInviteConfig invite = new DiscordInviteConfig(); public MessagesMainConfig messages = new MessagesMainConfig(); @Order(10) // To go below required linking config @ 5 @Comment("Configuration for the %1 placeholder") @Constants.Comment("%player_avatar_url%") public AvatarProviderConfig avatarProvider = new AvatarProviderConfig(); public abstract PluginIntegrationConfig integrations(); @Order(1000) public MemberCachingConfig memberCaching = new MemberCachingConfig(); @Order(5000) @Comment("Options for diagnosing DiscordSRV, you do not need to touch these options during normal operation") public DebugConfig debug = new DebugConfig(); }
5,209
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
AvatarProviderConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/AvatarProviderConfig.java
package com.discordsrv.common.config.main; import com.discordsrv.common.config.configurate.annotation.Constants; import com.discordsrv.common.config.configurate.annotation.Untranslated; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Comment; @ConfigSerializable public class AvatarProviderConfig { @Comment("Whether to let DiscordSRV decide an appropriate avatar URL automatically\n" + "This will result in appropriate head renders being provided for Bedrock players (when using Floodgate) and Offline Mode players (via username).") public boolean autoDecideAvatarUrl = true; @Untranslated(Untranslated.Type.VALUE) @Constants("auto-decide-avatar-url") @Comment("The template for URLs of player avatars\n" + "This will be used for official Java players only if %1 is set to true\n" + "This will be used ALWAYS if %1 is set to false") public String avatarUrlTemplate = "https://crafatar.com/avatars/%player_uuid_short%.png?size=128&overlay#%player_skin_texture_id%"; }
1,111
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordInviteConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/DiscordInviteConfig.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.config.main; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Comment; @ConfigSerializable public class DiscordInviteConfig { @Comment("Manually enter a invite url here, if this isn't set this is ignored and the options below will take effect") public String inviteUrl = ""; @Comment("If the bot is only in one Discord server, it will attempt to get its vanity url") public boolean attemptToUseVanityUrl = true; @Comment("If the bot is only in one Discord server, it will attempt to automatically create a invite for it.\n" + "The bot will only attempt to do so if it has permission to \"Create Invite\"\n" + "The server must also have a rules channel (available for community servers) or default channel (automatically determined by Discord)") public boolean autoCreateInvite = false; }
1,780
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
TimedUpdaterConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/TimedUpdaterConfig.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.config.main; import com.discordsrv.common.config.configurate.annotation.Constants; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Comment; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.concurrent.TimeUnit; @ConfigSerializable public class TimedUpdaterConfig { public List<VoiceChannelConfig> voiceChannels = new ArrayList<>(Collections.singletonList(new VoiceChannelConfig())); public List<TextChannelConfig> textChannels = new ArrayList<>(Collections.singletonList(new TextChannelConfig())); public List<UpdaterConfig> getConfigs() { List<UpdaterConfig> configs = new ArrayList<>(); configs.addAll(voiceChannels); configs.addAll(textChannels); return configs; } public interface UpdaterConfig { boolean any(); long timeSeconds(); long minimumSeconds(); } public static class VoiceChannelConfig implements UpdaterConfig { private static final int MINIMUM_MINUTES = 10; @Comment("The channel IDs.\n" + "The bot will need the \"View Channel\", \"Manage Channels\" and \"Connection\" permissions for the provided channels") public List<Long> channelIds = new ArrayList<>(); @Comment("The format for the channel name(s), placeholders are supported.") public String nameFormat = ""; @Comment("The time between updates in minutes. The minimum time is %1 minutes.") @Constants.Comment(intValue = MINIMUM_MINUTES) public int timeMinutes = MINIMUM_MINUTES; @Override public boolean any() { return !channelIds.isEmpty(); } @Override public long timeSeconds() { return TimeUnit.MINUTES.toSeconds(timeMinutes); } @Override public long minimumSeconds() { return TimeUnit.MINUTES.toSeconds(MINIMUM_MINUTES); } } public static class TextChannelConfig implements UpdaterConfig { private static final int MINIMUM_MINUTES = 10; @Comment("The channel IDs.\n" + "The bot will need the \"View Channel\" and \"Manage Channels\" permissions for the provided channels") public List<Long> channelIds = new ArrayList<>(); @Comment("The format for the channel name(s), placeholders are supported.\n" + "If this is blank, the name will not be updated") public String nameFormat = ""; @Comment("The format for the channel topic(s), placeholders are supported.\n" + "If this is blank, the topic will not be updated") public String topicFormat = ""; @Comment("The time between updates in minutes. The minimum time is %1 minutes.") @Constants.Comment(intValue = MINIMUM_MINUTES) public int timeMinutes = MINIMUM_MINUTES; @Override public boolean any() { return !channelIds.isEmpty(); } @Override public long timeSeconds() { return TimeUnit.MINUTES.toSeconds(timeMinutes); } @Override public long minimumSeconds() { return TimeUnit.MINUTES.toSeconds(MINIMUM_MINUTES); } } }
4,179
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ConsoleConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/ConsoleConfig.java
package com.discordsrv.common.config.main; import com.discordsrv.common.config.main.generic.DestinationConfig; import com.discordsrv.common.config.main.generic.GameCommandExecutionConditionConfig; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Comment; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; @ConfigSerializable public class ConsoleConfig { @Comment("The console channel or thread") public DestinationConfig.Single channel = new DestinationConfig.Single(); public Appender appender = new Appender(); public Execution commandExecution = new Execution(); @ConfigSerializable public static class Appender { @Comment("The format for log lines") public String lineFormat = "[%log_time:'ccc HH:mm:ss zzz'%] [%log_level%] [%logger_name%] %message%"; @Comment("The mode for the console output, available options are:\n" + "- off: Turn off console appending\n" + "- ansi: A colored ansi code block\n" + "- log: A \"accesslog\" code block\n" + "- diff: A \"diff\" code block highlighting warnings and errors with different colors\n" + "- markdown: Plain text with bold, italics, strikethrough and underlining\n" + "- plain: Plain text code block\n" + "- plain_content: Plain text") public OutputMode outputMode = OutputMode.ANSI; @Comment("In \"diff\" mode, should exception lines have the prefix character as well") public boolean diffExceptions = true; @Comment("If urls should have embeds disabled") public boolean disableLinkEmbeds = true; @Comment("Avoids sending new messages by editing the most recent message until it reaches it's maximum length") public boolean useEditing = true; @Comment("If console messages should be silent, not causing a notification") public boolean silentMessages = true; @Comment("A list of log levels to whitelist or blacklist") public Levels levels = new Levels(); public static class Levels { public List<String> levels = new ArrayList<>(Arrays.asList("DEBUG", "TRACE")); public boolean blacklist = true; } @Comment("A list of logger names to whitelist or blacklist, use \"NONE\" for log messages with no logger name") public Loggers loggers = new Loggers(); public static class Loggers { public List<String> loggers = new ArrayList<>(Collections.singletonList("ExcludedLogger")); public boolean blacklist = true; } } @ConfigSerializable public static class Execution { public Execution() { executionConditions.add( new GameCommandExecutionConditionConfig( new ArrayList<>(), false, new ArrayList<>(Arrays.asList("list", "whitelist")) ) ); executionConditions.add( new GameCommandExecutionConditionConfig( new ArrayList<>(), true, new ArrayList<>(Arrays.asList( "?", "op", "deop", "execute" )) ) ); } @Comment("If command execution is enabled") public boolean enabled = true; @Comment("At least one condition has to match to allow execution") public List<GameCommandExecutionConditionConfig> executionConditions = new ArrayList<>(); @Comment("If a command is inputted starting with /, a warning response will be given if this is enabled") public boolean enableSlashWarning = true; } public enum OutputMode { OFF(null, null), ANSI("```ansi\n", "```"), LOG("```accesslog\n", "```"), DIFF("```diff\n", "```"), MARKDOWN("", ""), PLAIN("```\n", "```"), PLAIN_CONTENT("", ""); private final String prefix; private final String suffix; OutputMode(String prefix, String suffix) { this.prefix = prefix; this.suffix = suffix; } public String prefix() { return prefix; } public String suffix() { return suffix; } public int blockLength() { return prefix().length() + suffix().length(); } } }
4,781
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
MemberCachingConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/MemberCachingConfig.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.config.main; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Comment; import java.util.ArrayList; import java.util.List; @ConfigSerializable public class MemberCachingConfig { @Comment("If linked users' members should be cached, this requires the \"Server Members Intent\"") public boolean linkedUsers = true; @Comment("If all members should be cached, this requires the \"Server Members Intent\"") public boolean all = false; @Comment("If members should be cached at startup, this requires the \"Server Members Intent\"") public boolean chunk = true; @Comment("Filter for which servers should be cached at startup") public GuildFilter chunkingServerFilter = new GuildFilter(); @ConfigSerializable public static class GuildFilter { @Comment("If the ids option acts as a blacklist, otherwise it is a whitelist") public boolean blacklist = true; public List<Long> ids = new ArrayList<>(); } }
1,907
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
GameCommandConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/GameCommandConfig.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.config.main; import com.discordsrv.common.config.configurate.annotation.Constants; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Comment; @ConfigSerializable public class GameCommandConfig { @Comment("If the %1 command should be set by DiscordSRV") @Constants.Comment("/discord") public boolean useDiscordCommand = true; @Comment("If %1 should be used as a alias for %2") @Constants.Comment({"/link", "/discord link"}) public boolean useLinkAlias = false; @Comment("The Discord command response format (%1), player placeholders may be used") @Constants.Comment("/discord") public String discordFormat = "[click:open_url:%discord_invite%][color:aqua][bold:on]Click here [color][bold][color:green]to join our Discord server!"; }
1,709
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
RequirementsConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/linking/RequirementsConfig.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.config.main.linking; import com.discordsrv.common.config.configurate.annotation.DefaultOnly; import com.discordsrv.common.config.connection.ConnectionConfig; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Comment; import org.spongepowered.configurate.objectmapping.meta.Setting; import java.util.ArrayList; import java.util.Collections; import java.util.List; @ConfigSerializable public class RequirementsConfig { @Setting("bypass-uuids") @Comment("A list of uuids that are allowed to bypass these requirements") @DefaultOnly public List<String> bypassUUIDs = new ArrayList<>(Collections.singletonList("6c983d46-0631-48b8-9baf-5e33eb5ffec4")); @Comment("Requirements players must meet to be pass requirements\n" + "Only one option has to pass, for example [\"TwitchSubscriber()\", \"DiscordRole(...)\"] allows twitch subscribers and users with the specified role to play\n" + "while [\"TwitchSubscriber() && DiscordRole(...)\"] only allows twitch subscribers with the specified role to play\n" + "\n" + "Valid values are:\n" + "DiscordServer(Server ID)\n" + "DiscordBoosting(Server ID)\n" + "DiscordRole(Role ID)\n" + "\n" + "The following are available if you're using MinecraftAuth.me for linked accounts and a MinecraftAuth.me token is specified in the " + ConnectionConfig.FILE_NAME + ":\n" + "PatreonSubscriber() or PatreonSubscriber(Tier Title)\n" + "GlimpseSubscriber() or GlimpseSubscriber(Level Name)\n" + "TwitchFollower()\n" + "TwitchSubscriber() or TwitchSubscriber(Tier)\n" + "YouTubeSubscriber()\n" + "YouTubeMember() or YouTubeMember(Tier)\n" + "\n" + "The following operators are available:\n" + "&& = and, for example: \"DiscordServer(...) && TwitchFollower()\"\n" + "|| = or, for example \"DiscordBoosting(...) || YouTubeMember()\"\n" + "You can also use brackets () to clear ambiguity, for example: \"DiscordServer(...) && (TwitchSubscriber() || PatreonSubscriber())\"\n" + "allows a member of the specified Discord server that is also a twitch or patreon subscriber to join the server") public List<String> requirements = new ArrayList<>(); }
3,284
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ProxyRequiredLinkingConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/linking/ProxyRequiredLinkingConfig.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.config.main.linking; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import java.util.HashMap; import java.util.Map; @ConfigSerializable public class ProxyRequiredLinkingConfig extends RequiredLinkingConfig { public TargetRequirementConfig proxyRequirements = new TargetRequirementConfig(); public Map<String, TargetRequirementConfig> serverRequirements = new HashMap<String, TargetRequirementConfig>() {{ put("example", new TargetRequirementConfig()); }}; @ConfigSerializable public static class TargetRequirementConfig extends RequirementsConfig {} }
1,470
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
LinkedAccountConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/linking/LinkedAccountConfig.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.config.main.linking; import com.discordsrv.common.config.configurate.annotation.Constants; import com.discordsrv.common.config.connection.ConnectionConfig; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Comment; @ConfigSerializable public class LinkedAccountConfig { @Comment("Should linked accounts be enabled") public boolean enabled = true; @Comment("The linked account provider\n" + "\n" + " - auto: Uses \"minecraftauth\" if the %1 permits it and the server is in online mode or using ip forwarding, otherwise \"%4\"\n" + " - minecraftauth: Uses %2 as the linked account provider (offline and (non-linked) bedrock players cannot link using this method)\n" + " - storage: Use the configured database for linked accounts") @Constants.Comment({ConnectionConfig.FILE_NAME, "minecraftauth.me"}) public Provider provider = Provider.AUTO; public enum Provider { AUTO, MINECRAFTAUTH, STORAGE } }
1,938
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
RequiredLinkingConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/linking/RequiredLinkingConfig.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.config.main.linking; import com.discordsrv.common.config.configurate.annotation.Order; import org.spongepowered.configurate.objectmapping.ConfigSerializable; @ConfigSerializable public abstract class RequiredLinkingConfig { @Order(-10) public boolean enabled = false; }
1,141
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ServerRequiredLinkingConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/linking/ServerRequiredLinkingConfig.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.config.main.linking; import com.discordsrv.common.config.configurate.annotation.Order; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Comment; import org.spongepowered.configurate.objectmapping.meta.Setting; @ConfigSerializable public class ServerRequiredLinkingConfig extends RequiredLinkingConfig { @Comment("How the player should be blocked from joining the server.\nAvailable options: kick, freeze") public Action action = Action.KICK; public enum Action { KICK, FREEZE } @Setting(nodeFromParent = true) @Order(10) public RequirementsConfig requirements = new RequirementsConfig(); }
1,578
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DiscordIgnoresConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/generic/DiscordIgnoresConfig.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.config.main.generic; import com.discordsrv.api.discord.entity.DiscordUser; import com.discordsrv.api.discord.entity.guild.DiscordGuildMember; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Comment; import java.util.ArrayList; import java.util.List; import java.util.Optional; @ConfigSerializable public class DiscordIgnoresConfig { @Comment("User, bot and webhook ids to ignore") public IDs userBotAndWebhookIds = new IDs(); @Comment("Role ids for users and bots to ignore") public IDs roleIds = new IDs(); @Comment("If all bots (webhooks not included) should be ignored") public boolean bots = false; @Comment("If all webhooks should be ignored (webhook messages sent by this DiscordSRV instance will always be ignored)") public boolean webhooks = true; @ConfigSerializable public static class IDs { public List<Long> ids = new ArrayList<>(); @Comment("true for whitelisting the provided ids, false for blacklisting them") public boolean whitelist = false; } public boolean shouldBeIgnored(boolean webhookMessage, DiscordUser author, DiscordGuildMember member) { if (webhooks && webhookMessage) { return true; } else if (bots && (author.isBot() && !webhookMessage)) { return true; } DiscordIgnoresConfig.IDs users = userBotAndWebhookIds; if (users != null && users.ids.contains(author.getId()) != users.whitelist) { return true; } DiscordIgnoresConfig.IDs roles = roleIds; return roles != null && Optional.ofNullable(member) .map(m -> m.getRoles().stream().anyMatch(role -> roles.ids.contains(role.getId()))) .map(hasRole -> hasRole != roles.whitelist) .orElse(false); } }
2,751
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
GameCommandExecutionConditionConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/generic/GameCommandExecutionConditionConfig.java
package com.discordsrv.common.config.main.generic; import com.discordsrv.api.discord.entity.DiscordUser; import com.discordsrv.api.discord.entity.guild.DiscordGuildMember; import com.discordsrv.api.discord.entity.guild.DiscordRole; import com.discordsrv.common.command.game.GameCommandExecutionHelper; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Comment; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; @ConfigSerializable public class GameCommandExecutionConditionConfig { @SuppressWarnings("unused") // Configurate public GameCommandExecutionConditionConfig() {} public GameCommandExecutionConditionConfig(List<Long> roleAndUserIds, boolean blacklist, List<String> commands) { this.roleAndUserIds = roleAndUserIds; this.blacklist = blacklist; this.commands = commands; } @Comment("The role and user ids that should be allowed to run the commands specified in this condition") public List<Long> roleAndUserIds = new ArrayList<>(); @Comment("true for blacklist (blocking commands), false for whitelist (allowing commands)") public boolean blacklist = true; @Comment("The commands and/or patterns that are allowed/blocked.\n" + "The command needs to start with input, this will attempt to normalize command aliases where possible (for the main command)\n" + "If the command start and ends with /, the input will be treated as a regular expression (regex) and it will pass if it matches the entire command") public List<String> commands = new ArrayList<>(); public static boolean isCommandMatch(String configCommand, String command, boolean suggestions, GameCommandExecutionHelper helper) { if (configCommand.startsWith("/") && configCommand.endsWith("/")) { // Regex handling Pattern pattern = Pattern.compile(configCommand.substring(1, configCommand.length() - 1)); Matcher matcher = pattern.matcher(command); return matcher.matches() && matcher.start() == 0 && matcher.end() == command.length(); } // Normal handling configCommand = configCommand.toLowerCase(Locale.ROOT); command = command.toLowerCase(Locale.ROOT); List<String> parts = new ArrayList<>(Arrays.asList(configCommand.split(" "))); String rootCommand = parts.remove(0); Set<String> rootCommands = new LinkedHashSet<>(); rootCommands.add(rootCommand); if (helper != null) { rootCommands.addAll(helper.getAliases(rootCommand)); } if (suggestions) { // Allow suggesting the commands up to the allowed command for (String rootCmd : rootCommands) { if (command.matches("^" + Pattern.quote(rootCmd) + " ?$")) { return true; } StringBuilder built = new StringBuilder(rootCmd); for (String part : parts) { built.append(" ").append(part); if (command.matches("^" + Pattern.quote(built.toString()) + " ?$")) { return true; } } } } String arguments = String.join(" ", parts); for (String rootCmd : rootCommands) { String joined = rootCmd + (arguments.isEmpty() ? "" : " " + arguments); // This part at the end prevents "command list" matching "command listsecrets" if (command.matches("^" + Pattern.quote(joined) + "(?:$| .+)")) { // Make sure it's the same command, the alias may be used by another command return helper == null || helper.isSameCommand(rootCommand, rootCmd); } } return false; } public boolean isAcceptableCommand(DiscordGuildMember member, DiscordUser user, String command, boolean suggestions, GameCommandExecutionHelper helper) { long userId = user.getId(); List<Long> roleIds = new ArrayList<>(); if (member != null) { for (DiscordRole role : member.getRoles()) { roleIds.add(role.getId()); } } boolean match = false; for (Long id : roleAndUserIds) { if (id == userId || roleIds.contains(id)) { match = true; break; } } if (!match) { return false; } for (String configCommand : commands) { if (isCommandMatch(configCommand, command, suggestions, helper) != blacklist) { return true; } } return false; } }
4,765
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
DestinationConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/generic/DestinationConfig.java
package com.discordsrv.common.config.main.generic; import com.discordsrv.common.config.configurate.annotation.Constants; import org.apache.commons.lang3.StringUtils; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Comment; import org.spongepowered.configurate.objectmapping.meta.Setting; import java.util.ArrayList; import java.util.Collections; import java.util.List; @ConfigSerializable public class DestinationConfig { @Setting("channel-ids") @Comment("The text and/or voice channel ids this in-game channel will forward to in Discord") public List<Long> channelIds = new ArrayList<>(); @Setting("threads") @Comment("The threads that this in-game channel will forward to in Discord (this can be used instead of or with the %1 option)") @Constants.Comment("channel-ids") public List<ThreadConfig> threads = new ArrayList<>(Collections.singletonList(new ThreadConfig())); @ConfigSerializable public static class Single { @Setting("channel-id") public Long channelId = 0L; @Setting("thread-name") @Comment("If specified this destination will be a thread in the provided channel-id's channel, if left blank the destination will be the channel") public String threadName = ""; public boolean privateThread = false; public DestinationConfig asDestination() { DestinationConfig config = new DestinationConfig(); if (StringUtils.isEmpty(threadName)) { config.channelIds.add(channelId); } else { ThreadConfig threadConfig = new ThreadConfig(); threadConfig.channelId = channelId; threadConfig.threadName = threadName; threadConfig.privateThread = privateThread; config.threads.add(threadConfig); } return config; } } }
1,960
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ThreadConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/generic/ThreadConfig.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.config.main.generic; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Comment; @ConfigSerializable public class ThreadConfig { @Comment("Specify the text or forum channel id and the name of the thread (the thread will be automatically created if it doesn't exist)") public Long channelId = 0L; public String threadName = "Minecraft Server chat bridge"; public boolean privateThread = false; }
1,351
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
IMessageConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/generic/IMessageConfig.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.config.main.generic; import com.discordsrv.api.discord.entity.message.SendableDiscordMessage; public interface IMessageConfig { boolean enabled(); SendableDiscordMessage.Builder format(); }
1,061
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
MentionsConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/generic/MentionsConfig.java
package com.discordsrv.common.config.main.generic; import com.discordsrv.common.config.configurate.annotation.Untranslated; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Comment; @ConfigSerializable public class MentionsConfig { public Format role = new Format( "%role_color%@%role_name%", "[color:#5865F2]@deleted-role" ); public Format channel = new Format( "[hover:show_text:Click to go to channel][click:open_url:%channel_jump_url%][color:#5865F2]#%channel_name%", "[color:#5865F2]#Unknown" ); public Format user = new Format( "[hover:show_text:Username: @%user_tag%\nRoles: %user_roles:', '|text:'[color:gray][italics:on]None[color][italics]'%][color:#5865F2]@%user_effective_server_name|user_effective_name%", "[color:#5865F2]@Unknown user" ); public String messageUrl = "[hover:show_text:Click to go to message][click:open_url:%jump_url%][color:#5865F2]#%channel_name% > ..."; @Comment("How should custom emoji be shown in-game:\n" + "- hide: custom emoji will not be shown in-game\n" + "- blank: custom emoji will only be shown in-game if it is rendered by a 3rd party plugin\n" + "- name: shows the name of the custom emoji in-game (for example :discordsrv:), unless rendered by a 3rd party plugin") public EmoteBehaviour customEmojiBehaviour = EmoteBehaviour.BLANK; public enum EmoteBehaviour { HIDE, BLANK, NAME } @ConfigSerializable public static class Format { @Comment("The format shown in-game") @Untranslated(Untranslated.Type.VALUE) public String format = ""; @Comment("The format when the entity is deleted or can't be looked up") @Untranslated(Untranslated.Type.VALUE) public String unknownFormat = ""; @SuppressWarnings("unused") // Configurate public Format() {} public Format(String format, String unknownFormat) { this.format = format; this.unknownFormat = unknownFormat; } } }
2,185
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
MinecraftToDiscordChatConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/channels/MinecraftToDiscordChatConfig.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.config.main.channels; import com.discordsrv.api.discord.entity.message.SendableDiscordMessage; import com.discordsrv.common.config.configurate.annotation.DefaultOnly; import com.discordsrv.common.config.configurate.annotation.Untranslated; import com.discordsrv.common.config.main.generic.IMessageConfig; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Comment; import java.util.LinkedHashMap; import java.util.Map; import java.util.regex.Pattern; @ConfigSerializable public class MinecraftToDiscordChatConfig implements IMessageConfig { public boolean enabled = true; @Untranslated(Untranslated.Type.VALUE) @DefaultOnly public SendableDiscordMessage.Builder format = SendableDiscordMessage.builder() .setWebhookUsername("%player_meta_prefix|player_prefix%%player_display_name|player_name%%player_meta_suffix|player_suffix%") .setWebhookAvatarUrl("%player_avatar_url%") .setContent("%message%"); // TODO: more info on regex pairs (String#replaceAll) @Comment("Regex filters for Minecraft message contents (this is the %message% part of the \"format\" option)") public Map<Pattern, String> contentRegexFilters = new LinkedHashMap<>(); public Mentions mentions = new Mentions(); @Override public boolean enabled() { return enabled; } @Override public SendableDiscordMessage.Builder format() { return format; } @ConfigSerializable public static class Mentions { @Comment("If role mentions should be rendered on Discord\n\n" + "The player needs one of the below permission to trigger notifications:\n" + "- discordsrv.mention.roles.mentionable (for roles which have \"Allow anyone to @mention this role\" enabled)\n" + "- discordsrv.mention.roles.all (to mention ALL roles except @everyone)") public boolean roles = true; @Comment("If channel mentions should be rendered on Discord") public boolean channels = true; @Comment("If user mentions should be rendered on Discord\n" + "The player needs the discordsrv.mention.user permission to trigger a notification") public boolean users = true; @Comment("If uncached users should be looked up from the Discord API when a mention (\"@something\") occurs in chat.\n" + "The player needs the discordsrv.mention.lookup.user permission for uncached members to be looked up") public boolean uncachedUsers = true; @Comment("If @everyone and @here mentions should be enabled\n" + "The player needs the discordsrv.mention.everyone permission to render the mention and trigger a notification") public boolean everyone = false; } }
3,720
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
ChannelLockingConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/channels/ChannelLockingConfig.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.config.main.channels; import org.spongepowered.configurate.objectmapping.ConfigSerializable; import org.spongepowered.configurate.objectmapping.meta.Comment; import java.util.ArrayList; import java.util.List; @ConfigSerializable public class ChannelLockingConfig { public Channels channels = new Channels(); public Threads threads = new Threads(); @ConfigSerializable public static class Channels { @Comment("If the permissions should be taken from @everyone while the server is offline") public boolean everyone = false; @Comment("Role ids for roles that should have the permissions taken while the server is offline") public List<Long> roleIds = new ArrayList<>(); @Comment("If the \"View Channel\" permission should be taken from the specified roles") public boolean read = false; @Comment("If the \"Send Messages\" permission should be taken from the specified roles") public boolean write = true; @Comment("If the \"Add Reactions\" permission should be taken from the specified roles") public boolean addReactions = true; } @ConfigSerializable public static class Threads { @Comment("If the configured threads should be archived while the server is shutdown") public boolean archive = true; @Comment("If the bot should attempt to unarchive threads rather than make new threads") public boolean unarchive = true; } }
2,339
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z
StopMessageConfig.java
/FileExtraction/Java_unseen/DiscordSRV_Ascension/common/src/main/java/com/discordsrv/common/config/main/channels/StopMessageConfig.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.config.main.channels; import com.discordsrv.api.discord.entity.message.SendableDiscordMessage; import com.discordsrv.common.config.configurate.annotation.Untranslated; import com.discordsrv.common.config.main.generic.IMessageConfig; import org.spongepowered.configurate.objectmapping.ConfigSerializable; @ConfigSerializable public class StopMessageConfig implements IMessageConfig { public boolean enabled = true; @Untranslated(Untranslated.Type.VALUE) public SendableDiscordMessage.Builder format = SendableDiscordMessage.builder() .setContent(":stop_button: **The server has stopped**"); @Override public boolean enabled() { return enabled; } @Override public SendableDiscordMessage.Builder format() { return format; } }
1,653
Java
.java
DiscordSRV/Ascension
17
3
1
2021-07-29T01:14:02Z
2024-05-08T00:28:36Z