/
JDAImpl.java
825 lines (715 loc) · 23.7 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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
/*
* Copyright 2015-2017 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 com.neovisionaries.ws.client.WebSocketFactory;
import gnu.trove.map.TLongObjectMap;
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.audio.AudioWebSocket;
import net.dv8tion.jda.core.audio.factory.DefaultSendFactory;
import net.dv8tion.jda.core.audio.factory.IAudioSendFactory;
import net.dv8tion.jda.core.entities.*;
import net.dv8tion.jda.core.events.StatusChangeEvent;
import net.dv8tion.jda.core.exceptions.AccountTypeException;
import net.dv8tion.jda.core.exceptions.RateLimitedException;
import net.dv8tion.jda.core.handle.EventCache;
import net.dv8tion.jda.core.hooks.IEventManager;
import net.dv8tion.jda.core.hooks.InterfacedEventManager;
import net.dv8tion.jda.core.managers.AudioManager;
import net.dv8tion.jda.core.managers.Presence;
import net.dv8tion.jda.core.managers.impl.AudioManagerImpl;
import net.dv8tion.jda.core.managers.impl.PresenceImpl;
import net.dv8tion.jda.core.requests.*;
import net.dv8tion.jda.core.utils.MiscUtil;
import net.dv8tion.jda.core.utils.SimpleLog;
import org.apache.http.HttpHost;
import org.apache.http.util.Args;
import org.json.JSONObject;
import javax.security.auth.login.LoginException;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadFactory;
import java.util.stream.Collectors;
public class JDAImpl implements JDA
{
public static final SimpleLog LOG = SimpleLog.getLog("JDA");
public final ScheduledExecutorService pool;
protected final TLongObjectMap<User> users = MiscUtil.newLongMap();
protected final TLongObjectMap<Guild> guilds = MiscUtil.newLongMap();
protected final TLongObjectMap<TextChannel> textChannels = MiscUtil.newLongMap();
protected final TLongObjectMap<VoiceChannel> voiceChannels = MiscUtil.newLongMap();
protected final TLongObjectMap<PrivateChannel> privateChannels = MiscUtil.newLongMap();
protected final TLongObjectMap<User> fakeUsers = MiscUtil.newLongMap();
protected final TLongObjectMap<PrivateChannel> fakePrivateChannels = MiscUtil.newLongMap();
protected final TLongObjectMap<AudioManagerImpl> audioManagers = MiscUtil.newLongMap();
protected final HttpHost proxy;
protected final WebSocketFactory wsFactory;
protected final AccountType accountType;
protected final PresenceImpl presence;
protected final JDAClient jdaClient;
protected final JDABot jdaBot;
protected final int maxReconnectDelay;
protected final Thread shutdownHook;
protected final EntityBuilder entityBuilder = new EntityBuilder(this);
protected final EventCache eventCache = new EventCache();
protected final GuildLock guildLock = new GuildLock(this);
protected final Object akapLock = new Object();
protected WebSocketClient client;
protected Requester requester;
protected IEventManager eventManager = new InterfacedEventManager();
protected IAudioSendFactory audioSendFactory = new DefaultSendFactory();
protected ScheduledThreadPoolExecutor audioKeepAlivePool;
protected Status status = Status.INITIALIZING;
protected SelfUser selfUser;
protected ShardInfo shardInfo;
protected String token = null;
protected boolean audioEnabled;
protected boolean bulkDeleteSplittingEnabled;
protected boolean autoReconnect;
protected long responseTotal;
protected long ping = -1;
public JDAImpl(AccountType accountType, HttpHost proxy, WebSocketFactory wsFactory,
boolean autoReconnect, boolean audioEnabled, boolean useShutdownHook, boolean bulkDeleteSplittingEnabled,
int corePoolSize, int maxReconnectDelay)
{
this.presence = new PresenceImpl(this);
this.accountType = accountType;
this.requester = new Requester(this);
this.proxy = proxy;
this.wsFactory = wsFactory;
this.autoReconnect = autoReconnect;
this.audioEnabled = audioEnabled;
this.shutdownHook = useShutdownHook ? new Thread(() -> JDAImpl.this.shutdown(true), "JDA Shutdown Hook") : null;
this.bulkDeleteSplittingEnabled = bulkDeleteSplittingEnabled;
this.pool = Executors.newScheduledThreadPool(corePoolSize, new JDAThreadFactory());
this.maxReconnectDelay = maxReconnectDelay;
this.jdaClient = accountType == AccountType.CLIENT ? new JDAClientImpl(this) : null;
this.jdaBot = accountType == AccountType.BOT ? new JDABotImpl(this) : null;
}
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!");
client = new WebSocketClient(this);
if (shutdownHook != null)
{
Runtime.getRuntime().addShutdownHook(shutdownHook);
}
}
public void setStatus(Status status)
{
synchronized (this.status)
{
Status oldStatus = this.status;
this.status = status;
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<JSONObject> 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;
try
{
userResponse = login.complete(false);
}
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.complete(false);
}
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 long getPing()
{
return ping;
}
@Override
public List<String> getCloudflareRays()
{
return Collections.unmodifiableList(new LinkedList<>(client.getCfRays()));
}
@Override
public List<User> getUsers()
{
return Collections.unmodifiableList(new ArrayList<>(users.valueCollection()));
}
@Override
public User getUserById(String id)
{
return users.get(MiscUtil.parseSnowflake(id));
}
@Override
public User getUserById(long id)
{
return users.get(id);
}
@Override
public List<Guild> getMutualGuilds(User... users)
{
Args.notNull(users, "users");
return getMutualGuilds(Arrays.asList(users));
}
@Override
public List<Guild> getMutualGuilds(Collection<User> users)
{
Args.notNull(users, "users");
for(User u : users)
{
Args.notNull(u, "All users");
}
return Collections.unmodifiableList(getGuilds().stream()
.filter(guild -> users.stream().allMatch(guild::isMember))
.collect(Collectors.toList()));
}
@Override
public List<User> getUsersByName(String name, boolean ignoreCase)
{
return users.valueCollection().stream().filter(u ->
ignoreCase
? name.equalsIgnoreCase(u.getName())
: name.equals(u.getName()))
.collect(Collectors.toList());
}
@Override
public RestAction<User> retrieveUserById(String id)
{
return retrieveUserById(MiscUtil.parseSnowflake(id));
}
@Override
public RestAction<User> retrieveUserById(long id)
{
if (accountType != AccountType.BOT)
throw new AccountTypeException(AccountType.BOT);
// check cache
User user = this.getUserById(id);
if (user != null)
return new RestAction.EmptyRestAction<>(user);
Route.CompiledRoute route = Route.Users.GET_USER.compile(Long.toUnsignedString(id));
return new RestAction<User>(this, route, null)
{
@Override
protected void handleResponse(Response response, Request<User> request)
{
if (!response.isOk())
{
request.onFailure(response);
return;
}
JSONObject user = response.getObject();
request.onSuccess(getEntityBuilder().createFakeUser(user, false));
}
};
}
@Override
public List<Guild> getGuilds()
{
return Collections.unmodifiableList(new ArrayList<>(guilds.valueCollection()));
}
@Override
public Guild getGuildById(String id)
{
return guilds.get(MiscUtil.parseSnowflake(id));
}
@Override
public Guild getGuildById(long id)
{
return guilds.get(id);
}
@Override
public List<Guild> getGuildsByName(String name, boolean ignoreCase)
{
return guilds.valueCollection().stream().filter(g ->
ignoreCase
? name.equalsIgnoreCase(g.getName())
: name.equals(g.getName()))
.collect(Collectors.toList());
}
@Override
public List<Role> getRoles()
{
return guilds.valueCollection().stream()
.flatMap(guild -> guild.getRoles().stream())
.collect(Collectors.toList());
}
@Override
public Role getRoleById(String id)
{
return getRoleById(MiscUtil.parseSnowflake(id));
}
@Override
public Role getRoleById(long id)
{
for (Guild guild : guilds.valueCollection())
{
Role r = guild.getRoleById(id);
if (r != null)
return r;
}
return null;
}
@Override
public List<Role> getRolesByName(String name, boolean ignoreCase)
{
return guilds.valueCollection().stream()
.flatMap(guild -> guild.getRolesByName(name, ignoreCase).stream())
.collect(Collectors.toList());
}
@Override
public List<TextChannel> getTextChannels()
{
return Collections.unmodifiableList(new ArrayList<>(textChannels.valueCollection()));
}
@Override
public TextChannel getTextChannelById(String id)
{
return textChannels.get(MiscUtil.parseSnowflake(id));
}
@Override
public TextChannel getTextChannelById(long id)
{
return textChannels.get(id);
}
@Override
public List<TextChannel> getTextChannelsByName(String name, boolean ignoreCase)
{
return textChannels.valueCollection().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.valueCollection()));
}
@Override
public VoiceChannel getVoiceChannelById(String id)
{
return voiceChannels.get(MiscUtil.parseSnowflake(id));
}
@Override
public VoiceChannel getVoiceChannelById(long id)
{
return voiceChannels.get(id);
}
@Override
public List<VoiceChannel> getVoiceChannelByName(String name, boolean ignoreCase)
{
return voiceChannels.valueCollection().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.valueCollection()));
}
@Override
public PrivateChannel getPrivateChannelById(String id)
{
return privateChannels.get(MiscUtil.parseSnowflake(id));
}
@Override
public PrivateChannel getPrivateChannelById(long id)
{
return privateChannels.get(id);
}
@Override
public List<Emote> getEmotes()
{
return guilds.valueCollection().stream()
.flatMap(guild -> guild.getEmotes().stream())
.collect(Collectors.toList());
}
@Override
public List<Emote> getEmotesByName(String name, boolean ignoreCase)
{
return guilds.valueCollection().stream()
.flatMap(guild -> guild.getEmotesByName(name, ignoreCase).stream())
.collect(Collectors.toList());
}
@Override
public Emote getEmoteById(String id)
{
return getEmoteById(MiscUtil.parseSnowflake(id));
}
@Override
public Emote getEmoteById(long id)
{
for (Guild guild : getGuilds())
{
Emote emote = guild.getEmoteById(id);
if (emote != null)
return emote;
}
return null;
}
public SelfUser getSelfUser()
{
return selfUser;
}
@Override
public void shutdown()
{
shutdown(true);
}
@Override
public void shutdown(boolean free)
{
setStatus(Status.SHUTTING_DOWN);
audioManagers.valueCollection().forEach(AudioManager::closeAudioConnection);
if (audioKeepAlivePool != null)
audioKeepAlivePool.shutdownNow();
getClient().setAutoReconnect(false);
getClient().close();
getRequester().shutdown();
pool.shutdown();
if (shutdownHook != null)
{
try
{
Runtime.getRuntime().removeShutdownHook(shutdownHook);
}
catch (Exception ignored) { }
}
if (free)
{
try
{
Unirest.shutdown();
}
catch (IOException ignored) {}
}
setStatus(Status.SHUTDOWN);
}
@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 int getMaxReconnectDelay()
{
return maxReconnectDelay;
}
@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 EntityBuilder getEntityBuilder()
{
return entityBuilder;
}
public GuildLock getGuildLock()
{
return this.guildLock;
}
public IAudioSendFactory getAudioSendFactory()
{
return audioSendFactory;
}
public void setAudioSendFactory(IAudioSendFactory factory)
{
Args.notNull(factory, "Provided IAudioSendFactory");
this.audioSendFactory = factory;
}
public void setPing(long ping)
{
this.ping = ping;
}
public Requester getRequester()
{
return requester;
}
public IEventManager getEventManager()
{
return eventManager;
}
public WebSocketFactory getWebSocketFactory()
{
return wsFactory;
}
public WebSocketClient getClient()
{
return client;
}
public TLongObjectMap<User> getUserMap()
{
return users;
}
public TLongObjectMap<Guild> getGuildMap()
{
return guilds;
}
public TLongObjectMap<TextChannel> getTextChannelMap()
{
return textChannels;
}
public TLongObjectMap<VoiceChannel> getVoiceChannelMap()
{
return voiceChannels;
}
public TLongObjectMap<PrivateChannel> getPrivateChannelMap()
{
return privateChannels;
}
public TLongObjectMap<User> getFakeUserMap()
{
return fakeUsers;
}
public TLongObjectMap<PrivateChannel> getFakePrivateChannelMap()
{
return fakePrivateChannels;
}
public TLongObjectMap<AudioManagerImpl> getAudioManagerMap()
{
return audioManagers;
}
public void setSelfUser(SelfUser selfUser)
{
this.selfUser = selfUser;
}
public void setResponseTotal(int responseTotal)
{
this.responseTotal = responseTotal;
}
public String getIdentifierString()
{
if (shardInfo != null)
return "JDA " + shardInfo.getShardString();
else
return "JDA";
}
private class JDAThreadFactory implements ThreadFactory
{
@Override
public Thread newThread(Runnable r)
{
final Thread thread = new Thread(r, "JDA-Thread " + getIdentifierString());
thread.setDaemon(true);
return thread;
}
}
public ScheduledThreadPoolExecutor getAudioKeepAlivePool()
{
ScheduledThreadPoolExecutor akap = audioKeepAlivePool;
if (akap == null)
{
synchronized (akapLock)
{
akap = audioKeepAlivePool;
if (akap == null)
akap = audioKeepAlivePool = new ScheduledThreadPoolExecutor(1, new AudioWebSocket.KeepAliveThreadFactory(this));
}
}
return akap;
}
public EventCache getEventCache()
{
return eventCache;
}
}