-
-
Notifications
You must be signed in to change notification settings - Fork 737
/
JDAImpl.java
909 lines (779 loc) · 28.1 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
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
/*
* Copyright 2015-2018 Austin Keener & Michael Ritter & Florian Spieß
*
* 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.neovisionaries.ws.client.WebSocketFactory;
import gnu.trove.map.TLongObjectMap;
import net.dv8tion.jda.annotations.DeprecatedSince;
import net.dv8tion.jda.annotations.ReplaceWith;
import net.dv8tion.jda.bot.entities.impl.JDABotImpl;
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.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.handle.GuildSetupController;
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.PresenceImpl;
import net.dv8tion.jda.core.requests.*;
import net.dv8tion.jda.core.requests.restaction.GuildAction;
import net.dv8tion.jda.core.utils.*;
import net.dv8tion.jda.core.utils.cache.CacheFlag;
import net.dv8tion.jda.core.utils.cache.CacheView;
import net.dv8tion.jda.core.utils.cache.SnowflakeCacheView;
import net.dv8tion.jda.core.utils.cache.UpstreamReference;
import net.dv8tion.jda.core.utils.cache.impl.AbstractCacheView;
import net.dv8tion.jda.core.utils.cache.impl.SnowflakeCacheViewImpl;
import net.dv8tion.jda.core.utils.concurrent.CountingThreadFactory;
import net.dv8tion.jda.core.utils.tuple.Pair;
import okhttp3.OkHttpClient;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.MDC;
import javax.security.auth.login.LoginException;
import java.util.*;
import java.util.concurrent.*;
import java.util.stream.Collectors;
public class JDAImpl implements JDA
{
public static final Logger LOG = JDALogger.getLog(JDA.class);
protected final ScheduledExecutorService rateLimitPool;
protected final ScheduledExecutorService gatewayPool;
protected final ExecutorService callbackPool;
protected final boolean shutdownRateLimitPool;
protected final boolean shutdownGatewayPool;
protected final boolean shutdownCallbackPool;
protected final Object audioLifeCycleLock = new Object();
protected ScheduledThreadPoolExecutor audioLifeCyclePool;
protected final SnowflakeCacheViewImpl<User> userCache = new SnowflakeCacheViewImpl<>(User.class, User::getName);
protected final SnowflakeCacheViewImpl<Guild> guildCache = new SnowflakeCacheViewImpl<>(Guild.class, Guild::getName);
protected final SnowflakeCacheViewImpl<Category> categories = new SnowflakeCacheViewImpl<>(Category.class, Channel::getName);
protected final SnowflakeCacheViewImpl<TextChannel> textChannelCache = new SnowflakeCacheViewImpl<>(TextChannel.class, Channel::getName);
protected final SnowflakeCacheViewImpl<VoiceChannel> voiceChannelCache = new SnowflakeCacheViewImpl<>(VoiceChannel.class, Channel::getName);
protected final SnowflakeCacheViewImpl<PrivateChannel> privateChannelCache = new SnowflakeCacheViewImpl<>(PrivateChannel.class, MessageChannel::getName);
protected final TLongObjectMap<User> fakeUsers = MiscUtil.newLongMap();
protected final TLongObjectMap<PrivateChannel> fakePrivateChannels = MiscUtil.newLongMap();
protected final AbstractCacheView<AudioManager> audioManagers = new CacheView.SimpleCacheView<>(AudioManager.class, m -> m.getGuild().getName());
protected final ConcurrentMap<String, String> contextMap;
protected final OkHttpClient httpClient;
protected final WebSocketFactory wsFactory;
protected final AccountType accountType;
protected final PresenceImpl presence;
protected final JDAClientImpl jdaClient;
protected final JDABotImpl jdaBot;
protected final int maxReconnectDelay;
protected final Thread shutdownHook;
protected final EntityBuilder entityBuilder = new EntityBuilder(this);
protected final EventCache eventCache = new EventCache();
protected final EnumSet<CacheFlag> cacheFlags;
protected final SessionController sessionController;
protected final GuildSetupController guildSetupController;
protected UpstreamReference<WebSocketClient> client;
protected Requester requester;
protected IEventManager eventManager = new InterfacedEventManager();
protected IAudioSendFactory audioSendFactory = new DefaultSendFactory();
protected Status status = Status.INITIALIZING;
protected SelfUser selfUser;
protected ShardInfo shardInfo;
protected boolean audioEnabled;
protected boolean bulkDeleteSplittingEnabled;
protected boolean autoReconnect;
protected long responseTotal;
protected long ping = -1;
protected String token;
protected String gatewayUrl;
public JDAImpl(
AccountType accountType, String token, SessionController controller, OkHttpClient httpClient, WebSocketFactory wsFactory,
ScheduledExecutorService rateLimitPool, ScheduledExecutorService gatewayPool, ExecutorService callbackPool,
boolean autoReconnect, boolean audioEnabled, boolean useShutdownHook,
boolean bulkDeleteSplittingEnabled, boolean retryOnTimeout, boolean enableMDC,
boolean shutdownRateLimitPool, boolean shutdownGatewayPool, boolean shutdownCallbackPool,
int poolSize, int maxReconnectDelay,
ConcurrentMap<String, String> contextMap, EnumSet<CacheFlag> cacheFlags)
{
this.accountType = accountType;
this.setToken(token);
this.httpClient = httpClient;
this.wsFactory = wsFactory;
this.autoReconnect = autoReconnect;
this.audioEnabled = audioEnabled;
this.shutdownHook = useShutdownHook ? new Thread(this::shutdown, "JDA Shutdown Hook") : null;
this.bulkDeleteSplittingEnabled = bulkDeleteSplittingEnabled;
this.rateLimitPool = rateLimitPool == null ? newScheduler(poolSize, "RateLimit") : rateLimitPool;
this.gatewayPool = gatewayPool == null ? newScheduler(1, "Gateway") : gatewayPool;
this.callbackPool = callbackPool == null ? ForkJoinPool.commonPool() : callbackPool;
this.shutdownRateLimitPool = shutdownRateLimitPool;
this.shutdownGatewayPool = shutdownGatewayPool;
this.shutdownCallbackPool = shutdownCallbackPool;
this.maxReconnectDelay = maxReconnectDelay;
this.sessionController = controller == null ? new SessionControllerAdapter() : controller;
if (enableMDC)
this.contextMap = contextMap == null ? new ConcurrentHashMap<>() : contextMap;
else
this.contextMap = null;
this.presence = new PresenceImpl(this);
this.requester = new Requester(this);
this.requester.setRetryOnTimeout(retryOnTimeout);
this.jdaClient = accountType == AccountType.CLIENT ? new JDAClientImpl(this) : null;
this.jdaBot = accountType == AccountType.BOT ? new JDABotImpl(this) : null;
this.guildSetupController = new GuildSetupController(this);
this.cacheFlags = cacheFlags;
}
private ScheduledThreadPoolExecutor newScheduler(int coreSize, String baseName)
{
return new ScheduledThreadPoolExecutor(coreSize, new CountingThreadFactory(this::getIdentifierString, baseName));
}
public boolean isCacheFlagSet(CacheFlag flag)
{
return cacheFlags.contains(flag);
}
public SessionController getSessionController()
{
return sessionController;
}
@Deprecated
@DeprecatedSince("3.8.0")
@ReplaceWith("getGuildSetupController()")
public GuildLock getGuildLock()
{
return new GuildLock(this);
}
public GuildSetupController getGuildSetupController()
{
return guildSetupController;
}
public int login(String gatewayUrl, ShardInfo shardInfo, boolean compression, boolean validateToken) throws LoginException
{
this.gatewayUrl = gatewayUrl;
this.shardInfo = shardInfo;
setStatus(Status.LOGGING_IN);
if (token == null || token.isEmpty())
throw new LoginException("Provided token was null or empty!");
Map<String, String> previousContext = null;
if (contextMap != null)
{
if (shardInfo != null)
{
contextMap.put("jda.shard", shardInfo.getShardString());
contextMap.put("jda.shard.id", String.valueOf(shardInfo.getShardId()));
contextMap.put("jda.shard.total", String.valueOf(shardInfo.getShardTotal()));
}
// set MDC metadata for build thread
previousContext = MDC.getCopyOfContextMap();
contextMap.forEach(MDC::put);
requester.setContextReady(true);
}
if (validateToken)
{
verifyToken();
LOG.info("Login Successful!");
}
client = new UpstreamReference<>(new WebSocketClient(this, compression));
// remove our MDC metadata when we exit our code
if (previousContext != null)
previousContext.forEach(MDC::put);
if (shutdownHook != null)
Runtime.getRuntime().addShutdownHook(shutdownHook);
return shardInfo == null ? -1 : shardInfo.getShardTotal();
}
public String getGateway()
{
return getSessionController().getGateway(this);
}
// This method also checks for a valid bot token as it is required to get the recommended shard count.
public Pair<String, Integer> getGatewayBot()
{
return getSessionController().getGatewayBot(this);
}
public ConcurrentMap<String, String> getContextMap()
{
return contextMap == null ? null : new ConcurrentHashMap<>(contextMap);
}
public void setContext()
{
if (contextMap != null)
contextMap.forEach(MDC::put);
}
public void setStatus(Status status)
{
//noinspection SynchronizeOnNonFinalField
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
{
this.verifyToken(false);
}
// @param alreadyFailed If has already been a failed attempt with the current configuration
public void verifyToken(boolean alreadyFailed) throws LoginException
{
RestAction<JSONObject> login = new RestAction<JSONObject>(this, Route.Self.GET_SELF.compile())
{
@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;
if (!alreadyFailed)
{
userResponse = checkToken(login);
if (userResponse != null)
{
verifyAccountType(userResponse);
return;
}
}
//If we received a null return for userResponse, then that means we hit a 401.
// 401 occurs when 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.substring("Bot ".length());
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);
}
userResponse = checkToken(login);
shutdownNow();
//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)
verifyAccountType(userResponse);
else //We 401'd again. This is an invalid token
throw new LoginException("The provided token is invalid!");
}
private void verifyAccountType(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!");
}
}
private JSONObject checkToken(RestAction<JSONObject> login) throws LoginException
{
JSONObject userResponse;
try
{
userResponse = login.complete();
}
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() instanceof ExecutionException ? e.getCause().getCause() : null;
if (ex instanceof LoginException)
throw new LoginException(ex.getMessage());
else
throw e;
}
return userResponse;
}
@Override
public String getToken()
{
return token;
}
@Override
public boolean isAudioEnabled()
{
return audioEnabled;
}
@Override
public boolean isBulkDeleteSplittingEnabled()
{
return bulkDeleteSplittingEnabled;
}
@Override
public void setAutoReconnect(boolean autoReconnect)
{
this.autoReconnect = autoReconnect;
WebSocketClient client = getClient();
if (client != null)
client.setAutoReconnect(autoReconnect);
}
@Override
public void setRequestTimeoutRetry(boolean retryOnTimeout)
{
requester.setRetryOnTimeout(retryOnTimeout);
}
@Override
public boolean isAutoReconnect()
{
return autoReconnect;
}
@Override
public Status getStatus()
{
return status;
}
@Override
public long getPing()
{
return ping;
}
@Override
public JDA awaitStatus(Status status) throws InterruptedException
{
Checks.notNull(status, "Status");
Checks.check(status.isInit(), "Cannot await the status %s as it is not part of the login cycle!", status);
if (getStatus() == Status.CONNECTED)
return this;
while (!getStatus().isInit() // JDA might disconnect while starting
|| getStatus().ordinal() < status.ordinal()) // Wait until status is bypassed
{
if (getStatus() == Status.SHUTDOWN)
throw new IllegalStateException("Was shutdown trying to await status");
Thread.sleep(50);
}
return this;
}
@Override
public List<String> getCloudflareRays()
{
WebSocketClient client = getClient();
return client == null ? Collections.emptyList() : Collections.unmodifiableList(new LinkedList<>(client.getCfRays()));
}
@Override
public List<String> getWebSocketTrace()
{
WebSocketClient client = getClient();
return client == null ? Collections.emptyList() : Collections.unmodifiableList(new LinkedList<>(client.getTraces()));
}
@Override
public List<Guild> getMutualGuilds(User... users)
{
Checks.notNull(users, "users");
return getMutualGuilds(Arrays.asList(users));
}
@Override
public List<Guild> getMutualGuilds(Collection<User> users)
{
Checks.notNull(users, "users");
for(User u : users)
Checks.notNull(u, "All users");
return Collections.unmodifiableList(getGuilds().stream()
.filter(guild -> users.stream().allMatch(guild::isMember))
.collect(Collectors.toList()));
}
@Override
public RestAction<User> retrieveUserById(String id)
{
return retrieveUserById(MiscUtil.parseSnowflake(id));
}
@Override
public RestAction<User> retrieveUserById(long id)
{
AccountTypeException.check(accountType, AccountType.BOT);
// check cache
User user = this.getUserById(id);
if (user != null)
return new RestAction.EmptyRestAction<>(this, user);
Route.CompiledRoute route = Route.Users.GET_USER.compile(Long.toUnsignedString(id));
return new RestAction<User>(this, route)
{
@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 CacheView<AudioManager> getAudioManagerCache()
{
return audioManagers;
}
@Override
public SnowflakeCacheView<Guild> getGuildCache()
{
return guildCache;
}
@Override
public SnowflakeCacheView<Role> getRoleCache()
{
return CacheView.allSnowflakes(() -> guildCache.stream().map(Guild::getRoleCache));
}
@Override
public SnowflakeCacheView<Emote> getEmoteCache()
{
return CacheView.allSnowflakes(() -> guildCache.stream().map(Guild::getEmoteCache));
}
@Override
public SnowflakeCacheView<Category> getCategoryCache()
{
return categories;
}
@Override
public SnowflakeCacheView<TextChannel> getTextChannelCache()
{
return textChannelCache;
}
@Override
public SnowflakeCacheView<VoiceChannel> getVoiceChannelCache()
{
return voiceChannelCache;
}
@Override
public SnowflakeCacheView<PrivateChannel> getPrivateChannelCache()
{
return privateChannelCache;
}
@Override
public SnowflakeCacheView<User> getUserCache()
{
return userCache;
}
public SelfUser getSelfUser()
{
return selfUser;
}
@Override
public void shutdownNow()
{
shutdown();
if (shutdownRateLimitPool)
getRateLimitPool().shutdownNow();
if (shutdownGatewayPool)
getGatewayPool().shutdownNow();
if (shutdownCallbackPool)
getCallbackPool().shutdownNow();
}
@Override
public void shutdown()
{
if (status == Status.SHUTDOWN || status == Status.SHUTTING_DOWN)
return;
setStatus(Status.SHUTTING_DOWN);
WebSocketClient client = getClient();
if (client != null)
client.shutdown();
shutdownInternals();
}
public synchronized void shutdownInternals()
{
if (status == Status.SHUTDOWN)
return;
//so we can shutdown from WebSocketClient properly
audioManagers.forEach(AudioManager::closeAudioConnection);
audioManagers.clear();
if (audioLifeCyclePool != null)
audioLifeCyclePool.shutdownNow();
getRequester().shutdown();
if (shutdownGatewayPool)
getGatewayPool().shutdown();
if (shutdownCallbackPool)
getCallbackPool().shutdown();
if (shutdownRateLimitPool)
{
ScheduledExecutorService rateLimitPool = getRateLimitPool();
if (rateLimitPool instanceof ScheduledThreadPoolExecutor)
{
ScheduledThreadPoolExecutor executor = (ScheduledThreadPoolExecutor) rateLimitPool;
executor.setKeepAliveTime(5L, TimeUnit.SECONDS);
executor.allowCoreThreadTimeOut(true);
}
else
{
rateLimitPool.shutdown();
}
}
if (shutdownHook != null)
{
try
{
Runtime.getRuntime().removeShutdownHook(shutdownHook);
}
catch (Exception ignored) {}
}
setStatus(Status.SHUTDOWN);
}
@Override
public JDAClientImpl asClient()
{
AccountTypeException.check(getAccountType(), AccountType.CLIENT);
return jdaClient;
}
@Override
public JDABotImpl asBot()
{
AccountTypeException.check(getAccountType(), 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 IEventManager getEventManager()
{
return eventManager;
}
//@Override
//public AuditableRestAction<Void> installAuxiliaryCable(int port) throws UnsupportedOperationException
//{
// return new AuditableRestAction.FailedRestAction<>(new UnsupportedOperationException("nice try but next time think first :)"));
//}
@Override
public AccountType getAccountType()
{
return accountType;
}
@Override
public void setEventManager(IEventManager eventManager)
{
this.eventManager = eventManager == null ? new InterfacedEventManager() : eventManager;
}
@Override
public void addEventListener(Object... listeners)
{
Checks.noneNull(listeners, "listeners");
for (Object listener: listeners)
eventManager.register(listener);
}
@Override
public void removeEventListener(Object... listeners)
{
Checks.noneNull(listeners, "listeners");
for (Object listener: listeners)
eventManager.unregister(listener);
}
@Override
public List<Object> getRegisteredListeners()
{
return Collections.unmodifiableList(eventManager.getRegisteredListeners());
}
@Override
public GuildAction createGuild(String name)
{
switch (accountType)
{
case BOT:
if (guildCache.size() >= 10)
throw new IllegalStateException("Cannot create a Guild with a Bot in more than 10 guilds!");
break;
case CLIENT:
if (guildCache.size() >= 100)
throw new IllegalStateException("Cannot be in more than 100 guilds with AccountType.CLIENT!");
}
return new GuildAction(this, name);
}
@Override
public RestAction<Webhook> getWebhookById(String webhookId)
{
Checks.isSnowflake(webhookId, "Webhook ID");
Route.CompiledRoute route = Route.Webhooks.GET_WEBHOOK.compile(webhookId);
return new RestAction<Webhook>(this, route)
{
@Override
protected void handleResponse(Response response, Request<Webhook> request)
{
if (!response.isOk())
{
request.onFailure(response);
return;
}
JSONObject object = response.getObject();
EntityBuilder builder = api.get().getEntityBuilder();
Webhook webhook = builder.createWebhook(object);
request.onSuccess(webhook);
}
};
}
public EntityBuilder getEntityBuilder()
{
return entityBuilder;
}
public IAudioSendFactory getAudioSendFactory()
{
return audioSendFactory;
}
public void setAudioSendFactory(IAudioSendFactory factory)
{
Checks.notNull(factory, "Provided IAudioSendFactory");
this.audioSendFactory = factory;
}
public void setPing(long ping)
{
this.ping = ping;
}
public Requester getRequester()
{
return requester;
}
public WebSocketFactory getWebSocketFactory()
{
return wsFactory;
}
public WebSocketClient getClient()
{
return client == null ? null : client.get();
}
public TLongObjectMap<User> getUserMap()
{
return userCache.getMap();
}
public TLongObjectMap<Guild> getGuildMap()
{
return guildCache.getMap();
}
public TLongObjectMap<Category> getCategoryMap()
{
return categories.getMap();
}
public TLongObjectMap<TextChannel> getTextChannelMap()
{
return textChannelCache.getMap();
}
public TLongObjectMap<VoiceChannel> getVoiceChannelMap()
{
return voiceChannelCache.getMap();
}
public TLongObjectMap<PrivateChannel> getPrivateChannelMap()
{
return privateChannelCache.getMap();
}
public TLongObjectMap<User> getFakeUserMap()
{
return fakeUsers;
}
public TLongObjectMap<PrivateChannel> getFakePrivateChannelMap()
{
return fakePrivateChannels;
}
public TLongObjectMap<AudioManager> getAudioManagerMap()
{
return audioManagers.getMap();
}
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";
}
public EventCache getEventCache()
{
return eventCache;
}
public OkHttpClient getHttpClient()
{
return httpClient;
}
public String getGatewayUrl()
{
return gatewayUrl;
}
public void resetGatewayUrl()
{
this.gatewayUrl = getGateway();
}
public ScheduledThreadPoolExecutor getAudioLifeCyclePool()
{
ScheduledThreadPoolExecutor pool = audioLifeCyclePool;
if (pool == null)
{
synchronized (audioLifeCycleLock)
{
pool = audioLifeCyclePool;
if (pool == null)
pool = audioLifeCyclePool = newScheduler(1, "AudioLifeCycle");
}
}
return pool;
}
public ScheduledExecutorService getRateLimitPool()
{
return rateLimitPool;
}
public ScheduledExecutorService getGatewayPool()
{
return gatewayPool;
}
public ExecutorService getCallbackPool()
{
return callbackPool;
}
}