/
GuildImpl.java
728 lines (629 loc) · 20 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
/*
* Copyright 2015-2017 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.impl;
import gnu.trove.map.TLongObjectMap;
import net.dv8tion.jda.client.requests.restaction.pagination.MentionPaginationAction;
import net.dv8tion.jda.core.AccountType;
import net.dv8tion.jda.core.Permission;
import net.dv8tion.jda.core.Region;
import net.dv8tion.jda.core.entities.*;
import net.dv8tion.jda.core.exceptions.AccountTypeException;
import net.dv8tion.jda.core.exceptions.GuildUnavailableException;
import net.dv8tion.jda.core.exceptions.InsufficientPermissionException;
import net.dv8tion.jda.core.exceptions.PermissionException;
import net.dv8tion.jda.core.managers.AudioManager;
import net.dv8tion.jda.core.managers.GuildController;
import net.dv8tion.jda.core.managers.GuildManager;
import net.dv8tion.jda.core.managers.GuildManagerUpdatable;
import net.dv8tion.jda.core.managers.impl.AudioManagerImpl;
import net.dv8tion.jda.core.requests.Request;
import net.dv8tion.jda.core.requests.Response;
import net.dv8tion.jda.core.requests.RestAction;
import net.dv8tion.jda.core.requests.Route;
import net.dv8tion.jda.core.requests.restaction.pagination.AuditLogPaginationAction;
import net.dv8tion.jda.core.utils.Checks;
import net.dv8tion.jda.core.utils.MiscUtil;
import net.dv8tion.jda.core.utils.cache.*;
import net.dv8tion.jda.core.utils.cache.impl.MemberCacheViewImpl;
import net.dv8tion.jda.core.utils.cache.impl.SnowflakeCacheViewImpl;
import net.dv8tion.jda.core.utils.cache.impl.SortedSnowflakeCacheView;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import javax.annotation.Nullable;
import java.time.OffsetDateTime;
import java.time.temporal.ChronoUnit;
import java.util.*;
import java.util.stream.Collectors;
public class GuildImpl implements Guild
{
private final long id;
private final JDAImpl api;
private final SortedSnowflakeCacheView<Category> categoryCache = new SortedSnowflakeCacheView<Category>(Channel::getName, Comparator.naturalOrder());
private final SortedSnowflakeCacheView<VoiceChannel> voiceChannelCache = new SortedSnowflakeCacheView<VoiceChannel>(Channel::getName, Comparator.naturalOrder());
private final SortedSnowflakeCacheView<TextChannel> textChannelCache = new SortedSnowflakeCacheView<TextChannel>(Channel::getName, Comparator.naturalOrder());
private final SortedSnowflakeCacheView<Role> roleCache = new SortedSnowflakeCacheView<Role>(Role::getName, Comparator.reverseOrder());
private final SnowflakeCacheViewImpl<Emote> emoteCache = new SnowflakeCacheViewImpl<>(Emote::getName);
private final MemberCacheViewImpl memberCache = new MemberCacheViewImpl();
private final TLongObjectMap<JSONObject> cachedPresences = MiscUtil.newLongMap();
private final Object mngLock = new Object();
private volatile GuildManager manager;
private volatile GuildManagerUpdatable managerUpdatable;
private volatile GuildController controller;
private Member owner;
private String name;
private String iconId;
private String splashId;
private Region region;
private VoiceChannel afkChannel;
private TextChannel systemChannel;
private Role publicRole;
private VerificationLevel verificationLevel;
private NotificationLevel defaultNotificationLevel;
private MFALevel mfaLevel;
private ExplicitContentLevel explicitContentLevel;
private Timeout afkTimeout;
private boolean available;
private boolean canSendVerification = false;
public GuildImpl(JDAImpl api, long id)
{
this.id = id;
this.api = api;
}
@Override
public String getName()
{
return name;
}
@Override
public String getIconId()
{
return iconId;
}
@Override
public String getIconUrl()
{
return iconId == null ? null : "https://cdn.discordapp.com/icons/" + id + "/" + iconId + ".jpg";
}
@Override
public String getSplashId()
{
return splashId;
}
@Override
public String getSplashUrl()
{
return splashId == null ? null : "https://cdn.discordapp.com/splashes/" + id + "/" + splashId + ".jpg";
}
@Override
public VoiceChannel getAfkChannel()
{
return afkChannel;
}
@Override
public TextChannel getSystemChannel()
{
return systemChannel;
}
@Override
public RestAction<List<Webhook>> getWebhooks()
{
if (!getSelfMember().hasPermission(Permission.MANAGE_WEBHOOKS))
throw new InsufficientPermissionException(Permission.MANAGE_WEBHOOKS);
Route.CompiledRoute route = Route.Guilds.GET_WEBHOOKS.compile(getId());
return new RestAction<List<Webhook>>(api, route)
{
@Override
protected void handleResponse(Response response, Request<List<Webhook>> request)
{
if (!response.isOk())
{
request.onFailure(response);
return;
}
List<Webhook> webhooks = new LinkedList<>();
JSONArray array = response.getArray();
EntityBuilder builder = api.getEntityBuilder();
for (Object object : array)
{
try
{
webhooks.add(builder.createWebhook((JSONObject) object));
}
catch (JSONException | NullPointerException e)
{
JDAImpl.LOG.fatal(e);
}
}
request.onSuccess(webhooks);
}
};
}
@Override
public Member getOwner()
{
return owner;
}
@Override
public Timeout getAfkTimeout()
{
return afkTimeout;
}
@Override
public Region getRegion()
{
return region;
}
@Override
public boolean isMember(User user)
{
return memberCache.getMap().containsKey(user.getIdLong());
}
@Override
public Member getSelfMember()
{
return getMember(getJDA().getSelfUser());
}
@Override
public Member getMember(User user)
{
return getMemberById(user.getIdLong());
}
@Override
public MemberCacheView getMemberCache()
{
return memberCache;
}
@Override
public SnowflakeCacheView<Category> getCategoryCache()
{
return categoryCache;
}
@Override
public SnowflakeCacheView<TextChannel> getTextChannelCache()
{
return textChannelCache;
}
@Override
public SnowflakeCacheView<VoiceChannel> getVoiceChannelCache()
{
return voiceChannelCache;
}
@Override
public SnowflakeCacheView<Role> getRoleCache()
{
return roleCache;
}
@Override
public SnowflakeCacheView<Emote> getEmoteCache()
{
return emoteCache;
}
@Override
public RestAction<List<User>> getBans()
{
if (!isAvailable())
throw new GuildUnavailableException();
if (!getSelfMember().hasPermission(Permission.BAN_MEMBERS))
throw new InsufficientPermissionException(Permission.BAN_MEMBERS);
Route.CompiledRoute route = Route.Guilds.GET_BANS.compile(getId());
return new RestAction<List<User>>(getJDA(), route)
{
@Override
protected void handleResponse(Response response, Request<List<User>> request)
{
if (!response.isOk())
{
request.onFailure(response);
return;
}
EntityBuilder builder = api.getEntityBuilder();
List<User> bans = new LinkedList<>();
JSONArray bannedArr = response.getArray();
for (int i = 0; i < bannedArr.length(); i++)
{
JSONObject user = bannedArr.getJSONObject(i).getJSONObject("user");
bans.add(builder.createFakeUser(user, false));
}
request.onSuccess(Collections.unmodifiableList(bans));
}
};
}
@Override
public RestAction<Integer> getPrunableMemberCount(int days)
{
if (!isAvailable())
throw new GuildUnavailableException();
if (!getSelfMember().hasPermission(Permission.KICK_MEMBERS))
throw new InsufficientPermissionException(Permission.KICK_MEMBERS);
if (days < 1)
throw new IllegalArgumentException("Days amount must be at minimum 1 day.");
Route.CompiledRoute route = Route.Guilds.PRUNABLE_COUNT.compile(getId()).withQueryParams("days", Integer.toString(days));
return new RestAction<Integer>(getJDA(), route)
{
@Override
protected void handleResponse(Response response, Request<Integer> request)
{
if (response.isOk())
request.onSuccess(response.getObject().getInt("pruned"));
else
request .onFailure(response);
}
};
}
@Override
public Role getPublicRole()
{
return publicRole;
}
@Override
public TextChannel getPublicChannel()
{
return textChannelCache.getElementById(id);
}
@Nullable
@Override
public TextChannel getDefaultChannel()
{
final Role role = getPublicRole();
return getTextChannelsMap().valueCollection().stream()
.filter(c -> role.hasPermission(c, Permission.MESSAGE_READ))
.sorted(Comparator.naturalOrder())
.findFirst().orElse(null);
}
@Override
public GuildManager getManager()
{
GuildManager mng = manager;
if (mng == null)
{
synchronized (mngLock)
{
mng = manager;
if (mng == null)
mng = manager = new GuildManager(this);
}
}
return mng;
}
@Override
public GuildManagerUpdatable getManagerUpdatable()
{
GuildManagerUpdatable mng = managerUpdatable;
if (mng == null)
{
synchronized (mngLock)
{
mng = managerUpdatable;
if (mng == null)
mng = managerUpdatable = new GuildManagerUpdatable(this);
}
}
return mng;
}
@Override
public GuildController getController()
{
GuildController ctrl = controller;
if (ctrl == null)
{
synchronized (mngLock)
{
ctrl = controller;
if (ctrl == null)
ctrl = controller = new GuildController(this);
}
}
return ctrl;
}
@Override
public MentionPaginationAction getRecentMentions()
{
if (getJDA().getAccountType() != AccountType.CLIENT)
throw new AccountTypeException(AccountType.CLIENT);
return getJDA().asClient().getRecentMentions(this);
}
@Override
public AuditLogPaginationAction getAuditLogs()
{
return new AuditLogPaginationAction(this);
}
@Override
public RestAction<Void> leave()
{
if (owner.equals(getSelfMember()))
throw new IllegalStateException("Cannot leave a guild that you are the owner of! Transfer guild ownership first!");
Route.CompiledRoute route = Route.Self.LEAVE_GUILD.compile(getId());
return new RestAction<Void>(api, route)
{
@Override
protected void handleResponse(Response response, Request<Void> request)
{
if (response.isOk())
request.onSuccess(null);
else
request.onFailure(response);
}
};
}
@Override
public RestAction<Void> delete()
{
if (api.getSelfUser().isMfaEnabled())
throw new IllegalStateException("Cannot delete a guild without providing MFA code. Use Guild#delete(String)");
return delete(null);
}
@Override
public RestAction<Void> delete(String mfaCode)
{
if (!owner.equals(getSelfMember()))
throw new PermissionException("Cannot delete a guild that you do not own!");
JSONObject mfaBody = null;
if (api.getSelfUser().isMfaEnabled())
{
Checks.notEmpty(mfaCode, "Provided MultiFactor Auth code");
mfaBody = new JSONObject().put("code", mfaCode);
}
Route.CompiledRoute route = Route.Guilds.DELETE_GUILD.compile(getId());
return new RestAction<Void>(api, route, mfaBody)
{
@Override
protected void handleResponse(Response response, Request<Void> request)
{
if (response.isOk())
request.onSuccess(null);
else
request.onFailure(response);
}
};
}
@Override
public AudioManager getAudioManager()
{
if (!api.isAudioEnabled())
throw new IllegalStateException("Audio is disabled. Cannot retrieve an AudioManager while audio is disabled.");
final TLongObjectMap<AudioManager> managerMap = api.getAudioManagerMap();
AudioManager mng = managerMap.get(id);
if (mng == null)
{
// No previous manager found -> create one
synchronized (managerMap)
{
mng = managerMap.get(id);
if (mng == null)
{
mng = new AudioManagerImpl(this);
managerMap.put(id, mng);
}
}
}
return mng;
}
@Override
public JDAImpl getJDA()
{
return api;
}
@Override
public List<GuildVoiceState> getVoiceStates()
{
return Collections.unmodifiableList(
getMembersMap().valueCollection().stream().map(Member::getVoiceState).collect(Collectors.toList()));
}
@Override
public VerificationLevel getVerificationLevel()
{
return verificationLevel;
}
@Override
public NotificationLevel getDefaultNotificationLevel()
{
return defaultNotificationLevel;
}
@Override
public MFALevel getRequiredMFALevel()
{
return mfaLevel;
}
@Override
public ExplicitContentLevel getExplicitContentLevel()
{
return explicitContentLevel;
}
@Override
public boolean checkVerification()
{
if (api.getAccountType() == AccountType.BOT)
return true;
if(canSendVerification)
return true;
switch (verificationLevel)
{
case HIGH:
if(ChronoUnit.MINUTES.between(getSelfMember().getJoinDate(), OffsetDateTime.now()) < 10)
break;
case MEDIUM:
if(ChronoUnit.MINUTES.between(MiscUtil.getCreationTime(api.getSelfUser()), OffsetDateTime.now()) < 5)
break;
case LOW:
if(!api.getSelfUser().isVerified())
break;
case NONE:
canSendVerification = true;
return true;
}
return false;
}
@Override
public boolean isAvailable()
{
return available;
}
@Override
public long getIdLong()
{
return id;
}
// ---- Setters -----
public GuildImpl setAvailable(boolean available)
{
this.available = available;
return this;
}
public GuildImpl setOwner(Member owner)
{
this.owner = owner;
return this;
}
public GuildImpl setName(String name)
{
this.name = name;
return this;
}
public GuildImpl setIconId(String iconId)
{
this.iconId = iconId;
return this;
}
public GuildImpl setSplashId(String splashId)
{
this.splashId = splashId;
return this;
}
public GuildImpl setRegion(Region region)
{
this.region = region;
return this;
}
public GuildImpl setAfkChannel(VoiceChannel afkChannel)
{
this.afkChannel = afkChannel;
return this;
}
public GuildImpl setSystemChannel(TextChannel systemChannel)
{
this.systemChannel = systemChannel;
return this;
}
public GuildImpl setPublicRole(Role publicRole)
{
this.publicRole = publicRole;
return this;
}
public GuildImpl setVerificationLevel(VerificationLevel level)
{
this.verificationLevel = level;
this.canSendVerification = false; //recalc on next send
return this;
}
public GuildImpl setDefaultNotificationLevel(NotificationLevel level)
{
this.defaultNotificationLevel = level;
return this;
}
public GuildImpl setRequiredMFALevel(MFALevel level)
{
this.mfaLevel = level;
return this;
}
public GuildImpl setExplicitContentLevel(ExplicitContentLevel level)
{
this.explicitContentLevel = level;
return this;
}
public GuildImpl setAfkTimeout(Timeout afkTimeout)
{
this.afkTimeout = afkTimeout;
return this;
}
// -- Map getters --
public TLongObjectMap<Category> getCategoriesMap()
{
return categoryCache.getMap();
}
public TLongObjectMap<TextChannel> getTextChannelsMap()
{
return textChannelCache.getMap();
}
public TLongObjectMap<VoiceChannel> getVoiceChannelsMap()
{
return voiceChannelCache.getMap();
}
public TLongObjectMap<Member> getMembersMap()
{
return memberCache.getMap();
}
public TLongObjectMap<Role> getRolesMap()
{
return roleCache.getMap();
}
public TLongObjectMap<Emote> getEmoteMap()
{
return emoteCache.getMap();
}
public TLongObjectMap<JSONObject> getCachedPresenceMap()
{
return cachedPresences;
}
// -- Object overrides --
@Override
public boolean equals(Object o)
{
if (!(o instanceof GuildImpl))
return false;
GuildImpl oGuild = (GuildImpl) o;
return this == oGuild || this.id == oGuild.id;
}
@Override
public int hashCode()
{
return Long.hashCode(id);
}
@Override
public String toString()
{
return "G:" + getName() + '(' + id + ')';
}
@Override
public RestAction<List<Invite>> getInvites()
{
if (!this.getSelfMember().hasPermission(Permission.MANAGE_SERVER))
throw new InsufficientPermissionException(Permission.MANAGE_SERVER);
final Route.CompiledRoute route = Route.Invites.GET_GUILD_INVITES.compile(getId());
return new RestAction<List<Invite>>(api, route)
{
@Override
protected void handleResponse(final Response response, final Request<List<Invite>> request)
{
if (response.isOk())
{
EntityBuilder entityBuilder = this.api.getEntityBuilder();
JSONArray array = response.getArray();
List<Invite> invites = new ArrayList<>(array.length());
for (int i = 0; i < array.length(); i++)
{
invites.add(entityBuilder.createInvite(array.getJSONObject(i)));
}
request.onSuccess(invites);
}
else
{
request.onFailure(response);
}
}
};
}
}