-
-
Notifications
You must be signed in to change notification settings - Fork 720
/
GuildImpl.java
2355 lines (2052 loc) · 80.8 KB
/
GuildImpl.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 net.dv8tion.jda.api.Permission;
import net.dv8tion.jda.api.Region;
import net.dv8tion.jda.api.audio.hooks.ConnectionStatus;
import net.dv8tion.jda.api.entities.*;
import net.dv8tion.jda.api.entities.automod.AutoModRule;
import net.dv8tion.jda.api.entities.automod.build.AutoModRuleData;
import net.dv8tion.jda.api.entities.channel.Channel;
import net.dv8tion.jda.api.entities.channel.ChannelType;
import net.dv8tion.jda.api.entities.channel.attribute.ICategorizableChannel;
import net.dv8tion.jda.api.entities.channel.attribute.IThreadContainer;
import net.dv8tion.jda.api.entities.channel.concrete.*;
import net.dv8tion.jda.api.entities.channel.middleman.AudioChannel;
import net.dv8tion.jda.api.entities.channel.middleman.GuildChannel;
import net.dv8tion.jda.api.entities.channel.unions.DefaultGuildChannelUnion;
import net.dv8tion.jda.api.entities.emoji.RichCustomEmoji;
import net.dv8tion.jda.api.entities.sticker.GuildSticker;
import net.dv8tion.jda.api.entities.sticker.StandardSticker;
import net.dv8tion.jda.api.entities.sticker.StickerSnowflake;
import net.dv8tion.jda.api.entities.templates.Template;
import net.dv8tion.jda.api.exceptions.HierarchyException;
import net.dv8tion.jda.api.exceptions.InsufficientPermissionException;
import net.dv8tion.jda.api.exceptions.ParsingException;
import net.dv8tion.jda.api.exceptions.PermissionException;
import net.dv8tion.jda.api.interactions.DiscordLocale;
import net.dv8tion.jda.api.interactions.commands.Command;
import net.dv8tion.jda.api.interactions.commands.PrivilegeConfig;
import net.dv8tion.jda.api.interactions.commands.build.CommandData;
import net.dv8tion.jda.api.interactions.commands.privileges.IntegrationPrivilege;
import net.dv8tion.jda.api.managers.*;
import net.dv8tion.jda.api.requests.GatewayIntent;
import net.dv8tion.jda.api.requests.RestAction;
import net.dv8tion.jda.api.requests.Route;
import net.dv8tion.jda.api.requests.restaction.*;
import net.dv8tion.jda.api.requests.restaction.order.CategoryOrderAction;
import net.dv8tion.jda.api.requests.restaction.order.ChannelOrderAction;
import net.dv8tion.jda.api.requests.restaction.order.RoleOrderAction;
import net.dv8tion.jda.api.requests.restaction.pagination.AuditLogPaginationAction;
import net.dv8tion.jda.api.utils.FileUpload;
import net.dv8tion.jda.api.utils.cache.*;
import net.dv8tion.jda.api.utils.concurrent.Task;
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.entities.automod.AutoModRuleImpl;
import net.dv8tion.jda.internal.handle.EventCache;
import net.dv8tion.jda.internal.interactions.CommandDataImpl;
import net.dv8tion.jda.internal.interactions.command.CommandImpl;
import net.dv8tion.jda.internal.managers.*;
import net.dv8tion.jda.internal.requests.*;
import net.dv8tion.jda.internal.requests.restaction.*;
import net.dv8tion.jda.internal.requests.restaction.order.CategoryOrderActionImpl;
import net.dv8tion.jda.internal.requests.restaction.order.ChannelOrderActionImpl;
import net.dv8tion.jda.internal.requests.restaction.order.RoleOrderActionImpl;
import net.dv8tion.jda.internal.requests.restaction.pagination.AuditLogPaginationActionImpl;
import net.dv8tion.jda.internal.requests.restaction.pagination.BanPaginationActionImpl;
import net.dv8tion.jda.internal.utils.Checks;
import net.dv8tion.jda.internal.utils.EntityString;
import net.dv8tion.jda.internal.utils.Helpers;
import net.dv8tion.jda.internal.utils.UnlockHook;
import net.dv8tion.jda.internal.utils.cache.*;
import net.dv8tion.jda.internal.utils.concurrent.task.GatewayTask;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import javax.annotation.CheckReturnValue;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.time.Duration;
import java.time.OffsetDateTime;
import java.time.temporal.TemporalAccessor;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class GuildImpl implements Guild
{
private final long id;
private final JDAImpl api;
private final SortedSnowflakeCacheViewImpl<ScheduledEvent> scheduledEventCache = new SortedSnowflakeCacheViewImpl<>(ScheduledEvent.class, ScheduledEvent::getName, Comparator.naturalOrder());
private final SortedChannelCacheViewImpl<GuildChannel> channelCache = new SortedChannelCacheViewImpl<>(GuildChannel.class);
private final SortedSnowflakeCacheViewImpl<Role> roleCache = new SortedSnowflakeCacheViewImpl<>(Role.class, Role::getName, Comparator.reverseOrder());
private final SnowflakeCacheViewImpl<RichCustomEmoji> emojicache = new SnowflakeCacheViewImpl<>(RichCustomEmoji.class, RichCustomEmoji::getName);
private final SnowflakeCacheViewImpl<GuildSticker> stickerCache = new SnowflakeCacheViewImpl<>(GuildSticker.class, GuildSticker::getName);
private final MemberCacheViewImpl memberCache = new MemberCacheViewImpl();
private final CacheView.SimpleCacheView<MemberPresenceImpl> memberPresences;
private CompletableFuture<Void> pendingRequestToSpeak;
private Member owner;
private String name;
private String iconId, splashId;
private String vanityCode;
private String description, banner;
private int maxPresences, maxMembers;
private int boostCount;
private long ownerId;
private Set<String> features;
private VoiceChannel afkChannel;
private TextChannel systemChannel;
private TextChannel rulesChannel;
private TextChannel communityUpdatesChannel;
private Role publicRole;
private VerificationLevel verificationLevel = VerificationLevel.UNKNOWN;
private NotificationLevel defaultNotificationLevel = NotificationLevel.UNKNOWN;
private MFALevel mfaLevel = MFALevel.UNKNOWN;
private ExplicitContentLevel explicitContentLevel = ExplicitContentLevel.UNKNOWN;
private NSFWLevel nsfwLevel = NSFWLevel.UNKNOWN;
private Timeout afkTimeout;
private BoostTier boostTier = BoostTier.NONE;
private DiscordLocale preferredLocale = DiscordLocale.ENGLISH_US;
private int memberCount;
private boolean boostProgressBarEnabled;
public GuildImpl(JDAImpl api, long id)
{
this.id = id;
this.api = api;
if (api.getCacheFlags().stream().anyMatch(CacheFlag::isPresence))
memberPresences = new CacheView.SimpleCacheView<>(MemberPresenceImpl.class, null);
else
memberPresences = null;
}
public void invalidate()
{
//Remove everything from global cache
// this prevents some race-conditions for getting audio managers from guilds
getJDA().getGuildsView().remove(id);
ChannelCacheViewImpl<Channel> channelsView = getJDA().getChannelsView();
try (UnlockHook hook = channelsView.writeLock())
{
getChannels().forEach(channel -> channelsView.remove(channel.getType(), channel.getIdLong()));
}
// Clear audio connection
getJDA().getClient().removeAudioConnection(id);
final AbstractCacheView<AudioManager> audioManagerView = getJDA().getAudioManagersView();
final AudioManagerImpl manager = (AudioManagerImpl) audioManagerView.get(id); //read-lock access/release
if (manager != null)
manager.closeAudioConnection(ConnectionStatus.DISCONNECTED_REMOVED_FROM_GUILD); //connection-lock access/release
audioManagerView.remove(id); //write-lock access/release
//cleaning up all users that we do not share a guild with anymore
// Anything left in memberIds will be removed from the main userMap
//Use a new HashSet so that we don't actually modify the Member map so it doesn't affect Guild#getMembers for the leave event.
TLongSet memberIds = getMembersView().keySet(); // copies keys
getJDA().getGuildCache().stream()
.map(GuildImpl.class::cast)
.forEach(g -> memberIds.removeAll(g.getMembersView().keySet()));
// Remember, everything left in memberIds is removed from the userMap
SnowflakeCacheViewImpl<User> userView = getJDA().getUsersView();
try (UnlockHook hook = userView.writeLock())
{
long selfId = getJDA().getSelfUser().getIdLong();
memberIds.forEach(memberId -> {
if (memberId == selfId)
return true; // don't remove selfUser from cache
userView.remove(memberId);
getJDA().getEventCache().clear(EventCache.Type.USER, memberId);
return true;
});
}
}
public void uncacheChannel(GuildChannel channel, boolean keepThreads)
{
long id = channel.getIdLong();
// Enforce idempotence by checking the channel was in cache
// If the channel was not in cache, there is no reason to cleanup anything else.
// This idempotency makes sure that new cache is never affected by old cache
if (channelCache.remove(channel.getType(), id) == null)
return;
api.getChannelsView().remove(channel.getType(), id);
if (!keepThreads && channel instanceof IThreadContainer)
{
// Remove dangling threads
SortedChannelCacheViewImpl<GuildChannel> localView = this.getChannelView();
ChannelCacheViewImpl<Channel> globalView = api.getChannelsView();
Predicate<ThreadChannel> predicate = thread -> channel.equals(thread.getParentChannel());
try (UnlockHook hook1 = localView.writeLock(); UnlockHook hook2 = globalView.writeLock())
{
localView.removeIf(ThreadChannel.class, predicate);
globalView.removeIf(ThreadChannel.class, predicate);
}
}
}
@Nonnull
@Override
public RestAction<List<Command>> retrieveCommands(boolean withLocalizations)
{
Route.CompiledRoute route = Route.Interactions.GET_GUILD_COMMANDS
.compile(getJDA().getSelfUser().getApplicationId(), getId())
.withQueryParams("with_localizations", String.valueOf(withLocalizations));
return new RestActionImpl<>(getJDA(), route,
(response, request) ->
response.getArray()
.stream(DataArray::getObject)
.map(json -> new CommandImpl(getJDA(), this, json))
.collect(Collectors.toList()));
}
@Nonnull
@Override
public RestAction<Command> retrieveCommandById(@Nonnull String id)
{
Checks.isSnowflake(id);
Route.CompiledRoute route = Route.Interactions.GET_GUILD_COMMAND.compile(getJDA().getSelfUser().getApplicationId(), getId(), id);
return new RestActionImpl<>(getJDA(), route, (response, request) -> new CommandImpl(getJDA(), this, response.getObject()));
}
@Nonnull
@Override
public CommandCreateAction upsertCommand(@Nonnull CommandData command)
{
Checks.notNull(command, "CommandData");
return new CommandCreateActionImpl(this, (CommandDataImpl) command);
}
@Nonnull
@Override
public CommandListUpdateAction updateCommands()
{
Route.CompiledRoute route = Route.Interactions.UPDATE_GUILD_COMMANDS.compile(getJDA().getSelfUser().getApplicationId(), getId());
return new CommandListUpdateActionImpl(getJDA(), this, route);
}
@Nonnull
@Override
public CommandEditAction editCommandById(@Nonnull String id)
{
Checks.isSnowflake(id);
return new CommandEditActionImpl(this, id);
}
@Nonnull
@Override
public RestAction<Void> deleteCommandById(@Nonnull String commandId)
{
Checks.isSnowflake(commandId);
Route.CompiledRoute route = Route.Interactions.DELETE_GUILD_COMMAND.compile(getJDA().getSelfUser().getApplicationId(), getId(), commandId);
return new RestActionImpl<>(getJDA(), route);
}
@Nonnull
@Override
public RestAction<List<IntegrationPrivilege>> retrieveIntegrationPrivilegesById(@Nonnull String targetId)
{
Checks.isSnowflake(targetId, "ID");
Route.CompiledRoute route = Route.Interactions.GET_COMMAND_PERMISSIONS.compile(getJDA().getSelfUser().getApplicationId(), getId(), targetId);
return new RestActionImpl<>(getJDA(), route, (response, request) -> parsePrivilegesList(response.getObject()));
}
@Nonnull
@Override
public RestAction<PrivilegeConfig> retrieveCommandPrivileges()
{
Route.CompiledRoute route = Route.Interactions.GET_ALL_COMMAND_PERMISSIONS.compile(getJDA().getSelfUser().getApplicationId(), getId());
return new RestActionImpl<>(getJDA(), route, (response, request) -> {
Map<String, List<IntegrationPrivilege>> privileges = new HashMap<>();
response.getArray().stream(DataArray::getObject).forEach(obj -> {
String id = obj.getString("id");
List<IntegrationPrivilege> list = Collections.unmodifiableList(parsePrivilegesList(obj));
privileges.put(id, list);
});
return new PrivilegeConfig(this, privileges);
});
}
private List<IntegrationPrivilege> parsePrivilegesList(DataObject obj)
{
return obj.getArray("permissions")
.stream(DataArray::getObject)
.map(this::parsePrivilege)
.collect(Collectors.toList());
}
private IntegrationPrivilege parsePrivilege(DataObject data)
{
IntegrationPrivilege.Type type = IntegrationPrivilege.Type.fromKey(data.getInt("type", 1));
boolean enabled = data.getBoolean("permission");
return new IntegrationPrivilege(this, type, enabled, data.getUnsignedLong("id"));
}
@Nonnull
@Override
public RestAction<EnumSet<Region>> retrieveRegions(boolean includeDeprecated)
{
Route.CompiledRoute route = Route.Guilds.GET_VOICE_REGIONS.compile(getId());
return new RestActionImpl<>(getJDA(), route, (response, request) ->
{
EnumSet<Region> set = EnumSet.noneOf(Region.class);
DataArray arr = response.getArray();
for (int i = 0; i < arr.length(); i++)
{
DataObject obj = arr.getObject(i);
if (!includeDeprecated && obj.getBoolean("deprecated"))
continue;
String id = obj.getString("id", "");
Region region = Region.fromKey(id);
if (region != Region.UNKNOWN)
set.add(region);
}
return set;
});
}
@Nonnull
@Override
public RestAction<List<AutoModRule>> retrieveAutoModRules()
{
checkPermission(Permission.MANAGE_SERVER);
Route.CompiledRoute route = Route.AutoModeration.LIST_RULES.compile(getId());
return new RestActionImpl<>(api, route, (response, request) ->
{
DataArray array = response.getArray();
List<AutoModRule> rules = new ArrayList<>(array.length());
for (int i = 0; i < array.length(); i++)
{
try
{
DataObject obj = array.getObject(i);
rules.add(AutoModRuleImpl.fromData(this, obj));
}
catch (ParsingException exception)
{
EntityBuilder.LOG.error("Failed to parse AutoModRule", exception);
}
}
return Collections.unmodifiableList(rules);
});
}
@Nonnull
@Override
public RestAction<AutoModRule> retrieveAutoModRuleById(@Nonnull String id)
{
Checks.isSnowflake(id);
checkPermission(Permission.MANAGE_SERVER);
Route.CompiledRoute route = Route.AutoModeration.GET_RULE.compile(getId(), id);
return new RestActionImpl<>(api, route, (response, request) -> AutoModRuleImpl.fromData(this, response.getObject()));
}
@Nonnull
@Override
public AuditableRestAction<AutoModRule> createAutoModRule(@Nonnull AutoModRuleData rule)
{
Checks.notNull(rule, "AutoMod Rule");
rule.getRequiredPermissions().forEach(this::checkPermission);
Route.CompiledRoute route = Route.AutoModeration.CREATE_RULE.compile(getId());
return new AuditableRestActionImpl<>(api, route, rule.toData(), (response, request) -> AutoModRuleImpl.fromData(this, response.getObject()));
}
@Nonnull
@Override
public AutoModRuleManager modifyAutoModRuleById(@Nonnull String id)
{
Checks.isSnowflake(id);
checkPermission(Permission.MANAGE_SERVER);
return new AutoModRuleManagerImpl(this, id);
}
@Nonnull
@Override
public AuditableRestAction<Void> deleteAutoModRuleById(@Nonnull String id)
{
Checks.isSnowflake(id);
checkPermission(Permission.MANAGE_SERVER);
Route.CompiledRoute route = Route.AutoModeration.DELETE_RULE.compile(getId(), id);
return new AuditableRestActionImpl<>(api, route);
}
@Nonnull
@Override
public MemberAction addMember(@Nonnull String accessToken, @Nonnull UserSnowflake user)
{
Checks.notBlank(accessToken, "Access-Token");
Checks.notNull(user, "User");
Checks.check(!isMember(user), "User is already in this guild");
if (!getSelfMember().hasPermission(Permission.CREATE_INSTANT_INVITE))
throw new InsufficientPermissionException(this, Permission.CREATE_INSTANT_INVITE);
return new MemberActionImpl(getJDA(), this, user.getId(), accessToken);
}
@Override
public boolean isLoaded()
{
// Only works with GUILD_MEMBERS intent
return getJDA().isIntent(GatewayIntent.GUILD_MEMBERS)
&& (long) getMemberCount() <= getMemberCache().size();
}
@Override
public void pruneMemberCache()
{
try (UnlockHook h = memberCache.writeLock())
{
EntityBuilder builder = getJDA().getEntityBuilder();
Set<Member> members = memberCache.asSet();
members.forEach(m -> builder.updateMemberCache((MemberImpl) m));
}
}
@Override
public boolean unloadMember(long userId)
{
if (userId == api.getSelfUser().getIdLong())
return false;
MemberImpl member = (MemberImpl) getMemberById(userId);
if (member == null)
return false;
api.getEntityBuilder().updateMemberCache(member, true);
return true;
}
@Override
public int getMemberCount()
{
return memberCount;
}
@Nonnull
@Override
public String getName()
{
return name;
}
@Override
public String getIconId()
{
return iconId;
}
@Nonnull
@Override
public Set<String> getFeatures()
{
return features;
}
@Override
public String getSplashId()
{
return splashId;
}
@Nullable
@Override
public String getVanityCode()
{
return vanityCode;
}
@Override
@Nonnull
public RestAction<VanityInvite> retrieveVanityInvite()
{
checkPermission(Permission.MANAGE_SERVER);
JDAImpl api = getJDA();
Route.CompiledRoute route = Route.Guilds.GET_VANITY_URL.compile(getId());
return new RestActionImpl<>(api, route,
(response, request) -> new VanityInvite(vanityCode, response.getObject().getInt("uses")));
}
@Nullable
@Override
public String getDescription()
{
return description;
}
@Nonnull
@Override
public DiscordLocale getLocale()
{
return preferredLocale;
}
@Nullable
@Override
public String getBannerId()
{
return banner;
}
@Nonnull
@Override
public BoostTier getBoostTier()
{
return boostTier;
}
@Override
public int getBoostCount()
{
return boostCount;
}
@Nonnull
@Override
@SuppressWarnings("ConstantConditions") // can't be null here
public List<Member> getBoosters()
{
return memberCache.applyStream((members) ->
members.filter(m -> m.getTimeBoosted() != null)
.sorted(Comparator.comparing(Member::getTimeBoosted))
.collect(Helpers.toUnmodifiableList()));
}
@Override
public int getMaxMembers()
{
return maxMembers;
}
@Override
public int getMaxPresences()
{
return maxPresences;
}
@Nonnull
@Override
public RestAction<MetaData> retrieveMetaData()
{
Route.CompiledRoute route = Route.Guilds.GET_GUILD.compile(getId());
route = route.withQueryParams("with_counts", "true");
return new RestActionImpl<>(getJDA(), route, (response, request) -> {
DataObject json = response.getObject();
int memberLimit = json.getInt("max_members", 0);
int presenceLimit = json.getInt("max_presences", 5000);
this.maxMembers = memberLimit;
this.maxPresences = presenceLimit;
int approxMembers = json.getInt("approximate_member_count", this.memberCount);
int approxPresence = json.getInt("approximate_presence_count", 0);
return new MetaData(memberLimit, presenceLimit, approxPresence, approxMembers);
});
}
@Override
public VoiceChannel getAfkChannel()
{
return afkChannel;
}
@Override
public TextChannel getSystemChannel()
{
return systemChannel;
}
@Override
public TextChannel getRulesChannel()
{
return rulesChannel;
}
@Nonnull
@Override
public CacheRestAction<ScheduledEvent> retrieveScheduledEventById(@Nonnull String id)
{
Checks.isSnowflake(id);
return new DeferredRestAction<>(getJDA(), ScheduledEvent.class,
() -> getScheduledEventById(id),
() ->
{
Route.CompiledRoute route = Route.Guilds.GET_SCHEDULED_EVENT.compile(getId(), id);
return new RestActionImpl<>(getJDA(), route, (response, request) -> api.getEntityBuilder().createScheduledEvent(this, response.getObject()));
});
}
@Nonnull
@Override
public CacheRestAction<ScheduledEvent> retrieveScheduledEventById(long id)
{
return retrieveScheduledEventById(Long.toUnsignedString(id));
}
@Nonnull
@Override
public ScheduledEventAction createScheduledEvent(@Nonnull String name, @Nonnull String location, @Nonnull OffsetDateTime startTime, @Nonnull OffsetDateTime endTime)
{
checkPermission(Permission.MANAGE_EVENTS);
return new ScheduledEventActionImpl(name, location, startTime, endTime, this);
}
@Nonnull
@Override
public ScheduledEventAction createScheduledEvent(@Nonnull String name, @Nonnull GuildChannel channel, @Nonnull OffsetDateTime startTime)
{
checkPermission(Permission.MANAGE_EVENTS);
return new ScheduledEventActionImpl(name, channel, startTime, this);
}
@Override
public TextChannel getCommunityUpdatesChannel()
{
return communityUpdatesChannel;
}
@Nonnull
@Override
public RestAction<List<Webhook>> retrieveWebhooks()
{
if (!getSelfMember().hasPermission(Permission.MANAGE_WEBHOOKS))
throw new InsufficientPermissionException(this, Permission.MANAGE_WEBHOOKS);
Route.CompiledRoute route = Route.Guilds.GET_WEBHOOKS.compile(getId());
return new RestActionImpl<>(getJDA(), route, (response, request) ->
{
DataArray array = response.getArray();
List<Webhook> webhooks = new ArrayList<>(array.length());
EntityBuilder builder = api.getEntityBuilder();
for (int i = 0; i < array.length(); i++)
{
try
{
webhooks.add(builder.createWebhook(array.getObject(i)));
}
catch (Exception e)
{
JDAImpl.LOG.error("Error creating webhook from json", e);
}
}
return Collections.unmodifiableList(webhooks);
});
}
@Override
public Member getOwner()
{
return owner;
}
@Override
public long getOwnerIdLong()
{
return ownerId;
}
@Nonnull
@Override
public Timeout getAfkTimeout()
{
return afkTimeout;
}
@Override
public boolean isMember(@Nonnull UserSnowflake user)
{
return memberCache.get(user.getIdLong()) != null;
}
@Nonnull
@Override
public Member getSelfMember()
{
Member member = getMember(getJDA().getSelfUser());
if (member == null)
throw new IllegalStateException("Guild does not have a self member");
return member;
}
@Override
public Member getMember(@Nonnull UserSnowflake user)
{
Checks.notNull(user, "User");
return getMemberById(user.getIdLong());
}
@Nonnull
@Override
public MemberCacheView getMemberCache()
{
return memberCache;
}
@Nonnull
@Override
public SortedSnowflakeCacheView<ScheduledEvent> getScheduledEventCache()
{
return scheduledEventCache;
}
@Nonnull
@Override
public SortedSnowflakeCacheView<Category> getCategoryCache()
{
return channelCache.ofType(Category.class);
}
@Nonnull
@Override
public SortedSnowflakeCacheView<TextChannel> getTextChannelCache()
{
return channelCache.ofType(TextChannel.class);
}
@Nonnull
@Override
public SortedSnowflakeCacheView<NewsChannel> getNewsChannelCache()
{
return channelCache.ofType(NewsChannel.class);
}
@Nonnull
@Override
public SortedSnowflakeCacheView<VoiceChannel> getVoiceChannelCache()
{
return channelCache.ofType(VoiceChannel.class);
}
@Nonnull
@Override
public SortedSnowflakeCacheView<ForumChannel> getForumChannelCache()
{
return channelCache.ofType(ForumChannel.class);
}
@Nonnull
@Override
public SnowflakeCacheView<MediaChannel> getMediaChannelCache()
{
return channelCache.ofType(MediaChannel.class);
}
@Nonnull
@Override
public SortedSnowflakeCacheView<StageChannel> getStageChannelCache()
{
return channelCache.ofType(StageChannel.class);
}
@Nonnull
@Override
public SortedSnowflakeCacheView<ThreadChannel> getThreadChannelCache()
{
return channelCache.ofType(ThreadChannel.class);
}
@Nonnull
@Override
public SortedChannelCacheViewImpl<GuildChannel> getChannelCache()
{
return channelCache;
}
@Nullable
@Override
public GuildChannel getGuildChannelById(long id)
{
return channelCache.getElementById(id);
}
@Override
public GuildChannel getGuildChannelById(@Nonnull ChannelType type, long id)
{
return channelCache.getElementById(type, id);
}
@Nonnull
@Override
public SortedSnowflakeCacheView<Role> getRoleCache()
{
return roleCache;
}
@Nonnull
@Override
public SnowflakeCacheView<RichCustomEmoji> getEmojiCache()
{
return emojicache;
}
@Nonnull
@Override
public SnowflakeCacheView<GuildSticker> getStickerCache()
{
return stickerCache;
}
@Nonnull
@Override
public List<GuildChannel> getChannels(boolean includeHidden)
{
if (includeHidden)
{
return channelCache.applyStream(stream ->
stream.filter(it -> !it.getType().isThread())
.sorted()
.collect(Helpers.toUnmodifiableList())
);
}
// When we remove hidden channels there are 2 considerations to account for:
//
// 1. A channel is not visible if we don't have VIEW_CHANNEL permissions
// 2. A category is not visible if we don't see any channels within it
//
// In our implementation we iterate all applicable channels and only add categories,
// when a member of the category is added too.
//
// Note: We avoid using Category#getChannels because it would iterate the entire cache each time.
// This is an optimization to avoid many unnecessary iterations.
Member self = getSelfMember();
SortedSet<GuildChannel> channels = new TreeSet<>();
channelCache.ofType(ICategorizableChannel.class).forEachUnordered(channel ->
{
// Hide threads and inaccessible channels
if (channel.getType().isThread() || !self.hasPermission(channel, Permission.VIEW_CHANNEL)) return;
Category category = channel.getParentCategory();
channels.add(channel);
// Empty categories will never show up here,
// since no categorizable channel will add them to this group
if (category != null)
channels.add(category);
});
return Collections.unmodifiableList(new ArrayList<>(channels));
}
@Nonnull
@Override
public RestAction<List<RichCustomEmoji>> retrieveEmojis()
{
Route.CompiledRoute route = Route.Emojis.GET_EMOJIS.compile(getId());
return new RestActionImpl<>(getJDA(), route, (response, request) ->
{
EntityBuilder builder = GuildImpl.this.getJDA().getEntityBuilder();
DataArray emojis = response.getArray();
List<RichCustomEmoji> list = new ArrayList<>(emojis.length());
for (int i = 0; i < emojis.length(); i++)
{
DataObject emoji = emojis.getObject(i);
list.add(builder.createEmoji(GuildImpl.this, emoji));
}
return Collections.unmodifiableList(list);
});
}
@Nonnull
@Override
public RestAction<RichCustomEmoji> retrieveEmojiById(@Nonnull String id)
{
Checks.isSnowflake(id, "Emoji ID");
JDAImpl jda = getJDA();
return new DeferredRestAction<>(jda, RichCustomEmoji.class,
() -> {
RichCustomEmoji emoji = getEmojiById(id);
if (emoji != null)
{
if (emoji.getOwner() != null || !getSelfMember().hasPermission(Permission.MANAGE_GUILD_EXPRESSIONS))
return emoji;
}
return null;
}, () -> {
Route.CompiledRoute route = Route.Emojis.GET_EMOJI.compile(getId(), id);
return new AuditableRestActionImpl<>(jda, route, (response, request) ->
{
EntityBuilder builder = GuildImpl.this.getJDA().getEntityBuilder();
return builder.createEmoji(GuildImpl.this, response.getObject());
});
});
}
@Nonnull
@Override
public RestAction<List<GuildSticker>> retrieveStickers()
{
Route.CompiledRoute route = Route.Stickers.GET_GUILD_STICKERS.compile(getId());
return new RestActionImpl<>(getJDA(), route, (response, request) -> {
DataArray array = response.getArray();
List<GuildSticker> stickers = new ArrayList<>(array.length());
EntityBuilder builder = api.getEntityBuilder();
for (int i = 0; i < array.length(); i++)
{
DataObject object = null;
try
{
object = array.getObject(i);
GuildSticker sticker = (GuildSticker) builder.createRichSticker(object);
stickers.add(sticker);
}
catch (ParsingException | ClassCastException ex)
{
EntityBuilder.LOG.error("Failed to parse sticker for JSON: {}", object, ex);
}
}
return Collections.unmodifiableList(stickers);
});
}
@Nonnull
@Override
public RestAction<GuildSticker> retrieveSticker(@Nonnull StickerSnowflake sticker)
{
Checks.notNull(sticker, "Sticker");
Route.CompiledRoute route = Route.Stickers.GET_GUILD_STICKER.compile(getId(), sticker.getId());
return new RestActionImpl<>(getJDA(), route, (response, request) -> {
DataObject object = response.getObject();
EntityBuilder builder = api.getEntityBuilder();
return (GuildSticker) builder.createRichSticker(object);
});
}
@Nonnull
@Override
public GuildStickerManager editSticker(@Nonnull StickerSnowflake sticker)
{
Checks.notNull(sticker, "Sticker");
if (sticker instanceof GuildSticker)
Checks.check(((GuildSticker) sticker).getGuildIdLong() == id, "Cannot edit a sticker from another guild!");
Checks.check(!(sticker instanceof StandardSticker), "Cannot edit a standard sticker.");
return new GuildStickerManagerImpl(this, id, sticker);
}
@Nonnull
@Override
public BanPaginationActionImpl retrieveBanList()
{
if (!getSelfMember().hasPermission(Permission.BAN_MEMBERS))
throw new InsufficientPermissionException(this, Permission.BAN_MEMBERS);
return new BanPaginationActionImpl(this);
}
@Nonnull
@Override
public RestAction<Ban> retrieveBan(@Nonnull UserSnowflake user)
{
if (!getSelfMember().hasPermission(Permission.BAN_MEMBERS))
throw new InsufficientPermissionException(this, Permission.BAN_MEMBERS);
Checks.notNull(user, "User");
Route.CompiledRoute route = Route.Guilds.GET_BAN.compile(getId(), user.getId());
return new RestActionImpl<>(getJDA(), route, (response, request) ->
{
EntityBuilder builder = api.getEntityBuilder();
DataObject bannedObj = response.getObject();
DataObject userJson = bannedObj.getObject("user");
return new Ban(builder.createUser(userJson), bannedObj.getString("reason", null));
});
}
@Nonnull
@Override
public RestAction<Integer> retrievePrunableMemberCount(int days)
{
if (!getSelfMember().hasPermission(Permission.KICK_MEMBERS))
throw new InsufficientPermissionException(this, Permission.KICK_MEMBERS);
Checks.check(days >= 1 && days <= 30, "Provided %d days must be between 1 and 30.", days);
Route.CompiledRoute route = Route.Guilds.PRUNABLE_COUNT.compile(getId()).withQueryParams("days", Integer.toString(days));
return new RestActionImpl<>(getJDA(), route, (response, request) -> response.getObject().getInt("pruned"));