feat: audio filters, rate limiting, stability fixes & new announcement channel

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
This commit is contained in:
NoLogicAlan committed 2026-04-23 17:19:49 +03:00
1 parent c339e32e9c
commit 57f018c815
17 files changed
+468 -232

No files matched your search

+24
View File
@@ -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}>`;
+6
View File
@@ -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
+17 -47
View File
@@ -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);
}
+182 -86
View File
@@ -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;
}
+14 -1
View File
@@ -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; }
+24 -20
View File
@@ -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;
}