-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathMain.java
More file actions
371 lines (315 loc) · 13.9 KB
/
Main.java
File metadata and controls
371 lines (315 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
package com.namelessmc.bot;
import com.google.common.base.Preconditions;
import com.namelessmc.bot.Language.LanguageLoadException;
import com.namelessmc.bot.commands.Command;
import com.namelessmc.bot.connections.BackendStorageException;
import com.namelessmc.bot.connections.ConnectionManager;
import com.namelessmc.bot.connections.StorageInitializer;
import com.namelessmc.bot.http.HttpMain;
import com.namelessmc.bot.http.Root;
import com.namelessmc.bot.listeners.CommandListener;
import com.namelessmc.bot.listeners.DiscordRoleListener;
import com.namelessmc.bot.listeners.GuildJoinHandler;
import com.namelessmc.java_api.NamelessAPI;
import com.namelessmc.java_api.exception.ApiException;
import com.namelessmc.java_api.exception.NamelessException;
import com.namelessmc.java_api.logger.ApiLogger;
import com.namelessmc.java_api.logger.Slf4jLogger;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.JDA.Status;
import net.dv8tion.jda.api.JDABuilder;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.entities.Activity;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.exceptions.ErrorResponseException;
import net.dv8tion.jda.api.requests.GatewayIntent;
import net.dv8tion.jda.api.utils.MemberCachePolicy;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.net.ssl.SSLHandshakeException;
import java.io.IOException;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.net.UnknownHostException;
import java.security.cert.CertificateException;
import java.util.Collection;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Consumer;
public class Main {
public static final String USER_AGENT = "Nameless-Link/" + Main.class.getPackage().getImplementationVersion();
private static final String DEFAULT_LANGUAGE_CODE = "en_UK";
private static JDA[] jda;
public static JDA getJda(final int shardId) { return jda[shardId]; }
public static JDA getJdaForGuild(final long guildId) {
return getJda((int) ((guildId >> 22) % getShardCount()));
}
public static Guild getGuildById(final long guildId) {
return getJdaForGuild(guildId).getGuildById(guildId);
}
private static final Logger LOGGER = LoggerFactory.getLogger(Main.class);
private static ScheduledExecutorService executorService;
public static ScheduledExecutorService getExecutorService() { return executorService; }
private static ConnectionManager connectionManager;
public static ConnectionManager getConnectionManager() { return connectionManager; }
private static URL botUrl;
public static URL getBotUrl() { return Objects.requireNonNull(botUrl); }
private static String webserverInterface;
public static String getWebserverInterface() { return Objects.requireNonNull(webserverInterface); }
private static int webserverPort;
public static int getWebserverPort() { return webserverPort; }
/**
* When false, try to detect local addresses and display a user-friendly warning. This setting will not block
* private addresses perfectly, do not rely on it for security!
*/
private static boolean localAllowed;
public static boolean isLocalAllowed() { return localAllowed; }
private static @Nullable ApiLogger apiDebugLogger;
public static @Nullable ApiLogger getApiDebugLogger() { return apiDebugLogger; }
private static int shards;
public static int getShardCount() { return shards; }
private static @Nullable Activity getConfiguredActivity() {
String typeEnv = System.getenv("BOT_ACTIVITY_TYPE");
String message = System.getenv("BOT_ACTIVITY_MESSAGE");
if (typeEnv == null || message == null) {
LOGGER.info("BOT_ACTIVITY_TYPE or BOT_ACTIVITY_MESSAGE not set; skipping status configuration.");
return null;
}
return switch (typeEnv.toUpperCase()) {
case "PLAYING" -> Activity.playing(message);
case "LISTENING" -> Activity.listening(message);
case "WATCHING" -> Activity.watching(message);
case "COMPETING" -> Activity.competing(message);
case "STREAMING" -> {
String url = System.getenv("BOT_ACTIVITY_URL");
if (url == null) {
LOGGER.warn("BOT_ACTIVITY_TYPE is STREAMING but BOT_ACTIVITY_URL is not set. Using default Twitch URL.");
url = "https://www.twitch.tv/discord";
}
yield Activity.streaming(message, url);
}
case "CUSTOM" -> Activity.customStatus(message);
default -> {
LOGGER.warn("Invalid BOT_ACTIVITY_TYPE: '{}'. Valid options: PLAYING, LISTENING, WATCHING, COMPETING, STREAMING, CUSTOM.", typeEnv);
yield null;
}
};
}
public static void main(final String[] args) throws BackendStorageException, NamelessException {
LOGGER.info("Starting Nameless Link version {}", Main.class.getPackage().getImplementationVersion());
int poolSize = 5;
if (System.getenv("THREAD_POOL_SIZE") != null) {
poolSize = Integer.parseInt(System.getenv("THREAD_POOL_SIZE"));
LOGGER.info("Configured thread pool with {} threads", poolSize);
}
executorService = Executors.newScheduledThreadPool(poolSize);
botUrl = StorageInitializer.getEnvUrl("BOT_URL");
if (System.getenv("SERVER_PORT") != null) {
LOGGER.info("Environment variable SERVER_PORT is set (by Pterodactyl Panel). Using that instead of WEBSERVER_PORT.");
webserverPort = (int) StorageInitializer.getEnvLong("SERVER_PORT", null);
} else {
webserverPort = (int) StorageInitializer.getEnvLong("WEBSERVER_PORT", null);
}
localAllowed = System.getenv("ALLOW_LOCAL_ADDRESSES") != null;
String defaultLang = StorageInitializer.getEnvString("DEFAULT_LANGUAGE", DEFAULT_LANGUAGE_CODE);
try {
Language.setDefaultLanguage(defaultLang);
} catch (LanguageLoadException e) {
LOGGER.warn("Unable to set default language, '{}' is not a valid language.", defaultLang);
}
if (System.getenv("API_DEBUG") != null && Boolean.parseBoolean(System.getenv("API_DEBUG"))) {
apiDebugLogger = new Slf4jLogger(LoggerFactory.getLogger("nameless-java-api debug"));
} else {
apiDebugLogger = null;
}
webserverInterface = StorageInitializer.getEnvString("WEBSERVER_BIND", "127.0.0.1");
shards = (int) StorageInitializer.getEnvLong("SHARDS", 1L);
// Temporary workaround for OpenJDK 17 bug
// https://github.com/DV8FromTheWorld/JDA/issues/1858#issuecomment-942066283
final int cores = Runtime.getRuntime().availableProcessors();
if (cores <= 1) {
LOGGER.info("Available cores {}, setting parallelism flag", cores);
System.setProperty("java.util.concurrent.ForkJoinPool.common.parallelism", "1");
}
initializeConnectionManager();
String token = StorageInitializer.getEnvString("DISCORD_TOKEN", null);
jda = new JDA[shards];
for (int i = 0; i < shards; i++) {
LOGGER.info("Initializing shard {}", i);
jda[i] = JDABuilder.createDefault(token)
.addEventListeners(new GuildJoinHandler())
.addEventListeners(new CommandListener())
.addEventListeners(new DiscordRoleListener())
.setActivity(getConfiguredActivity())
.enableIntents(GatewayIntent.GUILD_MEMBERS, GatewayIntent.DIRECT_MESSAGES)
.setMemberCachePolicy(MemberCachePolicy.ALL)
.useSharding(i, shards)
.build();
}
LOGGER.info("Waiting for JDA to connect, this can take a long time (30+ seconds is not unusual)...");
LOGGER.info("Note: the JDA message \"Connected to WebSocket\" does not mean it is finished connecting!");
try {
for (int i = 0; i < Main.getShardCount(); i++) {
Main.getJda(i).awaitStatus(Status.CONNECTED);
LOGGER.info("Shard {} connected", i);
}
} catch (final InterruptedException e) {
e.printStackTrace();
System.exit(1);
}
LOGGER.info("JDA connected!");
try {
LOGGER.info("Starting web server...");
HttpMain.init();
} catch (IOException e) {
throw new RuntimeException(e);
}
sendBotSettings();
if (!Main.getConnectionManager().isReadOnly()) {
Main.getExecutorService().scheduleAtFixedRate(
() -> Main.getExecutorService().execute(ConnectionCleanup::run),
15, TimeUnit.HOURS.toMinutes(12), TimeUnit.MINUTES);
}
Main.getExecutorService().scheduleAtFixedRate(new UsernameSync(), 6, 6, TimeUnit.HOURS);
new Metrics();
}
private static void sendBotSettings() throws NamelessException, BackendStorageException {
final User user = Main.getJda(0).getSelfUser();
final String username = user.getName();
if (Main.getConnectionManager().isReadOnly()) {
final Collection<NamelessAPI> apiConnections = connectionManager.listConnections();
Preconditions.checkArgument(apiConnections.size() == 1, "Stateless connection manager should always have 1 connection");
final NamelessAPI api = apiConnections.iterator().next();
final long guildId = connectionManager.getGuildIdByApiConnection(api).orElseThrow();
LOGGER.info("Sending bot settings to " + api.apiUrl());
api.discord().updateBotSettings(botUrl, guildId, username, user.getIdLong());
final Guild guild = Main.getJda(0).getGuildById(guildId);
if (guild == null) {
LOGGER.error("Guild with id '{}' does not exist. Is the ID wrong or is the bot not in this guild?", guildId);
System.exit(1);
}
try {
Command.sendCommands(guild);
} catch (ErrorResponseException e) {
LOGGER.error("Failed to register slash commands: " + e.getMessage());
LOGGER.error("Make sure you invite the bot with the 'applications.commands' scope enabled.");
}
DiscordRoleListener.sendRolesAsync(guildId);
LOGGER.info("Sent bot settings to website and registered commands successfully.");
} else {
int threads;
if (System.getenv("UPDATE_SETTINGS_THREADS") != null) {
threads = Integer.parseInt(System.getenv("UPDATE_SETTINGS_THREADS"));
} else {
threads = 2;
}
final ExecutorService service = Executors.newFixedThreadPool(threads);
final AtomicInteger countTotal = new AtomicInteger();
final AtomicInteger countSuccess = new AtomicInteger();
final AtomicInteger countError = new AtomicInteger();
LOGGER.info("Updating bot settings and sending slash commands...");
for (int shard = 0; shard < getShardCount(); shard++) {
for (final Guild guild : getJda(shard).getGuilds()) {
service.execute(() -> {
try {
Command.sendCommands(guild);
} catch (ErrorResponseException e) {
LOGGER.warn("{} failed to send commands: {}", guild.getIdLong(), e.getMessage());
}
try {
final NamelessAPI api = connectionManager.getApiConnection(guild.getIdLong());
if (api != null) {
try {
api.discord().updateBotSettings(botUrl, guild.getIdLong(), username, user.getIdLong());
LOGGER.info("{} sent commands, sent settings to {}", guild.getIdLong(), api.apiUrl());
countSuccess.incrementAndGet();
} catch (final NamelessException e) {
LOGGER.info("{} sent commands, failed to send settings to {}", guild.getIdLong(), api.apiUrl());
countError.incrementAndGet();
}
} else {
LOGGER.info("{} sent commands", guild.getIdLong());
}
} catch (final BackendStorageException e) {
LOGGER.error(guild.getIdLong() + " backend storage exception", e);
}
countTotal.incrementAndGet();
});
}
}
service.shutdown();
try {
service.awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS);
} catch (final InterruptedException e) {
e.printStackTrace();
}
LOGGER.info("Done updating bot settings");
LOGGER.info("{} total guilds, {} websites successful, {} websites unsuccessful", countTotal, countSuccess, countError);
Root.pingSuccessCount = countSuccess.get();
Root.pingFailCount = countError.get();
}
}
public static void canModifySettings(final User user, final Guild guild, final Consumer<Boolean> canModifySettings) {
guild.retrieveMember(user).queue(
// success
member -> canModifySettings.accept(member.hasPermission(Permission.ADMINISTRATOR)),
// failure
t -> {
LOGGER.warn("Error while retrieving member in canModifySettings, assuming user {} is not allowed to modify settings.", user.getId());
canModifySettings.accept(false);
});
}
private static void initializeConnectionManager() {
String storageType = System.getenv("STORAGE_TYPE");
if (storageType == null) {
LOGGER.info("STORAGE_TYPE not specified, assuming STORAGE_TYPE=stateless");
storageType = "stateless";
}
final StorageInitializer<? extends ConnectionManager> init = StorageInitializer.getByName(storageType);
if (init == null) {
LOGGER.error("The chosen STORAGE_TYPE is not available, please choose from: {}",
String.join(", ", StorageInitializer.getAvailableNames()));
System.exit(1);
}
connectionManager = init.get();
}
private static final Set<Class<?>> IGNORED_EXCEPTIONS = Set.of(
UnknownHostException.class,
SSLHandshakeException.class,
CertificateException.class,
SocketTimeoutException.class,
ConnectException.class
);
public static void logConnectionError(final Logger logger, final @Nullable String message, final NamelessException e) {
Objects.requireNonNull(logger, "Logger is null");
Objects.requireNonNull(e, "Exception is null");
if (e instanceof ApiException apiException) {
if (message != null) {
logger.warn(message + " (API error {})", apiException.apiError());
} else {
logger.warn("API error {}", apiException.apiError());
}
} else if (e.getCause() != null &&
apiDebugLogger == null &&
IGNORED_EXCEPTIONS.contains(e.getCause().getClass())) {
if (message != null) {
logger.warn(message + " ({})", e.getCause().getClass().getSimpleName());
} else {
logger.warn(e.getCause().getClass().getSimpleName());
}
} else {
logger.warn(Objects.requireNonNullElse(message, "Unexpected connection error"), e);
}
}
public static void logConnectionError(final Logger logger, final NamelessException e) {
logConnectionError(logger, null, e);
}
}