diff --git a/commands/debug.mjs b/commands/debug.mjs index d96c41f..25d86e2 100644 --- a/commands/debug.mjs +++ b/commands/debug.mjs @@ -53,14 +53,10 @@ export async function run(msg, data) { }; const MAX_DESC = 4096; - const CODE_WRAP = 12; // "```json\n" (8) + "\n```" (4) + const CODE_WRAP = 12; - // ── Build pages ──────────────────────────────────────────────────────── - // Page 0: summary + compact server list - // Page 1..N: detailed JSON for each server (one per page, or grouped if small) const pages = []; - // Page 0 — Summary const summaryLines = [ `📊 **Summary**`, `Players in map: **${summary.playerMapSize}**`, @@ -73,7 +69,6 @@ export async function run(msg, data) { const s = servers[i]; const status = s.conn === "yes" && !s.destroyed && !s.leaving ? "🟢" : "🔴"; const line = `${status} \`${s.guildname}\` / \`#${s.name}\` — conn:${s.conn} room:${s.roomState} media:${s.mediaPlayer}`; - // Guard against overflow even for the summary if (summaryLines.join("\n").length + line.length + 1 > MAX_DESC - 30) { summaryLines.push(`… and ${servers.length - i} more (see next pages)`); break; @@ -82,7 +77,6 @@ export async function run(msg, data) { } pages.push(summaryLines.join("\n")); - // Pages 1..N — Detailed JSON per-server (group small ones together) { let groupJson = ""; let groupStart = 0; @@ -92,22 +86,20 @@ export async function run(msg, data) { const codeBlock = "```json\n" + groupJson + "\n```"; pages.push(codeBlock.slice(0, MAX_DESC)); groupJson = ""; - groupStart = i; // will be set by outer loop + groupStart = i; }; let i = 0; for (i = 0; i < servers.length; i++) { const singleJson = JSON.stringify(servers[i], null, 2); const candidate = groupJson - ? groupJson.slice(0, -1) + ",\n" + singleJson.slice(1) // merge objects into array-like + ? groupJson.slice(0, -1) + ",\n" + singleJson.slice(1) : singleJson; if (("```json\n" + candidate + "\n```").length > MAX_DESC && groupJson) { - // Current group is full — flush it, start new group with this server pages.push(("```json\n" + groupJson + "\n```").slice(0, MAX_DESC)); groupJson = singleJson; } else if (("```json\n" + candidate + "\n```").length > MAX_DESC) { - // Even a single server is too big — truncate it const budget = MAX_DESC - CODE_WRAP; groupJson = singleJson.slice(0, budget); pages.push(("```json\n" + groupJson + "\n```").slice(0, MAX_DESC)); @@ -121,7 +113,6 @@ export async function run(msg, data) { } } - // ── Single page — no pagination needed ──────────────────────────────── if (pages.length === 1) { const embed = new EmbedBuilder() .setColor(getGlobalColor()) @@ -131,7 +122,6 @@ export async function run(msg, data) { return msg.reply({ embeds: [embed] }); } - // ── Multi-page with reactions ───────────────────────────────────────── const totalPages = pages.length; let currentPage = 0; diff --git a/commands/eval.mjs b/commands/eval.mjs index 9a1a968..b693527 100644 --- a/commands/eval.mjs +++ b/commands/eval.mjs @@ -3,11 +3,9 @@ import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; import { inspect } from "node:util"; -// Auto-remove timer: 1 minute 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 = [ @@ -27,12 +25,8 @@ const RESTRICTED = [ "webhook", ]; -// 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; @@ -88,31 +82,24 @@ async function clean(value) { return output .replace(/`/g, "`\u200b") - .replace(/@/g, "@\u200b") || "undefined"; // Fallback if output is empty + .replace(/@/g, "@\u200b") || "undefined"; } function isSingleExpression(code) { const trimmed = code.trim(); - // Empty code if (!trimmed) return false; - // Block statements — user is writing a full function body if (/^(if|for|while|do|switch|try|catch|finally|with)\s*[\({]/.test(trimmed)) return false; - // Declarations — always multi-statement style if (/^\s*(const|let|var|function\s|class\s)/.test(trimmed)) return false; - // Contains semicolons that look like statement separators (but not inside strings) - // Strip string literals to avoid false positives from semicolons inside strings const stripped = trimmed - .replace(/'(?:[^'\\]|\\.)*'/g, '""') // single-quoted strings - .replace(/"(?:[^"\\]|\\.)*"/g, '""') // double-quoted strings - .replace(/`(?:[^`\\]|\\.)*`/g, '""'); // template literals (simplified) + .replace(/'(?:[^'\\]|\\.)*'/g, '""') + .replace(/"(?:[^"\\]|\\.)*"/g, '""') + .replace(/`(?:[^`\\]|\\.)*`/g, '""'); if (stripped.includes(";")) return false; - // Contains newlines that suggest multiple statements - // (but allow multi-line method chains like `.foo()\n.bar()`) const withoutChains = trimmed.replace(/\.\s*\n/g, "."); if (withoutChains.includes("\n")) return false; @@ -128,12 +115,10 @@ async function runEval(expression, context) { let result, isError = false, type = "undefined"; try { - // Auto-return single expressions so users don't need to write `return` const code = isSingleExpression(expression) ? `return (${expression});` : expression; - // Use eval() — runs in module scope so `this` is the context passed via .call() result = await eval(`(async function() { ${code} })`).call(context); type = result === null ? "null" : typeof result; } catch (e) { @@ -162,21 +147,9 @@ export const command = new CommandBuilder() export async function run(msg, data) { const expression = data.get("expression").value; - // Build a rich context with shorthand variables so eval can access - // everything easily via `this`. `this` = Remix instance merged with - // the extra shortcuts below. - // this.client → Fluxer Client - // this.guilds → this.client.guilds - // this.channels → this.client.channels - // this.users → this.client.users - // this.players → PlayerManager - // this.settings → SettingsManager - // this.msg → the Message wrapper - // this.message → the raw fluxer message object const context = Object.assign({ message: msg?.message, msg, - // Shorthand aliases for convenience guilds: this.client?.guilds, channels: this.client?.channels, users: this.client?.users, @@ -184,11 +157,8 @@ export async function run(msg, data) { settings: this.settingsMgr, }, this); - // 1. Run the evaluation const { output, isError, type, elapsed } = await runEval(expression, context); - // 2. Chunk the output to bypass Discord limits (Max embed description is 4096 chars) - // We use 3800 to leave room for the header and markdown formatting const chunkSize = 3800; const chunks = []; for (let i = 0; i < output.length; i += chunkSize) { @@ -198,25 +168,22 @@ export async function run(msg, data) { const totalPages = chunks.length; let currentPage = 0; - // Helper to build the specific embed page const buildPageContent = (pageIdx, expired = false) => { const title = isError ? this.t(msg, "responses.eval.resultTitleError") : this.t(msg, "responses.eval.resultTitleSuccess"); - // Embed description includes the metadata and the codeblock const typeLabel = this.t(msg, "responses.eval.typeLabel"); const timeLabel = this.t(msg, "responses.eval.timeLabel"); const desc = `**${typeLabel}** \`${type}\` • **${timeLabel}** \`${elapsed}ms\`\n\`\`\`js\n${chunks[pageIdx]}\n\`\`\``.slice(0, 4096); - // Customize footer based on state let footerText = this.t(msg, "responses.eval.pageLabel", { page: pageIdx + 1, total: totalPages }); if (expired) footerText = this.t(msg, "responses.eval.controlsExpired"); else if (totalPages > 1) footerText += " " + this.t(msg, "responses.eval.navigateHint"); else footerText += " " + this.t(msg, "responses.eval.deleteHint"); const embed = new EmbedBuilder() - .setColor(isError ? "#ff0000" : getGlobalColor()) // Red if error, default otherwise + .setColor(isError ? "#ff0000" : getGlobalColor()) .setTitle(title) .setDescription(desc) .setFooter({ text: footerText }) @@ -225,12 +192,9 @@ export async function run(msg, data) { return { embeds: [embed] }; }; - // 3. Send the initial message using the wrapper const replyMsg = await msg.reply(buildPageContent(0)); if (!replyMsg?.message) return; - // 4. Setup React UI - // If it's only 1 page, we just show the Delete button. Otherwise, add arrows. const navEmojis = totalPages > 1 ? ["⬅️", "➡️", "❌"] : ["❌"]; let unobserve = null; let emojiTimeout = null; @@ -239,7 +203,6 @@ export async function run(msg, data) { await replyMsg.message.react(emoji).catch(() => {}); } - // Helper: Clear reactions when time runs out const clearReactions = async () => { try { await replyMsg.message.removeAllReactions(); @@ -252,7 +215,6 @@ export async function run(msg, data) { } }; - // Helper: Reset inactivity timer const resetTimer = () => { clearTimeout(emojiTimeout); emojiTimeout = setTimeout(async () => { @@ -262,15 +224,12 @@ export async function run(msg, data) { }, EMOJI_REMOVE_TIMEOUT); }; - // 5. Start listening for reactions unobserve = replyMsg.onReaction(navEmojis, async (e) => { - // Handle specific actions if (e.emoji_id === "❌") { - // Clean up and delete the message clearTimeout(emojiTimeout); if (unobserve) unobserve(); await replyMsg.message.delete().catch(() => {}); - return; // Exit completely + return; } resetTimer(); @@ -281,7 +240,6 @@ export async function run(msg, data) { currentPage = currentPage < totalPages - 1 ? currentPage + 1 : 0; } - // Update Embed await replyMsg.edit(buildPageContent(currentPage)).catch(() => {}); }); diff --git a/commands/filter.mjs b/commands/filter.mjs index b0d9961..fb72df9 100644 --- a/commands/filter.mjs +++ b/commands/filter.mjs @@ -3,7 +3,6 @@ import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; import { Utils } from "../src/Utils.mjs"; -// ── Filter catalogue ────────────────────────────────────────────────────────── const FILTERS = [ { emoji: "🔇", @@ -177,7 +176,7 @@ const SESSION_MS = 60_000; function mergeFilterPayloads(keys) { const merged = {}; for (const key of keys) { - if (key === "off") continue; // "off" clears everything — handled upstream + if (key === "off") continue; const f = FILTERS.find(f => f.key === key); if (!f || !f.payload || Object.keys(f.payload).length === 0) continue; for (const [category, settings] of Object.entries(f.payload)) { @@ -187,7 +186,6 @@ function mergeFilterPayloads(keys) { return merged; } -// ── Command definition ──────────────────────────────────────────────────────── export const command = new CommandBuilder() .setName("filter") .setDescription( @@ -197,7 +195,6 @@ export const command = new CommandBuilder() .setCategory("music") .addAliases("filters", "fx", "effect"); -// ── Build page embed ────────────────────────────────────────────────────────── function buildPageEmbed(t, msg, page, activeKeys, current) { const totalPages = Math.ceil(FILTERS.length / PAGE_SIZE); const start = page * PAGE_SIZE; @@ -207,7 +204,6 @@ function buildPageEmbed(t, msg, page, activeKeys, current) { ? `🎵 **${Utils.truncate(current.title, 45)}**` : t(msg, "responses.filter.nothingPlayingInline"); - // Show active filter indicators const activeSet = new Set(activeKeys); const lines = pageItems.map(f => { const isActive = activeSet.has(f.key); @@ -219,7 +215,6 @@ function buildPageEmbed(t, msg, page, activeKeys, current) { ? `\n\n${PREV_EMOJI} Prev ${NEXT_EMOJI} Next ${CANCEL_EMOJI} ${t(msg, "responses.filter.closeHint")}` : `\n\n${CANCEL_EMOJI} ${t(msg, "responses.filter.closeHint")}`; - // Build active summary line let activeSummary = ""; if (activeKeys.length > 0) { const activeLabels = activeKeys.map(k => { @@ -243,12 +238,10 @@ function buildPageEmbed(t, msg, page, activeKeys, current) { ; } -// ── Command handler ─────────────────────────────────────────────────────────── export async function run(msg) { const player = await this.getPlayer(msg, false, false, false); if (!player) return; - // Track multiple active filters (stackable) let activeKeys = player.activeFilter?.key ? player.activeFilter.key.split("+").filter(Boolean) : []; @@ -340,10 +333,8 @@ export async function run(msg) { resetTimer(); - // Normalise emoji identifier across Fluxer reaction event shapes const emoji = e.emoji_id ?? e.emoji?.name ?? e.emoji?.id ?? e.emoji; - // ── Navigation ────────────────────────────────────────────────────────── if (emoji === CANCEL_EMOJI) { return close(this.t(msg, "responses.filter.pickerClosed")); } @@ -374,13 +365,12 @@ export async function run(msg) { return; } - // ── Filter selection ──────────────────────────────────────────────────── const filter = FILTERS.find(f => f.emoji === emoji); if (!filter) return; const track = player.queue.getCurrent(); const previousActiveKeys = [...activeKeys]; - if (!track && false) { // pending filters are allowed; keep old fallback block unreachable + if (!track && false) { await menuMsg.edit({ embeds: [buildPageEmbed(this.t.bind(this), msg, page, activeKeys, null)] }).catch(() => {}); @@ -396,20 +386,17 @@ export async function run(msg) { return; } - // Toggle behavior: if already active, remove it; otherwise add it - // "off" always clears everything if (filter.key === "off") { activeKeys = []; } else { const idx = activeKeys.indexOf(filter.key); if (idx !== -1) { - activeKeys.splice(idx, 1); // Toggle off + activeKeys.splice(idx, 1); } else { - activeKeys.push(filter.key); // Toggle on + activeKeys.push(filter.key); } } - // Build merged payload from all active keys const mergedPayload = mergeFilterPayloads(activeKeys); const meta = activeKeys.length > 0 ? { @@ -437,7 +424,6 @@ export async function run(msg) { return; } - // Update active key and refresh embed (player.activeFilter is already updated by applyFilter) activeKeys = meta ? meta.key.split("+") : []; const successMsg = pending @@ -464,7 +450,6 @@ export async function run(msg) { await menuMsg.edit({ embeds: [confirmEmbed] }).catch(() => {}); await Utils.sleep(1200); - // Restore picker (session stays open) if (!settled) { await menuMsg.edit({ embeds: [buildPageEmbed(this.t.bind(this), msg, page, activeKeys, player.queue.getCurrent())] diff --git a/commands/join.mjs b/commands/join.mjs index f2cc625..27133e9 100644 --- a/commands/join.mjs +++ b/commands/join.mjs @@ -35,7 +35,6 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) { return message.reply({ embeds: [embed] }); } - // Guard: moonlink must be ready before we can play anything if (!this.moonlink) { const embed = new EmbedBuilder().setColor(getGlobalColor()) .setDescription(this.t(message, "responses.join.audioNodeConnecting")); @@ -59,7 +58,6 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) { const homeChannelId = String(p._home247Channel ?? activeChannelId).replace(/\D/g, "") || activeChannelId; const guildId = getGuildId(message); - // Check 24/7 mode for this channel const is247 = (() => { try { const raw = this.settingsMgr?.getServer?.(guildId)?.get?.("stay_247"); @@ -67,7 +65,6 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) { } catch (_) { return false; } })(); - // Determine per-channel mode const mode247 = (() => { if (!is247) return "off"; try { @@ -87,7 +84,6 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) { p.destroy(); if (is247 && (mode247 === "on" || mode247 === "auto")) { - // 24/7 mode — auto-rejoin after a delay const rejoinDelay = this.config?.timers?.rejoin247Delay ?? 3_000; const prefix = (() => { try { return this._commands?.getPrefix?.(guildId) ?? "%"; } catch (_) { return "%"; } @@ -105,7 +101,6 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) { } }, rejoinDelay); } else { - // Not 24/7 — send inactivity message const prefix = (() => { try { return this._commands?.getPrefix?.(guildId) ?? "%"; } catch (_) { return "%"; } })(); @@ -125,16 +120,12 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) { message.channel.send({ embeds: [embed] }); }); - // Mark as pending so concurrent commands see the channel is taken, - // but don't add to playerMap until join() succeeds to avoid phantom - // entries inflating the player count. this.players._pendingJoins.add(cleanChannelId); const joiningEmbed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(message, "responses.join.joining")); const statusMsg = await message.reply({ embeds: [joiningEmbed] }); try { await p.join(cleanChannelId); - // Only add to playerMap after join succeeds this.players.playerMap.set(cleanChannelId, p); this.players._pendingJoins.delete(cleanChannelId); const okEmbed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(message, "responses.join.joined", { channel: cid })); @@ -162,11 +153,9 @@ export const command = new CommandBuilder() ); export async function run(message, data) { - // Check if a channel argument was provided (mention like <#123456>, bare ID, or name) const rawArg = data?.get?.("channel")?.value?.trim?.() ?? null; if (rawArg) { - // Parse channel mention <#ID>, bare numeric ID, or channel name const mentionMatch = rawArg.match(/^<#(\d+)>$/); const idMatch = rawArg.match(/^(\d{15,})$/); let resolvedId = null; @@ -176,14 +165,12 @@ export async function run(message, data) { } else if (idMatch) { resolvedId = idMatch[1]; } else { - // Try to look up by name const guildId = cleanId(getGuildId(message)); const allChannels = [ ...(this.client?.channels?.values?.() ?? []) ]; const match = allChannels.find(c => { const cServerId = cleanId(c.guildId ?? c.guild?.id ?? c.server_id ?? c.serverId); - // Fluxer uses numeric channel types: 0=text, 2=voice, 4=category, 5=link const isVoice = c.type === 2; return isVoice && cServerId === guildId && (c.name?.toLowerCase() === rawArg.toLowerCase()); @@ -200,7 +187,6 @@ export async function run(message, data) { return this.players.initPlayer(message, resolvedId); } - // No argument — auto-detect the user's current voice channel const cid = this.players.checkVoiceChannels(message); if (!cid) { diff --git a/commands/lastfm.mjs b/commands/lastfm.mjs index 79b9092..f8858e6 100644 --- a/commands/lastfm.mjs +++ b/commands/lastfm.mjs @@ -23,7 +23,6 @@ export const command = new CommandBuilder() .setRequired(false) ); -// ── Helpers ──────────────────────────────────────────────────────────────────── function notConfigured(msg) { return { @@ -41,7 +40,6 @@ function notLinked(prefix) { }; } -// Valid categories that can be played (without a sub-number) const SIMPLE_CATEGORIES = ["loved", "top", "recent", "albums"]; function buildLastFmTrackMeta(track) { @@ -72,7 +70,6 @@ async function resolveLastFmTrack(player, track, resolveProvider = "yt") { * * @param {object} ctx - The command `this` context (has .lastfm, .getPlayer, .handler, .t) * @param {object} msg - The message object - * @param {string} userId - Discord user ID * @param {string} category - "loved", "top", "recent", or "playlist" * @param {object} [options] * @param {string} [options.period] - Period for top tracks @@ -88,7 +85,6 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = { if (!lastfm || !lastfm.enabled) return msg.reply(notConfigured(msg)); - // Validate category const validCategories = [...SIMPLE_CATEGORIES, "playlist"]; if (!validCategories.includes(category)) { return msg.reply({ @@ -98,7 +94,6 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = { }); } - // Playlist requires an ID if (category === "playlist" && !options.playlistId) { return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( @@ -107,19 +102,15 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = { }); } - // Check if user is linked const user = await lastfm.getUser(userId); if (!user) return msg.reply(notLinked(prefix)); - // Get a player (user must be in a voice channel) const p = await ctx.getPlayer(msg, true, true, true); if (!p) return; - // Fetch tracks from Last.fm const categoryEmoji = { loved: "❤️", top: "📊", recent: "🕐", playlist: "📋", albums: "💿" }[category]; const categoryLabel = { loved: "Loved", top: "Top", recent: "Recent", playlist: "Playlist", albums: "Top Albums" }[category]; - // Show which provider is being used for resolving tracks (if not the default YouTube) const resolveLabel = resolveProvider !== "yt" ? ` via ${resolveProvider.toUpperCase()}` : ""; let statusMsg; @@ -152,7 +143,6 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = { return; } - // Play each track sequentially — first one via play(), rest added to queue let added = 0; let failed = 0; @@ -200,14 +190,12 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = { * @returns {{ category: string, playlistId?: string|number }} */ function parsePlayArgs(msg, data) { - // Try from the token option first let raw = data.get("token")?.value; if (!raw) { const content = msg.message?.content ?? ""; const args = content.split(/\s+/); const playIdx = args.indexOf("play"); if (playIdx >= 0 && args[playIdx + 1]) { - // Collect everything after "play" raw = args.slice(playIdx + 1).join(" "); } } @@ -216,9 +204,6 @@ function parsePlayArgs(msg, data) { const lower = raw.toLowerCase().trim(); - // Sub-provider syntax: "td:top", "sp", "lf:loved" - // Non-lastfm providers only allow "top" (or bare provider defaults to "top") - // Last.fm as resolve provider allows all categories: loved, top, recent, albums, playlist const subMatch = lower.match(/^([a-z]+):\s*(.*)$/); if (subMatch) { const maybeProvider = subMatch[1]; @@ -227,16 +212,13 @@ function parsePlayArgs(msg, data) { const isLastFmProvider = maybeProvider === "lf" || maybeProvider === "lastfm"; if (!rest) { - // No category specified — default based on provider if (isLastFmProvider) { return { category: "", resolveProvider: maybeProvider, showAllCategories: true }; } - // All other providers default to "top" return { category: "top", resolveProvider: maybeProvider }; } if (isLastFmProvider) { - // Last.fm as resolve provider: all categories allowed const playlistMatch = rest.match(/^playlist\s+(\d+)$/); if (playlistMatch) { return { category: "playlist", playlistId: playlistMatch[1], resolveProvider: maybeProvider }; @@ -245,18 +227,14 @@ function parsePlayArgs(msg, data) { return { category: rest, resolveProvider: maybeProvider }; } } else { - // Non-lastfm providers: only "top" allowed if (rest === "top") { return { category: "top", resolveProvider: maybeProvider }; } - // Any other category with a non-lastfm provider is invalid return { category: "", resolveProvider: maybeProvider, invalidCategory: rest }; } } } - // Bare provider without colon: "td", "sp", "yt" → defaults to "top" - // (lf/lastfm as bare provider shows all categories instead) if (PROVIDER_CHOICES.includes(lower)) { const isLastFmProvider = lower === "lf" || lower === "lastfm"; if (isLastFmProvider) { @@ -265,13 +243,11 @@ function parsePlayArgs(msg, data) { return { category: "top", resolveProvider: lower }; } - // "playlist 3" or "playlist 1" const playlistMatch = lower.match(/^playlist\s+(\d+)$/); if (playlistMatch) { return { category: "playlist", playlistId: playlistMatch[1] }; } - // "loved", "top", "recent" if (SIMPLE_CATEGORIES.includes(lower)) { return { category: lower }; } @@ -279,7 +255,6 @@ function parsePlayArgs(msg, data) { return { category: "" }; } -// ── Run ──────────────────────────────────────────────────────────────────────── export async function run(msg, data) { const lastfm = this.lastfm; @@ -290,9 +265,7 @@ export async function run(msg, data) { const userId = msg.message?.author?.id ?? msg.author?.id; switch (action) { - // ── Link ──────────────────────────────────────────────────────────────── case "link": { - // Check if already linked const existing = await lastfm.getUser(userId); if (existing) { return msg.reply({ @@ -302,7 +275,6 @@ export async function run(msg, data) { }); } - // Step 1: Get auth token let token; try { token = await lastfm.getAuthToken(); @@ -314,7 +286,6 @@ export async function run(msg, data) { const authUrl = lastfm.getAuthUrl(token); - // Send auth URL via DM so it's private let sent = false; try { const dm = await msg.author.createDM(); @@ -336,7 +307,6 @@ export async function run(msg, data) { }); sent = true; } catch { - // DM failed — send in channel with a warning } const replyEmbed = new EmbedBuilder() @@ -350,9 +320,7 @@ export async function run(msg, data) { return msg.reply({ embeds: [replyEmbed] }); } - // ── Confirm (completes the auth flow) ────────────────────────────────── case "confirm": { - // Get token from the option, or fall back to parsing the message let tokenValue = data.get("token")?.value; if (!tokenValue) { const rawContent = msg.message?.content ?? ""; @@ -385,7 +353,6 @@ export async function run(msg, data) { }); } - // ── Unlink ───────────────────────────────────────────────────────────── case "unlink": { const user = await lastfm.getUser(userId); if (!user) return msg.reply(notLinked(prefix)); @@ -396,7 +363,6 @@ export async function run(msg, data) { }); } - // ── Toggle scrobbling ────────────────────────────────────────────────── case "scrobble": { const user = await lastfm.getUser(userId); if (!user) return msg.reply(notLinked(prefix)); @@ -414,7 +380,6 @@ export async function run(msg, data) { }); } - // ── Now playing info ─────────────────────────────────────────────────── case "np": { const user = await lastfm.getUser(userId); if (!user) return msg.reply(notLinked(prefix)); @@ -445,7 +410,6 @@ export async function run(msg, data) { return msg.reply({ embeds: [embed] }); } - // ── Profile ──────────────────────────────────────────────────────────── case "profile": { const user = await lastfm.getUser(userId); if (!user) return msg.reply(notLinked(prefix)); @@ -459,7 +423,6 @@ export async function run(msg, data) { }); } - // Sync scrobble count in background (keeps leaderboard fresh) lastfm.syncUserScrobbleCount(userId).catch(() => {}); const embed = new EmbedBuilder() @@ -477,7 +440,6 @@ export async function run(msg, data) { return msg.reply({ embeds: [embed] }); } - // ── Playlists ────────────────────────────────────────────────────────── case "playlists": { const user = await lastfm.getUser(userId); if (!user) return msg.reply(notLinked(prefix)); @@ -514,11 +476,9 @@ export async function run(msg, data) { }); } - // ── Play (loved/top/recent/playlist tracks as queue) ──────────────────── case "play": { const parsed = parsePlayArgs(msg, data); - // Invalid category used with a non-lastfm provider (e.g. "sp:loved", "td:recent") if (parsed.invalidCategory) { return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( @@ -571,7 +531,6 @@ export async function run(msg, data) { }); } - // ── Loved tracks ────────────────────────────────────────────────────── case "loved": { const user = await lastfm.getUser(userId); if (!user) return msg.reply(notLinked(prefix)); @@ -594,7 +553,6 @@ export async function run(msg, data) { return msg.reply({ embeds: [buildTrackList(user.username, "❤️ Loved Tracks", tracks, false, prefix)] }); } - // ── Top tracks ───────────────────────────────────────────────────────── case "top": { const user = await lastfm.getUser(userId); if (!user) return msg.reply(notLinked(prefix)); @@ -617,7 +575,6 @@ export async function run(msg, data) { return msg.reply({ embeds: [buildTrackList(user.username, "📊 Top Tracks", tracks, true, prefix)] }); } - // ── Leaderboard ───────────────────────────────────────────────────── case "leaderboard": case "lb": { let lb; @@ -637,18 +594,14 @@ export async function run(msg, data) { }); } - // Single page — no pagination needed if (lb.totalPages <= 1) { const embed = buildLeaderboardEmbed(lb, 0, prefix); return msg.reply({ embeds: [embed] }); } - // Multi-page with emoji navigation let currentPage = 0; const buildPage = (pageIdx, expired = false) => { - // Fetch for this page index (we pre-load only page 0; - // subsequent pages are fetched on navigation) const footerText = expired ? "Controls expired" : `Page ${pageIdx + 1}/${lb.totalPages} • Use ◀️▶️ to navigate`; @@ -701,7 +654,6 @@ export async function run(msg, data) { currentPage = currentPage < lb.totalPages - 1 ? currentPage + 1 : 0; } - // Fetch the page data from DB try { lb = await lastfm.getLeaderboard(currentPage, 10); } catch { @@ -715,7 +667,6 @@ export async function run(msg, data) { break; } - // ── Recent tracks ────────────────────────────────────────────────────── case "recent": { const user = await lastfm.getUser(userId); if (!user) return msg.reply(notLinked(prefix)); @@ -781,7 +732,6 @@ export async function run(msg, data) { } } -// ── Track list embed builder ────────────────────────────────────────────────── function buildTrackList(username, title, tracks, showPlaycount = false, prefix = "%") { const lines = tracks.map((t, i) => { @@ -802,7 +752,6 @@ function buildTrackList(username, title, tracks, showPlaycount = false, prefix = .setFooter({ text: `💡 Use ${prefix}lastfm play loved to play these!` }); } -// ── Leaderboard embed builder ───────────────────────────────────────────────── function buildLeaderboardEmbed(lb, pageIdx, prefix) { const MEDALS = ["🥇", "🥈", "🥉"]; diff --git a/commands/leave.mjs b/commands/leave.mjs index 1d7f0ec..e39f793 100644 --- a/commands/leave.mjs +++ b/commands/leave.mjs @@ -49,19 +49,12 @@ export async function run(msg, data) { ?? msg.message?.serverId; const cleanGuildId = cleanId(guildId); - // Gather all active players in this guild. - // resolvePlayerGuildId handles players whose _guildId is still null by - // checking the channel cache — critical for the multi-voice use case where - // a player may have been joined before _guildId was written. const client = this.client; const guildPlayers = [...this.players.playerMap.entries()].filter(([mapKey, p]) => { if (p?._destroyed) return false; return resolvePlayerGuildId(p, mapKey, client) === cleanGuildId; }); - // Resolve the target channel to leave: - // 1. If a channel option was provided, use that - // 2. Otherwise, use the user's current voice channel const specifiedChannel = data?.get("channel")?.value; let targetChannelId = null; @@ -72,12 +65,10 @@ export async function run(msg, data) { if (userChannelId) targetChannelId = cleanId(userChannelId); } - // If we still don't have a target channel if (!targetChannelId) { if (guildPlayers.length === 0) { return msg.reply(embed(this.t(msg, "responses.leave.notInVoice"))); } - // User not in voice and no channel specified — list all channels the bot is in const channelList = guildPlayers.map(([mapKey, p]) => { const id = cleanId(p._channelId ?? mapKey); return id ? `<#${id}>` : "`unknown`"; @@ -90,10 +81,6 @@ export async function run(msg, data) { )); } - // Find the player for the target channel. - // Match against both the map key and _channelId because after a voice-move - // these can differ (the map key stays as the original join channel ID while - // _channelId updates to the new channel). const player = this.players.playerMap.get(targetChannelId) ?? guildPlayers.find(([mapKey, p]) => cleanId(p._channelId) === targetChannelId || cleanId(mapKey) === targetChannelId @@ -101,7 +88,6 @@ export async function run(msg, data) { ?? null; if (!player) { - // No player in that channel — check if user picked a non-voice channel if (guildPlayers.length === 0) { return msg.reply(embed(this.t(msg, "responses.leave.notInVoice"))); } @@ -122,7 +108,6 @@ export async function run(msg, data) { const activeChannelId = cleanId(player._channelId) || targetChannelId; const homeChannelId = cleanId(player._home247Channel) || activeChannelId; - // ── 24/7 handling ──────────────────────────────────────────────────────── const set = this.getSettings(msg); const raw = set?.get("stay_247"); const ch247 = (!raw || raw === "none") @@ -131,11 +116,6 @@ export async function run(msg, data) { ? new Set(raw.map(id => cleanId(id)).filter(Boolean)) : new Set([cleanId(raw)]); - // ── Snapshot all 247 auto channels in this guild BEFORE leaving ──────── - // When the bot leaves one channel, the gateway may send a guild-level - // disconnect that kills ALL voice connections in the guild (not just the - // target). By snapshotting beforehand, we can schedule rejoins for every - // 24/7 auto channel that was collateral-disconnected. const other247AutoChannels = [...ch247].filter(id => { if (id === activeChannelId || id === homeChannelId || id === targetChannelId) return false; const mode = get247ChannelMode(set, id); @@ -165,19 +145,13 @@ export async function run(msg, data) { } }, leave247Delay); - // ── Rejoin other 24/7 auto channels that may have been disconnected ── - // If the gateway sent a guild-level leave, all other 24/7 auto channels - // also lost their connections. Schedule a rejoin for each one with a - // staggered delay to avoid overloading the global join queue. if (other247AutoChannels.length > 0) { const rejoinBaseDelay = leave247Delay; const rejoinStagger = this.config?.timers?.rejoin247Delay ?? 3000; for (let i = 0; i < other247AutoChannels.length; i++) { const otherChannelId = other247AutoChannels[i]; const otherPlayer = this.players.playerMap.get(otherChannelId); - // Only rejoin if the player is gone (was collateral-disconnected) if (!otherPlayer || otherPlayer._destroyed) { - // Clean up the dead player from the map if (otherPlayer) { this.players.playerMap.delete(otherChannelId); try { otherPlayer.destroy(); } catch (_) {} @@ -197,8 +171,6 @@ export async function run(msg, data) { } } } else { - // Mode is "on" — bot left, won't rejoin automatically for this channel. - // But still check if other 24/7 auto channels need rejoining. msg.reply(embed(this.t(msg, "responses.leave.left247On", { prefix: set?.get("prefix") ?? "%" }))); if (other247AutoChannels.length > 0) { diff --git a/commands/list.mjs b/commands/list.mjs index b895e84..cac130b 100644 --- a/commands/list.mjs +++ b/commands/list.mjs @@ -41,11 +41,9 @@ export async function run(message, data) { let desc = ""; - // ── Header: track count + remaining time ────────────────────────────── const remaining = p.getQueueRemainingTime(); desc += `📋 **${totalTracks} track${totalTracks !== 1 ? "s" : ""} in queue** • ⏱️ \`${remaining}\`\n`; - // ── Now Playing block ───────────────────────────────────────────────── if (current) { const elapsed = p.getCurrentElapsedDuration(); const total = p.getCurrentDuration(); @@ -60,7 +58,6 @@ export async function run(message, data) { desc += `\n`; - // ── Queue list ──────────────────────────────────────────────────────── if (totalTracks === 0) { desc += this.t(message, "responses.list.emptyInline"); } else { @@ -73,8 +70,6 @@ export async function run(message, data) { let title = vid.title; if (title.length > 45) title = title.slice(0, 42) + "..."; title = link ? `[${title}](${link})` : title; - // Mark the very first item in the queue as "Up Next" — useful after - // a bot recovery or shuffle so the next song's position is obvious. const upNext = (start + i === 0) ? " ▶" : ""; desc += `\`${index}.\` ${title}${upNext} • \`${dur}\`\n`; }); diff --git a/commands/lyrics.mjs b/commands/lyrics.mjs index 9c5b44e..e9709dc 100644 --- a/commands/lyrics.mjs +++ b/commands/lyrics.mjs @@ -24,7 +24,6 @@ export async function run(message) { return message.reply({ embeds: [embed] }); } - // Animated loading spinner let frame = 0; const loadingMsg = await message.reply({ embeds: [ new EmbedBuilder().setColor(getGlobalColor()) @@ -67,25 +66,21 @@ export async function run(message) { const MAX_DESC = 4096; let totalPages = Math.ceil(totalLines / LINES_PER_PAGE); - // Build page payloads — each is the raw lyric lines for that page const pages = []; for (let i = 0; i < totalLines; i += LINES_PER_PAGE) { pages.push(lines.slice(i, i + LINES_PER_PAGE).join("\n")); } - // ── Re-check: if a page's content + header + code block exceeds 4096, re-split - // into smaller chunks so setDescription never throws RangeError. ────────── - const CODE_WRAP = 13; // "```\n" (4) + "\n```" (5) + header-ish overhead + const CODE_WRAP = 13; { const reshaped = []; for (const pageText of pages) { const headerLine = `by *${artist}*${syncIndicator}`; - const overhead = headerLine.length + 1 + 1 + CODE_WRAP; // header + blank + ``` + ``` + const overhead = headerLine.length + 1 + 1 + CODE_WRAP; const budget = MAX_DESC - overhead; if (pageText.length <= budget) { reshaped.push(pageText); } else { - // Split this page's text into chunks that fit const pageLines = pageText.split("\n"); let chunk = ""; for (const ln of pageLines) { @@ -104,7 +99,6 @@ export async function run(message) { totalPages = pages.length; } - // ── Single page — no pagination needed ──────────────────────────────────── if (totalPages === 1) { const headerLine = `by *${artist}*${syncIndicator}`; const descBody = pages[0]; @@ -119,7 +113,6 @@ export async function run(message) { return message.reply({ embeds: [singleEmbed] }); } - // ── Multi-page ──────────────────────────────────────────────────────────── let currentPage = 0; let emojiRemoveTimeout; @@ -177,7 +170,6 @@ export async function run(message) { resetEmojiTimer(); - // Full session close after SESSION_MS setTimeout(() => { clearTimeout(emojiRemoveTimeout); unobserve(); diff --git a/commands/play.mjs b/commands/play.mjs index e442236..cc03404 100644 --- a/commands/play.mjs +++ b/commands/play.mjs @@ -7,10 +7,10 @@ import { playLastFmCategory } from "./lastfm.mjs"; /** * Parse a Last.fm music URL and extract artist and track info. * Supports: - * https://www.last.fm/music/Drake/ICEMAN/Make+Them+Cry - * https://www.last.fm/music/SAJA+BOYS/_/Soda+Pop - * https://www.last.fm/music/Drake/_/Make+Them+Cry ("_" = album placeholder) - * https://www.last.fm/music/Drake (artist only) + * https: + * https: + * https: + * https: * * @param {string} url * @returns {{ artist: string, track: string|null, album: string|null, url: string } | null} @@ -20,8 +20,6 @@ function parseLastFmUrl(url) { const u = new URL(url); if (!/^(?:www\.)?last\.fm$/i.test(u.hostname)) return null; - // Path format: /music/Artist[/Album][/Track] - // Or: /music/Artist/_/Track (underscore = album placeholder) const match = u.pathname.match(/^\/music\/([^/]+)(?:\/([^/]+))?(?:\/([^/]+))?/); if (!match) return null; @@ -33,12 +31,9 @@ function parseLastFmUrl(url) { let album = null; if (segment3) { - // /music/Artist/Album/Track or /music/Artist/_/Track album = segment2 === "_" ? null : segment2; track = segment3; } else if (segment2 && segment2 !== "_") { - // /music/Artist/Track (no album segment) - // Could be an album page or track page — treat as track if short enough track = segment2; } @@ -63,7 +58,6 @@ function isLastFmUrl(str) { } } -// Last.fm provider keywords that trigger special play logic const LASTFM_PLAY_CATEGORIES = ["loved", "top", "recent", "albums"]; /** @@ -73,8 +67,6 @@ const LASTFM_PLAY_CATEGORIES = ["loved", "top", "recent", "albums"]; */ function parseLastFmSubProvider(query) { const value = query.trim(); - // Non-lastfm providers only allow "top" (or bare provider defaults to "top") - // Last.fm as resolve provider allows all categories: loved, top, recent, albums, playlist const subMatch = value.match(/^([a-z]+):\s*(.*)$/i); if (subMatch) { const maybeProvider = subMatch[1].toLowerCase(); @@ -90,12 +82,10 @@ function parseLastFmSubProvider(query) { } if (isLastFmProvider) { - // Last.fm as resolve provider: all categories allowed if (LASTFM_PLAY_CATEGORIES.includes(rest) || rest.startsWith("playlist")) { return { category: rest, resolveProvider: maybeProvider }; } } else { - // Non-lastfm providers: only "top" allowed if (rest === "top") { return { category: "top", resolveProvider: maybeProvider }; } @@ -104,7 +94,6 @@ function parseLastFmSubProvider(query) { } } - // Bare provider without colon: "td", "sp", "yt" → defaults to "top" const lower = value.toLowerCase(); if (PROVIDER_CHOICES.includes(lower)) { const isLastFmProvider = lower === "lf" || lower === "lastfm"; @@ -196,20 +185,11 @@ export async function run(message, data) { const { provider: inlineProvider, query } = parseInlineProvider(rawQuery); const provider = inlineProvider ?? flagProvider ?? "ytm"; - // ── Last.fm URL detection ──────────────────────────────────────────────── - // If the raw query (or extracted query) is a Last.fm URL, parse it to get - // the artist and track name, then play it through the normal search pipeline - // with Last.fm metadata attached for accurate scrobbling. - // - // Examples: - // %play https://www.last.fm/music/Drake/ICEMAN/Make+Them+Cry - // %play https://www.last.fm/music/SAJA+BOYS/_/Soda+Pop if (isLastFmUrl(rawQuery) || isLastFmUrl(query)) { const lfUrl = isLastFmUrl(rawQuery) ? rawQuery : query; const parsed = parseLastFmUrl(lfUrl); if (parsed && parsed.track) { - // We have artist + track — search using the combined query with Last.fm metadata const lastfmTrackMeta = { artist: parsed.artist, name: parsed.track, @@ -237,7 +217,6 @@ export async function run(message, data) { } if (parsed && !parsed.track) { - // Artist-only URL (e.g. /music/Drake) — search for the artist const p = await this.getPlayer(message, true, true, true); if (!p) return; @@ -258,15 +237,11 @@ export async function run(message, data) { } } - // ── Last.fm special provider: %play lastfm:loved / lastfm:top / lastfm:recent / lastfm:playlist 1 ── - // Also supports sub-provider syntax: %play lastfm:td:top (play Last.fm top tracks, search on Tidal) - // Bare provider defaults: %play lastfm:sp → top tracks on Spotify, %play lastfm:td → top tracks on Tidal if (provider === "lastfm" || provider === "lf") { const parsed = parseLastFmSubProvider(query); const lowerQuery = parsed.category; const resolveProvider = parsed.resolveProvider; - // Invalid category used with a non-lastfm provider (e.g. "sp:loved", "td:recent") if (parsed.invalidCategory) { return message.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( @@ -275,7 +250,6 @@ export async function run(message, data) { }); } - // If lf/lastfm used as resolve provider without a category, show help if (!lowerQuery && resolveProvider && (resolveProvider === "lf" || resolveProvider === "lastfm")) { return message.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription([ @@ -291,13 +265,11 @@ export async function run(message, data) { }); } - // Simple categories: lastfm:loved, lastfm:top, lastfm:recent if (LASTFM_PLAY_CATEGORIES.includes(lowerQuery)) { const userId = message.message?.author?.id ?? message.author?.id; return playLastFmCategory(this, message, userId, lowerQuery, { resolveProvider }); } - // Playlist: lastfm:playlist 1 or lastfm:playlist 3 const playlistMatch = lowerQuery.match(/^playlist\s+(\d+)$/); if (playlistMatch) { const userId = message.message?.author?.id ?? message.author?.id; @@ -307,22 +279,15 @@ export async function run(message, data) { }); } - // ── Freeform Last.fm search: %play lastfm:soda pop or %play lastfm:drake make them cry ── - // If the query after lastfm: is NOT a recognized category, treat it as a - // freeform track search on Last.fm. This uses Last.fm's track.search API - // to find the best match, then resolves it for playback. if (lowerQuery && !LASTFM_PLAY_CATEGORIES.includes(lowerQuery) && !lowerQuery.startsWith("playlist")) { const lastfm = this.lastfm; if (lastfm && lastfm.enabled) { - // Try to parse as "track by artist" or "artist - track" first const trackMeta = parseLastFmTrackQuery(query); let searchResult; if (trackMeta) { - // Direct artist+track from the query — use it directly searchResult = { artist: trackMeta.artist, name: trackMeta.name, url: "" }; } else { - // Freeform query — search Last.fm for the best match let statusMsg = null; try { statusMsg = await message.reply({ @@ -346,7 +311,6 @@ export async function run(message, data) { } } - // We have a Last.fm result — play it using the combined query with metadata const lastfmTrackMeta = { artist: searchResult.artist, name: searchResult.name, @@ -394,7 +358,6 @@ export async function run(message, data) { try { statusMsg = await message.reply({ embeds: [searchEmbed] }); } catch (err) { - // Fluxer API timed out sending the status message — continue without it } const playQuery = lastfmTrackMeta @@ -407,7 +370,6 @@ export async function run(message, data) { if (statusMsg) { statusMsg.edit({ embeds: [embed] }).catch(() => {}); } else { - // statusMsg failed to send earlier, fall back to a fresh reply message.reply({ embeds: [embed] }).catch(() => {}); } }); diff --git a/commands/player.mjs b/commands/player.mjs index 2b431d3..831549d 100644 --- a/commands/player.mjs +++ b/commands/player.mjs @@ -8,7 +8,6 @@ export const command = new CommandBuilder() .setDescription("Create an interactive player control panel with live progress", "commands.player") .setCategory("music"); -// Visual states const STATES = { playing: "🎵", paused: "⏸️", @@ -16,7 +15,6 @@ const STATES = { loading: "⏳" }; -// Control layout const CONTROLS = { prev: { emoji: "⏮️", action: "previous", desc: "Previous" }, play: { emoji: "▶️", action: "resume", desc: "Play" }, @@ -32,7 +30,6 @@ const CONTROLS = { close: { emoji: "❌", action: "close", desc: "Close" } }; -// Progress bar characters const PROGRESS = { filled: "▰", empty: "▱", @@ -41,7 +38,6 @@ const PROGRESS = { end: "▕" }; -// Auto-remove timer: 1 minute const EMOJI_REMOVE_TIMEOUT = 60000; export async function run(msg) { @@ -98,7 +94,6 @@ 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("+")) { diff --git a/commands/reload.mjs b/commands/reload.mjs index 411fbc4..b141b3c 100644 --- a/commands/reload.mjs +++ b/commands/reload.mjs @@ -23,7 +23,6 @@ function embed(desc) { const __dirname = path.dirname(new URL(import.meta.url).pathname); const ROOT = path.resolve(__dirname, ".."); -// ── Reload a single command ─────────────────────────────────────────────────── async function reloadCommand(ctx, msg, name) { if (name === "index") return { ok: false, msg: ctx.t(msg, "responses.reload.indexNoReload") }; @@ -34,14 +33,11 @@ async function reloadCommand(ctx, msg, name) { const file = ctx.commandFiles.get(command.uid); if (!file) return { ok: false, msg: ctx.t(msg, "responses.reload.noFileTracked", { name }) }; - // Unregister old command.subcommands.forEach(sub => ctx.runnables.delete(sub.uid)); ctx.handler.removeCommand(command); ctx.runnables.delete(command.uid); ctx.commandFiles.delete(command.uid); - // 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); @@ -63,7 +59,6 @@ async function reloadCommand(ctx, msg, name) { return { ok: true, msg: ctx.t(msg, "responses.reload.reloaded", { name }) }; } -// ── Reload a src/ or audio/ module ─────────────────────────────────────────── async function reloadModule(ctx, msg, filePath, label) { if (!fs.existsSync(filePath)) return { ok: false, msg: ctx.t(msg, "responses.reload.fileNotFound", { label }) }; @@ -75,7 +70,6 @@ async function reloadModule(ctx, msg, filePath, label) { } } -// ── List all module files in a subdirectory ─────────────────────────────────── function allModuleFiles(subdir) { const dir = path.join(ROOT, subdir); if (!fs.existsSync(dir)) return []; @@ -84,7 +78,6 @@ function allModuleFiles(subdir) { .map(f => ({ file: path.join(dir, f), label: `${subdir}/${f}` })); } -// ── Paginated embed helper ──────────────────────────────────────────────────── async function showPaged(msg, title, lines, pageSize = 14) { const pages = []; for (let i = 0; i < lines.length; i += pageSize) @@ -120,7 +113,6 @@ async function showPaged(msg, title, lines, pageSize = 14) { setTimeout(() => { unsub?.(); }, 5 * 60_000); } -// ── Batch results → paginated display ──────────────────────────────────────── async function showResults(msg, results, label) { const ok = results.filter(r => r.ok).length; const bad = results.filter(r => !r.ok).length; @@ -128,11 +120,9 @@ async function showResults(msg, results, label) { await showPaged(msg, `🔄 Reload — ${label}`, [header, "", ...results.map(r => r.msg)]); } -// ── Main ────────────────────────────────────────────────────────────────────── export async function run(msg, data) { const target = (data.get("target")?.value ?? "").trim().toLowerCase(); - // No target — show paginated list of everything reloadable if (!target) { const cmdLines = this.handler.commands.map(c => `📦 \`${c.name}\` *(command)*`); const srcLines = allModuleFiles("src").map(m => `🔧 \`${m.label}\` *(src)*`); @@ -150,7 +140,6 @@ export async function run(msg, data) { return showPaged(msg, this.t(msg, "responses.reload.availableTargetsTitle"), lines); } - // Batch keywords if (target === "commands") { const results = []; for (const c of [...this.handler.commands]) { @@ -187,13 +176,11 @@ export async function run(msg, data) { return showResults(msg, results, "Everything"); } - // Single command by name if (this.handler.commands.some(c => c.name === target)) { const res = await reloadCommand(this, msg, target); return msg.reply(embed(res.msg)); } - // Single src/ or audio/ module by filename (with or without extension/subdir) const allMods = [...allModuleFiles("src"), ...allModuleFiles("audio")]; const mod = allMods.find(m => m.label.toLowerCase() === target || diff --git a/commands/search.mjs b/commands/search.mjs index e357199..895a89d 100644 --- a/commands/search.mjs +++ b/commands/search.mjs @@ -5,7 +5,6 @@ import { PROVIDER_CHOICES, PROVIDER_NAMES } from "../src/constants/providers.mjs const NUMBER_EMOJIS = ["1️⃣","2️⃣","3️⃣","4️⃣","5️⃣","6️⃣","7️⃣","8️⃣","9️⃣"]; const CANCEL_EMOJI = "❌"; -// SESSION_MS is now read from config.timers.searchSessionTimeout (fallback: 30s) function parseInlineProvider(raw) { const match = raw.match(/^([a-z]+):\s*(.+)$/i); @@ -53,7 +52,6 @@ export async function run(msg, data) { const name = PROVIDER_NAMES[provider] ?? "YouTube Music"; - // Send loading embed const channel = msg.channel?.channel ?? msg.message?.channel; if (!channel?.send) return; @@ -79,14 +77,12 @@ export async function run(msg, data) { ).catch(() => null); if (!rawMsg) return; - // Fetch results const res = await p.fetchResults(query, msg.authorId, provider); if (!res?.count) { rawMsg.edit({ embeds: [makeEmbed(this.t(msg, "responses.search.noResults"))] }).catch(() => {}); return; } - // Build results embed const results = p.searches.get(msg.authorId) ?? []; const reactions = NUMBER_EMOJIS.slice(0, res.count); @@ -107,7 +103,6 @@ export async function run(msg, data) { )] }).catch(() => {}); - // Add reactions for (const emoji of [...reactions, CANCEL_EMOJI]) { await rawMsg.react(emoji).catch(() => {}); } @@ -127,7 +122,6 @@ 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 — normalise across Fluxer reaction event shapes const reactorId = e.user_id ?? e.userId ?? e.user?.id ?? null; if (reactorId && reactorId !== authorId) return; @@ -157,7 +151,6 @@ export async function run(msg, data) { }).catch(() => {}); }); - // Read session timeout from config (fallback 30 s) const SESSION_MS = this.config?.timers?.searchSessionTimeout ?? 30_000; const timer = setTimeout(() => { unobserve(); @@ -165,5 +158,5 @@ export async function run(msg, data) { rawMsg.edit({ embeds: [makeEmbed(this.t(msg, "responses.search.timedOut"), this.t(msg, "responses.search.sessionClosed"), `${name} — Search Results`)] }).catch(() => {}); - }, SESSION_MS); // configurable via config.timers.searchSessionTimeout + }, SESSION_MS); } diff --git a/commands/servers.mjs b/commands/servers.mjs index e242a96..3fb3b40 100644 --- a/commands/servers.mjs +++ b/commands/servers.mjs @@ -8,13 +8,11 @@ export const command = new CommandBuilder() .setRequirement(r => r.setOwnerOnly(true)) .setCategory("util"); -// Auto-remove timer: 1 minute const EMOJI_REMOVE_TIMEOUT = 60000; export async function run(msg) { const guilds = [...this.client.guilds.values()]; - // Fallback if the bot is in 0 servers if (guilds.length === 0) { const emptyEmbed = new EmbedBuilder() .setColor(getGlobalColor()) @@ -27,8 +25,6 @@ export async function run(msg) { const MAX_DESC = 4096; const pages = []; - // Build pages dynamically — each page accumulates lines until it would - // exceed the 4096-char description limit, then starts a new page. let currentLines = []; let currentLen = 0; @@ -37,7 +33,7 @@ export async function run(msg) { let name = g.name || "unknown"; if (name.length > 40) name = name.slice(0, 37) + "..."; const line = `${i + 1}. **${name}** (\`${g.id}\`)`; - const addedLen = line.length + (currentLines.length ? 1 : 0); // +1 for \n + const addedLen = line.length + (currentLines.length ? 1 : 0); if (currentLen + addedLen > MAX_DESC - 20 && currentLines.length > 0) { pages.push(currentLines.join("\n")); @@ -53,7 +49,6 @@ export async function run(msg) { let currentPage = 0; - // Helper function to generate the embed for a specific page const buildPageContent = (pageIdx, expired = false) => { const embed = new EmbedBuilder() .setColor(getGlobalColor()) @@ -71,10 +66,8 @@ export async function run(msg) { return { embeds: [embed] }; }; - // Send the initial message using the framework's wrapper const replyMsg = await msg.reply(buildPageContent(0)); - // Safety check and single-page exit if (!replyMsg?.message) return; if (totalPages <= 1) return; @@ -82,12 +75,10 @@ export async function run(msg) { let unobserve = null; let emojiTimeout = null; - // Add reactions for (const emoji of navEmojis) { await replyMsg.message.react(emoji).catch(() => {}); } - // Helper: Clear all reactions (matches player.mjs fallback logic) const clearReactions = async () => { try { await replyMsg.message.removeAllReactions(); @@ -100,7 +91,6 @@ export async function run(msg) { } }; - // Helper: Reset the expiration timer const resetTimer = () => { clearTimeout(emojiTimeout); emojiTimeout = setTimeout(async () => { @@ -110,22 +100,17 @@ export async function run(msg) { }, EMOJI_REMOVE_TIMEOUT); }; - // Start listening for reactions using the framework's native listener unobserve = replyMsg.onReaction(navEmojis, async (e) => { - resetTimer(); // Reset the 1-minute timer when interacting + resetTimer(); if (e.emoji_id === "⬅️") { - // Go backward (loops to the end if on the first page) currentPage = currentPage > 0 ? currentPage - 1 : totalPages - 1; } else if (e.emoji_id === "➡️") { - // Go forward (loops to the beginning if on the last page) currentPage = currentPage < totalPages - 1 ? currentPage + 1 : 0; } - // Update the embed using the framework's native edit method await replyMsg.edit(buildPageContent(currentPage)).catch(() => {}); }); - // Start the initial countdown resetTimer(); } \ No newline at end of file diff --git a/commands/settings.mjs b/commands/settings.mjs index 7f3b613..9a9ad40 100644 --- a/commands/settings.mjs +++ b/commands/settings.mjs @@ -11,7 +11,6 @@ function embed(desc, opts = {}) { } /** Build a rich embed with fields for the 24/7 status panel. - * Fluxer EmbedBuilder does not have addField() (that's discord.js). * Instead, we build the base embed with EmbedBuilder, call .toJSON() * to get the raw object, then attach a `fields` array directly. */ @@ -21,7 +20,6 @@ function richEmbed(fields, opts = {}) { if (opts.description) b.setDescription(opts.description); if (opts.footer) b.setFooter({ text: opts.footer }); if (opts.iconURL) b.setAuthor({ name: opts.title || "\u200b", iconURL: opts.iconURL }); - // EmbedBuilder doesn't have addField — use .toJSON() + raw fields const raw = b.toJSON(); raw.fields = fields.map(f => ({ name: f.name, @@ -31,7 +29,6 @@ function richEmbed(fields, opts = {}) { return { embeds: [raw] }; } -// ── Constants ───────────────────────────────────────────────────────────────── const SHORTCUTS = { prefix: "prefix", @@ -54,7 +51,6 @@ const VOLUME_MIN = 1; const VOLUME_MAX = 200; const MAX_247_CHANNELS = 10; -// ── Helpers ─────────────────────────────────────────────────────────────────── /** Extract clean numeric channel ID from any format */ function cleanId(raw) { @@ -103,7 +99,6 @@ function getGuildName(message) { return message.message?.guild?.name ?? message.channel?.guild?.name ?? "this server"; } -// ── 24/7 helpers ────────────────────────────────────────────────────────────── /** * Get the 24/7 mode for a specific channel. @@ -120,7 +115,6 @@ function get247ChannelMode(set, channelId) { const perChannel = modes[channelId]; if (perChannel === "on" || perChannel === "auto" || perChannel === "off") return perChannel; } - // Fallback: guild-wide mode (legacy) const guildMode = set.get("stay_247_mode") ?? "off"; return guildMode; } @@ -137,7 +131,6 @@ function set247ChannelMode(set, channelId, mode) { if (!modes || typeof modes !== "object" || Array.isArray(modes)) modes = {}; modes[channelId] = mode; set.set("stay_247_modes", modes); - // Also update guild-wide mode for backward compat with older code set.set("stay_247_mode", mode); } @@ -154,7 +147,6 @@ function remove247ChannelMode(set, channelId, currentChannels) { if (!modes || typeof modes !== "object" || Array.isArray(modes)) return; delete modes[channelId]; set.set("stay_247_modes", modes); - // Update guild-wide mode to match the first remaining channel, or "off" if (currentChannels.size === 0) { set.set("stay_247_mode", "off"); } else { @@ -177,8 +169,6 @@ function get247Channels(set) { } function save247Channels(set, channels) { - // Only keep valid Fluxer IDs — strip anything that isn't - // a proper channel ID (e.g. garbage from DB corruption). const arr = [...channels].filter(id => id && isValidFluxerId(id)); set.set("stay_247", arr.length > 0 ? arr : "none"); } @@ -239,7 +229,6 @@ function build247StatusPanel(set, ctx, message, t, guildId) { }); } - // Simple per-channel list: emoji + channel mention + mode const lines = channels.map(chId => { const mode = get247ChannelMode(set, chId); const chName = resolveChannelName(ctx.client, chId); @@ -288,7 +277,6 @@ function build247EnabledPanel(set, channelId, mode, joined, ctx, guildId, t) { const chName = resolveChannelName(ctx.client, channelId); const label = chName ? `**${chName}** <#${channelId}>` : `<#${channelId}>`; - // Build simple list of all saved channels const lines = channels.map(id => { const m = get247ChannelMode(set, id); const n = resolveChannelName(ctx.client, id); @@ -420,7 +408,6 @@ async function handle247(ctx, message, value) { const guildId = getGuildId(message); const mode = value.toLowerCase().trim(); - // Normalise legacy true/false const resolved = mode === "true" ? "auto" : mode === "false" ? "off" : mode; if (!["off", "on", "auto"].includes(resolved)) { @@ -429,7 +416,6 @@ async function handle247(ctx, message, value) { )); } - // ── OFF ─────────────────────────────────────────────────────────────────── if (resolved === "off") { if (!guildId) return message.reply(embed(ctx.t(message, "responses.settings.noServer"))); @@ -458,7 +444,6 @@ async function handle247(ctx, message, value) { return message.reply(build247DisabledPanel(set, id, guildId, t247)); } - // Not in a channel — disable all for this guild save247Channels(set, new Set()); set.set("stay_247_mode", "off"); set.set("stay_247_modes", {}); @@ -488,7 +473,6 @@ async function handle247(ctx, message, value) { })); } - // ── ON / AUTO ───────────────────────────────────────────────────────────── if (!guildId) return message.reply(embed(ctx.t(message, "responses.settings.noServer"))); const userChannelId = ctx.players.checkVoiceChannels(message); @@ -498,9 +482,6 @@ async function handle247(ctx, message, value) { )); } - // Save only the channel the user explicitly toggled. - // Multi-voice 24/7 should be opt-in per voice channel, not "whatever - // channels the bot currently happens to be in". const id = cleanId(userChannelId); const channels = get247Channels(set); if (!channels.has(id) && channels.size >= MAX_247_CHANNELS) { @@ -540,7 +521,6 @@ async function handle247(ctx, message, value) { } } -// ── Per-setting validation & apply ─────────────────────────────────────────── /** * Validate and save a setting value. @@ -548,7 +528,6 @@ async function handle247(ctx, message, value) { * For stay_247, replies directly and always returns null. */ async function applySet(ctx, message, set, key, rawValue) { - // Boolean settings if (BOOL_SETTINGS.has(key)) { const bool = parseBool(rawValue); if (bool === null) { @@ -558,13 +537,11 @@ async function applySet(ctx, message, set, key, rawValue) { return null; } - // 24/7 mode — replies on its own if (key === "stay_247") { await handle247(ctx, message, rawValue); return null; } - // Volume if (key === "volume") { const num = parseInt(rawValue, 10); if (isNaN(num) || num < VOLUME_MIN || num > VOLUME_MAX) { @@ -574,7 +551,6 @@ async function applySet(ctx, message, set, key, rawValue) { return null; } - // Locale if (key === "locale") { if (!VALID_LOCALES.has(rawValue)) { return ctx.t(message, "responses.settings.invalidLocale", { @@ -583,14 +559,11 @@ async function applySet(ctx, message, set, key, rawValue) { }); } set.set(key, rawValue); - // Invalidate locale cache so the new locale takes effect immediately - // without requiring a bot reboot. const guildId = getGuildId(message); if (guildId) ctx.locale.invalidateCache(guildId); return null; } - // Prefix if (key === "prefix") { if (!rawValue || rawValue.length > 5) { return ctx.t(message, "responses.settings.prefixLength"); @@ -600,7 +573,6 @@ async function applySet(ctx, message, set, key, rawValue) { } } - // General: run the runnable hook if present if (runnables[key]) { const err = runnables[key].call(ctx, rawValue, { msg: message }); if (err) return `❌ ${err}`; @@ -610,12 +582,10 @@ async function applySet(ctx, message, set, key, rawValue) { return null; } -// ── Shortcut handler (%prefix, %pfx, %247) ─────────────────────────────────── async function handleShortcut(ctx, message, settingKey, valueTokens) { const set = ctx.getSettings(message); - // GET (no value provided) — show rich 24/7 panel if (valueTokens.length === 0) { if (settingKey === "stay_247") { const t247 = ctx.locale?.translate?.bind(ctx.locale); @@ -625,23 +595,18 @@ async function handleShortcut(ctx, message, settingKey, valueTokens) { return message.reply(embed(`\`${settingKey}\` → ${displayValue(settingKey, val)}`)); } - // SET const rawValue = valueTokens.join(" "); const err = await applySet(ctx, message, set, settingKey, rawValue); if (err) return message.reply(embed(err)); - // handle247 replies on its own if (settingKey !== "stay_247") { const val = set.get(settingKey); return message.reply(embed(ctx.t(message, "responses.settings.setSuccess", { label: settingKey, value: displayValue(settingKey, val) }))); } } -// ── Command definition ──────────────────────────────────────────────────────── export const command = function() { - // Populate valid locales from the Locale instance so the list stays - // in sync when new locale files are added to storage/locales/bot/. if (this.locale) { VALID_LOCALES = this.locale.availableLocales(); } @@ -737,13 +702,11 @@ export const command = function() { ); }; -// ── Command runner ──────────────────────────────────────────────────────────── export async function run(message, data) { const set = this.getSettings(message); const cmd = data.commandId || "getSettings"; - // ── Shortcut commands (%prefix, %pfx, %247) ─────────────────────────────── if (cmd?.startsWith("shortcut_")) { const alias = cmd.replace("shortcut_", ""); const settingKey = SHORTCUTS[alias]; @@ -754,7 +717,6 @@ export async function run(message, data) { return handleShortcut(this, message, settingKey, tokens); } - // ── Inline shortcut: %settings [value] ──────────────────────────── const raw = (message.content ?? message.message?.content ?? "").trim(); const prefix = set.get("prefix") ?? "%"; const body = raw.startsWith(prefix) ? raw.slice(prefix.length).trim() : raw; @@ -766,7 +728,6 @@ export async function run(message, data) { const settingKey = data.get("setting")?.value; - // ── set ─────────────────────────────────────────────────────────────────── if (cmd === "setSettings") { const rawValue = data.get("value")?.value; @@ -780,13 +741,12 @@ export async function run(message, data) { const err = await applySet(this, message, set, settingKey, rawValue); if (err) return message.reply(embed(err)); - if (settingKey === "stay_247") return; // handle247 replied already + if (settingKey === "stay_247") return; const newVal = set.get(settingKey); return message.reply(embed(this.t(message, "responses.settings.setSuccess", { label: prettifySettingLabel(settingKey), value: displayValue(settingKey, newVal) }))); } - // ── get ─────────────────────────────────────────────────────────────────── if (cmd === "getSettings") { if (settingKey) { if (settingKey === "stay_247") { @@ -800,18 +760,15 @@ export async function run(message, data) { return message.reply(embed(reply)); } - // List all settings const d = set.getAll(); const guildName = getGuildName(message); - // Use the Fluxer CDN raw property pattern (guild.icon is a hash string, not a URL). - // guild.iconURL() is a method that does not exist on @fluxerjs/core Guild objects. const rawGuild = message.message?.guild; const iconUrl = rawGuild?.icon ? `https://cdn.fluxer.app/icons/${rawGuild.id}/${rawGuild.icon}.webp` : null; const lines = Object.entries(d) - .filter(([k]) => k !== "stay_247_mode") // surfaced inline with stay_247 + .filter(([k]) => k !== "stay_247_mode") .map(([k]) => { if (k === "stay_247") { return `• **24/7 mode** — ${format247Status(set, this.locale?.translate?.bind(this.locale), getGuildId(message))}`; @@ -826,13 +783,11 @@ export async function run(message, data) { )); } - // ── reset ───────────────────────────────────────────────────────────────── if (cmd === "resetSettings") { if (!this.settingsMgr.isOption(settingKey)) { return message.reply(embed(this.t(message, "responses.settings.unknownSetting", { setting: settingKey }))); } set.reset(settingKey); - // Invalidate locale cache if the locale setting was reset if (settingKey === "locale") { const guildId = getGuildId(message); if (guildId) this.locale.invalidateCache(guildId); @@ -843,7 +798,6 @@ export async function run(message, data) { )); } - // ── help ────────────────────────────────────────────────────────────────── if (cmd === "helpSettings") { const pfx = set.get("prefix") ?? "%"; diff --git a/commands/stats.mjs b/commands/stats.mjs index d352d96..cdbe65a 100644 --- a/commands/stats.mjs +++ b/commands/stats.mjs @@ -9,7 +9,6 @@ export const command = new CommandBuilder() .addAliases("info") .setCategory("util"); -// ── User count cache ────────────────────────────────────────────────────────── const CACHE_TTL_MS = 5 * 60 * 1000; @@ -97,20 +96,15 @@ function getLivePlayerCount(playerMap) { return live; } -// ── Guild count helper (paginated REST) ─────────────────────────────────────── -// client.guilds.size only reflects guilds Fluxer has cached — which is -// but caps at 200 per page, so we paginate until we get them all. let cachedGuildCount = null; let guildCacheExpiresAt = 0; async function getGuildCount(client) { - // Return cached value if still fresh if (cachedGuildCount !== null && Date.now() < guildCacheExpiresAt) { return cachedGuildCount; } - // Paginate through /users/@me/guilds try { let total = 0; let after = null; @@ -119,12 +113,11 @@ async function getGuildCount(client) { const url = "/users/@me/guilds?limit=200" + (after ? "&after=" + after : ""); const chunk = await client.rest.get(url); - // chunk should be an array; guard against null/non-array responses if (!Array.isArray(chunk) || chunk.length === 0) break; total += chunk.length; - if (chunk.length < 200) break; // last page + if (chunk.length < 200) break; after = chunk[chunk.length - 1].id; } @@ -133,13 +126,11 @@ async function getGuildCount(client) { guildCacheExpiresAt = Date.now() + CACHE_TTL_MS; return total; } catch { - // REST failed — fall back to local cache if (typeof client.guilds?.size === "number") return client.guilds.size; return Object.keys(client.guilds ?? {}).length; } } -// ── Embed builder ───────────────────────────────────────────────────────────── function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount, linkedUsers, ping, uptime, comHash, comLink, reason, footer, loading, lastfmEnabled }) { const num = (v) => Utils.formatNumber(v); @@ -178,14 +169,13 @@ function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount, return builder; } -// ── Runner ──────────────────────────────────────────────────────────────────── export async function run(message) { const lastfm = this.lastfm; const lastfmEnabled = lastfm?.enabled ?? false; const shared = { - guildCount: cachedGuildCount ?? this.client.guilds.size, // use cache or local fallback for instant reply + guildCount: cachedGuildCount ?? this.client.guilds.size, playerCount: getLivePlayerCount(this.players.playerMap), scrobbleCount: 0, linkedUsers: 0, @@ -208,7 +198,6 @@ export async function run(message) { }); const ping = Date.now() - start; - // Fetch everything in parallel including the real paginated guild count const [users, scrobbleCount, linkedUsers, guildCount] = await Promise.all([ getUserCount(this.client), scrobblePromise, diff --git a/commands/test.mjs b/commands/test.mjs index 8fe269d..9804265 100644 --- a/commands/test.mjs +++ b/commands/test.mjs @@ -16,10 +16,8 @@ export async function run(msg, data) { const channelCounts = new Map(); - // Use VoiceStateCache API for both humans and bots const cache = this.voiceCache ?? this.observedVoiceUsers; if (cache) { - // Humans if (typeof cache.iterateHumanUsers === "function") { for (const [, state] of cache.iterateHumanUsers()) { if (state.guildId !== guild.id) continue; @@ -31,7 +29,6 @@ export async function run(msg, data) { channelCounts.set(state.channelId, (channelCounts.get(state.channelId) ?? 0) + 1); } } - // Bots if (typeof cache.iterateBotUsers === "function") { for (const [, state] of cache.iterateBotUsers()) { if (state.guildId !== guild.id) continue; @@ -67,7 +64,6 @@ export async function run(msg, data) { for (const [channelId, total] of channelCounts) { const name = await getChannelName(channelId); const entry = this.t(msg, "responses.test.channelEntry", { name, count: total }); - // Guard against 4096-char embed description limit if (desc.length + entry.length > 4080) break; desc += entry; } diff --git a/commands/vote.mjs b/commands/vote.mjs index 37a2f41..f12a660 100644 --- a/commands/vote.mjs +++ b/commands/vote.mjs @@ -4,7 +4,6 @@ import { getGlobalColor } from "../src/MessageHandler.mjs"; import { Utils } from "../src/Utils.mjs"; import { FLUXERLIST, buildVoteLink } from "../src/constants/API.mjs"; -// Auto-remove timer for reaction navigation: 60 seconds const EMOJI_REMOVE_TIMEOUT = 60_000; export const command = new CommandBuilder() @@ -35,7 +34,6 @@ export const command = new CommandBuilder() .setRequired(false) ); -// ── Helpers ──────────────────────────────────────────────────────────────────── function notConfigured(prefix) { return { @@ -97,7 +95,6 @@ function buildVotersEmbed(voters, total, page, limit, type, resourceId, expired return { embeds: [embed] }; } -// ── Run ──────────────────────────────────────────────────────────────────────── export async function run(msg, data) { const fluxerlist = this.fluxerlist; @@ -108,7 +105,6 @@ export async function run(msg, data) { const page = data.get("page")?.value ?? 1; switch (action) { - // ── Info — Show vote link & FluxerList info ──────────────────────────────── case "info": { const resolvedType = type || "bot"; const id = resourceId || (resolvedType === "server" ? fluxerlist?.serverId : fluxerlist?.botId); @@ -132,7 +128,6 @@ export async function run(msg, data) { }); } - // Use slug for website links (slugs work on the website; numeric IDs don't) const slug = resourceId || (resolvedType === "server" ? fluxerlist?.serverSlug : fluxerlist?.botSlug); const voteUrl = slug ? buildVoteLink(resolvedType, slug) : null; const label = resolvedType === "server" ? "Server" : "Bot"; @@ -158,7 +153,6 @@ export async function run(msg, data) { return msg.reply({ embeds: [embed] }); } - // ── Check / Voters — Show voter list ─────────────────────────────────────── case "check": case "voters": { if (!fluxerlist || !fluxerlist.enabled) return msg.reply(notConfigured(prefix)); @@ -168,7 +162,6 @@ export async function run(msg, data) { if (!id) return msg.reply(noResourceId(resolvedType, prefix)); - // Fetch the first page let voterData; try { voterData = await fluxerlist.getVoters(resolvedType, id, { page, limit: 20 }); @@ -180,7 +173,6 @@ export async function run(msg, data) { }); } - // No voters at all if (voterData.total === 0) { return msg.reply({ embeds: [new EmbedBuilder() @@ -191,13 +183,11 @@ export async function run(msg, data) { const totalPages = Math.max(1, Math.ceil(voterData.total / 20)); - // Single page — no navigation needed if (totalPages <= 1) { const embed = buildVotersEmbed(voterData.voters, voterData.total, voterData.page, 20, resolvedType, id); return msg.reply(embed); } - // Multi-page — add emoji navigation let currentPage = voterData.page; const buildPage = (pageIdx, expired = false) => { @@ -248,7 +238,6 @@ export async function run(msg, data) { currentPage = currentPage < totalPages ? currentPage + 1 : 1; } - // Fetch the new page data try { voterData = await fluxerlist.getVoters(resolvedType, id, { page: currentPage, limit: 20 }); } catch { diff --git a/index.mjs b/index.mjs index e0bba49..7e3dd51 100644 --- a/index.mjs +++ b/index.mjs @@ -50,7 +50,6 @@ function mkEmbed(desc) { export class Remix { constructor() { - // ── Config ─────────────────────────────────────────────────────────────── let config; try { config = JSON.parse(fs.readFileSync("config.json", "utf8")); @@ -70,10 +69,8 @@ export class Remix { } this.config = config; - // Apply embed color from config globally setGlobalColor(config.embedColor); - // ── Locale (i18n) ──────────────────────────────────────────────────────── this.locale = new Locale(); this.locale.load(); @@ -86,7 +83,6 @@ export class Remix { const presenceContents = config.presenceContents ?? []; const presenceInterval = config.presenceInterval ?? 30_000; - // ── Timers config ───────────────────────────────────────────────────────── const timers = config.timers ?? {}; this.T = { aloneCheckInterval: timers.aloneCheckInterval ?? 30_000, @@ -96,11 +92,6 @@ export class Remix { intentionalLeaveTTL: timers.intentionalLeaveTTL ?? 10_000, }; - // ── Fluxer Client ──────────────────────────────────────────────────────── - // Fluxer does NOT support intents — the value is always sent as 0 in the - // gateway IDENTIFY payload regardless of what you set here. Setting a - // non-zero value only produces a warning unless suppressIntentWarning - // is true. Always use intents: 0 for Fluxer bots. const client = new Client({ intents: 0, suppressIntentWarning: true, @@ -142,7 +133,6 @@ export class Remix { client.setMaxListeners(50); this.client = client; - // ── VoiceManager initialization (MUST be before login) ───────────────── try { getVoiceManager(client); logger.player("[Startup] VoiceManager initialized before login."); @@ -150,17 +140,12 @@ export class Remix { logger.warn("[Startup] VoiceManager pre-login init failed:", e.message); } - // ── Message & Settings handlers ────────────────────────────────────────── const messages = new MessageHandler(this.client); this.messages = messages; const settings = new RemoteSettingsManager(config.mysql, "./storage/defaults.json"); this.settingsMgr = settings; - // Override the default prefix with config.json value if set. - // This ensures that when the bot joins a NEW server (no DB row yet), it uses - // the config prefix instead of the hardcoded "%" from defaults.json. - // Existing servers keep whatever prefix they already have in the DB. const configPrefix = config.prefix ?? null; if (configPrefix && settings.defaults) { settings.defaults.prefix = configPrefix; @@ -168,11 +153,6 @@ export class Remix { this.locale.bind(this.settingsMgr); - // ── Command handler ────────────────────────────────────────────────────── - // config.prefix from config.json overrides the defaults.json prefix. - // This way, if you run multiple bots in the same server (e.g. Remix + test bot), - // each can have its own default prefix (Remix=%, test bot=!) without needing - // a separate database or manual %prefix per server. const commands = new CommandHandler(messages, configPrefix); this.handler = commands; @@ -181,7 +161,6 @@ export class Remix { commands.setLocale(this.locale); messages.setLocale(this.locale); - // ── Help command ────────────────────────────────────────────────────────── new HelpCommand(commands, messages, (msg) => this.getSettings(msg)).register(); commands.onPing = (msg) => { @@ -201,29 +180,16 @@ export class Remix { }; commands.owners = config.owners ?? []; - // ── MoonlinkManager (placeholder) ─────────────────────────────────────── this.moonlink = null; let moonlinkInitialised = false; - // ── Voice state tracking — indexed cache with LRU eviction ────────── - // Replaces raw observedVoiceUsers/observedVoiceBots Maps with O(1) - // channel-member lookups, composite keys, and bounded memory. this.voiceCache = new VoiceStateCache({ maxUsers: 50_000, maxBots: 10_000 }); - // ── Backward-compat aliases (deprecated — use voiceCache directly) ─── - // observedVoiceUsers iterates HUMAN users only (backward compat). - // observedVoiceBots iterates BOT users only (backward compat). - // Previously both pointed to the same VoiceStateCache, which caused - // observedVoiceBots to return human users instead of bots. - // We create thin wrapper objects that delegate to the correct - // internal indexes while preserving the Map-like interface. - this.observedVoiceUsers = this.voiceCache; // default iterator = human users + this.observedVoiceUsers = this.voiceCache; this.observedVoiceBots = createBotView(this.voiceCache); - // ── Caches ─────────────────────────────────────────────────────────────── - // _announcementChannelCache: TTL-based (5 min), auto-evicts stale entries this._announcementChannelCache = new Map(); - this._announcementChannelTTL = 5 * 60 * 1000; // 5 min + this._announcementChannelTTL = 5 * 60 * 1000; setInterval(() => { const now = Date.now(); for (const [k, v] of this._announcementChannelCache) { @@ -232,34 +198,20 @@ export class Remix { }, 60_000); this.intentionalLeaves = new Map(); - // ── Gateway Handler ───────────────────────────────────────────────────── - // Handles raw WS gateway events, voice-state tracking, presence rotation, - // and high-level Fluxer event handlers (GuildCreate, GuildDelete, - // VoiceStateUpdate). this.gatewayHandler = new GatewayHandler(this); - // Register GuildCreate, GuildDelete, VoiceStateUpdate handlers now so they - // are active before the first Ready event fires. this.gatewayHandler.setupEventHandlers(); - // ── Last.fm Manager ───────────────────────────────────────────────────── - // Handles Last.fm API auth, scrobbling, and user data. this.lastfm = new LastFmManager(config.lastfm, config.mysql); - // ── FluxerList Manager ────────────────────────────────────────────────── - // Handles FluxerList API voter data queries. this.fluxerlist = new FluxerListManager(config.fluxerlist); - // ── Settings ready callback ────────────────────────────────────────────── settings.on("ready", () => { initLogger(config); logger.settings("[settings] Loaded from DB."); for (const [guildId, serverSettings] of settings.guilds) { const val = serverSettings.get("stay_247"); if (!val || val === "none") continue; - // ── Sanitise stay_247 values ──────────────────────────────────────── - // Strip any value that isn't a valid Fluxer ID (>= 15 digits). - // This catches corruption from old JSON_SET paths or bad data. const rawArr = Array.isArray(val) ? val : [val]; const cleaned = rawArr .map(id => String(id).replace(/\D/g, "")) @@ -276,10 +228,6 @@ export class Remix { ); } - // ── Migrate guild-wide stay_247_mode → per-channel stay_247_modes ── - // If stay_247_modes doesn't exist yet but stay_247_mode does, create - // the per-channel map from the guild-wide mode so all channels inherit - // the same mode (backward compatible). const modesMap = serverSettings.get("stay_247_modes"); if (!modesMap || typeof modesMap !== "object") { const guildMode = serverSettings.get("stay_247_mode") ?? "off"; @@ -298,34 +246,19 @@ export class Remix { }); - // ── Bot ready ───────────────────────────────────────────────────────────── client.on(Events.Ready, async () => { try { logger.player("Logged in as " + (client.user?.username ?? "bot")); - // ── Attach proactive error handlers on WS shards ─────────────────── - // @fluxerjs/ws throws "WebSocket error" on socket close/reconnect. - // Without an error handler on the WS object, this escalates to - // uncaughtException and produces noisy stack traces. By attaching - // .on("error") handlers on every shard's WebSocket, we catch the - // error at the source and log it cleanly instead. this._attachWsErrorHandlers(); - // VoiceManager was already initialized before login (required for - // VOICE_STATES_SYNC event registration). No need to re-initialize here. const botId = client.user?.id ?? "0"; - // Set the bot ID on all managers that use the shared MySQL database. - // This isolates each bot's data (settings, Last.fm users, Redis channels) - // so multiple bots can share the same database without conflicts. await this.settingsMgr.setBotId(botId); await this.lastfm.setBotId(botId); this.dashboard.setBotId(botId); - // MoonlinkManager initialisation — stays here because it's audio - // infrastructure, not gateway handling. The guard prevents stacking - // listeners on reconnect. if (!moonlinkInitialised) { moonlinkInitialised = true; this.moonlink = new MoonlinkManager(config.nodelink ?? {}, client); @@ -352,24 +285,14 @@ export class Remix { } } - // Delegate remaining Ready work to the gateway handler (voice-state - // seeding, raw WS listener, presence rotation, tryAutoJoin). this.gatewayHandler.onReady(); } catch (e) { logger.error("[Ready] Fatal error in Ready handler:", e); } }); - // ── FluxerRevoice Instance (shared across all players) ───────────────── - // Uses the Fluxer gateway (via @fluxerjs/voice) to join voice channels - // instead of a third-party REST API. This avoids the 401 error that occurs - // when a Fluxer bot token is sent to an incompatible API endpoint. - // The FluxerRevoice class provides the same .join() interface as - // revoice.js's Revoice class, returning FluxerVoiceConnection objects - // that wrap LiveKit Rooms compatible with revoice.js's MediaPlayer. this.revoice = FluxerRevoice.getInstance(client); - // ── Player Manager ─────────────────────────────────────────────────────── this.playerContext = { client: this.client, config, @@ -388,9 +311,6 @@ export class Remix { this.players.voiceCache = this.voiceCache; this.players._lastfm = this.lastfm; - // ── Periodic alone-check ─────────────────────────────────────────────────── - // Uses VoiceStateCache.channelMembers index for O(1) per-player lookup - // instead of iterating ALL observedVoiceUsers (which was O(N×M)). const ALONE_CHECK_INTERVAL = this.T.aloneCheckInterval; setInterval(() => { for (const [mapKey, player] of this.players.playerMap) { @@ -418,11 +338,8 @@ export class Remix { if (player._is247Enabled()) continue; - // O(1) lookup via VoiceStateCache channelMembers index let hasHuman = this.voiceCache.hasHumansInChannel(cleanGuildId, cleanChanId); - // Fallback: check guild voice_states cache if voiceCache - // didn't find anyone (can happen after bot restart before reseed). if (!hasHuman) { try { const guild = this.client?.guilds?.get?.(cleanGuildId); @@ -441,7 +358,6 @@ export class Remix { const isBot = member?.user?.bot ?? state?.member?.user?.bot ?? false; if (!isBot) { hasHuman = true; - // Also update voiceCache so future checks are O(1) if (stateUserId) { this.voiceCache.updateUser({ guildId: cleanGuildId, userId: stateUserId, channelId: cleanChanId, isBot: false }); } @@ -453,7 +369,6 @@ export class Remix { } catch (_) {} } - // Fallback: check LiveKit remote participants if guild cache is empty. if (!hasHuman) { try { const room = player.connection?.room; @@ -484,7 +399,6 @@ export class Remix { } }, ALONE_CHECK_INTERVAL); - // ── Voice channel detection ────────────────────────────────────────────── const self = this; this.players.checkVoiceChannels = function (message) { const userId = message?.author?.id ?? message?.message?.author?.id; @@ -577,7 +491,7 @@ export class Remix { } catch (e) { logger.voice(`[checkVC] guild error: ${e.message}`); } try { - const loc = self.voiceCache.getHumanUser(userId); // scan all guilds + const loc = self.voiceCache.getHumanUser(userId); if (loc && String(loc.guildId ?? "").replace(/\D/g, "") === cleanGuild) { logger.voice(`[checkVC] HIT voiceCache scan → ${loc.channelId}`); return loc.channelId; @@ -588,8 +502,6 @@ export class Remix { return null; }; - // ── Git commit hash ─────────────────────────────────────────────────────── - // Must be computed BEFORE comLink is built so the hash is available. const __dirname = import.meta.dirname; try { this.comHash = childProcess.execSync("git rev-parse --short HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim(); @@ -602,7 +514,6 @@ export class Remix { this.comLink = "https://github.com/remix-bot/fluxer/commit/" + (this.comHashLong ?? ""); - // ── Commands ────────────────────────────────────────────────────────────── const loader = new CommandLoader(commands, this); const dir = path.join(__dirname, "commands"); logger.commands("Started loading commands."); @@ -610,7 +521,6 @@ export class Remix { .then(() => logger.commands("Commands loaded.")) .catch(e => logger.error("Failed to load commands:", e)); - // ── Modules ─────────────────────────────────────────────────────────────── logger.commands("Loading Modules."); this.loadedModules = new Map(); try { @@ -638,14 +548,12 @@ export class Remix { logger.commands(`Modules loaded (${succeeded} succeeded, ${failed} failed).`); }); - // ── Login ───────────────────────────────────────────────────────────────── client.login(config.token).catch(e => { logger.error("[Startup] Login failed:", e.message); process.exit(1); }); } - // ─── Helpers ────────────────────────────────────────────────────────────── /** * Attach error handlers on all @fluxerjs/ws shard WebSockets. @@ -666,11 +574,8 @@ export class Remix { const wsManager = this.client?.ws; if (!wsManager) return; - // @fluxerjs/ws may use a single connection or a ShardManager. - // Handle both patterns: const attachToSocket = (wsObj, label) => { if (!wsObj) return; - // Avoid attaching duplicate handlers on reconnect if (wsObj._fluxerErrorHandled) return; wsObj._fluxerErrorHandled = true; @@ -687,24 +592,20 @@ export class Remix { } }; - // Pattern 1: ws.shards is a Map (multi-shard) if (wsManager.shards && typeof wsManager.shards.forEach === "function") { wsManager.shards.forEach((shard, id) => { attachToSocket(shard?.ws, `Shard ${id}`); }); } - // Pattern 2: ws itself has a .ws property (single-shard) if (wsManager.ws) { attachToSocket(wsManager.ws, "Gateway"); } - // Pattern 3: ws is itself a WebSocket-like object if (typeof wsManager.on === "function" && !wsManager._fluxerErrorHandled) { attachToSocket(wsManager, "WSManager"); } - // Also listen for new shards being created (future-proofing) if (typeof wsManager.on === "function" && !wsManager._shardCreateHandled) { wsManager._shardCreateHandled = true; wsManager.on("shardCreate", (shard) => { @@ -745,21 +646,16 @@ export class Remix { if (!cleanChannelId) throw new Error("_spawnPlayer: invalid channelId"); - // Already have a player for this channel? - // Use guild→player reverse index for O(1) lookup, fallback to playerMap.get() const existing = this.players.playerMap.get(cleanChannelId) ?? this.players.getPlayerByGuildAndChannel(cleanGuildId, cleanChannelId); if (existing) return existing; - // Guard: moonlink must be ready if (!this.moonlink) throw new Error("Audio node not ready yet — try again in a moment"); - // Guard: channel must exist and be a voice channel const channel = this.client?.channels?.get?.(cleanChannelId); if (!channel) throw new Error("Channel not found"); if (channel.type !== 2) throw new Error("Not a voice channel"); - // Guard: no duplicate pending join if (this.players._pendingJoins?.has?.(cleanChannelId)) { throw new Error("Join already in progress for this channel"); } @@ -778,18 +674,14 @@ export class Remix { locale: this.locale ?? null, }); - // Set 24/7 home channel so _is247Enabled() works correctly player._home247Channel = cleanChannelId; - // Set up dashboard and lifecycle events (same as normal joins) this.players.setupEvents(player, { channelId: cleanChannelId, guildId: cleanGuildId, }); - // Handle autoleave — clean up the player map and destroy the player player.on("autoleave", () => { - // Safety guard: don't destroy 24/7 players or players with humans/queue const mode = player._get247Mode(); if (mode === "auto" || mode === "on") { logger.inactivity(`[_spawnPlayer] autoleave suppressed for 24/7 ${mode} channel ${cleanChannelId} (guild ${cleanGuildId})`); @@ -808,7 +700,6 @@ export class Remix { const homeChId = String(player._home247Channel ?? activeChId).replace(/\D/g, "") || activeChId; this.players.playerMap.delete(activeChId); this.players._unindexPlayer?.(cleanGuildId, activeChId); - // Clean up pending scrobble timer const pendingScrobble = this.players._pendingScrobbleTimers?.get(cleanChannelId); if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this.players._pendingScrobbleTimers.delete(cleanChannelId); } if (activeChId !== cleanChannelId) this.players.playerMap.delete(cleanChannelId); @@ -816,21 +707,14 @@ export class Remix { player.destroy(); }); - // Handle player messages (song announcements etc.) - // On reboot, there's no textChannel from a user command, so we resolve - // one from the saved announcementChannelId setting or fall back to the - // guild's system channel / first visible text channel. player.on("message", async (m) => { try { - // Check if song announcements are disabled for this guild const serverSettings = this.settingsMgr?.getServer?.(cleanGuildId); const raw = serverSettings?.get?.("songAnnouncements"); const disabled = raw === false || raw === 0 || ["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim()); if (disabled) return; - // Resolve the text channel: prefer player.textChannel, then saved - // announcementChannelId, then guild system channel, then first text channel let ch = player.textChannel; if (!ch || typeof ch.send !== "function") { const savedAnnChId = serverSettings?.get?.("announcementChannelId"); @@ -857,7 +741,6 @@ export class Remix { } if (!ch || typeof ch.send !== "function") return; - // Cache the resolved channel so future announcements don't need to re-resolve if (!player.textChannel) player.textChannel = ch; ch.send(typeof m === "object" && Array.isArray(m.embeds) ? m : mkEmbed(m)).catch(err => { @@ -868,7 +751,6 @@ export class Remix { } catch (_) {} }); - // Mark as pending join if (this.players._pendingJoins) { this.players._pendingJoins.add(cleanChannelId); } @@ -876,14 +758,12 @@ export class Remix { try { await player.join(cleanChannelId); - // Add to playerMap only after join succeeds this.players.playerMap.set(cleanChannelId, player); this.players._indexPlayer(cleanGuildId, cleanChannelId); if (this.players._pendingJoins) { this.players._pendingJoins.delete(cleanChannelId); } - // Restore saved volume for this guild const savedVol = this.settingsMgr?.getServer?.(cleanGuildId)?.get?.("volume"); if (savedVol !== undefined && savedVol !== null) { const vol = Number(savedVol); @@ -915,7 +795,6 @@ export class Remix { ? new Set(raw.map(id => String(id).replace(/\D/g, "")).filter(Boolean)) : new Set([String(raw).replace(/\D/g, "")]); - // Use per-channel mode (not the guild-wide legacy mode) const channelMode = channels.has(cleanId) ? get247ChannelMode(set, cleanId) : "off"; if (channels.has(cleanId) && !force) { @@ -937,7 +816,6 @@ export class Remix { if (channels.has(cleanId)) { channels.delete(cleanId); set.set("stay_247", channels.size > 0 ? [...channels] : "none"); - // Also clean up the per-channel mode entry (prevents orphaned mode data) remove247ChannelMode(set, cleanId, channels); } @@ -947,7 +825,6 @@ export class Remix { if (player) { this.players.playerMap.delete(cleanId); this.players._unindexPlayer(player._guildId, cleanId); - // Clean up pending scrobble timer const pendingScrobble = this.players._pendingScrobbleTimers?.get(cleanId); if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this.players._pendingScrobbleTimers.delete(cleanId); } await player.leave().catch(() => {}); @@ -1004,19 +881,16 @@ export class Remix { for (const guild of this.client.guilds.values()) { let isMember = false; - // 1. Fast path — check cached members if (guild.members?.has?.(user.id)) { isMember = true; } - // 2. Fallback — check voiceCache for this guild (O(1) per guild) if (!isMember) { const cleanGuildId = String(guild.id).replace(/\D/g, ""); const userLoc = this.voiceCache.getUserLocation(cleanGuildId, user.id); if (userLoc) isMember = true; } - // 3. Slow path — REST fetch for large guilds with incomplete caches if (!isMember) { try { const member = await guild.members.fetch(user.id).catch(() => null); @@ -1060,20 +934,13 @@ export class Remix { } -// ── Boot ────────────────────────────────────────────────────────────────────── const remix = new Remix(); -// ── Error handling ──────────────────────────────────────────────────────────── const isIgnorableWsCrash = (err) => { const message = String(err?.message ?? err ?? ""); const stack = String(err?.stack ?? ""); - // WebSocket transport errors from @fluxerjs/ws — these are recoverable - // because the gateway client automatically reconnects. They should be - // caught by the proactive .on("error") handlers in _attachWsErrorHandlers(), - // but this acts as a safety net in case a new shard is created after the - // initial handler attachment or the error slips through via a different path. return message === "WebSocket error" && ( stack.includes("@fluxerjs/ws/dist/index.mjs") || @@ -1101,7 +968,6 @@ process.on("uncaughtExceptionMonitor", (err, origin) => { logger.error("Error:", err, origin); }); -// ── Shutdown Hooks ────────────────────────────────────────────────────────── const saveAndExit = async () => { logger.recovery("\n[Shutdown] Cleaning up before exit..."); try { @@ -1125,9 +991,4 @@ process.once("SIGINT", saveAndExit); process.once("SIGTERM", saveAndExit); process.once("SIGUSR2", saveAndExit); -// ── SIGPIPE handler ────────────────────────────────────────────────────────── -// On some systems, writing to a broken pipe (e.g. Redis connection) raises -// SIGPIPE which defaults to terminating the process. Ignoring it lets the -// error surface through the normal exception/rejection handlers above so -// recovery state is saved before exit. process.on("SIGPIPE", () => {}); diff --git a/settings/Settings.mjs b/settings/Settings.mjs index 30bc00b..45bb771 100644 --- a/settings/Settings.mjs +++ b/settings/Settings.mjs @@ -50,15 +50,12 @@ export class MySqlSettingsManager extends SettingsManager { _hasBotIdColumn = false; /** @type {Promise|null} Tracks the in-flight load() so setBotId() can wait for it */ _loadPromise = null; - // Per-server debounce timers — collapses rapid set() calls into one remoteSave() _debounceTimers = new Map(); constructor(config, defaultsPath, botId = null) { super(); this.botId = botId; this.db = mysql.createPool({ connectionLimit: 15, ...config }); - // Without this listener, any pool-level error (connection drop, timeout, protocol error) - // fires an unhandled 'error' event which crashes the entire process with no log output. this.db.on("error", (err) => { logger.error("[DB] MySQL pool error:", err.code ?? err.message); }); @@ -81,7 +78,6 @@ export class MySqlSettingsManager extends SettingsManager { async _ensureBotIdColumn() { if (this._hasBotIdColumn) return; - // Check if bot_id column exists and its properties const res = await this.query( `SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_KEY FROM information_schema.COLUMNS ` + `WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'settings' AND COLUMN_NAME = 'bot_id'` @@ -93,11 +89,8 @@ export class MySqlSettingsManager extends SettingsManager { } if (res.results.length === 0) { - // ── Column doesn't exist: add it and update PK ───────────────────── logger.settings("[Settings] Auto-migrating: adding bot_id column to settings table..."); - // NOT NULL DEFAULT '' — primary key columns can't be NULL in MySQL. - // Existing rows get bot_id = '' which we'll claim for the current bot. const alterRes = await this.query( `ALTER TABLE settings ADD COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''` ); @@ -106,22 +99,18 @@ export class MySqlSettingsManager extends SettingsManager { return; } - // Claim all existing rows for the current bot before updating PK. - // This preserves existing settings (prefix, volume, etc.) instead of - // leaving them orphaned with bot_id = ''. if (this.botId) { await this.query( `UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''` ); } - // Update primary key from (id) to (id, bot_id) const pkRes = await this.query( `ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)` ); if (pkRes.error) { logger.error("[Settings] Failed to update primary key:", pkRes.error); - return; // Don't set flag — bot_id features can't work without composite PK + return; } this._hasBotIdColumn = true; @@ -129,41 +118,34 @@ export class MySqlSettingsManager extends SettingsManager { return; } - // ── Column already exists: verify it's in the primary key ───────────── const colInfo = res.results[0]; const isNullable = colInfo.IS_NULLABLE === 'YES'; const isPrimaryKey = colInfo.COLUMN_KEY === 'PRI'; if (isPrimaryKey) { - // Column exists and is part of composite PK — all good this._hasBotIdColumn = true; return; } - // Column exists but is NOT in PK — the ALTER TABLE PK update must have - // failed previously (likely because the column had NULL values). logger.settings("[Settings] Fixing bot_id column: adding to primary key..."); - // Step 1: Replace NULLs with empty string (PK columns can't be Null) if (isNullable) { await this.query(`UPDATE settings SET bot_id = '' WHERE bot_id IS NULL`); await this.query(`ALTER TABLE settings MODIFY COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''`); } - // Step 2: Claim unclaimed rows (bot_id = '') for the current bot if (this.botId) { await this.query( `UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''` ); } - // Step 3: Update primary key const pkRes = await this.query( `ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)` ); if (pkRes.error) { logger.error("[Settings] Failed to update primary key:", pkRes.error); - return; // Don't set flag — can't use bot_id without composite PK + return; } this._hasBotIdColumn = true; @@ -183,7 +165,6 @@ export class MySqlSettingsManager extends SettingsManager { if (this._loadPromise) await this._loadPromise; await this._ensureBotIdColumn(); - // Claim any unclaimed legacy rows (bot_id = '') for this bot. if (this._hasBotIdColumn && this.botId) { const claimRes = await this.query( `UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''` @@ -235,8 +216,6 @@ export class MySqlSettingsManager extends SettingsManager { res.results.forEach((r) => { try { const server = new ServerSettings(r.id, this); - // mysql2 may return JSON columns as already-parsed objects; - // only JSON.parse when the value is still a string. const parsed = (typeof r.data === "string") ? JSON.parse(r.data) : r.data; server.deserialize(parsed); server.checkDefaults(this.defaults); @@ -249,15 +228,10 @@ export class MySqlSettingsManager extends SettingsManager { } async remoteUpdate(server, key) { const val = server.data[key]; - // Arrays/objects must go through remoteSave — JSON_SET with scalar - // interpolation corrupts arrays by merging IDs into one number on read-back. if (Array.isArray(val) || (typeof val === "object" && val !== null)) { return this.remoteSave(server); } const escapedKey = mysql.escape(`$.${key}`); - // Preserve native boolean/number types so MySQL stores them as JSON - // booleans/numbers, not as strings. String(true) would store "true" - // which then reads back as a string — breaking strict equality checks. const escapedVal = (typeof val === "boolean" || typeof val === "number") ? mysql.escape(val) : mysql.escape(String(val)); @@ -294,8 +268,6 @@ export class MySqlSettingsManager extends SettingsManager { const escapedId = mysql.escape(id); const escapedData = mysql.escape(JSON.stringify(server.data)); const bi = this._botIdInsert(); - // INSERT IGNORE: if the row already exists (race condition or failed - // migration), silently skip instead of crashing with ER_DUP_ENTRY. const r = await this.query( `INSERT IGNORE INTO settings (id, data${bi.col}) VALUES (${escapedId}, ${escapedData}${bi.val})` ); @@ -305,7 +277,6 @@ 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]; - // 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(() => { diff --git a/settings/migrate.mjs b/settings/migrate.mjs index 241bae3..ed8373c 100644 --- a/settings/migrate.mjs +++ b/settings/migrate.mjs @@ -4,19 +4,11 @@ import { logger } from "../src/constants/Logger.mjs"; const config = JSON.parse(fs.readFileSync(new URL("../config.json", import.meta.url))); -// Pass bot ID from config if available, so migrations are bot-isolated. -// If no botId in config, all rows are migrated (legacy behavior). const botId = config.botId ?? null; -// Both source and destination use RemoteSettingsManager to ensure the -// `guilds` Map is populated from MySQL. The abstract SettingsManager base -// class has no implementation (no guilds, no load, no defaults). const sm = new RemoteSettingsManager(config.mysql, "./storage/defaults.json", botId); const rsm = new RemoteSettingsManager(config.mysql, "./storage/defaults.json", botId); -// Ensure source manager is fully loaded BEFORE starting migration. -// Previously, rsm's "ready" could fire before sm finished loading, -// resulting in an empty servers array and a silent no-op migration. let migrationStarted = false; sm.on("ready", async () => { @@ -25,7 +17,6 @@ sm.on("ready", async () => { const servers = [...sm.guilds.entries()]; - // Wait for the destination manager to be ready too if (!rsm.guilds.size) { await new Promise(resolve => rsm.on("ready", resolve)); } diff --git a/settings/runnables.mjs b/settings/runnables.mjs index fb47a88..6f09bd1 100644 --- a/settings/runnables.mjs +++ b/settings/runnables.mjs @@ -1,6 +1,5 @@ export default { prefix: function(value, data) { - // prefix change hook — Settings handles persistence }, pfp: function(value, data) { @@ -9,7 +8,6 @@ export default { } }, - // stay_247 is managed exclusively by the %247 command and auto-join logic. stay_247: function(value, data) { return false; }, diff --git a/src/CommandHandler.mjs b/src/CommandHandler.mjs index 7058e93..dcd6eb0 100644 --- a/src/CommandHandler.mjs +++ b/src/CommandHandler.mjs @@ -70,7 +70,6 @@ export class CommandRequirement { } export class Option { - // Fluxer uses channel mentions: <#id> and user mentions <@id> channelRegex = /^<#(?\d+)>/; userRegex = /^<@!?(?\d+)>/; idRegex = /^(?\d+)/; @@ -141,10 +140,9 @@ export class Option { const results = this.channelRegex.exec(i) ?? this.idRegex.exec(i); const guildId = msg?.channel?.guildId ?? msg?.guildId; - // dry-run eval mode if (guildId === "eval") return (results) ? results.groups["id"] : i; - const voiceTypes = [2, 13]; // GuildVoice and GuildStageVoice + const voiceTypes = [2, 13]; const byName = msg?.guild?.channels?.find(c => c.name === i && voiceTypes.includes(c.type)); const cObj = results ? client.channels.get(results.groups["id"]) @@ -381,11 +379,8 @@ 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 + _cmdCooldownMs = 1500; constructor(handler, prefix = "!") { super(); @@ -439,7 +434,6 @@ export class CommandHandler extends EventEmitter { if (!msg || !msg.content) return; const trimmed = msg.content.trim(); if (/^<@!?\d+>$/.test(trimmed)) { - // Only respond if the bot itself was pinged const botId = this.client.user?.id; if (botId && (trimmed === `<@${botId}>` || trimmed === `<@!${botId}>`)) { return this.onPing?.(msg); @@ -447,16 +441,12 @@ 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) { @@ -513,12 +503,8 @@ export class CommandHandler extends EventEmitter { } processCommand(cmd, args, msg, previous = false, external = false) { - // Guard first — cmd could be undefined if called from an edge case if (!cmd) return logger.warn("[CommandHandler.processCommand] Invalid case: `cmd` falsy."); - // Check if the bot itself has the critical permissions it needs in this channel. - // This runs BEFORE user-requirement checks so the user gets a clear error - // about what the bot is missing, rather than a generic 403 crash later. if (!external) { const channel = msg.channel?.channel ?? msg.channel; if (channel?.guild) { @@ -528,7 +514,6 @@ export class CommandHandler extends EventEmitter { try { msg.message?.reply?.({ embeds: [permEmbed] }, { ping: false }); } catch (_) { - // Last resort: plain text try { const names = botPermResult.missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k); msg.message?.reply?.("I'm missing critical permissions: **" + names.join("**, **") + "**. Ask an admin to fix this.", { ping: false }); @@ -689,16 +674,12 @@ export class CommandHandler extends EventEmitter { const member = guild.members.get(authorId) ?? null; if (member?.permissions) { - // cached — check directly const missing = req.permissions.filter(p => !member.permissions.has(PermissionFlags[p] ?? p)); if (missing.length > 0) { this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg); return false; } } else { - // not cached — fetch async and re-run - // guild.fetchMember(id) is a Fluxer shorthand; guild.members.fetch(id) is the - // standard compatible form. Try both so either API name works. const fetchPromise = typeof guild.fetchMember === "function" ? guild.fetchMember(authorId) : typeof guild.members?.fetch === "function" @@ -709,14 +690,11 @@ export class CommandHandler extends EventEmitter { if (missing.length > 0) { this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg); } else { - // Re-parse args the same way messageHandler does so quoted args survive. const guildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId; const prefix2 = this.getPrefix(guildId2); const rawContent = msg.message.content; const len2 = rawContent.startsWith(prefix2) ? prefix2.length : 0; const args = rawContent.slice(len2).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim()); - // Pass external=true to skip re-checking requirements and avoid - // re-entering the fetch loop if the member is still not cached. this.processCommand(cmd, args, msg, false, true); } }).catch(() => this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg)); @@ -755,7 +733,6 @@ export class CommandLoader { this.commands = commands; this.context = context; this.context.loader ??= this; - // expose loader helpers on context so reload.js can use them this.context.commandFiles = this.commandFiles; this.context.runnables = this.runnables; diff --git a/src/FluxerListManager.mjs b/src/FluxerListManager.mjs index 4af0162..6d355dc 100644 --- a/src/FluxerListManager.mjs +++ b/src/FluxerListManager.mjs @@ -7,7 +7,7 @@ * - In-memory response caching with configurable TTL * - Graceful error handling (401/403 auth errors, network failures) * - * FluxerList API docs: https://fluxerlist.com/api/v1 + * FluxerList API docs: https: */ import { logger } from "./constants/Logger.mjs"; @@ -18,7 +18,6 @@ import { buildFluxerListUrl, } from "./constants/API.mjs"; -// ── FluxerListManager ─────────────────────────────────────────────────────────── export class FluxerListManager { /** @@ -37,7 +36,6 @@ export class FluxerListManager { this.botSlug = config?.botSlug ?? config?.botId ?? ""; this.enabled = !!this.apiKey; - // In-memory cache: Map this._cache = new Map(); if (!this.enabled) { @@ -47,7 +45,6 @@ export class FluxerListManager { } } - // ── Cache helpers ─────────────────────────────────────────────────────────── /** * Generate a cache key from the request parameters. @@ -88,7 +85,6 @@ export class FluxerListManager { expiresAt: Date.now() + (ttlMs ?? FLUXERLIST_LIMITS.CACHE_TTL_MS), }); - // Evict stale entries periodically to prevent unbounded growth if (this._cache.size > 200) { const now = Date.now(); for (const [k, v] of this._cache) { @@ -97,7 +93,6 @@ export class FluxerListManager { } } - // ── API calls ─────────────────────────────────────────────────────────────── /** * Fetch the list of voters for a server or bot. @@ -122,7 +117,6 @@ export class FluxerListManager { const page = options.page ?? FLUXERLIST_LIMITS.DEFAULT_PAGE; const limit = options.limit ?? FLUXERLIST_LIMITS.DEFAULT_LIMIT; - // Check cache first const cacheKey = this._cacheKey(type, resourceId, page, limit); if (!options.skipCache) { const cached = this._getCached(cacheKey); @@ -132,14 +126,12 @@ export class FluxerListManager { } } - // Build request URL const endpoint = type === "server" ? FLUXERLIST.ENDPOINTS.SERVER_VOTERS : FLUXERLIST.ENDPOINTS.BOT_VOTERS; const url = buildFluxerListUrl(endpoint, resourceId, { page, limit }); - // Make the API call const res = await fetch(url, { method: "GET", headers: { @@ -149,7 +141,6 @@ export class FluxerListManager { }, }); - // Handle HTTP errors if (res.status === 401) { throw new Error("Invalid FluxerList API key. Check your config.json fluxerlist.apiKey."); } @@ -167,12 +158,10 @@ export class FluxerListManager { const data = await res.json(); - // Validate response shape if (typeof data.total !== "number" || !Array.isArray(data.voters)) { throw new Error("Unexpected FluxerList API response format."); } - // Cache the result this._setCached(cacheKey, data); logger.settings(`[FluxerList] Fetched ${data.voters.length} voters for ${type} ${resourceId} (page ${page}, total ${data.total})`); @@ -217,21 +206,18 @@ export class FluxerListManager { let allVoters = []; let total = Infinity; - // Safety: max 50 pages to prevent runaway loops while (allVoters.length < total && page <= 50) { const data = await this.getVoters(type, id, { page, limit, skipCache: options.skipCache }); allVoters = allVoters.concat(data.voters); total = data.total; page++; - // If we got fewer results than the limit, we've reached the last page if (data.voters.length < limit) break; } return allVoters; } - // ── Internal ──────────────────────────────────────────────────────────────── _assertEnabled() { if (!this.enabled) { diff --git a/src/GatewayHandler.mjs b/src/GatewayHandler.mjs index 70d1181..a0b6f40 100644 --- a/src/GatewayHandler.mjs +++ b/src/GatewayHandler.mjs @@ -21,41 +21,22 @@ export class GatewayHandler { constructor(remix) { this.remix = remix; - // ── Timers config (kept local — derived from remix.config) ─────────────── const timers = remix.config.timers ?? {}; this.T = { aloneCheckDebounce: timers.aloneCheckDebounce ?? 500, rejoin247Delay: timers.rejoin247Delay ?? 3_000, }; - // ── Presence rotation config ───────────────────────────────────────────── this.presenceContents = remix.config.presenceContents ?? []; this.presenceInterval = remix.config.presenceInterval ?? 30_000; - // ── One-time setup guards (persist across reconnects) ───────────────────── this.wsListenerAttached = false; this.presenceTimer = null; this.presenceIndex = 0; - // ── Previous voice state per-user (for detecting channel moves) ─────────── /** @type {Map} guildId:userId → state */ this._prevVoiceState = new Map(); - // ── Startup GuildDelete deferral ─────────────────────────────────────── - // Fluxer's GUILD_DELETE does NOT expose the `unavailable` flag, so we - // cannot distinguish "bot was kicked" from "guild is temporarily - // unavailable." During startup, the gateway sends GUILD_DELETE for - // guilds that went offline while the bot was down, followed immediately - // by GUILD_CREATE when they come back. If we process GuildDelete - // immediately, we wipe in-memory state (settings cache, player map, - // voice observations) for guilds the bot IS still in, then GuildCreate - // has to re-load everything from DB — wasting time and causing scary - // "bot removed from server" log messages for guilds that are fine. - // - // Solution: During a startup grace period, buffer GuildDelete events - // and only process them after the grace period expires. If a GuildCreate - // arrives for the same guild before the grace period ends, we cancel the - // deferred cleanup because the guild is still active. /** @type {Map} guildId → deferred cleanup data */ this._deferredGuildDeletes = new Map(); /** @type {number} How long to defer GuildDelete processing during startup (ms) */ @@ -66,7 +47,6 @@ export class GatewayHandler { this._deferredDeleteCount = 0; } - // ── Voice-state key helpers ────────────────────────────────────────────────── /** * Generate a composite key for bots in the observedVoiceBots map. @@ -102,7 +82,6 @@ export class GatewayHandler { return { key: null, value: null }; } - // ── Guild permission check on join ──────────────────────────────────────── /** * Check if the bot has all required permissions in a newly joined guild. @@ -115,25 +94,21 @@ export class GatewayHandler { async _checkGuildPermissions(guild, guildId) { const { remix } = this; - // Ensure the bot's member is cached so we can check permissions try { if (guild.members && !guild.members.me) { await guild.members.fetchMe(); } } catch (_) { /* fetch failed — we'll still try */ } - // Find a text channel to check permissions in (prefer system channel) const channels = guild.channels; if (!channels) return; let targetChannel = null; - // Try system channel first if (guild.systemChannelId) { targetChannel = channels.get?.(guild.systemChannelId) ?? channels.cache?.get?.(guild.systemChannelId) ?? null; } - // Fall back to first text channel the bot can see if (!targetChannel) { for (const ch of (channels.values?.() ?? [])) { if (ch.isTextBased?.() || ch.type === 0 || ch.type === "GUILD_TEXT") { @@ -145,9 +120,8 @@ export class GatewayHandler { if (!targetChannel) return; const result = remix.messages.checkAllBotPermissions(targetChannel); - if (result.missing.length === 0) return; // All good! + if (result.missing.length === 0) return; - // Log the missing permissions const missingNames = result.missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k); if (result.criticalMissing.length > 0) { logger.warn( @@ -160,12 +134,10 @@ export class GatewayHandler { ); } - // Try to send a permission warning embed to the channel try { const permEmbed = remix.messages.buildPermissionEmbed(result.missing, guildId); await targetChannel.send({ embeds: [permEmbed] }); } catch (e) { - // Can't send embed (missing SendMessages/EmbedLinks) — try plain text logger.warn(`[GuildCreate] Cannot send permission warning to server ${guildId}: ${e.message}`); try { await targetChannel.send( @@ -174,13 +146,11 @@ export class GatewayHandler { "Please ask a server administrator to grant these permissions in Server Settings → Roles." ); } catch (_) { - // Completely blocked — can't notify the server at all. The log message above is the only recourse. logger.warn(`[GuildCreate] Cannot send ANY notification to server ${guildId} — bot is missing SendMessages permission.`); } } } - // ── Voice-state seeding from guild cache ───────────────────────────────────── /** * Seed observedVoiceUsers / observedVoiceBots from all cached guild voice @@ -190,27 +160,19 @@ export class GatewayHandler { const { remix } = this; const client = remix.client; - // ── Primary source: @fluxerjs/voice VoiceManager.voiceStates ──────────── - // The VoiceManager populates its voiceStates Map from VOICE_STATES_SYNC - // and VOICE_STATE_UPDATE gateway events. This is the most reliable source - // because it works regardless of whether guild.voice_states is populated - // by @fluxerjs/core (which it often isn't on Fluxer). try { const vm = getVoiceManager(client); if (vm?.voiceStates) { - // voiceStates is a Map> for (const [guildId, userMap] of vm.voiceStates) { if (!userMap || typeof userMap.forEach !== "function") continue; const cleanGuildId = String(guildId).replace(/\D/g, ""); if (!cleanGuildId) continue; userMap.forEach((channelId, userId) => { if (!userId || !channelId) return; - // The bot's own ID is included in voiceStates — track it as a bot const botId = client.user?.id; if (userId === botId) { remix.voiceCache.updateUser({ guildId: cleanGuildId, userId, channelId, isBot: true }); } else { - // Check if this user is a bot via the members cache const guild = client.guilds.get(cleanGuildId) ?? client.guilds.get(guildId); const member = guild?.members?.get?.(userId); const isBot = member?.user?.bot ?? false; @@ -226,14 +188,12 @@ export class GatewayHandler { `[Seed] Seeded from VoiceManager.voiceStates — ` + `${remix.voiceCache.observedVoiceUsersSize} humans, ${remix.voiceCache.observedVoiceBotsSize} bots tracked.` ); - return; // VoiceManager is the primary source — skip fallback + return; } } catch (e) { logger.voiceState(`[Seed] VoiceManager seeding failed: ${e?.message} — falling back to guild cache.`); } - // ── Fallback: guild.voice_states cache ────────────────────────────────── - // Only used if VoiceManager is unavailable (shouldn't happen in normal ops). for (const [gId, guild] of client.guilds) { const voiceStatesRaw = guild.voice_states ?? @@ -265,7 +225,6 @@ export class GatewayHandler { } } - // ── Reseed voice states for a specific channel ───────────────────────────── /** * Re-read the guild's voice_states cache and update observedVoiceUsers @@ -293,7 +252,6 @@ export class GatewayHandler { let humansFound = 0; const botId = client.user?.id; - // ── Primary source: @fluxerjs/voice VoiceManager.voiceStates ──────────── try { const vm = getVoiceManager(client); if (vm?.voiceStates) { @@ -321,7 +279,6 @@ export class GatewayHandler { } }); - // Update the bot's own entry if (botId) { remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true }); } @@ -331,7 +288,6 @@ export class GatewayHandler { `found ${humansFound} human(s) via VoiceManager, observedVoiceUsers size now ${remix.voiceCache.observedVoiceUsersSize}` ); - // If VoiceManager found humans, skip fallbacks if (humansFound > 0) return humansFound; } } @@ -339,7 +295,6 @@ export class GatewayHandler { logger.voiceState(`[Reseed] VoiceManager lookup failed: ${e?.message} — falling back.`); } - // ── Fallback: guild.voice_states cache ────────────────────────────────── const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId); if (!guild) { logger.voiceState( @@ -388,7 +343,6 @@ export class GatewayHandler { } } - // Update bot's own entry if (botId) { remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true }); } @@ -403,9 +357,7 @@ export class GatewayHandler { } } - // ── Fallback: VoiceStateCache (was observedVoiceUsers) ──────────────── if (humansFound === 0 && remix.voiceCache) { - // O(1) lookup via channelMembers index instead of full scan const humans = remix.voiceCache.getHumansInChannel(cleanGuild, cleanChannel); for (const uid of humans) { humansFound++; @@ -414,13 +366,11 @@ export class GatewayHandler { ); } - // Update bot's own entry if (botId) { remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true }); } } - // ── Last resort: LiveKit remote participants ──────────────────────────── if (humansFound === 0) { try { const player = remix.players.playerMap.get(cleanChannel); @@ -450,7 +400,6 @@ export class GatewayHandler { return humansFound; } - // ── Raw WebSocket gateway listener ─────────────────────────────────────────── /** * Attach a raw "message" listener to the shard-0 WebSocket so we can @@ -467,7 +416,6 @@ export class GatewayHandler { const shard0 = client.ws?.shards?.get?.(0); const wsObj = shard0?.ws ?? null; - // Remove listener from the previous socket if it's a different object if (this.wsListenerAttached && remix._rawGatewayWsObj && remix._rawGatewayWsObj !== wsObj) { try { if (typeof remix._rawGatewayWsObj.removeEventListener === "function") { @@ -501,7 +449,6 @@ export class GatewayHandler { if (payload?.op !== 0) return; - // READY — seed voice states from unavailable-guilds summary if (payload.t === "READY") { logger.player(`[Gateway] READY received (session ${payload.d?.session_id ?? "unknown"})`); const readyGuilds = payload.d?.guilds; @@ -579,7 +526,6 @@ export class GatewayHandler { } catch (_) {} } - // ── Presence rotation ─────────────────────────────────────────────────────── setupPresenceRotation() { if (this.presenceContents.length === 0) return; @@ -590,9 +536,6 @@ export class GatewayHandler { const setPresence = () => { const entry = this.presenceContents[this.presenceIndex]; - // Support both plain strings and rich objects: - // String: "Ping for Prefix" - // Object: { text: "...", emoji_name: "🎵", activity: { name: "kyun.sh", type: 2 } } const isObj = typeof entry === "object" && entry !== null; const custom_status = {}; @@ -611,7 +554,6 @@ export class GatewayHandler { custom_status, }; - // Add activity (e.g. "Listening to kyun.sh") if provided if (isObj && entry.activity) { presence.activities = [{ name: entry.activity.name ?? "music", @@ -633,7 +575,6 @@ export class GatewayHandler { this.presenceTimer = setInterval(setPresence, this.presenceInterval); } - // ── Fluxer event handlers ───────────────────────────────────────────────────── /** * Register all high-level Fluxer event listeners on the Fluxer client. @@ -643,16 +584,10 @@ export class GatewayHandler { const { remix } = this; const client = remix.client; - // ── GUILD_CREATE ──────────────────────────────────────────────────────── - // Voice-state seeding + settings init for new/re-joined servers. client.on(Events.GuildCreate, async (guild) => { const guildId = guild?.id ?? guild?._id; if (!guildId) return; - // ── Cancel any deferred GuildDelete for this guild ──────────────── - // If we got GuildDelete → GuildCreate for the same guild during the - // startup grace period, the guild was temporarily unavailable, not - // actually kicked. Cancel the deferred cleanup timer. const deferred = this._deferredGuildDeletes.get(guildId); if (deferred) { clearTimeout(deferred.timer); @@ -663,20 +598,12 @@ export class GatewayHandler { ); } - // Part 1: Voice state population - // Only purge stale entries if the GUILD_CREATE actually contains - // voice_states data. If voice_states is empty, the guild may just - // not provide voice state data in GUILD_CREATE (common on Fluxer), - // and purging would destroy data we collected from VOICE_STATE_UPDATE - // events. Only purge entries for users that appear in the new - // voice_states data (so we can replace them with fresh data). const voiceStatesRaw = guild.voice_states ?? guild.voiceStates ?? null; if (voiceStatesRaw) { - // Build a set of user IDs from the new voice_states data const newUserIds = new Set(); if (!Array.isArray(voiceStatesRaw) && typeof voiceStatesRaw === "object" && typeof voiceStatesRaw.values !== "function") { @@ -693,11 +620,6 @@ export class GatewayHandler { } } - // Only purge entries for users/bots that are being replaced by new data. - // Previously, ALL observedVoiceBots entries for the guild were deleted, - // which removed the bot's own entry that was set up during recovery. - // Now we only delete entries for bots whose user ID appears in the new - // voice_states data, matching the same logic used for observedVoiceUsers. remix.voiceCache.purgeUsersInGuild(guildId, newUserIds); } if (voiceStatesRaw) { @@ -726,7 +648,6 @@ export class GatewayHandler { } } - // Part 2: Settings init for new/re-joined servers if (!remix.settingsMgr.guilds.has(guildId)) { logger.guild(`[GuildCreate] (Re-)joined server ${guildId} — initialising settings.`); try { @@ -736,8 +657,6 @@ export class GatewayHandler { if (res?.results?.length) { const row = res.results[0]; const server = new ServerSettings(guildId, remix.settingsMgr); - // mysql2 may return JSON columns as already-parsed objects; - // only JSON.parse when the value is still a string. const parsed = (typeof row.data === "string") ? JSON.parse(row.data) : row.data; server.deserialize(parsed); server.checkDefaults(remix.settingsMgr.defaults); @@ -755,41 +674,27 @@ export class GatewayHandler { } } - // ── Bot permission check ──────────────────────────────────────────── - // After the bot joins a server, check if it has the required permissions - // in the first available text channel. If critical permissions are missing, - // log a warning and try to notify the server via system channel. this._checkGuildPermissions(guild, guildId); }); - // ── GUILD_DELETE ──────────────────────────────────────────────────────── client.on(Events.GuildDelete, (guild) => { const guildId = guild?.id ?? guild?._id; if (!guildId) return; - // ── Startup deferral ────────────────────────────────────────────── - // During startup, the gateway may send GUILD_DELETE for guilds that - // are temporarily unavailable (not actually kicked). If we process - // these immediately, we wipe settings/players for guilds that will - // come back via GUILD_CREATE moments later. Defer cleanup during - // the startup grace period; if GuildCreate arrives first, cancel. if (this._inStartupGrace) { this._deferredDeleteCount++; - // Only log the first few deferrals individually, then suppress if (this._deferredDeleteCount <= 3) { logger.guild( `[GuildDelete] Deferring cleanup for server ${guildId} ` + `(startup grace — will confirm after ${this._startupDeleteGraceMs / 1000}s).` ); } - // Cancel any existing deferred timer for this guild const existing = this._deferredGuildDeletes.get(guildId); if (existing) clearTimeout(existing.timer); const timer = setTimeout(() => { this._deferredGuildDeletes.delete(guildId); - // Grace period expired without GuildCreate — this guild is really gone this._processGuildDelete(guildId); }, this._startupDeleteGraceMs); @@ -797,12 +702,10 @@ export class GatewayHandler { return; } - // ── Runtime (after startup grace) — process immediately ───────── logger.guild(`[GuildDelete] Removed from server ${guildId} — cleaning up.`); this._processGuildDelete(guildId); }); - // ── VOICE_STATE_UPDATE ────────────────────────────────────────────────── client.on(Events.VoiceStateUpdate, async (data) => { this._handleVoiceStateUpdate(data); }); @@ -824,26 +727,16 @@ export class GatewayHandler { const guildId = data?.guild_id; const isBot = data?.member?.user?.bot ?? null; - // Capture old channel BEFORE updating prev state const prevEntry = this.findPrevVoiceStateEntry(userId, guildId); const prev = prevEntry.value; - // Only treat as a channel move if the previous state is from the SAME guild. - // Cross-guild previous states are NOT moves — the bot can be in multiple - // guilds' voice channels simultaneously. Without this check, concurrent - // 24/7 recovery triggers a cascading re-key that destroys all but the - // last guild's playerMap entry. const prevSameGuild = prev && String(prev.guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, ""); const oldChannelId = prevSameGuild ? (prev?.channelId ?? null) : null; const prevKey = prevEntry.key; - // Update prev state const nextKey = this.getPrevVoiceStateKey(userId, guildId ?? prev?.guildId); if (channelId) { if (prevKey && prevKey !== nextKey) { - // Only delete the previous entry if it's from the SAME guild. - // The bot can be in multiple guilds' voice channels simultaneously, - // so we must preserve cross-guild entries. const prevGuildPart = prevKey.split(":")[0]; const nextGuildPart = nextKey.split(":")[0]; if (prevGuildPart === nextGuildPart) { @@ -854,17 +747,11 @@ export class GatewayHandler { const evictKey = this._prevVoiceState.keys().next().value; const evictEntry = this._prevVoiceState.get(evictKey); this._prevVoiceState.delete(evictKey); - // When evicting a stale prevVoiceState entry, also clean up the - // corresponding VoiceStateCache entry so it doesn't hold a stale - // channel mapping that could cause incorrect "channel move" detection - // on the next voice state update for that user. if (evictEntry) { const evictGuildId = evictEntry.guildId; const evictUserId = evictKey.split(":")[1]; if (evictGuildId && evictUserId) { const currentLoc = remix.voiceCache.getUserLocation(evictGuildId, evictUserId); - // Only remove from voiceCache if the user is still in the evicted - // channel — if they've moved since, the cache is already correct. if (currentLoc && currentLoc.channelId === evictEntry.channelId) { remix.voiceCache.updateUser({ guildId: evictGuildId, userId: evictUserId, channelId: null, isBot: false }); } @@ -876,11 +763,9 @@ export class GatewayHandler { if (prevKey) this._prevVoiceState.delete(prevKey); } - // Always update/delete the voice maps if (channelId) { remix.voiceCache.updateUser({ guildId: guildId ?? prev?.guildId, userId, channelId, isBot: isBot === true }); } else { - // User left voice — remove from both human and bot indexes const resolvedGuildId = guildId ?? prev?.guildId; remix.voiceCache.deleteHumanUser(userId, resolvedGuildId); remix.voiceCache.deleteBotUser(VoiceStateCache.userKey(resolvedGuildId, userId)); @@ -889,7 +774,6 @@ export class GatewayHandler { const isBotUser = isBot === true && userId === client.user?.id; if (!isBotUser) { - // ── Human user logic ────────────────────────────────────────────────── const resolvedGuildId = guildId ?? prev?.guildId; if (!resolvedGuildId) return; @@ -904,7 +788,6 @@ export class GatewayHandler { } catch (_) {} } - // Human LEFT a voice channel if (oldChannelId && oldChannelId !== channelId) { try { const cleanOld = String(oldChannelId).replace(/\D/g, ""); @@ -920,7 +803,6 @@ export class GatewayHandler { } catch (_) {} } - // Human JOINED the bot's channel if (channelId) { try { const cleanId = String(channelId).replace(/\D/g, ""); @@ -932,7 +814,6 @@ export class GatewayHandler { } catch (_) {} } - // Dashboard update if (remix.dashboard?.enabled) { try { const userObj = data?.member?.user; @@ -940,7 +821,6 @@ export class GatewayHandler { try { await client.users.fetch(userId).catch(() => {}); } catch (_) {} } if (userObj) { - // Send user update on the global :users channel const details = { type: channelId ? "join" : "leave", guildId: resolvedGuildId, @@ -950,22 +830,18 @@ export class GatewayHandler { remix.dashboard.updateUser(details, userObj); } - // Send per-player channel events for join/leave const refChannel = channelId ?? oldChannelId; const cleanId_ref = refChannel ? String(refChannel).replace(/\D/g, "") : null; if (cleanId_ref) { const player = remix.players.playerMap.get(cleanId_ref); if (player) { - // Send "join" or "leave" on the per-player channel - // (standard format: { type, data } where data = userId) const eventType = channelId ? "join" : "leave"; remix.dashboard.updatePlayer({ type: eventType, data: userId, }, player); - // Also update the global players channel with current player state remix.dashboard.playerUpdate({ type: eventType, }, player); @@ -977,19 +853,14 @@ export class GatewayHandler { return; } - // ── Bot-only logic below ─────────────────────────────────────────────── const activeGuildPlayers = [...remix.players.playerMap.entries()].filter(([, player]) => String(player?._guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, "") ); const multiVoiceGuild = activeGuildPlayers.length > 1; - // Bot moved channels — auto-save 247 setting if (channelId && guildId && oldChannelId && oldChannelId !== channelId) { try { - // For multi-voice guilds, only re-key if we can unambiguously match - // the player by oldChannelId. Previously this skipped entirely for - // multi-voice guilds, which broke recovery for all channels. const cleanId = String(channelId).replace(/\D/g, ""); const cleanOld = String(oldChannelId).replace(/\D/g, ""); const moveSet = remix.settingsMgr.getServer(guildId); @@ -1039,10 +910,6 @@ export class GatewayHandler { let rekeyed = false; if (existingPlayer && cleanId !== cleanOld) { if (newChannelAlreadySaved || newChannelPendingSpawn) { - // Multi-voice case: joining/spawning another channel in the same - // guild can look like a move event for the bot user. In that - // situation we must NOT re-key the old player or rewrite stay_247, - // otherwise one saved channel gets collapsed into the newer one. logger.voice247( `[247] Keeping both channels ${cleanOld} and ${cleanId} ` + `(saved=${newChannelAlreadySaved} pending=${newChannelPendingSpawn})` @@ -1050,13 +917,8 @@ export class GatewayHandler { rekeyed = false; } else if (guildIsAmbiguous) { - // Multi-voice guild: we need to re-key the playerMap so that - // lookups by the new channelId work. First check that no OTHER - // player is already using the new channelId as its key. const playerAtNewKey = remix.players.playerMap.get(cleanId); if (playerAtNewKey && playerAtNewKey !== existingPlayer) { - // Another player already uses the new key — update the moved - // player's channel fields but don't re-key to avoid collision. existingPlayer._channelId = cleanId; existingPlayer._home247Channel = cleanId; if (targetGuildId) existingPlayer._guildId = targetGuildId; @@ -1067,7 +929,6 @@ export class GatewayHandler { `new key occupied by another player — skipped re-key)` ); } else { - // Safe to re-key: no collision remix.players.playerMap.delete(cleanOld); remix.players.playerMap.set(cleanId, existingPlayer); existingPlayer._channelId = cleanId; @@ -1080,29 +941,14 @@ export class GatewayHandler { ); } } else if (playerGuildId && targetGuildId && playerGuildId !== targetGuildId) { - // If there's no player for the old channel in playerMap, this is a - // stale "move" from a pre-restart voice state — the bot was in - // cleanOld before the restart, but recovery already spawned a - // player for the new channel (cleanId) or a different channel. - // In this case, just update the observed bot state without re-keying. if (!existingPlayer) { logger.voice247( `[247] Stale cross-guild move ${cleanOld} → ${cleanId} ` + `(no player in playerMap for old channel — updating bot state only)` ); } else { - // There IS a player in the old channel but the guilds don't match. - // This can happen during recovery when voice state data is - // inconsistent. Instead of refusing outright, check if the player - // in the old channel actually belongs to the target guild (the - // playerGuildId might be stale from before restart). - // If the target channel's guild matches the VOICE_STATE_UPDATE's - // guild, update the player's guildId and re-key. const vsuGuildId = String(guildId ?? "").replace(/\D/g, ""); if (vsuGuildId && targetGuildId === vsuGuildId) { - // The VOICE_STATE_UPDATE guild matches the target channel — - // this is likely a stale playerGuildId from before restart. - // Safe to update the player's guild and re-key. existingPlayer._guildId = targetGuildId; existingPlayer._channelId = cleanId; existingPlayer._home247Channel = cleanId; @@ -1146,7 +992,6 @@ export class GatewayHandler { return; } - // ── Multi-voice guard ────────────────────────────────────────── const currentGuildPlayers = [...remix.players.playerMap.values()].filter(p => String(p?._guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, "") ); @@ -1166,12 +1011,10 @@ export class GatewayHandler { return; } - // Single-voice guild: genuine move — replace old channel with new. channels.delete(cleanOld); channels.add(cleanId); set.set("stay_247", [...channels]); - // Move the per-channel mode from old → new channel const modes = set.get("stay_247_modes"); if (modes && typeof modes === "object" && !Array.isArray(modes)) { if (modes[cleanOld] && !modes[cleanId]) { @@ -1189,19 +1032,11 @@ export class GatewayHandler { } } - // Bot disconnected unexpectedly — handle based on 24/7 mode: - // %247 auto → clean up old player and schedule rejoin (always stays in voice) - // %247 on → emit autoleave (only rejoins on reboot, not on disconnect) - // off → emit autoleave if (!channelId && oldChannelId && guildId) { try { const cleanOld = String(oldChannelId).replace(/\D/g, ""); const cleanGuild = String(guildId).replace(/\D/g, ""); - // During boot recovery, stale voice state events may arrive from - // deferred GuildDelete processing. If the bot just joined this channel - // as part of 24/7 boot recovery, the player is still good — skip - // the autoleave/rejoin logic to avoid disrupting a healthy connection. if (this._inStartupGrace) { const bootPlayer = remix.players.playerMap.get(cleanOld); if (bootPlayer && !bootPlayer._destroyed) { @@ -1221,12 +1056,8 @@ export class GatewayHandler { if (remix.intentionalLeaves.has(cleanOld)) { logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — intentional leave.`); } else if (remix.revoice?._intentionalDisconnects?.has?.(cleanOld)) { - // The player's destroy() or FluxerRevoice internally marked this - // disconnect as intentional (e.g. cleaning up a stale connection - // during a rejoin). Don't schedule another rejoin. logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — intentional (revoice).`); } else { - // Check 24/7 mode for this channel const set = remix.settingsMgr.getServer(guildId); const mode = set ? get247ChannelMode(set, cleanOld) : "off"; @@ -1236,25 +1067,18 @@ export class GatewayHandler { ); const player = remix.players.playerMap.get(cleanOld); if (player && !player._destroyed) { - // Remove from player map first to prevent stale lookups remix.players.playerMap.delete(cleanOld); - // Also clean up any alternate keys const homeChannel = String(player._home247Channel ?? "").replace(/\D/g, ""); if (homeChannel && homeChannel !== cleanOld) { remix.players.playerMap.delete(homeChannel); } - // Destroy the player (stops media, disconnects room) try { player.destroy(); } catch (_) {} - // Clean up pending scrobble timer if any const pendingScrobble = remix.players._pendingScrobbleTimers?.get(cleanOld); if (pendingScrobble) { clearTimeout(pendingScrobble.timer); remix.players._pendingScrobbleTimers.delete(cleanOld); } } - // Schedule rejoin with delay to avoid overwhelming LiveKit. - // The delay also gives the Fluxer gateway time to process the - // leave signal before we attempt a new VOICE_STATE_UPDATE. const rejoinDelay = this.T.rejoin247Delay ?? 3_000; setTimeout(() => { this._rejoinChannel(cleanGuild, cleanOld).catch(err => { @@ -1262,7 +1086,6 @@ export class GatewayHandler { }); }, rejoinDelay); } else { - // %247 on or off: just emit autoleave (no reconnect on disconnect) const player = remix.players.playerMap.get(cleanOld); if (player && !player.leaving && !player._destroyed) { logger.voiceState( @@ -1278,7 +1101,6 @@ export class GatewayHandler { } } - // ── Rejoin a single channel after disconnect (for %247 auto) ────────────── /** @type {Set} Channel IDs currently being rejoined (dedup guard) */ _rejoinInProgress = new Set(); @@ -1306,13 +1128,11 @@ export class GatewayHandler { const cleanGuildId = String(guildId).replace(/\D/g, ""); const cleanChannelId = String(channelId).replace(/\D/g, ""); - // ── Deduplication: prevent concurrent rejoin for the same channel ────── if (this._rejoinInProgress.has(cleanChannelId)) { logger.voice247(`[Rejoin] Channel ${cleanChannelId} rejoin already in progress — skipping.`); return; } - // Don't rejoin if there's already a player for this channel const existing = remix.players.playerMap.get(cleanChannelId); if (existing && !existing._destroyed) { logger.voice247(`[Rejoin] Channel ${cleanChannelId} already has a player — skipping.`); @@ -1320,20 +1140,17 @@ export class GatewayHandler { return; } - // Don't rejoin if a join is already pending if (remix.players._pendingJoins?.has?.(cleanChannelId)) { logger.voice247(`[Rejoin] Channel ${cleanChannelId} already has a pending join — skipping.`); return; } - // Don't rejoin if the bot was intentionally disconnected if (remix.intentionalLeaves.has(cleanChannelId)) { logger.voice247(`[Rejoin] Channel ${cleanChannelId} was intentionally left — skipping.`); this._rejoinAttempts.delete(cleanChannelId); return; } - // Verify the channel still exists const channel = remix.client?.channels?.get?.(cleanChannelId); if (!channel) { logger.voice247(`[Rejoin] Channel ${cleanChannelId} no longer exists — skipping.`); @@ -1341,7 +1158,6 @@ export class GatewayHandler { return; } - // Mark as in-progress to prevent concurrent attempts this._rejoinInProgress.add(cleanChannelId); const maxRetries = GatewayHandler.MAX_REJOIN_RETRIES; @@ -1354,7 +1170,6 @@ export class GatewayHandler { logger.voice247(`[Rejoin] Successfully rejoined channel ${cleanChannelId}`); this._rejoinAttempts.delete(cleanChannelId); - // Reseed voice states so we know about humans in the channel this.reseedVoiceStatesForChannel(cleanGuildId, cleanChannelId); return player; @@ -1365,8 +1180,6 @@ export class GatewayHandler { || errMsg.includes("Failed to create MediaPlayer"); if (isTrackTimeout && attempt < maxRetries) { - // Track publication timeout — likely transient (LiveKit overloaded). - // Retry with exponential backoff: 5s, 10s, 20s const backoffMs = 5_000 * Math.pow(2, attempt - 1); logger.voice247( `[Rejoin] Track publication failed for channel ${cleanChannelId} (attempt ${attempt}/${maxRetries}) — ` + @@ -1384,14 +1197,11 @@ export class GatewayHandler { ); this._rejoinAttempts.delete(cleanChannelId); - // If all retries exhausted, the channel will be picked up on next - // bot reboot via BootRecovery (for both %247 auto and %247 on). } finally { this._rejoinInProgress.delete(cleanChannelId); } } - // ── Called from Events.Ready ───────────────────────────────────────────────── /** * Invoke after the bot has connected and Moonlink has been initialised. @@ -1425,14 +1235,7 @@ export class GatewayHandler { for (const g of chunk) { const id = g?.id; if (!id) continue; - // Only add if not already cached by Fluxer if (!client.guilds.has(id)) { - // Insert a proper Guild instance (not a plain object) so that - // gateway handlers like MESSAGE_CREATE can safely access - // guild.members.set(), guild.channels, etc. without crashing. - // A plain { id, name, _stub: true } stub caused: - // TypeError: Cannot read properties of undefined (reading 'set') - // because guild.members was undefined. try { const Guild = this._getGuildClass(); if (Guild) { @@ -1440,8 +1243,6 @@ export class GatewayHandler { stub._stub = true; client.guilds.set(id, stub); } else { - // Fallback: create a safe stub with empty collections - // so that gateway handlers don't crash on .set() calls client.guilds.set(id, { id, name: g.name ?? "unknown", @@ -1454,7 +1255,6 @@ export class GatewayHandler { }); } } catch (stubErr) { - // If Guild constructor fails (e.g. missing data), use safe stub logger.guild(`[GuildSeed] Guild constructor failed for ${id}, using safe stub: ${stubErr?.message}`); client.guilds.set(id, { id, @@ -1493,9 +1293,6 @@ export class GatewayHandler { _getGuildClass() { if (this._GuildClass) return this._GuildClass; try { - // The Guild class is exported from @fluxerjs/core but not as a named - // export we can easily import. Instead, look at an existing guild - // in the cache and use its constructor. const { client } = this.remix; for (const guild of client.guilds.values()) { if (guild && !guild._stub && typeof guild.constructor === 'function' && guild.constructor.name === 'Guild') { @@ -1510,14 +1307,11 @@ export class GatewayHandler { onReady() { this.seedVoiceStatesFromGuilds(); - this.seedGuildsFromRest(); // fill in guilds Fluxer didn't cache via GUILD_CREATE + this.seedGuildsFromRest(); this.attachRawListener(); this.setupPresenceRotation(); - // End the startup grace period after the configured delay. - // Any deferred GuildDelete events that weren't cancelled by a GuildCreate - // will be processed at this point. setTimeout(() => { this._inStartupGrace = false; const pending = this._deferredGuildDeletes.size; @@ -1529,7 +1323,6 @@ export class GatewayHandler { } else { logger.guild(`[GuildDelete] Startup grace period ended. No deferred deletions.`); } - // Log suppressed count if we had more than 3 deferred deletes if (this._deferredDeleteCount > 3) { logger.guild( `[GuildDelete] (Suppressed ${this._deferredDeleteCount - 3} deferral log lines for brevity)` @@ -1537,7 +1330,6 @@ export class GatewayHandler { } }, this._startupDeleteGraceMs); - // ── Boot 24/7 auto-rejoin ────────────────────────────────────────────── this.rejoin247Channels(); } @@ -1555,7 +1347,6 @@ export class GatewayHandler { const { remix } = this; const channelsToRejoin = []; - // Collect all 24/7 channels from settings (both "auto" and "on" modes) for (const [guildId, serverSettings] of remix.settingsMgr.guilds) { const raw = serverSettings.get("stay_247"); if (!raw || raw === "none") continue; @@ -1567,7 +1358,6 @@ export class GatewayHandler { for (const channelId of channels) { const mode = get247ChannelMode(serverSettings, channelId); - // Rejoin both "auto" and "on" channels on boot if (mode === "auto" || mode === "on") { channelsToRejoin.push({ guildId, channelId, mode }); } @@ -1597,7 +1387,6 @@ export class GatewayHandler { await new Promise(resolve => setTimeout(resolve, staggerDelay)); } - // Don't rejoin if already has a player or pending join const existing = remix.players.playerMap.get(channelId); if (existing && !existing._destroyed) { logger.voice247(`[BootRecovery] Channel ${channelId} already has a player — skipping.`); @@ -1608,10 +1397,6 @@ export class GatewayHandler { continue; } - // Pre-validate: check if the channel still exists and is a voice channel. - // On Fluxer, if a channel was deleted while the bot was offline, the 24/7 - // setting still references it but the channel is gone. Without this check, - // _spawnPlayer throws "Channel not found" every boot. const channelObj = remix.client?.channels?.get?.(channelId); if (!channelObj) { logger.warn( @@ -1639,10 +1424,6 @@ export class GatewayHandler { continue; } - // If this guild already has an active 24/7 player from a previous - // iteration, joining another channel in the same guild may cause the - // Fluxer gateway to "move" the bot (disconnect from the first channel). - // Add extra delay to let the previous connection stabilize. const guildHasActivePlayer = [...remix.players.playerMap.values()] .some(p => !p._destroyed && String(p._guildId ?? "").replace(/\D/g, "") === guildId); if (guildHasActivePlayer && i > 0) { @@ -1666,14 +1447,13 @@ export class GatewayHandler { try { const player = await remix._spawnPlayer(guildId, channelId); - // Reseed voice states so we know about humans in the channel this.reseedVoiceStatesForChannel(guildId, channelId); logger.voice247( `[BootRecovery] Successfully rejoined channel ${channelId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]` + (bootRetries > 0 ? ` (after ${bootRetries} retry/retries)` : '') ); - break; // success — move to next channel + break; } catch (err) { bootRetries++; const errMsg = err?.message ?? String(err); @@ -1697,9 +1477,6 @@ export class GatewayHandler { (bootRetries > 1 ? ` (after ${bootRetries} attempts)` : '') ); - // Auto-cleanup: if all retries exhausted due to track publication - // failure, remove the channel from 24/7 so it doesn't block boot - // recovery on every restart. if (isTrackTimeout && bootRetries >= BOOT_MAX_RETRIES) { try { const set = remix.settingsMgr.getServer(guildId); @@ -1724,7 +1501,7 @@ export class GatewayHandler { } } - break; // non-retryable error or max retries exhausted + break; } } } @@ -1734,7 +1511,6 @@ export class GatewayHandler { ); } - // ── GuildDelete cleanup (extracted for deferred processing) ──────────────── /** * Perform the actual cleanup for a guild that the bot was removed from. @@ -1745,27 +1521,15 @@ export class GatewayHandler { _processGuildDelete(guildId) { const { remix } = this; const cleanGuildId = String(guildId).replace(/\D/g, ""); - // During startup grace batch, suppress individual cleanup logs to reduce spam const batchMode = this._deferredDeleteCount > 3; - // Protect 24/7 voice connections from GuildDelete cleanup ── - // During startup, the gateway sends GuildDelete for guilds that are - // temporarily unavailable. If we destroy players for 24/7 channels, - // BootRecovery has to rejoin from scratch, causing audio interruption. - // Instead, skip destroying players that have an active 24/7 mode - // and still have a healthy LiveKit room connection — the guild will - // come back via GuildCreate, and the voice connection stays alive. for (const [channelId, player] of remix.players.playerMap) { if (String(player._guildId ?? "").replace(/\D/g, "") !== cleanGuildId) continue; - // Check if this player is a 24/7 channel with an active connection const is247 = player._is247Enabled(); const roomAlive = player.connection?.room?.isConnected ?? false; if (is247 && roomAlive) { - // The LiveKit room is still connected and this is a 24/7 channel. - // The GuildDelete is stale (guild is temporarily unavailable). - // Keep the player alive — the guild will come back via GuildCreate. if (!batchMode) { logger.guild( `[GuildDelete] Preserving 24/7 player for channel ${channelId} ` + diff --git a/src/LastFmManager.mjs b/src/LastFmManager.mjs index 3321a82..7bc38da 100644 --- a/src/LastFmManager.mjs +++ b/src/LastFmManager.mjs @@ -8,7 +8,7 @@ * - Fetch loved / top / recent tracks for %play lastfm loved/top/recent * - Per-user session key storage in MySQL table `lastfm_users` * - * Last.fm API docs: https://www.last.fm/api + * Last.fm API docs: https: */ import crypto from "node:crypto"; @@ -25,18 +25,14 @@ function normalizeTrackText(value) { .toLowerCase(); } -// ── Helpers ──────────────────────────────────────────────────────────────────── /** * Build the API signature required by Last.fm for authenticated calls. - * See: https://www.last.fm/api/authspec#_8-signing-calls + * See: https: */ function buildSignature(params, apiSecret) { - // 1. Sort all parameter keys alphabetically const sorted = Object.keys(params).sort(); - // 2. Concatenate key+value pairs const str = sorted.map(k => k + params[k]).join(""); - // 3. Append secret return crypto.createHash("md5").update(str + apiSecret).digest("hex"); } @@ -48,11 +44,9 @@ function buildSignature(params, apiSecret) { * @returns {Promise} Parsed JSON response */ async function apiCall(params, apiSecret, post = false) { - // Per Last.fm spec: format must NOT be included in the signature. - // See: https://www.last.fm/api/authspec#_8-signing-calls const allParams = { ...params }; allParams.api_sig = buildSignature(allParams, apiSecret); - allParams.format = "json"; // add AFTER signature + allParams.format = "json"; const url = post ? BASE_URL : `${BASE_URL}?${new URLSearchParams(allParams)}`; @@ -77,7 +71,6 @@ async function apiCall(params, apiSecret, post = false) { return data; } -// ── LastFmManager ────────────────────────────────────────────────────────────── export class LastFmManager { /** @@ -88,10 +81,9 @@ export class LastFmManager { this.apiKey = config?.apiKey ?? ""; this.apiSecret = config?.apiSecret ?? ""; this.enabled = !!(this.apiKey && this.apiSecret); - this.scrobbleThreshold = config?.scrobbleThreshold ?? 0.5; // fraction of track duration - this.scrobbleMinMs = config?.scrobbleMinMs ?? 240_000; // 4 min fallback + this.scrobbleThreshold = config?.scrobbleThreshold ?? 0.5; + this.scrobbleMinMs = config?.scrobbleMinMs ?? 240_000; - // MySQL pool (lazy-created on first query) this._mysqlConfig = mysqlConfig; this._pool = null; @@ -100,10 +92,8 @@ export class LastFmManager { /** @type {boolean} Whether the bot_id column exists in the lastfm tables */ this._hasBotIdColumn = false; - // In-memory user cache: Map this._userCache = new Map(); - // Cache for total synced scrobbles (sum of all users' lifetime scrobble counts) this._totalScrobblesCache = null; this._totalScrobblesCacheExpiry = 0; this._totalScrobblesInflight = null; @@ -113,12 +103,10 @@ export class LastFmManager { } } - // ── Bot ID isolation ───────────────────────────────────────────────────── /** * Set the bot ID for multi-bot database isolation. * Ensures bot_id column exists in lastfm tables, then clears caches. - * @param {string} id - The bot's Discord user ID */ async setBotId(id) { const changed = this.botId !== id; @@ -139,22 +127,18 @@ export class LastFmManager { if (this._hasBotIdColumn) return; const pool = await this._getPool(); - // ── lastfm_users ────────────────────────────────────────────────────── const [cols] = await pool.execute( `SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_KEY FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'lastfm_users' AND COLUMN_NAME = 'bot_id'` ); if (cols.length === 0) { logger.settings("[LastFm] Auto-migrating: adding bot_id column to lastfm_users..."); - // NOT NULL DEFAULT '' — PK columns can't be NULL in MySQL await pool.execute("ALTER TABLE `lastfm_users` ADD COLUMN `bot_id` VARCHAR(32) NOT NULL DEFAULT ''"); - // Claim existing rows for the current bot if (this.botId) { await pool.execute("UPDATE `lastfm_users` SET `bot_id` = ? WHERE `bot_id` = ''", [String(this.botId)]); } await pool.execute("ALTER TABLE `lastfm_users` DROP PRIMARY KEY, ADD PRIMARY KEY (user_id, bot_id)"); logger.settings("[LastFm] Auto-migration complete: lastfm_users.bot_id added."); } else { - // Column exists — check if it's part of the PK const colInfo = cols[0]; const isNullable = colInfo.IS_NULLABLE === 'YES'; const isPK = colInfo.COLUMN_KEY === 'PRI'; @@ -172,7 +156,6 @@ export class LastFmManager { } } - // ── lastfm_stats ────────────────────────────────────────────────────── const [statsCols] = await pool.execute( `SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_KEY FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'lastfm_stats' AND COLUMN_NAME = 'bot_id'` ); @@ -215,11 +198,9 @@ export class LastFmManager { return { where: " AND bot_id = ?", params: [String(this.botId)] }; } - // ── MySQL ────────────────────────────────────────────────────────────────── async _getPool() { if (this._pool) return this._pool; - // Dynamic import so we don't crash if mysql2 isn't needed const mysql = await import("mysql2/promise"); this._pool = mysql.createPool({ host: this._mysqlConfig.host, @@ -245,14 +226,11 @@ export class LastFmManager { ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; `); - // Auto-migrate: add scrobble_count column if it doesn't exist (existing tables) try { await pool.execute("ALTER TABLE \`lastfm_users\` ADD COLUMN \`scrobble_count\` BIGINT NOT NULL DEFAULT 0 AFTER \`scrobble\`"); } catch { - // Column already exists — ignore } - // Stats table — single row tracking global scrobble counts await pool.execute(` CREATE TABLE IF NOT EXISTS \`lastfm_stats\` ( \`id\` TINYINT(1) NOT NULL PRIMARY KEY DEFAULT 1, @@ -260,13 +238,11 @@ export class LastFmManager { \`linked_users\` INT NOT NULL DEFAULT 0 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; `); - // Ensure the single row exists await pool.execute(` INSERT IGNORE INTO \`lastfm_stats\` (id, stored_scrobbles, linked_users) VALUES (1, 0, 0) `); } - // ── User persistence ─────────────────────────────────────────────────────── async getUser(userId) { const cached = this._userCache.get(userId); @@ -303,14 +279,12 @@ export class LastFmManager { const data = { sessionKey, username: username ?? "", scrobbleEnabled: true }; this._userCache.set(userId, data); - // Increment linked_users counter (only on new links, not re-links) try { await pool.execute( `UPDATE lastfm_stats SET linked_users = linked_users + 1 WHERE id = 1${f.where} AND NOT EXISTS (SELECT 1 FROM (SELECT 1 FROM lastfm_users WHERE user_id = ?${f.where} AND linked_at < NOW()) AS tmp)`, [...f.params, String(userId), ...f.params] ); } catch { - // Non-critical — don't fail the save } return data; @@ -334,7 +308,6 @@ export class LastFmManager { if (cached) cached.scrobbleEnabled = enabled; } - // ── Auth flow ────────────────────────────────────────────────────────────── /** * Step 1: Get an auth token. The user must visit the Last.fm auth URL to approve it. @@ -366,10 +339,9 @@ export class LastFmManager { { method: "auth.getsession", api_key: this.apiKey, token }, this.apiSecret ); - return data.session; // { key, name } + return data.session; } - // ── Scrobbling ───────────────────────────────────────────────────────────── /** * Send a "now playing" notification to Last.fm (does NOT count as a scrobble). @@ -393,7 +365,7 @@ export class LastFmManager { trackNumber: track.trackNumber ?? "", }, this.apiSecret, - true // POST + true ); } catch (err) { logger.warn(`[LastFm] updateNowPlaying failed for ${userId}: ${err.message}`); @@ -422,22 +394,19 @@ export class LastFmManager { "duration[0]": this._extractDurationSec(track), }, this.apiSecret, - true // POST + true ); logger.settings(`[LastFm] Scrobbled "${track.title}" for ${userId}`); - // Increment stored scrobbles counter (non-blocking) this._incrementScrobbleCount(userId); } catch (err) { logger.warn(`[LastFm] Scrobble failed for ${userId}: ${err.message}`); } } - // ── User data (for play command) ────────────────────────────────────────── /** * Get the user's loved tracks. - * @param {string} userId - Discord/Fluxer user ID * @param {number} [limit=20] - Max tracks to return * @returns {Promise>} */ @@ -534,7 +503,6 @@ export class LastFmManager { track, }; - // If user is linked, include their username for personal playcount if (userId) { const user = await this.getUser(userId); if (user) params.username = user.username; @@ -591,7 +559,6 @@ export class LastFmManager { let score = 0; - // ── Positive matching ──────────────────────────────────────────────── if (combined === normalizedQuery) score += 50; if (combined.includes(normalizedQuery) && normalizedQuery) score += 25; if (normalizedQuery.includes(nameNorm) && nameNorm) score += 15; @@ -600,10 +567,6 @@ export class LastFmManager { const overlap = queryTokens.filter(token => combined.includes(token)).length; score += overlap * 4; - // ── Penalize non-song results ──────────────────────────────────────── - // Track names that contain these phrases are usually lyric videos, - // official videos, or other non-song entries that shouldn't be the - // top result when a user is searching for the actual song. const nameLower = name.toLowerCase(); const artistLower = artist.toLowerCase(); const urlLower = String(track.url ?? "").toLowerCase(); @@ -616,7 +579,7 @@ export class LastFmManager { /\blyric video\b/, /\blyrics video\b/, /\bmusic video\b/, - /\bofficial audio\b/, // some entries are titled "Official Audio" on last.fm + /\bofficial audio\b/, /\bvisuali[sz]er\b/, /\bkaraoke\b/, /\bcover\b/, @@ -628,20 +591,18 @@ export class LastFmManager { /\breverb\b/, /\bnightcore\b/, /\b8d\b/, - /\bclip officiel\b/, // French official video - /\bvideo oficial\b/, // Spanish/Portuguese official video + /\bclip officiel\b/, + /\bvideo oficial\b/, /\bperformance\b/, ]; for (const re of negativePatterns) { if (re.test(fullText)) { score -= 30; - break; // only penalize once per track + break; } } - // Penalize results where the artist is a label/production company - // instead of the actual artist (e.g. "Sony Pictures Animation") const labelKeywords = [ /\bpictures\b/i, /\banimation\b/i, @@ -660,17 +621,12 @@ export class LastFmManager { } } - // Penalize results where the track name is wrapped in quotes - // (e.g. '"Soda Pop" Official Lyric Video' — the quotes indicate - // it's a video title, not the actual track name) if (/^["""].*["""]$/.test(name) || /["""]/.test(name)) { score -= 15; } - // Prefer results that have a clean /music/Artist/_/Track URL format - // (actual tracks) over /music/Artist/Track+Extra+Stuff (video entries) if (urlLower.includes("/_/")) { - score += 5; // Clean track URL format + score += 5; } return { @@ -691,10 +647,10 @@ export class LastFmManager { /** * Parse a Last.fm music URL and extract artist and track info. * Supports: - * https://www.last.fm/music/Drake/ICEMAN/Make+Them+Cry - * https://www.last.fm/music/SAJA+BOYS/_/Soda+Pop - * https://www.last.fm/music/Drake/_/Make+Them+Cry ("_" = album placeholder) - * https://www.last.fm/music/Drake (artist only) + * https: + * https: + * https: + * https: * * @param {string} url * @returns {{ artist: string, track: string|null, album: string|null, url: string } | null} @@ -704,8 +660,6 @@ export class LastFmManager { const u = new URL(url); if (!/^(?:www\.)?last\.fm$/i.test(u.hostname)) return null; - // Path format: /music/Artist[/Album][/Track] - // Or: /music/Artist/_/Track (underscore = album placeholder) const match = u.pathname.match(/^\/music\/([^/]+)(?:\/([^/]+))?(?:\/([^/]+))?/); if (!match) return null; @@ -717,11 +671,9 @@ export class LastFmManager { let album = null; if (segment3) { - // /music/Artist/Album/Track or /music/Artist/_/Track album = segment2 === "_" ? null : segment2; track = segment3; } else if (segment2 && segment2 !== "_") { - // /music/Artist/Track (no album segment) track = segment2; } @@ -765,7 +717,6 @@ export class LastFmManager { return data.user; } - // ── Playlists & Albums ──────────────────────────────────────────────────────── /** * Get a list of the user's Last.fm playlists by scraping their profile page. @@ -790,9 +741,6 @@ export class LastFmManager { const html = await res.text(); const playlists = []; - // Parse playlist links from the HTML - // Last.fm playlist links look like: /user/USERNAME/playlists/123456 - // Each playlist item has a .playlist-item or similar container const playlistRegex = /href="\/user\/[^/]+\/playlists\/(\d+)"[^>]*>([^<]+)<\/a>/gi; let match; while ((match = playlistRegex.exec(html)) !== null) { @@ -807,14 +755,12 @@ export class LastFmManager { } } - // Try to extract track counts (e.g. "12 tracks" or "1 track") const countRegex = /(\d+)\s+track/gi; const counts = []; let cMatch; while ((cMatch = countRegex.exec(html)) !== null) { counts.push(+cMatch[1]); } - // Pair counts with playlists (order should match) playlists.forEach((pl, i) => { pl.trackCount = counts[i] ?? 0; }); @@ -837,10 +783,9 @@ export class LastFmManager { let playlistUrl; - // If playlistId is a number, look up the playlist URL from the user's playlists if (/^\d+$/.test(String(playlistId))) { const playlists = await this.getPlaylists(userId); - const idx = +playlistId - 1; // 1-based to 0-based + const idx = +playlistId - 1; if (idx < 0 || idx >= playlists.length) { throw new Error(`Playlist #${playlistId} not found. You have ${playlists.length} playlist(s). Use \`%lastfm playlists\` to see them.`); } @@ -848,11 +793,9 @@ export class LastFmManager { } else if (String(playlistId).startsWith("http")) { playlistUrl = String(playlistId); } else { - // Assume it's a playlist ID slug — build the URL playlistUrl = `https://www.last.fm/user/${user.username}/playlists/${playlistId}`; } - // Scrape the playlist page for track info const res = await fetch(playlistUrl, { headers: { "User-Agent": "RemixBot/1.0 (Last.fm Integration)" }, }); @@ -864,24 +807,18 @@ export class LastFmManager { const html = await res.text(); const tracks = []; - // Last.fm playlist pages contain track items with: - // Track Name - // We extract artist and track from the URL pattern /music/Artist+Name/Track+Name const trackLinkRegex = /href="\/music\/([^"]+?)"[^>]*class="[^"]*(?:link-block-target|chartlist-name)[^"]*"[^>]*>([^<]+)<\/a>/gi; let tMatch; while ((tMatch = trackLinkRegex.exec(html)) !== null && tracks.length < limit) { const urlPath = decodeURIComponent(tMatch[1]); const name = tMatch[2].trim(); - // URL format: /music/Artist+Name/Track+Name or /music/Artist+Name/_/Track+Name const parts = urlPath.split("/"); let artist = "Unknown"; if (parts.length >= 1) { artist = parts[0].replace(/\+/g, " "); } if (parts.length >= 3 && parts[1] === "_") { - // /music/Artist/_/Track format } else if (parts.length >= 2) { - // /music/Artist/Track format — the track name from URL } if (name && name !== "Unknown") { @@ -894,7 +831,6 @@ export class LastFmManager { } } - // Fallback: try a broader regex if the first one didn't find anything if (!tracks.length) { const broadRegex = /href="\/music\/([^"]+)"[^>]*>([^<]{2,80})<\/a>/gi; const seen = new Set(); @@ -902,7 +838,6 @@ export class LastFmManager { while ((bMatch = broadRegex.exec(html)) !== null && tracks.length < limit) { const urlPath = decodeURIComponent(bMatch[1]); const name = bMatch[2].trim(); - // Only include actual track links (Artist/Track or Artist/_/Track) const parts = urlPath.split("/"); if (parts.length < 2) continue; if (seen.has(urlPath)) continue; @@ -958,7 +893,6 @@ export class LastFmManager { })); } - // ── Play helper (for %lastfm play and %play lastfm:loved etc.) ───────────── /** * Fetch tracks from Last.fm by category and return search queries @@ -988,7 +922,6 @@ export class LastFmManager { break; case "recent": tracks = await this.getRecentTracks(userId, limit); - // Filter out "now playing" entries (they have no finished timestamp) tracks = tracks.filter(t => !t.now); break; case "playlist": @@ -996,13 +929,11 @@ export class LastFmManager { tracks = await this.getPlaylistTracks(userId, options.playlistId, limit); break; case "albums": - // Top albums — we fetch albums, then for each album we use the album name + artist as search query const albums = await this.getTopAlbums(userId, options.period ?? "overall", limit); tracks = albums.map(a => ({ artist: a.artist, name: a.name, url: a.url, - // For albums, search the album name + artist to get the full album query: `${a.artist} ${a.name} album`, image: a.image ?? "", })); @@ -1025,7 +956,6 @@ export class LastFmManager { }; } - // ── Global stats ──────────────────────────────────────────────────────────── /** * Get the total lifetime scrobbles across ALL linked Last.fm users. @@ -1038,12 +968,10 @@ export class LastFmManager { async getTotalScrobbles(concurrency = 3) { if (!this.enabled) return 0; - // Return cached value if still fresh if (this._totalScrobblesCache !== null && Date.now() < this._totalScrobblesCacheExpiry) { return this._totalScrobblesCache; } - // Deduplicate concurrent calls if (this._totalScrobblesInflight) return this._totalScrobblesInflight; this._totalScrobblesInflight = this._refreshTotalScrobbles(concurrency); @@ -1061,7 +989,6 @@ export class LastFmManager { try { const pool = await this._getPool(); - // Get all linked user IDs const f = this._botIdFilter(); const [rows] = await pool.execute( `SELECT user_id FROM lastfm_users WHERE 1=1${f.where}`, @@ -1074,16 +1001,13 @@ export class LastFmManager { return 0; } - // Sync each user's scrobble count from the Last.fm API (with concurrency limit) const userIds = rows.map(r => r.user_id); - // Batch the sync calls to avoid overloading the Last.fm API for (let i = 0; i < userIds.length; i += concurrency) { const batch = userIds.slice(i, i + concurrency); await Promise.allSettled(batch.map(uid => this.syncUserScrobbleCount(uid))); } - // Now sum up all scrobble_count values from the DB const [sumRows] = await pool.execute( `SELECT COALESCE(SUM(scrobble_count), 0) AS total FROM lastfm_users WHERE 1=1${f.where}`, [...f.params] @@ -1097,7 +1021,6 @@ export class LastFmManager { return total; } catch (err) { logger.warn(`[LastFm] _refreshTotalScrobbles failed: ${err.message}`); - // Return stale cache if available, otherwise 0 return this._totalScrobblesCache ?? 0; } } @@ -1133,7 +1056,6 @@ export class LastFmManager { const pool = await this._getPool(); const f = this._botIdFilter(); - // Get total count const [countRows] = await pool.execute( `SELECT COUNT(*) AS total FROM lastfm_users WHERE scrobble_count > 0${f.where}`, [...f.params] @@ -1141,7 +1063,6 @@ export class LastFmManager { const totalUsers = Number(countRows[0]?.total ?? 0); const totalPages = Math.max(1, Math.ceil(totalUsers / perPage)); - // Clamp page page = Math.max(0, Math.min(page, totalPages - 1)); const offset = page * perPage; @@ -1183,7 +1104,6 @@ export class LastFmManager { } } - // ── Internal helpers ─────────────────────────────────────────────────────── _assertEnabled() { if (!this.enabled) throw new Error("Last.fm integration is not configured (missing apiKey/apiSecret)."); @@ -1231,7 +1151,6 @@ export class LastFmManager { _extractDurationSec(track) { if (!track.duration) return ""; - // Duration can be: { seconds: N }, "PT3M0S", or milliseconds number if (typeof track.duration === "object" && track.duration.seconds) return track.duration.seconds; if (typeof track.duration === "number") return Math.round(track.duration / 1000); if (typeof track.duration === "string") { @@ -1253,7 +1172,7 @@ export class LastFmManager { ? track.duration : null; - if (!durationMs || durationMs < 30_000) return false; // too short + if (!durationMs || durationMs < 30_000) return false; const normalizedTitle = normalizeTrackText(this._extractTitle(track)); const normalizedArtist = normalizeTrackText(this._extractArtist(track)); diff --git a/src/MessageHandler.mjs b/src/MessageHandler.mjs index 318f111..326391d 100644 --- a/src/MessageHandler.mjs +++ b/src/MessageHandler.mjs @@ -31,7 +31,6 @@ export const OPTIONAL_PERMISSIONS = ["AddReactions", "ReadMessageHistory", "Mana export function parseColor(value, fallback = 0xe9196c) { if (!value) return fallback; if (typeof value === "number") return value; - // Strip leading # ("‌#ff0000" → "ff0000") or 0x prefix ("0xe9196c" → "e9196c") const cleaned = String(value).replace(/^#/, "").replace(/^0x/i, ""); const n = parseInt(cleaned, 16); return isNaN(n) ? fallback : n; @@ -92,7 +91,6 @@ export class MessageHandler { setupEvents() { const reactionUpdate = (reaction, user) => { - // fluxerjs reaction events pass a MessageReaction and a User const messageId = reaction.message?.id ?? reaction.messageId; const emoji = reaction.emoji?.name ?? reaction.emoji?.id ?? reaction.emoji; const event = { user_id: user.id, emoji_id: emoji }; @@ -118,19 +116,17 @@ export class MessageHandler { * @returns {string[]} Missing permission flag keys. */ checkPermissions(permissions, channel) { - if (!channel?.guild) return []; // DMs — no guild perms + if (!channel?.guild) return []; const me = channel.guild.members?.me ?? null; if (!me) { logger.warn("[MessageHandler] Cannot check permissions — guild.members.me is null"); - return []; // can't verify + return []; } const perms = channel.permissionsFor?.(me) ?? null; if (!perms) { logger.warn("[MessageHandler] Cannot check permissions — channel.permissionsFor() unavailable"); - return []; // can't verify + return []; } - // Convert string names (e.g. "SendMessages") to numeric PermissionFlags values, - // same as CommandHandler.assertRequirements does. return permissions.filter(p => !perms.has(PermissionFlags[p] ?? p)); } @@ -177,7 +173,7 @@ export class MessageHandler { } } - const embed = new EmbedBuilder().setColor(0xFF4444); // Red for errors + const embed = new EmbedBuilder().setColor(0xFF4444); if (criticalItems.length > 0) { embed.setTitle("Missing Permissions — Bot Cannot Work Properly"); @@ -192,7 +188,7 @@ export class MessageHandler { "Some features may not work without these permissions, but the bot can still play music.\n\n" + optionalItems.join("\n") ); - embed.setColor(0xFFA500); // Orange for warnings + embed.setColor(0xFFA500); } embed.setFooter({ @@ -209,7 +205,6 @@ export class MessageHandler { * @returns {Promise} If all permissions are given. */ async assertPermissions(permissions, message) { - // Ensure bot's guild member is cached before checking const guild = message.guild ?? await message.client?.guilds?.resolve?.(message.guildId); if (guild && !guild.members?.me) { try { await guild.members.fetchMe(); } catch (_) { /* fetch failed, checkPermissions will warn */ } @@ -229,12 +224,10 @@ export class MessageHandler { return false; } - // Build a rich embed listing what's missing and why const permEmbed = this.buildPermissionEmbed(missing, message.guildId); try { await message.reply({ embeds: [permEmbed] }, { ping: false }); } catch (e) { - // If reply fails (e.g. also missing EmbedLinks), fall back to plain text logger.warn("[MessageHandler] Failed to send permission embed:", e.message); try { const names = missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k); @@ -264,8 +257,6 @@ export class MessageHandler { * @returns {Message|null} */ get(id) { - // channel.messages is a MessageManager — @fluxerjs/core may not expose it. - // Guard with optional chaining so the loop is a no-op if the property is absent. for (const channel of this.client.channels.values()) { const msg = channel.messages?.get?.(id) ?? null; if (msg) return new Message(msg, this); @@ -283,8 +274,6 @@ export class MessageHandler { const cached = this.get(id); if (cached) return cached; const channel = await this.client.channels.fetch(channelId); - // channel.fetchMessage() is the @fluxerjs/core method. - // Fall back to the channel.messages.fetch() if the former is absent. const raw = typeof channel.fetchMessage === "function" ? await channel.fetchMessage(id) : await channel.messages?.fetch?.(id); @@ -390,7 +379,6 @@ export class MessageHandler { if (!(await this.assertPermissions(["SendMessages", "EmbedLinks"], replyingTo))) return null; let opts; if (typeof message === "string") { - // Auto-wrap plain text in an embed (matches old replyEmbed behavior) opts = this.#createEmbed(message, replyingTo); } else { opts = { ...message }; @@ -407,7 +395,6 @@ export class MessageHandler { async replyEmbed(replyingTo, message, options = {}) { if (!(await this.assertPermissions(["SendMessages", "EmbedLinks"], replyingTo))) return null; - // Raw embed payload — pass straight through without re-wrapping if (typeof message === "object" && Array.isArray(message.embeds)) { return new Message(await replyingTo.reply(message, { ping: false }), this); } @@ -438,7 +425,6 @@ export class MessageHandler { } let opts; if (typeof message === "string") { - // Auto-wrap plain text in an embed (matches old sendEmbed behavior) opts = this.#createEmbed(message, channel); } else { opts = message; @@ -456,7 +442,6 @@ export class MessageHandler { if (this.checkPermissions(["SendMessages", "EmbedLinks"], channel).length !== 0) { return this.sendMessage(channel, typeof content === "string" ? content : content?.embedText ?? ""); } - // Raw embed payload — pass straight through without re-wrapping if (typeof content === "object" && Array.isArray(content.embeds)) { return new Message(await channel.send(content), this); } @@ -476,12 +461,10 @@ export class MessageHandler { * @returns {Promise} */ async editEmbed(message, content, embedOptions = {}) { - // Transient HTTP status codes worth retrying (gateway/server hiccups). const RETRYABLE = new Set([502, 503, 504]); const MAX_ATTEMPTS = 3; const RETRY_DELAY_MS = 1500; - // Build the payload once, outside the retry loop. let payload; if (typeof content === "object" && Array.isArray(content.embeds)) { payload = content; @@ -499,13 +482,11 @@ export class MessageHandler { try { return new Message(await message.edit(payload), this); } catch (err) { - // Message was deleted — nothing to edit, bail silently. if (err.code === "UNKNOWN_MESSAGE" || err.code === 10008) { logger.warn("[MessageHandler] editEmbed: Message no longer exists, skipping edit."); return null; } - // Retry on transient gateway errors (502/503/504). if (RETRYABLE.has(err.statusCode) && attempt < MAX_ATTEMPTS) { logger.warn(`[MessageHandler] editEmbed: ${err.statusCode} on attempt ${attempt}/${MAX_ATTEMPTS}, retrying in ${RETRY_DELAY_MS}ms…`); await new Promise(r => setTimeout(r, RETRY_DELAY_MS)); @@ -545,7 +526,6 @@ export class MessageHandler { m.edit(send()).catch(() => {}); }); - // Auto-close after 5 minutes const guildId = msg.message?.guildId ?? null; setTimeout(() => { unobserve(); @@ -561,7 +541,6 @@ export class MessageHandler { const { joinVoiceChannel } = await import("@fluxerjs/voice"); const channel = await this.client.channels.fetch(channelId); if (!channel || !("guildId" in channel)) throw new Error("Cannot join a non-guild voice channel."); - // @fluxerjs/voice API: joinVoiceChannel(client, channel) — NOT the old object style return joinVoiceChannel(this.client, channel); } } @@ -777,13 +756,13 @@ export class PageBuilder { setForm(form) { this.form = form; - this.initiated = false; // reset so createPages() rebuilds if called again + this.initiated = false; return this; } setMaxLines(maxLinesPerPage = 2) { this.maxLinesPerPage = maxLinesPerPage; - this.initiated = false; // reset so createPages() rebuilds with new page size + this.initiated = false; return this; } @@ -912,7 +891,6 @@ export class RichPaginator { const tabEmojis = this._tabs.map(t => t.emoji); const allReactions = [...tabEmojis, this._prev, this._next]; - // Send initial embed const nativeMsg = this._msg.message ?? this._msg; if (!nativeMsg?.reply) return null; @@ -925,7 +903,6 @@ export class RichPaginator { const guildId = (this._msg.channel?.guildId) ?? (this._msg.guildId) ?? null; - // Add reactions for (const emoji of allReactions) { await rawMsg.react(emoji).catch(() => {}); } @@ -964,7 +941,6 @@ export class RichPaginator { } catch (e) { logger.warn("[RichPaginator] removeAllReactions failed:", e?.message ?? e); } - // Fallback: remove each bot reaction individually for (const emoji of allReactions) { try { await rawMsg.removeReaction(emoji); @@ -972,10 +948,8 @@ export class RichPaginator { } }; - // Timer resets on every reaction interaction const closeSession = async () => { unobserve(); - // Update footer to show session closed const currentEmbed = buildEmbed(state.tab, state.page); if (!currentEmbed.footer) currentEmbed.footer = { text: "" }; currentEmbed.footer.text += " • " + this._handler.t(guildId, "pagination.embed.sclosedTitle"); @@ -990,7 +964,6 @@ export class RichPaginator { timer = setTimeout(closeSession, this._timeout); }; - // Wrap reaction handler to reset timer on each interaction const origHandler = wrapped.handler.observedReactions.get(rawMsg.id); if (origHandler) { const origCb = origHandler.cb; @@ -1051,7 +1024,6 @@ export class QueuePaginator { const guildId = (this._msg.channel?.guildId) ?? (this._msg.guildId) ?? null; - // No arrows needed for single page if (totalPages <= 1) return rawMsg; const prev = this._prev; @@ -1108,26 +1080,10 @@ export class QueuePaginator { } } -// ─── HelpCommand ────────────────────────────────────────────────────────────── -// Self-contained help command — no help.mjs needed. -// -// Usage in index.mjs (inside the Remix constructor, after commands are set up): -// -// import { HelpCommand } from "./src/MessageHandler.mjs"; -// -// new HelpCommand(this.handler, this.messages, (msg) => this.getSettings(msg)) -// .register(); -// -// That's it. %help, %h, and %commands all work automatically. -// The \x00help hack in index.mjs and the commands.helpCommand override are -// no longer needed — remove them both. const HELP_CMDS_PER_PAGE = 10; -const HELP_SESSION_MS = 30 * 1000; // 30 seconds +const HELP_SESSION_MS = 30 * 1000; -// ── Tab definitions ─────────────────────────────────────────────────────────── -// Add or remove tabs here. `categories` maps to cmd.category values set via -// .setCategory() on CommandBuilder. `static: true` renders a hand-written page. const HELP_TABS = [ { emoji: "🏠", @@ -1227,26 +1183,19 @@ 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 this._commands.helpCommand = "\x00help"; const _fmt = this._commands.format.bind(this._commands); this._commands.format = (text, guildId) => _fmt(text, guildId).replace(/\x00help/g, "help"); - // Intercept replyHandler to swallow the "Unknown Command" error - // that CommandHandler emits when it sees %help but can't find it. const _reply = this._commands.replyHandler.bind(this._commands); this._commands.replyHandler = (message, msg) => { if (typeof message === "string" && message.toLowerCase().includes("unknown command")) { - // Check if the triggering command was a help alias — if so, drop it silently const content = msg?.content ?? msg?.message?.content ?? ""; const guildId = msg?.channel?.channel?.guildId ?? msg?.message?.guildId; const prefix = this._commands.getPrefix(guildId); @@ -1259,13 +1208,12 @@ export class HelpCommand { else if (content.startsWith(ping)) body = content.slice(ping.length).trim(); if (body !== null) { const first = body.split(/\s+/)[0]?.toLowerCase(); - if (HELP_ALIASES.includes(first)) return; // silently drop + if (HELP_ALIASES.includes(first)) return; } } return _reply(message, msg); }; - // Safety evict in case help.mjs is still present const evict = () => { for (const alias of HELP_ALIASES) { const i = this._commands.commandNames.indexOf(alias); @@ -1284,7 +1232,6 @@ export class HelpCommand { return r; }; - // Our sole listener for help this._messages.onMessage((msg) => { if (!msg?.content) return; const content = msg.content.trim(); @@ -1307,15 +1254,12 @@ export class HelpCommand { }); } - // ── Internal handler ─────────────────────────────────────────────────────── _handle(msg, args, prefix) { const allCmds = this._commands.commands; const query = (args[0] ?? "").trim(); - // ── Specific command lookup (%help play, %help settings get, …) ────────── if (query && isNaN(Number(query))) { - // Walk subcommands: %help settings get → finds "settings" then "get" let currCmd = null; for (const word of [query, ...args.slice(1)]) { const pool = currCmd ? currCmd.subcommands : allCmds; @@ -1335,7 +1279,6 @@ export class HelpCommand { return; } - // ── Tab jump by number (%help 2 → open tab index 1) ────────────────────── const startTab = query ? Math.max(0, Math.min(HELP_TABS.length - 1, parseInt(query) - 1)) : 0; diff --git a/src/MoonlinkManager.mjs b/src/MoonlinkManager.mjs index 0714b7d..999f49d 100644 --- a/src/MoonlinkManager.mjs +++ b/src/MoonlinkManager.mjs @@ -9,9 +9,6 @@ import { logger } from "./constants/Logger.mjs"; import { EventEmitter } from "node:events"; import { Events } from "@fluxerjs/core"; -// ═══════════════════════════════════════════════════════════════════════════════ -// MoonlinkManager ────────────────────────────────────────────────────────────── -// ═══════════════════════════════════════════════════════════════════════════════ export class MoonlinkManager extends EventEmitter { /** @type {Manager} */ diff --git a/src/Player.mjs b/src/Player.mjs index f9d2cee..58c0893 100644 --- a/src/Player.mjs +++ b/src/Player.mjs @@ -36,8 +36,6 @@ function mkEmbed(desc) { /** 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(); /** @@ -69,14 +67,13 @@ function sanitizeError(msg, nl = {}) { 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); for (const re of regexes) { - re.lastIndex = 0; // reset stateful global regexes between calls + re.lastIndex = 0; s = s.replace(re, re.source.includes("redacted") ? "[redacted]" : "[internal]"); } return s; @@ -87,19 +84,15 @@ function isIgnorableMediaStateError(err) { return msg.includes("InvalidState") || msg.includes("failed to capture frame") || msg.includes("capture frame"); } -// ═══════════════════════════════════════════════════════════════════════════════ -// PlayerWorkerPool — persistent worker pool to avoid spawning a new Node.js -// isolate (~40 MB V8 heap) for every search/play command. -// ═══════════════════════════════════════════════════════════════════════════════ class PlayerWorkerPool { constructor(size, workerPath, nlConfig = {}) { this._size = size; this._workerPath = workerPath; this._nlConfig = nlConfig; - this._workers = []; // { worker, busy, _currentJobKey } - this._queue = []; // { jobKey, msg, resolve, reject, onMessage } - this._pending = new Map(); // jobKey → { resolve, reject, onMessage } + this._workers = []; + this._queue = []; + this._pending = new Map(); this._jobCounter = 0; for (let i = 0; i < size; i++) this._spawn(); @@ -109,8 +102,6 @@ class PlayerWorkerPool { const worker = new Worker(this._workerPath, { workerData: { poolMode: true, - // Pass NodeLink config so the module-level nlGet fallback - // has the correct host/port/password if _nlGet is ever null. data: { nodelink: this._nlConfig ?? {} } } }); @@ -141,9 +132,6 @@ class PlayerWorkerPool { }); worker.on("error", (err) => { - // Release only the job currently assigned to THIS worker. - // Iterating all _pending would incorrectly reject in-flight jobs - // from other workers, leaving those workers stuck busy=true forever. if (entry._currentJobKey != null) { const cb = this._pending.get(entry._currentJobKey); if (cb) { @@ -153,7 +141,6 @@ class PlayerWorkerPool { entry._currentJobKey = null; } entry.busy = false; - // Replace dead worker const errIdx = this._workers.indexOf(entry); if (errIdx !== -1) this._workers.splice(errIdx, 1); this._spawn(); @@ -207,9 +194,6 @@ class PlayerWorkerPool { } } -// ═══════════════════════════════════════════════════════════════════════════════ -// Queue Class -// ═══════════════════════════════════════════════════════════════════════════════ export class Queue extends EventEmitter { data = []; @@ -308,50 +292,37 @@ export class Queue extends EventEmitter { } } -// ═══════════════════════════════════════════════════════════════════════════════ -// Player Class -// ═══════════════════════════════════════════════════════════════════════════════ export default class Player extends EventEmitter { /** @type {import("revoice.js").VoiceConnection|null} */ connection = null; _guildId = null; _channelId = null; - // The channel this player was originally spawned/assigned to for 247 mode. - // Set externally by spawnPlayer after joining. Used by _is247Enabled() so - // that even if the bot is temporarily in a transit channel (e.g. "move"), - // the player knows its intended home channel and can check 247 correctly. _home247Channel = null; - // Components queue = null; client = null; settings = null; config = {}; - // revoice.js instances /** @type {import("revoice.js").MediaPlayer|null} */ _mediaPlayer = null; /** @type {import("./constants/FluxerRevoice.mjs").FluxerRevoice|null} Shared FluxerRevoice instance (injected from Remix) */ _revoice = null; - // moonlink.js manager reference (set by PlayerManager) /** @type {import("./MoonlinkManager.mjs").MoonlinkManager|null} */ _moonlink = null; - // Playback state leaving = false; _paused = false; - _pausedAt = null; // track exact moment of pause for clock sync + _pausedAt = null; _playingNext = false; startedPlaying = null; - // searches Map with max-size eviction to prevent memory leak on busy servers. searches = new Map(); _searchMaxSize = 50; - _maxQueueSize = 10_000; // Max tracks in queue to prevent unbounded memory growth + _maxQueueSize = 10_000; resultLimit = 5; preferredVolume = 1; - // Streaming state _streamingStopped = false; _skipping = false; _currentPassthrough = null; @@ -359,22 +330,17 @@ export default class Player extends EventEmitter { _radioAnnounced = false; _queueEndedSent = false; - // Active audio filter — { key, label, payload } or null activeFilter = null; activeFilterPayload = null; - // Inactivity timeout _inactivityTimer = null; - _inactivityLimit = 3 * 60 * 1000; // 3 min default - _pendingInactivityCheck = false; // Guard to prevent race between join() timer and reseed + _inactivityLimit = 3 * 60 * 1000; + _pendingInactivityCheck = false; - // Join mutex — prevents concurrent join() calls from racing each other _isJoining = false; - // destroyed flag — prevents playback/worker spawn after destroy() _destroyed = false; - // NodeLink config (kept for direct stream URL building; session managed by moonlink) _nl = { host: "localhost", port: 3000, @@ -395,14 +361,12 @@ export default class Player extends EventEmitter { this._voiceCache = opts.voiceCache ?? null; this.locale = opts.locale ?? null; - // Merge NodeLink config (for stream URL building) this._nl = { ...this._nl, ...(this.config?.nodelink ?? {}), ...(opts.nodelink ?? {}), }; - // Set inactivity limit const inactivityMs = this.config?.timers?.inactivityTimeout ?? this.config?.inactivityTimeout; if (inactivityMs !== undefined) { const parsed = Number(inactivityMs); @@ -411,13 +375,10 @@ export default class Player extends EventEmitter { } } - // moonlink.js manager reference — injected by PlayerManager this._moonlink = opts.moonlink ?? null; - // revoice.js shared instance — injected by PlayerManager this._revoice = opts.revoice ?? null; - // Robust session sync that handles stale sessions if (this._moonlink) { this._onMoonlinkReady = (sessionId) => { const oldId = this._nl.sessionId; @@ -427,7 +388,6 @@ export default class Player extends EventEmitter { } }; this._moonlink.on("ready", this._onMoonlinkReady); - // Immediate sync if moonlink is already ready const existingSession = this._moonlink.getLiveSessionId?.() ?? this._moonlink.sessionId; if (existingSession) { this._nl.sessionId = existingSession; @@ -435,9 +395,6 @@ export default class Player extends EventEmitter { } } - // ═══════════════════════════════════════════════════════════════════════════ - // 24/7 Mode Check - // ═══════════════════════════════════════════════════════════════════════════ /** * Check if 24/7 mode is enabled for this player's channel. @@ -467,22 +424,16 @@ export default class Player extends EventEmitter { ? raw.map(id => String(id).replace(/\D/g, "")).filter(Boolean) : [String(raw).replace(/\D/g, "")]; - // Use the home channel this player was assigned to for 247 — this is - // set by spawnPlayer and doesn't change when the bot is temporarily - // moved to a transit channel. This gives a per-player 247 check that - // works correctly with multi-voice-per-guild setups. const homeChannel = this._home247Channel ? String(this._home247Channel).replace(/\D/g, "") : null; const currentChannel = String(this._channelId ?? "").replace(/\D/g, ""); - // Determine which channel to check the mode for const matchChannel = channels.includes(homeChannel) ? homeChannel : channels.includes(currentChannel) ? currentChannel : null; if (!matchChannel) return "off"; - // Per-channel mode lookup: each channel can have its own on/auto/off return get247ChannelMode(set, matchChannel); }; @@ -502,7 +453,6 @@ export default class Player extends EventEmitter { const cleanGuild = String(this._guildId ?? "").replace(/\D/g, ""); if (cleanGuild) return cleanGuild; - // Fallback: resolve from the channel object try { const channelId = this._channelId ?? this._home247Channel; if (channelId) { @@ -515,10 +465,6 @@ export default class Player extends EventEmitter { return null; } - // ═══════════════════════════════════════════════════════════════════════════ - // ═══════════════════════════════════════════════════════════════════════════ - // Volume Restore - // ═══════════════════════════════════════════════════════════════════════════ _restoreVolume() { if (!this._guildId) return; @@ -545,21 +491,16 @@ export default class Player extends EventEmitter { } } - // ═══════════════════════════════════════════════════════════════════════════ - // Inactivity Timer - // ═══════════════════════════════════════════════════════════════════════════ _hasHumansInChannel() { if (!this._channelId || !this._guildId) return false; const cleanChan = String(this._channelId).replace(/\D/g, ""); const cleanGuild = String(this._guildId).replace(/\D/g, ""); - // O(1) lookup via VoiceStateCache channelMembers index if (this._voiceCache && this._voiceCache.hasHumansInChannel(cleanGuild, cleanChan)) { return true; } - // Legacy fallback: iterate observedVoiceUsers (O(n)) try { const voiceUsers = this._observedVoiceUsers; if (voiceUsers && typeof voiceUsers.iterateHumanUsers === "function") { @@ -570,7 +511,6 @@ export default class Player extends EventEmitter { ) return true; } } else if (voiceUsers) { - // Raw Map fallback (shouldn't happen with new code) for (const [, info] of voiceUsers) { if ( String(info.guildId ?? "").replace(/\D/g, "") === cleanGuild && @@ -600,7 +540,6 @@ export default class Player extends EventEmitter { } } catch (_) {} - // LiveKit participant fallback try { const room = this.connection?.room; if (room?.isConnected && room.remoteParticipants) { @@ -622,17 +561,11 @@ export default class Player extends EventEmitter { const mode = this._get247Mode(); logger.inactivity(`[Player] Checking 24/7 mode for guild ${this._guildId}: ${mode}`); - // %247 auto: bot always stays in voice, never start inactivity timer - // %247 on: bot stays in voice permanently — never start inactivity timer - // %247 off: bot leaves when alone — timer is allowed if (mode === "auto" || mode === "on") { logger.inactivity(`[Player] 24/7 ${mode} mode active for guild ${this._guildId}, skipping inactivity timer`); return; } - // Don't start the inactivity timer if there is a song currently playing - // or songs waiting in the queue — the bot should stay as long as there's - // music to play, even if no humans are currently in the channel. if (this.queue?.getCurrent() || !this.queue?.isEmpty()) { logger.inactivity(`[Player] Queue has songs for guild ${this._guildId}, skipping inactivity timer`); return; @@ -645,8 +578,6 @@ export default class Player extends EventEmitter { logger.inactivity(`[Player] Starting inactivity timer for guild ${this._guildId} (${this._inactivityLimit / 1000}s)`); this._inactivityTimer = setTimeout(() => { - // Re-check all conditions before leaving — they may have changed while - // the timer was running (user joined, 24/7 enabled, song queued, etc.) const currentMode = this._get247Mode(); if (currentMode === "auto" || currentMode === "on") { logger.inactivity(`[Player] 24/7 ${currentMode} mode enabled during inactivity wait, aborting leave`); @@ -666,8 +597,6 @@ export default class Player extends EventEmitter { } _stopInactivityTimer() { - // Also cancel any pending inactivity check that Player.join() scheduled. - // Clearing the flag prevents that delayed check from restarting the timer. this._pendingInactivityCheck = false; if (this._inactivityTimer) { logger.inactivity(`[Player] Stopping inactivity timer for guild ${this._guildId}`); @@ -676,9 +605,6 @@ export default class Player extends EventEmitter { } } - // ═══════════════════════════════════════════════════════════════════════════ - // MediaPlayer Management - // ═══════════════════════════════════════════════════════════════════════════ async _ensureMediaPlayer() { if (this._destroyed) return false; @@ -731,7 +657,7 @@ export default class Player extends EventEmitter { e?.message?.includes("InvalidState") || e?.message?.includes("failed to capture frame") ) { - return; // race condition on skip/leave — safe to swallow + return; } throw e; } @@ -790,14 +716,10 @@ export default class Player extends EventEmitter { logger.error("[Player] Error stopping media player:", e.message); } - // Null the reference so the native revoice.js/LiveKit object can be GC'd. this._mediaPlayer = null; } } - // ═══════════════════════════════════════════════════════════════════════════ - // HTTP/Stream Helpers - // ═══════════════════════════════════════════════════════════════════════════ async _request(url, options = {}, returnStream = false) { return new Promise((resolve, reject) => { @@ -825,7 +747,6 @@ export default class Player extends EventEmitter { if (!loc) return reject(new Error("Redirect without location")); if (loc.startsWith("/")) loc = `${urlObj.protocol}//${urlObj.host}${loc}`; if (_redirects >= 5) return reject(new Error("Too many redirects")); - // Strip auth header on cross-origin redirects const redirectUrl = new URL(loc); if (redirectUrl.host !== urlObj.host) { delete options.headers?.Authorization; @@ -893,9 +814,6 @@ export default class Player extends EventEmitter { return elapsedMs / totalMs >= 0.85 || remainingMs <= 15_000; } - // ═══════════════════════════════════════════════════════════════════════════ - // Audio Streaming (revoice.js) - // ═══════════════════════════════════════════════════════════════════════════ async _streamViaRevoice(url, inputOptions = []) { if (this._streamingStopped) return; @@ -938,7 +856,6 @@ export default class Player extends EventEmitter { const onFfmpegError = (err) => { const ffMsg = err?.message ?? String(err); - // treat SIGKILL as graceful — _stopMediaPlayer() always kills FFmpeg with SIGKILL. const isGracefulKill = ffMsg.includes("aborted") || ffMsg.includes("Input stream error") || @@ -952,12 +869,10 @@ export default class Player extends EventEmitter { return resolve(); } cleanup(); - // If we deliberately stopped (skip/leave), resolve silently if (this._streamingStopped || this._skipping) return resolve(); return reject(new Error(`FFmpeg stream ended early: ${ffMsg}`)); } - // Genuine unexpected FFmpeg error logger.error("[Player] FFmpeg error:", ffMsg); cleanup(); if (this._streamingStopped || this._skipping) return resolve(); @@ -990,11 +905,10 @@ export default class Player extends EventEmitter { return reject(e); } - // Dynamic safety timeout based on track duration. const trackDuration = this._getTrackDurationMs(currentTrack); const safetyMs = (trackDuration > 0 && currentTrack?.type !== "radio") ? trackDuration + 15_000 - : 20 * 60 * 1000; // default 20 min for radio/unknown + : 20 * 60 * 1000; const safetyTimer = setTimeout(() => { logger.warn(`[Player] Stream safety timeout hit (${Math.round(safetyMs/1000)}s) — advancing queue`); @@ -1044,7 +958,6 @@ export default class Player extends EventEmitter { if (url.includes("/v4/loadstream")) { logger.player(`[Player] NodeLink loadStream PCM active`); - // Raw PCM from NodeLink — tell FFmpeg the input format const pcmInputOpts = ["-f", "s16le", "-ar", "48000", "-ac", "2"]; return await this._streamViaRevoice(url, pcmInputOpts); } @@ -1065,9 +978,6 @@ export default class Player extends EventEmitter { } } - // ═══════════════════════════════════════════════════════════════════════════ - // Voice Connection (revoice.js) - // ═══════════════════════════════════════════════════════════════════════════ async join(channelId) { if (this._destroyed) return; @@ -1082,13 +992,9 @@ export default class Player extends EventEmitter { logger.player(`[Player] Already in channel: ${channelId}`); return; } - // Connection is dead — clean up. No auto-reconnect; the caller - // must explicitly re-join if they want to reconnect. logger.player(`[Player] Dead connection detected for ${channelId}, cleaning up`); try { this.connection.removeAllListeners(); } catch (_) {} - // Use FluxerRevoice's channel-specific leave instead of raw - // vm.updateVoiceState(guildId, null) which nukes ALL guild channels. if (this._revoice && this._channelId) { try { this._revoice.markIntentionalDisconnect(this._channelId); } catch (_) {} try { this._revoice._leaveGateway(this._channelId, this._guildId ?? this._resolveGuildId()); } catch (_) {} @@ -1109,8 +1015,6 @@ export default class Player extends EventEmitter { logger.mediaplayer("[Player] Cleaning up existing connection before join"); try { this.connection.removeAllListeners(); } catch (_) {} - // Use FluxerRevoice's channel-specific leave instead of raw - // vm.updateVoiceState(guildId, null) which nukes ALL guild channels. if (this._revoice && this._channelId) { try { this._revoice.markIntentionalDisconnect(this._channelId); } catch (_) {} try { this._revoice._leaveGateway(this._channelId, this._guildId ?? this._resolveGuildId()); } catch (_) {} @@ -1121,20 +1025,11 @@ export default class Player extends EventEmitter { await this.connection.disconnect(); } catch (_) {} - // Brief wait so the gateway processes the leave before we join a - // new channel. FluxerRevoice adds its own _globalJoinDelay too. await Utils.sleep(500); this.connection = null; this._mediaPlayer = null; } - // ── FluxerRevoice join ───────────────────────────────────────────── - // Use the FluxerRevoice instance to join the voice channel via the - // Fluxer gateway. FluxerRevoice sends a VOICE_STATE_UPDATE through - // the gateway, receives VOICE_SERVER_UPDATE with LiveKit credentials, - // then creates a FluxerVoiceConnection wrapping a LiveKit Room. - // The FluxerVoiceConnection is API-compatible with revoice.js's - // VoiceConnection (has .room, .disconnect(), .leave(), events). if (!this._revoice) { throw new Error("FluxerRevoice instance not available — cannot join voice channel"); } @@ -1154,19 +1049,10 @@ export default class Player extends EventEmitter { logger.mediaplayer(`[Player] FluxerVoiceConnection obtained (isConnected: ${room.isConnected}, connectionState: ${room.connectionState})`); - // ── Wait for the room to be connected ────────────────────────────── - // FluxerRevoice already waits for the LiveKit room to be ready before - // resolving the join() promise, but we add a safety net for slow - // LiveKit servers. - // Uses the correct @livekit/rtc-node API: - // room.isConnected — boolean getter - // room.connectionState — ConnectionState enum - // RoomEvent.ConnectionStateChanged — fires with ConnectionState value let connected = false; let settled = false; try { - // If already connected (FluxerRevoice.wait usually resolves this), skip if (room.isConnected) { connected = true; settled = true; @@ -1182,7 +1068,6 @@ export default class Player extends EventEmitter { const timeout = setTimeout(() => { if (settled) return; cleanup(); - // Use room.isConnected as the source of truth if (room.isConnected) { connected = true; settled = true; @@ -1190,7 +1075,6 @@ export default class Player extends EventEmitter { } else if (!room.isConnected && (room.connectionState === ConnectionState.CONN_DISCONNECTED || room.connectionState === 0)) { reject(new Error(`LiveKit disconnected (connectionState: ${room.connectionState})`)); } else { - // Still connecting or indeterminate — optimistically proceed connected = true; settled = true; resolve(); @@ -1226,7 +1110,6 @@ export default class Player extends EventEmitter { } }, 500); - // Immediate check using correct API if (room.isConnected) { connected = true; settled = true; @@ -1248,9 +1131,6 @@ export default class Player extends EventEmitter { logger.mediaplayer("[Player] Room ready via FluxerRevoice, proceeding to MediaPlayer"); } - // ── VoiceConnection event handlers ────────────────────────────────── - // FluxerVoiceConnection emits "disconnect" on unexpected - // disconnection and "autoleave" when the room empties. connection.on("error", (err) => { if (this.connection !== connection) { try { connection.removeAllListeners(); } catch (_) {} @@ -1262,9 +1142,6 @@ export default class Player extends EventEmitter { .catch(() => {}) .finally(() => { if (this.leaving || this._destroyed) return; - // %247 on/auto: don't autoleave on voice errors — stop the media - // player but stay in the channel. The GatewayHandler will - // detect the state change and schedule a rejoin if needed. if (mode === "auto" || mode === "on") { logger.inactivity(`[Player] Voice error in 24/7 ${mode} mode — staying in channel, not autoleaving`); return; @@ -1281,16 +1158,9 @@ export default class Player extends EventEmitter { if (!this.leaving && !this._destroyed) { const mode = this._get247Mode(); if (mode === "auto" || mode === "on") { - // %247 auto/on: Do NOT emit autoleave on unexpected disconnect. - // The GatewayHandler will detect the bot's voice state change - // and schedule a rejoin. Emitting autoleave here would cause - // the player to be destroyed before the rejoin can be scheduled, - // and creates a race condition where both Player.mjs AND - // GatewayHandler try to handle the disconnect simultaneously. logger.mediaplayer(`[Player] Unexpected disconnect detected (24/7 ${mode}) — stopping media player, GatewayHandler will schedule rejoin`); this._stopMediaPlayer().catch(() => {}); } else { - // %247 off: emit autoleave as normal. logger.mediaplayer("[Player] Unexpected disconnect detected"); this._stopMediaPlayer() .catch(() => {}) @@ -1303,8 +1173,6 @@ export default class Player extends EventEmitter { connection.on("autoleave", () => { if (this.connection !== connection) return; - // Check 24/7 mode before forwarding the autoleave — for 24/7 channels - // the bot should never leave due to an empty room. const mode = this._get247Mode(); if (mode === "auto" || mode === "on") { logger.mediaplayer(`[Player] Auto-leave suppressed for 24/7 ${mode} channel (room empty but staying)`); @@ -1316,7 +1184,6 @@ export default class Player extends EventEmitter { } }); - // Send self-deaf voice state update via @fluxerjs/voice if available try { const vm = getVoiceManager(this.client); vm.updateVoiceState(channelId, { self_deaf: true, self_mute: false }); @@ -1349,7 +1216,6 @@ export default class Player extends EventEmitter { logger.error("[Player] Join failed:", e.message, causeStr); if (e.message?.includes("401") || e.message?.includes("Unauthorized")) { - // Track 401 errors for logging purposes logger.warn(`[Player] Join failed with 401 Unauthorized for guild ${this._guildId}`); } @@ -1375,7 +1241,6 @@ export default class Player extends EventEmitter { this._mediaPlayer = null; } - // Clean up from FluxerRevoice connections map before disconnecting const channelId = this._channelId; if (this._revoice && channelId) { try { @@ -1425,10 +1290,6 @@ export default class Player extends EventEmitter { const connToDestroy = this.connection; this.connection = null; this._mediaPlayer = null; - // Mark the disconnect as intentional BEFORE disconnecting so that - // the RoomEvent.Disconnected handler in FluxerRevoice (and the - // VoiceState bot-disconnect handler in GatewayHandler) do NOT treat - // this as an unexpected drop and schedule a spurious rejoin. if (this._revoice && this._channelId) { try { this._revoice.markIntentionalDisconnect(this._channelId); } catch (_) {} } @@ -1448,9 +1309,6 @@ export default class Player extends EventEmitter { } } - // ═══════════════════════════════════════════════════════════════════════════ - // Playback Controls - // ═══════════════════════════════════════════════════════════════════════════ get paused() { return this._paused; } @@ -1460,7 +1318,7 @@ export default class Player extends EventEmitter { if (this._paused) return ":negative_squared_cross_mark: Already paused!"; this._paused = true; - this._pausedAt = Date.now(); // Capture freeze moment + this._pausedAt = Date.now(); this._mediaPlayer?.pause(); this.emit("playback", false); this._stopInactivityTimer(); @@ -1473,7 +1331,6 @@ export default class Player extends EventEmitter { if (!this._paused) return ":negative_squared_cross_mark: Not paused!"; - // Adjust start time by the duration of the pause if (this._pausedAt) { this.startedPlaying += (Date.now() - this._pausedAt); } @@ -1532,7 +1389,6 @@ export default class Player extends EventEmitter { this.queue.current = null; this._skipping = true; - // If the queue is now empty after splicing, send queue-end immediately. if (this.queue.isEmpty() && !this._wasRadio && !this._queueEndedSent) { this._queueEndedSent = true; const prefix = (() => { @@ -1557,15 +1413,11 @@ export default class Player extends EventEmitter { } }).catch(e => logger.error("[Player] skipTo stop error:", e.message)) .finally(() => { - // Always reset _skipping — even if _stopMediaPlayer() threw. this._skipping = false; }); return `:track_next: Skipped to position ${position}`; } - // ═══════════════════════════════════════════════════════════════════════════ - // Volume Control - // ═══════════════════════════════════════════════════════════════════════════ setVolume(v) { this.preferredVolume = Utils.clamp(v, 0, 2); @@ -1576,9 +1428,6 @@ export default class Player extends EventEmitter { return `Volume changed to \`${Math.round(this.preferredVolume * 100)}%\`.`; } - // ═══════════════════════════════════════════════════════════════════════════ - // Audio Filter Control - // ═══════════════════════════════════════════════════════════════════════════ async applyFilter(filterPayload, meta = null) { const guildId = this._guildId; @@ -1620,15 +1469,6 @@ export default class Player extends EventEmitter { this.activeFilterPayload = meta ? filterPayload : null; this.emit("filter", this.activeFilter); - // Restart the current stream so the loadstream URL picks up the new filters. - // The PATCH only updates NodeLink's player state — it does NOT modify the - // currently-streaming PCM pipe. Without restarting, the audio won't change. - // - // Guard: only restart if we're mid-playback (startedPlaying is set) AND - // _doPlayNext is NOT in progress. When _doPlayNext calls applyFilter() - // before starting a new track, startedPlaying hasn't been set yet and - // _doPlayNext itself handles the stream — firing _replayWithFilters here - // would cause the same song to play twice simultaneously. if (current?.encoded && this.connection && !this.leaving && !this._streamingStopped && this.startedPlaying && !this._playingNext) { const elapsed = this.startedPlaying ? (Date.now() - this.startedPlaying) : 0; const positionMs = Math.max(0, elapsed); @@ -1653,28 +1493,23 @@ export default class Player extends EventEmitter { const current = this.queue.getCurrent(); if (!current?.encoded || !this.connection || this.leaving) return; - // Stop the current stream (kills FFmpeg + passthrough) this._streamingStopped = true; await this._stopMediaPlayer().catch(() => {}); this._streamingStopped = false; - // _stopMediaPlayer sets _mediaPlayer to null — must recreate before streaming const hasPlayer = await this._ensureMediaPlayer(); if (!hasPlayer) { logger.warn("[Player] _replayWithFilters: could not recreate MediaPlayer"); return; } - // Restore volume on the fresh player if (this.preferredVolume !== 1) { this._mediaPlayer.setVolume(this.preferredVolume); } - // Build a fresh loadstream URL — include filters so NodeLink applies them server-side const nlBase = `http://${this._nl.host}:${this._nl.port}`; let streamUrl = `${nlBase}/v4/loadstream?encodedTrack=${encodeURIComponent(current.encoded)}&position=${positionMs}&volume=100`; - // Append active filter payload to the URL so NodeLink processes them if (this.activeFilterPayload) { streamUrl += `&filters=${encodeURIComponent(JSON.stringify(this.activeFilterPayload))}`; } @@ -1686,14 +1521,10 @@ export default class Player extends EventEmitter { } } - // ═══════════════════════════════════════════════════════════════════════════ - // Queue Management - // ═══════════════════════════════════════════════════════════════════════════ isEmpty() { return this.queue.isEmpty(); } addToQueue(d, t) { - // Enforce queue size cap to prevent unbounded memory growth if (this.queue.data.length >= this._maxQueueSize) { logger.warn(`[Player] Queue size cap reached (${this._maxQueueSize}) — dropping oldest track`); this.queue.data.shift(); @@ -1713,7 +1544,6 @@ export default class Player extends EventEmitter { addManyToQueue(t, top = false) { if (!Array.isArray(t)) return 0; - // Enforce queue size cap const overflow = (this.queue.data.length + t.length) - this._maxQueueSize; if (overflow > 0) { logger.warn(`[Player] Queue size cap (${this._maxQueueSize}) — dropping ${overflow} oldest tracks`); @@ -1759,22 +1589,17 @@ export default class Player extends EventEmitter { return msg; } - // ═══════════════════════════════════════════════════════════════════════════ - // Display Helpers - // ═══════════════════════════════════════════════════════════════════════════ _createProgressBar(length = 15) { const current = this.queue.getCurrent(); if (!current?.duration || !this.startedPlaying) return Utils.progressBar(0, 1, length); - // Common elapsed calculation const totalMs = this._getTrackDurationMs(current); let elapsed = Date.now() - this.startedPlaying; if (this._paused && this._pausedAt) { elapsed = this._pausedAt - this.startedPlaying; } - // Clamp to ensure 1:58/1:30 doesn't happen if (totalMs > 0 && elapsed > totalMs) elapsed = totalMs; elapsed = Math.max(0, elapsed); @@ -1837,7 +1662,6 @@ export default class Player extends EventEmitter { elapsed = this._pausedAt - this.startedPlaying; } - // Clamp UI to total duration if (totalMs > 0 && elapsed > totalMs) elapsed = totalMs; return Utils.prettifyMS(Math.max(0, elapsed)); } @@ -1954,9 +1778,6 @@ export default class Player extends EventEmitter { }))); } - // ═══════════════════════════════════════════════════════════════════════════ - // Worker Management - // ═══════════════════════════════════════════════════════════════════════════ _workerPool = null; @@ -1985,9 +1806,6 @@ export default class Player extends EventEmitter { ); } - // ═══════════════════════════════════════════════════════════════════════════ - // Public Play Methods - // ═══════════════════════════════════════════════════════════════════════════ async fetchResults(query, id, provider = "ytm") { try { @@ -2074,9 +1892,6 @@ export default class Player extends EventEmitter { return events; } - // ═══════════════════════════════════════════════════════════════════════════ - // Radio track builder - // ═══════════════════════════════════════════════════════════════════════════ _buildRadioTrack(radio) { return { @@ -2120,9 +1935,6 @@ export default class Player extends EventEmitter { if (!this.leaving) this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); } - // ═══════════════════════════════════════════════════════════════════════════ - // Core Playback - // ═══════════════════════════════════════════════════════════════════════════ async playNext() { if (this._playingNext) return; @@ -2182,8 +1994,6 @@ export default class Player extends EventEmitter { if (!room || !room.isConnected) { const cs = room?.connectionState; const mode = this._get247Mode(); - // For 24/7 channels, don't autoleave on dead room — put the song back - // and wait for the GatewayHandler to schedule a rejoin. if (mode === "auto" || mode === "on") { logger.mediaplayer(`[Player] Room not connected (isConnected: ${room?.isConnected}, connectionState: ${cs}) in 24/7 ${mode} mode — deferring autoleave, waiting for rejoin.`); if (songData) { @@ -2236,7 +2046,6 @@ export default class Player extends EventEmitter { const positionMs = 0; streamUrl = `${nlBase}/v4/loadstream?encodedTrack=${encodeURIComponent(songData.encoded)}&position=${positionMs}&volume=100`; - // Append active filters so NodeLink applies them server-side if (this.activeFilterPayload) { streamUrl += `&filters=${encodeURIComponent(JSON.stringify(this.activeFilterPayload))}`; } @@ -2273,7 +2082,6 @@ export default class Player extends EventEmitter { logger.player(`[Player:${this._guildId}] Streaming: ${songData.title}`); - // Reset all timing flags this.startedPlaying = Date.now(); this._paused = false; this._pausedAt = null; @@ -2299,8 +2107,6 @@ export default class Player extends EventEmitter { if (!this.leaving && !this._skipping) { if (songData.type === "radio") { - // Radio track ended — do NOT auto-retry/re-queue. - // The user must manually restart if they want to continue. logger.player(`[Player] Radio stream ended: ${songData.title}`); this.queue.current = null; this._streamingStopped = true; @@ -2320,9 +2126,6 @@ export default class Player extends EventEmitter { this._skipping = false; } - // ═══════════════════════════════════════════════════════════════════════════ - // Lyrics - // ═══════════════════════════════════════════════════════════════════════════ async lyrics() { const current = this.queue.getCurrent(); diff --git a/src/PlayerManager.mjs b/src/PlayerManager.mjs index 3f650d4..b64b016 100644 --- a/src/PlayerManager.mjs +++ b/src/PlayerManager.mjs @@ -65,26 +65,15 @@ function getPlayerChannelId(player, fallbackChannelId = null) { function botHasVoicePermissions(client, channelId) { try { const channel = client?.channels?.get?.(channelId); - if (!channel) return true; // can't check — assume yes, let gateway decide + if (!channel) return true; const me = channel.guild?.members?.me; - if (!me) return true; // not cached — assume yes - // FluxerJS uses member.permissionsIn(channel), NOT channel.permissionsFor(member). - // The permissionsFor method does not exist in FluxerJS (it's a Discord.js API). - // permissionsIn computes base perms + channel overwrites, and expands Administrator - // to ALL_PERMISSIONS_BIGINT — so Admin bots always pass every has() check. + if (!me) return true; const perms = me.permissionsIn?.(channel); - if (!perms) return true; // can't read perms — assume yes - // FluxerJS PermissionFlags (from @fluxerjs/util): - // Administrator = 1n << 3n (0x8) - // ViewChannel = 1n << 10n (0x400) - // Connect = 1n << 20n (0x100000) - // Speak = 1n << 21n (0x200000) - // Administrator short-circuit: Admin bypasses all channel restrictions. + if (!perms) return true; if (perms.has(0x8)) return true; - // Bot must be able to see the channel, connect to it, and speak in it. return perms.has(0x400) && perms.has(0x100000) && perms.has(0x200000); } catch (_) { - return true; // can't check — assume yes + return true; } } @@ -104,11 +93,9 @@ function botHasVoicePermissions(client, channelId) { function sanitizeJoinError(err, client = null, channelId = null) { const msg = String(err?.message ?? err ?? ""); if (msg.includes("401") || msg.includes("Unauthorized")) { - // Gateway said 401 — but is it a real permission issue or a stale session? if (client && channelId && !botHasVoicePermissions(client, channelId)) { - return "PERMISSION"; // bot genuinely lacks Connect/Speak + return "PERMISSION"; } - // Bot has the permissions — this is a stale session race, not a real denial return "SESSION_RACE"; } if (msg.includes("permission") || msg.includes("Permission")) { @@ -123,7 +110,7 @@ function sanitizeJoinError(err, client = null, channelId = null) { if (msg.includes("timeout") || msg.includes("timed out")) { return "TIMEOUT"; } - return null; // unknown — fall back to raw message + return null; } export class PlayerManager { @@ -173,12 +160,9 @@ export class PlayerManager { this.dashboard = config.dashboard ?? null; this.locale = config.locale ?? null; this.timers = config.timers ?? {}; - this._lastfm = null; // Set later by Remix class after init + this._lastfm = null; } - // ═══════════════════════════════════════════════════════════════════════════ - // Guild→Player Reverse Index — O(1) lookups instead of O(n) scans - // ═══════════════════════════════════════════════════════════════════════════ /** * Add a channel to the guild→player reverse index. @@ -226,7 +210,7 @@ export class PlayerManager { for (const channelId of set) { const player = this.playerMap.get(channelId); if (!player || player._destroyed) { - set.delete(channelId); // prune stale entry + set.delete(channelId); continue; } result.push([channelId, player]); @@ -256,7 +240,6 @@ export class PlayerManager { */ getPlayerByChannelId(channelId) { const cId = cleanId(channelId); - // Try all guild indexes for (const [, channelSet] of this._guildPlayerIndex) { for (const mapChannelId of channelSet) { const player = this.playerMap.get(mapChannelId); @@ -292,34 +275,18 @@ export class PlayerManager { writable: true, }); - // ── Per-player channel: standard { type, data } format ──────── - // The backend PlayerManager.setupEvents() expects: - // { type: "startplay", data: serialisedVideo } - // { type: "stopplay", data: null } - // { type: "pause", data: { elapsedTime: ms } } - // { type: "resume", data: { elapsedTime: ms } } - // { type: "volume", data: number } - // { type: "queue", data: serialisedQueueEvent } - // { type: "join", data: userId } - // { type: "leave", data: userId } const emit = (type, data) => { if (!this.dashboard?.enabled) return; this.dashboard.updatePlayer({ type, data }, player); }; - // ── Global channel: lifecycle events ────────────────────────────────── - // The backend PlayerManager.initChannels() expects: - // { type: "init", player: serialisedPlayer } — when player connects - // { type: "close", player: serialisedPlayer } — when player disconnects const emitGlobal = (type) => { if (!this.dashboard?.enabled) return; this.dashboard.playerUpdate({ type }, player); }; - // Broadcast user list changes to the global :users channel when - // someone joins or leaves the player's voice channel. const sendUserUpdates = (eventType) => { if (!this.dashboard?.enabled) return; const channelId = getPlayerChannelId(player, context.channelId); @@ -339,10 +306,7 @@ export class PlayerManager { if (stateChannelId !== channelId) continue; const member = guild.members?.get?.(state.userId ?? state.user_id); if (!member?.user || member.user?.bot) continue; - // Send per-player channel "join"/"leave" event with just the user ID - // (matching standard format where data = userId string) emit(eventType, member.user.id); - // Also send global user update this.dashboard.userUpdate({ type: eventType, guildId: cleanId(player._guildId ?? context.guildId), @@ -351,24 +315,17 @@ export class PlayerManager { } }; - // ── Player event handlers ───────────────────────────────────────────── player.on("roomfetched", () => { - // Player connected — send "init" on the global channel emitGlobal("init"); sendUserUpdates("join"); }); player.on("startplay", (song) => { - // Send the serialised video to the per-player channel emit("startplay", Dashboard.convertVideo(song ?? player.queue?.current)); - // Emit streamStartPlay with current timestamp so the backend can - // calculate elapsed time accurately (standard behaviour) emit("streamStartPlay", Date.now()); - // Also broadcast on global channel for full state update this.dashboard.playerUpdate({ type: "startplay" }, player); - // ── Last.fm: now-playing notification + deferred scrobble ──────────── if (this._lastfm?.enabled && song) { this._handleLastFmStartPlay(player, song); } @@ -380,7 +337,6 @@ export class PlayerManager { }); player.on("playback", (playing) => { - // Sends "pause" or "resume" with { elapsedTime } — match that format const elapsedMs = player._pausedAt ? (player._pausedAt.getTime?.() ?? Number(player._pausedAt)) - (player.startedPlaying?.getTime?.() ?? Number(player.startedPlaying ?? 0)) @@ -396,37 +352,28 @@ export class PlayerManager { }); player.on("filter", (filter) => { - // Filter events are Fluxer-specific. - // Send as a custom event type; the backend will ignore unknown types. emit("filter", filter); }); player.on("update", (scope) => { - // Generic update — send full player state on global channel this.dashboard.playerUpdate({ type: "update" }, player); }); player.on("message", (message) => { - // No per-player equivalent — skip, only global broadcast }); player.on("autoleave", () => { sendUserUpdates("leave"); - // Send "close" on global channel so backend removes the player emitGlobal("close"); emit("stopplay", null); }); player.on("leave", () => { sendUserUpdates("leave"); - // Send "close" on global channel so backend removes the player emitGlobal("close"); emit("stopplay", null); }); - // ── Queue event handler ─────────────────────────────────────────────── - // Queue events must be serialised with Dashboard.convertVideo() to match - // the format the backend Queue.update() method expects. player.queue?.on("queue", (queueEvent) => { const serialised = { type: queueEvent.type }; @@ -469,7 +416,6 @@ export class PlayerManager { }; break; default: - // Unknown queue event — pass through as-is serialised.data = queueEvent.data; break; } @@ -494,9 +440,6 @@ export class PlayerManager { return this.locale.translate(guildId, key, replacements); } - // ═══════════════════════════════════════════════════════════════════════════ - // Voice Channel Detection - // ═══════════════════════════════════════════════════════════════════════════ /** * Attempt to detect the voice channel a user is currently in. @@ -516,7 +459,6 @@ export class PlayerManager { const seedObserved = (channelId) => { const cleanChannelId = cleanId(channelId); if (!cleanChannelId) return null; - // Use voiceCache (O(1) with guildId) or fall back to observedVoiceUsers const cache = this.voiceCache ?? this.observedVoiceUsers; if (cache && !cache.has(userId, cleanGuild)) { cache.set(userId, { channelId: cleanChannelId, guildId: cleanGuild }); @@ -539,10 +481,6 @@ export class PlayerManager { if (seeded) return seeded; } catch (_) {} - // ── Fallback: VoiceManager.voiceStates direct lookup ──────────────── - // After a reboot, getVoiceChannelId() may return null if the - // VoiceManager hasn't synced yet, but voiceStates (populated from - // READY / GUILD_CREATE raw gateway events) may already have the data. try { const vm = getVoiceManager(this.commands.client); if (vm?.voiceStates) { @@ -596,10 +534,6 @@ export class PlayerManager { } } catch (_) {} - // ── Fallback: match user to any active player in the guild ────────── - // After a reboot with 24/7, voice states may not be fully populated. - // If the guild has active players, check if any of them have the user - // as a remote participant in their LiveKit room. const liveGuildPlayers = [...this.playerMap.entries()].filter(([channelId, player]) => { const fallbackChannel = this.commands.client?.channels?.get?.(channelId) ?? @@ -609,8 +543,6 @@ export class PlayerManager { if (liveGuildPlayers.length === 1) { return getPlayerChannelId(liveGuildPlayers[0][1], liveGuildPlayers[0][0]) || cleanId(liveGuildPlayers[0][0]); } - // Multiple players — try LiveKit remote participants to find which - // channel the user is actually in. if (liveGuildPlayers.length > 1) { for (const [mapKey, player] of liveGuildPlayers) { try { @@ -630,9 +562,6 @@ export class PlayerManager { return null; } - // ═══════════════════════════════════════════════════════════════════════════ - // Player Retrieval - // ═══════════════════════════════════════════════════════════════════════════ /** * Get or create a player for the user's voice channel. @@ -662,9 +591,8 @@ export class PlayerManager { } catch (_) {} return player; } - // Also check if a join is in-progress for this channel if (this._pendingJoins.has(cleanUserChannelId)) { - return null; // A player is being created — caller should retry + return null; } } @@ -676,8 +604,6 @@ export class PlayerManager { const channelList = serverPlayers.map(([chId]) => `<#${chId}>`).join(" or "); if (!userChannelId) { - // verifyUser=false: allow controlling the bot without being in voice - // (e.g. volume, clear, remove — admin-style controls). if (!verifyUser) { const first = serverPlayers[0]; first[1].textChannel = message.channel; @@ -701,7 +627,6 @@ export class PlayerManager { return match[1]; } - // User is in a different channel than existing players. if (shouldJoin) { return new Promise((resolve) => { this.initPlayer(message, userChannelId, (p) => resolve(p)); @@ -719,7 +644,6 @@ export class PlayerManager { if (!userChannelId) { if (shouldJoin) { - // Auto-detect failed — fall back to interactive channel selection prompt return this.promptVC(message); } message.reply(mkEmbed(this._t(message, "responses._common.noVoiceChannel"))); @@ -735,9 +659,6 @@ export class PlayerManager { return null; } - // ═══════════════════════════════════════════════════════════════════════════ - // Channel Selection Prompt - // ═══════════════════════════════════════════════════════════════════════════ /** * Prompt the user to select a voice channel. @@ -828,9 +749,6 @@ export class PlayerManager { }); } - // ═══════════════════════════════════════════════════════════════════════════ - // Leave - // ═══════════════════════════════════════════════════════════════════════════ /** * Make the player leave its current voice channel. @@ -859,13 +777,9 @@ export class PlayerManager { const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId; this.playerMap.delete(activeChannelId); this._unindexPlayer(player._guildId, activeChannelId); - // Clean up pending scrobble timer const pendingScrobble = this._pendingScrobbleTimers.get(activeChannelId); if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this._pendingScrobbleTimers.delete(activeChannelId); } if (activeChannelId !== cleanChannelId) this.playerMap.delete(cleanChannelId); - // Leave the voice channel BEFORE confirming to the user. - // Previously, the reply was sent first, which meant the user saw "successfully left" - // even if player.leave() subsequently threw an error. try { await player.leave(); } catch (e) { @@ -875,9 +789,6 @@ export class PlayerManager { await msg.reply(mkEmbed(this._t(msg, "responses._common.successfullyLeft"))); } - // ═══════════════════════════════════════════════════════════════════════════ - // Player Initialisation - // ═══════════════════════════════════════════════════════════════════════════ /** * Create and register a new Player for the given voice channel. @@ -900,11 +811,6 @@ export class PlayerManager { return message.reply(mkEmbed(this._t(message, "responses._common.voiceChannelRequired"))); } - // Pre-check: verify the bot actually has Connect + Speak permission on the - // voice channel BEFORE sending VOICE_STATE_UPDATE to the gateway. This - // avoids a confusing 401 roundtrip when the bot genuinely lacks permission, - // and makes the error message accurate instead of relying on the gateway's - // ambiguous 401 (which can also mean "stale session"). if (!botHasVoicePermissions(this.commands?.client, cid)) { return message.reply(mkEmbed( this._t(message, "responses.join.joinFailedPerms", { channel: `<#${cleanId(cid)}>` }) @@ -919,7 +825,6 @@ export class PlayerManager { cb(existing); return message.reply(mkEmbed(this._t(message, "responses.join.alreadyJoined", { channel: cid }))); } - // Also block if a join is already in-progress for this channel if (this._pendingJoins.has(cleanChannelId)) { return message.reply(mkEmbed(this._t(message, "responses.join.joining"))); } @@ -950,7 +855,6 @@ export class PlayerManager { const ch = player.textChannel; const guildId = cleanId(player._guildId ?? ch?.guildId ?? ch?.guild?.id ?? getMessageGuildId({ channel: ch })); - // Check 24/7 settings for this channel (per-channel mode) const raw247 = (() => { try { return this.settings.getServer(guildId)?.get("stay_247"); } catch (_) { return null; } })(); @@ -962,7 +866,6 @@ export class PlayerManager { return channels.includes(homeChannelId) || channels.includes(activeChannelId); })(); - // Per-channel mode: check the mode for this specific channel const matchChannel = isIn247List ? (channels247list => channels247list.includes(homeChannelId) ? homeChannelId : activeChannelId)( Array.isArray(raw247) ? raw247.map(id => String(id).replace(/\D/g, "")) : [String(raw247).replace(/\D/g, "")] @@ -972,13 +875,6 @@ export class PlayerManager { ? get247ChannelMode(this.settings.getServer(guildId), matchChannel) : "off"; - // ── Safety guard: re-validate before destroying ──────────────────── - // Even if autoleave was emitted, don't destroy the player if: - // 1. 24/7 mode is "on" or "auto" (bot should never leave) - // 2. Humans are still in the channel - // 3. There are songs in the queue or currently playing - // This catches cases where the autoleave event was emitted from a - // code path that didn't check these conditions (e.g. old timers). if (mode247 === "auto" || mode247 === "on") { logger.inactivity(`[PlayerManager] autoleave suppressed for 24/7 ${mode247} channel ${activeChannelId} (guild ${guildId})`); return; @@ -992,20 +888,14 @@ export class PlayerManager { return; } - // Remove player from map and destroy this.playerMap.delete(activeChannelId); this._unindexPlayer(player._guildId, activeChannelId); - // Clean up pending scrobble timer const pendingScrobble = this._pendingScrobbleTimers.get(activeChannelId); if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this._pendingScrobbleTimers.delete(activeChannelId); } if (activeChannelId !== cleanChannelId) this.playerMap.delete(cleanChannelId); if (homeChannelId !== activeChannelId) this.playerMap.delete(homeChannelId); player.destroy(); - // Notify the channel that the bot left. - // For %247 on: bot will rejoin on reboot (but not on disconnect) - // For %247 auto: bot will rejoin automatically after disconnect - // For non-247: user must manually re-invoke the join command const prefix = (() => { try { return this.settings.getServer(guildId)?.get("prefix") ?? "%"; } catch (_) { return "%"; } })(); @@ -1041,8 +931,6 @@ export class PlayerManager { ["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim()); if (disabled) return; - // If textChannel is not set (e.g. after reboot recovery via _spawnPlayer), - // resolve it from the saved announcementChannelId or guild channels if (!ch || typeof ch.send !== "function") { try { const serverSettings = this.settings.getServer(guildId); @@ -1075,7 +963,6 @@ export class PlayerManager { } if (!ch || typeof ch.send !== "function") return; - // Cache the resolved channel so future announcements don't need to re-resolve if (!player.textChannel) player.textChannel = ch; ch.send(typeof m === "object" && Array.isArray(m.embeds) ? m : mkEmbed(m)).catch(err => { @@ -1085,15 +972,12 @@ export class PlayerManager { }); }); - // _pendingJoins was already added earlier (right after duplicate check) (async () => { const statusMsg = await message.reply(mkEmbed(this._t(message, "responses.join.joining"))); try { await player.join(cid); - // Only add to playerMap after join succeeds — this prevents phantom - // entries from inflating the player count. this.playerMap.set(cleanChannelId, player); this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId); this._pendingJoins.delete(cleanChannelId); @@ -1116,19 +1000,15 @@ export class PlayerManager { const errCode = sanitizeJoinError(err, this.commands?.client, cleanChannelId); let errorMsg; if (errCode === "SESSION_RACE") { - // Stale session — retry once after a short delay so the gateway can - // clean up the previous voice session. logger.warn(`[PlayerManager] Stale voice session detected for channel ${cleanChannelId}, retrying in 2s...`); try { await new Promise(r => setTimeout(r, 2_000)); - // Clean up any leftover state before retrying if (player._revoice && player._channelId) { try { player._revoice._leaveGateway(player._channelId, player._guildId ?? player._resolveGuildId()); } catch (_) {} try { player._revoice.deleteConnection(player._channelId); } catch (_) {} } await player.join(cid); - // Retry succeeded this.playerMap.set(cleanChannelId, player); this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId); await statusMsg.edit(mkEmbed(this._t(message, "responses.join.joined", { channel: cid }))); @@ -1165,9 +1045,6 @@ export class PlayerManager { })(); } - // ═══════════════════════════════════════════════════════════════════════════ - // Last.fm Scrobbling - // ═══════════════════════════════════════════════════════════════════════════ /** * Handle the "startplay" event for Last.fm: send now-playing notification @@ -1184,16 +1061,13 @@ export class PlayerManager { const guildId = cleanId(player._guildId); if (!guildId) return; - // Find all human users in the voice channel const channelId = getPlayerChannelId(player); const humanUserIds = []; - // Use VoiceStateCache O(1) channel index instead of iterating all users if (this.voiceCache) { const users = this.voiceCache.getHumansInChannel(guildId, channelId); humanUserIds.push(...users); } else if (this.observedVoiceUsers) { - // Legacy fallback (VoiceStateCache is iterable via [Symbol.iterator]) for (const [uid, info] of this.observedVoiceUsers) { if (cleanId(info.guildId) === guildId && cleanId(info.channelId) === channelId) { humanUserIds.push(uid); @@ -1201,7 +1075,6 @@ export class PlayerManager { } } - // Also check guild voice states as fallback const guild = player.client?.guilds?.get(guildId); if (guild) { const voiceStates = guild.voice_states ?? guild.voiceStates ?? null; @@ -1215,7 +1088,6 @@ export class PlayerManager { const uid = state?.userId ?? state?.user_id; const chId = cleanId(state?.channelId ?? state?.channel_id); if (uid && chId === channelId) { - // Skip bots const member = guild.members?.get?.(uid); if (member?.user?.bot) continue; if (!humanUserIds.includes(uid)) humanUserIds.push(uid); @@ -1226,9 +1098,6 @@ export class PlayerManager { const startedAtMs = player.startedPlaying; - // ── Cancel any previous pending scrobble timer for this channel ─────── - // Prevents duplicate scrobbles when startplay fires multiple times - // (e.g. recovery rejoining, track restart, queue loop). const pendingKey = channelId; const existing = this._pendingScrobbleTimers.get(pendingKey); if (existing) { @@ -1236,12 +1105,10 @@ export class PlayerManager { this._pendingScrobbleTimers.delete(pendingKey); } - // Send now-playing for each linked user for (const userId of humanUserIds) { lastfm.updateNowPlaying(userId, song).catch(() => {}); } - // Schedule deferred scrobble after threshold const durationMs = (() => { const d = song.duration; if (!d) return null; @@ -1255,15 +1122,13 @@ export class PlayerManager { durationMs * lastfm.scrobbleThreshold, lastfm.scrobbleMinMs ); - // Don't schedule if threshold is too far out (cap at 10 min) if (thresholdMs <= 600_000) { const timer = setTimeout(() => { this._pendingScrobbleTimers.delete(pendingKey); - // Only scrobble if the same song is still playing const current = player.queue?.getCurrent(); if (!current || player._destroyed || player.leaving) return; if (current.title !== song.title || current.url !== song.url) return; - if (player._paused) return; // don't scrobble if paused + if (player._paused) return; const playedMs = Date.now() - (player.startedPlaying ?? startedAtMs ?? Date.now()); if (lastfm.shouldScrobble(song, playedMs)) { @@ -1273,7 +1138,6 @@ export class PlayerManager { } }, thresholdMs); - // Store the timer so we can cancel it if startplay fires again this._pendingScrobbleTimers.set(pendingKey, { timer, songUrl: song.url, startedAtMs }); } } diff --git a/src/Settings.mjs b/src/Settings.mjs index 3e73b14..72e530f 100644 --- a/src/Settings.mjs +++ b/src/Settings.mjs @@ -3,8 +3,6 @@ import { logger } from "./constants/Logger.mjs"; import mysql from "mysql2"; import { EventEmitter } from "node:events"; -// Re-export the abstract SettingsManager base class so JSDoc type hints and -// the migrate script can import it from a single canonical path. export { SettingsManager } from "../settings/Settings.mjs"; export class ServerSettings { @@ -24,7 +22,6 @@ export class ServerSettings { loadDefaults() { for (let key in this.manager.defaults) { this.data[key] = this.manager.defaults[key]; } } deserialize(json) { for (let k in json) { if (k === "id") continue; this.data[k] = json[k]; } } - // was `if (!this.data[key])` which clobbered valid falsy values like 0, false, "" checkDefaults(d) { for (let key in d) { if (this.data[key] === undefined) this.data[key] = d[key]; } } get serializationData() { return { ...this.data, id: this.id }; } @@ -42,22 +39,15 @@ export class RemoteSettingsManager extends EventEmitter { /** @type {boolean} Whether the bot_id column exists in the settings table */ _hasBotIdColumn = false; - // track retry count and apply exponential backoff on load failures _loadAttempts = 0; /** @type {Promise|null} Tracks the in-flight load() so setBotId() can wait for it */ _loadPromise = null; - // 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, botId = null) { super(); this.botId = botId; this.db = mysql.createPool({ connectionLimit: 15, ...config }); - // Without this listener, any pool-level error (connection drop, timeout, protocol error) - // fires an unhandled 'error' event which crashes the entire process with no log output. this.db.on("error", (err) => { logger.error("[DB] MySQL pool error:", err.code ?? err.message); }); @@ -78,9 +68,8 @@ export class RemoteSettingsManager extends EventEmitter { * when two bots tried to INSERT rows for the same guild. */ async _ensureBotIdColumn() { - if (this._hasBotIdColumn) return; // already verified column + PK + if (this._hasBotIdColumn) return; - // Check if bot_id column exists and its properties const res = await this.query( `SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_KEY FROM information_schema.COLUMNS ` + `WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'settings' AND COLUMN_NAME = 'bot_id'` @@ -92,11 +81,8 @@ export class RemoteSettingsManager extends EventEmitter { } if (res.results.length === 0) { - // ── Column doesn't exist: add it and update PK ───────────────────── logger.settings("[Settings] Auto-migrating: adding bot_id column to settings table..."); - // NOT NULL DEFAULT '' — primary key columns can't be NULL in MySQL. - // Existing rows get bot_id = '' which we'll claim for the current bot. const alterRes = await this.query( `ALTER TABLE settings ADD COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''` ); @@ -105,22 +91,18 @@ export class RemoteSettingsManager extends EventEmitter { return; } - // Claim all existing rows for the current bot before updating PK. - // This preserves existing settings (prefix, volume, etc.) instead of - // leaving them orphaned with bot_id = ''. if (this.botId) { await this.query( `UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''` ); } - // Update primary key from (id) to (id, bot_id) const pkRes = await this.query( `ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)` ); if (pkRes.error) { logger.error("[Settings] Failed to update primary key:", pkRes.error); - return; // Don't set flag — bot_id features can't work without composite PK + return; } this._hasBotIdColumn = true; @@ -128,41 +110,34 @@ export class RemoteSettingsManager extends EventEmitter { return; } - // ── Column already exists: verify it's in the primary key ───────────── const colInfo = res.results[0]; const isNullable = colInfo.IS_NULLABLE === 'YES'; const isPrimaryKey = colInfo.COLUMN_KEY === 'PRI'; if (isPrimaryKey) { - // Column exists and is part of composite PK — all good this._hasBotIdColumn = true; return; } - // Column exists but is NOT in PK — the ALTER TABLE PK update must have - // failed previously (likely because the column had NULL values). logger.settings("[Settings] Fixing bot_id column: adding to primary key..."); - // Step 1: Replace NULLs with empty string (PK columns can't be NULL) if (isNullable) { await this.query(`UPDATE settings SET bot_id = '' WHERE bot_id IS NULL`); await this.query(`ALTER TABLE settings MODIFY COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''`); } - // Step 2: Claim unclaimed rows (bot_id = '') for the current bot if (this.botId) { await this.query( `UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''` ); } - // Step 3: Update primary key const pkRes = await this.query( `ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)` ); if (pkRes.error) { logger.error("[Settings] Failed to update primary key:", pkRes.error); - return; // Don't set flag — can't use bot_id without composite PK + return; } this._hasBotIdColumn = true; @@ -180,14 +155,9 @@ export class RemoteSettingsManager extends EventEmitter { const changed = this.botId !== id; this.botId = id; if (changed) { - // Wait for the initial load to finish before clearing and reloading if (this._loadPromise) await this._loadPromise; - // Ensure the DB schema supports bot_id before querying with it await this._ensureBotIdColumn(); - // Claim any unclaimed legacy rows (bot_id = '') for this bot. - // This handles the case where the column was already properly set up - // (e.g. by another bot's migration) but legacy rows weren't claimed yet. if (this._hasBotIdColumn && this.botId) { const claimRes = await this.query( `UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''` @@ -197,7 +167,6 @@ export class RemoteSettingsManager extends EventEmitter { } } - // Reload with the new botId so we pick up this bot's rows this.guilds.clear(); this._loadPromise = this.load(); await this._loadPromise; @@ -247,7 +216,6 @@ export class RemoteSettingsManager extends EventEmitter { const res = await this.query(`SELECT * FROM settings WHERE 1=1${this._botIdWhere()}`); if (res.error) { this._loadAttempts++; - // exponential backoff with a cap of 30s instead of forever-at-2s const delay = Math.min(1000 * Math.pow(2, this._loadAttempts - 1), 30_000); logger.error("[Settings] Init error (attempt", this._loadAttempts, "retrying in", delay + "ms):", res.error); return setTimeout(() => { this.load().catch(err => logger.error("[Settings] Retry load error:", err?.message ?? err)); }, delay); @@ -256,8 +224,6 @@ export class RemoteSettingsManager extends EventEmitter { res.results.forEach((r) => { try { const server = new ServerSettings(r.id, this); - // mysql2 may return JSON columns as already-parsed objects; - // only JSON.parse when the value is still a string. const parsed = (typeof r.data === "string") ? JSON.parse(r.data) : r.data; server.deserialize(parsed); server.checkDefaults(this.defaults); @@ -271,14 +237,9 @@ export class RemoteSettingsManager extends EventEmitter { async remoteUpdate(server, key) { const val = server.data[key]; - // Arrays/objects must go through remoteSave — JSON_SET with scalar - // interpolation corrupts arrays by merging IDs into one number on read-back. if (Array.isArray(val) || (typeof val === "object" && val !== null)) { return this.remoteSave(server); } - // Use mysql.escape() for every user-supplied value to prevent SQL injection. - // Preserve native boolean/number types — mysql.escape(String(false)) stores "false" - // (a truthy string) which breaks strict equality checks like songAnnouncements === false. const escapedPath = mysql.escape(`$.${key}`); const escapedVal = (typeof val === "boolean" || typeof val === "number") ? mysql.escape(val) @@ -316,8 +277,6 @@ export class RemoteSettingsManager extends EventEmitter { const escapedId = mysql.escape(id); const escapedData = mysql.escape(JSON.stringify(server.data)); const bi = this._botIdInsert(); - // INSERT IGNORE: if the row already exists (race condition or failed - // migration), silently skip instead of crashing with ER_DUP_ENTRY. const r = await this.query( `INSERT IGNORE INTO settings (id, data${bi.col}) VALUES (${escapedId}, ${escapedData}${bi.val})` ); @@ -328,9 +287,6 @@ 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]; - // 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(() => { @@ -344,8 +300,6 @@ export class RemoteSettingsManager extends EventEmitter { getServer(id) { if (!this.guilds.has(id)) { - // Return a fresh object but don't register it yet; - // update() will call create() on the first real write. return new ServerSettings(id, this); } return this.guilds.get(id); @@ -357,8 +311,6 @@ export class RemoteSettingsManager extends EventEmitter { * @param {string} id - Guild / server ID */ removeServer(id) { - // Clear any pending debounce timer so it doesn't fire after the guild is gone - // and attempt a DB write for a server that no longer belongs to us. const timer = this._debounceTimers.get(id); if (timer) { clearTimeout(timer); diff --git a/src/Utils.mjs b/src/Utils.mjs index aa1c4f1..ac493f1 100644 --- a/src/Utils.mjs +++ b/src/Utils.mjs @@ -9,16 +9,13 @@ * string processing, and validation used across the music bot. */ export class Utils { - // ═════════════════════════════════════════════════════════════════════════════ - // Time & Duration - // ═════════════════════════════════════════════════════════════════════════════ /** * Format milliseconds to human-readable time string (H:MM:SS or M:SS) * @param {number} milliseconds - Duration in milliseconds * @returns {string} Formatted time string - * @example Utils.prettifyMS(125000) // "2:05" - * @example Utils.prettifyMS(3661000) // "1:01:01" + * @example Utils.prettifyMS(125000) + * @example Utils.prettifyMS(3661000) */ static prettifyMS(milliseconds) { if (!milliseconds || milliseconds < 0 || !isFinite(milliseconds)) { @@ -49,9 +46,9 @@ export class Utils { if (parts.some(isNaN) || parts.some(n => n < 0)) return 0; let ms = 0; - if (parts[0] !== undefined) ms += parts[0] * 1000; // seconds - if (parts[1] !== undefined) ms += parts[1] * 60 * 1000; // minutes - if (parts[2] !== undefined) ms += parts[2] * 3600 * 1000; // hours + if (parts[0] !== undefined) ms += parts[0] * 1000; + if (parts[1] !== undefined) ms += parts[1] * 60 * 1000; + if (parts[2] !== undefined) ms += parts[2] * 3600 * 1000; return ms; } @@ -66,9 +63,6 @@ export class Utils { return this.prettifyMS(seconds * 1000); } - // ═════════════════════════════════════════════════════════════════════════════ - // Array Manipulation - // ═════════════════════════════════════════════════════════════════════════════ /** * Shuffles array in-place using Fisher-Yates algorithm @@ -124,9 +118,6 @@ export class Utils { return [...new Set(array)]; } - // ═════════════════════════════════════════════════════════════════════════════ - // String Formatting - // ═════════════════════════════════════════════════════════════════════════════ /** * Truncate text with ellipsis @@ -154,11 +145,11 @@ export class Utils { return title .replace(/\s*[\(\[][^\)\]]*(?:feat|ft|featuring|remix|edit|version|prod|official|audio|video|lyrics|visualizer)[^\)\]]*[\)\]]/gi, "") .replace(/\s*-\s*(?:feat|ft|featuring)\.?.*/gi, "") - .replace(/\s*\|.*$/g, "") // Remove pipe and everything after - .replace(/\s*【.*?】/g, "") // Remove Japanese brackets - .replace(/\s*\[.*?\]/g, "") // Remove square brackets - .replace(/\s*\(.*?\)/g, "") // Remove parentheses - .replace(/\s{2,}/g, " ") // Collapse multiple spaces + .replace(/\s*\|.*$/g, "") + .replace(/\s*【.*?】/g, "") + .replace(/\s*\[.*?\]/g, "") + .replace(/\s*\(.*?\)/g, "") + .replace(/\s{2,}/g, " ") .trim(); } @@ -171,14 +162,13 @@ export class Utils { static sanitizeFilename(str, maxLen = 50) { if (!str || typeof str !== "string") return "unknown"; return str - .replace(/[^a-z0-9\u4e00-\u9fa5]/gi, "_") // Keep CJK chars too + .replace(/[^a-z0-9\u4e00-\u9fa5]/gi, "_") .replace(/_{2,}/g, "_") .substring(0, maxLen) .replace(/^_+|_+$/g, ""); } /** - * Escape markdown characters for Discord * @param {string} text - Raw text * @returns {string} Escaped text */ @@ -220,9 +210,6 @@ export class Utils { return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${sizes[i]}`; } - // ═════════════════════════════════════════════════════════════════════════════ - // ID Generation - // ═════════════════════════════════════════════════════════════════════════════ /** * Generate random unique ID @@ -235,7 +222,6 @@ export class Utils { const timestamp = Date.now().toString(36).toUpperCase(); let random = ""; - // Generate enough random data while ((timestamp + random).length < targetLen) { random += Math.random().toString(36).substring(2).toUpperCase(); } @@ -255,9 +241,6 @@ export class Utils { }); } - // ═════════════════════════════════════════════════════════════════════════════ - // Validation & Safety (CRITICAL for worker.mjs compatibility) - // ═════════════════════════════════════════════════════════════════════════════ /** * Check if a string represents a finite number @@ -313,9 +296,6 @@ export class Utils { } } - // ═════════════════════════════════════════════════════════════════════════════ - // Async Utilities - // ═════════════════════════════════════════════════════════════════════════════ /** * Sleep/delay promise @@ -363,9 +343,6 @@ export class Utils { * @returns {Promise} */ static timeout(promise, ms, message = "Operation timed out") { - // Always clear the timeout timer once the race settles — whether promise wins or - // the timeout wins. Without this, every successful call leaks a live timer for the - // full `ms` duration, holding the timer handle in the event loop and bloating heap. let timerId; const timeoutPromise = new Promise((_, reject) => { timerId = setTimeout(() => reject(new Error(message)), ms); @@ -373,9 +350,6 @@ export class Utils { return Promise.race([promise, timeoutPromise]).finally(() => clearTimeout(timerId)); } - // ═════════════════════════════════════════════════════════════════════════════ - // Object Utilities - // ═════════════════════════════════════════════════════════════════════════════ /** * Deep clone an object (JSON method - not suitable for circular refs) @@ -424,9 +398,6 @@ export class Utils { return result; } - // ═════════════════════════════════════════════════════════════════════════════ - // Music-Specific Helpers - // ═════════════════════════════════════════════════════════════════════════════ /** * Create progress bar string diff --git a/src/constants/API.mjs b/src/constants/API.mjs index 7f92c98..b378f8c 100644 --- a/src/constants/API.mjs +++ b/src/constants/API.mjs @@ -8,7 +8,6 @@ * Edit only here; FluxerListManager.mjs and commands/vote.mjs import from this file. */ -// ── FluxerList API ────────────────────────────────────────────────────────────── export const FLUXERLIST = { /** Base URL for all FluxerList API v1 endpoints */ diff --git a/src/constants/FluxerRevoice.mjs b/src/constants/FluxerRevoice.mjs index 30138d4..d098921 100644 --- a/src/constants/FluxerRevoice.mjs +++ b/src/constants/FluxerRevoice.mjs @@ -32,62 +32,37 @@ import { joinVoiceChannel, getVoiceManager } from "@fluxerjs/voice"; import { logger } from "./Logger.mjs"; { - // ── LiveKit SDK log suppression ────────────────────────────────────────── - // The LiveKit Node.js SDK (via pino) emits verbose JSON and human-readable - // log lines that flood the console. We monkey-patch console.log and - // process.stdout.write to silently drop lines from the "lk-rtc" logger. - // - // Guard: only patch once even if the module is imported multiple times - // (e.g. during hot-reload). The global symbol ensures idempotency. if (!globalThis.__fluxerLiveKitLogPatchApplied) { globalThis.__fluxerLiveKitLogPatchApplied = true; const _originalConsoleLog = console.log; console.log = function (...args) { - // Fast path: if the first arg is a string that looks like a pino JSON log if (args.length === 1 && typeof args[0] === "string" && args[0].startsWith("{")) { try { const parsed = JSON.parse(args[0]); - // Drop pino logs from LiveKit SDK ("lk-rtc" name) if (parsed.name === "lk-rtc") return; } catch (_) { - // Not valid JSON — pass through } } - // Suppress LiveKit SDK's human-readable log lines: - // [voice LiveKitRtc] connected to room - // [voice LiveKitRtc] Room disconnected - // [voice LiveKitRtc] emitting disconnect - // [voice LiveKitRtc] Room reconnecting... - // [voice LiveKitRtc] Room reconnected if (args.length >= 1 && typeof args[0] === "string" && args[0].includes("[voice LiveKitRtc]")) { - return; // silently drop + return; } _originalConsoleLog.apply(console, args); }; - // ── Also monkey-patch process.stdout.write ────────────────────────────── - // Pino writes directly to process.stdout.write, bypassing console.log - // entirely. This is the primary path for the JSON log lines like: - // {"level":20,"time":1778784504183,"pid":961949,"name":"lk-rtc",...} - // We intercept these and silently drop them. const _originalStdoutWrite = process.stdout.write.bind(process.stdout); process.stdout.write = function (chunk, encoding, callback) { - // Only intercept string chunks that look like pino JSON logs if (typeof chunk === "string" && chunk.startsWith("{")) { try { - // Fast check: does it contain lk-rtc before full parse? if (chunk.includes('"lk-rtc"')) { const parsed = JSON.parse(chunk); if (parsed.name === "lk-rtc") { - // Silently drop — call callback to signal "written" so pino doesn't stall if (typeof encoding === "function") { encoding(); } else if (typeof callback === "function") { callback(); } return true; } } } catch (_) { - // Not valid JSON — pass through } } return _originalStdoutWrite(chunk, encoding, callback); @@ -95,26 +70,18 @@ import { logger } from "./Logger.mjs"; } } -// ConnectionState enum values for reference: -// ConnectionState.CONN_DISCONNECTED = 0 -// ConnectionState.CONN_CONNECTED = 1 -// ConnectionState.CONN_RECONNECTING = 2 /** Helper: returns a human-readable label for a ConnectionState value */ function stateLabel(cs) { if (cs === ConnectionState?.CONN_CONNECTED) return "CONN_CONNECTED"; if (cs === ConnectionState?.CONN_DISCONNECTED) return "CONN_DISCONNECTED"; if (cs === ConnectionState?.CONN_RECONNECTING) return "CONN_RECONNECTING"; - // Fallback for numeric values if enum import fails if (cs === 1) return "CONN_CONNECTED(1)"; if (cs === 0) return "CONN_DISCONNECTED(0)"; if (cs === 2) return "CONN_RECONNECTING(2)"; return String(cs); } -// ═══════════════════════════════════════════════════════════════════════════════ -// FluxerVoiceConnection — compatible with revoice.js VoiceConnection -// ═══════════════════════════════════════════════════════════════════════════════ /** * A voice connection that wraps a LiveKit Room obtained via the Fluxer @@ -132,12 +99,11 @@ export class FluxerVoiceConnection extends EventEmitter { /** @type {Room|null} */ room = null; channelId = null; - _voice = null; // parent FluxerRevoice instance - _connected = false; // internal flag, set by events - _users = []; // internal, derived from parent FluxerRevoice.users + _voice = null; + _connected = false; + _users = []; _destroyed = false; - // @fluxerjs/voice native connection reference (for proper disconnect) _nativeConn = null; /** @@ -159,7 +125,6 @@ export class FluxerVoiceConnection extends EventEmitter { this._voice = voice; this.room = opts.room ?? null; this._nativeConn = opts.nativeConnection ?? null; - // Use room.isConnected (boolean getter) — the correct Node.js SDK API this._connected = !!(this.room && this.room.isConnected); } @@ -170,7 +135,6 @@ export class FluxerVoiceConnection extends EventEmitter { */ get connected() { if (this._destroyed) return false; - // Prefer the LiveKit Room's own isConnected getter (source of truth) if (this.room) return this.room.isConnected; return this._connected; } @@ -186,29 +150,20 @@ export class FluxerVoiceConnection extends EventEmitter { */ async disconnect() { if (this._destroyed) return; - // Mark this as an intentional disconnect so the RoomEvent.Disconnected - // handler can log it correctly if (this._voice && this.channelId) { this._voice.markIntentionalDisconnect(this.channelId); - // Prefer a channel-scoped gateway leave before tearing down the room. - // The native disconnect path can be guild-scoped in some environments, - // which drops every voice connection in the guild. const guildId = this._voice._resolveGuildForChannel?.(this.channelId) ?? null; this._voice._leaveGateway?.(this.channelId, guildId); } this._destroyed = true; this._connected = false; - // Close the LiveKit room directly after sending the leave signal. - // This keeps the disconnect scoped to the target channel. if (this.room) { try { await this.room.disconnect(); } catch (e) { - // Room may already be closed } } else if (this._nativeConn && typeof this._nativeConn.disconnect === "function") { - // Fallback only when no room object is available. try { await this._nativeConn.disconnect(); } catch (e) { @@ -228,33 +183,27 @@ export class FluxerVoiceConnection extends EventEmitter { } } -// ═══════════════════════════════════════════════════════════════════════════════ -// FluxerRevoice — drop-in replacement for revoice.js Revoice -// ═══════════════════════════════════════════════════════════════════════════════ /** * Revoice-compatible class that uses the Fluxer gateway for voice joins. * * Usage (drop-in for `new Revoice(token)`): * - * // Before (third-party API — 401 on Fluxer): + * * this.revoice = new Revoice(config.token); * - * // After (Fluxer API — works on Fluxer): + * * this.revoice = new FluxerRevoice(client); */ export class FluxerRevoice extends EventEmitter { /** @type {import("@fluxerjs/core").Client} */ client = null; connections = new Map(); - // Unified users map: keyed by "channelId:userId", value is { id, connectedTo } - // This is the single source of truth; connection.users is derived from it. users = new Map(); /** @type {Map} */ _guildJoinQueue = new Map(); - // ── Global join queue ────────────────────────────────────────────────────── /** @type {Promise} Global join serializer — only one join at a time across all guilds */ _globalJoinQueue = Promise.resolve(); /** @type {number} Minimum delay between ANY two joins (ms), even across guilds. @@ -304,7 +253,6 @@ export class FluxerRevoice extends EventEmitter { */ markIntentionalDisconnect(channelId) { this._intentionalDisconnects.add(String(channelId)); - // Auto-clear after 10 seconds as safety net setTimeout(() => this._intentionalDisconnects.delete(String(channelId)), 10_000); } @@ -331,11 +279,6 @@ export class FluxerRevoice extends EventEmitter { const guildForLeave = guildId ?? this._resolveGuildForChannel(channelId); - // ── Method 1 (PREFERRED): Use vm.leaveChannel(channelId) ────────── - // This sends a channel-specific VOICE_STATE_UPDATE that only leaves - // the specified channel, preserving all other voice connections in - // the same guild. This is critical for multi-voice / 24/7 setups - // where the bot may be in several channels simultaneously. if (typeof vm.leaveChannel === "function") { try { vm.leaveChannel(channelId); @@ -346,10 +289,6 @@ export class FluxerRevoice extends EventEmitter { } } - // ── Method 2: Use vm.leave(guildId) — guild-level fallback ───────── - // WARNING: This disconnects ALL voice channels in the guild, not just - // the target channel. Only used when leaveChannel() is unavailable. - // The caller must handle rejoining other 24/7 channels if needed. if (guildForLeave && typeof vm.leave === "function") { try { vm.leave(guildForLeave); @@ -360,12 +299,8 @@ export class FluxerRevoice extends EventEmitter { } } - // ── Method 3: Use vm.updateVoiceState() as last resort ───────────── if (typeof vm.updateVoiceState === "function") { if (guildForLeave) { - // NEVER send an unscoped updateVoiceState(null, opts) because it - // tells the gateway to leave ALL guilds' voice channels, causing - // cascading disconnections across all active voice connections. try { vm.updateVoiceState(guildForLeave, null, { self_deaf: false, self_mute: false }); logger.player(`[FluxerRevoice] Sent gateway leave via updateVoiceState() for guild ${guildForLeave}`); @@ -407,19 +342,15 @@ export class FluxerRevoice extends EventEmitter { * @param {FluxerVoiceConnection} existing */ async _destroyStaleConnection(channelId, existing) { - // 1. Remove from map immediately so no other code can get this dead ref this.connections.delete(channelId); - // Mark as intentional so the LiveKit disconnect handler logs correctly this.markIntentionalDisconnect(channelId); const staleGuildId = this._resolveGuildForChannel(channelId); this._leaveGateway(channelId, staleGuildId); - // 2. Close the LiveKit Room directly if (existing.room) { try { await existing.room.disconnect(); } catch (_) { - // Room may already be closed } } else if (existing._nativeConn && typeof existing._nativeConn.disconnect === "function") { try { @@ -429,7 +360,6 @@ export class FluxerRevoice extends EventEmitter { } } - // 3. Mark as destroyed and clean up listeners existing._destroyed = true; existing._connected = false; try { existing.removeAllListeners(); } catch (_) {} @@ -448,17 +378,13 @@ export class FluxerRevoice extends EventEmitter { */ async join(channelId, _leaveIfEmpty = false) { const joinOperation = async () => { - // Small gap between joins to let the gateway process the previous - // session's cleanup. This runs BEFORE the actual join logic. await new Promise(r => setTimeout(r, this._globalJoinDelay)); return await this._joinInternal(channelId, _leaveIfEmpty); }; - // Chain onto the global queue: our join only starts after the previous - // one has fully completed (or failed). We store the new tail of the chain. const prevQueue = this._globalJoinQueue; const ourResult = prevQueue.then(() => joinOperation()); - this._globalJoinQueue = ourResult.catch(() => {}); // don't break chain on error + this._globalJoinQueue = ourResult.catch(() => {}); return await ourResult; } @@ -471,7 +397,6 @@ export class FluxerRevoice extends EventEmitter { * @returns {Promise} */ async _joinInternal(channelId, _leaveIfEmpty = false) { - // Resolve the guild ID for this channel let guildId = null; try { const ch = this.client.channels?.get?.(channelId); @@ -480,10 +405,6 @@ export class FluxerRevoice extends EventEmitter { if (this.connections.has(channelId)) { const existing = this.connections.get(channelId); - // If the existing connection is still alive, reuse it. - // If the LiveKit room disconnected, the connection is stale — clean it - // up fully and rejoin instead of returning a dead connection that will - // fail with "LiveKit disconnected (connectionState: 0)". if (existing && !existing._destroyed && existing.room && existing.room.isConnected) { logger.player(`[FluxerRevoice] Already connected to ${channelId}, returning existing connection`); return existing; @@ -498,7 +419,6 @@ export class FluxerRevoice extends EventEmitter { logger.player(`[FluxerRevoice] Joining channel ${channelId} via Fluxer gateway...`); - // Fetch the channel object from the client cache (or REST) let channel = this.client.channels?.get?.(channelId); if (!channel) { try { @@ -511,17 +431,8 @@ export class FluxerRevoice extends EventEmitter { throw new Error(`Channel not found: ${channelId}`); } - // Resolve the guild ID for this channel (used for guild-scoped leave signals) const channelGuildId = guildId ?? channel?.guildId ?? channel?.guild?.id ?? null; - // Use @fluxerjs/voice to join the channel via the Fluxer gateway. - // This handles the VOICE_STATE_UPDATE → VOICE_SERVER_UPDATE flow - // and creates a LiveKit connection with the returned credentials. - // - // Permission validation is handled upstream in PlayerManager via - // botHasVoicePermissions() — real permission errors are caught before - // we even reach this point. If we get a 401 here, it's a stale session, - // and PlayerManager's sanitizeJoinError will handle the retry. let nativeConnection; try { nativeConnection = await joinVoiceChannel(this.client, channel); @@ -535,17 +446,13 @@ export class FluxerRevoice extends EventEmitter { logger.player(`[FluxerRevoice] Gateway join successful for ${channelId}`); - // The @fluxerjs/voice connection wraps a LiveKit Room. - // Extract it so we can use it with revoice.js's MediaPlayer. let room = null; - // Try to get the LiveKit Room from the native connection if (nativeConnection.room) { room = nativeConnection.room; logger.player(`[FluxerRevoice] Got LiveKit room from native connection (isConnected: ${room.isConnected}, connectionState: ${stateLabel(room.connectionState)})`); } - // (non-LiveKit) which we don't support for music playback. if (!room) { try { await nativeConnection.disconnect(); } catch (_) {} throw new Error( @@ -554,16 +461,10 @@ export class FluxerRevoice extends EventEmitter { ); } - // ── Wait for the room to be connected ──────────────────────────────── - // Use room.isConnected (boolean) and room.connectionState (enum) which - // are the correct APIs in @livekit/rtc-node Node.js SDK. - // Also listen for the ConnectionStateChanged event for immediate feedback. const maxWait = 10_000; const startTime = Date.now(); - // If already connected, skip the wait loop if (!room.isConnected) { - // Listen for the ConnectionStateChanged event to resolve faster let eventResolved = false; const statePromise = new Promise((resolve) => { const handler = (cs) => { @@ -575,30 +476,25 @@ export class FluxerRevoice extends EventEmitter { } else if (cs === ConnectionState?.CONN_DISCONNECTED || cs === 0) { eventResolved = true; room.off(RoomEvent.ConnectionStateChanged, handler); - resolve(); // resolve so we can check isConnected below + resolve(); } }; room.on(RoomEvent.ConnectionStateChanged, handler); }); - // Poll + event race while (!room.isConnected && (Date.now() - startTime) < maxWait) { - // Wait for either the event to fire or a 200ms poll interval await Promise.race([ statePromise, new Promise(r => setTimeout(r, 200)), ]); - // Check if connected if (room.isConnected) break; - // Check if disconnected (dead state) const cs = room.connectionState; if (cs === ConnectionState?.CONN_DISCONNECTED || cs === 0) break; } } - // Final state check using the correct API const finalConnected = room.isConnected; const finalCS = room.connectionState; @@ -609,15 +505,11 @@ export class FluxerRevoice extends EventEmitter { logger.player(`[FluxerRevoice] LiveKit room ready (isConnected: ${finalConnected}, connectionState: ${stateLabel(finalCS)})`); - // Create our FluxerVoiceConnection wrapper const connection = new FluxerVoiceConnection(channelId, this, { room, nativeConnection, }); - // ── LiveKit room event forwarding ────────────────────────────────── - // Forward LiveKit events to FluxerVoiceConnection events so - // Player.mjs's connection.on("disconnect") etc. still work. room.on(RoomEvent.Disconnected, (reason) => { const isIntentional = this._intentionalDisconnects.has(String(channelId)); @@ -627,17 +519,11 @@ export class FluxerRevoice extends EventEmitter { connection._connected = false; connection._destroyed = true; - // Remove from connections map so the next join() creates a fresh - // connection instead of returning this dead one. this.connections.delete(channelId); if (!isIntentional) { - // Unexpected disconnects still need a gateway leave signal so the - // next join gets a fresh voice session. this._leaveGateway(channelId, channelGuildId); - // Best-effort cleanup for the native wrapper. Skip this on intentional - // leaves because it can collapse multi-voice into a guild-wide leave. if (nativeConnection && typeof nativeConnection.disconnect === "function") { try { nativeConnection.disconnect(); } catch (_) {} } @@ -646,16 +532,12 @@ export class FluxerRevoice extends EventEmitter { connection.emit("disconnect"); }); - // No automatic reconnection handling — if the LiveKit room disconnects - // unexpectedly, the connection is considered dead. The caller (Player.mjs) - // will emit "autoleave" and the user must manually rejoin if desired. room.on(RoomEvent.ParticipantConnected, (participant) => { const userId = participant?.identity ?? participant?.sid; if (userId) { const uKey = `${channelId}:${userId}`; this.users.set(uKey, { id: userId, connectedTo: channelId }); - // Derive connection.users from the unified map (single source of truth) connection._users = [...this.users.values()].filter(u => u.connectedTo === channelId); connection.emit("userjoin", userId); } @@ -666,19 +548,15 @@ export class FluxerRevoice extends EventEmitter { if (userId) { const uKey = `${channelId}:${userId}`; this.users.delete(uKey); - // Derive connection.users from the unified map connection._users = [...this.users.values()].filter(u => u.connectedTo === channelId); connection.emit("userleave", userId); } }); - // Track the connection this.connections.set(channelId, connection); - // Auto-leave when room empties (if requested) if (_leaveIfEmpty) { connection.on("userleave", () => { - // Only trigger autoleave if no remote participants remain const remoteCount = room.remoteParticipants?.size ?? 0; if (remoteCount === 0) { logger.player(`[FluxerRevoice] Room empty, triggering autoleave for ${channelId}`); diff --git a/src/constants/Helpers247.mjs b/src/constants/Helpers247.mjs index 7741bab..c955c13 100644 --- a/src/constants/Helpers247.mjs +++ b/src/constants/Helpers247.mjs @@ -27,7 +27,6 @@ export function get247ChannelMode(set, channelId) { const perChannel = modes[channelId]; if (perChannel === "on" || perChannel === "auto" || perChannel === "off") return perChannel; } - // Fallback: guild-wide mode (legacy) const guildMode = set.get("stay_247_mode") ?? "off"; return guildMode; } @@ -44,7 +43,6 @@ export function set247ChannelMode(set, channelId, mode) { if (!modes || typeof modes !== "object" || Array.isArray(modes)) modes = {}; modes[channelId] = mode; set.set("stay_247_modes", modes); - // Also update guild-wide mode for backward compat set.set("stay_247_mode", mode); } diff --git a/src/constants/Locale.mjs b/src/constants/Locale.mjs index fc748f1..e936e4b 100644 --- a/src/constants/Locale.mjs +++ b/src/constants/Locale.mjs @@ -48,7 +48,6 @@ export class Locale { return; } - // Auto-discover all .json files in the locales directory let files; try { files = readdirSync(LOCALES_DIR).filter(f => f.endsWith(".json")); @@ -93,11 +92,9 @@ export class Locale { _getLocaleData(guildId) { if (!guildId) return this.locales.get(this.defaultLocale) ?? {}; - // Check cache first const cached = this._resolved.get(guildId); if (cached) return cached; - // Resolve locale from guild settings let code = this.defaultLocale; try { const serverSettings = this.settingsMgr?.guilds?.get?.(guildId); @@ -151,22 +148,17 @@ export class Locale { * @returns {string} Translated string, or the key itself if not found */ translate(guildId, key, replacements = {}) { - // Resolve locale data for this guild (uses cache internally) const localeData = this._getLocaleData(guildId); - // Try guild's locale first let value = this._resolve(localeData, key); - // Fallback to English if not found in guild locale if (value === undefined) { value = this._resolve(this.locales.get(this.defaultLocale) ?? {}, key); } - // If still not found, return the key so devs can see what's missing if (value === undefined) return key; if (typeof value !== "string") return key; - // Replace {{placeholder}} patterns for (const [placeholder, val] of Object.entries(replacements)) { value = value.replace( new RegExp(`\\{\\{${placeholder}\\}\\}`, "g"), diff --git a/src/constants/Logger.mjs b/src/constants/Logger.mjs index 3252a70..8824717 100644 --- a/src/constants/Logger.mjs +++ b/src/constants/Logger.mjs @@ -30,9 +30,8 @@ export function initLogger(config) { } function isEnabled(category) { - if (!_config) return true; // default on if not yet initialised + if (!_config) return true; if (_config.enabled === false) return false; - // If the category key is missing, default to true return _config[category] !== false; } @@ -41,17 +40,14 @@ function ts() { } export const logger = { - // ── always-on (errors / warnings critical to operation) ────────────────── error(tag, ...args) { console.error(`[${ts()}] ${tag}`, ...args); }, warn(tag, ...args) { - // warnings are on unless master switch is off if (_config?.enabled === false) return; console.warn(`[${ts()}] ${tag}`, ...args); }, - // ── categorised logs ───────────────────────────────────────────────────── player(...args) { if (isEnabled("player")) console.log(`[${ts()}]`, ...args); }, inactivity(...args) { if (isEnabled("inactivity")) console.log(`[${ts()}]`, ...args); }, voice247(...args) { if (isEnabled("voice247")) console.log(`[${ts()}]`, ...args); }, diff --git a/src/constants/VoiceStateCache.mjs b/src/constants/VoiceStateCache.mjs index e6ee3c1..2cf4483 100644 --- a/src/constants/VoiceStateCache.mjs +++ b/src/constants/VoiceStateCache.mjs @@ -28,19 +28,16 @@ export class VoiceStateCache { * @param {number} [opts.maxBots=10000] Max bot entries before LRU eviction */ constructor(opts = {}) { - // ── Human users ────────────────────────────────────────────────────── /** @type {Map} keyed "guildId:userId" */ this.userLocations = new Map(); /** @type {Map>} keyed "guildId:channelId", values are userIds */ this.channelMembers = new Map(); - // ── Bot users ──────────────────────────────────────────────────────── /** @type {Map} keyed "guildId:userId" */ this.botLocations = new Map(); /** @type {Map>} keyed "guildId:channelId", values are userIds */ this.botChannelMembers = new Map(); - // ── LRU tracking ───────────────────────────────────────────────────── this._maxUsers = opts.maxUsers ?? 50_000; this._maxBots = opts.maxBots ?? 10_000; /** @type {string[]} MRU-first list of user location keys */ @@ -49,7 +46,6 @@ export class VoiceStateCache { this._lruBotKeys = []; } - // ── Key helpers ────────────────────────────────────────────────────────── /** Build composite key "guildId:userId" (both cleaned to digits only) */ static userKey(guildId, userId) { @@ -61,7 +57,6 @@ export class VoiceStateCache { return `${String(guildId ?? "").replace(/\D/g, "")}:${String(channelId ?? "").replace(/\D/g, "")}`; } - // ── Core update (unified — called by both raw WS and high-level handler) ─ /** * Update voice state for a user. @@ -84,7 +79,6 @@ export class VoiceStateCache { const lruKeys = isBot ? this._lruBotKeys : this._lruUserKeys; const uKey = VoiceStateCache.userKey(cleanGuild, cleanUser); - // ── Remove from previous channel index ─────────────────────────────── const prev = locations.get(uKey); if (prev) { const prevCKey = VoiceStateCache.channelKey(prev.guildId, prev.channelId); @@ -96,33 +90,21 @@ export class VoiceStateCache { } if (cleanChannel) { - // ── Add to new channel index ─────────────────────────────────────── const cKey = VoiceStateCache.channelKey(cleanGuild, cleanChannel); let set = channelIdx.get(cKey); if (!set) { set = new Set(); channelIdx.set(cKey, set); } set.add(cleanUser); - // ── Update location map ──────────────────────────────────────────── locations.set(uKey, { channelId: cleanChannel, guildId: cleanGuild, userId: cleanUser }); - // ── LRU: move to most-recently-used position ────────────────────── - // JavaScript Maps maintain insertion order, so delete + re-insert - // is O(1) amortized instead of O(n) with indexOf + splice on an array. - // We keep the _lruUserKeys / _lruBotKeys arrays as fast eviction queues - // but use the Map's own key order for O(1) move-to-front. if (locations.has(uKey)) { - // Re-insert to move to end (most recently used) — O(1) locations.delete(uKey); locations.set(uKey, { channelId: cleanChannel, guildId: cleanGuild, userId: cleanUser }); } - // ── Evict if over cap ────────────────────────────────────────────── - // Use the Map's insertion order to find the oldest entry (first key). - // This is O(1) per eviction instead of popping from an array. while (locations.size > maxEntries) { const evictKey = locations.keys().next().value; if (evictKey === uKey) { - // Don't evict the entry we just added — re-insert at end and move to next const evictVal = locations.get(evictKey); locations.delete(evictKey); locations.set(evictKey, evictVal); @@ -138,20 +120,16 @@ export class VoiceStateCache { } locations.delete(evictKey); } - // Also remove from LRU key list if present const lruIdx = lruKeys.indexOf(evictKey); if (lruIdx !== -1) lruKeys.splice(lruIdx, 1); } } else { - // ── User left voice — remove from location map ───────────────────── locations.delete(uKey); - // Remove from LRU list const idx = lruKeys.indexOf(uKey); if (idx !== -1) lruKeys.splice(idx, 1); } } - // ── Query methods ──────────────────────────────────────────────────────── /** * Check if there are any human users in a specific channel. @@ -242,11 +220,10 @@ export class VoiceStateCache { seedUser(guildId, userId, channelId, isBot = false) { const uKey = VoiceStateCache.userKey(guildId, userId); const locations = isBot ? this.botLocations : this.userLocations; - if (locations.has(uKey)) return; // already tracked — don't overwrite + if (locations.has(uKey)) return; this.updateUser({ guildId, userId, channelId, isBot }); } - // ── Bulk operations ────────────────────────────────────────────────────── /** * Remove all entries for a specific guild (used on GuildDelete). @@ -257,7 +234,6 @@ export class VoiceStateCache { const cleanGuild = String(guildId).replace(/\D/g, ""); const prefix = cleanGuild + ":"; - // Humans for (const [uKey, loc] of this.userLocations) { if (uKey.startsWith(prefix)) { const cKey = VoiceStateCache.channelKey(loc.guildId, loc.channelId); @@ -266,14 +242,11 @@ export class VoiceStateCache { this.userLocations.delete(uKey); } } - // Clean up channel member sets for this guild for (const [cKey, set] of this.channelMembers) { if (cKey.startsWith(prefix)) this.channelMembers.delete(cKey); } - // Clean LRU this._lruUserKeys = this._lruUserKeys.filter(k => !k.startsWith(prefix)); - // Bots for (const [uKey, loc] of this.botLocations) { if (uKey.startsWith(prefix)) { const cKey = VoiceStateCache.channelKey(loc.guildId, loc.channelId); @@ -297,13 +270,11 @@ export class VoiceStateCache { removeChannel(guildId, channelId) { const cKey = VoiceStateCache.channelKey(guildId, channelId); - // Humans const humanSet = this.channelMembers.get(cKey); if (humanSet) { for (const userId of humanSet) { const uKey = VoiceStateCache.userKey(guildId, userId); const loc = this.userLocations.get(uKey); - // Only delete if the user is still in THIS channel (not moved) if (loc && loc.channelId === String(channelId).replace(/\D/g, "")) { this.userLocations.delete(uKey); } @@ -311,7 +282,6 @@ export class VoiceStateCache { this.channelMembers.delete(cKey); } - // Bots const botSet = this.botChannelMembers.get(cKey); if (botSet) { for (const userId of botSet) { @@ -337,7 +307,6 @@ export class VoiceStateCache { const cleanGuild = String(guildId).replace(/\D/g, ""); if (!botsOnly) { - // Purge human entries for (const userId of userIds) { const uKey = VoiceStateCache.userKey(cleanGuild, userId); const loc = this.userLocations.get(uKey); @@ -350,7 +319,6 @@ export class VoiceStateCache { } } - // Purge bot entries for (const userId of userIds) { const uKey = VoiceStateCache.userKey(cleanGuild, userId); const loc = this.botLocations.get(uKey); @@ -363,9 +331,6 @@ export class VoiceStateCache { } } - // ── Backward-compatible accessors ──────────────────────────────────────── - // These provide the same interface as the old raw Maps so that existing - // code (dashboard, commands) doesn't need to be rewritten immediately. /** * Get the "observedVoiceUsers" size (human count). @@ -386,7 +351,6 @@ export class VoiceStateCache { */ *iterateHumanUsers() { for (const [uKey, loc] of this.userLocations) { - // Yield the userId (not composite key) as first element for compat yield [loc.userId, { channelId: loc.channelId, guildId: loc.guildId }]; } } @@ -415,7 +379,6 @@ export class VoiceStateCache { if (guildId) { return this.userLocations.get(VoiceStateCache.userKey(guildId, userId)); } - // Legacy fallback: scan for first match const cleanUser = String(userId).replace(/\D/g, ""); for (const [uKey, loc] of this.userLocations) { if (loc.userId === cleanUser) return { channelId: loc.channelId, guildId: loc.guildId }; @@ -446,7 +409,6 @@ export class VoiceStateCache { setBotUser(compositeKey, info) { const guildId = info.guildId; const channelId = info.channelId; - // Extract userId from composite key (format: "guildId:userId") const userId = compositeKey.split(":").pop(); if (guildId && channelId && userId) { this.updateUser({ guildId, userId, channelId, isBot: true }); @@ -464,7 +426,6 @@ export class VoiceStateCache { if (guildId) { this.updateUser({ guildId, userId, channelId: null, isBot: false }); } else { - // Legacy: remove from ALL guilds const cleanUser = String(userId).replace(/\D/g, ""); for (const [uKey, loc] of this.userLocations) { if (loc.userId === cleanUser) { @@ -501,7 +462,6 @@ export class VoiceStateCache { if (guildId) { return this.userLocations.has(VoiceStateCache.userKey(guildId, userId)); } - // Legacy: scan const cleanUser = String(userId).replace(/\D/g, ""); for (const [uKey, loc] of this.userLocations) { if (loc.userId === cleanUser) return true; @@ -520,10 +480,6 @@ export class VoiceStateCache { return this.botLocations.has(compositeKey); } - // ── Map-compatible iteration ───────────────────────────────────────────── - // Allows `for (const [uid, info] of voiceCache)` to work the same as - // `for (const [uid, info] of observedVoiceUsers)` on a raw Map. - // Delegates to iterateHumanUsers() so the yielded shape matches. /** * Default iterator — iterates human users. @@ -553,7 +509,6 @@ export class VoiceStateCache { if (guildId !== undefined) { return this.userLocations.has(VoiceStateCache.userKey(guildId, userId)); } - // Legacy: scan for first match by userId only const cleanUser = String(userId).replace(/\D/g, ""); for (const [, loc] of this.userLocations) { if (loc.userId === cleanUser) return true; @@ -575,7 +530,6 @@ export class VoiceStateCache { const loc = this.userLocations.get(VoiceStateCache.userKey(guildId, userId)); return loc ? { channelId: loc.channelId, guildId: loc.guildId } : undefined; } - // Legacy: scan for first match by userId only const cleanUser = String(userId).replace(/\D/g, ""); for (const [, loc] of this.userLocations) { if (loc.userId === cleanUser) return { channelId: loc.channelId, guildId: loc.guildId }; @@ -607,7 +561,6 @@ export class VoiceStateCache { if (guildId !== undefined) { this.updateUser({ guildId, userId, channelId: null, isBot: false }); } else { - // Legacy: remove from ALL guilds const cleanUser = String(userId).replace(/\D/g, ""); const toRemove = []; for (const [uKey, loc] of this.userLocations) { @@ -655,7 +608,6 @@ export class VoiceStateCache { } } - // ── Debug / stats ──────────────────────────────────────────────────────── get stats() { return { diff --git a/src/constants/providers.mjs b/src/constants/providers.mjs index 90269f9..4c528dd 100644 --- a/src/constants/providers.mjs +++ b/src/constants/providers.mjs @@ -9,7 +9,6 @@ */ export const PROVIDERS = { - // ── Standard search ────────────────────────────────────────────────────── yt: { prefix: "ytsearch", label: "YouTube" }, ytm: { prefix: "ytmsearch", label: "YouTube Music" }, scld: { prefix: "scsearch", label: "SoundCloud" }, @@ -56,14 +55,12 @@ export const PROVIDERS = { anghami: { prefix: "agsearch", label: "Anghami" }, bk: { prefix: "bksearch", label: "Bluesky" }, bluesky: { prefix: "bksearch", label: "Bluesky" }, - // ── Recommendations ────────────────────────────────────────────────────── ytrec: { prefix: "ytrec", label: "YouTube (recommended)" }, sprec: { prefix: "sprec", label: "Spotify (recommended)" }, dzrec: { prefix: "dzrec", label: "Deezer (recommended)" }, tdrec: { prefix: "tdrec", label: "Tidal (recommended)" }, jsrec: { prefix: "jsrec", label: "JioSaavn (recommended)" }, vkrec: { prefix: "vkrec", label: "VK Music (recommended)" }, - // ── TTS ────────────────────────────────────────────────────────────────── gtts: { prefix: "gtts", label: "Google TTS" }, tts: { prefix: "gtts", label: "Google TTS" }, ftts: { prefix: "ftts", label: "Flowery TTS" }, diff --git a/src/dashboard/Dashboard.mjs b/src/dashboard/Dashboard.mjs index 02b7d7f..6134833 100644 --- a/src/dashboard/Dashboard.mjs +++ b/src/dashboard/Dashboard.mjs @@ -8,7 +8,7 @@ import { logger } from "../constants/Logger.mjs"; export class Dashboard { enabled = false; - expiryTime = 1000 * 60 * 60 * 6; // 6 hours — login code expiry + expiryTime = 1000 * 60 * 60 * 6; /** * @param {Remix} remix @@ -23,8 +23,6 @@ export class Dashboard { if (!this.enabled) return this; - // DatabaseManager for login code verification (optional — only needed if - // the backend uses the bot-based login flow instead of Fluxer OAuth2) if (opts.mysql) { this.db = new DatabaseManager(opts.mysql); } @@ -55,10 +53,9 @@ export class Dashboard { const guild = await this.remix.client.guilds.fetch(data.key); if (!guild) return { error: "Server not found" }; const member = await guild.members.fetch(data.accessor).catch(() => null); - const channels = await guild.fetchChannels(); // execute before converting the guild, see caching + const channels = await guild.fetchChannels(); const server = Dashboard.convertServer(guild); if (!member) { - // Non-member should not see any channels — return error instead of leaking all return { error: "You are not a member of this server" }; } server.channels = server.channels.filter(c => { @@ -79,8 +76,6 @@ export class Dashboard { } case "allServers": { - // Auth check: owners see all servers, non-owners see only shared servers - //if (data.accessor && this.remix.handler?.owners?.includes?.(data.accessor)) { try { const guilds = await this.remix.client.user.fetchGuilds(); return guilds.map(g => Dashboard.convertServer(g)); @@ -89,14 +84,12 @@ export class Dashboard { logger.dashboard("[Dashboard] allServers error:", id, e); return []; } - //} if (data.accessor) { try { const accessorUser = await this.remix.client.users.fetch(data.accessor).catch(() => null); if (accessorUser) return await this.remix.getSharedServers(accessorUser); } catch (_) {} } - // Always return an array — backend does .findIndex() on result return []; } @@ -120,23 +113,16 @@ export class Dashboard { }); } - // ═══════════════════════════════════════════════════════════════════════════ - // ── Bot ID isolation ────────────────────────────────────────────────────── /** * Set the bot ID for multi-bot Redis namespace isolation. * Updates the Redis platform string so each bot uses its own channel namespace. - * @param {string} botId - The bot's Discord user ID */ setBotId(botId) { if (!this.enabled || !this.redis) return; - // Use "fluxer_" as the platform so each bot's Redis messages - // are isolated. The dashboard backend must also be configured to match. this.redis.platform = `fluxer`; } - // Dashboard Function Dispatch - // ═══════════════════════════════════════════════════════════════════════════ /** * @param {Object} params @@ -159,9 +145,6 @@ export class Dashboard { if (!user) return { error: "Invalid user" }; let voiceChannel, textChannel; try { - // Fluxer.js uses channels.get() for cached lookup and channels.fetch() - // for REST fetch. Try fetch first (more reliable for uncached channels), - // fall back to get (cache-only). const chMgr = this.remix.client.channels; if (typeof chMgr.fetch === "function") { voiceChannel = await chMgr.fetch(params.data.channel); @@ -172,19 +155,15 @@ export class Dashboard { } if (!voiceChannel) return { error: "Voice channel not found" }; - // Validate textChannel: if it's a voice channel (type === 2) or missing, - // find a suitable text channel from the guild instead const isText = (ch) => ch && (ch.type === 0 || ch.type === 5 || ch.type === 13 || (typeof ch.isText === "function" && ch.isText())); if (!isText(textChannel)) { - // Auto-pick a text channel from the guild const guild = this.remix.client.guilds.get(voiceChannel.guildId); if (guild?.channels) { const channelValues = typeof guild.channels.values === "function" ? [...guild.channels.values()] : Array.isArray(guild.channels) ? guild.channels : Object.values(guild.channels); - // Prefer system channel, then first text channel const sysCh = guild.systemChannelId ? channelValues.find(c => (c.id ?? c._id) === guild.systemChannelId && isText(c)) : null; @@ -192,29 +171,22 @@ export class Dashboard { } if (!textChannel) { logger.dashboard("[Dashboard] No text channel found for guild", voiceChannel.guildId, "— voice channel will be used as fallback"); - textChannel = voiceChannel; // last resort — _sendToTextChannel will handle it + textChannel = voiceChannel; } } } catch (e) { logger.dashboard("[Dashboard] Error:", e); return { error: "Invalid Channel" }; } - // Verify the user has permission to join the voice channel const authErr = await this._authorizeUserInGuild(user, voiceChannel.guildId); if (authErr) return { error: authErr }; if (this.remix.players.playerMap.has(voiceChannel.id)) { - // Bot is already in this channel — just add the user to the player's - // user list so the backend PlayerManager and SocketHandler can track - // them for real-time updates and multi-user dashboard support. const existingPlayer = this.remix.players.playerMap.get(voiceChannel.id); if (existingPlayer && user && !existingPlayer._dashboardUsers) { existingPlayer._dashboardUsers = []; } if (existingPlayer && user && !existingPlayer._dashboardUsers.includes(String(user.id))) { existingPlayer._dashboardUsers.push(String(user.id)); - // Publish a "join" event on the player's per-channel Redis topic - // so the backend PlayerManager adds this user to the player's users - // list and the SocketHandler subscribes them. try { const pubChannel = this.remix.redis?.publisher ?? this.remix.redis; if (pubChannel && typeof pubChannel.publish === "function") { @@ -227,17 +199,12 @@ export class Dashboard { } return { message: "Already Connected" }; } - // Build a minimal fake message that satisfies PlayerManager.initPlayer(). - // player.textChannel is set to message.channel, so it MUST be the real - // textChannel object (which has .send()) — not a wrapper. Without this, - // ch?.send throws "not a function" when announceSong fires. const fakeMsg = { channel: textChannel, message: { guildId: voiceChannel.guildId }, reply: async () => ({ edit: async () => {}, catch: () => {} }), }; this.remix.players.initPlayer(fakeMsg, voiceChannel.id); - // Track this dashboard user on the player for multi-user support const newPlayer = this.remix.players.playerMap.get(voiceChannel.id); if (newPlayer && user) { if (!newPlayer._dashboardUsers) newPlayer._dashboardUsers = []; @@ -303,7 +270,6 @@ export class Dashboard { player.playRadio(radio); return { message: "Adding radio station" }; } - // Sanitize: reject obviously malicious patterns if (/^(javascript|data|vbscript):/i.test(query.trim())) { return { error: "Invalid query protocol" }; } @@ -316,11 +282,8 @@ export class Dashboard { } case "voiceState": { - // Return the user's current voice channel (if any) if (!user) return { channel: null }; const userId = String(user.id).replace(/\D/g, ""); - // Check VoiceStateCache first (most reliable for Fluxer) - // Uses O(1) lookup via iterateHumanUsers() / [Symbol.iterator] if (this.remix.voiceCache) { for (const [mapUserId, info] of this.remix.voiceCache) { if (String(mapUserId).replace(/\D/g, "") === userId && info.channelId) { @@ -333,7 +296,6 @@ export class Dashboard { } } } - // Fallback: check all guilds for the user's voice state const guilds = this.remix.client.guilds; const guildValues = guilds && typeof guilds.values === "function" ? [...guilds.values()] : guilds ? Object.values(guilds) : []; @@ -358,22 +320,16 @@ export class Dashboard { case "leave": { if (!user) return { error: "Invalid user" }; - // Support both params.data.channel and params.data.player for - // backward compatibility with different backend versions. const playerId = params.data.channel ?? params.data.player; const player = this._getPlayerById(playerId); if (!player) return { error: "Player not found" }; const authErr = await this._authorizeUserInGuild(user, player._guildId); if (authErr) return { error: authErr }; - // Remove this user from the dashboard users list if (player._dashboardUsers && user) { const idx = player._dashboardUsers.indexOf(String(user.id)); if (idx !== -1) player._dashboardUsers.splice(idx, 1); } - // If there are still dashboard users connected, don't destroy the player - // — just remove this user. The player stays active for other users. if (player._dashboardUsers && player._dashboardUsers.length > 0) { - // Publish a leave event for this user on the player channel try { const pubChannel = this.remix.dashboard?.redis?.client ?? this.remix.redis?.client; if (pubChannel && typeof pubChannel.publish === "function") { @@ -398,7 +354,6 @@ export class Dashboard { } } - // ── Authorization helpers ────────────────────────────────────────────── /** * Check if a user is a bot owner, or is in the same voice channel as the player. @@ -416,14 +371,12 @@ export class Dashboard { const observed = this.remix.voiceCache; if (observed) { - // O(1) lookup: check if user is in the same channel as the player const guildId = String(player._guildId ?? "").replace(/\D/g, ""); const userLoc = observed.get(cleanUserId, guildId || undefined); if (userLoc) { const infoChannelId = String(userLoc.channelId ?? "").replace(/\D/g, ""); if (infoChannelId === cleanChanId) return null; } - // Legacy scan fallback (user might not have guildId) for (const [mapUserId, info] of observed) { if (String(mapUserId).replace(/\D/g, "") === cleanUserId) { const infoChannelId = String(info.channelId ?? "").replace(/\D/g, ""); @@ -468,14 +421,11 @@ export class Dashboard { ?? null; } - // ── Static converters ───────────────────────────────────────────────────── /** * @param {import("@fluxerjs/core").User} user */ static convertUser(user) { - // Build avatar URL using fluxerusercontent.com CDN pattern - // user.avatar is the avatar hash string; user.id is the user ID let avatarUrl = ""; if (user.avatar) { avatarUrl = `https://fluxerusercontent.com/avatars/${user.id}/${user.avatar}.webp`; @@ -484,7 +434,6 @@ export class Dashboard { } else if (typeof user.avatarURL === "function") { try { avatarUrl = user.avatarURL() ?? ""; } catch (_) {} } - // Fallback to default avatar if no custom avatar if (!avatarUrl && user.discriminator) { avatarUrl = `https://fluxerusercontent.com/embed/avatars/${parseInt(user.discriminator || "0") % 5}.png`; } @@ -528,8 +477,6 @@ export class Dashboard { static convertChannel(channel) { const type = channel.type ?? 0; const isVoice = channel.isVoice?.() ?? (type === 2) ?? false; - // Discord channel types: 0=text, 1=DM, 2=voice, 3=group DM, 4=category, - // 5=announcement, 13=stage, 15=form, 16=forum, 17=media const isCategory = type === 4; const isText = !isVoice && !isCategory && ( type === 0 || type === 5 || type === 13 || @@ -582,10 +529,8 @@ export class Dashboard { : []; const allChannels = channelValues .map(Dashboard.convertChannel) - .filter(c => !c.isCategory); // exclude categories — they are not joinable + .filter(c => !c.isCategory); - // Build icon URL using fluxerusercontent.com CDN pattern - // guild.icon is the icon hash string; guild.id is the server ID let iconUrl = null; if (guild.icon) { iconUrl = `https://fluxerusercontent.com/icons/${guild.id}/${guild.icon}.webp`; @@ -601,7 +546,6 @@ export class Dashboard { description: guild.description ?? null, ownerId: guild.ownerId, channels: allChannels, - // Frontend expects voiceChannels array for server list display voiceChannels: allChannels.filter(c => c.isVoice), }; } @@ -611,7 +555,6 @@ export class Dashboard { * @param {import("@fluxerjs/core").Guild} guild */ static convertServerSummary(guild) { - // Build icon URL using fluxerusercontent.com CDN pattern let iconUrl = null; if (guild.icon) { iconUrl = `https://fluxerusercontent.com/icons/${guild.id}/${guild.icon}.webp`; @@ -637,7 +580,6 @@ export class Dashboard { const cleanChannelId = channelId ? String(channelId).replace(/\D/g, "") : ""; const cleanGuildId = player._guildId ? String(player._guildId).replace(/\D/g, "") : ""; - // Null-guard: player.queue can be null during teardown const queue = player.queue ?? { loop: false, songLoop: false, current: null, data: [] }; return { @@ -665,14 +607,8 @@ export class Dashboard { } } } - // Fallback: VoiceStateCache (seeded from READY/GUILD_CREATE). - // After a bot reload, guild.voice_states may only contain the bot's - // own voice state, while VoiceStateCache has ALL humans who were - // already in voice when the bot reconnected. - // Try O(1) channel lookup first, then fall back to iteration. const vc = player._voiceCache ?? player._observedVoiceUsers; if (vc && cleanChannelId && cleanGuildId) { - // O(1) lookup via getHumansInChannel if (typeof vc.getHumansInChannel === "function") { const channelHumans = vc.getHumansInChannel(cleanGuildId, cleanChannelId); for (const hid of channelHumans) { @@ -683,13 +619,11 @@ export class Dashboard { seen.add(hid); } } else { - // Legacy iteration fallback for (const [mapUserId, info] of vc) { if (seen.has(mapUserId)) continue; const infoCh = String(info.channelId ?? "").replace(/\D/g, ""); const infoG = String(info.guildId ?? "").replace(/\D/g, ""); if (infoCh === cleanChannelId && infoG === cleanGuildId) { - // Skip the bot itself const botId = player.client?.user?.id; if (botId && String(mapUserId) === String(botId)) continue; ids.push(String(mapUserId)); @@ -698,7 +632,6 @@ export class Dashboard { } } } - // Merge dashboard users (connected via web UI but not necessarily in Discord voice) if (player._dashboardUsers) { for (const du of player._dashboardUsers) { if (!seen.has(du)) { ids.push(du); seen.add(du); } @@ -707,9 +640,6 @@ export class Dashboard { return ids; })(), channel: channel ? Dashboard.convertChannel(channel) : null, - // Use lightweight server summary to avoid serializing hundreds of channels - // per player update. The frontend should fetch full server details via - // the "server" request type when needed. server: guild ? Dashboard.convertServerSummary(guild) : null, }; } @@ -750,30 +680,7 @@ export class Dashboard { }; } - // ═══════════════════════════════════════════════════════════════════════════ - // Pub/Sub broadcast helpers - // - // CRITICAL: The backend (backend-master) expects standard message - // formats on both the global :players channel and the per-player - // :player_{channelId} channel. The formats are: - // - // Global (:players): - // { type: "init", player: serialisedPlayer } — when bot joins a VC - // { type: "close", player: serialisedPlayer } — when bot leaves a VC - // - // Per-player (:player_{channelId}): - // { type: "startplay", data: serialisedVideo } - // { type: "streamStartPlay", data: timestamp } - // { type: "stopplay", data: null } - // { type: "pause", data: { elapsedTime: ms } } - // { type: "resume", data: { elapsedTime: ms } } - // { type: "volume", data: number } - // { type: "queue", data: serialisedQueueEvent } - // { type: "join", data: userId } - // { type: "leave", data: userId } - // ═══════════════════════════════════════════════════════════════════════════ - // Debounce map for playerUpdate — prevents flooding Redis with rapid updates. _playerUpdateTimers = new Map(); /** @@ -796,8 +703,6 @@ export class Dashboard { if (!this.enabled) return; const key = player._channelId ?? player._guildId ?? "unknown"; - // For "init" and "close" events, send immediately (no debounce) — the - // backend relies on these for player lifecycle management. if (details.type === "init" || details.type === "close") { try { const serialised = Dashboard.convertPlayer(player); @@ -811,13 +716,12 @@ export class Dashboard { return; } - // All other events are debounced to avoid flooding Redis. if (this._playerUpdateTimers.has(key)) { clearTimeout(this._playerUpdateTimers.get(key)); } this._playerUpdateTimers.set(key, setTimeout(() => { this._playerUpdateTimers.delete(key); - if (player._destroyed) return; // skip destroyed players + if (player._destroyed) return; try { const serialised = Dashboard.convertPlayer(player); this.redis.send(this.redis.platform + ":players", JSON.stringify({ @@ -877,9 +781,6 @@ export class Dashboard { this.redis.send(channel, JSON.stringify(details)); } - // ═══════════════════════════════════════════════════════════════════════════ - // Login Confirmation (for backend-based DM code verification flow) - // ═══════════════════════════════════════════════════════════════════════════ /** * Verify a login code submitted by a user via DM. @@ -906,13 +807,13 @@ export class Dashboard { if (res.length === 0) return "If this is a valid code, it was not created for your account."; for (let i = 0; i < res.length; i++) { - if (res[i].verified) continue; // skip already-verified codes (double guard) + if (res[i].verified) continue; if (await this.db.compareHash(code, res[i].token)) { if (Date.now() - this.expiryTime > (new Date(res[i].createdAt)).getTime()) { return "Login token expired"; } await this.db.execute("UPDATE login_codes SET verified=true WHERE id=?", [res[i].id]); - return null; // success + return null; } } diff --git a/src/dashboard/DatabaseManager.mjs b/src/dashboard/DatabaseManager.mjs index 43c544e..46a40c1 100644 --- a/src/dashboard/DatabaseManager.mjs +++ b/src/dashboard/DatabaseManager.mjs @@ -15,8 +15,6 @@ export class DatabaseManager { connectionLimit: 15, ...config, }); - // Without this listener, unhandled pool-level errors (connection drops, - // timeouts) fire an unhandled 'error' event which crashes the process. this.db.on("error", (err) => { logger.error("[DashboardDB] MySQL pool error:", err.code ?? err.message); }); diff --git a/src/dashboard/RedisHandler.mjs b/src/dashboard/RedisHandler.mjs index 18bf883..efb17f0 100644 --- a/src/dashboard/RedisHandler.mjs +++ b/src/dashboard/RedisHandler.mjs @@ -8,7 +8,6 @@ import { logger } from "../constants/Logger.mjs"; */ const DEFAULT_RETRY_STRATEGY = (options) => { if (options.totalRetryTime > 60_000) { - // Stop retrying after 60s total — something is fundamentally wrong return new Error("Redis reconnection exhausted after 60s"); } return Math.min(options.attempt * 500, 5_000); diff --git a/src/probe.mjs b/src/probe.mjs index 4b9e029..c634e87 100644 --- a/src/probe.mjs +++ b/src/probe.mjs @@ -1,11 +1,10 @@ import ffprobe from "ffprobe-static"; import { spawn } from "node:child_process"; -const PROBE_TIMEOUT_MS = 15_000; // 15 seconds +const PROBE_TIMEOUT_MS = 15_000; export default function probe(file) { return new Promise((res, rej) => { - // Pass args as an array — splitting a string on " " breaks paths that contain spaces. const args = [ "-hide_banner", "-show_entries", "format_tags:format=duration", diff --git a/src/worker.mjs b/src/worker.mjs index 8b2879d..8a713a7 100644 --- a/src/worker.mjs +++ b/src/worker.mjs @@ -12,22 +12,15 @@ import { Utils } from "./Utils.mjs"; import { PROVIDERS } from "./constants/providers.mjs"; import { logger } from "./constants/Logger.mjs"; -// ═══════════════════════════════════════════════════════════════════════════════ -// NodeLink Configuration (forwarded from Player via workerData) -// ═══════════════════════════════════════════════════════════════════════════════ const nl = workerData?.data?.nodelink ?? {}; const NL_HOST = nl.host ?? "localhost"; const NL_PORT = nl.port ?? 3000; -// 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_SESSION_ID = nl.sessionId ?? null; 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") { @@ -43,21 +36,16 @@ const _sanitizeRegexes = (() => { return r; })(); -// Strips the NodeLink host, port, and password from any string so they are -// never shown to end-users in messages. function sanitizeError(msg) { if (!msg) return msg; let s = String(msg); for (const { re, sub } of _sanitizeRegexes) { - re.lastIndex = 0; // reset stateful global regexes between calls + re.lastIndex = 0; s = s.replace(re, sub); } return s; } -// ═══════════════════════════════════════════════════════════════════════════════ -// HTTP Helper -// ═══════════════════════════════════════════════════════════════════════════════ /** * Make a GET request to NodeLink and return the parsed JSON body. @@ -109,9 +97,6 @@ async function loadTracks(identifier, nlGetFn = nlGet) { return nlGetFn(`/v4/loadtracks?identifier=${encodeURIComponent(identifier)}`); } -// ═══════════════════════════════════════════════════════════════════════════════ -// Track Conversion -// ═══════════════════════════════════════════════════════════════════════════════ /** * Convert a NodeLink track object to the internal video format. @@ -157,15 +142,9 @@ function tokenizeMatchText(value) { return normalizeMatchText(value).split(" ").filter(Boolean); } -// ═══════════════════════════════════════════════════════════════════════════════ -// Provider Configuration (imported from constants/providers.mjs) -// ═══════════════════════════════════════════════════════════════════════════════ const TYPE_MODIFIERS = ["track","playlist","album","artist","channel","user"]; -// ═══════════════════════════════════════════════════════════════════════════════ -// YTUtils Class -// ═══════════════════════════════════════════════════════════════════════════════ class YTUtils extends EventEmitter { constructor() { super(); } @@ -206,10 +185,8 @@ class YTUtils extends EventEmitter { try { const urlObj = new URL(url); - // Check if it's a YouTube Radio/Mix URL const list = urlObj.searchParams.get("list"); if (list && list.startsWith("RD")) { - // Extract just the video ID and create clean URL const videoId = urlObj.searchParams.get("v"); if (videoId) { logger.worker(`[Worker] Cleaning YouTube Radio URL, extracted video: ${videoId}`); @@ -217,7 +194,6 @@ class YTUtils extends EventEmitter { } } - // Remove start_radio parameter if present if (urlObj.searchParams.has("start_radio")) { urlObj.searchParams.delete("start_radio"); return urlObj.toString(); @@ -387,11 +363,9 @@ class YTUtils extends EventEmitter { async getVideoData(query, provider = "ytm", trackMeta = null) { const request = this._buildRequestContext(query, trackMeta); - // Handle URLs (including YouTube Radio/Mix) if (this.isValidUrl(query)) { this.emit("message", "Loading..."); - // Clean YouTube Radio URLs to prevent metadata mismatches const cleanedUrl = this._cleanYouTubeUrl(query); if (cleanedUrl !== query) { logger.worker(`[Worker] URL cleaned: ${query} -> ${cleanedUrl}`); @@ -405,7 +379,6 @@ class YTUtils extends EventEmitter { return { type: "error", data: null, error: sanitizeError(e.message) }; } - // Handle playlist results if (data.loadType === "playlist") { const tracks = (data.data?.tracks ?? []).map(track => this._applyTrackMeta(trackToVideo(track), trackMeta)); tracks.forEach(t => { t.playlistName = data.data?.info?.name ?? null; }); @@ -413,7 +386,6 @@ class YTUtils extends EventEmitter { return { type: "list", data: tracks }; } - // Handle single track if (data.loadType === "track" && data.data) { const video = this._applyTrackMeta(trackToVideo(data.data), trackMeta); if (!video) return { type: "error", data: "Failed to parse track data." }; @@ -426,7 +398,6 @@ class YTUtils extends EventEmitter { return { type: "error", data: "Empty track data returned." }; } - // Handle search results (take first) if (data.loadType === "search" && data.data?.length) { const bestTrack = this._pickBestTrack(data.data, provider, request) ?? data.data[0]; const video = this._applyTrackMeta(trackToVideo(bestTrack), trackMeta); @@ -434,12 +405,10 @@ class YTUtils extends EventEmitter { return { type: "video", data: video }; } - // No recognizable loadType this.emit("message", `**Could not load that URL.** (loadType: ${data.loadType || "unknown"})`); return { type: "error", data: null, error: "Unknown loadType: " + (data.loadType || "none") }; } - // Handle search queries (non-URLs) this.emit("message", `Searching ${this._providerLabel(provider)}...`); let data; @@ -450,7 +419,6 @@ class YTUtils extends EventEmitter { return { type: "error", data: null, error: sanitizeError(e.message) }; } - // Handle search results if (data.loadType === "search" && data.data?.length) { const trackToUse = this._pickBestTrack(data.data, provider, request) ?? data.data[0]; const video = this._applyTrackMeta(trackToVideo(trackToUse), trackMeta); @@ -458,7 +426,6 @@ class YTUtils extends EventEmitter { return { type: "video", data: video }; } - // Handle playlist from search if (data.loadType === "playlist") { const tracks = (data.data?.tracks ?? []).map(track => this._applyTrackMeta(trackToVideo(track), trackMeta)); if (tracks.length > 0) { @@ -467,7 +434,6 @@ class YTUtils extends EventEmitter { } } - // Single track from search if (data.loadType === "track" && data.data) { const video = this._applyTrackMeta(trackToVideo(data.data), trackMeta); if (!video) return { type: "error", data: "Failed to parse track data." }; @@ -480,22 +446,15 @@ class YTUtils extends EventEmitter { return { type: "error", data: "Empty track data returned." }; } - // Nothing found this.emit("message", `**No results found for '${query}'.**`); return { type: "error", data: null, error: "No results found" }; } } -// ═══════════════════════════════════════════════════════════════════════════════ -// Worker Entry Point -// ═══════════════════════════════════════════════════════════════════════════════ const jobId = workerData?.jobId; const data = workerData?.data; -// ─── Pool mode ──────────────────────────────────────────────────────────────── -// When spawned by PlayerWorkerPool, the worker stays alive and handles multiple -// jobs via parentPort messages instead of exiting after one. if (workerData?.poolMode) { const utils = new YTUtils(); @@ -518,8 +477,6 @@ if (workerData?.poolMode) { const NL_SID_job = nl.sessionId ?? null; const NL_GID_job = jData?.guildId ?? null; - // Build a job-scoped request helper so pool workers handle different - // nodelink configs per job (useful when the session ID rotates). const nlGetJob = (path) => new Promise((resolve, reject) => { const isHttps = NL_PORT_job === 443; const mod = isHttps ? https : http; @@ -577,10 +534,8 @@ if (workerData?.poolMode) { } }); - // Keep the worker alive — don't exit, the pool will terminate() when done. } -// ─── Legacy single-job mode (fallback / dev) ────────────────────────────────── else { if (!jobId) {