mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-23 21:52:45 -05:00
Remix — the complete rewrite
Upgrades the bot from fluxerjs 2.2 to 3.0 and restructures everything into a layered architecture (~28K lines): Dependencies: - @fluxerjs/core, util, voice: ^2.2.0 -> ^3.0.0 (typed events, PartialMessage payloads, camelCase API) - @fluxerjs/sharding ^3.0.0 added — built-in sharding mode (shard.mjs, one process per shard) - @discordjs/opus dropped — opusscript + prism-media cover encoding Architecture: - commands: every command split into submodules (player, lastfm, settings, debug) with a shared CommandBuilder/Loader/Handler core - ui: embeds, paginators, help command, permission checks - voice: gateway event routing, rejoin/247 boot recovery, state resolver - music: player split into Queue/Search/Playback/Display mixins, stream pipeline + WebM/Opus muxer (no FFmpeg needed) - dashboard: Redis pub/sub, RPC handlers, serializers - db: MySQL manager + per-guild settings - services: LastFm manager split into focused mixins - utils: sharding, 24/7 helpers, API client Runtime fixes over v2: - Redis v5 reconnect: capped numeric backoff (0.5s ramp to 15s), never exhausts, auto-recovers when the server comes back - Redis main/subscriber clients connect in parallel; clean shutdown - Logger storm guard: identical error/warn lines deduped in a 60s window - self-deaf fix on voice join - config example uses redis://127.0.0.1 (avoids IPv6 ENETUNREACH) Housekeeping: dead code removed (Tuna.mjs + follow-redirects dep), .gitignore added (config.json, .env, node_modules, runtime state).
This commit is contained in:
1 parent
0f085a6ae4
commit
253d11cd57
150 files changed
+19935
-16894
No files matched your search
@@ -0,0 +1,589 @@
|
||||
/** @module src/voice/VoiceStateCache */
|
||||
|
||||
import { logger } from "../core/Logger.mjs";
|
||||
import { cleanId } from "../utils/Utils.mjs";
|
||||
|
||||
/**
|
||||
* LRU-backed cache mapping users (and bots) to their voice-channel locations.
|
||||
* Supports O(1) lookups by guild+user or guild+channel and implements the
|
||||
* Map-like interface (`get`, `set`, `delete`, `has`, `forEach`, `entries`, `keys`, `values`).
|
||||
* @class
|
||||
*/
|
||||
export class VoiceStateCache {
|
||||
/**
|
||||
* @param {object} [opts]
|
||||
* @param {number} [opts.maxUsers=50000] - Max cached human user entries.
|
||||
* @param {number} [opts.maxBots=10000] - Max cached bot user entries.
|
||||
*/
|
||||
constructor(opts = {}) {
|
||||
this.userLocations = new Map();
|
||||
this.channelMembers = new Map();
|
||||
|
||||
this.botLocations = new Map();
|
||||
this.botChannelMembers = new Map();
|
||||
|
||||
this._maxUsers = opts.maxUsers ?? 50_000;
|
||||
this._maxBots = opts.maxBots ?? 10_000;
|
||||
this._lruUserKeys = [];
|
||||
this._lruBotKeys = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a composite user key for storage.
|
||||
* @param {string} guildId
|
||||
* @param {string} userId
|
||||
* @returns {string}
|
||||
*/
|
||||
static userKey(guildId, userId) {
|
||||
return `${cleanId(guildId)}:${cleanId(userId)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a composite channel key for storage.
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
* @returns {string}
|
||||
*/
|
||||
static channelKey(guildId, channelId) {
|
||||
return `${cleanId(guildId)}:${cleanId(channelId)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update (or remove) a user's voice-channel location in the cache.
|
||||
* When `channelId` is provided the user is added; when `null`/falsy the user is removed.
|
||||
* Automatically evicts LRU entries when capacity is exceeded.
|
||||
* @param {{ guildId: string, userId: string, channelId: string|null, isBot?: boolean }} opts
|
||||
*/
|
||||
updateUser({ guildId, userId, channelId, isBot = false }) {
|
||||
const cleanGuild = cleanId(guildId);
|
||||
const cleanUser = cleanId(userId);
|
||||
const cleanChannel = channelId ? cleanId(channelId) : null;
|
||||
if (!cleanGuild || !cleanUser) return;
|
||||
|
||||
const locations = isBot ? this.botLocations : this.userLocations;
|
||||
const channelIdx = isBot ? this.botChannelMembers : this.channelMembers;
|
||||
const maxEntries = isBot ? this._maxBots : this._maxUsers;
|
||||
const lruKeys = isBot ? this._lruBotKeys : this._lruUserKeys;
|
||||
const uKey = VoiceStateCache.userKey(cleanGuild, cleanUser);
|
||||
|
||||
const prev = locations.get(uKey);
|
||||
if (prev) {
|
||||
const prevCKey = VoiceStateCache.channelKey(prev.guildId, prev.channelId);
|
||||
const prevSet = channelIdx.get(prevCKey);
|
||||
if (prevSet) {
|
||||
prevSet.delete(cleanUser);
|
||||
if (prevSet.size === 0) channelIdx.delete(prevCKey);
|
||||
}
|
||||
}
|
||||
|
||||
if (cleanChannel) {
|
||||
const cKey = VoiceStateCache.channelKey(cleanGuild, cleanChannel);
|
||||
let set = channelIdx.get(cKey);
|
||||
if (!set) { set = new Set(); channelIdx.set(cKey, set); }
|
||||
set.add(cleanUser);
|
||||
|
||||
locations.delete(uKey);
|
||||
locations.set(uKey, { channelId: cleanChannel, guildId: cleanGuild, userId: cleanUser });
|
||||
|
||||
const lruIdx = lruKeys.indexOf(uKey);
|
||||
if (lruIdx !== -1) lruKeys.splice(lruIdx, 1);
|
||||
lruKeys.push(uKey);
|
||||
|
||||
while (locations.size > maxEntries) {
|
||||
let evicted = false;
|
||||
for (let i = 0; i < lruKeys.length; i++) {
|
||||
const evictKey = lruKeys[i];
|
||||
if (evictKey === uKey) continue;
|
||||
|
||||
const evictEntry = locations.get(evictKey);
|
||||
if (evictEntry) {
|
||||
const evictCKey = VoiceStateCache.channelKey(evictEntry.guildId, evictEntry.channelId);
|
||||
const evictSet = channelIdx.get(evictCKey);
|
||||
if (evictSet) {
|
||||
evictSet.delete(evictEntry.userId);
|
||||
if (evictSet.size === 0) channelIdx.delete(evictCKey);
|
||||
}
|
||||
locations.delete(evictKey);
|
||||
}
|
||||
lruKeys.splice(i, 1);
|
||||
evicted = true;
|
||||
break;
|
||||
}
|
||||
if (!evicted) break;
|
||||
}
|
||||
} else {
|
||||
locations.delete(uKey);
|
||||
const idx = lruKeys.indexOf(uKey);
|
||||
if (idx !== -1) lruKeys.splice(idx, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether any human users are cached in the given channel.
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
* @returns {boolean}
|
||||
*/
|
||||
hasHumansInChannel(guildId, channelId) {
|
||||
const cKey = VoiceStateCache.channelKey(guildId, channelId);
|
||||
const set = this.channelMembers.get(cKey);
|
||||
return set ? set.size > 0 : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the count of human users cached in the given channel.
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
* @returns {number}
|
||||
*/
|
||||
getHumanCount(guildId, channelId) {
|
||||
const cKey = VoiceStateCache.channelKey(guildId, channelId);
|
||||
const set = this.channelMembers.get(cKey);
|
||||
return set ? set.size : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the array of human user IDs cached in the given channel.
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
* @returns {string[]}
|
||||
*/
|
||||
getHumansInChannel(guildId, channelId) {
|
||||
const cKey = VoiceStateCache.channelKey(guildId, channelId);
|
||||
const set = this.channelMembers.get(cKey);
|
||||
return set ? [...set] : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the channel ID a human user is currently in, or `null`.
|
||||
* @param {string} guildId
|
||||
* @param {string} userId
|
||||
* @returns {string|null}
|
||||
*/
|
||||
getUserChannel(guildId, userId) {
|
||||
const uKey = VoiceStateCache.userKey(guildId, userId);
|
||||
const loc = this.userLocations.get(uKey);
|
||||
return loc ? loc.channelId : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a human user exists in the cache for the given guild.
|
||||
* @param {string} guildId
|
||||
* @param {string} userId
|
||||
* @returns {boolean}
|
||||
*/
|
||||
hasUser(guildId, userId) {
|
||||
return this.userLocations.has(VoiceStateCache.userKey(guildId, userId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the full location record for a human user.
|
||||
* @param {string} guildId
|
||||
* @param {string} userId
|
||||
* @returns {{ channelId: string, guildId: string, userId: string }|undefined}
|
||||
*/
|
||||
getUserLocation(guildId, userId) {
|
||||
return this.userLocations.get(VoiceStateCache.userKey(guildId, userId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Seed a user into the cache only if not already present.
|
||||
* @param {string} guildId
|
||||
* @param {string} userId
|
||||
* @param {string} channelId
|
||||
* @param {boolean} [isBot=false]
|
||||
*/
|
||||
seedUser(guildId, userId, channelId, isBot = false) {
|
||||
const uKey = VoiceStateCache.userKey(guildId, userId);
|
||||
const locations = isBot ? this.botLocations : this.userLocations;
|
||||
if (locations.has(uKey)) return;
|
||||
this.updateUser({ guildId, userId, channelId, isBot });
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all cached entries (human and bot) for a given guild.
|
||||
* @param {string} guildId
|
||||
*/
|
||||
removeGuild(guildId) {
|
||||
const cleanGuild = cleanId(guildId);
|
||||
const prefix = cleanGuild + ":";
|
||||
|
||||
|
||||
const userKeysToRemove = [];
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
if (uKey.startsWith(prefix)) userKeysToRemove.push(uKey);
|
||||
}
|
||||
for (const uKey of userKeysToRemove) {
|
||||
const loc = this.userLocations.get(uKey);
|
||||
if (loc) {
|
||||
const cKey = VoiceStateCache.channelKey(loc.guildId, loc.channelId);
|
||||
const set = this.channelMembers.get(cKey);
|
||||
if (set) { set.delete(loc.userId); if (set.size === 0) this.channelMembers.delete(cKey); }
|
||||
}
|
||||
this.userLocations.delete(uKey);
|
||||
}
|
||||
const channelKeysToRemove = [];
|
||||
for (const [cKey] of this.channelMembers) {
|
||||
if (cKey.startsWith(prefix)) channelKeysToRemove.push(cKey);
|
||||
}
|
||||
for (const cKey of channelKeysToRemove) this.channelMembers.delete(cKey);
|
||||
this._lruUserKeys = this._lruUserKeys.filter(k => !k.startsWith(prefix));
|
||||
|
||||
const botKeysToRemove = [];
|
||||
for (const [uKey, loc] of this.botLocations) {
|
||||
if (uKey.startsWith(prefix)) botKeysToRemove.push(uKey);
|
||||
}
|
||||
for (const uKey of botKeysToRemove) {
|
||||
const loc = this.botLocations.get(uKey);
|
||||
if (loc) {
|
||||
const cKey = VoiceStateCache.channelKey(loc.guildId, loc.channelId);
|
||||
const set = this.botChannelMembers.get(cKey);
|
||||
if (set) { set.delete(loc.userId); if (set.size === 0) this.botChannelMembers.delete(cKey); }
|
||||
}
|
||||
this.botLocations.delete(uKey);
|
||||
}
|
||||
const botChannelKeysToRemove = [];
|
||||
for (const [cKey] of this.botChannelMembers) {
|
||||
if (cKey.startsWith(prefix)) botChannelKeysToRemove.push(cKey);
|
||||
}
|
||||
for (const cKey of botChannelKeysToRemove) this.botChannelMembers.delete(cKey);
|
||||
this._lruBotKeys = this._lruBotKeys.filter(k => !k.startsWith(prefix));
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all cached entries (human and bot) for a specific channel.
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
*/
|
||||
removeChannel(guildId, channelId) {
|
||||
const cKey = VoiceStateCache.channelKey(guildId, channelId);
|
||||
|
||||
const humanSet = this.channelMembers.get(cKey);
|
||||
if (humanSet) {
|
||||
for (const userId of humanSet) {
|
||||
const uKey = VoiceStateCache.userKey(guildId, userId);
|
||||
const loc = this.userLocations.get(uKey);
|
||||
if (loc && loc.channelId === cleanId(channelId)) {
|
||||
this.userLocations.delete(uKey);
|
||||
}
|
||||
}
|
||||
this.channelMembers.delete(cKey);
|
||||
}
|
||||
|
||||
const botSet = this.botChannelMembers.get(cKey);
|
||||
if (botSet) {
|
||||
for (const userId of botSet) {
|
||||
const uKey = VoiceStateCache.userKey(guildId, userId);
|
||||
const loc = this.botLocations.get(uKey);
|
||||
if (loc && loc.channelId === cleanId(channelId)) {
|
||||
this.botLocations.delete(uKey);
|
||||
}
|
||||
}
|
||||
this.botChannelMembers.delete(cKey);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove specific users from a guild's cache.
|
||||
* @param {string} guildId
|
||||
* @param {string[]} userIds
|
||||
* @param {boolean} [botsOnly=false] - If `true`, only purge bot entries.
|
||||
*/
|
||||
purgeUsersInGuild(guildId, userIds, botsOnly = false) {
|
||||
const cleanGuild = cleanId(guildId);
|
||||
|
||||
if (!botsOnly) {
|
||||
for (const userId of userIds) {
|
||||
const uKey = VoiceStateCache.userKey(cleanGuild, userId);
|
||||
const loc = this.userLocations.get(uKey);
|
||||
if (loc) {
|
||||
const cKey = VoiceStateCache.channelKey(loc.guildId, loc.channelId);
|
||||
const set = this.channelMembers.get(cKey);
|
||||
if (set) { set.delete(loc.userId); if (set.size === 0) this.channelMembers.delete(cKey); }
|
||||
this.userLocations.delete(uKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const userId of userIds) {
|
||||
const uKey = VoiceStateCache.userKey(cleanGuild, userId);
|
||||
const loc = this.botLocations.get(uKey);
|
||||
if (loc) {
|
||||
const cKey = VoiceStateCache.channelKey(loc.guildId, loc.channelId);
|
||||
const set = this.botChannelMembers.get(cKey);
|
||||
if (set) { set.delete(loc.userId); if (set.size === 0) this.botChannelMembers.delete(cKey); }
|
||||
this.botLocations.delete(uKey);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Number of cached human users.
|
||||
* @type {number}
|
||||
*/
|
||||
get observedVoiceUsersSize() { return this.userLocations.size; }
|
||||
|
||||
/**
|
||||
* Number of cached bot users.
|
||||
* @type {number}
|
||||
*/
|
||||
get observedVoiceBotsSize() { return this.botLocations.size; }
|
||||
|
||||
/**
|
||||
* Iterate over all cached human user entries as `[userId, { channelId, guildId }]` pairs.
|
||||
* @yields {[string, { channelId: string, guildId: string }]}
|
||||
*/
|
||||
*iterateHumanUsers() {
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
yield [loc.userId, { channelId: loc.channelId, guildId: loc.guildId }];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate over all cached bot user entries as `[compositeKey, { channelId, guildId }]` pairs.
|
||||
* @yields {[string, { channelId: string, guildId: string }]}
|
||||
*/
|
||||
*iterateBotUsers() {
|
||||
for (const [uKey, loc] of this.botLocations) {
|
||||
yield [uKey, { channelId: loc.channelId, guildId: loc.guildId }];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the location record for a human user. If `guildId` is omitted, performs a linear scan.
|
||||
* @param {string} userId
|
||||
* @param {string|null} [guildId]
|
||||
* @returns {{ channelId: string, guildId: string }|undefined}
|
||||
*/
|
||||
getHumanUser(userId, guildId = null) {
|
||||
if (guildId) {
|
||||
return this.userLocations.get(VoiceStateCache.userKey(guildId, userId));
|
||||
}
|
||||
const cleanUser = cleanId(userId);
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
if (loc.userId === cleanUser) return { channelId: loc.channelId, guildId: loc.guildId };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a human user's voice location via `updateUser`.
|
||||
* @param {string} userId
|
||||
* @param {{ guildId: string, channelId: string }} info
|
||||
*/
|
||||
setHumanUser(userId, info) {
|
||||
const guildId = info.guildId;
|
||||
const channelId = info.channelId;
|
||||
if (guildId && channelId) {
|
||||
this.updateUser({ guildId, userId, channelId, isBot: false });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a bot user's voice location via `updateUser`.
|
||||
* @param {string} compositeKey - `guildId:userId` composite key.
|
||||
* @param {{ guildId: string, channelId: string }} info
|
||||
*/
|
||||
setBotUser(compositeKey, info) {
|
||||
const guildId = info.guildId;
|
||||
const channelId = info.channelId;
|
||||
const userId = compositeKey.split(":").pop();
|
||||
if (guildId && channelId && userId) {
|
||||
this.updateUser({ guildId, userId, channelId, isBot: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a human user from the cache. If `guildId` is omitted, scans all entries.
|
||||
* @param {string} userId
|
||||
* @param {string|null} [guildId]
|
||||
*/
|
||||
deleteHumanUser(userId, guildId = null) {
|
||||
if (guildId) {
|
||||
this.updateUser({ guildId, userId, channelId: null, isBot: false });
|
||||
} else {
|
||||
const cleanUser = cleanId(userId);
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
if (loc.userId === cleanUser) {
|
||||
this.updateUser({ guildId: loc.guildId, userId: cleanUser, channelId: null, isBot: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a bot user from the cache by its composite key.
|
||||
* @param {string} compositeKey - `guildId:userId` composite key.
|
||||
*/
|
||||
deleteBotUser(compositeKey) {
|
||||
const parts = compositeKey.split(":");
|
||||
const guildId = parts[0];
|
||||
const userId = parts[1];
|
||||
if (guildId && userId) {
|
||||
this.updateUser({ guildId, userId, channelId: null, isBot: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a human user exists in the cache. If `guildId` is omitted, scans all entries.
|
||||
* @param {string} userId
|
||||
* @param {string|null} [guildId]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
hasHumanUser(userId, guildId = null) {
|
||||
if (guildId) {
|
||||
return this.userLocations.has(VoiceStateCache.userKey(guildId, userId));
|
||||
}
|
||||
const cleanUser = cleanId(userId);
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
if (loc.userId === cleanUser) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a bot user exists in the cache by composite key.
|
||||
* @param {string} compositeKey - `guildId:userId` composite key.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
hasBotUser(compositeKey) {
|
||||
return this.botLocations.has(compositeKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implement the iterable protocol over human user entries.
|
||||
* @yields {[string, { channelId: string, guildId: string }]}
|
||||
*/
|
||||
*[Symbol.iterator]() {
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
yield [loc.userId, { channelId: loc.channelId, guildId: loc.guildId }];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Number of cached human users (Map-like `.size`).
|
||||
* @type {number}
|
||||
*/
|
||||
get size() { return this.userLocations.size; }
|
||||
|
||||
/**
|
||||
* Map-like `has` — checks if a human user is cached.
|
||||
* @param {string} userId
|
||||
* @param {string} [guildId]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
has(userId, guildId) {
|
||||
if (guildId !== undefined) {
|
||||
return this.userLocations.has(VoiceStateCache.userKey(guildId, userId));
|
||||
}
|
||||
const cleanUser = cleanId(userId);
|
||||
for (const [, loc] of this.userLocations) {
|
||||
if (loc.userId === cleanUser) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map-like `get` — retrieve a human user's location.
|
||||
* @param {string} userId
|
||||
* @param {string} [guildId]
|
||||
* @returns {{ channelId: string, guildId: string }|undefined}
|
||||
*/
|
||||
get(userId, guildId) {
|
||||
if (guildId !== undefined) {
|
||||
const loc = this.userLocations.get(VoiceStateCache.userKey(guildId, userId));
|
||||
return loc ? { channelId: loc.channelId, guildId: loc.guildId } : undefined;
|
||||
}
|
||||
const cleanUser = cleanId(userId);
|
||||
for (const [, loc] of this.userLocations) {
|
||||
if (loc.userId === cleanUser) return { channelId: loc.channelId, guildId: loc.guildId };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map-like `set` — upsert a human user's location.
|
||||
* @param {string} userId
|
||||
* @param {{ guildId: string, channelId: string }} info
|
||||
*/
|
||||
set(userId, info) {
|
||||
const guildId = info?.guildId;
|
||||
const channelId = info?.channelId;
|
||||
if (guildId && channelId) {
|
||||
this.updateUser({ guildId, userId, channelId, isBot: false });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Map-like `delete` — remove a human user. If `guildId` is omitted, removes all matching entries.
|
||||
* @param {string} userId
|
||||
* @param {string} [guildId]
|
||||
*/
|
||||
delete(userId, guildId) {
|
||||
if (guildId !== undefined) {
|
||||
this.updateUser({ guildId, userId, channelId: null, isBot: false });
|
||||
} else {
|
||||
const cleanUser = cleanId(userId);
|
||||
const toRemove = [];
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
if (loc.userId === cleanUser) toRemove.push(loc);
|
||||
}
|
||||
for (const loc of toRemove) {
|
||||
this.updateUser({ guildId: loc.guildId, userId: cleanUser, channelId: null, isBot: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Map-like `forEach` — iterate over human user entries.
|
||||
* @param {function(string, { channelId: string, guildId: string }, VoiceStateCache): void} fn
|
||||
*/
|
||||
forEach(fn) {
|
||||
for (const [userId, info] of this) {
|
||||
fn(userId, info, this);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Map-like `entries` iterator.
|
||||
* @yields {[string, { channelId: string, guildId: string }]}
|
||||
*/
|
||||
*entries() {
|
||||
yield* this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map-like `keys` iterator.
|
||||
* @yields {string}
|
||||
*/
|
||||
*keys() {
|
||||
for (const [userId] of this) {
|
||||
yield userId;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Map-like `values` iterator.
|
||||
* @yields {{ channelId: string, guildId: string }}
|
||||
*/
|
||||
*values() {
|
||||
for (const [, info] of this) {
|
||||
yield info;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Diagnostic statistics for the cache.
|
||||
* @type {{ humanUsers: number, botUsers: number, humanChannels: number, botChannels: number, lruUserKeysLen: number, lruBotKeysLen: number }}
|
||||
*/
|
||||
get stats() {
|
||||
return {
|
||||
humanUsers: this.userLocations.size,
|
||||
botUsers: this.botLocations.size,
|
||||
humanChannels: this.channelMembers.size,
|
||||
botChannels: this.botChannelMembers.size,
|
||||
lruUserKeysLen: this._lruUserKeys.length,
|
||||
lruBotKeysLen: this._lruBotKeys.length,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
/** @module src/voice/VoiceStateResolver */
|
||||
|
||||
import { logger } from "../core/Logger.mjs";
|
||||
|
||||
/**
|
||||
* Iterate over a guild's voice states, normalising different data shapes.
|
||||
* Yields objects with `{ userId, channelId, isBot }` for each member in a voice channel.
|
||||
* @param {object} guild - guild object with a `voice_states` property.
|
||||
* @yields {{ userId: string, channelId: string, isBot: boolean }}
|
||||
*/
|
||||
export function* iterateVoiceStates(guild) {
|
||||
if (!guild) return;
|
||||
|
||||
const voiceStates = guild.voice_states;
|
||||
if (!voiceStates) return;
|
||||
|
||||
let entries;
|
||||
try {
|
||||
if (Array.isArray(voiceStates)) {
|
||||
entries = voiceStates;
|
||||
} else if (typeof voiceStates.values === "function") {
|
||||
entries = voiceStates.values();
|
||||
} else if (typeof voiceStates[Symbol.iterator] === "function") {
|
||||
entries = voiceStates;
|
||||
} else {
|
||||
entries = Object.values(voiceStates);
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[VoiceStateResolver] Failed to enumerate voice states:", e?.message);
|
||||
return;
|
||||
}
|
||||
|
||||
for (const state of entries) {
|
||||
if (!state) continue;
|
||||
const userId = state.userId ?? state.user_id;
|
||||
const channelId = state.channelId ?? state.channel_id;
|
||||
if (!userId || !channelId) continue;
|
||||
|
||||
const member = guild.members?.get?.(userId);
|
||||
const isBot = member?.user?.bot ?? false;
|
||||
|
||||
yield { userId: String(userId), channelId: String(channelId), isBot };
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether any non-bot humans are currently in a voice channel.
|
||||
* Checks, in order: VoiceStateCache → ObservedVoiceUsers → guild voice_states → LiveKit participants.
|
||||
* @param {object} opts
|
||||
* @param {string} opts.guildId
|
||||
* @param {string} opts.channelId
|
||||
* @param {object} [opts.client] - client with `guilds`.
|
||||
* @param {VoiceStateCache} [opts.voiceCache]
|
||||
* @param {Map} [opts.observedVoiceUsers]
|
||||
* @param {object} [opts.room] - LiveKit room with `remoteParticipants`.
|
||||
* @param {string} [opts.botId]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function hasHumansInChannel({ guildId, channelId, client, voiceCache, observedVoiceUsers, room, botId }) {
|
||||
if (!channelId || !guildId) return false;
|
||||
|
||||
|
||||
if (voiceCache && typeof voiceCache.hasHumansInChannel === "function") {
|
||||
if (voiceCache.hasHumansInChannel(guildId, channelId)) return true;
|
||||
}
|
||||
|
||||
|
||||
if (observedVoiceUsers) {
|
||||
try {
|
||||
const iterator = typeof observedVoiceUsers.iterateHumanUsers === "function"
|
||||
? observedVoiceUsers.iterateHumanUsers()
|
||||
: observedVoiceUsers.entries();
|
||||
|
||||
for (const [, info] of iterator) {
|
||||
const gId = String(info.guildId ?? "");
|
||||
const cId = String(info.channelId ?? "");
|
||||
if (gId === guildId && cId === channelId) return true;
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[VoiceStateResolver] ObservedVoiceUsers check failed:", e?.message);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (client) {
|
||||
try {
|
||||
const guild = client.guilds?.get?.(guildId);
|
||||
if (guild) {
|
||||
for (const vs of iterateVoiceStates(guild)) {
|
||||
if (vs.channelId === channelId && !vs.isBot) return true;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[VoiceStateResolver] Guild voice_states check failed:", e?.message);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (room?.isConnected && room.remoteParticipants) {
|
||||
try {
|
||||
for (const [, participant] of room.remoteParticipants) {
|
||||
const pId = participant?.identity || participant?.sid;
|
||||
if (pId && pId !== botId) return true;
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[VoiceStateResolver] LiveKit participants check failed:", e?.message);
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the set of channel IDs that contain at least one human user.
|
||||
* @param {object} guild - guild object.
|
||||
* @returns {Set<string>}
|
||||
*/
|
||||
export function getChannelsWithHumans(guild) {
|
||||
const channels = new Set();
|
||||
for (const vs of iterateVoiceStates(guild)) {
|
||||
if (!vs.isBot) channels.add(vs.channelId);
|
||||
}
|
||||
return channels;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of user IDs present in a specific voice channel.
|
||||
* @param {object} guild - guild object.
|
||||
* @param {string} channelId
|
||||
* @returns {string[]}
|
||||
*/
|
||||
export function getUsersInChannel(guild, channelId) {
|
||||
const users = [];
|
||||
for (const vs of iterateVoiceStates(guild)) {
|
||||
if (vs.channelId === channelId) users.push(vs.userId);
|
||||
}
|
||||
return users;
|
||||
}
|
||||
@@ -0,0 +1,602 @@
|
||||
/**
|
||||
* @module src/voice/gateway/GatewayHandler
|
||||
* @description Handles all gateway events relevant to voice state
|
||||
* tracking, 24/7 mode, boot recovery, presence rotation, and permission
|
||||
* checks. Base class file: constructor & state, raw WS listener, presence
|
||||
* rotation, event registration, READY sequencing and 24/7 boot recovery.
|
||||
* Voice-state routing, guild sync and rejoin management live in sibling
|
||||
* mixin modules applied onto the prototype at the bottom of this file.
|
||||
*/
|
||||
import { Events, GatewayOpcodes } from "@fluxerjs/core";
|
||||
import { logger, _wsErrorCooldown } from "../../core/Logger.mjs";
|
||||
import { ServerSettings } from "../../db/Settings.mjs";
|
||||
import { get247ChannelMode, remove247ChannelMode } from "../../utils/Helpers247.mjs";
|
||||
import { cleanId } from "../../utils/Utils.mjs";
|
||||
import * as ShardingUtils from "../../utils/ShardingUtils.mjs";
|
||||
import { iterateVoiceStates, hasHumansInChannel, getChannelsWithHumans } from "../VoiceStateResolver.mjs";
|
||||
import { applyMixins } from "../../utils/mixins.mjs";
|
||||
import VoiceStateRouting from "./VoiceStateRouting.mjs";
|
||||
import GuildSync from "./GuildSync.mjs";
|
||||
import RejoinManager from "./RejoinManager.mjs";
|
||||
|
||||
const RAW_GATEWAY_INTEREST =
|
||||
/"(?:t|op)":\s*(?:"(?:VOICE_STATE_UPDATE|VOICE_SERVER_UPDATE|GUILD_CREATE|READY|RESUMED)"|(?:7|9|10|12)\b)/;
|
||||
|
||||
/** @class GatewayHandler @description Handles all gateway events relevant to voice state tracking, 24/7 mode, boot recovery, presence rotation, and permission checks. Key responsibilities include voice state cache seeding and updates, bot move-away detection with 24/7 rejoin scheduling, boot recovery with sequential rejoin of 24/7 channels, inactivity timer management on human join/leave, and guild create/delete handling with startup grace period. */
|
||||
class GatewayHandler {
|
||||
/**
|
||||
* Create a new GatewayHandler.
|
||||
* @param {import('../../core/Bot.mjs').Remix} remix - The bot context.
|
||||
*/
|
||||
constructor(remix) {
|
||||
this.remix = remix;
|
||||
|
||||
const timers = remix.config.timers ?? {};
|
||||
this.T = {
|
||||
aloneCheckDebounce: timers.aloneCheckDebounce ?? 500,
|
||||
rejoin247Delay: timers.rejoin247Delay ?? 3_000,
|
||||
};
|
||||
|
||||
this.presenceContents = remix.config.presenceContents ?? [];
|
||||
this.presenceInterval = remix.config.presenceInterval ?? 30_000;
|
||||
|
||||
this.wsListenerAttached = false;
|
||||
this.presenceTimer = null;
|
||||
this.presenceIndex = 0;
|
||||
|
||||
this._prevVoiceState = new Map();
|
||||
|
||||
this._deferredGuildDeletes = new Map();
|
||||
this._startupDeleteGraceMs = 15_000;
|
||||
this._inStartupGrace = true;
|
||||
this._deferredDeleteCount = 0;
|
||||
|
||||
this._lastReadyAt = 0;
|
||||
this._wsReconnectGraceMs = 30_000;
|
||||
this._moveEvidenceWindowMs = 10_000;
|
||||
}
|
||||
|
||||
/** @private @type {Set<string>} @description Channel IDs currently being rejoined (duplicate guard). */
|
||||
_rejoinInProgress = new Set();
|
||||
|
||||
/** @private @type {Map<string, number>} @description Channel ID → retry count for exponential backoff. */
|
||||
_rejoinAttempts = new Map();
|
||||
|
||||
/** @private @type {boolean} @description Whether boot recovery is actively rejoining 24/7 channels. */
|
||||
_bootRecoveryActive = false;
|
||||
|
||||
/** @type {number} @description Maximum number of rejoin retry attempts per channel. */
|
||||
static MAX_REJOIN_RETRIES = 3;
|
||||
|
||||
/**
|
||||
* Check whether a WebSocket reconnect happened recently (within 30s).
|
||||
* Used to treat transient disconnects as non-24/7-requiring.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isWsReconnectRecent() {
|
||||
if (!this._lastReadyAt) return false;
|
||||
return Date.now() - this._lastReadyAt < this._wsReconnectGraceMs;
|
||||
}
|
||||
|
||||
/** @private Build a composite bot key for voice state tracking. @param {string} userId @param {string} guildId @returns {string|null} */
|
||||
getObservedVoiceBotKey(userId, guildId) {
|
||||
const cleanUserId = cleanId(userId ?? "");
|
||||
const cleanGuildId = cleanId(guildId ?? "");
|
||||
return cleanUserId && cleanGuildId ? `${cleanGuildId}:${cleanUserId}` : cleanUserId || null;
|
||||
}
|
||||
|
||||
/** @private Build a previous voice state lookup key. @param {string} userId @param {string} guildId @returns {string|null} */
|
||||
getPrevVoiceStateKey(userId, guildId) {
|
||||
const cleanUserId = cleanId(userId ?? "");
|
||||
const cleanGuildId = cleanId(guildId ?? "");
|
||||
return cleanUserId && cleanGuildId ? `${cleanGuildId}:${cleanUserId}` : null;
|
||||
}
|
||||
|
||||
/** Find a previous voice state entry for a user. @param {string} userId @param {string|null} [guildId=null] @returns {{key: string|null, value: object|null}} */
|
||||
findPrevVoiceStateEntry(userId, guildId = null) {
|
||||
const directKey = this.getPrevVoiceStateKey(userId, guildId);
|
||||
if (directKey && this._prevVoiceState.has(directKey)) {
|
||||
return { key: directKey, value: this._prevVoiceState.get(directKey) };
|
||||
}
|
||||
|
||||
const cleanUserId = cleanId(userId ?? "");
|
||||
if (!cleanUserId) return { key: null, value: null };
|
||||
|
||||
for (const [key, value] of this._prevVoiceState) {
|
||||
if (key.endsWith(`:${cleanUserId}`)) {
|
||||
return { key, value };
|
||||
}
|
||||
}
|
||||
|
||||
return { key: null, value: null };
|
||||
}
|
||||
|
||||
/** Attach a raw WebSocket listener to cache VOICE_SERVER_UPDATE events. @private */
|
||||
attachRawListener() {
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
|
||||
try {
|
||||
// Fluxer 3.0 + sharding: the ws manager exposes shards via getShards()
|
||||
// (2.2 used a `shards` Map property) and a sharded child owns several
|
||||
// shards — track the raw socket of EVERY local shard, not just shard 0.
|
||||
const wsObjs = ShardingUtils.localShardSockets(client);
|
||||
|
||||
if (!remix._rawGatewayWsObjs) remix._rawGatewayWsObjs = new Set();
|
||||
const attached = remix._rawGatewayWsObjs;
|
||||
|
||||
// Detach listeners from sockets that went away (reconnects).
|
||||
for (const old of attached) {
|
||||
if (wsObjs.includes(old)) continue;
|
||||
try {
|
||||
if (typeof old.removeEventListener === "function") {
|
||||
old.removeEventListener("message", remix._rawGatewayMessageListener ?? remix._rawGatewayHandler);
|
||||
old.removeEventListener("error", remix._rawGatewayErrorHandler);
|
||||
} else if (typeof old.off === "function") {
|
||||
old.off("message", remix._rawGatewayMessageListener ?? remix._rawGatewayHandler);
|
||||
old.off("error", remix._rawGatewayErrorHandler);
|
||||
}
|
||||
} catch(e) { logger.warn("[Gateway] Failed to detach old WS listener:", e?.message); }
|
||||
attached.delete(old);
|
||||
}
|
||||
|
||||
let attachedNew = false;
|
||||
|
||||
// Create the shared raw-socket handlers once (stateless parsers
|
||||
// shared by every local shard socket).
|
||||
if (!remix._rawGatewayHandler) {
|
||||
remix._rawGatewayHandler = (data) => {
|
||||
try {
|
||||
if (typeof data === "string" && !RAW_GATEWAY_INTEREST.test(data)) return;
|
||||
const payload = typeof data === "string" ? JSON.parse(data) : data;
|
||||
|
||||
if (payload?.op === GatewayOpcodes.GatewayError || payload?.op === 12) {
|
||||
logger.warn("[Gateway] GatewayError (12) received from Fluxer:", payload.d);
|
||||
}
|
||||
|
||||
if (payload?.op === GatewayOpcodes.Hello || payload?.op === 10) {
|
||||
logger.player(`[Gateway] HELLO received (heartbeat ${payload.d?.heartbeat_interval ?? "unknown"}ms)`);
|
||||
}
|
||||
if (payload?.op === GatewayOpcodes.Reconnect || payload?.op === 7) {
|
||||
logger.warn("[Gateway] RECONNECT requested by gateway.");
|
||||
}
|
||||
if (payload?.op === GatewayOpcodes.InvalidSession || payload?.op === 9) {
|
||||
logger.warn("[Gateway] INVALID_SESSION received from gateway.");
|
||||
}
|
||||
|
||||
if (payload?.op !== 0) return;
|
||||
|
||||
if (payload.t === "READY") {
|
||||
logger.player(`[Gateway] READY received (session ${payload.d?.session_id ?? "unknown"})`);
|
||||
const readyGuilds = payload.d?.guilds;
|
||||
if (Array.isArray(readyGuilds)) {
|
||||
for (const g of readyGuilds) {
|
||||
const gId = g?.id;
|
||||
if (!gId || !Array.isArray(g.voice_states)) continue;
|
||||
for (const state of g.voice_states) {
|
||||
const userId = state.user_id;
|
||||
const channelId = state.channel_id;
|
||||
if (!userId || !channelId) continue;
|
||||
const isBot = state.member?.user?.bot ?? false;
|
||||
remix.voiceCache.updateUser({ guildId: gId, userId, channelId, isBot });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (payload.t === "RESUMED") {
|
||||
logger.player("[Gateway] RESUMED received from gateway.");
|
||||
}
|
||||
|
||||
if (payload.t === "GUILD_CREATE") {
|
||||
const d = payload.d;
|
||||
const gId = d?.id;
|
||||
const voiceStates = d?.voice_states;
|
||||
if (gId && Array.isArray(voiceStates) && voiceStates.length > 0) {
|
||||
for (const state of voiceStates) {
|
||||
const userId = state.user_id;
|
||||
const channelId = state.channel_id;
|
||||
if (!userId || !channelId) continue;
|
||||
const isBot = state.member?.user?.bot ?? false;
|
||||
remix.voiceCache.updateUser({ guildId: gId, userId, channelId, isBot });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (payload.t === "VOICE_SERVER_UPDATE") {
|
||||
logger.voiceState(`[Gateway] VOICE_SERVER_UPDATE guild=${payload.d?.guild_id ?? "dm"} endpoint=${payload.d?.endpoint ?? "unknown"}`);
|
||||
}
|
||||
|
||||
if (payload.t === "VOICE_STATE_UPDATE") {
|
||||
const d = payload.d;
|
||||
const userId = d?.user_id;
|
||||
const channelId = d?.channel_id ?? null;
|
||||
const guildId = d?.guild_id;
|
||||
const isBot = d?.member?.user?.bot ?? false;
|
||||
if (!userId) return;
|
||||
if (channelId) {
|
||||
remix.voiceCache.updateUser({ guildId, userId, channelId, isBot });
|
||||
} else {
|
||||
remix.voiceCache.updateUser({ guildId, userId, channelId: null, isBot });
|
||||
}
|
||||
}
|
||||
} catch(e) { logger.warn("[Gateway] Raw gateway handler error:", e?.message); }
|
||||
};
|
||||
|
||||
remix._rawGatewayErrorHandler = (errOrEvent) => {
|
||||
if (typeof errOrEvent?.preventDefault === "function") errOrEvent.preventDefault();
|
||||
const err = errOrEvent?.error ?? errOrEvent?.message ?? errOrEvent;
|
||||
const now = Date.now();
|
||||
if (now - _wsErrorCooldown.lastLogged < _wsErrorCooldown.COOLDOWN_MS) return;
|
||||
_wsErrorCooldown.lastLogged = now;
|
||||
logger.warn("[Gateway] Raw WS socket error (will reconnect):", err?.message ?? err);
|
||||
};
|
||||
remix._rawGatewayMessageListener = (event) => remix._rawGatewayHandler(event?.data ?? event);
|
||||
}
|
||||
|
||||
for (const wsObj of wsObjs) {
|
||||
if (attached.has(wsObj)) continue;
|
||||
|
||||
if (typeof wsObj.addEventListener === "function") {
|
||||
wsObj.addEventListener("message", remix._rawGatewayMessageListener);
|
||||
wsObj.addEventListener("error", remix._rawGatewayErrorHandler);
|
||||
} else if (typeof wsObj.on === "function") {
|
||||
wsObj.on("message", remix._rawGatewayMessageListener);
|
||||
wsObj.on("error", remix._rawGatewayErrorHandler);
|
||||
}
|
||||
|
||||
attached.add(wsObj);
|
||||
attachedNew = true;
|
||||
}
|
||||
|
||||
// Legacy singular field kept in sync (first socket) for compatibility.
|
||||
remix._rawGatewayWsObj = wsObjs[0] ?? null;
|
||||
this.wsListenerAttached = attached.size > 0;
|
||||
if (attachedNew) {
|
||||
logger.player("[Gateway] Raw WS listener attached to new socket.");
|
||||
}
|
||||
} catch(e) { logger.warn("[Gateway] attachRawListener failed:", e?.message); }
|
||||
}
|
||||
|
||||
/** Rotate the bot's presence/status text at a configured interval. @private */
|
||||
setupPresenceRotation() {
|
||||
if (this.presenceContents.length === 0) return;
|
||||
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
|
||||
const setPresence = () => {
|
||||
const entry = this.presenceContents[this.presenceIndex];
|
||||
|
||||
const isObj = typeof entry === "object" && entry !== null;
|
||||
|
||||
const custom_status = {};
|
||||
if (isObj) {
|
||||
if (entry.text) custom_status.text = entry.text;
|
||||
if (entry.emoji_name) custom_status.emoji_name = entry.emoji_name;
|
||||
if (entry.emoji_id) custom_status.emoji_id = entry.emoji_id;
|
||||
} else {
|
||||
custom_status.text = String(entry);
|
||||
}
|
||||
|
||||
const presence = {
|
||||
status: "online",
|
||||
mobile: false,
|
||||
afk: false,
|
||||
custom_status,
|
||||
};
|
||||
|
||||
if (isObj && entry.activity) {
|
||||
presence.activities = [{
|
||||
name: entry.activity.name ?? "music",
|
||||
type: entry.activity.type ?? 0,
|
||||
url: entry.activity.url ?? undefined,
|
||||
}];
|
||||
}
|
||||
|
||||
// Fluxer 3.0: client.ws is a throwing getter when the gateway is not
|
||||
// connected (2.2 exposed a plain optional). The raw opcode-3 payload
|
||||
// below stays in wire format (custom_status) because it bypasses
|
||||
// ClientUser.setPresence() and hits the shard directly.
|
||||
// Sharded children fan the update out to every gateway shard in this
|
||||
// process (presence is per shard); single process = shard 0 as before.
|
||||
try {
|
||||
if (client.ws?.send) {
|
||||
for (const id of ShardingUtils.localShardIds(client)) {
|
||||
client.ws.send(id, { op: GatewayOpcodes.PresenceUpdate, d: presence });
|
||||
}
|
||||
} else {
|
||||
const shard = ShardingUtils.getShard(client, 0);
|
||||
if (shard) shard.send({ op: GatewayOpcodes.PresenceUpdate, d: presence });
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[Presence] Gateway not ready, skipping rotation update:", e?.message);
|
||||
}
|
||||
this.presenceIndex = (this.presenceIndex + 1) % this.presenceContents.length;
|
||||
};
|
||||
setPresence();
|
||||
if (this.presenceTimer) clearInterval(this.presenceTimer);
|
||||
this.presenceTimer = setInterval(setPresence, this.presenceInterval);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register all gateway event handlers (GuildCreate, GuildDelete, VoiceStateUpdate, VoiceStatesSync).
|
||||
* Called once during bot initialisation.
|
||||
*/
|
||||
setupEventHandlers() {
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
|
||||
client.on(Events.GuildCreate, async (guild) => {
|
||||
const guildId = guild?.id ?? guild?._id;
|
||||
if (!guildId) return;
|
||||
|
||||
const deferred = this._deferredGuildDeletes.get(guildId);
|
||||
if (deferred) {
|
||||
clearTimeout(deferred.timer);
|
||||
this._deferredGuildDeletes.delete(guildId);
|
||||
logger.guild(
|
||||
`[GuildDelete] Cancelled deferred cleanup for server ${guildId} — ` +
|
||||
`guild came back (GuildCreate received during grace period).`
|
||||
);
|
||||
}
|
||||
|
||||
const voiceStatesRaw =
|
||||
guild.voice_states ??
|
||||
guild.voiceStates ??
|
||||
null;
|
||||
|
||||
if (voiceStatesRaw) {
|
||||
const newUserIds = new Set();
|
||||
for (const vs of iterateVoiceStates(guild)) {
|
||||
newUserIds.add(vs.userId);
|
||||
}
|
||||
remix.voiceCache.purgeUsersInGuild(guildId, newUserIds);
|
||||
}
|
||||
if (voiceStatesRaw) {
|
||||
for (const vs of iterateVoiceStates(guild)) {
|
||||
remix.voiceCache.updateUser({ guildId, userId: vs.userId, channelId: vs.channelId, isBot: vs.isBot });
|
||||
}
|
||||
}
|
||||
|
||||
if (!remix.settingsMgr.guilds.has(guildId)) {
|
||||
logger.guild(`[GuildCreate] (Re-)joined server ${guildId} — initialising settings.`);
|
||||
try {
|
||||
const cleanGuildId = cleanId(guildId);
|
||||
if (!cleanGuildId) throw new Error("Invalid guildId: " + guildId);
|
||||
const res = await remix.settingsMgr.selectGuild(cleanGuildId);
|
||||
if (res?.results?.length) {
|
||||
const row = res.results[0];
|
||||
const server = new ServerSettings(guildId, remix.settingsMgr);
|
||||
const parsed = (typeof row.data === "string") ? JSON.parse(row.data) : row.data;
|
||||
server.deserialize(parsed);
|
||||
server.checkDefaults(remix.settingsMgr.defaults);
|
||||
remix.settingsMgr.guilds.set(guildId, server);
|
||||
logger.guild(`[GuildCreate] Restored existing settings for server ${guildId}.`);
|
||||
} else {
|
||||
const server = new ServerSettings(guildId, remix.settingsMgr);
|
||||
server.checkDefaults(remix.settingsMgr.defaults);
|
||||
remix.settingsMgr.guilds.set(guildId, server);
|
||||
await remix.settingsMgr.create(guildId, server);
|
||||
logger.guild(`[GuildCreate] Fresh settings initialised for server ${guildId}.`);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn("[GuildCreate] Settings init failed for", guildId, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
this._checkGuildPermissions(guild, guildId).catch(e => logger.warn("[GuildCreate] Permission check error for", guildId, e.message));
|
||||
|
||||
});
|
||||
|
||||
client.on(Events.GuildDelete, (guild) => {
|
||||
const guildId = guild?.id ?? guild?._id;
|
||||
if (!guildId) return;
|
||||
|
||||
if (this._inStartupGrace) {
|
||||
this._deferredDeleteCount++;
|
||||
if (this._deferredDeleteCount <= 3) {
|
||||
logger.guild(
|
||||
`[GuildDelete] Deferring cleanup for server ${guildId} ` +
|
||||
`(startup grace — will confirm after ${this._startupDeleteGraceMs / 1000}s).`
|
||||
);
|
||||
}
|
||||
const existing = this._deferredGuildDeletes.get(guildId);
|
||||
if (existing) clearTimeout(existing.timer);
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
this._deferredGuildDeletes.delete(guildId);
|
||||
this._processGuildDelete(guildId);
|
||||
}, this._startupDeleteGraceMs);
|
||||
|
||||
this._deferredGuildDeletes.set(guildId, { guild, timer });
|
||||
return;
|
||||
}
|
||||
|
||||
logger.guild(`[GuildDelete] Received GuildDelete for server ${guildId}.`);
|
||||
this._processGuildDelete(guildId);
|
||||
});
|
||||
|
||||
client.on(Events.VoiceStateUpdate, async (data) => {
|
||||
this._handleVoiceStateUpdate(data);
|
||||
});
|
||||
|
||||
client.on(Events.VoiceStatesSync, (data) => {
|
||||
this._handleVoiceStatesSync(data);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the bot receives the READY event.
|
||||
* Seeds voice states, starts presence rotation, ends startup grace period,
|
||||
* and begins 24/7 boot recovery.
|
||||
*/
|
||||
onReady() {
|
||||
this._lastReadyAt = Date.now();
|
||||
this.seedVoiceStatesFromGuilds();
|
||||
this.seedGuildsFromRest().catch(e => logger.warn("[onReady] seedGuildsFromRest error:", e.message));
|
||||
this.attachRawListener();
|
||||
|
||||
this.setupPresenceRotation();
|
||||
|
||||
setTimeout(() => {
|
||||
this._inStartupGrace = false;
|
||||
const pending = this._deferredGuildDeletes.size;
|
||||
if (pending > 0) {
|
||||
logger.guild(
|
||||
`[GuildDelete] Startup grace period ended. ` +
|
||||
`${pending} deferred deletion(s) confirmed — cleaning up.`
|
||||
);
|
||||
} else {
|
||||
logger.guild(`[GuildDelete] Startup grace period ended. No deferred deletions.`);
|
||||
}
|
||||
if (this._deferredDeleteCount > 3) {
|
||||
logger.guild(
|
||||
`[GuildDelete] (Suppressed ${this._deferredDeleteCount - 3} deferral log lines for brevity)`
|
||||
);
|
||||
}
|
||||
}, this._startupDeleteGraceMs);
|
||||
|
||||
this.rejoin247Channels();
|
||||
}
|
||||
|
||||
/**
|
||||
* Boot recovery: sequentially rejoin all saved 24/7 channels.
|
||||
* Sets _bootRecoveryActive=true to suppress fake move events during the process.
|
||||
* Cleans up missing channels from settings to prevent repeated failures.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async rejoin247Channels() {
|
||||
this._bootRecoveryActive = true;
|
||||
try {
|
||||
await this._rejoin247ChannelsInner();
|
||||
} catch (err) {
|
||||
logger.warn("[BootRecovery] 24/7 boot recovery crashed:", err?.message ?? err);
|
||||
} finally {
|
||||
this._bootRecoveryActive = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** @private Inner boot-recovery loop. The flag reset is handled by the caller's finally block. */
|
||||
async _rejoin247ChannelsInner() {
|
||||
const { remix } = this;
|
||||
const channelsToRejoin = [];
|
||||
|
||||
for (const [guildId, serverSettings] of remix.settingsMgr.guilds) {
|
||||
const raw = serverSettings.get("stay_247");
|
||||
if (!raw || raw === "none") continue;
|
||||
|
||||
const rawArr = Array.isArray(raw) ? raw : [raw];
|
||||
const channels = rawArr
|
||||
.map(id => cleanId(id))
|
||||
.filter(id => id.length >= 15 && id.length <= 22);
|
||||
|
||||
for (const channelId of channels) {
|
||||
const mode = get247ChannelMode(serverSettings, channelId);
|
||||
if (mode === "on") {
|
||||
channelsToRejoin.push({ guildId, channelId, mode });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (channelsToRejoin.length === 0) {
|
||||
logger.voice247("[BootRecovery] No 24/7 channels to rejoin.");
|
||||
return;
|
||||
}
|
||||
|
||||
logger.voice247(
|
||||
`[BootRecovery] Found ${channelsToRejoin.length} 24/7 channel(s) to rejoin: ` +
|
||||
channelsToRejoin.map(c => `${c.channelId}(${c.mode})`).join(", ")
|
||||
);
|
||||
|
||||
const baseStagger = remix.config?.timers?.bootRejoinStagger ?? 5_000;
|
||||
|
||||
for (let i = 0; i < channelsToRejoin.length; i++) {
|
||||
const { guildId, channelId, mode } = channelsToRejoin[i];
|
||||
|
||||
if (i > 0) {
|
||||
let staggerDelay = baseStagger;
|
||||
if (i >= 8) staggerDelay = baseStagger * 2;
|
||||
else if (i >= 4) staggerDelay = Math.round(baseStagger * 1.5);
|
||||
logger.voice247(`[BootRecovery] Waiting ${staggerDelay / 1000}s before rejoining next channel...`);
|
||||
await new Promise(resolve => setTimeout(resolve, staggerDelay));
|
||||
}
|
||||
|
||||
const existing = remix.players.playerMap.get(channelId);
|
||||
if (existing && !existing._destroyed) {
|
||||
logger.voice247(`[BootRecovery] Channel ${channelId} already has a player — skipping.`);
|
||||
continue;
|
||||
}
|
||||
if (remix.players._pendingJoins?.has?.(channelId)) {
|
||||
logger.voice247(`[BootRecovery] Channel ${channelId} already has a pending join — skipping.`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const channelObj = remix.client?.channels?.get?.(channelId);
|
||||
if (!channelObj) {
|
||||
logger.warn(
|
||||
`[BootRecovery] Channel ${channelId} in guild ${guildId} no longer exists — ` +
|
||||
`removing from 24/7 settings to prevent repeated failures.`
|
||||
);
|
||||
try {
|
||||
const set = remix.settingsMgr.getServer(guildId);
|
||||
if (set) {
|
||||
const raw = set.get("stay_247");
|
||||
const arr = Array.isArray(raw) ? raw : raw ? [raw] : [];
|
||||
const filtered = arr.filter(id => id && id !== "none" && cleanId(id) !== channelId);
|
||||
const remainingSet = new Set(filtered.map(id => cleanId(id)));
|
||||
remove247ChannelMode(set, channelId, remainingSet);
|
||||
set.set("stay_247", filtered.length > 0 ? filtered : "none");
|
||||
}
|
||||
} catch (cleanupErr) {
|
||||
logger.warn(`[BootRecovery] Failed to auto-remove missing channel ${channelId} from 24/7:`, cleanupErr?.message);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (channelObj.type !== 2) {
|
||||
logger.warn(
|
||||
`[BootRecovery] Channel ${channelId} in guild ${guildId} is not a voice channel (type: ${channelObj.type}) — skipping.`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const guildHasActivePlayer = [...remix.players.playerMap.values()]
|
||||
.some(p => !p._destroyed && cleanId(p._guildId ?? "") === guildId);
|
||||
if (guildHasActivePlayer && i > 0) {
|
||||
const extraDelay = 3_000;
|
||||
logger.voice247(
|
||||
`[BootRecovery] Guild ${guildId} already has an active player — ` +
|
||||
`waiting extra ${extraDelay / 1000}s to avoid move-disconnect.`
|
||||
);
|
||||
await new Promise(resolve => setTimeout(resolve, extraDelay));
|
||||
}
|
||||
|
||||
logger.voice247(
|
||||
`[BootRecovery] Rejoining channel ${channelId} in guild ${guildId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]`
|
||||
);
|
||||
|
||||
const player = await this._attemptRejoin(channelId, guildId, 3, 5_000, "BootRecovery");
|
||||
|
||||
if (player) {
|
||||
logger.voice247(
|
||||
`[BootRecovery] Successfully rejoined channel ${channelId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]`
|
||||
);
|
||||
} else {
|
||||
logger.warn(
|
||||
`[BootRecovery] Failed to rejoin channel ${channelId} in guild ${guildId} after retries — ` +
|
||||
`keeping 24/7 setting intact, will retry on next disconnect/restart.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
logger.voice247(
|
||||
`[BootRecovery] Boot recovery complete. ${channelsToRejoin.length} channel(s) processed.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Attach the split-out concerns: voice-state routing (VoiceStateRouting),
|
||||
// guild sync & seeding (GuildSync), and 24/7 rejoin management (RejoinManager).
|
||||
applyMixins(GatewayHandler, VoiceStateRouting, GuildSync, RejoinManager);
|
||||
|
||||
export { GatewayHandler };
|
||||
@@ -0,0 +1,391 @@
|
||||
/**
|
||||
* @module src/voice/gateway/GuildSync
|
||||
* @description Guild synchronisation concern for {@link GatewayHandler}:
|
||||
* bot permission checks on guild create, voice-state cache seeding
|
||||
* (VoiceManager, guild cache, VoiceStateCache, LiveKit participants), REST
|
||||
* guild-cache stubbing for guilds without GUILD_CREATE, and confirmed
|
||||
* guild-delete cleanup.
|
||||
*
|
||||
* These methods are applied onto the GatewayHandler class prototype via
|
||||
* {@link applyMixins} — `this` is a GatewayHandler instance.
|
||||
*/
|
||||
|
||||
import { getVoiceManager } from "@fluxerjs/voice";
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
import { REQUIRED_BOT_PERMISSIONS } from "../../ui/index.mjs";
|
||||
import { cleanId } from "../../utils/Utils.mjs";
|
||||
import { iterateVoiceStates } from "../VoiceStateResolver.mjs";
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
* @description Guild sync mixin — applied to GatewayHandler.
|
||||
*/
|
||||
const GuildSync = {
|
||||
/**
|
||||
* Check and warn about missing bot permissions in a guild.
|
||||
* Sends an embed to the system channel if critical or optional perms are missing.
|
||||
* @param {object} guild - The guild object.
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @returns {Promise<void>}
|
||||
* @private
|
||||
*/
|
||||
async _checkGuildPermissions(guild, guildId) {
|
||||
const { remix } = this;
|
||||
|
||||
try {
|
||||
if (guild.members && !guild.members.me) {
|
||||
await guild.members.fetchMe();
|
||||
}
|
||||
} catch (e) { logger.warn("[GatewayHandler] fetchMe failed:", e?.message); }
|
||||
|
||||
const channels = guild.channels;
|
||||
if (!channels) return;
|
||||
|
||||
let targetChannel = null;
|
||||
if (guild.systemChannelId) {
|
||||
targetChannel = channels.get?.(guild.systemChannelId) ?? null;
|
||||
}
|
||||
if (!targetChannel) {
|
||||
for (const ch of (channels.values?.() ?? [])) {
|
||||
if (ch.isTextBased?.() || ch.type === 0 || ch.type === "GUILD_TEXT") {
|
||||
targetChannel = ch;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!targetChannel) return;
|
||||
|
||||
const result = remix.messages.checkAllBotPermissions(targetChannel);
|
||||
if (result.missing.length === 0) return;
|
||||
|
||||
const missingNames = result.missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k);
|
||||
if (result.criticalMissing.length > 0) {
|
||||
logger.warn(
|
||||
`[GuildCreate] Server ${guildId} is missing CRITICAL bot permissions: ${result.criticalMissing.join(", ")}\n` +
|
||||
` All missing: ${missingNames.join(", ")}`
|
||||
);
|
||||
} else {
|
||||
logger.guild(
|
||||
`[GuildCreate] Server ${guildId} is missing optional permissions: ${result.optionalMissing.join(", ")}`
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const permEmbed = remix.messages.buildPermissionEmbed(result.missing, guildId);
|
||||
await targetChannel.send({ embeds: [permEmbed], allowedMentions: { parse: [] } });
|
||||
} catch (e) {
|
||||
logger.warn(`[GuildCreate] Cannot send permission warning to server ${guildId}: ${e.message}`);
|
||||
try {
|
||||
const t = this.remix.locale?.translate?.bind(this.remix.locale);
|
||||
const guildIdStr = cleanId(guildId);
|
||||
await targetChannel.send({
|
||||
content: t ? t(guildIdStr, "responses.gateway.missingPermsFallback", { perms: missingNames.join("**, **") }) :
|
||||
"⚠️ I'm missing permissions I need to work properly! Missing: **" + missingNames.join("**, **") + "**. Please ask a server administrator to grant these permissions in Server Settings → Roles.",
|
||||
allowedMentions: { parse: [] },
|
||||
});
|
||||
} catch (e) {
|
||||
logger.warn(`[GuildCreate] Cannot send ANY notification to server ${guildId} — bot is missing SendMessages permission:`, e?.message);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Seed the voice state cache from VoiceManager or guild cache on startup.
|
||||
* @private
|
||||
*/
|
||||
seedVoiceStatesFromGuilds() {
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
|
||||
try {
|
||||
const vm = getVoiceManager(client);
|
||||
if (vm?.voiceStates && vm.voiceStates.size > 0) {
|
||||
let totalHumans = 0;
|
||||
let totalBots = 0;
|
||||
for (const [guildId, userMap] of vm.voiceStates) {
|
||||
if (!userMap || typeof userMap.forEach !== "function") continue;
|
||||
const cleanGuildId = cleanId(guildId);
|
||||
if (!cleanGuildId) continue;
|
||||
userMap.forEach((channelId, userId) => {
|
||||
if (!userId || !channelId) return;
|
||||
const botId = client.user?.id;
|
||||
if (userId === botId) {
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuildId, userId, channelId, isBot: true });
|
||||
totalBots++;
|
||||
} else {
|
||||
const guild = client.guilds.get(cleanGuildId) ?? client.guilds.get(guildId);
|
||||
const member = guild?.members?.get?.(userId);
|
||||
const isBot = member?.user?.bot ?? false;
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuildId, userId, channelId, isBot });
|
||||
if (isBot) totalBots++;
|
||||
else totalHumans++;
|
||||
}
|
||||
});
|
||||
}
|
||||
logger.voiceState(
|
||||
`[Seed] Seeded from VoiceManager.voiceStates — ` +
|
||||
`${totalHumans} humans, ${totalBots} bots across ${vm.voiceStates.size} guilds. ` +
|
||||
`Cache now: ${remix.voiceCache.observedVoiceUsersSize} humans, ${remix.voiceCache.observedVoiceBotsSize} bots.`
|
||||
);
|
||||
return;
|
||||
}
|
||||
logger.voiceState(`[Seed] VoiceManager.voiceStates is empty (${vm?.voiceStates?.size ?? "null"} guilds). ` +
|
||||
`This is expected if no users were in voice when the bot started. ` +
|
||||
`VoiceStatesSync handler will populate the cache as guilds become available.`);
|
||||
} catch (e) {
|
||||
logger.voiceState(`[Seed] VoiceManager seeding failed: ${e?.message} — falling back to guild cache.`);
|
||||
}
|
||||
|
||||
for (const [gId, guild] of client.guilds) {
|
||||
for (const vs of iterateVoiceStates(guild)) {
|
||||
remix.voiceCache.updateUser({ guildId: gId, userId: vs.userId, channelId: vs.channelId, isBot: vs.isBot });
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Re-seed voice states for a specific channel from multiple sources.
|
||||
* Checks VoiceManager, guild cache, VoiceStateCache, and LiveKit participants.
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @param {string} channelId - The channel ID.
|
||||
* @returns {number} Number of humans found in the channel.
|
||||
*/
|
||||
reseedVoiceStatesForChannel(guildId, channelId) {
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
|
||||
const cleanGuild = cleanId(guildId);
|
||||
const cleanChannel = cleanId(channelId);
|
||||
if (!cleanGuild || !cleanChannel) return 0;
|
||||
|
||||
let humansFound = 0;
|
||||
const botId = client.user?.id;
|
||||
|
||||
try {
|
||||
const vm = getVoiceManager(client);
|
||||
if (vm?.voiceStates) {
|
||||
const guildVoiceMap = vm.voiceStates.get(cleanGuild) ?? vm.voiceStates.get(guildId);
|
||||
if (guildVoiceMap && typeof guildVoiceMap.forEach === "function") {
|
||||
guildVoiceMap.forEach((userChannelId, userId) => {
|
||||
if (!userId || !userChannelId) return;
|
||||
const userChannel = cleanId(userChannelId);
|
||||
if (userChannel !== cleanChannel) return;
|
||||
if (userId === botId) {
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: true });
|
||||
} else {
|
||||
const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId);
|
||||
const member = guild?.members?.get?.(userId);
|
||||
const isBot = member?.user?.bot ?? false;
|
||||
if (isBot) {
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: true });
|
||||
} else {
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: false });
|
||||
humansFound++;
|
||||
logger.voiceState(
|
||||
`[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild}) via VoiceManager`
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (botId) {
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true });
|
||||
}
|
||||
|
||||
logger.voiceState(
|
||||
`[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` +
|
||||
`found ${humansFound} human(s) via VoiceManager, observedVoiceUsers size now ${remix.voiceCache.observedVoiceUsersSize}`
|
||||
);
|
||||
|
||||
if (humansFound > 0) return humansFound;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
logger.voiceState(`[Reseed] VoiceManager lookup failed: ${e?.message} — falling back.`);
|
||||
}
|
||||
|
||||
const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId);
|
||||
if (!guild) {
|
||||
logger.voiceState(
|
||||
`[Reseed] Guild ${cleanGuild} not in cache — cannot reseed voice states.`
|
||||
);
|
||||
} else {
|
||||
for (const vs of iterateVoiceStates(guild)) {
|
||||
if (vs.isBot) continue;
|
||||
if (vs.channelId === cleanChannel) {
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId: vs.userId, channelId: vs.channelId, isBot: false });
|
||||
humansFound++;
|
||||
logger.voiceState(
|
||||
`[Reseed] Found human ${vs.userId} in channel ${cleanChannel} (guild ${cleanGuild})`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (botId) {
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true });
|
||||
}
|
||||
|
||||
if (humansFound > 0) {
|
||||
logger.voiceState(
|
||||
`[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` +
|
||||
`found ${humansFound} human(s), observedVoiceUsers size now ${remix.voiceCache.observedVoiceUsersSize}`
|
||||
);
|
||||
return humansFound;
|
||||
}
|
||||
}
|
||||
|
||||
if (humansFound === 0 && remix.voiceCache) {
|
||||
const humans = remix.voiceCache.getHumansInChannel(cleanGuild, cleanChannel);
|
||||
for (const uid of humans) {
|
||||
humansFound++;
|
||||
logger.voiceState(
|
||||
`[Reseed] Found human ${uid} in channel ${cleanChannel} (guild ${cleanGuild}) via VoiceStateCache`
|
||||
);
|
||||
}
|
||||
|
||||
if (botId) {
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true });
|
||||
}
|
||||
}
|
||||
|
||||
if (humansFound === 0) {
|
||||
try {
|
||||
const player = remix.players.playerMap.get(cleanChannel);
|
||||
const room = player?.connection?.room;
|
||||
if (room?.isConnected && room.remoteParticipants) {
|
||||
for (const [, participant] of room.remoteParticipants) {
|
||||
const userId = participant?.identity ?? participant?.sid;
|
||||
if (userId) {
|
||||
humansFound++;
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: false });
|
||||
logger.voiceState(
|
||||
`[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild}) via LiveKit participants`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
logger.voiceState(`[Reseed] LiveKit participant fallback error: ${e?.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
logger.voiceState(
|
||||
`[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` +
|
||||
`found ${humansFound} human(s), observedVoiceUsers size now ${remix.voiceCache.observedVoiceUsersSize}`
|
||||
);
|
||||
|
||||
return humansFound;
|
||||
},
|
||||
|
||||
/** @async @private Fetch all guilds the bot is in via REST and create stub entries in the client cache for any missing guilds. This ensures settings and 24/7 lookups work even for guilds that haven't sent GUILD_CREATE yet. */
|
||||
async seedGuildsFromRest() {
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
|
||||
try {
|
||||
let after = null;
|
||||
let added = 0;
|
||||
|
||||
while (true) {
|
||||
const url = "/users/@me/guilds?limit=200" + (after ? "&after=" + after : "");
|
||||
const chunk = await client.rest.get(url);
|
||||
|
||||
if (!Array.isArray(chunk) || chunk.length === 0) break;
|
||||
|
||||
for (const g of chunk) {
|
||||
const id = g?.id;
|
||||
if (!id) continue;
|
||||
if (!client.guilds.has(id)) {
|
||||
try {
|
||||
const Guild = this._getGuildClass();
|
||||
if (Guild) {
|
||||
const stub = new Guild(client, { id, name: g.name ?? "unknown" });
|
||||
stub._stub = true;
|
||||
client.guilds.set(id, stub);
|
||||
} else {
|
||||
client.guilds.set(id, {
|
||||
id,
|
||||
name: g.name ?? "unknown",
|
||||
_stub: true,
|
||||
members: { set: () => {}, get: () => undefined, has: () => false, me: null },
|
||||
channels: { set: () => {}, get: () => undefined, has: () => false },
|
||||
roles: { set: () => {}, get: () => undefined, has: () => false },
|
||||
emojis: { set: () => {}, get: () => undefined, has: () => false },
|
||||
stickers: { set: () => {}, get: () => undefined, has: () => false },
|
||||
});
|
||||
}
|
||||
} catch (stubErr) {
|
||||
logger.guild(`[GuildSeed] Guild constructor failed for ${id}, using safe stub: ${stubErr?.message}`);
|
||||
client.guilds.set(id, {
|
||||
id,
|
||||
name: g.name ?? "unknown",
|
||||
_stub: true,
|
||||
members: { set: () => {}, get: () => undefined, has: () => false, me: null },
|
||||
channels: { set: () => {}, get: () => undefined, has: () => false },
|
||||
roles: { set: () => {}, get: () => undefined, has: () => false },
|
||||
emojis: { set: () => {}, get: () => undefined, has: () => false },
|
||||
stickers: { set: () => {}, get: () => undefined, has: () => false },
|
||||
});
|
||||
}
|
||||
added++;
|
||||
}
|
||||
}
|
||||
|
||||
if (chunk.length < 200) break;
|
||||
after = chunk[chunk.length - 1].id;
|
||||
}
|
||||
|
||||
if (added > 0) {
|
||||
logger.guild(`[GuildSeed] Added ${added} missing guild stub(s) from REST. Total: ${client.guilds.size}`);
|
||||
} else {
|
||||
logger.guild(`[GuildSeed] All guilds already cached. Total: ${client.guilds.size}`);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn("[GuildSeed] REST guild seeding failed:", err?.message ?? err);
|
||||
}
|
||||
},
|
||||
|
||||
/** @private @returns {Function|null} The Guild constructor class. */
|
||||
_getGuildClass() {
|
||||
if (this._GuildClass) return this._GuildClass;
|
||||
try {
|
||||
const { client } = this.remix;
|
||||
for (const guild of client.guilds.values()) {
|
||||
if (guild && !guild._stub && typeof guild.constructor === 'function' && guild.constructor.name === 'Guild') {
|
||||
this._GuildClass = guild.constructor;
|
||||
return this._GuildClass;
|
||||
}
|
||||
}
|
||||
} catch(e) { logger.warn("[Gateway] _getGuildClass failed:", e?.message); }
|
||||
this._GuildClass = null;
|
||||
return null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Process a confirmed guild deletion. Cleans up voice cache and previous state.
|
||||
* Does NOT delete 24/7 settings (preserved for re-invite).
|
||||
* @param {string} guildId - The deleted guild ID.
|
||||
* @private
|
||||
*/
|
||||
_processGuildDelete(guildId) {
|
||||
const { remix } = this;
|
||||
const cleanGuildId = cleanId(guildId);
|
||||
|
||||
logger.guild(
|
||||
`[GuildDelete] Received GuildDelete for server ${guildId} — ` +
|
||||
`skipping removal (24/7 removal system disabled). ` +
|
||||
`Settings and players are preserved. If the server truly removed the bot, ` +
|
||||
`the GuildCreate handler will re-initialise on re-invite.`
|
||||
);
|
||||
|
||||
remix.voiceCache.removeGuild(cleanGuildId);
|
||||
for (const [stateKey, info] of [...this._prevVoiceState]) {
|
||||
if (cleanId(info.guildId) === cleanGuildId)
|
||||
this._prevVoiceState.delete(stateKey);
|
||||
}
|
||||
remix._announcementChannelCache?.delete(guildId);
|
||||
},
|
||||
};
|
||||
|
||||
export default GuildSync;
|
||||
export { GuildSync };
|
||||
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* @module src/voice/gateway/RejoinManager
|
||||
* @description Rejoin concern for {@link GatewayHandler}: 24/7 channel
|
||||
* rejoin with exponential-backoff retries, duplicate-join guarding, and
|
||||
* guild move-in-progress detection. The MAX_REJOIN_RETRIES static lives on
|
||||
* the base GatewayHandler class (imported below).
|
||||
*
|
||||
* These methods are applied onto the GatewayHandler class prototype via
|
||||
* {@link applyMixins} — `this` is a GatewayHandler instance.
|
||||
*/
|
||||
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
import { cleanId } from "../../utils/Utils.mjs";
|
||||
import { GatewayHandler } from "./GatewayHandler.mjs";
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
* @description Rejoin manager mixin — applied to GatewayHandler.
|
||||
*/
|
||||
const RejoinManager = {
|
||||
/**
|
||||
* Attempt to spawn a player for a channel with exponential-backoff retries.
|
||||
* @param {string} channelId - The target channel ID.
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @param {number} [maxRetries=3] - Maximum retry attempts.
|
||||
* @param {number} [baseDelay=5000] - Base delay in ms (doubled each retry).
|
||||
* @param {string} [context='Rejoin'] - Label for log messages.
|
||||
* @returns {Promise<Player|null>} The spawned player, or null if all retries failed.
|
||||
* @private
|
||||
*/
|
||||
async _attemptRejoin(channelId, guildId, maxRetries = 3, baseDelay = 5_000, context = 'Rejoin') {
|
||||
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
const player = await this.remix._spawnPlayer(guildId, channelId);
|
||||
this.reseedVoiceStatesForChannel(guildId, channelId);
|
||||
logger.voice247(
|
||||
`[${context}] Successfully rejoined channel ${channelId}` +
|
||||
(attempt > 1 ? ` (after ${attempt - 1} retry/retries)` : '')
|
||||
);
|
||||
return player;
|
||||
} catch (err) {
|
||||
const errMsg = err?.message ?? String(err);
|
||||
const isTrackTimeout = errMsg.includes("track publication timed out")
|
||||
|| errMsg.includes("lavalink player create failed")
|
||||
|| errMsg.includes("Failed to create audio player")
|
||||
|| errMsg.includes("internal error");
|
||||
|
||||
if (isTrackTimeout && attempt < maxRetries) {
|
||||
const backoffMs = baseDelay * Math.pow(2, attempt - 1);
|
||||
logger.warn(
|
||||
`[${context}] Track publication failed for channel ${channelId} (attempt ${attempt}/${maxRetries}) — ` +
|
||||
`retrying in ${backoffMs / 1000}s: ${errMsg}`
|
||||
);
|
||||
await new Promise(resolve => setTimeout(resolve, backoffMs));
|
||||
continue;
|
||||
}
|
||||
|
||||
logger.warn(
|
||||
`[${context}] Failed to rejoin channel ${channelId} (attempt ${attempt}/${maxRetries}): ${errMsg}` +
|
||||
(attempt > 1 ? ` (after ${attempt} attempts)` : '')
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Safely rejoin a 24/7 channel. Guards against duplicate joins,
|
||||
* intentional leaves, missing channels, and pending joins.
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @param {string} channelId - The target channel ID.
|
||||
* @returns {Promise<Player|null>} The spawned player, or null if skipped.
|
||||
* @private
|
||||
*/
|
||||
async _rejoinChannel(guildId, channelId) {
|
||||
const { remix } = this;
|
||||
const cleanGuildId = cleanId(guildId);
|
||||
const cleanChannelId = cleanId(channelId);
|
||||
|
||||
if (this._rejoinInProgress.has(cleanChannelId)) {
|
||||
logger.voice247(`[Rejoin] Channel ${cleanChannelId} rejoin already in progress — skipping.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const existing = remix.players.playerMap.get(cleanChannelId);
|
||||
if (existing && !existing._destroyed) {
|
||||
logger.voice247(`[Rejoin] Channel ${cleanChannelId} already has a player — skipping.`);
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (remix.players._pendingJoins?.has?.(cleanChannelId)) {
|
||||
logger.voice247(`[Rejoin] Channel ${cleanChannelId} already has a pending join — skipping.`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (remix.intentionalLeaves.has(cleanChannelId)) {
|
||||
logger.voice247(`[Rejoin] Channel ${cleanChannelId} was intentionally left — skipping.`);
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
return;
|
||||
}
|
||||
|
||||
const channel = remix.client?.channels?.get?.(cleanChannelId);
|
||||
if (!channel) {
|
||||
logger.voice247(`[Rejoin] Channel ${cleanChannelId} no longer exists — skipping.`);
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
return;
|
||||
}
|
||||
|
||||
this._rejoinInProgress.add(cleanChannelId);
|
||||
|
||||
const maxRetries = GatewayHandler.MAX_REJOIN_RETRIES;
|
||||
logger.voice247(
|
||||
`[Rejoin] Attempting to rejoin channel ${cleanChannelId} in guild ${cleanGuildId}...`
|
||||
);
|
||||
|
||||
try {
|
||||
const player = await this._attemptRejoin(cleanChannelId, cleanGuildId, maxRetries, 5_000, "Rejoin");
|
||||
if (player) {
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
} else {
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
}
|
||||
return player;
|
||||
} finally {
|
||||
this._rejoinInProgress.delete(cleanChannelId);
|
||||
}
|
||||
},
|
||||
|
||||
/** @private Check whether a guild currently has a move in progress (recently connected player or pending join). Used to suppress false positive disconnect-rejoin loops. @param {string} guildId - The guild ID. @param {string} oldChannelId - The channel the bot just left. @returns {boolean} True if a move is in progress within the evidence window. */
|
||||
_isGuildMoveInProgress(guildId, oldChannelId) {
|
||||
const { remix } = this;
|
||||
const cleanGuild = cleanId(guildId);
|
||||
const cleanOld = cleanId(oldChannelId);
|
||||
if (!cleanGuild || !cleanOld) return false;
|
||||
|
||||
const now = Date.now();
|
||||
const activePlayers = [...remix.players.playerMap.values()].filter(
|
||||
p => !p._destroyed && cleanId(p._guildId ?? "") === cleanGuild
|
||||
);
|
||||
|
||||
for (const player of activePlayers) {
|
||||
const playerChannel = cleanId(player._channelId ?? "");
|
||||
if (!playerChannel || playerChannel === cleanOld) continue;
|
||||
const connectedAt = player._lastConnectedAt ?? 0;
|
||||
if (now - connectedAt < this._moveEvidenceWindowMs) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (remix.players._pendingJoins) {
|
||||
for (const pendingId of remix.players._pendingJoins) {
|
||||
const cleanPending = cleanId(pendingId);
|
||||
if (cleanPending && cleanPending !== cleanOld) {
|
||||
const pendingChannel = remix.client?.channels?.get?.(cleanPending);
|
||||
if (pendingChannel && cleanId(pendingChannel.guildId ?? "") === cleanGuild) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
};
|
||||
|
||||
export default RejoinManager;
|
||||
export { RejoinManager };
|
||||
@@ -0,0 +1,435 @@
|
||||
/**
|
||||
* @module src/voice/gateway/VoiceStateRouting
|
||||
* @description Voice-state routing concern for {@link GatewayHandler}:
|
||||
* VOICE_STATE_UPDATE dispatch (human vs. bot paths), VOICE_STATES_SYNC bulk
|
||||
* seeding, previous-state map maintenance, voice cache updates, inactivity
|
||||
* timers on human join/leave, dashboard updates, and 24/7 bot move-away /
|
||||
* disconnect handling.
|
||||
*
|
||||
* These methods are applied onto the GatewayHandler class prototype via
|
||||
* {@link applyMixins} — `this` is a GatewayHandler instance.
|
||||
*/
|
||||
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
import { get247ChannelMode } from "../../utils/Helpers247.mjs";
|
||||
import { VoiceStateCache } from "../VoiceStateCache.mjs";
|
||||
import { cleanId } from "../../utils/Utils.mjs";
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
* @description Voice-state routing mixin — applied to GatewayHandler.
|
||||
*/
|
||||
const VoiceStateRouting = {
|
||||
/**
|
||||
* Main handler for VOICE_STATE_UPDATE events. Routes to human or bot sub-handlers.
|
||||
* @param {object} data - The voice state update payload from the gateway.
|
||||
* @returns {Promise<void>}
|
||||
* @private
|
||||
*/
|
||||
async _handleVoiceStateUpdate(data) {
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
|
||||
const userId = data?.user_id;
|
||||
if (!userId) return;
|
||||
|
||||
const newChannelId = data?.channel_id ?? null;
|
||||
const vsuGuildId = data?.guild_id;
|
||||
const isBot = data?.member?.user?.bot ?? null;
|
||||
|
||||
|
||||
const prevEntry = this.findPrevVoiceStateEntry(userId, vsuGuildId);
|
||||
const prev = prevEntry.value;
|
||||
const prevSameGuild = prev &&
|
||||
cleanId(prev.guildId ?? "") === cleanId(vsuGuildId ?? "");
|
||||
const oldChannelId = prevSameGuild ? (prev?.channelId ?? null) : null;
|
||||
|
||||
|
||||
this._updatePreviousStates(userId, vsuGuildId, oldChannelId, newChannelId, isBot, prevEntry, prev);
|
||||
this._updateVoiceStateCache(userId, vsuGuildId, oldChannelId, newChannelId, isBot, prev);
|
||||
|
||||
|
||||
const { player, playerGuildId, homeChannelId } = this._findAffectedPlayer(vsuGuildId, oldChannelId, newChannelId);
|
||||
|
||||
const isBotUser = isBot === true && userId === client.user?.id;
|
||||
|
||||
if (!isBotUser) {
|
||||
|
||||
this._handleInactivityOnVoiceChange(player, playerGuildId, homeChannelId, userId, oldChannelId, newChannelId, vsuGuildId, data);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
this._handleBotVoiceChange(player, playerGuildId, homeChannelId, oldChannelId, newChannelId, vsuGuildId, data);
|
||||
},
|
||||
|
||||
/** Handle VoiceStatesSync bulk event from the gateway. @param {object} data - Sync payload with voiceStates array. @private */
|
||||
_handleVoiceStatesSync(data) {
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
const guildId = data?.guildId;
|
||||
if (!guildId || !Array.isArray(data?.voiceStates)) return;
|
||||
|
||||
const botId = client.user?.id;
|
||||
let humansAdded = 0;
|
||||
let botsAdded = 0;
|
||||
|
||||
for (const vs of data.voiceStates) {
|
||||
const userId = vs.user_id;
|
||||
const channelId = vs.channel_id;
|
||||
if (!userId || !channelId) continue;
|
||||
|
||||
const isBot = vs.member?.user?.bot ?? (userId === botId);
|
||||
|
||||
remix.voiceCache.updateUser({ guildId, userId, channelId, isBot });
|
||||
if (isBot) {
|
||||
botsAdded++;
|
||||
} else {
|
||||
humansAdded++;
|
||||
}
|
||||
}
|
||||
|
||||
if (humansAdded > 0 || botsAdded > 0) {
|
||||
logger.voiceState(
|
||||
`[VoiceStatesSync] Guild ${guildId}: seeded ${humansAdded} humans, ${botsAdded} bots ` +
|
||||
`(${data.voiceStates.length} total states).`
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
/** @private Update the voice state cache for a user joining/leaving. @param {string} userId @param {string} guildId @param {string|null} oldChannelId @param {string|null} newChannelId @param {boolean} isBot @param {object|null} prev */
|
||||
_updateVoiceStateCache(userId, guildId, oldChannelId, newChannelId, isBot, prev) {
|
||||
const { remix } = this;
|
||||
|
||||
if (newChannelId) {
|
||||
remix.voiceCache.updateUser({ guildId: guildId ?? prev?.guildId, userId, channelId: newChannelId, isBot: isBot === true });
|
||||
} else {
|
||||
const resolvedGuildId = guildId ?? prev?.guildId;
|
||||
if (resolvedGuildId) {
|
||||
remix.voiceCache.deleteHumanUser(userId, resolvedGuildId);
|
||||
remix.voiceCache.deleteBotUser(VoiceStateCache.userKey(resolvedGuildId, userId));
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/** @private Update the previous-voice-state map and evict stale entries. @param {string} userId @param {string} guildId @param {string|null} oldChannelId @param {string|null} newChannelId @param {boolean} isBot @param {object} prevEntry @param {object|null} prev */
|
||||
_updatePreviousStates(userId, guildId, oldChannelId, newChannelId, isBot, prevEntry, prev) {
|
||||
const { remix } = this;
|
||||
const prevKey = prevEntry.key;
|
||||
const nextKey = this.getPrevVoiceStateKey(userId, guildId ?? prev?.guildId);
|
||||
|
||||
if (newChannelId) {
|
||||
if (prevKey && prevKey !== nextKey) {
|
||||
const prevGuildPart = prevKey.split(":")[0];
|
||||
const nextGuildPart = nextKey.split(":")[0];
|
||||
if (prevGuildPart === nextGuildPart) {
|
||||
this._prevVoiceState.delete(prevKey);
|
||||
}
|
||||
}
|
||||
if (nextKey && this._prevVoiceState.size >= 10_000 && !this._prevVoiceState.has(nextKey)) {
|
||||
const evictKey = this._prevVoiceState.keys().next().value;
|
||||
const evictEntry = this._prevVoiceState.get(evictKey);
|
||||
this._prevVoiceState.delete(evictKey);
|
||||
if (evictEntry) {
|
||||
const evictGuildId = evictEntry.guildId;
|
||||
const evictUserId = evictKey.split(":")[1];
|
||||
if (evictGuildId && evictUserId) {
|
||||
const currentLoc = remix.voiceCache.getUserLocation(evictGuildId, evictUserId);
|
||||
if (currentLoc && currentLoc.channelId === evictEntry.channelId) {
|
||||
remix.voiceCache.updateUser({ guildId: evictGuildId, userId: evictUserId, channelId: null, isBot: evictEntry.isBot ?? false });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (nextKey) this._prevVoiceState.set(nextKey, { channelId: newChannelId, guildId: guildId ?? prev?.guildId, isBot: isBot === true });
|
||||
} else {
|
||||
if (prevKey) this._prevVoiceState.delete(prevKey);
|
||||
}
|
||||
},
|
||||
|
||||
/** @private Find a player affected by a voice state change. @param {string} guildId @param {string|null} oldChannelId @param {string|null} newChannelId @returns {{player: Player|null, playerGuildId: string|null, homeChannelId: string|null}} */
|
||||
_findAffectedPlayer(guildId, oldChannelId, newChannelId) {
|
||||
const { remix } = this;
|
||||
|
||||
|
||||
if (oldChannelId) {
|
||||
const cleanOld = cleanId(oldChannelId);
|
||||
const player = remix.players.playerMap.get(cleanOld);
|
||||
if (player) {
|
||||
return { player, playerGuildId: player._guildId, homeChannelId: player._home247Channel };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (newChannelId) {
|
||||
const cleanNew = cleanId(newChannelId);
|
||||
const player = remix.players.playerMap.get(cleanNew);
|
||||
if (player) {
|
||||
return { player, playerGuildId: player._guildId, homeChannelId: player._home247Channel };
|
||||
}
|
||||
}
|
||||
|
||||
return { player: null, playerGuildId: null, homeChannelId: null };
|
||||
},
|
||||
|
||||
/** @private Manage inactivity timers when a human joins or leaves a voice channel. @param {Player|null} player @param {string|null} playerGuildId @param {string|null} homeChannelId @param {string} userId @param {string|null} oldChannelId @param {string|null} newChannelId @param {string} vsuGuildId @param {object} vsu */
|
||||
async _handleInactivityOnVoiceChange(player, playerGuildId, homeChannelId, userId, oldChannelId, newChannelId, vsuGuildId, vsu) {
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
const resolvedGuildId = vsuGuildId ?? playerGuildId;
|
||||
if (!resolvedGuildId) return;
|
||||
|
||||
if (newChannelId) {
|
||||
try {
|
||||
const cleanId247 = cleanId(newChannelId);
|
||||
const player247 = remix.players.playerMap.get(cleanId247);
|
||||
if (player247 && typeof player247._stopInactivityTimer === "function") {
|
||||
logger.voiceState(`[VoiceState] Human joined 247 channel ${cleanId247}, stopping inactivity timer`);
|
||||
player247._stopInactivityTimer();
|
||||
}
|
||||
} catch(e) { logger.warn("[VoiceState] 247 inactivity timer stop failed:", e?.message); }
|
||||
}
|
||||
|
||||
if (oldChannelId && oldChannelId !== newChannelId) {
|
||||
try {
|
||||
const cleanOld = cleanId(oldChannelId);
|
||||
const oldPlayer = remix.players.playerMap.get(cleanOld);
|
||||
if (oldPlayer && typeof oldPlayer._startInactivityTimer === "function") {
|
||||
setTimeout(() => {
|
||||
if (!oldPlayer._hasHumansInChannel()) {
|
||||
logger.voiceState(`[VoiceState] Last human left ${cleanOld}, starting inactivity timer`);
|
||||
oldPlayer._startInactivityTimer();
|
||||
}
|
||||
}, this.T.aloneCheckDebounce);
|
||||
}
|
||||
} catch(e) { logger.warn("[VoiceState] Inactivity timer start failed:", e?.message); }
|
||||
}
|
||||
|
||||
if (newChannelId) {
|
||||
try {
|
||||
const cleanChId = cleanId(newChannelId);
|
||||
const newPlayer = remix.players.playerMap.get(cleanChId);
|
||||
if (newPlayer && typeof newPlayer._stopInactivityTimer === "function") {
|
||||
logger.voiceState(`[VoiceState] Human joined ${cleanChId}, stopping inactivity timer`);
|
||||
newPlayer._stopInactivityTimer();
|
||||
}
|
||||
} catch(e) { logger.warn("[VoiceState] Inactivity timer stop failed:", e?.message); }
|
||||
}
|
||||
|
||||
if (remix.dashboard?.enabled) {
|
||||
try {
|
||||
let userObj = vsu?.member?.user;
|
||||
if (!userObj) {
|
||||
try { userObj = await client.users.fetch(userId).catch(() => null); } catch(e) { logger.warn("[VoiceState] Dashboard user fetch failed:", e?.message); }
|
||||
}
|
||||
if (userObj) {
|
||||
const details = {
|
||||
type: newChannelId ? "join" : "leave",
|
||||
guildId: resolvedGuildId,
|
||||
channelId: newChannelId ?? null,
|
||||
oldChannelId: oldChannelId ?? null,
|
||||
};
|
||||
remix.dashboard.updateUser(details, userObj);
|
||||
}
|
||||
|
||||
const refChannel = newChannelId ?? oldChannelId;
|
||||
const cleanId_ref = refChannel ? cleanId(refChannel) : null;
|
||||
|
||||
if (cleanId_ref) {
|
||||
const dashPlayer = remix.players.playerMap.get(cleanId_ref);
|
||||
if (dashPlayer) {
|
||||
const eventType = newChannelId ? "join" : "leave";
|
||||
remix.dashboard.updatePlayer({
|
||||
type: eventType,
|
||||
data: userId,
|
||||
}, dashPlayer);
|
||||
|
||||
remix.dashboard.playerUpdate({
|
||||
type: eventType,
|
||||
}, dashPlayer);
|
||||
}
|
||||
}
|
||||
} catch(e) { logger.warn("[VoiceState] Dashboard update failed:", e?.message); }
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Handle a voice state update for the bot itself.
|
||||
* Detects move-away from 24/7 channels and unexpected disconnects.
|
||||
* @param {Player|null} player - The affected player (if any).
|
||||
* @param {string|null} playerGuildId - The guild ID from the player.
|
||||
* @param {string|null} homeChannelId - The 24/7 home channel ID from the player.
|
||||
* @param {string|null} oldChannelId - The channel the bot was in.
|
||||
* @param {string|null} newChannelId - The channel the bot moved to (null if disconnected).
|
||||
* @param {string} vsuGuildId - The guild ID from the VSU event.
|
||||
* @param {object} vsu - The raw VSU payload.
|
||||
* @private
|
||||
*/
|
||||
_handleBotVoiceChange(player, playerGuildId, homeChannelId, oldChannelId, newChannelId, vsuGuildId, vsu) {
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
const guildId = vsuGuildId;
|
||||
|
||||
if (newChannelId && guildId && oldChannelId && oldChannelId !== newChannelId) {
|
||||
// During boot recovery, ignore move events — the recovery loop handles rejoining.
|
||||
if (this._bootRecoveryActive) {
|
||||
logger.voice247(
|
||||
`[247] Ignoring bot move ${cleanId(oldChannelId)} → ${cleanId(newChannelId)} during boot recovery.`
|
||||
);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const cleanNew = cleanId(newChannelId);
|
||||
const cleanOld = cleanId(oldChannelId);
|
||||
|
||||
// Check if old channel is a saved 24/7 channel
|
||||
const oldIs247 = (() => {
|
||||
try {
|
||||
const set = remix.settingsMgr.getServer(guildId);
|
||||
return get247ChannelMode(set, cleanOld) === "on";
|
||||
} catch (_) { return false; }
|
||||
})();
|
||||
|
||||
// Check if new channel is a saved 24/7 channel or has a pending spawn
|
||||
const newChannelSaved = (() => {
|
||||
try {
|
||||
const set = remix.settingsMgr.getServer(guildId);
|
||||
return get247ChannelMode(set, cleanNew) === "on";
|
||||
} catch (_) { return false; }
|
||||
})();
|
||||
const newChannelPendingSpawn = remix.players?._pendingJoins?.has?.(cleanNew) || false;
|
||||
|
||||
const existingPlayer = remix.players.playerMap.get(cleanOld);
|
||||
|
||||
if (oldIs247 && existingPlayer) {
|
||||
// Old channel is 24/7 — bot physically moved away, so the voice
|
||||
// connection to old channel is dead. Destroy the old player and
|
||||
// schedule a fresh rejoin so it gets a new live connection.
|
||||
logger.voice247(
|
||||
`[247] Bot moved away from 24/7 channel ${cleanOld} → ${cleanNew}. ` +
|
||||
`Destroying stale player, scheduling rejoin for ${cleanOld}.`
|
||||
);
|
||||
remix.players.playerMap.delete(cleanOld);
|
||||
const homeCh = cleanId(existingPlayer._home247Channel ?? "");
|
||||
if (homeCh && homeCh !== cleanOld) remix.players.playerMap.delete(homeCh);
|
||||
try { existingPlayer.destroy(); } catch (_) {}
|
||||
const rejoinDelay = this.T.rejoin247Delay ?? 3_000;
|
||||
setTimeout(() => {
|
||||
this._rejoinChannel(cleanId(guildId), cleanOld).catch(err => {
|
||||
logger.warn(`[247] Failed to rejoin ${cleanOld} after move-away:`, err.message);
|
||||
});
|
||||
}, rejoinDelay);
|
||||
} else if (newChannelSaved || newChannelPendingSpawn) {
|
||||
// New channel is already 24/7 or being spawned — keep both, don't rekey.
|
||||
logger.voice247(
|
||||
`[247] Keeping both channels ${cleanOld} and ${cleanNew} ` +
|
||||
`(saved=${newChannelSaved} pending=${newChannelPendingSpawn})`
|
||||
);
|
||||
} else if (existingPlayer && cleanNew !== cleanOld) {
|
||||
// Neither channel is 24/7 — safe to rekey the player.
|
||||
const targetChannel = client.channels.get(cleanNew)
|
||||
?? client.channels.get?.(cleanNew)
|
||||
?? null;
|
||||
const targetGuildId = cleanId(targetChannel?.guildId ?? targetChannel?.guild?.id ?? guildId ?? "");
|
||||
|
||||
const playerAtNewKey = remix.players.playerMap.get(cleanNew);
|
||||
if (!playerAtNewKey || playerAtNewKey === existingPlayer) {
|
||||
remix.players.playerMap.delete(cleanOld);
|
||||
remix.players.playerMap.set(cleanNew, existingPlayer);
|
||||
existingPlayer._channelId = cleanNew;
|
||||
existingPlayer._home247Channel = cleanNew;
|
||||
if (targetGuildId) existingPlayer._guildId = targetGuildId;
|
||||
logger.voice247(`[247] Re-keyed playerMap ${cleanOld} → ${cleanNew}`);
|
||||
} else {
|
||||
logger.voice247(
|
||||
`[247] Skipped re-key ${cleanOld} → ${cleanNew} (new key occupied by another player)`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Simplified 24/7: stay_247 list only changes via !247 command.
|
||||
// Do NOT auto-add/remove channels on bot move.
|
||||
} catch (e) {
|
||||
logger.warn("[247] Bot move handler failed:", e.message);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (!newChannelId && oldChannelId && guildId) {
|
||||
try {
|
||||
const cleanOld = cleanId(oldChannelId);
|
||||
const cleanGuild = cleanId(guildId);
|
||||
|
||||
if (this._inStartupGrace) {
|
||||
const bootPlayer = remix.players.playerMap.get(cleanOld);
|
||||
if (bootPlayer && !bootPlayer._destroyed) {
|
||||
logger.voiceState(
|
||||
`[VoiceState] Bot disconnected from ${cleanOld} during startup grace — ` +
|
||||
`player still active, ignoring stale disconnect.`
|
||||
);
|
||||
} else {
|
||||
logger.voiceState(
|
||||
`[VoiceState] Bot disconnected from ${cleanOld} during startup grace — ` +
|
||||
`deferring until grace period ends.`
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (remix.intentionalLeaves.has(cleanOld)) {
|
||||
logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — intentional leave.`);
|
||||
} else if (this._isGuildMoveInProgress(cleanGuild, cleanOld)) {
|
||||
logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — guild move in progress, skipping.`);
|
||||
} else if (this._bootRecoveryActive) {
|
||||
logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — boot recovery active, skipping.`);
|
||||
} else {
|
||||
const set = remix.settingsMgr.getServer(guildId);
|
||||
const mode = set ? get247ChannelMode(set, cleanOld) : "off";
|
||||
const wsInduced = this.isWsReconnectRecent();
|
||||
|
||||
if (mode === "on" || wsInduced) {
|
||||
const reason = wsInduced && mode !== "on"
|
||||
? `WS reconnect detected (${Math.round((Date.now() - this._lastReadyAt) / 1000)}s ago) — treating as transient, scheduling rejoin`
|
||||
: `24/7 mode — scheduling rejoin`;
|
||||
logger.voice247(
|
||||
`[VoiceState] Bot unexpectedly disconnected from ${cleanOld} — ${reason}.`
|
||||
);
|
||||
const discPlayer = remix.players.playerMap.get(cleanOld);
|
||||
if (discPlayer && !discPlayer._destroyed) {
|
||||
remix.players.playerMap.delete(cleanOld);
|
||||
const homeChannel = cleanId(discPlayer._home247Channel ?? "");
|
||||
if (homeChannel && homeChannel !== cleanOld) {
|
||||
remix.players.playerMap.delete(homeChannel);
|
||||
}
|
||||
try { discPlayer.destroy(); } catch(e) { logger.warn("[VoiceState] Player destroy failed:", e?.message); }
|
||||
const pendingScrobble = remix.players._pendingScrobbleTimers?.get(cleanOld);
|
||||
if (pendingScrobble) {
|
||||
clearTimeout(pendingScrobble.timer);
|
||||
remix.players._pendingScrobbleTimers.delete(cleanOld);
|
||||
}
|
||||
}
|
||||
const rejoinDelay = this.T.rejoin247Delay ?? 3_000;
|
||||
setTimeout(() => {
|
||||
this._rejoinChannel(cleanGuild, cleanOld).catch(err => {
|
||||
logger.warn(`[VoiceState] Failed to rejoin ${cleanOld} after disconnect:`, err.message);
|
||||
});
|
||||
}, rejoinDelay);
|
||||
} else {
|
||||
const leavePlayer = remix.players.playerMap.get(cleanOld);
|
||||
if (leavePlayer && !leavePlayer.leaving && !leavePlayer._destroyed) {
|
||||
logger.voiceState(
|
||||
`[VoiceState] Bot disconnected from ${cleanOld} (24/7 mode: ${mode}) — emitting autoleave.`
|
||||
);
|
||||
leavePlayer.emit("autoleave");
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[VoiceState] Bot disconnect handler failed:", e.message);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export default VoiceStateRouting;
|
||||
export { VoiceStateRouting };
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* @module src/voice/gateway
|
||||
* @description Barrel for the gateway layer: re-exports the GatewayHandler
|
||||
* base class with its applied mixins (VoiceStateRouting, GuildSync,
|
||||
* RejoinManager).
|
||||
*/
|
||||
|
||||
export { GatewayHandler } from "./GatewayHandler.mjs";
|
||||
Reference in new issue
Block a user