diff --git a/commands/test.mjs b/commands/test.mjs index 47dafba..8fe269d 100644 --- a/commands/test.mjs +++ b/commands/test.mjs @@ -16,13 +16,28 @@ export async function run(msg, data) { const channelCounts = new Map(); - for (const [, state] of this.observedVoiceUsers) { - if (state.guildId !== guild.id) continue; - channelCounts.set(state.channelId, (channelCounts.get(state.channelId) ?? 0) + 1); - } - for (const [, state] of this.observedVoiceBots) { - if (state.guildId !== guild.id) continue; - channelCounts.set(state.channelId, (channelCounts.get(state.channelId) ?? 0) + 1); + // Use VoiceStateCache API for both humans and bots + const cache = this.voiceCache ?? this.observedVoiceUsers; + if (cache) { + // Humans + if (typeof cache.iterateHumanUsers === "function") { + for (const [, state] of cache.iterateHumanUsers()) { + if (state.guildId !== guild.id) continue; + channelCounts.set(state.channelId, (channelCounts.get(state.channelId) ?? 0) + 1); + } + } else { + for (const [, state] of cache) { + if (state.guildId !== guild.id) continue; + channelCounts.set(state.channelId, (channelCounts.get(state.channelId) ?? 0) + 1); + } + } + // Bots + if (typeof cache.iterateBotUsers === "function") { + for (const [, state] of cache.iterateBotUsers()) { + if (state.guildId !== guild.id) continue; + channelCounts.set(state.channelId, (channelCounts.get(state.channelId) ?? 0) + 1); + } + } } if (channelCounts.size === 0) { diff --git a/src/GatewayHandler.mjs b/src/GatewayHandler.mjs index 551c41c..b82e3b6 100644 --- a/src/GatewayHandler.mjs +++ b/src/GatewayHandler.mjs @@ -324,17 +324,15 @@ export class GatewayHandler { } } - // ── Fallback: observedVoiceUsers ──────────────────────────────────────── - if (humansFound === 0) { - for (const [uid, info] of remix.observedVoiceUsers) { - const infoGuild = String(info.guildId ?? "").replace(/\D/g, ""); - const infoChannel = String(info.channelId ?? "").replace(/\D/g, ""); - if (infoGuild === cleanGuild && infoChannel === cleanChannel) { - humansFound++; - logger.voiceState( - `[Reseed] Found human ${uid} in channel ${cleanChannel} (guild ${cleanGuild}) via observedVoiceUsers` - ); - } + // ── Fallback: VoiceStateCache (was observedVoiceUsers) ──────────────── + if (humansFound === 0 && remix.voiceCache) { + // O(1) lookup via channelMembers index instead of full scan + 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` + ); } // Update bot's own entry diff --git a/src/PlayerManager.mjs b/src/PlayerManager.mjs index 26226e9..55b0431 100644 --- a/src/PlayerManager.mjs +++ b/src/PlayerManager.mjs @@ -462,13 +462,17 @@ export class PlayerManager { const seedObserved = (channelId) => { const cleanChannelId = cleanId(channelId); if (!cleanChannelId) return null; - if (!this.observedVoiceUsers?.has(userId)) { - this.observedVoiceUsers?.set(userId, { channelId: cleanChannelId, guildId: cleanGuild }); + // Use voiceCache (O(1) with guildId) or fall back to observedVoiceUsers + const cache = this.voiceCache ?? this.observedVoiceUsers; + if (cache && !cache.has(userId, cleanGuild)) { + cache.set(userId, { channelId: cleanChannelId, guildId: cleanGuild }); } - return cleanId(this.observedVoiceUsers?.get(userId)?.channelId) || cleanChannelId; + const loc = cache?.get(userId, cleanGuild); + return cleanId(loc?.channelId) || cleanChannelId; }; - const observed = this.observedVoiceUsers?.get?.(userId); + const cache = this.voiceCache ?? this.observedVoiceUsers; + const observed = cache?.get?.(userId, cleanGuild); if (cleanId(observed?.guildId) === cleanGuild) { const observedChannelId = cleanId(observed?.channelId); if (observedChannelId) return observedChannelId; @@ -1018,8 +1022,8 @@ export class PlayerManager { const users = this.voiceCache.getHumansInChannel(guildId, channelId); humanUserIds.push(...users); } else if (this.observedVoiceUsers) { - // Legacy fallback - for (const [uid, info] of this.observedVoiceUsers.iterateHumanUsers()) { + // Legacy fallback (VoiceStateCache is iterable via [Symbol.iterator]) + for (const [uid, info] of this.observedVoiceUsers) { if (cleanId(info.guildId) === guildId && cleanId(info.channelId) === channelId) { humanUserIds.push(uid); } diff --git a/src/constants/VoiceStateCache.mjs b/src/constants/VoiceStateCache.mjs index a0f590a..3b09ad1 100644 --- a/src/constants/VoiceStateCache.mjs +++ b/src/constants/VoiceStateCache.mjs @@ -503,6 +503,141 @@ export class VoiceStateCache { return this.botLocations.has(compositeKey); } + // ── Map-compatible iteration ───────────────────────────────────────────── + // Allows `for (const [uid, info] of voiceCache)` to work the same as + // `for (const [uid, info] of observedVoiceUsers)` on a raw Map. + // Delegates to iterateHumanUsers() so the yielded shape matches. + + /** + * Default iterator — iterates human users. + * Yields [userId, {channelId, guildId}] — same shape as old observedVoiceUsers Map. + */ + *[Symbol.iterator]() { + for (const [uKey, loc] of this.userLocations) { + yield [loc.userId, { channelId: loc.channelId, guildId: loc.guildId }]; + } + } + + /** + * Backward-compat with `observedVoiceUsers.size`. + */ + get size() { return this.userLocations.size; } + + /** + * Backward-compat with `observedVoiceUsers.has(userId)`. + * If called with a single argument (userId), scans all guilds. + * If called with two arguments (userId, guildId), does O(1) lookup. + * + * @param {string} userId + * @param {string} [guildId] + * @returns {boolean} + */ + has(userId, guildId) { + if (guildId !== undefined) { + return this.userLocations.has(VoiceStateCache.userKey(guildId, userId)); + } + // Legacy: scan for first match by userId only + const cleanUser = String(userId).replace(/\D/g, ""); + for (const [, loc] of this.userLocations) { + if (loc.userId === cleanUser) return true; + } + return false; + } + + /** + * Backward-compat with `observedVoiceUsers.get(userId)`. + * If called with a single argument (userId), returns first match across all guilds. + * If called with two arguments (userId, guildId), does O(1) lookup. + * + * @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; + } + // Legacy: scan for first match by userId only + const cleanUser = String(userId).replace(/\D/g, ""); + for (const [, loc] of this.userLocations) { + if (loc.userId === cleanUser) return { channelId: loc.channelId, guildId: loc.guildId }; + } + return undefined; + } + + /** + * Backward-compat with `observedVoiceUsers.set(userId, {channelId, guildId})`. + * + * @param {string} userId + * @param {{channelId: string, guildId: string}} info + */ + set(userId, info) { + const guildId = info?.guildId; + const channelId = info?.channelId; + if (guildId && channelId) { + this.updateUser({ guildId, userId, channelId, isBot: false }); + } + } + + /** + * Backward-compat with `observedVoiceUsers.delete(userId)`. + * + * @param {string} userId + * @param {string} [guildId] + */ + delete(userId, guildId) { + if (guildId !== undefined) { + this.updateUser({ guildId, userId, channelId: null, isBot: false }); + } else { + // Legacy: remove from ALL guilds + const cleanUser = String(userId).replace(/\D/g, ""); + 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 }); + } + } + } + + /** + * Backward-compat with `observedVoiceUsers.forEach(fn)`. + * + * @param {Function} fn callback(userId, info, cache) + */ + forEach(fn) { + for (const [userId, info] of this) { + fn(userId, info, this); + } + } + + /** + * Backward-compat with `observedVoiceUsers.entries()`. + */ + *entries() { + yield* this; + } + + /** + * Backward-compat with `observedVoiceUsers.keys()`. + */ + *keys() { + for (const [userId] of this) { + yield userId; + } + } + + /** + * Backward-compat with `observedVoiceUsers.values()`. + */ + *values() { + for (const [, info] of this) { + yield info; + } + } + // ── Debug / stats ──────────────────────────────────────────────────────── get stats() { diff --git a/src/dashboard/Dashboard.mjs b/src/dashboard/Dashboard.mjs index c30cc42..7d6830c 100644 --- a/src/dashboard/Dashboard.mjs +++ b/src/dashboard/Dashboard.mjs @@ -129,7 +129,7 @@ export class Dashboard { // Validate textChannel: if it's a voice channel (type === 2) or missing, // find a suitable text channel from the guild instead const isText = (ch) => ch && (ch.type === 0 || ch.type === 5 || ch.type === 13 || - (typeof ch.isText === "function" && ch.isText())); + (typeof ch.isText === "function" && ch.isText())); if (!isText(textChannel)) { // Auto-pick a text channel from the guild @@ -272,9 +272,10 @@ export class Dashboard { // Return the user's current voice channel (if any) if (!user) return { channel: null }; const userId = String(user.id).replace(/\D/g, ""); - // Check observedVoiceUsers first (most reliable for Fluxer) - if (this.remix.observedVoiceUsers) { - for (const [mapUserId, info] of this.remix.observedVoiceUsers) { + // Check VoiceStateCache first (most reliable for Fluxer) + // Uses O(1) lookup via iterateHumanUsers() / [Symbol.iterator] + if (this.remix.voiceCache) { + for (const [mapUserId, info] of this.remix.voiceCache) { if (String(mapUserId).replace(/\D/g, "") === userId && info.channelId) { const ch = this.remix.client.channels.get(info.channelId); return { @@ -362,8 +363,16 @@ export class Dashboard { const cleanChanId = String(player._channelId ?? "").replace(/\D/g, ""); if (!cleanChanId) return "Player has no active channel"; - const observed = this.remix.observedVoiceUsers; + const observed = this.remix.voiceCache; if (observed) { + // O(1) lookup: check if user is in the same channel as the player + const guildId = String(player._guildId ?? "").replace(/\D/g, ""); + const userLoc = observed.get(cleanUserId, guildId || undefined); + if (userLoc) { + const infoChannelId = String(userLoc.channelId ?? "").replace(/\D/g, ""); + if (infoChannelId === cleanChanId) return null; + } + // Legacy scan fallback (user might not have guildId) for (const [mapUserId, info] of observed) { if (String(mapUserId).replace(/\D/g, "") === cleanUserId) { const infoChannelId = String(info.channelId ?? "").replace(/\D/g, ""); @@ -472,8 +481,8 @@ export class Dashboard { // 5=announcement, 13=stage, 15=form, 16=forum, 17=media const isCategory = type === 4; const isText = !isVoice && !isCategory && ( - type === 0 || type === 5 || type === 13 || - (typeof channel.isText === "function" && channel.isText()) + type === 0 || type === 5 || type === 13 || + (typeof channel.isText === "function" && channel.isText()) ); let voiceParticipants = []; if (isVoice) { @@ -521,8 +530,8 @@ export class Dashboard { ? [...channelStore.values()] : []; const allChannels = channelValues - .map(Dashboard.convertChannel) - .filter(c => !c.isCategory); // exclude categories — they are not joinable + .map(Dashboard.convertChannel) + .filter(c => !c.isCategory); // exclude categories — they are not joinable // Build icon URL using fluxerusercontent.com CDN pattern // guild.icon is the icon hash string; guild.id is the server ID @@ -602,22 +611,36 @@ export class Dashboard { } } } - // Fallback: observedVoiceUsers (seeded from READY/GUILD_CREATE). + // Fallback: VoiceStateCache (seeded from READY/GUILD_CREATE). // After a bot reload, guild.voice_states may only contain the bot's - // own voice state, while observedVoiceUsers has ALL humans who were + // own voice state, while VoiceStateCache has ALL humans who were // already in voice when the bot reconnected. - const ovu = player._observedVoiceUsers; - if (ovu && cleanChannelId && cleanGuildId) { - for (const [mapUserId, info] of ovu) { - if (seen.has(mapUserId)) continue; - const infoCh = String(info.channelId ?? "").replace(/\D/g, ""); - const infoG = String(info.guildId ?? "").replace(/\D/g, ""); - if (infoCh === cleanChannelId && infoG === cleanGuildId) { - // Skip the bot itself + // Try O(1) channel lookup first, then fall back to iteration. + const vc = player._voiceCache ?? player._observedVoiceUsers; + if (vc && cleanChannelId && cleanGuildId) { + // O(1) lookup via getHumansInChannel + if (typeof vc.getHumansInChannel === "function") { + const channelHumans = vc.getHumansInChannel(cleanGuildId, cleanChannelId); + for (const hid of channelHumans) { + if (seen.has(hid)) continue; const botId = player.client?.user?.id; - if (botId && String(mapUserId) === String(botId)) continue; - ids.push(String(mapUserId)); - seen.add(mapUserId); + if (botId && String(hid) === String(botId)) continue; + ids.push(String(hid)); + seen.add(hid); + } + } else { + // Legacy iteration fallback + for (const [mapUserId, info] of vc) { + if (seen.has(mapUserId)) continue; + const infoCh = String(info.channelId ?? "").replace(/\D/g, ""); + const infoG = String(info.guildId ?? "").replace(/\D/g, ""); + if (infoCh === cleanChannelId && infoG === cleanGuildId) { + // Skip the bot itself + const botId = player.client?.user?.id; + if (botId && String(mapUserId) === String(botId)) continue; + ids.push(String(mapUserId)); + seen.add(mapUserId); + } } } } @@ -839,4 +862,4 @@ export class Dashboard { return "Invalid code."; } -} \ No newline at end of file +}