/
JDAImpl.java
602 lines (521 loc) · 17.2 KB
/
JDAImpl.java
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
/*
* Copyright 2015-2016 Austin Keener & Michael Ritter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.dv8tion.jda.core.entities.impl;
import com.mashape.unirest.http.Unirest;
import net.dv8tion.jda.bot.JDABot;
import net.dv8tion.jda.bot.entities.impl.JDABotImpl;
import net.dv8tion.jda.client.JDAClient;
import net.dv8tion.jda.client.entities.impl.JDAClientImpl;
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.entities.*;
import net.dv8tion.jda.core.exceptions.AccountTypeException;
import net.dv8tion.jda.core.exceptions.RateLimitedException;
import net.dv8tion.jda.core.hooks.IEventManager;
import net.dv8tion.jda.core.hooks.InterfacedEventManager;
import net.dv8tion.jda.core.managers.Presence;
import net.dv8tion.jda.core.managers.impl.PresenceImpl;
import net.dv8tion.jda.core.requests.*;
import net.dv8tion.jda.core.requests.ratelimit.IBucket;
import net.dv8tion.jda.core.utils.SimpleLog;
import org.apache.http.HttpHost;
import org.json.JSONObject;
import javax.security.auth.login.LoginException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
public class JDAImpl implements JDA
{
public static final SimpleLog LOG = SimpleLog.getLog("JDA");
protected final HashMap<String, User> users = new HashMap<>(200);
protected final HashMap<String, Guild> guilds = new HashMap<>(10);
protected final HashMap<String, TextChannel> textChannels = new HashMap<>();
protected final HashMap<String, VoiceChannel> voiceChannels = new HashMap<>();
protected final HashMap<String, PrivateChannel> privateChannels = new HashMap<>();
protected final HashMap<String, User> fakeUsers = new HashMap<>();
protected final HashMap<String, PrivateChannel> fakePrivateChannels = new HashMap<>();
protected final AccountType accountType;
protected final PresenceImpl presence;
protected final JDAClient jdaClient;
protected final JDABot jdaBot;
protected HttpHost proxy;
protected WebSocketClient client;
protected Requester requester = new Requester(this);
protected IEventManager eventManager = new InterfacedEventManager();
protected Status status = Status.INITIALIZING;
protected SelfInfo selfInfo;
protected ShardInfo shardInfo;
protected String token = null;
protected boolean audioEnabled;
protected boolean useShutdownHook;
protected boolean bulkDeleteSplittingEnabled;
protected boolean autoReconnect;
protected long responseTotal;
public JDAImpl(AccountType accountType, HttpHost proxy, boolean autoReconnect, boolean audioEnabled, boolean useShutdownHook, boolean bulkDeleteSplittingEnabled)
{
this.presence = new PresenceImpl(this);
this.accountType = accountType;
this.proxy = proxy;
this.autoReconnect = autoReconnect;
this.audioEnabled = audioEnabled;
this.useShutdownHook = useShutdownHook;
this.bulkDeleteSplittingEnabled = bulkDeleteSplittingEnabled;
this.jdaClient = accountType == AccountType.CLIENT ? new JDAClientImpl(this) : null;
this.jdaBot = accountType == AccountType.BOT ? new JDABotImpl(this) : null;
if (audioEnabled)
; //TODO: setup audio system
}
public void login(String token, ShardInfo shardInfo) throws LoginException, RateLimitedException
{
setStatus(Status.LOGGING_IN);
if (token == null || token.isEmpty())
throw new LoginException("Provided token was null or empty!");
setToken(token);
verifyToken();
this.shardInfo = shardInfo;
LOG.info("Login Successful!");
//TODO: Implement sharding
client = new WebSocketClient(this);
if (useShutdownHook)
{
Runtime.getRuntime().addShutdownHook(new Thread("JDA Shutdown Hook")
{
@Override
public void run()
{
JDAImpl.this.shutdownNow(true);
}
});
}
}
public void setStatus(Status status)
{
synchronized (this.status)
{
Status oldStatus = this.status;
this.status = status;
//TODO: Fire status change event.
// eventManager.handle(new StatusChangeEvent(this, status, oldStatus));
}
}
public void setToken(String token)
{
if (getAccountType() == AccountType.BOT)
this.token = "Bot " + token;
else
this.token = token;
}
public void verifyToken() throws LoginException, RateLimitedException
{
RestAction<JSONObject> login = new RestAction<JSONObject>(this, Route.Self.GET_SELF.compile(), null)
{
@Override
protected void handleResponse(Response response, Request request)
{
if (response.isOk())
request.onSuccess(response.getObject());
else if (response.isRateLimit())
request.onFailure(new RateLimitedException(request.getRoute(), response.retryAfter));
else if (response.code == 401)
request.onSuccess(null);
else
request.onFailure(new LoginException("When verifying the authenticity of the provided token, Discord returned an unknown response:\n" +
response.toString()));
}
};
JSONObject userResponse = null;
try
{
userResponse = login.block();
}
catch (RuntimeException e)
{
//We check if the LoginException is masked inside of a ExecutionException which is masked inside of the RuntimeException
Throwable ex = e.getCause() != null ? e.getCause().getCause() : null;
if (ex instanceof LoginException)
throw (LoginException) ex;
else
throw e;
}
if (userResponse != null)
{
verifyToken(userResponse);
}
else
{
//If we received a null return for userResponse, then that means we hit a 401.
// 401 occurs we attempt to access the users/@me endpoint with the wrong token prefix.
// e.g: If we use a Client token and prefix it with "Bot ", or use a bot token and don't prefix it.
// It also occurs when we attempt to access the endpoint with an invalid token.
//The code below already knows that something is wrong with the token. We want to determine if it is invalid
// or if the developer attempted to login with a token using the wrong AccountType.
//If we attempted to login as a Bot, remove the "Bot " prefix and set the Requester to be a client.
if (getAccountType() == AccountType.BOT)
{
token = token.replace("Bot ", "");
requester = new Requester(this, AccountType.CLIENT);
}
else //If we attempted to login as a Client, prepend the "Bot " prefix and set the Requester to be a Bot
{
token = "Bot " + token;
requester = new Requester(this, AccountType.BOT);
}
try
{
//Now that we have reversed the AccountTypes, attempt to get User info again.
userResponse = login.block();
}
catch (RuntimeException e)
{
//We check if the LoginException is masked inside of a ExecutionException which is masked inside of the RuntimeException
Throwable ex = e.getCause() != null ? e.getCause().getCause() : null;
if (ex instanceof LoginException)
throw (LoginException) ex;
else
throw e;
}
//If the response isn't null (thus it didn't 401) send it to the secondary verify method to determine
// which account type the developer wrongly attempted to login as
if (userResponse != null)
verifyToken(userResponse);
else //We 401'd again. This is an invalid token
throw new LoginException("The provided token is invalid!");
}
}
private void verifyToken(JSONObject userResponse)
{
if (getAccountType() == AccountType.BOT)
{
if (!userResponse.has("bot") || !userResponse.getBoolean("bot"))
throw new AccountTypeException(AccountType.BOT, "Attempted to login as a BOT with a CLIENT token!");
}
else
{
if (userResponse.has("bot") && userResponse.getBoolean("bot"))
throw new AccountTypeException(AccountType.CLIENT, "Attempted to login as a CLIENT with a BOT token!");
}
}
@Override
public String getToken()
{
return token;
}
@Override
public HttpHost getGlobalProxy()
{
return proxy;
}
@Override
public boolean isAudioEnabled()
{
return audioEnabled;
}
@Override
public boolean isBulkDeleteSplittingEnabled()
{
return bulkDeleteSplittingEnabled;
}
@Override
public void setAutoReconnect(boolean autoReconnect)
{
this.autoReconnect = autoReconnect;
if (client != null)
{
client.setAutoReconnect(autoReconnect);
}
}
@Override
public boolean isAutoReconnect()
{
return autoReconnect;
}
@Override
public Status getStatus()
{
return status;
}
@Override
public List<User> getUsers()
{
return Collections.unmodifiableList(new ArrayList<>(users.values()));
}
@Override
public User getUserById(String id)
{
return users.get(id);
}
@Override
public List<User> getUsersByName(String name, boolean ignoreCase)
{
return users.values().stream().filter(u ->
ignoreCase
? name.equalsIgnoreCase(u.getName())
: name.equals(u.getName()))
.collect(Collectors.toList());
}
@Override
public List<Guild> getGuilds()
{
return Collections.unmodifiableList(new ArrayList<>(guilds.values()));
}
@Override
public Guild getGuildById(String id)
{
return guilds.get(id);
}
@Override
public List<Guild> getGuildsByName(String name, boolean ignoreCase)
{
return guilds.values().stream().filter(g ->
ignoreCase
? name.equalsIgnoreCase(g.getName())
: name.equals(g.getName()))
.collect(Collectors.toList());
}
@Override
public List<TextChannel> getTextChannels()
{
return Collections.unmodifiableList(new ArrayList<>(textChannels.values()));
}
@Override
public TextChannel getTextChannelById(String id)
{
return textChannels.get(id);
}
@Override
public List<TextChannel> getTextChannelsByName(String name, boolean ignoreCase)
{
return textChannels.values().stream().filter(tc ->
ignoreCase
? name.equalsIgnoreCase(tc.getName())
: name.equals(tc.getName()))
.collect(Collectors.toList());
}
@Override
public List<VoiceChannel> getVoiceChannels()
{
return Collections.unmodifiableList(new ArrayList<>(voiceChannels.values()));
}
@Override
public VoiceChannel getVoiceChannelById(String id)
{
return voiceChannels.get(id);
}
@Override
public List<VoiceChannel> getVoiceChannelByName(String name, boolean ignoreCase)
{
return voiceChannels.values().stream().filter(vc ->
ignoreCase
? name.equalsIgnoreCase(vc.getName())
: name.equals(vc.getName()))
.collect(Collectors.toList());
}
@Override
public List<PrivateChannel> getPrivateChannels()
{
return Collections.unmodifiableList(new ArrayList<>(privateChannels.values()));
}
@Override
public PrivateChannel getPrivateChannelById(String id)
{
return privateChannels.get(id);
}
@Override
public List<Emote> getEmotes()
{
List<Emote> emotes = new ArrayList<>();
getGuilds().parallelStream().forEach(g -> emotes.addAll(g.getEmotes()));
return Collections.unmodifiableList(emotes);
}
@Override
public List<Emote> getEmotesByName(String name, boolean ignoreCase)
{
List<Emote> emotes = new ArrayList<>();
getGuilds().parallelStream().forEach(g -> emotes.addAll(g.getEmotesByName(name, ignoreCase)));
return Collections.unmodifiableList(emotes);
}
@Override
public Emote getEmoteById(String id)
{
for (Guild guild : getGuilds())
{
Emote emote = guild.getEmoteById(id);
if (emote != null)
return emote;
}
return null;
}
@Override
public SelfInfo getSelfInfo()
{
return selfInfo;
}
@Override
public void shutdown()
{
shutdown(true);
}
//TODO: offer a timeout version.
@Override
public void shutdown(boolean free)
{
setStatus(Status.SHUTTING_DOWN);
getRequester().shutdown();
//TODO: Shutdown audio connections.
getClient().setAutoReconnect(false);
getClient().close();
if (free)
{
try
{
Unirest.shutdown();
}
catch (IOException ignored) {}
}
setStatus(Status.SHUTDOWN);
}
@Override
public List<IBucket> shutdownNow(boolean free)
{
setStatus(Status.SHUTTING_DOWN);
List<IBucket> buckets = getRequester().shutdownNow();
//TODO: Shutdown audio connections.
getClient().setAutoReconnect(false);
getClient().close();
if (free)
{
try
{
Unirest.shutdown();
}
catch (IOException ignored) {}
}
setStatus(Status.SHUTDOWN);
return buckets;
}
@Override
public JDAClient asClient()
{
if (getAccountType() != AccountType.CLIENT)
throw new AccountTypeException(AccountType.CLIENT);
return jdaClient;
}
@Override
public JDABot asBot()
{
if (getAccountType() != AccountType.BOT)
throw new AccountTypeException(AccountType.BOT);
return jdaBot;
}
@Override
public long getResponseTotal()
{
return responseTotal;
}
@Override
public ShardInfo getShardInfo()
{
return shardInfo;
}
@Override
public Presence getPresence()
{
return presence;
}
@Override
public void installAuxiliaryCable(int port) throws UnsupportedOperationException
{
throw new UnsupportedOperationException("Nice try m8!");
}
@Override
public AccountType getAccountType()
{
return accountType;
}
@Override
public void setEventManager(IEventManager eventManager)
{
this.eventManager = eventManager;
}
@Override
public void addEventListener(Object... listeners)
{
for (Object listener: listeners)
eventManager.register(listener);
}
@Override
public void removeEventListener(Object... listeners)
{
for (Object listener: listeners)
eventManager.unregister(listener);
}
@Override
public List<Object> getRegisteredListeners()
{
return Collections.unmodifiableList(eventManager.getRegisteredListeners());
}
public Requester getRequester()
{
return requester;
}
public IEventManager getEventManager()
{
return eventManager;
}
public WebSocketClient getClient()
{
return client;
}
public HashMap<String, User> getUserMap()
{
return users;
}
public HashMap<String, Guild> getGuildMap()
{
return guilds;
}
public HashMap<String, TextChannel> getTextChannelMap()
{
return textChannels;
}
public HashMap<String, VoiceChannel> getVoiceChannelMap()
{
return voiceChannels;
}
public HashMap<String, PrivateChannel> getPrivateChannelMap()
{
return privateChannels;
}
public HashMap<String, User> getFakeUserMap()
{
return fakeUsers;
}
public HashMap<String, PrivateChannel> getFakePrivateChannelMap()
{
return fakePrivateChannels;
}
public void setSelfInfo(SelfInfo selfInfo)
{
this.selfInfo = selfInfo;
}
public void setResponseTotal(int responseTotal)
{
this.responseTotal = responseTotal;
}
}