/
EntityBuilder.java
1764 lines (1580 loc) · 72.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 Austin Keener, Michael Ritter, Florian Spieß, and the JDA contributors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.dv8tion.jda.internal.entities;
import gnu.trove.map.TLongObjectMap;
import gnu.trove.map.hash.TLongObjectHashMap;
import gnu.trove.set.TLongSet;
import gnu.trove.set.hash.TLongHashSet;
import net.dv8tion.jda.api.JDA;
import net.dv8tion.jda.api.OnlineStatus;
import net.dv8tion.jda.api.audit.ActionType;
import net.dv8tion.jda.api.audit.AuditLogChange;
import net.dv8tion.jda.api.audit.AuditLogEntry;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.entities.Guild.VerificationLevel;
import net.dv8tion.jda.api.entities.MessageEmbed.*;
import net.dv8tion.jda.api.events.guild.member.GuildMemberRoleAddEvent;
import net.dv8tion.jda.api.events.guild.member.GuildMemberRoleRemoveEvent;
import net.dv8tion.jda.api.events.guild.member.update.GuildMemberUpdateBoostTimeEvent;
import net.dv8tion.jda.api.events.guild.member.update.GuildMemberUpdateNicknameEvent;
import net.dv8tion.jda.api.events.guild.member.update.GuildMemberUpdatePendingEvent;
import net.dv8tion.jda.api.events.user.update.UserUpdateAvatarEvent;
import net.dv8tion.jda.api.events.user.update.UserUpdateDiscriminatorEvent;
import net.dv8tion.jda.api.events.user.update.UserUpdateFlagsEvent;
import net.dv8tion.jda.api.events.user.update.UserUpdateNameEvent;
import net.dv8tion.jda.api.interactions.components.ActionRow;
import net.dv8tion.jda.api.utils.cache.CacheFlag;
import net.dv8tion.jda.api.utils.cache.CacheView;
import net.dv8tion.jda.api.utils.data.DataArray;
import net.dv8tion.jda.api.utils.data.DataObject;
import net.dv8tion.jda.internal.JDAImpl;
import net.dv8tion.jda.internal.handle.EventCache;
import net.dv8tion.jda.internal.utils.JDALogger;
import net.dv8tion.jda.internal.utils.UnlockHook;
import net.dv8tion.jda.internal.utils.cache.MemberCacheViewImpl;
import net.dv8tion.jda.internal.utils.cache.SnowflakeCacheViewImpl;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.map.CaseInsensitiveMap;
import org.slf4j.Logger;
import javax.annotation.Nullable;
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.ToLongFunction;
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 JDAImpl api;
public EntityBuilder(JDA api)
{
this.api = (JDAImpl) api;
}
public JDAImpl getJDA()
{
return api;
}
public SelfUser createSelfUser(DataObject self)
{
SelfUserImpl selfUser = (SelfUserImpl) (getJDA().hasSelfUser() ? getJDA().getSelfUser() : null);
if (selfUser == null)
{
final long id = self.getLong("id");
selfUser = new SelfUserImpl(id, getJDA());
getJDA().setSelfUser(selfUser);
}
SnowflakeCacheViewImpl<User> userView = getJDA().getUsersView();
try (UnlockHook hook = userView.writeLock())
{
if (userView.getElementById(selfUser.getIdLong()) == null)
userView.getMap().put(selfUser.getIdLong(), selfUser);
}
if (!self.isNull("application_id"))
selfUser.setApplicationId(self.getUnsignedLong("application_id"));
selfUser.setVerified(self.getBoolean("verified"))
.setMfaEnabled(self.getBoolean("mfa_enabled"))
.setName(self.getString("username"))
.setDiscriminator(self.getString("discriminator"))
.setAvatarId(self.getString("avatar", null))
.setBot(self.getBoolean("bot"))
.setSystem(false);
return selfUser;
}
public static Activity createActivity(String name, String url, Activity.ActivityType type)
{
return new ActivityImpl(name, url, type);
}
private void createGuildEmotePass(GuildImpl guildObj, DataArray array)
{
if (!getJDA().isCacheFlagSet(CacheFlag.EMOTE))
return;
SnowflakeCacheViewImpl<Emote> emoteView = guildObj.getEmotesView();
try (UnlockHook hook = emoteView.writeLock())
{
TLongObjectMap<Emote> emoteMap = emoteView.getMap();
for (int i = 0; i < array.length(); i++)
{
DataObject object = array.getObject(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));
}
}
}
public TLongObjectMap<DataObject> convertToUserMap(ToLongFunction<DataObject> getId, DataArray array)
{
TLongObjectMap<DataObject> map = new TLongObjectHashMap<>();
for (int i = 0; i < array.length(); i++)
{
DataObject obj = array.getObject(i);
long userId = getId.applyAsLong(obj);
map.put(userId, obj);
}
return map;
}
public GuildImpl createGuild(long guildId, DataObject guildJson, TLongObjectMap<DataObject> members, int memberCount)
{
final GuildImpl guildObj = new GuildImpl(getJDA(), guildId);
final String name = guildJson.getString("name", "");
final String iconId = guildJson.getString("icon", null);
final String splashId = guildJson.getString("splash", null);
final String region = guildJson.getString("region", null);
final String description = guildJson.getString("description", null);
final String vanityCode = guildJson.getString("vanity_url_code", null);
final String bannerId = guildJson.getString("banner", null);
final String locale = guildJson.getString("preferred_locale", "en");
final DataArray roleArray = guildJson.getArray("roles");
final DataArray channelArray = guildJson.getArray("channels");
final DataArray emotesArray = guildJson.getArray("emojis");
final DataArray voiceStateArray = guildJson.getArray("voice_states");
final Optional<DataArray> featuresArray = guildJson.optArray("features");
final Optional<DataArray> presencesArray = guildJson.optArray("presences");
final long ownerId = guildJson.getUnsignedLong("owner_id", 0L);
final long afkChannelId = guildJson.getUnsignedLong("afk_channel_id", 0L);
final long systemChannelId = guildJson.getUnsignedLong("system_channel_id", 0L);
final long rulesChannelId = guildJson.getUnsignedLong("rules_channel_id", 0L);
final long communityUpdatesChannelId = guildJson.getUnsignedLong("public_updates_channel_id", 0L);
final int boostCount = guildJson.getInt("premium_subscription_count", 0);
final int boostTier = guildJson.getInt("premium_tier", 0);
final int maxMembers = guildJson.getInt("max_members", 0);
final int maxPresences = guildJson.getInt("max_presences", 5000);
final int mfaLevel = guildJson.getInt("mfa_level", 0);
final int afkTimeout = guildJson.getInt("afk_timeout", 0);
final int verificationLevel = guildJson.getInt("verification_level", 0);
final int notificationLevel = guildJson.getInt("default_message_notifications", 0);
final int explicitContentLevel = guildJson.getInt("explicit_content_filter", 0);
guildObj.setAvailable(true)
.setName(name)
.setIconId(iconId)
.setSplashId(splashId)
.setRegion(region)
.setDescription(description)
.setBannerId(bannerId)
.setVanityCode(vanityCode)
.setMaxMembers(maxMembers)
.setMaxPresences(maxPresences)
.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))
.setLocale(locale)
.setBoostCount(boostCount)
.setBoostTier(boostTier)
.setMemberCount(memberCount);
SnowflakeCacheViewImpl<Guild> guildView = getJDA().getGuildsView();
try (UnlockHook hook = guildView.writeLock())
{
guildView.getMap().put(guildId, guildObj);
}
guildObj.setFeatures(featuresArray.map(it ->
StreamSupport.stream(it.spliterator(), false)
.map(String::valueOf)
.collect(Collectors.toSet())
).orElse(Collections.emptySet()));
SnowflakeCacheViewImpl<Role> roleView = guildObj.getRolesView();
try (UnlockHook hook = roleView.writeLock())
{
TLongObjectMap<Role> map = roleView.getMap();
for (int i = 0; i < roleArray.length(); i++)
{
DataObject obj = roleArray.getObject(i);
Role role = createRole(guildObj, obj, guildId);
map.put(role.getIdLong(), role);
if (role.getIdLong() == guildObj.getIdLong())
guildObj.setPublicRole(role);
}
}
for (int i = 0; i < channelArray.length(); i++)
{
DataObject channelJson = channelArray.getObject(i);
createGuildChannel(guildObj, channelJson);
}
TLongObjectMap<DataObject> voiceStates = convertToUserMap((o) -> o.getUnsignedLong("user_id", 0L), voiceStateArray);
TLongObjectMap<DataObject> presences = presencesArray.map(o1 -> convertToUserMap(o2 -> o2.getObject("user").getUnsignedLong("id"), o1)).orElseGet(TLongObjectHashMap::new);
try (UnlockHook h1 = guildObj.getMembersView().writeLock();
UnlockHook h2 = getJDA().getUsersView().writeLock())
{
//Add members to cache when subscriptions are disabled when they appear here
// this is done because we can still keep track of members in voice channels
for (DataObject memberJson : members.valueCollection())
{
long userId = memberJson.getObject("user").getUnsignedLong("id");
DataObject voiceState = voiceStates.get(userId);
DataObject presence = presences.get(userId);
updateMemberCache(createMember(guildObj, memberJson, voiceState, presence));
}
}
if (guildObj.getOwner() == null)
LOG.debug("Finished setup for guild with a null owner. GuildId: {} OwnerId: {}", guildId, guildJson.opt("owner_id").orElse(null));
createGuildEmotePass(guildObj, emotesArray);
guildObj.setAfkChannel(guildObj.getVoiceChannelById(afkChannelId))
.setSystemChannel(guildObj.getTextChannelById(systemChannelId))
.setRulesChannel(guildObj.getTextChannelById(rulesChannelId))
.setCommunityUpdatesChannel(guildObj.getTextChannelById(communityUpdatesChannelId));
return guildObj;
}
private void createGuildChannel(GuildImpl guildObj, DataObject 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;
case STORE:
createStoreChannel(guildObj, channelData, guildObj.getIdLong());
break;
default:
LOG.debug("Cannot create channel for type " + channelData.getInt("type"));
}
}
public UserImpl createUser(DataObject user)
{
boolean newUser = false;
final long id = user.getLong("id");
UserImpl userObj;
SnowflakeCacheViewImpl<User> userView = getJDA().getUsersView();
try (UnlockHook hook = userView.readLock())
{
userObj = (UserImpl) userView.getElementById(id);
if (userObj == null)
{
userObj = new UserImpl(id, getJDA());
newUser = true;
}
}
if (newUser)
{
// Initial creation
userObj.setName(user.getString("username"))
.setDiscriminator(user.get("discriminator").toString())
.setAvatarId(user.getString("avatar", null))
.setBot(user.getBoolean("bot"))
.setSystem(user.getBoolean("system"))
.setFlags(user.getInt("public_flags", 0));
}
else
{
// Fire update events
updateUser(userObj, user);
}
return userObj;
}
public void updateUser(UserImpl userObj, DataObject user)
{
String oldName = userObj.getName();
String newName = user.getString("username");
String oldDiscriminator = userObj.getDiscriminator();
String newDiscriminator = user.get("discriminator").toString();
String oldAvatar = userObj.getAvatarId();
String newAvatar = user.getString("avatar", null);
int oldFlags = userObj.getFlagsRaw();
int newFlags = user.getInt("public_flags", 0);
JDAImpl jda = getJDA();
long responseNumber = jda.getResponseTotal();
if (!oldName.equals(newName))
{
userObj.setName(newName);
jda.handleEvent(
new UserUpdateNameEvent(
jda, responseNumber,
userObj, oldName));
}
if (!oldDiscriminator.equals(newDiscriminator))
{
userObj.setDiscriminator(newDiscriminator);
jda.handleEvent(
new UserUpdateDiscriminatorEvent(
jda, responseNumber,
userObj, oldDiscriminator));
}
if (!Objects.equals(oldAvatar, newAvatar))
{
userObj.setAvatarId(newAvatar);
jda.handleEvent(
new UserUpdateAvatarEvent(
jda, responseNumber,
userObj, oldAvatar));
}
if (oldFlags != newFlags)
{
userObj.setFlags(newFlags);
jda.handleEvent(
new UserUpdateFlagsEvent(
jda, responseNumber,
userObj, User.UserFlag.getFlags(oldFlags)));
}
}
public boolean updateMemberCache(MemberImpl member)
{
return updateMemberCache(member, false);
}
public boolean updateMemberCache(MemberImpl member, boolean forceRemove)
{
GuildImpl guild = member.getGuild();
UserImpl user = (UserImpl) member.getUser();
MemberCacheViewImpl membersView = guild.getMembersView();
if (forceRemove || !getJDA().cacheMember(member))
{
if (membersView.remove(member.getIdLong()) == null)
return false;
LOG.trace("Unloading member {}", member);
if (user.getMutualGuilds().isEmpty())
{
// we no longer share any guilds/channels with this user so remove it from cache
user.setFake(true);
getJDA().getUsersView().remove(user.getIdLong());
}
GuildVoiceStateImpl voiceState = (GuildVoiceStateImpl) member.getVoiceState();
if (voiceState != null)
{
VoiceChannelImpl connectedChannel = (VoiceChannelImpl) voiceState.getChannel();
if (connectedChannel != null)
connectedChannel.getConnectedMembersMap().remove(member.getIdLong());
voiceState.setConnectedChannel(null);
}
return false;
}
else if (guild.getMemberById(member.getIdLong()) != null)
{
// Member should be added to cache but already is cached -> do nothing
return true;
}
LOG.trace("Loading member {}", member);
if (getJDA().getUserById(user.getIdLong()) == null)
{
SnowflakeCacheViewImpl<User> usersView = getJDA().getUsersView();
try (UnlockHook hook1 = usersView.writeLock())
{
usersView.getMap().put(user.getIdLong(), user);
}
}
try (UnlockHook hook = membersView.writeLock())
{
membersView.getMap().put(member.getIdLong(), member);
if (member.isOwner())
guild.setOwner(member);
}
long hashId = guild.getIdLong() ^ user.getIdLong();
getJDA().getEventCache().playbackCache(EventCache.Type.USER, member.getIdLong());
getJDA().getEventCache().playbackCache(EventCache.Type.MEMBER, hashId);
return true;
}
public MemberImpl createMember(GuildImpl guild, DataObject memberJson)
{
return createMember(guild, memberJson, null, null);
}
public MemberImpl createMember(GuildImpl guild, DataObject memberJson, DataObject voiceStateJson, DataObject presence)
{
boolean playbackCache = false;
User user = createUser(memberJson.getObject("user"));
DataArray roleArray = memberJson.getArray("roles");
MemberImpl member = (MemberImpl) guild.getMember(user);
if (member == null)
{
// Create a brand new member
member = new MemberImpl(guild, user);
member.setNickname(memberJson.getString("nick", null));
long epoch = 0;
if (!memberJson.isNull("premium_since"))
{
TemporalAccessor date = DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(memberJson.getString("premium_since"));
epoch = Instant.from(date).toEpochMilli();
}
member.setBoostDate(epoch);
if (!memberJson.isNull("pending"))
member.setPending(memberJson.getBoolean("pending"));
Set<Role> roles = member.getRoleSet();
for (int i = 0; i < roleArray.length(); i++)
{
long roleId = roleArray.getUnsignedLong(i);
Role role = guild.getRoleById(roleId);
if (role != null)
roles.add(role);
}
}
else
{
// Update cached member and fire events
List<Role> roles = new ArrayList<>(roleArray.length());
for (int i = 0; i < roleArray.length(); i++)
{
long roleId = roleArray.getUnsignedLong(i);
Role role = guild.getRoleById(roleId);
if (role != null)
roles.add(role);
}
updateMember(guild, member, memberJson, roles);
}
// Load joined_at if necessary
if (!memberJson.isNull("joined_at") && !member.hasTimeJoined())
{
String joinedAtRaw = memberJson.getString("joined_at");
TemporalAccessor joinedAt = DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(joinedAtRaw);
long joinEpoch = Instant.from(joinedAt).toEpochMilli();
member.setJoinDate(joinEpoch);
}
// Load voice state and presence if necessary
if (voiceStateJson != null && member.getVoiceState() != null)
createVoiceState(guild, voiceStateJson, user, member);
if (presence != null)
createPresence(member, presence);
return member;
}
private void createVoiceState(GuildImpl guild, DataObject voiceStateJson, User user, MemberImpl member)
{
GuildVoiceStateImpl voiceState = (GuildVoiceStateImpl) member.getVoiceState();
final long channelId = voiceStateJson.getLong("channel_id");
VoiceChannelImpl voiceChannel = (VoiceChannelImpl) guild.getVoiceChannelsView().get(channelId);
if (voiceChannel != null)
voiceChannel.getConnectedMembersMap().put(member.getIdLong(), member);
else
LOG.error("Received a GuildVoiceState with a channel ID for a non-existent channel! ChannelId: {} GuildId: {} UserId: {}",
channelId, guild.getId(), user.getId());
// VoiceState is considered volatile so we don't expect anything to actually exist
voiceState.setSelfMuted(voiceStateJson.getBoolean("self_mute"))
.setSelfDeafened(voiceStateJson.getBoolean("self_deaf"))
.setGuildMuted(voiceStateJson.getBoolean("mute"))
.setGuildDeafened(voiceStateJson.getBoolean("deaf"))
.setSuppressed(voiceStateJson.getBoolean("suppress"))
.setSessionId(voiceStateJson.getString("session_id"))
.setStream(voiceStateJson.getBoolean("self_stream"))
.setConnectedChannel(voiceChannel);
}
public void updateMember(GuildImpl guild, MemberImpl member, DataObject content, List<Role> newRoles)
{
//If newRoles is null that means that we didn't find a role that was in the array and was cached this event
long responseNumber = getJDA().getResponseTotal();
if (newRoles != null)
{
updateMemberRoles(member, newRoles, responseNumber);
}
if (content.hasKey("nick"))
{
String oldNick = member.getNickname();
String newNick = content.getString("nick", null);
if (!Objects.equals(oldNick, newNick))
{
member.setNickname(newNick);
getJDA().handleEvent(
new GuildMemberUpdateNicknameEvent(
getJDA(), responseNumber,
member, oldNick));
}
}
if (content.hasKey("premium_since"))
{
long epoch = 0;
if (!content.isNull("premium_since"))
{
TemporalAccessor date = DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(content.getString("premium_since"));
epoch = Instant.from(date).toEpochMilli();
}
if (epoch != member.getBoostDateRaw())
{
OffsetDateTime oldTime = member.getTimeBoosted();
member.setBoostDate(epoch);
getJDA().handleEvent(
new GuildMemberUpdateBoostTimeEvent(
getJDA(), responseNumber,
member, oldTime));
}
}
if (!content.isNull("joined_at") && !member.hasTimeJoined())
{
String joinedAtRaw = content.getString("joined_at");
TemporalAccessor joinedAt = DateTimeFormatter.ISO_OFFSET_DATE_TIME.parse(joinedAtRaw);
long joinEpoch = Instant.from(joinedAt).toEpochMilli();
member.setJoinDate(joinEpoch);
}
if (!content.isNull("pending"))
{
boolean pending = content.getBoolean("pending");
boolean oldPending = member.isPending();
if (pending != oldPending)
{
member.setPending(pending);
getJDA().handleEvent(
new GuildMemberUpdatePendingEvent(
getJDA(), responseNumber,
member, oldPending));
}
}
updateUser((UserImpl) member.getUser(), content.getObject("user"));
}
private void updateMemberRoles(MemberImpl member, List<Role> newRoles, long responseNumber)
{
Set<Role> currentRoles = member.getRoleSet();
//Find the roles removed.
List<Role> removedRoles = new LinkedList<>();
each:
for (Role role : currentRoles)
{
for (Iterator<Role> it = newRoles.iterator(); it.hasNext(); )
{
Role r = it.next();
if (role.equals(r))
{
it.remove();
continue each;
}
}
removedRoles.add(role);
}
if (removedRoles.size() > 0)
currentRoles.removeAll(removedRoles);
if (newRoles.size() > 0)
currentRoles.addAll(newRoles);
if (removedRoles.size() > 0)
{
getJDA().handleEvent(
new GuildMemberRoleRemoveEvent(
getJDA(), responseNumber,
member, removedRoles));
}
if (newRoles.size() > 0)
{
getJDA().handleEvent(
new GuildMemberRoleAddEvent(
getJDA(), responseNumber,
member, newRoles));
}
}
public void createPresence(MemberImpl member, DataObject presenceJson)
{
if (member == null)
throw new NullPointerException("Provided member was null!");
OnlineStatus onlineStatus = OnlineStatus.fromKey(presenceJson.getString("status"));
if (onlineStatus == OnlineStatus.OFFLINE)
return; // don't cache offline member presences!
MemberPresenceImpl presence = member.getPresence();
if (presence == null)
{
CacheView.SimpleCacheView<MemberPresenceImpl> view = member.getGuild().getPresenceView();
if (view == null)
return;
presence = new MemberPresenceImpl();
try (UnlockHook lock = view.writeLock())
{
view.getMap().put(member.getIdLong(), presence);
}
}
boolean cacheGame = getJDA().isCacheFlagSet(CacheFlag.ACTIVITY);
boolean cacheStatus = getJDA().isCacheFlagSet(CacheFlag.CLIENT_STATUS);
DataArray activityArray = !cacheGame || presenceJson.isNull("activities") ? null : presenceJson.getArray("activities");
DataObject clientStatusJson = !cacheStatus || presenceJson.isNull("client_status") ? null : presenceJson.getObject("client_status");
List<Activity> activities = new ArrayList<>();
boolean parsedActivity = false;
if (cacheGame && activityArray != null)
{
for (int i = 0; i < activityArray.length(); i++)
{
try
{
activities.add(createActivity(activityArray.getObject(i)));
parsedActivity = true;
}
catch (Exception ex)
{
String userId = member.getId();
if (LOG.isDebugEnabled())
LOG.warn("Encountered exception trying to parse a presence! UserId: {} JSON: {}", userId, activityArray, ex);
else
LOG.warn("Encountered exception trying to parse a presence! UserId: {} Message: {} Enable debug for details", userId, ex.getMessage());
}
}
}
if (cacheGame && parsedActivity)
presence.setActivities(activities);
presence.setOnlineStatus(onlineStatus);
if (clientStatusJson != null)
{
for (String key : clientStatusJson.keys())
{
ClientType type = ClientType.fromKey(key);
OnlineStatus status = OnlineStatus.fromKey(clientStatusJson.getString(key));
presence.setOnlineStatus(type, status);
}
}
}
public static Activity createActivity(DataObject gameJson)
{
String name = String.valueOf(gameJson.get("name"));
String url = gameJson.isNull("url") ? null : String.valueOf(gameJson.get("url"));
Activity.ActivityType type;
try
{
type = gameJson.isNull("type")
? Activity.ActivityType.DEFAULT
: Activity.ActivityType.fromKey(Integer.parseInt(gameJson.get("type").toString()));
}
catch (NumberFormatException e)
{
type = Activity.ActivityType.DEFAULT;
}
RichPresence.Timestamps timestamps = null;
if (!gameJson.isNull("timestamps"))
{
DataObject obj = gameJson.getObject("timestamps");
long start, end;
start = obj.getLong("start", 0L);
end = obj.getLong("end", 0L);
timestamps = new RichPresence.Timestamps(start, end);
}
Activity.Emoji emoji = null;
if (!gameJson.isNull("emoji"))
{
DataObject emojiJson = gameJson.getObject("emoji");
String emojiName = emojiJson.getString("name");
long emojiId = emojiJson.getUnsignedLong("id", 0);
boolean emojiAnimated = emojiJson.getBoolean("animated");
emoji = new Activity.Emoji(emojiName, emojiId, emojiAnimated);
}
if (type == Activity.ActivityType.CUSTOM_STATUS)
{
if (gameJson.hasKey("state") && name.equalsIgnoreCase("Custom Status"))
{
name = gameJson.getString("state", "");
gameJson = gameJson.remove("state");
}
}
if (!CollectionUtils.containsAny(gameJson.keys(), richGameFields))
return new ActivityImpl(name, url, type, timestamps, emoji);
// data for spotify
long id = gameJson.getLong("application_id", 0L);
String sessionId = gameJson.getString("session_id", null);
String syncId = gameJson.getString("sync_id", null);
int flags = gameJson.getInt("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"))
{
DataObject obj = gameJson.getObject("party");
String partyId = obj.isNull("id") ? null : obj.getString("id");
DataArray sizeArr = obj.isNull("size") ? null : obj.getArray("size");
long size = 0, max = 0;
if (sizeArr != null && sizeArr.length() > 0)
{
size = sizeArr.getLong(0);
max = sizeArr.length() < 2 ? 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"))
{
DataObject assets = gameJson.getObject("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 RichPresenceImpl(type, name, url,
id, emoji, party, details, state, timestamps, syncId, sessionId, flags,
largeImageKey, largeImageText, smallImageKey, smallImageText);
}
public EmoteImpl createEmote(GuildImpl guildObj, DataObject json)
{
DataArray emoteRoles = json.optArray("roles").orElseGet(DataArray::empty);
final long emoteId = json.getLong("id");
final User user = json.isNull("user") ? null : createUser(json.getObject("user"));
EmoteImpl emoteObj = (EmoteImpl) guildObj.getEmoteById(emoteId);
if (emoteObj == null)
emoteObj = new EmoteImpl(emoteId, guildObj);
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.getString("name", ""))
.setAnimated(json.getBoolean("animated"))
.setManaged(json.getBoolean("managed"))
.setAvailable(json.getBoolean("available", true));
}
public Category createCategory(DataObject json, long guildId)
{
return createCategory(null, json, guildId);
}
public Category createCategory(GuildImpl guild, DataObject json, long guildId)
{
boolean playbackCache = false;
final long id = json.getLong("id");
CategoryImpl channel = (CategoryImpl) getJDA().getCategoriesView().get(id);
if (channel == null)
{
if (guild == null)
guild = (GuildImpl) getJDA().getGuildsView().get(guildId);
SnowflakeCacheViewImpl<Category>
guildCategoryView = guild.getCategoriesView(),
categoryView = getJDA().getCategoriesView();
try (
UnlockHook glock = guildCategoryView.writeLock();
UnlockHook jlock = categoryView.writeLock())
{
channel = new CategoryImpl(id, guild);
guildCategoryView.getMap().put(id, channel);
playbackCache = categoryView.getMap().put(id, channel) == null;
}
}
channel
.setName(json.getString("name"))
.setPosition(json.getInt("position"));
createOverridesPass(channel, json.getArray("permission_overwrites"));
if (playbackCache)
getJDA().getEventCache().playbackCache(EventCache.Type.CHANNEL, id);
return channel;
}
public StoreChannel createStoreChannel(DataObject json, long guildId)
{
return createStoreChannel(null, json, guildId);
}
public StoreChannel createStoreChannel(GuildImpl guild, DataObject json, long guildId)
{
boolean playbackCache = false;
final long id = json.getLong("id");
StoreChannelImpl channel = (StoreChannelImpl) getJDA().getStoreChannelsView().get(id);
if (channel == null)
{
if (guild == null)
guild = (GuildImpl) getJDA().getGuildById(guildId);
SnowflakeCacheViewImpl<StoreChannel>
guildStoreView = guild.getStoreChannelView(),
storeView = getJDA().getStoreChannelsView();
try (
UnlockHook glock = guildStoreView.writeLock();
UnlockHook jlock = storeView.writeLock())
{
channel = new StoreChannelImpl(id, guild);
guildStoreView.getMap().put(id, channel);
playbackCache = storeView.getMap().put(id, channel) == null;
}
}
channel
.setParent(json.getLong("parent_id", 0))
.setName(json.getString("name"))
.setPosition(json.getInt("position"));
createOverridesPass(channel, json.getArray("permission_overwrites"));
if (playbackCache)
getJDA().getEventCache().playbackCache(EventCache.Type.CHANNEL, id);
return channel;
}
public TextChannel createTextChannel(DataObject json, long guildId)
{
return createTextChannel(null, json, guildId);
}
public TextChannel createTextChannel(GuildImpl guildObj, DataObject json, long guildId)
{
boolean playbackCache = false;
final long id = json.getLong("id");
TextChannelImpl channel = (TextChannelImpl) getJDA().getTextChannelsView().get(id);
if (channel == null)
{
if (guildObj == null)
guildObj = (GuildImpl) getJDA().getGuildsView().get(guildId);
SnowflakeCacheViewImpl<TextChannel>
guildTextView = guildObj.getTextChannelsView(),
textView = getJDA().getTextChannelsView();
try (
UnlockHook glock = guildTextView.writeLock();
UnlockHook jlock = textView.writeLock())
{
channel = new TextChannelImpl(id, guildObj);
guildTextView.getMap().put(id, channel);
playbackCache = textView.getMap().put(id, channel) == null;
}
}
channel
.setParent(json.getLong("parent_id", 0))
.setLastMessageId(json.getLong("last_message_id", 0))
.setName(json.getString("name"))
.setTopic(json.getString("topic", null))
.setPosition(json.getInt("position"))
.setNSFW(json.getBoolean("nsfw"))
.setNews(json.getInt("type") == 5)
.setSlowmode(json.getInt("rate_limit_per_user", 0));
createOverridesPass(channel, json.getArray("permission_overwrites"));
if (playbackCache)
getJDA().getEventCache().playbackCache(EventCache.Type.CHANNEL, id);
return channel;
}
public VoiceChannel createVoiceChannel(DataObject json, long guildId)
{
return createVoiceChannel(null, json, guildId);
}
public VoiceChannel createVoiceChannel(GuildImpl guild, DataObject json, long guildId)
{
boolean playbackCache = false;
final long id = json.getLong("id");
VoiceChannelImpl channel = ((VoiceChannelImpl) getJDA().getVoiceChannelsView().get(id));
if (channel == null)
{
if (guild == null)
guild = (GuildImpl) getJDA().getGuildsView().get(guildId);
SnowflakeCacheViewImpl<VoiceChannel>
guildVoiceView = guild.getVoiceChannelsView(),
voiceView = getJDA().getVoiceChannelsView();
try (
UnlockHook vlock = guildVoiceView.writeLock();
UnlockHook jlock = voiceView.writeLock())
{
channel = new VoiceChannelImpl(id, guild);
guildVoiceView.getMap().put(id, channel);
playbackCache = voiceView.getMap().put(id, channel) == null;
}
}
channel
.setParent(json.getLong("parent_id", 0))
.setName(json.getString("name"))
.setPosition(json.getInt("position"))
.setUserLimit(json.getInt("user_limit"))
.setBitrate(json.getInt("bitrate"));
createOverridesPass(channel, json.getArray("permission_overwrites"));
if (playbackCache)
getJDA().getEventCache().playbackCache(EventCache.Type.CHANNEL, id);
return channel;
}
public PrivateChannel createPrivateChannel(DataObject json)
{
final long channelId = json.getUnsignedLong("id");
PrivateChannel channel = api.getPrivateChannelById(channelId);
api.usedPrivateChannel(channelId);
if (channel != null)
return channel;
DataObject recipient = json.hasKey("recipients") ?
json.getArray("recipients").getObject(0) :
json.getObject("recipient");
final long userId = recipient.getLong("id");