/
ChannelUpdateHandler.java
570 lines (494 loc) · 23.4 KB
/
ChannelUpdateHandler.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
/*
* 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.handle;
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.Permission;
import net.dv8tion.jda.api.Region;
import net.dv8tion.jda.api.entities.Guild;
import net.dv8tion.jda.api.entities.IPermissionHolder;
import net.dv8tion.jda.api.entities.PermissionOverride;
import net.dv8tion.jda.api.entities.channel.ChannelFlag;
import net.dv8tion.jda.api.entities.channel.ChannelType;
import net.dv8tion.jda.api.entities.channel.attribute.IThreadContainer;
import net.dv8tion.jda.api.entities.channel.concrete.Category;
import net.dv8tion.jda.api.entities.channel.concrete.NewsChannel;
import net.dv8tion.jda.api.entities.channel.concrete.TextChannel;
import net.dv8tion.jda.api.entities.channel.concrete.ThreadChannel;
import net.dv8tion.jda.api.entities.channel.forums.ForumTag;
import net.dv8tion.jda.api.entities.emoji.EmojiUnion;
import net.dv8tion.jda.api.events.channel.forum.ForumTagAddEvent;
import net.dv8tion.jda.api.events.channel.forum.ForumTagRemoveEvent;
import net.dv8tion.jda.api.events.channel.forum.update.ForumTagUpdateEmojiEvent;
import net.dv8tion.jda.api.events.channel.forum.update.ForumTagUpdateModeratedEvent;
import net.dv8tion.jda.api.events.channel.forum.update.ForumTagUpdateNameEvent;
import net.dv8tion.jda.api.events.channel.update.*;
import net.dv8tion.jda.api.events.guild.override.PermissionOverrideCreateEvent;
import net.dv8tion.jda.api.events.guild.override.PermissionOverrideDeleteEvent;
import net.dv8tion.jda.api.events.guild.override.PermissionOverrideUpdateEvent;
import net.dv8tion.jda.api.events.thread.ThreadHiddenEvent;
import net.dv8tion.jda.api.utils.cache.CacheFlag;
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.*;
import net.dv8tion.jda.internal.entities.channel.concrete.NewsChannelImpl;
import net.dv8tion.jda.internal.entities.channel.concrete.TextChannelImpl;
import net.dv8tion.jda.internal.entities.channel.concrete.VoiceChannelImpl;
import net.dv8tion.jda.internal.entities.channel.middleman.AbstractGuildChannelImpl;
import net.dv8tion.jda.internal.entities.channel.mixin.attribute.*;
import net.dv8tion.jda.internal.entities.channel.mixin.middleman.AudioChannelMixin;
import net.dv8tion.jda.internal.requests.WebSocketClient;
import net.dv8tion.jda.internal.utils.UnlockHook;
import net.dv8tion.jda.internal.utils.cache.SnowflakeCacheViewImpl;
import net.dv8tion.jda.internal.utils.cache.SortedSnowflakeCacheViewImpl;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
@SuppressWarnings("ConstantConditions")
public class ChannelUpdateHandler extends SocketHandler
{
public ChannelUpdateHandler(JDAImpl api)
{
super(api);
}
@Override
protected Long handleInternally(DataObject content)
{
ChannelType type = ChannelType.fromId(content.getInt("type"));
if (type == ChannelType.GROUP)
{
WebSocketClient.LOG.warn("Ignoring CHANNEL_UPDATE for a group which we don't support");
return null;
}
if (!content.isNull("guild_id"))
{
long guildId = content.getUnsignedLong("guild_id");
if (getJDA().getGuildSetupController().isLocked(guildId))
return guildId;
}
long channelId = content.getUnsignedLong("id");
//We assume the CHANNEL_UPDATE was for a GuildChannel because PrivateChannels don't emit CHANNEL_UPDATE for 1:1 DMs, only Groups.
AbstractGuildChannelImpl<?> channel = (AbstractGuildChannelImpl<?>) getJDA().getGuildChannelById(channelId);
if (channel == null)
{
getJDA().getEventCache().cache(EventCache.Type.CHANNEL, channelId, responseNumber, allContent, this::handle);
EventCache.LOG.debug("CHANNEL_UPDATE attempted to update a channel that does not exist. JSON: {}", content);
return null;
}
//Detect if we changed the channel type at all and reconstruct the channel entity if needed
channel = handleChannelTypeChange(channel, content, type);
//Handle shared properties
String oldName = channel.getName();
String name = content.getString("name", oldName);
if (!Objects.equals(oldName, name))
{
channel.setName(name);
getJDA().handleEvent(
new ChannelUpdateNameEvent(
getJDA(), responseNumber,
channel, oldName, name));
}
if (channel instanceof ITopicChannelMixin<?>)
handleTopic((ITopicChannelMixin<?>) channel, content.getString("topic", null));
if (channel instanceof ISlowmodeChannelMixin<?>)
handleSlowmode((ISlowmodeChannelMixin<?>) channel, content.getInt("rate_limit_per_user", 0));
if (channel instanceof IAgeRestrictedChannelMixin<?>)
handleNsfw((IAgeRestrictedChannelMixin<?>) channel, content.getBoolean("nsfw"));
if (channel instanceof ICategorizableChannelMixin<?>)
handleParentCategory((ICategorizableChannelMixin<?>) channel, content.getUnsignedLong("parent_id", 0));
if (channel instanceof IPositionableChannelMixin<?>)
handlePosition((IPositionableChannelMixin<?>) channel, content.getInt("position", 0));
if (channel instanceof IThreadContainerMixin<?>)
handleThreadContainer((IThreadContainerMixin<?>) channel, content);
if (channel instanceof AudioChannelMixin<?>)
handleAudioChannel((AudioChannelMixin<?>) channel, content);
//Handle concrete type specific properties
switch (type)
{
case FORUM:
ForumChannelImpl forumChannel = (ForumChannelImpl) channel;
int flags = content.getInt("flags", 0);
// int sortOrder = content.getInt("default_sort_order", ((ForumChannelImpl) channel).getRawSortOrder());
EmojiUnion defaultReaction = content.optObject("default_reaction_emoji")
.map(json -> EntityBuilder.createEmoji(json, "emoji_name", "emoji_id"))
.orElse(null);
int oldFlags = forumChannel.getRawFlags();
// int oldSortOrder = forumChannel.getRawSortOrder();
EmojiUnion oldDefaultReaction = forumChannel.getDefaultReaction();
content.optArray("available_tags").ifPresent(
array -> handleTagsUpdate(forumChannel, array)
);
if (oldFlags != flags)
{
forumChannel.setFlags(flags);
getJDA().handleEvent(
new ChannelUpdateFlagsEvent(
getJDA(), responseNumber,
forumChannel, ChannelFlag.fromRaw(oldFlags), ChannelFlag.fromRaw(flags)));
}
// if (oldSortOrder != sortOrder)
// {
// forumChannel.setDefaultSortOrder(sortOrder);
// getJDA().handleEvent(
// new ChannelUpdateDefaultSortOrderEvent(
// getJDA(), responseNumber,
// forumChannel, ForumChannel.SortOrder.fromKey(oldSortOrder), ForumChannel.SortOrder.fromKey(sortOrder)));
// }
if (!Objects.equals(oldDefaultReaction, defaultReaction))
{
forumChannel.setDefaultReaction(content.optObject("default_reaction_emoji").orElse(null));
getJDA().handleEvent(
new ChannelUpdateDefaultReactionEvent(
getJDA(), responseNumber,
forumChannel, oldDefaultReaction, defaultReaction));
}
break;
case VOICE:
VoiceChannelImpl voiceChannel = (VoiceChannelImpl) channel;
int userLimit = content.getInt("user_limit");
int oldLimit = voiceChannel.getUserLimit();
if (oldLimit != userLimit)
{
voiceChannel.setUserLimit(userLimit);
getJDA().handleEvent(
new ChannelUpdateUserLimitEvent(
getJDA(), responseNumber,
voiceChannel, oldLimit, userLimit));
}
break;
case TEXT:
case NEWS:
case STAGE:
case CATEGORY:
break;
default:
WebSocketClient.LOG.debug("CHANNEL_UPDATE provided an unrecognized channel type JSON: {}", content);
}
DataArray permOverwrites = content.getArray("permission_overwrites");
applyPermissions((IPermissionContainerMixin<?>) channel, permOverwrites);
boolean hasAccessToChannel = channel.getGuild().getSelfMember().hasPermission(channel, Permission.VIEW_CHANNEL);
if (channel instanceof IThreadContainer && !hasAccessToChannel)
handleHideChildThreads((IThreadContainer) channel);
return null;
}
private AbstractGuildChannelImpl<?> handleChannelTypeChange(AbstractGuildChannelImpl<?> channel, DataObject content, ChannelType newChannelType)
{
if (channel.getType() == newChannelType)
return channel;
EntityBuilder builder = getJDA().getEntityBuilder();
GuildImpl guild = channel.getGuild();
if (newChannelType == ChannelType.TEXT)
{
//This assumes that if we're moving to a TextChannel that we're transitioning from a NewsChannel
NewsChannel newsChannel = (NewsChannel) channel;
getJDA().getNewsChannelView().remove(newsChannel.getIdLong());
guild.getNewsChannelView().remove(newsChannel.getIdLong());
TextChannelImpl textChannel = (TextChannelImpl) builder.createTextChannel(guild, content, guild.getIdLong());
//CHANNEL_UPDATE doesn't track last_message_id, so make sure to copy it over.
textChannel.setLatestMessageIdLong(newsChannel.getLatestMessageIdLong());
getJDA().handleEvent(
new ChannelUpdateTypeEvent(
getJDA(), responseNumber,
textChannel, ChannelType.NEWS, ChannelType.TEXT));
return textChannel;
}
if (newChannelType == ChannelType.NEWS)
{
//This assumes that if we're moving to a NewsChannel that we're transitioning from a TextChannel
TextChannel textChannel = (TextChannel) channel;
getJDA().getTextChannelsView().remove(textChannel.getIdLong());
guild.getTextChannelsView().remove(textChannel.getIdLong());
NewsChannelImpl newsChannel = (NewsChannelImpl) builder.createNewsChannel(guild, content, guild.getIdLong());
//CHANNEL_UPDATE doesn't track last_message_id, so make sure to copy it over.
newsChannel.setLatestMessageIdLong(textChannel.getLatestMessageIdLong());
getJDA().handleEvent(
new ChannelUpdateTypeEvent(
getJDA(), responseNumber,
newsChannel, ChannelType.TEXT, ChannelType.NEWS));
return newsChannel;
}
return channel;
}
private void applyPermissions(IPermissionContainerMixin<?> channel, DataArray permOverwrites)
{
TLongObjectMap<PermissionOverride> currentOverrides = new TLongObjectHashMap<>(channel.getPermissionOverrideMap());
List<IPermissionHolder> changed = new ArrayList<>(currentOverrides.size());
Guild guild = channel.getGuild();
for (int i = 0; i < permOverwrites.length(); i++)
{
DataObject overrideJson = permOverwrites.getObject(i);
long id = overrideJson.getUnsignedLong("id", 0);
if (handlePermissionOverride(currentOverrides.remove(id), overrideJson, id, channel))
addPermissionHolder(changed, guild, id);
}
currentOverrides.forEachValue(override -> {
channel.getPermissionOverrideMap().remove(override.getIdLong());
addPermissionHolder(changed, guild, override.getIdLong());
api.handleEvent(
new PermissionOverrideDeleteEvent(
api, responseNumber,
channel, override));
return true;
});
}
private void addPermissionHolder(List<IPermissionHolder> changed, Guild guild, long id)
{
IPermissionHolder holder = guild.getRoleById(id);
if (holder == null)
holder = guild.getMemberById(id);
if (holder != null) // Members might not be cached
changed.add(holder);
}
// True => override status changed (created/deleted/updated)
// False => nothing changed, ignore
private boolean handlePermissionOverride(PermissionOverride currentOverride, DataObject override, long overrideId, IPermissionContainerMixin<?> channel)
{
final long allow = override.getLong("allow");
final long deny = override.getLong("deny");
final int type = override.getInt("type");
final boolean isRole = type == 0;
if (!isRole)
{
if (type != 1)
{
EntityBuilder.LOG.debug("Ignoring unknown invite of type '{}'. JSON: {}", type, override);
return false;
}
else if (!api.isCacheFlagSet(CacheFlag.MEMBER_OVERRIDES) && overrideId != api.getSelfUser().getIdLong())
{
return false;
}
}
if (currentOverride != null) // Permissions were updated?
{
long oldAllow = currentOverride.getAllowedRaw();
long oldDeny = currentOverride.getDeniedRaw();
PermissionOverrideImpl impl = (PermissionOverrideImpl) currentOverride;
if (oldAllow == allow && oldDeny == deny)
return false;
if (overrideId == channel.getGuild().getIdLong() && (allow | deny) == 0L)
{
// We delete empty overrides for the @everyone role because that's what the client also does, otherwise our sync checks don't work!
channel.getPermissionOverrideMap().remove(overrideId);
api.handleEvent(
new PermissionOverrideDeleteEvent(
api, responseNumber,
channel, currentOverride));
return true;
}
impl.setAllow(allow);
impl.setDeny(deny);
api.handleEvent(
new PermissionOverrideUpdateEvent(
api, responseNumber,
channel, currentOverride, oldAllow, oldDeny));
}
else // New override?
{
// Empty @everyone overrides should be treated as not existing at all
if (overrideId == channel.getGuild().getIdLong() && (allow | deny) == 0L)
return false;
PermissionOverrideImpl impl;
currentOverride = impl = new PermissionOverrideImpl(channel, overrideId, isRole);
impl.setAllow(allow);
impl.setDeny(deny);
channel.getPermissionOverrideMap().put(overrideId, currentOverride);
api.handleEvent(
new PermissionOverrideCreateEvent(
api, responseNumber,
channel, currentOverride));
}
return true;
}
private void handleHideChildThreads(IThreadContainer channel)
{
List<ThreadChannel> threads = channel.getThreadChannels();
if (threads.isEmpty())
return;
for (ThreadChannel thread : threads)
{
GuildImpl guild = (GuildImpl) channel.getGuild();
SnowflakeCacheViewImpl<ThreadChannel>
guildThreadView = guild.getThreadChannelsView(),
threadView = getJDA().getThreadChannelsView();
try (
UnlockHook vlock = guildThreadView.writeLock();
UnlockHook jlock = threadView.writeLock())
{
//TODO-threads: When we figure out how member chunking is going to work for thread related members
// we may need to revisit this to ensure they kicked out of the cache if needed.
threadView.getMap().remove(thread.getIdLong());
guildThreadView.getMap().remove(thread.getIdLong());
}
}
//Fire these events outside the write locks
for (ThreadChannel thread : threads)
{
api.handleEvent(new ThreadHiddenEvent(api, responseNumber, thread));
}
}
private void handleTagsUpdate(ForumChannelImpl channel, DataArray tags)
{
if (!api.isCacheFlagSet(CacheFlag.FORUM_TAGS))
return;
EntityBuilder builder = api.getEntityBuilder();
SortedSnowflakeCacheViewImpl<ForumTag> view = channel.getAvailableTagCache();
try (UnlockHook hook = view.writeLock())
{
TLongObjectMap<ForumTag> cache = view.getMap();
TLongSet removedTags = new TLongHashSet(cache.keySet());
for (int i = 0; i < tags.length(); i++)
{
DataObject tagJson = tags.getObject(i);
long id = tagJson.getUnsignedLong("id");
if (removedTags.remove(id))
{
ForumTagImpl impl = (ForumTagImpl) cache.get(id);
if (impl == null)
continue;
String name = tagJson.getString("name");
boolean moderated = tagJson.getBoolean("moderated");
String oldName = impl.getName();
EmojiUnion oldEmoji = impl.getEmoji();
impl.setEmoji(tagJson);
impl.setPosition(i);
if (!Objects.equals(oldEmoji, impl.getEmoji()))
{
api.handleEvent(new ForumTagUpdateEmojiEvent(api, responseNumber, channel, impl, oldEmoji));
}
if (!name.equals(oldName))
{
impl.setName(name);
api.handleEvent(new ForumTagUpdateNameEvent(api, responseNumber, channel, impl, oldName));
}
if (moderated != impl.isModerated())
{
impl.setModerated(moderated);
api.handleEvent(new ForumTagUpdateModeratedEvent(api, responseNumber, channel, impl, moderated));
}
}
else
{
ForumTag tag = builder.createForumTag(channel, tagJson, i);
cache.put(id, tag);
api.handleEvent(new ForumTagAddEvent(api, responseNumber, channel, tag));
}
}
removedTags.forEach(id -> {
ForumTag tag = cache.remove(id);
if (tag != null)
api.handleEvent(new ForumTagRemoveEvent(api, responseNumber, channel, tag));
return true;
});
}
}
private void handleTopic(ITopicChannelMixin<?> channel, String topic)
{
String oldTopic = channel.getTopic();
if (Objects.equals(oldTopic, topic))
return;
channel.setTopic(topic);
api.handleEvent(
new ChannelUpdateTopicEvent(
api, responseNumber,
channel, oldTopic, topic));
}
private void handleSlowmode(ISlowmodeChannelMixin<?> channel, int slowmode)
{
int oldSlowmode = channel.getSlowmode();
if (oldSlowmode == slowmode)
return;
channel.setSlowmode(slowmode);
api.handleEvent(
new ChannelUpdateSlowmodeEvent(
api, responseNumber,
channel, oldSlowmode, slowmode));
}
private void handleNsfw(IAgeRestrictedChannelMixin<?> channel, boolean nsfw)
{
boolean oldNsfw = channel.isNSFW();
if (oldNsfw == nsfw)
return;
channel.setNSFW(nsfw);
api.handleEvent(
new ChannelUpdateNSFWEvent(
api, responseNumber,
channel, oldNsfw, nsfw));
}
private void handleParentCategory(ICategorizableChannelMixin<?> channel, long parentId)
{
long oldParentId = channel.getParentCategoryIdLong();
if (oldParentId == parentId)
return;
Category oldParent = channel.getParentCategory();
channel.setParentCategory(parentId);
Category newParent = channel.getParentCategory();
api.handleEvent(
new ChannelUpdateParentEvent(
api, responseNumber,
channel, oldParent, newParent));
}
private void handlePosition(IPositionableChannelMixin<?> channel, int position)
{
int oldPosition = channel.getPositionRaw();
if (oldPosition == position)
return;
channel.setPosition(position);
api.handleEvent(
new ChannelUpdatePositionEvent(
api, responseNumber,
channel, oldPosition, position));
}
private void handleThreadContainer(IThreadContainerMixin<?> channel, DataObject content)
{
int oldDefaultThreadSlowmode = channel.getDefaultThreadSlowmode();
int defaultThreadSlowmode = content.getInt("default_thread_rate_limit_per_user", 0);
if (oldDefaultThreadSlowmode != defaultThreadSlowmode)
{
channel.setDefaultThreadSlowmode(defaultThreadSlowmode);
api.handleEvent(
new ChannelUpdateDefaultThreadSlowmodeEvent(
api, responseNumber,
channel, oldDefaultThreadSlowmode, defaultThreadSlowmode));
}
}
private void handleAudioChannel(AudioChannelMixin<?> channel, DataObject content)
{
int oldBitrate = channel.getBitrate();
int bitrate = content.getInt("bitrate");
if (oldBitrate != bitrate)
{
channel.setBitrate(bitrate);
api.handleEvent(
new ChannelUpdateBitrateEvent(
api, responseNumber,
channel, oldBitrate, bitrate));
}
String oldRegion = channel.getRegionRaw();
String regionRaw = content.getString("rtc_region", null);
if (!Objects.equals(oldRegion, regionRaw))
{
channel.setRegion(regionRaw);
api.handleEvent(
new ChannelUpdateRegionEvent(
api, responseNumber,
channel, Region.fromKey(oldRegion), Region.fromKey(regionRaw)));
}
}
}