From 6fa8f3b54044876399e7d05530d924513f688fe1 Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Sat, 16 May 2026 20:30:56 +0300 Subject: [PATCH] lots of changes --- commands/join.mjs | 9 ++- commands/player.mjs | 8 +-- commands/radio.mjs | 5 +- commands/reload.mjs | 22 ++++--- commands/remove.mjs | 2 +- commands/skip.mjs | 2 +- index.mjs | 63 +++++++++++++----- settings/Settings.mjs | 34 ++++++---- settings/migrate.mjs | 21 ++++-- src/GatewayHandler.mjs | 20 +++++- src/Player.mjs | 5 +- src/PlayerManager.mjs | 11 +++- src/Settings.mjs | 34 ++++++---- src/Utils.mjs | 6 +- src/constants/FluxerRevoice.mjs | 105 +++++++++++++++++------------- src/constants/VoiceStateCache.mjs | 31 +++++++-- src/dashboard/Dashboard.mjs | 33 ++++++---- src/dashboard/DatabaseManager.mjs | 6 ++ src/probe.mjs | 19 ++++++ src/worker.mjs | 4 +- 20 files changed, 296 insertions(+), 144 deletions(-) diff --git a/commands/join.mjs b/commands/join.mjs index fb09017..f2cc625 100644 --- a/commands/join.mjs +++ b/commands/join.mjs @@ -94,8 +94,7 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) { })(); const embed = new EmbedBuilder().setColor(getGlobalColor()) .setDescription(this.t(message, "responses.join.autoLeaveInactive247", { channel: activeChannelId, prefix })); - message.channel.send({ embeds: [embed] }); - + message.channel.send({ embeds: [embed] }).catch(() => {}); setTimeout(async () => { try { if (typeof this._spawnPlayer === "function") { @@ -110,9 +109,9 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) { const prefix = (() => { try { return this._commands?.getPrefix?.(guildId) ?? "%"; } catch (_) { return "%"; } })(); - const embed = new EmbedBuilder().setColor(getGlobalColor()) + const embed2 = new EmbedBuilder().setColor(getGlobalColor()) .setDescription(this.t(message, "responses.join.autoLeaveInactive", { channel: activeChannelId })); - message.channel.send({ embeds: [embed] }); + message.channel.send({ embeds: [embed2] }).catch(() => {}); } }); @@ -162,7 +161,7 @@ export const command = new CommandBuilder() .setRequired(false) ); -export function run(message, data) { +export async function run(message, data) { // Check if a channel argument was provided (mention like <#123456>, bare ID, or name) const rawArg = data?.get?.("channel")?.value?.trim?.() ?? null; diff --git a/commands/player.mjs b/commands/player.mjs index 0a6634e..2b431d3 100644 --- a/commands/player.mjs +++ b/commands/player.mjs @@ -48,7 +48,7 @@ export async function run(msg) { const player = await this.getPlayer(msg, false, false, false); if (!player) return; - const timeout = this.config?.timers?.playerSessionTimeout ?? this.config.playerAFKTimeout ?? 300000; + const timeout = Math.max(60_000, this.config?.timers?.playerSessionTimeout ?? this.config.playerAFKTimeout ?? 300000); const controlsLayout = [ [CONTROLS.prev, CONTROLS.play, CONTROLS.pause, CONTROLS.stop, CONTROLS.next], [CONTROLS.loop, CONTROLS.shuffle, CONTROLS.volDown, CONTROLS.volUp, CONTROLS.lyrics], @@ -91,7 +91,7 @@ export async function run(msg) { progressBar = PROGRESS.start + PROGRESS.empty.repeat(20) + PROGRESS.end; } - const volPercent = Math.round((player.preferredVolume || 1) * 100); + const volPercent = Math.round((player.preferredVolume ?? 1) * 100); const volBars = Math.ceil(volPercent / 10); const volumeBar = "█".repeat(volBars) + "░".repeat(10 - volBars); @@ -349,13 +349,13 @@ export async function run(msg) { break; case "voldown": { - const newVolDown = Utils.clamp((player.preferredVolume || 1) - 0.1, 0, 1); + const newVolDown = Utils.clamp((player.preferredVolume ?? 1) - 0.1, 0, 1); reply = player.setVolume(newVolDown); break; } case "volup": { - const newVolUp = Utils.clamp((player.preferredVolume || 1) + 0.1, 0, 1); + const newVolUp = Utils.clamp((player.preferredVolume ?? 1) + 0.1, 0, 1); reply = player.setVolume(newVolUp); break; } diff --git a/commands/radio.mjs b/commands/radio.mjs index 2e62d11..2c27512 100644 --- a/commands/radio.mjs +++ b/commands/radio.mjs @@ -17,7 +17,7 @@ export const command = function() { if (!this.config.radio?.length) return null; return new CommandBuilder() .setName("radio") - .setDescription("Play a radio station. Use `%radio list` to browse all stations.", "commands.radio") + .setDescription("Play a radio station. Use `${prefix}radio list` to browse all stations.", "commands.radio") .addAliases("r") .setCategory("music") .addTextOption(o => @@ -137,13 +137,14 @@ async function playStation(ctx, msg, radio, editTarget = null) { if (current?.type === "radio" || hasRadioQueued) await p.switchRadio(radio); else p.playRadio(radio); + const prefix = (() => { try { return ctx.handler?.getPrefix?.(msg?.channel?.channel?.guildId ?? msg?.message?.guildId) ?? "%"; } catch (_) { return "%"; } })(); const embed = new EmbedBuilder() .setColor(getGlobalColor()) .setTitle(`📻 ${radio.detailedName}`) .setDescription( `**[${radio.detailedName}](${radio.author.url})**\n\n` + `${radio.description}\n\n` + - `_Use \`%skip\` to stop the radio, or \`%radio list\` to switch stations._` + `_Use \`${prefix}skip\` to stop the radio, or \`${prefix}radio list\` to switch stations._` ) ; diff --git a/commands/reload.mjs b/commands/reload.mjs index a09c661..411fbc4 100644 --- a/commands/reload.mjs +++ b/commands/reload.mjs @@ -152,9 +152,10 @@ export async function run(msg, data) { // Batch keywords if (target === "commands") { - const results = await Promise.all( - this.handler.commands.map(c => reloadCommand(this, msg, c.name)) - ); + const results = []; + for (const c of [...this.handler.commands]) { + results.push(await reloadCommand(this, msg, c.name)); + } return showResults(msg, results, "Commands"); } @@ -173,11 +174,16 @@ export async function run(msg, data) { } if (target === "all") { - const results = await Promise.all([ - ...this.handler.commands.map(c => reloadCommand(this, msg, c.name)), - ...allModuleFiles("src").map(m => reloadModule(this, msg, m.file, m.label)), - ...allModuleFiles("audio").map(m => reloadModule(this, msg, m.file, m.label)), - ]); + const results = []; + for (const c of [...this.handler.commands]) { + results.push(await reloadCommand(this, msg, c.name)); + } + for (const m of allModuleFiles("src")) { + results.push(await reloadModule(this, msg, m.file, m.label)); + } + for (const m of allModuleFiles("audio")) { + results.push(await reloadModule(this, msg, m.file, m.label)); + } return showResults(msg, results, "Everything"); } diff --git a/commands/remove.mjs b/commands/remove.mjs index 7e247e8..3eb5ab0 100644 --- a/commands/remove.mjs +++ b/commands/remove.mjs @@ -13,7 +13,7 @@ export async function run(message, data) { const p = await this.getPlayer(message, false, false, false); if (!p) return; const index = data.get("index")?.value; - if (index == null) return message.reply("Please provide a valid queue position."); + if (index == null || index < 1) return message.replyEmbed("Queue position must be 1 or greater."); const res = p.remove(index - 1); message.replyEmbed(res); } diff --git a/commands/skip.mjs b/commands/skip.mjs index 8af705a..705f92f 100644 --- a/commands/skip.mjs +++ b/commands/skip.mjs @@ -17,7 +17,7 @@ export async function run(message) { const skippedLink = current ? (current.spotifyUrl || current.url || "") : ""; const err = p.skip(); - if (err && err.includes("nothing playing")) { + if (err) { const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(err); return message.reply({ embeds: [embed] }); } diff --git a/index.mjs b/index.mjs index 24e14b4..5655167 100644 --- a/index.mjs +++ b/index.mjs @@ -17,6 +17,31 @@ import { VoiceStateCache } from "./src/constants/VoiceStateCache.mjs"; import { GatewayHandler } from "./src/GatewayHandler.mjs"; import { LastFmManager } from "./src/LastFmManager.mjs"; +/** + * Create a backward-compatible "bot view" wrapper around VoiceStateCache. + * + * The old code used separate Maps for observedVoiceUsers and observedVoiceBots. + * VoiceStateCache merged both into one object, but the default iterator/size + * only exposes human users. This wrapper provides the Map-like interface that + * iterates BOT entries instead, so code that does `for (const [k, v] of observedVoiceBots)` + * still gets bot data, not human data. + */ +function createBotView(voiceCache) { + return { + get size() { return voiceCache.botLocations.size; }, + get(key) { return voiceCache.botLocations.get(key); }, + set(key, val) { voiceCache.setBotUser(key, val); }, + has(key) { return voiceCache.botLocations.has(key); }, + delete(key) { voiceCache.deleteBotUser(key); }, + forEach(fn) { for (const [k, v] of voiceCache.iterateBotUsers()) fn(v, k, this); }, + *[Symbol.iterator]() { yield* voiceCache.iterateBotUsers(); }, + *entries() { yield* voiceCache.iterateBotUsers(); }, + *keys() { for (const [k] of voiceCache.iterateBotUsers()) yield k; }, + *values() { for (const [, v] of voiceCache.iterateBotUsers()) yield v; }, + get observedVoiceBotsSize() { return voiceCache.botLocations.size; }, + }; +} + export class Remix { constructor() { // ── Config ─────────────────────────────────────────────────────────────── @@ -166,10 +191,14 @@ export class Remix { 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; + // observedVoiceUsers iterates HUMAN users only (backward compat). + // observedVoiceBots iterates BOT users only (backward compat). + // Previously both pointed to the same VoiceStateCache, which caused + // observedVoiceBots to return human users instead of bots. + // We create thin wrapper objects that delegate to the correct + // internal indexes while preserving the Map-like interface. + this.observedVoiceUsers = this.voiceCache; // default iterator = human users + this.observedVoiceBots = createBotView(this.voiceCache); // ── Caches ─────────────────────────────────────────────────────────────── // _announcementChannelCache: TTL-based (5 min), auto-evicts stale entries @@ -324,13 +353,14 @@ export class Remix { const ALONE_CHECK_INTERVAL = this.T.aloneCheckInterval; setInterval(() => { for (const [mapKey, player] of this.players.playerMap) { + let channelId; try { const guildId = player._guildId; if (!guildId) continue; if (player._isJoining) continue; - const channelId = player._channelId ?? mapKey; + channelId = player._channelId ?? mapKey; const cleanChanId = String(channelId).replace(/\D/g, ""); if (!cleanChanId) continue; @@ -517,11 +547,22 @@ export class Remix { return null; }; + // ── Git commit hash ─────────────────────────────────────────────────────── + // Must be computed BEFORE comLink is built so the hash is available. + const __dirname = import.meta.dirname; + try { + this.comHash = childProcess.execSync("git rev-parse --short HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim(); + this.comHashLong = childProcess.execSync("git rev-parse HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim(); + } catch { + logger.warn("[Git] comhash error"); + this.comHash = "Newest"; + this.comHashLong = null; + } + this.comLink = "https://github.com/remix-bot/fluxer/commit/" + (this.comHashLong ?? ""); // ── Commands ────────────────────────────────────────────────────────────── const loader = new CommandLoader(commands, this); - const __dirname = import.meta.dirname; const dir = path.join(__dirname, "commands"); logger.commands("Started loading commands."); loader.loadFromDir(dir) @@ -556,16 +597,6 @@ export class Remix { logger.commands(`Modules loaded (${succeeded} succeeded, ${failed} failed).`); }); - // ── Git commit hash ─────────────────────────────────────────────────────── - try { - this.comHash = childProcess.execSync("git rev-parse --short HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim(); - this.comHashLong = childProcess.execSync("git rev-parse HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim(); - } catch { - logger.warn("[Git] comhash error"); - this.comHash = "Newest"; - this.comHashLong = null; - } - // ── Login ───────────────────────────────────────────────────────────────── client.login(config.token); } diff --git a/settings/Settings.mjs b/settings/Settings.mjs index d0e2d41..37ee8b6 100644 --- a/settings/Settings.mjs +++ b/settings/Settings.mjs @@ -56,7 +56,7 @@ export class MySqlSettingsManager extends SettingsManager { logger.error("[DB] MySQL pool error:", err.code ?? err.message); }); if (defaultsPath) this.loadDefaultsSync(defaultsPath); - this.load(); + this.load().catch(err => logger.error("[Settings] Initial load failed:", err?.message ?? err)); } query(query) { return new Promise(res => { @@ -73,13 +73,17 @@ export class MySqlSettingsManager extends SettingsManager { } this._loadAttempts = 0; res.results.forEach((r) => { - const server = new ServerSettings(r.id, this); - // mysql2 may return JSON columns as already-parsed objects; - // only JSON.parse when the value is still a string. - const parsed = (typeof r.data === "string") ? JSON.parse(r.data) : r.data; - server.deserialize(parsed); - server.checkDefaults(this.defaults); - this.guilds.set(server.id, server); + try { + const server = new ServerSettings(r.id, this); + // mysql2 may return JSON columns as already-parsed objects; + // only JSON.parse when the value is still a string. + const parsed = (typeof r.data === "string") ? JSON.parse(r.data) : r.data; + server.deserialize(parsed); + server.checkDefaults(this.defaults); + this.guilds.set(server.id, server); + } catch (e) { + logger.error("[Settings] Failed to parse settings for server", r.id, ":", e.message); + } }); this.emit("ready"); } @@ -112,10 +116,16 @@ export class MySqlSettingsManager extends SettingsManager { if (r.error) logger.error("[Settings] remoteSave error:", r.error); } loadDefaultsSync(filePath) { - const d = fs.readFileSync(filePath, "utf8"); - const parsed = JSON.parse(d); - this.descriptions = parsed.descriptions; - this.defaults = parsed.values; + try { + const d = fs.readFileSync(filePath, "utf8"); + const parsed = JSON.parse(d); + this.descriptions = parsed.descriptions; + this.defaults = parsed.values; + } catch (e) { + logger.error("[Settings] Failed to load defaults from", filePath, ":", e.message); + this.descriptions = {}; + this.defaults = {}; + } } async saveAsync() { await Promise.allSettled([...this.guilds.values()].map(v => this.remoteSave(v))); diff --git a/settings/migrate.mjs b/settings/migrate.mjs index ab7ef3e..fd0ae6f 100644 --- a/settings/migrate.mjs +++ b/settings/migrate.mjs @@ -10,13 +10,22 @@ const config = JSON.parse(fs.readFileSync(new URL("../config.json", import.meta. const sm = new RemoteSettingsManager(config.mysql, "./storage/defaults.json"); const rsm = new RemoteSettingsManager(config.mysql, "./storage/defaults.json"); -// Capture entries after the source manager has loaded from DB. -let servers = []; -sm.on("ready", () => { - servers = sm.guilds.entries(); -}); +// Ensure source manager is fully loaded BEFORE starting migration. +// Previously, rsm's "ready" could fire before sm finished loading, +// resulting in an empty servers array and a silent no-op migration. +let migrationStarted = false; + +sm.on("ready", async () => { + if (migrationStarted) return; + migrationStarted = true; + + const servers = [...sm.guilds.entries()]; + + // Wait for the destination manager to be ready too + if (!rsm.guilds.size) { + await new Promise(resolve => rsm.on("ready", resolve)); + } -rsm.on("ready", async () => { for (const [id, s] of servers) { logger.settings("[migrate] Processing server:", id); if (rsm.hasServer(id)) { diff --git a/src/GatewayHandler.mjs b/src/GatewayHandler.mjs index 1144739..d99a306 100644 --- a/src/GatewayHandler.mjs +++ b/src/GatewayHandler.mjs @@ -768,7 +768,25 @@ export class GatewayHandler { } } if (nextKey && this._prevVoiceState.size >= 10_000 && !this._prevVoiceState.has(nextKey)) { - this._prevVoiceState.delete(this._prevVoiceState.keys().next().value); + const evictKey = this._prevVoiceState.keys().next().value; + const evictEntry = this._prevVoiceState.get(evictKey); + this._prevVoiceState.delete(evictKey); + // When evicting a stale prevVoiceState entry, also clean up the + // corresponding VoiceStateCache entry so it doesn't hold a stale + // channel mapping that could cause incorrect "channel move" detection + // on the next voice state update for that user. + if (evictEntry) { + const evictGuildId = evictEntry.guildId; + const evictUserId = evictKey.split(":")[1]; + if (evictGuildId && evictUserId) { + const currentLoc = remix.voiceCache.getUserLocation(evictGuildId, evictUserId); + // Only remove from voiceCache if the user is still in the evicted + // channel — if they've moved since, the cache is already correct. + if (currentLoc && currentLoc.channelId === evictEntry.channelId) { + remix.voiceCache.updateUser({ guildId: evictGuildId, userId: evictUserId, channelId: null, isBot: false }); + } + } + } } if (nextKey) this._prevVoiceState.set(nextKey, { channelId, guildId: guildId ?? prev?.guildId }); } else { diff --git a/src/Player.mjs b/src/Player.mjs index 22fcf7a..7f9389e 100644 --- a/src/Player.mjs +++ b/src/Player.mjs @@ -709,7 +709,10 @@ export default class Player extends EventEmitter { for (let attempt = 1; attempt <= MAX_PUBLISH_RETRIES; attempt++) { try { this._mediaPlayer = new MediaPlayer(); - this._mediaPlayer.setMaxListeners(0); + // Set a reasonable max listeners cap instead of 0 (unlimited). + // Unlimited masks real event emitter leaks; 20 is enough for + // the finish/error/playStream listeners plus dashboard forwarding. + this._mediaPlayer.setMaxListeners(20); await this._mediaPlayer.publishToRoom(room); logger.mediaplayer("[Player] MediaPlayer published successfully"); return true; diff --git a/src/PlayerManager.mjs b/src/PlayerManager.mjs index 55b0431..592f63b 100644 --- a/src/PlayerManager.mjs +++ b/src/PlayerManager.mjs @@ -810,9 +810,16 @@ export class PlayerManager { const pendingScrobble = this._pendingScrobbleTimers.get(activeChannelId); if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this._pendingScrobbleTimers.delete(activeChannelId); } if (activeChannelId !== cleanChannelId) this.playerMap.delete(cleanChannelId); - await msg.reply(mkEmbed(this._t(msg, "responses._common.successfullyLeft"))); - await player.leave(); + // Leave the voice channel BEFORE confirming to the user. + // Previously, the reply was sent first, which meant the user saw "successfully left" + // even if player.leave() subsequently threw an error. + try { + await player.leave(); + } catch (e) { + logger.warn("[PlayerManager] leave() error (non-fatal):", e.message); + } player.destroy(); + await msg.reply(mkEmbed(this._t(msg, "responses._common.successfullyLeft"))); } // ═══════════════════════════════════════════════════════════════════════════ diff --git a/src/Settings.mjs b/src/Settings.mjs index a8de513..69fdf36 100644 --- a/src/Settings.mjs +++ b/src/Settings.mjs @@ -55,7 +55,7 @@ export class RemoteSettingsManager extends EventEmitter { logger.error("[DB] MySQL pool error:", err.code ?? err.message); }); if (defaultsPath) this.loadDefaultsSync(defaultsPath); - this.load(); + this.load().catch(err => logger.error("[Settings] Initial load failed:", err?.message ?? err)); } query(q) { @@ -75,13 +75,17 @@ export class RemoteSettingsManager extends EventEmitter { } this._loadAttempts = 0; res.results.forEach((r) => { - const server = new ServerSettings(r.id, this); - // mysql2 may return JSON columns as already-parsed objects; - // only JSON.parse when the value is still a string. - const parsed = (typeof r.data === "string") ? JSON.parse(r.data) : r.data; - server.deserialize(parsed); - server.checkDefaults(this.defaults); - this.guilds.set(server.id, server); + try { + const server = new ServerSettings(r.id, this); + // mysql2 may return JSON columns as already-parsed objects; + // only JSON.parse when the value is still a string. + const parsed = (typeof r.data === "string") ? JSON.parse(r.data) : r.data; + server.deserialize(parsed); + server.checkDefaults(this.defaults); + this.guilds.set(server.id, server); + } catch (e) { + logger.error("[Settings] Failed to parse settings for server", r.id, ":", e.message); + } }); this.emit("ready"); } @@ -113,10 +117,16 @@ export class RemoteSettingsManager extends EventEmitter { } loadDefaultsSync(filePath) { - const d = fs.readFileSync(filePath, "utf8"); - const parsed = JSON.parse(d); - this.descriptions = parsed.descriptions; - this.defaults = parsed.values; + try { + const d = fs.readFileSync(filePath, "utf8"); + const parsed = JSON.parse(d); + this.descriptions = parsed.descriptions; + this.defaults = parsed.values; + } catch (e) { + logger.error("[Settings] Failed to load defaults from", filePath, ":", e.message); + this.descriptions = {}; + this.defaults = {}; + } } async saveAsync() { diff --git a/src/Utils.mjs b/src/Utils.mjs index 2f4d76c..aa1c4f1 100644 --- a/src/Utils.mjs +++ b/src/Utils.mjs @@ -210,8 +210,8 @@ export class Utils { * @returns {string} Human readable size */ static formatBytes(bytes, decimals = 2) { - if (!bytes || bytes === 0) return "0 Bytes"; - if (bytes < 0) return "Unknown"; + if (bytes === 0) return "0 Bytes"; + if (!bytes || bytes < 0 || !isFinite(bytes)) return "Unknown"; const k = 1024; const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB"]; @@ -453,7 +453,7 @@ export class Utils { progress = this.clamp(current, 0, 1); } - const position = Math.floor(progress * length); + const position = Math.min(Math.floor(progress * length), length - 1); let bar = ""; for (let i = 0; i < length; i++) { diff --git a/src/constants/FluxerRevoice.mjs b/src/constants/FluxerRevoice.mjs index 90357f9..1ab2472 100644 --- a/src/constants/FluxerRevoice.mjs +++ b/src/constants/FluxerRevoice.mjs @@ -32,56 +32,67 @@ import { joinVoiceChannel, getVoiceManager } from "@fluxerjs/voice"; import { logger } from "./Logger.mjs"; { - 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 - } - _originalConsoleLog.apply(console, args); - }; + // ── 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; - // ── 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; - } + 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 } - } catch (_) { - // Not valid JSON — pass through } - } - return _originalStdoutWrite(chunk, encoding, callback); - }; + // 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 + } + _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); + }; + } } // ConnectionState enum values for reference: diff --git a/src/constants/VoiceStateCache.mjs b/src/constants/VoiceStateCache.mjs index 3b09ad1..e6ee3c1 100644 --- a/src/constants/VoiceStateCache.mjs +++ b/src/constants/VoiceStateCache.mjs @@ -105,15 +105,29 @@ export class VoiceStateCache { // ── 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); + // ── 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 ────────────────────────────────────────────── - while (lruKeys.length > maxEntries) { - const evictKey = lruKeys.pop(); - if (evictKey === uKey) continue; // don't evict the entry we just added + // 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); + continue; + } const evicted = locations.get(evictKey); if (evicted) { const evictCKey = VoiceStateCache.channelKey(evicted.guildId, evicted.channelId); @@ -124,6 +138,9 @@ 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 ───────────────────── diff --git a/src/dashboard/Dashboard.mjs b/src/dashboard/Dashboard.mjs index 7d6830c..a234ef9 100644 --- a/src/dashboard/Dashboard.mjs +++ b/src/dashboard/Dashboard.mjs @@ -53,17 +53,19 @@ export class Dashboard { 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); - 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); - return ch ? ch.permissionsFor?.(member)?.has?.("ViewChannel") ?? true : true; - }); + if (!member) { + // Non-member should not see any channels — return error instead of leaking all + return { error: "You are not a member of this server" }; } + server.channels = server.channels.filter(c => { + const ch = channels.find(cl => c.id === cl.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); + return ch ? ch.permissionsFor?.(member)?.has?.("ViewChannel") ?? true : true; + }); return server; } catch (e) { const id = Utils.uid(); @@ -236,7 +238,7 @@ export class Dashboard { if (authErr) return { error: authErr }; const vol = Number(params.data.volume); if (isNaN(vol) || vol < 0 || vol > 150) return { error: "Volume must be between 0 and 150" }; - const msg = player.setVolume(vol); + const msg = player.setVolume(vol / 100); return { message: msg }; } @@ -310,7 +312,10 @@ export class Dashboard { } case "leave": { - const player = this._getPlayerById(params.data.channel); + // Support both params.data.channel and params.data.player for + // backward compatibility with different backend versions. + const playerId = params.data.channel ?? params.data.player; + const player = this._getPlayerById(playerId); if (!player) return { error: "Player not found" }; const authErr = await this._authorizeUserInGuild(user, player._guildId); if (authErr) return { error: authErr }; @@ -324,9 +329,9 @@ export class Dashboard { if (player._dashboardUsers && player._dashboardUsers.length > 0) { // Publish a leave event for this user on the player channel try { - const pubChannel = this.remix.redis?.publisher ?? this.remix.redis; + const pubChannel = this.remix.dashboard?.redis?.client ?? this.remix.redis?.client; if (pubChannel && typeof pubChannel.publish === "function") { - pubChannel.publish("fluxer:player_" + params.data.channel, JSON.stringify({ + pubChannel.publish("fluxer:player_" + playerId, JSON.stringify({ type: "leave", data: String(user.id) })); diff --git a/src/dashboard/DatabaseManager.mjs b/src/dashboard/DatabaseManager.mjs index 52e7f24..43c544e 100644 --- a/src/dashboard/DatabaseManager.mjs +++ b/src/dashboard/DatabaseManager.mjs @@ -1,5 +1,6 @@ import { compare, genSalt, hash } from "bcryptjs"; import { createPool } from "mysql2/promise"; +import { logger } from "../constants/Logger.mjs"; /** * DatabaseManager — MySQL pool for dashboard login codes and API tokens. @@ -14,6 +15,11 @@ export class DatabaseManager { connectionLimit: 15, ...config, }); + // Without this listener, unhandled pool-level errors (connection drops, + // timeouts) fire an unhandled 'error' event which crashes the process. + this.db.on("error", (err) => { + logger.error("[DashboardDB] MySQL pool error:", err.code ?? err.message); + }); } /** diff --git a/src/probe.mjs b/src/probe.mjs index 527be23..4b9e029 100644 --- a/src/probe.mjs +++ b/src/probe.mjs @@ -1,6 +1,8 @@ import ffprobe from "ffprobe-static"; import { spawn } from "node:child_process"; +const PROBE_TIMEOUT_MS = 15_000; // 15 seconds + export default function probe(file) { return new Promise((res, rej) => { // Pass args as an array — splitting a string on " " breaks paths that contain spaces. @@ -13,15 +15,32 @@ export default function probe(file) { const proc = spawn(ffprobe.path, args); const chunks = []; const errChunks = []; + let settled = false; + + const cleanup = () => { + settled = true; + clearTimeout(timeoutHandle); + try { proc.kill(); } catch (_) {} + }; + + const timeoutHandle = setTimeout(() => { + if (settled) return; + cleanup(); + rej(new Error("[probe] ffprobe timed out after " + (PROBE_TIMEOUT_MS / 1000) + "s")); + }, PROBE_TIMEOUT_MS); proc.stdout.on("data", (d) => { chunks.push(d); }); proc.stderr.on("data", (d) => { errChunks.push(d); }); proc.on("error", (err) => { + if (settled) return; + cleanup(); rej(new Error("[probe] Failed to spawn ffprobe: " + err.message)); }); proc.on("close", (code) => { + if (settled) return; + cleanup(); try { const raw = Buffer.concat(chunks).toString(); if (!raw.trim()) { diff --git a/src/worker.mjs b/src/worker.mjs index 431d080..8b2879d 100644 --- a/src/worker.mjs +++ b/src/worker.mjs @@ -562,7 +562,7 @@ if (workerData?.poolMode) { result = await jobUtils.getResults(jData.query, jData.resultCount, jData.provider, jData.trackMeta); break; case "search": - result = await jobUtils.getVideoData(String(jData), "ytm"); + result = await jobUtils.getVideoData(jData.query ?? String(jData), "ytm"); result = result?.data ?? null; break; default: @@ -628,7 +628,7 @@ utils.on("error", (m) => { break; } case "search": { - const result = await utils.getVideoData(String(data), "ytm"); + const result = await utils.getVideoData(data.query ?? String(data), "ytm"); post("finished", result?.data ?? null); break; }