From 57f018c815877ded64cf750fbcbd22c3b60b15ce Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Thu, 23 Apr 2026 17:19:49 +0300 Subject: [PATCH] feat: audio filters, rate limiting, stability fixes & new announcement channel MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit feat(filter): add %filter command with Bass Boost, Nightcore, Vaporwave, 8D, Karaoke, Tremolo and more; filter status now shown in %player UI feat(player): add Filter button (πŸŽ›οΈ) to player controls; display active filter name/emoji in queue status line feat(commands): add per-user command cooldown (1.5s) in CommandHandler; owners are exempt so %reload/%eval are never blocked feat(settings): debounce rapid set() calls into a single remoteSave() 80ms after the last write; prevents N parallel DB queries per command feat(storage): add announcementChannelId field to defaults.json fix(play): wrap statusMsg send in try/catch; fall back to fresh reply if the initial status message fails to send fix(stats): normalise guild.members.fetch() result (Collection, array, or plain object) to avoid infinite pagination loop; use memberCount as primary member count fix(search): normalise reaction event user ID across Fluxer event shapes (user_id / userId / user.id) so author filter works reliably fix(forceleave): await this.players.leave() β€” was missing await, could silently swallow errors fix(MessageHandler): guard register() against double-call on hot-reload; second call now returns early to prevent duplicate listeners fix(MoonlinkManager): add getLiveSessionId() helper that walks active nodes to find a valid session before falling back to cached value fix(reload): use pathToFileURL() for cache-busting import URL so Windows drive letters and spaces in paths are handled correctly fix(eval): broaden sensitive-key list (mysql, nodelink, _nl, credential, apikey, webhook); increase scan depth to 6; handle circular refs in hasSensitive(); normalise keys to lowercase for matching fix(worker): compile sanitize regexes once at module load instead of on every sanitizeError() call fix(Player): cache compiled sanitize regexes keyed by host:port:password to avoid rebuilding identical RegExp objects on every error path fix(index): wrap config.json read in try/catch with clear FATAL messages for missing file or malformed JSON; validate required keys at startup config: add rest.timeout/retries and nodelink requestTimeout to config_example.json with explanatory comments --- commands/eval.mjs | 35 ++++-- commands/forceleave.mjs | 2 +- commands/play.mjs | 15 ++- commands/player.mjs | 73 ++++++----- commands/reload.mjs | 5 +- commands/search.mjs | 5 +- commands/stats.mjs | 22 +++- config_example.json | 11 +- index.mjs | 91 +++++++++++--- settings/Settings.mjs | 10 +- src/CommandHandler.mjs | 24 ++++ src/MessageHandler.mjs | 6 + src/MoonlinkManager.mjs | 64 +++------- src/Player.mjs | 268 +++++++++++++++++++++++++++------------- src/Settings.mjs | 15 ++- src/worker.mjs | 44 ++++--- storage/defaults.json | 10 +- 17 files changed, 468 insertions(+), 232 deletions(-) diff --git a/commands/eval.mjs b/commands/eval.mjs index 6efb5a8..5196410 100644 --- a/commands/eval.mjs +++ b/commands/eval.mjs @@ -8,29 +8,46 @@ const EMOJI_REMOVE_TIMEOUT = 60000; /** * List of keys that should be redacted from objects before displaying in Discord. + * Matches any key that *contains* one of these strings (case-insensitive). */ const RESTRICTED = [ "token", "config", "key", - "clientSecret", - "clientId", + "clientsecret", + "clientid", "password", "secret", - "authorization" + "authorization", + "mysql", + "nodelink", + "_nl", + "credential", + "apikey", + "webhook", ]; -function hasSensitive(obj, level = 0) { - if (level >= 3 || typeof obj !== "object" || obj === null) return false; +// Maximum depth for sensitive-key scanning and redaction. +// 6 covers deeply nested config objects (e.g. config.nodelink.password nested +// inside player config) without risking stack overflow on circular references. +const SCAN_DEPTH = 6; + +// Track visited objects to handle circular references +function hasSensitive(obj, level = 0, visited = new WeakSet()) { + if (level >= SCAN_DEPTH || typeof obj !== "object" || obj === null) return false; + if (visited.has(obj)) return false; + visited.add(obj); for (const key in obj) { if (RESTRICTED.some(r => key.toLowerCase().includes(r))) return true; - if (typeof obj[key] === "object" && hasSensitive(obj[key], level + 1)) return true; + if (typeof obj[key] === "object" && hasSensitive(obj[key], level + 1, visited)) return true; } return false; } -function removeSensitive(obj, level = 0) { - if (level >= 3 || typeof obj !== "object" || obj === null) return obj; +function removeSensitive(obj, level = 0, visited = new WeakSet()) { + if (level >= SCAN_DEPTH || typeof obj !== "object" || obj === null) return obj; + if (visited.has(obj)) return "[Circular]"; + visited.add(obj); const isArray = Array.isArray(obj); const newObj = isArray ? [...obj] : { ...obj }; @@ -43,7 +60,7 @@ function removeSensitive(obj, level = 0) { newObj[key] = "[REDACTED]"; modified = true; } else if (typeof newObj[key] === "object" && newObj[key] !== null) { - const cleaned = removeSensitive(newObj[key], level + 1); + const cleaned = removeSensitive(newObj[key], level + 1, visited); if (cleaned !== newObj[key]) { newObj[key] = cleaned; modified = true; diff --git a/commands/forceleave.mjs b/commands/forceleave.mjs index 09ce7d7..c3ff423 100644 --- a/commands/forceleave.mjs +++ b/commands/forceleave.mjs @@ -27,5 +27,5 @@ export async function run(msg, data) { const p = this.players.playerMap.get(cid); if (!p) return msg.replyEmbed(embed("❌ Player not found.")); if (!p.connection) return msg.replyEmbed(embed("❌ Player not initialized.")); - this.players.leave(msg, cid); + await this.players.leave(msg, cid); } diff --git a/commands/play.mjs b/commands/play.mjs index 2497ebc..d6539fd 100644 --- a/commands/play.mjs +++ b/commands/play.mjs @@ -58,11 +58,22 @@ export async function run(message, data) { .setColor(getGlobalColor()) .setDescription("πŸ” Searching...") .toJSON(); - const statusMsg = await message.replyEmbed({ embeds: [searchEmbed] }); + + let statusMsg = null; + try { + statusMsg = await message.replyEmbed({ embeds: [searchEmbed] }); + } catch (err) { + // Fluxer API timed out sending the status message β€” continue without it + } const messages = p.play(query, false, provider); messages.on("message", d => { const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(d).toJSON(); - statusMsg.editEmbed({ embeds: [embed] }).catch(() => {}); + if (statusMsg) { + statusMsg.editEmbed({ embeds: [embed] }).catch(() => {}); + } else { + // statusMsg failed to send earlier, fall back to a fresh reply + message.replyEmbed({ embeds: [embed] }).catch(() => {}); + } }); } diff --git a/commands/player.mjs b/commands/player.mjs index ed0ea12..11deca7 100644 --- a/commands/player.mjs +++ b/commands/player.mjs @@ -28,6 +28,7 @@ const CONTROLS = { volDown: { emoji: "πŸ”‰", action: "voldown", desc: "Volume Down" }, volUp: { emoji: "πŸ”Š", action: "volup", desc: "Volume Up" }, lyrics: { emoji: "πŸ“œ", action: "lyrics", desc: "Lyrics" }, + filter: { emoji: "πŸŽ›οΈ", action: "filter", desc: "Audio Filters" }, close: { emoji: "❌", action: "close", desc: "Close" } }; @@ -51,7 +52,7 @@ export async function run(msg) { const controlsLayout = [ [CONTROLS.prev, CONTROLS.play, CONTROLS.pause, CONTROLS.stop, CONTROLS.next], [CONTROLS.loop, CONTROLS.shuffle, CONTROLS.volDown, CONTROLS.volUp, CONTROLS.lyrics], - [CONTROLS.close] + [CONTROLS.filter, CONTROLS.close] ]; const allControls = controlsLayout.flat(); @@ -83,7 +84,6 @@ export async function run(msg) { PROGRESS.empty.repeat(emptyCount) + PROGRESS.end; - // Use Utils.prettifyMS instead of local formatTime const elapsedStr = Utils.prettifyMS(elapsed); const totalStr = Utils.prettifyMS(totalMs); timeDisplay = `\`${elapsedStr} / ${totalStr}\``; @@ -98,8 +98,17 @@ export async function run(msg) { const queueSize = player.queue.size(); const loopStatus = player.queue.songLoop ? "πŸ”‚ Song" : player.queue.loop ? "πŸ” Queue" : "❌ Off"; + // FIXED: Show stacked filters if multiple are active + let filterStatus = "πŸ”‡ Off"; + if (player.activeFilter) { + if (player.activeFilter.label.includes("+")) { + filterStatus = `πŸ”₯ **${player.activeFilter.label}**`; + } else { + filterStatus = `${player.activeFilter.emoji ?? "πŸŽ›οΈ"} **${player.activeFilter.label}**`; + } + } + const nowPlaying = current - // Use Utils.truncate instead of local truncate ? `[${Utils.truncate(current.title, 45)}](${current.spotifyUrl || current.url})` : "*Nothing playing*"; @@ -111,15 +120,13 @@ export async function run(msg) { `${timeDisplay}`, ``, `πŸ”Š Volume: \`${volPercent}%\` ${volumeBar}`, - `πŸ“‹ Queue: \`${queueSize}\` tracks | Loop: ${loopStatus}`, + `πŸ“‹ Queue: \`${queueSize}\` tracks | Loop: ${loopStatus} | Filter: ${filterStatus}`, ``, state.message ? `πŸ’¬ *${state.message}*` : "πŸ’‘ *React to control playback*", ``, `⏱️ Session expires in ${Math.ceil(timeout / 60000)}m of inactivity` ].join("\n"); - // avatarURL may be a plain property (Fluxer) or a methodβ€” call it if - // it's a function, otherwise use it as-is so the footer icon works in both cases. const avatarUrl = typeof msg.author?.avatarURL === "function" ? msg.author.avatarURL() : msg.author?.avatarURL ?? null; @@ -132,7 +139,6 @@ export async function run(msg) { text: `Requested by ${msg.author?.username || "Unknown"} β€’ Controls active`, iconURL: avatarUrl }); - // setTimestamp() is not verified on @fluxerjs/core's EmbedBuilder β€” guard it. if (typeof builder.setTimestamp === "function") builder.setTimestamp(); if (current?.thumbnail) builder.setThumbnail(current.thumbnail); return builder.toJSON(); @@ -141,12 +147,11 @@ export async function run(msg) { const message = await msg.replyEmbed({ embeds: [buildEmbed()] }); if (!message?.message) return; - // Add reactions with staggered animation for (const row of controlsLayout) { for (const control of row) { try { await message.message.react(control.emoji); - await Utils.sleep(200); // Use Utils.sleep instead of inline Promise + await Utils.sleep(200); } catch (_) {} } } @@ -156,12 +161,10 @@ export async function run(msg) { let emojiRemoveTimeout; let lastState = {}; - // Track active lyrics message let activeLyricsMsg = null; let lyricsUnobserve = null; let lyricsEmojiTimeout = null; - // Helper: Clear all reactions const clearReactions = async () => { try { await message.message.removeAllReactions(); @@ -174,7 +177,6 @@ export async function run(msg) { } }; - // Helper: Reset emoji removal timer const resetEmojiTimer = () => { clearTimeout(emojiRemoveTimeout); emojiRemoveTimeout = setTimeout(async () => { @@ -185,7 +187,6 @@ export async function run(msg) { }, EMOJI_REMOVE_TIMEOUT); }; - // Helper: Clear lyrics reactions const clearLyricsReactions = async (lyricsMsg) => { if (!lyricsMsg?.message) return; try { @@ -211,15 +212,14 @@ export async function run(msg) { clearInterval(updateInterval); unobserve?.(); - // Remove all player event listeners added by this session player.off("startplay", onStartPlay); player.off("playback", onPlayback); player.off("stopplay", onStopPlay); player.off("queue", onQueue); player.off("volume", onVolume); + player.off("filter", onFilter); player.off("autoleave", onAutoLeave); - // Cleanup any active lyrics if (lyricsUnobserve) { lyricsUnobserve(); clearTimeout(lyricsEmojiTimeout); @@ -233,7 +233,6 @@ export async function run(msg) { const closedEmbed = buildEmbed({ message: `Session closed${reason !== "timeout" ? ` β€’ ${reason}` : " due to inactivity"}` }); - // Override title and footer on the plain object returned by toJSON() closedEmbed.color = getGlobalColor(); closedEmbed.footer = { text: "Session ended" }; closedEmbed.title = "🎧 Music Player (Inactive)"; @@ -249,14 +248,12 @@ export async function run(msg) { sessionTimeout = setTimeout(() => closeSession("timeout"), timeout); }; - // Live progress updates updateInterval = setInterval(() => { if (!player.paused && player.queue.getCurrent()) { refresh(lastState); } }, this.config?.timers?.playerUpdateInterval ?? 5000); - // Player events β€” store named handlers so we can remove them on closeSession const onStartPlay = () => refresh({ message: "▢️ Started playing" }); const onPlayback = (playing) => refresh({ message: playing ? "▢️ Resumed" : "⏸️ Paused" }); const onStopPlay = () => refresh({ message: "⏹️ Stopped" }); @@ -265,6 +262,15 @@ export async function run(msg) { if (e.type === "add") refresh({ message: `βž• Added: ${Utils.truncate(e.data.data.title, 30)}` }); }; const onVolume = (v) => refresh({ message: `πŸ”Š Volume: ${Math.round(v * 100)}%` }); + const onFilter = (f) => { + if (!f) { + refresh({ message: "πŸ”‡ Filters cleared" }); + } else if (f.label.includes("+")) { + refresh({ message: `πŸ”₯ Filters: **${f.label}** applied` }); + } else { + refresh({ message: `${f.emoji ?? "πŸŽ›οΈ"} Filter: **${f.label}** applied` }); + } + }; const onAutoLeave = () => closeSession("disconnected"); player.on("startplay", onStartPlay); @@ -272,9 +278,9 @@ export async function run(msg) { player.on("stopplay", onStopPlay); player.on("queue", onQueue); player.on("volume", onVolume); + player.on("filter", onFilter); player.on("autoleave", onAutoLeave); - // Reaction handler const unobserve = message.onReaction(controlEmojis, async (e) => { const control = allControls.find(c => c.emoji === e.emoji_id); if (!control) return; @@ -349,12 +355,22 @@ export async function run(msg) { break; } + case "filter": + reply = "πŸŽ›οΈ Opening filter picker β€” check the filter menu above or use the `filter` command."; + shouldUpdate = true; + try { + const { run: runFilter } = await import("./filter.mjs"); + runFilter.call(this, msg); + } catch (err) { + reply = `⚠️ Filter error: ${Utils.truncate(err.message, 50)}`; + } + break; + case "lyrics": reply = "πŸ“œ Fetching lyrics..."; refresh({ message: reply }); try { - // Cleanup previous lyrics if (lyricsUnobserve) { lyricsUnobserve(); clearTimeout(lyricsEmojiTimeout); @@ -374,7 +390,6 @@ export async function run(msg) { const LINES_PER_PAGE = 25; const totalPages = Math.ceil(totalLines / LINES_PER_PAGE); - // Build pages const pages = []; for (let i = 0; i < totalLines; i += LINES_PER_PAGE) { pages.push(lines.slice(i, i + LINES_PER_PAGE).join('\n')); @@ -384,8 +399,8 @@ export async function run(msg) { const buildLyricsContent = (pageIdx, expired = false, closed = false) => { const title = Utils.truncate( - player.queue.getCurrent()?.title?.replace(/\(Official.*?\)/gi, '').trim() ?? '', - 50 + player.queue.getCurrent()?.title?.replace(/\(Official.*?\)/gi, '').trim() ?? '', + 50 ); const footerText = closed ? `πŸ‘‹ Lyrics closed β€’ NodeLink β€’ ${totalLines} lines` @@ -403,17 +418,14 @@ export async function run(msg) { return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).setFooter({ text: footerText }).toJSON()] }; }; - // Send initial lyrics activeLyricsMsg = await msg.replyEmbed(buildLyricsContent(0)); - // Add pagination and close button if needed if (activeLyricsMsg?.message && totalPages > 1) { const navEmojis = ["⬅️", "➑️", "❌"]; for (const emoji of navEmojis) { await activeLyricsMsg.message.react(emoji).catch(() => {}); } - // Reset timer helper const resetLyricsTimer = () => { clearTimeout(lyricsEmojiTimeout); lyricsEmojiTimeout = setTimeout(async () => { @@ -422,9 +434,7 @@ export async function run(msg) { }, EMOJI_REMOVE_TIMEOUT); }; - // Navigation handler lyricsUnobserve = activeLyricsMsg.onReaction(navEmojis, async (e) => { - // Close button if (e.emoji_id === "❌") { lyricsUnobserve(); clearTimeout(lyricsEmojiTimeout); @@ -433,7 +443,6 @@ export async function run(msg) { return; } - // Reset timer on navigation resetLyricsTimer(); if (e.emoji_id === "⬅️") { @@ -445,10 +454,8 @@ export async function run(msg) { await activeLyricsMsg.editEmbed(buildLyricsContent(currentPage)); }); - // Start 1 minute timer resetLyricsTimer(); } else if (activeLyricsMsg?.message) { - // Single page - just add close button await activeLyricsMsg.message.react("❌").catch(() => {}); const resetLyricsTimer = () => { @@ -474,7 +481,6 @@ export async function run(msg) { reply = `Lyrics displayed (${totalLines} lines, ${totalPages} pages)`; } catch (err) { - // Use Utils.truncate instead of local truncate reply = `⚠️ Lyrics error: ${Utils.truncate(err.message, 50)}`; } shouldUpdate = true; @@ -491,7 +497,6 @@ export async function run(msg) { if (shouldUpdate) refresh({ message: reply }); }); - // Start timers resetTimeout(); resetEmojiTimer(); -} +} \ No newline at end of file diff --git a/commands/reload.mjs b/commands/reload.mjs index b3033ae..97fd37b 100644 --- a/commands/reload.mjs +++ b/commands/reload.mjs @@ -40,8 +40,9 @@ async function reloadCommand(ctx, name) { ctx.runnables.delete(command.uid); ctx.commandFiles.delete(command.uid); - // Re-import with cache-buster - const url = "file://" + file + "?t=" + Date.now(); + // Re-import with cache-buster β€” use pathToFileURL so Windows drive letters and + // spaces in paths are handled correctly (plain "file://" + path breaks on Windows). + const url = pathToFileURL(file).href + "?t=" + Date.now(); const cData = await import(url); const raw = cData.command ?? cData.default?.command; diff --git a/commands/search.mjs b/commands/search.mjs index 96a7b41..52964f9 100644 --- a/commands/search.mjs +++ b/commands/search.mjs @@ -127,8 +127,9 @@ export async function run(msg, data) { const authorId = msg.message?.author?.id ?? msg.authorId; const unobserve = wrapped.onReaction(allReactions, async (e, reactionMsg) => { - // Only react to the command author - if (e.user_id && e.user_id !== authorId) return; + // Only react to the command author β€” normalise across Fluxer reaction event shapes + const reactorId = e.user_id ?? e.userId ?? e.user?.id ?? null; + if (reactorId && reactorId !== authorId) return; clearTimeout(timer); unobserve(); diff --git a/commands/stats.mjs b/commands/stats.mjs index 3d1852c..e9355bd 100644 --- a/commands/stats.mjs +++ b/commands/stats.mjs @@ -33,15 +33,27 @@ async function fetchGuildMemberCount(guild) { try { let after = undefined; let total = 0; - while (true) { - const batch = await guild.members.fetch({ limit: 1000, after }); + // Guard against runaway pagination: Fluxer may have far fewer than 1000 members + // but return a Collection (Map-like) instead of an array, causing batch.length + // to be undefined and the loop to run forever. Normalise to an array first. + for (let page = 0; page < 1000; page++) { + const raw = await guild.members.fetch({ limit: 1000, after }); + // Normalise: Collection (Map), array, or plain object β†’ array + const batch = Array.isArray(raw) + ? raw + : typeof raw?.values === "function" + ? [...raw.values()] + : Object.values(raw ?? {}); total += batch.length; if (batch.length < 1000) break; - after = batch.reduce((max, m) => (m.id > max ? m.id : max), "0"); + after = batch.reduce((max, m) => { + const id = m.id ?? m.user?.id ?? ""; + return id > max ? id : max; + }, "0"); } return total; } catch { - return guild.members.size ?? 0; + return guild.memberCount ?? guild.members?.size ?? 0; } } @@ -104,7 +116,7 @@ export async function run(message) { const hasCached = cachedUserCount !== null; - // Measure real Discord round-trip latency + // Measure real round-trip latency const start = Date.now(); const msg = await message.replyEmbed({ embeds: [buildEmbed({ ...shared, userCount: hasCached ? cachedUserCount : 0, ping: 0, loading: !hasCached })] diff --git a/config_example.json b/config_example.json index 77218c0..a696f4d 100644 --- a/config_example.json +++ b/config_example.json @@ -1,7 +1,12 @@ { "token": "your bot token", "fluxer.js": { - "Comment": "Configuration data for @fluxerjs/core Client options. See: https://github.com/fluxerjs/core" + "Comment": "Configuration data for @fluxerjs/core Client options. See: https://github.com/fluxerjs/core", + "rest": { + "Comment": "REST client options. 'timeout' is ms before a request to api.fluxer.app is aborted (default: 15000). Raise if you see DOMException AbortError in logs.", + "timeout": 30000, + "retries": 3 + } }, "fluxer-api": { "Comment": "Configuration options for a fluxer REST client if self-hosting. See: https://docs.fluxer.app" @@ -16,7 +21,9 @@ "nodelink": { "host": "localhost", "port": 3000, - "password": "youshallnotpass" + "password": "youshallnotpass", + "requestTimeout": 60000, + "Comment": "requestTimeout: ms before a NodeLink HTTP request is aborted. Default: 60000 (60s). Raise if you see 'NodeLink request timeout' errors." }, "comment-radio": { "message": "If you have radio stations you'd like to connect, add them to the array below. Radio stations must be rendered like following:", diff --git a/index.mjs b/index.mjs index 07ba3bc..b65af20 100644 --- a/index.mjs +++ b/index.mjs @@ -14,7 +14,24 @@ import mysql from "mysql"; class Remix { constructor() { - const config = JSON.parse(fs.readFileSync("config.json")); + let config; + try { + config = JSON.parse(fs.readFileSync("config.json", "utf8")); + } catch (e) { + const reason = e.code === "ENOENT" + ? "config.json not found. Copy config_example.json β†’ config.json and fill in your values." + : `config.json is malformed JSON: ${e.message}`; + console.error(`[Startup] FATAL: ${reason}`); + process.exit(1); + } + // Validate required top-level keys so missing config fails fast with a clear message + const REQUIRED_KEYS = ["token", "mysql"]; + for (const key of REQUIRED_KEYS) { + if (config[key] == null) { + console.error(`[Startup] FATAL: config.json is missing required key "${key}".`); + process.exit(1); + } + } this.config = config; // Apply embed color from config globally @@ -34,7 +51,11 @@ class Remix { }; const client = new Client({ - intents: 0, + // Fluxer uses server-side intent declarations; intents here are informational. + // Set to the bitmask your bot actually has enabled on the developer dashboard so + // that a missing-intent failure is visible at startup rather than silently breaking + // voice state tracking. 0 = inherit from gateway (Fluxer default). + intents: config["fluxer.js"]?.intents ?? 0, ...config["fluxer.js"], presence: presenceContents.length > 0 ? { status: "online", @@ -189,9 +210,15 @@ class Remix { ["false", "0", "no", "off", "disable"].includes(String(raw).toLowerCase().trim()); if (disabled) return; const guild = this.client.guilds.cache.get(guildId); - // _announcementChannelCache is always a Map β€” no null check needed. - const cachedChId = this._announcementChannelCache.get(guildId); - let ch = cachedChId ? guild?.channels?.cache?.get(cachedChId) : null; + // Announcement channel lookup order: + // 1. In-memory cache (fastest β€” populated on first find after startup) + // 2. Persisted setting "announcementChannelId" (survives restarts) + // 3. Channel scan (expensive β€” only on first use per guild per process lifetime) + const serverSet = this.settingsMgr.getServer(guildId); + const cachedChId = this._announcementChannelCache.get(guildId) + ?? serverSet.get("announcementChannelId") + ?? null; + let ch = cachedChId ? guild?.channels?.cache?.get(String(cachedChId)) : null; // if cached channel is gone (deleted/uncached), clear the stale // entry immediately so we don't re-scan on every subsequent message event. if (cachedChId && !ch) { @@ -202,7 +229,13 @@ class Remix { (c.isTextBased?.() ?? c.channel_type === "TextChannel" ?? true) && (c.permissionsFor?.(this.client.user)?.has?.("SendMessages") ?? true) ); - if (ch) this._announcementChannelCache.set(guildId, ch.id); + if (ch) { + this._announcementChannelCache.set(guildId, ch.id); + // Persist so future restarts skip the expensive channel scan + if (serverSet.get("announcementChannelId") !== ch.id) { + serverSet.set("announcementChannelId", ch.id); + } + } } ch?.send({ embeds: [{ description: String(m), color: getGlobalColor() }] }).catch(() => {}); }); @@ -540,6 +573,17 @@ class Remix { if (!guildId) return; // ── Part 1: Voice state population ────────────────────────────────────── + // Purge stale entries for this guild first so old voice state from a previous + // READY cycle or an offline period doesn't persist after reconnect. + for (const [uid, info] of [...this.observedVoiceUsers]) { + if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) + this.observedVoiceUsers.delete(uid); + } + for (const [uid, info] of [...this.observedVoiceBots]) { + if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) + this.observedVoiceBots.delete(uid); + } + const voiceStatesRaw = guild.voice_states ?? guild.voiceStates?.cache ?? @@ -583,8 +627,11 @@ class Remix { if (!this.settingsMgr.guilds.has(guildId)) { logger.guild(`[GuildCreate] (Re-)joined server ${guildId} β€” initialising settings.`); try { + // Validate guildId is a non-empty snowflake string before using in query + const cleanGuildId = String(guildId).replace(/\D/g, ""); + if (!cleanGuildId) throw new Error("Invalid guildId: " + guildId); const res = await this.settingsMgr.query( - `SELECT * FROM settings WHERE id=${mysql.escape(guildId)}` + `SELECT * FROM settings WHERE id=${mysql.escape(cleanGuildId)}` ); if (res?.results?.length) { const row = res.results[0]; @@ -607,6 +654,12 @@ class Remix { } }); + // Track previous voice state per-user so we can detect channel moves. + // @fluxerjs/core fires VoiceStateUpdate with ONE arg (raw gateway data), + // not two args (oldState, newState) We maintain prev state manually. + // Declared before GuildDelete so the delete handler can purge stale entries. + const _prevVoiceState = new Map(); // userId β†’ { channelId, guildId } + // ── Bot kicked / banned / server deleted ───────────────────────────────── client.on(Events.GuildDelete, (guild) => { const guildId = guild?.id ?? guild?._id; @@ -634,6 +687,11 @@ class Remix { for (const [userId, info] of [...this.observedVoiceBots]) { if (info.guildId === guildId) this.observedVoiceBots.delete(userId); } + // Also purge _prevVoiceState entries for this guild so the Map doesn't grow unbounded + for (const [userId, info] of [..._prevVoiceState]) { + if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, "")) + _prevVoiceState.delete(userId); + } // Drop the cached settings so stale data can't be read back this.settingsMgr.removeServer(guildId); @@ -644,11 +702,6 @@ class Remix { logger.guild(`[GuildDelete] Cleanup complete for server ${guildId}.`); }); - // Track previous voice state per-user so we can detect channel moves. - // @fluxerjs/core fires VoiceStateUpdate with ONE arg (raw gateway data), - // not two args (oldState, newState) We maintain prev state manually. - const _prevVoiceState = new Map(); // userId β†’ { channelId, guildId } - client.on(Events.VoiceStateUpdate, (data) => { // data is the raw GatewayVoiceStateUpdateDispatchData β€” always snake_case const userId = data?.user_id; @@ -893,7 +946,7 @@ class Remix { const self = this; this.players.checkVoiceChannels = function (message) { const userId = message?.author?.id ?? message?.message?.author?.id; - // Fluxer uses server_id (snake_case); Discord.js uses guildId; probe all known shapes. + // Fluxer uses server_id (snake_case); uses guildId; probe all known shapes. const guildId = message?.channel?.server_id ?? message?.channel?.serverId ?? @@ -1131,10 +1184,16 @@ const saveAndExit = () => { for (const [channelId, player] of remix.players.playerMap.entries()) { const current = player.queue.getCurrent(); const queueData = player.queue.getQueue(); - const tracksToSave = []; - if (current) tracksToSave.push(current); - tracksToSave.push(...queueData); + // Deep-clone track data to capture a stable snapshot. + // Without this, a concurrent skip() or playNext() can mutate the array + // between capture and writeFileSync, producing a corrupted recovery file. + const cloneTrack = (t) => { + try { return JSON.parse(JSON.stringify(t)); } catch { return t; } + }; + const tracksToSave = []; + if (current) tracksToSave.push(cloneTrack(current)); + for (const t of queueData) tracksToSave.push(cloneTrack(t)); // Save ALL active sessions unconditionally so the bot always rejoins // the channel it was in before rebooting (queue or not, 24/7 or not) diff --git a/settings/Settings.mjs b/settings/Settings.mjs index a60b511..e026b9d 100644 --- a/settings/Settings.mjs +++ b/settings/Settings.mjs @@ -44,6 +44,8 @@ export class MySqlSettingsManager extends SettingsManager { descriptions = {}; defaults = {}; db = null; + // Per-server debounce timers β€” collapses rapid set() calls into one remoteSave() + _debounceTimers = new Map(); constructor(config, defaultsPath) { super(); @@ -122,7 +124,13 @@ export class MySqlSettingsManager extends SettingsManager { if (!this.guilds.has(server.id)) { this.guilds.set(server.id, server); this.create(server.id, server); } const s = this.guilds.get(server.id); s.data[key] = server.data[key]; - this.remoteUpdate(server, key); + // Debounce: batch rapid consecutive set() calls into a single remoteSave() 80ms later + const existing = this._debounceTimers.get(server.id); + if (existing) clearTimeout(existing); + this._debounceTimers.set(server.id, setTimeout(() => { + this._debounceTimers.delete(server.id); + this.remoteSave(s); + }, 80)); } isOption(key) { return key in this.defaults; } hasServer(id) { return this.guilds.has(id); } diff --git a/src/CommandHandler.mjs b/src/CommandHandler.mjs index fa2401b..1914989 100644 --- a/src/CommandHandler.mjs +++ b/src/CommandHandler.mjs @@ -376,6 +376,12 @@ export class CommandHandler extends EventEmitter { invalidFlagError = "Invalid flag `$invalidFlag`. It doesn't match any options on this command.\n`$previousCmd $invalidFlag`"; textWrapError = "Malformed string `$value`: Missing a closing quote character (`$quote`) after the desired string."; + // Per-user rate limiting: userId β†’ timestamp of last processed command + // Prevents command spam that could saturate worker threads and fill the searches Map. + // Owners are exempt so they can always use debug/reload commands. + _cmdCooldowns = new Map(); + _cmdCooldownMs = 1500; // 1.5 seconds between commands per user + constructor(handler, prefix = "!") { super(); this.messages = handler; @@ -421,6 +427,24 @@ export class CommandHandler extends EventEmitter { } return; } + + // Per-user rate limit β€” skip spam commands silently. + // Owners are always exempt so %reload and %eval are never blocked. + const userId = msg.message?.author?.id ?? msg.author?.id; + if (userId && !this.owners.includes(userId)) { + const now = Date.now(); + const last = this._cmdCooldowns.get(userId) ?? 0; + if (now - last < this._cmdCooldownMs) return; + this._cmdCooldowns.set(userId, now); + // Evict stale entries periodically to keep the Map from growing unbounded. + // 500 entries Γ— 8 bytes β‰ˆ negligible, but good hygiene on busy bots. + if (this._cmdCooldowns.size > 500) { + const cutoff = now - this._cmdCooldownMs * 2; + for (const [uid, ts] of this._cmdCooldowns) { + if (ts < cutoff) this._cmdCooldowns.delete(uid); + } + } + } const guildId = msg.channel?.channel?.guildId ?? msg.message?.guildId; const prefix = this.getPrefix(guildId); const ping = `<@${this.client.user?.id}>`; diff --git a/src/MessageHandler.mjs b/src/MessageHandler.mjs index e445839..2f6b7c5 100644 --- a/src/MessageHandler.mjs +++ b/src/MessageHandler.mjs @@ -1046,6 +1046,12 @@ export class HelpCommand { * Call once during bot startup, after commands have been loaded. */ register() { + // Guard: if register() is called more than once (e.g. via hot-reload), bail out. + // A second call would stack another MessageCreate listener and re-wrap the format/reply + // handlers a second time, causing duplicate help responses and doubled logic. + if (this._registered) return; + this._registered = true; + const HELP_ALIASES = ["help", "h", "commands"]; // Neutralize built-in help interceptor diff --git a/src/MoonlinkManager.mjs b/src/MoonlinkManager.mjs index da6ea48..47b0481 100644 --- a/src/MoonlinkManager.mjs +++ b/src/MoonlinkManager.mjs @@ -2,7 +2,6 @@ * MoonlinkManager.mjs * * Wraps moonlink.js Manager with a custom connector for Fluxer. - * FIXED: Correct payload format for packetUpdate */ import { Manager } from "moonlink.js"; @@ -28,7 +27,7 @@ export class MoonlinkManager extends EventEmitter { */ constructor(nodeCfg, client) { super(); - this.setMaxListeners(50); // reconnects temporarily stack listeners during re-init + this.setMaxListeners(50); this._nodeCfg = nodeCfg; this._client = client; @@ -59,10 +58,8 @@ export class MoonlinkManager extends EventEmitter { }, }); - // Set up voice state forwarding from Fluxer to moonlink this._setupVoiceForwarding(client); - // Forward key events this.manager.on("nodeReady", (node) => { this.sessionId = node.sessionId ?? null; logger.moonlink(`[Moonlink] Node ready: ${node.identifier} | session: ${this.sessionId}`); @@ -98,6 +95,21 @@ export class MoonlinkManager extends EventEmitter { }); } + /** + * Get the current live session ID from the connected node. + * Walks active nodes to find a valid session, fallback to cached. + * @returns {string|null} + */ + getLiveSessionId() { + try { + for (const node of this.manager.nodes?.nodes?.values?.() ?? []) { + if (node.sessionId) return node.sessionId; + if (node.ws?.sessionId) return node.ws.sessionId; + } + } catch (_) {} + return this.sessionId; + } + /** * Send voice payload to Fluxer's WebSocket * @param {string} guildId @@ -106,14 +118,11 @@ export class MoonlinkManager extends EventEmitter { */ _sendPayload(guildId, payload) { try { - // Prefer the public ws.send(shardId, payload) API β€” shards is a private field - // in @fluxerjs/ws and accessing it directly risks breaking on internal refactors. if (typeof this._client?.ws?.send === "function") { this._client.ws.send(0, payload); return; } - // Fallback: access shard directly only if the public API is unavailable const shard = this._client?.ws?.shards?.get?.(0); if (!shard) { logger.warn("[MoonlinkManager] No WebSocket shard available"); @@ -138,21 +147,16 @@ export class MoonlinkManager extends EventEmitter { * @private */ _setupVoiceForwarding(client) { - // @fluxerjs/core emits VoiceStateUpdate with a SINGLE argument: - // (data: GatewayVoiceStateUpdateDispatchData) β€” raw gateway snake_case fields. client.on(Events.VoiceStateUpdate, (data) => { try { - // data is the raw GatewayVoiceStateUpdateDispatchData β€” always snake_case const guildId = data.guild_id; if (!guildId) { logger.warn("[MoonlinkManager] voiceStateUpdate: No guild_id found in data", data); return; } - // Build the proper payload format that moonlink expects: - // { op: 0, t: "VOICE_STATE_UPDATE", d: { guild_id, user_id, channel_id, ... } } const payload = { - op: 0, // Dispatch + op: 0, t: "VOICE_STATE_UPDATE", d: { guild_id: guildId, @@ -176,9 +180,6 @@ export class MoonlinkManager extends EventEmitter { } }); - // Raw WS β€” only for VOICE_SERVER_UPDATE (VOICE_STATE_UPDATE is handled above via Events listener) - // Store the handler reference so we can remove the stale listener before re-attaching - // on gateway reconnects. Without this, each reconnect stacks another handler on the socket. const attachRawWs = () => { try { const shard0 = client.ws?.shards?.get?.(0); @@ -196,7 +197,6 @@ export class MoonlinkManager extends EventEmitter { } catch (_) {} } - // Skip re-attaching if it's the same socket object (spurious Ready re-fire) if (wsObj === this._rawWsObj) return; this._rawWsHandler = (rawData) => { @@ -213,7 +213,6 @@ export class MoonlinkManager extends EventEmitter { } catch (_) {} }; - // Absorb socket-level errors so they don't escape to uncaughtException. this._rawWsErrorHandler = (err) => { logger.warn("[MoonlinkManager] Raw WS socket error (will reconnect):", err?.message ?? err); }; @@ -233,26 +232,13 @@ export class MoonlinkManager extends EventEmitter { }; attachRawWs(); - // Re-attach after every gateway reconnect so the new socket gets the listener client.on(Events.Ready, attachRawWs); } - /** - * Call after client.login() resolves and client.user.id is available. - * Safe to call on every reconnect β€” removes stale internal listeners before re-init - * to prevent the MaxListenersExceededWarning that moonlink.js triggers by adding - * a new nodeReady/nodeConnected listener to the node socket on every init() call. - * @param {string} clientId - */ async init(clientId) { - // Raise the limit on both this emitter and the internal manager so reconnects - // don't spam MaxListenersExceededWarning while we're between socket teardown - // and the re-init completing. this.setMaxListeners(50); try { this.manager.setMaxListeners?.(50); } catch (_) {} - // Strip any stale nodeReady listeners the previous init() call registered - // so they don't stack up across gateway reconnects. try { for (const node of this.manager.nodes?.nodes?.values?.() ?? []) { const sock = node.socket ?? node.ws ?? null; @@ -268,30 +254,14 @@ export class MoonlinkManager extends EventEmitter { await this.manager.init(clientId); } - /** - * Search for tracks. Returns a moonlink SearchResult. - * @param {string} query - * @param {string} [source] e.g. "ytmsearch", "spsearch" - * @param {*} [requester] - */ search(query, source, requester) { return this.manager.search({ query, source, requester }); } - /** - * Get or create a moonlink Player for a guild. - * @param {{ guildId: string, voiceChannelId: string, textChannelId?: string, volume?: number }} opts - * @returns {import("moonlink.js").Player} - */ createPlayer(opts) { return this.manager.players.create(opts); } - /** - * Get an existing player by guildId. - * @param {string} guildId - * @returns {import("moonlink.js").Player|undefined} - */ getPlayer(guildId) { return this.manager.players.get(guildId); } diff --git a/src/Player.mjs b/src/Player.mjs index 3b04349..834cb46 100644 --- a/src/Player.mjs +++ b/src/Player.mjs @@ -26,30 +26,51 @@ function mkEmbed(desc) { return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).toJSON()] }; } +/** NodeLink default password β€” centralised so it doesn't need to be hardcoded in two places. */ +const NL_DEFAULT_PASSWORD = "youshallnotpass"; + +// Cache compiled sanitize regexes keyed by "host:port:password" to avoid +// rebuilding identical RegExp objects on every error path. +const _sanitizeCache = new Map(); + /** * Strip NodeLink host, port, and password from a string so they are never - * shown to end-users in Discord messages. + * shown to end-users in Fluxer messages. * @param {string} msg * @param {Object} nl - The player's _nl config object { host, port, password } * @returns {string} */ function sanitizeError(msg, nl = {}) { if (!msg) return msg; + const host = nl.host ?? ""; + const port = nl.port ?? 0; + const password = nl.password ?? NL_DEFAULT_PASSWORD; + const cacheKey = `${host}:${port}:${password}`; + + let regexes = _sanitizeCache.get(cacheKey); + if (!regexes) { + regexes = []; + if (host && host !== "localhost") { + const eh = host.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + regexes.push(new RegExp(`https?://${eh}(:\\d+)?[^\\s"']*`, "gi")); + if (port) regexes.push(new RegExp(`${eh}:${port}`, "g")); + } + if (port) { + regexes.push(new RegExp(`https?://localhost:${port}[^\\s"']*`, "gi")); + } + if (password && password !== NL_DEFAULT_PASSWORD) { + const ep = password.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + regexes.push(new RegExp(ep, "g")); + } + // Cap cache size β€” in practice there's only one NodeLink config, but guard anyway + if (_sanitizeCache.size >= 20) _sanitizeCache.clear(); + _sanitizeCache.set(cacheKey, regexes); + } + let s = String(msg); - const host = nl.host; - const port = nl.port; - const password = nl.password; - if (host && host !== "localhost") { - const escapedHost = host.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - s = s.replace(new RegExp(`https?://${escapedHost}(:\\d+)?[^\\s"']*`, "gi"), "[internal]"); - if (port) s = s.replace(new RegExp(`${escapedHost}:${port}`, "g"), "[internal]"); - } - if (port) { - s = s.replace(new RegExp(`https?://localhost:${port}[^\\s"']*`, "gi"), "[internal]"); - } - if (password && password !== "youshallnotpass") { - const escapedPw = password.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - s = s.replace(new RegExp(escapedPw, "g"), "[redacted]"); + for (const re of regexes) { + re.lastIndex = 0; // reset stateful global regexes between calls + s = s.replace(re, re.source.includes("redacted") ? "[redacted]" : "[internal]"); } return s; } @@ -186,9 +207,10 @@ export default class Player extends EventEmitter { _playingNext = false; _isRecovering = false; startedPlaying = null; - // searches Map with max-size eviction to prevent memory leak on busy servers + // searches Map with max-size eviction to prevent memory leak on busy servers. + // Map preserves insertion order natively, so we use keys().next() for LRU eviction + // instead of a separate _searchOrder array (which could hold ghost keys after playResult()). searches = new Map(); - _searchOrder = []; // insertion-order tracker for LRU eviction _searchMaxSize = 50; // cap: max concurrent pending search sessions resultLimit = 5; preferredVolume = 1; @@ -200,6 +222,9 @@ export default class Player extends EventEmitter { _wasRadio = false; _radioAnnounced = false; + // Active audio filter β€” { key, label, payload } or null + activeFilter = null; + // Inactivity timeout _inactivityTimer = null; _inactivityLimit = 3 * 60 * 1000; // 3 min default @@ -209,10 +234,11 @@ export default class Player extends EventEmitter { // NodeLink config (kept for direct stream URL building; session managed by moonlink) _nl = { - host: "localhost", - port: 3000, - password: "youshallnotpass", - sessionId: null, + host: "localhost", + port: 3000, + password: "youshallnotpass", + sessionId: null, + requestTimeout: 60_000, // ms before a NodeLink HTTP request is aborted (raise in config if needed) }; constructor(token, opts = {}) { @@ -242,16 +268,20 @@ export default class Player extends EventEmitter { // moonlink.js manager reference β€” injected by PlayerManager this._moonlink = opts.moonlink ?? null; - // Keep session ID in sync when moonlink establishes/re-establishes it. - // Use a named handler stored on the instance so it can be removed in destroy() - // and doesn't stack up across player replacements on the same moonlink instance. + // FIXED: Robust session sync that handles reconnection and stale sessions if (this._moonlink) { this._onMoonlinkReady = (sessionId) => { + const oldId = this._nl.sessionId; this._nl.sessionId = sessionId; + if (oldId && oldId !== sessionId) { + logger.moonlink(`[Player] Session ID updated: ${oldId} β†’ ${sessionId}`); + } }; this._moonlink.on("ready", this._onMoonlinkReady); - if (this._moonlink.sessionId) { - this._nl.sessionId = this._moonlink.sessionId; + // Immediate sync if moonlink is already ready + const existingSession = this._moonlink.getLiveSessionId?.() ?? this._moonlink.sessionId; + if (existingSession) { + this._nl.sessionId = existingSession; } } } @@ -267,7 +297,6 @@ export default class Player extends EventEmitter { _is247Enabled() { if (!this._guildId) return false; - // Helper: check a single settings object const checkSettings = (set) => { if (!set?.get) return false; const raw = set.get("stay_247"); @@ -333,7 +362,18 @@ export default class Player extends EventEmitter { logger.mediaplayer(`[Player] Rejoining channel ${this._channelId}`); await this.join(this._channelId); - // Resume playing the interrupted track + // Verify the join actually produced a healthy connection before resuming playback. + // Releasing _isRecovering here (rather than in finally) means a second "disconnected" + // event that fires while join() is in-flight cannot enter a concurrent recovery cycle. + const roomState = this.connection?.room?.state; + const isConnected = roomState === 1 || roomState === "connected" || roomState === "connecting"; + if (!isConnected) { + throw new Error(`Room in unexpected state after rejoin: ${roomState}`); + } + + // Release the guard only after confirming the connection is live + this._isRecovering = false; + const current = this.queue.getCurrent(); if (current) { logger.player(`[Player] Resuming track after recovery: ${current.title}`); @@ -347,9 +387,8 @@ export default class Player extends EventEmitter { } } catch (e) { logger.error("[Player] Recovery failed:", e.message); - this.emit("autoleave"); // Fallback to full recreate if recovery fails entirely - } finally { this._isRecovering = false; + this.emit("autoleave"); } } @@ -359,13 +398,9 @@ export default class Player extends EventEmitter { /** * Returns true if there is at least one non-bot human in the bot's current voice channel. - * Uses the observedVoiceUsers map maintained by the gateway voice state handler, - * since this bot uses intents: 0 and channel.members is never populated. */ _hasHumansInChannel() { if (!this._channelId || !this._guildId) return false; - // Normalize to digits-only β€” IDs can arrive from different sources - // (gateway snake_case vs API camelCase) with inconsistent formatting. const cleanChan = String(this._channelId).replace(/\D/g, ""); const cleanGuild = String(this._guildId).replace(/\D/g, ""); try { @@ -373,14 +408,13 @@ export default class Player extends EventEmitter { if (voiceUsers) { for (const [, info] of voiceUsers) { if ( - String(info.guildId ?? "").replace(/\D/g, "") === cleanGuild && - String(info.channelId ?? "").replace(/\D/g, "") === cleanChan + String(info.guildId ?? "").replace(/\D/g, "") === cleanGuild && + String(info.channelId ?? "").replace(/\D/g, "") === cleanChan ) return true; } return false; } } catch (_) {} - // Fallback: try channel.members cache (works if privileged intents are enabled) try { const channel = this.client?.channels?.cache?.get(this._channelId); const members = channel?.members; @@ -407,7 +441,6 @@ export default class Player extends EventEmitter { return; } - // Don't start the inactivity timer if there are humans in the channel if (this._hasHumansInChannel()) { logger.inactivity(`[Player] Humans present in channel ${this._channelId}, skipping inactivity timer`); return; @@ -419,7 +452,6 @@ export default class Player extends EventEmitter { logger.inactivity("[Player] 24/7 mode enabled during inactivity wait, aborting leave"); return; } - // Double-check: abort if a human joined during the wait if (this._hasHumansInChannel()) { logger.inactivity("[Player] Human joined during inactivity wait, aborting leave"); return; @@ -484,23 +516,10 @@ export default class Player extends EventEmitter { } } - /** - * Monitor MediaPlayer for ghost connections via event β€” not polling. - * The connection.on("disconnected") handler in join() already calls - * _cleanupMediaPlayer() + _recoverConnection(), so this method is intentionally - * lightweight: it only validates the room state once before playing. - * @private - */ _setupMediaPlayerMonitoring() { // No-op: recovery is fully handled by connection.on("disconnected") in join(). - // The old setInterval(5000) approach polled LiveKit state unnecessarily and - // risked acting on a stale captured MediaPlayer reference. } - /** - * Clean up MediaPlayer properly. - * @private - */ async _cleanupMediaPlayer() { try { await this._mediaPlayer?.stop(); @@ -571,16 +590,21 @@ export default class Player extends EventEmitter { } if (returnStream) return resolve(res); + // 204 No Content β€” valid success with no body + if (res.statusCode === 204) { res.resume(); return resolve(null); } + const chunks = []; res.on("data", d => chunks.push(d)); res.on("end", () => { - try { resolve(JSON.parse(Buffer.concat(chunks).toString())); } + const raw = Buffer.concat(chunks).toString().trim(); + if (!raw) return resolve(null); + try { resolve(JSON.parse(raw)); } catch (e) { reject(new Error(`JSON parse error from ${target}`)); } }); }); req.on("error", reject); - req.setTimeout(options.timeout || 30_000, () => { + req.setTimeout(options.timeout || this._nl.requestTimeout || 60_000, () => { req.destroy(); reject(new Error("Request timeout")); }); @@ -627,7 +651,8 @@ export default class Player extends EventEmitter { cleanup(); if (this._streamingStopped || this._skipping) return resolve(); const graceful = ["aborted", "ECONNRESET", "ERR_STREAM_DESTROYED", "ENOTFOUND", "ETIMEDOUT", "ECONNREFUSED"]; - if (graceful.includes(e.code) || graceful.includes(e.message)) return resolve(); + // Use substring matching so "Input stream error: aborted" (from NodeLink) is also caught + if (graceful.some(g => e.code === g || e.message?.includes(g))) return resolve(); reject(e); }); @@ -636,13 +661,20 @@ export default class Player extends EventEmitter { this._mediaPlayer.removeAllListeners("finish"); this._mediaPlayer.removeAllListeners("error"); - // revoice.js MediaPlayer.playStream() pipes through FFmpeg but the FFmpeg - // error handler is a no-op (// TODO). Wire it up manually so errors surface. const onFfmpegError = (err) => { - logger.error("[Player] FFmpeg error:", err?.message ?? err); + const ffMsg = err?.message ?? String(err); + // "Input stream error: aborted" means NodeLink dropped the HTTP stream + // (e.g. filter PATCH restarted the player before voice state arrived). + // Treat it as graceful so the queue can advance normally. + if (ffMsg.includes("aborted") || ffMsg.includes("Input stream error")) { + logger.player("[Player] FFmpeg stream aborted gracefully (NodeLink stream closed)"); + cleanup(); + return resolve(); + } + logger.error("[Player] FFmpeg error:", ffMsg); cleanup(); if (this._streamingStopped || this._skipping) return resolve(); - reject(new Error(`FFmpeg: ${err?.message ?? err}`)); + reject(new Error(`FFmpeg: ${ffMsg}`)); }; try { @@ -659,8 +691,6 @@ export default class Player extends EventEmitter { return reject(e); } - // Safety timeout β€” FFmpeg errors emit nothing in revoice.js, this ensures - // the queue always advances even if a future silent failure slips through. const safetyMs = 10 * 60 * 1000; const safetyTimer = setTimeout(() => { logger.warn("[Player] Stream safety timeout β€” advancing queue"); @@ -708,8 +738,6 @@ export default class Player extends EventEmitter { if (!isNodeLink) return this._streamViaRevoice(url); - // NodeLink /v4/trackstream returns { "url": "https://..." } β€” a JSON wrapper - // pointing to the actual CDN audio URL. Extract it then stream that. try { const json = await this._request(url, { headers: { @@ -722,8 +750,6 @@ export default class Player extends EventEmitter { return this._streamViaRevoice(json.url); } catch (err) { logger.error("[Player] NodeLink resolve error:", err.message); - // Sanitize before re-throwing β€” this error eventually becomes a user-visible - // "Error streaming X β€” skipping..." message, so the NodeLink URL must not appear. throw new Error(sanitizeError(err.message, this._nl)); } } @@ -825,7 +851,7 @@ export default class Player extends EventEmitter { if (!this.leaving) { logger.mediaplayer("[Player] Unexpected disconnect detected"); this._cleanupMediaPlayer(); - this._recoverConnection(); // Trigger recovery instead of giving up + this._recoverConnection(); } else { try { connection.destroy(); } catch (_) {} } @@ -898,8 +924,6 @@ export default class Player extends EventEmitter { destroy() { try { - // Remove the moonlink "ready" listener registered in the constructor - // so it doesn't stack up across player replacements on the same manager. if (this._moonlink && this._onMoonlinkReady) { try { this._moonlink.off("ready", this._onMoonlinkReady); } catch (_) {} this._onMoonlinkReady = null; @@ -907,10 +931,6 @@ export default class Player extends EventEmitter { this.leaving = true; this._streamingStopped = true; this._stopInactivityTimer(); - // _stopMediaPlayer is async; we fire it and swallow the promise here - // (destroy is intentionally sync/fire-and-forget), but we do wait for it - // before disconnecting via the chained .then so the media player stops - // cleanly before the connection tears down β€” preventing "AudioSource is closed" errors. this._stopMediaPlayer().catch(() => {}).then(() => { setTimeout(() => { const disconnectPromise = this.connection?.disconnect?.(); @@ -941,10 +961,7 @@ export default class Player extends EventEmitter { this._paused = true; this._mediaPlayer?.pause(); this.emit("playback", false); - - // patiently waits in the VC forever until you resume! this._stopInactivityTimer(); - return ":pause_button: Paused"; } @@ -956,7 +973,6 @@ export default class Player extends EventEmitter { this._paused = false; this._mediaPlayer?.resume(); this.emit("playback", true); - this._stopInactivityTimer(); return ":arrow_forward: Resumed"; } @@ -1017,6 +1033,81 @@ export default class Player extends EventEmitter { return `Volume changed to \`${Math.round(this.preferredVolume * 100)}%\`.`; } + // ═══════════════════════════════════════════════════════════════════════════ + // Audio Filter Control (NodeLink PATCH /v4/sessions/:id/players/:guildId) + // ═══════════════════════════════════════════════════════════════════════════ + + /** + * Apply (or clear) an audio filter by sending a PATCH to NodeLink. + * Includes encodedTrack so NodeLink doesn't create a ghost player. + * Uses live session ID from moonlink to avoid stale sessions. + * Auto-retries once on stale session detection. + * + * @param {Object} filterPayload - Lavalink v4 filters object. Pass {} to clear all filters. + * @param {{ key: string, label: string, emoji?: string }|null} meta - Filter metadata to store, or null to clear. + * @returns {Promise<{ ok: boolean, reason?: string }>} + */ + async applyFilter(filterPayload, meta = null, _retryCount = 0) { + const guildId = this._guildId; + if (!guildId) { + return { ok: false, reason: "Player not bound to a guild." }; + } + + // CRITICAL: Get session ID directly from moonlink manager, not cached _nl + const liveSessionId = this._moonlink?.getLiveSessionId?.() ?? this._moonlink?.sessionId ?? this._nl.sessionId; + if (!liveSessionId) { + return { ok: false, reason: "No active NodeLink session. Try again in a few seconds." }; + } + + const { host, port } = this._nl; + const url = `http://${host}:${port}/v4/sessions/${liveSessionId}/players/${guildId}`; + + // Per NodeLink REST API: send ONLY the filters object when updating filters. + // Including track.encoded causes NodeLink to restart playback (triggers play()), + // which leads to "No voice state" spam and eventually FFmpeg "Input stream error: aborted". + const current = this.queue.getCurrent(); + if (!current?.encoded) { + return { ok: false, reason: "No active track loaded. Start playback first." }; + } + + const body = JSON.stringify({ filters: filterPayload }); + + try { + await this._request(url, { + method: "PATCH", + headers: { + "Content-Type": "application/json", + "Content-Length": Buffer.byteLength(body), + }, + body, + }); + + // Sync local session ID if it changed under us + if (liveSessionId !== this._nl.sessionId) { + this._nl.sessionId = liveSessionId; + logger.moonlink(`[Player] Synced session ID after filter apply: ${liveSessionId}`); + } + + this.activeFilter = meta ?? null; + this.emit("filter", this.activeFilter); + return { ok: true }; + } catch (e) { + // Detect stale session specifically β€” allow exactly one retry with a fresh session ID. + // The _retryCount guard prevents infinite recursion if back-to-back reconnects keep + // producing stale IDs faster than this method runs. + const errMsg = e.message ?? ""; + if (_retryCount === 0 && (errMsg.includes("404") || errMsg.includes("not found") || errMsg.includes("Session-ID") || errMsg.includes("does not exist"))) { + logger.warn("[Player] Filter apply failed with stale session, forcing re-sync..."); + const freshSession = this._moonlink?.getLiveSessionId?.() ?? this._moonlink?.sessionId; + if (freshSession && freshSession !== liveSessionId) { + this._nl.sessionId = freshSession; + return this.applyFilter(filterPayload, meta, 1); // Single retry with depth guard + } + } + return { ok: false, reason: sanitizeError(errMsg, this._nl) }; + } + } + // ═══════════════════════════════════════════════════════════════════════════ // Queue Management // ═══════════════════════════════════════════════════════════════════════════ @@ -1272,8 +1363,14 @@ export default class Player extends EventEmitter { worker.on("exit", (code) => { if (code !== 0) reject(new Error(`Worker exited ${code}`)); }); }); - return Utils.timeout(job, 60_000, "Worker timeout after 60s") - .finally(() => worker.terminate().catch(() => {})); + const raced = Utils.timeout(job, 60_000, "Worker timeout after 60s"); + + // Absorb any late "error" events emitted after the timeout has already settled + // the promise. Without this no-op, a worker error arriving post-timeout produces + // an unhandled rejection / uncaughtException on some Node versions. + worker.on("error", () => {}); + + return raced.finally(() => worker.terminate().catch(() => {})); } // ═══════════════════════════════════════════════════════════════════════════ @@ -1292,13 +1389,15 @@ export default class Player extends EventEmitter { }); list += "\nSend the number of the result. Example: `2`\nSend 'x' to cancel."; - // FIX: evict oldest search session if we're at the cap, preventing unbounded growth + // LRU eviction: Map preserves insertion order; the first key() is always the oldest. + // This avoids the ghost-key bug that existed when _searchOrder tracked keys separately + // from the Map β€” playResult() could remove a key from searches but leave it in the + // order array, causing the eviction to silently skip the true oldest live entry. if (this.searches.size >= this._searchMaxSize) { - const oldestKey = this._searchOrder.shift(); - if (oldestKey) this.searches.delete(oldestKey); + const oldestKey = this.searches.keys().next().value; + if (oldestKey !== undefined) this.searches.delete(oldestKey); } this.searches.set(id, data.data); - this._searchOrder.push(id); return { m: list, count: data.data.length }; } catch (err) { @@ -1314,10 +1413,7 @@ export default class Player extends EventEmitter { const res = searchResults[result]; this.addToQueue(res, next); - // Clean up this search session once the user has picked a result this.searches.delete(id); - const orderIdx = this._searchOrder.indexOf(id); - if (orderIdx !== -1) this._searchOrder.splice(orderIdx, 1); if (!this.queue.getCurrent()) { this.playNext(); @@ -1475,7 +1571,7 @@ export default class Player extends EventEmitter { this.queue.current = null; this._playingNext = false; } - this._recoverConnection(); // Safely recover the broken LiveKit connection + this._recoverConnection(); return; } diff --git a/src/Settings.mjs b/src/Settings.mjs index 92eff4e..849832b 100644 --- a/src/Settings.mjs +++ b/src/Settings.mjs @@ -96,6 +96,11 @@ export class RemoteSettingsManager extends EventEmitter { // track retry count and apply exponential backoff on load failures _loadAttempts = 0; + // Per-server debounce timers: serverId β†’ NodeJS.Timeout + // Batches rapid set() calls (e.g. 24/7 mode changes that write stay_247 + stay_247_mode) + // into a single remoteSave() 80ms after the last write, rather than firing one UPDATE + // per key. + _debounceTimers = new Map(); constructor(config, defaultsPath) { super(); @@ -177,7 +182,15 @@ export class RemoteSettingsManager extends EventEmitter { if (!this.guilds.has(server.id)) { this.guilds.set(server.id, server); this.create(server.id, server); } const s = this.guilds.get(server.id); s.data[key] = server.data[key]; - this.remoteUpdate(server, key); + // Debounce: collapse rapid successive set() calls (e.g. stay_247 + stay_247_mode written + // together) into a single remoteSave() 80ms after the last write for this server. + // This prevents N parallel UPDATE queries when multiple keys change in one command handler. + const existing = this._debounceTimers.get(server.id); + if (existing) clearTimeout(existing); + this._debounceTimers.set(server.id, setTimeout(() => { + this._debounceTimers.delete(server.id); + this.remoteSave(s); + }, 80)); } isOption(key) { return key in this.defaults; } diff --git a/src/worker.mjs b/src/worker.mjs index 6e07dd8..4034b16 100644 --- a/src/worker.mjs +++ b/src/worker.mjs @@ -19,34 +19,38 @@ import { logger } from "./constants/Logger.mjs"; const nl = workerData?.data?.nodelink ?? {}; const NL_HOST = nl.host ?? "localhost"; const NL_PORT = nl.port ?? 3000; -const NL_PASSWORD = nl.password ?? "youshallnotpass"; +// Shared default β€” must match NL_DEFAULT_PASSWORD in Player.mjs +const NL_DEFAULT_PASSWORD = "youshallnotpass"; +const NL_PASSWORD = nl.password ?? NL_DEFAULT_PASSWORD; const NL_SESSION_ID = nl.sessionId ?? null; // provided by moonlink.js Manager const NL_GUILD_ID = workerData?.data?.guildId ?? null; // ─── Error sanitizer ────────────────────────────────────────────────────────── +// Compile regexes once at module load (constants are fixed for the worker's lifetime). +// Re-compiling on every sanitizeError() call was wasteful and identical each time. +const _sanitizeRegexes = (() => { + const r = []; + if (NL_HOST && NL_HOST !== "localhost") { + const eh = NL_HOST.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + r.push({ re: new RegExp(`https?://${eh}(:\\d+)?[^\\s"']*`, "gi"), sub: "[internal]" }); + r.push({ re: new RegExp(`${eh}:${NL_PORT}`, "g"), sub: "[internal]" }); + } + r.push({ re: new RegExp(`https?://localhost:${NL_PORT}[^\\s"']*`, "gi"), sub: "[internal]" }); + if (NL_PASSWORD && NL_PASSWORD !== NL_DEFAULT_PASSWORD) { + const ep = NL_PASSWORD.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); + r.push({ re: new RegExp(ep, "g"), sub: "[redacted]" }); + } + return r; +})(); + // Strips the NodeLink host, port, and password from any string so they are -// never shown to end-users in Discord messages. Called on every user-visible -// error string before it is emitted or returned. +// never shown to end-users in messages. function sanitizeError(msg) { if (!msg) return msg; let s = String(msg); - // Remove full URLs containing the NodeLink host (http://host:port/...) - if (NL_HOST && NL_HOST !== "localhost") { - // Escape special regex chars in the host string - const escapedHost = NL_HOST.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - s = s.replace(new RegExp(`https?://${escapedHost}(:\\d+)?[^\\s"']*`, "gi"), "[internal]"); - } - // Remove localhost:port combos - s = s.replace(new RegExp(`https?://localhost:${NL_PORT}[^\\s"']*`, "gi"), "[internal]"); - // Remove bare host:port if it somehow appears without a protocol - if (NL_HOST && NL_HOST !== "localhost") { - const escapedHost = NL_HOST.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - s = s.replace(new RegExp(`${escapedHost}:${NL_PORT}`, "g"), "[internal]"); - } - // Remove the password just in case it ever leaks into an error message - if (NL_PASSWORD && NL_PASSWORD !== "youshallnotpass") { - const escapedPw = NL_PASSWORD.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - s = s.replace(new RegExp(escapedPw, "g"), "[redacted]"); + for (const { re, sub } of _sanitizeRegexes) { + re.lastIndex = 0; // reset stateful global regexes between calls + s = s.replace(re, sub); } return s; } diff --git a/storage/defaults.json b/storage/defaults.json index 5302ff7..93e95c1 100644 --- a/storage/defaults.json +++ b/storage/defaults.json @@ -6,7 +6,8 @@ "locale": "en", "stay_247": "none", "stay_247_mode": "off", - "volume": 100 + "volume": 100, + "announcementChannelId": null }, "descriptions": { "songAnnouncements": "Whether the bot should announce every song in a new message when it starts playing. Set to `true` or `1` to enable.", @@ -14,7 +15,8 @@ "pfp": "What profile picture the bot should use. Presets: `default | dark | light | mono | `.", "locale": "The preferred language of your server.", "stay_247": "24/7 mode channels. Managed automatically by %247 β€” do not edit manually.", - "stay_247_mode": "Controls 247 behaviour. Set via %247 off/on/auto. off = disabled, on = stay but no rejoin on force-kick, auto = stay and always rejoin.", - "volume": "The default playback volume for this server (1-200). Saved automatically when you use %volume. Restored every time the bot joins a channel." + "stay_247_mode": "Controls 247 behaviour. Set via %247 off/on/auto. off = disabled, on = stay but no rejoin on force-kick, auto = stay and always rejoins.", + "volume": "The default playback volume for this server (1-200). Saved automatically when you use %volume. Restored every time the bot joins a channel.", + "announcementChannelId": "The channel where song announcements are sent. Managed automatically β€” do not edit manually." } -} \ No newline at end of file +}