/
EntityBuilder.java
1454 lines (1286 loc) · 61.4 KB
/
EntityBuilder.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.entities;
import gnu.trove.map.TLongObjectMap;
import gnu.trove.set.TLongSet;
import gnu.trove.set.hash.TLongHashSet;
import net.dv8tion.jda.bot.entities.ApplicationInfo;
import net.dv8tion.jda.bot.entities.impl.ApplicationInfoImpl;
import net.dv8tion.jda.client.entities.*;
import net.dv8tion.jda.client.entities.impl.*;
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.JDA;
import net.dv8tion.jda.core.OnlineStatus;
import net.dv8tion.jda.core.WebSocketCode;
import net.dv8tion.jda.core.audit.ActionType;
import net.dv8tion.jda.core.audit.AuditLogChange;
import net.dv8tion.jda.core.audit.AuditLogEntry;
import net.dv8tion.jda.core.entities.MessageEmbed.*;
import net.dv8tion.jda.core.entities.impl.*;
import net.dv8tion.jda.core.exceptions.AccountTypeException;
import net.dv8tion.jda.core.handle.GuildMembersChunkHandler;
import net.dv8tion.jda.core.handle.ReadyHandler;
import net.dv8tion.jda.core.utils.Helpers;
import net.dv8tion.jda.core.utils.JDALogger;
import net.dv8tion.jda.core.utils.MiscUtil;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.map.CaseInsensitiveMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.slf4j.Logger;
import java.time.Instant;
import java.time.OffsetDateTime;
import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.UnaryOperator;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
public class EntityBuilder
{
public static final Logger LOG = JDALogger.getLog(EntityBuilder.class);
public static final String MISSING_CHANNEL = "MISSING_CHANNEL";
public static final String MISSING_USER = "MISSING_USER";
public static final String UNKNOWN_MESSAGE_TYPE = "UNKNOWN_MESSAGE_TYPE";
private static final Set<String> richGameFields;
static
{
Set<String> tmp = new HashSet<>();
tmp.add("application_id");
tmp.add("assets");
tmp.add("details");
tmp.add("flags");
tmp.add("party");
tmp.add("session_id");
tmp.add("state");
tmp.add("sync_id");
tmp.add("timestamps");
richGameFields = Collections.unmodifiableSet(tmp);
}
protected final JDAImpl api;
protected final TLongObjectMap<JSONObject> cachedGuildJsons = MiscUtil.newLongMap();
protected final TLongObjectMap<Consumer<Guild>> cachedGuildCallbacks = MiscUtil.newLongMap();
public EntityBuilder(JDA api)
{
this.api = (JDAImpl) api;
}
public SelfUser createSelfUser(JSONObject self)
{
SelfUserImpl selfUser = ((SelfUserImpl) api.getSelfUser());
if (selfUser == null)
{
final long id = self.getLong("id");
selfUser = new SelfUserImpl(id, api);
api.setSelfUser(selfUser);
}
if (!api.getUserMap().containsKey(selfUser.getIdLong()))
api.getUserMap().put(selfUser.getIdLong(), selfUser);
selfUser.setVerified(self.getBoolean("verified"))
.setMfaEnabled(self.getBoolean("mfa_enabled"))
.setName(self.getString("username"))
.setDiscriminator(self.getString("discriminator"))
.setAvatarId(self.optString("avatar", null))
.setBot(Helpers.optBoolean(self, "bot"));
if (this.api.getAccountType() == AccountType.CLIENT)
{
selfUser
.setEmail(self.optString("email", null))
.setMobile(Helpers.optBoolean(self, "mobile"))
.setNitro(Helpers.optBoolean(self, "premium"))
.setPhoneNumber(self.optString("phone", null));
}
return selfUser;
}
public Game createGame(String name, String url, Game.GameType type)
{
return new Game(name, url, type);
}
public void createGuildFirstPass(JSONObject guild, Consumer<Guild> secondPassCallback)
{
final long id = guild.getLong("id");
GuildImpl guildObj = ((GuildImpl) api.getGuildMap().get(id));
if (guildObj == null)
{
guildObj = new GuildImpl(api, id);
api.getGuildMap().put(id, guildObj);
}
if (Helpers.optBoolean(guild, "unavailable"))
{
guildObj.setAvailable(false);
//This is used for when GuildCreateHandler receives a guild that is currently unavailable. During normal READY
// loading for bots (which unavailable is always true) the secondPassCallback parameter will always
// be null.
if (secondPassCallback != null)
secondPassCallback.accept(guildObj);
api.getGuildLock().lock(id);
return;
}
//If we make it to here, the Guild is available. This means 1 of 2 things:
//Either:
// 1) This is Guild provided during READY for a Client account
// 2) This is a Guild received from GuildCreateHandler from a GUILD_CREATE event.
// This could be triggered by joining a guild or due to discord finally
// providing us with Guild information about a previously unavailable guild.
// Whether it was unavailable due to Bot READY unavailability or due to an
// outage within discord matters now.
//
// Either way, we now have enough information to fill in the general information about the Guild.
// This does NOT necessarily mean that we have all information to complete the guild.
// For Client accounts, we will also need to use op 12 (GUILD_SYNC) to get all presences of online users because
// discord only provides Online users that we have an open PM channel with or are friends with for Client accounts.
// On larger guilds we will still need to request all users using op 8 (GUILD_MEMBERS_CHUNK).
//
// The code below takes the information we -do- have and starts to fill in the Guild. It won't create anything
// that might rely on Users that we don't have due to needing the GUILD_MEMBERS_CHUNK
// This includes making VoiceStatus and PermissionOverrides
guildObj.setAvailable(true)
.setIconId(guild.optString("icon", null))
.setSplashId(guild.optString("splash", null))
.setRegion(guild.getString("region"))
.setName(guild.getString("name"))
.setAfkTimeout(Guild.Timeout.fromKey(guild.getInt("afk_timeout")))
.setVerificationLevel(Guild.VerificationLevel.fromKey(guild.getInt("verification_level")))
.setDefaultNotificationLevel(Guild.NotificationLevel.fromKey(guild.getInt("default_message_notifications")))
.setRequiredMFALevel(Guild.MFALevel.fromKey(guild.getInt("mfa_level")))
.setExplicitContentLevel(Guild.ExplicitContentLevel.fromKey(guild.getInt("explicit_content_filter")));
if(guild.isNull("features"))
guildObj.setFeatures(Collections.emptySet());
else
{
guildObj.setFeatures(
StreamSupport.stream(guild.getJSONArray("features").spliterator(), false)
.map(String::valueOf)
.collect(Collectors.toSet())
);
}
JSONArray roles = guild.getJSONArray("roles");
for (int i = 0; i < roles.length(); i++)
{
Role role = createRole(roles.getJSONObject(i), guildObj.getIdLong());
guildObj.getRolesMap().put(role.getIdLong(), role);
if (role.getIdLong() == guildObj.getIdLong())
guildObj.setPublicRole(role);
}
if (!guild.isNull("emojis"))
{
JSONArray array = guild.getJSONArray("emojis");
TLongObjectMap<Emote> emoteMap = guildObj.getEmoteMap();
for (int i = 0; i < array.length(); i++)
{
JSONObject object = array.getJSONObject(i);
if (object.isNull("id"))
{
LOG.error("Received GUILD_CREATE with an emoji with a null ID. JSON: {}", object);
continue;
}
JSONArray emoteRoles = object.isNull("roles") ? new JSONArray() : object.getJSONArray("roles");
final long emoteId = object.getLong("id");
EmoteImpl emoteObj = new EmoteImpl(emoteId, guildObj);
Set<Role> roleSet = emoteObj.getRoleSet();
for (int j = 0; j < emoteRoles.length(); j++)
roleSet.add(guildObj.getRoleById(emoteRoles.getString(j)));
emoteMap.put(emoteId, emoteObj
.setName(object.optString("name"))
.setAnimated(object.optBoolean("animated"))
.setManaged(Helpers.optBoolean(object, "managed")));
}
}
if (guild.has("members"))
{
JSONArray members = guild.getJSONArray("members");
createGuildMemberPass(guildObj, members);
}
//This could be null for Client accounts. Will be fixed by GUILD_SYNC
Member owner = guildObj.getMemberById(guild.getLong("owner_id"));
if (owner != null)
guildObj.setOwner(owner);
if (guild.has("presences"))
{
JSONArray presences = guild.getJSONArray("presences");
for (int i = 0; i < presences.length(); i++)
{
JSONObject presence = presences.getJSONObject(i);
final long userId = presence.getJSONObject("user").getLong("id");
MemberImpl member = (MemberImpl) guildObj.getMembersMap().get(userId);
if (member == null)
LOG.debug("Received a ghost presence in GuildFirstPass! UserId: {} Guild: {}", userId, guildObj);
else
createPresence(member, presence);
}
}
if (guild.has("channels"))
{
JSONArray channels = guild.getJSONArray("channels");
for (int i = 0; i < channels.length(); i++)
{
JSONObject channel = channels.getJSONObject(i);
ChannelType type = ChannelType.fromId(channel.getInt("type"));
switch (type)
{
case TEXT:
createTextChannel(channel, guildObj.getIdLong(), false);
break;
case VOICE:
createVoiceChannel(channel, guildObj.getIdLong(), false);
break;
case CATEGORY:
createCategory(channel, guildObj.getIdLong(), false);
break;
default:
LOG.error("Received a channel for a guild that isn't a text, voice or category channel. JSON: {}", channel);
}
}
}
if (!guild.isNull("system_channel_id"))
guildObj.setSystemChannel(guildObj.getTextChannelsMap().get(guild.getLong("system_channel_id")));
if (!guild.isNull("afk_channel_id"))
guildObj.setAfkChannel(guildObj.getVoiceChannelsMap().get(guild.getLong("afk_channel_id")));
//If the members that we were provided with (and loaded above) were not all of the
// the members in this guild, then we need to request more users from Discord using
// op 9 (GUILD_MEMBERS_CHUNK). To do so, we will cache the guild's JSON so we can properly
// load stuff that relies on Users like Channels, PermissionOverrides and VoiceStatuses
// after we have the rest of the users. We will request the GUILD_MEMBERS_CHUNK information
// which will be sent from discord over the main Websocket and will be handled by
// GuildMemberChunkHandler. After the handler has received all users as determined by the
// value set using `setExpectedGuildMembers`, it will do one of the following:
// 1) If this is a Bot account, immediately call EntityBuilder#createGuildSecondPass, thus finishing
// the Guild object creation process.
// 2) If this is a Client account, it will request op 12 (GUILD_SYNC) to make sure we have all information
// about online users as GUILD_MEMBERS_CHUNK does not include presence information, and when loading the
// members from GUILD_MEMBERS_CHUNK, we assume they are offline. GUILD_SYNC makes sure that we mark them
// properly. After GUILD_SYNC is received by GuildSyncHandler, it will call EntityBuilder#createGuildSecondPass
//
//If we actually -did- get all of the users needed, then we don't need to Chunk. Furthermore,
// we don't need to use GUILD_SYNC because we always get presences with users thus we have all information
// needed to guild the Guild. We will skip
if (guild.getJSONArray("members").length() != guild.getInt("member_count"))
{
cachedGuildJsons.put(id, guild);
cachedGuildCallbacks.put(id, secondPassCallback);
GuildMembersChunkHandler handler = api.getClient().getHandler("GUILD_MEMBERS_CHUNK");
handler.setExpectedGuildMembers(id, guild.getInt("member_count"));
//If we are already past READY / RESUME, then chunk at runtime. Otherwise, pass back to the ReadyHandler
// and let it send a burst chunk request.
if (api.getClient().isReady())
{
if (api.getAccountType() == AccountType.CLIENT)
{
JSONObject obj = new JSONObject()
.put("op", WebSocketCode.GUILD_SYNC)
.put("guild_id", guildObj.getId());
api.getClient().chunkOrSyncRequest(obj);
}
JSONObject obj = new JSONObject()
.put("op", WebSocketCode.MEMBER_CHUNK_REQUEST)
.put("d", new JSONObject()
.put("guild_id", id)
.put("query","")
.put("limit", 0)
);
api.getClient().chunkOrSyncRequest(obj);
}
else
{
ReadyHandler readyHandler = api.getClient().getHandler("READY");
readyHandler.acknowledgeGuild(guildObj, true, true, api.getAccountType() == AccountType.CLIENT);
}
api.getGuildLock().lock(id);
return;
}
//As detailed in the comment above, if we've made it this far then we have all member information needed to
// create the Guild. Thus, we fill in the remaining information, unlock the guild, and provide the guild
// to the callback
//This should only occur on small user count guilds.
JSONArray channels = guild.getJSONArray("channels");
createGuildChannelPass(guildObj, channels); //Actually creates PermissionOverrides
JSONArray voiceStates = guild.getJSONArray("voice_states");
createGuildVoiceStatePass(guildObj, voiceStates);
api.getGuildLock().unlock(guildObj.getIdLong());
if (secondPassCallback != null)
secondPassCallback.accept(guildObj);
}
public void createGuildSecondPass(long guildId, List<JSONArray> memberChunks)
{
JSONObject guildJson = cachedGuildJsons.remove(guildId);
Consumer<Guild> secondPassCallback = cachedGuildCallbacks.remove(guildId);
GuildImpl guildObj = (GuildImpl) api.getGuildMap().get(guildId);
if (guildObj == null)
throw new IllegalStateException("Attempted to perform a second pass on an unknown Guild. Guild not in JDA " +
"mapping. GuildId: " + guildId);
if (guildJson == null)
throw new IllegalStateException("Attempted to perform a second pass on an unknown Guild. No cached Guild " +
"for second pass. GuildId: " + guildId);
if (secondPassCallback == null)
throw new IllegalArgumentException("No callback provided for the second pass on the Guild!");
for (JSONArray chunk : memberChunks)
createGuildMemberPass(guildObj, chunk);
Member owner = guildObj.getMemberById(guildJson.getLong("owner_id"));
if (owner != null)
guildObj.setOwner(owner);
if (guildObj.getOwner() == null)
LOG.error("Never set the Owner of the Guild: {} because we don't have the owner User object! How?!", guildObj.getId());
JSONArray channels = guildJson.getJSONArray("channels");
createGuildChannelPass(guildObj, channels);
JSONArray voiceStates = guildJson.getJSONArray("voice_states");
createGuildVoiceStatePass(guildObj, voiceStates);
secondPassCallback.accept(guildObj);
api.getGuildLock().unlock(guildId);
}
public void handleGuildSync(GuildImpl guild, JSONArray members, JSONArray presences)
{
for (int i = 0; i < members.length(); i++)
{
JSONObject memberJson = members.getJSONObject(i);
createMember(guild, memberJson);
}
for (int i = 0; i < presences.length(); i++)
{
JSONObject presenceJson = presences.getJSONObject(i);
final long userId = presenceJson.getJSONObject("user").getLong("id");
MemberImpl member = (MemberImpl) guild.getMembersMap().get(userId);
if (member == null)
LOG.error("Received a Presence for a non-existent Member when dealing with GuildSync!");
else
this.createPresence(member, presenceJson);
}
}
private void createGuildMemberPass(GuildImpl guildObj, JSONArray members)
{
for (int i = 0; i < members.length(); i++)
{
JSONObject memberJson = members.getJSONObject(i);
createMember(guildObj, memberJson);
}
}
private void createGuildChannelPass(GuildImpl guildObj, JSONArray channels)
{
for (int i = 0; i < channels.length(); i++)
{
JSONObject channel = channels.getJSONObject(i);
ChannelType type = ChannelType.fromId(channel.getInt("type"));
Channel channelObj = null;
switch (type)
{
case TEXT:
channelObj = api.getTextChannelById(channel.getLong("id"));
break;
case VOICE:
channelObj = api.getVoiceChannelById(channel.getLong("id"));
break;
case CATEGORY:
channelObj = api.getCategoryMap().get(channel.getLong("id"));
break;
default:
LOG.error("Received a channel for a guild that isn't a text, voice or category channel (ChannelPass). JSON: {}", channel);
}
if (channelObj != null)
{
JSONArray permissionOverwrites = channel.getJSONArray("permission_overwrites");
createOverridesPass((AbstractChannelImpl<?>) channelObj, permissionOverwrites);
}
else
{
LOG.error("Got permission_override for unknown channel with id: {}", channel.getString("id"));
}
}
}
public void createGuildVoiceStatePass(GuildImpl guildObj, JSONArray voiceStates)
{
for (int i = 0; i < voiceStates.length(); i++)
{
JSONObject voiceStateJson = voiceStates.getJSONObject(i);
final long userId = voiceStateJson.getLong("user_id");
Member member = guildObj.getMembersMap().get(userId);
if (member == null)
{
LOG.error("Received a VoiceState for a unknown Member! GuildId: "
+ guildObj.getId() + " MemberId: " + voiceStateJson.getString("user_id"));
continue;
}
final long channelId = voiceStateJson.getLong("channel_id");
VoiceChannelImpl voiceChannel =
(VoiceChannelImpl) guildObj.getVoiceChannelsMap().get(channelId);
if (voiceChannel != null)
voiceChannel.getConnectedMembersMap().put(member.getUser().getIdLong(), member);
else
LOG.error("Received a GuildVoiceState with a channel ID for a non-existent channel! ChannelId: {} GuildId: {} UserId: {}",
channelId, guildObj.getId(), userId);
// VoiceState is considered volatile so we don't expect anything to actually exist
GuildVoiceStateImpl voiceState = (GuildVoiceStateImpl) member.getVoiceState();
voiceState.setSelfMuted(Helpers.optBoolean(voiceStateJson, "self_mute"))
.setSelfDeafened(Helpers.optBoolean(voiceStateJson, "self_deaf"))
.setGuildMuted(Helpers.optBoolean(voiceStateJson, "mute"))
.setGuildDeafened(Helpers.optBoolean(voiceStateJson, "deaf"))
.setSuppressed(Helpers.optBoolean(voiceStateJson, "suppress"))
.setSessionId(voiceStateJson.optString("session_id"))
.setConnectedChannel(voiceChannel);
}
}
public UserImpl createFakeUser(JSONObject user, boolean modifyCache) { return createUser(user, true, modifyCache); }
public UserImpl createUser(JSONObject user) { return createUser(user, false, true); }
private UserImpl createUser(JSONObject user, boolean fake, boolean modifyCache)
{
final long id = user.getLong("id");
UserImpl userObj;
userObj = (UserImpl) api.getUserMap().get(id);
if (userObj == null)
{
userObj = (UserImpl) api.getFakeUserMap().get(id);
if (userObj != null)
{
if (!fake && modifyCache)
{
api.getFakeUserMap().remove(id);
userObj.setFake(false);
api.getUserMap().put(userObj.getIdLong(), userObj);
if (userObj.hasPrivateChannel())
{
PrivateChannelImpl priv = (PrivateChannelImpl) userObj.getPrivateChannel();
priv.setFake(false);
api.getFakePrivateChannelMap().remove(priv.getIdLong());
api.getPrivateChannelMap().put(priv.getIdLong(), priv);
}
}
}
else
{
userObj = new UserImpl(id, api).setFake(fake);
if (modifyCache)
{
if (fake)
api.getFakeUserMap().put(id, userObj);
else
api.getUserMap().put(id, userObj);
}
}
}
return userObj
.setName(user.getString("username"))
.setDiscriminator(user.get("discriminator").toString())
.setAvatarId(user.optString("avatar", null))
.setBot(Helpers.optBoolean(user, "bot"));
}
public Member createMember(GuildImpl guild, JSONObject memberJson)
{
User user = createUser(memberJson.getJSONObject("user"));
MemberImpl member = (MemberImpl) guild.getMember(user);
if (member == null)
{
member = new MemberImpl(guild, user);
guild.getMembersMap().put(user.getIdLong(), member);
}
((GuildVoiceStateImpl) member.getVoiceState())
.setGuildMuted(memberJson.getBoolean("mute"))
.setGuildDeafened(memberJson.getBoolean("deaf"));
member.setJoinDate(OffsetDateTime.parse(memberJson.getString("joined_at")))
.setNickname(memberJson.optString("nick", null));
JSONArray rolesJson = memberJson.getJSONArray("roles");
for (int k = 0; k < rolesJson.length(); k++)
{
final long roleId = rolesJson.getLong(k);
Role r = guild.getRolesMap().get(roleId);
if (r == null)
{
LOG.debug("Received a Member with an unknown Role. MemberId: {} GuildId: {} roleId: {}",
member.getUser().getId(), guild.getId(), roleId);
}
else
{
member.getRoleSet().add(r);
}
}
return member;
}
//Effectively the same as createFriendPresence
public void createPresence(Object memberOrFriend, JSONObject presenceJson)
{
if (memberOrFriend == null)
throw new NullPointerException("Provided memberOrFriend was null!");
JSONObject gameJson = presenceJson.isNull("game") ? null : presenceJson.getJSONObject("game");
OnlineStatus onlineStatus = OnlineStatus.fromKey(presenceJson.getString("status"));
Game game = null;
boolean parsedGame = false;
if (gameJson != null && !gameJson.isNull("name"))
{
try
{
game = createGame(gameJson);
parsedGame = true;
}
catch (Exception ex)
{
String userId;
if (memberOrFriend instanceof Member)
userId = ((Member) memberOrFriend).getUser().getId();
else if (memberOrFriend instanceof Friend)
userId = ((Friend) memberOrFriend).getUser().getId();
else
userId = "unknown";
if (LOG.isDebugEnabled())
LOG.warn("Encountered exception trying to parse a presence! UserId: {} JSON: {}", userId, gameJson, ex);
else
LOG.warn("Encountered exception trying to parse a presence! UserId: {} Message: {} Enable debug for details", userId, ex.getMessage());
}
}
if (memberOrFriend instanceof Member)
{
MemberImpl member = (MemberImpl) memberOrFriend;
member.setOnlineStatus(onlineStatus);
if (parsedGame)
member.setGame(game);
}
else if (memberOrFriend instanceof Friend)
{
FriendImpl friend = (FriendImpl) memberOrFriend;
friend.setOnlineStatus(onlineStatus);
if (parsedGame)
friend.setGame(game);
OffsetDateTime lastModified = OffsetDateTime.ofInstant(
Instant.ofEpochMilli(presenceJson.getLong("last_modified")),
TimeZone.getTimeZone("GMT").toZoneId());
friend.setOnlineStatusModifiedTime(lastModified);
}
else
throw new IllegalArgumentException("An object was provided to EntityBuilder#createPresence that wasn't a Member or Friend. JSON: " + presenceJson);
}
public static Game createGame(JSONObject gameJson)
{
String name = String.valueOf(gameJson.get("name"));
String url = gameJson.isNull("url") ? null : String.valueOf(gameJson.get("url"));
Game.GameType type;
try
{
type = gameJson.isNull("type")
? Game.GameType.DEFAULT
: Game.GameType.fromKey(Integer.parseInt(gameJson.get("type").toString()));
}
catch (NumberFormatException e)
{
type = Game.GameType.DEFAULT;
}
RichPresence.Timestamps timestamps = null;
if (!gameJson.isNull("timestamps"))
{
JSONObject obj = gameJson.getJSONObject("timestamps");
long start, end;
start = obj.isNull("start") ? 0 : obj.getLong("start");
end = obj.isNull("end") ? 0 : obj.getLong("end");
timestamps = new RichPresence.Timestamps(start, end);
}
if (!CollectionUtils.containsAny(gameJson.keySet(), richGameFields))
return new Game(name, url, type, timestamps);
// data for spotify
long id = Helpers.optLong(gameJson, "application_id", 0);
String sessionId = gameJson.optString("session_id", null);
String syncId = gameJson.optString("sync_id", null);
int flags = Helpers.optInt(gameJson, "flags", 0);
String details = gameJson.isNull("details") ? null : String.valueOf(gameJson.get("details"));
String state = gameJson.isNull("state") ? null : String.valueOf(gameJson.get("state"));
RichPresence.Party party = null;
if (!gameJson.isNull("party"))
{
JSONObject obj = gameJson.getJSONObject("party");
String partyId = obj.isNull("id") ? null : obj.getString("id");
JSONArray sizeArr = obj.isNull("size") ? null : obj.getJSONArray("size");
long size = 0, max = 0;
if (sizeArr != null && sizeArr.length() > 0)
{
size = sizeArr.getLong(0);
max = sizeArr.isNull(1) ? 0 : sizeArr.getLong(1);
}
party = new RichPresence.Party(partyId, size, max);
}
String smallImageKey = null, smallImageText = null;
String largeImageKey = null, largeImageText = null;
if (!gameJson.isNull("assets"))
{
JSONObject assets = gameJson.getJSONObject("assets");
if (!assets.isNull("small_image"))
{
smallImageKey = String.valueOf(assets.get("small_image"));
smallImageText = assets.isNull("small_text") ? null : String.valueOf(assets.get("small_text"));
}
if (!assets.isNull("large_image"))
{
largeImageKey = String.valueOf(assets.get("large_image"));
largeImageText = assets.isNull("large_text") ? null : String.valueOf(assets.get("large_text"));
}
}
return new RichPresence(type, name, url,
id, party, details, state, timestamps, syncId, sessionId, flags,
largeImageKey, largeImageText, smallImageKey, smallImageText);
}
public Category createCategory(JSONObject json, long guildId)
{
return createCategory(json, guildId, true);
}
public Category createCategory(JSONObject json, long guildId, boolean guildIsLoaded)
{
final long id = json.getLong("id");
CategoryImpl channel = (CategoryImpl) api.getCategoryMap().get(id);
if (channel == null)
{
GuildImpl guild = ((GuildImpl) api.getGuildMap().get(guildId));
channel = new CategoryImpl(id, guild);
guild.getCategoriesMap().put(id, channel);
api.getCategoryMap().put(id, channel);
}
if (!json.isNull("permission_overwrites") && guildIsLoaded)
{
JSONArray overrides = json.getJSONArray("permission_overwrites");
createOverridesPass(channel, overrides);
}
return channel
.setName(json.getString("name"))
.setPosition(json.getInt("position"));
}
public TextChannel createTextChannel(JSONObject json, long guildId)
{
return createTextChannel(json, guildId, true);
}
public TextChannel createTextChannel(JSONObject json, long guildId, boolean guildIsLoaded)
{
final long id = json.getLong("id");
TextChannelImpl channel = (TextChannelImpl) api.getTextChannelMap().get(id);
if (channel == null)
{
GuildImpl guild = ((GuildImpl) api.getGuildMap().get(guildId));
channel = new TextChannelImpl(id, guild);
guild.getTextChannelsMap().put(id, channel);
api.getTextChannelMap().put(id, channel);
}
if (!json.isNull("permission_overwrites") && guildIsLoaded)
{
JSONArray overrides = json.getJSONArray("permission_overwrites");
createOverridesPass(channel, overrides);
}
return channel
.setParent(Helpers.optLong(json, "parent_id", 0))
.setLastMessageId(Helpers.optLong(json, "last_message_id", 0))
.setName(json.getString("name"))
.setTopic(json.optString("topic"))
.setPosition(json.getInt("position"))
.setNSFW(Helpers.optBoolean(json, "nsfw"));
}
public VoiceChannel createVoiceChannel(JSONObject json, long guildId)
{
return createVoiceChannel(json, guildId, true);
}
public VoiceChannel createVoiceChannel(JSONObject json, long guildId, boolean guildIsLoaded)
{
final long id = json.getLong("id");
VoiceChannelImpl channel = ((VoiceChannelImpl) api.getVoiceChannelMap().get(id));
if (channel == null)
{
GuildImpl guild = (GuildImpl) api.getGuildMap().get(guildId);
channel = new VoiceChannelImpl(id, guild);
guild.getVoiceChannelsMap().put(id, channel);
api.getVoiceChannelMap().put(id, channel);
}
if (!json.isNull("permission_overwrites") && guildIsLoaded)
{
JSONArray overrides = json.getJSONArray("permission_overwrites");
createOverridesPass(channel, overrides);
}
return channel
.setParent(Helpers.optLong(json, "parent_id", 0))
.setName(json.getString("name"))
.setPosition(json.getInt("position"))
.setUserLimit(json.getInt("user_limit"))
.setBitrate(json.getInt("bitrate"));
}
public PrivateChannel createPrivateChannel(JSONObject privatechat)
{
JSONObject recipient = privatechat.has("recipients") ?
privatechat.getJSONArray("recipients").getJSONObject(0) :
privatechat.getJSONObject("recipient");
final long userId = recipient.getLong("id");
UserImpl user = ((UserImpl) api.getUserMap().get(userId));
if (user == null)
{ //The API can give us private channels connected to Users that we can no longer communicate with.
// As such, make a fake user and fake private channel.
user = (UserImpl) createFakeUser(recipient, true);
}
final long channelId = privatechat.getLong("id");
PrivateChannelImpl priv = new PrivateChannelImpl(channelId, user)
.setLastMessageId(Helpers.optLong(privatechat, "last_message_id", 0));
user.setPrivateChannel(priv);
if (user.isFake())
{
priv.setFake(true);
api.getFakePrivateChannelMap().put(channelId, priv);
}
else
api.getPrivateChannelMap().put(channelId, priv);
return priv;
}
public void createOverridesPass(AbstractChannelImpl<?> channel, JSONArray overrides)
{
for (int i = 0; i < overrides.length(); i++)
{
try
{
createPermissionOverride(overrides.getJSONObject(i), channel);
}
catch (NoSuchElementException e)
{
//Caused by Discord not properly clearing PermissionOverrides when a Member leaves a Guild.
LOG.debug("{}. Ignoring PermissionOverride.", e.getMessage());
}
catch (IllegalArgumentException e)
{
//Missing handling for a type
LOG.warn("{}. Ignoring PermissionOverride.", e.getMessage());
}
}
}
public Role createRole(JSONObject roleJson, long guildId)
{
final long id = roleJson.getLong("id");
GuildImpl guild = ((GuildImpl) api.getGuildMap().get(guildId));
RoleImpl role = ((RoleImpl) guild.getRolesMap().get(id));
if (role == null)
{
role = new RoleImpl(id, guild);
guild.getRolesMap().put(id, role);
}
final int color = roleJson.getInt("color");
return role.setName(roleJson.getString("name"))
.setRawPosition(roleJson.getInt("position"))
.setRawPermissions(roleJson.getLong("permissions"))
.setManaged(roleJson.getBoolean("managed"))
.setHoisted(roleJson.getBoolean("hoist"))
.setColor(color == 0 ? Role.DEFAULT_COLOR_RAW : color)
.setMentionable(roleJson.has("mentionable") && roleJson.getBoolean("mentionable"));
}
public Message createMessage(JSONObject jsonObject) { return createMessage(jsonObject, false); }
public Message createMessage(JSONObject jsonObject, boolean exceptionOnMissingUser)
{
final long channelId = jsonObject.getLong("channel_id");
MessageChannel chan = api.getTextChannelById(channelId);
if (chan == null)
chan = api.getPrivateChannelById(channelId);
if (chan == null)
chan = api.getFakePrivateChannelMap().get(channelId);
if (chan == null && api.getAccountType() == AccountType.CLIENT)
chan = api.asClient().getGroupById(channelId);
if (chan == null)
throw new IllegalArgumentException(MISSING_CHANNEL);
return createMessage(jsonObject, chan, exceptionOnMissingUser);
}
public Message createMessage(JSONObject jsonObject, MessageChannel chan, boolean exceptionOnMissingUser)
{
final long id = jsonObject.getLong("id");
String content = jsonObject.optString("content");
JSONObject author = jsonObject.getJSONObject("author");
final long authorId = author.getLong("id");
final boolean fromWebhook = jsonObject.has("webhook_id");
final boolean pinned = Helpers.optBoolean(jsonObject, "pinned");
final boolean tts = Helpers.optBoolean(jsonObject, "tts");
final boolean mentionsEveryone = Helpers.optBoolean(jsonObject, "mention_everyone");
final OffsetDateTime editTime = jsonObject.isNull("edited_timestamp") ? null : OffsetDateTime.parse(jsonObject.getString("edited_timestamp"));
final String nonce = jsonObject.isNull("nonce") ? null : jsonObject.get("nonce").toString();
final List<Message.Attachment> attachments = map(jsonObject, "attachments", this::createMessageAttachment);
final List<MessageEmbed> embeds = map(jsonObject, "embeds", this::createMessageEmbed);
final List<MessageReaction> reactions = map(jsonObject, "reactions", (obj) -> createMessageReaction(chan, id, obj));
User user;
switch (chan.getType())
{
case PRIVATE:
if (authorId == api.getSelfUser().getIdLong())
user = api.getSelfUser();
else
user = ((PrivateChannel) chan).getUser();
break;
case GROUP:
user = api.getUserById(authorId);
if (user == null)
user = api.getFakeUserMap().get(authorId);
if (user == null && fromWebhook)
user = createFakeUser(author, false);
if (user == null)
{
if (exceptionOnMissingUser)
throw new IllegalArgumentException(MISSING_USER); // Specifically for MESSAGE_CREATE
else
user = createFakeUser(author, false); // Any other message creation
}
if (user.isFake() && !fromWebhook)
{
UserImpl impl = (UserImpl) user;
impl.setName(author.getString("username"))
.setDiscriminator(author.get("discriminator").toString())
.setAvatarId(author.optString("avatar", null))
.setBot(Helpers.optBoolean(author, "bot"));
}
break;
case TEXT:
Guild guild = ((TextChannel) chan).getGuild();
Member member = guild.getMemberById(authorId);
user = member != null ? member.getUser() : null;
if (user == null)
{
if (fromWebhook || !exceptionOnMissingUser)
user = createFakeUser(author, false);
else
throw new IllegalArgumentException(MISSING_USER); // Specifically for MESSAGE_CREATE
}
break;
default: throw new IllegalArgumentException("Invalid Channel for creating a Message [" + chan.getType() + ']');
}
TLongSet mentionedRoles = new TLongHashSet();
TLongSet mentionedUsers = new TLongHashSet(map(jsonObject, "mentions", (o) -> o.getLong("id")));
JSONArray roleMentionArr = jsonObject.optJSONArray("mention_roles");
if (roleMentionArr != null)
{
for (int i = 0; i < roleMentionArr.length(); i++)
mentionedRoles.add(roleMentionArr.getLong(i));
}
MessageType type = MessageType.fromId(jsonObject.getInt("type"));
switch (type)
{
case DEFAULT:
return new ReceivedMessage(id, chan, type, fromWebhook,
mentionsEveryone, mentionedUsers, mentionedRoles, tts, pinned,
content, nonce, user, editTime, reactions, attachments, embeds);
case UNKNOWN:
throw new IllegalArgumentException(UNKNOWN_MESSAGE_TYPE);
default:
return new SystemMessage(id, chan, type, fromWebhook,
mentionsEveryone, mentionedUsers, mentionedRoles, tts, pinned,
content, nonce, user, editTime, reactions, attachments, embeds);
}
}
public MessageReaction createMessageReaction(MessageChannel chan, long id, JSONObject obj)
{
JSONObject emoji = obj.getJSONObject("emoji");
final Long emojiID = emoji.isNull("id") ? null : emoji.getLong("id");
final String name = emoji.optString("name", null);
final boolean animated = emoji.optBoolean("animated");
final int count = Helpers.optInt(obj, "count", -1);
final boolean me = Helpers.optBoolean(obj, "me");
final MessageReaction.ReactionEmote reactionEmote;
if (emojiID != null)
{
Emote emote = api.getEmoteById(emojiID);
// creates fake emoji because no guild has this emoji id
if (emote == null)
emote = new EmoteImpl(emojiID, api).setAnimated(animated).setName(name);
reactionEmote = new MessageReaction.ReactionEmote(emote);
}
else
{
reactionEmote = new MessageReaction.ReactionEmote(name, null, api);
}
return new MessageReaction(chan, reactionEmote, id, me, count);
}
public Message.Attachment createMessageAttachment(JSONObject jsonObject)
{
final int width = Helpers.optInt(jsonObject, "width", -1);
final int height = Helpers.optInt(jsonObject, "height", -1);