This commit is contained in:
NoLogicAlan committed 2026-05-20 22:32:39 +03:00
1 parent 05fb38aabd
commit bc1fe82919
43 files changed
+122 -1784

No files matched your search

-1
View File
@@ -8,7 +8,6 @@
* Edit only here; FluxerListManager.mjs and commands/vote.mjs import from this file.
*/
// ── FluxerList API ──────────────────────────────────────────────────────────────
export const FLUXERLIST = {
/** Base URL for all FluxerList API v1 endpoints */
+8 -130
View File
@@ -32,62 +32,37 @@ import { joinVoiceChannel, getVoiceManager } from "@fluxerjs/voice";
import { logger } from "./Logger.mjs";
{
// ── LiveKit SDK log suppression ──────────────────────────────────────────
// The LiveKit Node.js SDK (via pino) emits verbose JSON and human-readable
// log lines that flood the console. We monkey-patch console.log and
// process.stdout.write to silently drop lines from the "lk-rtc" logger.
//
// Guard: only patch once even if the module is imported multiple times
// (e.g. during hot-reload). The global symbol ensures idempotency.
if (!globalThis.__fluxerLiveKitLogPatchApplied) {
globalThis.__fluxerLiveKitLogPatchApplied = true;
const _originalConsoleLog = console.log;
console.log = function (...args) {
// Fast path: if the first arg is a string that looks like a pino JSON log
if (args.length === 1 && typeof args[0] === "string" && args[0].startsWith("{")) {
try {
const parsed = JSON.parse(args[0]);
// Drop pino logs from LiveKit SDK ("lk-rtc" name)
if (parsed.name === "lk-rtc") return;
} catch (_) {
// Not valid JSON — pass through
}
}
// Suppress LiveKit SDK's human-readable log lines:
// [voice LiveKitRtc] connected to room
// [voice LiveKitRtc] Room disconnected
// [voice LiveKitRtc] emitting disconnect
// [voice LiveKitRtc] Room reconnecting...
// [voice LiveKitRtc] Room reconnected
if (args.length >= 1 && typeof args[0] === "string" && args[0].includes("[voice LiveKitRtc]")) {
return; // silently drop
return;
}
_originalConsoleLog.apply(console, args);
};
// ── Also monkey-patch process.stdout.write ──────────────────────────────
// Pino writes directly to process.stdout.write, bypassing console.log
// entirely. This is the primary path for the JSON log lines like:
// {"level":20,"time":1778784504183,"pid":961949,"name":"lk-rtc",...}
// We intercept these and silently drop them.
const _originalStdoutWrite = process.stdout.write.bind(process.stdout);
process.stdout.write = function (chunk, encoding, callback) {
// Only intercept string chunks that look like pino JSON logs
if (typeof chunk === "string" && chunk.startsWith("{")) {
try {
// Fast check: does it contain lk-rtc before full parse?
if (chunk.includes('"lk-rtc"')) {
const parsed = JSON.parse(chunk);
if (parsed.name === "lk-rtc") {
// Silently drop — call callback to signal "written" so pino doesn't stall
if (typeof encoding === "function") { encoding(); }
else if (typeof callback === "function") { callback(); }
return true;
}
}
} catch (_) {
// Not valid JSON — pass through
}
}
return _originalStdoutWrite(chunk, encoding, callback);
@@ -95,26 +70,18 @@ import { logger } from "./Logger.mjs";
}
}
// ConnectionState enum values for reference:
// ConnectionState.CONN_DISCONNECTED = 0
// ConnectionState.CONN_CONNECTED = 1
// ConnectionState.CONN_RECONNECTING = 2
/** Helper: returns a human-readable label for a ConnectionState value */
function stateLabel(cs) {
if (cs === ConnectionState?.CONN_CONNECTED) return "CONN_CONNECTED";
if (cs === ConnectionState?.CONN_DISCONNECTED) return "CONN_DISCONNECTED";
if (cs === ConnectionState?.CONN_RECONNECTING) return "CONN_RECONNECTING";
// Fallback for numeric values if enum import fails
if (cs === 1) return "CONN_CONNECTED(1)";
if (cs === 0) return "CONN_DISCONNECTED(0)";
if (cs === 2) return "CONN_RECONNECTING(2)";
return String(cs);
}
// ═══════════════════════════════════════════════════════════════════════════════
// FluxerVoiceConnection — compatible with revoice.js VoiceConnection
// ═══════════════════════════════════════════════════════════════════════════════
/**
* A voice connection that wraps a LiveKit Room obtained via the Fluxer
@@ -132,12 +99,11 @@ export class FluxerVoiceConnection extends EventEmitter {
/** @type {Room|null} */
room = null;
channelId = null;
_voice = null; // parent FluxerRevoice instance
_connected = false; // internal flag, set by events
_users = []; // internal, derived from parent FluxerRevoice.users
_voice = null;
_connected = false;
_users = [];
_destroyed = false;
// @fluxerjs/voice native connection reference (for proper disconnect)
_nativeConn = null;
/**
@@ -159,7 +125,6 @@ export class FluxerVoiceConnection extends EventEmitter {
this._voice = voice;
this.room = opts.room ?? null;
this._nativeConn = opts.nativeConnection ?? null;
// Use room.isConnected (boolean getter) — the correct Node.js SDK API
this._connected = !!(this.room && this.room.isConnected);
}
@@ -170,7 +135,6 @@ export class FluxerVoiceConnection extends EventEmitter {
*/
get connected() {
if (this._destroyed) return false;
// Prefer the LiveKit Room's own isConnected getter (source of truth)
if (this.room) return this.room.isConnected;
return this._connected;
}
@@ -186,29 +150,20 @@ export class FluxerVoiceConnection extends EventEmitter {
*/
async disconnect() {
if (this._destroyed) return;
// Mark this as an intentional disconnect so the RoomEvent.Disconnected
// handler can log it correctly
if (this._voice && this.channelId) {
this._voice.markIntentionalDisconnect(this.channelId);
// Prefer a channel-scoped gateway leave before tearing down the room.
// The native disconnect path can be guild-scoped in some environments,
// which drops every voice connection in the guild.
const guildId = this._voice._resolveGuildForChannel?.(this.channelId) ?? null;
this._voice._leaveGateway?.(this.channelId, guildId);
}
this._destroyed = true;
this._connected = false;
// Close the LiveKit room directly after sending the leave signal.
// This keeps the disconnect scoped to the target channel.
if (this.room) {
try {
await this.room.disconnect();
} catch (e) {
// Room may already be closed
}
} else if (this._nativeConn && typeof this._nativeConn.disconnect === "function") {
// Fallback only when no room object is available.
try {
await this._nativeConn.disconnect();
} catch (e) {
@@ -228,33 +183,27 @@ export class FluxerVoiceConnection extends EventEmitter {
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// FluxerRevoice — drop-in replacement for revoice.js Revoice
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Revoice-compatible class that uses the Fluxer gateway for voice joins.
*
* Usage (drop-in for `new Revoice(token)`):
*
* // Before (third-party API — 401 on Fluxer):
*
* this.revoice = new Revoice(config.token);
*
* // After (Fluxer API — works on Fluxer):
*
* this.revoice = new FluxerRevoice(client);
*/
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>} */
_guildJoinQueue = new Map();
// ── Global join queue ──────────────────────────────────────────────────────
/** @type {Promise} Global join serializer — only one join at a time across all guilds */
_globalJoinQueue = Promise.resolve();
/** @type {number} Minimum delay between ANY two joins (ms), even across guilds.
@@ -304,7 +253,6 @@ export class FluxerRevoice extends EventEmitter {
*/
markIntentionalDisconnect(channelId) {
this._intentionalDisconnects.add(String(channelId));
// Auto-clear after 10 seconds as safety net
setTimeout(() => this._intentionalDisconnects.delete(String(channelId)), 10_000);
}
@@ -331,11 +279,6 @@ export class FluxerRevoice extends EventEmitter {
const guildForLeave = guildId ?? this._resolveGuildForChannel(channelId);
// ── Method 1 (PREFERRED): Use vm.leaveChannel(channelId) ──────────
// This sends a channel-specific VOICE_STATE_UPDATE that only leaves
// the specified channel, preserving all other voice connections in
// the same guild. This is critical for multi-voice / 24/7 setups
// where the bot may be in several channels simultaneously.
if (typeof vm.leaveChannel === "function") {
try {
vm.leaveChannel(channelId);
@@ -346,10 +289,6 @@ export class FluxerRevoice extends EventEmitter {
}
}
// ── Method 2: Use vm.leave(guildId) — guild-level fallback ─────────
// WARNING: This disconnects ALL voice channels in the guild, not just
// the target channel. Only used when leaveChannel() is unavailable.
// The caller must handle rejoining other 24/7 channels if needed.
if (guildForLeave && typeof vm.leave === "function") {
try {
vm.leave(guildForLeave);
@@ -360,12 +299,8 @@ export class FluxerRevoice extends EventEmitter {
}
}
// ── Method 3: Use vm.updateVoiceState() as last resort ─────────────
if (typeof vm.updateVoiceState === "function") {
if (guildForLeave) {
// NEVER send an unscoped updateVoiceState(null, opts) because it
// tells the gateway to leave ALL guilds' voice channels, causing
// cascading disconnections across all active voice connections.
try {
vm.updateVoiceState(guildForLeave, null, { self_deaf: false, self_mute: false });
logger.player(`[FluxerRevoice] Sent gateway leave via updateVoiceState() for guild ${guildForLeave}`);
@@ -407,19 +342,15 @@ export class FluxerRevoice extends EventEmitter {
* @param {FluxerVoiceConnection} existing
*/
async _destroyStaleConnection(channelId, existing) {
// 1. Remove from map immediately so no other code can get this dead ref
this.connections.delete(channelId);
// Mark as intentional so the LiveKit disconnect handler logs correctly
this.markIntentionalDisconnect(channelId);
const staleGuildId = this._resolveGuildForChannel(channelId);
this._leaveGateway(channelId, staleGuildId);
// 2. Close the LiveKit Room directly
if (existing.room) {
try {
await existing.room.disconnect();
} catch (_) {
// Room may already be closed
}
} else if (existing._nativeConn && typeof existing._nativeConn.disconnect === "function") {
try {
@@ -429,7 +360,6 @@ export class FluxerRevoice extends EventEmitter {
}
}
// 3. Mark as destroyed and clean up listeners
existing._destroyed = true;
existing._connected = false;
try { existing.removeAllListeners(); } catch (_) {}
@@ -448,17 +378,13 @@ export class FluxerRevoice extends EventEmitter {
*/
async join(channelId, _leaveIfEmpty = false) {
const joinOperation = async () => {
// Small gap between joins to let the gateway process the previous
// session's cleanup. This runs BEFORE the actual join logic.
await new Promise(r => setTimeout(r, this._globalJoinDelay));
return await this._joinInternal(channelId, _leaveIfEmpty);
};
// Chain onto the global queue: our join only starts after the previous
// one has fully completed (or failed). We store the new tail of the chain.
const prevQueue = this._globalJoinQueue;
const ourResult = prevQueue.then(() => joinOperation());
this._globalJoinQueue = ourResult.catch(() => {}); // don't break chain on error
this._globalJoinQueue = ourResult.catch(() => {});
return await ourResult;
}
@@ -471,7 +397,6 @@ export class FluxerRevoice extends EventEmitter {
* @returns {Promise<FluxerVoiceConnection>}
*/
async _joinInternal(channelId, _leaveIfEmpty = false) {
// Resolve the guild ID for this channel
let guildId = null;
try {
const ch = this.client.channels?.get?.(channelId);
@@ -480,10 +405,6 @@ export class FluxerRevoice extends EventEmitter {
if (this.connections.has(channelId)) {
const existing = this.connections.get(channelId);
// If the existing connection is still alive, reuse it.
// If the LiveKit room disconnected, the connection is stale — clean it
// up fully and rejoin instead of returning a dead connection that will
// fail with "LiveKit disconnected (connectionState: 0)".
if (existing && !existing._destroyed && existing.room && existing.room.isConnected) {
logger.player(`[FluxerRevoice] Already connected to ${channelId}, returning existing connection`);
return existing;
@@ -498,7 +419,6 @@ export class FluxerRevoice extends EventEmitter {
logger.player(`[FluxerRevoice] Joining channel ${channelId} via Fluxer gateway...`);
// Fetch the channel object from the client cache (or REST)
let channel = this.client.channels?.get?.(channelId);
if (!channel) {
try {
@@ -511,17 +431,8 @@ export class FluxerRevoice extends EventEmitter {
throw new Error(`Channel not found: ${channelId}`);
}
// Resolve the guild ID for this channel (used for guild-scoped leave signals)
const channelGuildId = guildId ?? channel?.guildId ?? channel?.guild?.id ?? null;
// Use @fluxerjs/voice to join the channel via the Fluxer gateway.
// This handles the VOICE_STATE_UPDATE → VOICE_SERVER_UPDATE flow
// and creates a LiveKit connection with the returned credentials.
//
// Permission validation is handled upstream in PlayerManager via
// botHasVoicePermissions() — real permission errors are caught before
// we even reach this point. If we get a 401 here, it's a stale session,
// and PlayerManager's sanitizeJoinError will handle the retry.
let nativeConnection;
try {
nativeConnection = await joinVoiceChannel(this.client, channel);
@@ -535,17 +446,13 @@ export class FluxerRevoice extends EventEmitter {
logger.player(`[FluxerRevoice] Gateway join successful for ${channelId}`);
// The @fluxerjs/voice connection wraps a LiveKit Room.
// Extract it so we can use it with revoice.js's MediaPlayer.
let room = null;
// Try to get the LiveKit Room from the native connection
if (nativeConnection.room) {
room = nativeConnection.room;
logger.player(`[FluxerRevoice] Got LiveKit room from native connection (isConnected: ${room.isConnected}, connectionState: ${stateLabel(room.connectionState)})`);
}
// (non-LiveKit) which we don't support for music playback.
if (!room) {
try { await nativeConnection.disconnect(); } catch (_) {}
throw new Error(
@@ -554,16 +461,10 @@ export class FluxerRevoice extends EventEmitter {
);
}
// ── Wait for the room to be connected ────────────────────────────────
// Use room.isConnected (boolean) and room.connectionState (enum) which
// are the correct APIs in @livekit/rtc-node Node.js SDK.
// Also listen for the ConnectionStateChanged event for immediate feedback.
const maxWait = 10_000;
const startTime = Date.now();
// If already connected, skip the wait loop
if (!room.isConnected) {
// Listen for the ConnectionStateChanged event to resolve faster
let eventResolved = false;
const statePromise = new Promise((resolve) => {
const handler = (cs) => {
@@ -575,30 +476,25 @@ export class FluxerRevoice extends EventEmitter {
} else if (cs === ConnectionState?.CONN_DISCONNECTED || cs === 0) {
eventResolved = true;
room.off(RoomEvent.ConnectionStateChanged, handler);
resolve(); // resolve so we can check isConnected below
resolve();
}
};
room.on(RoomEvent.ConnectionStateChanged, handler);
});
// Poll + event race
while (!room.isConnected && (Date.now() - startTime) < maxWait) {
// Wait for either the event to fire or a 200ms poll interval
await Promise.race([
statePromise,
new Promise(r => setTimeout(r, 200)),
]);
// Check if connected
if (room.isConnected) break;
// Check if disconnected (dead state)
const cs = room.connectionState;
if (cs === ConnectionState?.CONN_DISCONNECTED || cs === 0) break;
}
}
// Final state check using the correct API
const finalConnected = room.isConnected;
const finalCS = room.connectionState;
@@ -609,15 +505,11 @@ export class FluxerRevoice extends EventEmitter {
logger.player(`[FluxerRevoice] LiveKit room ready (isConnected: ${finalConnected}, connectionState: ${stateLabel(finalCS)})`);
// Create our FluxerVoiceConnection wrapper
const connection = new FluxerVoiceConnection(channelId, this, {
room,
nativeConnection,
});
// ── LiveKit room event forwarding ──────────────────────────────────
// Forward LiveKit events to FluxerVoiceConnection events so
// Player.mjs's connection.on("disconnect") etc. still work.
room.on(RoomEvent.Disconnected, (reason) => {
const isIntentional = this._intentionalDisconnects.has(String(channelId));
@@ -627,17 +519,11 @@ export class FluxerRevoice extends EventEmitter {
connection._connected = false;
connection._destroyed = true;
// Remove from connections map so the next join() creates a fresh
// connection instead of returning this dead one.
this.connections.delete(channelId);
if (!isIntentional) {
// Unexpected disconnects still need a gateway leave signal so the
// next join gets a fresh voice session.
this._leaveGateway(channelId, channelGuildId);
// Best-effort cleanup for the native wrapper. Skip this on intentional
// leaves because it can collapse multi-voice into a guild-wide leave.
if (nativeConnection && typeof nativeConnection.disconnect === "function") {
try { nativeConnection.disconnect(); } catch (_) {}
}
@@ -646,16 +532,12 @@ export class FluxerRevoice extends EventEmitter {
connection.emit("disconnect");
});
// No automatic reconnection handling — if the LiveKit room disconnects
// unexpectedly, the connection is considered dead. The caller (Player.mjs)
// will emit "autoleave" and the user must manually rejoin if desired.
room.on(RoomEvent.ParticipantConnected, (participant) => {
const userId = participant?.identity ?? participant?.sid;
if (userId) {
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);
}
@@ -666,19 +548,15 @@ export class FluxerRevoice extends EventEmitter {
if (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);
}
});
// Track the connection
this.connections.set(channelId, connection);
// Auto-leave when room empties (if requested)
if (_leaveIfEmpty) {
connection.on("userleave", () => {
// Only trigger autoleave if no remote participants remain
const remoteCount = room.remoteParticipants?.size ?? 0;
if (remoteCount === 0) {
logger.player(`[FluxerRevoice] Room empty, triggering autoleave for ${channelId}`);
-2
View File
@@ -27,7 +27,6 @@ export function get247ChannelMode(set, channelId) {
const perChannel = modes[channelId];
if (perChannel === "on" || perChannel === "auto" || perChannel === "off") return perChannel;
}
// Fallback: guild-wide mode (legacy)
const guildMode = set.get("stay_247_mode") ?? "off";
return guildMode;
}
@@ -44,7 +43,6 @@ export function set247ChannelMode(set, channelId, mode) {
if (!modes || typeof modes !== "object" || Array.isArray(modes)) modes = {};
modes[channelId] = mode;
set.set("stay_247_modes", modes);
// Also update guild-wide mode for backward compat
set.set("stay_247_mode", mode);
}
-8
View File
@@ -48,7 +48,6 @@ export class Locale {
return;
}
// Auto-discover all .json files in the locales directory
let files;
try {
files = readdirSync(LOCALES_DIR).filter(f => f.endsWith(".json"));
@@ -93,11 +92,9 @@ export class Locale {
_getLocaleData(guildId) {
if (!guildId) return this.locales.get(this.defaultLocale) ?? {};
// Check cache first
const cached = this._resolved.get(guildId);
if (cached) return cached;
// Resolve locale from guild settings
let code = this.defaultLocale;
try {
const serverSettings = this.settingsMgr?.guilds?.get?.(guildId);
@@ -151,22 +148,17 @@ export class Locale {
* @returns {string} Translated string, or the key itself if not found
*/
translate(guildId, key, replacements = {}) {
// Resolve locale data for this guild (uses cache internally)
const localeData = this._getLocaleData(guildId);
// Try guild's locale first
let value = this._resolve(localeData, key);
// Fallback to English if not found in guild locale
if (value === undefined) {
value = this._resolve(this.locales.get(this.defaultLocale) ?? {}, key);
}
// If still not found, return the key so devs can see what's missing
if (value === undefined) return key;
if (typeof value !== "string") return key;
// Replace {{placeholder}} patterns
for (const [placeholder, val] of Object.entries(replacements)) {
value = value.replace(
new RegExp(`\\{\\{${placeholder}\\}\\}`, "g"),
+1 -5
View File
@@ -30,9 +30,8 @@ export function initLogger(config) {
}
function isEnabled(category) {
if (!_config) return true; // default on if not yet initialised
if (!_config) return true;
if (_config.enabled === false) return false;
// If the category key is missing, default to true
return _config[category] !== false;
}
@@ -41,17 +40,14 @@ function ts() {
}
export const logger = {
// ── always-on (errors / warnings critical to operation) ──────────────────
error(tag, ...args) {
console.error(`[${ts()}] ${tag}`, ...args);
},
warn(tag, ...args) {
// warnings are on unless master switch is off
if (_config?.enabled === false) return;
console.warn(`[${ts()}] ${tag}`, ...args);
},
// ── categorised logs ─────────────────────────────────────────────────────
player(...args) { if (isEnabled("player")) console.log(`[${ts()}]`, ...args); },
inactivity(...args) { if (isEnabled("inactivity")) console.log(`[${ts()}]`, ...args); },
voice247(...args) { if (isEnabled("voice247")) console.log(`[${ts()}]`, ...args); },
+1 -49
View File
@@ -28,19 +28,16 @@ export class VoiceStateCache {
* @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 */
@@ -49,7 +46,6 @@ export class VoiceStateCache {
this._lruBotKeys = [];
}
// ── Key helpers ──────────────────────────────────────────────────────────
/** Build composite key "guildId:userId" (both cleaned to digits only) */
static userKey(guildId, userId) {
@@ -61,7 +57,6 @@ export class VoiceStateCache {
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.
@@ -84,7 +79,6 @@ export class VoiceStateCache {
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);
@@ -96,33 +90,21 @@ export class VoiceStateCache {
}
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 most-recently-used position ──────────────────────
// JavaScript Maps maintain insertion order, so delete + re-insert
// is O(1) amortized instead of O(n) with indexOf + splice on an array.
// We keep the _lruUserKeys / _lruBotKeys arrays as fast eviction queues
// but use the Map's own key order for O(1) move-to-front.
if (locations.has(uKey)) {
// Re-insert to move to end (most recently used) — O(1)
locations.delete(uKey);
locations.set(uKey, { channelId: cleanChannel, guildId: cleanGuild, userId: cleanUser });
}
// ── Evict if over cap ──────────────────────────────────────────────
// Use the Map's insertion order to find the oldest entry (first key).
// This is O(1) per eviction instead of popping from an array.
while (locations.size > maxEntries) {
const evictKey = locations.keys().next().value;
if (evictKey === uKey) {
// Don't evict the entry we just added — re-insert at end and move to next
const evictVal = locations.get(evictKey);
locations.delete(evictKey);
locations.set(evictKey, evictVal);
@@ -138,20 +120,16 @@ export class VoiceStateCache {
}
locations.delete(evictKey);
}
// Also remove from LRU key list if present
const lruIdx = lruKeys.indexOf(evictKey);
if (lruIdx !== -1) lruKeys.splice(lruIdx, 1);
}
} 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.
@@ -242,11 +220,10 @@ export class VoiceStateCache {
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
if (locations.has(uKey)) return;
this.updateUser({ guildId, userId, channelId, isBot });
}
// ── Bulk operations ──────────────────────────────────────────────────────
/**
* Remove all entries for a specific guild (used on GuildDelete).
@@ -257,7 +234,6 @@ export class VoiceStateCache {
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);
@@ -266,14 +242,11 @@ export class VoiceStateCache {
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);
@@ -297,13 +270,11 @@ export class VoiceStateCache {
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);
}
@@ -311,7 +282,6 @@ export class VoiceStateCache {
this.channelMembers.delete(cKey);
}
// Bots
const botSet = this.botChannelMembers.get(cKey);
if (botSet) {
for (const userId of botSet) {
@@ -337,7 +307,6 @@ export class VoiceStateCache {
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);
@@ -350,7 +319,6 @@ export class VoiceStateCache {
}
}
// Purge bot entries
for (const userId of userIds) {
const uKey = VoiceStateCache.userKey(cleanGuild, userId);
const loc = this.botLocations.get(uKey);
@@ -363,9 +331,6 @@ export class VoiceStateCache {
}
}
// ── 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).
@@ -386,7 +351,6 @@ export class VoiceStateCache {
*/
*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 }];
}
}
@@ -415,7 +379,6 @@ export class VoiceStateCache {
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 };
@@ -446,7 +409,6 @@ export class VoiceStateCache {
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 });
@@ -464,7 +426,6 @@ export class VoiceStateCache {
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) {
@@ -501,7 +462,6 @@ export class VoiceStateCache {
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;
@@ -520,10 +480,6 @@ 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.
@@ -553,7 +509,6 @@ export class VoiceStateCache {
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;
@@ -575,7 +530,6 @@ export class VoiceStateCache {
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 };
@@ -607,7 +561,6 @@ export class VoiceStateCache {
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) {
@@ -655,7 +608,6 @@ export class VoiceStateCache {
}
}
// ── Debug / stats ────────────────────────────────────────────────────────
get stats() {
return {
-3
View File
@@ -9,7 +9,6 @@
*/
export const PROVIDERS = {
// ── Standard search ──────────────────────────────────────────────────────
yt: { prefix: "ytsearch", label: "YouTube" },
ytm: { prefix: "ytmsearch", label: "YouTube Music" },
scld: { prefix: "scsearch", label: "SoundCloud" },
@@ -56,14 +55,12 @@ export const PROVIDERS = {
anghami: { prefix: "agsearch", label: "Anghami" },
bk: { prefix: "bksearch", label: "Bluesky" },
bluesky: { prefix: "bksearch", label: "Bluesky" },
// ── Recommendations ──────────────────────────────────────────────────────
ytrec: { prefix: "ytrec", label: "YouTube (recommended)" },
sprec: { prefix: "sprec", label: "Spotify (recommended)" },
dzrec: { prefix: "dzrec", label: "Deezer (recommended)" },
tdrec: { prefix: "tdrec", label: "Tidal (recommended)" },
jsrec: { prefix: "jsrec", label: "JioSaavn (recommended)" },
vkrec: { prefix: "vkrec", label: "VK Music (recommended)" },
// ── TTS ──────────────────────────────────────────────────────────────────
gtts: { prefix: "gtts", label: "Google TTS" },
tts: { prefix: "gtts", label: "Google TTS" },
ftts: { prefix: "ftts", label: "Flowery TTS" },