mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-23 21:52:45 -05:00
hotfix for VoiceStateCache.mjs
This commit is contained in:
1 parent
16e4f853a6
commit
68938e0d29
7 files changed
+832
-223
No files matched your search
@@ -13,6 +13,7 @@ import { FluxerRevoice } from "./src/constants/FluxerRevoice.mjs";
|
||||
import { MoonlinkManager } from "./src/MoonlinkManager.mjs";
|
||||
import { Dashboard } from "./src/dashboard/Dashboard.mjs";
|
||||
import { Locale } from "./src/constants/Locale.mjs";
|
||||
import { VoiceStateCache } from "./src/constants/VoiceStateCache.mjs";
|
||||
import { GatewayHandler } from "./src/GatewayHandler.mjs";
|
||||
import { LastFmManager } from "./src/LastFmManager.mjs";
|
||||
|
||||
@@ -159,12 +160,21 @@ export class Remix {
|
||||
this.moonlink = null;
|
||||
let moonlinkInitialised = false;
|
||||
|
||||
// ── Voice state tracking maps (created early so all modules can reference) ──
|
||||
this.observedVoiceUsers = new Map();
|
||||
this.observedVoiceBots = new Map();
|
||||
// ── Voice state tracking — indexed cache with LRU eviction ──────────
|
||||
// Replaces raw observedVoiceUsers/observedVoiceBots Maps with O(1)
|
||||
// channel-member lookups, composite keys, and bounded memory.
|
||||
this.voiceCache = new VoiceStateCache({ maxUsers: 50_000, maxBots: 10_000 });
|
||||
|
||||
// ── Backward-compat aliases (deprecated — use voiceCache directly) ───
|
||||
// These expose the same .size / .get / .set / .has / .delete / iteration
|
||||
// interface so existing code (dashboard, commands) continues to work.
|
||||
this.observedVoiceUsers = this.voiceCache;
|
||||
this.observedVoiceBots = this.voiceCache;
|
||||
|
||||
// ── Caches ───────────────────────────────────────────────────────────────
|
||||
// _announcementChannelCache: TTL-based (5 min), auto-evicts stale entries
|
||||
this._announcementChannelCache = new Map();
|
||||
this._announcementChannelTTL = 5 * 60 * 1000; // 5 min
|
||||
this.intentionalLeaves = new Map();
|
||||
|
||||
// ── Gateway Handler ─────────────────────────────────────────────────────
|
||||
@@ -305,9 +315,12 @@ export class Remix {
|
||||
timers: this.T,
|
||||
});
|
||||
this.players.observedVoiceUsers = this.observedVoiceUsers;
|
||||
this.players.voiceCache = this.voiceCache;
|
||||
this.players._lastfm = this.lastfm;
|
||||
|
||||
// ── Periodic alone-check ───────────────────────────────────────────────────
|
||||
// Uses VoiceStateCache.channelMembers index for O(1) per-player lookup
|
||||
// instead of iterating ALL observedVoiceUsers (which was O(N×M)).
|
||||
const ALONE_CHECK_INTERVAL = this.T.aloneCheckInterval;
|
||||
setInterval(() => {
|
||||
for (const [mapKey, player] of this.players.playerMap) {
|
||||
@@ -334,17 +347,10 @@ export class Remix {
|
||||
|
||||
if (player._is247Enabled()) continue;
|
||||
|
||||
let hasHuman = false;
|
||||
for (const [, info] of this.observedVoiceUsers) {
|
||||
const infoChannel = String(info.channelId ?? "").replace(/\D/g, "");
|
||||
const infoGuild = String(info.guildId ?? "").replace(/\D/g, "");
|
||||
if (infoGuild === cleanGuildId && infoChannel === cleanChanId) {
|
||||
hasHuman = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// O(1) lookup via VoiceStateCache channelMembers index
|
||||
let hasHuman = this.voiceCache.hasHumansInChannel(cleanGuildId, cleanChanId);
|
||||
|
||||
// Fallback: check guild voice_states cache if observedVoiceUsers
|
||||
// Fallback: check guild voice_states cache if voiceCache
|
||||
// didn't find anyone (can happen after bot restart before reseed).
|
||||
if (!hasHuman) {
|
||||
try {
|
||||
@@ -364,9 +370,9 @@ export class Remix {
|
||||
const isBot = member?.user?.bot ?? state?.member?.user?.bot ?? false;
|
||||
if (!isBot) {
|
||||
hasHuman = true;
|
||||
// Also update observedVoiceUsers so future checks are fast
|
||||
// Also update voiceCache so future checks are O(1)
|
||||
if (stateUserId) {
|
||||
this.observedVoiceUsers.set(stateUserId, { channelId: cleanChanId, guildId: cleanGuildId });
|
||||
this.voiceCache.updateUser({ guildId: cleanGuildId, userId: stateUserId, channelId: cleanChanId, isBot: false });
|
||||
}
|
||||
break;
|
||||
}
|
||||
@@ -377,8 +383,6 @@ export class Remix {
|
||||
}
|
||||
|
||||
// Fallback: check LiveKit remote participants if guild cache is empty.
|
||||
// This is the most reliable source of truth — if the bot's LiveKit room
|
||||
// has remote participants, those are real humans in the channel.
|
||||
if (!hasHuman) {
|
||||
try {
|
||||
const room = player.connection?.room;
|
||||
@@ -427,10 +431,7 @@ export class Remix {
|
||||
|
||||
logger.voice(`[checkVC] userId=${userId} guildId=${guildId}`);
|
||||
logger.voice(`[checkVC] channel keys: ${Object.keys(message?.channel ?? {}).join(",")}`);
|
||||
logger.voice(`[checkVC] observedVoiceUsers size=${self.observedVoiceUsers.size}`);
|
||||
for (const [uid, info] of self.observedVoiceUsers) {
|
||||
logger.voice(`[checkVC] stored: uid=${uid} channelId=${info.channelId} guildId=${info.guildId}`);
|
||||
}
|
||||
logger.voice(`[checkVC] voiceCache humans=${self.voiceCache.observedVoiceUsersSize} bots=${self.voiceCache.observedVoiceBotsSize}`);
|
||||
|
||||
if (!userId || !guildId) {
|
||||
logger.voice(`[checkVC] BAIL — missing userId or guildId`);
|
||||
@@ -440,16 +441,16 @@ export class Remix {
|
||||
const cleanGuild = String(guildId).replace(/\D/g, "");
|
||||
|
||||
const seed = (channelId) => {
|
||||
if (!self.observedVoiceUsers.has(userId)) {
|
||||
self.observedVoiceUsers.set(userId, { channelId, guildId: cleanGuild });
|
||||
if (!self.voiceCache.hasHumanUser(userId, cleanGuild)) {
|
||||
self.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId, isBot: false });
|
||||
}
|
||||
return self.observedVoiceUsers.get(userId)?.channelId ?? channelId;
|
||||
return self.voiceCache.getUserChannel(cleanGuild, userId) ?? channelId;
|
||||
};
|
||||
|
||||
const observed = self.observedVoiceUsers.get(userId);
|
||||
const observed = self.voiceCache.getUserLocation(cleanGuild, userId);
|
||||
logger.voice(`[checkVC] observed=${JSON.stringify(observed)} cleanGuild=${cleanGuild}`);
|
||||
if (observed && String(observed.guildId).replace(/\D/g, "") === cleanGuild) {
|
||||
logger.voice(`[checkVC] HIT observedVoiceUsers → ${observed.channelId}`);
|
||||
if (observed && observed.channelId) {
|
||||
logger.voice(`[checkVC] HIT voiceCache → ${observed.channelId}`);
|
||||
return observed.channelId;
|
||||
}
|
||||
|
||||
@@ -505,13 +506,10 @@ export class Remix {
|
||||
} catch (e) { logger.voice(`[checkVC] guild error: ${e.message}`); }
|
||||
|
||||
try {
|
||||
for (const [uid, info] of self.observedVoiceUsers) {
|
||||
if (uid !== userId) continue;
|
||||
logger.voice(`[checkVC] last-resort: uid=${uid} stored.guildId=${info.guildId} cleanGuild=${cleanGuild}`);
|
||||
if (String(info.guildId).replace(/\D/g, "") === cleanGuild) {
|
||||
logger.voice(`[checkVC] HIT last-resort → ${info.channelId}`);
|
||||
return info.channelId;
|
||||
}
|
||||
const loc = self.voiceCache.getHumanUser(userId); // scan all guilds
|
||||
if (loc && String(loc.guildId ?? "").replace(/\D/g, "") === cleanGuild) {
|
||||
logger.voice(`[checkVC] HIT voiceCache scan → ${loc.channelId}`);
|
||||
return loc.channelId;
|
||||
}
|
||||
} catch (e) { logger.voice(`[checkVC] last-resort error: ${e.message}`); }
|
||||
|
||||
@@ -673,10 +671,9 @@ export class Remix {
|
||||
if (!cleanChannelId) throw new Error("_spawnPlayer: invalid channelId");
|
||||
|
||||
// Already have a player for this channel?
|
||||
// Use guild→player reverse index for O(1) lookup, fallback to playerMap.get()
|
||||
const existing = this.players.playerMap.get(cleanChannelId)
|
||||
?? [...this.players.playerMap.values()].find(p =>
|
||||
String(p?._channelId ?? "").replace(/\D/g, "") === cleanChannelId
|
||||
);
|
||||
?? this.players.getPlayerByGuildAndChannel(cleanGuildId, cleanChannelId);
|
||||
if (existing) return existing;
|
||||
|
||||
// Guard: moonlink must be ready
|
||||
@@ -702,6 +699,7 @@ export class Remix {
|
||||
revoice: this.revoice ?? null,
|
||||
settingsMgr: this.settingsMgr ?? this.settings ?? null,
|
||||
observedVoiceUsers: this.observedVoiceUsers ?? null,
|
||||
voiceCache: this.voiceCache ?? null,
|
||||
locale: this.locale ?? null,
|
||||
});
|
||||
|
||||
@@ -739,6 +737,7 @@ export class Remix {
|
||||
|
||||
// Add to playerMap only after join succeeds
|
||||
this.players.playerMap.set(cleanChannelId, player);
|
||||
this.players._indexPlayer(cleanGuildId, cleanChannelId);
|
||||
if (this.players._pendingJoins) {
|
||||
this.players._pendingJoins.delete(cleanChannelId);
|
||||
}
|
||||
@@ -865,15 +864,14 @@ export class Remix {
|
||||
isMember = true;
|
||||
}
|
||||
|
||||
// 2. Fallback — observed voice users (REST-less)
|
||||
// 2. Fallback — check voiceCache for this guild (O(1) per guild)
|
||||
if (!isMember) {
|
||||
const cleanGuildId = String(guild.id).replace(/\D/g, "");
|
||||
for (const [, info] of (this.observedVoiceUsers ?? [])) {
|
||||
if (String(info.guildId ?? "").replace(/\D/g, "") === cleanGuildId) {
|
||||
isMember = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
// Check if any human users are tracked in this guild
|
||||
const hasVoiceUsers = [...this.voiceCache.userLocations.values()].some(
|
||||
loc => loc.guildId === cleanGuildId
|
||||
);
|
||||
if (hasVoiceUsers) isMember = true;
|
||||
}
|
||||
|
||||
// 3. Slow path — REST fetch for large guilds with incomplete caches
|
||||
|
||||
+100
-134
@@ -3,6 +3,7 @@ import { getVoiceManager } from "@fluxerjs/voice";
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
import { ServerSettings } from "./Settings.mjs";
|
||||
import { get247ChannelMode, remove247ChannelMode } from "./constants/Helpers247.mjs";
|
||||
import { VoiceStateCache } from "./constants/VoiceStateCache.mjs";
|
||||
import mysql from "mysql2";
|
||||
|
||||
/**
|
||||
@@ -128,25 +129,23 @@ export class GatewayHandler {
|
||||
// The bot's own ID is included in voiceStates — track it as a bot
|
||||
const botId = client.user?.id;
|
||||
if (userId === botId) {
|
||||
const botKey = this.getObservedVoiceBotKey(userId, cleanGuildId);
|
||||
if (botKey) remix.observedVoiceBots.set(botKey, { channelId, guildId: cleanGuildId });
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuildId, userId, channelId, isBot: true });
|
||||
} else {
|
||||
// Check if this user is a bot via the members cache
|
||||
const guild = client.guilds.get(cleanGuildId) ?? client.guilds.get(guildId);
|
||||
const member = guild?.members?.get?.(userId);
|
||||
const isBot = member?.user?.bot ?? false;
|
||||
if (isBot) {
|
||||
const botKey = this.getObservedVoiceBotKey(userId, cleanGuildId);
|
||||
if (botKey) remix.observedVoiceBots.set(botKey, { channelId, guildId: cleanGuildId });
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuildId, userId, channelId, isBot: true });
|
||||
} else {
|
||||
remix.observedVoiceUsers.set(userId, { channelId, guildId: cleanGuildId });
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuildId, userId, channelId, isBot: false });
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
logger.voiceState(
|
||||
`[Seed] Seeded from VoiceManager.voiceStates — ` +
|
||||
`${remix.observedVoiceUsers.size} humans, ${remix.observedVoiceBots.size} bots tracked.`
|
||||
`[Seed] Seeded from VoiceManager.voiceStates — ` +
|
||||
`${remix.voiceCache.observedVoiceUsersSize} humans, ${remix.voiceCache.observedVoiceBotsSize} bots tracked.`
|
||||
);
|
||||
return; // VoiceManager is the primary source — skip fallback
|
||||
}
|
||||
@@ -170,8 +169,7 @@ export class GatewayHandler {
|
||||
: val?.channelId ?? val?.channel_id ?? null;
|
||||
if (!uid || !channelId) continue;
|
||||
const isBot = val?.member?.user?.bot ?? false;
|
||||
const target = isBot ? remix.observedVoiceBots : remix.observedVoiceUsers;
|
||||
target.set(uid, { channelId, guildId: gId });
|
||||
remix.voiceCache.updateUser({ guildId: gId, userId: uid, channelId, isBot });
|
||||
}
|
||||
} else {
|
||||
const entries = Array.isArray(voiceStatesRaw)
|
||||
@@ -182,8 +180,7 @@ export class GatewayHandler {
|
||||
const channelId = state?.channelId ?? state?.channel_id;
|
||||
if (!userId || !channelId) continue;
|
||||
const isBot = state?.member?.user?.bot ?? false;
|
||||
const target = isBot ? remix.observedVoiceBots : remix.observedVoiceUsers;
|
||||
target.set(userId, { channelId, guildId: gId });
|
||||
remix.voiceCache.updateUser({ guildId: gId, userId, channelId, isBot });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -228,20 +225,18 @@ export class GatewayHandler {
|
||||
const userChannel = String(userChannelId).replace(/\D/g, "");
|
||||
if (userChannel !== cleanChannel) return;
|
||||
if (userId === botId) {
|
||||
const botKey = this.getObservedVoiceBotKey(userId, cleanGuild);
|
||||
if (botKey) remix.observedVoiceBots.set(botKey, { channelId: cleanChannel, guildId: cleanGuild });
|
||||
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) {
|
||||
const botKey = this.getObservedVoiceBotKey(userId, cleanGuild);
|
||||
if (botKey) remix.observedVoiceBots.set(botKey, { channelId: cleanChannel, guildId: cleanGuild });
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: true });
|
||||
} else {
|
||||
remix.observedVoiceUsers.set(userId, { channelId: cleanChannel, guildId: cleanGuild });
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: false });
|
||||
humansFound++;
|
||||
logger.voiceState(
|
||||
`[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild}) via VoiceManager`
|
||||
`[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild}) via VoiceManager`
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -249,13 +244,12 @@ export class GatewayHandler {
|
||||
|
||||
// Update the bot's own entry
|
||||
if (botId) {
|
||||
const botKey = this.getObservedVoiceBotKey(botId, cleanGuild);
|
||||
if (botKey) remix.observedVoiceBots.set(botKey, { channelId: cleanChannel, guildId: cleanGuild });
|
||||
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.observedVoiceUsers.size}`
|
||||
`[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` +
|
||||
`found ${humansFound} human(s) via VoiceManager, observedVoiceUsers size now ${remix.voiceCache.observedVoiceUsersSize}`
|
||||
);
|
||||
|
||||
// If VoiceManager found humans, skip fallbacks
|
||||
@@ -270,7 +264,7 @@ export class GatewayHandler {
|
||||
const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId);
|
||||
if (!guild) {
|
||||
logger.voiceState(
|
||||
`[Reseed] Guild ${cleanGuild} not in cache — cannot reseed voice states.`
|
||||
`[Reseed] Guild ${cleanGuild} not in cache — cannot reseed voice states.`
|
||||
);
|
||||
} else {
|
||||
const voiceStatesRaw =
|
||||
@@ -288,10 +282,10 @@ export class GatewayHandler {
|
||||
const isBot = val?.member?.user?.bot ?? false;
|
||||
if (isBot) continue;
|
||||
if (String(stateChannel).replace(/\D/g, "") === cleanChannel) {
|
||||
remix.observedVoiceUsers.set(uid, { channelId: stateChannel, guildId: cleanGuild });
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId: uid, channelId: stateChannel, isBot: false });
|
||||
humansFound++;
|
||||
logger.voiceState(
|
||||
`[Reseed] Found human ${uid} in channel ${cleanChannel} (guild ${cleanGuild})`
|
||||
`[Reseed] Found human ${uid} in channel ${cleanChannel} (guild ${cleanGuild})`
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -306,10 +300,10 @@ export class GatewayHandler {
|
||||
const isBot = state?.member?.user?.bot ?? false;
|
||||
if (isBot) continue;
|
||||
if (String(stateChannel).replace(/\D/g, "") === cleanChannel) {
|
||||
remix.observedVoiceUsers.set(userId, { channelId: stateChannel, guildId: cleanGuild });
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: stateChannel, isBot: false });
|
||||
humansFound++;
|
||||
logger.voiceState(
|
||||
`[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild})`
|
||||
`[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild})`
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -317,14 +311,13 @@ export class GatewayHandler {
|
||||
|
||||
// Update bot's own entry
|
||||
if (botId) {
|
||||
const botKey = this.getObservedVoiceBotKey(botId, cleanGuild);
|
||||
if (botKey) remix.observedVoiceBots.set(botKey, { channelId: cleanChannel, guildId: cleanGuild });
|
||||
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.observedVoiceUsers.size}`
|
||||
`[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` +
|
||||
`found ${humansFound} human(s), observedVoiceUsers size now ${remix.voiceCache.observedVoiceUsersSize}`
|
||||
);
|
||||
return humansFound;
|
||||
}
|
||||
@@ -339,15 +332,14 @@ export class GatewayHandler {
|
||||
if (infoGuild === cleanGuild && infoChannel === cleanChannel) {
|
||||
humansFound++;
|
||||
logger.voiceState(
|
||||
`[Reseed] Found human ${uid} in channel ${cleanChannel} (guild ${cleanGuild}) via observedVoiceUsers`
|
||||
`[Reseed] Found human ${uid} in channel ${cleanChannel} (guild ${cleanGuild}) via observedVoiceUsers`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Update bot's own entry
|
||||
if (botId) {
|
||||
const botKey = this.getObservedVoiceBotKey(botId, cleanGuild);
|
||||
if (botKey) remix.observedVoiceBots.set(botKey, { channelId: cleanChannel, guildId: cleanGuild });
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true });
|
||||
}
|
||||
}
|
||||
|
||||
@@ -361,9 +353,9 @@ export class GatewayHandler {
|
||||
const userId = participant?.identity ?? participant?.sid;
|
||||
if (userId) {
|
||||
humansFound++;
|
||||
remix.observedVoiceUsers.set(userId, { channelId: cleanChannel, guildId: cleanGuild });
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: false });
|
||||
logger.voiceState(
|
||||
`[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild}) via LiveKit participants`
|
||||
`[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild}) via LiveKit participants`
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -374,8 +366,8 @@ export class GatewayHandler {
|
||||
}
|
||||
|
||||
logger.voiceState(
|
||||
`[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` +
|
||||
`found ${humansFound} human(s), observedVoiceUsers size now ${remix.observedVoiceUsers.size}`
|
||||
`[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` +
|
||||
`found ${humansFound} human(s), observedVoiceUsers size now ${remix.voiceCache.observedVoiceUsersSize}`
|
||||
);
|
||||
|
||||
return humansFound;
|
||||
@@ -445,8 +437,7 @@ export class GatewayHandler {
|
||||
const channelId = state.channel_id;
|
||||
if (!userId || !channelId) continue;
|
||||
const isBot = state.member?.user?.bot ?? false;
|
||||
const target = isBot ? remix.observedVoiceBots : remix.observedVoiceUsers;
|
||||
target.set(isBot ? this.getObservedVoiceBotKey(userId, gId) : userId, { channelId, guildId: gId });
|
||||
remix.voiceCache.updateUser({ guildId: gId, userId, channelId, isBot });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -466,8 +457,7 @@ export class GatewayHandler {
|
||||
const channelId = state.channel_id;
|
||||
if (!userId || !channelId) continue;
|
||||
const isBot = state.member?.user?.bot ?? false;
|
||||
const target = isBot ? remix.observedVoiceBots : remix.observedVoiceUsers;
|
||||
target.set(isBot ? this.getObservedVoiceBotKey(userId, gId) : userId, { channelId, guildId: gId });
|
||||
remix.voiceCache.updateUser({ guildId: gId, userId, channelId, isBot });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -483,10 +473,11 @@ export class GatewayHandler {
|
||||
const guildId = d?.guild_id;
|
||||
const isBot = d?.member?.user?.bot ?? false;
|
||||
if (!userId) return;
|
||||
const target = isBot ? remix.observedVoiceBots : remix.observedVoiceUsers;
|
||||
const voiceKey = isBot ? this.getObservedVoiceBotKey(userId, guildId) : userId;
|
||||
if (channelId) target.set(voiceKey, { channelId, guildId });
|
||||
else if (voiceKey) target.delete(voiceKey);
|
||||
if (channelId) {
|
||||
remix.voiceCache.updateUser({ guildId, userId, channelId, isBot });
|
||||
} else {
|
||||
remix.voiceCache.updateUser({ guildId, userId, channelId: null, isBot });
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
};
|
||||
@@ -590,8 +581,8 @@ export class GatewayHandler {
|
||||
clearTimeout(deferred.timer);
|
||||
this._deferredGuildDeletes.delete(guildId);
|
||||
logger.guild(
|
||||
`[GuildDelete] Cancelled deferred cleanup for server ${guildId} — ` +
|
||||
`guild came back (GuildCreate received during grace period).`
|
||||
`[GuildDelete] Cancelled deferred cleanup for server ${guildId} — ` +
|
||||
`guild came back (GuildCreate received during grace period).`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -606,7 +597,7 @@ export class GatewayHandler {
|
||||
guild.voice_states ??
|
||||
guild.voiceStates ??
|
||||
null;
|
||||
|
||||
|
||||
if (voiceStatesRaw) {
|
||||
// Build a set of user IDs from the new voice_states data
|
||||
const newUserIds = new Set();
|
||||
@@ -624,29 +615,13 @@ export class GatewayHandler {
|
||||
if (userId) newUserIds.add(userId);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
// Only purge entries for users/bots that are being replaced by new data.
|
||||
// Previously, ALL observedVoiceBots entries for the guild were deleted,
|
||||
// which removed the bot's own entry that was set up during recovery.
|
||||
// Now we only delete entries for bots whose user ID appears in the new
|
||||
// voice_states data, matching the same logic used for observedVoiceUsers.
|
||||
for (const [uid, info] of [...remix.observedVoiceUsers]) {
|
||||
if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")
|
||||
&& newUserIds.has(uid)) {
|
||||
remix.observedVoiceUsers.delete(uid);
|
||||
}
|
||||
}
|
||||
for (const [uid, info] of [...remix.observedVoiceBots]) {
|
||||
if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) {
|
||||
// Only delete if this bot's user ID appears in the new voice_states
|
||||
// data — i.e., it's being replaced by fresh data. This prevents
|
||||
// destroying the bot's own entry set up during recovery.
|
||||
const botUserId = uid.split(":").pop(); // key is "guildId:userId"
|
||||
if (botUserId && newUserIds.has(botUserId)) {
|
||||
remix.observedVoiceBots.delete(uid);
|
||||
}
|
||||
}
|
||||
}
|
||||
remix.voiceCache.purgeUsersInGuild(guildId, newUserIds);
|
||||
}
|
||||
if (voiceStatesRaw) {
|
||||
if (!Array.isArray(voiceStatesRaw) && typeof voiceStatesRaw === "object"
|
||||
@@ -656,8 +631,7 @@ export class GatewayHandler {
|
||||
: val?.channelId ?? val?.channel_id ?? null;
|
||||
if (!uid || !channelId) continue;
|
||||
const isBot = val?.member?.user?.bot ?? false;
|
||||
const target = isBot ? remix.observedVoiceBots : remix.observedVoiceUsers;
|
||||
target.set(isBot ? this.getObservedVoiceBotKey(uid, guildId) : uid, { channelId, guildId });
|
||||
remix.voiceCache.updateUser({ guildId, userId: uid, channelId, isBot });
|
||||
}
|
||||
} else {
|
||||
const entries = Array.isArray(voiceStatesRaw)
|
||||
@@ -670,8 +644,7 @@ export class GatewayHandler {
|
||||
const sgid = state?.guildId ?? state?.guild_id ?? guildId;
|
||||
const isBot = state?.member?.user?.bot ?? false;
|
||||
if (!channelId || !userId) continue;
|
||||
const target = isBot ? remix.observedVoiceBots : remix.observedVoiceUsers;
|
||||
target.set(isBot ? this.getObservedVoiceBotKey(userId, sgid) : userId, { channelId, guildId: sgid });
|
||||
remix.voiceCache.updateUser({ guildId: sgid, userId, channelId, isBot });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -725,8 +698,8 @@ export class GatewayHandler {
|
||||
// Only log the first few deferrals individually, then suppress
|
||||
if (this._deferredDeleteCount <= 3) {
|
||||
logger.guild(
|
||||
`[GuildDelete] Deferring cleanup for server ${guildId} ` +
|
||||
`(startup grace — will confirm after ${this._startupDeleteGraceMs / 1000}s).`
|
||||
`[GuildDelete] Deferring cleanup for server ${guildId} ` +
|
||||
`(startup grace — will confirm after ${this._startupDeleteGraceMs / 1000}s).`
|
||||
);
|
||||
}
|
||||
// Cancel any existing deferred timer for this guild
|
||||
@@ -805,15 +778,13 @@ export class GatewayHandler {
|
||||
}
|
||||
|
||||
// Always update/delete the voice maps
|
||||
const target = isBot === true ? remix.observedVoiceBots : remix.observedVoiceUsers;
|
||||
const voiceKey = isBot === true ? this.getObservedVoiceBotKey(userId, guildId ?? prev?.guildId) : userId;
|
||||
if (channelId) {
|
||||
if (voiceKey) target.set(voiceKey, { channelId, guildId });
|
||||
remix.voiceCache.updateUser({ guildId: guildId ?? prev?.guildId, userId, channelId, isBot: isBot === true });
|
||||
} else {
|
||||
remix.observedVoiceUsers.delete(userId);
|
||||
if (voiceKey) remix.observedVoiceBots.delete(voiceKey);
|
||||
const fallbackBotKey = this.getObservedVoiceBotKey(userId, prev?.guildId);
|
||||
if (fallbackBotKey && fallbackBotKey !== voiceKey) remix.observedVoiceBots.delete(fallbackBotKey);
|
||||
// User left voice — remove from both human and bot indexes
|
||||
const resolvedGuildId = guildId ?? prev?.guildId;
|
||||
remix.voiceCache.deleteHumanUser(userId, resolvedGuildId);
|
||||
remix.voiceCache.deleteBotUser(VoiceStateCache.userKey(resolvedGuildId, userId));
|
||||
}
|
||||
|
||||
const isBotUser = isBot === true && userId === client.user?.id;
|
||||
@@ -910,7 +881,7 @@ export class GatewayHandler {
|
||||
// ── Bot-only logic below ───────────────────────────────────────────────
|
||||
|
||||
const activeGuildPlayers = [...remix.players.playerMap.entries()].filter(([, player]) =>
|
||||
String(player?._guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, "")
|
||||
String(player?._guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, "")
|
||||
);
|
||||
const multiVoiceGuild = activeGuildPlayers.length > 1;
|
||||
|
||||
@@ -932,9 +903,9 @@ export class GatewayHandler {
|
||||
|
||||
if (saved247Channels.length > 1) {
|
||||
logger.voice247(
|
||||
`[247] Ignoring move-style bot voice update ${cleanOld} → ${cleanId} ` +
|
||||
`because guild ${guildId} already has multiple saved 24/7 channels ` +
|
||||
`[${saved247Channels.join(", ")}]`
|
||||
`[247] Ignoring move-style bot voice update ${cleanOld} → ${cleanId} ` +
|
||||
`because guild ${guildId} already has multiple saved 24/7 channels ` +
|
||||
`[${saved247Channels.join(", ")}]`
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -957,12 +928,12 @@ export class GatewayHandler {
|
||||
remix.players?._pendingJoins?.has?.(cleanId) ||
|
||||
false;
|
||||
const targetChannel = client.channels.get(cleanId)
|
||||
?? client.channels.get?.(cleanId)
|
||||
?? null;
|
||||
?? client.channels.get?.(cleanId)
|
||||
?? null;
|
||||
const targetGuildId = String(targetChannel?.guildId ?? targetChannel?.guild?.id ?? guildId ?? "").replace(/\D/g, "");
|
||||
const playerGuildId = String(existingPlayer?._guildId ?? "").replace(/\D/g, "");
|
||||
const guildPlayers = [...remix.players.playerMap.entries()].filter(([, player]) =>
|
||||
String(player?._guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, "")
|
||||
String(player?._guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, "")
|
||||
);
|
||||
const guildIsAmbiguous = guildPlayers.length > 1;
|
||||
|
||||
@@ -974,8 +945,8 @@ export class GatewayHandler {
|
||||
// situation we must NOT re-key the old player or rewrite stay_247,
|
||||
// otherwise one saved channel gets collapsed into the newer one.
|
||||
logger.voice247(
|
||||
`[247] Keeping both channels ${cleanOld} and ${cleanId} ` +
|
||||
`(saved=${newChannelAlreadySaved} pending=${newChannelPendingSpawn})`
|
||||
`[247] Keeping both channels ${cleanOld} and ${cleanId} ` +
|
||||
`(saved=${newChannelAlreadySaved} pending=${newChannelPendingSpawn})`
|
||||
);
|
||||
rekeyed = false;
|
||||
} else
|
||||
@@ -992,9 +963,9 @@ export class GatewayHandler {
|
||||
if (targetGuildId) existingPlayer._guildId = targetGuildId;
|
||||
rekeyed = false;
|
||||
logger.voice247(
|
||||
`[247] Updated player channel ${cleanOld} → ${cleanId} ` +
|
||||
`(guild ${guildId} has ${guildPlayers.length} active players, ` +
|
||||
`new key occupied by another player — skipped re-key)`
|
||||
`[247] Updated player channel ${cleanOld} → ${cleanId} ` +
|
||||
`(guild ${guildId} has ${guildPlayers.length} active players, ` +
|
||||
`new key occupied by another player — skipped re-key)`
|
||||
);
|
||||
} else {
|
||||
// Safe to re-key: no collision
|
||||
@@ -1005,8 +976,8 @@ export class GatewayHandler {
|
||||
if (targetGuildId) existingPlayer._guildId = targetGuildId;
|
||||
rekeyed = true;
|
||||
logger.voice247(
|
||||
`[247] Re-keyed playerMap ${cleanOld} → ${cleanId} ` +
|
||||
`(guild ${guildId} has ${guildPlayers.length} active players)`
|
||||
`[247] Re-keyed playerMap ${cleanOld} → ${cleanId} ` +
|
||||
`(guild ${guildId} has ${guildPlayers.length} active players)`
|
||||
);
|
||||
}
|
||||
} else if (playerGuildId && targetGuildId && playerGuildId !== targetGuildId) {
|
||||
@@ -1017,8 +988,8 @@ export class GatewayHandler {
|
||||
// In this case, just update the observed bot state without re-keying.
|
||||
if (!existingPlayer) {
|
||||
logger.voice247(
|
||||
`[247] Stale cross-guild move ${cleanOld} → ${cleanId} ` +
|
||||
`(no player in playerMap for old channel — updating bot state only)`
|
||||
`[247] Stale cross-guild move ${cleanOld} → ${cleanId} ` +
|
||||
`(no player in playerMap for old channel — updating bot state only)`
|
||||
);
|
||||
} else {
|
||||
// There IS a player in the old channel but the guilds don't match.
|
||||
@@ -1040,13 +1011,13 @@ export class GatewayHandler {
|
||||
remix.players.playerMap.set(cleanId, existingPlayer);
|
||||
rekeyed = true;
|
||||
logger.voice247(
|
||||
`[247] Fixed stale guild during recovery: re-keyed ${cleanOld} → ${cleanId} ` +
|
||||
`(playerGuild ${playerGuildId} → ${targetGuildId})`
|
||||
`[247] Fixed stale guild during recovery: re-keyed ${cleanOld} → ${cleanId} ` +
|
||||
`(playerGuild ${playerGuildId} → ${targetGuildId})`
|
||||
);
|
||||
} else {
|
||||
logger.warn(
|
||||
`[247] Refused cross-guild re-key ${cleanOld} → ${cleanId} ` +
|
||||
`(playerGuild=${playerGuildId} targetGuild=${targetGuildId})`
|
||||
`[247] Refused cross-guild re-key ${cleanOld} → ${cleanId} ` +
|
||||
`(playerGuild=${playerGuildId} targetGuild=${targetGuildId})`
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1070,8 +1041,8 @@ export class GatewayHandler {
|
||||
if (channels.has(cleanOld) && cleanOld !== cleanId && cleanId.length >= 15) {
|
||||
if (channels.has(cleanId) || newChannelAlreadySaved || newChannelPendingSpawn) {
|
||||
logger.voice247(
|
||||
`[247] Preserved stay_247 channels ${cleanOld} and ${cleanId} ` +
|
||||
`(saved=${channels.has(cleanId) || newChannelAlreadySaved} pending=${newChannelPendingSpawn})`
|
||||
`[247] Preserved stay_247 channels ${cleanOld} and ${cleanId} ` +
|
||||
`(saved=${channels.has(cleanId) || newChannelAlreadySaved} pending=${newChannelPendingSpawn})`
|
||||
);
|
||||
return;
|
||||
}
|
||||
@@ -1119,7 +1090,7 @@ export class GatewayHandler {
|
||||
|
||||
if (mode === "auto") {
|
||||
logger.voice247(
|
||||
`[VoiceState] Bot unexpectedly disconnected from ${cleanOld} (24/7 auto) — cleaning up and scheduling rejoin.`
|
||||
`[VoiceState] Bot unexpectedly disconnected from ${cleanOld} (24/7 auto) — cleaning up and scheduling rejoin.`
|
||||
);
|
||||
const player = remix.players.playerMap.get(cleanOld);
|
||||
if (player && !player._destroyed) {
|
||||
@@ -1153,7 +1124,7 @@ export class GatewayHandler {
|
||||
const player = remix.players.playerMap.get(cleanOld);
|
||||
if (player && !player.leaving && !player._destroyed) {
|
||||
logger.voiceState(
|
||||
`[VoiceState] Bot disconnected from ${cleanOld} (24/7 mode: ${mode}) — emitting autoleave.`
|
||||
`[VoiceState] Bot disconnected from ${cleanOld} (24/7 mode: ${mode}) — emitting autoleave.`
|
||||
);
|
||||
player.emit("autoleave");
|
||||
}
|
||||
@@ -1233,7 +1204,7 @@ export class GatewayHandler {
|
||||
|
||||
const maxRetries = GatewayHandler.MAX_REJOIN_RETRIES;
|
||||
logger.voice247(
|
||||
`[Rejoin] Attempting to rejoin channel ${cleanChannelId} in guild ${cleanGuildId} (attempt ${attempt}/${maxRetries})...`
|
||||
`[Rejoin] Attempting to rejoin channel ${cleanChannelId} in guild ${cleanGuildId} (attempt ${attempt}/${maxRetries})...`
|
||||
);
|
||||
|
||||
try {
|
||||
@@ -1256,8 +1227,8 @@ export class GatewayHandler {
|
||||
// Retry with exponential backoff: 5s, 10s, 20s
|
||||
const backoffMs = 5_000 * Math.pow(2, attempt - 1);
|
||||
logger.voice247(
|
||||
`[Rejoin] Track publication failed for channel ${cleanChannelId} (attempt ${attempt}/${maxRetries}) — ` +
|
||||
`retrying in ${backoffMs / 1000}s: ${errMsg}`
|
||||
`[Rejoin] Track publication failed for channel ${cleanChannelId} (attempt ${attempt}/${maxRetries}) — ` +
|
||||
`retrying in ${backoffMs / 1000}s: ${errMsg}`
|
||||
);
|
||||
this._rejoinInProgress.delete(cleanChannelId);
|
||||
|
||||
@@ -1267,7 +1238,7 @@ export class GatewayHandler {
|
||||
}
|
||||
|
||||
logger.warn(
|
||||
`[Rejoin] Failed to rejoin channel ${cleanChannelId} (attempt ${attempt}/${maxRetries}): ${errMsg}`
|
||||
`[Rejoin] Failed to rejoin channel ${cleanChannelId} (attempt ${attempt}/${maxRetries}): ${errMsg}`
|
||||
);
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
|
||||
@@ -1300,8 +1271,8 @@ export class GatewayHandler {
|
||||
const pending = this._deferredGuildDeletes.size;
|
||||
if (pending > 0) {
|
||||
logger.guild(
|
||||
`[GuildDelete] Startup grace period ended. ` +
|
||||
`${pending} deferred deletion(s) confirmed — cleaning up.`
|
||||
`[GuildDelete] Startup grace period ended. ` +
|
||||
`${pending} deferred deletion(s) confirmed — cleaning up.`
|
||||
);
|
||||
} else {
|
||||
logger.guild(`[GuildDelete] Startup grace period ended. No deferred deletions.`);
|
||||
@@ -1309,7 +1280,7 @@ export class GatewayHandler {
|
||||
// Log suppressed count if we had more than 3 deferred deletes
|
||||
if (this._deferredDeleteCount > 3) {
|
||||
logger.guild(
|
||||
`[GuildDelete] (Suppressed ${this._deferredDeleteCount - 3} deferral log lines for brevity)`
|
||||
`[GuildDelete] (Suppressed ${this._deferredDeleteCount - 3} deferral log lines for brevity)`
|
||||
);
|
||||
}
|
||||
}, this._startupDeleteGraceMs);
|
||||
@@ -1357,8 +1328,8 @@ export class GatewayHandler {
|
||||
}
|
||||
|
||||
logger.voice247(
|
||||
`[BootRecovery] Found ${channelsToRejoin.length} 24/7 channel(s) to rejoin: ` +
|
||||
channelsToRejoin.map(c => `${c.channelId}(${c.mode})`).join(", ")
|
||||
`[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;
|
||||
@@ -1386,7 +1357,7 @@ export class GatewayHandler {
|
||||
}
|
||||
|
||||
logger.voice247(
|
||||
`[BootRecovery] Rejoining channel ${channelId} in guild ${guildId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]`
|
||||
`[BootRecovery] Rejoining channel ${channelId} in guild ${guildId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]`
|
||||
);
|
||||
|
||||
const BOOT_MAX_RETRIES = 3;
|
||||
@@ -1401,8 +1372,8 @@ export class GatewayHandler {
|
||||
this.reseedVoiceStatesForChannel(guildId, channelId);
|
||||
|
||||
logger.voice247(
|
||||
`[BootRecovery] Successfully rejoined channel ${channelId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]` +
|
||||
(bootRetries > 0 ? ` (after ${bootRetries} retry/retries)` : '')
|
||||
`[BootRecovery] Successfully rejoined channel ${channelId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]` +
|
||||
(bootRetries > 0 ? ` (after ${bootRetries} retry/retries)` : '')
|
||||
);
|
||||
break; // success — move to next channel
|
||||
} catch (err) {
|
||||
@@ -1416,16 +1387,16 @@ export class GatewayHandler {
|
||||
if (isTrackTimeout && bootRetries < BOOT_MAX_RETRIES) {
|
||||
const backoffMs = BOOT_BASE_RETRY_MS * Math.pow(2, bootRetries - 1);
|
||||
logger.warn(
|
||||
`[BootRecovery] Track publication failed for channel ${channelId} (attempt ${bootRetries}/${BOOT_MAX_RETRIES}) — ` +
|
||||
`retrying in ${backoffMs / 1000}s: ${errMsg}`
|
||||
`[BootRecovery] Track publication failed for channel ${channelId} (attempt ${bootRetries}/${BOOT_MAX_RETRIES}) — ` +
|
||||
`retrying in ${backoffMs / 1000}s: ${errMsg}`
|
||||
);
|
||||
await new Promise(resolve => setTimeout(resolve, backoffMs));
|
||||
continue;
|
||||
}
|
||||
|
||||
logger.warn(
|
||||
`[BootRecovery] Failed to rejoin channel ${channelId} (mode: ${mode}): ${errMsg}` +
|
||||
(bootRetries > 1 ? ` (after ${bootRetries} attempts)` : '')
|
||||
`[BootRecovery] Failed to rejoin channel ${channelId} (mode: ${mode}): ${errMsg}` +
|
||||
(bootRetries > 1 ? ` (after ${bootRetries} attempts)` : '')
|
||||
);
|
||||
|
||||
// Auto-cleanup: if all retries exhausted due to track publication
|
||||
@@ -1437,20 +1408,20 @@ export class GatewayHandler {
|
||||
if (set) {
|
||||
const raw = set.get("stay_247");
|
||||
const channels = new Set(
|
||||
(Array.isArray(raw) ? raw : [raw])
|
||||
.filter(id => id && id !== "none" && String(id).replace(/\D/g, "") !== channelId)
|
||||
(Array.isArray(raw) ? raw : [raw])
|
||||
.filter(id => id && id !== "none" && String(id).replace(/\D/g, "") !== channelId)
|
||||
);
|
||||
set.set("stay_247", channels.size > 0 ? [...channels] : "none");
|
||||
remove247ChannelMode(set, channelId, channels);
|
||||
logger.warn(
|
||||
`[BootRecovery] Auto-removed channel ${channelId} from 24/7 ` +
|
||||
`in guild ${guildId} after persistent track publication failure`
|
||||
`[BootRecovery] Auto-removed channel ${channelId} from 24/7 ` +
|
||||
`in guild ${guildId} after persistent track publication failure`
|
||||
);
|
||||
}
|
||||
} catch (cleanupErr) {
|
||||
logger.error(
|
||||
`[BootRecovery] Failed to auto-remove channel ${channelId} from 24/7:`,
|
||||
cleanupErr?.message ?? cleanupErr
|
||||
`[BootRecovery] Failed to auto-remove channel ${channelId} from 24/7:`,
|
||||
cleanupErr?.message ?? cleanupErr
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1461,7 +1432,7 @@ export class GatewayHandler {
|
||||
}
|
||||
|
||||
logger.voice247(
|
||||
`[BootRecovery] Boot recovery complete. ${channelsToRejoin.length} channel(s) processed.`
|
||||
`[BootRecovery] Boot recovery complete. ${channelsToRejoin.length} channel(s) processed.`
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1499,8 +1470,8 @@ export class GatewayHandler {
|
||||
// Keep the player alive — the guild will come back via GuildCreate.
|
||||
if (!batchMode) {
|
||||
logger.guild(
|
||||
`[GuildDelete] Preserving 24/7 player for channel ${channelId} ` +
|
||||
`(LiveKit room still connected — guild ${cleanGuildId} likely temporarily unavailable).`
|
||||
`[GuildDelete] Preserving 24/7 player for channel ${channelId} ` +
|
||||
`(LiveKit room still connected — guild ${cleanGuildId} likely temporarily unavailable).`
|
||||
);
|
||||
}
|
||||
continue;
|
||||
@@ -1512,12 +1483,7 @@ export class GatewayHandler {
|
||||
if (!batchMode) logger.guild(`[GuildDelete] Destroyed player for channel ${channelId}.`);
|
||||
}
|
||||
|
||||
for (const [userId, info] of [...remix.observedVoiceUsers]) {
|
||||
if (String(info.guildId).replace(/\D/g, "") === cleanGuildId) remix.observedVoiceUsers.delete(userId);
|
||||
}
|
||||
for (const [userId, info] of [...remix.observedVoiceBots]) {
|
||||
if (String(info.guildId).replace(/\D/g, "") === cleanGuildId) remix.observedVoiceBots.delete(userId);
|
||||
}
|
||||
remix.voiceCache.removeGuild(cleanGuildId);
|
||||
for (const [stateKey, info] of [...this._prevVoiceState]) {
|
||||
if (String(info.guildId).replace(/\D/g, "") === cleanGuildId)
|
||||
this._prevVoiceState.delete(stateKey);
|
||||
|
||||
+31
-18
@@ -327,6 +327,7 @@ export default class Player extends EventEmitter {
|
||||
// searches Map with max-size eviction to prevent memory leak on busy servers.
|
||||
searches = new Map();
|
||||
_searchMaxSize = 50;
|
||||
_maxQueueSize = 10_000; // Max tracks in queue to prevent unbounded memory growth
|
||||
resultLimit = 5;
|
||||
preferredVolume = 1;
|
||||
|
||||
@@ -370,6 +371,7 @@ export default class Player extends EventEmitter {
|
||||
this.settings = opts.settings ?? null;
|
||||
this.settingsMgr = opts.settingsMgr ?? null;
|
||||
this._observedVoiceUsers = opts.observedVoiceUsers ?? null;
|
||||
this._voiceCache = opts.voiceCache ?? null;
|
||||
this.locale = opts.locale ?? null;
|
||||
|
||||
// Merge NodeLink config (for stream URL building)
|
||||
@@ -524,25 +526,34 @@ export default class Player extends EventEmitter {
|
||||
if (!this._channelId || !this._guildId) return false;
|
||||
const cleanChan = String(this._channelId).replace(/\D/g, "");
|
||||
const cleanGuild = String(this._guildId).replace(/\D/g, "");
|
||||
|
||||
// O(1) lookup via VoiceStateCache channelMembers index
|
||||
if (this._voiceCache && this._voiceCache.hasHumansInChannel(cleanGuild, cleanChan)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Legacy fallback: iterate observedVoiceUsers (O(n))
|
||||
try {
|
||||
const voiceUsers = this._observedVoiceUsers;
|
||||
if (voiceUsers) {
|
||||
for ( const [, info] of voiceUsers) {
|
||||
if (voiceUsers && typeof voiceUsers.iterateHumanUsers === "function") {
|
||||
for (const [, info] of voiceUsers.iterateHumanUsers()) {
|
||||
if (
|
||||
String(info.guildId ?? "").replace(/\D/g, "") === cleanGuild &&
|
||||
String(info.channelId ?? "").replace(/\D/g, "") === cleanChan
|
||||
) return true;
|
||||
}
|
||||
} else if (voiceUsers) {
|
||||
// Raw Map fallback (shouldn't happen with new code)
|
||||
for (const [, info] of voiceUsers) {
|
||||
if (
|
||||
String(info.guildId ?? "").replace(/\D/g, "") === cleanGuild &&
|
||||
String(info.channelId ?? "").replace(/\D/g, "") === cleanChan
|
||||
) return true;
|
||||
}
|
||||
// Don't return false here — fall through to guild voice_states
|
||||
// fallback in case observedVoiceUsers hasn't been populated yet
|
||||
// (e.g., right after bot restart before reseed completes).
|
||||
}
|
||||
} catch (_) {}
|
||||
try {
|
||||
// @fluxerjs channels do NOT have a .members property.
|
||||
// Use the guild's member manager and filter by voice state instead.
|
||||
const guild = this.client?.guilds?.get?.(this._guildId);
|
||||
// Iterate raw voice_states on the guild object.
|
||||
const voiceStates = guild?.voice_states;
|
||||
if (voiceStates) {
|
||||
const entries = Array.isArray(voiceStates)
|
||||
@@ -554,7 +565,6 @@ export default class Player extends EventEmitter {
|
||||
const stateChannelId = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, "");
|
||||
if (stateChannelId === cleanChan) {
|
||||
const userId = String(state?.userId ?? state?.user_id ?? "");
|
||||
// Check if user is a bot — look up via members or observedVoiceUsers
|
||||
const member = guild?.members?.get?.(userId);
|
||||
const isBot = member?.user?.bot ?? false;
|
||||
if (!isBot) return true;
|
||||
@@ -563,19 +573,11 @@ export default class Player extends EventEmitter {
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
// ── LiveKit participant fallback ──────────────────────────────────────
|
||||
// If the above methods didn't find any humans (e.g., because
|
||||
// voice_states cache is empty and observedVoiceUsers hasn't been
|
||||
// populated yet after a restart), check the LiveKit room's remote
|
||||
// participants. This is the most reliable source of truth for who's
|
||||
// actually in the voice channel, since LiveKit knows about every
|
||||
// connected participant regardless of gateway cache state.
|
||||
// LiveKit participant fallback
|
||||
try {
|
||||
const room = this.connection?.room;
|
||||
if (room?.isConnected && room.remoteParticipants) {
|
||||
for (const [, participant] of room.remoteParticipants) {
|
||||
// Remote participants in the LiveKit room are humans (the bot is
|
||||
// the local participant). If there's at least one, humans are present.
|
||||
if (participant?.identity || participant?.sid) {
|
||||
return true;
|
||||
}
|
||||
@@ -1590,6 +1592,11 @@ export default class Player extends EventEmitter {
|
||||
isEmpty() { return this.queue.isEmpty(); }
|
||||
|
||||
addToQueue(d, t) {
|
||||
// Enforce queue size cap to prevent unbounded memory growth
|
||||
if (this.queue.data.length >= this._maxQueueSize) {
|
||||
logger.warn(`[Player] Queue size cap reached (${this._maxQueueSize}) — dropping oldest track`);
|
||||
this.queue.data.shift();
|
||||
}
|
||||
this.queue.add(d, t);
|
||||
this.emit("update", "queue");
|
||||
this._stopInactivityTimer();
|
||||
@@ -1604,6 +1611,12 @@ export default class Player extends EventEmitter {
|
||||
}
|
||||
|
||||
addManyToQueue(t, top = false) {
|
||||
// Enforce queue size cap
|
||||
const overflow = (this.queue.data.length + t.length) - this._maxQueueSize;
|
||||
if (overflow > 0) {
|
||||
logger.warn(`[Player] Queue size cap (${this._maxQueueSize}) — dropping ${overflow} oldest tracks`);
|
||||
this.queue.data.splice(0, overflow);
|
||||
}
|
||||
const added = this.queue.addMany(t, top);
|
||||
this.emit("update", "queue");
|
||||
this._stopInactivityTimer();
|
||||
|
||||
+114
-17
@@ -81,9 +81,12 @@ export class PlayerManager {
|
||||
/** @type {CommandHandler} */
|
||||
commands;
|
||||
|
||||
/** @type {Map<string, Player>} */
|
||||
/** @type {Map<string, Player>} Keyed by cleaned channel ID */
|
||||
playerMap = new Map();
|
||||
|
||||
/** @type {Map<string, Set<string>>} Reverse index: guildId → Set<channelId> for O(1) guild lookups */
|
||||
_guildPlayerIndex = new Map();
|
||||
|
||||
/** @type {Set<string>} Channel IDs currently being joined (not yet in playerMap) */
|
||||
_pendingJoins = new Set();
|
||||
|
||||
@@ -121,6 +124,94 @@ export class PlayerManager {
|
||||
this._lastfm = null; // Set later by Remix class after init
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Guild→Player Reverse Index — O(1) lookups instead of O(n) scans
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Add a channel to the guild→player reverse index.
|
||||
* Called after a successful player join.
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
*/
|
||||
_indexPlayer(guildId, channelId) {
|
||||
const gId = cleanId(guildId);
|
||||
const cId = cleanId(channelId);
|
||||
if (!gId || !cId) return;
|
||||
let set = this._guildPlayerIndex.get(gId);
|
||||
if (!set) { set = new Set(); this._guildPlayerIndex.set(gId, set); }
|
||||
set.add(cId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a channel from the guild→player reverse index.
|
||||
* Called on player leave/destroy.
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
*/
|
||||
_unindexPlayer(guildId, channelId) {
|
||||
const gId = cleanId(guildId);
|
||||
const cId = cleanId(channelId);
|
||||
if (!gId) return;
|
||||
const set = this._guildPlayerIndex.get(gId);
|
||||
if (set) {
|
||||
set.delete(cId);
|
||||
if (set.size === 0) this._guildPlayerIndex.delete(gId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all [channelId, Player] entries for a guild.
|
||||
* Uses the reverse index for O(1) guild lookup instead of O(n) scan.
|
||||
* @param {string} guildId
|
||||
* @returns {Array<[string, Player]>}
|
||||
*/
|
||||
getGuildPlayers(guildId) {
|
||||
const gId = cleanId(guildId);
|
||||
const set = this._guildPlayerIndex.get(gId);
|
||||
if (!set) return [];
|
||||
const result = [];
|
||||
for (const channelId of set) {
|
||||
const player = this.playerMap.get(channelId);
|
||||
if (player && !player._destroyed) {
|
||||
result.push([channelId, player]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a player by guildId and channelId using the reverse index.
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
* @returns {Player|null}
|
||||
*/
|
||||
getPlayerByGuildAndChannel(guildId, channelId) {
|
||||
const cId = cleanId(channelId);
|
||||
const players = this.getGuildPlayers(guildId);
|
||||
for (const [mapChannelId, player] of players) {
|
||||
if (getPlayerChannelId(player, mapChannelId) === cId) return player;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a player by channelId alone (scans guild index first, then fallback).
|
||||
* @param {string} channelId
|
||||
* @returns {Player|null}
|
||||
*/
|
||||
getPlayerByChannelId(channelId) {
|
||||
const cId = cleanId(channelId);
|
||||
// Try all guild indexes
|
||||
for (const [, channelSet] of this._guildPlayerIndex) {
|
||||
for (const mapChannelId of channelSet) {
|
||||
const player = this.playerMap.get(mapChannelId);
|
||||
if (player && getPlayerChannelId(player, mapChannelId) === cId) return player;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Forward player lifecycle/state events to the dashboard pub/sub channels.
|
||||
*
|
||||
@@ -502,9 +593,7 @@ export class PlayerManager {
|
||||
|
||||
if (cleanUserChannelId) {
|
||||
const player = this.playerMap.get(cleanUserChannelId)
|
||||
?? [...this.playerMap.values()].find(p =>
|
||||
getPlayerChannelId(p) === cleanUserChannelId
|
||||
);
|
||||
?? this.getPlayerByGuildAndChannel(cleanGuildId, cleanUserChannelId);
|
||||
if (player) {
|
||||
player.textChannel = message.channel;
|
||||
try {
|
||||
@@ -523,9 +612,7 @@ export class PlayerManager {
|
||||
}
|
||||
|
||||
const serverPlayers = cleanGuildId
|
||||
? [...this.playerMap.entries()].filter(([, player]) => {
|
||||
return getPlayerGuildId(player) === cleanGuildId;
|
||||
})
|
||||
? this.getGuildPlayers(cleanGuildId)
|
||||
: [];
|
||||
|
||||
if (serverPlayers.length > 0) {
|
||||
@@ -544,7 +631,7 @@ export class PlayerManager {
|
||||
}
|
||||
|
||||
const match = serverPlayers.find(([, player]) =>
|
||||
String(player?._channelId ?? "").replace(/\D/g, "") === cleanUserChannelId
|
||||
getPlayerChannelId(player) === cleanUserChannelId
|
||||
);
|
||||
if (match) {
|
||||
match[1].textChannel = message.channel;
|
||||
@@ -697,22 +784,24 @@ export class PlayerManager {
|
||||
if (!cid) {
|
||||
const guildId = getMessageGuildId(msg);
|
||||
if (guildId) {
|
||||
const matchedEntry = [...this.playerMap.entries()].find(([, player]) =>
|
||||
getPlayerGuildId(player) === cleanId(guildId)
|
||||
);
|
||||
cid = getPlayerChannelId(matchedEntry?.[1], matchedEntry?.[0]) || matchedEntry?.[0] || null;
|
||||
const guildPlayers = this.getGuildPlayers(cleanId(guildId));
|
||||
if (guildPlayers.length > 0) {
|
||||
const [, firstPlayer] = guildPlayers[0];
|
||||
cid = getPlayerChannelId(firstPlayer, guildPlayers[0][0]) || guildPlayers[0][0];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const cleanChannelId = cleanId(cid);
|
||||
const player = cleanChannelId
|
||||
? this.playerMap.get(cleanChannelId) ??
|
||||
[...this.playerMap.values()].find((entry) => getPlayerChannelId(entry) === cleanChannelId)
|
||||
this.getPlayerByChannelId(cleanChannelId)
|
||||
: null;
|
||||
if (!player) return msg.reply(mkEmbed(this._t(msg, "responses._common.notInVoice")));
|
||||
|
||||
const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId;
|
||||
this.playerMap.delete(activeChannelId);
|
||||
this._unindexPlayer(player._guildId, activeChannelId);
|
||||
// Clean up pending scrobble timer
|
||||
const pendingScrobble = this._pendingScrobbleTimers.get(activeChannelId);
|
||||
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this._pendingScrobbleTimers.delete(activeChannelId); }
|
||||
@@ -749,7 +838,7 @@ export class PlayerManager {
|
||||
|
||||
const cleanChannelId = cleanId(cid);
|
||||
const existing = this.playerMap.get(cleanChannelId)
|
||||
?? [...this.playerMap.values()].find((entry) => getPlayerChannelId(entry) === cleanChannelId);
|
||||
?? this.getPlayerByChannelId(cleanChannelId);
|
||||
if (existing) {
|
||||
existing.textChannel = message.channel;
|
||||
cb(existing);
|
||||
@@ -769,6 +858,7 @@ export class PlayerManager {
|
||||
revoice: this.playerConfig?.revoice ?? null,
|
||||
settingsMgr: this.settings,
|
||||
observedVoiceUsers: this.observedVoiceUsers ?? null,
|
||||
voiceCache: this.voiceCache ?? null,
|
||||
locale: this.locale ?? null,
|
||||
});
|
||||
|
||||
@@ -808,6 +898,7 @@ export class PlayerManager {
|
||||
|
||||
// Remove player from map and destroy
|
||||
this.playerMap.delete(activeChannelId);
|
||||
this._unindexPlayer(player._guildId, activeChannelId);
|
||||
// Clean up pending scrobble timer
|
||||
const pendingScrobble = this._pendingScrobbleTimers.get(activeChannelId);
|
||||
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this._pendingScrobbleTimers.delete(activeChannelId); }
|
||||
@@ -862,6 +953,7 @@ export class PlayerManager {
|
||||
// Only add to playerMap after join succeeds — this prevents phantom
|
||||
// entries from inflating the player count.
|
||||
this.playerMap.set(cleanChannelId, player);
|
||||
this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
|
||||
this._pendingJoins.delete(cleanChannelId);
|
||||
|
||||
await statusMsg.edit(mkEmbed(this._t(message, "responses.join.joined", { channel: cid })));
|
||||
@@ -892,6 +984,7 @@ export class PlayerManager {
|
||||
}
|
||||
await statusMsg.edit(mkEmbed(errorMsg)).catch(() => {});
|
||||
this.playerMap.delete(cleanChannelId);
|
||||
this._unindexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
|
||||
player.destroy();
|
||||
}
|
||||
})();
|
||||
@@ -920,9 +1013,13 @@ export class PlayerManager {
|
||||
const channelId = getPlayerChannelId(player);
|
||||
const humanUserIds = [];
|
||||
|
||||
// Check observedVoiceUsers first
|
||||
if (this.observedVoiceUsers) {
|
||||
for (const [uid, info] of this.observedVoiceUsers) {
|
||||
// Use VoiceStateCache O(1) channel index instead of iterating all users
|
||||
if (this.voiceCache) {
|
||||
const users = this.voiceCache.getHumansInChannel(guildId, channelId);
|
||||
humanUserIds.push(...users);
|
||||
} else if (this.observedVoiceUsers) {
|
||||
// Legacy fallback
|
||||
for (const [uid, info] of this.observedVoiceUsers.iterateHumanUsers()) {
|
||||
if (cleanId(info.guildId) === guildId && cleanId(info.channelId) === channelId) {
|
||||
humanUserIds.push(uid);
|
||||
}
|
||||
|
||||
@@ -123,12 +123,25 @@ export class FluxerVoiceConnection extends EventEmitter {
|
||||
channelId = null;
|
||||
_voice = null; // parent FluxerRevoice instance
|
||||
_connected = false; // internal flag, set by events
|
||||
users = [];
|
||||
_users = []; // internal, derived from parent FluxerRevoice.users
|
||||
_destroyed = false;
|
||||
|
||||
// @fluxerjs/voice native connection reference (for proper disconnect)
|
||||
_nativeConn = null;
|
||||
|
||||
/**
|
||||
* Users currently in this voice channel.
|
||||
* Derived from the parent FluxerRevoice's unified users map (single source of truth).
|
||||
* This prevents the old divergence bug where the array and Map could get out of sync.
|
||||
*/
|
||||
get users() {
|
||||
return this._users;
|
||||
}
|
||||
|
||||
set users(val) {
|
||||
this._users = Array.isArray(val) ? val : [];
|
||||
}
|
||||
|
||||
constructor(channelId, voice, opts = {}) {
|
||||
super();
|
||||
this.channelId = channelId;
|
||||
@@ -223,6 +236,8 @@ export class FluxerRevoice extends EventEmitter {
|
||||
/** @type {import("@fluxerjs/core").Client} */
|
||||
client = null;
|
||||
connections = new Map();
|
||||
// Unified users map: keyed by "channelId:userId", value is { id, connectedTo }
|
||||
// This is the single source of truth; connection.users is derived from it.
|
||||
users = new Map();
|
||||
|
||||
/** @type {Map<string, Promise>} */
|
||||
@@ -628,8 +643,10 @@ export class FluxerRevoice extends EventEmitter {
|
||||
room.on(RoomEvent.ParticipantConnected, (participant) => {
|
||||
const userId = participant?.identity ?? participant?.sid;
|
||||
if (userId) {
|
||||
connection.users.push({ id: userId, connectedTo: channelId });
|
||||
this.users.set(userId, { id: userId, connectedTo: channelId });
|
||||
const uKey = `${channelId}:${userId}`;
|
||||
this.users.set(uKey, { id: userId, connectedTo: channelId });
|
||||
// Derive connection.users from the unified map (single source of truth)
|
||||
connection._users = [...this.users.values()].filter(u => u.connectedTo === channelId);
|
||||
connection.emit("userjoin", userId);
|
||||
}
|
||||
});
|
||||
@@ -637,8 +654,10 @@ export class FluxerRevoice extends EventEmitter {
|
||||
room.on(RoomEvent.ParticipantDisconnected, (participant) => {
|
||||
const userId = participant?.identity ?? participant?.sid;
|
||||
if (userId) {
|
||||
connection.users = connection.users.filter(u => u.id !== userId);
|
||||
this.users.delete(userId);
|
||||
const uKey = `${channelId}:${userId}`;
|
||||
this.users.delete(uKey);
|
||||
// Derive connection.users from the unified map
|
||||
connection._users = [...this.users.values()].filter(u => u.connectedTo === channelId);
|
||||
connection.emit("userleave", userId);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -0,0 +1,518 @@
|
||||
/**
|
||||
* VoiceStateCache — O(1) voice-state lookups with bounded memory.
|
||||
*
|
||||
* Replaces the raw `observedVoiceUsers` / `observedVoiceBots` Maps with a
|
||||
* composite-keyed, indexed, LRU-evicted cache that supports:
|
||||
*
|
||||
* • O(1) lookup: "is anyone in channel X?" → channelMembers.get(guildId, channelId)
|
||||
* • O(1) lookup: "what channel is user X in?" → userLocations.get(guildId, userId)
|
||||
* • O(1) lookup: "how many humans in channel X?" → channelMembers.get(...).size
|
||||
* • Bounded memory via LRU eviction (default 50 000 entries)
|
||||
* • Composite keys (guildId:userId) so multi-guild users don't overwrite
|
||||
* • Single update function used by both raw WS and high-level handlers
|
||||
*
|
||||
* Data structures:
|
||||
* userLocations — Map<"guildId:userId", {channelId, guildId, userId}>
|
||||
* channelMembers — Map<"guildId:channelId", Set<userId>>
|
||||
* botLocations — Map<"guildId:userId", {channelId, guildId, userId}>
|
||||
* botChannelMembers — Map<"guildId:channelId", Set<userId>>
|
||||
* _lruOrder — String[] (most-recently-updated keys, for eviction)
|
||||
*/
|
||||
|
||||
import { logger } from "./Logger.mjs";
|
||||
|
||||
export class VoiceStateCache {
|
||||
/**
|
||||
* @param {object} [opts]
|
||||
* @param {number} [opts.maxUsers=50000] Max human entries before LRU eviction
|
||||
* @param {number} [opts.maxBots=10000] Max bot entries before LRU eviction
|
||||
*/
|
||||
constructor(opts = {}) {
|
||||
// ── Human users ──────────────────────────────────────────────────────
|
||||
/** @type {Map<string, {channelId, guildId, userId}>} keyed "guildId:userId" */
|
||||
this.userLocations = new Map();
|
||||
/** @type {Map<string, Set<string>>} keyed "guildId:channelId", values are userIds */
|
||||
this.channelMembers = new Map();
|
||||
|
||||
// ── Bot users ────────────────────────────────────────────────────────
|
||||
/** @type {Map<string, {channelId, guildId, userId}>} keyed "guildId:userId" */
|
||||
this.botLocations = new Map();
|
||||
/** @type {Map<string, Set<string>>} keyed "guildId:channelId", values are userIds */
|
||||
this.botChannelMembers = new Map();
|
||||
|
||||
// ── LRU tracking ─────────────────────────────────────────────────────
|
||||
this._maxUsers = opts.maxUsers ?? 50_000;
|
||||
this._maxBots = opts.maxBots ?? 10_000;
|
||||
/** @type {string[]} MRU-first list of user location keys */
|
||||
this._lruUserKeys = [];
|
||||
/** @type {string[]} MRU-first list of bot location keys */
|
||||
this._lruBotKeys = [];
|
||||
}
|
||||
|
||||
// ── Key helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
/** Build composite key "guildId:userId" (both cleaned to digits only) */
|
||||
static userKey(guildId, userId) {
|
||||
return `${String(guildId ?? "").replace(/\D/g, "")}:${String(userId ?? "").replace(/\D/g, "")}`;
|
||||
}
|
||||
|
||||
/** Build composite key "guildId:channelId" (both cleaned to digits only) */
|
||||
static channelKey(guildId, channelId) {
|
||||
return `${String(guildId ?? "").replace(/\D/g, "")}:${String(channelId ?? "").replace(/\D/g, "")}`;
|
||||
}
|
||||
|
||||
// ── Core update (unified — called by both raw WS and high-level handler) ─
|
||||
|
||||
/**
|
||||
* Update voice state for a user.
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {string} params.guildId
|
||||
* @param {string} params.userId
|
||||
* @param {string|null} params.channelId null = user left voice
|
||||
* @param {boolean} [params.isBot=false]
|
||||
*/
|
||||
updateUser({ guildId, userId, channelId, isBot = false }) {
|
||||
const cleanGuild = String(guildId ?? "").replace(/\D/g, "");
|
||||
const cleanUser = String(userId ?? "").replace(/\D/g, "");
|
||||
const cleanChannel = channelId ? String(channelId).replace(/\D/g, "") : 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);
|
||||
|
||||
// ── Remove from previous channel index ───────────────────────────────
|
||||
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) {
|
||||
// ── Add to new channel index ───────────────────────────────────────
|
||||
const cKey = VoiceStateCache.channelKey(cleanGuild, cleanChannel);
|
||||
let set = channelIdx.get(cKey);
|
||||
if (!set) { set = new Set(); channelIdx.set(cKey, set); }
|
||||
set.add(cleanUser);
|
||||
|
||||
// ── Update location map ────────────────────────────────────────────
|
||||
locations.set(uKey, { channelId: cleanChannel, guildId: cleanGuild, userId: cleanUser });
|
||||
|
||||
// ── LRU: move to front ─────────────────────────────────────────────
|
||||
const idx = lruKeys.indexOf(uKey);
|
||||
if (idx !== -1) lruKeys.splice(idx, 1);
|
||||
lruKeys.unshift(uKey);
|
||||
|
||||
// ── Evict if over cap ──────────────────────────────────────────────
|
||||
while (lruKeys.length > maxEntries) {
|
||||
const evictKey = lruKeys.pop();
|
||||
if (evictKey === uKey) continue; // don't evict the entry we just added
|
||||
const evicted = locations.get(evictKey);
|
||||
if (evicted) {
|
||||
const evictCKey = VoiceStateCache.channelKey(evicted.guildId, evicted.channelId);
|
||||
const evictSet = channelIdx.get(evictCKey);
|
||||
if (evictSet) {
|
||||
evictSet.delete(evicted.userId);
|
||||
if (evictSet.size === 0) channelIdx.delete(evictCKey);
|
||||
}
|
||||
locations.delete(evictKey);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// ── User left voice — remove from location map ─────────────────────
|
||||
locations.delete(uKey);
|
||||
// Remove from LRU list
|
||||
const idx = lruKeys.indexOf(uKey);
|
||||
if (idx !== -1) lruKeys.splice(idx, 1);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Query methods ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Check if there are any human users in a specific channel.
|
||||
* O(1) via channelMembers index.
|
||||
*
|
||||
* @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 number of human users in a specific channel.
|
||||
* O(1) via channelMembers index.
|
||||
*
|
||||
* @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 all human userIds in a specific channel.
|
||||
* O(1) lookup + Set iteration.
|
||||
*
|
||||
* @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 channelId a human user is currently in (within a specific guild).
|
||||
* O(1) via userLocations index.
|
||||
*
|
||||
* @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 if a human user is tracked in a specific guild.
|
||||
*
|
||||
* @param {string} guildId
|
||||
* @param {string} userId
|
||||
* @returns {boolean}
|
||||
*/
|
||||
hasUser(guildId, userId) {
|
||||
return this.userLocations.has(VoiceStateCache.userKey(guildId, userId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user location info (channelId, guildId) 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; // already tracked — don't overwrite
|
||||
this.updateUser({ guildId, userId, channelId, isBot });
|
||||
}
|
||||
|
||||
// ── Bulk operations ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Remove all entries for a specific guild (used on GuildDelete).
|
||||
*
|
||||
* @param {string} guildId
|
||||
*/
|
||||
removeGuild(guildId) {
|
||||
const cleanGuild = String(guildId).replace(/\D/g, "");
|
||||
const prefix = cleanGuild + ":";
|
||||
|
||||
// Humans
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
if (uKey.startsWith(prefix)) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
// Clean up channel member sets for this guild
|
||||
for (const [cKey, set] of this.channelMembers) {
|
||||
if (cKey.startsWith(prefix)) this.channelMembers.delete(cKey);
|
||||
}
|
||||
// Clean LRU
|
||||
this._lruUserKeys = this._lruUserKeys.filter(k => !k.startsWith(prefix));
|
||||
|
||||
// Bots
|
||||
for (const [uKey, loc] of this.botLocations) {
|
||||
if (uKey.startsWith(prefix)) {
|
||||
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);
|
||||
}
|
||||
}
|
||||
for (const [cKey, set] of this.botChannelMembers) {
|
||||
if (cKey.startsWith(prefix)) this.botChannelMembers.delete(cKey);
|
||||
}
|
||||
this._lruBotKeys = this._lruBotKeys.filter(k => !k.startsWith(prefix));
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a specific channel's index entries (used when a player leaves).
|
||||
*
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
*/
|
||||
removeChannel(guildId, channelId) {
|
||||
const cKey = VoiceStateCache.channelKey(guildId, channelId);
|
||||
|
||||
// Humans
|
||||
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);
|
||||
// Only delete if the user is still in THIS channel (not moved)
|
||||
if (loc && loc.channelId === String(channelId).replace(/\D/g, "")) {
|
||||
this.userLocations.delete(uKey);
|
||||
}
|
||||
}
|
||||
this.channelMembers.delete(cKey);
|
||||
}
|
||||
|
||||
// Bots
|
||||
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 === String(channelId).replace(/\D/g, "")) {
|
||||
this.botLocations.delete(uKey);
|
||||
}
|
||||
}
|
||||
this.botChannelMembers.delete(cKey);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Selectively remove entries for users whose IDs appear in a given set
|
||||
* (used during GuildCreate to purge stale entries being replaced).
|
||||
*
|
||||
* @param {string} guildId
|
||||
* @param {Set<string>} userIds User IDs whose entries should be purged
|
||||
* @param {boolean} [botsOnly=false] Only purge bot entries
|
||||
*/
|
||||
purgeUsersInGuild(guildId, userIds, botsOnly = false) {
|
||||
const cleanGuild = String(guildId).replace(/\D/g, "");
|
||||
|
||||
if (!botsOnly) {
|
||||
// Purge human entries
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Purge bot entries
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Backward-compatible accessors ────────────────────────────────────────
|
||||
// These provide the same interface as the old raw Maps so that existing
|
||||
// code (dashboard, commands) doesn't need to be rewritten immediately.
|
||||
|
||||
/**
|
||||
* Get the "observedVoiceUsers" size (human count).
|
||||
* Backward-compat with `this.observedVoiceUsers.size`
|
||||
*/
|
||||
get observedVoiceUsersSize() { return this.userLocations.size; }
|
||||
|
||||
/**
|
||||
* Get the "observedVoiceBots" size.
|
||||
* Backward-compat with `this.observedVoiceBots.size`
|
||||
*/
|
||||
get observedVoiceBotsSize() { return this.botLocations.size; }
|
||||
|
||||
/**
|
||||
* Iterate over all human user locations.
|
||||
* Yields [compositeKey, {channelId, guildId, userId}] — same shape as Map entries.
|
||||
* Backward-compat with `for (const [uid, info] of this.observedVoiceUsers)`.
|
||||
*/
|
||||
*iterateHumanUsers() {
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
// Yield the userId (not composite key) as first element for compat
|
||||
yield [loc.userId, { channelId: loc.channelId, guildId: loc.guildId }];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate over all bot user locations.
|
||||
* Yields [compositeKey, {channelId, guildId, userId}].
|
||||
* Backward-compat with `for (const [uid, info] of this.observedVoiceBots)`.
|
||||
*/
|
||||
*iterateBotUsers() {
|
||||
for (const [uKey, loc] of this.botLocations) {
|
||||
yield [uKey, { channelId: loc.channelId, guildId: loc.guildId }];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a human user's location by userId and guildId.
|
||||
* If guildId is provided, uses O(1) composite key.
|
||||
* If guildId is null, falls back to O(n) scan (legacy compat).
|
||||
*
|
||||
* @param {string} userId
|
||||
* @param {string|null} [guildId=null]
|
||||
* @returns {{channelId: string, guildId: string}|undefined}
|
||||
*/
|
||||
getHumanUser(userId, guildId = null) {
|
||||
if (guildId) {
|
||||
return this.userLocations.get(VoiceStateCache.userKey(guildId, userId));
|
||||
}
|
||||
// Legacy fallback: scan for first match
|
||||
const cleanUser = String(userId).replace(/\D/g, "");
|
||||
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 location (backward-compat with observedVoiceUsers.set).
|
||||
*
|
||||
* @param {string} userId
|
||||
* @param {{channelId: string, guildId: 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 location (backward-compat with observedVoiceBots.set).
|
||||
*
|
||||
* @param {string} compositeKey "guildId:userId" composite key
|
||||
* @param {{channelId: string, guildId: string}} info
|
||||
*/
|
||||
setBotUser(compositeKey, info) {
|
||||
const guildId = info.guildId;
|
||||
const channelId = info.channelId;
|
||||
// Extract userId from composite key (format: "guildId:userId")
|
||||
const userId = compositeKey.split(":").pop();
|
||||
if (guildId && channelId && userId) {
|
||||
this.updateUser({ guildId, userId, channelId, isBot: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a human user by userId (scans all guilds if no guildId given).
|
||||
* Backward-compat with observedVoiceUsers.delete(userId).
|
||||
*
|
||||
* @param {string} userId
|
||||
* @param {string|null} [guildId=null]
|
||||
*/
|
||||
deleteHumanUser(userId, guildId = null) {
|
||||
if (guildId) {
|
||||
this.updateUser({ guildId, userId, channelId: null, isBot: false });
|
||||
} else {
|
||||
// Legacy: remove from ALL guilds
|
||||
const cleanUser = String(userId).replace(/\D/g, "");
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
if (loc.userId === cleanUser) {
|
||||
this.updateUser({ guildId: loc.guildId, userId: cleanUser, channelId: null, isBot: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a bot user by composite key.
|
||||
* Backward-compat with observedVoiceBots.delete(compositeKey).
|
||||
*
|
||||
* @param {string} compositeKey "guildId:userId"
|
||||
*/
|
||||
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 if a human user exists in the cache.
|
||||
* Backward-compat with observedVoiceUsers.has(userId).
|
||||
*
|
||||
* @param {string} userId
|
||||
* @param {string|null} [guildId=null]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
hasHumanUser(userId, guildId = null) {
|
||||
if (guildId) {
|
||||
return this.userLocations.has(VoiceStateCache.userKey(guildId, userId));
|
||||
}
|
||||
// Legacy: scan
|
||||
const cleanUser = String(userId).replace(/\D/g, "");
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
if (loc.userId === cleanUser) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a bot user exists in the cache.
|
||||
* Backward-compat with observedVoiceBots.has(compositeKey).
|
||||
*
|
||||
* @param {string} compositeKey
|
||||
* @returns {boolean}
|
||||
*/
|
||||
hasBotUser(compositeKey) {
|
||||
return this.botLocations.has(compositeKey);
|
||||
}
|
||||
|
||||
// ── Debug / stats ────────────────────────────────────────────────────────
|
||||
|
||||
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,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -48,19 +48,17 @@ export class Dashboard {
|
||||
|
||||
case "server": {
|
||||
try {
|
||||
const guild = await this.remix.client.guilds.fetch(data.key);
|
||||
const guild = this.remix.client.guilds.get(data.key);
|
||||
if (!guild) return { error: "Server not found" };
|
||||
const member = await guild.members.fetch(data.accessor).catch(() => null);
|
||||
const channels = await guild.fetchChannels(); // execute before converting the guild, see caching
|
||||
const server = Dashboard.convertServer(guild);
|
||||
if (member) {
|
||||
server.channels = server.channels.filter(c => {
|
||||
const ch = channels.find(cl => c.id === cl.id);
|
||||
const ch = guild.channels.get(c.id);
|
||||
return ch ? ch.permissionsFor?.(member)?.has?.("ViewChannel") ?? true : true;
|
||||
});
|
||||
server.voiceChannels = server.voiceChannels.filter(c => {
|
||||
if (c.type !== 2) return false;
|
||||
const ch = channels.find(cl => c.id === cl.id);
|
||||
const ch = guild.channels.get(c.id);
|
||||
return ch ? ch.permissionsFor?.(member)?.has?.("ViewChannel") ?? true : true;
|
||||
});
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user