-
-
Notifications
You must be signed in to change notification settings - Fork 722
/
EntityBuilder.java
1402 lines (1245 loc) · 58.3 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.audit.ActionType;
import net.dv8tion.jda.core.audit.AuditLogChange;
import net.dv8tion.jda.core.audit.AuditLogEntry;
import net.dv8tion.jda.core.entities.Guild.VerificationLevel;
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.EventCache;
import net.dv8tion.jda.core.utils.Checks;
import net.dv8tion.jda.core.utils.Helpers;
import net.dv8tion.jda.core.utils.JDALogger;
import net.dv8tion.jda.core.utils.cache.CacheFlag;
import net.dv8tion.jda.core.utils.cache.UpstreamReference;
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.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.*;
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");
richGameFields = Collections.unmodifiableSet(tmp);
}
protected final UpstreamReference<JDAImpl> api;
public EntityBuilder(JDA api)
{
this.api = new UpstreamReference<>((JDAImpl) api);
}
public JDAImpl getJDA()
{
return api.get();
}
public SelfUser createSelfUser(JSONObject self)
{
SelfUserImpl selfUser = ((SelfUserImpl) getJDA().getSelfUser());
if (selfUser == null)
{
final long id = self.getLong("id");
selfUser = new SelfUserImpl(id, getJDA());
getJDA().setSelfUser(selfUser);
}
if (!getJDA().getUserMap().containsKey(selfUser.getIdLong()))
getJDA().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.getJDA().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);
}
private void createGuildEmotePass(GuildImpl guildObj, JSONArray array)
{
if (!getJDA().isCacheFlagSet(CacheFlag.EMOTE))
return;
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;
}
final long emoteId = object.getLong("id");
emoteMap.put(emoteId, createEmote(guildObj, object, false));
}
}
public GuildImpl createGuild(long guildId, JSONObject guildJson, TLongObjectMap<JSONObject> members)
{
final GuildImpl guildObj = new GuildImpl(getJDA(), guildId);
final String name = guildJson.optString("name", "");
final String iconId = guildJson.optString("icon", null);
final String splashId = guildJson.optString("splash", null);
final String region = guildJson.optString("region", null);
final JSONArray roleArray = guildJson.getJSONArray("roles");
final JSONArray channelArray = guildJson.getJSONArray("channels");
final JSONArray emotesArray = guildJson.getJSONArray("emojis");
final JSONArray voiceStateArray = guildJson.getJSONArray("voice_states");
final JSONArray featuresArray = guildJson.optJSONArray("features");
final JSONArray presencesArray = guildJson.optJSONArray("presences");
final long ownerId = Helpers.optLong(guildJson, "owner_id", 0L);
final long afkChannelId = Helpers.optLong(guildJson, "afk_channel_id", 0L);
final long systemChannelId = Helpers.optLong(guildJson, "system_channel_id", 0L);
final int mfaLevel = Helpers.optInt(guildJson, "mfa_level", 0);
final int afkTimeout = Helpers.optInt(guildJson, "afk_timeout", 0);
final int verificationLevel = Helpers.optInt(guildJson, "verification_level", 0);
final int notificationLevel = Helpers.optInt(guildJson, "default_message_notifications", 0);
final int explicitContentLevel = Helpers.optInt(guildJson, "explicit_content_filter", 0);
guildObj.setAvailable(true)
.setName(name)
.setIconId(iconId)
.setSplashId(splashId)
.setRegion(region)
.setOwnerId(ownerId)
.setAfkTimeout(Guild.Timeout.fromKey(afkTimeout))
.setVerificationLevel(VerificationLevel.fromKey(verificationLevel))
.setDefaultNotificationLevel(Guild.NotificationLevel.fromKey(notificationLevel))
.setExplicitContentLevel(Guild.ExplicitContentLevel.fromKey(explicitContentLevel))
.setRequiredMFALevel(Guild.MFALevel.fromKey(mfaLevel));
if (featuresArray == null)
{
guildObj.setFeatures(Collections.emptySet());
}
else
{
guildObj.setFeatures(
StreamSupport.stream(featuresArray.spliterator(), false)
.map(String::valueOf)
.collect(Collectors.toSet()));
}
for (int i = 0; i < roleArray.length(); i++)
{
JSONObject obj = roleArray.getJSONObject(i);
Role role = createRole(guildObj, obj, guildId);
guildObj.getRolesMap().put(role.getIdLong(), role);
if (role.getIdLong() == guildObj.getIdLong())
guildObj.setPublicRole(role);
}
for (JSONObject memberJson : members.valueCollection())
createMember(guildObj, memberJson);
if (guildObj.getOwner() == null)
LOG.warn("Finished setup for guild with a null owner. GuildId: {} OwnerId: {}", guildId, guildJson.opt("owner_id"));
for (int i = 0; i < channelArray.length(); i++)
{
JSONObject channelJson = channelArray.getJSONObject(i);
createGuildChannel(guildObj, channelJson);
}
createGuildEmotePass(guildObj, emotesArray);
createGuildVoiceStatePass(guildObj, voiceStateArray);
guildObj.setAfkChannel(guildObj.getVoiceChannelById(afkChannelId))
.setSystemChannel(guildObj.getTextChannelById(systemChannelId));
for (int i = 0; i < presencesArray.length(); i++)
{
JSONObject presence = presencesArray.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);
}
getJDA().getGuildMap().put(guildId, guildObj);
return guildObj;
}
private void createGuildChannel(GuildImpl guildObj, JSONObject channelData)
{
final ChannelType channelType = ChannelType.fromId(channelData.getInt("type"));
switch (channelType)
{
case TEXT:
createTextChannel(guildObj, channelData, guildObj.getIdLong());
break;
case VOICE:
createVoiceChannel(guildObj, channelData, guildObj.getIdLong());
break;
case CATEGORY:
createCategory(guildObj, channelData, guildObj.getIdLong());
break;
default:
throw new IllegalArgumentException("Cannot create channel for type " + channelData.getInt("type"));
}
}
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;
}
GuildVoiceStateImpl voiceState = (GuildVoiceStateImpl) member.getVoiceState();
if (voiceState == null)
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
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) getJDA().getUserMap().get(id);
if (userObj == null)
{
userObj = (UserImpl) getJDA().getFakeUserMap().get(id);
if (userObj != null)
{
if (!fake && modifyCache)
{
getJDA().getFakeUserMap().remove(id);
userObj.setFake(false);
getJDA().getUserMap().put(userObj.getIdLong(), userObj);
if (userObj.hasPrivateChannel())
{
PrivateChannelImpl priv = (PrivateChannelImpl) userObj.getPrivateChannel();
priv.setFake(false);
getJDA().getFakePrivateChannelMap().remove(priv.getIdLong());
getJDA().getPrivateChannelMap().put(priv.getIdLong(), priv);
}
}
}
else
{
userObj = new UserImpl(id, getJDA()).setFake(fake);
if (modifyCache)
{
if (fake)
getJDA().getFakeUserMap().put(id, userObj);
else
getJDA().getUserMap().put(id, userObj);
}
}
}
userObj
.setName(user.getString("username"))
.setDiscriminator(user.get("discriminator").toString())
.setAvatarId(user.optString("avatar", null))
.setBot(Helpers.optBoolean(user, "bot"));
if (!fake && modifyCache)
getJDA().getEventCache().playbackCache(EventCache.Type.USER, id);
return userObj;
}
public Member createMember(GuildImpl guild, JSONObject memberJson)
{
boolean playbackCache = false;
User user = createUser(memberJson.getJSONObject("user"));
MemberImpl member = (MemberImpl) guild.getMember(user);
if (member == null)
{
member = new MemberImpl(guild, user);
playbackCache = guild.getMembersMap().put(user.getIdLong(), member) == null;
if (guild.getOwnerIdLong() == user.getIdLong())
{
LOG.trace("Found owner of guild with id {}", guild.getId());
guild.setOwner(member);
}
}
GuildVoiceStateImpl state = (GuildVoiceStateImpl) member.getVoiceState();
if (state != null)
{
state.setGuildMuted(memberJson.getBoolean("mute"))
.setGuildDeafened(memberJson.getBoolean("deaf"));
}
TemporalAccessor joinedAt = DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(memberJson.getString("joined_at"));
member.setJoinDate(Instant.from(joinedAt).toEpochMilli())
.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);
}
}
if (playbackCache)
{
long hashId = guild.getIdLong() ^ user.getIdLong();
getJDA().getEventCache().playbackCache(EventCache.Type.MEMBER, hashId);
}
return member;
}
//Effectively the same as createFriendPresence
public void createPresence(Object memberOrFriend, JSONObject presenceJson)
{
if (memberOrFriend == null)
throw new NullPointerException("Provided memberOrFriend was null!");
boolean cacheGame = getJDA().isCacheFlagSet(CacheFlag.GAME);
JSONObject gameJson = !cacheGame || presenceJson.isNull("game") ? null : presenceJson.getJSONObject("game");
OnlineStatus onlineStatus = OnlineStatus.fromKey(presenceJson.getString("status"));
Game game = null;
boolean parsedGame = false;
if (cacheGame && 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 (cacheGame && parsedGame)
member.setGame(game);
}
else if (memberOrFriend instanceof Friend)
{
FriendImpl friend = (FriendImpl) memberOrFriend;
friend.setOnlineStatus(onlineStatus);
if (cacheGame && 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 EmoteImpl createEmote(GuildImpl guildObj, JSONObject json, boolean fake)
{
JSONArray emoteRoles = json.isNull("roles") ? new JSONArray() : json.getJSONArray("roles");
final long emoteId = json.getLong("id");
final User user = json.isNull("user") ? null : createFakeUser(json.getJSONObject("user"), false);
EmoteImpl emoteObj = (EmoteImpl) guildObj.getEmoteById(emoteId);
if (emoteObj == null)
emoteObj = new EmoteImpl(emoteId, guildObj, fake);
Set<Role> roleSet = emoteObj.getRoleSet();
roleSet.clear();
for (int j = 0; j < emoteRoles.length(); j++)
{
Role role = guildObj.getRoleById(emoteRoles.getString(j));
if (role != null)
roleSet.add(role);
}
if (user != null)
emoteObj.setUser(user);
return emoteObj
.setName(json.optString("name"))
.setAnimated(json.optBoolean("animated"))
.setManaged(Helpers.optBoolean(json, "managed"));
}
public Category createCategory(JSONObject json, long guildId)
{
return createCategory(null, json, guildId);
}
public Category createCategory(GuildImpl guild, JSONObject json, long guildId)
{
boolean playbackCache = false;
final long id = json.getLong("id");
CategoryImpl channel = (CategoryImpl) getJDA().getCategoryMap().get(id);
if (channel == null)
{
if (guild == null)
guild = (GuildImpl) getJDA().getGuildMap().get(guildId);
channel = new CategoryImpl(id, guild);
guild.getCategoriesMap().put(id, channel);
playbackCache = getJDA().getCategoryMap().put(id, channel) == null;
}
if (!json.isNull("permission_overwrites"))
{
JSONArray overrides = json.getJSONArray("permission_overwrites");
createOverridesPass(channel, overrides);
}
channel
.setName(json.getString("name"))
.setPosition(json.getInt("position"));
if (playbackCache)
getJDA().getEventCache().playbackCache(EventCache.Type.CHANNEL, id);
return channel;
}
public TextChannel createTextChannel(JSONObject json, long guildId)
{
return createTextChannel(null, json, guildId);
}
public TextChannel createTextChannel(GuildImpl guildObj, JSONObject json, long guildId)
{
boolean playbackCache = false;
final long id = json.getLong("id");
TextChannelImpl channel = (TextChannelImpl) getJDA().getTextChannelMap().get(id);
if (channel == null)
{
if (guildObj == null)
guildObj = (GuildImpl) getJDA().getGuildMap().get(guildId);
channel = new TextChannelImpl(id, guildObj);
guildObj.getTextChannelsMap().put(id, channel);
playbackCache = getJDA().getTextChannelMap().put(id, channel) == null;
}
if (!json.isNull("permission_overwrites"))
{
JSONArray overrides = json.getJSONArray("permission_overwrites");
createOverridesPass(channel, overrides);
}
channel
.setParent(Helpers.optLong(json, "parent_id", 0))
.setLastMessageId(Helpers.optLong(json, "last_message_id", 0))
.setName(json.getString("name"))
.setTopic(json.optString("topic", null))
.setPosition(json.getInt("position"))
.setNSFW(Helpers.optBoolean(json, "nsfw"))
.setSlowmode(Helpers.optInt(json, "rate_limit_per_user", 0));
if (playbackCache)
getJDA().getEventCache().playbackCache(EventCache.Type.CHANNEL, id);
return channel;
}
public VoiceChannel createVoiceChannel(JSONObject json, long guildId)
{
return createVoiceChannel(null, json, guildId);
}
public VoiceChannel createVoiceChannel(GuildImpl guild, JSONObject json, long guildId)
{
boolean playbackCache = false;
final long id = json.getLong("id");
VoiceChannelImpl channel = ((VoiceChannelImpl) getJDA().getVoiceChannelMap().get(id));
if (channel == null)
{
if (guild == null)
guild = (GuildImpl) getJDA().getGuildMap().get(guildId);
channel = new VoiceChannelImpl(id, guild);
guild.getVoiceChannelsMap().put(id, channel);
playbackCache = getJDA().getVoiceChannelMap().put(id, channel) == null;
}
if (!json.isNull("permission_overwrites"))
{
JSONArray overrides = json.getJSONArray("permission_overwrites");
createOverridesPass(channel, overrides);
}
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"));
if (playbackCache)
getJDA().getEventCache().playbackCache(EventCache.Type.CHANNEL, id);
return channel;
}
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) getJDA().getUserMap().get(userId);
if (user == null)
{ //The getJDA() 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 = 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);
getJDA().getFakePrivateChannelMap().put(channelId, priv);
}
else
{
getJDA().getPrivateChannelMap().put(channelId, priv);
getJDA().getEventCache().playbackCache(EventCache.Type.CHANNEL, channelId);
}
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(GuildImpl guild, JSONObject roleJson, long guildId)
{
boolean playbackCache = false;
final long id = roleJson.getLong("id");
if (guild == null)
guild = (GuildImpl) getJDA().getGuildMap().get(guildId);
RoleImpl role = (RoleImpl) guild.getRolesMap().get(id);
if (role == null)
{
role = new RoleImpl(id, guild);
playbackCache = guild.getRolesMap().put(id, role) == null;
}
final int color = roleJson.getInt("color");
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"));
if (playbackCache)
getJDA().getEventCache().playbackCache(EventCache.Type.ROLE, id);
return role;
}
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 = getJDA().getTextChannelById(channelId);
if (chan == null)
chan = getJDA().getPrivateChannelById(channelId);
if (chan == null)
chan = getJDA().getFakePrivateChannelMap().get(channelId);
if (chan == null && getJDA().getAccountType() == AccountType.CLIENT)
chan = getJDA().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));
MessageActivity activity = null;
if (!jsonObject.isNull("activity"))
{
JSONObject activityData = jsonObject.getJSONObject("activity");
final MessageActivity.ActivityType activityType = MessageActivity.ActivityType.fromId(activityData.getInt("type"));
final String partyId = activityData.optString("party_id", null);
MessageActivity.Application application = null;
if (!jsonObject.isNull("application"))
{
JSONObject applicationData = jsonObject.getJSONObject("application");
final String name = applicationData.getString("name");
final String description = applicationData.getString("description");
final String iconId = applicationData.getString("icon");
final String coverId = applicationData.getString("cover_image");
final long applicationId = applicationData.getLong("id");
application = new MessageActivity.Application(name, description, iconId, coverId, applicationId);
}
if (activityType == MessageActivity.ActivityType.UNKNOWN)
{
LOG.debug("Received an unknown ActivityType, Activity: {}", activityData);
}
activity = new MessageActivity(activityType, partyId, application);
}
User user;
switch (chan.getType())
{
case PRIVATE:
if (authorId == getJDA().getSelfUser().getIdLong())
user = getJDA().getSelfUser();
else
user = ((PrivateChannel) chan).getUser();
break;
case GROUP:
user = getJDA().getUserById(authorId);
if (user == null)
user = getJDA().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, activity, 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, activity, 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 = getJDA().getEmoteById(emojiID);
// creates fake emoji because no guild has this emoji id
if (emote == null)
emote = new EmoteImpl(emojiID, getJDA()).setAnimated(animated).setName(name);
reactionEmote = new MessageReaction.ReactionEmote(emote);
}
else
{
reactionEmote = new MessageReaction.ReactionEmote(name, null, getJDA());
}
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);
final int size = jsonObject.getInt("size");
final String url = jsonObject.optString("url", null);
final String proxyUrl = jsonObject.optString("proxy_url", null);
final String filename = jsonObject.getString("filename");
final long id = jsonObject.getLong("id");
return new Message.Attachment(id, url, proxyUrl, filename, size, height, width, getJDA());
}
public MessageEmbed createMessageEmbed(JSONObject content)
{
if (content.isNull("type"))
throw new JSONException("Encountered embed object with missing/null type field for Json: " + content);
EmbedType type = EmbedType.fromKey(content.getString("type"));
final String url = content.optString("url", null);
final String title = content.optString("title", null);
final String description = content.optString("description", null);
final OffsetDateTime timestamp = content.isNull("timestamp") ? null : OffsetDateTime.parse(content.getString("timestamp"));
final int color = content.isNull("color") ? Role.DEFAULT_COLOR_RAW : content.getInt("color");
final Thumbnail thumbnail;
if (content.isNull("thumbnail"))
{
thumbnail = null;
}
else
{
JSONObject obj = content.getJSONObject("thumbnail");
thumbnail = new Thumbnail(obj.optString("url", null),
obj.optString("proxy_url", null),
Helpers.optInt(obj, "width", -1),
Helpers.optInt(obj, "height", -1));
}
final Provider provider;
if (content.isNull("provider"))
{
provider = null;
}
else
{
JSONObject obj = content.getJSONObject("provider");
provider = new Provider(obj.optString("name", null),
obj.optString("url", null));
}
final AuthorInfo author;
if (content.isNull("author"))
{
author = null;
}
else
{
JSONObject obj = content.getJSONObject("author");
author = new AuthorInfo(obj.optString("name", null),
obj.optString("url", null),
obj.optString("icon_url", null),
obj.optString("proxy_icon_url", null));
}
final VideoInfo video;
if (content.isNull("video"))
{
video = null;
}
else
{
JSONObject obj = content.getJSONObject("video");
video = new VideoInfo(obj.optString("url"),
Helpers.optInt(obj, "width", -1),
Helpers.optInt(obj, "height", -1));
}
final Footer footer;
if (content.isNull("footer"))
{
footer = null;
}
else
{
JSONObject obj = content.getJSONObject("footer");
footer = new Footer(obj.optString("text", null),
obj.optString("icon_url", null),
obj.optString("proxy_icon_url", null));
}
final ImageInfo image;
if (content.isNull("image"))
{
image = null;
}
else
{
JSONObject obj = content.getJSONObject("image");
image = new ImageInfo(obj.optString("url", null),
obj.optString("proxy_url", null),
Helpers.optInt(obj, "width", -1),
Helpers.optInt(obj, "height", -1));
}