-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathConfigureCommand.java
More file actions
330 lines (290 loc) · 17.4 KB
/
ConfigureCommand.java
File metadata and controls
330 lines (290 loc) · 17.4 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
package com.namelessmc.bot.commands;
import static com.namelessmc.bot.Language.Term.APIURL_FAILED_CONNECTION;
import static com.namelessmc.bot.Language.Term.APIURL_URL_INVALID;
import static com.namelessmc.bot.Language.Term.APIURL_URL_LOCAL;
import static com.namelessmc.bot.Language.Term.APIURL_URL_MALFORMED;
import static com.namelessmc.bot.Language.Term.CONFIGURE_DESCRIPTION;
import static com.namelessmc.bot.Language.Term.CONFIGURE_LINK_ALREADY_CONFIGURED;
import static com.namelessmc.bot.Language.Term.CONFIGURE_LINK_DESCRIPTION;
import static com.namelessmc.bot.Language.Term.CONFIGURE_LINK_OPTION_API_KEY;
import static com.namelessmc.bot.Language.Term.CONFIGURE_LINK_OPTION_API_URL;
import static com.namelessmc.bot.Language.Term.CONFIGURE_LINK_SUCCESS;
import static com.namelessmc.bot.Language.Term.CONFIGURE_TEST_DESCRIPTION;
import static com.namelessmc.bot.Language.Term.CONFIGURE_TEST_WORKING;
import static com.namelessmc.bot.Language.Term.CONFIGURE_UNLINK_DESCRIPTION;
import static com.namelessmc.bot.Language.Term.CONFIGURE_UNLINK_NOT_LINKED;
import static com.namelessmc.bot.Language.Term.CONFIGURE_UNLINK_SUCCESS;
import static com.namelessmc.bot.Language.Term.CONFIGURE_UPDATE_USERNAMES_DESCRIPTION;
import static com.namelessmc.bot.Language.Term.CONFIGURE_UPDATE_USERNAMES_DONE;
import static com.namelessmc.bot.Language.Term.CONFIGURE_USERNAME_SYNC_DESCRIPTION;
import static com.namelessmc.bot.Language.Term.CONFIGURE_USERNAME_SYNC_DISABLED;
import static com.namelessmc.bot.Language.Term.CONFIGURE_USERNAME_SYNC_ENABLED;
import static com.namelessmc.bot.Language.Term.CONFIGURE_USERNAME_SYNC_MISSING_PERMISSION;
import static com.namelessmc.bot.Language.Term.CONFIGURE_USERNAME_SYNC_OPTION_STATE;
import static com.namelessmc.bot.Language.Term.ERROR_GENERIC;
import static com.namelessmc.bot.Language.Term.ERROR_NOT_SET_UP;
import static com.namelessmc.bot.Language.Term.ERROR_NO_PERMISSION;
import static com.namelessmc.bot.Language.Term.ERROR_WEBSITE_CONNECTION;
import static com.namelessmc.bot.Language.Term.ERROR_WEBSITE_VERSION;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.Optional;
import java.util.stream.Collectors;
import org.checkerframework.checker.nullness.qual.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.google.common.base.Ascii;
import com.namelessmc.bot.Language;
import com.namelessmc.bot.Main;
import com.namelessmc.bot.connections.BackendStorageException;
import com.namelessmc.bot.util.EmbedUtil;
import com.namelessmc.bot.connections.ConnectionCache;
import com.namelessmc.bot.listeners.DiscordRoleListener;
import com.namelessmc.java_api.NamelessAPI;
import com.namelessmc.java_api.NamelessVersion;
import com.namelessmc.java_api.Website;
import com.namelessmc.java_api.exception.NamelessException;
import com.namelessmc.java_api.exception.UnknownNamelessVersionException;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.User;
import net.dv8tion.jda.api.events.interaction.command.SlashCommandInteractionEvent;
import net.dv8tion.jda.api.exceptions.HierarchyException;
import net.dv8tion.jda.api.exceptions.InsufficientPermissionException;
import net.dv8tion.jda.api.interactions.InteractionHook;
import net.dv8tion.jda.api.interactions.commands.DefaultMemberPermissions;
import net.dv8tion.jda.api.interactions.commands.OptionType;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.dv8tion.jda.api.interactions.commands.build.Commands;
import net.dv8tion.jda.api.interactions.commands.build.SubcommandData;
public class ConfigureCommand extends Command {
private static final Logger LOGGER = LoggerFactory.getLogger(ConfigureCommand.class);
ConfigureCommand() {
super("configure");
}
@Override
public CommandData getCommandData(final Language language) {
return Commands.slash(this.name, language.get(CONFIGURE_DESCRIPTION))
.addSubcommands(
new SubcommandData("link", language.get(CONFIGURE_LINK_DESCRIPTION))
.addOption(OptionType.STRING, "api_url", language.get(CONFIGURE_LINK_OPTION_API_URL), true)
.addOption(OptionType.STRING, "api_key", language.get(CONFIGURE_LINK_OPTION_API_KEY), true),
new SubcommandData("unlink", language.get(CONFIGURE_UNLINK_DESCRIPTION)),
new SubcommandData("test", language.get(CONFIGURE_TEST_DESCRIPTION)),
new SubcommandData("username_sync", language.get(CONFIGURE_USERNAME_SYNC_DESCRIPTION))
.addOption(OptionType.BOOLEAN, "state", language.get(CONFIGURE_USERNAME_SYNC_OPTION_STATE), true),
new SubcommandData("update_usernames", language.get(CONFIGURE_UPDATE_USERNAMES_DESCRIPTION))
)
.setDefaultPermissions(DefaultMemberPermissions.DISABLED);
}
@Override
public void execute(SlashCommandInteractionEvent event, InteractionHook hook, Language language, Guild guild, @Nullable NamelessAPI api) {
Main.canModifySettings(event.getUser(), guild, canModifySettings -> {
if (!canModifySettings) {
hook.sendMessageEmbeds(EmbedUtil.message(event.getJDA(), language.get(ERROR_NO_PERMISSION))).queue();
LOGGER.info("User {} does not have permission to modify settings", event.getUser().getIdLong());
return;
}
final String subcommand = event.getSubcommandName();
LOGGER.info("Subcommand: {}", subcommand);
switch (subcommand) {
case "link" -> this.link(event, hook, language, api);
case "unlink" -> this.unlink(event, hook, language, api);
case "test" -> this.testConnection(event, hook, language, api);
case "username_sync" -> this.changeUsernameSync(event, hook, language);
case "update_usernames" -> this.updateUsernames(event, hook, language, api);
default -> throw new IllegalArgumentException("Unknown subcommand: " + subcommand);
}
});
LOGGER.info(event.getSubcommandName());
}
private void unlink(SlashCommandInteractionEvent event, InteractionHook hook, Language language, @Nullable NamelessAPI oldApi) {
if (oldApi == null) {
hook.sendMessageEmbeds(EmbedUtil.message(event.getJDA(), language.get(CONFIGURE_UNLINK_NOT_LINKED))).queue();
LOGGER.info("Cannot unlink, bot was not linked");
return;
}
final long guildId = event.getGuild().getIdLong();
try {
Main.getConnectionManager().removeConnection(guildId);
hook.sendMessageEmbeds(EmbedUtil.message(event.getJDA(), language.get(CONFIGURE_UNLINK_SUCCESS))).queue();
LOGGER.info("Unlinked from guild {}", guildId);
} catch (final BackendStorageException e) {
hook.sendMessageEmbeds(EmbedUtil.message(event.getJDA(), language.get(ERROR_GENERIC))).queue();
LOGGER.error("storage backend", e);
}
}
private void link(SlashCommandInteractionEvent event, InteractionHook hook, Language language, @Nullable NamelessAPI oldApi) {
final long guildId = event.getGuild().getIdLong();
final String apiUrlString = event.getOption("api_url").getAsString();
final String apiKey = event.getOption("api_key").getAsString();
final URL apiUrl;
try {
apiUrl = new URI(apiUrlString).toURL();
} catch (final MalformedURLException | URISyntaxException e) {
hook.sendMessageEmbeds(EmbedUtil.message(event.getJDA(), language.get(APIURL_URL_MALFORMED))).queue();
return;
}
try {
LOGGER.info("Checking if API URL works...");
final NamelessAPI api = ConnectionCache.getApiConnection(apiUrl, apiKey);
final long ping = this.ping(api, language, hook);
if (ping == -1) {
// it didn't work, the checkConnection method already send an error message
return;
}
final Optional<Long> optExistingGuildId = Main.getConnectionManager().getGuildIdByApiUrl(apiUrl);
if (optExistingGuildId.isPresent() && optExistingGuildId.get() != guildId) {
// We can safely do this, since we have just verified the user knows the secret API key.
LOGGER.info("URL was already linked to a different guild. It will be unlinked.");
Main.getConnectionManager().removeConnection(optExistingGuildId.get());
}
LOGGER.info("API URL seems to work. Sending bot settings...");
try {
final User botUser = Main.getJdaForGuild(guildId).getSelfUser();
api.discord().updateBotSettings(Main.getBotUrl(), guildId, botUser.getName(), botUser.getIdLong());
if (oldApi == null) {
// User is setting up new connection
Main.getConnectionManager().createConnection(guildId, apiUrl, apiKey);
hook.sendMessageEmbeds(EmbedUtil.message(event.getJDA(), language.get(CONFIGURE_LINK_SUCCESS))).queue();
LOGGER.info("Set API URL for guild {} to {}", guildId, apiUrl);
} else {
// User is modifying API URL for existing connection
Main.getConnectionManager().updateConnection(guildId, apiUrl, apiKey);
hook.sendMessageEmbeds(EmbedUtil.message(event.getJDA(), language.get(CONFIGURE_LINK_SUCCESS))).queue();
LOGGER.info("Updated API URL for guild {} from {} to {}", guildId, oldApi, apiUrl);
}
DiscordRoleListener.sendRolesAsync(guildId);
} catch (final NamelessException e) {
hook.sendMessage("```\n" + Ascii.truncate(e.getMessage(), 1500, "[truncated]") + "\n```").queue();
hook.sendMessageEmbeds(EmbedUtil.message(event.getJDA(), language.get(APIURL_FAILED_CONNECTION))).queue();
Main.logConnectionError(LOGGER, e);
}
} catch (final BackendStorageException e) {
if (e.getCause() instanceof UnsupportedOperationException) {
hook.sendMessageEmbeds(EmbedUtil.message(event.getJDA(), language.get(CONFIGURE_LINK_ALREADY_CONFIGURED)))
.setEphemeral(true)
.queue(response -> {
LOGGER.info("The bot is ALREADY configured using environment variables, please update the config via environment settings instead. Used in guild: {}", guildId);
}, error -> {
LOGGER.error("Failed to send environment variables warning for guild {}", guildId, error);
});
return;
}
hook.sendMessageEmbeds(EmbedUtil.message(event.getJDA(), language.get(ERROR_GENERIC))).queue();
LOGGER.error("storage backend", e);
}
}
void testConnection(SlashCommandInteractionEvent event, InteractionHook hook, Language language, @Nullable NamelessAPI api) {
if (api == null) {
hook.sendMessageEmbeds(EmbedUtil.message(event.getJDA(), language.get(ERROR_NOT_SET_UP))).queue();
return;
}
final long ping = this.ping(api, language, event.getHook());
if (ping >= 0) {
hook.sendMessageEmbeds(EmbedUtil.message(event.getJDA(), language.get(CONFIGURE_TEST_WORKING, "time", ping))).queue();
}
}
private long ping(final NamelessAPI api, final Language language, final InteractionHook hook) {
final URL url = api.apiUrl();
if (!url.getProtocol().equals("http") && !url.getProtocol().equals("https") ||
!url.getPath().endsWith("/index.php") ||
!url.getQuery().equals("route=/api/v2") && !url.getQuery().equals("route=/api/v2/")
) {
LOGGER.info("Invalid URL with protocol '{}' host '{}' path '{}' query '{}'", url.getProtocol(), url.getHost(), url.getPath(), url.getQuery());
hook.sendMessageEmbeds(EmbedUtil.message(hook.getJDA(), language.get(APIURL_URL_INVALID))).queue();
return -1;
}
final String host = url.getHost();
if (!Main.isLocalAllowed() && (
host.equals("localhost") ||
host.startsWith("127.") ||
host.startsWith("192.168.") ||
host.startsWith("10.")
// checking 172.16.0.0/12 is too much work...
)) {
LOGGER.info("Local host: '{}'", host);
hook.sendMessageEmbeds(EmbedUtil.message(hook.getJDA(), language.get(APIURL_URL_LOCAL))).queue();
return -1;
}
try {
final long start = System.currentTimeMillis();
LOGGER.info("Making request to info endpoint");
final Website info = api.website();
try {
if (!NamelessVersion.isSupportedByJavaApi(info.parsedVersion())) {
hook.sendMessageEmbeds(EmbedUtil.message(hook.getJDA(), language.get(ERROR_WEBSITE_VERSION, "version", info.rawVersion(), "compatibleVersions", supportedVersionsList()))).queue();
LOGGER.info("Incompatible NamelessMC version");
return -1;
}
LOGGER.info("Website connection is working");
return System.currentTimeMillis() - start;
} catch (final UnknownNamelessVersionException e) {
hook.sendMessageEmbeds(EmbedUtil.message(hook.getJDA(), language.get(ERROR_WEBSITE_VERSION, "version", info.rawVersion(), "compatibleVersions", supportedVersionsList()))).queue();
Main.logConnectionError(LOGGER, "unknown nameless version", e);
return -1;
}
} catch (final NamelessException e) {
hook.sendMessage("```\n" + Ascii.truncate(e.getMessage(), 1500, "[truncated]") + "\n```").queue();
hook.sendMessageEmbeds(EmbedUtil.message(hook.getJDA(), language.get(APIURL_FAILED_CONNECTION))).queue();
Main.logConnectionError(LOGGER, "NamelessException during ping", e);
return -1;
}
}
public static String supportedVersionsList() {
return NamelessVersion.supportedVersions().stream().map(NamelessVersion::friendlyName).collect(Collectors.joining(", "));
}
private void changeUsernameSync(SlashCommandInteractionEvent event, InteractionHook hook, Language language) {
final boolean state = event.getOption("state").getAsBoolean();
final String originalNickname = event.getMember().getNickname();
// Modify nickname to check if permission is working
try {
event.getMember().modifyNickname("test_permission").complete();
// Restore original nickname, if the member running the command was not the server owner
event.getMember().modifyNickname(originalNickname).queue();
} catch (final HierarchyException ignored) {
// This is expected, changing the nickname of the owner is never allowed.
} catch (final InsufficientPermissionException e) {
hook.sendMessageEmbeds(EmbedUtil.message(event.getJDA(), language.get(CONFIGURE_USERNAME_SYNC_MISSING_PERMISSION))).queue();
return;
}
try {
Main.getConnectionManager().setUsernameSyncEnabled(event.getGuild().getIdLong(), state);
} catch (final BackendStorageException e) {
hook.sendMessageEmbeds(EmbedUtil.message(event.getJDA(), language.get(ERROR_GENERIC))).queue();
LOGGER.error("storage backend", e);
return;
}
if (state) {
hook.sendMessageEmbeds(EmbedUtil.message(event.getJDA(), language.get(CONFIGURE_USERNAME_SYNC_ENABLED))).queue();
} else {
hook.sendMessageEmbeds(EmbedUtil.message(event.getJDA(), language.get(CONFIGURE_USERNAME_SYNC_DISABLED))).queue();
}
}
private void updateUsernames(SlashCommandInteractionEvent event, InteractionHook hook, Language language, @Nullable NamelessAPI api) {
if (api == null) {
hook.sendMessageEmbeds(EmbedUtil.message(event.getJDA(), language.get(ERROR_NOT_SET_UP))).queue();
return;
}
hook.sendMessageEmbeds(EmbedUtil.message(event.getJDA(), language.get(CONFIGURE_UPDATE_USERNAMES_DONE))).queue();
event.getGuild().loadMembers().onSuccess(members -> {
final long[] discordIds = new long[members.size()];
final String[] discordUsernames = new String[members.size()];
for (int i = 0; i < members.size(); i++) {
final User user = members.get(i).getUser();
discordIds[i] = user.getIdLong();
discordUsernames[i] = user.getName();
}
try {
api.discord().updateDiscordUsernames(discordIds, discordUsernames);
} catch (final NamelessException e) {
hook.sendMessageEmbeds(EmbedUtil.message(event.getJDA(), language.get(ERROR_WEBSITE_CONNECTION))).queue();
Main.logConnectionError(LOGGER, e);
return;
}
hook.setEphemeral(true); // Ephemeral needs to be set again after last message
hook.sendMessageEmbeds(EmbedUtil.message(event.getJDA(), language.get(CONFIGURE_UPDATE_USERNAMES_DONE))).queue();
});
}
}