/
GuildSetupNode.java
463 lines (419 loc) · 15.6 KB
/
GuildSetupNode.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
/*
* 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.iterator.TLongIterator;
import gnu.trove.iterator.TLongObjectIterator;
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.audio.hooks.ConnectionListener;
import net.dv8tion.jda.api.audio.hooks.ConnectionStatus;
import net.dv8tion.jda.api.entities.channel.concrete.VoiceChannel;
import net.dv8tion.jda.api.events.guild.GuildAvailableEvent;
import net.dv8tion.jda.api.events.guild.GuildJoinEvent;
import net.dv8tion.jda.api.events.guild.GuildReadyEvent;
import net.dv8tion.jda.api.events.guild.UnavailableGuildJoinedEvent;
import net.dv8tion.jda.api.managers.AudioManager;
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.GuildImpl;
import net.dv8tion.jda.internal.managers.AudioManagerImpl;
import net.dv8tion.jda.internal.utils.UnlockHook;
import net.dv8tion.jda.internal.utils.cache.AbstractCacheView;
import javax.annotation.Nullable;
import java.util.LinkedList;
import java.util.List;
import java.util.Optional;
public class GuildSetupNode
{
private final long id;
private final GuildSetupController controller;
private final List<DataObject> cachedEvents = new LinkedList<>();
private TLongObjectMap<DataObject> members;
private TLongSet removedMembers;
private DataObject partialGuild;
private int expectedMemberCount = 1;
boolean requestedChunk;
final Type type;
boolean firedUnavailableJoin = false;
boolean markedUnavailable = false;
GuildSetupController.Status status = GuildSetupController.Status.INIT;
GuildSetupNode(long id, GuildSetupController controller, Type type)
{
this.id = id;
this.controller = controller;
this.type = type;
}
public long getIdLong()
{
return id;
}
public String getId()
{
return Long.toUnsignedString(id);
}
public GuildSetupController.Status getStatus()
{
return status;
}
@Nullable
public DataObject getGuildPayload()
{
return partialGuild;
}
public int getExpectedMemberCount()
{
return expectedMemberCount;
}
public int getCurrentMemberCount()
{
TLongHashSet knownMembers = new TLongHashSet(members.keySet());
knownMembers.removeAll(removedMembers);
return knownMembers.size();
}
public Type getType()
{
return type;
}
public boolean isJoin()
{
return type == Type.JOIN;
}
public boolean isMarkedUnavailable()
{
return markedUnavailable;
}
public boolean requestedChunks()
{
return requestedChunk;
}
public boolean containsMember(long userId)
{
if (members == null || members.isEmpty())
return false;
return members.containsKey(userId);
}
@Override
public String toString()
{
return "GuildSetupNode[" + id + "|" + status + ']' +
'{' +
"expectedMemberCount=" + expectedMemberCount + ", " +
"requestedChunk=" + requestedChunk + ", " +
"type=" + type + ", " +
"markedUnavailable=" + markedUnavailable +
'}';
}
@Override
public int hashCode()
{
return Long.hashCode(id);
}
@Override
public boolean equals(Object obj)
{
if (!(obj instanceof GuildSetupNode))
return false;
GuildSetupNode node = (GuildSetupNode) obj;
return node.id == id;
}
private GuildSetupController getController()
{
return controller;
}
void updateStatus(GuildSetupController.Status status)
{
if (status == this.status)
return;
try
{
getController().listener.onStatusChange(id, this.status, status);
}
catch (Exception ex)
{
GuildSetupController.log.error("Uncaught exception in status listener", ex);
}
this.status = status;
}
void reset()
{
updateStatus(GuildSetupController.Status.UNAVAILABLE);
expectedMemberCount = 1;
partialGuild = null;
requestedChunk = false;
if (members != null)
members.clear();
if (removedMembers != null)
removedMembers.clear();
cachedEvents.clear();
}
void handleReady(DataObject obj) {}
void handleCreate(DataObject obj)
{
if (partialGuild == null)
{
partialGuild = obj;
}
else
{
for (String key : obj.keys())
{
partialGuild.put(key, obj.opt(key).orElse(null));
}
}
boolean unavailable = partialGuild.getBoolean("unavailable");
boolean wasMarkedUnavailable = this.markedUnavailable;
this.markedUnavailable = unavailable;
if (unavailable)
{
if (!firedUnavailableJoin && isJoin())
{
firedUnavailableJoin = true;
JDAImpl api = getController().getJDA();
api.handleEvent(new UnavailableGuildJoinedEvent(api, api.getResponseTotal(), id));
}
return;
}
ensureMembers();
}
void handleSync(DataObject obj)
{
if (partialGuild == null)
{
//In this case we received a GUILD_DELETE with unavailable = true while syncing
// however we have to wait for the GUILD_CREATE with unavailable = false before
// requesting new chunks
GuildSetupController.log.debug("Dropping sync update due to unavailable guild");
return;
}
for (String key : obj.keys())
{
partialGuild.put(key, obj.opt(key).orElse(null));
}
ensureMembers();
}
boolean handleMemberChunk(boolean last, DataArray arr)
{
if (partialGuild == null)
{
//In this case we received a GUILD_DELETE with unavailable = true while chunking
// however we have to wait for the GUILD_CREATE with unavailable = false before
// requesting new chunks
GuildSetupController.log.debug("Dropping member chunk due to unavailable guild");
return true;
}
for (int index = 0; index < arr.length(); index++)
{
DataObject obj = arr.getObject(index);
long id = obj.getObject("user").getLong("id");
members.put(id, obj);
}
if (last || members.size() >= expectedMemberCount || !getController().getJDA().chunkGuild(id))
{
completeSetup();
return false;
}
return true;
}
void handleAddMember(DataObject member)
{
if (members == null || removedMembers == null)
return;
expectedMemberCount++;
long userId = member.getObject("user").getLong("id");
members.put(userId, member);
removedMembers.remove(userId);
}
void handleRemoveMember(DataObject member)
{
if (members == null || removedMembers == null)
return;
expectedMemberCount--;
long userId = member.getObject("user").getLong("id");
members.remove(userId);
removedMembers.add(userId);
EventCache eventCache = getController().getJDA().getEventCache();
if (!getController().containsMember(userId, this)) // if no other setup node contains this userId we clear it here
eventCache.clear(EventCache.Type.USER, userId);
}
void cacheEvent(DataObject event)
{
GuildSetupController.log.trace("Caching {} event during init. GuildId: {}", event.getString("t"), id);
cachedEvents.add(event);
//Check if more than 2000 events cached - suspicious
// Print warning every 1000 events
int cacheSize = cachedEvents.size();
if (cacheSize >= 2000 && cacheSize % 1000 == 0)
{
GuildSetupController controller = getController();
GuildSetupController.log.warn(
"Accumulating suspicious amounts of cached events during guild setup, " +
"something might be wrong. Cached: {} Members: {}/{} Status: {} GuildId: {} Incomplete: {}/{}",
cacheSize, getCurrentMemberCount(), getExpectedMemberCount(),
status, id, controller.getChunkingCount(), controller.getIncompleteCount());
if (status == GuildSetupController.Status.CHUNKING)
{
GuildSetupController.log.debug("Forcing new chunk request for guild: {}", id);
controller.sendChunkRequest(id);
}
}
}
void cleanup()
{
updateStatus(GuildSetupController.Status.REMOVED);
EventCache eventCache = getController().getJDA().getEventCache();
eventCache.clear(EventCache.Type.GUILD, id);
if (partialGuild == null)
return;
Optional<DataArray> channels = partialGuild.optArray("channels");
Optional<DataArray> roles = partialGuild.optArray("roles");
channels.ifPresent((arr) -> {
for (int i = 0; i < arr.length(); i++)
{
DataObject json = arr.getObject(i);
long id = json.getLong("id");
eventCache.clear(EventCache.Type.CHANNEL, id);
}
});
roles.ifPresent((arr) -> {
for (int i = 0; i < arr.length(); i++)
{
DataObject json = arr.getObject(i);
long id = json.getLong("id");
eventCache.clear(EventCache.Type.ROLE, id);
}
});
if (members != null)
{
for (TLongObjectIterator<DataObject> it = members.iterator(); it.hasNext();)
{
it.advance();
long userId = it.key();
if (!getController().containsMember(userId, this)) // if no other setup node contains this userId we clear it here
eventCache.clear(EventCache.Type.USER, userId);
}
}
}
private void completeSetup()
{
updateStatus(GuildSetupController.Status.BUILDING);
JDAImpl api = getController().getJDA();
for (TLongIterator it = removedMembers.iterator(); it.hasNext(); )
members.remove(it.next());
removedMembers.clear();
GuildImpl guild = api.getEntityBuilder().createGuild(id, partialGuild, members, expectedMemberCount);
updateAudioManagerReference(guild);
switch (type)
{
case AVAILABLE:
api.handleEvent(new GuildAvailableEvent(api, api.getResponseTotal(), guild));
getController().remove(id);
break;
case JOIN:
api.handleEvent(new GuildJoinEvent(api, api.getResponseTotal(), guild));
if (requestedChunk)
getController().ready(id);
else
getController().remove(id);
break;
default:
api.handleEvent(new GuildReadyEvent(api, api.getResponseTotal(), guild));
getController().ready(id);
break;
}
updateStatus(GuildSetupController.Status.READY);
GuildSetupController.log.debug("Finished setup for guild {} firing cached events {}", id, cachedEvents.size());
api.getClient().handle(cachedEvents);
api.getEventCache().playbackCache(EventCache.Type.GUILD, id);
}
private void ensureMembers()
{
expectedMemberCount = partialGuild.getInt("member_count");
members = new TLongObjectHashMap<>(expectedMemberCount);
removedMembers = new TLongHashSet();
DataArray memberArray = partialGuild.getArray("members");
if (!getController().getJDA().chunkGuild(id))
{
handleMemberChunk(true, memberArray);
}
else if (memberArray.length() < expectedMemberCount && !requestedChunk)
{
updateStatus(GuildSetupController.Status.CHUNKING);
getController().addGuildForChunking(id, isJoin());
requestedChunk = true;
}
else if (handleMemberChunk(false, memberArray) && !requestedChunk)
{
// Discord sent us enough members to satisfy the member_count
// but we found duplicates and still didn't reach enough to satisfy the count
// in this case we try to do chunking instead
// This is caused by lazy guilds and intended behavior according to jake
GuildSetupController.log.trace(
"Received suspicious members with a guild payload. Attempting to chunk. " +
"member_count: {} members: {} actual_members: {} guild_id: {}",
expectedMemberCount, memberArray.length(), members.size(), id);
members.clear();
updateStatus(GuildSetupController.Status.CHUNKING);
getController().addGuildForChunking(id, isJoin());
requestedChunk = true;
}
}
private void updateAudioManagerReference(GuildImpl guild)
{
JDAImpl api = getController().getJDA();
AbstractCacheView<AudioManager> managerView = api.getAudioManagersView();
try (UnlockHook hook = managerView.writeLock())
{
TLongObjectMap<AudioManager> audioManagerMap = managerView.getMap();
AudioManagerImpl mng = (AudioManagerImpl) audioManagerMap.get(id);
if (mng == null)
return;
ConnectionListener listener = mng.getConnectionListener();
final AudioManagerImpl newMng = new AudioManagerImpl(guild);
newMng.setSelfMuted(mng.isSelfMuted());
newMng.setSelfDeafened(mng.isSelfDeafened());
newMng.setQueueTimeout(mng.getConnectTimeout());
newMng.setSendingHandler(mng.getSendingHandler());
newMng.setReceivingHandler(mng.getReceivingHandler());
newMng.setConnectionListener(listener);
newMng.setAutoReconnect(mng.isAutoReconnect());
if (mng.isConnected())
{
final long channelId = mng.getConnectedChannel().getIdLong();
final VoiceChannel channel = api.getVoiceChannelById(channelId);
if (channel != null)
{
if (mng.isConnected())
mng.closeAudioConnection(ConnectionStatus.ERROR_CANNOT_RESUME);
}
else
{
//The voice channel is not cached. It was probably deleted.
api.getClient().removeAudioConnection(id);
if (listener != null)
listener.onStatusChange(ConnectionStatus.DISCONNECTED_CHANNEL_DELETED);
}
}
audioManagerMap.put(id, newMng);
}
}
public enum Type
{
INIT, JOIN, AVAILABLE
}
}