/
WebSocketClient.java
962 lines (882 loc) · 36.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
/*
* Copyright 2015-2016 Austin Keener & Michael Ritter
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.dv8tion.jda.core.requests;
import com.neovisionaries.ws.client.*;
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.entities.EntityBuilder;
import net.dv8tion.jda.core.entities.Guild;
import net.dv8tion.jda.core.entities.VoiceChannel;
import net.dv8tion.jda.core.entities.impl.JDAImpl;
import net.dv8tion.jda.core.events.ReadyEvent;
import net.dv8tion.jda.core.events.ReconnectedEvent;
import net.dv8tion.jda.core.events.ResumedEvent;
import net.dv8tion.jda.core.handle.*;
import net.dv8tion.jda.core.managers.AudioManager;
import net.dv8tion.jda.core.managers.impl.PresenceImpl;
import net.dv8tion.jda.core.utils.SimpleLog;
import org.apache.commons.lang3.tuple.MutablePair;
import org.apache.http.HttpHost;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;
public class WebSocketClient extends WebSocketAdapter implements WebSocketListener
{
public static final SimpleLog LOG = SimpleLog.getLog("JDASocket");
public static final int DISCORD_GATEWAY_VERSION = 6;
protected final JDAImpl api;
protected final JDA.ShardInfo shardInfo;
protected final HttpHost proxy;
protected final HashMap<String, SocketHandler> handlers = new HashMap<>();
protected WebSocket socket;
protected String gatewayUrl = null;
protected String sessionId = null;
protected volatile Thread keepAliveThread;
protected boolean connected;
protected volatile boolean chunkingAndSyncing = false;
protected boolean initiating; //cache all events?
protected final List<JSONObject> cachedEvents = new LinkedList<>();
protected boolean shouldReconnect = true;
protected int reconnectTimeoutS = 2;
//GuildId, <TimeOfNextAttempt, AudioConnection>
protected final HashMap<String, MutablePair<Long, VoiceChannel>> queuedAudioConnections = new HashMap<>();
protected final LinkedList<String> ratelimitQueue = new LinkedList<>();
protected volatile Thread ratelimitThread = null;
protected volatile long ratelimitResetTime;
protected volatile int messagesSent;
protected volatile boolean printedRateLimitMessage = false;
protected boolean firstInit = true;
public WebSocketClient(JDAImpl api)
{
this.api = api;
this.shardInfo = api.getShardInfo();
this.proxy = api.getGlobalProxy();
this.shouldReconnect = api.isAutoReconnect();
setupHandlers();
setupSendingThread();
connect();
}
public void setAutoReconnect(boolean reconnect)
{
this.shouldReconnect = reconnect;
}
public boolean isConnected()
{
return connected;
}
public void ready()
{
if (initiating)
{
initiating = false;
if (firstInit)
{
firstInit = false;
JDAImpl.LOG.info("Finished Loading!");
if (api.getGuilds().size() >= 2500) //Show large warning when connected to >2500 guilds
{
JDAImpl.LOG.warn(" __ __ _ ___ _ _ ___ _ _ ___ _ ");
JDAImpl.LOG.warn(" \\ \\ / //_\\ | _ \\| \\| ||_ _|| \\| | / __|| |");
JDAImpl.LOG.warn(" \\ \\/\\/ // _ \\ | /| .` | | | | .` || (_ ||_|");
JDAImpl.LOG.warn(" \\_/\\_//_/ \\_\\|_|_\\|_|\\_||___||_|\\_| \\___|(_)");
JDAImpl.LOG.warn("You're running a session with over 2500 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");
}
api.getEventManager().handle(new ReadyEvent(api, api.getResponseTotal()));
}
else
{
restoreAudioHandlers();
reconnectAudioConnections();
JDAImpl.LOG.info("Finished (Re)Loading!");
api.getEventManager().handle(new ReconnectedEvent(api, api.getResponseTotal()));
}
}
else
{
reconnectAudioConnections();
JDAImpl.LOG.info("Successfully resumed Session!");
api.getEventManager().handle(new ResumedEvent(api, api.getResponseTotal()));
}
api.setStatus(JDA.Status.CONNECTED);
LOG.debug("Resending " + cachedEvents.size() + " cached events...");
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);
}
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()
{
String shardString;
if (shardInfo != null)
shardString = " Shard [" + shardInfo.getShardId() + "\\" + shardInfo.getShardTotal() + "]";
else
shardString = "";
ratelimitThread = new Thread("JDA" + shardString + " Main-WS sending thread")
{
@Override
public void run()
{
boolean needRatelimit;
boolean attemptedToSend;
while (!this.isInterrupted())
{
try
{
attemptedToSend = false;
needRatelimit = false;
MutablePair<Long, VoiceChannel> audioRequest = getNextAudioConnectRequest();
if (audioRequest != null)
{
VoiceChannel channel = audioRequest.getRight();
AudioManager audioManager = channel.getGuild().getAudioManager();
JSONObject audioConnectPacket = new JSONObject()
.put("op", 4)
.put("d", new JSONObject()
.put("guild_id", channel.getGuild().getId())
.put("channel_id", channel.getId())
.put("self_mute", audioManager.isSelfMuted())
.put("self_deaf", audioManager.isSelfDeafened())
);
needRatelimit = !send(audioConnectPacket.toString(), false);
if (!needRatelimit)
{
//Next allowed connect request, 5 seconds from now
audioRequest.setLeft(System.currentTimeMillis() + 2000);
}
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;
}
}
}
};
ratelimitThread.start();
}
public void close()
{
socket.sendClose(1000);
}
/*
### Start Internal methods ###
*/
protected void connect()
{
if (api.getStatus() != JDA.Status.ATTEMPTING_TO_RECONNECT)
api.setStatus(JDA.Status.CONNECTING_TO_WEBSOCKET);
initiating = true;
WebSocketFactory factory = new WebSocketFactory();
if (proxy != null)
{
ProxySettings settings = factory.getProxySettings();
settings.setHost(proxy.getHostName());
settings.setPort(proxy.getPort());
}
try
{
if (gatewayUrl == null)
{
gatewayUrl = getGateway();
if (gatewayUrl == null)
{
throw new RuntimeException("Could not fetch WS-Gateway!");
}
}
socket = factory.createSocket(gatewayUrl)
.addHeader("Accept-Encoding", "gzip")
.addListener(this);
socket.connect();
}
catch (IOException | WebSocketException e)
{
//Completely fail here. We couldn't make the connection.
throw new RuntimeException(e);
}
}
protected String getGateway()
{
try
{
RestAction<String> gateway = new RestAction<String>(api, Route.Self.GATEWAY.compile(),null)
{
@Override
protected void handleResponse(Response response, Request request)
{
try
{
if (response.isOk())
request.onSuccess(response.getObject().getString("url"));
else
request.onFailure(new Exception("Failed to get gateway url"));
}
catch (Exception e)
{
request.onFailure(e);
}
}
};
return gateway.block() + "?encoding=json&v=" + DISCORD_GATEWAY_VERSION;
}
catch (Exception ex)
{
return null;
}
}
@Override
public void onConnected(WebSocket websocket, Map<String, List<String>> headers)
{
api.setStatus(JDA.Status.LOADING_SUBSYSTEMS);
LOG.info("Connected to WebSocket");
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)
{
connected = false;
api.setStatus(JDA.Status.DISCONNECTED);
if (keepAliveThread != null)
{
keepAliveThread.interrupt();
keepAliveThread = null;
}
if (serverCloseFrame != null && serverCloseFrame.getCloseCode() == 4008)
{
LOG.fatal("WebSocket connection closed due to ratelimit! Sent more than 120 websocket messages in under 60 seconds!");
}
if (!shouldReconnect) //we should not reconnect
{
if (ratelimitThread != null)
ratelimitThread.interrupt();
api.setStatus(JDA.Status.SHUTDOWN);
// api.getEventManager().handle(new ShutdownEvent(api, OffsetDateTime.now(), dcAudioConnections));
}
else
{
//TODO reimplement audio connection preservation.
// for (AudioManager mng : api.getAudioManagersMap().values())
// {
// AudioManagerImpl mngImpl = (AudioManagerImpl) mng;
// VoiceChannel channel = null;
// if (mngImpl.isConnected())
// {
// //This causes the AudioDisconnectEvent to be fired.. maybe we should reevaluate that.
// channel = mng.getConnectedChannel();
// mngImpl.closeAudioConnection();
// }
// else if (mngImpl.isAttemptingToConnect())
// channel = mng.getQueuedAudioConnection();
// else if (mngImpl.wasUnexpectedlyDisconnected())
// channel = mngImpl.getUnexpectedDisconnectedChannel();
//
// if (channel != null)
// {
// dcAudioConnections.add(channel);
// }
// }
// api.getEventManager().handle(new DisconnectEvent(api, serverCloseFrame, clientCloseFrame, closedByServer, OffsetDateTime.now(), dcAudioConnections));
reconnect();
}
}
protected void reconnect()
{
LOG.warn("Got disconnected from WebSocket (Internet?!)... Attempting to reconnect in " + reconnectTimeoutS + "s");
while(shouldReconnect)
{
try
{
api.setStatus(JDA.Status.WAITING_TO_RECONNECT);
Thread.sleep(reconnectTimeoutS * 1000);
api.setStatus(JDA.Status.ATTEMPTING_TO_RECONNECT);
}
catch(InterruptedException ignored) {}
LOG.warn("Attempting to reconnect!");
try
{
connect();
break;
}
catch (RuntimeException ex)
{
reconnectTimeoutS = Math.min(reconnectTimeoutS << 1, 900); //*2, cap at 15min max
LOG.warn("Reconnect failed! Next attempt in " + reconnectTimeoutS + "s");
}
}
}
@Override
public void onTextMessage(WebSocket websocket, String message)
{
JSONObject content = new JSONObject(message);
int opCode = content.getInt("op");
if (content.has("s") && !content.isNull("s"))
{
api.setResponseTotal(content.getInt("s"));
}
switch (opCode)
{
case 0:
handleEvent(content);
break;
case 1:
LOG.debug("Got Keep-Alive request (OP 1). Sending response...");
sendKeepAlive();
break;
case 7:
LOG.debug("Got Reconnect request (OP 7). Closing connection now...");
close();
break;
case 9:
LOG.debug("Got Invalidate request (OP 9). Invalidating...");
invalidate();
sendIdentify();
break;
case 10:
LOG.debug("Got HELLO packet (OP 10). Initializing keep-alive.");
setupKeepAlive(content.getJSONObject("d").getLong("heartbeat_interval"));
break;
case 11:
LOG.trace("Got Heartbeat Ack (OP 11).");
break;
default:
LOG.debug("Got unknown op-code: " + opCode + " with content: " + message);
}
}
protected void setupKeepAlive(long timeout)
{
keepAliveThread = new Thread(() ->
{
while (connected)
{
try
{
sendKeepAlive();
//Sleep for heartbeat interval
Thread.sleep(timeout);
}
catch (InterruptedException ex)
{
//connection got cut... terminating keepAliveThread
break;
}
}
});
keepAliveThread.setName("JDA MainWS-KeepAlive" + (shardInfo != null
? " Shard [" + shardInfo.getShardId() + " / " + shardInfo.getShardTotal() + "]"
: ""));
keepAliveThread.setPriority(Thread.MAX_PRIORITY);
keepAliveThread.setDaemon(true);
keepAliveThread.start();
}
protected void sendKeepAlive()
{
String keepAlivePacket =
new JSONObject()
.put("op", 1)
.put("d", api.getResponseTotal()
).toString();
if (!send(keepAlivePacket, true))
ratelimitQueue.addLast(keepAlivePacket);
}
protected void sendIdentify()
{
LOG.debug("Sending Identify-packet...");
PresenceImpl presenceObj = (PresenceImpl) api.getPresence();
JSONObject identify = new JSONObject()
.put("op", 2)
.put("d", new JSONObject()
.put("presence", presenceObj.getFullPresence())
.put("token", api.getToken())
.put("properties", new JSONObject()
.put("$os", System.getProperty("os.name"))
.put("$browser", "JDA")
.put("$device", "JDA")
.put("$referring_domain", "")
.put("$referrer", "")
)
.put("v", DISCORD_GATEWAY_VERSION)
.put("large_threshold", 250)
.put("compress", true)); //Used to make the READY event be given as compressed binary data when over a certain size. TY @ShadowLordAlpha
if (shardInfo != null)
{
identify.getJSONObject("d")
.put("shard", new JSONArray()
.put(shardInfo.getShardId())
.put(shardInfo.getShardTotal()));
}
send(identify.toString(), true);
}
protected void sendResume()
{
LOG.debug("Sending Resume-packet...");
JSONObject resume = new JSONObject()
.put("op", 6)
.put("d", new JSONObject()
.put("session_id", sessionId)
.put("token", api.getToken())
.put("seq", api.getResponseTotal())
);
send(resume.toString(), true);
}
protected void invalidate()
{
sessionId = null;
chunkingAndSyncing = false;
// TODO: Reimplement audio handler preservation
// //Preserve the audio handlers through registry invalidation
// api.getAudioManagersMap().values().forEach(
// mng ->
// {
// String guildId = mng.getGuild().getId();
// if (mng.getSendingHandler() != null)
// audioSendHandlers.put(guildId, mng.getSendingHandler());
// if (mng.getReceiveHandler() != null)
// audioReceivedHandlers.put(guildId, mng.getReceiveHandler());
// }
// );
//
// TODO: Reimplement registry clearing
// //clearing the registry...
// api.getAudioManagersMap().clear();
api.getTextChannelMap().clear();
api.getVoiceChannelMap().clear();
api.getGuildMap().clear();
api.getUserMap().clear();
api.getPrivateChannelMap().clear();
api.getFakeUserMap().clear();
api.getFakePrivateChannelMap().clear();
EntityBuilder.get(api).clearCache();
EventCache.get(api).clear();
GuildLock.get(api).clear();
this.<ReadyHandler>getHandler("READY").clearCache();
this.<GuildMembersChunkHandler>getHandler("GUILD_MEMBERS_CHUNK").clearCache();
if (api.getAccountType() == AccountType.CLIENT)
{
JDAClientImpl client = (JDAClientImpl) api.asClient();
client.getRelationshipMap().clear();
client.getGroupMap().clear();
client.getCallUserMap().clear();
}
}
protected void restoreAudioHandlers()
{
LOG.trace("Restoring cached AudioHandlers.");
// audioSendHandlers.forEach((guildId, handler) ->
// {
// Guild guild = api.getGuildMap().get(guildId);
// if (guild != null)
// {
// AudioManager mng = api.getAudioManager(guild);
// mng.setSendingHandler(handler);
// }
// else
// {
// LOG.warn("Could not restore an AudioSendHandler after reconnect due to the Guild it was connected to " +
// "no longer existing in JDA's registry. Guild Id: " + guildId);
// }
// });
//
// audioReceivedHandlers.forEach((guildId, handler) ->
// {
// Guild guild = api.getGuildMap().get(guildId);
// if (guild != null)
// {
// AudioManager mng = api.getAudioManager(guild);
// mng.setReceivingHandler(handler);
// }
// else
// {
// LOG.warn("Could not restore an AudioReceiveHandler after reconnect due to the Guild it was connected to " +
// "no longer existing in JDA's registry. Guild Id: " + guildId);
// }
// });
// audioSendHandlers.clear();
// audioReceivedHandlers.clear();
// LOG.trace("Finished restoring cached AudioHandlers");
}
protected void reconnectAudioConnections()
{
// if (dcAudioConnections.size() == 0)
// return;
//
// LOG.trace("Cleaning up previous Audio Connections.");
// for (VoiceChannel chan : dcAudioConnections)
// {
// JSONObject obj = new JSONObject()
// .put("op", 4)
// .put("d", new JSONObject()
// .put("guild_id", chan.getGuild().getId())
// .put("channel_id", JSONObject.NULL)
// .put("self_mute", false)
// .put("self_deaf", false)
// );
// send(obj.toString());
// }
//
// LOG.trace("Attempting to reconnect previous Audio Connections...");
// for (VoiceChannel chan : dcAudioConnections)
// {
// String guildId = chan.getGuild().getId();
// String chanId = chan.getId();
//
// Guild guild = api.getGuildMap().get(guildId);
// if (guild == null)
// {
// JDAImpl.LOG.warn("Could not reestablish audio connection during reconnect due to the previous " +
// "connection being connected to a Guild that we are no longer connected to. " +
// "Guild Id: " + guildId
// );
// continue;
// }
//
// VoiceChannel channel = api.getVoiceChannelMap().get(chanId);
// if (channel == null)
// {
// JDAImpl.LOG.warn("Could not reestablish audio connection during reconnect due to the previous " +
// "connection being connected to a VoiceChannel that no longer exists. " +
// "VChannel Id: " + chanId);
// continue;
// }
//
//
// AudioManager manager = api.getAudioManager(guild);
// manager.openAudioConnection(channel);
// }
// LOG.debug("Finished sending packets to reopen previous Audio Connections.");
// dcAudioConnections.clear();
}
protected void handleEvent(JSONObject raw)
{
String type = raw.getString("t");
long responseTotal = api.getResponseTotal();
if (type.equals("GUILD_MEMBER_ADD"))
((GuildMembersChunkHandler) getHandler("GUILD_MEMBERS_CHUNK")).modifyExpectedGuildMember(raw.getJSONObject("d").getString("guild_id"), 1);
if (type.equals("GUILD_MEMBER_REMOVE"))
((GuildMembersChunkHandler) getHandler("GUILD_MEMBERS_CHUNK")).modifyExpectedGuildMember(raw.getJSONObject("d").getString("guild_id"), -1);
//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"))))
{
LOG.debug("Caching " + type + " event during init!");
cachedEvents.add(raw);
return;
}
//
// // Needs special handling due to content of "d" being an array
// if(type.equals("PRESENCE_REPLACE"))
// {
// JSONArray presences = raw.getJSONArray("d");
// LOG.trace(String.format("%s -> %s", type, presences.toString()));
// PresenceUpdateHandler handler = new PresenceUpdateHandler(api, responseTotal);
// for (int i = 0; i < presences.length(); i++)
// {
// JSONObject presence = presences.getJSONObject(i);
// handler.handle(presence);
// }
// return;
// }
JSONObject content = raw.getJSONObject("d");
LOG.trace(String.format("%s -> %s", type, content.toString()));
try
{
switch (type)
{
//INIT types
case "READY":
LOG.debug(String.format("%s -> %s", type, content.toString()));
sessionId = content.getString("session_id");
handlers.get("READY").handle(responseTotal, raw);
break;
case "RESUMED":
initiating = false;
ready();
break;
// case "MESSAGE_DELETE_BULK":
// new MessageBulkDeleteHandler(api, responseTotal).handle(raw);
// break;
// case "VOICE_STATE_UPDATE":
// new VoiceChangeHandler(api, responseTotal).handle(raw);
// break;
// case "VOICE_SERVER_UPDATE":
// if (api.isAudioEnabled())
// new VoiceServerUpdateHandler(api, responseTotal).handle(raw);
// else
// LOG.debug("Received VOICE_SERVER_UPDATE event but ignoring due to audio being disabled/not supported.");
// break;
// case "GUILD_UPDATE":
// new GuildUpdateHandler(api, responseTotal).handle(raw);
// break;
// case "GUILD_ROLE_CREATE":
// new GuildRoleCreateHandler(api, responseTotal).handle(raw);
// break;
// case "GUILD_ROLE_UPDATE":
// new GuildRoleUpdateHandler(api, responseTotal).handle(raw);
// break;
// case "GUILD_ROLE_DELETE":
// new GuildRoleDeleteHandler(api, responseTotal).handle(raw);
// break;
// case "USER_UPDATE":
// new UserUpdateHandler(api, responseTotal).handle(raw);
// break;
// case "USER_GUILD_SETTINGS_UPDATE":
// //TODO: handle notification updates...
// break;
// //Events that Bots shouldn't care about.
// case "MESSAGE_ACK":
// break;
default:
SocketHandler handler = handlers.get(type);
if (handler != null)
handler.handle(responseTotal, raw);
else
LOG.debug("Unrecognized event:\n" + raw);
}
}
catch (JSONException ex)
{
LOG.warn("Got an unexpected Json-parse error. Please redirect following message to the devs:\n\t"
+ ex.getMessage() + "\n\t" + type + " -> " + content);
}
catch (Exception ex)
{
LOG.log(ex);
}
}
@Override
public void onBinaryMessage(WebSocket websocket, byte[] binary) throws UnsupportedEncodingException, DataFormatException
{
//Thanks to ShadowLordAlpha for code and debugging.
//Get the compressed message and inflate it
StringBuilder builder = new StringBuilder();
Inflater decompresser = new Inflater();
decompresser.setInput(binary, 0, binary.length);
byte[] result = new byte[128];
while(!decompresser.finished())
{
int resultLength = decompresser.inflate(result);
builder.append(new String(result, 0, resultLength, "UTF-8"));
}
decompresser.end();
// send the inflated message to the TextMessage method
onTextMessage(websocket, builder.toString());
}
@Override
public void onUnexpectedError(WebSocket websocket, WebSocketException cause) throws Exception
{
handleCallbackError(websocket, cause);
}
@Override
public void handleCallbackError(WebSocket websocket, Throwable cause)
{
// LOG.log(cause);
}
public void setChunkingAndSyncing(boolean active)
{
chunkingAndSyncing = active;
}
public void queueAudioConnect(VoiceChannel channel)
{
queuedAudioConnections.put(channel.getGuild().getId(), new MutablePair<>(System.currentTimeMillis(), channel));
}
public HashMap<String, MutablePair<Long, VoiceChannel>> getQueuedAudioConnectionMap()
{
return queuedAudioConnections;
}
protected MutablePair<Long, VoiceChannel> getNextAudioConnectRequest()
{
synchronized (queuedAudioConnections)
{
long now = System.currentTimeMillis();
Iterator<MutablePair<Long, VoiceChannel>> it = queuedAudioConnections.values().iterator();
while (it.hasNext())
{
MutablePair<Long, VoiceChannel> audioRequest = it.next();
if (audioRequest.getLeft() < now)
{
VoiceChannel channel = audioRequest.getRight();
Guild guild = channel.getGuild();
Guild connGuild = api.getGuildById(guild.getId());
if (connGuild == null)
{
//changeStatus(ConnectionStatus.DISCONNECTED_REMOVED_FROM_GUILD);
it.remove();
continue;
}
VoiceChannel connChannel = connGuild.getVoiceChannelById(channel.getId());
if (connChannel == null)
{
//changeStatus(ConnectionStatus.DISCONNECTED_CHANNEL_DELETED);
it.remove();
continue;
}
if (!connGuild.getSelfMember().hasPermission(connChannel, Permission.VOICE_CONNECT))
{
//changeStatus(ConnectionStatus.DISCONNECTED_LOST_PERMISSION);
it.remove();
continue;
}
return audioRequest;
}
}
}
return null;
}
public HashMap<String, SocketHandler> getHandlers()
{
return handlers;
}
public <T> T getHandler(String type)
{
return (T) handlers.get(type);
}
private void setupHandlers()
{
handlers.put("CHANNEL_CREATE", new ChannelCreateHandler(api));
handlers.put("CHANNEL_DELETE", new ChannelDeleteHandler(api));
handlers.put("CHANNEL_UPDATE", new ChannelUpdateHandler(api));
handlers.put("GUILD_BAN_ADD", new GuildBanHandler(api, true));
handlers.put("GUILD_BAN_REMOVE", new GuildBanHandler(api, false));
handlers.put("GUILD_CREATE", new GuildCreateHandler(api));
handlers.put("GUILD_DELETE", new GuildDeleteHandler(api));
handlers.put("GUILD_EMOJIS_UPDATE", new GuildEmojisUpdateHandler(api));
handlers.put("GUILD_MEMBER_ADD", new GuildMemberAddHandler(api));
handlers.put("GUILD_MEMBER_REMOVE", new GuildMemberRemoveHandler(api));
handlers.put("GUILD_MEMBER_UPDATE", new GuildMemberUpdateHandler(api));
handlers.put("GUILD_MEMBERS_CHUNK", new GuildMembersChunkHandler(api));
handlers.put("GUILD_ROLE_CREATE", new GuildRoleCreateHandler(api));
handlers.put("GUILD_ROLE_DELETE", new GuildRoleDeleteHandler(api));
handlers.put("GUILD_ROLE_UPDATE", new GuildRoleUpdateHandler(api));
handlers.put("GUILD_SYNC", new GuildSyncHandler(api));
handlers.put("GUILD_UPDATE", new GuildUpdateHandler(api));
handlers.put("MESSAGE_CREATE", new MessageCreateHandler(api));
handlers.put("MESSAGE_DELETE", new MessageDeleteHandler(api));
handlers.put("MESSAGE_DELETE_BULK", new MessageBulkDeleteHandler(api));
handlers.put("MESSAGE_REACTION_ADD", new MessageReactionHandler(api, true));
handlers.put("MESSAGE_REACTION_REMOVE", new MessageReactionHandler(api, false));
handlers.put("MESSAGE_REACTION_REMOVE_ALL", new MessageReactionBulkRemoveHandler(api));
handlers.put("MESSAGE_UPDATE", new MessageUpdateHandler(api));
handlers.put("PRESENCE_UPDATE", new PresenceUpdateHandler(api));
handlers.put("READY", new ReadyHandler(api));
handlers.put("TYPING_START", new TypingStartHandler(api));
handlers.put("USER_UPDATE", new UserUpdateHandler(api));
handlers.put("VOICE_SERVER_UPDATE", new VoiceServerUpdateHandler(api));
handlers.put("VOICE_STATE_UPDATE", new VoiceStateUpdateHandler(api));
if (api.getAccountType() == AccountType.CLIENT)
{
handlers.put("CALL_CREATE", new CallCreateHandler(api));
handlers.put("CALL_DELETE", new CallDeleteHandler(api));
handlers.put("CALL_UPDATE", new CallUpdateHandler(api));
handlers.put("CHANNEL_RECIPIENT_ADD", new ChannelRecipientAddHandler(api));
handlers.put("CHANNEL_RECIPIENT_REMOVE", new ChannelRecipientRemoveHandler(api));
handlers.put("RELATIONSHIP_ADD", new RelationshipAddHandler(api));
handlers.put("RELATIONSHIP_REMOVE", new RelationshipRemoveHandler(api));
handlers.put("MESSAGE_ACK", new SocketHandler(api)
{
@Override
protected String handleInternally(JSONObject content)
{
return null;
}
});
}
}
}