/
WebSocketClient.java
1376 lines (1257 loc) · 50.4 KB
/
WebSocketClient.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
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright 2015-2020 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors
*
* 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.internal.requests;
import com.neovisionaries.ws.client.*;
import gnu.trove.iterator.TLongObjectIterator;
import gnu.trove.map.TLongObjectMap;
import net.dv8tion.jda.api.AccountType;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.audio.hooks.ConnectionListener;
import net.dv8tion.jda.api.audio.hooks.ConnectionStatus;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.VoiceChannel;
import net.dv8tion.jda.api.events.*;
import net.dv8tion.jda.api.exceptions.ParsingException;
import net.dv8tion.jda.api.managers.AudioManager;
import net.dv8tion.jda.api.requests.CloseCode;
import net.dv8tion.jda.api.utils.Compression;
import net.dv8tion.jda.api.utils.MiscUtil;
import net.dv8tion.jda.api.utils.SessionController;
import net.dv8tion.jda.api.utils.data.DataArray;
import net.dv8tion.jda.api.utils.data.DataObject;
import net.dv8tion.jda.api.utils.data.DataType;
import net.dv8tion.jda.internal.JDAImpl;
import net.dv8tion.jda.internal.audio.ConnectionRequest;
import net.dv8tion.jda.internal.audio.ConnectionStage;
import net.dv8tion.jda.internal.entities.GuildImpl;
import net.dv8tion.jda.internal.handle.*;
import net.dv8tion.jda.internal.managers.AudioManagerImpl;
import net.dv8tion.jda.internal.managers.PresenceImpl;
import net.dv8tion.jda.internal.utils.IOUtil;
import net.dv8tion.jda.internal.utils.JDALogger;
import net.dv8tion.jda.internal.utils.UnlockHook;
import net.dv8tion.jda.internal.utils.cache.AbstractCacheView;
import net.dv8tion.jda.internal.utils.compress.Decompressor;
import net.dv8tion.jda.internal.utils.compress.ZlibDecompressor;
import org.slf4j.Logger;
import org.slf4j.MDC;
import javax.annotation.Nonnull;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.lang.ref.SoftReference;
import java.time.OffsetDateTime;
import java.util.*;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.zip.DataFormatException;
public class WebSocketClient extends WebSocketAdapter implements WebSocketListener
{
public static final Logger LOG = JDALogger.getLog(WebSocketClient.class);
public static final int DISCORD_GATEWAY_VERSION = 6;
public static final int IDENTIFY_DELAY = 5;
public static final int ZLIB_SUFFIX = 0x0000FFFF;
protected static final String INVALIDATE_REASON = "INVALIDATE_SESSION";
protected static final long IDENTIFY_BACKOFF = TimeUnit.SECONDS.toMillis(SessionController.IDENTIFY_DELAY); // same as 1000 * IDENTIFY_DELAY
protected final JDAImpl api;
protected final JDA.ShardInfo shardInfo;
protected final Map<String, SocketHandler> handlers = new HashMap<>();
protected final Compression compression;
public WebSocket socket;
protected String sessionId = null;
protected final Object readLock = new Object();
protected Decompressor decompressor;
protected final ReentrantLock queueLock = new ReentrantLock();
protected final ScheduledExecutorService executor;
protected WebSocketSendingThread ratelimitThread;
protected volatile Future<?> keepAliveThread;
protected boolean initiating;
protected int reconnectTimeoutS = 2;
protected long heartbeatStartTime;
protected long identifyTime = 0;
protected final TLongObjectMap<ConnectionRequest> queuedAudioConnections = MiscUtil.newLongMap();
protected final Queue<String> chunkSyncQueue = new ConcurrentLinkedQueue<>();
protected final Queue<String> ratelimitQueue = new ConcurrentLinkedQueue<>();
protected volatile long ratelimitResetTime;
protected final AtomicInteger messagesSent = new AtomicInteger(0);
protected volatile boolean shutdown = false;
protected boolean shouldReconnect;
protected boolean handleIdentifyRateLimit = false;
protected boolean connected = false;
protected volatile boolean printedRateLimitMessage = false;
protected volatile boolean sentAuthInfo = false;
protected boolean firstInit = true;
protected boolean processingReady = true;
protected volatile ConnectNode connectNode;
public WebSocketClient(JDAImpl api, Compression compression)
{
this.api = api;
this.executor = api.getGatewayPool();
this.shardInfo = api.getShardInfo();
this.compression = compression;
this.shouldReconnect = api.isAutoReconnect();
this.connectNode = new StartingNode();
setupHandlers();
try
{
api.getSessionController().appendSession(connectNode);
}
catch (RuntimeException | Error e)
{
LOG.error("Failed to append new session to session controller queue. Shutting down!", e);
this.api.setStatus(JDA.Status.SHUTDOWN);
this.api.handleEvent(
new ShutdownEvent(api, OffsetDateTime.now(), 1006));
if (e instanceof RuntimeException)
throw (RuntimeException) e;
else
throw (Error) e;
}
}
public JDA getJDA()
{
return api;
}
public void setAutoReconnect(boolean reconnect)
{
this.shouldReconnect = reconnect;
}
public boolean isConnected()
{
return connected;
}
public void ready()
{
if (initiating)
{
initiating = false;
processingReady = false;
if (firstInit)
{
firstInit = false;
if (api.getGuilds().size() >= 2000) //Show large warning when connected to >=2000 guilds
{
JDAImpl.LOG.warn(" __ __ _ ___ _ _ ___ _ _ ___ _ ");
JDAImpl.LOG.warn(" \\ \\ / //_\\ | _ \\| \\| ||_ _|| \\| | / __|| |");
JDAImpl.LOG.warn(" \\ \\/\\/ // _ \\ | /| .` | | | | .` || (_ ||_|");
JDAImpl.LOG.warn(" \\_/\\_//_/ \\_\\|_|_\\|_|\\_||___||_|\\_| \\___|(_)");
JDAImpl.LOG.warn("You're running a session with over 2000 connected");
JDAImpl.LOG.warn("guilds. You should shard the connection in order");
JDAImpl.LOG.warn("to split the load or things like resuming");
JDAImpl.LOG.warn("connection might not work as expected.");
JDAImpl.LOG.warn("For more info see https://git.io/vrFWP");
}
JDAImpl.LOG.info("Finished Loading!");
api.handleEvent(new ReadyEvent(api, api.getResponseTotal()));
}
else
{
updateAudioManagerReferences();
JDAImpl.LOG.info("Finished (Re)Loading!");
api.handleEvent(new ReconnectedEvent(api, api.getResponseTotal()));
}
}
else
{
JDAImpl.LOG.info("Successfully resumed Session!");
api.handleEvent(new ResumedEvent(api, api.getResponseTotal()));
}
api.setStatus(JDA.Status.CONNECTED);
}
public boolean isReady()
{
return !initiating;
}
public void handle(List<DataObject> events)
{
events.forEach(this::onDispatch);
}
public void send(String message)
{
locked("Interrupted while trying to add request to queue", () -> ratelimitQueue.add(message));
}
public void chunkOrSyncRequest(DataObject request)
{
locked("Interrupted while trying to add chunk request", () -> chunkSyncQueue.add(request.toString()));
}
protected boolean send(String message, boolean skipQueue)
{
if (!connected)
return false;
long now = System.currentTimeMillis();
if (this.ratelimitResetTime <= now)
{
this.messagesSent.set(0);
this.ratelimitResetTime = now + 60000;//60 seconds
this.printedRateLimitMessage = false;
}
//Allows 115 messages to be sent before limiting.
if (this.messagesSent.get() <= 115 || (skipQueue && this.messagesSent.get() <= 119)) //technically we could go to 120, but we aren't going to chance it
{
LOG.trace("<- {}", message);
socket.sendText(message);
this.messagesSent.getAndIncrement();
return true;
}
else
{
if (!printedRateLimitMessage)
{
LOG.warn("Hit the WebSocket RateLimit! This can be caused by too many presence or voice status updates (connect/disconnect/mute/deaf). " +
"Regular: {} Voice: {} Chunking: {}", ratelimitQueue.size(), queuedAudioConnections.size(), chunkSyncQueue.size());
printedRateLimitMessage = true;
}
return false;
}
}
protected void setupSendingThread()
{
ratelimitThread = new WebSocketSendingThread(this);
ratelimitThread.start();
}
public void close()
{
if (socket != null)
socket.sendClose(1000);
}
public void close(int code)
{
if (socket != null)
socket.sendClose(code);
}
public void close(int code, String reason)
{
if (socket != null)
socket.sendClose(code, reason);
}
public synchronized void shutdown()
{
shutdown = true;
shouldReconnect = false;
if (connectNode != null)
api.getSessionController().removeSession(connectNode);
close(1000, "Shutting down");
}
/*
### Start Internal methods ###
*/
protected synchronized void connect()
{
if (api.getStatus() != JDA.Status.ATTEMPTING_TO_RECONNECT)
api.setStatus(JDA.Status.CONNECTING_TO_WEBSOCKET);
if (shutdown)
throw new RejectedExecutionException("JDA is shutdown!");
initiating = true;
String url = api.getGatewayUrl() + "?encoding=json&v=" + DISCORD_GATEWAY_VERSION;
if (compression != Compression.NONE)
{
url += "&compress=" + compression.getKey();
switch (compression)
{
case ZLIB:
if (decompressor == null || decompressor.getType() != Compression.ZLIB)
decompressor = new ZlibDecompressor(api.getMaxBufferSize());
break;
default:
throw new IllegalStateException("Unknown compression");
}
}
try
{
WebSocketFactory socketFactory = api.getWebSocketFactory();
//noinspection SynchronizationOnLocalVariableOrMethodParameter
synchronized (socketFactory)
{
String host = IOUtil.getHost(url);
// null if the host is undefined, unlikely but we should handle it
if (host != null)
socketFactory.setServerName(host);
else // practically should never happen
socketFactory.setServerNames(null);
socket = socketFactory.createSocket(url);
}
socket.addHeader("Accept-Encoding", "gzip")
.addListener(this)
.connect();
}
catch (IOException | WebSocketException e)
{
api.resetGatewayUrl();
//Completely fail here. We couldn't make the connection.
throw new IllegalStateException(e);
}
}
@Override
public void onThreadStarted(WebSocket websocket, ThreadType threadType, Thread thread) throws Exception
{
api.setContext();
}
@Override
public void onConnected(WebSocket websocket, Map<String, List<String>> headers)
{
api.setStatus(JDA.Status.IDENTIFYING_SESSION);
if (sessionId == null) //no need to log for resume here
LOG.info("Connected to WebSocket");
else
LOG.debug("Connected to WebSocket");
connected = true;
//reconnectTimeoutS = 2; We will reset this when the session was started successfully (ready/resume)
messagesSent.set(0);
ratelimitResetTime = System.currentTimeMillis() + 60000;
if (sessionId == null)
sendIdentify();
else
sendResume();
}
@Override
public void onDisconnected(WebSocket websocket, WebSocketFrame serverCloseFrame, WebSocketFrame clientCloseFrame, boolean closedByServer)
{
sentAuthInfo = false;
connected = false;
api.setStatus(JDA.Status.DISCONNECTED);
CloseCode closeCode = null;
int rawCloseCode = 1000;
//When we get 1000 from remote close we will try to resume
// as apparently discord doesn't understand what "graceful disconnect" means
boolean isInvalidate = false;
if (keepAliveThread != null)
{
keepAliveThread.cancel(false);
keepAliveThread = null;
}
if (serverCloseFrame != null)
{
rawCloseCode = serverCloseFrame.getCloseCode();
String rawCloseReason = serverCloseFrame.getCloseReason();
closeCode = CloseCode.from(rawCloseCode);
if (closeCode == CloseCode.RATE_LIMITED)
LOG.error("WebSocket connection closed due to ratelimit! Sent more than 120 websocket messages in under 60 seconds!");
else if (closeCode != null)
LOG.debug("WebSocket connection closed with code {}", closeCode);
else if (rawCloseReason != null)
LOG.warn("WebSocket connection closed with code {}: {}", rawCloseCode, rawCloseReason);
else
LOG.warn("WebSocket connection closed with unknown meaning for close-code {}", rawCloseCode);
}
if (clientCloseFrame != null
&& clientCloseFrame.getCloseCode() == 1000
&& Objects.equals(clientCloseFrame.getCloseReason(), INVALIDATE_REASON))
{
//When we close with 1000 we properly dropped our session due to invalidation
// in that case we can be sure that resume will not work and instead we invalidate and reconnect here
isInvalidate = true;
}
// null is considered -reconnectable- as we do not know the close-code meaning
boolean closeCodeIsReconnect = closeCode == null || closeCode.isReconnect();
if (!shouldReconnect || !closeCodeIsReconnect || executor.isShutdown()) //we should not reconnect
{
if (ratelimitThread != null)
{
ratelimitThread.shutdown();
ratelimitThread = null;
}
if (!closeCodeIsReconnect)
{
//it is possible that a token can be invalidated due to too many reconnect attempts
//or that a bot reached a new shard minimum and cannot connect with the current settings
//if that is the case we have to drop our connection and inform the user with a fatal error message
LOG.error("WebSocket connection was closed and cannot be recovered due to identification issues\n{}", closeCode);
}
if (decompressor != null)
decompressor.shutdown();
api.shutdownInternals();
api.handleEvent(new ShutdownEvent(api, OffsetDateTime.now(), rawCloseCode));
}
else
{
//reset our decompression tools
synchronized (readLock)
{
if (decompressor != null)
decompressor.reset();
}
if (isInvalidate)
invalidate(); // 1000 means our session is dropped so we cannot resume
api.handleEvent(new DisconnectEvent(api, serverCloseFrame, clientCloseFrame, closedByServer, OffsetDateTime.now()));
try
{
handleReconnect();
}
catch (InterruptedException e)
{
LOG.error("Failed to resume due to interrupted thread", e);
invalidate();
queueReconnect();
}
}
}
private void handleReconnect() throws InterruptedException
{
if (sessionId == null)
{
if (handleIdentifyRateLimit)
{
long backoff = calculateIdentifyBackoff();
if (backoff > 0)
{
// it seems that most of the time this is already sub-0 when we reach this point
LOG.error("Encountered IDENTIFY Rate Limit! Waiting {} milliseconds before trying again!", backoff);
Thread.sleep(backoff);
}
else
{
LOG.error("Encountered IDENTIFY Rate Limit!");
}
}
LOG.warn("Got disconnected from WebSocket. Appending to reconnect queue");
queueReconnect();
}
else // if resume is possible
{
LOG.warn("Got disconnected from WebSocket. Attempting to resume session");
reconnect();
}
}
protected long calculateIdentifyBackoff()
{
long currentTime = System.currentTimeMillis();
// calculate remaining backoff time since identify
return currentTime - (identifyTime + IDENTIFY_BACKOFF);
}
protected void queueReconnect()
{
try
{
this.api.setStatus(JDA.Status.RECONNECT_QUEUED);
this.connectNode = new ReconnectNode();
this.api.getSessionController().appendSession(connectNode);
}
catch (IllegalStateException ex)
{
LOG.error("Reconnect queue rejected session. Shutting down...");
this.api.setStatus(JDA.Status.SHUTDOWN);
this.api.handleEvent(new ShutdownEvent(api, OffsetDateTime.now(), 1006));
}
}
protected void reconnect() throws InterruptedException
{
reconnect(false);
}
/**
* This method is used to start the reconnect of the JDA instance.
* It is public for access from SessionReconnectQueue extensions.
*
* @param callFromQueue
* whether this was in SessionReconnectQueue and got polled
*/
public void reconnect(boolean callFromQueue) throws InterruptedException
{
Set<MDC.MDCCloseable> contextEntries = null;
Map<String, String> previousContext = null;
{
ConcurrentMap<String, String> contextMap = api.getContextMap();
if (callFromQueue && contextMap != null)
{
previousContext = MDC.getCopyOfContextMap();
contextEntries = contextMap.entrySet().stream()
.map((entry) -> MDC.putCloseable(entry.getKey(), entry.getValue()))
.collect(Collectors.toSet());
}
}
if (shutdown)
{
api.setStatus(JDA.Status.SHUTDOWN);
api.handleEvent(new ShutdownEvent(api, OffsetDateTime.now(), 1000));
return;
}
String message = "";
if (callFromQueue)
message = String.format("Queue is attempting to reconnect a shard...%s ", shardInfo != null ? " Shard: " + shardInfo.getShardString() : "");
LOG.debug("{}Attempting to reconnect in {}s", message, reconnectTimeoutS);
while (shouldReconnect)
{
api.setStatus(JDA.Status.WAITING_TO_RECONNECT);
int delay = reconnectTimeoutS;
// Exponential backoff, reset on session creation (ready/resume)
reconnectTimeoutS = Math.min(reconnectTimeoutS << 1, api.getMaxReconnectDelay());
Thread.sleep(delay * 1000);
handleIdentifyRateLimit = false;
api.setStatus(JDA.Status.ATTEMPTING_TO_RECONNECT);
LOG.debug("Attempting to reconnect!");
try
{
connect();
break;
}
catch (RejectedExecutionException ex)
{
// JDA has already been shutdown so we can stop here
api.setStatus(JDA.Status.SHUTDOWN);
api.handleEvent(new ShutdownEvent(api, OffsetDateTime.now(), 1000));
return;
}
catch (RuntimeException ex)
{
// reconnectTimeoutS = Math.min(reconnectTimeoutS << 1, api.getMaxReconnectDelay());
LOG.warn("Reconnect failed! Next attempt in {}s", reconnectTimeoutS);
}
}
if (contextEntries != null)
contextEntries.forEach(MDC.MDCCloseable::close);
if (previousContext != null)
previousContext.forEach(MDC::put);
}
protected void setupKeepAlive(long timeout)
{
keepAliveThread = executor.scheduleAtFixedRate(() ->
{
api.setContext();
if (connected)
sendKeepAlive();
}, 0, timeout, TimeUnit.MILLISECONDS);
}
protected void sendKeepAlive()
{
String keepAlivePacket =
DataObject.empty()
.put("op", WebSocketCode.HEARTBEAT)
.put("d", api.getResponseTotal()
).toString();
send(keepAlivePacket, true);
heartbeatStartTime = System.currentTimeMillis();
}
protected void sendIdentify()
{
LOG.debug("Sending Identify-packet...");
PresenceImpl presenceObj = (PresenceImpl) api.getPresence();
DataObject connectionProperties = DataObject.empty()
.put("$os", System.getProperty("os.name"))
.put("$browser", "JDA")
.put("$device", "JDA")
.put("$referring_domain", "")
.put("$referrer", "");
DataObject payload = DataObject.empty()
.put("presence", presenceObj.getFullPresence())
.put("token", getToken())
.put("properties", connectionProperties)
.put("v", DISCORD_GATEWAY_VERSION)
.put("guild_subscriptions", api.isGuildSubscriptions())
.put("large_threshold", api.getLargeThreshold());
//Used to make the READY event be given
// as compressed binary data when over a certain size. TY @ShadowLordAlpha
//.put("compress", true);
DataObject identify = DataObject.empty()
.put("op", WebSocketCode.IDENTIFY)
.put("d", payload);
if (shardInfo != null)
{
payload
.put("shard", DataArray.empty()
.add(shardInfo.getShardId())
.add(shardInfo.getShardTotal()));
}
send(identify.toString(), true);
handleIdentifyRateLimit = true;
identifyTime = System.currentTimeMillis();
sentAuthInfo = true;
api.setStatus(JDA.Status.AWAITING_LOGIN_CONFIRMATION);
}
protected void sendResume()
{
LOG.debug("Sending Resume-packet...");
DataObject resume = DataObject.empty()
.put("op", WebSocketCode.RESUME)
.put("d", DataObject.empty()
.put("session_id", sessionId)
.put("token", getToken())
.put("seq", api.getResponseTotal()));
send(resume.toString(), true);
//sentAuthInfo = true; set on RESUMED response as this could fail
api.setStatus(JDA.Status.AWAITING_LOGIN_CONFIRMATION);
}
protected void invalidate()
{
sessionId = null;
sentAuthInfo = false;
locked("Interrupted while trying to invalidate chunk/sync queue", chunkSyncQueue::clear);
api.getTextChannelsView().clear();
api.getVoiceChannelsView().clear();
api.getStoreChannelsView().clear();
api.getCategoriesView().clear();
api.getGuildsView().clear();
api.getUsersView().clear();
api.getPrivateChannelsView().clear();
api.getFakeUserMap().clear();
api.getFakePrivateChannelMap().clear();
api.getEventCache().clear();
api.getGuildSetupController().clearCache();
}
protected void updateAudioManagerReferences()
{
AbstractCacheView<AudioManager> managerView = api.getAudioManagersView();
try (UnlockHook hook = managerView.writeLock())
{
final TLongObjectMap<AudioManager> managerMap = managerView.getMap();
if (managerMap.size() > 0)
LOG.trace("Updating AudioManager references");
for (TLongObjectIterator<AudioManager> it = managerMap.iterator(); it.hasNext(); )
{
it.advance();
final long guildId = it.key();
final AudioManagerImpl mng = (AudioManagerImpl) it.value();
GuildImpl guild = (GuildImpl) api.getGuildById(guildId);
if (guild == null)
{
//We no longer have access to the guild that this audio manager was for. Set the value to null.
queuedAudioConnections.remove(guildId);
mng.closeAudioConnection(ConnectionStatus.DISCONNECTED_REMOVED_DURING_RECONNECT);
it.remove();
}
}
}
}
protected String getToken()
{
if (api.getAccountType() == AccountType.BOT)
return api.getToken().substring("Bot ".length());
return api.getToken();
}
protected List<DataObject> convertPresencesReplace(long responseTotal, DataArray array)
{
// Needs special handling due to content of "d" being an array
List<DataObject> output = new LinkedList<>();
for (int i = 0; i < array.length(); i++)
{
DataObject presence = array.getObject(i);
final DataObject obj = DataObject.empty();
obj.put("comment", "This was constructed from a PRESENCES_REPLACE payload")
.put("op", WebSocketCode.DISPATCH)
.put("s", responseTotal)
.put("d", presence)
.put("t", "PRESENCE_UPDATE");
output.add(obj);
}
return output;
}
protected void handleEvent(DataObject content)
{
try
{
onEvent(content);
}
catch (Exception ex)
{
LOG.error("Encountered exception on lifecycle level\nJSON: {}", content, ex);
api.handleEvent(new ExceptionEvent(api, ex, true));
}
}
protected void onEvent(DataObject content)
{
int opCode = content.getInt("op");
if (!content.isNull("s"))
{
api.setResponseTotal(content.getInt("s"));
}
switch (opCode)
{
case WebSocketCode.DISPATCH:
onDispatch(content);
break;
case WebSocketCode.HEARTBEAT:
LOG.debug("Got Keep-Alive request (OP 1). Sending response...");
sendKeepAlive();
break;
case WebSocketCode.RECONNECT:
LOG.debug("Got Reconnect request (OP 7). Closing connection now...");
close(4000, "OP 7: RECONNECT");
break;
case WebSocketCode.INVALIDATE_SESSION:
LOG.debug("Got Invalidate request (OP 9). Invalidating...");
handleIdentifyRateLimit = handleIdentifyRateLimit && System.currentTimeMillis() - identifyTime < IDENTIFY_BACKOFF;
sentAuthInfo = false;
final boolean isResume = content.getBoolean("d");
// When d: true we can wait a bit and then try to resume again
//sending 4000 to not drop session
int closeCode = isResume ? 4000 : 1000;
if (isResume)
LOG.debug("Session can be recovered... Closing and sending new RESUME request");
else
invalidate();
close(closeCode, INVALIDATE_REASON);
break;
case WebSocketCode.HELLO:
LOG.debug("Got HELLO packet (OP 10). Initializing keep-alive.");
final DataObject data = content.getObject("d");
setupKeepAlive(data.getLong("heartbeat_interval"));
break;
case WebSocketCode.HEARTBEAT_ACK:
LOG.trace("Got Heartbeat Ack (OP 11).");
api.setGatewayPing(System.currentTimeMillis() - heartbeatStartTime);
break;
default:
LOG.debug("Got unknown op-code: {} with content: {}", opCode, content);
}
}
protected void onDispatch(DataObject raw)
{
String type = raw.getString("t");
long responseTotal = api.getResponseTotal();
if (!raw.isType("d", DataType.OBJECT))
{
// Needs special handling due to content of "d" being an array
if (type.equals("PRESENCES_REPLACE"))
{
final DataArray payload = raw.getArray("d");
final List<DataObject> converted = convertPresencesReplace(responseTotal, payload);
final SocketHandler handler = getHandler("PRESENCE_UPDATE");
LOG.trace("{} -> {}", type, payload);
for (DataObject o : converted)
{
handler.handle(responseTotal, o);
// Send raw event after cache has been updated - including comment
if (api.isRawEvents())
api.handleEvent(new RawGatewayEvent(api, responseTotal, o));
}
}
else
{
LOG.debug("Received event with unhandled body type JSON: {}", raw);
}
return;
}
DataObject content = raw.getObject("d");
LOG.trace("{} -> {}", type, content);
JDAImpl jda = (JDAImpl) getJDA();
try
{
switch (type)
{
//INIT types
case "READY":
reconnectTimeoutS = 2;
api.setStatus(JDA.Status.LOADING_SUBSYSTEMS);
processingReady = true;
handleIdentifyRateLimit = false;
// first handle the ready payload before applying the session id
// this prevents a possible race condition with the cache of the guild setup controller
// otherwise the audio connection requests that are currently pending might be removed in the process
handlers.get("READY").handle(responseTotal, raw);
sessionId = content.getString("session_id");
break;
case "RESUMED":
reconnectTimeoutS = 2;
sentAuthInfo = true;
if (!processingReady)
{
initiating = false;
ready();
}
else
{
LOG.debug("Resumed while still processing initial ready");
jda.setStatus(JDA.Status.LOADING_SUBSYSTEMS);
}
break;
default:
long guildId = content.getLong("guild_id", 0L);
if (api.isUnavailable(guildId) && !type.equals("GUILD_CREATE") && !type.equals("GUILD_DELETE"))
{
LOG.debug("Ignoring {} for unavailable guild with id {}. JSON: {}", type, guildId, content);
break;
}
SocketHandler handler = handlers.get(type);
if (handler != null)
handler.handle(responseTotal, raw);
else
LOG.debug("Unrecognized event:\n{}", raw);
}
// Send raw event after cache has been updated
if (api.isRawEvents())
api.handleEvent(new RawGatewayEvent(api, responseTotal, raw));
}
catch (ParsingException ex)
{
LOG.warn("Got an unexpected Json-parse error. Please redirect following message to the devs:\n\t{}\n\t{} -> {}",
ex.getMessage(), type, content, ex);
}
catch (Exception ex)
{
LOG.error("Got an unexpected error. Please redirect following message to the devs:\n\t{} -> {}", type, content, ex);
}
if (responseTotal % EventCache.TIMEOUT_AMOUNT == 0)
jda.getEventCache().timeout(responseTotal);
}
@Override
public void onTextMessage(WebSocket websocket, String message)
{
handleEvent(DataObject.fromJson(message));
}
@Override
public void onBinaryMessage(WebSocket websocket, byte[] binary) throws DataFormatException
{
DataObject json;
// Only acquire lock for decompression and unlock for event handling
synchronized (readLock)
{
json = handleBinary(binary);
}
if (json != null)
handleEvent(json);
}
protected DataObject handleBinary(byte[] binary) throws DataFormatException
{
if (decompressor == null)
throw new IllegalStateException("Cannot decompress binary message due to unknown compression algorithm: " + compression);
// Scoping allows us to print the json that possibly failed parsing
String jsonString;
try
{
jsonString = decompressor.decompress(binary);
if (jsonString == null)
return null;
}
catch (DataFormatException e)
{
close(4000, "MALFORMED_PACKAGE");
throw e;
}
try
{
return DataObject.fromJson(jsonString);
}
catch (ParsingException e)
{
// Print the string that could not be parsed and re-throw the exception
LOG.error("Failed to parse json {}", jsonString);
throw e;
}
}
@Override
public void onUnexpectedError(WebSocket websocket, WebSocketException cause) throws Exception
{
handleCallbackError(websocket, cause);
}
@Override
public void handleCallbackError(WebSocket websocket, Throwable cause)
{
LOG.error("There was an error in the WebSocket connection", cause);
api.handleEvent(new ExceptionEvent(api, cause, true));
}
@Override
public void onThreadCreated(WebSocket websocket, ThreadType threadType, Thread thread) throws Exception
{
String identifier = api.getIdentifierString();
switch (threadType)
{
case CONNECT_THREAD:
thread.setName(identifier + " MainWS-ConnectThread");
break;
case FINISH_THREAD:
thread.setName(identifier + " MainWS-FinishThread");
break;
case READING_THREAD:
thread.setName(identifier + " MainWS-ReadThread");
break;
case WRITING_THREAD:
thread.setName(identifier + " MainWS-WriteThread");
break;
default:
thread.setName(identifier + " MainWS-" + threadType);
}
}
protected void maybeUnlock()
{
if (queueLock.isHeldByCurrentThread())
queueLock.unlock();
}
protected void locked(String comment, Runnable task)
{
try
{
queueLock.lockInterruptibly();
task.run();
}
catch (InterruptedException e)
{
LOG.error(comment, e);
}
finally
{
maybeUnlock();
}
}
protected <T> T locked(String comment, Supplier<T> task)
{
try
{
queueLock.lockInterruptibly();
return task.get();
}
catch (InterruptedException e)
{
LOG.error(comment, e);
return null;
}
finally
{
maybeUnlock();
}
}