diff --git a/commands/autoplay.mjs b/commands/autoplay.mjs index 826f041..16904c8 100644 --- a/commands/autoplay.mjs +++ b/commands/autoplay.mjs @@ -1,3 +1,8 @@ +/** + * @file autoplay command — Toggle autoplay to automatically play similar tracks when the queue ends + * @module commands/autoplay + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; @@ -8,6 +13,12 @@ export const command = new CommandBuilder() .setCategory("music") .addAliases("ap"); +/** + * Execute the autoplay command. + * @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message + * @param {Map} data - Slash-command options map + * @returns {Promise} + */ export async function run(msg, data) { const p = await this.getPlayer(msg, true, true, false); if (!p) return; @@ -39,8 +50,7 @@ export async function run(msg, data) { const pick = similar[Math.floor(Math.random() * Math.min(3, similar.length))]; query = `${pick.name} ${pick.artist}`.trim(); } - } catch (_) { - } + } catch(e) { } } if (!query) { diff --git a/commands/clear.mjs b/commands/clear.mjs index c01fc9c..9832a05 100644 --- a/commands/clear.mjs +++ b/commands/clear.mjs @@ -1,3 +1,8 @@ +/** + * @file clear command — Remove all songs from the queue + * @module commands/clear + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; @@ -8,6 +13,12 @@ export const command = new CommandBuilder() .addAliases("c") .setCategory("music"); +/** + * Execute the clear command. + * @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message + * @param {Map} data - Slash-command options map + * @returns {Promise} + */ export async function run(msg) { const p = await this.getPlayer(msg, false, false, false); if (!p) return; @@ -16,5 +27,5 @@ export async function run(msg) { .setColor(getGlobalColor()) .setDescription(this.t(msg, "responses.clear.cleared")) ; - msg.reply({ embeds: [embed] }); + msg.reply({ embeds: [embed] }).catch(() => {}); } diff --git a/commands/debug.mjs b/commands/debug.mjs index 705c23f..da1993f 100644 --- a/commands/debug.mjs +++ b/commands/debug.mjs @@ -1,12 +1,24 @@ +/** + * @file debug command — Owner-only debug utilities for voice connections, ghost detection, and forced rejoins + * @module commands/debug + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { cleanId } from "../src/Utils.mjs"; import { getVoiceManager } from "@fluxerjs/voice"; +import { ERROR_COLOR, WARN_COLOR, SUCCESS_COLOR, DANGER_COLOR } from "../src/constants/UI.mjs"; +import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs"; -const EMOJI_REMOVE_TIMEOUT = 60_000; const REJOIN_DELAY_MS = 2_000; const INTENTIONAL_LEAVE_TTL = 30_000; +/** + * Return a human-readable label for a voice room's connection state. + * @param {object} room - The voice room instance + * @returns {string} + */ function roomStateLabel(room) { if (!room) return "none"; const cs = room.connectionState; @@ -20,6 +32,12 @@ function roomStateLabel(room) { return String(cs); } +/** + * Detect whether a player has a "ghost" connection — the player object exists + * but the underlying voice room is disconnected, reconnecting, or absent. + * @param {import("../src/Player.mjs").default} player + * @returns {boolean} + */ function isGhostConnection(player) { const conn = player.connection; if (!conn) return false; @@ -41,22 +59,28 @@ function isGhostConnection(player) { return false; } +/** + * Retrieve the bot's voice state from the gateway cache for a given guild. + * @param {object} client - The Discord client instance + * @param {string} guildId - The guild ID to look up + * @returns {{ userId: string, channelId: string } | null} + */ function getBotGatewayVoiceState(client, guildId) { const botId = client.user?.id; if (!botId || !guildId) return null; try { const vm = getVoiceManager(client); if (vm?.voiceStates) { - const cleanGuild = String(guildId).replace(/\D/g, ""); + const cleanGuild = cleanId(guildId); const guildVoiceMap = vm.voiceStates.get(cleanGuild) ?? vm.voiceStates.get(guildId); if (guildVoiceMap && typeof guildVoiceMap.get === "function") { const channelId = guildVoiceMap.get(botId); - if (channelId) return { userId: botId, channelId: String(channelId).replace(/\D/g, "") }; + if (channelId) return { userId: botId, channelId: cleanId(channelId) }; } } - } catch (_) {} + } catch(e) { } try { - const cleanGuild = String(guildId).replace(/\D/g, ""); + const cleanGuild = cleanId(guildId); const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId); const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null; if (!voiceStates) return null; @@ -73,13 +97,18 @@ function getBotGatewayVoiceState(client, guildId) { const uid = state?.user_id ?? state?.userId ?? state?.id; if (uid === botId) { const chId = state?.channel_id ?? state?.channelId ?? null; - if (chId) return { userId: botId, channelId: String(chId).replace(/\D/g, "") }; + if (chId) return { userId: botId, channelId: cleanId(chId) }; } } - } catch (_) {} - return null; + } catch(e) { } } +/** + * Check whether the gateway voice state is stale compared to the player's expected channel. + * @param {object} client - The Discord client instance + * @param {import("../src/Player.mjs").default} player + * @returns {boolean} + */ function isStaleGatewayPresence(client, player) { const guildId = player._guildId ?? player._resolveGuildId?.(); if (!guildId) return false; @@ -87,7 +116,7 @@ function isStaleGatewayPresence(client, player) { const gatewayState = getBotGatewayVoiceState(client, guildId); if (!gatewayState) return false; - const playerChannel = String(player._channelId ?? player._home247Channel ?? "").replace(/\D/g, ""); + const playerChannel = cleanId(player._channelId ?? player._home247Channel); const gatewayChannel = gatewayState.channelId; if (!playerChannel) return true; @@ -96,13 +125,19 @@ function isStaleGatewayPresence(client, player) { return false; } +/** + * Destroy a player's stale connection and respawn a fresh player, restoring queue and playback. + * @param {object} ctx - The bot context (this) + * @param {import("../src/Player.mjs").default} player + * @returns {Promise<{ success: boolean, reason?: string, channelId?: string, roomConnected?: boolean, roomState?: string, resumedPlayback?: boolean }>} + */ async function forceRejoinPlayer(ctx, player) { const channelId = player._channelId ?? player._home247Channel; const guildId = player._guildId ?? player._resolveGuildId?.(); if (!channelId || !guildId) return { success: false, reason: "no channel or guild id" }; - const cleanChannelId = String(channelId).replace(/\D/g, ""); - const cleanGuildId = String(guildId).replace(/\D/g, ""); + const cleanChannelId = cleanId(channelId); + const cleanGuildId = cleanId(guildId); const currentTrack = player.queue?.getCurrent(); const queueTracks = player.queue?.data ? [...player.queue.data] : []; @@ -118,7 +153,7 @@ async function forceRejoinPlayer(ctx, player) { const altIds = [player._channelId, player._home247Channel] .filter(Boolean) - .map(id => String(id).replace(/\D/g, "")) + .map(id => cleanId(id)) .filter(id => id !== cleanChannelId); for (const altId of altIds) { ctx.players.playerMap.delete(altId); @@ -135,16 +170,16 @@ async function forceRejoinPlayer(ctx, player) { const revoiceConn = ctx.revoice?.connections?.get(cleanChannelId); if (revoiceConn) { - try { await ctx.revoice._destroyStaleConnection(cleanChannelId, revoiceConn); } catch (_) {} + try { await ctx.revoice._destroyStaleConnection(cleanChannelId, revoiceConn); } catch(e) { } } else if (player.connection) { - try { player.connection.removeAllListeners(); } catch (_) {} - try { ctx.revoice?._leaveGateway?.(cleanChannelId, cleanGuildId); } catch (_) {} - try { ctx.revoice?.deleteConnection?.(cleanChannelId); } catch (_) {} - try { await player.connection.disconnect(); } catch (_) {} + try { player.connection.removeAllListeners(); } catch(e) { } + try { ctx.revoice?._leaveGateway?.(cleanChannelId, cleanGuildId); } catch(e) { } + try { ctx.revoice?.deleteConnection?.(cleanChannelId); } catch(e) { } + try { await player.connection.disconnect(); } catch(e) { } } - try { await player.leave(); } catch (_) {} - try { player.destroy(); } catch (_) {} + try { await player.leave(); } catch(e) { } + try { player.destroy(); } catch(e) { } await new Promise(r => setTimeout(r, REJOIN_DELAY_MS)); @@ -160,7 +195,7 @@ async function forceRejoinPlayer(ctx, player) { newPlayer.queue.current = null; await newPlayer.playNext(); if (wasPaused) newPlayer.pause(); - } catch (_) {} + } catch(e) { } } if (wasAutoplay) newPlayer._autoplay = true; @@ -189,6 +224,12 @@ export const command = new CommandBuilder() .addChoices("voice", "voice-rejoin", "247-rejoin") .setRequired(true)); +/** + * Execute the debug command. + * @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message + * @param {Map} data - Slash-command options map + * @returns {Promise} + */ export async function run(msg, data) { switch (data.get("target").value) { case "247-rejoin": { @@ -197,7 +238,7 @@ export async function run(msg, data) { if (channels247.length === 0) { const embed = new EmbedBuilder() - .setColor(0xFFAA00) + .setColor(WARN_COLOR) .setTitle("Debug — 24/7 Rejoin") .setDescription("No 24/7 channels found in the player map.") ; @@ -214,7 +255,7 @@ export async function run(msg, data) { const [cid, player] = channels247[i]; const channel = this.client.channels.get(cid); const gId = player._guildId ?? channel?.guildId; - const guild = gId ? this.client.guilds.get(String(gId).replace(/\D/g, "")) : null; + const guild = gId ? this.client.guilds.get(cleanId(gId)) : null; const label = `${guild?.name ?? "unknown"} / #${channel?.name ?? cid}`; const ghost = isGhostConnection(player) ? " 👻GHOST" : ""; const roomLabel = player.connection?.room ? roomStateLabel(player.connection.room) : "none"; @@ -223,7 +264,7 @@ export async function run(msg, data) { } const statusEmbed = new EmbedBuilder() - .setColor(0xFFAA00) + .setColor(WARN_COLOR) .setTitle("Debug — 24/7 Rejoin") .setDescription(statusLines.join("\n").slice(0, 4096)) ; @@ -235,7 +276,7 @@ export async function run(msg, data) { const [cid, player] = channels247[i]; const channel = this.client.channels.get(cid); const gId = player._guildId ?? channel?.guildId; - const guild = gId ? this.client.guilds.get(String(gId).replace(/\D/g, "")) : null; + const guild = gId ? this.client.guilds.get(cleanId(gId)) : null; const label = `${guild?.name ?? "unknown"} / #${channel?.name ?? cid}`; const result = await forceRejoinPlayer(this, player); @@ -274,7 +315,7 @@ export async function run(msg, data) { resultLines.push("", `⚠️ **${failedCount}** channel(s) could not be restored.`); } - const finalColor = failedCount === 0 ? 0x00CC66 : 0xFF4444; + const finalColor = failedCount === 0 ? SUCCESS_COLOR : DANGER_COLOR; const finalEmbed = new EmbedBuilder() .setColor(finalColor) .setTitle("Debug — 24/7 Rejoin") @@ -296,7 +337,7 @@ export async function run(msg, data) { ? `\n\n💡 No ghosts auto-detected, but 24/7 channels with dead WebSockets may still report as "connected".\nUse \`%debug 247-rejoin\` to force-rejoin all 24/7 channels.` : ""; const embed = new EmbedBuilder() - .setColor(0x00CC66) + .setColor(SUCCESS_COLOR) .setTitle("Debug — Voice Rejoin") .setDescription(`No ghost connections found. All voice connections appear healthy.${hintLine}`) ; @@ -313,7 +354,7 @@ export async function run(msg, data) { const [cid, player] = ghostEntries[i]; const channel = this.client.channels.get(cid); const gId = player._guildId ?? channel?.guildId; - const guild = gId ? this.client.guilds.get(String(gId).replace(/\D/g, "")) : null; + const guild = gId ? this.client.guilds.get(cleanId(gId)) : null; const label = `${guild?.name ?? "unknown"} / #${channel?.name ?? cid}`; const is247 = player._home247Channel ? "yes" : "no"; const hasTrack = player.queue?.getCurrent() ? "yes" : "no"; @@ -321,7 +362,7 @@ export async function run(msg, data) { } const statusEmbed = new EmbedBuilder() - .setColor(0xFFAA00) + .setColor(WARN_COLOR) .setTitle("Debug — Voice Rejoin") .setDescription(statusLines.join("\n").slice(0, 4096)) ; @@ -333,7 +374,7 @@ export async function run(msg, data) { const [cid, player] = ghostEntries[i]; const channel = this.client.channels.get(cid); const gId = player._guildId ?? channel?.guildId; - const guild = gId ? this.client.guilds.get(String(gId).replace(/\D/g, "")) : null; + const guild = gId ? this.client.guilds.get(cleanId(gId)) : null; const label = `${guild?.name ?? "unknown"} / #${channel?.name ?? cid}`; const result = await forceRejoinPlayer(this, player); @@ -372,7 +413,7 @@ export async function run(msg, data) { resultLines.push("", `⚠️ **${failedCount}** connection(s) could not be restored.`); } - const finalColor = failedCount === 0 ? 0x00CC66 : 0xFF4444; + const finalColor = failedCount === 0 ? SUCCESS_COLOR : DANGER_COLOR; const finalEmbed = new EmbedBuilder() .setColor(finalColor) .setTitle("Debug — Voice Rejoin") @@ -388,7 +429,7 @@ export async function run(msg, data) { const servers = [...this.players.playerMap.entries()].map(([cid, s]) => { const channel = this.client.channels.get(cid); const guildId = s._guildId ?? channel?.guildId ?? channel?.guild_id; - const guild = guildId ? this.client.guilds.get(String(guildId).replace(/\D/g, "")) : null; + const guild = guildId ? this.client.guilds.get(cleanId(guildId)) : null; const conn = s.connection; const room = conn?.room; const ghost = isGhostConnection(s); @@ -520,7 +561,7 @@ export async function run(msg, data) { } if (pages.length === 1) { - const embedColor = ghostConnections.length > 0 ? 0xFF4444 : getGlobalColor(); + const embedColor = ghostConnections.length > 0 ? DANGER_COLOR : getGlobalColor(); const embed = new EmbedBuilder() .setColor(embedColor) .setTitle(this.t(msg, "responses.debug.voiceTitle") + (ghostConnections.length > 0 ? ` — ${ghostConnections.length} Ghost(s) Detected!` : "")) @@ -540,7 +581,7 @@ export async function run(msg, data) { ? this.t(msg, "responses._common.controlsExpired") : `${this.t(msg, "responses.eval.pageLabel", { page: pageIdx + 1, total: totalPages })} • ${this.t(msg, "responses.eval.navigateHint")}`; - const embedColor = (pageIdx === 0 && ghostConnections.length > 0) ? 0xFF4444 : getGlobalColor(); + const embedColor = (pageIdx === 0 && ghostConnections.length > 0) ? DANGER_COLOR : getGlobalColor(); const titleSuffix = (pageIdx === 0 && ghostConnections.length > 0) ? ` — ${ghostConnections.length} Ghost(s) Detected!` : ""; const embed = new EmbedBuilder() @@ -565,7 +606,7 @@ export async function run(msg, data) { await replyMsg.message.removeAllReactions(); } catch { for (const emoji of navEmojis) { - try { await replyMsg.message.removeReaction(emoji); } catch {} + try { await replyMsg.message.removeReaction(emoji); } catch(e) { } } } }; diff --git a/commands/eval.mjs b/commands/eval.mjs index b693527..89c279c 100644 --- a/commands/eval.mjs +++ b/commands/eval.mjs @@ -1,9 +1,14 @@ +/** + * @file eval command — Owner-only JavaScript code evaluation with sensitive-data redaction + * @module commands/eval + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; import { inspect } from "node:util"; +import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs"; -const EMOJI_REMOVE_TIMEOUT = 60000; /** * Matches any key that *contains* one of these strings (case-insensitive). @@ -27,6 +32,13 @@ const RESTRICTED = [ const SCAN_DEPTH = 6; +/** + * Check whether an object contains sensitive keys at any nesting level. + * @param {object} obj - The object to scan + * @param {number} [level=0] - Current recursion depth + * @param {WeakSet} [visited=new WeakSet()] - Visited object tracker + * @returns {boolean} + */ 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; @@ -38,6 +50,13 @@ function hasSensitive(obj, level = 0, visited = new WeakSet()) { return false; } +/** + * Recursively redact sensitive keys from an object, replacing values with "[REDACTED]". + * @param {object} obj - The object to scrub + * @param {number} [level=0] - Current recursion depth + * @param {WeakSet} [visited=new WeakSet()] - Visited object tracker + * @returns {object} The scrubbed object (or the original if no changes were needed) + */ function removeSensitive(obj, level = 0, visited = new WeakSet()) { if (level >= SCAN_DEPTH || typeof obj !== "object" || obj === null) return obj; if (visited.has(obj)) return "[Circular]"; @@ -64,6 +83,11 @@ function removeSensitive(obj, level = 0, visited = new WeakSet()) { return modified ? newObj : obj; } +/** + * Await a value if it is a Promise, then redact sensitive data and format for display. + * @param {*} value - The value to clean and format + * @returns {Promise} Formatted, safe string representation + */ async function clean(value) { if (value instanceof Promise) value = await value; @@ -85,6 +109,11 @@ async function clean(value) { .replace(/@/g, "@\u200b") || "undefined"; } +/** + * Determine whether a code string is a single expression (no semicolons, blocks, or declarations). + * @param {string} code - The code to inspect + * @returns {boolean} + */ function isSingleExpression(code) { const trimmed = code.trim(); @@ -144,6 +173,12 @@ export const command = new CommandBuilder() .setRequired(true) ); +/** + * Execute the eval command. + * @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message + * @param {Map} data - Slash-command options map + * @returns {Promise} + */ export async function run(msg, data) { const expression = data.get("expression").value; @@ -183,7 +218,7 @@ export async function run(msg, data) { else footerText += " " + this.t(msg, "responses.eval.deleteHint"); const embed = new EmbedBuilder() - .setColor(isError ? "#ff0000" : getGlobalColor()) + .setColor(isError ? ERROR_COLOR : getGlobalColor()) .setTitle(title) .setDescription(desc) .setFooter({ text: footerText }) @@ -210,7 +245,7 @@ export async function run(msg, data) { for (const emoji of navEmojis) { try { await replyMsg.message.removeReaction(emoji); - } catch (_) {} + } catch(e) { } } } }; @@ -244,4 +279,4 @@ export async function run(msg, data) { }); resetTimer(); -} \ No newline at end of file +} diff --git a/commands/filter.mjs b/commands/filter.mjs index 64f038a..a7e1fd9 100644 --- a/commands/filter.mjs +++ b/commands/filter.mjs @@ -1,7 +1,15 @@ +/** + * @file filter command — Interactive audio filter picker with emoji-based toggling + * @module commands/filter + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; import { Utils } from "../src/Utils.mjs"; +import { PREV_EMOJI, NEXT_EMOJI, CANCEL_EMOJI } from "../src/constants/UI.mjs"; + +const NAV_EMOJIS = [PREV_EMOJI, NEXT_EMOJI, CANCEL_EMOJI]; const FILTERS = [ { @@ -160,10 +168,6 @@ const FILTERS = [ ]; const PAGE_SIZE = 9; -const PREV_EMOJI = "⬅️"; -const NEXT_EMOJI = "➡️"; -const CANCEL_EMOJI = "❌"; -const NAV_EMOJIS = [PREV_EMOJI, NEXT_EMOJI, CANCEL_EMOJI]; const SESSION_MS = 60_000; @@ -195,6 +199,15 @@ export const command = new CommandBuilder() .setCategory("music") .addAliases("filters", "fx", "effect"); +/** + * Build the embed for a single page of the filter picker. + * @param {Function} t - Translation function + * @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message + * @param {number} page - Current page index (0-based) + * @param {string[]} activeKeys - Currently active filter keys + * @param {object} [current] - The currently playing track + * @returns {import("@fluxerjs/core").EmbedBuilder} + */ function buildPageEmbed(t, msg, page, activeKeys, current) { const totalPages = Math.ceil(FILTERS.length / PAGE_SIZE); const start = page * PAGE_SIZE; @@ -238,6 +251,12 @@ function buildPageEmbed(t, msg, page, activeKeys, current) { ; } +/** + * Execute the filter command. + * @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message + * @param {Map} data - Slash-command options map + * @returns {Promise} + */ export async function run(msg) { const player = await this.getPlayer(msg, false, false, false); if (!player) return; @@ -267,14 +286,14 @@ export async function run(msg) { try { await menuMsg.message.react(emoji); await Utils.sleep(50); - } catch (_) {} + } catch(e) { } } }; const removePageFilterEmojis = async (p) => { const pageEmojis = getPageItems(p).map(f => f.emoji); for (const emoji of pageEmojis) { - try { await menuMsg.message.removeReaction(emoji); } catch (_) {} + try { await menuMsg.message.removeReaction(emoji); } catch(e) { } } }; @@ -288,7 +307,7 @@ export async function run(msg) { await menuMsg.message.removeAllReactions(); } catch (_) { for (const emoji of [...FILTERS.map(f => f.emoji), ...NAV_EMOJIS]) { - try { await menuMsg.message.removeReaction(emoji); } catch (_) {} + try { await menuMsg.message.removeReaction(emoji); } catch(e) { } } } }; @@ -442,4 +461,4 @@ export async function run(msg) { }); resetTimer(); -} \ No newline at end of file +} diff --git a/commands/forceleave.mjs b/commands/forceleave.mjs index abfbdb9..a0226af 100644 --- a/commands/forceleave.mjs +++ b/commands/forceleave.mjs @@ -1,6 +1,10 @@ +/** + * @file forceleave command — Force the bot to leave a voice channel (requires ManageChannels) + * @module commands/forceleave + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; -import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { cleanId } from "../src/MessageHandler.mjs"; export const command = new CommandBuilder() .setName("forceleave") @@ -14,23 +18,22 @@ export const command = new CommandBuilder() .setRequired(true) ); -function embed(desc) { - return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] }; -} - -function cleanId(value) { - return String(value ?? "").replace(/\D/g, ""); -} +/** + * Execute the forceleave command. + * @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message + * @param {Map} data - Slash-command options map + * @returns {Promise} + */ export async function run(msg, data) { const cid = cleanId(data.get("channelId").value); const targetChannel = this.client.channels.get(cid); - if (!targetChannel) return msg.reply(embed(this.t(msg, "responses.forceleave.channelNotFound"))); + if (!targetChannel) return msg.reply(this.t(msg, "responses.forceleave.channelNotFound")); if (cleanId(msg.message?.guildId) !== cleanId(targetChannel.guildId)) - return msg.reply(embed(this.t(msg, "responses.forceleave.wrongServer"))); + return msg.reply(this.t(msg, "responses.forceleave.wrongServer")); const p = this.players.playerMap.get(cid) ?? [...this.players.playerMap.values()].find((player) => cleanId(player?._channelId) === cid); - if (!p) return msg.reply(embed(this.t(msg, "responses.forceleave.playerNotFound"))); - if (!p.connection) return msg.reply(embed(this.t(msg, "responses.forceleave.playerNotInit"))); + if (!p) return msg.reply(this.t(msg, "responses.forceleave.playerNotFound")); + if (!p.connection) return msg.reply(this.t(msg, "responses.forceleave.playerNotInit")); await this.players.leave(msg, cid); } diff --git a/commands/invite.mjs b/commands/invite.mjs index 63f4f87..88d219b 100644 --- a/commands/invite.mjs +++ b/commands/invite.mjs @@ -1,3 +1,8 @@ +/** + * @file invite command — Get the bot invite link and support server invite + * @module commands/invite + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; @@ -8,6 +13,12 @@ export const command = new CommandBuilder() .addAliases("addbot", "remix") .setCategory("util"); +/** + * Execute the invite command. + * @param {import("../src/MessageHandler.mjs").Message} message - The incoming message + * @param {Map} data - Slash-command options map + * @returns {Promise} + */ export async function run(message) { const description = this.t(message, "responses.invite.description"); @@ -25,5 +36,5 @@ export async function run(message) { await message.reply({ embeds: [embed] - }); -} \ No newline at end of file + }).catch(() => {}); +} diff --git a/commands/join.mjs b/commands/join.mjs index 32b1eba..0f1dad8 100644 --- a/commands/join.mjs +++ b/commands/join.mjs @@ -1,23 +1,23 @@ +/** + * @file join command — Make the bot join a voice channel and initialise a player + * @module commands/join + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { getGlobalColor, cleanId, getMessageGuildId } from "../src/MessageHandler.mjs"; import { logger } from "../src/constants/Logger.mjs"; import Player from "../src/Player.mjs"; -function getGuildId(message) { - return message?.channel?.guildId - ?? message?.channel?.guild?.id - ?? message?.message?.guildId - ?? message?.message?.guild?.id - ?? message?.channel?.server_id - ?? message?.channel?.serverId - ?? null; -} - -function cleanId(value) { - return String(value ?? "").replace(/\D/g, ""); -} +/** + * Join a voice channel, create a Player, and register event listeners. + * @param {import("../src/MessageHandler.mjs").Message} message - The incoming message + * @param {string} cid - The voice channel ID to join + * @param {Function} [cb] - Callback invoked with the player on success + * @param {Function} [ecb] - Callback invoked on error + * @returns {Promise} + */ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) { const cleanChannelId = cleanId(cid); if (!this.client.channels.has(cleanChannelId)) { @@ -54,9 +54,9 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) { }); p.on("autoleave", () => { - const activeChannelId = String(p._channelId ?? cid).replace(/\D/g, "") || cid; - const homeChannelId = String(p._home247Channel ?? activeChannelId).replace(/\D/g, "") || activeChannelId; - const guildId = getGuildId(message); + const activeChannelId = cleanId(p._channelId ?? cid) || cid; + const homeChannelId = cleanId(p._home247Channel ?? activeChannelId) || activeChannelId; + const guildId = getMessageGuildId(message); const is247 = (() => { try { @@ -106,13 +106,13 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) { }); p.on("message", m => { - const guildId = getGuildId(message); + const guildId = getMessageGuildId(message); const raw = this.settingsMgr?.getServer?.(guildId)?.get("songAnnouncements"); const disabled = raw === false || raw === 0 || ["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim()); if (disabled) return; const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(m); - message.channel.send({ embeds: [embed] }); + message.channel.send({ embeds: [embed] }).catch(() => {}); }); this.players._pendingJoins.add(cleanChannelId); @@ -147,6 +147,12 @@ export const command = new CommandBuilder() .setRequired(false) ); +/** + * Execute the join command. + * @param {import("../src/MessageHandler.mjs").Message} message - The incoming message + * @param {Map} data - Slash-command options map + * @returns {Promise} + */ export async function run(message, data) { const rawArg = data?.get?.("channel")?.value?.trim?.() ?? null; @@ -160,7 +166,7 @@ export async function run(message, data) { } else if (idMatch) { resolvedId = idMatch[1]; } else { - const guildId = cleanId(getGuildId(message)); + const guildId = cleanId(getMessageGuildId(message)); const allChannels = [ ...(this.client?.channels?.values?.() ?? []) ]; @@ -182,10 +188,10 @@ export async function run(message, data) { return this.players.initPlayer(message, resolvedId); } - const cid = this.players.checkVoiceChannels(message); + const { channelId: cid } = await this.players.checkVoiceChannels(message); if (!cid) { - const prefix = this.handler.getPrefix(getGuildId(message)); + const prefix = this.handler.getPrefix(getMessageGuildId(message)); const embed = new EmbedBuilder().setColor(getGlobalColor()) .setDescription(this.t(message, "responses.join.noVoiceChannel", { prefix })); return message.reply({ embeds: [embed] }); @@ -197,4 +203,4 @@ export async function run(message, data) { export const exportDef = { name: "joinChannel", object: joinChannel -}; \ No newline at end of file +}; diff --git a/commands/lastfm.mjs b/commands/lastfm.mjs index b17d8ed..4d766d0 100644 --- a/commands/lastfm.mjs +++ b/commands/lastfm.mjs @@ -1,10 +1,15 @@ +/** + * @file lastfm command — Link Last.fm accounts, scrobble, view profiles, leaderboards, and more + * @module commands/lastfm + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; import { Utils } from "../src/Utils.mjs"; import { PROVIDER_CHOICES } from "../src/constants/providers.mjs"; +import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs"; -const EMOJI_REMOVE_TIMEOUT = 60_000; const VALID_PERIODS = ["7day", "1month", "3month", "6month", "12month", "overall"]; @@ -46,7 +51,7 @@ export const command = new CommandBuilder() function notConfigured(ctx, msg) { return { embeds: [new EmbedBuilder() - .setColor("#ff0000") + .setColor(ERROR_COLOR) .setDescription(ctx.t(msg, "responses.lastfm.notConfigured"))] }; } @@ -113,7 +118,7 @@ async function getGuildLinkedUsers(guild) { if (userId && !m.user?.bot) memberIds.push(String(userId)); } } - } catch {} + } catch(e) { } return memberIds; } @@ -142,7 +147,8 @@ function extractPeriod(data, msg) { * Shared between `%lastfm play ` and `%play lastfm:`. * * @param {object} ctx - The command `this` context (has .lastfm, .getPlayer, .handler, .t) - * @param {object} msg - The message object + * @param {import("../src/MessageHandler.mjs").Message} msg - The message object + * @param {string} userId - The Discord user ID * @param {string} category - "loved", "top", "recent", or "playlist" * @param {object} [options] * @param {string} [options.period] - Period for top tracks @@ -161,7 +167,7 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = { const validCategories = [...SIMPLE_CATEGORIES, "playlist"]; if (!validCategories.includes(category)) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( `❌ Unknown category \`${category}\`. Use \`loved\`, \`top\`, \`recent\`, \`albums\`, \`artists\`, or \`playlist\`.` )] }); @@ -169,7 +175,7 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = { if (category === "playlist" && !options.playlistId) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( `❌ Specify a playlist number. Use \`${prefix}lastfm playlists\` to see your playlists, then \`${prefix}lastfm play playlist \`.` )] }); @@ -201,7 +207,7 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = { } catch (err) { const errMsg = err.message === "NOT_LINKED" ? notLinked(ctx, msg, prefix) - : { embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(ctx.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; + : { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(ctx.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; if (statusMsg) statusMsg.edit(errMsg).catch(() => msg.reply(errMsg)); else msg.reply(errMsg); return; @@ -328,6 +334,12 @@ function parsePlayArgs(msg, data) { return { category: "" }; } +/** + * Execute the lastfm command. + * @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message + * @param {Map} data - Slash-command options map + * @returns {Promise} + */ export async function run(msg, data) { const lastfm = this.lastfm; if (!lastfm || !lastfm.enabled) return msg.reply(notConfigured(this, msg)); @@ -353,7 +365,7 @@ export async function run(msg, data) { token = await lastfm.getAuthToken(); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.tokenFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.tokenFailed", { error: err.message }))] }); } @@ -395,7 +407,7 @@ export async function run(msg, data) { if (!tokenValue) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.confirmUsage", { prefix }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.confirmUsage", { prefix }))] }); } @@ -404,7 +416,7 @@ export async function run(msg, data) { session = await lastfm.getSession(tokenValue); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.confirmFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.confirmFailed", { error: err.message }))] }); } @@ -453,7 +465,7 @@ export async function run(msg, data) { recentData = await lastfm.getRecentTracks(userId, 1); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } @@ -484,7 +496,7 @@ export async function run(msg, data) { info = await lastfm.getUserInfo(profileUserId); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } @@ -514,7 +526,7 @@ export async function run(msg, data) { playlists = await lastfm.getPlaylists(userId); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } @@ -546,7 +558,7 @@ export async function run(msg, data) { if (parsed.invalidCategory) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( `❌ \`${parsed.resolveProvider}:${parsed.invalidCategory}\` is not valid. Non-Last.fm providers only support \`top\`.\nUse \`${prefix}lastfm play ${parsed.resolveProvider}\` or \`${prefix}lastfm play ${parsed.resolveProvider}:top\` instead.\nFor other categories, use Last.fm as the resolve provider: \`${prefix}lastfm play lf:${parsed.invalidCategory}\`` )] }); @@ -557,7 +569,7 @@ export async function run(msg, data) { ? `\n\n💡 \`${prefix}lastfm play ${parsed.resolveProvider}:\` — Specify a category after the provider:` : ""; return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription([ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription([ `❌ Usage: \`${prefix}lastfm play \``, ``, `**Categories:**`, @@ -607,7 +619,7 @@ export async function run(msg, data) { tracks = await lastfm.getLovedTracks(userId, 15); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } @@ -631,7 +643,7 @@ export async function run(msg, data) { tracks = await lastfm.getTopTracks(userId, period, 15); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } @@ -652,7 +664,7 @@ export async function run(msg, data) { lb = await lastfm.getLeaderboard(0, 10); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } @@ -693,7 +705,7 @@ export async function run(msg, data) { await replyMsg.message.removeAllReactions(); } catch { for (const emoji of navEmojis) { - try { await replyMsg.message.removeReaction(emoji); } catch {} + try { await replyMsg.message.removeReaction(emoji); } catch(e) { } } } }; @@ -727,7 +739,7 @@ export async function run(msg, data) { try { lb = await lastfm.getLeaderboard(currentPage, 10); } catch { - /* keep previous data */ + } await replyMsg.edit(buildPage(currentPage)).catch(() => {}); @@ -746,7 +758,7 @@ export async function run(msg, data) { tracks = await lastfm.getRecentTracks(userId, 15); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } @@ -770,7 +782,7 @@ export async function run(msg, data) { artists = await lastfm.getTopArtists(userId, period, 15); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } @@ -809,7 +821,7 @@ export async function run(msg, data) { const track = pLove.queue?.getCurrent(); if (!track) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.nothingPlayingLove"))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.nothingPlayingLove"))] }); } @@ -823,7 +835,7 @@ export async function run(msg, data) { }); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.loveFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.loveFailed", { error: err.message }))] }); } } @@ -837,7 +849,7 @@ export async function run(msg, data) { const track = pUnlove.queue?.getCurrent(); if (!track) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.nothingPlayingUnlove"))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.nothingPlayingUnlove"))] }); } @@ -851,7 +863,7 @@ export async function run(msg, data) { }); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.unloveFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.unloveFailed", { error: err.message }))] }); } } @@ -875,7 +887,7 @@ export async function run(msg, data) { if (!artistName) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.nothingPlayingNoArtist"))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.nothingPlayingNoArtist"))] }); } @@ -895,7 +907,7 @@ export async function run(msg, data) { try { listeners = await lastfm.getWhoKnows(artistName, memberIds); } catch (err) { - const errEmbed = { embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; + const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed)); else msg.reply(errEmbed); return; @@ -951,7 +963,7 @@ export async function run(msg, data) { if (!artistName) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( this.t(msg, "responses.lastfm.noArtistSpecified") )] }); @@ -962,13 +974,13 @@ export async function run(msg, data) { info = await lastfm.getArtistInfo(artistName, userId); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } if (!info) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.artistNotFound", { artist: artistName }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.artistNotFound", { artist: artistName }))] }); } @@ -1043,7 +1055,7 @@ export async function run(msg, data) { if (!albumName) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( this.t(msg, "responses.lastfm.noAlbumSpecified") )] }); @@ -1054,13 +1066,13 @@ export async function run(msg, data) { info = await lastfm.getAlbumInfo(artistName || "", albumName, userId); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } if (!info) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.albumNotFound", { album: albumName }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.albumNotFound", { album: albumName }))] }); } @@ -1132,13 +1144,13 @@ export async function run(msg, data) { artistName = searchResult.artist; trackName = searchResult.name; } - } catch {} + } catch(e) { } } } if (!artistName || !trackName) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( this.t(msg, "responses.lastfm.noTrackSpecified") )] }); @@ -1149,13 +1161,13 @@ export async function run(msg, data) { info = await lastfm.getTrackInfo(artistName, trackName, userId); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } if (!info) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.trackNotFound", { track: trackName, artist: artistName }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.trackNotFound", { track: trackName, artist: artistName }))] }); } @@ -1215,7 +1227,7 @@ export async function run(msg, data) { let similarTracks = []; try { similarTracks = await lastfm.getSimilarTracks(artistName, trackName, 5); - } catch {} + } catch(e) { } if (similarTracks.length) { const simStr = similarTracks.map(t => { @@ -1242,7 +1254,7 @@ export async function run(msg, data) { albums = await lastfm.getTopAlbums(userId, period, 15); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } @@ -1288,7 +1300,7 @@ export async function run(msg, data) { tags = await lastfm.getUserTopTags(userId, 20); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } @@ -1319,7 +1331,7 @@ export async function run(msg, data) { const tagName = data.get("token")?.value; if (!tagName) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( this.t(msg, "responses.lastfm.tagProvideName", { prefix }) )] }); @@ -1337,13 +1349,13 @@ export async function run(msg, data) { ]); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } if (!tagInfo) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.tagNotFound", { tag: tagName }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.tagNotFound", { tag: tagName }))] }); } @@ -1392,7 +1404,7 @@ export async function run(msg, data) { if (!targetUserId) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( this.t(msg, "responses.lastfm.compareSpecifyUser", { prefix }) )] }); @@ -1401,7 +1413,7 @@ export async function run(msg, data) { const targetUser = await lastfm.getUser(targetUserId); if (!targetUser) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( this.t(msg, "responses.lastfm.compareUserNotLinked") )] }); @@ -1412,13 +1424,13 @@ export async function run(msg, data) { comparison = await lastfm.compareUsers(userId, targetUserId); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } if (!comparison) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.compareFailed"))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.compareFailed"))] }); } @@ -1455,7 +1467,7 @@ export async function run(msg, data) { const current = extractCurrentTrack(pCover); if (!current || !current.name) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.coverNothingPlaying"))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.coverNothingPlaying"))] }); } @@ -1473,7 +1485,7 @@ export async function run(msg, data) { coverUrl = albumInfo.image; albumTitle = `${albumInfo.name} by ${albumInfo.artist}`; } - } catch {} + } catch(e) { } } if (!coverUrl) { @@ -1486,7 +1498,7 @@ export async function run(msg, data) { albumTitle = trackInfo.album.title; } } - } catch {} + } catch(e) { } } if (!coverUrl) { @@ -1509,7 +1521,7 @@ export async function run(msg, data) { const guild = msg.message?.guild ?? msg.message?.member?.guild; if (!guild) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.refreshFailed"))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.refreshFailed"))] }); } let count = 0; @@ -1555,7 +1567,7 @@ export async function run(msg, data) { try { affinityResults = await lastfm.getAffinity(memberIds, 10); } catch (err) { - const errEmbed = { embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; + const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed)); else msg.reply(errEmbed); return; @@ -1606,7 +1618,7 @@ export async function run(msg, data) { try { crowns = await lastfm.getCrowns(userId, memberIds); } catch (err) { - const errEmbed = { embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; + const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed)); else msg.reply(errEmbed); return; @@ -1680,13 +1692,13 @@ export async function run(msg, data) { artistName = searchResult.artist; trackName = searchResult.name; } - } catch {} + } catch(e) { } } } if (!artistName || !trackName) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.noTrackSpecified"))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noTrackSpecified"))] }); } @@ -1704,7 +1716,7 @@ export async function run(msg, data) { try { listeners = await lastfm.getWhoKnowsTrack(artistName, trackName, memberIds); } catch (err) { - const errEmbed = { embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; + const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed)); else msg.reply(errEmbed); return; @@ -1767,7 +1779,7 @@ export async function run(msg, data) { if (!albumName) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.noAlbumSpecified"))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noAlbumSpecified"))] }); } @@ -1785,7 +1797,7 @@ export async function run(msg, data) { try { listeners = await lastfm.getWhoKnowsAlbum(artistName || "", albumName, memberIds); } catch (err) { - const errEmbed = { embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; + const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed)); else msg.reply(errEmbed); return; @@ -1837,7 +1849,7 @@ export async function run(msg, data) { if (!artistName) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.noArtistSpecified"))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noArtistSpecified"))] }); } @@ -1846,7 +1858,7 @@ export async function run(msg, data) { tags = await lastfm.getArtistTopTags(artistName, 15); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } @@ -1897,7 +1909,7 @@ export async function run(msg, data) { if (!albumName) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.noAlbumSpecified"))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noAlbumSpecified"))] }); } @@ -1906,7 +1918,7 @@ export async function run(msg, data) { tags = await lastfm.getAlbumTopTags(artistName || "", albumName, 15); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } @@ -1957,13 +1969,13 @@ export async function run(msg, data) { artistName = searchResult.artist; trackName = searchResult.name; } - } catch {} + } catch(e) { } } } if (!artistName || !trackName) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.noTrackSpecified"))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noTrackSpecified"))] }); } @@ -1972,7 +1984,7 @@ export async function run(msg, data) { tags = await lastfm.getTrackTopTags(artistName, trackName, 15); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } @@ -2008,7 +2020,7 @@ export async function run(msg, data) { friends = await lastfm.getUserFriends(userId, 20); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } @@ -2060,7 +2072,7 @@ export async function run(msg, data) { } } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } @@ -2104,7 +2116,7 @@ export async function run(msg, data) { } } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } @@ -2138,7 +2150,7 @@ export async function run(msg, data) { const tokenTextG = data.get("token")?.value?.trim() ?? ""; if (!tokenTextG) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Provide a query like \`artists \` or \`tracks \`. Example: \`${prefix}lastfm geo artists united states\`.`)] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Provide a query like \`artists \` or \`tracks \`. Example: \`${prefix}lastfm geo artists united states\`.`)] }); } @@ -2156,7 +2168,7 @@ export async function run(msg, data) { if (!country) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Please specify a country name. Example: \`${prefix}lastfm geo artists united states\`.`)] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Please specify a country name. Example: \`${prefix}lastfm geo artists united states\`.`)] }); } @@ -2173,7 +2185,7 @@ export async function run(msg, data) { } } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } @@ -2206,7 +2218,7 @@ export async function run(msg, data) { const tagName = data.get("token")?.value; if (!tagName) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Provide a tag name via the token option. Example: \`${prefix}lastfm tagalbums rock\``)] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Provide a tag name via the token option. Example: \`${prefix}lastfm tagalbums rock\``)] }); } @@ -2215,7 +2227,7 @@ export async function run(msg, data) { albums = await lastfm.getTagTopAlbums(tagName.trim(), 15); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } @@ -2265,7 +2277,7 @@ export async function run(msg, data) { if (!artistName) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.noArtistSpecified"))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noArtistSpecified"))] }); } @@ -2274,7 +2286,7 @@ export async function run(msg, data) { recentTracks = await lastfm.getRecentTracks(userId, 200); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } @@ -2311,7 +2323,7 @@ export async function run(msg, data) { const query = data.get("token")?.value; if (!query) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(`❌ Provide a search query via the token option. Example: \`${prefix}lastfm search radiohead\``)] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Provide a search query via the token option. Example: \`${prefix}lastfm search radiohead\``)] }); } @@ -2324,7 +2336,7 @@ export async function run(msg, data) { ]); } catch (err) { return msg.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }); } diff --git a/commands/leave.mjs b/commands/leave.mjs index 8f1356b..3d25015 100644 --- a/commands/leave.mjs +++ b/commands/leave.mjs @@ -1,7 +1,11 @@ +/** + * @file leave.mjs — Leave the current voice channel and stop playback + * @module commands.leave + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { logger } from "../src/constants/Logger.mjs"; -import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { getGlobalColor, cleanId } from "../src/MessageHandler.mjs"; import { get247ChannelMode } from "../src/constants/Helpers247.mjs"; export const command = new CommandBuilder() @@ -15,13 +19,6 @@ export const command = new CommandBuilder() .setRequired(false) ); -function embed(desc) { - return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] }; -} - -function cleanId(value) { - return String(value ?? "").replace(/\D/g, ""); -} function resolvePlayerGuildId(player, mapKey, client) { const direct = cleanId(player?._guildId); @@ -32,6 +29,12 @@ function resolvePlayerGuildId(player, mapKey, client) { return cleanId(ch?.guildId ?? ch?.guild?.id ?? ch?.server_id ?? ch?.serverId); } +/** + * Execute the leave command. + * @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message + * @param {Map>} data - Slash-command options map + * @returns {Promise} + */ export async function run(msg, data) { const guildId = msg.channel?.guild?.id ?? msg.channel?.guildId @@ -54,24 +57,24 @@ export async function run(msg, data) { if (specifiedChannel) { targetChannelId = cleanId(specifiedChannel); } else { - const userChannelId = this.players.checkVoiceChannels(msg); + const { channelId: userChannelId } = await this.players.checkVoiceChannels(msg); if (userChannelId) targetChannelId = cleanId(userChannelId); } if (!targetChannelId) { if (guildPlayers.length === 0) { - return msg.reply(embed(this.t(msg, "responses.leave.notInVoice"))); + return msg.reply(this.t(msg, "responses.leave.notInVoice")); } const channelList = guildPlayers.map(([mapKey, p]) => { const id = cleanId(p._channelId ?? mapKey); return id ? `<#${id}>` : "`unknown`"; }); - return msg.reply(embed( + return msg.reply( this.t(msg, "responses.leave.specifyChannel", { channels: channelList.map(c => `• ${c}`).join("\n"), prefix: this.handler.getPrefix(msg.message?.guildId ?? msg.channel?.guild?.id) }) - )); + ); } const player = this.players.playerMap.get(targetChannelId) @@ -82,21 +85,21 @@ export async function run(msg, data) { if (!player) { if (guildPlayers.length === 0) { - return msg.reply(embed(this.t(msg, "responses.leave.notInVoice"))); + return msg.reply(this.t(msg, "responses.leave.notInVoice")); } const channelList = guildPlayers.map(([mapKey, p]) => { const id = cleanId(p._channelId ?? mapKey); return id ? `<#${id}>` : "`unknown`"; }); - return msg.reply(embed( + return msg.reply( this.t(msg, "responses.leave.noPlayerInChannel", { channel: `<#${targetChannelId}>`, channels: channelList.map(c => `• ${c}`).join("\n") }) - )); + ); } - if (!player?.connection) return msg.reply(embed(this.t(msg, "responses.leave.playerNotInit"))); + if (!player?.connection) return msg.reply(this.t(msg, "responses.leave.playerNotInit")); const activeChannelId = cleanId(player._channelId) || targetChannelId; const homeChannelId = cleanId(player._home247Channel) || activeChannelId; @@ -134,7 +137,7 @@ export async function run(msg, data) { player.destroy(); if (mode === "auto") { - msg.reply(embed(this.t(msg, "responses.leave.leftRejoin247", { channel: targetChannelId, prefix }))); + msg.reply(this.t(msg, "responses.leave.leftRejoin247", { channel: targetChannelId, prefix })); const rejoinDelay = this.config?.timers?.leave247RejoinDelay ?? 5000; setTimeout(() => { if (this._spawnPlayer) { @@ -144,7 +147,7 @@ export async function run(msg, data) { } }, rejoinDelay); } else { - msg.reply(embed(this.t(msg, "responses.leave.left247On", { prefix }))); + msg.reply(this.t(msg, "responses.leave.left247On", { prefix })); } } else { await this.leaveChannel(activeChannelId, guildId, msg); diff --git a/commands/list.mjs b/commands/list.mjs index 08fa5df..822d8f2 100644 --- a/commands/list.mjs +++ b/commands/list.mjs @@ -1,3 +1,8 @@ +/** + * @file list.mjs — Display the current song queue with pagination + * @module commands.list + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { QueuePaginator, getGlobalColor } from "../src/MessageHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; @@ -16,6 +21,12 @@ export const command = new CommandBuilder() .setRequired(false) ); +/** + * Execute the list command. + * @param {import("../src/MessageHandler.mjs").Message} message - The incoming message + * @param {Map>} data - Slash-command options map + * @returns {Promise} + */ export async function run(message, data) { const p = await this.getPlayer(message); if (!p) return; @@ -85,5 +96,6 @@ export async function run(message, data) { new QueuePaginator(message, this.messages, this.client) .setTimeout(SESSION_MS) - .send(buildEmbed, totalPages, startPage); + .send(buildEmbed, totalPages, startPage) + .catch(() => {}); } diff --git a/commands/loop.mjs b/commands/loop.mjs index f5ae520..08cd20c 100644 --- a/commands/loop.mjs +++ b/commands/loop.mjs @@ -1,3 +1,8 @@ +/** + * @file loop.mjs — Toggle loop mode for the queue or current track + * @module commands.loop + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; @@ -12,6 +17,12 @@ export const command = new CommandBuilder() .setDescription("Specifies what loop should be toggled.", "options.loop.type") .setRequired(true)); +/** + * Execute the loop command. + * @param {import("../src/MessageHandler.mjs").Message} message - The incoming message + * @param {Map>} data - Slash-command options map + * @returns {Promise} + */ export async function run(message, data) { const p = await this.getPlayer(message); if (!p) return; @@ -20,5 +31,5 @@ export async function run(message, data) { .setColor(getGlobalColor()) .setDescription(res) ; - message.reply({ embeds: [embed] }); + message.reply({ embeds: [embed] }).catch(() => {}); } diff --git a/commands/lyrics.mjs b/commands/lyrics.mjs index e9709dc..fbcde47 100644 --- a/commands/lyrics.mjs +++ b/commands/lyrics.mjs @@ -1,8 +1,14 @@ +/** + * @file lyrics.mjs — Fetch and display lyrics for the current or specified song + * @module commands.lyrics + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { logger } from "../src/constants/Logger.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; import { Utils } from "../src/Utils.mjs"; +import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs"; export const command = new CommandBuilder() .setName("lyrics") @@ -11,9 +17,13 @@ export const command = new CommandBuilder() .setCategory("music"); const LOADING_FRAMES = ["◐", "◓", "◑", "◒"]; -const EMOJI_REMOVE_TIMEOUT = 60_000; const SESSION_MS = 180_000; +/** + * Execute the lyrics command. + * @param {import("../src/MessageHandler.mjs").Message} message - The incoming message + * @returns {Promise} + */ export async function run(message) { const p = await this.getPlayer(message, false, false, false); if (!p) return; @@ -28,7 +38,7 @@ export async function run(message) { const loadingMsg = await message.reply({ embeds: [ new EmbedBuilder().setColor(getGlobalColor()) .setDescription(`${LOADING_FRAMES[0]} ` + this.t(message, "responses.lyrics.searching", { title: Utils.truncate(current.title, 40) })) - + ] }); const loadingInterval = setInterval(() => { @@ -36,7 +46,7 @@ export async function run(message) { loadingMsg.edit({ embeds: [ new EmbedBuilder().setColor(getGlobalColor()) .setDescription(`${LOADING_FRAMES[frame]} ` + this.t(message, "responses.lyrics.searching", { title: Utils.truncate(current.title, 40) })) - + ] }).catch(() => {}); }, 800); @@ -54,7 +64,7 @@ export async function run(message) { ] }); } - try { await loadingMsg.message.delete(); } catch {} + try { await loadingMsg.message.delete(); } catch(e) { } const syncIndicator = result.synced ? this.t(message, "responses.lyrics.syncedBadge") : ""; const displayTitle = Utils.cleanTitle(current.title); @@ -189,4 +199,4 @@ export async function run(message) { logger.error("[Lyrics Command] Error:", err); loadingMsg.edit({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(message, "responses.lyrics.error", { error: Utils.truncate(err.message, 100) }))] }).catch(() => {}); } -} \ No newline at end of file +} diff --git a/commands/move.mjs b/commands/move.mjs index 920672d..14501a9 100644 --- a/commands/move.mjs +++ b/commands/move.mjs @@ -1,3 +1,8 @@ +/** + * @file move.mjs — Move a track from one position to another in the queue + * @module commands.move + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; export const command = new CommandBuilder() @@ -16,13 +21,19 @@ export const command = new CommandBuilder() .setRequired(true) ); +/** + * Execute the move command. + * @param {import("../src/MessageHandler.mjs").Message} message - The incoming message + * @param {Map>} data - Slash-command options map + * @returns {Promise} + */ export async function run(message, data) { const p = await this.getPlayer(message, false, false, false); if (!p) return; const from = data.get("from")?.value; const to = data.get("to")?.value; - if (from == null || from < 1) return message.replyEmbed("Source position must be 1 or greater."); - if (to == null || to < 1) return message.replyEmbed("Target position must be 1 or greater."); + if (from == null || from < 1) return message.replyEmbed("Source position must be 1 or greater.").catch(() => {}); + if (to == null || to < 1) return message.replyEmbed("Target position must be 1 or greater.").catch(() => {}); const res = p.move(from, to); - message.replyEmbed(res); + message.replyEmbed(res).catch(() => {}); } diff --git a/commands/np.mjs b/commands/np.mjs index 0185756..821da33 100644 --- a/commands/np.mjs +++ b/commands/np.mjs @@ -1,3 +1,8 @@ +/** + * @file np.mjs — Show now-playing information for the current track + * @module commands.np + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; @@ -7,6 +12,11 @@ export const command = new CommandBuilder() .setDescription("Request the name and url of the currently playing song.", "commands.np") .addAliases("current", "nowplaying"); +/** + * Execute the np command. + * @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message + * @returns {Promise} + */ export async function run(msg) { const p = await this.getPlayer(msg); if (!p) return; @@ -17,12 +27,19 @@ export async function run(msg) { ; const loadingMsg = await msg.reply({ embeds: [loadingEmbed] }); - const data = await p.nowPlaying(); + try { + const data = await p.nowPlaying(); + if (!data?.msg) { + loadingMsg.edit({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses._common.nothingPlaying"))] }).catch(() => {}); + return; + } + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setDescription(data.msg); + if (data.image) embed.setThumbnail(data.image); - const embed = new EmbedBuilder() - .setColor(getGlobalColor()) - .setDescription(data.msg); - if (data.image) embed.setThumbnail(data.image); - - loadingMsg.edit({ embeds: [embed] }).catch(() => {}); + loadingMsg.edit({ embeds: [embed] }).catch(() => {}); + } catch (e) { + loadingMsg.edit({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses._common.nothingPlaying"))] }).catch(() => {}); + } } diff --git a/commands/pause.mjs b/commands/pause.mjs index 8d83b94..5e4b660 100644 --- a/commands/pause.mjs +++ b/commands/pause.mjs @@ -1,3 +1,8 @@ +/** + * @file pause.mjs — Pause the current playback + * @module commands.pause + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; @@ -7,6 +12,11 @@ export const command = new CommandBuilder() .setDescription("Pause the playback in your voice channel", "commands.pause") .setCategory("music"); +/** + * Execute the pause command. + * @param {import("../src/MessageHandler.mjs").Message} message - The incoming message + * @returns {Promise} + */ export async function run(message) { const p = await this.getPlayer(message); if (!p) return; @@ -15,5 +25,5 @@ export async function run(message) { .setColor(getGlobalColor()) .setDescription(res) ; - message.reply({ embeds: [embed] }); + message.reply({ embeds: [embed] }).catch(() => {}); } diff --git a/commands/play.mjs b/commands/play.mjs index cc03404..47af60a 100644 --- a/commands/play.mjs +++ b/commands/play.mjs @@ -1,16 +1,22 @@ +/** + * @file play.mjs — Play a song, playlist, or Last.fm URL — the main music command with provider selection + * @module commands.play + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; -import { PROVIDER_CHOICES } from "../src/constants/providers.mjs"; +import { PROVIDER_CHOICES, parseInlineProvider } from "../src/constants/providers.mjs"; import { playLastFmCategory } from "./lastfm.mjs"; +import { ERROR_COLOR } from "../src/constants/UI.mjs"; /** * Parse a Last.fm music URL and extract artist and track info. * Supports: - * https: - * https: - * https: - * https: + * https://www.last.fm/music/Artist + * https://www.last.fm/music/Artist/Track + * https://www.last.fm/music/Artist/Album/Track + * https://www.last.fm/music/Artist/_/Track * * @param {string} url * @returns {{ artist: string, track: string|null, album: string|null, url: string } | null} @@ -106,15 +112,6 @@ function parseLastFmSubProvider(query) { return { category: lower, resolveProvider: null }; } -function parseInlineProvider(raw) { - const match = raw.match(/^([a-z]+):\s*(.+)$/i); - if (!match) return { provider: null, query: raw.trim() }; - const maybeProvider = match[1].toLowerCase(); - if (PROVIDER_CHOICES.includes(maybeProvider)) { - return { provider: maybeProvider, query: match[2].trim() }; - } - return { provider: null, query: raw.trim() }; -} function parseLastFmTrackQuery(raw) { const value = String(raw ?? "").trim(); @@ -179,6 +176,12 @@ export const command = new CommandBuilder() , true) .addAlias("p"); +/** + * Execute the play command. + * @param {import("../src/MessageHandler.mjs").Message} message - The incoming message + * @param {Map>} data - Slash-command options map + * @returns {Promise} + */ export async function run(message, data) { const rawQuery = data.get("query").value; const flagProvider = data.get("provider")?.value; @@ -204,7 +207,7 @@ export async function run(message, data) { .setColor(getGlobalColor()) .setDescription(this.t(message, "responses.play.searching")); let statusMsg = null; - try { statusMsg = await message.reply({ embeds: [searchEmbed] }); } catch {} + try { statusMsg = await message.reply({ embeds: [searchEmbed] }); } catch(e) { } const playQuery = `${parsed.track} ${parsed.artist}`.trim(); const messages = p.play(playQuery, false, provider === "lastfm" || provider === "lf" ? "yt" : provider, lastfmTrackMeta); @@ -224,7 +227,7 @@ export async function run(message, data) { .setColor(getGlobalColor()) .setDescription(this.t(message, "responses.play.searching")); let statusMsg = null; - try { statusMsg = await message.reply({ embeds: [searchEmbed] }); } catch {} + try { statusMsg = await message.reply({ embeds: [searchEmbed] }); } catch(e) { } const playQuery = parsed.artist; const messages = p.play(playQuery, false, provider === "lastfm" || provider === "lf" ? "yt" : provider); @@ -244,7 +247,7 @@ export async function run(message, data) { if (parsed.invalidCategory) { return message.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( `❌ \`${resolveProvider}:${parsed.invalidCategory}\` is not valid. Non-Last.fm providers only support \`top\`.\nUse \`lastfm:${resolveProvider}\` or \`lastfm:${resolveProvider}:top\` instead.\nFor other categories, use Last.fm as the resolve provider: \`lastfm:lf:${parsed.invalidCategory}\`` )] }); @@ -252,7 +255,7 @@ export async function run(message, data) { if (!lowerQuery && resolveProvider && (resolveProvider === "lf" || resolveProvider === "lastfm")) { return message.reply({ - embeds: [new EmbedBuilder().setColor("#ff0000").setDescription([ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription([ `❌ Specify a Last.fm category after \`lf:\``, ``, `**Available categories:**`, @@ -295,14 +298,14 @@ export async function run(message, data) { `🔍 Searching Last.fm for **${query}**...` )] }); - } catch {} + } catch(e) { } try { searchResult = await lastfm.searchTrack(query); - } catch {} + } catch(e) { } if (!searchResult) { - const noResult = { embeds: [new EmbedBuilder().setColor("#ff0000").setDescription( + const noResult = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( `❌ No results found on Last.fm for **${query}**.` )] }; if (statusMsg) statusMsg.edit(noResult).catch(() => message.reply(noResult)); diff --git a/commands/player.mjs b/commands/player.mjs index a2dde4a..4e98c60 100644 --- a/commands/player.mjs +++ b/commands/player.mjs @@ -1,7 +1,13 @@ +/** + * @file player.mjs — Interactive player control panel with playback buttons and now-playing display + * @module commands.player + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { Utils } from "../src/Utils.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs"; export const command = new CommandBuilder() .setName("player") @@ -38,8 +44,12 @@ const PROGRESS = { end: "▕" }; -const EMOJI_REMOVE_TIMEOUT = 60000; +/** + * Execute the player command. + * @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message + * @returns {Promise} + */ export async function run(msg) { const player = await this.getPlayer(msg, false, false, false); if (!player) return; @@ -68,17 +78,8 @@ export async function run(msg) { ? (current.duration.seconds ?? 0) * 1000 : current.duration; - const progress = Math.min(elapsed / totalMs, 1); - const barLength = 20; - const filled = Math.floor(progress * barLength); - const position = Math.min(Math.max(filled, 0), barLength - 1); - const emptyCount = Math.max(barLength - position - 1, 0); - - progressBar = PROGRESS.start + - PROGRESS.filled.repeat(position) + - (isPlaying ? PROGRESS.indicator : PROGRESS.filled) + - PROGRESS.empty.repeat(emptyCount) + - PROGRESS.end; + const bar = Utils.progressBar(elapsed, totalMs, 20, PROGRESS.filled, PROGRESS.empty, isPlaying ? PROGRESS.indicator : PROGRESS.filled); + progressBar = PROGRESS.start + bar + PROGRESS.end; const elapsedStr = Utils.prettifyMS(elapsed); const totalStr = Utils.prettifyMS(totalMs); @@ -147,7 +148,7 @@ export async function run(msg) { try { await message.message.react(control.emoji); await Utils.sleep(50); - } catch (_) {} + } catch(e) { } } } @@ -167,7 +168,7 @@ export async function run(msg) { for (const emoji of controlEmojis) { try { await message.message.removeReaction(emoji); - } catch (_) {} + } catch(e) { } } } }; @@ -190,7 +191,7 @@ export async function run(msg) { for (const emoji of ["⬅️", "➡️", "❌"]) { try { await lyricsMsg.message.removeReaction(emoji); - } catch (_) {} + } catch(e) { } } } }; @@ -233,9 +234,9 @@ export async function run(msg) { const closedEmbed = buildEmbed({ message: this.t(msg, "responses.player.sessionClosed", { reason: reason !== "timeout" ? ` • ${reason}` : "" }) }); - closedEmbed.color = getGlobalColor(); - closedEmbed.footer = { text: this.t(msg, "responses._common.sessionEnded") }; - closedEmbed.title = this.t(msg, "responses.player.inactiveTitle"); + closedEmbed.setColor(getGlobalColor()); + closedEmbed.setFooter({ text: this.t(msg, "responses._common.sessionEnded") }); + closedEmbed.setTitle(this.t(msg, "responses.player.inactiveTitle")); await message.edit({ embeds: [closedEmbed], @@ -301,7 +302,7 @@ export async function run(msg) { if (player.paused) { reply = player.resume(); } else if (!player.queue.getCurrent() && !player.queue.isEmpty()) { - player.playNext(); + player.playNext().catch(() => {}); reply = this.t(msg, "responses.player.startingPlayback"); } else { reply = this.t(msg, "responses.player.alreadyPlaying"); @@ -360,7 +361,7 @@ export async function run(msg) { shouldUpdate = true; try { const { run: runFilter } = await import("./filter.mjs"); - runFilter.call(this, msg); + await runFilter.call(this, msg); } catch (err) { reply = this.t(msg, "responses.player.filterError", { error: Utils.truncate(err.message, 50) }); } @@ -499,4 +500,4 @@ export async function run(msg) { resetTimeout(); resetEmojiTimer(); -} \ No newline at end of file +} diff --git a/commands/playnext.mjs b/commands/playnext.mjs index 0b20d64..fe428c4 100644 --- a/commands/playnext.mjs +++ b/commands/playnext.mjs @@ -1,17 +1,13 @@ +/** + * @file playnext.mjs — Add a song to the top of the queue (play next) + * @module commands.playnext + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; -import { PROVIDER_CHOICES } from "../src/constants/providers.mjs"; +import { PROVIDER_CHOICES, parseInlineProvider } from "../src/constants/providers.mjs"; -function parseInlineProvider(raw) { - const match = raw.match(/^([a-z]+):\s*(.+)$/i); - if (!match) return { provider: null, query: raw.trim() }; - const maybeProvider = match[1].toLowerCase(); - if (PROVIDER_CHOICES.includes(maybeProvider)) { - return { provider: maybeProvider, query: match[2].trim() }; - } - return { provider: null, query: raw.trim() }; -} export const command = new CommandBuilder() .setName("playnext") @@ -37,6 +33,12 @@ export const command = new CommandBuilder() , true) .addAlias("pn"); +/** + * Execute the playnext command. + * @param {import("../src/MessageHandler.mjs").Message} message - The incoming message + * @param {Map>} data - Slash-command options map + * @returns {Promise} + */ export async function run(message, data) { const p = await this.getPlayer(message, true, true, true); if (!p) return; @@ -50,7 +52,13 @@ export async function run(message, data) { .setColor(getGlobalColor()) .setDescription(this.t(message, "responses.playnext.searching")) ; - const statusMsg = await message.reply({ embeds: [searchEmbed] }); + + let statusMsg; + try { + statusMsg = await message.reply({ embeds: [searchEmbed] }); + } catch (_e) { + return; + } const messages = p.playFirst(query, provider); messages.on("message", d => { diff --git a/commands/radio.mjs b/commands/radio.mjs index 7805eed..9d202ae 100644 --- a/commands/radio.mjs +++ b/commands/radio.mjs @@ -1,17 +1,13 @@ +/** + * @file radio.mjs — Play a radio stream or search for radio stations + * @module commands.radio + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { NUMBER_EMOJIS, CANCEL_EMOJI, PREV_EMOJI, NEXT_EMOJI } from "../src/constants/UI.mjs"; -const NUMBER_EMOJIS = ["1️⃣","2️⃣","3️⃣","4️⃣","5️⃣","6️⃣","7️⃣","8️⃣","9️⃣"]; -const CANCEL_EMOJI = "❌"; -const PREV_EMOJI = "⬅️"; -const NEXT_EMOJI = "➡️"; - -function mkEmbed(desc, title) { - const b = new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc); - if (title) b.setTitle(title); - return { embeds: [b] }; -} export const command = function() { if (!this.config.radio?.length) return null; @@ -27,9 +23,15 @@ export const command = function() { ); }; +/** + * Execute the radio command. + * @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message + * @param {Map>} data - Slash-command options map + * @returns {Promise} + */ export async function run(msg, data) { const radios = this.config.radio; - if (!radios?.length) return msg.reply(mkEmbed(this.t(msg, "responses.radio.noStations"))); + if (!radios?.length) return msg.reply(this.t(msg, "responses.radio.noStations")); const input = (data.get("station")?.value ?? "").trim().toLowerCase(); @@ -49,7 +51,7 @@ export async function run(msg, data) { }); desc += `⬅️ Previous ➡️ Next ❌ Cancel`; - return { payload: mkEmbed(desc), pickable }; + return { payload: { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] }, pickable }; }; let { payload, pickable } = buildPage(); @@ -67,7 +69,7 @@ export async function run(msg, data) { await rawMsg.removeAllReactions(); } catch (_) { for (const emoji of baseEmojis) { - try { await rawMsg.removeReaction(emoji); } catch (_) {} + try { await rawMsg.removeReaction(emoji); } catch(e) { } } } }; @@ -77,7 +79,7 @@ export async function run(msg, data) { settled = true; unobserve(); clearReactions().catch(() => {}); - listMsg.edit(mkEmbed(this.t(msg, "responses.radio.timedOut"))).catch(() => {}); + listMsg.edit(this.t(msg, "responses.radio.timedOut")).catch(() => {}); }, 60_000); const normalize = (s) => s.replace(/\uFE0F/g, ""); @@ -91,7 +93,7 @@ export async function run(msg, data) { clearTimeout(timeout); unobserve(); await clearReactions(); - listMsg.edit(mkEmbed(this.t(msg, "responses.radio.cancelled"))).catch(() => {}); + listMsg.edit(this.t(msg, "responses.radio.cancelled")).catch(() => {}); return; } if (emoji === normalize(NEXT_EMOJI)) page = (page + 1) % totalPages; @@ -120,7 +122,7 @@ export async function run(msg, data) { const radio = radios.find(r => r.name.toLowerCase() === input); if (!radio) { const names = radios.map(r => `\`${r.name}\``).join(", "); - return msg.reply(mkEmbed(this.t(msg, "responses.radio.unknownStation", { station: input, stations: names }))); + return msg.reply(this.t(msg, "responses.radio.unknownStation", { station: input, stations: names })); } return playStation(this, msg, radio); } diff --git a/commands/reload.mjs b/commands/reload.mjs index b141b3c..08e5e14 100644 --- a/commands/reload.mjs +++ b/commands/reload.mjs @@ -1,3 +1,8 @@ +/** + * @file reload.mjs — Hot-reload commands without restarting the bot (owner-only) + * @module commands.reload + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; @@ -16,9 +21,6 @@ export const command = new CommandBuilder() ) .setRequirement(r => r.setOwnerOnly(true)); -function embed(desc) { - return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] }; -} const __dirname = path.dirname(new URL(import.meta.url).pathname); const ROOT = path.resolve(__dirname, ".."); @@ -88,17 +90,17 @@ async function showPaged(msg, title, lines, pageSize = 14) { const arrows = ["⬅️", "➡️"]; const curr = { n: 0 }; - const mkEmbed = (n) => ({ + const buildPageEmbed = (n) => ({ embeds: [ new EmbedBuilder() .setColor(getGlobalColor()) .setTitle(title) .setDescription(pages[n].join("\n") + (pages.length > 1 ? `\n\nPage **${n + 1}** / **${pages.length}**` : "")) - + ] }); - const m = await msg.reply(mkEmbed(0)); + const m = await msg.reply(buildPageEmbed(0)); if (!m || pages.length <= 1) return; m.message.react(arrows[0]).catch(() => {}); @@ -107,7 +109,7 @@ async function showPaged(msg, title, lines, pageSize = 14) { const unsub = m.onReaction(arrows, (e) => { if (e.emoji_id === arrows[0]) curr.n = Math.max(0, curr.n - 1); else curr.n = Math.min(pages.length - 1, curr.n + 1); - m.edit(mkEmbed(curr.n)).catch(() => {}); + m.edit(buildPageEmbed(curr.n)).catch(() => {}); }); setTimeout(() => { unsub?.(); }, 5 * 60_000); @@ -120,6 +122,12 @@ async function showResults(msg, results, label) { await showPaged(msg, `🔄 Reload — ${label}`, [header, "", ...results.map(r => r.msg)]); } +/** + * Execute the reload command. + * @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message + * @param {Map>} data - Slash-command options map + * @returns {Promise} + */ export async function run(msg, data) { const target = (data.get("target")?.value ?? "").trim().toLowerCase(); @@ -178,7 +186,7 @@ export async function run(msg, data) { if (this.handler.commands.some(c => c.name === target)) { const res = await reloadCommand(this, msg, target); - return msg.reply(embed(res.msg)); + return msg.reply(res.msg); } const allMods = [...allModuleFiles("src"), ...allModuleFiles("audio")]; @@ -189,10 +197,10 @@ export async function run(msg, data) { if (mod) { const res = await reloadModule(this, msg, mod.file, mod.label); - return msg.reply(embed(res.msg)); + return msg.reply(res.msg); } - return msg.reply(embed( + return msg.reply( this.t(msg, "responses.reload.unknownTarget", { target }) - )); + ); } diff --git a/commands/remove.mjs b/commands/remove.mjs index 3eb5ab0..a02614d 100644 --- a/commands/remove.mjs +++ b/commands/remove.mjs @@ -1,3 +1,8 @@ +/** + * @file remove.mjs — Remove a specific song from the queue by position + * @module commands.remove + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; export const command = new CommandBuilder() @@ -9,11 +14,17 @@ export const command = new CommandBuilder() .setDescription("The position of the song in the queue. You can view the indices with the 'list' command", "options.remove.index") .setRequired(true)); +/** + * Execute the remove command. + * @param {import("../src/MessageHandler.mjs").Message} message - The incoming message + * @param {Map>} data - Slash-command options map + * @returns {Promise} + */ export async function run(message, data) { const p = await this.getPlayer(message, false, false, false); if (!p) return; const index = data.get("index")?.value; - if (index == null || index < 1) return message.replyEmbed("Queue position must be 1 or greater."); + if (index == null || index < 1) return message.replyEmbed("Queue position must be 1 or greater.").catch(() => {}); const res = p.remove(index - 1); - message.replyEmbed(res); + message.replyEmbed(res).catch(() => {}); } diff --git a/commands/resume.mjs b/commands/resume.mjs index f407e53..46d380a 100644 --- a/commands/resume.mjs +++ b/commands/resume.mjs @@ -1,3 +1,8 @@ +/** + * @file resume.mjs — Resume paused playback + * @module commands.resume + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; @@ -7,6 +12,11 @@ export const command = new CommandBuilder() .setDescription("Resume the playback in your voice channel", "commands.resume") .setCategory("music"); +/** + * Execute the resume command. + * @param {import("../src/MessageHandler.mjs").Message} message - The incoming message + * @returns {Promise} + */ export async function run(message) { const p = await this.getPlayer(message, false, true, false); if (!p) return; @@ -15,5 +25,5 @@ export async function run(message) { .setColor(getGlobalColor()) .setDescription(res) ; - message.reply({ embeds: [embed] }); + message.reply({ embeds: [embed] }).catch(() => {}); } diff --git a/commands/search.mjs b/commands/search.mjs index a7c2f46..7778441 100644 --- a/commands/search.mjs +++ b/commands/search.mjs @@ -1,19 +1,13 @@ +/** + * @file search.mjs — Search for songs with interactive selection menu + * @module commands.search + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { Message, getGlobalColor } from "../src/MessageHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -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 = "❌"; - -function parseInlineProvider(raw) { - const match = raw.match(/^([a-z]+):\s*(.+)$/i); - if (!match) return { provider: null, query: raw.trim() }; - const maybeProvider = match[1].toLowerCase(); - if (PROVIDER_CHOICES.includes(maybeProvider)) - return { provider: maybeProvider, query: match[2].trim() }; - return { provider: null, query: raw.trim() }; -} +import { PROVIDER_CHOICES, PROVIDER_NAMES, parseInlineProvider } from "../src/constants/providers.mjs"; +import { NUMBER_EMOJIS, CANCEL_EMOJI } from "../src/constants/UI.mjs"; export const command = new CommandBuilder() .setName("search") @@ -41,6 +35,12 @@ export const command = new CommandBuilder() .setRequired(true) ); +/** + * Execute the search command. + * @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message + * @param {Map>} data - Slash-command options map + * @returns {Promise} + */ export async function run(msg, data) { const p = await this.getPlayer(msg, true, true, true); if (!p) return; @@ -115,7 +115,7 @@ export async function run(msg, data) { const clearReactions = async () => { try { await rawMsg.removeAllReactions(); - } catch (_) {} + } catch(e) { } }; const wrapped = new Message(rawMsg, this.messages); diff --git a/commands/seek.mjs b/commands/seek.mjs index 12467c8..e15c931 100644 --- a/commands/seek.mjs +++ b/commands/seek.mjs @@ -1,6 +1,13 @@ +/** + * @file seek.mjs — Seek to a specific position in the current track + * @module commands.seek + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { Utils } from "../src/Utils.mjs"; +import { ERROR_COLOR } from "../src/constants/UI.mjs"; export const command = new CommandBuilder() .setName("seek") @@ -12,6 +19,12 @@ export const command = new CommandBuilder() .setRequired(true) ); +/** + * Execute the seek command. + * @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message + * @param {Map>} data - Slash-command options map + * @returns {Promise} + */ export async function run(msg, data) { const positionInput = data.get("position")?.value; @@ -19,73 +32,34 @@ export async function run(msg, data) { if (!p) return; if (!p.queue?.getCurrent()) { - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.seek.nothingPlaying"))] }); + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.seek.nothingPlaying"))] }); } if (p._paused) { - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.seek.paused"))] }); + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.seek.paused"))] }); } - let seekMs = parseSeekPosition(positionInput); - if (seekMs === null || seekMs < 0) { - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.seek.invalidFormat"))] }); + let seekMs = Utils.parseDuration(positionInput); + if (!seekMs || seekMs < 0) { + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.seek.invalidFormat"))] }); } const trackDuration = p._getTrackDurationMs(p.queue.getCurrent()); if (trackDuration > 0 && seekMs >= trackDuration) { - const maxStr = formatDuration(trackDuration); - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.seek.exceedsDuration", { duration: maxStr }))] }); + const maxStr = Utils.prettifyMS(trackDuration); + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.seek.exceedsDuration", { duration: maxStr }))] }); } try { const result = await p.seekToPosition(seekMs); if (result) { - const seekStr = formatDuration(seekMs); - const totalStr = trackDuration > 0 ? formatDuration(trackDuration) : "∞"; + const seekStr = Utils.prettifyMS(seekMs); return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.seek.seeked", { position: seekStr }))] }); } else { - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.seek.notSupported"))] }); + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.seek.notSupported"))] }); } } catch (err) { - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.seek.failed", { error: err.message }))] }); + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.seek.failed", { error: err.message }))] }); } } - -function parseSeekPosition(str) { - if (!str || typeof str !== "string") return null; - str = str.trim(); - - if (/^\d+$/.test(str)) { - return parseInt(str, 10) * 1000; - } - - const parts = str.split(":").map(Number); - if (parts.some(isNaN)) return null; - - if (parts.length === 2) { - const [minutes, seconds] = parts; - if (seconds >= 60) return null; - return (minutes * 60 + seconds) * 1000; - } - - if (parts.length === 3) { - const [hours, minutes, seconds] = parts; - if (minutes >= 60 || seconds >= 60) return null; - return (hours * 3600 + minutes * 60 + seconds) * 1000; - } - - return null; -} - -function formatDuration(ms) { - const totalSeconds = Math.floor(ms / 1000); - const hours = Math.floor(totalSeconds / 3600); - const minutes = Math.floor((totalSeconds % 3600) / 60); - const seconds = totalSeconds % 60; - - if (hours > 0) { - return `${hours}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`; - } - return `${minutes}:${String(seconds).padStart(2, "0")}`; -} diff --git a/commands/servers.mjs b/commands/servers.mjs index 3fb3b40..6faab38 100644 --- a/commands/servers.mjs +++ b/commands/servers.mjs @@ -1,6 +1,12 @@ +/** + * @file servers.mjs — List servers the bot is currently in (owner-only) + * @module commands.servers + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs"; export const command = new CommandBuilder() .setName("servers") @@ -8,8 +14,12 @@ export const command = new CommandBuilder() .setRequirement(r => r.setOwnerOnly(true)) .setCategory("util"); -const EMOJI_REMOVE_TIMEOUT = 60000; +/** + * Execute the servers command. + * @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message + * @returns {Promise} + */ export async function run(msg) { const guilds = [...this.client.guilds.values()]; @@ -86,7 +96,7 @@ export async function run(msg) { for (const emoji of navEmojis) { try { await replyMsg.message.removeReaction(emoji); - } catch (_) {} + } catch(e) { } } } }; @@ -113,4 +123,4 @@ export async function run(msg) { }); resetTimer(); -} \ No newline at end of file +} diff --git a/commands/settings.mjs b/commands/settings.mjs index 97e3e9d..9a86466 100644 --- a/commands/settings.mjs +++ b/commands/settings.mjs @@ -1,6 +1,11 @@ +/** + * @file settings.mjs — Configure server settings — prefix, volume, 24/7 mode, DJ role, locale, and more + * @module commands.settings + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { getGlobalColor, cleanId, getMessageGuildId } from "../src/MessageHandler.mjs"; import runnables from "../settings/runnables.mjs"; function embed(desc, opts = {}) { @@ -50,10 +55,6 @@ const VOLUME_MIN = 1; const VOLUME_MAX = 200; const MAX_247_CHANNELS = 10; -/** Extract clean numeric channel ID from any format */ -function cleanId(raw) { - return String(raw).replace(/\D/g, ""); -} /** * Validate that a value looks like a real Fluxer ID. @@ -62,7 +63,7 @@ function cleanId(raw) { * (which would be garbage like "3", "42", "move", etc.). */ function isValidFluxerId(id) { - const cleaned = String(id).replace(/\D/g, ""); + const cleaned = cleanId(id); return cleaned.length >= 15 && cleaned.length <= 22; } @@ -81,16 +82,6 @@ function displayValue(key, value) { return `\`${value}\``; } -/** Resolve guild ID from a message context */ -function getGuildId(message) { - return message.message?.guildId - ?? message.message?.guild?.id - ?? message.channel?.guildId - ?? message.channel?.guild?.id - ?? message.channel?.server_id - ?? message.channel?.serverId - ?? null; -} /** Resolve guild name from a message context */ function getGuildName(message) { @@ -192,7 +183,7 @@ function resolveChannelName(client, channelId) { try { const ch = client?.channels?.get?.(channelId); if (ch?.name) return ch.name; - } catch (_) {} + } catch(e) { } return null; } @@ -406,7 +397,7 @@ function prettifySettingLabel(key, t, guildId) { async function handle247(ctx, message, value) { const set = ctx.getSettings(message); - const guildId = getGuildId(message); + const guildId = getMessageGuildId(message); const mode = value.toLowerCase().trim(); const resolved = mode === "true" ? "auto" : mode === "false" ? "off" : mode; @@ -420,7 +411,7 @@ async function handle247(ctx, message, value) { if (resolved === "off") { if (!guildId) return message.reply(embed(ctx.t(message, "responses.settings.noServer"))); - const channelId = ctx.players.checkVoiceChannels(message); + const { channelId } = await ctx.players.checkVoiceChannels(message); const channels = get247Channels(set); if (channelId) { @@ -474,7 +465,7 @@ async function handle247(ctx, message, value) { if (!guildId) return message.reply(embed(ctx.t(message, "responses.settings.noServer"))); - const userChannelId = ctx.players.checkVoiceChannels(message); + const { channelId: userChannelId } = await ctx.players.checkVoiceChannels(message); if (!userChannelId) { return message.reply(embed( ctx.t(message, "responses.settings.noVoice247", { mode: resolved, prefix: ctx.handler.getPrefix(guildId) }) @@ -554,7 +545,7 @@ async function applySet(ctx, message, set, key, rawValue) { }); } set.set(key, rawValue); - const guildId = getGuildId(message); + const guildId = getMessageGuildId(message); if (guildId) ctx.locale.invalidateCache(guildId); return null; } @@ -583,7 +574,7 @@ async function handleShortcut(ctx, message, settingKey, valueTokens) { if (valueTokens.length === 0) { if (settingKey === "stay_247") { const t247 = ctx.locale?.translate?.bind(ctx.locale); - return message.reply(build247StatusPanel(set, ctx, message, t247, getGuildId(message))); + return message.reply(build247StatusPanel(set, ctx, message, t247, getMessageGuildId(message))); } const val = set.get(settingKey); return message.reply(embed(`\`${settingKey}\` → ${displayValue(settingKey, val)}`)); @@ -695,6 +686,12 @@ export const command = function() { ); }; +/** + * Execute the settings command. + * @param {import("../src/MessageHandler.mjs").Message} message - The incoming message + * @param {Map>} data - Slash-command options map + * @returns {Promise} + */ export async function run(message, data) { const set = this.getSettings(message); const cmd = data.commandId || "getSettings"; @@ -744,11 +741,11 @@ export async function run(message, data) { if (settingKey) { if (settingKey === "stay_247") { const t247 = this.locale?.translate?.bind(this.locale); - return message.reply(build247StatusPanel(set, this, message, t247, getGuildId(message))); + return message.reply(build247StatusPanel(set, this, message, t247, getMessageGuildId(message))); } const val = set.get(settingKey); const description = this.settingsMgr.descriptions?.[settingKey]; - const prefix = ctx.handler.getPrefix(guildId); + const prefix = this.handler.getPrefix(guildId); const resolvedDesc = description ? description.replace(/\$prefix/gi, prefix) : null; let reply = `**${prettifySettingLabel(settingKey)}**\nValue: ${displayValue(settingKey, val)}`; if (resolvedDesc) reply += `\n\n*${resolvedDesc}*`; @@ -766,7 +763,7 @@ export async function run(message, data) { .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))}`; + return `• **24/7 mode** — ${format247Status(set, this.locale?.translate?.bind(this.locale), getMessageGuildId(message))}`; } return `• **${prettifySettingLabel(k)}** — ${displayValue(k, d[k])}`; }); @@ -784,7 +781,7 @@ export async function run(message, data) { } set.reset(settingKey); if (settingKey === "locale") { - const guildId = getGuildId(message); + const guildId = getMessageGuildId(message); if (guildId) this.locale.invalidateCache(guildId); } const def = set.get(settingKey); @@ -827,7 +824,7 @@ export async function run(message, data) { return message.reply(embed( `**⚙️ Setting: \`${settingKey}\`**\n\n` + `${description}${extra}\n\n` + - `**Current value:** ${settingKey === "stay_247" ? format247Status(set, this.locale?.translate?.bind(this.locale), getGuildId(message)) : displayValue(settingKey, currentVal)}\n` + + `**Current value:** ${settingKey === "stay_247" ? format247Status(set, this.locale?.translate?.bind(this.locale), getMessageGuildId(message)) : displayValue(settingKey, currentVal)}\n` + `**Default:** ${displayValue(settingKey, defaultVal)}`, { title: `⚙️ ${settingKey}` } )); diff --git a/commands/shuffle.mjs b/commands/shuffle.mjs index 9b5c5ed..0c2b2ec 100644 --- a/commands/shuffle.mjs +++ b/commands/shuffle.mjs @@ -1,3 +1,8 @@ +/** + * @file shuffle.mjs — Shuffle the current queue + * @module commands.shuffle + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; @@ -7,6 +12,11 @@ export const command = new CommandBuilder() .setDescription("Re-orders the queue randomly.", "commands.shuffle") .setCategory("music"); +/** + * Execute the shuffle command. + * @param {import("../src/MessageHandler.mjs").Message} message - The incoming message + * @returns {Promise} + */ export async function run(message) { const p = await this.getPlayer(message, false, true, false); if (!p) return; @@ -15,5 +25,5 @@ export async function run(message) { .setColor(getGlobalColor()) .setDescription(res) ; - message.reply({ embeds: [embed] }); + message.reply({ embeds: [embed] }).catch(() => {}); } diff --git a/commands/skip.mjs b/commands/skip.mjs index 705f92f..7901a4f 100644 --- a/commands/skip.mjs +++ b/commands/skip.mjs @@ -1,3 +1,8 @@ +/** + * @file skip.mjs — Skip the currently playing song + * @module commands.skip + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; @@ -8,6 +13,11 @@ export const command = new CommandBuilder() .addAliases("s") .setCategory("music"); +/** + * Execute the skip command. + * @param {import("../src/MessageHandler.mjs").Message} message - The incoming message + * @returns {Promise} + */ export async function run(message) { const p = await this.getPlayer(message); if (!p) return; @@ -30,5 +40,5 @@ export async function run(message) { .setColor(getGlobalColor()) .setDescription(desc) ; - message.reply({ embeds: [embed] }); + message.reply({ embeds: [embed] }).catch(() => {}); } diff --git a/commands/stats.mjs b/commands/stats.mjs index 3745b46..ca33ed8 100644 --- a/commands/stats.mjs +++ b/commands/stats.mjs @@ -1,7 +1,13 @@ +/** + * @file stats.mjs — Display bot statistics — uptime, servers, users, and memory usage + * @module commands.stats + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { Utils } from "../src/Utils.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { logger } from "../src/constants/Logger.mjs"; export const command = new CommandBuilder() .setName("stats") @@ -162,6 +168,11 @@ function buildEmbed(t, msg, { guildCount, userCount, playerCount, scrobbleCount, return builder; } +/** + * Execute the stats command. + * @param {import("../src/MessageHandler.mjs").Message} message - The incoming message + * @returns {Promise} + */ export async function run(message) { const lastfm = this.lastfm; const lastfmEnabled = lastfm?.enabled ?? false; @@ -199,5 +210,5 @@ export async function run(message) { await msg.edit({ embeds: [buildEmbed((...a) => this.t(...a), message, { ...shared, guildCount, userCount: users, scrobbleCount, linkedUsers, ping, loading: false })] - }).catch((err) => console.error("[stats] editEmbed failed:", err)); + }).catch((err) => logger.error("[stats] editEmbed failed:", err)); } diff --git a/commands/support.mjs b/commands/support.mjs index 3cd0b8a..d5da081 100644 --- a/commands/support.mjs +++ b/commands/support.mjs @@ -1,3 +1,8 @@ +/** + * @file support.mjs — Show support server invite link + * @module commands.support + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; @@ -8,6 +13,11 @@ export const command = new CommandBuilder() .addAliases("server") .setCategory("util"); +/** + * run function. + * @param {{*}} msg + * @returns {*} + */ export function run(msg) { const embed = new EmbedBuilder() .setColor(getGlobalColor()) @@ -16,5 +26,5 @@ export function run(msg) { this.t(msg, "responses.support.description") ) ; - msg.reply({ embeds: [embed] }); + msg.reply({ embeds: [embed] }).catch(() => {}); } diff --git a/commands/test.mjs b/commands/test.mjs index 9804265..7c4dfe1 100644 --- a/commands/test.mjs +++ b/commands/test.mjs @@ -1,3 +1,8 @@ +/** + * @file test.mjs — Test/debug command for voice channel user detection + * @module commands.test + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; @@ -7,6 +12,12 @@ export const command = new CommandBuilder() .setDescription("Shows how many people are in each voice channel.") .setRequirement(r => r.setOwnerOnly(true)); +/** + * Execute the test command. + * @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message + * @param {Map>} data - Slash-command options map + * @returns {Promise} + */ export async function run(msg, data) { const guild = msg.channel?.channel?.guild ?? msg.message?.guild; if (!guild) { @@ -56,7 +67,7 @@ export async function run(msg, data) { try { const fetched = await this.client.channels.fetch(channelId); if (fetched?.name) return fetched.name; - } catch (_) {} + } catch(e) { } return `Unknown (${channelId})`; }; @@ -73,5 +84,5 @@ export async function run(msg, data) { .setTitle(this.t(msg, "responses.test.title")) .setDescription(desc.trim().slice(0, 4096)) ; - msg.reply({ embeds: [embed] }); + msg.reply({ embeds: [embed] }).catch(() => {}); } diff --git a/commands/thumbnail.mjs b/commands/thumbnail.mjs index deabde0..94be6de 100644 --- a/commands/thumbnail.mjs +++ b/commands/thumbnail.mjs @@ -1,3 +1,8 @@ +/** + * @file thumbnail.mjs — Get the thumbnail image for the current or specified track + * @module commands.thumbnail + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; @@ -8,6 +13,11 @@ export const command = new CommandBuilder() .addAliases("thumb") .setCategory("music"); +/** + * Execute the thumbnail command. + * @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message + * @returns {Promise} + */ export async function run(msg) { const p = await this.getPlayer(msg); if (!p) return; @@ -18,5 +28,5 @@ export async function run(msg) { .setDescription(data.msg); if (data.image) embed.setImage(data.image); - msg.reply({ embeds: [embed] }); + msg.reply({ embeds: [embed] }).catch(() => {}); } diff --git a/commands/trackopt.mjs b/commands/trackopt.mjs index a8eaa43..052ca6f 100644 --- a/commands/trackopt.mjs +++ b/commands/trackopt.mjs @@ -1,7 +1,14 @@ +/** + * @file trackopt.mjs — Manage per-track options — auto-seek start position and end-time timer + * @module commands.trackopt + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { Utils } from "../src/Utils.mjs"; import { logger } from "../src/constants/Logger.mjs"; +import { ERROR_COLOR } from "../src/constants/UI.mjs"; const DEFAULT_ALIAS = "default"; @@ -51,35 +58,6 @@ export const command = new CommandBuilder() ) .addAlias("to"); -function parseTimeInput(str) { - if (!str || typeof str !== "string") return null; - str = str.trim(); - if (/^\d+$/.test(str)) return parseInt(str, 10) * 1000; - const parts = str.split(":").map(Number); - if (parts.some(isNaN)) return null; - if (parts.length === 2) { - const [minutes, seconds] = parts; - if (seconds >= 60) return null; - return (minutes * 60 + seconds) * 1000; - } - if (parts.length === 3) { - const [hours, minutes, seconds] = parts; - if (minutes >= 60 || seconds >= 60) return null; - return (hours * 3600 + minutes * 60 + seconds) * 1000; - } - return null; -} - -function formatMs(ms) { - if (ms == null || ms < 0) return "0:00"; - const totalSeconds = Math.floor(ms / 1000); - const hours = Math.floor(totalSeconds / 3600); - const minutes = Math.floor((totalSeconds % 3600) / 60); - const seconds = totalSeconds % 60; - if (hours > 0) return `${hours}:${String(minutes).padStart(2, "0")}:${String(seconds).padStart(2, "0")}`; - return `${minutes}:${String(seconds).padStart(2, "0")}`; -} - function extractAlias(parts) { for (let i = 0; i < parts.length; i++) { if (parts[i].toLowerCase().startsWith("alias:")) { @@ -91,10 +69,16 @@ function extractAlias(parts) { return DEFAULT_ALIAS; } +/** + * Execute the trackopt command. + * @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message + * @param {Map>} data - Slash-command options map + * @returns {Promise} + */ export async function run(msg, data) { const trackOpts = this.trackOptions; if (!trackOpts) { - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.notAvailable"))] }); + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.notAvailable"))] }); } const subCommand = data.command.name || data.commandId || "get"; @@ -104,12 +88,12 @@ export async function run(msg, data) { const current = p.queue?.getCurrent(); if (!current && subCommand !== "list") { - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.nothingPlaying"))] }); + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.nothingPlaying"))] }); } const userId = msg.message?.author?.id ?? msg.author?.id; if (!userId) { - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses._common.noVoiceChannel"))] }); + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses._common.noVoiceChannel"))] }); } const prefix = this.handler.getPrefix(msg.message?.guildId); @@ -117,49 +101,57 @@ export async function run(msg, data) { if (subCommand === "set") { const timesRaw = data.get("times")?.value; if (!timesRaw) { - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.invalidFormat"))] }); + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.invalidFormat"))] }); } const parts = timesRaw.trim().split(/\s+/); const aliasRaw = extractAlias(parts); - const startMs = parseTimeInput(parts[0]); - if (startMs === null || startMs < 0) { - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.invalidFormat"))] }); + const startMs = Utils.parseDuration(parts[0]); + if (!startMs || startMs < 0) { + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.invalidFormat"))] }); } let endMs = 0; if (parts.length > 1) { - endMs = parseTimeInput(parts[1]); - if (endMs === null || endMs <= 0) { - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.invalidFormat"))] }); + endMs = Utils.parseDuration(parts[1]); + if (!endMs || endMs <= 0) { + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.invalidFormat"))] }); } if (endMs <= startMs) { - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.invalidEndAfterStart"))] }); + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.invalidEndAfterStart"))] }); } } const trackDuration = p._getTrackDurationMs(current); if (trackDuration > 0) { if (startMs >= trackDuration) { - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.startExceedsDuration", { duration: formatMs(trackDuration) }))] }); + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.startExceedsDuration", { duration: Utils.prettifyMS(trackDuration) }))] }); } if (endMs > 0 && endMs > trackDuration) { - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.endExceedsDuration", { duration: formatMs(trackDuration) }))] }); + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.endExceedsDuration", { duration: Utils.prettifyMS(trackDuration) }))] }); } } const result = await trackOpts.set(userId, current, startMs, endMs, aliasRaw); if (!result) { - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.saveFailed"))] }); + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.saveFailed"))] }); } - const endLabel = endMs > 0 ? formatMs(endMs) : "full track"; + if (result.alias === DEFAULT_ALIAS && p.connection && !p._paused && startMs > 0) { + try { + await p.applyTrackOption({ startMs, endMs, alias: result.alias, userId }); + } catch (applyErr) { + logger.warn("[trackopt] Auto-apply after set failed:", applyErr.message); + } + } + + const endLabel = endMs > 0 ? Utils.prettifyMS(endMs) : "full track"; let desc; if (result.alias === DEFAULT_ALIAS) { - desc = this.t(msg, "responses.trackopt.saved", { title: current.title, aliasLabel: "", start: formatMs(startMs), end: endLabel }); + desc = this.t(msg, "responses.trackopt.saved", { title: current.title, aliasLabel: "", start: Utils.prettifyMS(startMs), end: endLabel }); } else { - desc = this.t(msg, "responses.trackopt.savedAlias", { title: current.title, alias: result.alias, start: formatMs(startMs), end: endLabel, prefix }); + desc = this.t(msg, "responses.trackopt.savedAlias", { title: current.title, alias: result.alias, start: Utils.prettifyMS(startMs), end: endLabel, prefix }); } return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] }); @@ -168,15 +160,15 @@ export async function run(msg, data) { if (subCommand === "get") { const rows = await trackOpts.getAllForTrack(userId, current); if (!rows || rows.length === 0) { - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.notSet", { title: current.title }))] }); + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.notSet", { title: current.title }))] }); } let desc = this.t(msg, "responses.trackopt.current", { title: current.title, count: rows.length }) + "\n\n"; for (const row of rows) { const aliasLabel = row.alias === DEFAULT_ALIAS ? "default" : row.alias; - const endStr = row.end_ms > 0 ? formatMs(row.end_ms) : "end"; + const endStr = row.end_ms > 0 ? Utils.prettifyMS(row.end_ms) : "end"; const autoTag = row.alias === DEFAULT_ALIAS ? " ← auto" : ""; - desc += this.t(msg, "responses.trackopt.currentEntry", { alias: aliasLabel, start: formatMs(row.start_ms), end: endStr, autoTag }) + "\n"; + desc += this.t(msg, "responses.trackopt.currentEntry", { alias: aliasLabel, start: Utils.prettifyMS(row.start_ms), end: endStr, autoTag }) + "\n"; } return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] }); @@ -185,12 +177,12 @@ export async function run(msg, data) { if (subCommand === "play") { const aliasRaw = data.get("alias")?.value; if (!aliasRaw) { - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.provideAlias", { prefix }))] }); + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.provideAlias", { prefix }))] }); } const safeAlias = aliasRaw.toLowerCase().replace(/[^a-zA-Z0-9_-]/g, "").slice(0, 32); if (!safeAlias) { - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.invalidAlias"))] }); + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.invalidAlias"))] }); } const result = await trackOpts.get(userId, current, safeAlias); @@ -198,26 +190,26 @@ export async function run(msg, data) { const allAliases = await trackOpts.getAllForTrack(userId, current); if (allAliases.length > 0) { const names = allAliases.map(r => r.alias === DEFAULT_ALIAS ? "default" : r.alias).join(", "); - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.aliasNotFound", { alias: safeAlias, title: current.title, names }))] }); + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.aliasNotFound", { alias: safeAlias, title: current.title, names }))] }); } - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.notFound", { title: current.title }))] }); + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.notFound", { title: current.title }))] }); } if (!p.connection || p._paused) { - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.mustBePlaying"))] }); + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.mustBePlaying"))] }); } try { const applied = await p.applyTrackOption(result); if (!applied) { - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.applyFailed", { error: "Unknown error" }))] }); + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.applyFailed", { error: "Unknown error" }))] }); } const aliasLabel = safeAlias === DEFAULT_ALIAS ? "default" : safeAlias; - const endStr = result.endMs > 0 ? formatMs(result.endMs) : "end"; - return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.trackopt.applied", { alias: aliasLabel, start: formatMs(result.startMs), end: endStr }))] }); + const endStr = result.endMs > 0 ? Utils.prettifyMS(result.endMs) : "end"; + return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.trackopt.applied", { alias: aliasLabel, start: Utils.prettifyMS(result.startMs), end: endStr }))] }); } catch (e) { - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.applyFailed", { error: e.message }))] }); + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.applyFailed", { error: e.message }))] }); } } @@ -225,7 +217,18 @@ export async function run(msg, data) { const aliasRaw = data.get("alias")?.value; const removed = await trackOpts.remove(userId, current, aliasRaw || null); if (!removed) { - return msg.reply({ embeds: [new EmbedBuilder().setColor("#ff0000").setDescription(this.t(msg, "responses.trackopt.notFound", { title: current.title }))] }); + return msg.reply({ embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.trackopt.notFound", { title: current.title }))] }); + } + if (p._activeTrackOpt) { + const removeDefault = !aliasRaw || aliasRaw.toLowerCase() === DEFAULT_ALIAS; + const activeIsDefault = p._activeTrackOpt.alias === DEFAULT_ALIAS; + if (removeDefault && activeIsDefault) { + p._activeTrackOpt = null; + p._clearTrackEndTimer(); + } else if (aliasRaw && p._activeTrackOpt.alias === aliasRaw.toLowerCase()) { + p._activeTrackOpt = null; + p._clearTrackEndTimer(); + } } if (aliasRaw) { return msg.reply({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.trackopt.removedAlias", { alias: aliasRaw, title: current.title }))] }); @@ -244,14 +247,14 @@ export async function run(msg, data) { for (const row of rows) { const title = row.track_title || row.track_identifier; const aliasLabel = row.alias === DEFAULT_ALIAS ? "default" : row.alias; - const endStr = row.end_ms > 0 ? formatMs(row.end_ms) : "end"; + const endStr = row.end_ms > 0 ? Utils.prettifyMS(row.end_ms) : "end"; if (title !== lastTrack) { if (lastTrack) desc += "\n"; desc += `🎵 **${title}**\n`; lastTrack = title; } const autoTag = row.alias === DEFAULT_ALIAS ? " ← auto" : ""; - desc += ` • ${aliasLabel}: ${formatMs(row.start_ms)} → ${endStr}${autoTag}\n`; + desc += ` • ${aliasLabel}: ${Utils.prettifyMS(row.start_ms)} → ${endStr}${autoTag}\n`; } desc += "\n" + this.t(msg, "responses.trackopt.listHint", { prefix }); diff --git a/commands/volume.mjs b/commands/volume.mjs index 5055349..6ba9fbc 100644 --- a/commands/volume.mjs +++ b/commands/volume.mjs @@ -1,8 +1,13 @@ +/** + * @file volume.mjs — Set or view the playback volume + * @module commands.volume + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { MAX_VOLUME } from "../src/constants/UI.mjs"; -const MAX_VOLUME = 200; export const command = new CommandBuilder() .setName("volume") @@ -15,6 +20,12 @@ export const command = new CommandBuilder() ) .addAliases("v", "vol"); +/** + * Execute the volume command. + * @param {import("../src/MessageHandler.mjs").Message} message - The incoming message + * @param {Map>} data - Slash-command options map + * @returns {Promise} + */ export async function run(message, data) { const p = await this.getPlayer(message, false, false, false); if (!p) return; @@ -37,5 +48,5 @@ export async function run(message, data) { } } - message.reply({ embeds: [embed] }); + message.reply({ embeds: [embed] }).catch(() => {}); } diff --git a/commands/volumedefault.mjs b/commands/volumedefault.mjs index 5a2e416..8415ec2 100644 --- a/commands/volumedefault.mjs +++ b/commands/volumedefault.mjs @@ -1,9 +1,14 @@ +/** + * @file volumedefault.mjs — Set the default volume for the server + * @module commands.volumedefault + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; import { PermissionFlags } from "@fluxerjs/core"; +import { MAX_VOLUME } from "../src/constants/UI.mjs"; -const MAX_VOLUME = 200; export const command = new CommandBuilder() .setName("volumedefault") @@ -16,6 +21,12 @@ export const command = new CommandBuilder() ) .addAliases("vd"); +/** + * Execute the volumedefault command. + * @param {import("../src/MessageHandler.mjs").Message} message - The incoming message + * @param {Map>} data - Slash-command options map + * @returns {Promise} + */ export async function run(message, data) { const p = await this.getPlayer(message, false, false, false); if (!p) return; @@ -61,5 +72,5 @@ export async function run(message, data) { } } - message.reply({ embeds: [embed] }); + message.reply({ embeds: [embed] }).catch(() => {}); } diff --git a/commands/vote.mjs b/commands/vote.mjs index 3af415e..6443ed3 100644 --- a/commands/vote.mjs +++ b/commands/vote.mjs @@ -1,10 +1,15 @@ +/** + * @file vote.mjs — Skip-vote system — start a vote to skip the current track + * @module commands.vote + */ + import { CommandBuilder } from "../src/CommandHandler.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; import { Utils } from "../src/Utils.mjs"; import { FLUXERLIST, buildVoteLink } from "../src/constants/API.mjs"; +import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs"; -const EMOJI_REMOVE_TIMEOUT = 60_000; export const command = new CommandBuilder() .setName("vote") @@ -37,7 +42,7 @@ export const command = new CommandBuilder() function notConfigured(prefix, t, guildId) { return { embeds: [new EmbedBuilder() - .setColor("#ff0000") + .setColor(ERROR_COLOR) .setDescription(t(guildId, "responses.vote.notConfigured"))] }; } @@ -45,7 +50,7 @@ function notConfigured(prefix, t, guildId) { function noResourceId(type, prefix, t, guildId) { return { embeds: [new EmbedBuilder() - .setColor("#ff0000") + .setColor(ERROR_COLOR) .setDescription(t(guildId, "responses.vote.noResourceId", { type, prefix }))] }; } @@ -94,6 +99,12 @@ function buildVotersEmbed(voters, total, page, limit, type, resourceId, expired return { embeds: [embed] }; } +/** + * Execute the vote command. + * @param {import("../src/MessageHandler.mjs").Message} msg - The incoming message + * @param {Map>} data - Slash-command options map + * @returns {Promise} + */ export async function run(msg, data) { const fluxerlist = this.fluxerlist; const prefix = this.handler.getPrefix(msg.message?.guildId); @@ -157,7 +168,7 @@ export async function run(msg, data) { } catch (err) { return msg.reply({ embeds: [new EmbedBuilder() - .setColor("#ff0000") + .setColor(ERROR_COLOR) .setDescription(this.t(msg, "responses.vote.fetchVotersFailed", { error: err.message }))] }); } @@ -179,11 +190,11 @@ export async function run(msg, data) { let currentPage = voterData.page; - const buildPage = (pageIdx, expired = false) => { - return buildVotersEmbed(voterData.voters, voterData.total, pageIdx, 20, resolvedType, id, expired, t, guildId); + const buildPage = (pageIdx, data, expired = false) => { + return buildVotersEmbed(data.voters, data.total, pageIdx, 20, resolvedType, id, expired, t, guildId); }; - const replyMsg = await msg.reply(buildPage(currentPage)); + const replyMsg = await msg.reply(buildPage(currentPage, voterData)); if (!replyMsg?.message) return; const navEmojis = ["\u25C0\uFE0F", "\u25B6\uFE0F", "\u274C"]; @@ -196,18 +207,18 @@ export async function run(msg, data) { await replyMsg.message.removeAllReactions(); } catch { for (const emoji of navEmojis) { - try { await replyMsg.message.removeReaction(emoji); } catch {} + try { await replyMsg.message.removeReaction(emoji); } catch(e) { } } } }; - let emojiTimeout; + let emojiTimeout = null; const resetTimer = () => { clearTimeout(emojiTimeout); emojiTimeout = setTimeout(async () => { unobserve?.(); await clearReactions(); - await replyMsg.edit(buildPage(currentPage, true)).catch(() => {}); + await replyMsg.edit(buildPage(currentPage, voterData, true)).catch(() => {}); }, EMOJI_REMOVE_TIMEOUT); }; @@ -230,10 +241,10 @@ export async function run(msg, data) { try { voterData = await fluxerlist.getVoters(resolvedType, id, { page: currentPage, limit: 20 }); } catch { - /* keep previous data */ + } - await replyMsg.edit(buildPage(currentPage)).catch(() => {}); + await replyMsg.edit(buildPage(currentPage, voterData)).catch(() => {}); }); resetTimer(); diff --git a/index.mjs b/index.mjs index 5f645ab..0d702c0 100644 --- a/index.mjs +++ b/index.mjs @@ -1,3 +1,8 @@ +/** + * @file index.mjs — Fluxer Remix bot — main entry point; initializes client, voice, commands, players, and event handlers + * @module index + */ + import * as fs from "fs"; import path from "path"; import { initLogger, logger, _wsErrorCooldown } from "./src/constants/Logger.mjs"; @@ -5,6 +10,7 @@ import { Client, Events, EmbedBuilder } from "@fluxerjs/core"; import { get247ChannelMode, remove247ChannelMode } from "./src/constants/Helpers247.mjs"; import { CommandHandler, CommandLoader, PrefixManager } from "./src/CommandHandler.mjs"; import { MessageHandler, PageBuilder, HelpCommand, setGlobalColor, getGlobalColor } from "./src/MessageHandler.mjs"; +import { cleanId } from "./src/Utils.mjs"; import { RemoteSettingsManager } from "./src/Settings.mjs"; import { PlayerManager } from "./src/PlayerManager.mjs"; import childProcess from "node:child_process"; @@ -44,11 +50,10 @@ function createBotView(voiceCache) { }; } -/** Helper — build a plain embed payload from a description string */ -function mkEmbed(desc) { - return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] }; -} +/** + * Remix class. + */ export class Remix { constructor() { let config; @@ -94,10 +99,10 @@ export class Remix { }; const client = new Client({ - intents: 0, suppressIntentWarning: true, waitForGuilds: true, ...config["fluxer.js"], + intents: 1 << 7, presence: (() => { if (presenceContents.length === 0) return undefined; const entry = presenceContents[0]; @@ -218,7 +223,7 @@ export class Remix { if (!val || val === "none") continue; const rawArr = Array.isArray(val) ? val : [val]; const cleaned = rawArr - .map(id => String(id).replace(/\D/g, "")) + .map(id => cleanId(id)) .filter(id => id.length >= 15 && id.length <= 22); const needsSave = JSON.stringify(cleaned) !== JSON.stringify(val); if (needsSave || !Array.isArray(val)) { @@ -327,15 +332,14 @@ export class Remix { if (player._isJoining) continue; channelId = player._channelId ?? mapKey; - const cleanChanId = String(channelId).replace(/\D/g, ""); + const cleanChanId = cleanId(channelId); if (!cleanChanId) continue; - const cleanGuildId = String(guildId).replace(/\D/g, ""); - const channelGuildId = String( + const cleanGuildId = cleanId(guildId); + const channelGuildId = cleanId( this.client?.channels?.get?.(channelId)?.guildId ?? - this.client?.channels?.get?.(channelId)?.guild_id ?? - "" - ).replace(/\D/g, ""); + this.client?.channels?.get?.(channelId)?.guild_id + ); if (channelGuildId && channelGuildId !== cleanGuildId) { logger.warn(`[AloneCheck] Skipping inconsistent player state channel=${channelId} playerGuild=${guildId} channelGuild=${channelGuildId}`); continue; @@ -356,7 +360,7 @@ export class Remix { ? [...voiceStates.values()] : Object.values(voiceStates); for (const state of entries) { - const stateChannel = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, ""); + const stateChannel = cleanId(state?.channelId ?? state?.channel_id); if (stateChannel === cleanChanId) { const stateUserId = state?.userId ?? state?.user_id ?? state?.id; const member = guild?.members?.get?.(stateUserId); @@ -371,7 +375,7 @@ export class Remix { } } } - } catch (_) {} + } catch(e) { } } if (!hasHuman) { @@ -381,7 +385,7 @@ export class Remix { hasHuman = true; logger.aloneCheck(`[AloneCheck] Found ${room.remoteParticipants.size} LiveKit remote participant(s) in ${channelId}`); } - } catch (_) {} + } catch(e) { } } logger.aloneCheck(`[AloneCheck] channel=${channelId} guild=${guildId} hasHuman=${hasHuman} paused=${player._paused}`); @@ -405,7 +409,7 @@ export class Remix { }, ALONE_CHECK_INTERVAL); const self = this; - this.players.checkVoiceChannels = function (message) { + this.players.checkVoiceChannels = async function (message) { const userId = message?.author?.id ?? message?.message?.author?.id; const guildId = message?.channel?.guildId ?? @@ -419,92 +423,108 @@ export class Remix { message?.message?.channel?.server_id ?? message?.message?.channel?.serverId; - logger.voice(`[checkVC] userId=${userId} guildId=${guildId}`); - logger.voice(`[checkVC] channel keys: ${Object.keys(message?.channel ?? {}).join(",")}`); - logger.voice(`[checkVC] voiceCache humans=${self.voiceCache.observedVoiceUsersSize} bots=${self.voiceCache.observedVoiceBotsSize}`); + const _empty = { channelId: null, alreadyInVoice: false, hasHumans: false }; if (!userId || !guildId) { logger.voice(`[checkVC] BAIL — missing userId or guildId`); - return null; + return _empty; } - const cleanGuild = String(guildId).replace(/\D/g, ""); + const cleanGuild = cleanId(guildId); - const seed = (channelId) => { + const makeResult = (channelId) => { + const cId = cleanId(channelId); + return { + channelId: cId, + alreadyInVoice: self.players.playerMap.has(cId), + hasHumans: self.voiceCache.hasHumansInChannel(cleanGuild, cId), + }; + }; + + const seedCache = (channelId) => { if (!self.voiceCache.hasHumanUser(userId, cleanGuild)) { self.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId, isBot: false }); } - return self.voiceCache.getUserChannel(cleanGuild, userId) ?? channelId; }; + logger.voice(`[checkVC] userId=${userId} guildId=${guildId} cleanGuild=${cleanGuild}`); + const observed = self.voiceCache.getUserLocation(cleanGuild, userId); - logger.voice(`[checkVC] observed=${JSON.stringify(observed)} cleanGuild=${cleanGuild}`); if (observed && observed.channelId) { logger.voice(`[checkVC] HIT voiceCache → ${observed.channelId}`); - return observed.channelId; + return makeResult(observed.channelId); } try { - const vm = getVoiceManager(client); - const channelId = vm?.getVoiceChannelId?.(guildId, userId); + const vm = getVoiceManager(client); + const channelId = vm?.getVoiceChannelId?.(guildId, userId) ?? vm?.getVoiceChannelId?.(cleanGuild, userId); logger.voice(`[checkVC] vm.getVoiceChannelId → ${channelId}`); - if (channelId) return seed(channelId); + if (channelId) { + seedCache(channelId); + return makeResult(channelId); + } } catch (e) { logger.voice(`[checkVC] vm error: ${e.message}`); } - const memberVoice = - message?.member?.voice?.channelId ?? - message?.message?.member?.voice?.channelId ?? - null; - logger.voice(`[checkVC] memberVoice=${memberVoice}`); - if (memberVoice) return seed(memberVoice); - try { const guild = client.guilds.get(guildId) ?? client.guilds.get(cleanGuild); - logger.voice(`[checkVC] guild=${guild?.id ?? guild?._id ?? "null"}`); const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null; - logger.voice(`[checkVC] voiceStates=${Array.isArray(voiceStates) ? "array["+voiceStates.length+"]" : typeof voiceStates}`); if (voiceStates) { - if (!Array.isArray(voiceStates) && typeof voiceStates === "object") { - const direct = voiceStates[userId]; - logger.voice(`[checkVC] direct lookup voiceStates[userId]=${JSON.stringify(direct)}`); - if (direct) { - const sch = typeof direct === "string" ? direct - : direct?.channelId ?? direct?.channel_id ?? null; - if (sch) { logger.voice(`[checkVC] HIT direct obj lookup → ${sch}`); return seed(sch); } - } - const firstKey = Object.keys(voiceStates)[0]; - if (firstKey) { - logger.voice(`[checkVC] shape sample: key=${firstKey} val=${JSON.stringify(voiceStates[firstKey])}`); - } - } const entries = Array.isArray(voiceStates) ? voiceStates : typeof voiceStates.values === "function" - ? voiceStates.values() + ? [...voiceStates.values()] : Object.values(voiceStates); for (const state of entries) { - const sid = state?.userId ?? state?.user_id ?? state?.id; - const sch = state?.channelId ?? state?.channel_id; - const sgid = String(state?.guildId ?? state?.guild_id ?? guildId).replace(/\D/g, ""); - logger.voice(`[checkVC] state: sid=${sid} sch=${sch} sgid=${sgid}`); - if (sid === userId && sgid === cleanGuild && sch) { - logger.voice(`[checkVC] HIT guild.voice_states iterate → ${sch}`); - return seed(sch); + const sid = state?.userId ?? state?.user_id ?? state?.id; + const sch = state?.channelId ?? state?.channel_id; + if ((sid === userId || sid === cleanId(userId)) && sch) { + logger.voice(`[checkVC] HIT guild.voice_states → ${sch}`); + seedCache(sch); + return makeResult(sch); } } } } catch (e) { logger.voice(`[checkVC] guild error: ${e.message}`); } try { - const loc = self.voiceCache.getHumanUser(userId); - if (loc && String(loc.guildId ?? "").replace(/\D/g, "") === cleanGuild) { + const loc = self.voiceCache.getHumanUser(userId, cleanGuild); + if (loc && loc.channelId) { logger.voice(`[checkVC] HIT voiceCache scan → ${loc.channelId}`); - return loc.channelId; + return makeResult(loc.channelId); } - } catch (e) { logger.voice(`[checkVC] last-resort error: ${e.message}`); } + } catch (e) { logger.voice(`[checkVC] scan error: ${e.message}`); } - logger.voice(`[checkVC] MISS — returning null`); - return null; + try { + const guild = client.guilds.get(guildId) ?? client.guilds.get(cleanGuild); + if (guild && typeof guild.fetchMember === "function") { + logger.voice(`[checkVC] Trying REST fetchMember fallback for user ${userId}`); + const member = await guild.fetchMember(userId); + const voiceState = member?.voice ?? member?.voiceState ?? null; + const restChannelId = voiceState?.channelId ?? voiceState?.channel_id ?? null; + if (restChannelId) { + logger.voice(`[checkVC] HIT REST member.voice → ${restChannelId}`); + seedCache(restChannelId); + return makeResult(restChannelId); + } + } + } catch (e) { logger.voice(`[checkVC] REST fallback error: ${e.message}`); } + + try { + const guild = client.guilds.get(guildId) ?? client.guilds.get(cleanGuild); + if (guild && typeof client.rest?.get === "function") { + logger.voice(`[checkVC] Trying raw REST /guilds/${cleanGuild}/members/${userId}`); + const memberData = await client.rest.get(`/guilds/${cleanGuild}/members/${userId}`); + const restChannelId = memberData?.voice_state?.channel_id ?? memberData?.channel_id ?? null; + if (restChannelId) { + logger.voice(`[checkVC] HIT raw REST → ${restChannelId}`); + seedCache(restChannelId); + return makeResult(restChannelId); + } + } + } catch (e) { logger.voice(`[checkVC] raw REST error: ${e.message}`); } + + logger.voice(`[checkVC] MISS — returning empty`); + return _empty; }; const __dirname = import.meta.dirname; @@ -641,13 +661,13 @@ export class Remix { } markIntentionalLeave(channelId, ttlMs = null) { - const clean = String(channelId).replace(/\D/g, ""); - if (!clean) return; + const cleanChId = cleanId(channelId); + if (!cleanChId) return; if (ttlMs === null) ttlMs = this.config?.timers?.intentionalLeaveTTL ?? 10_000; - const existing = this.intentionalLeaves.get(clean); + const existing = this.intentionalLeaves.get(cleanChId); if (existing) clearTimeout(existing); - this.intentionalLeaves.set(clean, setTimeout(() => { - this.intentionalLeaves.delete(clean); + this.intentionalLeaves.set(cleanChId, setTimeout(() => { + this.intentionalLeaves.delete(cleanChId); }, ttlMs)); } @@ -660,8 +680,8 @@ export class Remix { * @returns {Promise} The created player */ async _spawnPlayer(guildId, channelId) { - const cleanGuildId = String(guildId).replace(/\D/g, ""); - const cleanChannelId = String(channelId).replace(/\D/g, ""); + const cleanGuildId = cleanId(guildId); + const cleanChannelId = cleanId(channelId); if (!cleanChannelId) throw new Error("_spawnPlayer: invalid channelId"); @@ -717,8 +737,8 @@ export class Remix { return; } - const activeChId = String(player._channelId ?? cleanChannelId).replace(/\D/g, "") || cleanChannelId; - const homeChId = String(player._home247Channel ?? activeChId).replace(/\D/g, "") || activeChId; + const activeChId = cleanId(player._channelId ?? cleanChannelId) || cleanChannelId; + const homeChId = cleanId(player._home247Channel ?? activeChId) || activeChId; this.players.playerMap.delete(activeChId); this.players._unindexPlayer?.(cleanGuildId, activeChId); const pendingScrobble = this.players._pendingScrobbleTimers?.get(cleanChannelId); @@ -740,7 +760,7 @@ export class Remix { if (!ch || typeof ch.send !== "function") { const savedAnnChId = serverSettings?.get?.("announcementChannelId"); if (savedAnnChId) { - ch = this.client?.channels?.get?.(String(savedAnnChId).replace(/\D/g, "")) ?? null; + ch = this.client?.channels?.get?.(cleanId(savedAnnChId)) ?? null; } } if (!ch || typeof ch.send !== "function") { @@ -764,12 +784,14 @@ export class Remix { if (!player.textChannel) player.textChannel = ch; - ch.send(typeof m === "object" && Array.isArray(m.embeds) ? m : mkEmbed(m)).catch(err => { + ch.send(typeof m === "object" && Array.isArray(m.embeds) ? m : { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(m)] }).catch(err => { if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) { logger.warn(`[_spawnPlayer] Cannot send announcement in channel ${ch.id} — missing permissions`); } }); - } catch (_) {} + } catch(e) { + + } }); if (this.players._pendingJoins) { @@ -798,34 +820,34 @@ export class Remix { this.players._pendingJoins.delete(cleanChannelId); } this.players.playerMap.delete(cleanChannelId); - try { player.destroy(); } catch (_) {} + try { player.destroy(); } catch(e) { } logger.warn(`[_spawnPlayer] Failed to spawn player for channel ${cleanChannelId}:`, err.message); throw err; } } async leaveChannel(channelId, guildId, message, force = false) { - const cleanId = String(channelId).replace(/\D/g, ""); - const cleanGuildId = String(guildId).replace(/\D/g, ""); + const cleanChId = cleanId(channelId); + const cleanGuildId = cleanId(guildId); const set = this.settingsMgr.getServer(cleanGuildId); const raw = set?.get("stay_247"); const channels = (!raw || raw === "none") ? new Set() : Array.isArray(raw) - ? new Set(raw.map(id => String(id).replace(/\D/g, "")).filter(Boolean)) - : new Set([String(raw).replace(/\D/g, "")]); + ? new Set(raw.map(id => cleanId(id)).filter(Boolean)) + : new Set([cleanId(raw)]); - const channelMode = channels.has(cleanId) ? get247ChannelMode(set, cleanId) : "off"; + const channelMode = channels.has(cleanChId) ? get247ChannelMode(set, cleanChId) : "off"; - if (channels.has(cleanId) && !force) { + if (channels.has(cleanChId) && !force) { if (channelMode === "auto") { if (message) { const prefix = this.handler.getPrefix(cleanGuildId); const guildIdForLocale = message?.channel?.channel?.guildId ?? message?.guildId ?? cleanGuildId; message.replyEmbed( this.locale.translate(guildIdForLocale, "responses.leave.autoRejoinHint", { - channel: cleanId, + channel: cleanChId, prefix }) ); @@ -834,20 +856,20 @@ export class Remix { } } - if (channels.has(cleanId)) { - channels.delete(cleanId); + if (channels.has(cleanChId)) { + channels.delete(cleanChId); set.set("stay_247", channels.size > 0 ? [...channels] : "none"); - remove247ChannelMode(set, cleanId, channels); + remove247ChannelMode(set, cleanChId, channels); } - this.markIntentionalLeave(cleanId); + this.markIntentionalLeave(cleanChId); - const player = this.players.playerMap.get(cleanId); + const player = this.players.playerMap.get(cleanChId); if (player) { - this.players.playerMap.delete(cleanId); - this.players._unindexPlayer(player._guildId, cleanId); - const pendingScrobble = this.players._pendingScrobbleTimers?.get(cleanId); - if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this.players._pendingScrobbleTimers.delete(cleanId); } + this.players.playerMap.delete(cleanChId); + this.players._unindexPlayer(player._guildId, cleanChId); + const pendingScrobble = this.players._pendingScrobbleTimers?.get(cleanChId); + if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this.players._pendingScrobbleTimers.delete(cleanChId); } await player.leave().catch(() => {}); player.destroy(); } @@ -907,7 +929,7 @@ export class Remix { } if (!isMember) { - const cleanGuildId = String(guild.id).replace(/\D/g, ""); + const cleanGuildId = cleanId(guild.id); const userLoc = this.voiceCache.getUserLocation(cleanGuildId, user.id); if (userLoc) isMember = true; } @@ -916,7 +938,7 @@ export class Remix { try { const member = await guild.members.fetch(user.id).catch(() => null); if (member) isMember = true; - } catch (_) { /* not a member or fetch failed */ } + } catch (_) { } } if (!isMember) continue; diff --git a/package.json b/package.json index 593a5ce..ed7d968 100644 --- a/package.json +++ b/package.json @@ -7,16 +7,13 @@ "@fluxerjs/core": "^1.3.1", "@fluxerjs/voice": "^1.3.1", "bcryptjs": "^3.0.3", - "express": "^5.2.1", "ffmpeg-static": "^5.3.0", "ffprobe-static": "^3.1.0", "follow-redirects": "^1.16.0", - "genius-lyrics": "^4.4.7", "moonlink.js": "^5.2.0", "mysql2": "^3.9.0", "redis": "^5.12.1", - "revoice.js": "^0.2.1696", - "ws": "^8.20.0" + "revoice.js": "^0.2.1696" }, "scripts": { "dev": "node --inspect index.mjs --trace-warnings", diff --git a/settings/Settings.mjs b/settings/Settings.mjs index b5c229e..b90d0a0 100644 --- a/settings/Settings.mjs +++ b/settings/Settings.mjs @@ -1,290 +1,10 @@ -import { EventEmitter } from "node:events"; -import { logger } from "../src/constants/Logger.mjs"; -import * as fs from "node:fs"; -import * as mysql from "mysql2"; +/** + * @file Settings.mjs — Dashboard Settings — server-side settings manager for the web dashboard + * @module settings.Settings + */ -export class ServerSettings { - /** @type {string} */ - id; - /** @type {SettingsManager} */ - manager; - data = {}; - - constructor(id, mgr) { - this.id = id; this.manager = mgr; - this.loadDefaults(); - } - set(key, value) { this.data[key] = value; this.manager.update(this, key); } - get(key) { return this.data[key]; } - reset(key) { return this.set(key, this.manager.defaults[key]); } - getAll() { return this.data; } - loadDefaults() { for (let key in this.manager.defaults) { this.data[key] = this.manager.defaults[key]; } } - checkDefaults(d) { for (let key in d) { if (this.data[key] === undefined) this.data[key] = d[key]; } } - deserialize(json) { for (let k in json) { if (k === "id") continue; this.data[k] = json[k]; } } - get serializationData() { return { ...this.data, id: this.id }; } - serialize() { return this.serializationData; } - serializeObject() { return this.serializationData; } -} - -export class SettingsManager extends EventEmitter { - /** @abstract @type {Object} */ - defaults; - /** @abstract */ - update(server, key) { } - /** @abstract @returns {ServerSettings} */ - getServer(id) { } - /** @abstract @returns {boolean} */ - hasServer(id) { } - /** @abstract @returns {boolean} */ - isOption(key) { } -} - -export class MySqlSettingsManager extends SettingsManager { - guilds = new Map(); - descriptions = {}; - defaults = {}; - db = null; - /** @type {string|null} Bot user ID — used to isolate rows per-bot in shared databases */ - botId = null; - /** @type {boolean} Whether the bot_id column exists in the settings table */ - _hasBotIdColumn = false; - /** @type {Promise|null} Tracks the in-flight load() so setBotId() can wait for it */ - _loadPromise = null; - _debounceTimers = new Map(); - - constructor(config, defaultsPath, botId = null) { - super(); - this.botId = botId; - this.db = mysql.createPool({ connectionLimit: 15, ...config }); - this.db.on("error", (err) => { - logger.error("[DB] MySQL pool error:", err.code ?? err.message); - }); - if (defaultsPath) this.loadDefaultsSync(defaultsPath); - this._loadPromise = this.load().catch(err => logger.error("[Settings] Initial load failed:", err?.message ?? err)); - } - - /** - * Check whether the `bot_id` column exists in the settings table AND is - * part of the primary key. If the column is missing, auto-migrate by - * adding it (NOT NULL DEFAULT '') and updating the primary key to (id, bot_id). - * If the column exists but isn't in the PK (previous failed migration), - * fix the NULL values and retry the PK update. - * - * Key detail: MySQL primary key columns CANNOT be NULL. The previous version - * used DEFAULT NULL which caused ALTER TABLE ... ADD PRIMARY KEY to fail - * silently, leaving the PK as just (id) and producing ER_DUP_ENTRY errors - * when two bots tried to INSERT rows for the same guild. - */ - async _ensureBotIdColumn() { - if (this._hasBotIdColumn) return; - - 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'` - ); - - if (res.error) { - logger.error("[Settings] Failed to check bot_id column:", res.error); - return; - } - - if (res.results.length === 0) { - logger.settings("[Settings] Auto-migrating: adding bot_id column to settings table..."); - - const alterRes = await this.query( - `ALTER TABLE settings ADD COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''` - ); - if (alterRes.error) { - logger.error("[Settings] Failed to add bot_id column:", alterRes.error); - return; - } - - if (this.botId) { - await this.query( - `UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE 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; - } - - this._hasBotIdColumn = true; - logger.settings("[Settings] Auto-migration complete: bot_id column added."); - return; - } - - const colInfo = res.results[0]; - const isNullable = colInfo.IS_NULLABLE === 'YES'; - const isPrimaryKey = colInfo.COLUMN_KEY === 'PRI'; - - if (isPrimaryKey) { - this._hasBotIdColumn = true; - return; - } - - logger.settings("[Settings] Fixing bot_id column: adding to primary key..."); - - 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 ''`); - } - - if (this.botId) { - await this.query( - `UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE 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; - } - - this._hasBotIdColumn = true; - logger.settings("[Settings] Fix complete: bot_id column added to primary key."); - } - - /** - * Set or update the bot ID used for database row isolation. - * Ensures the bot_id column exists (auto-migrates if needed), claims any - * unclaimed legacy rows, then reloads guild data filtered by the bot's ID. - * @param {string} id - */ - async setBotId(id) { - const changed = this.botId !== id; - this.botId = id; - if (changed) { - if (this._loadPromise) await this._loadPromise; - await this._ensureBotIdColumn(); - - if (this._hasBotIdColumn && this.botId) { - const claimRes = await this.query( - `UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''` - ); - if (claimRes.results?.affectedRows > 0) { - logger.settings(`[Settings] Claimed ${claimRes.results.affectedRows} legacy row(s) for bot ${this.botId}`); - } - } - - this.guilds.clear(); - this._loadPromise = this.load(); - await this._loadPromise; - } - } - - _botIdWhere() { - if (!this.botId || !this._hasBotIdColumn) return ""; - return ` AND bot_id = ${mysql.escape(String(this.botId))}`; - } - - _botIdInsert() { - if (!this.botId || !this._hasBotIdColumn) return { col: "", val: "" }; - return { col: ", bot_id", val: `, ${mysql.escape(String(this.botId))}` }; - } - - /** - * Fetch a single guild's settings row from the database, filtered by bot_id. - * @param {string} guildId - * @returns {Promise<{error: object|null, results: Array, fields: Array}>} - */ - selectGuild(guildId) { - const escapedId = mysql.escape(String(guildId)); - return this.query(`SELECT * FROM settings WHERE id=${escapedId}${this._botIdWhere()}`); - } - query(query) { - return new Promise(res => { - this.db.query(query, (error, results, fields) => { res({ error, results, fields }); }); - }); - } - async load() { - const res = await this.query(`SELECT * FROM settings WHERE 1=1${this._botIdWhere()}`); - if (res.error) { - this._loadAttempts = (this._loadAttempts || 0) + 1; - 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 new Promise((resolve) => { setTimeout(() => { this.load().then(resolve).catch(resolve); }, delay); }); - } - this._loadAttempts = 0; - res.results.forEach((r) => { - try { - const server = new ServerSettings(r.id, this); - const parsed = (typeof r.data === "string") ? JSON.parse(r.data) : r.data; - server.deserialize(parsed); - server.checkDefaults(this.defaults); - this.guilds.set(server.id, server); - } catch (e) { - logger.error("[Settings] Failed to parse settings for server", r.id, ":", e.message); - } - }); - this.emit("ready"); - } - async remoteUpdate(server, key) { - const val = server.data[key]; - if (Array.isArray(val) || (typeof val === "object" && val !== null)) { - return this.remoteSave(server); - } - const escapedKey = mysql.escape(`$.${key}`); - const escapedVal = (typeof val === "boolean" || typeof val === "number") - ? mysql.escape(val) - : mysql.escape(String(val)); - const escapedId = mysql.escape(server.id); - const r = await this.query( - `UPDATE settings SET data = JSON_SET(data, ${escapedKey}, ${escapedVal}) WHERE id=${escapedId}${this._botIdWhere()}` - ); - if (r.error) logger.error("[Settings] remoteUpdate error:", r.error); - } - async remoteSave(server) { - const escapedData = mysql.escape(JSON.stringify(server.data)); - const escapedId = mysql.escape(server.id); - const r = await this.query( - `UPDATE settings SET data = ${escapedData} WHERE id=${escapedId}${this._botIdWhere()}` - ); - if (r.error) logger.error("[Settings] remoteSave error:", r.error); - } - loadDefaultsSync(filePath) { - try { - const d = fs.readFileSync(filePath, "utf8"); - const parsed = JSON.parse(d); - this.descriptions = parsed.descriptions; - this.defaults = parsed.values; - } catch (e) { - logger.error("[Settings] Failed to load defaults from", filePath, ":", e.message); - this.descriptions = {}; - this.defaults = {}; - } - } - async saveAsync() { - await Promise.allSettled([...this.guilds.values()].map(v => this.remoteSave(v))); - } - async create(id, server) { - const escapedId = mysql.escape(id); - const escapedData = mysql.escape(JSON.stringify(server.data)); - const bi = this._botIdInsert(); - const r = await this.query( - `INSERT IGNORE INTO settings (id, data${bi.col}) VALUES (${escapedId}, ${escapedData}${bi.val})` - ); - if (r.error) logger.error("[Settings] create error:", r.error); - } - update(server, key) { - 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]; - const existing = this._debounceTimers.get(server.id); - if (existing) clearTimeout(existing); - this._debounceTimers.set(server.id, setTimeout(() => { - this._debounceTimers.delete(server.id); - this.remoteSave(s); - }, 80)); - } - isOption(key) { return key in this.defaults; } - hasServer(id) { return this.guilds.has(id); } - getServer(id) { return (!this.guilds.has(id)) ? new ServerSettings(id, this) : this.guilds.get(id); } -} +/** + * Re-exports from src/Settings.mjs for backward compatibility. + * The canonical definitions now live in src/Settings.mjs. + */ +export { SettingsManager, ServerSettings, RemoteSettingsManager } from "../src/Settings.mjs"; diff --git a/settings/migrate.mjs b/settings/migrate.mjs index ed8373c..ea3583c 100644 --- a/settings/migrate.mjs +++ b/settings/migrate.mjs @@ -1,4 +1,9 @@ -import { SettingsManager, RemoteSettingsManager } from "../src/Settings.mjs"; +/** + * @file migrate.mjs — Migration script — migrates settings and 24/7 channel data between Redis and SQLite backends + * @module settings.migrate + */ + +import { RemoteSettingsManager } from "../src/Settings.mjs"; import fs from "node:fs"; import { logger } from "../src/constants/Logger.mjs"; diff --git a/settings/runnables.mjs b/settings/runnables.mjs index 6f09bd1..bde7cbc 100644 --- a/settings/runnables.mjs +++ b/settings/runnables.mjs @@ -1,14 +1,44 @@ +/** + * @file runnables.mjs — Runnable validators — server-side validation functions for settings values (prefix, volume, 24/7 mode, etc.) + * @module settings.runnables + */ + export default { - prefix: function(value, data) { + /** + * Validate a prefix setting value. + * @param {string} value - The proposed prefix + * @param {object} _data - Additional context (reserved for future use) + * @returns {true|string} True if valid, error message string if invalid + */ + prefix(value, _data) { + if (!value || typeof value !== "string") return "Prefix must be a non-empty string."; + if (value.length > 10) return "Prefix must be 10 characters or fewer."; + if (/\s/.test(value)) return "Prefix must not contain whitespace."; + return true; }, - pfp: function(value, data) { + /** + * Validate a profile picture setting value. + * @param {string} value - The proposed pfp value + * @param {object} _data - Additional context (reserved for future use) + * @returns {true|string} True if valid, error message string if invalid + */ + pfp(value, _data) { if (value !== "default") { return "Profile picture customisation is not supported on Fluxer."; } + return true; }, - stay_247: function(value, data) { - return false; + /** + * Validate the 24/7 stay mode setting. + * @param {string|boolean} value - The proposed stay_247 value + * @param {object} _data - Additional context (reserved for future use) + * @returns {true|string} True if valid, error message string if invalid + */ + stay_247(value, _data) { + if (value === true || value === false || value === "true" || value === "false") return true; + if (typeof value === "string" && value.length > 0) return true; + return "Invalid value for 24/7 mode."; }, -}; \ No newline at end of file +}; diff --git a/src/CommandHandler.mjs b/src/CommandHandler.mjs index 825a5b2..309cb44 100644 --- a/src/CommandHandler.mjs +++ b/src/CommandHandler.mjs @@ -1,3 +1,8 @@ +/** + * @file CommandHandler.mjs — CommandHandler — registers, resolves, and dispatches slash and prefix commands with option parsing and requirements + * @module src.CommandHandler + */ + import { pathToFileURL } from "node:url"; import { logger } from "./constants/Logger.mjs"; import { Utils } from "./Utils.mjs"; @@ -8,6 +13,9 @@ import { SettingsManager } from "./Settings.mjs"; import path from "node:path"; import * as fs from "node:fs"; +/** + * CommandBuilder class. + */ export class CommandBuilder { constructor() { this.name = null; @@ -52,6 +60,9 @@ export class CommandBuilder { addExamples(...examples) { this.examples.push(...examples); return this; } } +/** + * CommandRequirement class. + */ export class CommandRequirement { ownerOnly = false; constructor() { @@ -69,6 +80,9 @@ export class CommandRequirement { setPermissionError(e) { this.permissionError = e; return this; } } +/** + * Option class. + */ export class Option { static THRESHOLD = 10; static COLS_PER_LINE = 5; @@ -231,6 +245,9 @@ export class Option { set typeError(e) { this.tError = e; } } +/** + * Flag class. + */ export class Flag extends Option { constructor(type = "string") { if (type === "text") throw new Error("Flags can't be of type 'text'!"); @@ -238,6 +255,9 @@ export class Flag extends Option { } } +/** + * PrefixManager class. + */ export class PrefixManager { /** @type {SettingsManager} */ settings; @@ -250,6 +270,9 @@ export class PrefixManager { } } +/** + * HelpHandler class. + */ export class HelpHandler { /** @type {CommandHandler} */ commands; @@ -386,6 +409,9 @@ export class HelpHandler { } } +/** + * CommandHandler class. + */ export class CommandHandler extends EventEmitter { onPing = null; pingPrefix = true; @@ -547,7 +573,7 @@ export class CommandHandler extends EventEmitter { 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 }); - } catch (__) { /* completely blocked */ } + } catch (__) { } } return; } @@ -775,6 +801,9 @@ export class CommandHandler extends EventEmitter { } } +/** + * CommandLoader class. + */ export class CommandLoader { /** @type {CommandHandler} */ commands; @@ -861,4 +890,4 @@ export class CommandLoader { }); })); } -} \ No newline at end of file +} diff --git a/src/FluxerListManager.mjs b/src/FluxerListManager.mjs index d757cdf..240830b 100644 --- a/src/FluxerListManager.mjs +++ b/src/FluxerListManager.mjs @@ -1,3 +1,8 @@ +/** + * @file FluxerListManager.mjs — FluxerListManager — FluxerList bot listing API client for vote checking and server stats + * @module src.FluxerListManager + */ + /** * FluxerListManager.mjs — FluxerList API client for voter data queries. * @@ -7,7 +12,7 @@ * - In-memory response caching with configurable TTL * - Graceful error handling (401/403 auth errors, network failures) * - * FluxerList API docs: https: + * FluxerList API docs: https://fluxerlist.com/api/v1 */ import { logger } from "./constants/Logger.mjs"; @@ -18,6 +23,9 @@ import { buildFluxerListUrl, } from "./constants/API.mjs"; +/** + * FluxerListManager class. + */ export class FluxerListManager { /** * @param {object} config - The `fluxerlist` section from config.json diff --git a/src/GatewayHandler.mjs b/src/GatewayHandler.mjs index aaef217..c93ec0f 100644 --- a/src/GatewayHandler.mjs +++ b/src/GatewayHandler.mjs @@ -1,3 +1,8 @@ +/** + * @file GatewayHandler.mjs — GatewayHandler — processes raw WebSocket events for voice state tracking, 24/7 recovery, and guild lifecycle + * @module src.GatewayHandler + */ + import { Events, GatewayOpcodes } from "@fluxerjs/core"; import { getVoiceManager } from "@fluxerjs/voice"; import { logger, _wsErrorCooldown } from "./constants/Logger.mjs"; @@ -5,6 +10,8 @@ import { ServerSettings } from "./Settings.mjs"; import { get247ChannelMode, remove247ChannelMode } from "./constants/Helpers247.mjs"; import { VoiceStateCache } from "./constants/VoiceStateCache.mjs"; import { REQUIRED_BOT_PERMISSIONS } from "./MessageHandler.mjs"; +import { cleanId } from "./Utils.mjs"; +import { iterateVoiceStates, hasHumansInChannel, getChannelsWithHumans } from "./constants/VoiceStateResolver.mjs"; /** * GatewayHandler — manages raw WebSocket gateway events, voice-state tracking, @@ -51,14 +58,14 @@ export class GatewayHandler { * Bots can be in multiple guilds so we namespace by guildId. */ getObservedVoiceBotKey(userId, guildId) { - const cleanUserId = String(userId ?? "").replace(/\D/g, ""); - const cleanGuildId = String(guildId ?? "").replace(/\D/g, ""); + const cleanUserId = cleanId(userId ?? ""); + const cleanGuildId = cleanId(guildId ?? ""); return cleanUserId && cleanGuildId ? `${cleanGuildId}:${cleanUserId}` : cleanUserId || null; } getPrevVoiceStateKey(userId, guildId) { - const cleanUserId = String(userId ?? "").replace(/\D/g, ""); - const cleanGuildId = String(guildId ?? "").replace(/\D/g, ""); + const cleanUserId = cleanId(userId ?? ""); + const cleanGuildId = cleanId(guildId ?? ""); return cleanUserId && cleanGuildId ? `${cleanGuildId}:${cleanUserId}` : null; } @@ -68,7 +75,7 @@ export class GatewayHandler { return { key: directKey, value: this._prevVoiceState.get(directKey) }; } - const cleanUserId = String(userId ?? "").replace(/\D/g, ""); + const cleanUserId = cleanId(userId ?? ""); if (!cleanUserId) return { key: null, value: null }; for (const [key, value] of this._prevVoiceState) { @@ -95,7 +102,7 @@ export class GatewayHandler { if (guild.members && !guild.members.me) { await guild.members.fetchMe(); } - } catch (_) { /* fetch failed — we'll still try */ } + } catch (_) { } const channels = guild.channels; if (!channels) return; @@ -138,7 +145,7 @@ export class GatewayHandler { logger.warn(`[GuildCreate] Cannot send permission warning to server ${guildId}: ${e.message}`); try { const t = this.remix.locale?.translate?.bind(this.remix.locale); - const guildIdStr = String(guildId).replace(/\D/g, ""); + const guildIdStr = cleanId(guildId); await targetChannel.send( t ? t(guildIdStr, "responses.gateway.missingPermsFallback", { perms: missingNames.join("**, **") }) : "⚠️ I'm missing permissions I need to work properly! Missing: **" + missingNames.join("**, **") + "**. Please ask a server administrator to grant these permissions in Server Settings → Roles." @@ -159,65 +166,46 @@ export class GatewayHandler { try { const vm = getVoiceManager(client); - if (vm?.voiceStates) { + if (vm?.voiceStates && vm.voiceStates.size > 0) { + let totalHumans = 0; + let totalBots = 0; for (const [guildId, userMap] of vm.voiceStates) { if (!userMap || typeof userMap.forEach !== "function") continue; - const cleanGuildId = String(guildId).replace(/\D/g, ""); + const cleanGuildId = cleanId(guildId); if (!cleanGuildId) continue; userMap.forEach((channelId, userId) => { if (!userId || !channelId) return; const botId = client.user?.id; if (userId === botId) { remix.voiceCache.updateUser({ guildId: cleanGuildId, userId, channelId, isBot: true }); + totalBots++; } else { const guild = client.guilds.get(cleanGuildId) ?? client.guilds.get(guildId); const member = guild?.members?.get?.(userId); const isBot = member?.user?.bot ?? false; - if (isBot) { - remix.voiceCache.updateUser({ guildId: cleanGuildId, userId, channelId, isBot: true }); - } else { - remix.voiceCache.updateUser({ guildId: cleanGuildId, userId, channelId, isBot: false }); - } + remix.voiceCache.updateUser({ guildId: cleanGuildId, userId, channelId, isBot }); + if (isBot) totalBots++; + else totalHumans++; } }); } logger.voiceState( `[Seed] Seeded from VoiceManager.voiceStates — ` + - `${remix.voiceCache.observedVoiceUsersSize} humans, ${remix.voiceCache.observedVoiceBotsSize} bots tracked.` + `${totalHumans} humans, ${totalBots} bots across ${vm.voiceStates.size} guilds. ` + + `Cache now: ${remix.voiceCache.observedVoiceUsersSize} humans, ${remix.voiceCache.observedVoiceBotsSize} bots.` ); return; } + logger.voiceState(`[Seed] VoiceManager.voiceStates is empty (${vm?.voiceStates?.size ?? "null"} guilds). ` + + `This is expected if no users were in voice when the bot started. ` + + `VoiceStatesSync handler will populate the cache as guilds become available.`); } catch (e) { logger.voiceState(`[Seed] VoiceManager seeding failed: ${e?.message} — falling back to guild cache.`); } for (const [gId, guild] of client.guilds) { - const voiceStatesRaw = - guild.voice_states ?? - guild.voiceStates ?? - null; - if (!voiceStatesRaw) continue; - - if (!Array.isArray(voiceStatesRaw) && typeof voiceStatesRaw === "object" - && typeof voiceStatesRaw.values !== "function") { - for (const [uid, val] of Object.entries(voiceStatesRaw)) { - const channelId = typeof val === "string" ? val - : val?.channelId ?? val?.channel_id ?? null; - if (!uid || !channelId) continue; - const isBot = val?.member?.user?.bot ?? false; - remix.voiceCache.updateUser({ guildId: gId, userId: uid, channelId, isBot }); - } - } else { - const entries = Array.isArray(voiceStatesRaw) - ? voiceStatesRaw - : [...voiceStatesRaw.values()]; - for (const state of entries) { - const userId = state?.userId ?? state?.user_id ?? state?.id; - const channelId = state?.channelId ?? state?.channel_id; - if (!userId || !channelId) continue; - const isBot = state?.member?.user?.bot ?? false; - remix.voiceCache.updateUser({ guildId: gId, userId, channelId, isBot }); - } + for (const vs of iterateVoiceStates(guild)) { + remix.voiceCache.updateUser({ guildId: gId, userId: vs.userId, channelId: vs.channelId, isBot: vs.isBot }); } } } @@ -241,8 +229,8 @@ export class GatewayHandler { const { remix } = this; const client = remix.client; - const cleanGuild = String(guildId).replace(/\D/g, ""); - const cleanChannel = String(channelId).replace(/\D/g, ""); + const cleanGuild = cleanId(guildId); + const cleanChannel = cleanId(channelId); if (!cleanGuild || !cleanChannel) return 0; let humansFound = 0; @@ -255,7 +243,7 @@ export class GatewayHandler { if (guildVoiceMap && typeof guildVoiceMap.forEach === "function") { guildVoiceMap.forEach((userChannelId, userId) => { if (!userId || !userChannelId) return; - const userChannel = String(userChannelId).replace(/\D/g, ""); + const userChannel = cleanId(userChannelId); if (userChannel !== cleanChannel) return; if (userId === botId) { remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: true }); @@ -297,60 +285,28 @@ export class GatewayHandler { `[Reseed] Guild ${cleanGuild} not in cache — cannot reseed voice states.` ); } else { - const voiceStatesRaw = - guild.voice_states ?? - guild.voiceStates ?? - null; - - if (voiceStatesRaw) { - if (!Array.isArray(voiceStatesRaw) && typeof voiceStatesRaw === "object" - && typeof voiceStatesRaw.values !== "function") { - for (const [uid, val] of Object.entries(voiceStatesRaw)) { - const stateChannel = typeof val === "string" ? val - : val?.channelId ?? val?.channel_id ?? null; - if (!uid || !stateChannel) continue; - const isBot = val?.member?.user?.bot ?? false; - if (isBot) continue; - if (String(stateChannel).replace(/\D/g, "") === cleanChannel) { - remix.voiceCache.updateUser({ guildId: cleanGuild, userId: uid, channelId: stateChannel, isBot: false }); - humansFound++; - logger.voiceState( - `[Reseed] Found human ${uid} in channel ${cleanChannel} (guild ${cleanGuild})` - ); - } - } - } else { - const entries = Array.isArray(voiceStatesRaw) - ? voiceStatesRaw - : [...voiceStatesRaw.values()]; - for (const state of entries) { - const userId = state?.userId ?? state?.user_id ?? state?.id; - const stateChannel = state?.channelId ?? state?.channel_id; - if (!userId || !stateChannel) continue; - const isBot = state?.member?.user?.bot ?? false; - if (isBot) continue; - if (String(stateChannel).replace(/\D/g, "") === cleanChannel) { - remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: stateChannel, isBot: false }); - humansFound++; - logger.voiceState( - `[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild})` - ); - } - } - } - - if (botId) { - remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true }); - } - - if (humansFound > 0) { + for (const vs of iterateVoiceStates(guild)) { + if (vs.isBot) continue; + if (vs.channelId === cleanChannel) { + remix.voiceCache.updateUser({ guildId: cleanGuild, userId: vs.userId, channelId: vs.channelId, isBot: false }); + humansFound++; logger.voiceState( - `[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` + - `found ${humansFound} human(s), observedVoiceUsers size now ${remix.voiceCache.observedVoiceUsersSize}` + `[Reseed] Found human ${vs.userId} in channel ${cleanChannel} (guild ${cleanGuild})` ); - return humansFound; } } + + if (botId) { + remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true }); + } + + if (humansFound > 0) { + logger.voiceState( + `[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` + + `found ${humansFound} human(s), observedVoiceUsers size now ${remix.voiceCache.observedVoiceUsersSize}` + ); + return humansFound; + } } if (humansFound === 0 && remix.voiceCache) { @@ -420,7 +376,7 @@ export class GatewayHandler { remix._rawGatewayWsObj.off("message", remix._rawGatewayMessageListener ?? remix._rawGatewayHandler); remix._rawGatewayWsObj.off("error", remix._rawGatewayErrorHandler); } - } catch (_) {} + } catch(e) { logger.warn("[Gateway] Failed to detach old WS listener:", e?.message); } } if (wsObj && wsObj !== remix._rawGatewayWsObj) { @@ -498,7 +454,7 @@ export class GatewayHandler { remix.voiceCache.updateUser({ guildId, userId, channelId: null, isBot }); } } - } catch (_) {} + } catch(e) { logger.warn("[Gateway] Raw gateway handler error:", e?.message); } }; remix._rawGatewayErrorHandler = (errOrEvent) => { @@ -523,7 +479,7 @@ export class GatewayHandler { this.wsListenerAttached = true; logger.player("[Gateway] Raw WS listener attached to new socket."); } - } catch (_) {} + } catch(e) { logger.warn("[Gateway] attachRawListener failed:", e?.message); } } setupPresenceRotation() { @@ -603,53 +559,21 @@ export class GatewayHandler { if (voiceStatesRaw) { const newUserIds = new Set(); - if (!Array.isArray(voiceStatesRaw) && typeof voiceStatesRaw === "object" - && typeof voiceStatesRaw.values !== "function") { - for (const uid of Object.keys(voiceStatesRaw)) { - newUserIds.add(uid); - } - } else { - const entries = Array.isArray(voiceStatesRaw) - ? voiceStatesRaw - : [...voiceStatesRaw.values()]; - for (const state of entries) { - const userId = state?.userId ?? state?.user_id ?? state?.id; - if (userId) newUserIds.add(userId); - } + for (const vs of iterateVoiceStates(guild)) { + newUserIds.add(vs.userId); } - remix.voiceCache.purgeUsersInGuild(guildId, newUserIds); } if (voiceStatesRaw) { - if (!Array.isArray(voiceStatesRaw) && typeof voiceStatesRaw === "object" - && typeof voiceStatesRaw.values !== "function") { - for (const [uid, val] of Object.entries(voiceStatesRaw)) { - const channelId = typeof val === "string" ? val - : val?.channelId ?? val?.channel_id ?? null; - if (!uid || !channelId) continue; - const isBot = val?.member?.user?.bot ?? false; - remix.voiceCache.updateUser({ guildId, userId: uid, channelId, isBot }); - } - } else { - const entries = Array.isArray(voiceStatesRaw) - ? voiceStatesRaw - : [...voiceStatesRaw.values()]; - - for (const state of entries) { - const channelId = state?.channelId ?? state?.channel_id; - const userId = state?.userId ?? state?.user_id ?? state?.id; - const sgid = state?.guildId ?? state?.guild_id ?? guildId; - const isBot = state?.member?.user?.bot ?? false; - if (!channelId || !userId) continue; - remix.voiceCache.updateUser({ guildId: sgid, userId, channelId, isBot }); - } + for (const vs of iterateVoiceStates(guild)) { + remix.voiceCache.updateUser({ guildId, userId: vs.userId, channelId: vs.channelId, isBot: vs.isBot }); } } if (!remix.settingsMgr.guilds.has(guildId)) { logger.guild(`[GuildCreate] (Re-)joined server ${guildId} — initialising settings.`); try { - const cleanGuildId = String(guildId).replace(/\D/g, ""); + const cleanGuildId = cleanId(guildId); if (!cleanGuildId) throw new Error("Invalid guildId: " + guildId); const res = await remix.settingsMgr.selectGuild(cleanGuildId); if (res?.results?.length) { @@ -672,7 +596,7 @@ export class GatewayHandler { } } - this._checkGuildPermissions(guild, guildId); + this._checkGuildPermissions(guild, guildId).catch(e => logger.warn("[GuildCreate] Permission check error for", guildId, e.message)); }); @@ -707,12 +631,16 @@ export class GatewayHandler { client.on(Events.VoiceStateUpdate, async (data) => { this._handleVoiceStateUpdate(data); }); + + client.on(Events.VoiceStatesSync, (data) => { + this._handleVoiceStatesSync(data); + }); } /** - * Internal handler for VoiceStateUpdate events. - * Separated for readability — covers human join/leave, bot move, and bot - * disconnect recovery. + * Main voice state update dispatcher — calls focused sub-handlers. + * Parses the raw VOICE_STATE_UPDATE payload, computes the old channel, + * then delegates to specialised methods. */ async _handleVoiceStateUpdate(data) { const { remix } = this; @@ -721,19 +649,106 @@ export class GatewayHandler { const userId = data?.user_id; if (!userId) return; - const channelId = data?.channel_id ?? null; - const guildId = data?.guild_id; - const isBot = data?.member?.user?.bot ?? null; + const newChannelId = data?.channel_id ?? null; + const vsuGuildId = data?.guild_id; + const isBot = data?.member?.user?.bot ?? null; - const prevEntry = this.findPrevVoiceStateEntry(userId, guildId); + + const prevEntry = this.findPrevVoiceStateEntry(userId, vsuGuildId); const prev = prevEntry.value; const prevSameGuild = prev && - String(prev.guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, ""); + cleanId(prev.guildId ?? "") === cleanId(vsuGuildId ?? ""); const oldChannelId = prevSameGuild ? (prev?.channelId ?? null) : null; - const prevKey = prevEntry.key; + + this._updatePreviousStates(userId, vsuGuildId, oldChannelId, newChannelId, isBot, prevEntry, prev); + this._updateVoiceStateCache(userId, vsuGuildId, oldChannelId, newChannelId, isBot, prev); + + + const { player, playerGuildId, homeChannelId } = this._findAffectedPlayer(vsuGuildId, oldChannelId, newChannelId); + + const isBotUser = isBot === true && userId === client.user?.id; + + if (!isBotUser) { + + this._handleInactivityOnVoiceChange(player, playerGuildId, homeChannelId, userId, oldChannelId, newChannelId, vsuGuildId, data); + return; + } + + + this._handleBotVoiceChange(player, playerGuildId, homeChannelId, oldChannelId, newChannelId, vsuGuildId, data); + } + + /** + * Handle bulk voice state sync from GUILD_CREATE or READY. + * Populates VoiceStateCache with all users currently in voice channels + * for a guild. This is the PRIMARY way the bot learns about users who + * were already in voice when the bot started (before it receives any + * individual VOICE_STATE_UPDATE events). + * + * @param {{ guildId: string, voiceStates: Array<{user_id: string, channel_id: string|null, member?: {user?: {bot?: boolean}}}> }} data + */ + _handleVoiceStatesSync(data) { + const { remix } = this; + const client = remix.client; + const guildId = data?.guildId; + if (!guildId || !Array.isArray(data?.voiceStates)) return; + + const botId = client.user?.id; + let humansAdded = 0; + let botsAdded = 0; + + for (const vs of data.voiceStates) { + const userId = vs.user_id; + const channelId = vs.channel_id; + if (!userId || !channelId) continue; + + const isBot = vs.member?.user?.bot ?? (userId === botId); + + remix.voiceCache.updateUser({ guildId, userId, channelId, isBot }); + if (isBot) { + botsAdded++; + } else { + humansAdded++; + } + } + + if (humansAdded > 0 || botsAdded > 0) { + logger.voiceState( + `[VoiceStatesSync] Guild ${guildId}: seeded ${humansAdded} humans, ${botsAdded} bots ` + + `(${data.voiceStates.length} total states).` + ); + } + } + + /** + * Update the voice state cache when users move between channels. + * Adds users to the cache on join, removes them on leave. + */ + _updateVoiceStateCache(userId, guildId, oldChannelId, newChannelId, isBot, prev) { + const { remix } = this; + + if (newChannelId) { + remix.voiceCache.updateUser({ guildId: guildId ?? prev?.guildId, userId, channelId: newChannelId, isBot: isBot === true }); + } else { + const resolvedGuildId = guildId ?? prev?.guildId; + if (resolvedGuildId) { + remix.voiceCache.deleteHumanUser(userId, resolvedGuildId); + remix.voiceCache.deleteBotUser(VoiceStateCache.userKey(resolvedGuildId, userId)); + } + } + } + + /** + * Update the previous state map (LRU eviction). + * Maintains a bounded map of previous voice states for computing oldChannelId. + */ + _updatePreviousStates(userId, guildId, oldChannelId, newChannelId, isBot, prevEntry, prev) { + const { remix } = this; + const prevKey = prevEntry.key; const nextKey = this.getPrevVoiceStateKey(userId, guildId ?? prev?.guildId); - if (channelId) { + + if (newChannelId) { if (prevKey && prevKey !== nextKey) { const prevGuildPart = prevKey.split(":")[0]; const nextGuildPart = nextKey.split(":")[0]; @@ -756,123 +771,156 @@ export class GatewayHandler { } } } - if (nextKey) this._prevVoiceState.set(nextKey, { channelId, guildId: guildId ?? prev?.guildId, isBot: isBot === true }); + if (nextKey) this._prevVoiceState.set(nextKey, { channelId: newChannelId, guildId: guildId ?? prev?.guildId, isBot: isBot === true }); } else { if (prevKey) this._prevVoiceState.delete(prevKey); } + } - if (channelId) { - remix.voiceCache.updateUser({ guildId: guildId ?? prev?.guildId, userId, channelId, isBot: isBot === true }); - } else { - const resolvedGuildId = guildId ?? prev?.guildId; - if (resolvedGuildId) { - remix.voiceCache.deleteHumanUser(userId, resolvedGuildId); - remix.voiceCache.deleteBotUser(VoiceStateCache.userKey(resolvedGuildId, userId)); + /** + * Find which player is affected by this voice state change. + * Checks both old and new channels for an existing player. + * + * @returns {{ player: object|null, playerGuildId: string|null, homeChannelId: string|null }} + */ + _findAffectedPlayer(guildId, oldChannelId, newChannelId) { + const { remix } = this; + + + if (oldChannelId) { + const cleanOld = cleanId(oldChannelId); + const player = remix.players.playerMap.get(cleanOld); + if (player) { + return { player, playerGuildId: player._guildId, homeChannelId: player._home247Channel }; } } - const isBotUser = isBot === true && userId === client.user?.id; - if (!isBotUser) { - const resolvedGuildId = guildId ?? prev?.guildId; - if (!resolvedGuildId) return; - - if (channelId) { - try { - const cleanId247 = String(channelId).replace(/\D/g, ""); - const player247 = remix.players.playerMap.get(cleanId247); - if (player247 && typeof player247._stopInactivityTimer === "function") { - logger.voiceState(`[VoiceState] Human joined 247 channel ${cleanId247}, stopping inactivity timer`); - player247._stopInactivityTimer(); - } - } catch (_) {} + if (newChannelId) { + const cleanNew = cleanId(newChannelId); + const player = remix.players.playerMap.get(cleanNew); + if (player) { + return { player, playerGuildId: player._guildId, homeChannelId: player._home247Channel }; } + } - if (oldChannelId && oldChannelId !== channelId) { - try { - const cleanOld = String(oldChannelId).replace(/\D/g, ""); - const player = remix.players.playerMap.get(cleanOld); - if (player && typeof player._startInactivityTimer === "function") { - setTimeout(() => { - if (!player._hasHumansInChannel()) { - logger.voiceState(`[VoiceState] Last human left ${cleanOld}, starting inactivity timer`); - player._startInactivityTimer(); - } - }, this.T.aloneCheckDebounce); - } - } catch (_) {} - } + return { player: null, playerGuildId: null, homeChannelId: null }; + } - if (channelId) { - try { - const cleanId = String(channelId).replace(/\D/g, ""); - const player = remix.players.playerMap.get(cleanId); - if (player && typeof player._stopInactivityTimer === "function") { - logger.voiceState(`[VoiceState] Human joined ${cleanId}, stopping inactivity timer`); - player._stopInactivityTimer(); - } - } catch (_) {} - } + /** + * Manage inactivity timers when humans join/leave voice channels. + * Also handles dashboard updates for human voice state changes. + */ + async _handleInactivityOnVoiceChange(player, playerGuildId, homeChannelId, userId, oldChannelId, newChannelId, vsuGuildId, vsu) { + const { remix } = this; + const client = remix.client; + const resolvedGuildId = vsuGuildId ?? playerGuildId; + if (!resolvedGuildId) return; - if (remix.dashboard?.enabled) { - try { - let userObj = data?.member?.user; - if (!userObj) { - try { userObj = await client.users.fetch(userId).catch(() => null); } catch (_) {} - } - if (userObj) { - const details = { - type: channelId ? "join" : "leave", - guildId: resolvedGuildId, - channelId: channelId ?? null, - oldChannelId: oldChannelId ?? null, - }; - remix.dashboard.updateUser(details, userObj); - } + if (newChannelId) { + try { + const cleanId247 = cleanId(newChannelId); + const player247 = remix.players.playerMap.get(cleanId247); + if (player247 && typeof player247._stopInactivityTimer === "function") { + logger.voiceState(`[VoiceState] Human joined 247 channel ${cleanId247}, stopping inactivity timer`); + player247._stopInactivityTimer(); + } + } catch(e) { logger.warn("[VoiceState] 247 inactivity timer stop failed:", e?.message); } + } - 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) { - const eventType = channelId ? "join" : "leave"; - remix.dashboard.updatePlayer({ - type: eventType, - data: userId, - }, player); - - remix.dashboard.playerUpdate({ - type: eventType, - }, player); + if (oldChannelId && oldChannelId !== newChannelId) { + try { + const cleanOld = cleanId(oldChannelId); + const oldPlayer = remix.players.playerMap.get(cleanOld); + if (oldPlayer && typeof oldPlayer._startInactivityTimer === "function") { + setTimeout(() => { + if (!oldPlayer._hasHumansInChannel()) { + logger.voiceState(`[VoiceState] Last human left ${cleanOld}, starting inactivity timer`); + oldPlayer._startInactivityTimer(); } - } - } catch (_) {} - } - - return; + }, this.T.aloneCheckDebounce); + } + } catch(e) { logger.warn("[VoiceState] Inactivity timer start failed:", e?.message); } } - const activeGuildPlayers = [...remix.players.playerMap.entries()].filter(([, player]) => - String(player?._guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, "") + if (newChannelId) { + try { + const cleanChId = cleanId(newChannelId); + const newPlayer = remix.players.playerMap.get(cleanChId); + if (newPlayer && typeof newPlayer._stopInactivityTimer === "function") { + logger.voiceState(`[VoiceState] Human joined ${cleanChId}, stopping inactivity timer`); + newPlayer._stopInactivityTimer(); + } + } catch(e) { logger.warn("[VoiceState] Inactivity timer stop failed:", e?.message); } + } + + if (remix.dashboard?.enabled) { + try { + let userObj = vsu?.member?.user; + if (!userObj) { + try { userObj = await client.users.fetch(userId).catch(() => null); } catch(e) { logger.warn("[VoiceState] Dashboard user fetch failed:", e?.message); } + } + if (userObj) { + const details = { + type: newChannelId ? "join" : "leave", + guildId: resolvedGuildId, + channelId: newChannelId ?? null, + oldChannelId: oldChannelId ?? null, + }; + remix.dashboard.updateUser(details, userObj); + } + + const refChannel = newChannelId ?? oldChannelId; + const cleanId_ref = refChannel ? cleanId(refChannel) : null; + + if (cleanId_ref) { + const dashPlayer = remix.players.playerMap.get(cleanId_ref); + if (dashPlayer) { + const eventType = newChannelId ? "join" : "leave"; + remix.dashboard.updatePlayer({ + type: eventType, + data: userId, + }, dashPlayer); + + remix.dashboard.playerUpdate({ + type: eventType, + }, dashPlayer); + } + } + } catch(e) { logger.warn("[VoiceState] Dashboard update failed:", e?.message); } + } + } + + /** + * Handle the bot being moved to a different channel or disconnected. + * Covers 24/7 re-key on move and auto-rejoin / autoleave on disconnect. + */ + _handleBotVoiceChange(player, playerGuildId, homeChannelId, oldChannelId, newChannelId, vsuGuildId, vsu) { + const { remix } = this; + const client = remix.client; + const guildId = vsuGuildId; + + const activeGuildPlayers = [...remix.players.playerMap.entries()].filter(([, p]) => + cleanId(p?._guildId ?? "") === cleanId(guildId ?? "") ); const multiVoiceGuild = activeGuildPlayers.length > 1; - if (channelId && guildId && oldChannelId && oldChannelId !== channelId) { + + if (newChannelId && guildId && oldChannelId && oldChannelId !== newChannelId) { try { - const cleanId = String(channelId).replace(/\D/g, ""); - const cleanOld = String(oldChannelId).replace(/\D/g, ""); + const cleanNew = cleanId(newChannelId); + const cleanOld = cleanId(oldChannelId); const moveSet = remix.settingsMgr.getServer(guildId); const moveRaw = moveSet?.get("stay_247"); const saved247Channels = (!moveRaw || moveRaw === "none") ? [] : Array.isArray(moveRaw) - ? moveRaw.map(id => String(id).replace(/\D/g, "")).filter(id => id.length >= 15) - : [String(moveRaw).replace(/\D/g, "")].filter(id => id.length >= 15); + ? moveRaw.map(id => cleanId(id)).filter(id => id.length >= 15) + : [cleanId(moveRaw)].filter(id => id.length >= 15); if (saved247Channels.length > 1) { logger.voice247( - `[247] Ignoring move-style bot voice update ${cleanOld} → ${cleanId} ` + + `[247] Ignoring move-style bot voice update ${cleanOld} → ${cleanNew} ` + `because guild ${guildId} already has multiple saved 24/7 channels ` + `[${saved247Channels.join(", ")}]` ); @@ -886,93 +934,93 @@ export class GatewayHandler { const raw = set?.get("stay_247"); if (!raw || raw === "none") return false; const saved = Array.isArray(raw) - ? raw.map(id => String(id).replace(/\D/g, "")).filter(id => id.length >= 15) - : [String(raw).replace(/\D/g, "")].filter(id => id.length >= 15); - return saved.includes(cleanId); + ? raw.map(id => cleanId(id)).filter(id => id.length >= 15) + : [cleanId(raw)].filter(id => id.length >= 15); + return saved.includes(cleanNew); } catch (_) { return false; } })(); const newChannelPendingSpawn = - remix.players?._pendingJoins?.has?.(cleanId) || + remix.players?._pendingJoins?.has?.(cleanNew) || false; - const targetChannel = client.channels.get(cleanId) - ?? client.channels.get?.(cleanId) + const targetChannel = client.channels.get(cleanNew) + ?? client.channels.get?.(cleanNew) ?? null; - const targetGuildId = String(targetChannel?.guildId ?? targetChannel?.guild?.id ?? guildId ?? "").replace(/\D/g, ""); - const playerGuildId = String(existingPlayer?._guildId ?? "").replace(/\D/g, ""); - const guildPlayers = [...remix.players.playerMap.entries()].filter(([, player]) => - String(player?._guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, "") + const targetGuildId = cleanId(targetChannel?.guildId ?? targetChannel?.guild?.id ?? guildId ?? ""); + const playerGuildIdLocal = cleanId(existingPlayer?._guildId ?? ""); + const guildPlayers = [...remix.players.playerMap.entries()].filter(([, p]) => + cleanId(p?._guildId ?? "") === cleanId(guildId ?? "") ); const guildIsAmbiguous = guildPlayers.length > 1; let rekeyed = false; - if (existingPlayer && cleanId !== cleanOld) { + if (existingPlayer && cleanNew !== cleanOld) { if (newChannelAlreadySaved || newChannelPendingSpawn) { logger.voice247( - `[247] Keeping both channels ${cleanOld} and ${cleanId} ` + + `[247] Keeping both channels ${cleanOld} and ${cleanNew} ` + `(saved=${newChannelAlreadySaved} pending=${newChannelPendingSpawn})` ); rekeyed = false; } else if (guildIsAmbiguous) { - const playerAtNewKey = remix.players.playerMap.get(cleanId); + const playerAtNewKey = remix.players.playerMap.get(cleanNew); if (playerAtNewKey && playerAtNewKey !== existingPlayer) { - existingPlayer._channelId = cleanId; - existingPlayer._home247Channel = cleanId; + existingPlayer._channelId = cleanNew; + existingPlayer._home247Channel = cleanNew; if (targetGuildId) existingPlayer._guildId = targetGuildId; rekeyed = false; logger.voice247( - `[247] Updated player channel ${cleanOld} → ${cleanId} ` + + `[247] Updated player channel ${cleanOld} → ${cleanNew} ` + `(guild ${guildId} has ${guildPlayers.length} active players, ` + `new key occupied by another player — skipped re-key)` ); } else { remix.players.playerMap.delete(cleanOld); - remix.players.playerMap.set(cleanId, existingPlayer); - existingPlayer._channelId = cleanId; - existingPlayer._home247Channel = cleanId; + remix.players.playerMap.set(cleanNew, existingPlayer); + existingPlayer._channelId = cleanNew; + existingPlayer._home247Channel = cleanNew; if (targetGuildId) existingPlayer._guildId = targetGuildId; rekeyed = true; logger.voice247( - `[247] Re-keyed playerMap ${cleanOld} → ${cleanId} ` + + `[247] Re-keyed playerMap ${cleanOld} → ${cleanNew} ` + `(guild ${guildId} has ${guildPlayers.length} active players)` ); } - } else if (playerGuildId && targetGuildId && playerGuildId !== targetGuildId) { + } else if (playerGuildIdLocal && targetGuildId && playerGuildIdLocal !== targetGuildId) { if (!existingPlayer) { logger.voice247( - `[247] Stale cross-guild move ${cleanOld} → ${cleanId} ` + + `[247] Stale cross-guild move ${cleanOld} → ${cleanNew} ` + `(no player in playerMap for old channel — updating bot state only)` ); } else { - const vsuGuildId = String(guildId ?? "").replace(/\D/g, ""); - if (vsuGuildId && targetGuildId === vsuGuildId) { + const vsuGuildIdClean = cleanId(guildId ?? ""); + if (vsuGuildIdClean && targetGuildId === vsuGuildIdClean) { existingPlayer._guildId = targetGuildId; - existingPlayer._channelId = cleanId; - existingPlayer._home247Channel = cleanId; + existingPlayer._channelId = cleanNew; + existingPlayer._home247Channel = cleanNew; remix.players.playerMap.delete(cleanOld); - remix.players.playerMap.set(cleanId, existingPlayer); + remix.players.playerMap.set(cleanNew, existingPlayer); rekeyed = true; logger.voice247( - `[247] Fixed stale guild during recovery: re-keyed ${cleanOld} → ${cleanId} ` + - `(playerGuild ${playerGuildId} → ${targetGuildId})` + `[247] Fixed stale guild during recovery: re-keyed ${cleanOld} → ${cleanNew} ` + + `(playerGuild ${playerGuildIdLocal} → ${targetGuildId})` ); } else { logger.warn( - `[247] Refused cross-guild re-key ${cleanOld} → ${cleanId} ` + - `(playerGuild=${playerGuildId} targetGuild=${targetGuildId})` + `[247] Refused cross-guild re-key ${cleanOld} → ${cleanNew} ` + + `(playerGuild=${playerGuildIdLocal} targetGuild=${targetGuildId})` ); } } } else { remix.players.playerMap.delete(cleanOld); - remix.players.playerMap.set(cleanId, existingPlayer); - existingPlayer._channelId = cleanId; - existingPlayer._home247Channel = cleanId; + remix.players.playerMap.set(cleanNew, existingPlayer); + existingPlayer._channelId = cleanNew; + existingPlayer._home247Channel = cleanNew; if (targetGuildId) existingPlayer._guildId = targetGuildId; rekeyed = true; - logger.voice247(`[247] Re-keyed playerMap ${cleanOld} → ${cleanId}`); + logger.voice247(`[247] Re-keyed playerMap ${cleanOld} → ${cleanNew}`); } } @@ -980,50 +1028,50 @@ export class GatewayHandler { const raw = set?.get("stay_247"); if ((rekeyed || existingPlayer) && raw && raw !== "none") { const channels = Array.isArray(raw) - ? new Set(raw.map(id => String(id).replace(/\D/g, "")).filter(id => id.length >= 15)) + ? new Set(raw.map(id => cleanId(id)).filter(id => id.length >= 15)) : new Set(); - if (channels.has(cleanOld) && cleanOld !== cleanId && cleanId.length >= 15) { - if (channels.has(cleanId) || newChannelAlreadySaved || newChannelPendingSpawn) { + if (channels.has(cleanOld) && cleanOld !== cleanNew && cleanNew.length >= 15) { + if (channels.has(cleanNew) || newChannelAlreadySaved || newChannelPendingSpawn) { logger.voice247( - `[247] Preserved stay_247 channels ${cleanOld} and ${cleanId} ` + - `(saved=${channels.has(cleanId) || newChannelAlreadySaved} pending=${newChannelPendingSpawn})` + `[247] Preserved stay_247 channels ${cleanOld} and ${cleanNew} ` + + `(saved=${channels.has(cleanNew) || newChannelAlreadySaved} pending=${newChannelPendingSpawn})` ); return; } const currentGuildPlayers = [...remix.players.playerMap.values()].filter(p => - String(p?._guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, "") + cleanId(p?._guildId ?? "") === cleanId(guildId ?? "") ); if (currentGuildPlayers.length > 1) { - if (!channels.has(cleanId)) { - channels.add(cleanId); + if (!channels.has(cleanNew)) { + channels.add(cleanNew); set.set("stay_247", [...channels]); const modes2 = set.get("stay_247_modes"); - if (modes2 && typeof modes2 === "object" && !Array.isArray(modes2) && !modes2[cleanId]) { - modes2[cleanId] = modes2[cleanOld] ?? "auto"; + if (modes2 && typeof modes2 === "object" && !Array.isArray(modes2) && !modes2[cleanNew]) { + modes2[cleanNew] = modes2[cleanOld] ?? "auto"; set.set("stay_247_modes", modes2); } logger.voice247( - `[247] Added stay_247 channel ${cleanId} (kept ${cleanOld}) — guild has ${currentGuildPlayers.length} active players` + `[247] Added stay_247 channel ${cleanNew} (kept ${cleanOld}) — guild has ${currentGuildPlayers.length} active players` ); } return; } channels.delete(cleanOld); - channels.add(cleanId); + channels.add(cleanNew); set.set("stay_247", [...channels]); const modes = set.get("stay_247_modes"); if (modes && typeof modes === "object" && !Array.isArray(modes)) { - if (modes[cleanOld] && !modes[cleanId]) { - modes[cleanId] = modes[cleanOld]; + if (modes[cleanOld] && !modes[cleanNew]) { + modes[cleanNew] = modes[cleanOld]; } delete modes[cleanOld]; set.set("stay_247_modes", modes); } - logger.voice247(`[247] Updated stay_247: ${cleanOld} → ${cleanId}`); + logger.voice247(`[247] Updated stay_247: ${cleanOld} → ${cleanNew}`); } } } catch (e) { @@ -1031,10 +1079,11 @@ export class GatewayHandler { } } - if (!channelId && oldChannelId && guildId) { + + if (!newChannelId && oldChannelId && guildId) { try { - const cleanOld = String(oldChannelId).replace(/\D/g, ""); - const cleanGuild = String(guildId).replace(/\D/g, ""); + const cleanOld = cleanId(oldChannelId); + const cleanGuild = cleanId(guildId); if (this._inStartupGrace) { const bootPlayer = remix.players.playerMap.get(cleanOld); @@ -1064,14 +1113,14 @@ export class GatewayHandler { logger.voice247( `[VoiceState] Bot unexpectedly disconnected from ${cleanOld} (24/7 auto) — cleaning up and scheduling rejoin.` ); - const player = remix.players.playerMap.get(cleanOld); - if (player && !player._destroyed) { + const discPlayer = remix.players.playerMap.get(cleanOld); + if (discPlayer && !discPlayer._destroyed) { remix.players.playerMap.delete(cleanOld); - const homeChannel = String(player._home247Channel ?? "").replace(/\D/g, ""); + const homeChannel = cleanId(discPlayer._home247Channel ?? ""); if (homeChannel && homeChannel !== cleanOld) { remix.players.playerMap.delete(homeChannel); } - try { player.destroy(); } catch (_) {} + try { discPlayer.destroy(); } catch(e) { logger.warn("[VoiceState] Player destroy failed:", e?.message); } const pendingScrobble = remix.players._pendingScrobbleTimers?.get(cleanOld); if (pendingScrobble) { clearTimeout(pendingScrobble.timer); @@ -1085,12 +1134,12 @@ export class GatewayHandler { }); }, rejoinDelay); } else { - const player = remix.players.playerMap.get(cleanOld); - if (player && !player.leaving && !player._destroyed) { + const leavePlayer = remix.players.playerMap.get(cleanOld); + if (leavePlayer && !leavePlayer.leaving && !leavePlayer._destroyed) { logger.voiceState( `[VoiceState] Bot disconnected from ${cleanOld} (24/7 mode: ${mode}) — emitting autoleave.` ); - player.emit("autoleave"); + leavePlayer.emit("autoleave"); } } } @@ -1109,22 +1158,69 @@ export class GatewayHandler { /** @type {number} Maximum number of rejoin retry attempts */ static MAX_REJOIN_RETRIES = 3; + /** + * Shared rejoin attempt logic with exponential backoff retry. + * Used by both _rejoinChannel (disconnect recovery) and + * rejoin247Channels (boot recovery). + * + * @param {string} channelId - Clean channel ID + * @param {string} guildId - Clean guild ID + * @param {number} [maxRetries=3] Maximum retry attempts + * @param {number} [baseDelay=5000] Base delay for exponential backoff (ms) + * @param {string} [context="Rejoin"] Log context prefix + * @returns {Promise} The spawned player, or null on failure + */ + async _attemptRejoin(channelId, guildId, maxRetries = 3, baseDelay = 5_000, context = "Rejoin") { + for (let attempt = 1; attempt <= maxRetries; attempt++) { + try { + const player = await this.remix._spawnPlayer(guildId, channelId); + this.reseedVoiceStatesForChannel(guildId, channelId); + logger.voice247( + `[${context}] Successfully rejoined channel ${channelId}` + + (attempt > 1 ? ` (after ${attempt - 1} retry/retries)` : '') + ); + return player; + } catch (err) { + const errMsg = err?.message ?? String(err); + const isTrackTimeout = errMsg.includes("track publication timed out") + || errMsg.includes("publishToRoom failed") + || errMsg.includes("Failed to create MediaPlayer") + || errMsg.includes("internal error"); + + if (isTrackTimeout && attempt < maxRetries) { + const backoffMs = baseDelay * Math.pow(2, attempt - 1); + logger.warn( + `[${context}] Track publication failed for channel ${channelId} (attempt ${attempt}/${maxRetries}) — ` + + `retrying in ${backoffMs / 1000}s: ${errMsg}` + ); + await new Promise(resolve => setTimeout(resolve, backoffMs)); + continue; + } + + logger.warn( + `[${context}] Failed to rejoin channel ${channelId} (attempt ${attempt}/${maxRetries}): ${errMsg}` + + (attempt > 1 ? ` (after ${attempt} attempts)` : '') + ); + return null; + } + } + return null; + } + /** * Rejoin a voice channel after an unexpected disconnect. * Used by the %247 auto mode to automatically reconnect. * * Includes deduplication (prevents concurrent rejoin for the same channel) - * and retry with exponential backoff for transient failures like track - * publication timeouts. + * and delegates retry logic to _attemptRejoin. * * @param {string} guildId * @param {string} channelId - * @param {number} [attempt=1] Current attempt number (for retry logic) */ - async _rejoinChannel(guildId, channelId, attempt = 1) { + async _rejoinChannel(guildId, channelId) { const { remix } = this; - const cleanGuildId = String(guildId).replace(/\D/g, ""); - const cleanChannelId = String(channelId).replace(/\D/g, ""); + const cleanGuildId = cleanId(guildId); + const cleanChannelId = cleanId(channelId); if (this._rejoinInProgress.has(cleanChannelId)) { logger.voice247(`[Rejoin] Channel ${cleanChannelId} rejoin already in progress — skipping.`); @@ -1160,40 +1256,17 @@ export class GatewayHandler { const maxRetries = GatewayHandler.MAX_REJOIN_RETRIES; logger.voice247( - `[Rejoin] Attempting to rejoin channel ${cleanChannelId} in guild ${cleanGuildId} (attempt ${attempt}/${maxRetries})...` + `[Rejoin] Attempting to rejoin channel ${cleanChannelId} in guild ${cleanGuildId}...` ); try { - const player = await remix._spawnPlayer(cleanGuildId, cleanChannelId); - logger.voice247(`[Rejoin] Successfully rejoined channel ${cleanChannelId}`); - this._rejoinAttempts.delete(cleanChannelId); - - this.reseedVoiceStatesForChannel(cleanGuildId, cleanChannelId); - - return player; - } catch (err) { - const errMsg = err?.message ?? String(err); - const isTrackTimeout = errMsg.includes("track publication timed out") - || errMsg.includes("publishToRoom failed") - || errMsg.includes("Failed to create MediaPlayer"); - - if (isTrackTimeout && attempt < maxRetries) { - const backoffMs = 5_000 * Math.pow(2, attempt - 1); - logger.voice247( - `[Rejoin] Track publication failed for channel ${cleanChannelId} (attempt ${attempt}/${maxRetries}) — ` + - `retrying in ${backoffMs / 1000}s: ${errMsg}` - ); - - await new Promise(resolve => setTimeout(resolve, backoffMs)); - - return this._rejoinChannel(cleanGuildId, cleanChannelId, attempt + 1); + const player = await this._attemptRejoin(cleanChannelId, cleanGuildId, maxRetries, 5_000, "Rejoin"); + if (player) { + this._rejoinAttempts.delete(cleanChannelId); + } else { + this._rejoinAttempts.delete(cleanChannelId); } - - logger.warn( - `[Rejoin] Failed to rejoin channel ${cleanChannelId} (attempt ${attempt}/${maxRetries}): ${errMsg}` - ); - this._rejoinAttempts.delete(cleanChannelId); - + return player; } finally { this._rejoinInProgress.delete(cleanChannelId); } @@ -1296,14 +1369,14 @@ export class GatewayHandler { return this._GuildClass; } } - } catch (_) {} + } catch(e) { logger.warn("[Gateway] _getGuildClass failed:", e?.message); } this._GuildClass = null; return null; } onReady() { this.seedVoiceStatesFromGuilds(); - this.seedGuildsFromRest(); + this.seedGuildsFromRest().catch(e => logger.warn("[onReady] seedGuildsFromRest error:", e.message)); this.attachRawListener(); this.setupPresenceRotation(); @@ -1349,7 +1422,7 @@ export class GatewayHandler { const rawArr = Array.isArray(raw) ? raw : [raw]; const channels = rawArr - .map(id => String(id).replace(/\D/g, "")) + .map(id => cleanId(id)) .filter(id => id.length >= 15 && id.length <= 22); for (const channelId of channels) { @@ -1404,8 +1477,8 @@ export class GatewayHandler { if (set) { const raw = set.get("stay_247"); const arr = Array.isArray(raw) ? raw : raw ? [raw] : []; - const filtered = arr.filter(id => id && id !== "none" && String(id).replace(/\D/g, "") !== channelId); - const remainingSet = new Set(filtered.map(id => String(id).replace(/\D/g, ""))); + const filtered = arr.filter(id => id && id !== "none" && cleanId(id) !== channelId); + const remainingSet = new Set(filtered.map(id => cleanId(id))); remove247ChannelMode(set, channelId, remainingSet); set.set("stay_247", filtered.length > 0 ? filtered : "none"); } @@ -1422,7 +1495,7 @@ export class GatewayHandler { } const guildHasActivePlayer = [...remix.players.playerMap.values()] - .some(p => !p._destroyed && String(p._guildId ?? "").replace(/\D/g, "") === guildId); + .some(p => !p._destroyed && cleanId(p._guildId ?? "") === guildId); if (guildHasActivePlayer && i > 0) { const extraDelay = 3_000; logger.voice247( @@ -1436,69 +1509,34 @@ export class GatewayHandler { `[BootRecovery] Rejoining channel ${channelId} in guild ${guildId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]` ); - const BOOT_MAX_RETRIES = 3; - const BOOT_BASE_RETRY_MS = 5_000; - let bootRetries = 0; + const player = await this._attemptRejoin(channelId, guildId, 3, 5_000, "BootRecovery"); + + if (player) { + logger.voice247( + `[BootRecovery] Successfully rejoined channel ${channelId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]` + ); + } else { - while (bootRetries < BOOT_MAX_RETRIES) { try { - const player = await remix._spawnPlayer(guildId, channelId); - - this.reseedVoiceStatesForChannel(guildId, channelId); - - logger.voice247( - `[BootRecovery] Successfully rejoined channel ${channelId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]` + - (bootRetries > 0 ? ` (after ${bootRetries} retry/retries)` : '') - ); - break; - } catch (err) { - bootRetries++; - const errMsg = err?.message ?? String(err); - const isTrackTimeout = errMsg.includes("track publication timed out") - || errMsg.includes("publishToRoom failed") - || errMsg.includes("Failed to create MediaPlayer") - || errMsg.includes("internal error"); - - if (isTrackTimeout && bootRetries < BOOT_MAX_RETRIES) { - const backoffMs = BOOT_BASE_RETRY_MS * Math.pow(2, bootRetries - 1); + const set = remix.settingsMgr.getServer(guildId); + if (set) { + const raw = set.get("stay_247"); + const channels = new Set( + (Array.isArray(raw) ? raw : [raw]) + .filter(id => id && id !== "none" && cleanId(id) !== channelId) + ); + set.set("stay_247", channels.size > 0 ? [...channels] : "none"); + remove247ChannelMode(set, channelId, channels); logger.warn( - `[BootRecovery] Track publication failed for channel ${channelId} (attempt ${bootRetries}/${BOOT_MAX_RETRIES}) — ` + - `retrying in ${backoffMs / 1000}s: ${errMsg}` + `[BootRecovery] Auto-removed channel ${channelId} from 24/7 ` + + `in guild ${guildId} after persistent track publication failure` ); - await new Promise(resolve => setTimeout(resolve, backoffMs)); - continue; } - - logger.warn( - `[BootRecovery] Failed to rejoin channel ${channelId} (mode: ${mode}): ${errMsg}` + - (bootRetries > 1 ? ` (after ${bootRetries} attempts)` : '') + } catch (cleanupErr) { + logger.error( + `[BootRecovery] Failed to auto-remove channel ${channelId} from 24/7:`, + cleanupErr?.message ?? cleanupErr ); - - if (isTrackTimeout && bootRetries >= BOOT_MAX_RETRIES) { - try { - const set = remix.settingsMgr.getServer(guildId); - if (set) { - const raw = set.get("stay_247"); - const channels = new Set( - (Array.isArray(raw) ? raw : [raw]) - .filter(id => id && id !== "none" && String(id).replace(/\D/g, "") !== channelId) - ); - set.set("stay_247", channels.size > 0 ? [...channels] : "none"); - remove247ChannelMode(set, channelId, channels); - logger.warn( - `[BootRecovery] Auto-removed channel ${channelId} from 24/7 ` + - `in guild ${guildId} after persistent track publication failure` - ); - } - } catch (cleanupErr) { - logger.error( - `[BootRecovery] Failed to auto-remove channel ${channelId} from 24/7:`, - cleanupErr?.message ?? cleanupErr - ); - } - } - - break; } } } @@ -1516,7 +1554,7 @@ export class GatewayHandler { */ _processGuildDelete(guildId) { const { remix } = this; - const cleanGuildId = String(guildId).replace(/\D/g, ""); + const cleanGuildId = cleanId(guildId); logger.guild( `[GuildDelete] Received GuildDelete for server ${guildId} — ` + @@ -1527,7 +1565,7 @@ export class GatewayHandler { remix.voiceCache.removeGuild(cleanGuildId); for (const [stateKey, info] of [...this._prevVoiceState]) { - if (String(info.guildId).replace(/\D/g, "") === cleanGuildId) + if (cleanId(info.guildId) === cleanGuildId) this._prevVoiceState.delete(stateKey); } remix._announcementChannelCache?.delete(guildId); diff --git a/src/LastFmManager.mjs b/src/LastFmManager.mjs index df75b5d..517e0f3 100644 --- a/src/LastFmManager.mjs +++ b/src/LastFmManager.mjs @@ -1,3 +1,8 @@ +/** + * @file LastFmManager.mjs — LastFmManager — Last.fm API integration for scrobbling, now-playing, loved tracks, top tracks, and track recommendations + * @module src.LastFmManager + */ + /** * LastFmManager.mjs — Last.fm API client for scrobbling, auth, and user data. * @@ -8,26 +13,22 @@ * - 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: + * Last.fm API docs: https://www.last.fm/api */ import crypto from "node:crypto"; import { logger } from "./constants/Logger.mjs"; +import { Utils } from "./Utils.mjs"; const BASE_URL = "https://ws.audioscrobbler.com/2.0/"; function normalizeTrackText(value) { - return String(value ?? "") - .normalize("NFKD") - .replace(/[^\w\s]+/g, " ") - .replace(/\s+/g, " ") - .trim() - .toLowerCase(); + return Utils.normalizeText(value); } /** * Build the API signature required by Last.fm for authenticated calls. - * See: https: + * See: https://www.last.fm/api/authentication */ function buildSignature(params, apiSecret) { const sorted = Object.keys(params).sort(); @@ -70,6 +71,9 @@ async function apiCall(params, apiSecret, post = false) { return data; } +/** + * LastFmManager class. + */ export class LastFmManager { /** * @param {object} config - The `lastfm` section from config.json @@ -1261,10 +1265,10 @@ export class LastFmManager { /** * Parse a Last.fm music URL and extract artist and track info. * Supports: - * https: - * https: - * https: - * https: + * https://www.last.fm/music/Artist + * https://www.last.fm/music/Artist/Track + * https://www.last.fm/music/Artist/Album/Track + * https://www.last.fm/music/Artist/_/Track * * @param {string} url * @returns {{ artist: string, track: string|null, album: string|null, url: string } | null} diff --git a/src/MessageHandler.mjs b/src/MessageHandler.mjs index cdcabdc..509defa 100644 --- a/src/MessageHandler.mjs +++ b/src/MessageHandler.mjs @@ -1,3 +1,8 @@ +/** + * @file MessageHandler.mjs — MessageHandler — wraps Fluxer messages with reply helpers, embed builders, permission checks, and voice state utilities + * @module src.MessageHandler + */ + import { Client, Events, EmbedBuilder, PermissionFlags } from "@fluxerjs/core"; import { logger } from "./constants/Logger.mjs"; import { Utils } from "./Utils.mjs"; @@ -38,9 +43,44 @@ export function parseColor(value, fallback = 0xe9196c) { /** Global embed color — set once at startup from config */ let _globalColor = 0xe9196c; +/** + * setGlobalColor function. + * @param {{*}} value + * @returns {*} + */ export function setGlobalColor(value) { _globalColor = parseColor(value); } +/** + * getGlobalColor function. + * @returns {*} + */ export function getGlobalColor() { return _globalColor; } +/** + * Strip non-digit characters from a value, returning a clean ID string. + * Re-exported from Utils.mjs for backward compatibility. + */ +export { cleanId } from "./Utils.mjs"; + +/** + * Resolve a guild ID from various message-like shapes. + * @param {object} message + * @returns {string|null} + */ +export function getMessageGuildId(message) { + return message?.channel?.guildId ?? + message?.channel?.guild?.id ?? + message?.message?.guildId ?? + message?.message?.guild?.id ?? + message?.channel?.server_id ?? + message?.channel?.serverId ?? + message?.message?.server_id ?? + message?.message?.serverId ?? + null; +} + +/** + * MessageHandler class. + */ export class MessageHandler { /** * Fluxer.js client instance @@ -205,7 +245,7 @@ export class MessageHandler { async assertPermissions(permissions, message) { 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 */ } + try { await guild.members.fetchMe(); } catch (_) { } } const missing = this.checkPermissions(permissions, message.channel ?? message.channel?.channel); if (missing.length === 0) return true; @@ -230,7 +270,7 @@ export class MessageHandler { try { const names = missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k); await message.reply(this.t(message.guildId, "responses.messages.needPermsFallback", { perms: names.join("** **") }), { ping: false }); - } catch (_) { /* completely blocked */ } + } catch (_) { } } return false; } @@ -543,6 +583,9 @@ export class MessageHandler { } } +/** + * Channel class. + */ export class Channel { /** * The actual underlying fluxer.js channel instance @@ -640,6 +683,9 @@ export class Channel { } } +/** + * Message class. + */ export class Message { /** * The actual underlying message instance @@ -733,6 +779,9 @@ export class Message { } } +/** + * PageBuilder class. + */ export class PageBuilder { form = ""; maxLinesPerPage = 2; @@ -942,7 +991,7 @@ export class RichPaginator { for (const emoji of allReactions) { try { await rawMsg.removeReaction(emoji); - } catch (_) {} + } catch(e) { } } }; @@ -1041,7 +1090,7 @@ export class QueuePaginator { for (const emoji of [prev, next]) { try { await rawMsg.removeReaction(emoji); - } catch (_) {} + } catch(e) { } } } }; @@ -1159,6 +1208,9 @@ function _helpBuildCategoryPages(tab, allCmds, prefix) { return pages; } +/** + * HelpCommand class. + */ export class HelpCommand { /** * @param {import("./CommandHandler.mjs").CommandHandler} commandHandler diff --git a/src/MoonlinkManager.mjs b/src/MoonlinkManager.mjs index c3dd2bd..754b093 100644 --- a/src/MoonlinkManager.mjs +++ b/src/MoonlinkManager.mjs @@ -1,3 +1,8 @@ +/** + * @file MoonlinkManager.mjs — MoonlinkManager — wraps moonlink.js for track search, session management, and voice packet forwarding to NodeLink + * @module src.MoonlinkManager + */ + /** * MoonlinkManager.mjs * @@ -9,6 +14,9 @@ import { logger, _wsErrorCooldown } from "./constants/Logger.mjs"; import { EventEmitter } from "node:events"; import { Events } from "@fluxerjs/core"; +/** + * MoonlinkManager class. + */ export class MoonlinkManager extends EventEmitter { /** @type {Manager} */ manager = null; @@ -102,7 +110,7 @@ export class MoonlinkManager extends EventEmitter { if (node.sessionId) return node.sessionId; if (node.ws?.sessionId) return node.ws.sessionId; } - } catch (_) {} + } catch(e) { logger.warn("[Moonlink] getLiveSessionId:", e?.message); } return this.sessionId; } @@ -205,7 +213,7 @@ export class MoonlinkManager extends EventEmitter { this._rawWsObj.off("message", this._rawWsMessageListener ?? this._rawWsHandler); this._rawWsObj.off("error", this._rawWsErrorHandler); } - } catch (_) {} + } catch(e) { logger.warn("[Moonlink] Raw WS listener cleanup:", e?.message); } } if (wsObj === this._rawWsObj) return; @@ -221,7 +229,7 @@ export class MoonlinkManager extends EventEmitter { } this.manager.packetUpdate(payload); } - } catch (_) {} + } catch(e) { logger.warn("[Moonlink] Raw WS message parse error:", e?.message); } }; this._rawWsErrorHandler = (errOrEvent) => { @@ -254,7 +262,7 @@ export class MoonlinkManager extends EventEmitter { async init(clientId) { this.setMaxListeners(50); - try { this.manager.setMaxListeners?.(50); } catch (_) {} + try { this.manager.setMaxListeners?.(50); } catch(e) { logger.warn("[Moonlink] init setMaxListeners:", e?.message); } try { for (const node of this.manager.nodes?.nodes?.values?.() ?? []) { @@ -266,7 +274,7 @@ export class MoonlinkManager extends EventEmitter { sock.removeAllListeners("message"); } } - } catch (_) {} + } catch(e) { logger.warn("[Moonlink] init socket cleanup:", e?.message); } await this.manager.init(clientId); } @@ -288,6 +296,6 @@ export class MoonlinkManager extends EventEmitter { for (const node of this.manager.nodes?.nodes?.values?.() ?? []) { node.socket?.close?.(); } - } catch (_) {} + } catch(e) { logger.warn("[Moonlink] destroy:", e?.message); } } } diff --git a/src/Player.mjs b/src/Player.mjs index a4265a8..c54e7a8 100644 --- a/src/Player.mjs +++ b/src/Player.mjs @@ -1,3 +1,8 @@ +/** + * @file Player.mjs — Core Player class — manages voice connections, audio streaming, queue, and playback lifecycle via FluxerRevoice/LiveKit + * @module src.Player + */ + /** * Player.mjs — FluxerRevoice edition * @@ -28,15 +33,12 @@ import { getGlobalColor } from "./MessageHandler.mjs"; import { logger } from "./constants/Logger.mjs"; import { get247ChannelMode } from "./constants/Helpers247.mjs"; import { PROVIDER_NAMES } from "./constants/providers.mjs"; - -/** Emit a plain embed payload so listeners can send it directly */ -function mkEmbed(desc) { - return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] }; -} +import { cleanId } from "./Utils.mjs"; +import { hasHumansInChannel } from "./constants/VoiceStateResolver.mjs"; /** NodeLink default password — centralised so it doesn't need to be hardcoded in two places. */ -const NL_DEFAULT_PASSWORD = "youshallnotpass"; +export const NL_DEFAULT_PASSWORD = "youshallnotpass"; const _sanitizeCache = new Map(); @@ -129,7 +131,7 @@ class PlayerWorkerPool { cb.reject(new Error(String(data))); this._drain(); } - } catch (_) {} + } catch(e) { logger.warn("[Player] Worker message handler error:", e?.message); } }); worker.on("error", (err) => { @@ -195,6 +197,9 @@ class PlayerWorkerPool { } } +/** + * Queue class. + */ export class Queue extends EventEmitter { data = []; current = null; @@ -338,8 +343,16 @@ export default class Player extends EventEmitter { activeFilter = null; activeFilterPayload = null; + static INACTIVITY_DEFAULT_MS = 3 * 60 * 1000; + static TRACK_MOSTLY_FINISHED_RATIO = 0.85; + static TRACK_MOSTLY_FINISHED_FLOOR_MS = 15_000; + static RADIO_SAFETY_TIMEOUT_MS = 20 * 60 * 1000; + static PUBLISH_MAX_RETRIES = 3; + static PUBLISH_BASE_RETRY_MS = 3_000; + static CONNECTION_WAIT_MS = 3_000; + _inactivityTimer = null; - _inactivityLimit = 3 * 60 * 1000; + _inactivityLimit = Player.INACTIVITY_DEFAULT_MS; _pendingInactivityCheck = false; _isJoining = false; @@ -421,33 +434,26 @@ export default class Player extends EventEmitter { */ _get247Mode() { if (!this._guildId) return "off"; + const serverSettings = this.settingsMgr?.getServer?.(this._guildId) + ?? this.settings + ?? this.client?.settings?.getServer?.(this._guildId); + if (!serverSettings?.get) return "off"; - const checkSettings = (set) => { - if (!set?.get) return "off"; - const raw = set.get("stay_247"); - if (!raw || raw === "none") return "off"; + const channelId = cleanId(this._home247Channel ?? this._channelId ?? ""); + if (!channelId) return "off"; + + const raw = serverSettings.get("stay_247"); + if (raw && raw !== "none") { const channels = Array.isArray(raw) - ? raw.map(id => String(id).replace(/\D/g, "")).filter(Boolean) - : [String(raw).replace(/\D/g, "")]; + ? raw.map(id => cleanId(id)).filter(Boolean) + : [cleanId(raw)].filter(Boolean); + if (!channels.includes(channelId)) return "off"; + } else { + return "off"; + } - const homeChannel = this._home247Channel - ? String(this._home247Channel).replace(/\D/g, "") - : null; - const currentChannel = String(this._channelId ?? "").replace(/\D/g, ""); - - const matchChannel = channels.includes(homeChannel) ? homeChannel - : channels.includes(currentChannel) ? currentChannel - : null; - if (!matchChannel) return "off"; - - return get247ChannelMode(set, matchChannel); - }; - - if (this.settingsMgr?.getServer) return checkSettings(this.settingsMgr.getServer(this._guildId)); - if (this.settings?.get) return checkSettings(this.settings); - if (this.client?.settings?.getServer) return checkSettings(this.client.settings.getServer(this._guildId)); - return "off"; + return get247ChannelMode(serverSettings, channelId); } /** @@ -457,7 +463,7 @@ export default class Player extends EventEmitter { * @returns {string|null} */ _resolveGuildId() { - const cleanGuild = String(this._guildId ?? "").replace(/\D/g, ""); + const cleanGuild = cleanId(this._guildId ?? ""); if (cleanGuild) return cleanGuild; try { @@ -465,9 +471,9 @@ export default class Player extends EventEmitter { if (channelId) { const ch = this.client?.channels?.get?.(channelId); const fromChannel = ch?.guildId ?? ch?.guild?.id ?? null; - if (fromChannel) return String(fromChannel).replace(/\D/g, ""); + if (fromChannel) return cleanId(fromChannel); } - } catch (_) {} + } catch(e) { logger.warn("[Player] Guild resolution failed:", e?.message); } return null; } @@ -498,67 +504,15 @@ export default class Player extends EventEmitter { } _hasHumansInChannel() { - if (!this._channelId || !this._guildId) return false; - const cleanChan = String(this._channelId).replace(/\D/g, ""); - const cleanGuild = String(this._guildId).replace(/\D/g, ""); - - if (this._voiceCache && this._voiceCache.hasHumansInChannel(cleanGuild, cleanChan)) { - return true; - } - - try { - const voiceUsers = this._observedVoiceUsers; - if (voiceUsers && typeof voiceUsers.iterateHumanUsers === "function") { - for (const [, info] of voiceUsers.iterateHumanUsers()) { - if ( - String(info.guildId ?? "").replace(/\D/g, "") === cleanGuild && - String(info.channelId ?? "").replace(/\D/g, "") === cleanChan - ) return true; - } - } else if (voiceUsers) { - for (const [, info] of voiceUsers) { - if ( - String(info.guildId ?? "").replace(/\D/g, "") === cleanGuild && - String(info.channelId ?? "").replace(/\D/g, "") === cleanChan - ) return true; - } - } - } catch (_) {} - try { - const guild = this.client?.guilds?.get?.(this._guildId); - const voiceStates = guild?.voice_states; - if (voiceStates) { - const entries = Array.isArray(voiceStates) - ? voiceStates - : typeof voiceStates.values === "function" - ? voiceStates.values() - : Object.values(voiceStates); - for (const state of entries) { - const stateChannelId = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, ""); - if (stateChannelId === cleanChan) { - const userId = String(state?.userId ?? state?.user_id ?? ""); - const member = guild?.members?.get?.(userId); - const isBot = member?.user?.bot ?? false; - if (!isBot) return true; - } - } - } - } catch (_) {} - - try { - const room = this.connection?.room; - if (room?.isConnected && room.remoteParticipants) { - const botId = this.client?.user?.id; - for (const [, participant] of room.remoteParticipants) { - const pId = participant?.identity || participant?.sid; - if (pId && pId !== botId) { - return true; - } - } - } - } catch (_) {} - - return false; + return hasHumansInChannel({ + guildId: cleanId(this._guildId ?? ""), + channelId: cleanId(this._channelId ?? ""), + client: this.client, + voiceCache: this._voiceCache, + observedVoiceUsers: this._observedVoiceUsers, + room: this.connection?.room, + botId: this.client?.user?.id, + }); } _startInactivityTimer() { @@ -633,10 +587,10 @@ export default class Player extends EventEmitter { logger.mediaplayer("[Player] Existing MediaPlayer unhealthy, cleaning up..."); try { if (this._mediaPlayer.fProc) { - try { this._mediaPlayer.fProc.removeAllListeners(); } catch (_) {} + try { this._mediaPlayer.fProc.removeAllListeners(); } catch(e) { } } await this._mediaPlayer.stop(); - } catch (_) {} + } catch(e) { logger.warn("[Player] MediaPlayer stop error:", e?.message); } this._mediaPlayer = null; } @@ -647,8 +601,8 @@ export default class Player extends EventEmitter { if (this._destroyed) return false; - const MAX_PUBLISH_RETRIES = 3; - const BASE_RETRY_DELAY_MS = 3_000; + const MAX_PUBLISH_RETRIES = Player.PUBLISH_MAX_RETRIES; + const BASE_RETRY_DELAY_MS = Player.PUBLISH_BASE_RETRY_MS; for (let attempt = 1; attempt <= MAX_PUBLISH_RETRIES; attempt++) { try { @@ -685,7 +639,7 @@ export default class Player extends EventEmitter { || msg.includes("publishToRoom failed") || msg.includes("internal error"); - try { this._mediaPlayer?.stop?.(); } catch (_) {} + try { this._mediaPlayer?.stop?.(); } catch(e) { logger.warn("[Player] MediaPlayer stop during retry:", e?.message); } this._mediaPlayer = null; if (isTransient && attempt < MAX_PUBLISH_RETRIES) { @@ -720,7 +674,7 @@ export default class Player extends EventEmitter { if (this._mediaPlayer) { try { if (this._mediaPlayer.fProc) { - try { this._mediaPlayer.fProc.removeAllListeners(); } catch (_) {} + try { this._mediaPlayer.fProc.removeAllListeners(); } catch(e) { } } await this._mediaPlayer.stop(); @@ -730,9 +684,9 @@ export default class Player extends EventEmitter { try { if (this._mediaPlayer?.fProc && !this._mediaPlayer.ffmpegFinished) { - try { this._mediaPlayer.fProc.kill("SIGKILL"); } catch (_) {} + try { this._mediaPlayer.fProc.kill("SIGKILL"); } catch(e) { logger.warn("[Player] FFmpeg SIGKILL error:", e?.message); } } - } catch (_) {} + } catch(e) { logger.warn("[Player] Stop MediaPlayer error:", e?.message); } this._mediaPlayer = null; } @@ -828,15 +782,15 @@ export default class Player extends EventEmitter { const elapsedMs = Math.max(0, Date.now() - this.startedPlaying); const remainingMs = Math.max(0, totalMs - elapsedMs); - return elapsedMs / totalMs >= 0.85 || remainingMs <= 15_000; + return elapsedMs / totalMs >= Player.TRACK_MOSTLY_FINISHED_RATIO || remainingMs <= Player.TRACK_MOSTLY_FINISHED_FLOOR_MS; } async _streamViaRevoice(url, inputOptions = []) { if (this._streamingStopped) return; - this._streamingStopped = false; - let audioStream = null; + const currentTrack = this.queue.getCurrent(); + let audioStream = null; try { audioStream = await this._fetchStream(url); @@ -845,115 +799,96 @@ export default class Player extends EventEmitter { const cleanup = () => { if (audioStream) { try { - if (typeof audioStream.unpipe === "function") audioStream.unpipe(); + if (typeof audioStream.unpipe === "function") audioStream.unpipe(); if (typeof audioStream.destroy === "function") audioStream.destroy(); - } catch (_) {} + } catch (e) { } } this._currentPassthrough = null; }; - await new Promise((resolve, reject) => { + const isGracefulExit = () => + this._streamingStopped || this._skipping || this._seeking || this.leaving; + + + const streamError = new Promise((_, reject) => { audioStream.on("error", (e) => { - cleanup(); - if (this._streamingStopped || this._skipping || this._seeking) return resolve(); + if (isGracefulExit()) return; const graceful = ["aborted", "ECONNRESET", "ERR_STREAM_DESTROYED", "ENOTFOUND", "ETIMEDOUT", "ECONNREFUSED"]; if (graceful.some(g => e.code === g || e.message?.includes(g))) { - if (this._didTrackMostlyFinish(currentTrack)) return resolve(); + if (this._didTrackMostlyFinish(currentTrack)) return; return reject(new Error(`Stream ended early for ${currentTrack?.title || "track"}: ${e.message ?? e.code ?? "stream aborted"}`)); } reject(e); }); + }); - if (!this._mediaPlayer) { cleanup(); return resolve(); } + if (!this._mediaPlayer) { cleanup(); return; } - this._mediaPlayer.removeAllListeners("finish"); - this._mediaPlayer.removeAllListeners("error"); + this._mediaPlayer.removeAllListeners("finish"); + this._mediaPlayer.removeAllListeners("error"); - const onFfmpegError = (err) => { - const ffMsg = err?.message ?? String(err); - const isGracefulKill = - ffMsg.includes("aborted") || - ffMsg.includes("Input stream error") || - ffMsg.includes("SIGKILL") || - ffMsg.includes("killed with signal"); - - if (isGracefulKill) { - if (this._didTrackMostlyFinish(currentTrack)) { - logger.player("[Player] FFmpeg stream ended near track completion"); + try { + const playResult = this._mediaPlayer.playStream(audioStream, inputOptions); + if (playResult && typeof playResult.catch === "function") { + playResult.catch((e) => { + if (isIgnorableMediaStateError(e) || isGracefulExit()) { + logger.mediaplayer("[Player] Suppressed async playStream InvalidState rejection"); cleanup(); - return resolve(); + return; } cleanup(); - if (this._streamingStopped || this._skipping || this._seeking) return resolve(); - return reject(new Error(`FFmpeg stream ended early: ${ffMsg}`)); - } - - logger.error("[Player] FFmpeg error:", ffMsg); - cleanup(); - if (this._streamingStopped || this._skipping || this._seeking) return resolve(); - reject(new Error(`FFmpeg: ${ffMsg}`)); - }; - - try { - const playResult = this._mediaPlayer.playStream(audioStream, inputOptions); - if (playResult && typeof playResult.catch === "function") { - playResult.catch((e) => { - if (isIgnorableMediaStateError(e) || this._streamingStopped || this._skipping || this._seeking || this.leaving) { - logger.mediaplayer("[Player] Suppressed async playStream InvalidState rejection"); - cleanup(); - resolve(); - return; - } - cleanup(); - reject(e); - }); - } - if (this._mediaPlayer.fProc) { - this._mediaPlayer.fProc.once("error", onFfmpegError); - } - } catch (e) { - cleanup(); - if (isIgnorableMediaStateError(e)) { - logger.mediaplayer("[Player] Suppressed InvalidState during stream start"); - return resolve(); - } - return reject(e); + throw e; + }); } + } catch (e) { + cleanup(); + if (isIgnorableMediaStateError(e)) { + logger.mediaplayer("[Player] Suppressed InvalidState during stream start"); + return; + } + throw e; + } - const trackDuration = this._getTrackDurationMs(currentTrack); - const safetyMs = (trackDuration > 0 && currentTrack?.type !== "radio") - ? trackDuration + 15_000 - : 20 * 60 * 1000; + const trackDuration = this._getTrackDurationMs(currentTrack); + const safetyMs = (trackDuration > 0 && currentTrack?.type !== "radio") + ? trackDuration + Player.TRACK_MOSTLY_FINISHED_FLOOR_MS + : Player.RADIO_SAFETY_TIMEOUT_MS; + + await new Promise((resolve) => { const safetyTimer = setTimeout(() => { - logger.warn(`[Player] Stream safety timeout hit (${Math.round(safetyMs/1000)}s) — advancing queue`); + logger.warn(`[Player] Stream safety timeout hit (${Math.round(safetyMs / 1000)}s) — advancing queue`); cleanup(); resolve(); }, safetyMs); - this._mediaPlayer.once("finish", () => { + const onFinish = () => { clearTimeout(safetyTimer); - if (this._mediaPlayer?.fProc) this._mediaPlayer.fProc.removeListener("error", onFfmpegError); cleanup(); resolve(); - }); - this._mediaPlayer.once("error", (e) => { + }; + + const onError = (e) => { clearTimeout(safetyTimer); - if (this._mediaPlayer?.fProc) this._mediaPlayer.fProc.removeListener("error", onFfmpegError); cleanup(); if (isIgnorableMediaStateError(e)) { logger.mediaplayer("[Player] Suppressed InvalidState during playback"); return resolve(); } if (this._streamingStopped) return resolve(); - reject(e); - }); + + logger.warn("[Player] MediaPlayer error during stream:", e?.message); + resolve(); + }; + + this._mediaPlayer.once("finish", onFinish); + this._mediaPlayer.once("error", onError); }); } catch (e) { if (audioStream && !audioStream.destroyed) { - try { audioStream.destroy(); } catch (_) {} + try { audioStream.destroy(); } catch (e2) { } } this._currentPassthrough = null; if (isIgnorableMediaStateError(e)) { @@ -1008,15 +943,15 @@ export default class Player extends EventEmitter { return; } logger.player(`[Player] Dead connection detected for ${channelId}, cleaning up`); - try { this.connection.removeAllListeners(); } catch (_) {} + try { this.connection.removeAllListeners(); } catch(e) { logger.warn("[Player] Connection cleanup error:", e?.message); } if (this._revoice && this._channelId) { - try { this._revoice.markIntentionalDisconnect(this._channelId); } catch (_) {} - try { this._revoice._leaveGateway(this._channelId, this._guildId ?? this._resolveGuildId()); } catch (_) {} - try { this._revoice.deleteConnection(this._channelId); } catch (_) {} + try { this._revoice.markIntentionalDisconnect(this._channelId); } catch(e) { logger.warn("[Player] Mark intentional disconnect error:", e?.message); } + try { this._revoice._leaveGateway(this._channelId, this._guildId ?? this._resolveGuildId()); } catch(e) { logger.warn("[Player] Leave gateway error:", e?.message); } + try { this._revoice.deleteConnection(this._channelId); } catch(e) { logger.warn("[Player] Delete connection error:", e?.message); } } - try { await this.connection.disconnect(); } catch (_) {} + try { await this.connection.disconnect(); } catch(e) { logger.warn("[Player] Connection disconnect error:", e?.message); } this.connection = null; this._mediaPlayer = null; } @@ -1028,17 +963,17 @@ export default class Player extends EventEmitter { if (this.connection) { logger.mediaplayer("[Player] Cleaning up existing connection before join"); - try { this.connection.removeAllListeners(); } catch (_) {} + try { this.connection.removeAllListeners(); } catch(e) { logger.warn("[Player] Connection cleanup error:", e?.message); } if (this._revoice && this._channelId) { - try { this._revoice.markIntentionalDisconnect(this._channelId); } catch (_) {} - try { this._revoice._leaveGateway(this._channelId, this._guildId ?? this._resolveGuildId()); } catch (_) {} - try { this._revoice.deleteConnection(this._channelId); } catch (_) {} + try { this._revoice.markIntentionalDisconnect(this._channelId); } catch(e) { logger.warn("[Player] Mark intentional disconnect error:", e?.message); } + try { this._revoice._leaveGateway(this._channelId, this._guildId ?? this._resolveGuildId()); } catch(e) { logger.warn("[Player] Leave gateway error:", e?.message); } + try { this._revoice.deleteConnection(this._channelId); } catch(e) { logger.warn("[Player] Delete connection error:", e?.message); } } try { await this.connection.disconnect(); - } catch (_) {} + } catch(e) { logger.warn("[Player] Connection disconnect error:", e?.message); } await Utils.sleep(500); this.connection = null; @@ -1077,7 +1012,7 @@ export default class Player extends EventEmitter { const cleanup = () => { clearTimeout(timeout); clearInterval(poll); - try { room.off(LKRoomEvent.ConnectionStateChanged, onStateChange); } catch (_) {} + try { room.off(LKRoomEvent.ConnectionStateChanged, onStateChange); } catch(e) { logger.warn("[Player] Room listener cleanup error:", e?.message); } }; const timeout = setTimeout(() => { @@ -1094,7 +1029,7 @@ export default class Player extends EventEmitter { settled = true; resolve(); } - }, 3_000); + }, Player.CONNECTION_WAIT_MS); const onStateChange = (cs) => { if (settled) return; @@ -1148,7 +1083,7 @@ export default class Player extends EventEmitter { connection.on("error", (err) => { if (this.connection !== connection) { - try { connection.removeAllListeners(); } catch (_) {} + try { connection.removeAllListeners(); } catch(e) { logger.warn("[Player] Stale connection cleanup error:", e?.message); } return; } logger.error("[Player] Voice error:", err?.message ?? err); @@ -1167,7 +1102,7 @@ export default class Player extends EventEmitter { connection.on("disconnect", () => { if (this.connection !== connection) { - try { connection.removeAllListeners(); } catch (_) {} + try { connection.removeAllListeners(); } catch(e) { logger.warn("[Player] Stale connection cleanup error:", e?.message); } return; } if (!this.leaving && !this._destroyed) { @@ -1182,7 +1117,7 @@ export default class Player extends EventEmitter { .finally(() => this.emit("autoleave")); } } else { - try { connection.removeAllListeners(); } catch (_) {} + try { connection.removeAllListeners(); } catch(e) { logger.warn("[Player] Connection cleanup on leave error:", e?.message); } } }); @@ -1235,7 +1170,7 @@ export default class Player extends EventEmitter { } if (this.connection) { - try { this.connection.disconnect(); } catch (_) {} + try { this.connection.disconnect(); } catch(e) { logger.warn("[Player] Connection disconnect on join failure:", e?.message); } this.connection = null; } throw e; @@ -1255,7 +1190,7 @@ export default class Player extends EventEmitter { this._activeTrackOpt = null; if (this._mediaPlayer) { - this._mediaPlayer.destroy(); + try { this._mediaPlayer.destroy(); } catch(e) { /* MediaPlayer may not have destroy() */ } this._mediaPlayer = null; } @@ -1267,7 +1202,7 @@ export default class Player extends EventEmitter { } else if (this._revoice.connections) { this._revoice.connections.delete(channelId); } - } catch (_) {} + } catch(e) { logger.warn("[Player] Delete connection on leave error:", e?.message); } } await this.connection.leave(); @@ -1301,7 +1236,7 @@ export default class Player extends EventEmitter { try { if (this._moonlink && this._onMoonlinkReady) { - try { this._moonlink.off("ready", this._onMoonlinkReady); } catch (_) {} + try { this._moonlink.off("ready", this._onMoonlinkReady); } catch(e) { logger.warn("[Player] Moonlink cleanup error:", e?.message); } this._onMoonlinkReady = null; } this.leaving = true; @@ -1315,7 +1250,7 @@ export default class Player extends EventEmitter { this.searches.clear(); if (this._workerPool) { - try { this._workerPool.terminate(); } catch (_) {} + try { this._workerPool.terminate(); } catch(e) { logger.warn("[Player] Worker pool terminate error:", e?.message); } this._workerPool = null; } @@ -1323,11 +1258,11 @@ export default class Player extends EventEmitter { this.connection = null; this._mediaPlayer = null; if (this._revoice && this._channelId) { - try { this._revoice.markIntentionalDisconnect(this._channelId); } catch (_) {} + try { this._revoice.markIntentionalDisconnect(this._channelId); } catch(e) { logger.warn("[Player] Mark intentional disconnect on destroy:", e?.message); } } this._stopMediaPlayer().catch(() => {}).then(() => { if (connToDestroy) { - try { connToDestroy.removeAllListeners?.(); } catch (_) {} + try { connToDestroy.removeAllListeners?.(); } catch(e) { } const disconnectPromise = connToDestroy.disconnect?.(); if (disconnectPromise instanceof Promise) { disconnectPromise.catch((err) => { @@ -1391,7 +1326,7 @@ export default class Player extends EventEmitter { this.emit("queueEnd"); if (!this._autoplay) { const prefix = this._getPrefix?.(this._guildId) ?? "%"; - this.emit("message", { ...mkEmbed(this._t("responses._common.queueEnded", { prefix })), system: true }); + this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true }); } } @@ -1428,7 +1363,7 @@ export default class Player extends EventEmitter { this.emit("queueEnd"); if (!this._autoplay) { const prefix = this._getPrefix?.(this._guildId) ?? "%"; - this.emit("message", { ...mkEmbed(this._t("responses._common.queueEnded", { prefix })), system: true }); + this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true }); } } @@ -1903,12 +1838,12 @@ export default class Player extends EventEmitter { if (!s) return; if (s.type === "radio") { - this.emit("message", mkEmbed(this._t("responses.radio.nowPlaying", { + this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses.radio.nowPlaying", { title: Utils.escapeMarkdown(s.title), author: s.author?.name || "Unknown", url: s.author?.url || "", channel: this._channelId || "", - }))); + }))] }); return; } const author = s.artists @@ -1916,12 +1851,12 @@ export default class Player extends EventEmitter { : s.author?.url ? `[${s.author.name}](${s.author.url})` : s.author?.name || "Unknown"; - this.emit("message", mkEmbed(this._t("responses.play.nowPlaying", { + this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses.play.nowPlaying", { title: Utils.escapeMarkdown(s.title), url: s.spotifyUrl || s.url, author: author, channel: this._channelId || "", - }))); + }))] }); } _workerPool = null; @@ -2090,17 +2025,17 @@ export default class Player extends EventEmitter { try { if (typeof this._currentPassthrough.unpipe === "function") this._currentPassthrough.unpipe(); if (typeof this._currentPassthrough.destroy === "function") this._currentPassthrough.destroy(); - } catch (_) {} + } catch(e) { logger.warn("[Player] Passthrough cleanup error:", e?.message); } this._currentPassthrough = null; } if (this._mediaPlayer) { try { if (this._mediaPlayer.fProc) { - try { this._mediaPlayer.fProc.removeAllListeners(); } catch (_) {} + try { this._mediaPlayer.fProc.removeAllListeners(); } catch(e) { } } await this._mediaPlayer.stop(); - } catch (_) {} + } catch(e) { logger.warn("[Player] MediaPlayer stop on next track:", e?.message); } } this._streamingStopped = false; @@ -2121,7 +2056,7 @@ export default class Player extends EventEmitter { if (!this._wasRadio && !this._queueEndedSent && !this._autoplay) { this._queueEndedSent = true; const prefix = this._getPrefix?.(this._guildId) ?? "%"; - this.emit("message", { ...mkEmbed(this._t("responses._common.queueEnded", { prefix })), system: true }); + this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true }); } this._wasRadio = false; return; @@ -2156,7 +2091,7 @@ export default class Player extends EventEmitter { const hasValidPlayer = await this._ensureMediaPlayer(); if (!hasValidPlayer) { logger.error("[Player] Failed to create healthy MediaPlayer — cannot play."); - this.emit("message", mkEmbed(this._t("responses._common.voiceConnectionLost"))); + this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.voiceConnectionLost"))] }); if (!this._is247Enabled()) { this._startInactivityTimer(); @@ -2214,7 +2149,7 @@ export default class Player extends EventEmitter { if (!streamUrl || !Utils.isValidUrl(streamUrl)) { logger.error("[Player] No valid stream URL for:", songData.title); - this.emit("message", mkEmbed(this._t("responses._common.couldNotGetStream", { title: songData.title }))); + this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.couldNotGetStream", { title: songData.title }))] }); this._streamingStopped = true; this.emit("stopplay"); if (!this._is247Enabled()) { @@ -2235,7 +2170,7 @@ export default class Player extends EventEmitter { if (trackOptMatch) { this._activeTrackOpt = trackOptMatch; - if (trackOptMatch.startMs > 0 && songData.encoded && streamUrl.includes("/v4/loadstream")) { + if (trackOptMatch.startMs > 0 && streamUrl.includes("/v4/loadstream")) { startOffsetMs = trackOptMatch.startMs; streamUrl = streamUrl.replace(/position=\d+/, `position=${startOffsetMs}`); logger.player(`[Player] TrackOptions: starting from ${startOffsetMs}ms via loadstream position param`); @@ -2277,7 +2212,7 @@ export default class Player extends EventEmitter { this._streamingStopped = true; if (!this._skipping && !this.leaving && !this._paused) { if (songData.type !== "radio") { - this.emit("message", mkEmbed(this._t("responses._common.errorStreaming", { title: songData.title }))); + this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.errorStreaming", { title: songData.title }))] }); } } } @@ -2300,7 +2235,8 @@ export default class Player extends EventEmitter { this._lastPlayedTrack = this.queue.getCurrent() ?? songData; if (!this.queue.songLoop) this.queue.current = null; this._streamingStopped = false; - return this._doPlayNext(); + this._playingNext = false; + return this.playNext(); } } } @@ -2319,9 +2255,25 @@ export default class Player extends EventEmitter { this._trackEndRemainingMs = null; this._skipping = true; this._stopMediaPlayer().then(() => { - this._doPlayNext(); + this._playingNext = false; + if (!this.queue.isEmpty() && !this.leaving) { + this.playNext().catch(e => logger.error("[Player] TrackEnd playNext error:", e.message)); + } else { + this.emit("stopplay"); + if (!this._is247Enabled()) { + this._startInactivityTimer(); + } + } }).catch(() => { - this._doPlayNext(); + this._playingNext = false; + if (!this.queue.isEmpty() && !this.leaving) { + this.playNext().catch(e => logger.error("[Player] TrackEnd playNext error:", e.message)); + } else { + this.emit("stopplay"); + if (!this._is247Enabled()) { + this._startInactivityTimer(); + } + } }); } @@ -2372,8 +2324,8 @@ export default class Player extends EventEmitter { const userIds = []; if (this._voiceCache) { const humans = this._voiceCache.getHumansInChannel( - String(this._guildId).replace(/\D/g, ""), - String(this._channelId).replace(/\D/g, "") + cleanId(this._guildId), + cleanId(this._channelId) ); userIds.push(...humans); } @@ -2387,15 +2339,15 @@ export default class Player extends EventEmitter { : typeof voiceStates.values === "function" ? [...voiceStates.values()] : Object.values(voiceStates); for (const state of entries) { - const ch = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, ""); - if (ch === String(this._channelId).replace(/\D/g, "")) { + const ch = cleanId(state?.channelId ?? state?.channel_id ?? ""); + if (ch === cleanId(this._channelId)) { const uid = state?.userId ?? state?.user_id; const member = guild?.members?.get?.(uid); if (uid && !member?.user?.bot) userIds.push(uid); } } } - } catch (_) {} + } catch(e) { logger.warn("[Player] Voice state lookup error:", e?.message); } } if (userIds.length === 0) return null; @@ -2406,6 +2358,11 @@ export default class Player extends EventEmitter { async _applyTrackOptionsSeek(match) { if (!match || match.startMs <= 0) return; + const current = this.queue.getCurrent(); + if (!current?.encoded || !this.connection || this.leaving) { + logger.warn(`[Player] TrackOptions: cannot seek (encoded=${!!current?.encoded} connection=${!!this.connection} leaving=${this.leaving})`); + return; + } let seeked = false; for (let attempt = 0; attempt < 10; attempt++) { await Utils.sleep(500); @@ -2421,7 +2378,15 @@ export default class Player extends EventEmitter { } } if (!seeked) { - logger.warn(`[Player] TrackOptions: auto-seek to ${match.startMs}ms failed after all retries`); + logger.warn(`[Player] TrackOptions: auto-seek to ${match.startMs}ms failed after all retries, trying _replayWithFilters`); + try { + await this._replayWithFilters(match.startMs); + this.startedPlaying = Date.now() - match.startMs; + this._recalcTrackEndTimer(); + logger.player(`[Player] TrackOptions: fallback replay from ${match.startMs}ms succeeded`); + } catch (e) { + logger.warn(`[Player] TrackOptions: fallback replay also failed:`, e.message); + } } } diff --git a/src/PlayerManager.mjs b/src/PlayerManager.mjs index 987698c..7a8183f 100644 --- a/src/PlayerManager.mjs +++ b/src/PlayerManager.mjs @@ -1,3 +1,8 @@ +/** + * @file PlayerManager.mjs — PlayerManager — creates, caches, and routes Player instances per voice channel across all guilds + * @module src.PlayerManager + */ + /** * PlayerManager.mjs — Manages voice channel players across servers * @@ -6,37 +11,15 @@ */ import Player from "./Player.mjs"; -import { CommandHandler } from "./CommandHandler.mjs"; -import { Message } from "./MessageHandler.mjs"; -import { SettingsManager } from "./Settings.mjs"; -import { Utils } from "./Utils.mjs"; +import { Utils, cleanId } from "./Utils.mjs"; import { logger } from "./constants/Logger.mjs"; import { get247ChannelMode } from "./constants/Helpers247.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getVoiceManager } from "@fluxerjs/voice"; -import { getGlobalColor } from "./MessageHandler.mjs"; +import { getGlobalColor, getMessageGuildId } from "./MessageHandler.mjs"; import { Dashboard } from "./dashboard/Dashboard.mjs"; +import { hasHumansInChannel, iterateVoiceStates } from "./constants/VoiceStateResolver.mjs"; -/** Helper — build a plain embed payload from a description string */ -function mkEmbed(desc) { - return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] }; -} - -function cleanId(value) { - return String(value ?? "").replace(/\D/g, ""); -} - -function getMessageGuildId(message) { - return message?.channel?.guildId ?? - message?.channel?.guild?.id ?? - message?.message?.guildId ?? - message?.message?.guild?.id ?? - message?.channel?.server_id ?? - message?.channel?.serverId ?? - message?.message?.server_id ?? - message?.message?.serverId ?? - null; -} function getPlayerGuildId(player, fallbackChannel = null) { return cleanId( @@ -72,7 +55,8 @@ function botHasVoicePermissions(client, channelId) { if (!perms) return true; if (perms.has(0x8)) return true; return perms.has(0x400) && perms.has(0x100000) && perms.has(0x200000); - } catch (_) { + } catch (e) { + logger.warn("[PlayerManager] botHasVoicePermissions check failed:", e?.message); return true; } } @@ -113,6 +97,9 @@ function sanitizeJoinError(err, client = null, channelId = null) { return null; } +/** + * PlayerManager class. + */ export class PlayerManager { /** @type {SettingsManager} */ settings; @@ -436,122 +423,73 @@ export class PlayerManager { /** * Attempt to detect the voice channel a user is currently in. * @param {Message} message - * @returns {string|null} Voice channel ID or null + * @param {Object} [settings] + * @returns {Promise<{channelId: string|null, alreadyInVoice: boolean, hasHumans: boolean}>} */ - checkVoiceChannels(message) { - if (!message) return null; + async checkVoiceChannels(message, settings) { + const guildId = message?.guildId ?? message?.channel?.guildId ?? getMessageGuildId(message); + const userId = message?.author?.id ?? message?.member?.user?.id; + const cleanGuildId = cleanId(guildId); + if (!guildId || !userId) return { channelId: null, alreadyInVoice: false, hasHumans: false }; - const userId = message.author?.id ?? message.message?.author?.id; - const guildId = getMessageGuildId(message); + const guild = this.commands?.client?.guilds?.get?.(cleanGuildId); - if (!userId) return null; - if (!guildId) return null; - const cleanGuild = cleanId(guildId); - const seedObserved = (channelId) => { - const cleanChannelId = cleanId(channelId); - if (!cleanChannelId) return null; - const cache = this.voiceCache ?? this.observedVoiceUsers; - if (cache && !cache.has(userId, cleanGuild)) { - cache.set(userId, { channelId: cleanChannelId, guildId: cleanGuild }); + if (this.voiceCache) { + const observed = this.voiceCache.getUserLocation(cleanGuildId, userId); + if (observed && observed.channelId) { + const alreadyInVoice = this.playerMap.has(cleanId(observed.channelId)); + const hasHumans = this.voiceCache.hasHumansInChannel(cleanGuildId, cleanId(observed.channelId)); + return { channelId: observed.channelId, alreadyInVoice, hasHumans }; } - const loc = cache?.get(userId, cleanGuild); - return cleanId(loc?.channelId) || cleanChannelId; - }; - - const cache = this.voiceCache ?? this.observedVoiceUsers; - const observed = cache?.get?.(userId, cleanGuild); - if (cleanId(observed?.guildId) === cleanGuild) { - const observedChannelId = cleanId(observed?.channelId); - if (observedChannelId) return observedChannelId; } - try { - const vm = getVoiceManager(this.commands.client); - const voiceChannelId = vm?.getVoiceChannelId?.(guildId, userId); - const seeded = seedObserved(voiceChannelId); - if (seeded) return seeded; - } catch (_) {} - try { - const vm = getVoiceManager(this.commands.client); - if (vm?.voiceStates) { - const guildVoiceMap = vm.voiceStates.get(cleanGuild) ?? vm.voiceStates.get(guildId); - if (guildVoiceMap && typeof guildVoiceMap.get === "function") { - const vmChannelId = guildVoiceMap.get(userId); - const seeded = seedObserved(vmChannelId); - if (seeded) return seeded; + let channelId = message?.member?.voice?.channelId ?? null; + + + if (!channelId && guild) { + for (const vs of iterateVoiceStates(guild)) { + if (vs.userId === String(userId) && !vs.isBot) { + channelId = vs.channelId; + break; } } - } catch (_) {} - - const memberVoiceChannelId = - message?.member?.voice?.channelId ?? - message?.message?.member?.voice?.channelId ?? - null; - { - const seeded = seedObserved(memberVoiceChannelId); - if (seeded) return seeded; } - try { - const guild = - this.commands.client?.guilds?.get?.(guildId) ?? - this.commands.client?.guilds?.get?.(cleanGuild); - const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null; - if (voiceStates) { - if (!Array.isArray(voiceStates) && typeof voiceStates === "object") { - const direct = voiceStates[userId]; - const directChannelId = - typeof direct === "string" - ? direct - : direct?.channelId ?? direct?.channel_id ?? null; - const seeded = seedObserved(directChannelId); - if (seeded) return seeded; - } - const entries = Array.isArray(voiceStates) - ? voiceStates - : typeof voiceStates.values === "function" - ? voiceStates.values() - : Object.values(voiceStates); - - for (const state of entries) { - const stateUserId = state?.userId ?? state?.user_id ?? state?.id; - const stateGuildId = cleanId(state?.guildId ?? state?.guild_id ?? guildId); - if (stateUserId !== userId || stateGuildId !== cleanGuild) continue; - const seeded = seedObserved(state?.channelId ?? state?.channel_id); - if (seeded) return seeded; - } + if (!channelId) { + try { + const vm = getVoiceManager(this.commands?.client); + channelId = vm?.getVoiceChannelId?.(guildId, userId) ?? null; + } catch (e) { + logger.warn("[PlayerManager] VoiceManager lookup failed:", e?.message); } - } catch (_) {} + } - const liveGuildPlayers = [...this.playerMap.entries()].filter(([channelId, player]) => { - const fallbackChannel = - this.commands.client?.channels?.get?.(channelId) ?? - null; - return getPlayerGuildId(player, fallbackChannel) === cleanGuild && !player?._destroyed; + + if (!channelId && this.voiceCache) { + const loc = this.voiceCache.getHumanUser(userId); + if (loc && cleanId(loc.guildId) === cleanGuildId) { + channelId = loc.channelId; + } + } + + if (!channelId) return { channelId: null, alreadyInVoice: false, hasHumans: false }; + + const alreadyInVoice = this.playerMap.has(cleanId(channelId)); + + const hasHumansResult = hasHumansInChannel({ + guildId: cleanGuildId, + channelId: cleanId(channelId), + client: this.commands?.client, + voiceCache: this.voiceCache, + observedVoiceUsers: this.observedVoiceUsers, + room: this.playerMap.get(cleanId(channelId))?.connection?.room, + botId: this.commands?.client?.user?.id, }); - if (liveGuildPlayers.length === 1) { - return getPlayerChannelId(liveGuildPlayers[0][1], liveGuildPlayers[0][0]) || cleanId(liveGuildPlayers[0][0]); - } - if (liveGuildPlayers.length > 1) { - for (const [mapKey, player] of liveGuildPlayers) { - try { - const room = player?.connection?.room; - if (!room?.isConnected || !room.remoteParticipants) continue; - for (const [, participant] of room.remoteParticipants) { - const pId = participant?.identity ?? participant?.sid; - if (pId === userId) { - const found = getPlayerChannelId(player, mapKey) || cleanId(mapKey); - seedObserved(found); - return found; - } - } - } catch (_) {} - } - } - return null; + + return { channelId, alreadyInVoice, hasHumans: hasHumansResult }; } /** @@ -566,7 +504,7 @@ export class PlayerManager { const guildId = getMessageGuildId(message); const cleanGuildId = cleanId(guildId); - const userChannelId = this.checkVoiceChannels(message); + const { channelId: userChannelId } = await this.checkVoiceChannels(message); const cleanUserChannelId = cleanId(userChannelId); if (cleanUserChannelId) { @@ -579,7 +517,9 @@ export class PlayerManager { if (guildId && textChannelId) { this.settings.getServer(guildId)?.set("announcementChannelId", textChannelId); } - } catch (_) {} + } catch(e) { + logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message); + } return player; } if (this._pendingJoins.has(cleanUserChannelId)) { @@ -600,7 +540,7 @@ export class PlayerManager { first[1].textChannel = message.channel; return first[1]; } - message.reply(mkEmbed(this._t(message, "responses._common.noVoiceStrict"))); + message.reply(this._t(message, "responses._common.noVoiceStrict")); return null; } @@ -614,18 +554,18 @@ export class PlayerManager { if (cleanGuildId && textChannelId) { this.settings.getServer(cleanGuildId)?.set("announcementChannelId", textChannelId); } - } catch (_) {} + } catch(e) { + logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message); + } return match[1]; } if (shouldJoin) { - return new Promise((resolve) => { - this.initPlayer(message, userChannelId, (p) => resolve(p)); - }); + return this.initPlayer(message, userChannelId); } const prefix = this.commands.getPrefix(guildId); - message.reply(mkEmbed(this._t(message, "responses._common.alreadyInChannel", { channels: channelList, prefix }))); + message.reply(this._t(message, "responses._common.alreadyInChannel", { channels: channelList, prefix })); return null; } @@ -633,14 +573,12 @@ export class PlayerManager { if (shouldJoin) { return this.promptVC(message); } - message.reply(mkEmbed(this._t(message, "responses._common.noVoiceChannel"))); + message.reply(this._t(message, "responses._common.noVoiceChannel")); return null; } if (shouldJoin) { - return new Promise((resolve) => { - this.initPlayer(message, userChannelId, (p) => resolve(p)); - }); + return this.initPlayer(message, userChannelId); } return null; @@ -652,9 +590,9 @@ export class PlayerManager { * @returns {Promise} */ async promptVC(msg) { - const autoDetected = this.checkVoiceChannels(msg); + const { channelId: autoDetected } = await this.checkVoiceChannels(msg); if (autoDetected) { - return new Promise(resolve => this.initPlayer(msg, autoDetected, (p) => resolve(p))); + return this.initPlayer(msg, autoDetected); } const guildId = getMessageGuildId(msg); @@ -678,9 +616,9 @@ export class PlayerManager { } const hint = this._t(msg, "responses._common.voiceSelectionHint"); - const selectionMsg = await msg.reply(mkEmbed( + const selectionMsg = await msg.reply( (channelSelection ? channelSelection + "\n**..or** " + hint : "Please " + hint) - )); + ); return new Promise(resolve => { let unsubscribeReactions; @@ -694,7 +632,7 @@ export class PlayerManager { const timeout = setTimeout(() => { cleanup(); - msg.reply(mkEmbed(this._t(msg, "responses._common.voiceSelectionTimedOut"))); + msg.reply(this._t(msg, "responses._common.voiceSelectionTimedOut")); resolve(false); }, 30_000); @@ -708,7 +646,7 @@ export class PlayerManager { clearTimeout(timeout); cleanup(); const cid = channel._id ?? channel.id; - this.initPlayer(msg, cid, (p) => resolve(p)); + this.initPlayer(msg, cid).then(p => resolve(p)); }, promptUser ); @@ -719,18 +657,18 @@ export class PlayerManager { if (content === "x") { clearTimeout(timeout); cleanup(); - m.reply(mkEmbed(this._t(m, "voice.join.cancelled"))); + m.reply(this._t(m, "voice.join.cancelled")); resolve(false); return; } if (!this.commands.validateInput("voiceChannel", m.content, m)) { - m.reply(mkEmbed(this._t(m, "responses._common.voiceSelectionInvalid"))); + m.reply(this._t(m, "responses._common.voiceSelectionInvalid")); return; } const channel = this.commands.formatInput("voiceChannel", m.content, m); clearTimeout(timeout); cleanup(); - this.initPlayer(m, channel, (p) => resolve(p)); + this.initPlayer(m, channel).then(p => resolve(p)); }, promptUser); }); } @@ -757,7 +695,7 @@ export class PlayerManager { ? this.playerMap.get(cleanChannelId) ?? this.getPlayerByChannelId(cleanChannelId) : null; - if (!player) return msg.reply(mkEmbed(this._t(msg, "responses._common.notInVoice"))); + if (!player) return msg.reply(this._t(msg, "responses._common.notInVoice")); const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId; this.playerMap.delete(activeChannelId); @@ -771,37 +709,50 @@ export class PlayerManager { logger.warn("[PlayerManager] leave() error (non-fatal):", e.message); } player.destroy(); - await msg.reply(mkEmbed(this._t(msg, "responses._common.successfullyLeft"))); + await msg.reply(this._t(msg, "responses._common.successfullyLeft")); + } + + /** + * Restore saved volume for a player from server settings. + * @param {Player} player + * @param {string} guildId + */ + _restorePlayerVolume(player, guildId) { + const savedVol = this.settings?.getServer?.(guildId)?.get?.("volume"); + if (savedVol !== undefined && savedVol !== null) { + const vol = Number(savedVol); + if (!isNaN(vol)) player.setVolume(vol / 100); + } } /** * Create and register a new Player for the given voice channel. * @param {Message} message * @param {string} cid - Voice channel ID - * @param {Function} [cb] + * @returns {Promise} */ - initPlayer(message, cid, cb = () => {}) { + async initPlayer(message, cid) { const channel = this.commands.client?.channels?.get(cid); if (!channel) { - cb(null); - return message.reply(mkEmbed( + message.reply( this._t(message, "responses.join.channelNotFound", { channel: cid }) - )); + ); + return null; } const isVoice = channel.type === 2; if (!isVoice) { - cb(null); - return message.reply(mkEmbed(this._t(message, "responses._common.voiceChannelRequired"))); + message.reply(this._t(message, "responses._common.voiceChannelRequired")); + return null; } if (!botHasVoicePermissions(this.commands?.client, cid)) { - cb(null); - return message.reply(mkEmbed( + message.reply( this._t(message, "responses.join.joinFailedPerms", { channel: `<#${cleanId(cid)}>` }) - )); + ); + return null; } const cleanChannelId = cleanId(cid); @@ -809,12 +760,12 @@ export class PlayerManager { ?? this.getPlayerByChannelId(cleanChannelId); if (existing) { existing.textChannel = message.channel; - cb(existing); - return message.reply(mkEmbed(this._t(message, "responses.join.alreadyJoined", { channel: cid }))); + message.reply(this._t(message, "responses.join.alreadyJoined", { channel: cid })); + return existing; } if (this._pendingJoins.has(cleanChannelId)) { - cb(null); - return message.reply(mkEmbed(this._t(message, "responses.join.joining"))); + message.reply(this._t(message, "responses.join.joining")); + return null; } this._pendingJoins.add(cleanChannelId); @@ -846,19 +797,19 @@ export class PlayerManager { const guildId = cleanId(player._guildId ?? ch?.guildId ?? ch?.guild?.id ?? getMessageGuildId({ channel: ch })); const raw247 = (() => { - try { return this.settings.getServer(guildId)?.get("stay_247"); } catch (_) { return null; } + try { return this.settings.getServer(guildId)?.get("stay_247"); } catch (e) { logger.warn("[PlayerManager] Failed to read 24/7 setting:", e?.message); return null; } })(); const isIn247List = (() => { if (!raw247 || raw247 === "none") return false; const channels = Array.isArray(raw247) - ? raw247.map(id => String(id).replace(/\D/g, "")).filter(Boolean) - : [String(raw247).replace(/\D/g, "")].filter(Boolean); + ? raw247.map(id => cleanId(id)).filter(Boolean) + : [cleanId(raw247)].filter(Boolean); return channels.includes(homeChannelId) || channels.includes(activeChannelId); })(); 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, "")] + Array.isArray(raw247) ? raw247.map(id => cleanId(id)) : [cleanId(raw247)] ) : null; const mode247 = matchChannel @@ -900,7 +851,7 @@ export class PlayerManager { ?? `Left channel <#${activeChannelId}> because of inactivity.\nIf you want me to stay in voice, use \`${prefix}247 on/auto\``; } if (typeof ch?.send === "function") { - ch.send(mkEmbed(desc)).catch(err => { + ch.send({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] }).catch(err => { if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) { logger.warn(`[PlayerManager] Cannot send autoleave message in channel ${ch.id} — missing permissions`); } @@ -922,9 +873,11 @@ export class PlayerManager { const serverSettings = this.settings.getServer(guildId); const savedAnnChId = serverSettings?.get?.("announcementChannelId"); if (savedAnnChId) { - ch = this.commands?.client?.channels?.get?.(String(savedAnnChId).replace(/\D/g, "")) ?? null; + ch = this.commands?.client?.channels?.get?.(cleanId(savedAnnChId)) ?? null; } - } catch (_) {} + } catch(e) { + logger.warn("[PlayerManager] Failed to resolve announcement channel:", e?.message); + } } if (!ch || typeof ch.send !== "function") { try { @@ -932,7 +885,9 @@ export class PlayerManager { if (guild?.systemChannelId) { ch = guild.channels?.get?.(guild.systemChannelId) ?? null; } - } catch (_) {} + } catch(e) { + logger.warn("[PlayerManager] Failed to resolve system channel:", e?.message); + } } if (!ch || typeof ch.send !== "function") { try { @@ -945,89 +900,76 @@ export class PlayerManager { } } } - } catch (_) {} + } catch(e) { + logger.warn("[PlayerManager] Failed to find fallback text channel:", e?.message); + } } if (!ch || typeof ch.send !== "function") return; if (!player.textChannel) player.textChannel = ch; - ch.send(typeof m === "object" && Array.isArray(m.embeds) ? m : mkEmbed(m)).catch(err => { + ch.send(typeof m === "object" && Array.isArray(m.embeds) ? m : { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(m)] }).catch(err => { if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) { logger.warn(`[PlayerManager] Cannot send player message in channel ${ch.id} — missing permissions`); } }); }); - (async () => { - const statusMsg = await message.reply(mkEmbed(this._t(message, "responses.join.joining"))); - try { - await player.join(cid); + const statusMsg = await message.reply(this._t(message, "responses.join.joining")); + try { + await player.join(cid); - this.playerMap.set(cleanChannelId, player); - this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId); - this._pendingJoins.delete(cleanChannelId); + this.playerMap.set(cleanChannelId, player); + this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId); + this._pendingJoins.delete(cleanChannelId); - await statusMsg.edit(mkEmbed(this._t(message, "responses.join.joined", { channel: cid }))); + await statusMsg.edit(this._t(message, "responses.join.joined", { channel: cid })); - const guildId = cleanId(channel.guildId ?? getMessageGuildId(message)); - if (guildId) { - const savedVol = this.settings.getServer(guildId)?.get("volume"); - if (savedVol !== undefined && savedVol !== null) { - const vol = Number(savedVol); - if (!isNaN(vol)) player.setVolume(vol / 100); + const guildId = cleanId(channel.guildId ?? getMessageGuildId(message)); + this._restorePlayerVolume(player, guildId); + + return player; + } catch (err) { + this._pendingJoins.delete(cleanChannelId); + + const errCode = sanitizeJoinError(err, this.commands?.client, cleanChannelId); + let errorMsg; + if (errCode === "SESSION_RACE") { + logger.warn(`[PlayerManager] Stale voice session detected for channel ${cleanChannelId}, retrying in 2s...`); + try { + await new Promise(r => setTimeout(r, 2_000)); + if (player._revoice && player._channelId) { + try { player._revoice._leaveGateway(player._channelId, player._guildId ?? player._resolveGuildId()); } catch(e) { logger.warn("[PlayerManager] Failed to leave gateway during retry:", e?.message); } + try { player._revoice.deleteConnection(player._channelId); } catch(e) { logger.warn("[PlayerManager] Failed to delete connection during retry:", e?.message); } } + await player.join(cid); + + this.playerMap.set(cleanChannelId, player); + this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId); + await statusMsg.edit(this._t(message, "responses.join.joined", { channel: cid })); + + const retryGuildId = cleanId(channel.guildId ?? getMessageGuildId(message)); + this._restorePlayerVolume(player, retryGuildId); + return player; + } catch (retryErr) { + logger.warn(`[PlayerManager] Retry also failed for channel ${cleanChannelId}: ${retryErr.message}`); + errorMsg = this._t(message, "responses.join.joinFailedGeneric"); } - - cb(player); - } catch (err) { - this._pendingJoins.delete(cleanChannelId); - - const errCode = sanitizeJoinError(err, this.commands?.client, cleanChannelId); - let errorMsg; - if (errCode === "SESSION_RACE") { - logger.warn(`[PlayerManager] Stale voice session detected for channel ${cleanChannelId}, retrying in 2s...`); - try { - await new Promise(r => setTimeout(r, 2_000)); - 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); - - this.playerMap.set(cleanChannelId, player); - this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId); - await statusMsg.edit(mkEmbed(this._t(message, "responses.join.joined", { channel: cid }))); - - const retryGuildId = cleanId(channel.guildId ?? getMessageGuildId(message)); - if (retryGuildId) { - const savedVol = this.settings.getServer(retryGuildId)?.get("volume"); - if (savedVol !== undefined && savedVol !== null) { - const vol = Number(savedVol); - if (!isNaN(vol)) player.setVolume(vol / 100); - } - } - cb(player); - return; - } catch (retryErr) { - logger.warn(`[PlayerManager] Retry also failed for channel ${cleanChannelId}: ${retryErr.message}`); - errorMsg = this._t(message, "responses.join.joinFailedGeneric"); - } - } else if (errCode === "PERMISSION") { - errorMsg = this._t(message, "responses.join.joinFailedPerms", { channel: `<#${cleanChannelId}>` }); - } else if (errCode === "NOT_FOUND") { - errorMsg = this._t(message, "responses.join.joinFailedNotFound"); - } else if (errCode === "TIMEOUT") { - errorMsg = this._t(message, "responses.join.joinFailed"); - } else { - errorMsg = this._t(message, "responses.join.joinFailed", { error: err.message }); - } - await statusMsg.edit(mkEmbed(errorMsg)).catch(() => {}); - this.playerMap.delete(cleanChannelId); - this._unindexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId); - player.destroy(); - cb(null); + } else if (errCode === "PERMISSION") { + errorMsg = this._t(message, "responses.join.joinFailedPerms", { channel: `<#${cleanChannelId}>` }); + } else if (errCode === "NOT_FOUND") { + errorMsg = this._t(message, "responses.join.joinFailedNotFound"); + } else if (errCode === "TIMEOUT") { + errorMsg = this._t(message, "responses.join.joinFailed"); + } else { + errorMsg = this._t(message, "responses.join.joinFailed", { error: err.message }); } - })(); + await statusMsg.edit(errorMsg).catch(() => {}); + this.playerMap.delete(cleanChannelId); + this._unindexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId); + player.destroy(); + return null; + } } /** diff --git a/src/Settings.mjs b/src/Settings.mjs index 9165385..d56fe3e 100644 --- a/src/Settings.mjs +++ b/src/Settings.mjs @@ -1,10 +1,33 @@ +/** + * @file Settings.mjs — Settings — abstract base class and RemoteSettingsManager for per-server configuration backed by SQLite + * @module src.Settings + */ + import fs from "node:fs"; import { logger } from "./constants/Logger.mjs"; import mysql from "mysql2"; import { EventEmitter } from "node:events"; -export { SettingsManager } from "../settings/Settings.mjs"; +/** + * Abstract base class for settings managers. + * Provides the interface that all concrete settings managers must implement. + */ +export class SettingsManager extends EventEmitter { + /** @abstract @type {Object} */ + defaults; + /** @abstract */ + update(server, key) { } + /** @abstract @returns {ServerSettings} */ + getServer(id) { } + /** @abstract @returns {boolean} */ + hasServer(id) { } + /** @abstract @returns {boolean} */ + isOption(key) { } +} +/** + * ServerSettings class. + */ export class ServerSettings { id; manager; @@ -20,16 +43,20 @@ export class ServerSettings { reset(key) { return this.set(key, this.manager.defaults[key]); } getAll() { return this.data; } 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]; } } checkDefaults(d) { for (let key in d) { if (this.data[key] === undefined) this.data[key] = d[key]; } } + deserialize(json) { for (let k in json) { if (k === "id") continue; this.data[k] = json[k]; } } + get serializationData() { return { ...this.data, id: this.id }; } serialize() { return this.serializationData; } serializeObject() { return this.serializationData; } } -export class RemoteSettingsManager extends EventEmitter { +/** + * RemoteSettingsManager class. + */ +export class RemoteSettingsManager extends SettingsManager { guilds = new Map(); descriptions = {}; defaults = {}; @@ -61,11 +88,6 @@ export class RemoteSettingsManager extends EventEmitter { * adding it (NOT NULL DEFAULT '') and updating the primary key to (id, bot_id). * If the column exists but isn't in the PK (previous failed migration), * fix the NULL values and retry the PK update. - * - * Key detail: MySQL primary key columns CANNOT be NULL. The previous version - * used DEFAULT NULL which caused ALTER TABLE ... ADD PRIMARY KEY to fail - * silently, leaving the PK as just (id) and producing ER_DUP_ENTRY errors - * when two bots tried to INSERT rows for the same guild. */ async _ensureBotIdColumn() { if (this._hasBotIdColumn) return; @@ -147,8 +169,6 @@ export class RemoteSettingsManager extends EventEmitter { /** * Set or update the bot ID used for database row isolation. * Called after login when the bot user ID becomes available. - * Ensures the bot_id column exists (auto-migrates if needed), then - * reloads guild data filtered by the bot's ID. * @param {string} id */ async setBotId(id) { @@ -173,34 +193,16 @@ export class RemoteSettingsManager extends EventEmitter { } } - /** - * Returns the SQL WHERE clause fragment for bot_id filtering. - * When botId is set AND the bot_id column exists in the table, - * includes "AND bot_id = " in queries. - * Otherwise no filter is applied (backward-compatible with old schemas). - * @returns {string} - */ _botIdWhere() { if (!this.botId || !this._hasBotIdColumn) return ""; return ` AND bot_id = ${mysql.escape(String(this.botId))}`; } - /** - * Returns the bot_id column + value for INSERT statements. - * Only includes bot_id when both the botId is set AND the column exists. - * @returns {{ col: string, val: string }} - */ _botIdInsert() { if (!this.botId || !this._hasBotIdColumn) return { col: "", val: "" }; return { col: ", bot_id", val: `, ${mysql.escape(String(this.botId))}` }; } - /** - * Fetch a single guild's settings row from the database, filtered by bot_id. - * Used by GatewayHandler when a guild is (re-)joined and not in the cache. - * @param {string} guildId - * @returns {Promise<{error: object|null, results: Array, fields: Array}>} - */ selectGuild(guildId) { const escapedId = mysql.escape(String(guildId)); return this.query(`SELECT * FROM settings WHERE id=${escapedId}${this._botIdWhere()}`); @@ -284,7 +286,7 @@ export class RemoteSettingsManager extends EventEmitter { } update(server, key) { - if (!this.guilds.has(server.id)) { this.guilds.set(server.id, server); this.create(server.id, server); } + if (!this.guilds.has(server.id)) { this.guilds.set(server.id, server); this.create(server.id, server).catch(e => logger.error("[Settings] create error in update:", e.message)); } const s = this.guilds.get(server.id); s.data[key] = server.data[key]; const existing = this._debounceTimers.get(server.id); @@ -305,11 +307,6 @@ export class RemoteSettingsManager extends EventEmitter { return this.guilds.get(id); } - /** - * Drop a server from the in-memory cache without touching the DB row. - * This lets settings be restored automatically if the bot is re-invited. - * @param {string} id - Guild / server ID - */ removeServer(id) { const timer = this._debounceTimers.get(id); if (timer) { diff --git a/src/TrackOptionsManager.mjs b/src/TrackOptionsManager.mjs index 6cb00b6..f021fcd 100644 --- a/src/TrackOptionsManager.mjs +++ b/src/TrackOptionsManager.mjs @@ -1,9 +1,17 @@ +/** + * @file TrackOptionsManager.mjs — TrackOptionsManager — SQLite-backed per-track options storage for auto-seek and end-time timers + * @module src.TrackOptionsManager + */ + import mysql from "mysql2"; import { logger } from "./constants/Logger.mjs"; const DEFAULT_ALIAS = "default"; const MAX_ALIAS_LEN = 32; +/** + * TrackOptionsManager class. + */ export class TrackOptionsManager { db = null; botId = null; @@ -194,9 +202,11 @@ export class TrackOptionsManager { this._cache.delete(`${userId}:${identifier}:${safeAlias}`); } else { sql = `DELETE FROM track_options WHERE user_id = ${mysql.escape(userId)} AND track_identifier = ${mysql.escape(identifier)}${this._botIdWhere()}`; + const keysToDelete = []; for (const key of this._cache.keys()) { - if (key.startsWith(`${userId}:${identifier}:`)) this._cache.delete(key); + if (key.startsWith(`${userId}:${identifier}:`)) keysToDelete.push(key); } + for (const key of keysToDelete) this._cache.delete(key); } const result = await this._query(sql); return result.affectedRows > 0; diff --git a/src/Utils.mjs b/src/Utils.mjs index 700a03d..715fbdc 100644 --- a/src/Utils.mjs +++ b/src/Utils.mjs @@ -1,8 +1,28 @@ /** - * Utils.mjs — Utility functions for the music bot - * @module Utils + * @file Utils.mjs — Utility class with static helpers — text normalization, markdown escaping, duration parsing, and string truncation + * @module src.Utils */ +/** + * Utils.mjs — Music bot utility functions + * @module Utils + * + * Internal helpers delegate to @fluxerjs/util where available + * (escapeMarkdown, truncate) with additional null-safety guards. + */ + +import { escapeMarkdown as _escapeMarkdown, truncate as _truncate } from "@fluxerjs/util"; + +/** + * Strip non-digit characters from a value, returning a clean ID string. + * Replaces the inline `String(x).replace(/\D/g, "")` pattern used 97+ times. + * @param {string|number} value + * @returns {string} + */ +export function cleanId(value) { + return String(value ?? "").replace(/\D/g, ""); +} + /** * @class Utils * @description Static utility methods for time formatting, array manipulation, @@ -14,8 +34,6 @@ export class Utils { * 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) - * @example Utils.prettifyMS(3661000) */ static prettifyMS(milliseconds) { if (!milliseconds || milliseconds < 0 || !isFinite(milliseconds)) { @@ -35,12 +53,17 @@ export class Utils { } /** - * Parse duration string (H:MM:SS or M:SS) to milliseconds + * Parse duration string (H:MM:SS or M:SS or raw seconds) to milliseconds. * @param {string} str - Duration string * @returns {number} Milliseconds, 0 if invalid */ static parseDuration(str) { if (!str || typeof str !== "string") return 0; + str = str.trim(); + + if (/^\d+$/.test(str)) { + return parseInt(str, 10) * 1000; + } const parts = str.split(":").map((s) => parseInt(s.trim(), 10)).reverse(); if (parts.some(isNaN) || parts.some(n => n < 0)) return 0; @@ -79,45 +102,6 @@ export class Utils { return array; } - /** - * Get random element from array - * @template T - * @param {T[]} array - Source array - * @returns {T | undefined} Random element or undefined if empty - */ - static randomElement(array) { - if (!Array.isArray(array) || array.length === 0) return undefined; - return array[Math.floor(Math.random() * array.length)]; - } - - /** - * Chunk array into smaller arrays - * @template T - * @param {T[]} array - Array to chunk - * @param {number} size - Chunk size (minimum 1) - * @returns {T[][]} Array of chunks - */ - static chunk(array, size) { - if (!Array.isArray(array)) return []; - const chunkSize = Math.max(1, Math.floor(size)); - const chunks = []; - for (let i = 0; i < array.length; i += chunkSize) { - chunks.push(array.slice(i, i + chunkSize)); - } - return chunks; - } - - /** - * Remove duplicates from array (primitive values only) - * @template T - * @param {T[]} array - Array with potential duplicates - * @returns {T[]} New array without duplicates - */ - static unique(array) { - if (!Array.isArray(array)) return []; - return [...new Set(array)]; - } - /** * Truncate text with ellipsis * @param {string} str - String to truncate @@ -171,34 +155,14 @@ export class Utils { } /** - * Sanitize string for safe filename - * @param {string} str - Input string - * @param {number} [maxLen=50] - Maximum length - * @returns {string} Safe filename - */ - static sanitizeFilename(str, maxLen = 50) { - if (!str || typeof str !== "string") return "unknown"; - return str - .replace(/[^a-z0-9\u4e00-\u9fa5]/gi, "_") - .replace(/_{2,}/g, "_") - .substring(0, maxLen) - .replace(/^_+|_+$/g, ""); - } - - /** + * Escape markdown formatting characters. + * Delegates to @fluxerjs/util escapeMarkdown. * @param {string} text - Raw text * @returns {string} Escaped text */ static escapeMarkdown(text) { if (!text || typeof text !== "string") return ""; - return text - .replace(/\\/g, "\\\\") - .replace(/`/g, "\\`") - .replace(/\*/g, "\\*") - .replace(/_/g, "\\_") - .replace(/~/g, "\\~") - .replace(/\|/g, "\\|") - .replace(/>/g, "\\>"); + return _escapeMarkdown(text); } /** @@ -211,23 +175,6 @@ export class Utils { return num.toLocaleString("en-US"); } - /** - * Format bytes to human readable (KB, MB, GB) - * @param {number} bytes - Bytes to format - * @param {number} [decimals=2] - Decimal places - * @returns {string} Human readable size - */ - static formatBytes(bytes, decimals = 2) { - if (bytes === 0) return "0 Bytes"; - if (!bytes || bytes < 0 || !isFinite(bytes)) return "Unknown"; - - const k = 1024; - const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB"]; - const i = Math.min(Math.floor(Math.log(bytes) / Math.log(k)), sizes.length - 1); - - return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${sizes[i]}`; - } - /** * Generate random unique ID * @param {number} [length=16] - Desired length of ID (8-32 recommended) @@ -246,18 +193,6 @@ export class Utils { return (timestamp + random).substring(0, targetLen); } - /** - * Generate UUID v4 (RFC4122 compliant) - * @returns {string} UUID string - */ - static uuid() { - return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => { - const r = (Math.random() * 16) | 0; - const v = c === "x" ? r : (r & 0x3) | 0x8; - return v.toString(16); - }); - } - /** * Check if a value represents a finite number * @param {string|number} str @@ -298,22 +233,6 @@ export class Utils { return Math.max(min, Math.min(max, num)); } - /** - * Safe JSON parse with fallback - * @template T - * @param {string} str - JSON string - * @param {T} [fallback=null] - Fallback value on error - * @returns {T | null} Parsed object or fallback - */ - static safeJsonParse(str, fallback = null) { - if (!str || typeof str !== "string") return fallback; - try { - return JSON.parse(str); - } catch { - return fallback; - } - } - /** * Sleep/delay promise * @param {number} ms - Milliseconds to sleep @@ -323,34 +242,6 @@ export class Utils { return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms))); } - /** - * Retry an async operation with exponential backoff - * @template T - * @param {() => Promise} fn - Function to retry - * @param {number} [attempts=3] - Max retry attempts - * @param {number} [delay=1000] - Initial delay in ms - * @param {number} [backoff=2] - Backoff multiplier - * @returns {Promise} - */ - static async retry(fn, attempts = 3, delay = 1000, backoff = 2) { - if (typeof fn !== "function") { - throw new TypeError("First argument must be a function"); - } - - let lastError; - for (let i = 0; i < attempts; i++) { - try { - return await fn(); - } catch (err) { - lastError = err; - if (i < attempts - 1) { - await this.sleep(delay * Math.pow(backoff, i)); - } - } - } - throw lastError; - } - /** * Timeout wrapper for promises * @template T @@ -367,53 +258,6 @@ export class Utils { return Promise.race([promise, timeoutPromise]).finally(() => clearTimeout(timerId)); } - /** - * Deep clone an object (JSON method - not suitable for circular refs) - * @template T - * @param {T} obj - Object to clone - * @returns {T} Cloned object - */ - static deepClone(obj) { - if (obj === null || typeof obj !== "object") return obj; - try { - return JSON.parse(JSON.stringify(obj)); - } catch { - return obj; - } - } - - /** - * Pick specific keys from object - * @template T, K - * @param {T} obj - Source object - * @param {K[]} keys - Keys to pick - * @returns {Pick} New object with picked keys - */ - static pick(obj, keys) { - if (!obj || typeof obj !== "object") return {}; - const result = {}; - for (const key of keys) { - if (key in obj) result[key] = obj[key]; - } - return result; - } - - /** - * Omit specific keys from object - * @template T, K - * @param {T} obj - Source object - * @param {K[]} keys - Keys to omit - * @returns {Omit} New object without omitted keys - */ - static omit(obj, keys) { - if (!obj || typeof obj !== "object") return {}; - const result = { ...obj }; - for (const key of keys) { - delete result[key]; - } - return result; - } - /** * Create progress bar string * @param {number} current - Current position in ms or 0-1 ratio @@ -498,4 +342,22 @@ export class Utils { return (hours * 3600 + minutes * 60 + seconds) * 1000; } -} \ No newline at end of file + + /** + * Normalize text for fuzzy matching: NFKD, strip non-word chars, collapse whitespace, lowercase. + * Replaces the duplicated normalizeMatchText / normalizeTrackText functions. + * @param {string} value - Raw text to normalize + * @param {boolean} [cleanFirst=false] - Run cleanTitle() first (for worker.mjs title matching) + * @returns {string} Normalized text + */ + static normalizeText(value, cleanFirst = false) { + let text = String(value ?? ""); + if (cleanFirst) text = this.cleanTitle(text); + return text + .normalize("NFKD") + .replace(/[^\w\s]+/g, " ") + .replace(/\s+/g, " ") + .trim() + .toLowerCase(); + } +} diff --git a/src/constants/API.mjs b/src/constants/API.mjs index dbd7e39..2739c4e 100644 --- a/src/constants/API.mjs +++ b/src/constants/API.mjs @@ -1,3 +1,8 @@ +/** + * @file API.mjs — API constants — FluxerList API endpoints, authentication headers, pagination defaults, and cache TTL values + * @module src.constants.API + */ + /** * API.mjs — Single source of truth for all external API constants. * @@ -90,25 +95,14 @@ export function buildFluxerListUrl(endpoint, resourceId, queryParams = {}) { } /** - * Build the vote link for a resource on FluxerList. + * Build the vote/profile link for a resource on FluxerList. + * Both vote and profile links share the same URL pattern. * * @param {"server"|"bot"} type - Resource type * @param {string} resourceId - The server or bot ID or slug - * @returns {string} URL to the vote page on FluxerList + * @returns {string} URL to the resource page on FluxerList */ export function buildVoteLink(type, resourceId) { const path = type === "server" ? "servers" : "bots"; return `${FLUXERLIST.SITE_URL}/${path}/${resourceId}`; } - -/** - * Build the profile link for a resource on FluxerList. - * - * @param {"server"|"bot"} type - Resource type - * @param {string} resourceId - The server or bot ID or slug - * @returns {string} URL to the profile page on FluxerList - */ -export function buildProfileLink(type, resourceId) { - const path = type === "server" ? "servers" : "bots"; - return `${FLUXERLIST.SITE_URL}/${path}/${resourceId}`; -} diff --git a/src/constants/FluxerRevoice.mjs b/src/constants/FluxerRevoice.mjs index 593270e..147ec8b 100644 --- a/src/constants/FluxerRevoice.mjs +++ b/src/constants/FluxerRevoice.mjs @@ -1,3 +1,8 @@ +/** + * @file FluxerRevoice.mjs — FluxerRevoice — voice connection adapter that bridges Fluxer gateway with LiveKit rooms, replacing revoice.js API calls + * @module src.constants.FluxerRevoice + */ + /** * FluxerRevoice.mjs — Revoice-compatible adapter that uses the Fluxer API * @@ -42,55 +47,51 @@ export const LKRoomEvent = Object.freeze({ ParticipantDisconnected:"participantDisconnected", }); -/** @deprecated Use LKRoomEvent instead — kept for backward compat within this file */ -const RoomEvent = LKRoomEvent; - import { logger } from "./Logger.mjs"; -{ - if (!globalThis.__fluxerLiveKitLogPatchApplied) { - globalThis.__fluxerLiveKitLogPatchApplied = true; +/** + * LiveKit log filter — intercepts LiveKit SDK noise without monkey-patching + * console.log or process.stdout globally. Applied per-room by setting + * the room's logger to a filtered version. + */ +const LIVEKIT_LOG_PREFIXES = ["[voice LiveKitRtc]", "lk-rtc"]; - const _originalConsoleLog = console.log; - console.log = function (...args) { - if (args.length === 1 && typeof args[0] === "string" && args[0].startsWith("{")) { - try { - const parsed = JSON.parse(args[0]); - if (parsed.name === "lk-rtc") return; - } catch (_) { - } - } - if (args.length >= 1 && typeof args[0] === "string" && args[0].includes("[voice LiveKitRtc]")) { - return; - } - _originalConsoleLog.apply(console, args); - }; +function isLiveKitLogMessage(...args) { + if (args.length === 1 && typeof args[0] === "string") { + if (args[0].startsWith("{")) { + try { + const parsed = JSON.parse(args[0]); + if (parsed.name === "lk-rtc") return true; + } catch (_e) { } + } + if (LIVEKIT_LOG_PREFIXES.some(p => args[0].includes(p))) return true; + } + return false; +} - const _originalStdoutWrite = process.stdout.write.bind(process.stdout); - process.stdout.write = function (chunk, encoding, callback) { - if (typeof chunk === "string" && chunk.startsWith("{")) { - try { - if (chunk.includes('"lk-rtc"')) { - const parsed = JSON.parse(chunk); - if (parsed.name === "lk-rtc") { - if (typeof encoding === "function") { encoding(); } - else if (typeof callback === "function") { callback(); } - return true; - } - } - } catch (_) { - } - } - return _originalStdoutWrite(chunk, encoding, callback); - }; +/** + * Temporarily suppress LiveKit SDK log noise during room setup. + * Unlike the old global monkey-patch, this is scoped to a callback + * and restores the original console.log when done. + */ +function withSuppressedLiveKitLogs(fn) { + const origLog = console.log; + console.log = function (...args) { + if (isLiveKitLogMessage(...args)) return; + origLog.apply(console, args); + }; + try { + return fn(); + } finally { + console.log = origLog; } } /** 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"; + if (cs === ConnectionState.CONN_CONNECTED) return "CONN_CONNECTED"; + if (cs === ConnectionState.CONN_DISCONNECTED) return "CONN_DISCONNECTED"; + if (cs === ConnectionState.CONN_RECONNECTING) return "CONN_RECONNECTING"; if (cs === 1) return "CONN_CONNECTED(1)"; if (cs === 0) return "CONN_DISCONNECTED(0)"; if (cs === 2) return "CONN_RECONNECTING(2)"; @@ -176,6 +177,7 @@ export class FluxerVoiceConnection extends EventEmitter { try { await this.room.disconnect(); } catch (e) { + logger.warn("[FluxerVoiceConnection] Room disconnect error:", e?.message); } } else if (this._nativeConn && typeof this._nativeConn.disconnect === "function") { try { @@ -228,6 +230,9 @@ export class FluxerRevoice extends EventEmitter { /** @type {Set} Channel IDs where disconnect is expected (bot-initiated) */ _intentionalDisconnects = new Set(); + /** @type {Map} Per-channel timeout tokens for intentional disconnect marks */ + _intentionalDisconnectTokens = new Map(); + /** @type {FluxerRevoice|null} Singleton instance */ static _instance = null; @@ -245,28 +250,31 @@ export class FluxerRevoice extends EventEmitter { constructor(client) { super(); - if (FluxerRevoice._instance) { + if (FluxerRevoice._instance && FluxerRevoice._instance !== this) { logger.warn( - `[FluxerRevoice] Duplicate instance creation detected! ` + - `Use FluxerRevoice.getInstance() instead of new FluxerRevoice(). ` + - `Stack: ${new Error().stack?.split('\n').slice(2, 5).join(' | ')}` + `[FluxerRevoice] Duplicate instance detected! Use FluxerRevoice.getInstance().` ); - } else { - FluxerRevoice._instance = this; } if (!client) throw new Error("FluxerRevoice requires a Fluxer client instance"); this.client = client; + if (!FluxerRevoice._instance) FluxerRevoice._instance = this; logger.player("[FluxerRevoice] Instance created with Fluxer client."); } /** * Mark a channel as expecting an intentional disconnect so the - * RoomEvent.Disconnected handler can log it correctly. + * LKRoomEvent.Disconnected handler can log it correctly. * @param {string} channelId */ markIntentionalDisconnect(channelId) { - this._intentionalDisconnects.add(String(channelId)); - setTimeout(() => this._intentionalDisconnects.delete(String(channelId)), 10_000); + const key = String(channelId); + this._intentionalDisconnects.add(key); + const prev = this._intentionalDisconnectTokens.get(key); + if (prev) clearTimeout(prev); + this._intentionalDisconnectTokens.set(key, setTimeout(() => { + this._intentionalDisconnects.delete(key); + this._intentionalDisconnectTokens.delete(key); + }, 10_000)); } /** @@ -341,7 +349,8 @@ export class FluxerRevoice extends EventEmitter { if (existing.room) { try { await existing.room.disconnect(); - } catch (_) { + } catch (e) { + logger.warn("[FluxerRevoice] Stale room disconnect error:", e?.message); } } else if (existing._nativeConn && typeof existing._nativeConn.disconnect === "function") { try { @@ -353,7 +362,7 @@ export class FluxerRevoice extends EventEmitter { existing._destroyed = true; existing._connected = false; - try { existing.removeAllListeners(); } catch (_) {} + try { existing.removeAllListeners(); } catch (e) { } } /** @@ -375,7 +384,9 @@ export class FluxerRevoice extends EventEmitter { const prevQueue = this._globalJoinQueue; const ourResult = prevQueue.then(() => joinOperation()); - this._globalJoinQueue = ourResult.catch(() => {}); + this._globalJoinQueue = ourResult.catch((err) => { + logger.warn("[FluxerRevoice] Previous join in queue failed:", err?.message ?? err); + }); return await ourResult; } @@ -392,7 +403,9 @@ export class FluxerRevoice extends EventEmitter { try { const ch = this.client.channels?.get?.(channelId); guildId = ch?.guildId ?? ch?.guild?.id ?? null; - } catch (_) {} + } catch (e) { + logger.debug("[FluxerRevoice] Could not resolve guild for channel:", e?.message); + } if (this.connections.has(channelId)) { const existing = this.connections.get(channelId); @@ -444,8 +457,22 @@ export class FluxerRevoice extends EventEmitter { logger.player(`[FluxerRevoice] Got LiveKit room from native connection (isConnected: ${room.isConnected}, connectionState: ${stateLabel(room.connectionState)})`); } + + if (room && typeof room.setLogger === "function") { + try { + room.setLogger({ + debug: () => {}, + info: () => {}, + warn: (...args) => { if (!isLiveKitLogMessage(...args)) logger.warn("[LiveKit]", ...args); }, + error: (...args) => logger.error("[LiveKit]", ...args), + }); + } catch (_e) { } + } + if (!room) { - try { await nativeConnection.disconnect(); } catch (_) {} + try { await nativeConnection.disconnect(); } catch (e) { + logger.warn("[FluxerRevoice] Cleanup disconnect error:", e?.message); + } throw new Error( `Fluxer voice connection for ${channelId} does not expose a LiveKit Room. ` + `Music playback requires a LiveKit-based voice server.` @@ -460,17 +487,17 @@ export class FluxerRevoice extends EventEmitter { const statePromise = new Promise((resolve) => { const handler = (cs) => { if (eventResolved) return; - if (cs === ConnectionState?.CONN_CONNECTED || cs === 1) { + if (cs === ConnectionState.CONN_CONNECTED || cs === 1) { eventResolved = true; - room.off(RoomEvent.ConnectionStateChanged, handler); + room.off(LKRoomEvent.ConnectionStateChanged, handler); resolve(); - } else if (cs === ConnectionState?.CONN_DISCONNECTED || cs === 0) { + } else if (cs === ConnectionState.CONN_DISCONNECTED || cs === 0) { eventResolved = true; - room.off(RoomEvent.ConnectionStateChanged, handler); + room.off(LKRoomEvent.ConnectionStateChanged, handler); resolve(); } }; - room.on(RoomEvent.ConnectionStateChanged, handler); + room.on(LKRoomEvent.ConnectionStateChanged, handler); }); while (!room.isConnected && (Date.now() - startTime) < maxWait) { @@ -482,88 +509,97 @@ export class FluxerRevoice extends EventEmitter { if (room.isConnected) break; const cs = room.connectionState; - if (cs === ConnectionState?.CONN_DISCONNECTED || cs === 0) break; + if (cs === ConnectionState.CONN_DISCONNECTED || cs === 0) break; } } const finalConnected = room.isConnected; const finalCS = room.connectionState; - if (!finalConnected && (finalCS === ConnectionState?.CONN_DISCONNECTED || finalCS === 0)) { - try { await nativeConnection.disconnect(); } catch (_) {} + if (!finalConnected && (finalCS === ConnectionState.CONN_DISCONNECTED || finalCS === 0)) { + try { await nativeConnection.disconnect(); } catch (e) { + logger.warn("[FluxerRevoice] Cleanup disconnect error:", e?.message); + } throw new Error(`LiveKit room in disconnected state: ${stateLabel(finalCS)}`); } logger.player(`[FluxerRevoice] LiveKit room ready (isConnected: ${finalConnected}, connectionState: ${stateLabel(finalCS)})`); - const connection = new FluxerVoiceConnection(channelId, this, { - room, - nativeConnection, - }); - room.on(RoomEvent.ConnectionStateChanged, (cs) => { - if (cs === ConnectionState.CONN_RECONNECTING || cs === 2) { - logger.player(`[FluxerRevoice] Room reconnecting for channel ${channelId}`); - } else if (cs === ConnectionState.CONN_CONNECTED || cs === 1) { - if (connection._destroyed) return; - connection._connected = true; - logger.player(`[FluxerRevoice] Room (re)connected for channel ${channelId}`); - } - }); + const connection = withSuppressedLiveKitLogs(() => { + const conn = new FluxerVoiceConnection(channelId, this, { + room, + nativeConnection, + }); - room.on(RoomEvent.Disconnected, (reason) => { - const isIntentional = this._intentionalDisconnects.has(String(channelId)); - const reasonLabel = isIntentional ? "intentional" : (reason ?? "unexpected"); - logger.player(`[FluxerRevoice] Room disconnected: ${reasonLabel}`); - this._intentionalDisconnects.delete(String(channelId)); - connection._connected = false; - connection._destroyed = true; - - this.connections.delete(channelId); - - if (!isIntentional) { - this._leaveGateway(channelId, channelGuildId); - - if (nativeConnection && typeof nativeConnection.disconnect === "function") { - try { nativeConnection.disconnect(); } catch (_) {} - } - } - - connection.emit("disconnect"); - }); - - 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 }); - connection._users = [...this.users.values()].filter(u => u.connectedTo === channelId); - connection.emit("userjoin", userId); - } - }); - - room.on(RoomEvent.ParticipantDisconnected, (participant) => { - const userId = participant?.identity ?? participant?.sid; - if (userId) { - const uKey = `${channelId}:${userId}`; - this.users.delete(uKey); - connection._users = [...this.users.values()].filter(u => u.connectedTo === channelId); - connection.emit("userleave", userId); - } - }); - - this.connections.set(channelId, connection); - - if (_leaveIfEmpty) { - connection.on("userleave", () => { - const remoteCount = room.remoteParticipants?.size ?? 0; - if (remoteCount === 0) { - logger.player(`[FluxerRevoice] Room empty, triggering autoleave for ${channelId}`); - connection.emit("autoleave"); - this.connections.delete(channelId); + room.on(LKRoomEvent.ConnectionStateChanged, (cs) => { + if (cs === ConnectionState.CONN_RECONNECTING || cs === 2) { + logger.player(`[FluxerRevoice] Room reconnecting for channel ${channelId}`); + } else if (cs === ConnectionState.CONN_CONNECTED || cs === 1) { + if (conn._destroyed) return; + conn._connected = true; + logger.player(`[FluxerRevoice] Room (re)connected for channel ${channelId}`); } }); - } + + room.on(LKRoomEvent.Disconnected, (reason) => { + const isIntentional = this._intentionalDisconnects.has(String(channelId)); + const reasonLabel = isIntentional ? "intentional" : (reason ?? "unexpected"); + logger.player(`[FluxerRevoice] Room disconnected: ${reasonLabel}`); + this._intentionalDisconnects.delete(String(channelId)); + conn._connected = false; + conn._destroyed = true; + + this.connections.delete(channelId); + + if (!isIntentional) { + this._leaveGateway(channelId, channelGuildId); + + if (nativeConnection && typeof nativeConnection.disconnect === "function") { + try { nativeConnection.disconnect(); } catch (e) { + logger.warn("[FluxerRevoice] Native disconnect error:", e?.message); + } + } + } + + conn.emit("disconnect"); + }); + + room.on(LKRoomEvent.ParticipantConnected, (participant) => { + const userId = participant?.identity ?? participant?.sid; + if (userId) { + const uKey = `${channelId}:${userId}`; + this.users.set(uKey, { id: userId, connectedTo: channelId }); + conn._users = [...this.users.values()].filter(u => u.connectedTo === channelId); + conn.emit("userjoin", userId); + } + }); + + room.on(LKRoomEvent.ParticipantDisconnected, (participant) => { + const userId = participant?.identity ?? participant?.sid; + if (userId) { + const uKey = `${channelId}:${userId}`; + this.users.delete(uKey); + conn._users = [...this.users.values()].filter(u => u.connectedTo === channelId); + conn.emit("userleave", userId); + } + }); + + this.connections.set(channelId, conn); + + if (_leaveIfEmpty) { + conn.on("userleave", () => { + const remoteCount = room.remoteParticipants?.size ?? 0; + if (remoteCount === 0) { + logger.player(`[FluxerRevoice] Room empty, triggering autoleave for ${channelId}`); + conn.emit("autoleave"); + this.connections.delete(channelId); + } + }); + } + + return conn; + }); return connection; } diff --git a/src/constants/Helpers247.mjs b/src/constants/Helpers247.mjs index b75ce70..d4d277a 100644 --- a/src/constants/Helpers247.mjs +++ b/src/constants/Helpers247.mjs @@ -1,3 +1,8 @@ +/** + * @file Helpers247.mjs — Helpers247 — per-channel 24/7 mode management (on/auto/off) with guild-wide backward compatibility + * @module src.constants.Helpers247 + */ + /** * Shared 24/7 mode helpers. * diff --git a/src/constants/Locale.mjs b/src/constants/Locale.mjs index 1a0a3b1..b01a98f 100644 --- a/src/constants/Locale.mjs +++ b/src/constants/Locale.mjs @@ -1,3 +1,8 @@ +/** + * @file Locale.mjs — Locale — i18n system loading JSON locale files with per-guild language settings and template variable interpolation + * @module src.constants.Locale + */ + import { readFileSync, readdirSync, existsSync } from "fs"; import path from "path"; import { fileURLToPath } from "url"; @@ -108,7 +113,7 @@ export class Locale { code = setting; } } - } catch (_) {} + } catch(e) { } const data = this.locales.get(code) ?? this.locales.get(this.defaultLocale) ?? {}; this._resolved.set(guildId, data); @@ -156,8 +161,8 @@ export class Locale { const prefix = serverSettings.get("prefix"); if (prefix) return prefix; } - } catch (_) {} - return "%"; + } catch(e) { } + return this._defaultPrefix || "!"; } /** diff --git a/src/constants/Logger.mjs b/src/constants/Logger.mjs index 6b2a68b..9d79da6 100644 --- a/src/constants/Logger.mjs +++ b/src/constants/Logger.mjs @@ -1,3 +1,8 @@ +/** + * @file Logger.mjs — Logger — categorized logging (info, warn, error, voice, player) with timestamp formatting and module prefixes + * @module src.constants.Logger + */ + /** * Logger — configurable console output for Fluxer. * diff --git a/src/constants/UI.mjs b/src/constants/UI.mjs new file mode 100644 index 0000000..6eb7f85 --- /dev/null +++ b/src/constants/UI.mjs @@ -0,0 +1,45 @@ +/** + * @file UI.mjs — UI constants — shared color values, emoji arrays, timeout durations, and volume limits used across commands and embeds + * @module src.constants.UI + */ + +/** + * UI.mjs — Shared UI constants used across commands and embeds. + * + * Centralises emoji arrays, timeout values, and colour constants + * that were previously duplicated across many command files. + */ + +/** Error embed colour — used everywhere instead of hardcoding "#ff0000". */ +export const ERROR_COLOR = "#ff0000"; + +/** Warning/highlight colour for diagnostic and debug embeds. */ +export const WARN_COLOR = 0xFFAA00; + +/** Success colour for diagnostic embeds. */ +export const SUCCESS_COLOR = 0x00CC66; + +/** Failure/danger colour for diagnostic embeds (same as ERROR_COLOR but numeric). */ +export const DANGER_COLOR = 0xFF4444; + +/** Default timeout (ms) before removing navigation reactions from embeds. */ +export const EMOJI_REMOVE_TIMEOUT = 60_000; + +/** Default inactivity timeout (ms) for interactive embed sessions. */ +export const SESSION_TIMEOUT = 30_000; + +/** Number emojis for search/radio selection menus. */ +export const NUMBER_EMOJIS = [ + "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", + "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟", +]; + +/** Cancel emoji for selection menus. */ +export const CANCEL_EMOJI = "❌"; + +/** Navigation emojis for paginated embeds. */ +export const PREV_EMOJI = "⬅️"; +export const NEXT_EMOJI = "➡️"; + +/** Maximum allowed volume percentage. */ +export const MAX_VOLUME = 200; diff --git a/src/constants/VoiceStateCache.mjs b/src/constants/VoiceStateCache.mjs index 7fd5585..5220f65 100644 --- a/src/constants/VoiceStateCache.mjs +++ b/src/constants/VoiceStateCache.mjs @@ -1,3 +1,8 @@ +/** + * @file VoiceStateCache.mjs — VoiceStateCache — O(1) composite-keyed LRU cache for voice state lookups with dual indexes (user→channel, channel→users) + * @module src.constants.VoiceStateCache + */ + /** * VoiceStateCache — O(1) voice-state lookups with bounded memory. * @@ -20,7 +25,11 @@ */ import { logger } from "./Logger.mjs"; +import { cleanId } from "../Utils.mjs"; +/** + * VoiceStateCache class. + */ export class VoiceStateCache { /** * @param {object} [opts] @@ -48,12 +57,12 @@ export class VoiceStateCache { /** Build composite key "guildId:userId" (both cleaned to digits only) */ static userKey(guildId, userId) { - return `${String(guildId ?? "").replace(/\D/g, "")}:${String(userId ?? "").replace(/\D/g, "")}`; + return `${cleanId(guildId)}:${cleanId(userId)}`; } /** Build composite key "guildId:channelId" (both cleaned to digits only) */ static channelKey(guildId, channelId) { - return `${String(guildId ?? "").replace(/\D/g, "")}:${String(channelId ?? "").replace(/\D/g, "")}`; + return `${cleanId(guildId)}:${cleanId(channelId)}`; } /** @@ -66,9 +75,9 @@ export class VoiceStateCache { * @param {boolean} [params.isBot=false] */ updateUser({ guildId, userId, channelId, isBot = false }) { - const cleanGuild = String(guildId ?? "").replace(/\D/g, ""); - const cleanUser = String(userId ?? "").replace(/\D/g, ""); - const cleanChannel = channelId ? String(channelId).replace(/\D/g, "") : null; + const cleanGuild = cleanId(guildId); + const cleanUser = cleanId(userId); + const cleanChannel = channelId ? cleanId(channelId) : null; if (!cleanGuild || !cleanUser) return; const locations = isBot ? this.botLocations : this.userLocations; @@ -228,33 +237,48 @@ export class VoiceStateCache { * @param {string} guildId */ removeGuild(guildId) { - const cleanGuild = String(guildId).replace(/\D/g, ""); + const cleanGuild = cleanId(guildId); const prefix = cleanGuild + ":"; + + const userKeysToRemove = []; for (const [uKey, loc] of this.userLocations) { - if (uKey.startsWith(prefix)) { + if (uKey.startsWith(prefix)) userKeysToRemove.push(uKey); + } + for (const uKey of userKeysToRemove) { + const loc = this.userLocations.get(uKey); + if (loc) { const cKey = VoiceStateCache.channelKey(loc.guildId, loc.channelId); const set = this.channelMembers.get(cKey); if (set) { set.delete(loc.userId); if (set.size === 0) this.channelMembers.delete(cKey); } - this.userLocations.delete(uKey); } + this.userLocations.delete(uKey); } - for (const [cKey, set] of this.channelMembers) { - if (cKey.startsWith(prefix)) this.channelMembers.delete(cKey); + const channelKeysToRemove = []; + for (const [cKey] of this.channelMembers) { + if (cKey.startsWith(prefix)) channelKeysToRemove.push(cKey); } + for (const cKey of channelKeysToRemove) this.channelMembers.delete(cKey); this._lruUserKeys = this._lruUserKeys.filter(k => !k.startsWith(prefix)); + const botKeysToRemove = []; for (const [uKey, loc] of this.botLocations) { - if (uKey.startsWith(prefix)) { + if (uKey.startsWith(prefix)) botKeysToRemove.push(uKey); + } + for (const uKey of botKeysToRemove) { + const loc = this.botLocations.get(uKey); + if (loc) { const cKey = VoiceStateCache.channelKey(loc.guildId, loc.channelId); const set = this.botChannelMembers.get(cKey); if (set) { set.delete(loc.userId); if (set.size === 0) this.botChannelMembers.delete(cKey); } - this.botLocations.delete(uKey); } + this.botLocations.delete(uKey); } - for (const [cKey, set] of this.botChannelMembers) { - if (cKey.startsWith(prefix)) this.botChannelMembers.delete(cKey); + const botChannelKeysToRemove = []; + for (const [cKey] of this.botChannelMembers) { + if (cKey.startsWith(prefix)) botChannelKeysToRemove.push(cKey); } + for (const cKey of botChannelKeysToRemove) this.botChannelMembers.delete(cKey); this._lruBotKeys = this._lruBotKeys.filter(k => !k.startsWith(prefix)); } @@ -272,7 +296,7 @@ export class VoiceStateCache { for (const userId of humanSet) { const uKey = VoiceStateCache.userKey(guildId, userId); const loc = this.userLocations.get(uKey); - if (loc && loc.channelId === String(channelId).replace(/\D/g, "")) { + if (loc && loc.channelId === cleanId(channelId)) { this.userLocations.delete(uKey); } } @@ -284,7 +308,7 @@ export class VoiceStateCache { for (const userId of botSet) { const uKey = VoiceStateCache.userKey(guildId, userId); const loc = this.botLocations.get(uKey); - if (loc && loc.channelId === String(channelId).replace(/\D/g, "")) { + if (loc && loc.channelId === cleanId(channelId)) { this.botLocations.delete(uKey); } } @@ -301,7 +325,7 @@ export class VoiceStateCache { * @param {boolean} [botsOnly=false] Only purge bot entries */ purgeUsersInGuild(guildId, userIds, botsOnly = false) { - const cleanGuild = String(guildId).replace(/\D/g, ""); + const cleanGuild = cleanId(guildId); if (!botsOnly) { for (const userId of userIds) { @@ -375,7 +399,7 @@ export class VoiceStateCache { if (guildId) { return this.userLocations.get(VoiceStateCache.userKey(guildId, userId)); } - const cleanUser = String(userId).replace(/\D/g, ""); + const cleanUser = cleanId(userId); for (const [uKey, loc] of this.userLocations) { if (loc.userId === cleanUser) return { channelId: loc.channelId, guildId: loc.guildId }; } @@ -422,7 +446,7 @@ export class VoiceStateCache { if (guildId) { this.updateUser({ guildId, userId, channelId: null, isBot: false }); } else { - const cleanUser = String(userId).replace(/\D/g, ""); + const cleanUser = cleanId(userId); for (const [uKey, loc] of this.userLocations) { if (loc.userId === cleanUser) { this.updateUser({ guildId: loc.guildId, userId: cleanUser, channelId: null, isBot: false }); @@ -458,7 +482,7 @@ export class VoiceStateCache { if (guildId) { return this.userLocations.has(VoiceStateCache.userKey(guildId, userId)); } - const cleanUser = String(userId).replace(/\D/g, ""); + const cleanUser = cleanId(userId); for (const [uKey, loc] of this.userLocations) { if (loc.userId === cleanUser) return true; } @@ -504,7 +528,7 @@ export class VoiceStateCache { if (guildId !== undefined) { return this.userLocations.has(VoiceStateCache.userKey(guildId, userId)); } - const cleanUser = String(userId).replace(/\D/g, ""); + const cleanUser = cleanId(userId); for (const [, loc] of this.userLocations) { if (loc.userId === cleanUser) return true; } @@ -525,7 +549,7 @@ export class VoiceStateCache { const loc = this.userLocations.get(VoiceStateCache.userKey(guildId, userId)); return loc ? { channelId: loc.channelId, guildId: loc.guildId } : undefined; } - const cleanUser = String(userId).replace(/\D/g, ""); + const cleanUser = cleanId(userId); for (const [, loc] of this.userLocations) { if (loc.userId === cleanUser) return { channelId: loc.channelId, guildId: loc.guildId }; } @@ -556,7 +580,7 @@ export class VoiceStateCache { if (guildId !== undefined) { this.updateUser({ guildId, userId, channelId: null, isBot: false }); } else { - const cleanUser = String(userId).replace(/\D/g, ""); + const cleanUser = cleanId(userId); const toRemove = []; for (const [uKey, loc] of this.userLocations) { if (loc.userId === cleanUser) toRemove.push(loc); diff --git a/src/constants/VoiceStateResolver.mjs b/src/constants/VoiceStateResolver.mjs new file mode 100644 index 0000000..155e6e3 --- /dev/null +++ b/src/constants/VoiceStateResolver.mjs @@ -0,0 +1,157 @@ +/** + * @file VoiceStateResolver.mjs — VoiceStateResolver — unified voice state enumeration across Map/Array/Object guild voice_states with human-detection fallbacks + * @module src.constants.VoiceStateResolver + */ + +/** + * VoiceStateResolver.mjs — Unified voice state enumeration. + * + * Eliminates the 12+ duplicated voice-state-iteration blocks scattered + * across Player.mjs, PlayerManager.mjs, GatewayHandler.mjs, and Dashboard.mjs. + * + * Fluxer's guild.voice_states can be a Map, an Array, or a plain Object + * depending on the client version and cache state. This module normalises + * all three into a single iteration interface. + */ + +import { logger } from "./Logger.mjs"; + +/** + * Iterate over all voice states for a guild, yielding objects with + * { userId, channelId, isBot } regardless of the underlying data structure. + * + * @param {import("@fluxerjs/core").Guild} guild + * @yields {{ userId: string, channelId: string, isBot: boolean }} + */ +export function* iterateVoiceStates(guild) { + if (!guild) return; + + const voiceStates = guild.voice_states; + if (!voiceStates) return; + + let entries; + try { + if (Array.isArray(voiceStates)) { + entries = voiceStates; + } else if (typeof voiceStates.values === "function") { + entries = voiceStates.values(); + } else if (typeof voiceStates[Symbol.iterator] === "function") { + entries = voiceStates; + } else { + entries = Object.values(voiceStates); + } + } catch (e) { + logger.warn("[VoiceStateResolver] Failed to enumerate voice states:", e?.message); + return; + } + + for (const state of entries) { + if (!state) continue; + const userId = state.userId ?? state.user_id; + const channelId = state.channelId ?? state.channel_id; + if (!userId || !channelId) continue; + + const member = guild.members?.get?.(userId); + const isBot = member?.user?.bot ?? false; + + yield { userId: String(userId), channelId: String(channelId), isBot }; + } +} + +/** + * Check whether a guild's voice channel contains any non-bot users. + * Uses three fallback strategies: VoiceStateCache, guild.voice_states, + * and LiveKit remote participants. + * + * @param {object} opts + * @param {string} opts.guildId - Clean guild ID + * @param {string} opts.channelId - Clean channel ID + * @param {object} [opts.client] - Fluxer client (for guild cache) + * @param {object} [opts.voiceCache] - VoiceStateCache instance + * @param {Map} [opts.observedVoiceUsers] - Observed voice users map + * @param {object} [opts.room] - LiveKit Room (for remote participants) + * @param {string} [opts.botId] - Bot user ID (to exclude from LiveKit check) + * @returns {boolean} + */ +export function hasHumansInChannel({ guildId, channelId, client, voiceCache, observedVoiceUsers, room, botId }) { + if (!channelId || !guildId) return false; + + + if (voiceCache && typeof voiceCache.hasHumansInChannel === "function") { + if (voiceCache.hasHumansInChannel(guildId, channelId)) return true; + } + + + if (observedVoiceUsers) { + try { + const iterator = typeof observedVoiceUsers.iterateHumanUsers === "function" + ? observedVoiceUsers.iterateHumanUsers() + : observedVoiceUsers.entries(); + + for (const [, info] of iterator) { + const gId = String(info.guildId ?? ""); + const cId = String(info.channelId ?? ""); + if (gId === guildId && cId === channelId) return true; + } + } catch (e) { + logger.warn("[VoiceStateResolver] ObservedVoiceUsers check failed:", e?.message); + } + } + + + if (client) { + try { + const guild = client.guilds?.get?.(guildId); + if (guild) { + for (const vs of iterateVoiceStates(guild)) { + if (vs.channelId === channelId && !vs.isBot) return true; + } + } + } catch (e) { + logger.warn("[VoiceStateResolver] Guild voice_states check failed:", e?.message); + } + } + + + if (room?.isConnected && room.remoteParticipants) { + try { + for (const [, participant] of room.remoteParticipants) { + const pId = participant?.identity || participant?.sid; + if (pId && pId !== botId) return true; + } + } catch (e) { + logger.warn("[VoiceStateResolver] LiveKit participants check failed:", e?.message); + } + } + + return false; +} + +/** + * Get all channel IDs that have at least one human user in voice. + * + * @param {import("@fluxerjs/core").Guild} guild + * @returns {Set} Set of channel IDs with human users + */ +export function getChannelsWithHumans(guild) { + const channels = new Set(); + for (const vs of iterateVoiceStates(guild)) { + if (!vs.isBot) channels.add(vs.channelId); + } + return channels; +} + +/** + * Get all user IDs in a specific voice channel (including bots). + * + * @param {import("@fluxerjs/core").Guild} guild + * @param {string} channelId + * @returns {string[]} + */ +export function getUsersInChannel(guild, channelId) { + const users = []; + for (const vs of iterateVoiceStates(guild)) { + if (vs.channelId === channelId) users.push(vs.userId); + } + return users; +} diff --git a/src/constants/providers.mjs b/src/constants/providers.mjs index 4c528dd..c7cc386 100644 --- a/src/constants/providers.mjs +++ b/src/constants/providers.mjs @@ -1,3 +1,8 @@ +/** + * @file providers.mjs — Music provider definitions — source names, emoji icons, choice lists, and inline provider parsing for search commands + * @module src.constants.providers + */ + /** * providers.mjs — Single source of truth for all provider data. * @@ -98,3 +103,18 @@ export const PROVIDER_CHOICES = [ "ytrec", "sprec", "dzrec", "tdrec", "jsrec", "vkrec", "gtts", "tts", "ftts", ]; + +/** + * Parse an inline provider prefix from a query string (e.g. "sp: song name"). + * @param {string} raw + * @returns {{ provider: string|null, query: string }} + */ +export function parseInlineProvider(raw) { + const match = raw.match(/^([a-z]+):\s*(.+)$/i); + if (!match) return { provider: null, query: raw.trim() }; + const maybeProvider = match[1].toLowerCase(); + if (PROVIDER_CHOICES.includes(maybeProvider)) { + return { provider: maybeProvider, query: match[2].trim() }; + } + return { provider: null, query: raw.trim() }; +} diff --git a/src/dashboard/Dashboard.mjs b/src/dashboard/Dashboard.mjs index f4c412a..50f23f6 100644 --- a/src/dashboard/Dashboard.mjs +++ b/src/dashboard/Dashboard.mjs @@ -1,11 +1,20 @@ +/** + * @file Dashboard.mjs — Dashboard — web dashboard backend with player status API, guild listing, and bot statistics endpoints + * @module src.dashboard.Dashboard + */ + import { CommandBuilder, CommandHandler, Option } from "../CommandHandler.mjs"; import { PermissionFlags } from "@fluxerjs/core"; import Player from "../Player.mjs"; -import { Utils } from "../Utils.mjs"; +import { Utils, cleanId } from "../Utils.mjs"; import { DatabaseManager } from "./DatabaseManager.mjs"; import { RedisHandler } from "./RedisHandler.mjs"; import { logger } from "../constants/Logger.mjs"; +import { iterateVoiceStates } from "../constants/VoiceStateResolver.mjs"; +/** + * Dashboard class. + */ export class Dashboard { enabled = false; expiryTime = 1000 * 60 * 60 * 6; @@ -93,7 +102,7 @@ export class Dashboard { const sharedIds = new Set(shared.map(s => s.id)); result = result.filter(g => sharedIds.has(g.id)); } - } catch (_) {} + } catch(e) { logger.warn("[Dashboard] allServers accessor check:", e?.message); } } return result; } @@ -200,7 +209,7 @@ export class Dashboard { data: String(user.id) })); } - } catch (_) { /* non-critical */ } + } catch (_) { } } return { message: "Already Connected" }; } @@ -288,10 +297,10 @@ export class Dashboard { case "voiceState": { if (!user) return { channel: null }; - const userId = String(user.id).replace(/\D/g, ""); + const userId = cleanId(user.id); if (this.remix.voiceCache) { for (const [mapUserId, info] of this.remix.voiceCache) { - if (String(mapUserId).replace(/\D/g, "") === userId && info.channelId) { + if (cleanId(mapUserId) === userId && info.channelId) { const ch = this.remix.client.channels.get(info.channelId); return { channelId: info.channelId, @@ -305,16 +314,13 @@ export class Dashboard { const guildValues = guilds && typeof guilds.values === "function" ? [...guilds.values()] : guilds ? Object.values(guilds) : []; for (const guild of guildValues) { - if (!guild?.voice_states) continue; - const vs = Array.isArray(guild.voice_states) ? guild.voice_states : - typeof guild.voice_states.values === "function" ? [...guild.voice_states.values()] : Object.values(guild.voice_states); - for (const state of vs) { - const stateUserId = String(state?.userId ?? state?.user_id ?? "").replace(/\D/g, ""); - if (stateUserId === userId && state.channelId) { - const ch = this.remix.client.channels.get(state.channelId); + for (const vs of iterateVoiceStates(guild)) { + const stateUserId = cleanId(vs.userId); + if (stateUserId === userId && vs.channelId) { + const ch = this.remix.client.channels.get(vs.channelId); return { - channelId: state.channelId, - channel: ch ? Dashboard.convertChannel(ch) : { id: state.channelId, name: "Unknown" }, + channelId: vs.channelId, + channel: ch ? Dashboard.convertChannel(ch) : { id: vs.channelId, name: "Unknown" }, guildId: guild.id, }; } @@ -343,7 +349,7 @@ export class Dashboard { data: String(user.id) })); } - } catch (_) { /* non-critical */ } + } catch (_) { } return { message: "Left channel" }; } try { @@ -370,21 +376,21 @@ export class Dashboard { if (user && this.remix.handler?.owners?.includes?.(user.id)) return null; if (!user) return "User not provided"; - const cleanUserId = String(user.id).replace(/\D/g, ""); - const cleanChanId = String(player._channelId ?? "").replace(/\D/g, ""); + const cleanUserId = cleanId(user.id); + const cleanChanId = cleanId(player._channelId); if (!cleanChanId) return "Player has no active channel"; const observed = this.remix.voiceCache; if (observed) { - const guildId = String(player._guildId ?? "").replace(/\D/g, ""); + const guildId = cleanId(player._guildId); const userLoc = observed.get(cleanUserId, guildId || undefined); if (userLoc) { - const infoChannelId = String(userLoc.channelId ?? "").replace(/\D/g, ""); + const infoChannelId = cleanId(userLoc.channelId); if (infoChannelId === cleanChanId) return null; } for (const [mapUserId, info] of observed) { - if (String(mapUserId).replace(/\D/g, "") === cleanUserId) { - const infoChannelId = String(info.channelId ?? "").replace(/\D/g, ""); + if (cleanId(mapUserId) === cleanUserId) { + const infoChannelId = cleanId(info.channelId); if (infoChannelId === cleanChanId) return null; } } @@ -435,9 +441,9 @@ export class Dashboard { if (user.avatar) { avatarUrl = `https://fluxerusercontent.com/avatars/${user.id}/${user.avatar}.webp`; } else if (typeof user.displayAvatarURL === "function") { - try { avatarUrl = user.displayAvatarURL() ?? ""; } catch (_) {} + try { avatarUrl = user.displayAvatarURL() ?? ""; } catch(e) { logger.warn("[Dashboard] displayAvatarURL:", e?.message); } } else if (typeof user.avatarURL === "function") { - try { avatarUrl = user.avatarURL() ?? ""; } catch (_) {} + try { avatarUrl = user.avatarURL() ?? ""; } catch(e) { logger.warn("[Dashboard] avatarURL:", e?.message); } } if (!avatarUrl) { avatarUrl = `https://fluxerusercontent.com/embed/avatars/${parseInt(user.id?.slice(-4) ?? "0") % 5}.png`; @@ -490,16 +496,12 @@ export class Dashboard { let voiceParticipants = []; if (isVoice) { const guild = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId); - if (guild?.voice_states) { - const vs = Array.isArray(guild.voice_states) ? guild.voice_states : - typeof guild.voice_states.values === "function" ? [...guild.voice_states.values()] : Object.values(guild.voice_states); - for (const state of vs) { - const scId = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, ""); - const chId = String(channel?.id ?? "").replace(/\D/g, ""); - if (scId === chId) { - const user = guild.members?.get?.(state?.userId ?? state?.user_id)?.user; - if (user && !user.bot) voiceParticipants.push(Dashboard.convertUser(user)); - } + for (const vs of iterateVoiceStates(guild)) { + const scId = cleanId(vs.channelId); + const chId = cleanId(channel?.id); + if (scId === chId) { + const user = guild?.members?.get?.(vs.userId)?.user; + if (user && !user.bot) voiceParticipants.push(Dashboard.convertUser(user)); } } } @@ -582,8 +584,8 @@ export class Dashboard { const channelId = player._channelId; const channel = channelId ? player.client?.channels?.get(channelId) : null; const guild = channel?.guild ?? (player._guildId ? player.client?.guilds?.get(player._guildId) : null); - const cleanChannelId = channelId ? String(channelId).replace(/\D/g, "") : ""; - const cleanGuildId = player._guildId ? String(player._guildId).replace(/\D/g, "") : ""; + const cleanChannelId = channelId ? cleanId(channelId) : ""; + const cleanGuildId = player._guildId ? cleanId(player._guildId) : ""; const queue = player.queue ?? { loop: false, songLoop: false, current: null, data: [] }; @@ -600,16 +602,12 @@ export class Dashboard { const g = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId); const ids = []; const seen = new Set(); - if (g?.voice_states) { - const vs = Array.isArray(g.voice_states) ? g.voice_states : - typeof g.voice_states.values === "function" ? [...g.voice_states.values()] : Object.values(g.voice_states); - for (const state of vs) { - const scId = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, ""); - const chId = String(channel?.id ?? "").replace(/\D/g, ""); - if (scId === chId) { - const memberId = String(state?.userId ?? state?.user_id ?? ""); - if (memberId) { ids.push(memberId); seen.add(memberId); } - } + for (const vs of iterateVoiceStates(g)) { + const scId = cleanId(vs.channelId); + const chId = cleanId(channel?.id); + if (scId === chId) { + const memberId = vs.userId; + if (memberId) { ids.push(memberId); seen.add(memberId); } } } const vc = player._voiceCache ?? player._observedVoiceUsers; @@ -626,8 +624,8 @@ export class Dashboard { } else { 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, ""); + const infoCh = cleanId(info.channelId); + const infoG = cleanId(info.guildId); if (infoCh === cleanChannelId && infoG === cleanGuildId) { const botId = player.client?.user?.id; if (botId && String(mapUserId) === String(botId)) continue; diff --git a/src/dashboard/DatabaseManager.mjs b/src/dashboard/DatabaseManager.mjs index 46a40c1..03a5dcc 100644 --- a/src/dashboard/DatabaseManager.mjs +++ b/src/dashboard/DatabaseManager.mjs @@ -1,3 +1,8 @@ +/** + * @file DatabaseManager.mjs — DatabaseManager — SQLite database manager for the web dashboard's persistent storage + * @module src.dashboard.DatabaseManager + */ + import { compare, genSalt, hash } from "bcryptjs"; import { createPool } from "mysql2/promise"; import { logger } from "../constants/Logger.mjs"; diff --git a/src/dashboard/RedisHandler.mjs b/src/dashboard/RedisHandler.mjs index de3ac00..bf20202 100644 --- a/src/dashboard/RedisHandler.mjs +++ b/src/dashboard/RedisHandler.mjs @@ -1,3 +1,8 @@ +/** + * @file RedisHandler.mjs — RedisHandler — Redis pub/sub handler for cross-process dashboard state synchronization + * @module src.dashboard.RedisHandler + */ + import { createClient } from "redis"; import { logger } from "../constants/Logger.mjs"; @@ -13,6 +18,9 @@ const DEFAULT_RETRY_STRATEGY = (options) => { return Math.min(options.attempt * 500, 5_000); }; +/** + * RedisHandler class. + */ export class RedisHandler { platform = "fluxer"; @@ -163,8 +171,8 @@ export class RedisHandler { this._destroyed = true; if (this._pingInterval) { clearInterval(this._pingInterval); this._pingInterval = null; } if (this._readyTimer) { clearTimeout(this._readyTimer); this._readyTimer = null; } - try { await this.subscriber?.quit(); } catch (_) {} - try { await this.client?.quit(); } catch (_) {} + try { await this.subscriber?.quit(); } catch(e) { logger.warn("[Redis/Subscriber] Quit error:", e?.message); } + try { await this.client?.quit(); } catch(e) { logger.warn("[Redis/Main] Quit error:", e?.message); } logger.redis("[Redis] Connections closed gracefully"); } } diff --git a/src/probe.mjs b/src/probe.mjs index c634e87..ff04038 100644 --- a/src/probe.mjs +++ b/src/probe.mjs @@ -1,3 +1,8 @@ +/** + * @file probe.mjs — Health probe — monitors NodeLink and LiveKit endpoint availability + * @module src.probe + */ + import ffprobe from "ffprobe-static"; import { spawn } from "node:child_process"; @@ -19,7 +24,7 @@ export default function probe(file) { const cleanup = () => { settled = true; clearTimeout(timeoutHandle); - try { proc.kill(); } catch (_) {} + try { proc.kill(); } catch(e) { } }; const timeoutHandle = setTimeout(() => { diff --git a/src/worker.mjs b/src/worker.mjs index fe928ff..cb99289 100644 --- a/src/worker.mjs +++ b/src/worker.mjs @@ -1,3 +1,8 @@ +/** + * @file worker.mjs — Worker thread module — handles track search jobs via NodeLink REST API with provider fallback chains + * @module src.worker + */ + /** * worker.mjs — NodeLink REST edition (moonlink.js session-aware) */ @@ -6,14 +11,15 @@ import { workerData, parentPort } from "worker_threads"; import { EventEmitter } from "events"; import http from "http"; import https from "https"; -import { Utils } from "./Utils.mjs"; +import { Utils, cleanId } from "./Utils.mjs"; import { PROVIDERS } from "./constants/providers.mjs"; import { logger } from "./constants/Logger.mjs"; +import { NL_DEFAULT_PASSWORD } from "./Player.mjs"; const nl = workerData?.data?.nodelink ?? {}; const NL_HOST = nl.host ?? "localhost"; const NL_PORT = nl.port ?? 3000; -const NL_DEFAULT_PASSWORD = "youshallnotpass"; + const NL_PASSWORD = nl.password ?? NL_DEFAULT_PASSWORD; const NL_SESSION_ID = nl.sessionId ?? null; const NL_GUILD_ID = workerData?.data?.guildId ?? null; @@ -148,12 +154,7 @@ function trackToVideo(track) { } function normalizeMatchText(value) { - return Utils.cleanTitle(String(value ?? "")) - .normalize("NFKD") - .replace(/[^\w\s]+/g, " ") - .replace(/\s+/g, " ") - .trim() - .toLowerCase(); + return Utils.normalizeText(value, true); } function tokenizeMatchText(value) {