diff --git a/config_example.json b/config_example.json index e852714..7bf57e8 100644 --- a/config_example.json +++ b/config_example.json @@ -59,16 +59,6 @@ } }, "radio": [], - "cache": { - "guilds": { - "enabled": true, - "max": 5000 - }, - "members": { - "enabled": true, - "max": 10000 - } - }, "helpCatalog": true, "helpPagination": true, "mysql": { @@ -120,8 +110,10 @@ "enabled": true, "player": true, "inactivity": true, + "aloneCheck": true, "voiceState": true, "voice247": true, + "voice": false, "mediaplayer": false, "commands": true, "guild": true, diff --git a/index.mjs b/index.mjs index 3a6f15b..7012992 100644 --- a/index.mjs +++ b/index.mjs @@ -594,6 +594,7 @@ export class Remix { } if (typeof wsObj.addEventListener === "function") { wsObj.addEventListener("error", (event) => { + if (typeof event.preventDefault === "function") event.preventDefault(); const err = event?.error ?? event?.message ?? event; logWsError(label, err); }); diff --git a/src/GatewayHandler.mjs b/src/GatewayHandler.mjs index ea7b0eb..71b158e 100644 --- a/src/GatewayHandler.mjs +++ b/src/GatewayHandler.mjs @@ -501,7 +501,9 @@ export class GatewayHandler { } catch (_) {} }; - remix._rawGatewayErrorHandler = (err) => { + remix._rawGatewayErrorHandler = (errOrEvent) => { + if (typeof errOrEvent?.preventDefault === "function") errOrEvent.preventDefault(); + const err = errOrEvent?.error ?? errOrEvent?.message ?? errOrEvent; const now = Date.now(); if (now - _wsErrorCooldown.lastLogged < _wsErrorCooldown.COOLDOWN_MS) return; _wsErrorCooldown.lastLogged = now; diff --git a/src/LastFmManager.mjs b/src/LastFmManager.mjs index f763f72..d1aa1cd 100644 --- a/src/LastFmManager.mjs +++ b/src/LastFmManager.mjs @@ -91,6 +91,7 @@ export class LastFmManager { this._hasBotIdColumn = false; this._userCache = new Map(); + this._userCacheMax = 5000; this._totalScrobblesCache = null; this._totalScrobblesCacheExpiry = 0; @@ -263,6 +264,10 @@ export class LastFmManager { scrobbleEnabled: !!row.scrobble, }; this._userCache.set(userId, data); + while (this._userCache.size > this._userCacheMax) { + const oldestKey = this._userCache.keys().next().value; + this._userCache.delete(oldestKey); + } return data; } @@ -277,6 +282,10 @@ export class LastFmManager { ); const data = { sessionKey, username: username ?? "", scrobbleEnabled: true }; this._userCache.set(userId, data); + while (this._userCache.size > this._userCacheMax) { + const oldestKey = this._userCache.keys().next().value; + this._userCache.delete(oldestKey); + } try { await pool.execute( diff --git a/src/MoonlinkManager.mjs b/src/MoonlinkManager.mjs index 4f4c0fb..c3dd2bd 100644 --- a/src/MoonlinkManager.mjs +++ b/src/MoonlinkManager.mjs @@ -224,7 +224,9 @@ export class MoonlinkManager extends EventEmitter { } catch (_) {} }; - this._rawWsErrorHandler = (err) => { + this._rawWsErrorHandler = (errOrEvent) => { + if (typeof errOrEvent?.preventDefault === "function") errOrEvent.preventDefault(); + const err = errOrEvent?.error ?? errOrEvent?.message ?? errOrEvent; const now = Date.now(); if (now - _wsErrorCooldown.lastLogged < _wsErrorCooldown.COOLDOWN_MS) return; _wsErrorCooldown.lastLogged = now; diff --git a/src/TrackOptionsManager.mjs b/src/TrackOptionsManager.mjs index c954d8b..6cb00b6 100644 --- a/src/TrackOptionsManager.mjs +++ b/src/TrackOptionsManager.mjs @@ -140,7 +140,12 @@ export class TrackOptionsManager { const safeAlias = TrackOptionsManager.sanitizeAlias(alias); const cacheKey = `${userId}:${identifier}:${safeAlias}`; - if (this._cache.has(cacheKey)) return this._cache.get(cacheKey); + if (this._cache.has(cacheKey)) { + const cached = this._cache.get(cacheKey); + this._cache.delete(cacheKey); + this._cache.set(cacheKey, cached); + return cached; + } try { const rows = await this._query( diff --git a/src/Utils.mjs b/src/Utils.mjs index 2f23ab0..2c3bff9 100644 --- a/src/Utils.mjs +++ b/src/Utils.mjs @@ -98,10 +98,12 @@ export class Utils { * @returns {T[][]} Array of chunks */ static chunk(array, size) { - if (!Array.isArray(array) || size < 1) return []; + if (!Array.isArray(array)) return []; + const chunkSize = Math.max(1, Math.floor(size)); + if (chunkSize < 1) return []; const chunks = []; - for (let i = 0; i < array.length; i += size) { - chunks.push(array.slice(i, i + size)); + for (let i = 0; i < array.length; i += chunkSize) { + chunks.push(array.slice(i, i + chunkSize)); } return chunks; } @@ -140,15 +142,33 @@ export class Utils { static cleanTitle(title) { if (!title || typeof title !== "string") return "Unknown"; - return title - .replace(/\s*[\(\[][^\)\]]*(?:feat|ft|featuring|remix|edit|version|prod|official|audio|video|lyrics|visualizer)[^\)\]]*[\)\]]/gi, "") + let cleaned = title; + for (let pass = 0; pass < 3; pass++) { + const prev = cleaned; + cleaned = cleaned + .replace(/\s*\([^()]*\)/g, (match) => { + const inner = match.toLowerCase(); + if (/(?:feat|ft|featuring|remix|edit|version|prod|official|audio|video|lyrics|visualizer|deluxe|explicit|clean|radio|instrumental|acoustic|extended|mono|stereo|remaster)/.test(inner)) { + return ""; + } + return match; + }) + .replace(/\s*\[[^\[\]]*\]/g, (match) => { + const inner = match.toLowerCase(); + if (/(?:feat|ft|featuring|remix|edit|version|prod|official|audio|video|lyrics|visualizer|deluxe|explicit|clean|radio|instrumental|acoustic|extended|remaster)/.test(inner)) { + return ""; + } + return match; + }); + if (cleaned === prev) break; + } + + return cleaned .replace(/\s*-\s*(?:feat|ft|featuring)\.?.*/gi, "") .replace(/\s*\|.*$/g, "") .replace(/\s*【.*?】/g, "") - .replace(/\s*\[.*?\]/g, "") - .replace(/\s*\(.*?\)/g, "") .replace(/\s{2,}/g, " ") - .trim(); + .trim() || "Unknown"; } /** @@ -178,7 +198,8 @@ export class Utils { .replace(/\*/g, "\\*") .replace(/_/g, "\\_") .replace(/~/g, "\\~") - .replace(/\|/g, "\\|"); + .replace(/\|/g, "\\|") + .replace(/>/g, "\\>"); } /** @@ -188,7 +209,7 @@ export class Utils { */ static formatNumber(num) { if (num === null || num === undefined || isNaN(num)) return "0"; - return num.toLocaleString(); + return num.toLocaleString("en-US"); } /** @@ -239,12 +260,14 @@ export class Utils { } /** - * Check if a string represents a finite number - * @param {string} str + * Check if a value represents a finite number + * @param {string|number} str * @returns {boolean} */ static isNumber(str) { if (str === null || str === undefined || str === "") return false; + if (typeof str === "number") return !isNaN(str) && isFinite(str); + if (typeof str !== "string") return false; return !isNaN(str) && isFinite(str); } diff --git a/src/constants/FluxerRevoice.mjs b/src/constants/FluxerRevoice.mjs index d979e47..edb2702 100644 --- a/src/constants/FluxerRevoice.mjs +++ b/src/constants/FluxerRevoice.mjs @@ -523,6 +523,16 @@ export class FluxerRevoice extends EventEmitter { nativeConnection, }); + room.on(RoomEvent.ConnectionStateChanged, (cs) => { + if (cs === ConnectionState.CONN_RECONNECTING || cs === 2) { + logger.player(`[FluxerRevoice] Room reconnecting for channel ${channelId}`); + } else if (cs === ConnectionState.CONN_CONNECTED || cs === 1) { + if (connection._destroyed) return; + connection._connected = true; + logger.player(`[FluxerRevoice] Room (re)connected for channel ${channelId}`); + } + }); + room.on(RoomEvent.Disconnected, (reason) => { const isIntentional = this._intentionalDisconnects.has(String(channelId)); const reasonLabel = isIntentional ? "intentional" : (reason ?? "unexpected"); diff --git a/src/constants/Locale.mjs b/src/constants/Locale.mjs index f9e06e4..217b2ae 100644 --- a/src/constants/Locale.mjs +++ b/src/constants/Locale.mjs @@ -25,6 +25,8 @@ export class Locale { this.defaultLocale = "en"; /** settingsMgr reference — set after construction via bind() */ this.settingsMgr = null; + /** Maximum guild locale cache size */ + this._maxResolvedCache = 5000; } /** @@ -108,6 +110,12 @@ export class Locale { const data = this.locales.get(code) ?? this.locales.get(this.defaultLocale) ?? {}; this._resolved.set(guildId, data); + + while (this._resolved.size > this._maxResolvedCache) { + const oldestKey = this._resolved.keys().next().value; + this._resolved.delete(oldestKey); + } + return data; } diff --git a/src/constants/Logger.mjs b/src/constants/Logger.mjs index dafa715..6b2a68b 100644 --- a/src/constants/Logger.mjs +++ b/src/constants/Logger.mjs @@ -2,11 +2,14 @@ * Logger — configurable console output for Fluxer. * * Categories (all under config.logging): - * enabled — master switch; false silences everything except errors + * enabled — master switch; false silences everything except errors and warns + * warn — when enabled=false, set true to keep showing warnings (default: hidden) * player — voice connect/disconnect, stream start, volume restore * inactivity — alone-check, inactivity timer, human detection + * aloneCheck — periodic alone-check scan logs (separate from inactivity) * voice247 — 24/7 rejoin, auto-save channel, intentional leave skip * voiceState — raw VOICE_STATE_UPDATE events (human join/leave detection) + * voice — checkVoiceChannels debug logs * mediaplayer — MediaPlayer publish, LiveKit room state, connection recovery * commands — command load, module load, error IDs * guild — GuildCreate / GuildDelete lifecycle @@ -52,7 +55,8 @@ export const logger = { console.error(`[${ts()}] ${tag}`, ...args); }, warn(tag, ...args) { - if (_config?.enabled === false) return; + if (!_config) { console.warn(`[${ts()}] ${tag}`, ...args); return; } + if (_config.enabled === false && _config.warn !== true) return; console.warn(`[${ts()}] ${tag}`, ...args); }, info(tag, ...args) { @@ -71,7 +75,7 @@ export const logger = { settings(...args) { if (isEnabled("settings")) console.log(`[${ts()}]`, ...args); }, worker(...args) { if (isEnabled("worker")) console.log(`[${ts()}]`, ...args); }, moonlink(...args) { if (isEnabled("moonlink")) console.log(`[${ts()}]`, ...args); }, - aloneCheck(...args) { if (isEnabled("inactivity")) console.log(`[${ts()}]`, ...args); }, + aloneCheck(...args) { if (isEnabled("aloneCheck")) console.log(`[${ts()}]`, ...args); }, voice(...args) { if (isEnabled("voice")) console.log(`[${ts()}]`, ...args); }, dashboard(...args) { if (isEnabled("dashboard")) console.log(`[${ts()}]`, ...args); }, redis(...args) { if (isEnabled("redis")) console.log(`[${ts()}]`, ...args); }, diff --git a/src/constants/VoiceStateCache.mjs b/src/constants/VoiceStateCache.mjs index 0713cae..7fd5585 100644 --- a/src/constants/VoiceStateCache.mjs +++ b/src/constants/VoiceStateCache.mjs @@ -96,26 +96,31 @@ export class VoiceStateCache { locations.delete(uKey); locations.set(uKey, { channelId: cleanChannel, guildId: cleanGuild, userId: cleanUser }); + const lruIdx = lruKeys.indexOf(uKey); + if (lruIdx !== -1) lruKeys.splice(lruIdx, 1); + lruKeys.push(uKey); + while (locations.size > maxEntries) { - const evictKey = locations.keys().next().value; - if (evictKey === uKey) { - const evictVal = locations.get(evictKey); - locations.delete(evictKey); - locations.set(evictKey, evictVal); - continue; - } - 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); + let evicted = false; + for (let i = 0; i < lruKeys.length; i++) { + const evictKey = lruKeys[i]; + if (evictKey === uKey) continue; + + const evictEntry = locations.get(evictKey); + if (evictEntry) { + const evictCKey = VoiceStateCache.channelKey(evictEntry.guildId, evictEntry.channelId); + const evictSet = channelIdx.get(evictCKey); + if (evictSet) { + evictSet.delete(evictEntry.userId); + if (evictSet.size === 0) channelIdx.delete(evictCKey); + } + locations.delete(evictKey); } - locations.delete(evictKey); + lruKeys.splice(i, 1); + evicted = true; + break; } - const lruIdx = lruKeys.indexOf(evictKey); - if (lruIdx !== -1) lruKeys.splice(lruIdx, 1); + if (!evicted) break; } } else { locations.delete(uKey); diff --git a/src/constants/audio/StreamMerger.mjs b/src/constants/audio/StreamMerger.mjs index 9afe41b..371bf7e 100644 --- a/src/constants/audio/StreamMerger.mjs +++ b/src/constants/audio/StreamMerger.mjs @@ -69,8 +69,11 @@ class StreamMerger extends Transform { open.pipes.push(pipeNumber); open.available = true; const idx = open.children.findIndex(c => c === node); - if (idx === -1) throw new Error("Impossible case detected. Damaged node structure."); - open.children.splice(idx, 1); + if (idx === -1) { + logger.warn("[StreamMerger] Damaged node structure — child not found in parent on exit."); + } else { + open.children.splice(idx, 1); + } }); } } diff --git a/src/constants/audio/Tuna.mjs b/src/constants/audio/Tuna.mjs index 2cd1d45..b97601c 100644 --- a/src/constants/audio/Tuna.mjs +++ b/src/constants/audio/Tuna.mjs @@ -43,7 +43,7 @@ class Tuna { results.items = results.items.map(s => { s.download = function() { return new Promise((resolve, reject) => { - const req = https.get(this.oggPath, (r) => { resolve(r); }); + const req = https.get(this.oggPath, { maxRedirects: 20 }, (r) => { resolve(r); }); req.on("error", (err) => { reject(err); }); req.setTimeout(15_000, () => { req.destroy(); reject(new Error("Tuna download timeout")); }); }); @@ -57,7 +57,7 @@ class Tuna { return this.get("/v1/sounds/" + id).then(sound => { sound.download = function() { return new Promise((resolve, reject) => { - const req = https.get(this.oggPath, (result) => { resolve(result); }); + const req = https.get(this.oggPath, { maxRedirects: 20 }, (result) => { resolve(result); }); req.on("error", (err) => { reject(err); }); req.setTimeout(15_000, () => { req.destroy(); reject(new Error("Tuna download timeout")); }); }); diff --git a/src/dashboard/RedisHandler.mjs b/src/dashboard/RedisHandler.mjs index efb17f0..de3ac00 100644 --- a/src/dashboard/RedisHandler.mjs +++ b/src/dashboard/RedisHandler.mjs @@ -96,7 +96,7 @@ export class RedisHandler { logger.warn("[Redis/Subscriber] Info handler error:", e.message); } }); - setInterval(() => { + this._pingInterval = setInterval(() => { this.send(this.platform + ":ping", "" + Date.now()); }, 10000); } catch (e) { @@ -161,6 +161,8 @@ export class RedisHandler { */ async destroy() { this._destroyed = true; + if (this._pingInterval) { clearInterval(this._pingInterval); this._pingInterval = null; } + if (this._readyTimer) { clearTimeout(this._readyTimer); this._readyTimer = null; } try { await this.subscriber?.quit(); } catch (_) {} try { await this.client?.quit(); } catch (_) {} logger.redis("[Redis] Connections closed gracefully");