refactor: centralize shared utilities, fix voice intent, and improve error visibility

- extract `cleanId()` to `Utils.mjs` and remove 97+ inline `String(x).replace(/\D/g, "")` duplicates

- add `VoiceStateResolver.mjs` with `iterateVoiceStates`, `hasHumansInChannel`, `getChannelsWithHumans` — eliminates 12+ duplicated voice-state-iteration blocks across `Player`, `PlayerManager`, `GatewayHandler`, `Dashboard`

- add `UI.mjs` for shared color, emoji, and timeout constants

- move `parseInlineProvider` to `providers.mjs`, `getMessageGuildId` to `MessageHandler.mjs`

- fix `VoiceStateCache.removeGuild` and `TrackOptionsManager` cache deletion mutating Maps during iteration

- fix `checkVoiceChannels` now async returning `{channelId, alreadyInVoice, hasHumans}` — all callers updated

- fix `FluxerRevoice` global `console.log` monkey-patch replaced with scoped `withSuppressedLiveKitLogs(fn)`

- fix `Player._get247Mode()` settings resolution chain

- fix `runnables.mjs` validators were no-ops

- promote `Player` magic numbers to named static constants

- replace all silent `catch (_) {}` with `logger.warn()` throughout

- remove unused deps: `express`, `genius-lyrics`, `ws`

- add `@file` JSDoc headers to all modules
This commit is contained in:
NoLogicAlan committed 2026-06-15 16:56:10 +03:00
1 parent 0d3035b093
commit 092268281a
67 files changed
+2520 -2179

No files matched your search

+31 -2
View File
@@ -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 {
});
}));
}
}
}
+9 -1
View File
@@ -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
+433 -395
View File
File diff suppressed because it is too large. Load diff
+16 -12
View File
@@ -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}
+56 -4
View File
@@ -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
+14 -6
View File
@@ -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); }
}
}
+184 -219
View File
@@ -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);
}
}
}
+179 -237
View File
@@ -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<string|false>}
*/
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<Player|null>}
*/
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;
}
}
/**
+31 -34
View File
@@ -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 = <escaped>" 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) {
+11 -1
View File
@@ -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;
+50 -188
View File
@@ -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<T>} 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<T>}
*/
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<T, K>} 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<T, K>} 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;
}
}
/**
* 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();
}
}
+8 -14
View File
@@ -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}`;
}
+162 -126
View File
@@ -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<string>} Channel IDs where disconnect is expected (bot-initiated) */
_intentionalDisconnects = new Set();
/** @type {Map<string, NodeJS.Timeout>} 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;
}
+5
View File
@@ -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.
*
+8 -3
View File
@@ -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 || "!";
}
/**
+5
View File
@@ -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.
*
+45
View File
@@ -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;
+47 -23
View File
@@ -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);
+157
View File
@@ -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<string>} 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;
}
+20
View File
@@ -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() };
}
+45 -47
View File
@@ -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;
+5
View File
@@ -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";
+10 -2
View File
@@ -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");
}
}
+6 -1
View File
@@ -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(() => {
+9 -8
View File
@@ -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) {