/
WebSocketClient.java
1505 lines (1376 loc) · 56.7 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-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.requests;
import com.neovisionaries.ws.client.*;
import gnu.trove.iterator.TLongObjectIterator;
import gnu.trove.map.TLongObjectMap;
import net.dv8tion.jda.client.entities.impl.JDAClientImpl;
import net.dv8tion.jda.client.handle.*;
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.WebSocketCode;
import net.dv8tion.jda.core.audio.ConnectionRequest;
import net.dv8tion.jda.core.audio.ConnectionStage;
import net.dv8tion.jda.core.audio.hooks.ConnectionListener;
import net.dv8tion.jda.core.audio.hooks.ConnectionStatus;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.GuildVoiceState;
import net.dv8tion.jda.core.entities.VoiceChannel;
import net.dv8tion.jda.core.entities.impl.GuildImpl;
import net.dv8tion.jda.core.entities.impl.JDAImpl;
import net.dv8tion.jda.core.events.*;
import net.dv8tion.jda.core.handle.*;
import net.dv8tion.jda.core.managers.AudioManager;
import net.dv8tion.jda.core.managers.impl.AudioManagerImpl;
import net.dv8tion.jda.core.managers.impl.PresenceImpl;
import net.dv8tion.jda.core.utils.JDALogger;
import net.dv8tion.jda.core.utils.MiscUtil;
import net.dv8tion.jda.core.utils.SessionController;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.MDC;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.time.OffsetDateTime;
import java.util.*;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.locks.ReentrantLock;
import java.util.function.Supplier;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;
import java.util.zip.InflaterOutputStream;
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;
private static final String INVALIDATE_REASON = "INVALIDATE_SESSION";
protected final JDAImpl api;
protected final JDA.ShardInfo shardInfo;
protected final Map<String, SocketHandler> handlers = new HashMap<>();
protected final Set<String> cfRays = new HashSet<>();
protected final Set<String> traces = new HashSet<>();
public WebSocket socket;
protected String sessionId = null;
protected Inflater zlibContext = new Inflater();
protected ByteArrayOutputStream readBuffer;
protected volatile Thread keepAliveThread;
protected boolean initiating; //cache all events?
protected final List<JSONObject> cachedEvents = new LinkedList<>();
protected int reconnectTimeoutS = 2;
protected long heartbeatStartTime;
//GuildId, <TimeOfNextAttempt, ConnectionStage, AudioConnection>
protected final TLongObjectMap<ConnectionRequest> queuedAudioConnections = MiscUtil.newLongMap();
protected final ReentrantLock audioQueueLock = new ReentrantLock();
protected final LinkedList<String> chunkSyncQueue = new LinkedList<>();
protected final LinkedList<String> ratelimitQueue = new LinkedList<>();
protected volatile Thread ratelimitThread = null;
protected volatile long ratelimitResetTime;
protected volatile int messagesSent;
protected volatile boolean shutdown = false;
protected boolean shouldReconnect = true;
protected boolean handleIdentifyRateLimit = false;
protected boolean connected = false;
protected volatile boolean chunkingAndSyncing = false;
protected volatile boolean printedRateLimitMessage = false;
protected boolean sentAuthInfo = false;
protected boolean firstInit = true;
protected boolean processingReady = true;
protected volatile ConnectNode connectNode = null;
public WebSocketClient(JDAImpl api)
{
this.api = api;
this.shardInfo = api.getShardInfo();
this.shouldReconnect = api.isAutoReconnect();
this.connectNode = new StartingNode();
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.getEventManager().handle(
new ShutdownEvent(api, OffsetDateTime.now(), 1006));
if (e instanceof RuntimeException)
throw (RuntimeException) e;
else
throw (Error) e;
}
}
public JDA getJDA()
{
return api;
}
public Set<String> getCfRays()
{
return cfRays;
}
public Set<String> getTraces()
{
return traces;
}
protected void updateTraces(JSONArray arr, String type, int opCode)
{
WebSocketClient.LOG.debug("Received a _trace for {} (OP: {}) with {}", type, opCode, arr);
traces.clear();
for (Object o : arr)
traces.add(String.valueOf(o));
}
protected void allocateBuffer(byte[] binary) throws IOException
{
this.readBuffer = new ByteArrayOutputStream(binary.length * 2);
this.readBuffer.write(binary);
}
protected void extendBuffer(byte[] binary) throws IOException
{
if (this.readBuffer != null)
this.readBuffer.write(binary);
}
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.getEventManager().handle(new ReadyEvent(api, api.getResponseTotal()));
}
else
{
updateAudioManagerReferences();
JDAImpl.LOG.info("Finished (Re)Loading!");
api.getEventManager().handle(new ReconnectedEvent(api, api.getResponseTotal()));
}
}
else
{
JDAImpl.LOG.info("Successfully resumed Session!");
api.getEventManager().handle(new ResumedEvent(api, api.getResponseTotal()));
}
api.setStatus(JDA.Status.CONNECTED);
LOG.debug("Resending {} cached events...", cachedEvents.size());
handle(cachedEvents);
LOG.debug("Sending of cached events finished.");
cachedEvents.clear();
}
public boolean isReady()
{
return !initiating;
}
public void handle(List<JSONObject> events)
{
events.forEach(this::handleEvent);
}
public void send(String message)
{
ratelimitQueue.addLast(message);
}
public void chunkOrSyncRequest(JSONObject request)
{
chunkSyncQueue.addLast(request.toString());
}
private boolean send(String message, boolean skipQueue)
{
if (!connected)
return false;
long now = System.currentTimeMillis();
if (this.ratelimitResetTime <= now)
{
this.messagesSent = 0;
this.ratelimitResetTime = now + 60000;//60 seconds
this.printedRateLimitMessage = false;
}
//Allows 115 messages to be sent before limiting.
if (this.messagesSent <= 115 || (skipQueue && this.messagesSent <= 119)) //technically we could go to 120, but we aren't going to chance it
{
LOG.trace("<- {}", message);
socket.sendText(message);
this.messagesSent++;
return true;
}
else
{
if (!printedRateLimitMessage)
{
LOG.warn("Hit the WebSocket RateLimit! If you see this message a lot then you might need to talk to DV8FromTheWorld.");
printedRateLimitMessage = true;
}
return false;
}
}
private void setupSendingThread()
{
ratelimitThread = new Thread(() ->
{
if (api.getContextMap() != null)
MDC.setContextMap(api.getContextMap());
boolean needRatelimit;
boolean attemptedToSend;
while (!Thread.currentThread().isInterrupted())
{
try
{
//Make sure that we don't send any packets before sending auth info.
if (!sentAuthInfo)
{
Thread.sleep(500);
continue;
}
attemptedToSend = false;
needRatelimit = false;
audioQueueLock.lockInterruptibly();
ConnectionRequest audioRequest = getNextAudioConnectRequest();
String chunkOrSyncRequest = chunkSyncQueue.peekFirst();
//if lock isn't needed we already unlock here
if (audioRequest == null || chunkOrSyncRequest != null)
maybeUnlock();
if (chunkOrSyncRequest != null)
{
needRatelimit = !send(chunkOrSyncRequest, false);
if (!needRatelimit)
chunkSyncQueue.removeFirst();
attemptedToSend = true;
}
else if (audioRequest != null)
{
VoiceChannel channel = audioRequest.getChannel();
Guild guild = api.getGuildById(audioRequest.getGuildIdLong());
if (guild == null)
{
// race condition on guild delete, avoid NPE on DISCONNECT requests
queuedAudioConnections.remove(audioRequest.getGuildIdLong());
maybeUnlock();
continue;
}
ConnectionStage stage = audioRequest.getStage();
AudioManager audioManager = guild.getAudioManager();
JSONObject packet;
switch (stage)
{
case RECONNECT:
case DISCONNECT:
packet = newVoiceClose(audioRequest.getGuildIdLong());
break;
default:
case CONNECT:
packet = newVoiceOpen(audioManager, channel);
}
needRatelimit = !send(packet.toString(), false);
if (!needRatelimit)
{
//If we didn't get RateLimited, Next request attempt will be 2 seconds from now
// we remove it in VoiceStateUpdateHandler once we hear that it has updated our status
// in 2 seconds we will attempt again in case we did not receive an update
audioRequest.setNextAttemptEpoch(System.currentTimeMillis() + 2000);
//If we are already in the correct state according to voice state
// we will not receive a VOICE_STATE_UPDATE that would remove it
// thus we update it here
final GuildVoiceState voiceState = guild.getSelfMember().getVoiceState();
updateAudioConnection0(guild.getIdLong(), voiceState.getChannel());
}
maybeUnlock();
attemptedToSend = true;
}
else
{
String message = ratelimitQueue.peekFirst();
if (message != null)
{
needRatelimit = !send(message, false);
if (!needRatelimit)
ratelimitQueue.removeFirst();
attemptedToSend = true;
}
}
if (needRatelimit || !attemptedToSend)
Thread.sleep(1000);
}
catch (InterruptedException ignored)
{
LOG.debug("Main WS send thread interrupted. Most likely JDA is disconnecting the websocket.");
break;
}
finally
{
// on any exception that might cause this lock to not release
maybeUnlock();
}
}
});
ratelimitThread.setUncaughtExceptionHandler((thread, throwable) ->
{
handleCallbackError(socket, throwable);
setupSendingThread();
});
ratelimitThread.setName(api.getIdentifierString() + " MainWS-Sending Thread");
ratelimitThread.start();
}
private JSONObject newVoiceClose(long guildId)
{
return new JSONObject()
.put("op", WebSocketCode.VOICE_STATE)
.put("d", new JSONObject()
.put("guild_id", Long.toUnsignedString(guildId))
.put("channel_id", JSONObject.NULL)
.put("self_mute", false)
.put("self_deaf", false));
}
private JSONObject newVoiceOpen(AudioManager manager, VoiceChannel channel)
{
return new JSONObject()
.put("op", WebSocketCode.VOICE_STATE)
.put("d", new JSONObject()
.put("guild_id", channel.getGuild().getId())
.put("channel_id", channel.getId())
.put("self_mute", manager.isSelfMuted())
.put("self_deaf", manager.isSelfDeafened()));
}
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&compress=zlib-stream&v=" + DISCORD_GATEWAY_VERSION;
try
{
socket = api.getWebSocketFactory()
.createSocket(url)
.addHeader("Accept-Encoding", "gzip")
.addListener(this);
socket.connect();
}
catch (IOException | WebSocketException e)
{
//Completely fail here. We couldn't make the connection.
throw new IllegalStateException(e);
}
}
protected String getGateway()
{
try
{
return api.getSessionController().getGateway(api)
+ "?encoding=json&compress=zlib-stream&v=" + DISCORD_GATEWAY_VERSION;
}
catch (Exception ex)
{
return null;
}
}
@Override
public void onConnected(WebSocket websocket, Map<String, List<String>> headers)
{
//writing thread
if (api.getContextMap() != null)
MDC.setContextMap(api.getContextMap());
api.setStatus(JDA.Status.IDENTIFYING_SESSION);
LOG.info("Connected to WebSocket");
if (headers.containsKey("cf-ray"))
{
List<String> values = headers.get("cf-ray");
if (!values.isEmpty())
{
String ray = values.get(0);
cfRays.add(ray);
LOG.debug("Received new CF-RAY: {}", ray);
}
}
connected = true;
reconnectTimeoutS = 2;
messagesSent = 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.interrupt();
keepAliveThread = null;
}
if (serverCloseFrame != null)
{
rawCloseCode = serverCloseFrame.getCloseCode();
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
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) //we should not reconnect
{
if (ratelimitThread != null)
ratelimitThread.interrupt();
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);
}
api.setStatus(JDA.Status.SHUTDOWN);
api.getEventManager().handle(new ShutdownEvent(api, OffsetDateTime.now(), rawCloseCode));
}
else
{
//reset our zlib decompression tools
zlibContext = new Inflater();
readBuffer = null;
if (isInvalidate)
invalidate(); // 1000 means our session is dropped so we cannot resume
api.getEventManager().handle(new DisconnectEvent(api, serverCloseFrame, clientCloseFrame, closedByServer, OffsetDateTime.now()));
try
{
if (sessionId == null)
queueReconnect();
else // if resume is possible
reconnect();
}
catch (InterruptedException e)
{
LOG.error("Failed to resume due to interrupted thread", e);
invalidate();
queueReconnect();
}
}
}
protected void queueReconnect()
{
if (!handleIdentifyRateLimit)
LOG.warn("Got disconnected from WebSocket (Internet?!)... Appending session to reconnect queue");
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.getEventManager().handle(
new ShutdownEvent(api, OffsetDateTime.now(), 1006));
}
}
protected void reconnect() throws InterruptedException
{
reconnect(false, true);
}
/**
* 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
* @param shouldHandleIdentify
* whether SessionReconnectQueue already handled an IDENTIFY rate limit for this session
*/
public void reconnect(boolean callFromQueue, boolean shouldHandleIdentify) throws InterruptedException
{
if (callFromQueue && api.getContextMap() != null)
api.getContextMap().forEach(MDC::put);
if (shutdown)
{
api.setStatus(JDA.Status.SHUTDOWN);
api.getEventManager().handle(new ShutdownEvent(api, OffsetDateTime.now(), 1000));
return;
}
if (!handleIdentifyRateLimit)
{
if (callFromQueue)
LOG.warn("Queue is attempting to reconnect a shard...{}",
JDALogger.getLazyString(() -> shardInfo != null ? " Shard: " + shardInfo.getShardString() : ""));
else
LOG.warn("Got disconnected from WebSocket (Internet?!)...");
LOG.warn("Attempting to reconnect in {}s", reconnectTimeoutS);
}
while (shouldReconnect)
{
api.setStatus(JDA.Status.WAITING_TO_RECONNECT);
int delay = IDENTIFY_DELAY;
if (handleIdentifyRateLimit && shouldHandleIdentify)
LOG.error("Encountered IDENTIFY (OP {}) Rate Limit! Waiting {} seconds before trying again!", WebSocketCode.IDENTIFY, IDENTIFY_DELAY);
else
delay = reconnectTimeoutS;
Thread.sleep(delay * 1000);
handleIdentifyRateLimit = false;
api.setStatus(JDA.Status.ATTEMPTING_TO_RECONNECT);
LOG.warn("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.getEventManager().handle(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);
}
}
}
@Override
public void onTextMessage(WebSocket websocket, String message)
{
//reading thread
if (api.getContextMap() != null)
MDC.setContextMap(api.getContextMap());
JSONObject content = new JSONObject(message);
try
{
int opCode = content.getInt("op");
if (!content.isNull("s"))
{
api.setResponseTotal(content.getInt("s"));
}
switch (opCode)
{
case WebSocketCode.DISPATCH:
handleEvent(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...");
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 JSONObject data = content.getJSONObject("d");
setupKeepAlive(data.getLong("heartbeat_interval"));
if (!data.isNull("_trace"))
updateTraces(data.getJSONArray("_trace"), "HELLO", WebSocketCode.HELLO);
break;
case WebSocketCode.HEARTBEAT_ACK:
LOG.trace("Got Heartbeat Ack (OP 11).");
api.setPing(System.currentTimeMillis() - heartbeatStartTime);
break;
default:
LOG.debug("Got unknown op-code: {} with content: {}", opCode, message);
}
}
catch (Exception ex)
{
LOG.error("Encountered exception on lifecycle level\nJSON: {}", content, ex);
api.getEventManager().handle(new ExceptionEvent(api, ex, true));
}
}
protected void setupKeepAlive(long timeout)
{
keepAliveThread = new Thread(() ->
{
if (api.getContextMap() != null)
MDC.setContextMap(api.getContextMap());
while (connected)
{
try
{
sendKeepAlive();
//Sleep for heartbeat interval
Thread.sleep(timeout);
}
catch (InterruptedException ex)
{
//connection got cut... terminating keepAliveThread
break;
}
}
});
keepAliveThread.setUncaughtExceptionHandler((thread, throwable) ->
{
handleCallbackError(socket, throwable);
setupKeepAlive(timeout);
});
keepAliveThread.setName(api.getIdentifierString() + " MainWS-KeepAlive Thread");
keepAliveThread.setPriority(Thread.MAX_PRIORITY);
keepAliveThread.setDaemon(true);
keepAliveThread.start();
}
protected void sendKeepAlive()
{
String keepAlivePacket =
new JSONObject()
.put("op", WebSocketCode.HEARTBEAT)
.put("d", api.getResponseTotal()
).toString();
if (!send(keepAlivePacket, true))
ratelimitQueue.addLast(keepAlivePacket);
heartbeatStartTime = System.currentTimeMillis();
}
protected void sendIdentify()
{
LOG.debug("Sending Identify-packet...");
PresenceImpl presenceObj = (PresenceImpl) api.getPresence();
JSONObject connectionProperties = new JSONObject()
.put("$os", System.getProperty("os.name"))
.put("$browser", "JDA")
.put("$device", "JDA")
.put("$referring_domain", "")
.put("$referrer", "");
JSONObject payload = new JSONObject()
.put("presence", presenceObj.getFullPresence())
.put("token", getToken())
.put("properties", connectionProperties)
.put("v", DISCORD_GATEWAY_VERSION)
.put("large_threshold", 250)
//Used to make the READY event be given
// as compressed binary data when over a certain size. TY @ShadowLordAlpha
.put("compress", true);
JSONObject identify = new JSONObject()
.put("op", WebSocketCode.IDENTIFY)
.put("d", payload);
if (shardInfo != null)
{
payload
.put("shard", new JSONArray()
.put(shardInfo.getShardId())
.put(shardInfo.getShardTotal()));
}
send(identify.toString(), true);
handleIdentifyRateLimit = true;
sentAuthInfo = true;
api.setStatus(JDA.Status.AWAITING_LOGIN_CONFIRMATION);
}
protected void sendResume()
{
LOG.debug("Sending Resume-packet...");
JSONObject resume = new JSONObject()
.put("op", WebSocketCode.RESUME)
.put("d", new JSONObject()
.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;
chunkingAndSyncing = false;
sentAuthInfo = false;
chunkSyncQueue.clear();
api.getTextChannelMap().clear();
api.getVoiceChannelMap().clear();
api.getCategoryMap().clear();
api.getGuildMap().clear();
api.getUserMap().clear();
api.getPrivateChannelMap().clear();
api.getFakeUserMap().clear();
api.getFakePrivateChannelMap().clear();
api.getEntityBuilder().clearCache();
api.getEventCache().clear();
api.getGuildLock().clear();
this.<ReadyHandler>getHandler("READY").clearCache();
this.<GuildMembersChunkHandler>getHandler("GUILD_MEMBERS_CHUNK").clearCache();
if (api.getAccountType() == AccountType.CLIENT)
{
JDAClientImpl client = api.asClient();
client.getRelationshipMap().clear();
client.getGroupMap().clear();
client.getCallUserMap().clear();
}
}
protected void updateAudioManagerReferences()
{
final TLongObjectMap<AudioManager> managerMap = api.getAudioManagerMap();
if (managerMap.size() > 0)
LOG.trace("Updating AudioManager references");
synchronized (managerMap)
{
for (TLongObjectIterator<AudioManager> it = managerMap.iterator(); it.hasNext(); )
{
it.advance();
final long guildId = it.key();
final AudioManagerImpl mng = (AudioManagerImpl) it.value();
ConnectionListener listener = mng.getConnectionListener();
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);
if (listener != null)
listener.onStatusChange(ConnectionStatus.DISCONNECTED_REMOVED_FROM_GUILD);
it.remove();
}
else
{
final AudioManagerImpl newMng = new AudioManagerImpl(guild);
newMng.setSelfMuted(mng.isSelfMuted());
newMng.setSelfDeafened(mng.isSelfDeafened());
newMng.setQueueTimeout(mng.getConnectTimeout());
newMng.setSendingHandler(mng.getSendingHandler());
newMng.setReceivingHandler(mng.getReceiveHandler());
newMng.setConnectionListener(listener);
newMng.setAutoReconnect(mng.isAutoReconnect());
if (mng.isConnected() || mng.isAttemptingToConnect())
{
final long channelId = mng.isConnected()
? mng.getConnectedChannel().getIdLong()
: mng.getQueuedAudioConnection().getIdLong();
final VoiceChannel channel = api.getVoiceChannelById(channelId);
if (channel != null)
{
if (mng.isConnected())
mng.closeAudioConnection(ConnectionStatus.ERROR_CANNOT_RESUME);
//closing old connection in order to reconnect later
newMng.setQueuedAudioConnection(channel);
}
else
{
//The voice channel is not cached. It was probably deleted.
queuedAudioConnections.remove(guildId);
if (listener != null)
listener.onStatusChange(ConnectionStatus.DISCONNECTED_CHANNEL_DELETED);
}
}
it.setValue(newMng);
}
}
}
}
protected String getToken()
{
if (api.getAccountType() == AccountType.BOT)
return api.getToken().substring("Bot ".length());
return api.getToken();
}
private List<JSONObject> convertPresencesReplace(long responseTotal, JSONArray array)
{
// Needs special handling due to content of "d" being an array
List<JSONObject> output = new LinkedList<>();
for (int i = 0; i < array.length(); i++)
{
JSONObject presence = array.getJSONObject(i);
final JSONObject obj = new JSONObject();
obj.put("jda-field", "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(JSONObject raw)
{
String type = raw.getString("t");
long responseTotal = api.getResponseTotal();
if (type.equals("GUILD_MEMBER_ADD"))
this.<GuildMembersChunkHandler>getHandler("GUILD_MEMBERS_CHUNK").modifyExpectedGuildMember(raw.getJSONObject("d").getLong("guild_id"), 1);
if (type.equals("GUILD_MEMBER_REMOVE"))
this.<GuildMembersChunkHandler>getHandler("GUILD_MEMBERS_CHUNK").modifyExpectedGuildMember(raw.getJSONObject("d").getLong("guild_id"), -1);
boolean isJSON = raw.opt("d") instanceof JSONObject;
//If initiating, only allows READY, RESUMED, GUILD_MEMBERS_CHUNK, GUILD_SYNC, and GUILD_CREATE through.
// If we are currently chunking, we don't allow GUILD_CREATE through anymore.
if (initiating && !(type.equals("READY")
|| type.equals("GUILD_MEMBERS_CHUNK")
|| type.equals("RESUMED")
|| type.equals("GUILD_SYNC")
|| (!chunkingAndSyncing && type.equals("GUILD_CREATE"))))
{
if (!isJSON)
{
if (type.equals("PRESENCES_REPLACE"))
{
List<JSONObject> converted = convertPresencesReplace(responseTotal, raw.getJSONArray("d"));
LOG.debug("Caching PRESENCES_REPLACE event during init as PRESENCE_UPDATE dispatches!");
cachedEvents.addAll(converted);
}
else
{
LOG.debug("Received event with unhandled body type during init JSON: {}", raw);
}
return;
}
//If we are currently GuildStreaming, and we get a GUILD_DELETE informing us that a Guild is unavailable
// convert it to a GUILD_CREATE for handling.
JSONObject content = raw.getJSONObject("d");
if (!chunkingAndSyncing && type.equals("GUILD_DELETE") && content.has("unavailable") && content.getBoolean("unavailable"))
{
type = "GUILD_CREATE";
raw.put("t", "GUILD_CREATE")
.put("jda-field","This event was originally a GUILD_DELETE but was converted to GUILD_CREATE for WS init Guild streaming");
}
else
{
LOG.debug("Caching {} event during init!", type);
cachedEvents.add(raw);
return;
}
}