mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-23 21:52:45 -05:00
Remix — the complete rewrite
Upgrades the bot from fluxerjs 2.2 to 3.0 and restructures everything into a layered architecture (~28K lines): Dependencies: - @fluxerjs/core, util, voice: ^2.2.0 -> ^3.0.0 (typed events, PartialMessage payloads, camelCase API) - @fluxerjs/sharding ^3.0.0 added — built-in sharding mode (shard.mjs, one process per shard) - @discordjs/opus dropped — opusscript + prism-media cover encoding Architecture: - commands: every command split into submodules (player, lastfm, settings, debug) with a shared CommandBuilder/Loader/Handler core - ui: embeds, paginators, help command, permission checks - voice: gateway event routing, rejoin/247 boot recovery, state resolver - music: player split into Queue/Search/Playback/Display mixins, stream pipeline + WebM/Opus muxer (no FFmpeg needed) - dashboard: Redis pub/sub, RPC handlers, serializers - db: MySQL manager + per-guild settings - services: LastFm manager split into focused mixins - utils: sharding, 24/7 helpers, API client Runtime fixes over v2: - Redis v5 reconnect: capped numeric backoff (0.5s ramp to 15s), never exhausts, auto-recovers when the server comes back - Redis main/subscriber clients connect in parallel; clean shutdown - Logger storm guard: identical error/warn lines deduped in a 60s window - self-deaf fix on voice join - config example uses redis://127.0.0.1 (avoids IPv6 ENETUNREACH) Housekeeping: dead code removed (Tuna.mjs + follow-redirects dep), .gitignore added (config.json, .env, node_modules, runtime state).
This commit is contained in:
1 parent
0f085a6ae4
commit
253d11cd57
150 files changed
+19935
-16894
No files matched your search
@@ -1,927 +0,0 @@
|
||||
/** @module src/CommandHandler @description Command registration, loading, parsing, and execution framework with builder pattern, subcommands, and flags. */
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
import { Utils } from "./Utils.mjs";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { Message, MessageHandler, PageBuilder, REQUIRED_BOT_PERMISSIONS, CRITICAL_PERMISSIONS } from "./MessageHandler.mjs";
|
||||
import { Client, PermissionFlags } from "@fluxerjs/core";
|
||||
import { SettingsManager } from "./Settings.mjs";
|
||||
import path from "node:path";
|
||||
import * as fs from "node:fs";
|
||||
|
||||
/** @class CommandBuilder @description Fluent builder for constructing command definitions with name, description, options, subcommands, aliases, and requirements. */
|
||||
export class CommandBuilder {
|
||||
/** Create a new CommandBuilder with default empty state. */
|
||||
constructor() {
|
||||
this.name = null;
|
||||
this.description = null;
|
||||
this.id = null;
|
||||
this.aliases = [];
|
||||
this.subcommands = [];
|
||||
this.options = [];
|
||||
this.requirements = [];
|
||||
this.category = "default";
|
||||
this.examples = [];
|
||||
|
||||
this.uid = Utils.uid();
|
||||
|
||||
this.subcommandError = "Invalid subcommand. Try one of the following options: `$previousCmd <$cmdlist>`";
|
||||
this.parent = null;
|
||||
}
|
||||
/** Set the command name and add it as the primary alias. @param {string} n @returns {CommandBuilder} */
|
||||
setName(n) { this.name = n; this.aliases.push(n.toLowerCase()); return this; }
|
||||
/** Set the command description. @param {string} d @returns {CommandBuilder} */
|
||||
setDescription(d) { this.description = d; return this; }
|
||||
/** Set the command ID. @param {string} id @returns {CommandBuilder} */
|
||||
setId(id) { this.id = id; return this; }
|
||||
/** @returns {string} Full command path including parent chain (e.g. "music play"). */
|
||||
get command() { return (this.parent) ? this.parent.command + " " + this.name : this.name; }
|
||||
/** Add a permission/owner-only requirement. @param {Function} config @returns {CommandBuilder} */
|
||||
setRequirement(config) { let req = config(new CommandRequirement()); this.requirements.push(req); return this; }
|
||||
/** Add a subcommand builder. @param {Function} config @returns {CommandBuilder} */
|
||||
addSubcommand(config) { let sub = config(new CommandBuilder()); sub.parent = this; this.subcommands.push(sub); return this; }
|
||||
/** Add a string option. @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */
|
||||
addStringOption(config, flag = false) { this.options.push(config(Option.create("string", flag))); return this; }
|
||||
/** Add a number option. @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */
|
||||
addNumberOption(config, flag = false) { this.options.push(config(Option.create("number", flag))); return this; }
|
||||
/** Add a boolean option. @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */
|
||||
addBooleanOption(config, flag = false) { this.options.push(config(Option.create("boolean", flag))); return this; }
|
||||
/** Add a channel option. @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */
|
||||
addChannelOption(config, flag = false) { this.options.push(config(Option.create("channel", flag))); return this; }
|
||||
/** Add a user option. @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */
|
||||
addUserOption(config, flag = false) { this.options.push(config(Option.create("user", flag))); return this; }
|
||||
/** Add a text (remaining-args) option. Only one is allowed per command. @param {Function} config @returns {CommandBuilder} @throws {Error} If a text option already exists. */
|
||||
addTextOption(config) {
|
||||
if (this.options.findIndex(e => e.type === "text") !== -1) throw new Error("There can only be 1 text option.");
|
||||
this.options.push(config(new Option("text")));
|
||||
return this;
|
||||
}
|
||||
/** Add a choice option (enum-like). @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */
|
||||
addChoiceOption(config, flag = false) { this.options.push(config(Option.create("choice", flag))); return this; }
|
||||
/** Add an alias. @param {string} alias @returns {CommandBuilder} */
|
||||
addAlias(alias) { if (this.aliases.findIndex(e => e === alias.toLowerCase()) !== -1) return this; this.aliases.push(alias.toLowerCase()); return this; }
|
||||
/** Add multiple aliases. @param {...string} aliases @returns {CommandBuilder} */
|
||||
addAliases(...aliases) { aliases.forEach((a) => this.addAlias(a)); return this; }
|
||||
/** Set the command category. @param {string} cat @returns {CommandBuilder} */
|
||||
setCategory(cat) { this.category = cat; return this; }
|
||||
/** Add usage examples. @param {...string} examples @returns {CommandBuilder} */
|
||||
addExamples(...examples) { this.examples.push(...examples); return this; }
|
||||
}
|
||||
|
||||
/** @class CommandRequirement @description Defines permission and owner-only requirements for commands. */
|
||||
export class CommandRequirement {
|
||||
/** @type {boolean} Whether the command is restricted to bot owners. */
|
||||
ownerOnly = false;
|
||||
/** Create a new CommandRequirement. */
|
||||
constructor() {
|
||||
this.permissions = [];
|
||||
this.permissionError = "You don't have the needed permissions to run this command!";
|
||||
return this;
|
||||
}
|
||||
/** @param {boolean} bool @returns {CommandRequirement} */
|
||||
setOwnerOnly(bool) { this.ownerOnly = bool; return this; }
|
||||
/** @param {string} p @returns {CommandRequirement} */
|
||||
addPermission(p) { this.permissions.push(p); return this; }
|
||||
/** @param {...string} p @returns {CommandRequirement} */
|
||||
addPermissions(...p) { this.permissions.push(...p); return this; }
|
||||
/** @returns {string[]} */
|
||||
getPermissions() { return (this.ownerOnly) ? [...this.permissions, "Owner-only command"] : this.permissions; }
|
||||
/** @param {string} e @returns {CommandRequirement} */
|
||||
setPermissionError(e) { this.permissionError = e; return this; }
|
||||
}
|
||||
|
||||
/** @class Option @description Represents a command option (string, number, boolean, channel, choice, flag) with validation and formatting. */
|
||||
export class Option {
|
||||
/** @type {number} @description Maximum choices before switching to compact format. */
|
||||
static THRESHOLD = 10;
|
||||
/** @type {number} @description Number of choice columns per line in compact format. */
|
||||
static COLS_PER_LINE = 5;
|
||||
|
||||
/** Format choice values in a compact multi-column layout. @param {string[]} choices @param {number} [perLine=Option.COLS_PER_LINE] @returns {string} */
|
||||
static formatChoicesCompact(choices, perLine = Option.COLS_PER_LINE) {
|
||||
const lines = [];
|
||||
for (let i = 0; i < choices.length; i += perLine) {
|
||||
lines.push(choices.slice(i, i + perLine).map(c => '`' + c + '`').join(' · '));
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/** Format choice values inline, switching to compact layout above the threshold. @param {string[]} choices @returns {string} */
|
||||
static formatChoicesInline(choices) {
|
||||
if (choices.length <= Option.THRESHOLD) {
|
||||
return '`' + choices.join('`, `') + '`';
|
||||
}
|
||||
return Option.formatChoicesCompact(choices, 6);
|
||||
}
|
||||
|
||||
/** Format choice values for a usage string, truncating with "…" if over max. @param {string[]} choices @param {number} [max=6] @returns {string} */
|
||||
static formatChoicesUsage(choices, max = 6) {
|
||||
if (choices.length <= max) return choices.join(' | ');
|
||||
return choices.slice(0, max).join(' | ') + ' | ...';
|
||||
}
|
||||
channelRegex = /^<#(?<id>\d+)>/;
|
||||
userRegex = /^<@!?(?<id>\d+)>/;
|
||||
idRegex = /^(?<id>\d+)/;
|
||||
|
||||
/** @type {Function|null} Dynamic default value resolver. */
|
||||
dynamicDefault;
|
||||
|
||||
/** Create a new Option. @param {string} [type="string"] */
|
||||
constructor(type = "string") {
|
||||
this.name = null;
|
||||
this.description = null;
|
||||
this.required = false;
|
||||
this.id = null;
|
||||
this.uid = Utils.uid();
|
||||
this.type = type;
|
||||
this.tError = null;
|
||||
this.aliases = [null];
|
||||
this.choices = [];
|
||||
this.translations = {};
|
||||
this.defaultValue = null;
|
||||
this.dynamicDefault = null;
|
||||
}
|
||||
|
||||
/** Factory to create an Option or Flag instance. @param {string} type @param {boolean} [flag=false] @returns {Option|Flag} */
|
||||
static create(type, flag = false) {
|
||||
return (!flag) ? new Option(type) : new Flag(type);
|
||||
}
|
||||
|
||||
/** Set the option name. @param {string} n @returns {Option} */
|
||||
setName(n) { this.name = n; this.aliases[0] = n; return this; }
|
||||
/** Set the option description. @param {string} d @returns {Option} */
|
||||
setDescription(d) { this.description = d; return this; }
|
||||
/** Set whether the option is required. @param {boolean} r @returns {Option} */
|
||||
setRequired(r) { this.required = r; return this; }
|
||||
/** Set the option ID. @param {string} id @returns {Option} */
|
||||
setId(id) { this.id = id; return this; }
|
||||
/** Set the option type. @param {string} t @returns {Option} */
|
||||
setType(t) { this.type = t; return this; }
|
||||
/** Add flag aliases (e.g. "v" for "-v"). @param {...string} a @returns {Option} */
|
||||
addFlagAliases(...a) { this.aliases.push(...a); return this; }
|
||||
/** Add a single valid choice value. @param {string} c @returns {Option} @throws {Error} If option type is not "choice". */
|
||||
addChoice(c) { if (this.type !== "choice") throw new Error(".addChoice is only available for choice options!"); this.choices.push(c); return this; }
|
||||
/** Add multiple valid choice values. @param {...string} cs @returns {Option} @throws {Error} If option type is not "choice". */
|
||||
addChoices(...cs) { if (this.type !== "choice") throw new Error(".addChoices is only available for choice options!"); cs.forEach(c => this.addChoice(c)); return this; }
|
||||
/** Set the default value when the option is omitted. @param {*} value @returns {Option} */
|
||||
setDefault(value) { this.defaultValue = value; return this; }
|
||||
/** Set a dynamic default resolver function. @param {Function} callback @returns {Option} */
|
||||
setDynamicDefault(callback) { this.dynamicDefault = callback; return this; }
|
||||
|
||||
/** Check whether a value is considered empty/omitted. @param {*} i @returns {boolean} */
|
||||
empty(i) {
|
||||
if (i === undefined || i === null) return true;
|
||||
return (!i && !(String(i).includes("0")));
|
||||
}
|
||||
|
||||
/** Validate an input value for this option type. @param {*} i @param {object} client @param {object} msg @param {string} [type] @returns {boolean} */
|
||||
validateInput(i, client, msg, type) {
|
||||
switch (type || this.type) {
|
||||
case "text":
|
||||
case "string":
|
||||
return !!i;
|
||||
case "number":
|
||||
return !isNaN(i) && !isNaN(parseFloat(i));
|
||||
case "boolean":
|
||||
return i === "0" || i === "1" || i?.toLowerCase() === "true" || i?.toLowerCase() === "false";
|
||||
case "choice":
|
||||
return this.choices.includes(i);
|
||||
case "user":
|
||||
return this.userRegex.test(i) || this.idRegex.test(i);
|
||||
case "channel":
|
||||
if (i === undefined) return false;
|
||||
return this.channelRegex.test(i) || this.idRegex.test(i) || client.channels.some(c => c.name === i);
|
||||
case "voiceChannel": {
|
||||
if (!i) return false;
|
||||
const results = this.channelRegex.exec(i) ?? this.idRegex.exec(i);
|
||||
const guildId = msg?.channel?.guildId ?? msg?.guildId;
|
||||
|
||||
const voiceTypes = [2, 13];
|
||||
const byName = msg?.guild?.channels?.find(c => c.name === i && voiceTypes.includes(c.type));
|
||||
const cObj = results
|
||||
? client.channels.get(results.groups["id"])
|
||||
: (byName ?? null);
|
||||
return cObj ? voiceTypes.includes(cObj.type) : false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Format/parse an input value for this option type. @param {*} i @param {object} client @param {object} msg @param {string} [type] @returns {*} */
|
||||
formatInput(i, client, msg, type) {
|
||||
switch (type || this.type) {
|
||||
case "text":
|
||||
case "string":
|
||||
return i;
|
||||
case "number":
|
||||
return parseFloat(i);
|
||||
case "boolean":
|
||||
return i?.toLowerCase() === "true" || i === "1";
|
||||
case "choice":
|
||||
return i;
|
||||
case "user": {
|
||||
const rs = this.userRegex.exec(i) ?? this.idRegex.exec(i);
|
||||
return rs?.groups["id"] ?? null;
|
||||
}
|
||||
case "channel": {
|
||||
const results = this.channelRegex.exec(i) ?? this.idRegex.exec(i);
|
||||
const channel = client.channels.find(c => c.name === i);
|
||||
return results ? results.groups["id"] : (channel ? channel.id : null);
|
||||
}
|
||||
case "voiceChannel": {
|
||||
const r = this.channelRegex.exec(i) ?? this.idRegex.exec(i);
|
||||
const guildId = msg?.channel?.guildId ?? msg?.guildId;
|
||||
if (guildId === "eval") return r ? r.groups["id"] : (i || null);
|
||||
const voiceTypes = [2, 13];
|
||||
const c = msg?.guild?.channels?.find(c => c.name === i && voiceTypes.includes(c.type));
|
||||
return r ? r.groups["id"] : (c ? c.id : null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Generate a type-error message for this option. @returns {string} */
|
||||
get typeError() {
|
||||
if (this.tError) return this.tError;
|
||||
switch (this.type) {
|
||||
case "choice": {
|
||||
const choiceStr = this.choices.length > Option.THRESHOLD
|
||||
? Option.formatChoicesCompact(this.choices)
|
||||
: this.choices.map(c => '- ' + c).join('\n');
|
||||
return "Invalid value '$currValue'. The option `" + this.name + "` has to be one of the following: \n" + choiceStr + "\nSchematic: `$previousCmd <" + this.type + ">`";
|
||||
}
|
||||
case "voiceChannel":
|
||||
case "channel":
|
||||
return "Invalid value '$currValue'. The option `" + this.name + "` has to be a channel mention, id, or name.\nSchematic: `$previousCmd <" + this.type + ">`";
|
||||
default:
|
||||
return "Invalid value '$currValue'. The option `" + this.name + "` has to be of type `" + this.type + "`.\nSchematic: `$previousCmd <" + this.type + ">`";
|
||||
}
|
||||
}
|
||||
/** Set a custom type-error message template. @param {string} e */
|
||||
set typeError(e) { this.tError = e; }
|
||||
}
|
||||
|
||||
/** @class Flag @description A flag-type option that cannot be text. Extends Option. */
|
||||
export class Flag extends Option {
|
||||
/** Create a Flag (non-text option). @param {string} [type="string"] */
|
||||
constructor(type = "string") {
|
||||
if (type === "text") throw new Error("Flags can't be of type 'text'!");
|
||||
super(type);
|
||||
}
|
||||
}
|
||||
|
||||
/** @class PrefixManager @description Manages per-guild command prefixes (falling back to config or default). */
|
||||
export class PrefixManager {
|
||||
/** @type {RemoteSettingsManager} */
|
||||
settings;
|
||||
/** @type {string|null} */
|
||||
configPrefix;
|
||||
/** @param {RemoteSettingsManager} settings @param {string|null} [configPrefix=null] */
|
||||
constructor(settings, configPrefix = null) { this.settings = settings; this.configPrefix = configPrefix; }
|
||||
/** Get the command prefix for a guild. @param {string} guildId @returns {string} */
|
||||
getPrefix(guildId) {
|
||||
const serverPrefix = this.settings.getServer(guildId).get("prefix");
|
||||
return serverPrefix ?? this.configPrefix ?? "%";
|
||||
}
|
||||
}
|
||||
|
||||
/** @class HelpHandler @description Generates paginated help text for commands. */
|
||||
export class HelpHandler {
|
||||
/** @type {CommandHandler} */
|
||||
commands;
|
||||
/** @type {number} Commands per help page. */
|
||||
commandsPerPage = 5;
|
||||
|
||||
/** Default pagination handler that builds paginated help pages. @param {object} msg - Message wrapper with message data. @param {HelpHandler} helpHandler @param {Array} cmds @returns {string|null} */
|
||||
paginationHandler = (msg, helpHandler, cmds) => {
|
||||
const guildId = msg.message.guildId;
|
||||
let form = this.commands.t(guildId, "cmdHandler.help.pageStructure");
|
||||
|
||||
const contents = cmds.map((cmd, i) => {
|
||||
return (i + 1) + ". **" + cmd.name + "**: " + (cmd.description || "").split("\n")[0];
|
||||
});
|
||||
|
||||
const pages = new PageBuilder(contents)
|
||||
.setForm(helpHandler.commands.format(form, msg.message.guildId))
|
||||
.setMaxLines(helpHandler.commandsPerPage);
|
||||
|
||||
helpHandler.commands.messages.initPagination(pages, msg);
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @type {Function|null} Custom help handler function override. */
|
||||
customHelpHandler = null;
|
||||
|
||||
/** @param {CommandHandler} commands */
|
||||
constructor(commands) { this.commands = commands; }
|
||||
|
||||
/** @param {string} string @returns {string} Capitalised first letter. */
|
||||
static capitalise(string) {
|
||||
if (string.length < 1) return string;
|
||||
if (string.length === 1) return string.toUpperCase();
|
||||
return string.charAt(0).toUpperCase() + string.slice(1);
|
||||
}
|
||||
|
||||
/** @param {Array} [cmds] @returns {Array} Non-owner-only commands. */
|
||||
userCommands(cmds) {
|
||||
return (cmds || this.commands.commands).filter(c =>
|
||||
c.requirements.findIndex(r => r.ownerOnly) === -1
|
||||
);
|
||||
}
|
||||
|
||||
/** @returns {number} Total number of help pages. */
|
||||
pageNumber() {
|
||||
return Math.ceil(this.commands.commands.length / this.commandsPerPage);
|
||||
}
|
||||
|
||||
/** @param {object} message @returns {string|null} */
|
||||
help(message) {
|
||||
if (this.customHelpHandler) return this.customHelpHandler(message);
|
||||
if (this.paginationHandler) return this.genHelp(null, message, true);
|
||||
return this.getHelpPage(0, message);
|
||||
}
|
||||
|
||||
/** @param {number} n @param {object} msg @param {Array} [cmds=null] @returns {string} */
|
||||
getHelpPage(n, msg, cmds = null) {
|
||||
if (!cmds) cmds = this.commands.commands;
|
||||
if (!(this.commandsPerPage < cmds.length)) return this.genHelp(null, msg, false, cmds);
|
||||
let offset = this.commandsPerPage * n;
|
||||
const commands = cmds.slice(offset, offset + this.commandsPerPage);
|
||||
let max = Math.ceil(cmds.length / this.commandsPerPage);
|
||||
return this.genHelp({ curr: n + 1, max, offset }, msg, false, commands);
|
||||
}
|
||||
|
||||
/** @param {object|null} page @param {object} msg @param {boolean} [paginate=false] @param {Array} [cmds=null] @returns {string} */
|
||||
genHelp(page, msg, paginate = false, cmds = null) {
|
||||
cmds = this.userCommands(cmds);
|
||||
if (this.paginationHandler && msg && paginate) return this.paginationHandler(msg, this, cmds);
|
||||
|
||||
const guildId = msg.message.guildId;
|
||||
let p = (page) ? ` (page ${page.curr}/${page.max})` : "";
|
||||
const indexOffset = (page) ? page.offset : 0;
|
||||
let content = this.commands.t(guildId, "cmdHandler.help.availableCommands", { $page: p }) + "\n\n";
|
||||
if (page && page.curr !== 1) content += (indexOffset) + this.commands.t(guildId, "cmdHandler.help.ellipsis") + "\n";
|
||||
cmds.forEach((cmd, i) => { content += (i + 1 + indexOffset) + ". **" + cmd.name + "**: " + cmd.description + "\n"; });
|
||||
if (page && page.curr !== page.max) content += (cmds.length + indexOffset) + this.commands.t(guildId, "cmdHandler.help.ellipsis") + "\n";
|
||||
content += this.commands.format(this.commands.t(guildId, "cmdHandler.help.runHelp"), guildId);
|
||||
if (page) content += this.commands.format(this.commands.t(guildId, "cmdHandler.help.pageTip"), guildId);
|
||||
|
||||
return this.commands.format(content, guildId);
|
||||
}
|
||||
|
||||
/** Get the description of a command. @param {CommandBuilder} command @returns {string} */
|
||||
commandDescription(command) { return command.description; }
|
||||
|
||||
/** Build a usage string for a command including options and flags. @param {CommandBuilder} cmd @param {object} msg @returns {string} */
|
||||
commandUsage(cmd, msg) {
|
||||
if (cmd.subcommands.length > 0) {
|
||||
return this.commands.format("$prefix" + cmd.command, msg.message.guildId) + " <" + cmd.subcommands.map(e => e.name).join(" | ") + "> [...]";
|
||||
}
|
||||
let options = this.commands.format("$prefix" + cmd.command, msg.message.guildId);
|
||||
cmd.options.forEach(o => {
|
||||
if (o.type === "text") return;
|
||||
if (o instanceof Flag)
|
||||
return options += (o.type === "choice") ? "-" + o.aliases[0] + " <" + Option.formatChoicesUsage(o.choices) + ">" : " -" + o.aliases[0] + " '" + o.type + "'";
|
||||
options += (o.type === "choice") ? " <" + Option.formatChoicesUsage(o.choices) + ">" : " '" + o.name + ": " + o.type + "'";
|
||||
});
|
||||
let o = cmd.options.find(e => e.type === "text");
|
||||
if (o) options += "'" + o.name + ": " + o.type + "'";
|
||||
return options.trim();
|
||||
}
|
||||
|
||||
/** Generate detailed help for a single command. @param {object} command @param {object} msg @returns {string} */
|
||||
getCommandHelp(command, msg) {
|
||||
const guildId = msg.message.guildId;
|
||||
let content = `${HelpHandler.capitalise(command.name)}\n`;
|
||||
content += this.commandDescription(command, msg) + "\n\n";
|
||||
content += this.commands.t(guildId, "cmdHandler.help.usage") + "\n💻 `" + this.commandUsage(command, msg) + "`\n\n";
|
||||
if (command.examples.length > 0)
|
||||
content += this.commands.t(guildId, "cmdHandler.help.examples") + "\n- `" + command.examples.map(e => this.commands.format(e, guildId)).join("`\n- `") + "`\n\n";
|
||||
if (command.aliases.length > 1) {
|
||||
content += this.commands.t(guildId, "cmdHandler.help.aliases") + "\n";
|
||||
command.aliases.forEach(alias => { content += "- " + alias + "\n"; });
|
||||
content += "\n";
|
||||
}
|
||||
if (command.subcommands.length > 0) {
|
||||
content += this.commands.t(guildId, "cmdHandler.help.subcommands") + "\n";
|
||||
command.subcommands.forEach(s => {
|
||||
const optCount = s.options.length > 0 ? "; (`" + this.commands.t(guildId, "cmdHandler.help.optionCount", { $count: s.options.length }) + "`)" : "";
|
||||
content += "- " + s.name + ": " + (this.commandDescription(s, msg) || "").split("\n")[0] + optCount + "\n";
|
||||
});
|
||||
content += "\n";
|
||||
} else if (command.options.length > 0) {
|
||||
content += this.commands.t(guildId, "cmdHandler.help.arguments") + "\n";
|
||||
command.options.forEach(o => {
|
||||
const optional = ((o.required) ? "" : "?");
|
||||
const flag = (o instanceof Flag) ? "-" : "";
|
||||
if (o.type === "choice") {
|
||||
const choiceDisplay = Option.formatChoicesInline(o.choices);
|
||||
const aliasDisplay = o.aliases.filter(a => a !== null).join('`, `');
|
||||
content += "- **" + flag + o.name + "**" + optional + ": " + (o.description || "").split("\n")[0] + ";\n - " + this.commands.t(guildId, "cmdHandler.help.allowedValues") + choiceDisplay + "\n - " + this.commands.t(guildId, "cmdHandler.help.aliasesLabel") + "`" + aliasDisplay + "`\n";
|
||||
} else {
|
||||
content += "- **" + flag + o.name + "**" + optional + ": " + (o.description || "").split("\n")[0] + "\n - " + this.commands.t(guildId, "cmdHandler.help.aliasesLabel") + "`" + o.aliases.join("`, `") + "`\n";
|
||||
}
|
||||
content += "\n";
|
||||
});
|
||||
content += "\n";
|
||||
}
|
||||
if (command.requirements.length > 0) {
|
||||
content += this.commands.t(guildId, "cmdHandler.help.requirements") + "\n";
|
||||
command.requirements.forEach(r => {
|
||||
content += "- " + r.getPermissions().map(e => this.commands.t(guildId, "cmdHandler.help.permission", { $permission: e })).join("\n- ");
|
||||
});
|
||||
}
|
||||
return content.trim();
|
||||
}
|
||||
}
|
||||
|
||||
/** @class CommandHandler @description Main command dispatcher. Parses incoming messages, matches commands, validates arguments, checks permissions, and emits run events. @extends {EventEmitter} */
|
||||
export class CommandHandler extends EventEmitter {
|
||||
/** @type {Function|null} Custom handler when the bot is pinged. */
|
||||
onPing = null;
|
||||
/** @type {boolean} Whether the bot responds to pings as a prefix. */
|
||||
pingPrefix = true;
|
||||
/** @type {string[]} Bot owner user IDs. */
|
||||
owners = [];
|
||||
|
||||
messages;
|
||||
client;
|
||||
prefixes;
|
||||
helpHandler;
|
||||
|
||||
commandNames = [];
|
||||
commands = [];
|
||||
|
||||
locale = null;
|
||||
invalidFlagError = "Invalid flag `$invalidFlag`. It doesn't match any options on this command.\n`$previousCmd $invalidFlag`";
|
||||
textWrapError = "Malformed string `$value`: Missing a closing quote character (`$quote`) after the desired string.";
|
||||
|
||||
/** @private @type {Map<string, number>} Per-user last command timestamps for cooldown enforcement. */
|
||||
_cmdCooldowns = new Map();
|
||||
/** @private @type {number} Cooldown duration in milliseconds between commands per non-owner user. */
|
||||
_cmdCooldownMs = 1500;
|
||||
|
||||
/** @param {MessageHandler} handler - The message handler instance. @param {string} [prefix="%"] - Default command prefix. */
|
||||
constructor(handler, prefix = "%") {
|
||||
super();
|
||||
this.messages = handler;
|
||||
this.client = handler.client;
|
||||
this.prefix = prefix;
|
||||
this.helpHandler = new HelpHandler(this);
|
||||
this.helpCommand = "help";
|
||||
this.replyHandler = (message, msg) => {
|
||||
msg.reply(this.format(message, msg.channel.channel.guildId));
|
||||
};
|
||||
this.messages.onMessage(this.messageHandler.bind(this));
|
||||
}
|
||||
|
||||
/** Get the command prefix for a guild. @param {string} guildId @returns {string} */
|
||||
getPrefix(guildId) { return this.prefixes.getPrefix(guildId); }
|
||||
/** Enable or disable ping-as-prefix. @param {boolean} bool */
|
||||
setPingPrefix(bool) { this.pingPrefix = bool; }
|
||||
/** Set the prefix manager instance. @param {PrefixManager} manager */
|
||||
setPrefixManager(manager) { this.prefixes = manager; }
|
||||
/** Set a custom help handler. @param {HelpHandler} handler */
|
||||
setHelpHandler(handler) { this.helpHandler = handler; }
|
||||
/** Set the locale manager. @param {object} locale */
|
||||
setLocale(locale) { this.locale = locale; }
|
||||
|
||||
/** Translate a locale key. @param {string} guildId @param {string} key @param {object} [replacements={}] @returns {string} */
|
||||
t(guildId, key, replacements = {}) {
|
||||
if (!this.locale) return key;
|
||||
return this.locale.translate(guildId, key, replacements);
|
||||
}
|
||||
|
||||
/** Replace $prefix and $helpCmd placeholders in text. @param {string} text @param {string} guildId @returns {string} */
|
||||
format(text, guildId) {
|
||||
const prefix = (!guildId) ? this.prefix : this.getPrefix(guildId);
|
||||
return text
|
||||
.replace(/\$prefix/gi, prefix)
|
||||
.replace(/\$helpCmd/gi, this.helpCommand);
|
||||
}
|
||||
|
||||
/** Remove a command from the registry. @param {CommandBuilder} command */
|
||||
removeCommand(command) {
|
||||
command.aliases.forEach(a => {
|
||||
const idx = this.commandNames.indexOf(a);
|
||||
if (idx !== -1) this.commandNames.splice(idx, 1);
|
||||
});
|
||||
const idx = this.commands.findIndex(c => c.uid === command.uid);
|
||||
if (idx !== -1) this.commands.splice(idx, 1);
|
||||
}
|
||||
|
||||
/** @private Handle an incoming message and route to command processing. @param {Message} msg */
|
||||
messageHandler(msg) {
|
||||
if (!msg || !msg.content) return;
|
||||
const trimmed = msg.content.trim();
|
||||
if (/^<@!?\d+>$/.test(trimmed)) {
|
||||
const botId = this.client.user?.id;
|
||||
if (botId && (trimmed === `<@${botId}>` || trimmed === `<@!${botId}>`)) {
|
||||
return this.onPing?.(msg);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const guildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
const prefix = this.getPrefix(guildId);
|
||||
const ping = `<@${this.client.user?.id}>`;
|
||||
const pingBang = `<@!${this.client.user?.id}>`;
|
||||
if (!(msg.content.startsWith(prefix) || msg.content.startsWith(ping) || msg.content.startsWith(pingBang))) return;
|
||||
|
||||
const userId = msg.message?.author?.id ?? msg.author?.id;
|
||||
if (userId && !this.owners.includes(userId)) {
|
||||
const now = Date.now();
|
||||
const last = this._cmdCooldowns.get(userId) ?? 0;
|
||||
if (now - last < this._cmdCooldownMs) return;
|
||||
this._cmdCooldowns.set(userId, now);
|
||||
if (this._cmdCooldowns.size > 500) {
|
||||
const cutoff = now - this._cmdCooldownMs * 2;
|
||||
for (const [uid, ts] of this._cmdCooldowns) {
|
||||
if (ts < cutoff) this._cmdCooldowns.delete(uid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const len = msg.content.startsWith(prefix) ? prefix.length : (msg.content.startsWith(pingBang) ? pingBang.length : ping.length);
|
||||
const args = msg.content.slice(len).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim());
|
||||
|
||||
if (!args[0]) return;
|
||||
|
||||
if (args[0] === this.helpCommand) {
|
||||
if (!args[1]) {
|
||||
const res = this.helpHandler.help(msg);
|
||||
return (typeof res === "string") ? this.replyHandler(res, msg) : undefined;
|
||||
}
|
||||
if (args.length > 1 && Utils.isNumber(args[1])) {
|
||||
const pageNumber = parseInt(args[1]);
|
||||
if (pageNumber < 1 || pageNumber > this.helpHandler.pageNumber()) {
|
||||
return this.replyHandler(this.t(guildId, "cmdHandler.page.invalid", { number: pageNumber }), msg);
|
||||
}
|
||||
return this.replyHandler(this.helpHandler.getHelpPage(pageNumber - 1, msg), msg);
|
||||
}
|
||||
if (args.length <= 2) {
|
||||
let idx = this.commands.findIndex(e => e.aliases.some(al => al.toLowerCase() === args[1].toLowerCase()));
|
||||
if (idx === -1) return this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix" + args[1], guildId) }), msg);
|
||||
return this.replyHandler(this.helpHandler.getCommandHelp(this.commands[idx], msg), msg);
|
||||
}
|
||||
let currCmd = null;
|
||||
let prefix2 = "";
|
||||
for (let i = 0; i < args.slice(1).length; i++) {
|
||||
let a = args.slice(1)[i];
|
||||
let curr = (currCmd) ? currCmd.subcommands : this.commands;
|
||||
let idx = curr.findIndex(e => e.aliases.some(al => al.toLowerCase() === a.toLowerCase()));
|
||||
if (idx === -1) return this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix" + prefix2 + a, guildId) }), msg);
|
||||
currCmd = curr[idx];
|
||||
prefix2 += a + " ";
|
||||
}
|
||||
return this.replyHandler(this.helpHandler.getCommandHelp(currCmd, msg), msg);
|
||||
}
|
||||
|
||||
if (!this.commandNames.includes(args[0].toLowerCase())) {
|
||||
this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix$helpCmd", guildId) }), msg);
|
||||
return;
|
||||
}
|
||||
return this.processCommand(this.commands.find(e => e.aliases.includes(args[0].toLowerCase())), args, msg);
|
||||
}
|
||||
|
||||
/** Parse and execute a command with its options. @param {CommandBuilder} cmd @param {string[]} args @param {Message} msg @param {string|boolean} [previous=false] @param {boolean} [external=false] @returns {object|undefined} */
|
||||
processCommand(cmd, args, msg, previous = false, external = false) {
|
||||
if (!cmd) return logger.warn("[CommandHandler.processCommand] Invalid case: `cmd` falsy.");
|
||||
|
||||
if (!external) {
|
||||
const channel = msg.channel?.channel ?? msg.channel;
|
||||
if (channel?.guild) {
|
||||
const botPermResult = this.messages.checkAllBotPermissions(channel);
|
||||
if (botPermResult.criticalMissing.length > 0) {
|
||||
const permEmbed = this.messages.buildPermissionEmbed(botPermResult.missing, channel.guildId);
|
||||
try {
|
||||
msg.message?.reply?.({ embeds: [permEmbed] }, { ping: false });
|
||||
} catch (_) {
|
||||
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 (__) { logger.warn("[CommandHandler] Fallback perm reply failed"); }
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (cmd.requirements.length > 0 && !external) {
|
||||
if (!this.assertRequirements(cmd, msg)) return;
|
||||
}
|
||||
if (previous === false) previous = this.format("$prefix" + cmd.name, msg.channel?.channel?.guildId);
|
||||
if (!external) this.emit("command", { command: cmd, message: msg });
|
||||
|
||||
if (cmd.subcommands.length !== 0) {
|
||||
const idx = cmd.subcommands.findIndex(el => {
|
||||
if (!args[1]) return false;
|
||||
return el.name.toLowerCase() === args[1].toLowerCase();
|
||||
});
|
||||
if (idx === -1) {
|
||||
const list = cmd.subcommands.map(s => s.name).join(" | ");
|
||||
const subGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
const e = this.t(subGuildId, "cmdBuilder.subcommand.invalid").replace(/\$previousCmd/gi, previous).replace(/\$cmdList/gi, list);
|
||||
return (!external) ? this.replyHandler(e, msg) : e;
|
||||
}
|
||||
return this.processCommand(cmd.subcommands[idx], args.slice(1), msg, previous + this.format(" " + cmd.subcommands[idx].name), external);
|
||||
}
|
||||
|
||||
const opts = [];
|
||||
const texts = [];
|
||||
|
||||
/** @private Collect quoted arguments spanning multiple tokens. @param {number} index @param {string} currVal @param {string[]} as @returns {{args: string[], index: number}|null} */
|
||||
const collectArguments = (index, currVal, as) => {
|
||||
const lastChar = currVal.charAt(currVal.length - 1);
|
||||
if (lastChar === '"') return { args: as, index };
|
||||
const a = args[++index];
|
||||
if (!a) return null;
|
||||
as.push(a);
|
||||
return collectArguments(index, a, as);
|
||||
};
|
||||
|
||||
const options = cmd.options.slice().sort((a, b) => {
|
||||
const aText = (a.type === "text") ? 1 : 2;
|
||||
const bText = (b.type === "text") ? 1 : 2;
|
||||
return aText - bText;
|
||||
});
|
||||
|
||||
const STRING_TYPES = ["string", "text", "channel", "voiceChannel"];
|
||||
const usedOptions = [];
|
||||
let usedArgumentCount = 0;
|
||||
|
||||
for (let i = 0, argIndex = 1; i < options.length; i++) {
|
||||
const o = options[i];
|
||||
if (o?.type === "text") { texts.push(o); continue; }
|
||||
if ((args[argIndex] || "").startsWith("-")) {
|
||||
const flagName = args[argIndex].slice(1);
|
||||
const op = cmd.options.find(e => e.aliases.includes(flagName));
|
||||
if (!op) {
|
||||
const flagGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
const error = this.t(flagGuildId, "cmdHandler.invalidFlag").replace(/\$previousCmd/gi, previous).replace(/\$invalidFlag/gi, "-" + flagName);
|
||||
return (!external) ? this.replyHandler(error, msg) : error;
|
||||
}
|
||||
previous += " " + args[argIndex];
|
||||
let value = args[++argIndex];
|
||||
if ((value || "").startsWith('"') && (STRING_TYPES.includes(op.type))) {
|
||||
const data = collectArguments(argIndex, value, [value]);
|
||||
if (!data) { const twGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId; return this.replyHandler(this._textWrapErrorMsg(twGuildId, args.slice(argIndex).join(" "), args[argIndex].charAt(0)), msg); }
|
||||
argIndex += data.index - argIndex;
|
||||
const _joined = data.args.join(" ");
|
||||
value = _joined.slice(1, _joined.length - 1);
|
||||
}
|
||||
argIndex++;
|
||||
i--;
|
||||
const valid = op.validateInput(value, this.client, msg.message);
|
||||
if (!valid && (op.required || !op.empty(value))) {
|
||||
const errGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
const e = this._optionTypeError(errGuildId, op, value, previous);
|
||||
return (!external) ? this.replyHandler(e, msg) : e;
|
||||
}
|
||||
usedArgumentCount += 2;
|
||||
previous += " " + value;
|
||||
opts.push({ value: op.formatInput(value, this.client, msg.message), name: op.name, id: op.id, uid: op.uid });
|
||||
usedOptions.push(op.uid);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!o) continue;
|
||||
if (o instanceof Flag) continue;
|
||||
if (opts.findIndex(op => op.uid === o.uid) !== -1) continue;
|
||||
let value = args[argIndex];
|
||||
if ((args[argIndex] || "").startsWith('"') && (STRING_TYPES.includes(o.type))) {
|
||||
const data = collectArguments(argIndex, args[argIndex], [args[argIndex]]);
|
||||
if (!data) { const twGuildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId; return this.replyHandler(this._textWrapErrorMsg(twGuildId2, args.slice(argIndex).join(" "), args[argIndex].charAt(0)), msg); }
|
||||
argIndex += data.index - argIndex;
|
||||
value = data.args.join(" ");
|
||||
value = value.slice(1, value.length - 1);
|
||||
}
|
||||
let valid = o.validateInput(value, this.client, msg.message);
|
||||
if (!valid && o.dynamicDefault) {
|
||||
value = o.dynamicDefault(this.client, msg);
|
||||
valid = o.validateInput(value, this.client, msg.message);
|
||||
}
|
||||
if (!valid && (o.required || !o.empty(value))) {
|
||||
const errGuildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
const e = this._optionTypeError(errGuildId2, o, value, previous);
|
||||
return (!external) ? this.replyHandler(e, msg) : e;
|
||||
}
|
||||
if (o.empty(value)) value = o.defaultValue;
|
||||
opts.push({ value: o.formatInput(value, this.client, msg.message), name: o.name, id: o.id, uid: o.uid });
|
||||
usedOptions.push(o.uid);
|
||||
previous += " " + value;
|
||||
argIndex++;
|
||||
usedArgumentCount++;
|
||||
}
|
||||
|
||||
if (texts.length > 0) {
|
||||
let o = texts[0];
|
||||
let text = args.slice(usedArgumentCount + 1).join(" ");
|
||||
if (o.required && !o.validateInput(text, this.client, msg.message)) {
|
||||
const textErrGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
let e = this._optionTypeError(textErrGuildId, o, text, previous);
|
||||
return (!external) ? this.replyHandler(e, msg) : e;
|
||||
}
|
||||
const quote = (['"', "'"].includes(text.charAt(0))) ? text.charAt(0) : null;
|
||||
if (quote && text.charAt(text.length - 1) === quote) text = text.slice(1, text.length - 1);
|
||||
opts.push({ name: o.name, value: text, id: o.id, uid: o.uid });
|
||||
usedOptions.push(o.uid);
|
||||
}
|
||||
|
||||
options.filter(o => !usedOptions.includes(o.uid)).forEach(o => {
|
||||
if (!o.defaultValue) return;
|
||||
opts.push({ name: o.name, value: o.defaultValue, id: o.id, uid: o.uid });
|
||||
});
|
||||
|
||||
const commandRunData = {
|
||||
command: cmd,
|
||||
commandId: cmd.id,
|
||||
options: opts,
|
||||
message: msg,
|
||||
get: function (oName) { return this.options.find(o => o.name === oName); },
|
||||
getById: function (id) { return this.options.find(o => o.id === id); }
|
||||
};
|
||||
if (!external) this.emit("run", commandRunData);
|
||||
return commandRunData;
|
||||
}
|
||||
|
||||
/** Check whether the message author meets all command requirements (owner, permissions). @param {CommandBuilder} cmd @param {Message} msg @returns {boolean} */
|
||||
assertRequirements(cmd, msg) {
|
||||
const authorId = msg.message?.author?.id;
|
||||
const isOwner = this.owners.includes(authorId);
|
||||
const permGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
|
||||
for (let i = 0; i < cmd.requirements.length; i++) {
|
||||
let req = cmd.requirements[i];
|
||||
if (req.ownerOnly && !isOwner) return false;
|
||||
if (req.permissions.length > 0 && !isOwner) {
|
||||
const guild = msg.message?.guild ?? null;
|
||||
if (!guild) {
|
||||
this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg);
|
||||
return false;
|
||||
}
|
||||
|
||||
const member = guild.members.get(authorId) ?? null;
|
||||
if (member?.permissions) {
|
||||
const missing = req.permissions.filter(p => !member.permissions.has(PermissionFlags[p] ?? p));
|
||||
if (missing.length > 0) {
|
||||
this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
const fetchPromise = typeof guild.fetchMember === "function"
|
||||
? guild.fetchMember(authorId)
|
||||
: typeof guild.members?.fetch === "function"
|
||||
? guild.members.fetch(authorId)
|
||||
: Promise.reject(new Error("No member fetch API available"));
|
||||
fetchPromise.then(member => {
|
||||
const missing = req.permissions.filter(p => !member.permissions.has(PermissionFlags[p] ?? p));
|
||||
if (missing.length > 0) {
|
||||
this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg);
|
||||
} else {
|
||||
const guildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
const prefix2 = this.getPrefix(guildId2);
|
||||
const rawContent = msg.message.content;
|
||||
const len2 = rawContent.startsWith(prefix2) ? prefix2.length : 0;
|
||||
const args = rawContent.slice(len2).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim());
|
||||
this.processCommand(cmd, args, msg, false, true);
|
||||
}
|
||||
}).catch(() => this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Validate an input for a given option type. @param {string} type @param {*} i @param {object} m @returns {boolean} */
|
||||
validateInput(type, i, m) { return (new Option()).validateInput(i, this.client, m, type); }
|
||||
/** Format an input for a given option type. @param {string} type @param {*} i @param {object} m @returns {*} */
|
||||
formatInput(type, i, m) { return (new Option()).formatInput(i, this.client, m, type); }
|
||||
|
||||
/** @private Build a type-error message for an option. @param {string} guildId @param {Option} option @param {*} value @param {string} previous @returns {string} */
|
||||
_optionTypeError(guildId, option, value, previous) {
|
||||
if (option.tError) {
|
||||
return option.tError.replace(/\$previousCmd/gi, previous).replace(/\$currValue/gi, value);
|
||||
}
|
||||
const localeKey = option.type === 'choice' ? 'cmdBuilder.option.invalidChoice'
|
||||
: (option.type === 'channel' || option.type === 'voiceChannel') ? 'cmdBuilder.option.invalidChannel'
|
||||
: 'cmdBuilder.option.invalidType';
|
||||
const choiceStr = option.type === 'choice'
|
||||
? (option.choices.length > Option.THRESHOLD ? Option.formatChoicesCompact(option.choices) : option.choices.map(c => '- ' + c).join('\n'))
|
||||
: '';
|
||||
return this.t(guildId, localeKey, {
|
||||
$currValue: value,
|
||||
$optionName: option.name,
|
||||
$type: option.type,
|
||||
$choices: choiceStr
|
||||
}).replace(/\$previousCmd/gi, previous);
|
||||
}
|
||||
|
||||
/** @private Build a text-wrap error message. @param {string} guildId @param {string} value @param {string} quote @returns {string} */
|
||||
_textWrapErrorMsg(guildId, value, quote) {
|
||||
return this.t(guildId, 'cmdHandler.textWrapError', { $value: value, $quote: quote });
|
||||
}
|
||||
|
||||
/** Register a command builder and sort the command list alphabetically. @param {CommandBuilder} builder @returns {CommandBuilder[]} */
|
||||
addCommand(builder) {
|
||||
this.commandNames.push(...builder.aliases);
|
||||
this.commands.push(builder);
|
||||
this.commands.sort((a, b) => {
|
||||
let A = a.name.toUpperCase();
|
||||
let B = b.name.toUpperCase();
|
||||
return (A < B) ? -1 : (A > B) ? 1 : 0;
|
||||
});
|
||||
return this.commands;
|
||||
}
|
||||
}
|
||||
|
||||
/** @class CommandLoader @description Dynamically loads command files from a directory, registers builders, and binds run handlers. */
|
||||
export class CommandLoader {
|
||||
/** @type {CommandHandler} Reference to the command handler. */
|
||||
commands;
|
||||
/** @type {Map<string, string>} Command UID → file path. */
|
||||
commandFiles = new Map();
|
||||
/** @type {Map<string, Function>} Command UID → run function. */
|
||||
runnables = new Map();
|
||||
/** @type {object} Shared context (the bot instance). */
|
||||
context;
|
||||
|
||||
/** @param {CommandHandler} commands @param {object} context - Bot context object. */
|
||||
constructor(commands, context) {
|
||||
this.commands = commands;
|
||||
this.context = context;
|
||||
this.context.loader ??= this;
|
||||
this.context.commandFiles = this.commandFiles;
|
||||
this.context.runnables = this.runnables;
|
||||
|
||||
this.commands.on("run", (data) => {
|
||||
if (!this.runnables.has(data.command.uid)) return;
|
||||
const runFc = this.runnables.get(data.command.uid);
|
||||
const sendErrorReply = (id) => {
|
||||
Promise.resolve(data.message.reply("An error occurred. Error id: `#" + id + "`"))
|
||||
.catch(err => logger.warn("[CommandHandler] Failed to send error-reply; error id #" + id + ":", err?.message));
|
||||
};
|
||||
try {
|
||||
const result = runFc.call(this.context, data.message, data);
|
||||
if (result && typeof result.catch === "function") {
|
||||
result.catch(e => {
|
||||
const id = Utils.uid();
|
||||
logger.error("Error running command; error id #" + id, e);
|
||||
sendErrorReply(id);
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
const id = Utils.uid();
|
||||
logger.error("Error running command; error id #" + id, e);
|
||||
sendErrorReply(id);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Normalize a module export to { command, run, exportDef }. @param {object} cData @returns {object} */
|
||||
canonData(cData) {
|
||||
if (cData.command !== undefined) {
|
||||
return {
|
||||
command: cData.command,
|
||||
run: cData.run,
|
||||
exportDef: cData.exportDef ?? cData.export ?? null
|
||||
};
|
||||
}
|
||||
const d = cData.default ?? cData;
|
||||
return {
|
||||
command: d.command,
|
||||
run: d.run,
|
||||
exportDef: d.exportDef ?? d.export ?? null
|
||||
};
|
||||
}
|
||||
|
||||
/** @async Load all command files from a directory. @param {string} dir @returns {Promise<undefined[]>} */
|
||||
loadFromDir(dir) {
|
||||
const files = fs.readdirSync(dir)
|
||||
.filter(f => !f.startsWith(".") && (f.endsWith(".js") || f.endsWith(".mjs")));
|
||||
|
||||
return Promise.all(files.map(async commandFile => {
|
||||
const file = path.join(dir, commandFile);
|
||||
|
||||
const cData = this.canonData(await import(pathToFileURL(file).href));
|
||||
|
||||
const builder = (typeof cData.command === "function")
|
||||
? cData.command.call(this.context)
|
||||
: cData.command;
|
||||
|
||||
if (!builder) return logger.warn("No builder returned. Skipping '" + commandFile + "'");
|
||||
|
||||
if (cData.exportDef)
|
||||
this.context[cData.exportDef.name] = cData.exportDef.object;
|
||||
|
||||
this.commands.addCommand(builder);
|
||||
this.commandFiles.set(builder.uid, file);
|
||||
|
||||
if (!cData.run) return;
|
||||
|
||||
this.runnables.set(builder.uid, cData.run);
|
||||
builder.subcommands.forEach(sub => {
|
||||
this.runnables.set(sub.uid, cData.run);
|
||||
});
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -1,879 +0,0 @@
|
||||
/** @module src/FluxerAudioBridge @description Audio bridge for streaming Lavalink/NodeLink audio through Fluxer voice connections. 100% in-process — Opus encoding via prism-media (native/WASM), WebM muxing via WebMOpusMuxer. No FFmpeg processes. Supports MP3/AAC/radio streams via Lavalink resolve-through. */
|
||||
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
import { WebMOpusMuxer, OPUS_FRAME_MS } from "./constants/audio/WebMOpusMuxer.mjs";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { Readable } from "node:stream";
|
||||
import http from "node:http";
|
||||
import https from "node:https";
|
||||
import prismMedia from "prism-media";
|
||||
|
||||
const { Encoder: PrismOpusEncoder, OggDemuxer: PrismOggDemuxer } = prismMedia.opus;
|
||||
|
||||
/** @type {number} @description Maximum number of HTTP redirect hops to follow. */
|
||||
const MAX_REDIRECTS = 5;
|
||||
|
||||
/** @type {number} @description Timeout (ms) for HTTP requests to Lavalink REST endpoints (trackstream, loadtracks JSON). */
|
||||
const REST_REQUEST_TIMEOUT_MS = 15_000;
|
||||
|
||||
/** @type {number} @description Timeout (ms) to wait for the first byte from loadstream (Lavalink may need time to resolve HLS/external streams). */
|
||||
const LOADSTREAM_CONNECT_TIMEOUT_MS = 60_000;
|
||||
|
||||
/** @type {number} @description Idle timeout (ms) once loadstream data is flowing — if no data arrives for this long, abort. */
|
||||
const LOADSTREAM_IDLE_TIMEOUT_MS = 30_000;
|
||||
|
||||
/** @type {number} @description PCM sample rate expected from NodeLink loadstream (48kHz stereo s16le). */
|
||||
const PCM_RATE = 48000;
|
||||
/** @type {number} @description PCM channel count expected from NodeLink loadstream. */
|
||||
const PCM_CHANNELS = 2;
|
||||
/** @type {number} @description Opus frame size in samples per channel (20ms @ 48kHz). */
|
||||
const PCM_FRAME_SIZE = 960;
|
||||
/** @type {number} @description Opus encoding bitrate. */
|
||||
const OPUS_BITRATE = 128000;
|
||||
|
||||
/** @type {Buffer} @description WebM/Matroska EBML magic bytes. */
|
||||
const WEBM_MAGIC = Buffer.from([0x1a, 0x45, 0xdf, 0xa3]);
|
||||
/** @type {Buffer} @description OGG container magic bytes ("OggS"). */
|
||||
const OGG_MAGIC = Buffer.from("OggS", "ascii");
|
||||
|
||||
/** @type {number} @description livekit TrackKind.KIND_AUDIO — publications with this kind are managed by the bridge. */
|
||||
const TRACK_KIND_AUDIO = 1;
|
||||
|
||||
/** @extends {EventEmitter} */
|
||||
export class FluxerAudioBridge extends EventEmitter {
|
||||
_conn = null;
|
||||
_stream = null;
|
||||
_encoder = null;
|
||||
_sourceStream = null;
|
||||
_sourceReq = null;
|
||||
_playing = false;
|
||||
_stopped = false;
|
||||
_startedAt = 0;
|
||||
_currentUri = null;
|
||||
_lavalink = null;
|
||||
_playGeneration = 0;
|
||||
_durationTimer = null;
|
||||
_endResolve = null;
|
||||
_endReject = null;
|
||||
_usedTrackstream = false;
|
||||
|
||||
/** @type {boolean} @description Whether audio is currently playing. */
|
||||
get playing() { return this._playing; }
|
||||
/** @type {number} @description Timestamp (ms) when playback started. */
|
||||
get startedAt() { return this._startedAt; }
|
||||
/** @type {string|null} @description URI of the currently playing track. */
|
||||
get currentUri() { return this._currentUri; }
|
||||
|
||||
/** @param {LavalinkManager|null} lavalinkManager - LavalinkManager for trackstream/loadstream. */
|
||||
constructor(lavalinkManager = null) {
|
||||
super();
|
||||
this._lavalink = lavalinkManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Play a track through a Fluxer voice connection, entirely in-process.
|
||||
* Routing order:
|
||||
* 1. trackstream passthrough (seek=0, no filters) — NodeLink hands back a WebM/Opus
|
||||
* direct URL which the voice connection plays natively (zero re-encode).
|
||||
* 2. loadstream — NodeLink returns raw PCM (48k stereo s16le) with server-side
|
||||
* seek/filters; PCM is Opus-encoded in-process and muxed to WebM.
|
||||
* 3. direct URL fallback — magic-byte sniff: WebM passthrough or Ogg/Opus remux.
|
||||
* @param {object} conn - Fluxer voice connection
|
||||
* @param {object} trackInfo - Track metadata (encoded, title, url, guildId)
|
||||
* @param {object} [options]
|
||||
* @param {number} [options.seekSeconds=0]
|
||||
* @param {number} [options.durationMs=0]
|
||||
* @param {object} [options.filterPayload]
|
||||
* @returns {Promise<"finished"|"stopped">}
|
||||
*/
|
||||
async play(conn, trackInfo, options = {}) {
|
||||
this.stop();
|
||||
if (!conn) throw new Error("[AudioBridge] No voice connection provided");
|
||||
|
||||
this._unpublishStaleAudioTracks(conn);
|
||||
|
||||
const generation = ++this._playGeneration;
|
||||
this._conn = conn;
|
||||
this._playing = true;
|
||||
this._stopped = false;
|
||||
this._startedAt = Date.now();
|
||||
this._currentUri = trackInfo?.url ?? trackInfo?.title ?? "unknown";
|
||||
this._usedTrackstream = false;
|
||||
|
||||
const seekMs = Math.floor((options.seekSeconds ?? 0) * 1000);
|
||||
let durationMs = options.durationMs || 0;
|
||||
|
||||
try {
|
||||
if (seekMs === 0 && !options.filterPayload && trackInfo.encoded && this._lavalink) {
|
||||
try {
|
||||
const direct = await this._getTrackstreamUrl(trackInfo);
|
||||
if (direct?.url && /webm|opus/i.test(direct.format || "")) {
|
||||
this._usedTrackstream = true;
|
||||
logger.player("[AudioBridge] Passthrough webm/opus via trackstream (zero-copy): " + (trackInfo.title || "unknown"));
|
||||
|
||||
await conn.play(direct.url);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
if (durationMs > 0) await this._waitDuration(durationMs);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
if (this._playing && !this._stopped) {
|
||||
this._playing = false;
|
||||
logger.player("[AudioBridge] Track finished naturally (trackstream passthrough)");
|
||||
return "finished";
|
||||
}
|
||||
return "stopped";
|
||||
}
|
||||
if (direct?.url && this._lavalink && trackInfo.url && trackInfo.url.startsWith("http")) {
|
||||
logger.player("[AudioBridge] trackstream format " + (direct.format || "?") + " — resolving original source URL via Lavalink for fresh encoded track...");
|
||||
const freshEncoded = await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId);
|
||||
if (freshEncoded) {
|
||||
trackInfo.encoded = freshEncoded;
|
||||
logger.player("[AudioBridge] Fresh encoded track obtained — retrying trackstream for webm/opus...");
|
||||
try {
|
||||
const freshDirect = await this._getTrackstreamUrl(trackInfo);
|
||||
if (freshDirect?.url && /webm|opus/i.test(freshDirect.format || "")) {
|
||||
this._usedTrackstream = true;
|
||||
logger.player("[AudioBridge] Fresh trackstream is webm/opus — zero-copy passthrough: " + (trackInfo.title || "unknown"));
|
||||
await conn.play(freshDirect.url);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
if (durationMs > 0) await this._waitDuration(durationMs);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
if (this._playing && !this._stopped) {
|
||||
this._playing = false;
|
||||
logger.player("[AudioBridge] Track finished naturally (fresh trackstream passthrough)");
|
||||
return "finished";
|
||||
}
|
||||
return "stopped";
|
||||
}
|
||||
logger.player("[AudioBridge] Fresh trackstream also " + (freshDirect?.format || "?") + ", falling through to loadstream");
|
||||
} catch (e2) {
|
||||
logger.player("[AudioBridge] Fresh trackstream failed, falling through to loadstream: " + e2.message);
|
||||
}
|
||||
} else {
|
||||
logger.player("[AudioBridge] Could not resolve source URL via Lavalink, using original encoded track for loadstream");
|
||||
}
|
||||
} else {
|
||||
logger.player("[AudioBridge] trackstream format not opus/webm (" + (direct?.format || "?") + "), falling through to loadstream");
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[AudioBridge] Trackstream failed, falling back to loadstream: " + e.message);
|
||||
this._playing = true;
|
||||
this._stopped = false;
|
||||
this._startedAt = Date.now();
|
||||
}
|
||||
}
|
||||
|
||||
if (trackInfo.encoded && this._lavalink) {
|
||||
const loaded = await this._streamFromLoadstream(trackInfo, seekMs, options.filterPayload);
|
||||
if (generation !== this._playGeneration) {
|
||||
loaded.stream.destroy();
|
||||
return "stopped";
|
||||
}
|
||||
|
||||
const routed = await this._routeByMagic(loaded.stream);
|
||||
this._sourceStream = loaded.stream;
|
||||
this._sourceReq = loaded.req || null;
|
||||
|
||||
if (routed.kind === "webm") {
|
||||
logger.player("[AudioBridge] Playing loadstream webm/opus passthrough: " + (trackInfo.title || "unknown") +
|
||||
(seekMs > 0 ? " [seek: " + seekMs + "ms]" : ""));
|
||||
this._stream = routed.stream;
|
||||
await conn.play(routed.stream);
|
||||
} else if (routed.kind === "ogg") {
|
||||
logger.player("[AudioBridge] Playing loadstream ogg/opus (remux to webm): " + (trackInfo.title || "unknown"));
|
||||
const oggResult = await this._remuxOggToWebM(routed.stream);
|
||||
this._stream = oggResult;
|
||||
if (durationMs <= 0) durationMs = oggResult.getDurationMs();
|
||||
await conn.play(this._stream);
|
||||
} else {
|
||||
logger.player("[AudioBridge] Playing via loadstream PCM -> in-process Opus: " + (trackInfo.title || "unknown") +
|
||||
(seekMs > 0 ? " [seek: " + seekMs + "ms]" : "") +
|
||||
(options.filterPayload ? " [filters]" : ""));
|
||||
this._stream = this._buildPcmPipeline(routed.stream);
|
||||
await conn.play(this._stream);
|
||||
}
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
await this._awaitEnd(durationMs);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
if (this._playing && !this._stopped) {
|
||||
this._playing = false;
|
||||
logger.player("[AudioBridge] Track finished naturally (loadstream)");
|
||||
return "finished";
|
||||
}
|
||||
return "stopped";
|
||||
}
|
||||
|
||||
if (trackInfo.url && trackInfo.url.startsWith("http")) {
|
||||
logger.player("[AudioBridge] Route 3: Fetching directly: " + trackInfo.url.substring(0, 80) + "...");
|
||||
const response = await fetch(trackInfo.url, {
|
||||
headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)" },
|
||||
redirect: "follow",
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error("HTTP " + response.status + " for " + trackInfo.url);
|
||||
}
|
||||
const stream = Readable.fromWeb(response.body);
|
||||
this._sourceStream = stream;
|
||||
|
||||
const routed = await this._routeByMagic(stream);
|
||||
if (routed.kind === "webm") {
|
||||
logger.player("[AudioBridge] Route 3a: webm/opus passthrough: " + (trackInfo.title || "unknown"));
|
||||
this._stream = routed.stream;
|
||||
await conn.play(routed.stream);
|
||||
} else if (routed.kind === "ogg") {
|
||||
logger.player("[AudioBridge] Route 3b: ogg/opus remux to webm: " + (trackInfo.title || "unknown"));
|
||||
const oggResult = await this._remuxOggToWebM(routed.stream);
|
||||
this._stream = oggResult;
|
||||
await conn.play(this._stream);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
await new Promise(r => {
|
||||
if (this._stream.readableEnded) return r();
|
||||
const done = () => { this._stream.off("end", done); this._stream.off("close", done); r(); };
|
||||
this._stream.once("end", done);
|
||||
this._stream.once("close", done);
|
||||
});
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
const fullDurationMs = oggResult.getDurationMs();
|
||||
const elapsedMs = Date.now() - this._startedAt;
|
||||
const remainingMs = Math.max(0, fullDurationMs - elapsedMs);
|
||||
logger.player("[AudioBridge] Route 3b: OGG " + fullDurationMs + "ms total, " + elapsedMs + "ms elapsed, waiting " + remainingMs + "ms more");
|
||||
|
||||
if (remainingMs > 0) await this._awaitEnd(remainingMs);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
if (this._playing && !this._stopped) {
|
||||
this._playing = false;
|
||||
logger.player("[AudioBridge] Track finished naturally (direct URL, OGG remux)");
|
||||
return "finished";
|
||||
}
|
||||
return "stopped";
|
||||
} else {
|
||||
stream.destroy();
|
||||
this._sourceStream = null;
|
||||
logger.player("[AudioBridge] Route 3c: Direct stream is " + routed.kind + " (MP3/AAC?) — resolving through Lavalink...");
|
||||
|
||||
if (this._lavalink) {
|
||||
const encoded = await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId);
|
||||
if (encoded) {
|
||||
trackInfo.encoded = encoded;
|
||||
logger.player("[AudioBridge] Route 3c: Got encoded track from Lavalink, retrying via loadstream...");
|
||||
const loaded = await this._streamFromLoadstream(trackInfo, 0, null);
|
||||
if (generation !== this._playGeneration) {
|
||||
loaded.stream.destroy();
|
||||
return "stopped";
|
||||
}
|
||||
|
||||
const routed2 = await this._routeByMagic(loaded.stream);
|
||||
this._sourceStream = loaded.stream;
|
||||
this._sourceReq = loaded.req || null;
|
||||
|
||||
if (routed2.kind === "webm") {
|
||||
logger.player("[AudioBridge] Route 3c (Lavalink): webm/opus passthrough");
|
||||
this._stream = routed2.stream;
|
||||
await conn.play(routed2.stream);
|
||||
} else if (routed2.kind === "ogg") {
|
||||
logger.player("[AudioBridge] Route 3c (Lavalink): ogg/opus remux to webm");
|
||||
const oggResult3c = await this._remuxOggToWebM(routed2.stream);
|
||||
this._stream = oggResult3c;
|
||||
if (durationMs <= 0) durationMs = oggResult3c.getDurationMs();
|
||||
await conn.play(this._stream);
|
||||
} else {
|
||||
logger.player("[AudioBridge] Route 3c (Lavalink): PCM -> Opus -> WebM");
|
||||
this._stream = this._buildPcmPipeline(routed2.stream);
|
||||
await conn.play(this._stream);
|
||||
}
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
await this._awaitEnd(durationMs);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
if (this._playing && !this._stopped) {
|
||||
this._playing = false;
|
||||
logger.player("[AudioBridge] Track finished naturally (Route 3c Lavalink resolve)");
|
||||
return "finished";
|
||||
}
|
||||
return "stopped";
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
"[AudioBridge] Direct URL is not WebM/Opus or Ogg/Opus (" + routed.kind + "). " +
|
||||
"Lavalink resolve also failed or is unavailable. " +
|
||||
"Make sure your Lavalink/NodeLink node is running and can decode this stream format."
|
||||
);
|
||||
}
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
await this._awaitEnd(durationMs);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
if (this._playing && !this._stopped) {
|
||||
this._playing = false;
|
||||
logger.player("[AudioBridge] Track finished naturally (direct URL)");
|
||||
return "finished";
|
||||
}
|
||||
return "stopped";
|
||||
}
|
||||
|
||||
throw new Error("Could not get audio stream for: " + (trackInfo.title || trackInfo.url || "unknown"));
|
||||
|
||||
} catch (e) {
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
if (this._stopped || !this._playing) return "stopped";
|
||||
this._playing = false;
|
||||
logger.error("[AudioBridge] Playback error: " + e.message);
|
||||
throw e;
|
||||
} finally {
|
||||
this._cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Wait for playback end: duration timer for fixed-length tracks, pipeline
|
||||
* end event for live/radio streams (durationMs = 0). Rejects early on
|
||||
* pipeline errors so the player can skip to the next track.
|
||||
* @param {number} durationMs
|
||||
* @returns {Promise<void>}
|
||||
* @private
|
||||
*/
|
||||
_awaitEnd(durationMs) { return new Promise((resolve, reject) => {
|
||||
this._endResolve = resolve;
|
||||
this._endReject = reject;
|
||||
const failFast = (err) => {
|
||||
if (this._playing && !this._stopped) {
|
||||
this._playing = false;
|
||||
reject(err);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
|
||||
if (durationMs > 0) {
|
||||
this._durationTimer = setTimeout(resolve, durationMs);
|
||||
} else {
|
||||
const stream = this._stream;
|
||||
if (!stream) return resolve();
|
||||
const onEnd = () => resolve();
|
||||
stream.once("end", onEnd);
|
||||
stream.once("close", onEnd);
|
||||
stream.once("error", failFast);
|
||||
}
|
||||
|
||||
if (this._sourceStream) {
|
||||
this._sourceStream.once("error", failFast);
|
||||
}
|
||||
if (this._encoder) {
|
||||
this._encoder.once("error", failFast);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Simple timed wait used by the trackstream passthrough route (no local
|
||||
* pipeline to watch). Resolves early if stopped.
|
||||
* @param {number} durationMs
|
||||
* @returns {Promise<void>}
|
||||
* @private
|
||||
*/
|
||||
_waitDuration(durationMs) {
|
||||
return new Promise((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
this._durationTimer = null;
|
||||
resolve();
|
||||
}, durationMs);
|
||||
this._durationTimer = timer;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Peek at the first bytes of a stream and classify it, pushing the peeked
|
||||
* bytes back so nothing is lost.
|
||||
* @param {Readable} stream
|
||||
* @returns {Promise<{stream: Readable, kind: "webm"|"ogg"|"pcm"}>}
|
||||
* @private
|
||||
*/
|
||||
async _routeByMagic(stream) {
|
||||
const head = await this._peek(stream, 4);
|
||||
if (head.length >= 4 && head.subarray(0, 4).equals(WEBM_MAGIC)) return { stream, kind: "webm" };
|
||||
if (head.length >= 4 && head.subarray(0, 4).equals(OGG_MAGIC)) return { stream, kind: "ogg" };
|
||||
return { stream, kind: "pcm" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Read up to `n` bytes from a paused-mode stream, then unshift them.
|
||||
* @param {Readable} stream
|
||||
* @param {number} n
|
||||
* @returns {Promise<Buffer>}
|
||||
* @private
|
||||
*/
|
||||
_peek(stream, n) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const tryRead = () => {
|
||||
const chunks = [];
|
||||
let total = 0;
|
||||
let chunk;
|
||||
while (total < n && (chunk = stream.read()) !== null) {
|
||||
chunks.push(chunk);
|
||||
total += chunk.length;
|
||||
}
|
||||
if (total >= n || stream.readableEnded) {
|
||||
const buf = Buffer.concat(chunks);
|
||||
cleanup();
|
||||
if (buf.length > 0) stream.unshift(buf);
|
||||
resolve(buf.subarray(0, n));
|
||||
return;
|
||||
}
|
||||
};
|
||||
const onReadable = () => { cleanup(); tryRead(); };
|
||||
const onEnd = () => { cleanup(); tryRead(); };
|
||||
const onError = (err) => { cleanup(); reject(err); };
|
||||
const cleanup = () => {
|
||||
stream.off("readable", onReadable);
|
||||
stream.off("end", onEnd);
|
||||
stream.off("error", onError);
|
||||
};
|
||||
stream.once("readable", onReadable);
|
||||
stream.once("end", onEnd);
|
||||
stream.once("error", onError);
|
||||
tryRead();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the in-process PCM -> Opus -> WebM pipeline.
|
||||
* @param {Readable} pcmStream - s16le 48kHz stereo byte stream
|
||||
* @returns {WebMOpusMuxer} - byte stream consumable by conn.play()
|
||||
* @private
|
||||
*/
|
||||
_buildPcmPipeline(pcmStream) {
|
||||
let encoder;
|
||||
try {
|
||||
encoder = new PrismOpusEncoder({
|
||||
rate: PCM_RATE,
|
||||
channels: PCM_CHANNELS,
|
||||
frameSize: PCM_FRAME_SIZE,
|
||||
});
|
||||
} catch (e) {
|
||||
pcmStream.destroy();
|
||||
throw new Error(
|
||||
"No Opus encoder available (" + e.message + "). Install one: npm install @discordjs/opus (or opusscript)"
|
||||
);
|
||||
}
|
||||
try { encoder.setBitrate(OPUS_BITRATE); } catch (_) {}
|
||||
|
||||
const muxer = new WebMOpusMuxer({ sampleRate: PCM_RATE, channels: PCM_CHANNELS });
|
||||
this._encoder = encoder;
|
||||
|
||||
pcmStream.on("error", (err) => {
|
||||
logger.warn("[AudioBridge] PCM source error: " + err.message);
|
||||
encoder.destroy(err);
|
||||
});
|
||||
encoder.on("error", (err) => {
|
||||
muxer.destroy(err);
|
||||
});
|
||||
|
||||
pcmStream.pipe(encoder).pipe(muxer);
|
||||
return muxer;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remux an Ogg/Opus stream into WebM/Opus (packet-level, no re-encode).
|
||||
* @param {Readable} oggStream
|
||||
* @returns {Promise<{stream: WebMOpusMuxer, getDurationMs: function}>}
|
||||
* @private
|
||||
*/
|
||||
async _remuxOggToWebM(oggStream) {
|
||||
const demuxer = new PrismOggDemuxer();
|
||||
const muxer = new WebMOpusMuxer();
|
||||
oggStream.on("error", (err) => demuxer.destroy(err));
|
||||
demuxer.on("error", (err) => muxer.destroy(err));
|
||||
let frameCount = 0;
|
||||
demuxer.on("data", () => { frameCount++; });
|
||||
const headPromise = new Promise((resolve, reject) => {
|
||||
demuxer.once("head", () => resolve());
|
||||
demuxer.once("error", (err) => reject(new Error("OGG demux: " + err.message)));
|
||||
oggStream.once("error", (err) => reject(new Error("OGG source: " + err.message)));
|
||||
});
|
||||
oggStream.pipe(demuxer).pipe(muxer);
|
||||
await headPromise;
|
||||
const wrapper = Object.create(muxer);
|
||||
wrapper.getDurationMs = () => frameCount * OPUS_FRAME_MS;
|
||||
return wrapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} trackInfo
|
||||
* @returns {Promise<{url: string, format: string}>}
|
||||
* @private
|
||||
*/
|
||||
async _getTrackstreamUrl(trackInfo) {
|
||||
const nlInfo = this._lavalink.getNodeLinkInfo?.();
|
||||
if (!nlInfo) throw new Error("NodeLink info not available");
|
||||
|
||||
const protocol = nlInfo.secure ? "https" : "http";
|
||||
const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port;
|
||||
|
||||
const headers = { "Authorization": nlInfo.password };
|
||||
if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId;
|
||||
if (trackInfo.guildId) headers["Guild-Id"] = trackInfo.guildId;
|
||||
|
||||
const params = "encodedTrack=" + encodeURIComponent(trackInfo.encoded);
|
||||
const url = baseUrl + "/v4/trackstream?" + params;
|
||||
|
||||
logger.player("[AudioBridge] Querying /v4/trackstream...");
|
||||
|
||||
const body = await this._httpGetJson(url, headers);
|
||||
|
||||
const directUrl = body?.url;
|
||||
if (!directUrl || typeof directUrl !== "string") {
|
||||
throw new Error("trackstream returned no URL");
|
||||
}
|
||||
|
||||
const format = body?.format || "";
|
||||
logger.player("[AudioBridge] trackstream: format=" + format + " url=" + directUrl.substring(0, 100) + "...");
|
||||
|
||||
return { url: directUrl, format };
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} trackInfo
|
||||
* @param {number} [seekMs=0]
|
||||
* @param {object|null} [filterPayload]
|
||||
* @returns {Promise<{stream: Readable, inputFormat: string|null}>}
|
||||
* @private
|
||||
*/
|
||||
async _streamFromLoadstream(trackInfo, seekMs = 0, filterPayload = null) {
|
||||
const nlInfo = this._lavalink.getNodeLinkInfo?.();
|
||||
if (!nlInfo) {
|
||||
throw new Error("NodeLink info not available");
|
||||
}
|
||||
|
||||
const protocol = nlInfo.secure ? "https" : "http";
|
||||
const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port;
|
||||
|
||||
const headers = { "Authorization": nlInfo.password };
|
||||
if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId;
|
||||
if (trackInfo.guildId) headers["Guild-Id"] = trackInfo.guildId;
|
||||
|
||||
let baseParams = "encodedTrack=" + encodeURIComponent(trackInfo.encoded) + "&position=" + seekMs + "&volume=100";
|
||||
if (filterPayload) {
|
||||
baseParams += "&filters=" + encodeURIComponent(JSON.stringify(filterPayload));
|
||||
}
|
||||
|
||||
const url = baseUrl + "/v4/loadstream?" + baseParams;
|
||||
logger.player("[AudioBridge] Querying /v4/loadstream (seek: " + seekMs + "ms)...");
|
||||
|
||||
return this._httpRequestStream(url, headers);
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a direct audio URL through Lavalink's /v4/loadtracks to get an encoded track.
|
||||
* This allows MP3/AAC radio streams and direct audio URLs to be played through
|
||||
* the loadstream pipeline without any FFmpeg dependency.
|
||||
* @param {string} url - The HTTP(S) audio stream URL to resolve.
|
||||
* @param {string} [guildId] - Optional guild ID for the request.
|
||||
* @returns {Promise<string|null>} The encoded track string, or null if resolution failed.
|
||||
* @private
|
||||
*/
|
||||
async _resolveUrlViaLavalink(url, guildId) {
|
||||
try {
|
||||
const nlInfo = this._lavalink.getNodeLinkInfo?.();
|
||||
if (!nlInfo) {
|
||||
logger.warn("[AudioBridge] _resolveUrlViaLavalink: no NodeLink info");
|
||||
return null;
|
||||
}
|
||||
|
||||
const protocol = nlInfo.secure ? "https" : "http";
|
||||
const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port;
|
||||
|
||||
const headers = { "Authorization": nlInfo.password };
|
||||
if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId;
|
||||
if (guildId) headers["Guild-Id"] = guildId;
|
||||
|
||||
const params = "identifier=" + encodeURIComponent(url);
|
||||
const loadtracksUrl = baseUrl + "/v4/loadtracks?" + params;
|
||||
|
||||
logger.player("[AudioBridge] Resolving URL via Lavalink /v4/loadtracks: " + url.substring(0, 80) + "...");
|
||||
|
||||
const body = await this._httpGetJson(loadtracksUrl, headers, 0, 30_000);
|
||||
|
||||
const track = body?.data?.tracks?.[0] ?? body?.tracks?.[0] ?? body?.data;
|
||||
const encoded = track?.encoded ?? track?.data;
|
||||
|
||||
if (encoded && typeof encoded === "string") {
|
||||
logger.player("[AudioBridge] Lavalink resolved URL to encoded track successfully");
|
||||
return encoded;
|
||||
}
|
||||
|
||||
const loadType = body?.loadType ?? body?.data?.loadType;
|
||||
logger.warn("[AudioBridge] Lavalink loadtracks returned no playable track (loadType=" + loadType + ")");
|
||||
return null;
|
||||
} catch (e) {
|
||||
logger.warn("[AudioBridge] _resolveUrlViaLavalink failed: " + e.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} url
|
||||
* @param {object} [headers]
|
||||
* @returns {Promise<object>}
|
||||
* @private
|
||||
*/
|
||||
_httpGetJson(url, headers = {}, _redirectCount = 0, timeoutMs = REST_REQUEST_TIMEOUT_MS) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (_redirectCount >= MAX_REDIRECTS) {
|
||||
return reject(new Error("Too many redirects (" + _redirectCount + ")"));
|
||||
}
|
||||
const urlObj = new URL(url);
|
||||
const client = urlObj.protocol === "https:" ? https : http;
|
||||
|
||||
const req = client.request({
|
||||
protocol: urlObj.protocol,
|
||||
host: urlObj.hostname,
|
||||
port: urlObj.port,
|
||||
path: urlObj.pathname + urlObj.search,
|
||||
method: "GET",
|
||||
headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)", ...headers },
|
||||
}, (res) => {
|
||||
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
||||
res.resume();
|
||||
let loc = res.headers.location;
|
||||
if (loc.startsWith("/")) loc = urlObj.protocol + "//" + urlObj.host + loc;
|
||||
return this._httpGetJson(loc, headers, _redirectCount + 1, timeoutMs).then(resolve, reject);
|
||||
}
|
||||
if (res.statusCode !== 200) {
|
||||
let body = "";
|
||||
res.on("data", (chunk) => { body += chunk; });
|
||||
res.on("end", () => {
|
||||
reject(new Error("HTTP " + res.statusCode + " for " + url + ": " + body.substring(0, 300)));
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
let data = "";
|
||||
res.on("data", (chunk) => { data += chunk; });
|
||||
res.on("end", () => {
|
||||
try {
|
||||
resolve(JSON.parse(data));
|
||||
} catch (e) {
|
||||
reject(new Error("Invalid JSON from trackstream: " + data.substring(0, 200)));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
req.on("socket", (socket) => {
|
||||
socket.on("error", () => {});
|
||||
});
|
||||
req.on("error", reject);
|
||||
req.setTimeout(timeoutMs, () => {
|
||||
req.destroy();
|
||||
reject(new Error("REST request timeout (" + timeoutMs / 1000 + "s)"));
|
||||
});
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} url
|
||||
* @param {object} [headers]
|
||||
* @param {number} [_redirectCount=0]
|
||||
* @returns {Promise<{stream: Readable, inputFormat: string|null, req: http.ClientRequest}>}
|
||||
* @private
|
||||
*/
|
||||
_httpRequestStream(url, headers = {}, _redirectCount = 0) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (_redirectCount >= MAX_REDIRECTS) {
|
||||
return reject(new Error("Too many redirects (" + _redirectCount + ")"));
|
||||
}
|
||||
|
||||
const urlObj = new URL(url);
|
||||
const client = urlObj.protocol === "https:" ? https : http;
|
||||
let firstByte = true;
|
||||
let connectTimer = null;
|
||||
let idleTimer = null;
|
||||
|
||||
const resetIdleTimeout = () => {
|
||||
if (idleTimer) clearTimeout(idleTimer);
|
||||
idleTimer = setTimeout(() => {
|
||||
req.destroy();
|
||||
reject(new Error("loadstream idle timeout (" + LOADSTREAM_IDLE_TIMEOUT_MS / 1000 + "s no data)"));
|
||||
}, LOADSTREAM_IDLE_TIMEOUT_MS);
|
||||
idleTimer.unref?.();
|
||||
};
|
||||
|
||||
const req = client.request({
|
||||
protocol: urlObj.protocol,
|
||||
host: urlObj.hostname,
|
||||
port: urlObj.port,
|
||||
path: urlObj.pathname + urlObj.search,
|
||||
method: "GET",
|
||||
headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)", ...headers },
|
||||
}, (res) => {
|
||||
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
||||
if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; }
|
||||
res.resume();
|
||||
let nextHeaders = headers;
|
||||
let loc = res.headers.location;
|
||||
if (loc.startsWith("/")) loc = urlObj.protocol + "//" + urlObj.host + loc;
|
||||
try {
|
||||
const redirectHost = new URL(loc).hostname;
|
||||
if (redirectHost !== urlObj.hostname) {
|
||||
const { Authorization, "Session-Id": _, ...safe } = headers;
|
||||
nextHeaders = safe;
|
||||
}
|
||||
} catch (_) {}
|
||||
return this._httpRequestStream(loc, nextHeaders, _redirectCount + 1).then(resolve, reject);
|
||||
}
|
||||
if (res.statusCode !== 200) {
|
||||
if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; }
|
||||
let body = "";
|
||||
res.on("data", (chunk) => { body += chunk; });
|
||||
res.on("end", () => {
|
||||
reject(new Error("HTTP " + res.statusCode + " for " + url + ": " + body.substring(0, 300)));
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; }
|
||||
resetIdleTimeout();
|
||||
res.once("data", () => resetIdleTimeout());
|
||||
|
||||
logger.player("[AudioBridge] loadstream response: " + res.statusCode + " content-type=" + (res.headers["content-type"] || "?"));
|
||||
resolve({ stream: res, inputFormat: res.headers["content-type"] || null, req });
|
||||
});
|
||||
|
||||
req.on("socket", (socket) => {
|
||||
socket.on("error", () => {});
|
||||
});
|
||||
|
||||
req.on("error", (err) => {
|
||||
if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; }
|
||||
if (idleTimer) { clearTimeout(idleTimer); idleTimer = null; }
|
||||
reject(err);
|
||||
});
|
||||
|
||||
connectTimer = setTimeout(() => {
|
||||
req.destroy();
|
||||
reject(new Error("loadstream connect timeout (" + LOADSTREAM_CONNECT_TIMEOUT_MS / 1000 + "s — Lavalink took too long to start stream)"));
|
||||
}, LOADSTREAM_CONNECT_TIMEOUT_MS);
|
||||
connectTimer.unref?.();
|
||||
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
/** Stop current playback and clean up resources. */
|
||||
stop() {
|
||||
const wasPlaying = this._playing;
|
||||
this._stopped = true;
|
||||
this._playing = false;
|
||||
this._playGeneration++;
|
||||
|
||||
this._cleanup();
|
||||
|
||||
if (this._conn) {
|
||||
try { this._conn.stop(); } catch (_) {}
|
||||
this._unpublishStaleAudioTracks(this._conn);
|
||||
}
|
||||
|
||||
if (wasPlaying) {
|
||||
this.emit("stopped");
|
||||
logger.player("[AudioBridge] Playback stopped");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} conn - Fluxer voice connection
|
||||
* @param {string|null} [keepSid=null] - Track SID to keep (currently active publication)
|
||||
* @private
|
||||
*/
|
||||
_unpublishStaleAudioTracks(conn, keepSid = null) {
|
||||
try {
|
||||
const room = conn?.room;
|
||||
const participant = room?.localParticipant;
|
||||
if (!room?.isConnected || typeof participant?.unpublishTrack !== "function") return;
|
||||
|
||||
const publications = participant.trackPublications;
|
||||
if (!publications || typeof publications.entries !== "function") return;
|
||||
|
||||
for (const [sid, pub] of publications.entries()) {
|
||||
if (keepSid && sid === keepSid) continue;
|
||||
if (pub?.kind !== TRACK_KIND_AUDIO) continue;
|
||||
try {
|
||||
const p = participant.unpublishTrack(sid, true);
|
||||
if (p?.catch) p.catch(() => {});
|
||||
logger.player("[AudioBridge] Unpublished stale audio track: " + sid);
|
||||
} catch (_) {}
|
||||
}
|
||||
} catch (_) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the playback volume on the voice connection.
|
||||
* @param {number} percent - Volume 0–100.
|
||||
*/
|
||||
setVolume(percent) {
|
||||
if (this._conn) {
|
||||
try { this._conn.setVolume(percent); } catch (e) {
|
||||
logger.warn("[AudioBridge] setVolume error: " + e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @returns {number} Current volume percentage (0–100). */
|
||||
getVolume() {
|
||||
if (this._conn) {
|
||||
try { return this._conn.getVolume(); } catch (_) {}
|
||||
}
|
||||
return 100;
|
||||
}
|
||||
|
||||
/** @returns {boolean} Whether the voice connection is currently active. */
|
||||
isConnected() {
|
||||
if (this._conn) {
|
||||
try { return this._conn.isConnected(); } catch (_) {}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear timers, settle pending waits, and tear down the pipeline.
|
||||
* @private
|
||||
*/
|
||||
_cleanup() {
|
||||
if (this._durationTimer) { clearTimeout(this._durationTimer); this._durationTimer = null; }
|
||||
if (this._endResolve) {
|
||||
const resolve = this._endResolve;
|
||||
this._endResolve = null;
|
||||
this._endReject = null;
|
||||
resolve();
|
||||
}
|
||||
for (const s of [this._stream, this._encoder, this._sourceStream]) {
|
||||
if (s) {
|
||||
try { s.destroy(); } catch (_) {}
|
||||
}
|
||||
}
|
||||
if (this._sourceReq) {
|
||||
try { this._sourceReq.destroy(); } catch (_) {}
|
||||
}
|
||||
this._stream = null;
|
||||
this._encoder = null;
|
||||
this._sourceStream = null;
|
||||
this._sourceReq = null;
|
||||
}
|
||||
|
||||
/** Stop playback, release the voice connection, and remove all listeners. */
|
||||
destroy() {
|
||||
this.stop();
|
||||
this._conn = null;
|
||||
this._currentUri = null;
|
||||
this.removeAllListeners();
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
-2105
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,166 @@
|
||||
/**
|
||||
* @module src/commands/CommandBuilder
|
||||
* @description Fluent builder for command definitions (name, description,
|
||||
* options, subcommands, aliases, requirements) plus the permission
|
||||
* requirement model.
|
||||
*/
|
||||
|
||||
import { Utils } from "../utils/Utils.mjs";
|
||||
import { Option } from "./Option.mjs";
|
||||
|
||||
/**
|
||||
* @class CommandRequirement
|
||||
* @description Permission and owner-only gating for a command.
|
||||
*/
|
||||
export class CommandRequirement {
|
||||
/** @type {boolean} Whether the command is restricted to bot owners. */
|
||||
ownerOnly = false;
|
||||
|
||||
/** Create a new CommandRequirement with no permissions. */
|
||||
constructor() {
|
||||
this.permissions = [];
|
||||
this.permissionError = "You don't have the needed permissions to run this command!";
|
||||
return this;
|
||||
}
|
||||
|
||||
/** @param {boolean} bool @returns {CommandRequirement} */
|
||||
setOwnerOnly(bool) { this.ownerOnly = bool; return this; }
|
||||
/** @param {string} p @returns {CommandRequirement} */
|
||||
addPermission(p) { this.permissions.push(p); return this; }
|
||||
/** @param {...string} p @returns {CommandRequirement} */
|
||||
addPermissions(...p) { this.permissions.push(...p); return this; }
|
||||
|
||||
/**
|
||||
* @returns {string[]} The permission list (with an owner note appended when
|
||||
* the requirement is owner-only).
|
||||
*/
|
||||
getPermissions() { return (this.ownerOnly) ? [...this.permissions, "Owner-only command"] : this.permissions; }
|
||||
/** @param {string} e @returns {CommandRequirement} */
|
||||
setPermissionError(e) { this.permissionError = e; return this; }
|
||||
}
|
||||
|
||||
/**
|
||||
* @class CommandBuilder
|
||||
* @description Fluent builder for constructing command definitions with name,
|
||||
* description, options, subcommands, aliases, requirements and examples.
|
||||
*/
|
||||
export class CommandBuilder {
|
||||
/** Create a new CommandBuilder with default empty state. */
|
||||
constructor() {
|
||||
this.name = null;
|
||||
this.description = null;
|
||||
this.id = null;
|
||||
this.aliases = [];
|
||||
this.subcommands = [];
|
||||
this.options = [];
|
||||
this.requirements = [];
|
||||
this.category = "default";
|
||||
this.examples = [];
|
||||
|
||||
this.uid = Utils.uid();
|
||||
|
||||
this.subcommandError = "Invalid subcommand. Try one of the following options: `$previousCmd <$cmdlist>`";
|
||||
this.parent = null;
|
||||
}
|
||||
|
||||
/** Set the command name and register it as the primary alias. @param {string} n @returns {CommandBuilder} */
|
||||
setName(n) { this.name = n; this.aliases.push(n.toLowerCase()); return this; }
|
||||
/** Set the command description. @param {string} d @returns {CommandBuilder} */
|
||||
setDescription(d) { this.description = d; return this; }
|
||||
/** Set the command ID. @param {string} id @returns {CommandBuilder} */
|
||||
setId(id) { this.id = id; return this; }
|
||||
|
||||
/** @returns {string} Full command path including parent chain (e.g. "music play"). */
|
||||
get command() { return (this.parent) ? this.parent.command + " " + this.name : this.name; }
|
||||
|
||||
/**
|
||||
* Add a permission/owner-only requirement via a callback.
|
||||
* @param {Function} config - Callback receiving a fresh {@link CommandRequirement}.
|
||||
* @returns {CommandBuilder}
|
||||
*/
|
||||
setRequirement(config) { let req = config(new CommandRequirement()); this.requirements.push(req); return this; }
|
||||
|
||||
/**
|
||||
* Add a subcommand builder via a callback.
|
||||
* @param {Function} config - Callback receiving a fresh {@link CommandBuilder}.
|
||||
* @returns {CommandBuilder}
|
||||
*/
|
||||
addSubcommand(config) { let sub = config(new CommandBuilder()); sub.parent = this; this.subcommands.push(sub); return this; }
|
||||
|
||||
/**
|
||||
* Add a string option.
|
||||
* @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder}
|
||||
*/
|
||||
addStringOption(config, flag = false) { this.options.push(config(Option.create("string", flag))); return this; }
|
||||
/**
|
||||
* Add a number option.
|
||||
* @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder}
|
||||
*/
|
||||
addNumberOption(config, flag = false) { this.options.push(config(Option.create("number", flag))); return this; }
|
||||
/**
|
||||
* Add a boolean option.
|
||||
* @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder}
|
||||
*/
|
||||
addBooleanOption(config, flag = false) { this.options.push(config(Option.create("boolean", flag))); return this; }
|
||||
/**
|
||||
* Add a channel option.
|
||||
* @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder}
|
||||
*/
|
||||
addChannelOption(config, flag = false) { this.options.push(config(Option.create("channel", flag))); return this; }
|
||||
/**
|
||||
* Add a voice-channel option.
|
||||
* @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder}
|
||||
*/
|
||||
addVoiceChannelOption(config, flag = false) { this.options.push(config(Option.create("voiceChannel", flag))); return this; }
|
||||
/**
|
||||
* Add a user option.
|
||||
* @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder}
|
||||
*/
|
||||
addUserOption(config, flag = false) { this.options.push(config(Option.create("user", flag))); return this; }
|
||||
|
||||
/**
|
||||
* Add a text (remaining-args) option. Only one is allowed per command.
|
||||
* @param {Function} config
|
||||
* @returns {CommandBuilder}
|
||||
* @throws {Error} If a text option already exists.
|
||||
*/
|
||||
addTextOption(config) {
|
||||
if (this.options.findIndex(e => e.type === "text") !== -1) throw new Error("There can only be 1 text option.");
|
||||
this.options.push(config(new Option("text")));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a choice (enum-like) option.
|
||||
* @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder}
|
||||
*/
|
||||
addChoiceOption(config, flag = false) { this.options.push(config(Option.create("choice", flag))); return this; }
|
||||
|
||||
/**
|
||||
* Add an alias (case-insensitive, duplicates ignored).
|
||||
* @param {string} alias
|
||||
* @returns {CommandBuilder}
|
||||
*/
|
||||
addAlias(alias) {
|
||||
if (this.aliases.findIndex(e => e === alias.toLowerCase()) !== -1) return this;
|
||||
this.aliases.push(alias.toLowerCase());
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add multiple aliases.
|
||||
* @param {...string} aliases
|
||||
* @returns {CommandBuilder}
|
||||
*/
|
||||
addAliases(...aliases) { aliases.forEach((a) => this.addAlias(a)); return this; }
|
||||
|
||||
/** Set the command category (used by help grouping). @param {string} cat @returns {CommandBuilder} */
|
||||
setCategory(cat) { this.category = cat; return this; }
|
||||
|
||||
/**
|
||||
* Add usage examples.
|
||||
* @param {...string} examples
|
||||
* @returns {CommandBuilder}
|
||||
*/
|
||||
addExamples(...examples) { this.examples.push(...examples); return this; }
|
||||
}
|
||||
@@ -0,0 +1,569 @@
|
||||
/**
|
||||
* @module src/commands/CommandHandler
|
||||
* @description The command dispatcher: parses incoming messages, matches
|
||||
* commands and aliases, validates options/flags, enforces permissions and
|
||||
* per-user cooldowns, and emits "run" events consumed by the CommandLoader.
|
||||
*/
|
||||
|
||||
import { EventEmitter } from "node:events";
|
||||
import { PermissionFlags } from "@fluxerjs/core";
|
||||
import { logger } from "../core/Logger.mjs";
|
||||
import { Utils } from "../utils/Utils.mjs";
|
||||
import { Message, REQUIRED_BOT_PERMISSIONS } from "../ui/index.mjs";
|
||||
import { Option, Flag } from "./Option.mjs";
|
||||
import { HelpHandler } from "./HelpHandler.mjs";
|
||||
import { PrefixManager } from "./PrefixManager.mjs";
|
||||
|
||||
/** @type {string[]} Option types whose quoted values may span multiple tokens. */
|
||||
const QUOTABLE_TYPES = ["string", "text", "channel", "voiceChannel"];
|
||||
|
||||
/**
|
||||
* @class CommandHandler
|
||||
* @description Main command dispatcher.
|
||||
* @extends {EventEmitter}
|
||||
*
|
||||
* Events:
|
||||
* - `"command"` — emitted with `{ command, message }` when a command starts.
|
||||
* - `"run"` — emitted with the fully parsed run payload (see processCommand).
|
||||
*/
|
||||
export class CommandHandler extends EventEmitter {
|
||||
/** @type {Function|null} Custom handler when the bot is pinged. */
|
||||
onPing = null;
|
||||
/** @type {boolean} Whether the bot responds to pings as a prefix. */
|
||||
pingPrefix = true;
|
||||
/** @type {string[]} Bot owner user IDs. */
|
||||
owners = [];
|
||||
|
||||
/** @type {import('../ui/MessageHandler.mjs').MessageHandler} */
|
||||
messages;
|
||||
client;
|
||||
/** @type {PrefixManager} */
|
||||
prefixes;
|
||||
/** @type {HelpHandler} */
|
||||
helpHandler;
|
||||
|
||||
/** @type {string[]} All registered command aliases. */
|
||||
commandNames = [];
|
||||
/** @type {import('./CommandBuilder.mjs').CommandBuilder[]} Registered commands. */
|
||||
commands = [];
|
||||
|
||||
/** @type {object|null} Locale manager. */
|
||||
locale = null;
|
||||
|
||||
invalidFlagError = "Invalid flag `$invalidFlag`. It doesn't match any options on this command.\n`$previousCmd $invalidFlag`";
|
||||
textWrapError = "Malformed string `$value`: Missing a closing quote character (`$quote`) after the desired string.";
|
||||
|
||||
/** @private @type {Map<string, number>} Per-user last command timestamps for cooldown enforcement. */
|
||||
_cmdCooldowns = new Map();
|
||||
/** @private @type {number} Cooldown duration in ms between commands per non-owner user. */
|
||||
_cmdCooldownMs = 1500;
|
||||
|
||||
/**
|
||||
* @param {import('../ui/MessageHandler.mjs').MessageHandler} handler
|
||||
* @param {string} [prefix="%"]
|
||||
*/
|
||||
constructor(handler, prefix = "%") {
|
||||
super();
|
||||
this.messages = handler;
|
||||
this.client = handler.client;
|
||||
this.prefix = prefix;
|
||||
this.helpHandler = new HelpHandler(this);
|
||||
this.helpCommand = "help";
|
||||
this.replyHandler = (message, msg) => {
|
||||
msg.reply(this.format(message, msg.channel.channel.guildId));
|
||||
};
|
||||
this.messages.onMessage(this.messageHandler.bind(this));
|
||||
}
|
||||
|
||||
/** Get the command prefix for a guild. @param {string} guildId @returns {string} */
|
||||
getPrefix(guildId) { return this.prefixes.getPrefix(guildId); }
|
||||
/** Enable or disable ping-as-prefix. @param {boolean} bool */
|
||||
setPingPrefix(bool) { this.pingPrefix = bool; }
|
||||
/** @param {PrefixManager} manager */
|
||||
setPrefixManager(manager) { this.prefixes = manager; }
|
||||
/** @param {HelpHandler} handler */
|
||||
setHelpHandler(handler) { this.helpHandler = handler; }
|
||||
/** @param {object} locale */
|
||||
setLocale(locale) { this.locale = locale; }
|
||||
|
||||
/**
|
||||
* Translate a locale key.
|
||||
* @param {string} guildId
|
||||
* @param {string} key
|
||||
* @param {object} [replacements={}]
|
||||
* @returns {string}
|
||||
*/
|
||||
t(guildId, key, replacements = {}) {
|
||||
if (!this.locale) return key;
|
||||
return this.locale.translate(guildId, key, replacements);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace $prefix and $helpCmd placeholders in text.
|
||||
* @param {string} text
|
||||
* @param {string} guildId
|
||||
* @returns {string}
|
||||
*/
|
||||
format(text, guildId) {
|
||||
const prefix = (!guildId) ? this.prefix : this.getPrefix(guildId);
|
||||
return text
|
||||
.replace(/\$prefix/gi, prefix)
|
||||
.replace(/\$helpCmd/gi, this.helpCommand);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a command from the registry.
|
||||
* @param {import('./CommandBuilder.mjs').CommandBuilder} command
|
||||
*/
|
||||
removeCommand(command) {
|
||||
command.aliases.forEach(a => {
|
||||
const idx = this.commandNames.indexOf(a);
|
||||
if (idx !== -1) this.commandNames.splice(idx, 1);
|
||||
});
|
||||
const idx = this.commands.findIndex(c => c.uid === command.uid);
|
||||
if (idx !== -1) this.commands.splice(idx, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @private Handle an incoming message and route it to command processing.
|
||||
* Handles bare pings, prefix detection, cooldowns and the built-in help.
|
||||
* @param {Message} msg
|
||||
*/
|
||||
messageHandler(msg) {
|
||||
if (!msg || !msg.content) return;
|
||||
const trimmed = msg.content.trim();
|
||||
if (/^<@!?\d+>$/.test(trimmed)) {
|
||||
const botId = this.client.user?.id;
|
||||
if (botId && (trimmed === `<@${botId}>` || trimmed === `<@!${botId}>`)) {
|
||||
return this.onPing?.(msg);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const guildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
const prefix = this.getPrefix(guildId);
|
||||
const ping = `<@${this.client.user?.id}>`;
|
||||
const pingBang = `<@!${this.client.user?.id}>`;
|
||||
if (!(msg.content.startsWith(prefix) || msg.content.startsWith(ping) || msg.content.startsWith(pingBang))) return;
|
||||
|
||||
if (this._isCoolingDown(msg)) return;
|
||||
this._enforceCooldown(msg);
|
||||
|
||||
const len = msg.content.startsWith(prefix) ? prefix.length : (msg.content.startsWith(pingBang) ? pingBang.length : ping.length);
|
||||
const args = msg.content.slice(len).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim());
|
||||
|
||||
if (!args[0]) return;
|
||||
|
||||
if (args[0] === this.helpCommand) {
|
||||
return this._handleHelpInvocation(args, guildId, msg);
|
||||
}
|
||||
|
||||
if (!this.commandNames.includes(args[0].toLowerCase())) {
|
||||
this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix$helpCmd", guildId) }), msg);
|
||||
return;
|
||||
}
|
||||
return this.processCommand(this.commands.find(e => e.aliases.includes(args[0].toLowerCase())), args, msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* @private Apply the per-user cooldown gate: records the timestamp for the
|
||||
* invoking user and prunes the cooldown map when it grows too large.
|
||||
* Owners are exempt.
|
||||
* @param {Message} msg
|
||||
*/
|
||||
_enforceCooldown(msg) {
|
||||
const userId = msg.message?.author?.id ?? msg.author?.id;
|
||||
if (!userId || this.owners.includes(userId)) return;
|
||||
|
||||
const now = Date.now();
|
||||
this._cmdCooldowns.set(userId, now);
|
||||
if (this._cmdCooldowns.size > 500) {
|
||||
const cutoff = now - this._cmdCooldownMs * 2;
|
||||
for (const [uid, ts] of this._cmdCooldowns) {
|
||||
if (ts < cutoff) this._cmdCooldowns.delete(uid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @private Cooldown gate — returns true when the user invoked a command too
|
||||
* recently and the message should be dropped (owners are exempt).
|
||||
* @param {Message} msg
|
||||
* @returns {boolean}
|
||||
*/
|
||||
_isCoolingDown(msg) {
|
||||
const userId = msg.message?.author?.id ?? msg.author?.id;
|
||||
if (!userId || this.owners.includes(userId)) return false;
|
||||
const now = Date.now();
|
||||
const last = this._cmdCooldowns.get(userId) ?? 0;
|
||||
return (now - last) < this._cmdCooldownMs;
|
||||
}
|
||||
|
||||
/**
|
||||
* @private Built-in `%help` invocation handling (bare / page / command / subcommand path).
|
||||
* @param {string[]} args
|
||||
* @param {string} guildId
|
||||
* @param {Message} msg
|
||||
*/
|
||||
_handleHelpInvocation(args, guildId, msg) {
|
||||
if (!args[1]) {
|
||||
const res = this.helpHandler.help(msg);
|
||||
return (typeof res === "string") ? this.replyHandler(res, msg) : undefined;
|
||||
}
|
||||
if (args.length > 1 && Utils.isNumber(args[1])) {
|
||||
const pageNumber = parseInt(args[1]);
|
||||
if (pageNumber < 1 || pageNumber > this.helpHandler.pageNumber()) {
|
||||
return this.replyHandler(this.t(guildId, "cmdHandler.page.invalid", { number: pageNumber }), msg);
|
||||
}
|
||||
return this.replyHandler(this.helpHandler.getHelpPage(pageNumber - 1, msg), msg);
|
||||
}
|
||||
if (args.length <= 2) {
|
||||
let idx = this.commands.findIndex(e => e.aliases.some(al => al.toLowerCase() === args[1].toLowerCase()));
|
||||
if (idx === -1) return this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix" + args[1], guildId) }), msg);
|
||||
return this.replyHandler(this.helpHandler.getCommandHelp(this.commands[idx], msg), msg);
|
||||
}
|
||||
let currCmd = null;
|
||||
let prefix2 = "";
|
||||
for (let i = 0; i < args.slice(1).length; i++) {
|
||||
let a = args.slice(1)[i];
|
||||
let curr = (currCmd) ? currCmd.subcommands : this.commands;
|
||||
let idx = curr.findIndex(e => e.aliases.some(al => al.toLowerCase() === a.toLowerCase()));
|
||||
if (idx === -1) return this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix" + prefix2 + a, guildId) }), msg);
|
||||
currCmd = curr[idx];
|
||||
prefix2 += a + " ";
|
||||
}
|
||||
return this.replyHandler(this.helpHandler.getCommandHelp(currCmd, msg), msg);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse and execute a command with its options.
|
||||
* @param {import('./CommandBuilder.mjs').CommandBuilder} cmd
|
||||
* @param {string[]} args
|
||||
* @param {Message} msg
|
||||
* @param {string|boolean} [previous=false] - The command path so far (for error messages).
|
||||
* @param {boolean} [external=false] - When true, errors are returned instead of replied.
|
||||
* @returns {object|undefined} The command run payload.
|
||||
*/
|
||||
processCommand(cmd, args, msg, previous = false, external = false) {
|
||||
if (!cmd) return logger.warn("[CommandHandler.processCommand] Invalid case: `cmd` falsy.");
|
||||
|
||||
if (!external) {
|
||||
const channel = msg.channel?.channel ?? msg.channel;
|
||||
if (channel?.guild) {
|
||||
const botPermResult = this.messages.checkAllBotPermissions(channel);
|
||||
if (botPermResult.criticalMissing.length > 0) {
|
||||
const permEmbed = this.messages.buildPermissionEmbed(botPermResult.missing, channel.guildId);
|
||||
try {
|
||||
msg.message?.reply?.({ embeds: [permEmbed] }, { ping: false });
|
||||
} catch (_) {
|
||||
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 (__) { logger.warn("[CommandHandler] Fallback perm reply failed"); }
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (cmd.requirements.length > 0 && !external) {
|
||||
if (!this.assertRequirements(cmd, msg)) return;
|
||||
}
|
||||
if (previous === false) previous = this.format("$prefix" + cmd.name, msg.channel?.channel?.guildId);
|
||||
if (!external) this.emit("command", { command: cmd, message: msg });
|
||||
|
||||
if (cmd.subcommands.length !== 0) {
|
||||
const idx = cmd.subcommands.findIndex(el => {
|
||||
if (!args[1]) return false;
|
||||
return el.name.toLowerCase() === args[1].toLowerCase();
|
||||
});
|
||||
if (idx === -1) {
|
||||
const list = cmd.subcommands.map(s => s.name).join(" | ");
|
||||
const subGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
const e = this.t(subGuildId, "cmdBuilder.subcommand.invalid").replace(/\$previousCmd/gi, previous).replace(/\$cmdList/gi, list);
|
||||
return (!external) ? this.replyHandler(e, msg) : e;
|
||||
}
|
||||
return this.processCommand(cmd.subcommands[idx], args.slice(1), msg, previous + this.format(" " + cmd.subcommands[idx].name), external);
|
||||
}
|
||||
|
||||
// `error === true` → internal invocation: the error reply was already
|
||||
// sent by _parseOptions and, exactly like the original monolith, the
|
||||
// command must NOT run (no "run" emission). A string is the external-
|
||||
// mode error, returned to the caller as before.
|
||||
const { opts, error } = this._parseOptions(cmd, args, msg, previous, external);
|
||||
if (error) return (error === true) ? undefined : error;
|
||||
|
||||
const commandRunData = {
|
||||
command: cmd,
|
||||
commandId: cmd.id,
|
||||
options: opts,
|
||||
message: msg,
|
||||
get: function (oName) { return this.options.find(o => o.name === oName); },
|
||||
getById: function (id) { return this.options.find(o => o.id === id); }
|
||||
};
|
||||
if (!external) this.emit("run", commandRunData);
|
||||
return commandRunData;
|
||||
}
|
||||
|
||||
/**
|
||||
* @private Parse positional options, flags, quoted values and text options.
|
||||
* @param {import('./CommandBuilder.mjs').CommandBuilder} cmd
|
||||
* @param {string[]} args
|
||||
* @param {Message} msg
|
||||
* @param {string} previous
|
||||
* @param {boolean} external
|
||||
* @returns {{opts: Array, error: *}} Parsed options or a handled error:
|
||||
* `null` on success; `true` when an internal (non-external) invocation
|
||||
* already sent its error reply and the caller must stop (the original
|
||||
* monolith exited processCommand directly at these points); the error
|
||||
* string for external invocations at the option/flag validation sites
|
||||
* (textWrap sites always reply, matching the original's always-reply quirk).
|
||||
*/
|
||||
_parseOptions(cmd, args, msg, previous, external) {
|
||||
const opts = [];
|
||||
const texts = [];
|
||||
|
||||
/**
|
||||
* Collect quoted arguments spanning multiple tokens.
|
||||
* @param {number} index
|
||||
* @param {string} currVal
|
||||
* @param {string[]} as
|
||||
* @returns {{args: string[], index: number}|null}
|
||||
*/
|
||||
const collectArguments = (index, currVal, as) => {
|
||||
const lastChar = currVal.charAt(currVal.length - 1);
|
||||
if (lastChar === '"') return { args: as, index };
|
||||
const a = args[++index];
|
||||
if (!a) return null;
|
||||
as.push(a);
|
||||
return collectArguments(index, a, as);
|
||||
};
|
||||
|
||||
const options = cmd.options.slice().sort((a, b) => {
|
||||
const aText = (a.type === "text") ? 1 : 2;
|
||||
const bText = (b.type === "text") ? 1 : 2;
|
||||
return aText - bText;
|
||||
});
|
||||
|
||||
const usedOptions = [];
|
||||
let usedArgumentCount = 0;
|
||||
|
||||
for (let i = 0, argIndex = 1; i < options.length; i++) {
|
||||
const o = options[i];
|
||||
if (o?.type === "text") { texts.push(o); continue; }
|
||||
if ((args[argIndex] || "").startsWith("-")) {
|
||||
const flagName = args[argIndex].slice(1);
|
||||
const op = cmd.options.find(e => e.aliases.includes(flagName));
|
||||
if (!op) {
|
||||
const flagGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
const error = this.t(flagGuildId, "cmdHandler.invalidFlag").replace(/\$previousCmd/gi, previous).replace(/\$invalidFlag/gi, "-" + flagName);
|
||||
return { opts, error: (!external) ? (this.replyHandler(error, msg) ?? true) : error };
|
||||
}
|
||||
previous += " " + args[argIndex];
|
||||
let value = args[++argIndex];
|
||||
if ((value || "").startsWith('"') && (QUOTABLE_TYPES.includes(op.type))) {
|
||||
const data = collectArguments(argIndex, value, [value]);
|
||||
if (!data) {
|
||||
const twGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
return { opts, error: (this.replyHandler(this._textWrapErrorMsg(twGuildId, args.slice(argIndex).join(" "), args[argIndex].charAt(0)), msg) ?? true) };
|
||||
}
|
||||
argIndex += data.index - argIndex;
|
||||
const _joined = data.args.join(" ");
|
||||
value = _joined.slice(1, _joined.length - 1);
|
||||
}
|
||||
argIndex++;
|
||||
i--;
|
||||
const valid = op.validateInput(value, this.client, msg.message);
|
||||
if (!valid && (op.required || !op.empty(value))) {
|
||||
const errGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
const e = this._optionTypeError(errGuildId, op, value, previous);
|
||||
return { opts, error: (!external) ? (this.replyHandler(e, msg) ?? true) : e };
|
||||
}
|
||||
usedArgumentCount += 2;
|
||||
previous += " " + value;
|
||||
opts.push({ value: op.formatInput(value, this.client, msg.message), name: op.name, id: op.id, uid: op.uid });
|
||||
usedOptions.push(op.uid);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!o) continue;
|
||||
if (o instanceof Flag) continue;
|
||||
if (opts.findIndex(op => op.uid === o.uid) !== -1) continue;
|
||||
let value = args[argIndex];
|
||||
if ((args[argIndex] || "").startsWith('"') && (QUOTABLE_TYPES.includes(o.type))) {
|
||||
const data = collectArguments(argIndex, args[argIndex], [args[argIndex]]);
|
||||
if (!data) {
|
||||
const twGuildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
return { opts, error: (this.replyHandler(this._textWrapErrorMsg(twGuildId2, args.slice(argIndex).join(" "), args[argIndex].charAt(0)), msg) ?? true) };
|
||||
}
|
||||
argIndex += data.index - argIndex;
|
||||
value = data.args.join(" ");
|
||||
value = value.slice(1, value.length - 1);
|
||||
}
|
||||
let valid = o.validateInput(value, this.client, msg.message);
|
||||
if (!valid && o.dynamicDefault) {
|
||||
value = o.dynamicDefault(this.client, msg);
|
||||
valid = o.validateInput(value, this.client, msg.message);
|
||||
}
|
||||
if (!valid && (o.required || !o.empty(value))) {
|
||||
const errGuildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
const e = this._optionTypeError(errGuildId2, o, value, previous);
|
||||
return { opts, error: (!external) ? (this.replyHandler(e, msg) ?? true) : e };
|
||||
}
|
||||
if (o.empty(value)) value = o.defaultValue;
|
||||
opts.push({ value: o.formatInput(value, this.client, msg.message), name: o.name, id: o.id, uid: o.uid });
|
||||
usedOptions.push(o.uid);
|
||||
previous += " " + value;
|
||||
argIndex++;
|
||||
usedArgumentCount++;
|
||||
}
|
||||
|
||||
if (texts.length > 0) {
|
||||
let o = texts[0];
|
||||
let text = args.slice(usedArgumentCount + 1).join(" ");
|
||||
if (o.required && !o.validateInput(text, this.client, msg.message)) {
|
||||
const textErrGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
let e = this._optionTypeError(textErrGuildId, o, text, previous);
|
||||
return { opts, error: (!external) ? (this.replyHandler(e, msg) ?? true) : e };
|
||||
}
|
||||
const quote = (['"', "'"].includes(text.charAt(0))) ? text.charAt(0) : null;
|
||||
if (quote && text.charAt(text.length - 1) === quote) text = text.slice(1, text.length - 1);
|
||||
opts.push({ name: o.name, value: text, id: o.id, uid: o.uid });
|
||||
usedOptions.push(o.uid);
|
||||
}
|
||||
|
||||
options.filter(o => !usedOptions.includes(o.uid)).forEach(o => {
|
||||
if (!o.defaultValue) return;
|
||||
opts.push({ name: o.name, value: o.defaultValue, id: o.id, uid: o.uid });
|
||||
});
|
||||
|
||||
return { opts, error: null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the message author meets all command requirements
|
||||
* (owner-only, guild permissions). When member data must be fetched over
|
||||
* REST, re-invokes processCommand asynchronously once resolved.
|
||||
* @param {import('./CommandBuilder.mjs').CommandBuilder} cmd
|
||||
* @param {Message} msg
|
||||
* @returns {boolean}
|
||||
*/
|
||||
assertRequirements(cmd, msg) {
|
||||
const authorId = msg.message?.author?.id;
|
||||
const isOwner = this.owners.includes(authorId);
|
||||
const permGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
|
||||
for (let i = 0; i < cmd.requirements.length; i++) {
|
||||
let req = cmd.requirements[i];
|
||||
if (req.ownerOnly && !isOwner) return false;
|
||||
if (req.permissions.length > 0 && !isOwner) {
|
||||
const guild = msg.message?.guild ?? null;
|
||||
if (!guild) {
|
||||
this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg);
|
||||
return false;
|
||||
}
|
||||
|
||||
const member = guild.members.get(authorId) ?? null;
|
||||
if (member?.permissions) {
|
||||
const missing = req.permissions.filter(p => !member.permissions.has(PermissionFlags[p] ?? p));
|
||||
if (missing.length > 0) {
|
||||
this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
const fetchPromise = typeof guild.fetchMember === "function"
|
||||
? guild.fetchMember(authorId)
|
||||
: typeof guild.members?.fetch === "function"
|
||||
? guild.members.fetch(authorId)
|
||||
: Promise.reject(new Error("No member fetch API available"));
|
||||
fetchPromise.then(member => {
|
||||
const missing = req.permissions.filter(p => !member.permissions.has(PermissionFlags[p] ?? p));
|
||||
if (missing.length > 0) {
|
||||
this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg);
|
||||
} else {
|
||||
const guildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
const prefix2 = this.getPrefix(guildId2);
|
||||
const rawContent = msg.message.content;
|
||||
const len2 = rawContent.startsWith(prefix2) ? prefix2.length : 0;
|
||||
const args = rawContent.slice(len2).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim());
|
||||
this.processCommand(cmd, args, msg, false, true);
|
||||
}
|
||||
}).catch(() => this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an input for a given option type.
|
||||
* @param {string} type
|
||||
* @param {*} i
|
||||
* @param {object} m
|
||||
* @returns {boolean}
|
||||
*/
|
||||
validateInput(type, i, m) { return (new Option()).validateInput(i, this.client, m, type); }
|
||||
|
||||
/**
|
||||
* Format an input for a given option type.
|
||||
* @param {string} type
|
||||
* @param {*} i
|
||||
* @param {object} m
|
||||
* @returns {*}
|
||||
*/
|
||||
formatInput(type, i, m) { return (new Option()).formatInput(i, this.client, m, type); }
|
||||
|
||||
/**
|
||||
* @private Build a type-error message for an option.
|
||||
* @param {string} guildId
|
||||
* @param {Option} option
|
||||
* @param {*} value
|
||||
* @param {string} previous
|
||||
* @returns {string}
|
||||
*/
|
||||
_optionTypeError(guildId, option, value, previous) {
|
||||
if (option.tError) {
|
||||
return option.tError.replace(/\$previousCmd/gi, previous).replace(/\$currValue/gi, value);
|
||||
}
|
||||
const localeKey = option.type === 'choice' ? 'cmdBuilder.option.invalidChoice'
|
||||
: (option.type === 'channel' || option.type === 'voiceChannel') ? 'cmdBuilder.option.invalidChannel'
|
||||
: 'cmdBuilder.option.invalidType';
|
||||
const choiceStr = option.type === 'choice'
|
||||
? (option.choices.length > Option.THRESHOLD ? Option.formatChoicesCompact(option.choices) : option.choices.map(c => '- ' + c).join('\n'))
|
||||
: '';
|
||||
return this.t(guildId, localeKey, {
|
||||
$currValue: value,
|
||||
$optionName: option.name,
|
||||
$type: option.type,
|
||||
$choices: choiceStr
|
||||
}).replace(/\$previousCmd/gi, previous);
|
||||
}
|
||||
|
||||
/**
|
||||
* @private Build a text-wrap error message.
|
||||
* @param {string} guildId
|
||||
* @param {string} value
|
||||
* @param {string} quote
|
||||
* @returns {string}
|
||||
*/
|
||||
_textWrapErrorMsg(guildId, value, quote) {
|
||||
return this.t(guildId, 'cmdHandler.textWrapError', { $value: value, $quote: quote });
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a command builder and sort the command list alphabetically.
|
||||
* @param {import('./CommandBuilder.mjs').CommandBuilder} builder
|
||||
* @returns {import('./CommandBuilder.mjs').CommandBuilder[]}
|
||||
*/
|
||||
addCommand(builder) {
|
||||
this.commandNames.push(...builder.aliases);
|
||||
this.commands.push(builder);
|
||||
this.commands.sort((a, b) => {
|
||||
let A = a.name.toUpperCase();
|
||||
let B = b.name.toUpperCase();
|
||||
return (A < B) ? -1 : (A > B) ? 1 : 0;
|
||||
});
|
||||
return this.commands;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
/**
|
||||
* @module src/commands/CommandLoader
|
||||
* @description Dynamically loads command modules from a directory, registers
|
||||
* their builders, and binds run handlers with error capture + error-id replies.
|
||||
*/
|
||||
|
||||
import { pathToFileURL } from "node:url";
|
||||
import path from "node:path";
|
||||
import * as fs from "node:fs";
|
||||
import { logger } from "../core/Logger.mjs";
|
||||
import { Utils } from "../utils/Utils.mjs";
|
||||
|
||||
/**
|
||||
* @class CommandLoader
|
||||
* @description Loads command files from a directory, registers builders with
|
||||
* the CommandHandler, and dispatches "run" events to the matching run function.
|
||||
*
|
||||
* Command module shape (both shapes are accepted):
|
||||
* - `export const command` (builder or builder-factory), `export const run`
|
||||
* - default export object with the same keys
|
||||
* - optional `exportDef: { name, object }` registers a global on the context
|
||||
*/
|
||||
export class CommandLoader {
|
||||
/** @type {import('./CommandHandler.mjs').CommandHandler} */
|
||||
commands;
|
||||
/** @type {Map<string, string>} Command UID → file path. */
|
||||
commandFiles = new Map();
|
||||
/** @type {Map<string, Function>} Command UID → run function. */
|
||||
runnables = new Map();
|
||||
/** @type {object} Shared context (the bot instance). */
|
||||
context;
|
||||
|
||||
/**
|
||||
* @param {import('./CommandHandler.mjs').CommandHandler} commands
|
||||
* @param {object} context - Bot context object (gets loader/runnables refs attached).
|
||||
*/
|
||||
constructor(commands, context) {
|
||||
this.commands = commands;
|
||||
this.context = context;
|
||||
this.context.loader ??= this;
|
||||
this.context.commandFiles = this.commandFiles;
|
||||
this.context.runnables = this.runnables;
|
||||
|
||||
this.commands.on("run", (data) => {
|
||||
if (!this.runnables.has(data.command.uid)) return;
|
||||
const runFc = this.runnables.get(data.command.uid);
|
||||
const sendErrorReply = (id) => {
|
||||
Promise.resolve(data.message.reply("An error occurred. Error id: `#" + id + "`"))
|
||||
.catch(err => logger.warn("[CommandHandler] Failed to send error-reply; error id #" + id + ":", err?.message));
|
||||
};
|
||||
try {
|
||||
const result = runFc.call(this.context, data.message, data);
|
||||
if (result && typeof result.catch === "function") {
|
||||
result.catch(e => {
|
||||
const id = Utils.uid();
|
||||
logger.error("Error running command; error id #" + id, e);
|
||||
sendErrorReply(id);
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
const id = Utils.uid();
|
||||
logger.error("Error running command; error id #" + id, e);
|
||||
sendErrorReply(id);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize a module export to `{ command, run, exportDef }`.
|
||||
* @param {object} cData
|
||||
* @returns {object}
|
||||
*/
|
||||
canonData(cData) {
|
||||
if (cData.command !== undefined) {
|
||||
return {
|
||||
command: cData.command,
|
||||
run: cData.run,
|
||||
exportDef: cData.exportDef ?? cData.export ?? null
|
||||
};
|
||||
}
|
||||
const d = cData.default ?? cData;
|
||||
return {
|
||||
command: d.command,
|
||||
run: d.run,
|
||||
exportDef: d.exportDef ?? d.export ?? null
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @async Load all command files from a directory.
|
||||
* @param {string} dir
|
||||
* @returns {Promise<undefined[]>}
|
||||
*/
|
||||
loadFromDir(dir) {
|
||||
const files = fs.readdirSync(dir)
|
||||
.filter(f => !f.startsWith(".") && (f.endsWith(".js") || f.endsWith(".mjs")));
|
||||
|
||||
return Promise.all(files.map(async commandFile => {
|
||||
const file = path.join(dir, commandFile);
|
||||
|
||||
const cData = this.canonData(await import(pathToFileURL(file).href));
|
||||
|
||||
const builder = (typeof cData.command === "function")
|
||||
? cData.command.call(this.context)
|
||||
: cData.command;
|
||||
|
||||
if (!builder) return logger.warn("No builder returned. Skipping '" + commandFile + "'");
|
||||
|
||||
if (cData.exportDef)
|
||||
this.context[cData.exportDef.name] = cData.exportDef.object;
|
||||
|
||||
this.commands.addCommand(builder);
|
||||
this.commandFiles.set(builder.uid, file);
|
||||
|
||||
if (!cData.run) return;
|
||||
|
||||
this.runnables.set(builder.uid, cData.run);
|
||||
builder.subcommands.forEach(sub => {
|
||||
this.runnables.set(sub.uid, cData.run);
|
||||
});
|
||||
}));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
/**
|
||||
* @module src/commands/HelpHandler
|
||||
* @description Text-based help generation: paginated command lists, per-command
|
||||
* usage/aliases/options rendering. Used as the default help renderer behind
|
||||
* `%help <n>` (the rich tabbed help lives in src/ui/HelpCommand.mjs).
|
||||
*/
|
||||
|
||||
import { PageBuilder } from "../ui/Paginators.mjs";
|
||||
import { Option, Flag } from "./Option.mjs";
|
||||
|
||||
/**
|
||||
* @class HelpHandler
|
||||
* @description Generates paginated help text for commands.
|
||||
*/
|
||||
export class HelpHandler {
|
||||
/** @type {import('./CommandHandler.mjs').CommandHandler} */
|
||||
commands;
|
||||
/** @type {number} Commands per help page. */
|
||||
commandsPerPage = 5;
|
||||
|
||||
/**
|
||||
* Default pagination handler that builds paginated help pages.
|
||||
* @param {object} msg - Message wrapper with message data.
|
||||
* @param {HelpHandler} helpHandler
|
||||
* @param {Array} cmds
|
||||
* @returns {string|null}
|
||||
*/
|
||||
paginationHandler = (msg, helpHandler, cmds) => {
|
||||
const guildId = msg.message.guildId;
|
||||
let form = this.commands.t(guildId, "cmdHandler.help.pageStructure");
|
||||
|
||||
const contents = cmds.map((cmd, i) => {
|
||||
return (i + 1) + ". **" + cmd.name + "**: " + (cmd.description || "").split("\n")[0];
|
||||
});
|
||||
|
||||
const pages = new PageBuilder(contents)
|
||||
.setForm(helpHandler.commands.format(form, msg.message.guildId))
|
||||
.setMaxLines(helpHandler.commandsPerPage);
|
||||
|
||||
helpHandler.commands.messages.initPagination(pages, msg);
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @type {Function|null} Custom help handler function override. */
|
||||
customHelpHandler = null;
|
||||
|
||||
/** @param {import('./CommandHandler.mjs').CommandHandler} commands */
|
||||
constructor(commands) { this.commands = commands; }
|
||||
|
||||
/**
|
||||
* @param {string} string
|
||||
* @returns {string} Capitalised first letter.
|
||||
*/
|
||||
static capitalise(string) {
|
||||
if (string.length < 1) return string;
|
||||
if (string.length === 1) return string.toUpperCase();
|
||||
return string.charAt(0).toUpperCase() + string.slice(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Array} [cmds]
|
||||
* @returns {Array} Non-owner-only commands.
|
||||
*/
|
||||
userCommands(cmds) {
|
||||
return (cmds || this.commands.commands).filter(c =>
|
||||
c.requirements.findIndex(r => r.ownerOnly) === -1
|
||||
);
|
||||
}
|
||||
|
||||
/** @returns {number} Total number of help pages. */
|
||||
pageNumber() {
|
||||
return Math.ceil(this.commands.commands.length / this.commandsPerPage);
|
||||
}
|
||||
|
||||
/**
|
||||
* Entry point for help rendering.
|
||||
* @param {object} message
|
||||
* @returns {string|null}
|
||||
*/
|
||||
help(message) {
|
||||
if (this.customHelpHandler) return this.customHelpHandler(message);
|
||||
if (this.paginationHandler) return this.genHelp(null, message, true);
|
||||
return this.getHelpPage(0, message);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} n - 0-based page index.
|
||||
* @param {object} msg
|
||||
* @param {Array} [cmds=null]
|
||||
* @returns {string}
|
||||
*/
|
||||
getHelpPage(n, msg, cmds = null) {
|
||||
if (!cmds) cmds = this.commands.commands;
|
||||
if (!(this.commandsPerPage < cmds.length)) return this.genHelp(null, msg, false, cmds);
|
||||
let offset = this.commandsPerPage * n;
|
||||
const commands = cmds.slice(offset, offset + this.commandsPerPage);
|
||||
let max = Math.ceil(cmds.length / this.commandsPerPage);
|
||||
return this.genHelp({ curr: n + 1, max, offset }, msg, false, commands);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object|null} page
|
||||
* @param {object} msg
|
||||
* @param {boolean} [paginate=false]
|
||||
* @param {Array} [cmds=null]
|
||||
* @returns {string}
|
||||
*/
|
||||
genHelp(page, msg, paginate = false, cmds = null) {
|
||||
cmds = this.userCommands(cmds);
|
||||
if (this.paginationHandler && msg && paginate) return this.paginationHandler(msg, this, cmds);
|
||||
|
||||
const guildId = msg.message.guildId;
|
||||
let p = (page) ? ` (page ${page.curr}/${page.max})` : "";
|
||||
const indexOffset = (page) ? page.offset : 0;
|
||||
let content = this.commands.t(guildId, "cmdHandler.help.availableCommands", { $page: p }) + "\n\n";
|
||||
if (page && page.curr !== 1) content += (indexOffset) + this.commands.t(guildId, "cmdHandler.help.ellipsis") + "\n";
|
||||
cmds.forEach((cmd, i) => { content += (i + 1 + indexOffset) + ". **" + cmd.name + "**: " + cmd.description + "\n"; });
|
||||
if (page && page.curr !== page.max) content += (cmds.length + indexOffset) + this.commands.t(guildId, "cmdHandler.help.ellipsis") + "\n";
|
||||
content += this.commands.format(this.commands.t(guildId, "cmdHandler.help.runHelp"), guildId);
|
||||
if (page) content += this.commands.format(this.commands.t(guildId, "cmdHandler.help.pageTip"), guildId);
|
||||
|
||||
return this.commands.format(content, guildId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the description of a command.
|
||||
* @param {import('./CommandBuilder.mjs').CommandBuilder} command
|
||||
* @returns {string}
|
||||
*/
|
||||
commandDescription(command) { return command.description; }
|
||||
|
||||
/**
|
||||
* Build a usage string for a command including options and flags.
|
||||
* @param {import('./CommandBuilder.mjs').CommandBuilder} cmd
|
||||
* @param {object} msg
|
||||
* @returns {string}
|
||||
*/
|
||||
commandUsage(cmd, msg) {
|
||||
if (cmd.subcommands.length > 0) {
|
||||
return this.commands.format("$prefix" + cmd.command, msg.message.guildId) + " <" + cmd.subcommands.map(e => e.name).join(" | ") + "> [...]";
|
||||
}
|
||||
let options = this.commands.format("$prefix" + cmd.command, msg.message.guildId);
|
||||
cmd.options.forEach(o => {
|
||||
if (o.type === "text") return;
|
||||
if (o instanceof Flag)
|
||||
return options += (o.type === "choice") ? "-" + o.aliases[0] + " <" + Option.formatChoicesUsage(o.choices) + ">" : " -" + o.aliases[0] + " '" + o.type + "'";
|
||||
options += (o.type === "choice") ? " <" + Option.formatChoicesUsage(o.choices) + ">" : " '" + o.name + ": " + o.type + "'";
|
||||
});
|
||||
let o = cmd.options.find(e => e.type === "text");
|
||||
if (o) options += "'" + o.name + ": " + o.type + "'";
|
||||
return options.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate detailed help text for a single command.
|
||||
* @param {import('./CommandBuilder.mjs').CommandBuilder} command
|
||||
* @param {object} msg
|
||||
* @returns {string}
|
||||
*/
|
||||
getCommandHelp(command, msg) {
|
||||
const guildId = msg.message.guildId;
|
||||
let content = `${HelpHandler.capitalise(command.name)}\n`;
|
||||
content += this.commandDescription(command, msg) + "\n\n";
|
||||
content += this.commands.t(guildId, "cmdHandler.help.usage") + "\n💻 `" + this.commandUsage(command, msg) + "`\n\n";
|
||||
if (command.examples.length > 0)
|
||||
content += this.commands.t(guildId, "cmdHandler.help.examples") + "\n- `" + command.examples.map(e => this.commands.format(e, guildId)).join("`\n- `") + "`\n\n";
|
||||
if (command.aliases.length > 1) {
|
||||
content += this.commands.t(guildId, "cmdHandler.help.aliases") + "\n";
|
||||
command.aliases.forEach(alias => { content += "- " + alias + "\n"; });
|
||||
content += "\n";
|
||||
}
|
||||
if (command.subcommands.length > 0) {
|
||||
content += this.commands.t(guildId, "cmdHandler.help.subcommands") + "\n";
|
||||
command.subcommands.forEach(s => {
|
||||
const optCount = s.options.length > 0 ? "; (`" + this.commands.t(guildId, "cmdHandler.help.optionCount", { $count: s.options.length }) + "`)" : "";
|
||||
content += "- " + s.name + ": " + (this.commandDescription(s, msg) || "").split("\n")[0] + optCount + "\n";
|
||||
});
|
||||
content += "\n";
|
||||
} else if (command.options.length > 0) {
|
||||
content += this.commands.t(guildId, "cmdHandler.help.arguments") + "\n";
|
||||
command.options.forEach(o => {
|
||||
const optional = ((o.required) ? "" : "?");
|
||||
const flag = (o instanceof Flag) ? "-" : "";
|
||||
if (o.type === "choice") {
|
||||
const choiceDisplay = Option.formatChoicesInline(o.choices);
|
||||
const aliasDisplay = o.aliases.filter(a => a !== null).join('`, `');
|
||||
content += "- **" + flag + o.name + "**" + optional + ": " + (o.description || "").split("\n")[0] + ";\n - " + this.commands.t(guildId, "cmdHandler.help.allowedValues") + choiceDisplay + "\n - " + this.commands.t(guildId, "cmdHandler.help.aliasesLabel") + "`" + aliasDisplay + "`\n";
|
||||
} else {
|
||||
content += "- **" + flag + o.name + "**" + optional + ": " + (o.description || "").split("\n")[0] + "\n - " + this.commands.t(guildId, "cmdHandler.help.aliasesLabel") + "`" + o.aliases.join("`, `") + "`\n";
|
||||
}
|
||||
content += "\n";
|
||||
});
|
||||
content += "\n";
|
||||
}
|
||||
if (command.requirements.length > 0) {
|
||||
content += this.commands.t(guildId, "cmdHandler.help.requirements") + "\n";
|
||||
command.requirements.forEach(r => {
|
||||
content += "- " + r.getPermissions().map(e => this.commands.t(guildId, "cmdHandler.help.permission", { $permission: e })).join("\n- ");
|
||||
});
|
||||
}
|
||||
return content.trim();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,279 @@
|
||||
/**
|
||||
* @module src/commands/Option
|
||||
* @description Command option model — typed inputs (string, number, boolean,
|
||||
* channel, user, choice, text) with validation, formatting and flag support.
|
||||
*/
|
||||
|
||||
import { Utils } from "../utils/Utils.mjs";
|
||||
|
||||
/**
|
||||
* @class Option
|
||||
* @description Represents a single command option with validation and
|
||||
* user-friendly error formatting. Options are positional; Flags (dashed
|
||||
* `-name` arguments) share the same base class.
|
||||
*/
|
||||
export class Option {
|
||||
/** @type {number} Maximum choices before switching to compact format. */
|
||||
static THRESHOLD = 10;
|
||||
/** @type {number} Number of choice columns per line in compact format. */
|
||||
static COLS_PER_LINE = 5;
|
||||
|
||||
/**
|
||||
* Format choice values in a compact multi-column layout.
|
||||
* @param {string[]} choices
|
||||
* @param {number} [perLine=Option.COLS_PER_LINE]
|
||||
* @returns {string}
|
||||
*/
|
||||
static formatChoicesCompact(choices, perLine = Option.COLS_PER_LINE) {
|
||||
const lines = [];
|
||||
for (let i = 0; i < choices.length; i += perLine) {
|
||||
lines.push(choices.slice(i, i + perLine).map(c => '`' + c + '`').join(' · '));
|
||||
}
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Format choice values inline, switching to compact layout above the threshold.
|
||||
* @param {string[]} choices
|
||||
* @returns {string}
|
||||
*/
|
||||
static formatChoicesInline(choices) {
|
||||
if (choices.length <= Option.THRESHOLD) {
|
||||
return '`' + choices.join('`, `') + '`';
|
||||
}
|
||||
return Option.formatChoicesCompact(choices, 6);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format choice values for a usage string, truncating with "…" if over max.
|
||||
* @param {string[]} choices
|
||||
* @param {number} [max=6]
|
||||
* @returns {string}
|
||||
*/
|
||||
static formatChoicesUsage(choices, max = 6) {
|
||||
if (choices.length <= max) return choices.join(' | ');
|
||||
return choices.slice(0, max).join(' | ') + ' | ...';
|
||||
}
|
||||
|
||||
/** @type {RegExp} Matches a channel mention like `<#123456>`. */
|
||||
channelRegex = /^<#(?<id>\d+)>/;
|
||||
/** @type {RegExp} Matches a user mention like `<@123>` or `<@!123>`. */
|
||||
userRegex = /^<@!?(?<id>\d+)>/;
|
||||
/** @type {RegExp} Matches a leading numeric ID. */
|
||||
idRegex = /^(?<id>\d+)/;
|
||||
|
||||
/** @type {Function|null} Dynamic default value resolver. */
|
||||
dynamicDefault;
|
||||
|
||||
/**
|
||||
* @param {string} [type="string"] One of: string, number, boolean, channel,
|
||||
* voiceChannel, user, choice, text.
|
||||
*/
|
||||
constructor(type = "string") {
|
||||
this.name = null;
|
||||
this.description = null;
|
||||
this.required = false;
|
||||
this.id = null;
|
||||
this.uid = Utils.uid();
|
||||
this.type = type;
|
||||
this.tError = null;
|
||||
this.aliases = [null];
|
||||
this.choices = [];
|
||||
this.translations = {};
|
||||
this.defaultValue = null;
|
||||
this.dynamicDefault = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Factory to create an Option or Flag instance.
|
||||
* @param {string} type
|
||||
* @param {boolean} [flag=false]
|
||||
* @returns {Option|Flag}
|
||||
*/
|
||||
static create(type, flag = false) {
|
||||
return (!flag) ? new Option(type) : new Flag(type);
|
||||
}
|
||||
|
||||
/** @param {string} n @returns {Option} */
|
||||
setName(n) { this.name = n; this.aliases[0] = n; return this; }
|
||||
/** @param {string} d @returns {Option} */
|
||||
setDescription(d) { this.description = d; return this; }
|
||||
/** @param {boolean} r @returns {Option} */
|
||||
setRequired(r) { this.required = r; return this; }
|
||||
/** @param {string} id @returns {Option} */
|
||||
setId(id) { this.id = id; return this; }
|
||||
/** @param {string} t @returns {Option} */
|
||||
setType(t) { this.type = t; return this; }
|
||||
|
||||
/**
|
||||
* Add flag aliases (e.g. "v" for "-v").
|
||||
* @param {...string} a
|
||||
* @returns {Option}
|
||||
*/
|
||||
addFlagAliases(...a) { this.aliases.push(...a); return this; }
|
||||
|
||||
/**
|
||||
* Add a single valid choice value (choice options only).
|
||||
* @param {string} c
|
||||
* @returns {Option}
|
||||
* @throws {Error} If option type is not "choice".
|
||||
*/
|
||||
addChoice(c) {
|
||||
if (this.type !== "choice") throw new Error(".addChoice is only available for choice options!");
|
||||
this.choices.push(c);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add multiple valid choice values (choice options only).
|
||||
* @param {...string} cs
|
||||
* @returns {Option}
|
||||
* @throws {Error} If option type is not "choice".
|
||||
*/
|
||||
addChoices(...cs) {
|
||||
if (this.type !== "choice") throw new Error(".addChoices is only available for choice options!");
|
||||
cs.forEach(c => this.addChoice(c));
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the default value used when the option is omitted.
|
||||
* @param {*} value
|
||||
* @returns {Option}
|
||||
*/
|
||||
setDefault(value) { this.defaultValue = value; return this; }
|
||||
|
||||
/**
|
||||
* Set a dynamic default resolver function (called with (client, msg)).
|
||||
* @param {Function} callback
|
||||
* @returns {Option}
|
||||
*/
|
||||
setDynamicDefault(callback) { this.dynamicDefault = callback; return this; }
|
||||
|
||||
/**
|
||||
* Check whether a value is considered empty/omitted.
|
||||
* @param {*} i
|
||||
* @returns {boolean}
|
||||
*/
|
||||
empty(i) {
|
||||
if (i === undefined || i === null) return true;
|
||||
return (!i && !(String(i).includes("0")));
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an input value for this option type.
|
||||
* @param {*} i
|
||||
* @param {object} client
|
||||
* @param {object} msg
|
||||
* @param {string} [type]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
validateInput(i, client, msg, type) {
|
||||
switch (type || this.type) {
|
||||
case "text":
|
||||
case "string":
|
||||
return !!i;
|
||||
case "number":
|
||||
return !isNaN(i) && !isNaN(parseFloat(i));
|
||||
case "boolean":
|
||||
return i === "0" || i === "1" || i?.toLowerCase() === "true" || i?.toLowerCase() === "false";
|
||||
case "choice":
|
||||
return this.choices.includes(i);
|
||||
case "user":
|
||||
return this.userRegex.test(i) || this.idRegex.test(i);
|
||||
case "channel":
|
||||
if (i === undefined) return false;
|
||||
return this.channelRegex.test(i) || this.idRegex.test(i) || client.channels.some(c => c.name === i);
|
||||
case "voiceChannel": {
|
||||
if (!i) return false;
|
||||
const results = this.channelRegex.exec(i) ?? this.idRegex.exec(i);
|
||||
const voiceTypes = [2, 13];
|
||||
const byName = msg?.guild?.channels?.find(c => c.name === i && voiceTypes.includes(c.type));
|
||||
const cObj = results
|
||||
? client.channels.get(results.groups["id"])
|
||||
: (byName ?? null);
|
||||
return cObj ? voiceTypes.includes(cObj.type) : false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Format/parse an input value into its canonical form (IDs for mentions,
|
||||
* numbers for numeric options, booleans for bools).
|
||||
* @param {*} i
|
||||
* @param {object} client
|
||||
* @param {object} msg
|
||||
* @param {string} [type]
|
||||
* @returns {*}
|
||||
*/
|
||||
formatInput(i, client, msg, type) {
|
||||
switch (type || this.type) {
|
||||
case "text":
|
||||
case "string":
|
||||
return i;
|
||||
case "number":
|
||||
return parseFloat(i);
|
||||
case "boolean":
|
||||
return i?.toLowerCase() === "true" || i === "1";
|
||||
case "choice":
|
||||
return i;
|
||||
case "user": {
|
||||
const rs = this.userRegex.exec(i) ?? this.idRegex.exec(i);
|
||||
return rs?.groups["id"] ?? null;
|
||||
}
|
||||
case "channel": {
|
||||
const results = this.channelRegex.exec(i) ?? this.idRegex.exec(i);
|
||||
const channel = client.channels.find(c => c.name === i);
|
||||
return results ? results.groups["id"] : (channel ? channel.id : null);
|
||||
}
|
||||
case "voiceChannel": {
|
||||
const r = this.channelRegex.exec(i) ?? this.idRegex.exec(i);
|
||||
const guildId = msg?.channel?.guildId ?? msg?.guildId;
|
||||
if (guildId === "eval") return r ? r.groups["id"] : (i || null);
|
||||
const voiceTypes = [2, 13];
|
||||
const c = msg?.guild?.channels?.find(c => c.name === i && voiceTypes.includes(c.type));
|
||||
return r ? r.groups["id"] : (c ? c.id : null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a type-error message template for this option.
|
||||
* @returns {string}
|
||||
*/
|
||||
get typeError() {
|
||||
if (this.tError) return this.tError;
|
||||
switch (this.type) {
|
||||
case "choice": {
|
||||
const choiceStr = this.choices.length > Option.THRESHOLD
|
||||
? Option.formatChoicesCompact(this.choices)
|
||||
: this.choices.map(c => '- ' + c).join('\n');
|
||||
return "Invalid value '$currValue'. The option `" + this.name + "` has to be one of the following: \n" + choiceStr + "\nSchematic: `$previousCmd <" + this.type + ">`";
|
||||
}
|
||||
case "voiceChannel":
|
||||
case "channel":
|
||||
return "Invalid value '$currValue'. The option `" + this.name + "` has to be a channel mention, id, or name.\nSchematic: `$previousCmd <" + this.type + ">`";
|
||||
default:
|
||||
return "Invalid value '$currValue'. The option `" + this.name + "` has to be of type `" + this.type + "`.\nSchematic: `$previousCmd <" + this.type + ">`";
|
||||
}
|
||||
}
|
||||
|
||||
/** @param {string} e */
|
||||
set typeError(e) { this.tError = e; }
|
||||
}
|
||||
|
||||
/**
|
||||
* @class Flag
|
||||
* @description A dashed (`-name`) option. Flags cannot be of type "text".
|
||||
* @extends Option
|
||||
*/
|
||||
export class Flag extends Option {
|
||||
/**
|
||||
* @param {string} [type="string"]
|
||||
* @throws {Error} If type is "text".
|
||||
*/
|
||||
constructor(type = "string") {
|
||||
if (type === "text") throw new Error("Flags can't be of type 'text'!");
|
||||
super(type);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* @module src/commands/PrefixManager
|
||||
* @description Per-guild command prefix resolution (guild setting → config → "%").
|
||||
*/
|
||||
|
||||
/**
|
||||
* @class PrefixManager
|
||||
* @description Manages per-guild command prefixes, falling back to the
|
||||
* configured prefix and finally to "%".
|
||||
*/
|
||||
export class PrefixManager {
|
||||
/** @type {import('../db/Settings.mjs').RemoteSettingsManager} */
|
||||
settings;
|
||||
/** @type {string|null} */
|
||||
configPrefix;
|
||||
|
||||
/**
|
||||
* @param {import('../db/Settings.mjs').RemoteSettingsManager} settings
|
||||
* @param {string|null} [configPrefix=null]
|
||||
*/
|
||||
constructor(settings, configPrefix = null) {
|
||||
this.settings = settings;
|
||||
this.configPrefix = configPrefix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the command prefix for a guild.
|
||||
* @param {string} guildId
|
||||
* @returns {string}
|
||||
*/
|
||||
getPrefix(guildId) {
|
||||
const serverPrefix = this.settings.getServer(guildId).get("prefix");
|
||||
return serverPrefix ?? this.configPrefix ?? "%";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* @module src/commands
|
||||
* @description Public surface of the command framework layer.
|
||||
*
|
||||
* Import map from the old layout:
|
||||
* - `src/CommandHandler.mjs` → this module
|
||||
*/
|
||||
|
||||
export { CommandBuilder, CommandRequirement } from "./CommandBuilder.mjs";
|
||||
export { Option, Flag } from "./Option.mjs";
|
||||
export { PrefixManager } from "./PrefixManager.mjs";
|
||||
export { HelpHandler } from "./HelpHandler.mjs";
|
||||
export { CommandHandler } from "./CommandHandler.mjs";
|
||||
export { CommandLoader } from "./CommandLoader.mjs";
|
||||
@@ -5,7 +5,7 @@ import { logger } from "./Logger.mjs";
|
||||
/**
|
||||
* Iterate over a guild's voice states, normalising different data shapes.
|
||||
* Yields objects with `{ userId, channelId, isBot }` for each member in a voice channel.
|
||||
* @param {object} guild - Discord guild object with a `voice_states` property.
|
||||
* @param {object} guild - Fluxer guild object with a `voice_states` property.
|
||||
* @yields {{ userId: string, channelId: string, isBot: boolean }}
|
||||
*/
|
||||
export function* iterateVoiceStates(guild) {
|
||||
@@ -49,7 +49,7 @@ export function* iterateVoiceStates(guild) {
|
||||
* @param {object} opts
|
||||
* @param {string} opts.guildId
|
||||
* @param {string} opts.channelId
|
||||
* @param {object} [opts.client] - Discord client with `guilds`.
|
||||
* @param {object} [opts.client] - Fluxer client with `guilds`.
|
||||
* @param {VoiceStateCache} [opts.voiceCache]
|
||||
* @param {Map} [opts.observedVoiceUsers]
|
||||
* @param {object} [opts.room] - LiveKit room with `remoteParticipants`.
|
||||
@@ -112,7 +112,7 @@ export function hasHumansInChannel({ guildId, channelId, client, voiceCache, obs
|
||||
|
||||
/**
|
||||
* Get the set of channel IDs that contain at least one human user.
|
||||
* @param {object} guild - Discord guild object.
|
||||
* @param {object} guild - Fluxer guild object.
|
||||
* @returns {Set<string>}
|
||||
*/
|
||||
export function getChannelsWithHumans(guild) {
|
||||
@@ -125,7 +125,7 @@ export function getChannelsWithHumans(guild) {
|
||||
|
||||
/**
|
||||
* Get the list of user IDs present in a specific voice channel.
|
||||
* @param {object} guild - Discord guild object.
|
||||
* @param {object} guild - Fluxer guild object.
|
||||
* @param {string} channelId
|
||||
* @returns {string[]}
|
||||
*/
|
||||
|
||||
@@ -0,0 +1,588 @@
|
||||
/**
|
||||
* @module src/core/Bot
|
||||
* @description The Remix bot class: config loading, client construction,
|
||||
* service wiring (settings, commands, players, gateway, dashboard, Last.fm,
|
||||
* FluxerList, track options), presence rotation, alone-check loop, and
|
||||
* WebSocket error guards. Channel/voice operations live in BotVoiceMixin.
|
||||
*/
|
||||
|
||||
import * as fs from "node:fs";
|
||||
import path from "node:path";
|
||||
import childProcess from "node:child_process";
|
||||
import { Client, Events } from "@fluxerjs/core";
|
||||
import { getVoiceManager } from "@fluxerjs/voice";
|
||||
import { initLogger, logger, _wsErrorCooldown } from "./Logger.mjs";
|
||||
import { Locale } from "./Locale.mjs";
|
||||
import { CommandHandler, CommandLoader, PrefixManager } from "../commands/index.mjs";
|
||||
import { MessageHandler, HelpCommand, setGlobalColor } from "../ui/index.mjs";
|
||||
import { cleanId } from "../utils/Utils.mjs";
|
||||
import * as ShardingUtils from "../utils/ShardingUtils.mjs";
|
||||
import { RemoteSettingsManager } from "../db/Settings.mjs";
|
||||
import { PlayerManager } from "../music/PlayerManager.mjs";
|
||||
import { LavalinkManager } from "../music/LavalinkManager.mjs";
|
||||
import { Dashboard } from "../dashboard/Dashboard.mjs";
|
||||
import { VoiceStateCache } from "../voice/VoiceStateCache.mjs";
|
||||
import { GatewayHandler } from "../voice/gateway/GatewayHandler.mjs";
|
||||
import { LastFmManager } from "../services/lastfm/LastFmManager.mjs";
|
||||
import { FluxerListManager } from "../services/FluxerListManager.mjs";
|
||||
import { TrackOptionsManager } from "../services/TrackOptionsManager.mjs";
|
||||
import { applyMixins } from "../utils/mixins.mjs";
|
||||
import BotVoiceMixin from "./BotVoiceMixin.mjs";
|
||||
|
||||
/**
|
||||
* Create a Map-like view object that proxies bot voice-state lookups through
|
||||
* the VoiceStateCache's bot-specific methods.
|
||||
* @param {VoiceStateCache} voiceCache
|
||||
* @returns {Map}
|
||||
*/
|
||||
function createBotView(voiceCache) {
|
||||
return {
|
||||
get size() { return voiceCache.botLocations.size; },
|
||||
get(key) { return voiceCache.botLocations.get(key); },
|
||||
set(key, val) { return voiceCache.setBotUser(key, val); },
|
||||
has(key) { return voiceCache.botLocations.has(key); },
|
||||
delete(key) { return voiceCache.deleteBotUser(key); },
|
||||
forEach(fn) { for (const [k, v] of voiceCache.iterateBotUsers()) fn(v, k, this); },
|
||||
*[Symbol.iterator]() { yield* voiceCache.iterateBotUsers(); },
|
||||
*entries() { yield* voiceCache.iterateBotUsers(); },
|
||||
*keys() { for (const [k] of voiceCache.iterateBotUsers()) yield k; },
|
||||
*values() { for (const [, v] of voiceCache.iterateBotUsers()) yield v; },
|
||||
get observedVoiceBotsSize() { return voiceCache.botLocations.size; },
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a runtime presence update payload from a config entry (string or
|
||||
* object with text/emoji/activity).
|
||||
* @param {string|object} entry
|
||||
* @returns {object}
|
||||
*/
|
||||
function buildRuntimePresence(entry) {
|
||||
const isObj = typeof entry === "object" && entry !== null;
|
||||
const customStatus = {};
|
||||
if (isObj) {
|
||||
if (entry.text) customStatus.text = entry.text;
|
||||
if (entry.emoji_name) customStatus.emojiName = entry.emoji_name;
|
||||
if (entry.emoji_id) customStatus.emojiId = entry.emoji_id;
|
||||
} else {
|
||||
customStatus.text = String(entry);
|
||||
}
|
||||
|
||||
const update = { status: "online", afk: false, customStatus };
|
||||
|
||||
if (isObj && entry.activity) {
|
||||
update.activities = [{
|
||||
name: entry.activity.name ?? "music",
|
||||
type: entry.activity.type ?? 0,
|
||||
url: entry.activity.url ?? undefined,
|
||||
}];
|
||||
}
|
||||
|
||||
return update;
|
||||
}
|
||||
|
||||
/**
|
||||
* @class Remix
|
||||
* @description Main bot class. Orchestrates client, settings, players,
|
||||
* lavalink, gateway events, commands, and 24/7 voice channel management.
|
||||
*/
|
||||
class Remix {
|
||||
/**
|
||||
* Bootstrap the entire bot: load config, create the Fluxer client,
|
||||
* initialise settings/commands/players/dashboard, set up event handlers,
|
||||
* load modules, and log in.
|
||||
*/
|
||||
constructor() {
|
||||
let config;
|
||||
try {
|
||||
config = JSON.parse(fs.readFileSync("config.json", "utf8"));
|
||||
} catch (e) {
|
||||
const reason = e.code === "ENOENT"
|
||||
? "config.json not found. Copy config_example.json → config.json and fill in your values."
|
||||
: `config.json is malformed JSON: ${e.message}`;
|
||||
console.error(`[Startup] FATAL: ${reason}`);
|
||||
process.exit(1);
|
||||
}
|
||||
const REQUIRED_KEYS = ["token", "mysql"];
|
||||
for (const key of REQUIRED_KEYS) {
|
||||
if (config[key] == null) {
|
||||
console.error(`[Startup] FATAL: config.json is missing required key "${key}".`);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
this.config = config;
|
||||
|
||||
setGlobalColor(config.embedColor);
|
||||
|
||||
this.locale = new Locale(typeof config.prefix === "string" && config.prefix ? config.prefix : "%");
|
||||
this.locale.load();
|
||||
|
||||
this.dashboard = new Dashboard(this, {
|
||||
enabled: config.dashboard?.enabled,
|
||||
redis: config.dashboard?.redis,
|
||||
mysql: config.mysql,
|
||||
});
|
||||
|
||||
const presenceContents = config.presenceContents ?? [];
|
||||
const presenceInterval = config.presenceInterval ?? 30_000;
|
||||
|
||||
let presenceRotationIndex = presenceContents.length > 1 ? 1 : 0;
|
||||
let presenceRotationStarted = false;
|
||||
let wsHandlerRearmStarted = false;
|
||||
|
||||
const timers = config.timers ?? {};
|
||||
this.T = {
|
||||
aloneCheckInterval: timers.aloneCheckInterval ?? 60_000,
|
||||
aloneCheckDebounce: timers.aloneCheckDebounce ?? 500,
|
||||
rejoin247Delay: timers.rejoin247Delay ?? 3_000,
|
||||
leave247RejoinDelay: timers.leave247RejoinDelay ?? 5_000,
|
||||
intentionalLeaveTTL: timers.intentionalLeaveTTL ?? 10_000,
|
||||
};
|
||||
|
||||
// Fluxer 3.0: ClientOptions.presence is the normalized PresenceUpdateOptions
|
||||
// shape (customStatus/emojiName/emojiId) — the 2.2 wire format
|
||||
// (custom_status) is no longer read here. buildRuntimePresence() outputs
|
||||
// exactly the normalized shape, so the initial presence reuses it.
|
||||
const client = new Client({
|
||||
waitForGuilds: true,
|
||||
cache: { guilds: false, channels: false, users: false, members: false },
|
||||
...config["fluxer.js"],
|
||||
presence: presenceContents.length === 0 ? undefined : buildRuntimePresence(presenceContents[0]),
|
||||
});
|
||||
|
||||
client.setMaxListeners(50);
|
||||
this.client = client;
|
||||
|
||||
try {
|
||||
getVoiceManager(client);
|
||||
logger.player("[Startup] VoiceManager initialized before login.");
|
||||
} catch (e) {
|
||||
logger.warn("[Startup] VoiceManager pre-login init failed:", e.message);
|
||||
}
|
||||
|
||||
const messages = new MessageHandler(this.client);
|
||||
this.messages = messages;
|
||||
|
||||
const settings = new RemoteSettingsManager(config.mysql, "./storage/defaults.json");
|
||||
this.settingsMgr = settings;
|
||||
|
||||
const configPrefix = config.prefix ?? null;
|
||||
if (configPrefix && settings.defaults) {
|
||||
settings.defaults.prefix = configPrefix;
|
||||
}
|
||||
|
||||
this.locale.bind(this.settingsMgr);
|
||||
|
||||
const commands = new CommandHandler(messages, configPrefix);
|
||||
this.handler = commands;
|
||||
|
||||
const prefixMgr = new PrefixManager(settings, configPrefix);
|
||||
commands.setPrefixManager(prefixMgr);
|
||||
commands.setLocale(this.locale);
|
||||
messages.setLocale(this.locale);
|
||||
this.locale.setPrefixResolver((guildId) => commands.getPrefix(guildId));
|
||||
|
||||
new HelpCommand(commands, messages, (msg) => this.getSettings(msg)).register();
|
||||
|
||||
commands.onPing = (msg) => {
|
||||
msg.replyEmbed(
|
||||
this.handler.format(
|
||||
"My prefix in this server is `$prefix`\n\nRun `$prefix$helpCmd` to get started!",
|
||||
msg.message.guildId
|
||||
),
|
||||
false,
|
||||
{
|
||||
icon_url: msg.channel.channel.guild?.icon
|
||||
? `https://cdn.fluxer.app/icons/${msg.channel.channel.guild.id}/${msg.channel.channel.guild.icon}.webp`
|
||||
: null,
|
||||
title: msg.channel.channel.guild?.name ?? null,
|
||||
}
|
||||
);
|
||||
};
|
||||
commands.owners = config.owners ?? [];
|
||||
|
||||
this.lavalink = null;
|
||||
let lavalinkInitialised = false;
|
||||
|
||||
this.voiceCache = new VoiceStateCache({ maxUsers: 50_000, maxBots: 10_000 });
|
||||
|
||||
this.observedVoiceUsers = this.voiceCache;
|
||||
this.observedVoiceBots = createBotView(this.voiceCache);
|
||||
|
||||
this._announcementChannelCache = new Map();
|
||||
this._announcementChannelTTL = 5 * 60 * 1000;
|
||||
setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const [k, v] of this._announcementChannelCache) {
|
||||
if (v.timestamp && now - v.timestamp > this._announcementChannelTTL) this._announcementChannelCache.delete(k);
|
||||
}
|
||||
}, 60_000);
|
||||
this.intentionalLeaves = new Map();
|
||||
|
||||
this.gatewayHandler = new GatewayHandler(this);
|
||||
this.gatewayHandler.setupEventHandlers();
|
||||
|
||||
this.lastfm = new LastFmManager(config.lastfm, config.mysql);
|
||||
this.fluxerlist = new FluxerListManager(config.fluxerlist);
|
||||
this.trackOptions = new TrackOptionsManager(config.mysql);
|
||||
|
||||
settings.on("ready", () => this._onSettingsReady());
|
||||
|
||||
client.on(Events.Ready, async () => {
|
||||
try {
|
||||
logger.player("Logged in as " + (client.user?.username ?? "bot"));
|
||||
|
||||
this._attachWsErrorHandlers();
|
||||
|
||||
if (!wsHandlerRearmStarted) {
|
||||
wsHandlerRearmStarted = true;
|
||||
setInterval(() => {
|
||||
this._attachWsErrorHandlers();
|
||||
this.gatewayHandler.attachRawListener();
|
||||
}, 5_000).unref?.();
|
||||
}
|
||||
|
||||
const botId = client.user?.id ?? "0";
|
||||
|
||||
await this.settingsMgr.setBotId(botId);
|
||||
await this.lastfm.setBotId(botId);
|
||||
this.dashboard.setBotId(botId);
|
||||
this.trackOptions.setBotId(botId);
|
||||
|
||||
if (!lavalinkInitialised) {
|
||||
lavalinkInitialised = true;
|
||||
this.lavalink = new LavalinkManager(config.nodelink ?? {}, client, { id: botId, username: client.user?.username ?? "bot" });
|
||||
this.lavalink.on("ready", () => {
|
||||
logger.lavalink("[Lavalink] Session ready");
|
||||
});
|
||||
await this.lavalink.init();
|
||||
this.playerContext.lavalink = this.lavalink;
|
||||
}
|
||||
|
||||
this.gatewayHandler.onReady();
|
||||
|
||||
if (!presenceRotationStarted && presenceContents.length > 1) {
|
||||
presenceRotationStarted = true;
|
||||
setInterval(() => {
|
||||
try {
|
||||
const entry = presenceContents[presenceRotationIndex % presenceContents.length];
|
||||
client.user?.setPresence(buildRuntimePresence(entry));
|
||||
presenceRotationIndex = (presenceRotationIndex + 1) % presenceContents.length;
|
||||
} catch (e) {
|
||||
logger.warn("[Presence] Rotation update failed:", e?.message);
|
||||
}
|
||||
}, presenceInterval).unref?.();
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error("[Ready] Fatal error in Ready handler:", e);
|
||||
}
|
||||
});
|
||||
|
||||
client._remix = this;
|
||||
|
||||
this.playerContext = {
|
||||
client: this.client,
|
||||
config,
|
||||
lavalink: null,
|
||||
};
|
||||
this.players = new PlayerManager(settings, commands, {
|
||||
config,
|
||||
player: this.playerContext,
|
||||
dashboard: this.dashboard,
|
||||
locale: this.locale,
|
||||
timers: this.T,
|
||||
trackOptions: this.trackOptions,
|
||||
});
|
||||
this.players.observedVoiceUsers = this.observedVoiceUsers;
|
||||
this.players.voiceCache = this.voiceCache;
|
||||
this.players._lastfm = this.lastfm;
|
||||
|
||||
const ALONE_CHECK_INTERVAL = this.T.aloneCheckInterval;
|
||||
setInterval(() => this._runAloneCheck(), ALONE_CHECK_INTERVAL);
|
||||
|
||||
this.players.checkVoiceChannels = (message) => this._checkVoiceChannelsImpl(message);
|
||||
|
||||
const __dirname = import.meta.dirname;
|
||||
try {
|
||||
this.comHash = childProcess.execSync("git rev-parse --short HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim();
|
||||
this.comHashLong = childProcess.execSync("git rev-parse HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim();
|
||||
} catch (e) {
|
||||
logger.warn("[Git] comhash error:", e?.message);
|
||||
this.comHash = "Newest";
|
||||
this.comHashLong = null;
|
||||
}
|
||||
|
||||
this.comLink = "https://github.com/remix-bot/fluxer/commit/" + (this.comHashLong ?? "");
|
||||
|
||||
const loader = new CommandLoader(commands, this);
|
||||
const dir = path.join(__dirname, "..", "..", "commands");
|
||||
logger.commands("Started loading commands.");
|
||||
loader.loadFromDir(dir)
|
||||
.then(() => logger.commands("Commands loaded."))
|
||||
.catch(e => logger.error("Failed to load commands:", e));
|
||||
|
||||
logger.commands("Loading Modules.");
|
||||
this.loadedModules = new Map();
|
||||
try {
|
||||
this.modules = JSON.parse(fs.readFileSync("./storage/modules.json"));
|
||||
} catch (e) {
|
||||
const reason = e.code === "ENOENT"
|
||||
? "storage/modules.json not found."
|
||||
: `storage/modules.json is malformed JSON: ${e.message}`;
|
||||
console.error(`[Startup] WARN: ${reason} — starting with no modules.`);
|
||||
this.modules = [];
|
||||
}
|
||||
Promise.allSettled(this.modules.map(async m => {
|
||||
if (!m.enabled) return;
|
||||
try {
|
||||
const exported = await import(m.index);
|
||||
const ModClass = exported.default;
|
||||
this.loadedModules.set(m.name, { instance: new ModClass(this), c: ModClass });
|
||||
} catch (e) {
|
||||
logger.error(`[Module] Failed to load "${m.name}":`, e.message);
|
||||
}
|
||||
}))
|
||||
.then(results => {
|
||||
const succeeded = results.filter(r => r.status === "fulfilled").length;
|
||||
const failed = results.length - succeeded;
|
||||
logger.commands(`Modules loaded (${succeeded} succeeded, ${failed} failed).`);
|
||||
});
|
||||
|
||||
// Fluxer.js 3.0 sharding (opt-in, root `shard.mjs`): a child forked by a
|
||||
// ShardingManager attaches the child-side ShardClientUtil BEFORE login —
|
||||
// it applies FLUXER_SHARD_IDS/FLUXER_SHARD_COUNT to the client options
|
||||
// and routes IDENTIFYs through the parent's shared per-IP budget — then
|
||||
// reports readiness so the supervisor's spawn() promise resolves.
|
||||
const startLogin = async () => {
|
||||
if (ShardingUtils.isShardedProcess()) {
|
||||
try {
|
||||
const { attachShardClientUtil } = await import("@fluxerjs/sharding");
|
||||
this.shardUtil = attachShardClientUtil(client);
|
||||
logger.player(
|
||||
`[Startup] Sharding child attached — ${ShardingUtils.describeSharding(client)}.`
|
||||
);
|
||||
} catch (e) {
|
||||
// Fatal: without the shard slice this child would identify as shard 0
|
||||
// like every other child and thrash the gateway sessions.
|
||||
logger.error(
|
||||
"[Startup] FATAL: running under a ShardingManager but the sharding attach failed:",
|
||||
e?.message
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
await client.login(config.token);
|
||||
if (this.shardUtil) {
|
||||
try { this.shardUtil.notifyReady(); }
|
||||
catch (e) { logger.warn("[Startup] Sharding ready report failed:", e?.message); }
|
||||
}
|
||||
};
|
||||
startLogin().catch(e => {
|
||||
logger.error("[Startup] Login failed:", e?.message ?? e);
|
||||
process.exit(1);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings-ready handler: initialise the logger and normalise stay_247
|
||||
* values (single channel per guild, cleaned IDs).
|
||||
* @private
|
||||
*/
|
||||
_onSettingsReady() {
|
||||
initLogger(this.config);
|
||||
logger.settings("[settings] Loaded from DB.");
|
||||
for (const [guildId, serverSettings] of this.settingsMgr.guilds) {
|
||||
const val = serverSettings.get("stay_247");
|
||||
if (!val || val === "none") continue;
|
||||
const rawArr = Array.isArray(val) ? val : [val];
|
||||
const cleaned = rawArr
|
||||
.map(id => cleanId(id))
|
||||
.filter(id => id.length >= 15 && id.length <= 22);
|
||||
|
||||
if (cleaned.length > 1) {
|
||||
// Only 1 channel per guild supported. Keep first, drop the rest.
|
||||
serverSettings.set("stay_247", cleaned.slice(0, 1));
|
||||
logger.settings(
|
||||
`[settings] Trimmed stay_247 for guild ${guildId}: had ${cleaned.length} channels, kept first 1.`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const needsSave = JSON.stringify(cleaned) !== JSON.stringify(val);
|
||||
if (needsSave || !Array.isArray(val)) {
|
||||
const newVal = cleaned.length > 0 ? cleaned : "none";
|
||||
serverSettings.set("stay_247", newVal);
|
||||
logger.settings(
|
||||
`[settings] Cleaned stay_247 for guild ${guildId}: ${JSON.stringify(val)} → ${JSON.stringify(newVal)}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Periodic alone-check: for every active player, when no humans remain in
|
||||
* the channel, either arm the inactivity timer (music still queued) or
|
||||
* emit autoleave.
|
||||
* @private
|
||||
*/
|
||||
_runAloneCheck() {
|
||||
if (this.players.playerMap.size === 0) return;
|
||||
|
||||
for (const [mapKey, player] of this.players.playerMap) {
|
||||
let channelId;
|
||||
try {
|
||||
if (player._destroyed || player._isJoining) continue;
|
||||
|
||||
const guildId = player._guildId;
|
||||
if (!guildId) continue;
|
||||
|
||||
channelId = player._channelId ?? mapKey;
|
||||
const cleanChanId = cleanId(channelId);
|
||||
if (!cleanChanId) continue;
|
||||
|
||||
const cleanGuildId = cleanId(guildId);
|
||||
|
||||
if (player._is247Enabled()) continue;
|
||||
|
||||
if (!player.connection) continue;
|
||||
|
||||
let hasHuman = this.voiceCache.hasHumansInChannel(cleanGuildId, cleanChanId);
|
||||
|
||||
if (!hasHuman) {
|
||||
try {
|
||||
const guild = this.client?.guilds?.get?.(cleanGuildId);
|
||||
const voiceStates = guild?.voice_states ?? guild?.voiceStates;
|
||||
if (voiceStates) {
|
||||
const entries = Array.isArray(voiceStates)
|
||||
? voiceStates
|
||||
: typeof voiceStates.values === "function"
|
||||
? [...voiceStates.values()]
|
||||
: Object.values(voiceStates);
|
||||
for (const state of entries) {
|
||||
const stateChannel = cleanId(state?.channelId ?? state?.channel_id);
|
||||
if (stateChannel === cleanChanId) {
|
||||
const stateUserId = state?.userId ?? state?.user_id ?? state?.id;
|
||||
const member = guild?.members?.get?.(stateUserId);
|
||||
const isBot = member?.user?.bot ?? state?.member?.user?.bot ?? false;
|
||||
if (!isBot) {
|
||||
hasHuman = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch(e) { logger.warn("[AloneCheck] Voice state check error:", e?.message); }
|
||||
}
|
||||
|
||||
if (!hasHuman) {
|
||||
try {
|
||||
const room = player.connection?.room;
|
||||
if (room?.isConnected && room.remoteParticipants && room.remoteParticipants.size > 0) {
|
||||
hasHuman = true;
|
||||
}
|
||||
} catch(e) { logger.warn("[AloneCheck] LiveKit check error:", e?.message); }
|
||||
}
|
||||
|
||||
if (!hasHuman && !player._paused) {
|
||||
if (player.queue?.getCurrent() || !player.queue?.isEmpty()) {
|
||||
player._startInactivityTimer?.();
|
||||
} else {
|
||||
player._stopInactivityTimer?.();
|
||||
player.emit("autoleave");
|
||||
}
|
||||
} else if (hasHuman) {
|
||||
player._stopInactivityTimer?.();
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[AloneCheck] Error checking channel", channelId, e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach proactive error handlers to WebSocket sockets/shards to prevent
|
||||
* unhandled crashes from WebSocket transport errors. Re-armed periodically.
|
||||
* @private
|
||||
*/
|
||||
_attachWsErrorHandlers() {
|
||||
try {
|
||||
const wsManager = this.client?.ws;
|
||||
if (!wsManager) return;
|
||||
|
||||
let attachedNew = false;
|
||||
|
||||
const logWsError = (label, err) => {
|
||||
const now = Date.now();
|
||||
if (now - _wsErrorCooldown.lastLogged < _wsErrorCooldown.COOLDOWN_MS) return;
|
||||
_wsErrorCooldown.lastLogged = now;
|
||||
logger.warn(`[WS] ${label} transport error (auto-recovering): ${err?.message ?? err}`);
|
||||
};
|
||||
|
||||
const attachToSocket = (wsObj, label) => {
|
||||
if (!wsObj) return;
|
||||
if (wsObj._fluxerErrorHandled) return;
|
||||
wsObj._fluxerErrorHandled = true;
|
||||
attachedNew = true;
|
||||
|
||||
if (typeof wsObj.on === "function") {
|
||||
wsObj.on("error", (err) => logWsError(label, err));
|
||||
}
|
||||
if (typeof wsObj.addEventListener === "function") {
|
||||
wsObj.addEventListener("error", (event) => {
|
||||
if (typeof event.preventDefault === "function") event.preventDefault();
|
||||
const err = event?.error ?? event?.message ?? event;
|
||||
logWsError(label, err);
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const attachToShard = (shard, id) => {
|
||||
if (!shard) return;
|
||||
if (shard._fluxerErrorHandled) return;
|
||||
shard._fluxerErrorHandled = true;
|
||||
attachedNew = true;
|
||||
shard.on("error", (err) => logWsError(`Shard ${id}`, err));
|
||||
if (shard.ws) attachToSocket(shard.ws, `Shard ${id} socket`);
|
||||
};
|
||||
|
||||
// Fluxer 3.0: the ws manager exposes shards via getShards() (2.2 used a
|
||||
// `shards` Map property) and a sharded child owns several of them —
|
||||
// attach to every shard connected in this process, not just shard 0.
|
||||
for (const [id, shard] of ShardingUtils.getLocalShards(this.client)) {
|
||||
attachToShard(shard, id);
|
||||
}
|
||||
|
||||
if (wsManager.ws) {
|
||||
attachToSocket(wsManager.ws, "Gateway");
|
||||
}
|
||||
|
||||
if (typeof wsManager.on === "function" && !wsManager._fluxerErrorHandled) {
|
||||
wsManager._fluxerErrorHandled = true;
|
||||
attachedNew = true;
|
||||
wsManager.on("error", ({ shardId, error }) => {
|
||||
logWsError(`WSManager (shard ${shardId})`, error);
|
||||
});
|
||||
}
|
||||
|
||||
if (typeof wsManager.on === "function" && !wsManager._shardCreateHandled) {
|
||||
wsManager._shardCreateHandled = true;
|
||||
attachedNew = true;
|
||||
wsManager.on("shardCreate", (shard) => {
|
||||
attachToShard(shard, shard.id ?? "?");
|
||||
});
|
||||
}
|
||||
|
||||
if (attachedNew) {
|
||||
logger.player("[WS] Proactive error handlers attached to gateway sockets.");
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[WS] Failed to attach WS error handlers:", e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Attach channel/voice operations (spawn, leave, shared servers, helpers).
|
||||
applyMixins(Remix, BotVoiceMixin);
|
||||
|
||||
export { Remix };
|
||||
export default Remix;
|
||||
@@ -0,0 +1,511 @@
|
||||
/**
|
||||
* @module src/core/BotVoiceMixin
|
||||
* @description Channel & voice operations for the {@link Remix} bot class:
|
||||
* voice-channel resolution (checkVoiceChannels), 24/7 player spawning with
|
||||
* announcements, programmatic channel leave, shared-server listing, and
|
||||
* small translation/settings/pagination helpers.
|
||||
*
|
||||
* These methods are applied onto the Remix class prototype via
|
||||
* {@link applyMixins} — `this` is a Remix instance.
|
||||
*/
|
||||
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getVoiceManager } from "@fluxerjs/voice";
|
||||
import { getGlobalColor, PageBuilder } from "../ui/index.mjs";
|
||||
import { cleanId } from "../utils/Utils.mjs";
|
||||
import { remove247ChannelMode } from "../utils/Helpers247.mjs";
|
||||
import { logger } from "./Logger.mjs";
|
||||
import { Dashboard } from "../dashboard/Dashboard.mjs";
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
* @description Voice/channel mixin — applied to Remix.
|
||||
*/
|
||||
const BotVoiceMixin = {
|
||||
/**
|
||||
* Resolve the user's voice channel for a command invocation. Tries, in
|
||||
* order: the voice-state cache, the VoiceManager, guild voice states, a
|
||||
* cache scan, REST member fetch, and a raw REST member lookup.
|
||||
* @this {import('./Bot.mjs').Remix}
|
||||
* @param {object} message - Message wrapper.
|
||||
* @returns {Promise<{channelId: string|null, alreadyInVoice: boolean, hasHumans: boolean}>}
|
||||
*/
|
||||
async _checkVoiceChannelsImpl(message) {
|
||||
const userId = message?.author?.id ?? message?.message?.author?.id;
|
||||
const guildId =
|
||||
message?.channel?.guildId ??
|
||||
message?.channel?.guild?.id ??
|
||||
message?.channel?.server_id ??
|
||||
message?.channel?.serverId ??
|
||||
message?.message?.guildId ??
|
||||
message?.message?.guild?.id ??
|
||||
message?.message?.channel?.guildId ??
|
||||
message?.message?.channel?.guild?.id ??
|
||||
message?.message?.channel?.server_id ??
|
||||
message?.message?.channel?.serverId;
|
||||
|
||||
const _empty = { channelId: null, alreadyInVoice: false, hasHumans: false };
|
||||
|
||||
if (!userId || !guildId) {
|
||||
logger.voice(`[checkVC] BAIL — missing userId or guildId`);
|
||||
return _empty;
|
||||
}
|
||||
|
||||
const cleanGuild = cleanId(guildId);
|
||||
|
||||
const makeResult = (channelId) => {
|
||||
const cId = cleanId(channelId);
|
||||
return {
|
||||
channelId: cId,
|
||||
alreadyInVoice: this.players.playerMap.has(cId),
|
||||
hasHumans: this.voiceCache.hasHumansInChannel(cleanGuild, cId),
|
||||
};
|
||||
};
|
||||
|
||||
const seedCache = (channelId) => {
|
||||
if (!this.voiceCache.hasHumanUser(userId, cleanGuild)) {
|
||||
this.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId, isBot: false });
|
||||
}
|
||||
};
|
||||
|
||||
logger.voice(`[checkVC] userId=${userId} guildId=${guildId} cleanGuild=${cleanGuild}`);
|
||||
|
||||
const observed = this.voiceCache.getUserLocation(cleanGuild, userId);
|
||||
if (observed && observed.channelId) {
|
||||
logger.voice(`[checkVC] HIT voiceCache → ${observed.channelId}`);
|
||||
return makeResult(observed.channelId);
|
||||
}
|
||||
|
||||
try {
|
||||
const vm = getVoiceManager(this.client);
|
||||
const channelId = vm?.getVoiceChannelId?.(guildId, userId) ?? vm?.getVoiceChannelId?.(cleanGuild, userId);
|
||||
logger.voice(`[checkVC] vm.getVoiceChannelId → ${channelId}`);
|
||||
if (channelId) {
|
||||
seedCache(channelId);
|
||||
return makeResult(channelId);
|
||||
}
|
||||
} catch (e) { logger.voice(`[checkVC] vm error: ${e.message}`); }
|
||||
|
||||
try {
|
||||
const guild = this.client.guilds.get(guildId) ?? this.client.guilds.get(cleanGuild);
|
||||
const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null;
|
||||
if (voiceStates) {
|
||||
const entries = Array.isArray(voiceStates)
|
||||
? voiceStates
|
||||
: typeof voiceStates.values === "function"
|
||||
? [...voiceStates.values()]
|
||||
: Object.values(voiceStates);
|
||||
for (const state of entries) {
|
||||
const sid = state?.userId ?? state?.user_id ?? state?.id;
|
||||
const sch = state?.channelId ?? state?.channel_id;
|
||||
if ((sid === userId || sid === cleanId(userId)) && sch) {
|
||||
logger.voice(`[checkVC] HIT guild.voice_states → ${sch}`);
|
||||
seedCache(sch);
|
||||
return makeResult(sch);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) { logger.voice(`[checkVC] guild error: ${e.message}`); }
|
||||
|
||||
try {
|
||||
const loc = this.voiceCache.getHumanUser(userId, cleanGuild);
|
||||
if (loc && loc.channelId) {
|
||||
logger.voice(`[checkVC] HIT voiceCache scan → ${loc.channelId}`);
|
||||
return makeResult(loc.channelId);
|
||||
}
|
||||
} catch (e) { logger.voice(`[checkVC] scan error: ${e.message}`); }
|
||||
|
||||
try {
|
||||
const guild = this.client.guilds.get(guildId) ?? this.client.guilds.get(cleanGuild);
|
||||
if (guild && typeof guild.fetchMember === "function") {
|
||||
logger.voice(`[checkVC] Trying REST fetchMember fallback for user ${userId}`);
|
||||
const member = await guild.fetchMember(userId);
|
||||
const voiceState = member?.voice ?? member?.voiceState ?? null;
|
||||
const restChannelId = voiceState?.channelId ?? voiceState?.channel_id ?? null;
|
||||
if (restChannelId) {
|
||||
logger.voice(`[checkVC] HIT REST member.voice → ${restChannelId}`);
|
||||
seedCache(restChannelId);
|
||||
return makeResult(restChannelId);
|
||||
}
|
||||
}
|
||||
} catch (e) { logger.voice(`[checkVC] REST fallback error: ${e.message}`); }
|
||||
|
||||
try {
|
||||
const guild = this.client.guilds.get(guildId) ?? this.client.guilds.get(cleanGuild);
|
||||
if (guild && typeof this.client.rest?.get === "function") {
|
||||
logger.voice(`[checkVC] Trying raw REST /guilds/${cleanGuild}/members/${userId}`);
|
||||
const memberData = await this.client.rest.get(`/guilds/${cleanGuild}/members/${userId}`);
|
||||
const restChannelId = memberData?.voice_state?.channel_id ?? memberData?.channel_id ?? null;
|
||||
if (restChannelId) {
|
||||
logger.voice(`[checkVC] HIT raw REST → ${restChannelId}`);
|
||||
seedCache(restChannelId);
|
||||
return makeResult(restChannelId);
|
||||
}
|
||||
}
|
||||
} catch (e) { logger.voice(`[checkVC] raw REST error: ${e.message}`); }
|
||||
|
||||
logger.voice(`[checkVC] MISS — returning empty`);
|
||||
return _empty;
|
||||
},
|
||||
|
||||
/**
|
||||
* Mark a channel leave as intentional (user-initiated) to prevent the 24/7
|
||||
* auto-rejoin system from rejoining.
|
||||
* @this {import('./Bot.mjs').Remix}
|
||||
* @param {string} channelId - The channel ID.
|
||||
* @param {number|null} [ttlMs=null] - TTL in ms (default: config.timers.intentionalLeaveTTL or 10s).
|
||||
*/
|
||||
markIntentionalLeave(channelId, ttlMs = null) {
|
||||
const cleanChId = cleanId(channelId);
|
||||
if (!cleanChId) return;
|
||||
if (ttlMs === null) ttlMs = this.config?.timers?.intentionalLeaveTTL ?? 10_000;
|
||||
const existing = this.intentionalLeaves.get(cleanChId);
|
||||
if (existing) clearTimeout(existing);
|
||||
this.intentionalLeaves.set(cleanChId, setTimeout(() => {
|
||||
this.intentionalLeaves.delete(cleanChId);
|
||||
}, ttlMs));
|
||||
},
|
||||
|
||||
/**
|
||||
* Spawn a new Player for a channel. Used by 24/7 boot recovery and
|
||||
* enable247. Guards against duplicate players, missing channels, and
|
||||
* pending joins.
|
||||
* @this {import('./Bot.mjs').Remix}
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @param {string} channelId - The target voice channel ID.
|
||||
* @returns {Promise<import('../music/player/Player.mjs').Player>}
|
||||
* @throws {Error} If channel not found, not a voice channel, or join fails.
|
||||
*/
|
||||
async _spawnPlayer(guildId, channelId) {
|
||||
const cleanGuildId = cleanId(guildId);
|
||||
const cleanChannelId = cleanId(channelId);
|
||||
|
||||
if (!cleanChannelId) throw new Error("_spawnPlayer: invalid channelId");
|
||||
|
||||
const existing = this.players.playerMap.get(cleanChannelId)
|
||||
?? this.players.getPlayerByGuildAndChannel(cleanGuildId, cleanChannelId);
|
||||
if (existing) return existing;
|
||||
|
||||
if (!this.lavalink) throw new Error("Audio node not ready yet — try again in a moment");
|
||||
|
||||
const channel = this.client?.channels?.get?.(cleanChannelId);
|
||||
if (!channel) throw new Error("Channel not found");
|
||||
if (channel.type !== 2) throw new Error("Not a voice channel");
|
||||
|
||||
if (this.players._pendingJoins?.has?.(cleanChannelId)) {
|
||||
throw new Error("Join already in progress for this channel");
|
||||
}
|
||||
|
||||
const Player = (await import("../music/player/index.mjs")).default;
|
||||
|
||||
const player = new Player(this.config.token, {
|
||||
client: this.client,
|
||||
config: this.config,
|
||||
lavalink: this.lavalink ?? null,
|
||||
settingsMgr: this.settingsMgr ?? this.settings ?? null,
|
||||
getPrefix: (guildId) => this.handler.getPrefix(guildId),
|
||||
observedVoiceUsers: this.observedVoiceUsers ?? null,
|
||||
voiceCache: this.voiceCache ?? null,
|
||||
locale: this.locale ?? null,
|
||||
trackOptions: this.trackOptions ?? null,
|
||||
});
|
||||
|
||||
player._home247Channel = cleanChannelId;
|
||||
|
||||
this.players.setupEvents(player, {
|
||||
channelId: cleanChannelId,
|
||||
guildId: cleanGuildId,
|
||||
});
|
||||
|
||||
player.on("autoleave", () => {
|
||||
const mode = player._get247Mode();
|
||||
if (mode === "on") {
|
||||
logger.inactivity(`[_spawnPlayer] autoleave suppressed for 24/7 channel ${cleanChannelId} (guild ${cleanGuildId})`);
|
||||
return;
|
||||
}
|
||||
if (player._hasHumansInChannel()) {
|
||||
logger.inactivity(`[_spawnPlayer] autoleave suppressed — humans in channel ${cleanChannelId}`);
|
||||
return;
|
||||
}
|
||||
if (player.queue?.getCurrent() || !player.queue?.isEmpty()) {
|
||||
logger.inactivity(`[_spawnPlayer] autoleave suppressed — queue has songs in channel ${cleanChannelId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
const activeChId = cleanId(player._channelId ?? cleanChannelId) || cleanChannelId;
|
||||
const homeChId = cleanId(player._home247Channel ?? activeChId) || activeChId;
|
||||
this.players.playerMap.delete(activeChId);
|
||||
this.players._unindexPlayer?.(cleanGuildId, activeChId);
|
||||
const pendingScrobble = this.players._pendingScrobbleTimers?.get(cleanChannelId);
|
||||
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this.players._pendingScrobbleTimers.delete(cleanChannelId); }
|
||||
if (activeChId !== cleanChannelId) this.players.playerMap.delete(cleanChannelId);
|
||||
if (homeChId !== activeChId) this.players.playerMap.delete(homeChId);
|
||||
player.destroy();
|
||||
});
|
||||
|
||||
player.on("message", async (m) => {
|
||||
try {
|
||||
const serverSettings = this.settingsMgr?.getServer?.(cleanGuildId);
|
||||
const raw = serverSettings?.get?.("songAnnouncements");
|
||||
const disabled = raw === false || raw === 0 ||
|
||||
["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim());
|
||||
if (disabled) return;
|
||||
|
||||
const chMgr = this.client?.channels ?? null;
|
||||
const canPostById = (c) => !!c?.id && !!chMgr && typeof chMgr.send === "function";
|
||||
const asSendable = (c) => {
|
||||
if (!c || typeof c === "string" || typeof c.send === "function") return c;
|
||||
if (!canPostById(c)) return c;
|
||||
const target = { id: c.id, type: c.type };
|
||||
target.isTextBased = () => true;
|
||||
target.send = (options) => chMgr.send(c.id, options);
|
||||
return target;
|
||||
};
|
||||
const usable = (c) => !!c && typeof c === "object" &&
|
||||
(typeof c.send === "function" || canPostById(c));
|
||||
|
||||
const _tc = player.textChannel;
|
||||
let ch = (_tc && typeof _tc === "object" && _tc.channel && typeof _tc.channel === "object")
|
||||
? _tc.channel
|
||||
: _tc;
|
||||
if (!usable(ch)) {
|
||||
const savedAnnChId = serverSettings?.get?.("announcementChannelId");
|
||||
if (savedAnnChId) {
|
||||
ch = this.client?.channels?.get?.(cleanId(savedAnnChId)) ?? null;
|
||||
}
|
||||
}
|
||||
if (!usable(ch)) {
|
||||
const guild = this.client?.guilds?.get?.(cleanGuildId);
|
||||
if (guild?.systemChannelId) {
|
||||
ch = guild.channels?.get?.(guild.systemChannelId) ?? null;
|
||||
}
|
||||
}
|
||||
if (!usable(ch)) {
|
||||
const guild = this.client?.guilds?.get?.(cleanGuildId);
|
||||
if (guild?.channels) {
|
||||
for (const c of (guild.channels.values?.() ?? [])) {
|
||||
if (c.isTextBased?.() || c.type === 0 || c.type === "GUILD_TEXT") {
|
||||
ch = c;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!usable(ch)) return;
|
||||
|
||||
ch = asSendable(ch);
|
||||
if (!player.textChannel) player.textChannel = ch;
|
||||
|
||||
const payload = typeof m === "object" && Array.isArray(m.embeds)
|
||||
? { ...m, allowedMentions: { parse: [] } }
|
||||
: { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(m)], allowedMentions: { parse: [] } };
|
||||
ch.send(payload).catch(err => {
|
||||
if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) {
|
||||
logger.warn(`[_spawnPlayer] Cannot send announcement in channel ${ch.id} — missing permissions`);
|
||||
} else {
|
||||
logger.warn(`[_spawnPlayer] Failed to send announcement in channel ${ch.id}:`, err?.message ?? err);
|
||||
}
|
||||
});
|
||||
} catch(e) {
|
||||
logger.warn("[Player] Song announcement error:", e?.message);
|
||||
}
|
||||
});
|
||||
|
||||
if (this.players._pendingJoins) {
|
||||
this.players._pendingJoins.add(cleanChannelId);
|
||||
}
|
||||
|
||||
try {
|
||||
await player.join(cleanChannelId);
|
||||
|
||||
this.players.playerMap.set(cleanChannelId, player);
|
||||
this.players._indexPlayer(cleanGuildId, cleanChannelId);
|
||||
if (this.players._pendingJoins) {
|
||||
this.players._pendingJoins.delete(cleanChannelId);
|
||||
}
|
||||
|
||||
const savedVol = this.settingsMgr?.getServer?.(cleanGuildId)?.get?.("volume");
|
||||
if (savedVol !== undefined && savedVol !== null) {
|
||||
const vol = Number(savedVol);
|
||||
if (!isNaN(vol)) player.setVolume(vol / 100);
|
||||
}
|
||||
|
||||
logger.player(`[_spawnPlayer] Spawned player for channel ${cleanChannelId} in guild ${cleanGuildId}`);
|
||||
return player;
|
||||
} catch (err) {
|
||||
if (this.players._pendingJoins) {
|
||||
this.players._pendingJoins.delete(cleanChannelId);
|
||||
}
|
||||
this.players.playerMap.delete(cleanChannelId);
|
||||
try { player.destroy(); } catch(e) { logger.warn("[_spawnPlayer] Cleanup destroy error:", e?.message); }
|
||||
logger.warn(`[_spawnPlayer] Failed to spawn player for channel ${cleanChannelId}:`, err.message);
|
||||
throw err;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Leave a voice channel programmatically. Removes 24/7 if active, destroys
|
||||
* the player, and optionally sends a confirmation message.
|
||||
* @this {import('./Bot.mjs').Remix}
|
||||
* @param {string} channelId - The channel ID to leave.
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @param {object} [message=null] - Optional message for reply confirmation.
|
||||
* @param {boolean} [force=false] - Whether to force-leave regardless of 24/7 status.
|
||||
* @returns {Promise<boolean>} True on success.
|
||||
*/
|
||||
async leaveChannel(channelId, guildId, message, force = false) {
|
||||
const cleanChId = cleanId(channelId);
|
||||
const cleanGuildId = cleanId(guildId);
|
||||
const set = this.settingsMgr.getServer(cleanGuildId);
|
||||
const raw = set?.get("stay_247");
|
||||
|
||||
const channels = (!raw || raw === "none")
|
||||
? new Set()
|
||||
: Array.isArray(raw)
|
||||
? new Set(raw.map(id => cleanId(id)).filter(Boolean))
|
||||
: new Set([cleanId(raw)]);
|
||||
|
||||
if (channels.has(cleanChId)) {
|
||||
channels.delete(cleanChId);
|
||||
set.set("stay_247", channels.size > 0 ? [...channels] : "none");
|
||||
remove247ChannelMode(set, cleanChId, channels);
|
||||
}
|
||||
|
||||
this.markIntentionalLeave(cleanChId);
|
||||
|
||||
const player = this.players.playerMap.get(cleanChId);
|
||||
if (player) {
|
||||
this.players.playerMap.delete(cleanChId);
|
||||
this.players._unindexPlayer(player._guildId, cleanChId);
|
||||
const pendingScrobble = this.players._pendingScrobbleTimers?.get(cleanChId);
|
||||
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this.players._pendingScrobbleTimers.delete(cleanChId); }
|
||||
await player.leave().catch(() => {});
|
||||
player.destroy();
|
||||
}
|
||||
|
||||
if (message) {
|
||||
const guildIdForLocale = message?.channel?.channel?.guildId ?? message?.guildId ?? cleanGuildId;
|
||||
message.replyEmbed(this.locale.translate(guildIdForLocale, "responses._common.successfullyLeft"));
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the server settings for the guild associated with a message.
|
||||
* @this {import('./Bot.mjs').Remix}
|
||||
* @param {object} message - The incoming message wrapper.
|
||||
* @returns {object} The ServerSettings for the guild, or a fallback.
|
||||
*/
|
||||
getSettings(message) {
|
||||
const guildId = message?.channel?.channel?.guildId ?? message?.guildId ?? null;
|
||||
return this.settingsMgr.getServer(guildId);
|
||||
},
|
||||
|
||||
/**
|
||||
* Shorthand to translate a locale key for the guild of a given message.
|
||||
* @this {import('./Bot.mjs').Remix}
|
||||
* @param {object} message - The message wrapper (used to resolve guild ID).
|
||||
* @param {string} key - The locale key.
|
||||
* @param {object} [data={}] - Interpolation data.
|
||||
* @returns {string} The localised string.
|
||||
*/
|
||||
t(message, key, data = {}) {
|
||||
const guildId = message?.channel?.channel?.guildId
|
||||
?? message?.message?.guildId
|
||||
?? message?.guildId
|
||||
?? null;
|
||||
return this.locale.translate(guildId, key, data);
|
||||
},
|
||||
|
||||
/**
|
||||
* Get or create a player for the given message context.
|
||||
* @this {import('./Bot.mjs').Remix}
|
||||
* @param {object} message - The message wrapper.
|
||||
* @param {boolean} promptJoin - Whether to prompt the user to join a voice channel.
|
||||
* @param {boolean} verifyUser - Whether to verify the user is in a voice channel.
|
||||
* @param {boolean} shouldJoin - Whether to auto-join the voice channel.
|
||||
* @returns {Promise<object>} The Player instance.
|
||||
*/
|
||||
getPlayer(message, promptJoin, verifyUser, shouldJoin) {
|
||||
return this.players.getPlayer(message, promptJoin, verifyUser, shouldJoin);
|
||||
},
|
||||
|
||||
/**
|
||||
* Get all servers the bot and the given user share (i.e. the user is a
|
||||
* member). Used by the dashboard to determine which servers a user can
|
||||
* manage.
|
||||
* @this {import('./Bot.mjs').Remix}
|
||||
* @param {object} user - The Fluxer user.
|
||||
* @returns {Promise<Array<object>>} Array of server summaries with channels.
|
||||
*/
|
||||
async getSharedServers(user) {
|
||||
if (!user) return [];
|
||||
|
||||
const shared = [];
|
||||
|
||||
for (const guild of this.client.guilds?.values?.() ?? []) {
|
||||
let isMember = false;
|
||||
|
||||
if (guild.members?.has?.(user.id)) {
|
||||
isMember = true;
|
||||
}
|
||||
|
||||
if (!isMember) {
|
||||
const cleanGuildId = cleanId(guild.id);
|
||||
const userLoc = this.voiceCache.getUserLocation(cleanGuildId, user.id);
|
||||
if (userLoc) isMember = true;
|
||||
}
|
||||
|
||||
if (!isMember) {
|
||||
try {
|
||||
const member = await guild.members.fetch(user.id).catch(() => null);
|
||||
if (member) isMember = true;
|
||||
} catch (e) { logger.warn(`[getSharedServers] Member fetch error for ${user.id}:`, e?.message); }
|
||||
}
|
||||
|
||||
if (!isMember) continue;
|
||||
|
||||
const guildChannels = guild.channels
|
||||
? [...guild.channels.values()]
|
||||
: [];
|
||||
const allChannels = guildChannels
|
||||
.map(c => Dashboard.convertChannel(c))
|
||||
.filter(c => !c.isCategory);
|
||||
const channelIds = guildChannels.map(c => c.id);
|
||||
|
||||
shared.push({
|
||||
name: guild.name,
|
||||
id: guild.id,
|
||||
icon: guild.icon
|
||||
? `https://cdn.fluxer.app/icons/${guild.id}/${guild.icon}.webp`
|
||||
: null,
|
||||
description: guild.description ?? null,
|
||||
ownerId: guild.ownerId ?? null,
|
||||
channels: allChannels,
|
||||
channelIds: channelIds,
|
||||
voiceChannels: allChannels.filter(c => c.isVoice),
|
||||
});
|
||||
}
|
||||
|
||||
return shared;
|
||||
},
|
||||
|
||||
/**
|
||||
* Create and attach a paginated message to the given message.
|
||||
* @this {import('./Bot.mjs').Remix}
|
||||
* @param {string} form - The form/locale key for the page title.
|
||||
* @param {string} content - The full content to paginate.
|
||||
* @param {object} msg - The message wrapper.
|
||||
* @param {number} linesPerPage - Maximum lines per page.
|
||||
*/
|
||||
pagination(form, content, msg, linesPerPage) {
|
||||
this.messages.initPagination(
|
||||
new PageBuilder(content).setForm(form).setMaxLines(linesPerPage),
|
||||
msg
|
||||
);
|
||||
},
|
||||
};
|
||||
|
||||
export default BotVoiceMixin;
|
||||
export { BotVoiceMixin };
|
||||
@@ -0,0 +1,210 @@
|
||||
/** @module src/core/Locale */
|
||||
|
||||
import { readFileSync, readdirSync, existsSync } from "fs";
|
||||
import path from "path";
|
||||
import { fileURLToPath } from "url";
|
||||
import { logger } from "./Logger.mjs";
|
||||
|
||||
/** @private */
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
/** @private */
|
||||
const LOCALES_DIR = path.resolve(__dirname, "../../storage/locales/bot");
|
||||
|
||||
/**
|
||||
* Locale/i18n manager that loads JSON locale files from disk and provides
|
||||
* dot-notation key lookups with `{{placeholder}}` and `$prefix` substitution.
|
||||
* @class
|
||||
*/
|
||||
export class Locale {
|
||||
/**
|
||||
* @param {string} [defaultPrefix="%"] - Fallback prefix used when no prefix
|
||||
* resolver is registered and the settings manager yields no prefix.
|
||||
*/
|
||||
constructor(defaultPrefix = "%") {
|
||||
/** @private */ this.locales = new Map();
|
||||
/** @private */ this._resolved = new Map();
|
||||
/** @type {string} */ this.defaultLocale = "en";
|
||||
/** @private */ this.settingsMgr = null;
|
||||
/** @private */ this._getPrefixFn = null;
|
||||
/** @private */ this._defaultPrefix = defaultPrefix;
|
||||
/** @private */ this._maxResolvedCache = 5000;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind a settings manager so the locale resolver can look up per-guild locale preferences.
|
||||
* @param {object} settingsMgr - Settings manager exposing `guilds.get(guildId)`.
|
||||
*/
|
||||
bind(settingsMgr) {
|
||||
this.settingsMgr = settingsMgr;
|
||||
}
|
||||
|
||||
/**
|
||||
* Load all `.json` locale files from the locales directory.
|
||||
* Clears any previously loaded data and the resolved-cache.
|
||||
*/
|
||||
load() {
|
||||
this.locales.clear();
|
||||
this._resolved.clear();
|
||||
|
||||
if (!existsSync(LOCALES_DIR)) {
|
||||
logger.warn("[Locale] Locales directory not found:", LOCALES_DIR);
|
||||
return;
|
||||
}
|
||||
|
||||
let files;
|
||||
try {
|
||||
files = readdirSync(LOCALES_DIR).filter(f => f.endsWith(".json"));
|
||||
} catch (e) {
|
||||
logger.warn("[Locale] Failed to read locales directory:", e.message);
|
||||
return;
|
||||
}
|
||||
|
||||
for (const file of files) {
|
||||
const filePath = path.join(LOCALES_DIR, file);
|
||||
const code = file.replace(".json", "");
|
||||
try {
|
||||
const data = JSON.parse(readFileSync(filePath, "utf8"));
|
||||
this.locales.set(code, data);
|
||||
} catch (e) {
|
||||
logger.warn("[Locale] Failed to load " + file + ":", e.message);
|
||||
}
|
||||
}
|
||||
|
||||
logger.info("[Locale] Loaded " + this.locales.size + " locale(s): " + [...this.locales.keys()].join(", "));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the set of loaded locale codes.
|
||||
* @returns {Set<string>}
|
||||
*/
|
||||
availableLocales() {
|
||||
return new Set(this.locales.keys());
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the locale data object for a guild, using per-guild settings or falling
|
||||
* back to the default locale. Results are cached with an LRU-style cap.
|
||||
* @private
|
||||
* @param {string} guildId
|
||||
* @returns {object} The locale data object.
|
||||
*/
|
||||
_getLocaleData(guildId) {
|
||||
if (!guildId) return this.locales.get(this.defaultLocale) ?? {};
|
||||
|
||||
const cached = this._resolved.get(guildId);
|
||||
if (cached) return cached;
|
||||
|
||||
let code = this.defaultLocale;
|
||||
try {
|
||||
const serverSettings = this.settingsMgr?.guilds?.get?.(guildId);
|
||||
if (serverSettings) {
|
||||
const setting = serverSettings.get("locale");
|
||||
if (setting && this.locales.has(setting)) {
|
||||
code = setting;
|
||||
}
|
||||
}
|
||||
} catch(e) { logger.warn("[Locale] Error:", e?.message); }
|
||||
|
||||
const data = this.locales.get(code) ?? this.locales.get(this.defaultLocale) ?? {};
|
||||
this._resolved.set(guildId, data);
|
||||
|
||||
while (this._resolved.size > this._maxResolvedCache) {
|
||||
const oldestKey = this._resolved.keys().next().value;
|
||||
this._resolved.delete(oldestKey);
|
||||
}
|
||||
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invalidate the resolved-cache for a specific guild or all guilds.
|
||||
* @param {string} [guildId] - Omit to clear the entire cache.
|
||||
*/
|
||||
invalidateCache(guildId) {
|
||||
if (guildId) {
|
||||
this._resolved.delete(guildId);
|
||||
} else {
|
||||
this._resolved.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a custom prefix resolver function.
|
||||
* @param {function(string): string} fn - Receives `guildId`, returns the prefix string.
|
||||
*/
|
||||
setPrefixResolver(fn) {
|
||||
this._getPrefixFn = fn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the command prefix for a guild.
|
||||
* @private
|
||||
* @param {string} guildId
|
||||
* @returns {string}
|
||||
*/
|
||||
_getPrefix(guildId) {
|
||||
if (this._getPrefixFn) return this._getPrefixFn(guildId);
|
||||
try {
|
||||
const serverSettings = this.settingsMgr?.getServer?.(guildId);
|
||||
if (serverSettings) {
|
||||
const prefix = serverSettings.get("prefix");
|
||||
if (prefix) return prefix;
|
||||
}
|
||||
} catch(e) { logger.warn("[Locale] Error:", e?.message); }
|
||||
return this._defaultPrefix || "!";
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a dot-notation key against a nested object.
|
||||
* @private
|
||||
* @param {object} obj
|
||||
* @param {string} key - e.g. "commands.play.description"
|
||||
* @returns {*}
|
||||
*/
|
||||
_resolve(obj, key) {
|
||||
const parts = key.split(".");
|
||||
let current = obj;
|
||||
for (const part of parts) {
|
||||
if (current == null || typeof current !== "object") return undefined;
|
||||
current = current[part];
|
||||
}
|
||||
return current;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translate a locale key for a guild, applying `{{placeholder}}` replacements
|
||||
* and `$prefix` substitution. Falls back to the default locale, then the raw key.
|
||||
* @param {string} guildId
|
||||
* @param {string} key - Dot-notation locale key.
|
||||
* @param {Object<string, *>} [replacements={}] - Placeholder values to substitute.
|
||||
* @returns {string} The translated (or fallback) string.
|
||||
*/
|
||||
translate(guildId, key, replacements = {}) {
|
||||
const localeData = this._getLocaleData(guildId);
|
||||
|
||||
let value = this._resolve(localeData, key);
|
||||
|
||||
if (value === undefined) {
|
||||
value = this._resolve(this.locales.get(this.defaultLocale) ?? {}, key);
|
||||
}
|
||||
|
||||
if (value === undefined) return key;
|
||||
if (typeof value !== "string") return key;
|
||||
|
||||
for (const [placeholder, val] of Object.entries(replacements)) {
|
||||
const escaped = placeholder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
const replacement = String(val ?? "");
|
||||
value = value.replace(
|
||||
new RegExp(`\\{\\{${escaped}\\}\\}`, "g"),
|
||||
() => replacement
|
||||
);
|
||||
}
|
||||
|
||||
if (value.includes("$prefix")) {
|
||||
const prefix = this._getPrefix(guildId);
|
||||
value = value.replace(/\$prefix/gi, prefix);
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
/** @module src/core/Logger */
|
||||
|
||||
/** @private */
|
||||
let _config = null;
|
||||
|
||||
/**
|
||||
* Initialize the logger with a configuration object.
|
||||
* @param {object} [config] - Application configuration object.
|
||||
* @param {object} [config.logging] - Logging-specific configuration.
|
||||
*/
|
||||
export function initLogger(config) {
|
||||
_config = config?.logging ?? {};
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a given log category is enabled.
|
||||
* @private
|
||||
* @param {string} category - The log category name (e.g. "player", "voice").
|
||||
* @returns {boolean} `true` if the category is enabled (or no config is loaded).
|
||||
*/
|
||||
function isEnabled(category) {
|
||||
if (!_config) return true;
|
||||
if (_config.enabled === false) return false;
|
||||
return _config[category] !== false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an ISO-8601 timestamp string truncated to seconds.
|
||||
* @private
|
||||
* @returns {string} Timestamp in `YYYY-MM-DD HH:MM:SS` format.
|
||||
*/
|
||||
function ts() {
|
||||
return new Date().toISOString().replace("T", " ").slice(0, 19);
|
||||
}
|
||||
|
||||
/**
|
||||
* Cooldown state for WebSocket error logging to avoid spam.
|
||||
* @type {{ lastLogged: number, COOLDOWN_MS: number }}
|
||||
*/
|
||||
export const _wsErrorCooldown = { lastLogged: 0, COOLDOWN_MS: 15_000 };
|
||||
|
||||
/**
|
||||
* Log-storm suppression for identical repeated `error`/`warn` lines.
|
||||
* The first occurrence is always emitted; identical repeats within a 60s
|
||||
* window are counted silently, and once per window a single pulse line with
|
||||
* the repeat count is emitted instead. Bounds worst-case volume of any hot
|
||||
* retry loop to one line per minute instead of millions.
|
||||
* @private
|
||||
* @type {Map<string, {n: number, start: number}>}
|
||||
*/
|
||||
const _stormGuard = new Map();
|
||||
const STORM_WINDOW_MS = 60_000;
|
||||
const STORM_MAX_KEYS = 128;
|
||||
|
||||
/**
|
||||
* Decide whether an error/warn line should be emitted, and with what suffix.
|
||||
* @private
|
||||
* @param {string} level - Log level ("error" | "warn").
|
||||
* @param {string} tag - Caller tag (e.g. "[Redis/Main]").
|
||||
* @param {Array<*>} args - Message arguments.
|
||||
* @returns {{emit: boolean, suffix: string}} Whether to emit, and the pulse suffix.
|
||||
*/
|
||||
function _stormGate(level, tag, args) {
|
||||
const key = level + "|" + tag + "|" + args.map(a => (typeof a === "string" ? a : String(a))).join(" ");
|
||||
const now = Date.now();
|
||||
const st = _stormGuard.get(key);
|
||||
if (st === undefined) {
|
||||
if (_stormGuard.size >= STORM_MAX_KEYS) {
|
||||
// Evict the oldest key to bound memory.
|
||||
_stormGuard.delete(_stormGuard.keys().next().value);
|
||||
}
|
||||
_stormGuard.set(key, { n: 0, start: now });
|
||||
return { emit: true, suffix: "" };
|
||||
}
|
||||
st.n++;
|
||||
if (now - st.start >= STORM_WINDOW_MS) {
|
||||
const n = st.n;
|
||||
st.n = 0;
|
||||
st.start = now;
|
||||
return { emit: true, suffix: `── identical line suppressed ${n}x in the last 60s` };
|
||||
}
|
||||
return { emit: false, suffix: "" };
|
||||
}
|
||||
|
||||
/**
|
||||
* Reset the log-storm suppression state (used by tests).
|
||||
* @returns {void}
|
||||
*/
|
||||
export function _resetStormGuard() {
|
||||
_stormGuard.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Structured logger exposing category-gated log methods.
|
||||
* @namespace logger
|
||||
*/
|
||||
export const logger = {
|
||||
/**
|
||||
* Log an error message (always emitted regardless of config).
|
||||
* @param {string} tag - A tag identifying the source (e.g. "[Player]").
|
||||
* @param {...*} args - Additional values to log.
|
||||
*/
|
||||
error(tag, ...args) {
|
||||
const g = _stormGate("error", tag, args);
|
||||
if (!g.emit) return;
|
||||
console.error(`[${ts()}] ${tag}`, ...args, ...(g.suffix ? [g.suffix] : []));
|
||||
},
|
||||
/**
|
||||
* Log a warning message. Honours `logging.warn` override when logging is disabled.
|
||||
* @param {string} tag - A tag identifying the source.
|
||||
* @param {...*} args - Additional values to log.
|
||||
*/
|
||||
warn(tag, ...args) {
|
||||
if (_config?.enabled === false && _config?.warn !== true) return;
|
||||
const g = _stormGate("warn", tag, args);
|
||||
if (!g.emit) return;
|
||||
console.warn(`[${ts()}] ${tag}`, ...args, ...(g.suffix ? [g.suffix] : []));
|
||||
},
|
||||
/**
|
||||
* Log an info message. Suppressed when `logging.enabled === false`.
|
||||
* @param {string} tag - A tag identifying the source.
|
||||
* @param {...*} args - Additional values to log.
|
||||
*/
|
||||
info(tag, ...args) {
|
||||
if (_config?.enabled === false) return;
|
||||
console.log(`[${ts()}] ${tag}`, ...args);
|
||||
},
|
||||
|
||||
/**
|
||||
* Category-gated player log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
player(...args) { if (isEnabled("player")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated inactivity log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
inactivity(...args) { if (isEnabled("inactivity")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated voice 24/7 log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
voice247(...args) { if (isEnabled("voice247")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated voice-state log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
voiceState(...args) { if (isEnabled("voiceState")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated media-player log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
mediaplayer(...args) { if (isEnabled("mediaplayer")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated commands log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
commands(...args) { if (isEnabled("commands")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated guild log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
guild(...args) { if (isEnabled("guild")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated recovery log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
recovery(...args) { if (isEnabled("recovery")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated settings log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
settings(...args) { if (isEnabled("settings")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated lavalink log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
lavalink(...args) { if (isEnabled("lavalink")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated alone-check log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
aloneCheck(...args) { if (isEnabled("aloneCheck")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated voice log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
voice(...args) { if (isEnabled("voice")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated dashboard log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
dashboard(...args) { if (isEnabled("dashboard")) console.log(`[${ts()}]`, ...args); },
|
||||
/**
|
||||
* Category-gated redis log.
|
||||
* @param {...*} args
|
||||
*/
|
||||
redis(...args) { if (isEnabled("redis")) console.log(`[${ts()}]`, ...args); },
|
||||
};
|
||||
+34
-634
@@ -2,29 +2,41 @@
|
||||
* @module dashboard/Dashboard
|
||||
* @description Web dashboard backend controller. Manages Redis pub/sub communication
|
||||
* with the dashboard frontend, handles remote function calls (join, play, pause, etc.),
|
||||
* and provides static data-conversion helpers for Discord entities.
|
||||
* and provides static data-conversion helpers for bot entities.
|
||||
*
|
||||
* Base class of the dashboard split: class fields, construction (including the
|
||||
* Redis request-routing switch), the Redis/MySQL lifecycle, setBotId and the
|
||||
* player/user update broadcasts. The remote RPC handler methods (runFunction,
|
||||
* confirmLogin, authorization helpers) live in RpcHandlersMixin.mjs and the static
|
||||
* conversion helpers in Serializers.mjs — both are attached at the bottom of this file.
|
||||
*/
|
||||
|
||||
import { CommandBuilder, CommandHandler, Option } from "../CommandHandler.mjs";
|
||||
import { CommandBuilder, CommandHandler, Option } from "../commands/index.mjs";
|
||||
import { PermissionFlags } from "@fluxerjs/core";
|
||||
import Player from "../Player.mjs";
|
||||
import { Utils, cleanId } from "../Utils.mjs";
|
||||
import { DatabaseManager } from "./DatabaseManager.mjs";
|
||||
import Player from "../music/player/index.mjs";
|
||||
import { Utils, cleanId } from "../utils/Utils.mjs";
|
||||
import { DatabaseManager } from "../db/DatabaseManager.mjs";
|
||||
import { RedisHandler } from "./RedisHandler.mjs";
|
||||
import { logger } from "../constants/Logger.mjs";
|
||||
import { iterateVoiceStates } from "../constants/VoiceStateResolver.mjs";
|
||||
import { logger } from "../core/Logger.mjs";
|
||||
import { iterateVoiceStates } from "../voice/VoiceStateResolver.mjs";
|
||||
import { applyMixins } from "../utils/mixins.mjs";
|
||||
import RpcHandlersMixin from "./RpcHandlersMixin.mjs";
|
||||
import Serializers from "./Serializers.mjs";
|
||||
|
||||
/**
|
||||
* @class
|
||||
* @description Orchestrates the web dashboard: wires up Redis request/response handling,
|
||||
* converts Discord data for the frontend, and exposes remote control functions.
|
||||
* converts bot data for the frontend, and exposes remote control functions.
|
||||
*/
|
||||
export class Dashboard {
|
||||
class Dashboard {
|
||||
/** @type {boolean} Whether the dashboard is enabled. */
|
||||
enabled = false;
|
||||
/** @type {number} Login code expiry time in milliseconds (default 6 hours). */
|
||||
expiryTime = 1000 * 60 * 60 * 6;
|
||||
|
||||
/** @private */
|
||||
_playerUpdateTimers = new Map();
|
||||
|
||||
/**
|
||||
* Create a new Dashboard instance.
|
||||
* @param {object} remix - The main bot (Remix) instance.
|
||||
@@ -134,10 +146,9 @@ export class Dashboard {
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Set the bot ID for the Redis platform prefix.
|
||||
* @param {string} botId - The bot's Discord user ID.
|
||||
* @param {string} botId - The bot's user ID.
|
||||
*/
|
||||
setBotId(botId) {
|
||||
if (!this.enabled || !this.redis) return;
|
||||
@@ -145,590 +156,6 @@ export class Dashboard {
|
||||
this.redis.readyMessage();
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Execute a remote dashboard function (e.g. join, pause, volume).
|
||||
* @async
|
||||
* @param {object} params - Function call parameters.
|
||||
* @param {string} params.func - The function name to execute.
|
||||
* @param {object} [params.data] - Additional data for the function.
|
||||
* @param {string} [params.data.user] - The Discord user ID making the request.
|
||||
* @returns {Promise<object>} Result object with `message` or `error`.
|
||||
*/
|
||||
async runFunction(params) {
|
||||
let user;
|
||||
if (params.data?.user) {
|
||||
try {
|
||||
user = await this.remix.client.users.fetch(params.data.user);
|
||||
} catch (e) {
|
||||
logger.dashboard("[Dashboard] Error:", e);
|
||||
return { error: "Invalid User" };
|
||||
}
|
||||
}
|
||||
switch (params.func) {
|
||||
case "join": {
|
||||
if (!user) return { error: "Invalid user" };
|
||||
let voiceChannel, textChannel;
|
||||
try {
|
||||
const chMgr = this.remix.client.channels;
|
||||
if (typeof chMgr.fetch === "function") {
|
||||
voiceChannel = await chMgr.fetch(params.data.channel).catch(() => null);
|
||||
if (params.data.text) textChannel = await chMgr.fetch(params.data.text).catch(() => null);
|
||||
} else {
|
||||
voiceChannel = chMgr.get(params.data.channel);
|
||||
if (params.data.text) textChannel = chMgr.get(params.data.text);
|
||||
}
|
||||
if (!voiceChannel) return { error: "Voice channel not found" };
|
||||
|
||||
const isText = (ch) => ch && (ch.type === 0 || ch.type === 5 || ch.type === 13 ||
|
||||
(typeof ch.isText === "function" && ch.isText()));
|
||||
|
||||
if (!isText(textChannel)) {
|
||||
const guild = this.remix.client.guilds.get(voiceChannel.guildId);
|
||||
if (guild?.channels) {
|
||||
const channelValues = typeof guild.channels.values === "function"
|
||||
? [...guild.channels.values()]
|
||||
: Array.isArray(guild.channels) ? guild.channels : Object.values(guild.channels);
|
||||
const sysCh = guild.systemChannelId
|
||||
? channelValues.find(c => (c.id ?? c._id) === guild.systemChannelId && isText(c))
|
||||
: null;
|
||||
textChannel = sysCh ?? channelValues.find(c => isText(c)) ?? null;
|
||||
}
|
||||
if (!textChannel) {
|
||||
logger.dashboard("[Dashboard] No text channel found for guild", voiceChannel.guildId, "— voice channel will be used as fallback");
|
||||
textChannel = voiceChannel;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
logger.dashboard("[Dashboard] Error:", e);
|
||||
return { error: "Invalid Channel" };
|
||||
}
|
||||
const authErr = await this._authorizeUserInGuild(user, voiceChannel.guildId);
|
||||
if (authErr) return { error: authErr };
|
||||
if (this.remix.players.playerMap.has(voiceChannel.id)) {
|
||||
const existingPlayer = this.remix.players.playerMap.get(voiceChannel.id);
|
||||
if (existingPlayer && user && !existingPlayer._dashboardUsers) {
|
||||
existingPlayer._dashboardUsers = [];
|
||||
}
|
||||
if (existingPlayer && user && !existingPlayer._dashboardUsers.includes(String(user.id))) {
|
||||
existingPlayer._dashboardUsers.push(String(user.id));
|
||||
try {
|
||||
const pubChannel = this.remix.redis?.publisher ?? this.remix.redis;
|
||||
if (pubChannel && typeof pubChannel.publish === "function") {
|
||||
pubChannel.publish("fluxer:player_" + voiceChannel.id, JSON.stringify({
|
||||
type: "join",
|
||||
data: String(user.id)
|
||||
}));
|
||||
}
|
||||
} catch (e) { logger.warn("[Dashboard] Error:", e?.message); }
|
||||
}
|
||||
return { message: "Already Connected" };
|
||||
}
|
||||
const fakeMsg = {
|
||||
channel: textChannel,
|
||||
message: { guildId: voiceChannel.guildId },
|
||||
reply: async () => ({ edit: async () => {}, catch: () => {} }),
|
||||
};
|
||||
this.remix.players.initPlayer(fakeMsg, voiceChannel.id);
|
||||
const newPlayer = this.remix.players.playerMap.get(voiceChannel.id);
|
||||
if (newPlayer && user) {
|
||||
if (!newPlayer._dashboardUsers) newPlayer._dashboardUsers = [];
|
||||
if (!newPlayer._dashboardUsers.includes(String(user.id))) {
|
||||
newPlayer._dashboardUsers.push(String(user.id));
|
||||
}
|
||||
}
|
||||
return { message: "Joining" };
|
||||
}
|
||||
|
||||
case "pausePlayback": {
|
||||
const player = this._getPlayerById(params.data.player);
|
||||
if (!player) return { error: "Player not found" };
|
||||
const authErr = this._authorizePlayerControl(user, player);
|
||||
if (authErr) return { error: authErr };
|
||||
const msg = player.pause() || "Paused successfully";
|
||||
return { message: msg };
|
||||
}
|
||||
|
||||
case "resumePlayback": {
|
||||
const player = this._getPlayerById(params.data.player);
|
||||
if (!player) return { error: "Player not found" };
|
||||
const authErr = this._authorizePlayerControl(user, player);
|
||||
if (authErr) return { error: authErr };
|
||||
const msg = player.resume() || "Resumed successfully";
|
||||
return { message: msg };
|
||||
}
|
||||
|
||||
case "skip": {
|
||||
const player = this._getPlayerById(params.data.player);
|
||||
if (!player) return { error: "Player not found" };
|
||||
const authErr = this._authorizePlayerControl(user, player);
|
||||
if (authErr) return { error: authErr };
|
||||
const msg = player.skip() || "Skipped song";
|
||||
return { message: msg };
|
||||
}
|
||||
|
||||
case "volume": {
|
||||
const player = this._getPlayerById(params.data.player);
|
||||
if (!player) return { error: "Player not found" };
|
||||
const authErr = this._authorizePlayerControl(user, player);
|
||||
if (authErr) return { error: authErr };
|
||||
const vol = Number(params.data.volume);
|
||||
if (isNaN(vol) || vol < 0 || vol > 2) return {
|
||||
error: "Volume must be between 0 and 2" };
|
||||
const msg = player.setVolume(vol);
|
||||
return { message: msg };
|
||||
}
|
||||
|
||||
case "addToQueue": {
|
||||
const player = this._getPlayerById(params.data.player);
|
||||
if (!player) return { error: "Player not found" };
|
||||
if (!user) return { error: "Invalid user" };
|
||||
const authErr = this._authorizePlayerControl(user, player);
|
||||
if (authErr) return { error: authErr };
|
||||
const type = params.data.type;
|
||||
const query = params.data.query;
|
||||
if (!query || typeof query !== "string") return { error: "Missing or invalid query" };
|
||||
if (query.length > 500) return { error: "Query too long (max 500 characters)" };
|
||||
if (type === "radio") {
|
||||
const radio = this.remix.config.radio.find(e => e.name === query);
|
||||
if (!radio) return { error: "Invalid radio station" };
|
||||
player.playRadio(radio);
|
||||
return { message: "Adding radio station" };
|
||||
}
|
||||
if (/^(javascript|data|vbscript):/i.test(query.trim())) {
|
||||
return { error: "Invalid query protocol" };
|
||||
}
|
||||
player.play(query);
|
||||
return { message: "Adding to queue" };
|
||||
}
|
||||
|
||||
case "testConnection": {
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
case "voiceState": {
|
||||
if (!user) return { channel: null };
|
||||
const userId = cleanId(user.id);
|
||||
if (this.remix.voiceCache) {
|
||||
for (const [mapUserId, info] of this.remix.voiceCache) {
|
||||
if (cleanId(mapUserId) === userId && info.channelId) {
|
||||
const ch = this.remix.client.channels.get(info.channelId);
|
||||
return {
|
||||
channelId: info.channelId,
|
||||
channel: ch ? Dashboard.convertChannel(ch) : { id: info.channelId, name: "Unknown" },
|
||||
guildId: info.guildId ?? ch?.guildId ?? null,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
const guilds = this.remix.client.guilds;
|
||||
const guildValues = guilds && typeof guilds.values === "function"
|
||||
? [...guilds.values()] : guilds ? Object.values(guilds) : [];
|
||||
for (const guild of guildValues) {
|
||||
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: vs.channelId,
|
||||
channel: ch ? Dashboard.convertChannel(ch) : { id: vs.channelId, name: "Unknown" },
|
||||
guildId: guild.id,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
return { channel: null };
|
||||
}
|
||||
|
||||
case "leave": {
|
||||
if (!user) return { error: "Invalid user" };
|
||||
const playerId = params.data.channel ?? params.data.player;
|
||||
const player = this._getPlayerById(playerId);
|
||||
if (!player) return { error: "Player not found" };
|
||||
const authErr = await this._authorizeUserInGuild(user, player._guildId);
|
||||
if (authErr) return { error: authErr };
|
||||
if (player._dashboardUsers && user) {
|
||||
const idx = player._dashboardUsers.indexOf(String(user.id));
|
||||
if (idx !== -1) player._dashboardUsers.splice(idx, 1);
|
||||
}
|
||||
if (player._dashboardUsers && player._dashboardUsers.length > 0) {
|
||||
try {
|
||||
const pubChannel = this.remix.dashboard?.redis?.client ?? this.remix.redis?.client;
|
||||
if (pubChannel && typeof pubChannel.publish === "function") {
|
||||
pubChannel.publish("fluxer:player_" + playerId, JSON.stringify({
|
||||
type: "leave",
|
||||
data: String(user.id)
|
||||
}));
|
||||
}
|
||||
} catch (e) { logger.warn("[Dashboard] Error:", e?.message); }
|
||||
return { message: "Left channel" };
|
||||
}
|
||||
try {
|
||||
await player.leave();
|
||||
return { message: "Left channel" };
|
||||
} catch (e) {
|
||||
return { error: "Failed to leave: " + e.message };
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
return { error: "Unknown function: " + (params.func ?? "(none)") };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Verify that the given user is allowed to control the given player.
|
||||
* Bot owners bypass the check; otherwise the user must be in the same voice channel.
|
||||
* @private
|
||||
* @param {object} user - The Discord user attempting to control the player.
|
||||
* @param {object} player - The Player instance to control.
|
||||
* @returns {string|null} An error message if unauthorized, or null if authorized.
|
||||
*/
|
||||
_authorizePlayerControl(user, player) {
|
||||
if (user && this.remix.handler?.owners?.includes?.(user.id)) return null;
|
||||
if (!user) return "User not provided";
|
||||
|
||||
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 = cleanId(player._guildId);
|
||||
const userLoc = observed.get(cleanUserId, guildId || undefined);
|
||||
if (userLoc) {
|
||||
const infoChannelId = cleanId(userLoc.channelId);
|
||||
if (infoChannelId === cleanChanId) return null;
|
||||
}
|
||||
for (const [mapUserId, info] of observed) {
|
||||
if (cleanId(mapUserId) === cleanUserId) {
|
||||
const infoChannelId = cleanId(info.channelId);
|
||||
if (infoChannelId === cleanChanId) return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return "You must be in the same voice channel as the bot to control playback";
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify that the given user is a member of the specified guild.
|
||||
* Bot owners bypass the check.
|
||||
* @private
|
||||
* @async
|
||||
* @param {object} user - The Discord user to verify.
|
||||
* @param {string} guildId - The guild ID to check membership in.
|
||||
* @returns {Promise<string|null>} An error message if not a member, or null if authorized.
|
||||
*/
|
||||
async _authorizeUserInGuild(user, guildId) {
|
||||
if (this.remix.handler?.owners?.includes?.(user.id)) return null;
|
||||
|
||||
try {
|
||||
const guild = this.remix.client.guilds.get(guildId);
|
||||
if (!guild) return "Server not found";
|
||||
const member = await guild.members.fetch(user.id).catch(() => null);
|
||||
if (!member) return "You are not a member of this server";
|
||||
return null;
|
||||
} catch (e) {
|
||||
return "Failed to verify membership: " + e.message;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up a player by channel ID, guild ID, or player ID.
|
||||
* @private
|
||||
* @param {string} id - Channel ID, guild ID, or player ID.
|
||||
* @returns {object|null} The matching Player instance, or null.
|
||||
*/
|
||||
_getPlayerById(id) {
|
||||
return this.remix.players.playerMap.get(id)
|
||||
?? [...this.remix.players.playerMap.values()].find(
|
||||
p => p._channelId === id || p._guildId === id
|
||||
)
|
||||
?? null;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Convert a Discord user object to a dashboard-safe plain object.
|
||||
* @static
|
||||
* @param {object} user - The Discord user.
|
||||
* @returns {{ id: string, username: string, displayName: string, avatar: { url: string } }}
|
||||
*/
|
||||
static convertUser(user) {
|
||||
let avatarUrl = "";
|
||||
if (user.avatar) {
|
||||
avatarUrl = `https://fluxerusercontent.com/avatars/${user.id}/${user.avatar}.webp`;
|
||||
} else if (typeof user.displayAvatarURL === "function") {
|
||||
try { avatarUrl = user.displayAvatarURL() ?? ""; } catch(e) { logger.warn("[Dashboard] displayAvatarURL:", e?.message); }
|
||||
} else if (typeof user.avatarURL === "function") {
|
||||
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`;
|
||||
}
|
||||
return {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
displayName: user.displayName ?? user.globalName ?? user.username,
|
||||
avatar: {
|
||||
url: avatarUrl,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a video/track object to a dashboard-safe plain object.
|
||||
* @static
|
||||
* @param {object} vid - The video/track object from the player queue.
|
||||
* @returns {object|null} Sanitised video data, or null if input is falsy.
|
||||
*/
|
||||
static convertVideo(vid) {
|
||||
if (!vid) return null;
|
||||
const durationMs =
|
||||
typeof vid.duration === "number" ? vid.duration :
|
||||
typeof vid.duration === "object" && vid.duration?.seconds !== null ? vid.duration.seconds * 1000 :
|
||||
0;
|
||||
return {
|
||||
title: vid.title,
|
||||
url: vid.type === "radio" ? vid.author?.url : vid.url,
|
||||
videoId: vid.videoId,
|
||||
type: vid.type,
|
||||
duration: vid.type === "radio" ? "--:--" : Utils.prettifyMS(durationMs),
|
||||
description: vid.description,
|
||||
artist: {
|
||||
name: vid.author?.name ?? vid.artist,
|
||||
url: vid.author?.url,
|
||||
},
|
||||
thumbnail: vid.thumbnail,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a Discord channel to a dashboard-safe plain object, including
|
||||
* voice participant info for voice channels.
|
||||
* @static
|
||||
* @param {object} channel - The Discord channel.
|
||||
* @returns {object} Sanitised channel data.
|
||||
*/
|
||||
static convertChannel(channel) {
|
||||
const type = channel.type ?? 0;
|
||||
const isVoice = channel.isVoice?.() || type === 2;
|
||||
const isCategory = type === 4;
|
||||
const isText = !isVoice && !isCategory && (
|
||||
type === 0 || type === 5 || type === 13 ||
|
||||
(typeof channel.isText === "function" && channel.isText())
|
||||
);
|
||||
let voiceParticipants = [];
|
||||
if (isVoice) {
|
||||
const guild = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId);
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
name: channel.name,
|
||||
displayName: channel.name,
|
||||
id: channel.id,
|
||||
icon: null,
|
||||
description: channel.topic ?? null,
|
||||
type,
|
||||
isVoice,
|
||||
isCategory,
|
||||
isText,
|
||||
parentId: channel.parentId ?? channel.parent_id ?? null,
|
||||
voiceParticipants,
|
||||
mature: channel.nsfw ?? false,
|
||||
serverId: channel.guildId,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a Discord guild (server) to a dashboard-safe plain object with channels.
|
||||
* @static
|
||||
* @param {object} guild - The Discord guild.
|
||||
* @returns {object} Sanitised server data including channels and voice channels.
|
||||
*/
|
||||
static convertServer(guild) {
|
||||
const channelStore = guild.channels;
|
||||
const channelIds = channelStore && typeof channelStore.keys === "function"
|
||||
? [...channelStore.keys()]
|
||||
: [];
|
||||
const channelValues = channelStore && typeof channelStore.values === "function"
|
||||
? [...channelStore.values()]
|
||||
: [];
|
||||
const allChannels = channelValues
|
||||
.map(Dashboard.convertChannel)
|
||||
.filter(c => !c.isCategory);
|
||||
|
||||
let iconUrl = null;
|
||||
if (guild.icon) {
|
||||
iconUrl = `https://fluxerusercontent.com/icons/${guild.id}/${guild.icon}.webp`;
|
||||
} else if (typeof guild.iconURL === "function") {
|
||||
try { iconUrl = guild.iconURL() ?? null; } catch (e) { logger.warn("[Dashboard] iconURL error:", e?.message); iconUrl = null; }
|
||||
}
|
||||
|
||||
return {
|
||||
name: guild.name,
|
||||
id: guild.id,
|
||||
icon: iconUrl,
|
||||
channelIds,
|
||||
description: guild.description ?? null,
|
||||
ownerId: guild.ownerId,
|
||||
channels: allChannels,
|
||||
voiceChannels: allChannels.filter(c => c.isVoice),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a Discord guild to a lightweight summary object (no channels).
|
||||
* @static
|
||||
* @param {object} guild - The Discord guild.
|
||||
* @returns {{ name: string, id: string, icon: string|null, description: string|null, ownerId: string|null }}
|
||||
*/
|
||||
static convertServerSummary(guild) {
|
||||
let iconUrl = null;
|
||||
if (guild.icon) {
|
||||
iconUrl = `https://fluxerusercontent.com/icons/${guild.id}/${guild.icon}.webp`;
|
||||
} else if (typeof guild.iconURL === "function") {
|
||||
try { iconUrl = guild.iconURL() ?? null; } catch (e) { logger.warn("[Dashboard] iconURL error:", e?.message); iconUrl = null; }
|
||||
}
|
||||
return {
|
||||
name: guild.name,
|
||||
id: guild.id,
|
||||
icon: iconUrl,
|
||||
description: guild.description ?? null,
|
||||
ownerId: guild.ownerId,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a Player instance to a dashboard-safe serialisable object.
|
||||
* Includes queue, users, channel, and server info.
|
||||
* @static
|
||||
* @param {object} player - The Player instance.
|
||||
* @returns {object} Sanitised player data.
|
||||
*/
|
||||
static convertPlayer(player) {
|
||||
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 ? cleanId(channelId) : "";
|
||||
const cleanGuildId = player._guildId ? cleanId(player._guildId) : "";
|
||||
|
||||
const queue = player.queue ?? { loop: false, songLoop: false, current: null, data: [] };
|
||||
|
||||
return {
|
||||
loop: (queue.loop ? 1 : 0) + (queue.songLoop ? 2 : 0),
|
||||
paused: !!player._paused,
|
||||
volume: Number.isFinite(player.preferredVolume) ? player.preferredVolume * 100 : 100,
|
||||
queue: {
|
||||
current: Dashboard.convertVideo(queue.current),
|
||||
data: Array.isArray(queue.data) ? queue.data.slice(0, 500).map(v => Dashboard.convertVideo(v)) : [],
|
||||
},
|
||||
users: (() => {
|
||||
if (!channel) return player._dashboardUsers ?? [];
|
||||
const g = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId);
|
||||
const ids = [];
|
||||
const seen = new Set();
|
||||
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;
|
||||
if (vc && cleanChannelId && cleanGuildId) {
|
||||
if (typeof vc.getHumansInChannel === "function") {
|
||||
const channelHumans = vc.getHumansInChannel(cleanGuildId, cleanChannelId);
|
||||
for (const hid of channelHumans) {
|
||||
if (seen.has(hid)) continue;
|
||||
const botId = player.client?.user?.id;
|
||||
if (botId && String(hid) === String(botId)) continue;
|
||||
ids.push(String(hid));
|
||||
seen.add(hid);
|
||||
}
|
||||
} else {
|
||||
for (const [mapUserId, info] of vc) {
|
||||
if (seen.has(mapUserId)) continue;
|
||||
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;
|
||||
ids.push(String(mapUserId));
|
||||
seen.add(mapUserId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (player._dashboardUsers) {
|
||||
for (const du of player._dashboardUsers) {
|
||||
if (!seen.has(du)) { ids.push(du); seen.add(du); }
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
})(),
|
||||
channel: channel ? Dashboard.convertChannel(channel) : null,
|
||||
server: guild ? Dashboard.convertServerSummary(guild) : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a command option to a dashboard-safe plain object.
|
||||
* @static
|
||||
* @param {object} opt - The command option.
|
||||
* @returns {object} Sanitised option data.
|
||||
*/
|
||||
static convertOption(opt) {
|
||||
return {
|
||||
type: opt.type,
|
||||
name: opt.name,
|
||||
choices: opt.choices,
|
||||
description: opt.description,
|
||||
required: opt.required,
|
||||
uid: opt.uid,
|
||||
defaultValue: opt.defaultValue,
|
||||
dynamicDefaultPresent: !!opt.dynamicDefault,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a command (and its subcommands/options) to a dashboard-safe plain object.
|
||||
* @static
|
||||
* @param {object} com - The command object.
|
||||
* @param {object} commands - The CommandHandler instance (for usage generation).
|
||||
* @returns {object} Sanitised command data.
|
||||
*/
|
||||
static convertCommand(com, commands) {
|
||||
return {
|
||||
name: com.name,
|
||||
description: com.description,
|
||||
uid: com.uid,
|
||||
aliases: com.aliases,
|
||||
subcommands: com.subcommands.map(c => Dashboard.convertCommand(c, commands)),
|
||||
category: com.category,
|
||||
examples: com.examples,
|
||||
usage: commands.helpHandler?.commandUsage?.(com, {
|
||||
message: { guildId: null },
|
||||
}) ?? null,
|
||||
options: com.options.map(o => Dashboard.convertOption(o)),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
/** @private */
|
||||
_playerUpdateTimers = new Map();
|
||||
|
||||
/**
|
||||
* Broadcast a player state update to the dashboard via Redis.
|
||||
* Debounces non-init/close updates by 500ms.
|
||||
@@ -784,7 +211,7 @@ export class Dashboard {
|
||||
/**
|
||||
* Broadcast a user update to the global users Redis channel.
|
||||
* @param {object} details - The update payload.
|
||||
* @param {object} user - The Discord user.
|
||||
* @param {object} user - The user.
|
||||
*/
|
||||
userUpdate(details, user) {
|
||||
if (!this.enabled) return;
|
||||
@@ -798,48 +225,21 @@ export class Dashboard {
|
||||
/**
|
||||
* Send a lightweight update to the user-specific Redis channel.
|
||||
* @param {object} details - The update payload.
|
||||
* @param {object} user - The Discord user.
|
||||
* @param {object} user - The user.
|
||||
*/
|
||||
updateUser(details, user) {
|
||||
if (!this.enabled) return;
|
||||
const channel = this.redis.platform + ":user_" + user.id;
|
||||
this.redis.send(channel, JSON.stringify(details));
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Verify a dashboard login code for a user.
|
||||
* @async
|
||||
* @param {string} user - The Discord user ID.
|
||||
* @param {string} code - The login code to verify.
|
||||
* @returns {Promise<string|null>} An error message if verification fails, or null on success.
|
||||
*/
|
||||
async confirmLogin(user, code) {
|
||||
if (!this.enabled) return "Dashboard not enabled.";
|
||||
if (!this.db) return "Dashboard database not configured.";
|
||||
|
||||
let res;
|
||||
try {
|
||||
res = await this.db.execute("SELECT * FROM login_codes WHERE user=? AND (verified IS NULL OR verified !== true)", [user]);
|
||||
} catch (e) {
|
||||
const id = Utils.uid();
|
||||
logger.dashboard("[Dashboard] MySQL error, id:", id, e);
|
||||
return "An error occurred, please contact an administrator if this happens again. Error id: `" + id + "`";
|
||||
}
|
||||
|
||||
if (res.length === 0) return "If this is a valid code, it was not created for your account.";
|
||||
|
||||
for (let i = 0; i < res.length; i++) {
|
||||
if (res[i].verified) continue;
|
||||
if (await this.db.compareHash(code, res[i].token)) {
|
||||
if (Date.now() - this.expiryTime > (new Date(res[i].createdAt)).getTime()) {
|
||||
return "Login token expired";
|
||||
}
|
||||
await this.db.execute("UPDATE login_codes SET verified=true WHERE id=?", [res[i].id]);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return "Invalid code.";
|
||||
}
|
||||
}
|
||||
|
||||
// Attach the split-out concerns: the remote RPC handler methods (runFunction,
|
||||
// confirmLogin and the authorization helpers) from RpcHandlersMixin.
|
||||
applyMixins(Dashboard, RpcHandlersMixin);
|
||||
|
||||
// Re-attach the static conversion helpers (convertUser, convertChannel,
|
||||
// convertPlayer, …) so external `Dashboard.convertX(...)` call sites keep working.
|
||||
Object.assign(Dashboard, Serializers);
|
||||
|
||||
export { Dashboard };
|
||||
@@ -6,20 +6,23 @@
|
||||
*/
|
||||
|
||||
import { createClient } from "redis";
|
||||
import { logger } from "../constants/Logger.mjs";
|
||||
import { logger } from "../core/Logger.mjs";
|
||||
|
||||
/**
|
||||
* Default reconnection strategy for Redis sockets.
|
||||
* @param {object} options - Reconnection options from the Redis client.
|
||||
* @param {number} options.totalRetryTime - Cumulative retry time so far.
|
||||
* @param {number} options.attempt - Current retry attempt number.
|
||||
* @returns {number|Error} Delay in ms before next retry, or an Error to stop retrying.
|
||||
* redis@5 calls the strategy as `strategy(retries, cause)` where `retries` is a
|
||||
* plain NUMBER of reconnect attempts made so far — NOT an options object.
|
||||
* The previous version read cumulative-time / attempt-count properties off
|
||||
* that number, which produced NaN; NaN passes redis@5's `typeof !== "number"`
|
||||
* gate and collapses `setTimeout(NaN)` to a ~1ms hot-retry loop (log storm).
|
||||
* Strategy now: linear ramp 0.5s -> 5s, then a steady 15s retry pulse. It
|
||||
* never exhausts, so the dashboard auto-recovers whenever Redis returns.
|
||||
* @param {number} retries - Reconnect attempts made so far (redis@5 argument).
|
||||
* @returns {number} Delay in ms before the next reconnect attempt.
|
||||
*/
|
||||
const DEFAULT_RETRY_STRATEGY = (options) => {
|
||||
if (options.totalRetryTime > 60_000) {
|
||||
return new Error("Redis reconnection exhausted after 60s");
|
||||
}
|
||||
return Math.min(options.attempt * 500, 5_000);
|
||||
const DEFAULT_RETRY_STRATEGY = (retries) => {
|
||||
if (!Number.isFinite(retries)) return 15_000; // defensive: wrong-shape argument
|
||||
return retries < 10 ? Math.min(retries * 500, 5_000) : 15_000;
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -46,12 +49,12 @@ export class RedisHandler {
|
||||
constructor(opts = {}) {
|
||||
this.platform = opts.platform ?? "fluxer";
|
||||
|
||||
const clientOpts = {
|
||||
...opts,
|
||||
socket: {
|
||||
...(opts.socket ?? {}),
|
||||
reconnectStrategy: DEFAULT_RETRY_STRATEGY,
|
||||
},
|
||||
// `url` (and any explicit socket options) come from config; the retry
|
||||
// strategy is always pinned so misconfig can never cause a hot retry loop.
|
||||
const { platform: _platform, ...clientOpts } = { ...opts };
|
||||
clientOpts.socket = {
|
||||
...(clientOpts.socket ?? {}),
|
||||
reconnectStrategy: DEFAULT_RETRY_STRATEGY,
|
||||
};
|
||||
|
||||
this.client = createClient(clientOpts);
|
||||
@@ -74,51 +77,58 @@ export class RedisHandler {
|
||||
* @async
|
||||
*/
|
||||
async _connect() {
|
||||
try {
|
||||
await this.client.connect();
|
||||
logger.redis("[Redis/Main] Connected");
|
||||
this.readyMessage();
|
||||
} catch (e) {
|
||||
logger.error("[Redis/Main] Initial connection failed:", e.message);
|
||||
}
|
||||
|
||||
try {
|
||||
await this.subscriber.connect();
|
||||
logger.redis("[Redis/Subscriber] Connected");
|
||||
|
||||
this.subscriber.subscribe("request", async (m) => {
|
||||
// Connect both clients CONCURRENTLY. The previous sequential awaits made
|
||||
// the subscriber wait behind the main client's retry loop: while Redis was
|
||||
// down, the subscriber never even attempted to connect.
|
||||
this.client.connect()
|
||||
.then(() => {
|
||||
if (this._destroyed) return;
|
||||
try {
|
||||
const payload = JSON.parse(m);
|
||||
if (payload.platform !== this.platform) return;
|
||||
if (typeof this.handleRequest !== "function") return;
|
||||
const result = await this.handleRequest(payload.content);
|
||||
this.send("response", JSON.stringify({
|
||||
id: payload.id,
|
||||
content: result,
|
||||
}));
|
||||
} catch (e) {
|
||||
logger.error("[Redis/Subscriber] Request handler error:", e.message);
|
||||
}
|
||||
logger.redis("[Redis/Main] Connected");
|
||||
this.readyMessage();
|
||||
})
|
||||
.catch((e) => {
|
||||
logger.error("[Redis/Main] Initial connection failed:", e.message);
|
||||
});
|
||||
|
||||
this.subscriber.subscribe("info", (m) => {
|
||||
this.subscriber.connect()
|
||||
.then(() => {
|
||||
if (this._destroyed) return;
|
||||
try {
|
||||
const data = JSON.parse(m);
|
||||
if (data.platform !== "backend") return;
|
||||
if (data.type !== "requestConnected") return;
|
||||
this.readyMessage();
|
||||
} catch (e) {
|
||||
logger.warn("[Redis/Subscriber] Info handler error:", e.message);
|
||||
}
|
||||
logger.redis("[Redis/Subscriber] Connected");
|
||||
|
||||
this.subscriber.subscribe("request", async (m) => {
|
||||
if (this._destroyed) return;
|
||||
try {
|
||||
const payload = JSON.parse(m);
|
||||
if (payload.platform !== this.platform) return;
|
||||
if (typeof this.handleRequest !== "function") return;
|
||||
const result = await this.handleRequest(payload.content);
|
||||
this.send("response", JSON.stringify({
|
||||
id: payload.id,
|
||||
content: result,
|
||||
}));
|
||||
} catch (e) {
|
||||
logger.error("[Redis/Subscriber] Request handler error:", e.message);
|
||||
}
|
||||
});
|
||||
|
||||
this.subscriber.subscribe("info", (m) => {
|
||||
if (this._destroyed) return;
|
||||
try {
|
||||
const data = JSON.parse(m);
|
||||
if (data.platform !== "backend") return;
|
||||
if (data.type !== "requestConnected") return;
|
||||
this.readyMessage();
|
||||
} catch (e) {
|
||||
logger.warn("[Redis/Subscriber] Info handler error:", e.message);
|
||||
}
|
||||
});
|
||||
this._pingInterval = setInterval(() => {
|
||||
this.send(this.platform + ":ping", "" + Date.now());
|
||||
}, 10000);
|
||||
})
|
||||
.catch((e) => {
|
||||
logger.error("[Redis/Subscriber] Initial connection failed:", e.message);
|
||||
});
|
||||
this._pingInterval = setInterval(() => {
|
||||
this.send(this.platform + ":ping", "" + Date.now());
|
||||
}, 10000);
|
||||
} catch (e) {
|
||||
logger.error("[Redis/Subscriber] Initial connection failed:", e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -173,8 +183,16 @@ 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(e) { logger.warn("[Redis/Subscriber] Quit error:", e?.message); }
|
||||
try { await this.client?.quit(); } catch(e) { logger.warn("[Redis/Main] Quit error:", e?.message); }
|
||||
// quit() waits for a live connection; on a still-connecting/down client it
|
||||
// would pend forever (bot shutdown hang). Hard-disconnect instead.
|
||||
try {
|
||||
if (this.subscriber?.isReady) await this.subscriber.quit();
|
||||
else this.subscriber?.disconnect();
|
||||
} catch(e) { logger.warn("[Redis/Subscriber] Quit error:", e?.message); }
|
||||
try {
|
||||
if (this.client?.isReady) await this.client.quit();
|
||||
else this.client?.disconnect();
|
||||
} catch(e) { logger.warn("[Redis/Main] Quit error:", e?.message); }
|
||||
logger.redis("[Redis] Connections closed gracefully");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,362 @@
|
||||
/**
|
||||
* @module dashboard/RpcHandlersMixin
|
||||
* @description Remote-control concern for {@link Dashboard}: the dashboard RPC
|
||||
* "function" dispatch (runFunction — join / pausePlayback / resumePlayback / skip /
|
||||
* volume / addToQueue / testConnection / voiceState / leave), the login-code
|
||||
* verification (confirmLogin) and the authorization / player-lookup helpers.
|
||||
*
|
||||
* These methods are applied onto the Dashboard class prototype via
|
||||
* {@link applyMixins} — `this` is a Dashboard instance.
|
||||
*/
|
||||
|
||||
import { Dashboard } from "./Dashboard.mjs";
|
||||
import { Utils, cleanId } from "../utils/Utils.mjs";
|
||||
import { logger } from "../core/Logger.mjs";
|
||||
import { iterateVoiceStates } from "../voice/VoiceStateResolver.mjs";
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
* @description RPC handlers mixin — applied to Dashboard.
|
||||
*/
|
||||
const RpcHandlersMixin = {
|
||||
/**
|
||||
* Execute a remote dashboard function (e.g. join, pause, volume).
|
||||
* @async
|
||||
* @param {object} params - Function call parameters.
|
||||
* @param {string} params.func - The function name to execute.
|
||||
* @param {object} [params.data] - Additional data for the function.
|
||||
* @param {string} [params.data.user] - The user ID making the request.
|
||||
* @returns {Promise<object>} Result object with `message` or `error`.
|
||||
*/
|
||||
async runFunction(params) {
|
||||
let user;
|
||||
if (params.data?.user) {
|
||||
try {
|
||||
user = await this.remix.client.users.fetch(params.data.user);
|
||||
} catch (e) {
|
||||
logger.dashboard("[Dashboard] Error:", e);
|
||||
return { error: "Invalid User" };
|
||||
}
|
||||
}
|
||||
switch (params.func) {
|
||||
case "join": {
|
||||
if (!user) return { error: "Invalid user" };
|
||||
let voiceChannel, textChannel;
|
||||
try {
|
||||
const chMgr = this.remix.client.channels;
|
||||
if (typeof chMgr.fetch === "function") {
|
||||
voiceChannel = await chMgr.fetch(params.data.channel).catch(() => null);
|
||||
if (params.data.text) textChannel = await chMgr.fetch(params.data.text).catch(() => null);
|
||||
} else {
|
||||
voiceChannel = chMgr.get(params.data.channel);
|
||||
if (params.data.text) textChannel = chMgr.get(params.data.text);
|
||||
}
|
||||
if (!voiceChannel) return { error: "Voice channel not found" };
|
||||
|
||||
const isText = (ch) => ch && (ch.type === 0 || ch.type === 5 || ch.type === 13 ||
|
||||
(typeof ch.isText === "function" && ch.isText()));
|
||||
|
||||
if (!isText(textChannel)) {
|
||||
const guild = this.remix.client.guilds.get(voiceChannel.guildId);
|
||||
if (guild?.channels) {
|
||||
const channelValues = typeof guild.channels.values === "function"
|
||||
? [...guild.channels.values()]
|
||||
: Array.isArray(guild.channels) ? guild.channels : Object.values(guild.channels);
|
||||
const sysCh = guild.systemChannelId
|
||||
? channelValues.find(c => (c.id ?? c._id) === guild.systemChannelId && isText(c))
|
||||
: null;
|
||||
textChannel = sysCh ?? channelValues.find(c => isText(c)) ?? null;
|
||||
}
|
||||
if (!textChannel) {
|
||||
logger.dashboard("[Dashboard] No text channel found for guild", voiceChannel.guildId, "— voice channel will be used as fallback");
|
||||
textChannel = voiceChannel;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
logger.dashboard("[Dashboard] Error:", e);
|
||||
return { error: "Invalid Channel" };
|
||||
}
|
||||
const authErr = await this._authorizeUserInGuild(user, voiceChannel.guildId);
|
||||
if (authErr) return { error: authErr };
|
||||
if (this.remix.players.playerMap.has(voiceChannel.id)) {
|
||||
const existingPlayer = this.remix.players.playerMap.get(voiceChannel.id);
|
||||
if (existingPlayer && user && !existingPlayer._dashboardUsers) {
|
||||
existingPlayer._dashboardUsers = [];
|
||||
}
|
||||
if (existingPlayer && user && !existingPlayer._dashboardUsers.includes(String(user.id))) {
|
||||
existingPlayer._dashboardUsers.push(String(user.id));
|
||||
try {
|
||||
const pubChannel = this.remix.redis?.publisher ?? this.remix.redis;
|
||||
if (pubChannel && typeof pubChannel.publish === "function") {
|
||||
pubChannel.publish("fluxer:player_" + voiceChannel.id, JSON.stringify({
|
||||
type: "join",
|
||||
data: String(user.id)
|
||||
}));
|
||||
}
|
||||
} catch (e) { logger.warn("[Dashboard] Error:", e?.message); }
|
||||
}
|
||||
return { message: "Already Connected" };
|
||||
}
|
||||
const fakeMsg = {
|
||||
channel: textChannel,
|
||||
message: { guildId: voiceChannel.guildId },
|
||||
reply: async () => ({ edit: async () => {}, catch: () => {} }),
|
||||
};
|
||||
this.remix.players.initPlayer(fakeMsg, voiceChannel.id);
|
||||
const newPlayer = this.remix.players.playerMap.get(voiceChannel.id);
|
||||
if (newPlayer && user) {
|
||||
if (!newPlayer._dashboardUsers) newPlayer._dashboardUsers = [];
|
||||
if (!newPlayer._dashboardUsers.includes(String(user.id))) {
|
||||
newPlayer._dashboardUsers.push(String(user.id));
|
||||
}
|
||||
}
|
||||
return { message: "Joining" };
|
||||
}
|
||||
|
||||
case "pausePlayback": {
|
||||
const player = this._getPlayerById(params.data.player);
|
||||
if (!player) return { error: "Player not found" };
|
||||
const authErr = this._authorizePlayerControl(user, player);
|
||||
if (authErr) return { error: authErr };
|
||||
const msg = player.pause() || "Paused successfully";
|
||||
return { message: msg };
|
||||
}
|
||||
|
||||
case "resumePlayback": {
|
||||
const player = this._getPlayerById(params.data.player);
|
||||
if (!player) return { error: "Player not found" };
|
||||
const authErr = this._authorizePlayerControl(user, player);
|
||||
if (authErr) return { error: authErr };
|
||||
const msg = player.resume() || "Resumed successfully";
|
||||
return { message: msg };
|
||||
}
|
||||
|
||||
case "skip": {
|
||||
const player = this._getPlayerById(params.data.player);
|
||||
if (!player) return { error: "Player not found" };
|
||||
const authErr = this._authorizePlayerControl(user, player);
|
||||
if (authErr) return { error: authErr };
|
||||
const msg = player.skip() || "Skipped song";
|
||||
return { message: msg };
|
||||
}
|
||||
|
||||
case "volume": {
|
||||
const player = this._getPlayerById(params.data.player);
|
||||
if (!player) return { error: "Player not found" };
|
||||
const authErr = this._authorizePlayerControl(user, player);
|
||||
if (authErr) return { error: authErr };
|
||||
const vol = Number(params.data.volume);
|
||||
if (isNaN(vol) || vol < 0 || vol > 2) return {
|
||||
error: "Volume must be between 0 and 2" };
|
||||
const msg = player.setVolume(vol);
|
||||
return { message: msg };
|
||||
}
|
||||
|
||||
case "addToQueue": {
|
||||
const player = this._getPlayerById(params.data.player);
|
||||
if (!player) return { error: "Player not found" };
|
||||
if (!user) return { error: "Invalid user" };
|
||||
const authErr = this._authorizePlayerControl(user, player);
|
||||
if (authErr) return { error: authErr };
|
||||
const type = params.data.type;
|
||||
const query = params.data.query;
|
||||
if (!query || typeof query !== "string") return { error: "Missing or invalid query" };
|
||||
if (query.length > 500) return { error: "Query too long (max 500 characters)" };
|
||||
if (type === "radio") {
|
||||
const radio = this.remix.config.radio.find(e => e.name === query);
|
||||
if (!radio) return { error: "Invalid radio station" };
|
||||
player.playRadio(radio);
|
||||
return { message: "Adding radio station" };
|
||||
}
|
||||
if (/^(javascript|data|vbscript):/i.test(query.trim())) {
|
||||
return { error: "Invalid query protocol" };
|
||||
}
|
||||
player.play(query);
|
||||
return { message: "Adding to queue" };
|
||||
}
|
||||
|
||||
case "testConnection": {
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
case "voiceState": {
|
||||
if (!user) return { channel: null };
|
||||
const userId = cleanId(user.id);
|
||||
if (this.remix.voiceCache) {
|
||||
for (const [mapUserId, info] of this.remix.voiceCache) {
|
||||
if (cleanId(mapUserId) === userId && info.channelId) {
|
||||
const ch = this.remix.client.channels.get(info.channelId);
|
||||
return {
|
||||
channelId: info.channelId,
|
||||
channel: ch ? Dashboard.convertChannel(ch) : { id: info.channelId, name: "Unknown" },
|
||||
guildId: info.guildId ?? ch?.guildId ?? null,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
const guilds = this.remix.client.guilds;
|
||||
const guildValues = guilds && typeof guilds.values === "function"
|
||||
? [...guilds.values()] : guilds ? Object.values(guilds) : [];
|
||||
for (const guild of guildValues) {
|
||||
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: vs.channelId,
|
||||
channel: ch ? Dashboard.convertChannel(ch) : { id: vs.channelId, name: "Unknown" },
|
||||
guildId: guild.id,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
return { channel: null };
|
||||
}
|
||||
|
||||
case "leave": {
|
||||
if (!user) return { error: "Invalid user" };
|
||||
const playerId = params.data.channel ?? params.data.player;
|
||||
const player = this._getPlayerById(playerId);
|
||||
if (!player) return { error: "Player not found" };
|
||||
const authErr = await this._authorizeUserInGuild(user, player._guildId);
|
||||
if (authErr) return { error: authErr };
|
||||
if (player._dashboardUsers && user) {
|
||||
const idx = player._dashboardUsers.indexOf(String(user.id));
|
||||
if (idx !== -1) player._dashboardUsers.splice(idx, 1);
|
||||
}
|
||||
if (player._dashboardUsers && player._dashboardUsers.length > 0) {
|
||||
try {
|
||||
const pubChannel = this.remix.dashboard?.redis?.client ?? this.remix.redis?.client;
|
||||
if (pubChannel && typeof pubChannel.publish === "function") {
|
||||
pubChannel.publish("fluxer:player_" + playerId, JSON.stringify({
|
||||
type: "leave",
|
||||
data: String(user.id)
|
||||
}));
|
||||
}
|
||||
} catch (e) { logger.warn("[Dashboard] Error:", e?.message); }
|
||||
return { message: "Left channel" };
|
||||
}
|
||||
try {
|
||||
await player.leave();
|
||||
return { message: "Left channel" };
|
||||
} catch (e) {
|
||||
return { error: "Failed to leave: " + e.message };
|
||||
}
|
||||
}
|
||||
|
||||
default:
|
||||
return { error: "Unknown function: " + (params.func ?? "(none)") };
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Verify that the given user is allowed to control the given player.
|
||||
* Bot owners bypass the check; otherwise the user must be in the same voice channel.
|
||||
* @private
|
||||
* @param {object} user - The user attempting to control the player.
|
||||
* @param {object} player - The Player instance to control.
|
||||
* @returns {string|null} An error message if unauthorized, or null if authorized.
|
||||
*/
|
||||
_authorizePlayerControl(user, player) {
|
||||
if (user && this.remix.handler?.owners?.includes?.(user.id)) return null;
|
||||
if (!user) return "User not provided";
|
||||
|
||||
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 = cleanId(player._guildId);
|
||||
const userLoc = observed.get(cleanUserId, guildId || undefined);
|
||||
if (userLoc) {
|
||||
const infoChannelId = cleanId(userLoc.channelId);
|
||||
if (infoChannelId === cleanChanId) return null;
|
||||
}
|
||||
for (const [mapUserId, info] of observed) {
|
||||
if (cleanId(mapUserId) === cleanUserId) {
|
||||
const infoChannelId = cleanId(info.channelId);
|
||||
if (infoChannelId === cleanChanId) return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return "You must be in the same voice channel as the bot to control playback";
|
||||
},
|
||||
|
||||
/**
|
||||
* Verify that the given user is a member of the specified guild.
|
||||
* Bot owners bypass the check.
|
||||
* @private
|
||||
* @async
|
||||
* @param {object} user - The user to verify.
|
||||
* @param {string} guildId - The guild ID to check membership in.
|
||||
* @returns {Promise<string|null>} An error message if not a member, or null if authorized.
|
||||
*/
|
||||
async _authorizeUserInGuild(user, guildId) {
|
||||
if (this.remix.handler?.owners?.includes?.(user.id)) return null;
|
||||
|
||||
try {
|
||||
const guild = this.remix.client.guilds.get(guildId);
|
||||
if (!guild) return "Server not found";
|
||||
const member = await guild.members.fetch(user.id).catch(() => null);
|
||||
if (!member) return "You are not a member of this server";
|
||||
return null;
|
||||
} catch (e) {
|
||||
return "Failed to verify membership: " + e.message;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Look up a player by channel ID, guild ID, or player ID.
|
||||
* @private
|
||||
* @param {string} id - Channel ID, guild ID, or player ID.
|
||||
* @returns {object|null} The matching Player instance, or null.
|
||||
*/
|
||||
_getPlayerById(id) {
|
||||
return this.remix.players.playerMap.get(id)
|
||||
?? [...this.remix.players.playerMap.values()].find(
|
||||
p => p._channelId === id || p._guildId === id
|
||||
)
|
||||
?? null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Verify a dashboard login code for a user.
|
||||
* @async
|
||||
* @param {string} user - The user ID.
|
||||
* @param {string} code - The login code to verify.
|
||||
* @returns {Promise<string|null>} An error message if verification fails, or null on success.
|
||||
*/
|
||||
async confirmLogin(user, code) {
|
||||
if (!this.enabled) return "Dashboard not enabled.";
|
||||
if (!this.db) return "Dashboard database not configured.";
|
||||
|
||||
let res;
|
||||
try {
|
||||
res = await this.db.execute("SELECT * FROM login_codes WHERE user=? AND (verified IS NULL OR verified !== true)", [user]);
|
||||
} catch (e) {
|
||||
const id = Utils.uid();
|
||||
logger.dashboard("[Dashboard] MySQL error, id:", id, e);
|
||||
return "An error occurred, please contact an administrator if this happens again. Error id: `" + id + "`";
|
||||
}
|
||||
|
||||
if (res.length === 0) return "If this is a valid code, it was not created for your account.";
|
||||
|
||||
for (let i = 0; i < res.length; i++) {
|
||||
if (res[i].verified) continue;
|
||||
if (await this.db.compareHash(code, res[i].token)) {
|
||||
if (Date.now() - this.expiryTime > (new Date(res[i].createdAt)).getTime()) {
|
||||
return "Login token expired";
|
||||
}
|
||||
await this.db.execute("UPDATE login_codes SET verified=true WHERE id=?", [res[i].id]);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
return "Invalid code.";
|
||||
},
|
||||
};
|
||||
|
||||
export default RpcHandlersMixin;
|
||||
export { RpcHandlersMixin };
|
||||
@@ -0,0 +1,300 @@
|
||||
/**
|
||||
* @module dashboard/Serializers
|
||||
* @description Static data-conversion helpers for {@link Dashboard}: turn
|
||||
* users, videos/tracks, channels, guilds, players and commands into
|
||||
* dashboard-safe plain objects.
|
||||
*
|
||||
* This plain object is attached to the Dashboard class as static methods via
|
||||
* `Object.assign(Dashboard, Serializers)` at the bottom of Dashboard.mjs, so
|
||||
* `Dashboard.convertChannel(...)`, `Dashboard.convertPlayer(...)`, etc. keep
|
||||
* working for external callers.
|
||||
*/
|
||||
|
||||
import { Dashboard } from "./Dashboard.mjs";
|
||||
import { Utils, cleanId } from "../utils/Utils.mjs";
|
||||
import { logger } from "../core/Logger.mjs";
|
||||
import { iterateVoiceStates } from "../voice/VoiceStateResolver.mjs";
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
* @description Serializers — attached to Dashboard as static methods.
|
||||
*/
|
||||
const Serializers = {
|
||||
/**
|
||||
* Convert a user object to a dashboard-safe plain object.
|
||||
* @static
|
||||
* @param {object} user - The user.
|
||||
* @returns {{ id: string, username: string, displayName: string, avatar: { url: string } }}
|
||||
*/
|
||||
convertUser(user) {
|
||||
let avatarUrl = "";
|
||||
if (user.avatar) {
|
||||
avatarUrl = `https://fluxerusercontent.com/avatars/${user.id}/${user.avatar}.webp`;
|
||||
} else if (typeof user.displayAvatarURL === "function") {
|
||||
try { avatarUrl = user.displayAvatarURL() ?? ""; } catch(e) { logger.warn("[Dashboard] displayAvatarURL:", e?.message); }
|
||||
} else if (typeof user.avatarURL === "function") {
|
||||
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`;
|
||||
}
|
||||
return {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
displayName: user.displayName ?? user.globalName ?? user.username,
|
||||
avatar: {
|
||||
url: avatarUrl,
|
||||
},
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Convert a video/track object to a dashboard-safe plain object.
|
||||
* @static
|
||||
* @param {object} vid - The video/track object from the player queue.
|
||||
* @returns {object|null} Sanitised video data, or null if input is falsy.
|
||||
*/
|
||||
convertVideo(vid) {
|
||||
if (!vid) return null;
|
||||
const durationMs =
|
||||
typeof vid.duration === "number" ? vid.duration :
|
||||
typeof vid.duration === "object" && vid.duration?.seconds !== null ? vid.duration.seconds * 1000 :
|
||||
0;
|
||||
return {
|
||||
title: vid.title,
|
||||
url: vid.type === "radio" ? vid.author?.url : vid.url,
|
||||
videoId: vid.videoId,
|
||||
type: vid.type,
|
||||
duration: vid.type === "radio" ? "--:--" : Utils.prettifyMS(durationMs),
|
||||
description: vid.description,
|
||||
artist: {
|
||||
name: vid.author?.name ?? vid.artist,
|
||||
url: vid.author?.url,
|
||||
},
|
||||
thumbnail: vid.thumbnail,
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Convert a channel to a dashboard-safe plain object, including
|
||||
* voice participant info for voice channels.
|
||||
* @static
|
||||
* @param {object} channel - The channel.
|
||||
* @returns {object} Sanitised channel data.
|
||||
*/
|
||||
convertChannel(channel) {
|
||||
const type = channel.type ?? 0;
|
||||
const isVoice = channel.isVoice?.() || type === 2;
|
||||
const isCategory = type === 4;
|
||||
const isText = !isVoice && !isCategory && (
|
||||
type === 0 || type === 5 || type === 13 ||
|
||||
(typeof channel.isText === "function" && channel.isText())
|
||||
);
|
||||
let voiceParticipants = [];
|
||||
if (isVoice) {
|
||||
const guild = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId);
|
||||
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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
name: channel.name,
|
||||
displayName: channel.name,
|
||||
id: channel.id,
|
||||
icon: null,
|
||||
description: channel.topic ?? null,
|
||||
type,
|
||||
isVoice,
|
||||
isCategory,
|
||||
isText,
|
||||
parentId: channel.parentId ?? channel.parent_id ?? null,
|
||||
voiceParticipants,
|
||||
mature: channel.nsfw ?? false,
|
||||
serverId: channel.guildId,
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Convert a guild (server) to a dashboard-safe plain object with channels.
|
||||
* @static
|
||||
* @param {object} guild - The guild.
|
||||
* @returns {object} Sanitised server data including channels and voice channels.
|
||||
*/
|
||||
convertServer(guild) {
|
||||
const channelStore = guild.channels;
|
||||
const channelIds = channelStore && typeof channelStore.keys === "function"
|
||||
? [...channelStore.keys()]
|
||||
: [];
|
||||
const channelValues = channelStore && typeof channelStore.values === "function"
|
||||
? [...channelStore.values()]
|
||||
: [];
|
||||
const allChannels = channelValues
|
||||
.map(Dashboard.convertChannel)
|
||||
.filter(c => !c.isCategory);
|
||||
|
||||
let iconUrl = null;
|
||||
if (guild.icon) {
|
||||
iconUrl = `https://fluxerusercontent.com/icons/${guild.id}/${guild.icon}.webp`;
|
||||
} else if (typeof guild.iconURL === "function") {
|
||||
try { iconUrl = guild.iconURL() ?? null; } catch (e) { logger.warn("[Dashboard] iconURL error:", e?.message); iconUrl = null; }
|
||||
}
|
||||
|
||||
return {
|
||||
name: guild.name,
|
||||
id: guild.id,
|
||||
icon: iconUrl,
|
||||
channelIds,
|
||||
description: guild.description ?? null,
|
||||
ownerId: guild.ownerId,
|
||||
channels: allChannels,
|
||||
voiceChannels: allChannels.filter(c => c.isVoice),
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Convert a guild to a lightweight summary object (no channels).
|
||||
* @static
|
||||
* @param {object} guild - The guild.
|
||||
* @returns {{ name: string, id: string, icon: string|null, description: string|null, ownerId: string|null }}
|
||||
*/
|
||||
convertServerSummary(guild) {
|
||||
let iconUrl = null;
|
||||
if (guild.icon) {
|
||||
iconUrl = `https://fluxerusercontent.com/icons/${guild.id}/${guild.icon}.webp`;
|
||||
} else if (typeof guild.iconURL === "function") {
|
||||
try { iconUrl = guild.iconURL() ?? null; } catch (e) { logger.warn("[Dashboard] iconURL error:", e?.message); iconUrl = null; }
|
||||
}
|
||||
return {
|
||||
name: guild.name,
|
||||
id: guild.id,
|
||||
icon: iconUrl,
|
||||
description: guild.description ?? null,
|
||||
ownerId: guild.ownerId,
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Convert a Player instance to a dashboard-safe serialisable object.
|
||||
* Includes queue, users, channel, and server info.
|
||||
* @static
|
||||
* @param {object} player - The Player instance.
|
||||
* @returns {object} Sanitised player data.
|
||||
*/
|
||||
convertPlayer(player) {
|
||||
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 ? cleanId(channelId) : "";
|
||||
const cleanGuildId = player._guildId ? cleanId(player._guildId) : "";
|
||||
|
||||
const queue = player.queue ?? { loop: false, songLoop: false, current: null, data: [] };
|
||||
|
||||
return {
|
||||
loop: (queue.loop ? 1 : 0) + (queue.songLoop ? 2 : 0),
|
||||
paused: !!player._paused,
|
||||
volume: Number.isFinite(player.preferredVolume) ? player.preferredVolume * 100 : 100,
|
||||
queue: {
|
||||
current: Dashboard.convertVideo(queue.current),
|
||||
data: Array.isArray(queue.data) ? queue.data.slice(0, 500).map(v => Dashboard.convertVideo(v)) : [],
|
||||
},
|
||||
users: (() => {
|
||||
if (!channel) return player._dashboardUsers ?? [];
|
||||
const g = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId);
|
||||
const ids = [];
|
||||
const seen = new Set();
|
||||
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;
|
||||
if (vc && cleanChannelId && cleanGuildId) {
|
||||
if (typeof vc.getHumansInChannel === "function") {
|
||||
const channelHumans = vc.getHumansInChannel(cleanGuildId, cleanChannelId);
|
||||
for (const hid of channelHumans) {
|
||||
if (seen.has(hid)) continue;
|
||||
const botId = player.client?.user?.id;
|
||||
if (botId && String(hid) === String(botId)) continue;
|
||||
ids.push(String(hid));
|
||||
seen.add(hid);
|
||||
}
|
||||
} else {
|
||||
for (const [mapUserId, info] of vc) {
|
||||
if (seen.has(mapUserId)) continue;
|
||||
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;
|
||||
ids.push(String(mapUserId));
|
||||
seen.add(mapUserId);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (player._dashboardUsers) {
|
||||
for (const du of player._dashboardUsers) {
|
||||
if (!seen.has(du)) { ids.push(du); seen.add(du); }
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
})(),
|
||||
channel: channel ? Dashboard.convertChannel(channel) : null,
|
||||
server: guild ? Dashboard.convertServerSummary(guild) : null,
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Convert a command option to a dashboard-safe plain object.
|
||||
* @static
|
||||
* @param {object} opt - The command option.
|
||||
* @returns {object} Sanitised option data.
|
||||
*/
|
||||
convertOption(opt) {
|
||||
return {
|
||||
type: opt.type,
|
||||
name: opt.name,
|
||||
choices: opt.choices,
|
||||
description: opt.description,
|
||||
required: opt.required,
|
||||
uid: opt.uid,
|
||||
defaultValue: opt.defaultValue,
|
||||
dynamicDefaultPresent: !!opt.dynamicDefault,
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Convert a command (and its subcommands/options) to a dashboard-safe plain object.
|
||||
* @static
|
||||
* @param {object} com - The command object.
|
||||
* @param {object} commands - The CommandHandler instance (for usage generation).
|
||||
* @returns {object} Sanitised command data.
|
||||
*/
|
||||
convertCommand(com, commands) {
|
||||
return {
|
||||
name: com.name,
|
||||
description: com.description,
|
||||
uid: com.uid,
|
||||
aliases: com.aliases,
|
||||
subcommands: com.subcommands.map(c => Dashboard.convertCommand(c, commands)),
|
||||
category: com.category,
|
||||
examples: com.examples,
|
||||
usage: commands.helpHandler?.commandUsage?.(com, {
|
||||
message: { guildId: null },
|
||||
}) ?? null,
|
||||
options: com.options.map(o => Dashboard.convertOption(o)),
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
export default Serializers;
|
||||
export { Serializers };
|
||||
@@ -0,0 +1,6 @@
|
||||
/**
|
||||
* @module dashboard
|
||||
* @description Barrel for the dashboard layer — re-exports the Dashboard class.
|
||||
*/
|
||||
|
||||
export { Dashboard } from "./Dashboard.mjs";
|
||||
@@ -0,0 +1,82 @@
|
||||
/**
|
||||
* @module src/db/DatabaseManager
|
||||
* @description MySQL connection pool wrapper for the dashboard. Provides parameterised
|
||||
* query execution and bcrypt hashing utilities for login code management.
|
||||
*/
|
||||
|
||||
import { compare, genSalt, hash } from "bcryptjs";
|
||||
import { createPool } from "mysql2/promise";
|
||||
import { logger } from "../core/Logger.mjs";
|
||||
|
||||
/**
|
||||
* @class
|
||||
* @description Wraps a mysql2 connection pool with convenience methods for
|
||||
* parameterised queries and bcrypt hash operations.
|
||||
*/
|
||||
export class DatabaseManager {
|
||||
/**
|
||||
* Create a new DatabaseManager.
|
||||
* @param {object} config - mysql2 pool configuration (host, user, password, database, etc.).
|
||||
*/
|
||||
constructor(config) {
|
||||
this.db = createPool({
|
||||
connectionLimit: 15,
|
||||
...config,
|
||||
});
|
||||
this.db.on("error", (err) => {
|
||||
logger.error("[DashboardDB] MySQL pool error:", err.code ?? err.message);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a raw SQL query (no parameter binding).
|
||||
* @async
|
||||
* @param {string} query - The SQL query string.
|
||||
* @returns {Promise<Array>} The query result rows and fields.
|
||||
*/
|
||||
async query(query) {
|
||||
return this.db.query(query);
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a parameterised SQL query.
|
||||
* @async
|
||||
* @param {string} query - The SQL query with `?` placeholders.
|
||||
* @param {Array} data - The values to bind.
|
||||
* @returns {Promise<Array>} The result rows.
|
||||
*/
|
||||
async execute(query, data) {
|
||||
const [res, _fields] = await this.db.execute(query, data);
|
||||
return res;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a bcrypt hash of the given plaintext.
|
||||
* @async
|
||||
* @param {string} plain - The plaintext string.
|
||||
* @returns {Promise<string>} The hashed string.
|
||||
*/
|
||||
async hash(plain) {
|
||||
const salt = await genSalt(10);
|
||||
return hash(plain, salt);
|
||||
}
|
||||
|
||||
/**
|
||||
* Compare a plaintext string against a bcrypt hash.
|
||||
* @async
|
||||
* @param {string} plain - The plaintext string.
|
||||
* @param {string} hashed - The bcrypt hash.
|
||||
* @returns {Promise<boolean>} True if the plaintext matches the hash.
|
||||
*/
|
||||
async compareHash(plain, hashed) {
|
||||
return await compare(plain, hashed);
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the underlying MySQL connection pool.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
close() {
|
||||
return this.db.end();
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
/**
|
||||
* @module src/Settings
|
||||
* @module src/db/Settings
|
||||
* @description MySQL-backed settings system for per-guild bot configuration.
|
||||
* Supports debounced writes (80ms), multi-bot via bot_id column, and
|
||||
* automatic schema migration for legacy tables.
|
||||
@@ -8,7 +8,7 @@
|
||||
import fs from "node:fs";
|
||||
import mysql from "mysql2";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
import { logger } from "../core/Logger.mjs";
|
||||
|
||||
/**
|
||||
* Base settings manager providing defaults, descriptions, and key utilities.
|
||||
@@ -1,10 +1,11 @@
|
||||
/** @module src/LavalinkManager @description Manages Lavalink/NodeLink connection, voice forwarding, and audio search functionality. */
|
||||
/** @module src/music/LavalinkManager @description Manages Lavalink/NodeLink connection, voice forwarding, and audio search functionality. */
|
||||
|
||||
import { LavalinkManager as LavalinkClientManager, NodeType } from "lavalink-client";
|
||||
import { logger, _wsErrorCooldown } from "./constants/Logger.mjs";
|
||||
import { logger, _wsErrorCooldown } from "../core/Logger.mjs";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { Events } from "@fluxerjs/core";
|
||||
import { getVoiceManager } from "@fluxerjs/voice";
|
||||
import * as ShardingUtils from "../utils/ShardingUtils.mjs";
|
||||
|
||||
/** @class LavalinkManager @description Manages Lavalink/NodeLink connection, voice forwarding, and audio search functionality. Wraps the lavalink-client library and provides node lifecycle management, search, player creation, and WebSocket payload interception. @extends {EventEmitter} */
|
||||
export class LavalinkManager extends EventEmitter {
|
||||
@@ -23,7 +24,7 @@ export class LavalinkManager extends EventEmitter {
|
||||
/** @private @type {Map<string, object>} @description Cached VOICE_SERVER_UPDATE payloads keyed by guild ID. */
|
||||
_cachedVoiceServerUpdates = new Map();
|
||||
|
||||
/** Create a new LavalinkManager and initialize the underlying lavalink-client connection. @param {object} nodeCfg - Node configuration (id, host, port, password, secure). @param {object} client - Discord bot client instance. @param {object} user - Bot user object with id and username. */
|
||||
/** Create a new LavalinkManager and initialize the underlying lavalink-client connection. @param {object} nodeCfg - Node configuration (id, host, port, password, secure). @param {object} client - bot client instance. @param {object} user - Bot user object with id and username. */
|
||||
constructor(nodeCfg, client, user) {
|
||||
super();
|
||||
this.setMaxListeners(50);
|
||||
@@ -178,12 +179,16 @@ export class LavalinkManager extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// Fluxer 3.0 sharding: gateway payloads are guild-scoped — route to the
|
||||
// shard that owns this guild (single process: always shard 0, as before).
|
||||
const targetShardId = ShardingUtils.shardIdForGuild(this._client, guildId);
|
||||
|
||||
if (typeof this._client?.ws?.send === "function") {
|
||||
this._client.ws.send(0, payload);
|
||||
this._client.ws.send(targetShardId, payload);
|
||||
return;
|
||||
}
|
||||
|
||||
const shard = this._client?.ws?.shards?.get?.(0);
|
||||
const shard = ShardingUtils.getShard(this._client, targetShardId);
|
||||
if (!shard) {
|
||||
logger.warn("[LavalinkManager] No WebSocket shard available");
|
||||
return;
|
||||
@@ -206,24 +211,31 @@ export class LavalinkManager extends EventEmitter {
|
||||
|
||||
const attachRawWs = () => {
|
||||
try {
|
||||
const shard0 = client.ws?.shards?.get?.(0);
|
||||
const wsObj = shard0?.ws ?? null;
|
||||
if (!wsObj) return;
|
||||
// Fluxer 3.0 + sharding: getShards() replaces the 2.2 `shards` Map
|
||||
// property, and a sharded child owns several shards — track the raw
|
||||
// socket of EVERY local shard, not just shard 0.
|
||||
const wsObjs = ShardingUtils.localShardSockets(client);
|
||||
if (wsObjs.length === 0) return;
|
||||
|
||||
if (this._rawWsHandler && this._rawWsObj && this._rawWsObj !== wsObj) {
|
||||
if (!this._rawWsObjs) this._rawWsObjs = new Set();
|
||||
const attached = this._rawWsObjs;
|
||||
|
||||
// Detach listeners from sockets that went away (reconnects).
|
||||
for (const old of attached) {
|
||||
if (wsObjs.includes(old)) continue;
|
||||
try {
|
||||
if (typeof this._rawWsObj.removeEventListener === "function") {
|
||||
this._rawWsObj.removeEventListener(
|
||||
if (typeof old.removeEventListener === "function") {
|
||||
old.removeEventListener(
|
||||
"message",
|
||||
this._rawWsMessageListener ?? this._rawWsHandler
|
||||
);
|
||||
this._rawWsObj.removeEventListener("error", this._rawWsErrorHandler);
|
||||
} else if (typeof this._rawWsObj.off === "function") {
|
||||
this._rawWsObj.off(
|
||||
old.removeEventListener("error", this._rawWsErrorHandler);
|
||||
} else if (typeof old.off === "function") {
|
||||
old.off(
|
||||
"message",
|
||||
this._rawWsMessageListener ?? this._rawWsHandler
|
||||
);
|
||||
this._rawWsObj.off("error", this._rawWsErrorHandler);
|
||||
old.off("error", this._rawWsErrorHandler);
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn(
|
||||
@@ -231,10 +243,11 @@ export class LavalinkManager extends EventEmitter {
|
||||
e?.message
|
||||
);
|
||||
}
|
||||
attached.delete(old);
|
||||
}
|
||||
|
||||
if (wsObj === this._rawWsObj) return;
|
||||
|
||||
// Create the shared handlers once (stateless parsers).
|
||||
if (!this._rawWsHandler) {
|
||||
const botId = this._client?.user?.id;
|
||||
let _vsuLogCooldown = 0;
|
||||
let _vsuBotLogCooldown = 0;
|
||||
@@ -290,16 +303,24 @@ export class LavalinkManager extends EventEmitter {
|
||||
|
||||
this._rawWsMessageListener = (event) =>
|
||||
this._rawWsHandler(event?.data ?? event);
|
||||
|
||||
if (typeof wsObj.addEventListener === "function") {
|
||||
wsObj.addEventListener("message", this._rawWsMessageListener);
|
||||
wsObj.addEventListener("error", this._rawWsErrorHandler);
|
||||
} else if (typeof wsObj.on === "function") {
|
||||
wsObj.on("message", this._rawWsMessageListener);
|
||||
wsObj.on("error", this._rawWsErrorHandler);
|
||||
}
|
||||
|
||||
this._rawWsObj = wsObj;
|
||||
for (const wsObj of wsObjs) {
|
||||
if (attached.has(wsObj)) continue;
|
||||
|
||||
if (typeof wsObj.addEventListener === "function") {
|
||||
wsObj.addEventListener("message", this._rawWsMessageListener);
|
||||
wsObj.addEventListener("error", this._rawWsErrorHandler);
|
||||
} else if (typeof wsObj.on === "function") {
|
||||
wsObj.on("message", this._rawWsMessageListener);
|
||||
wsObj.on("error", this._rawWsErrorHandler);
|
||||
}
|
||||
|
||||
attached.add(wsObj);
|
||||
}
|
||||
|
||||
// Legacy singular field kept in sync (first socket).
|
||||
this._rawWsObj = wsObjs[0] ?? null;
|
||||
} catch (e) {
|
||||
logger.warn("[LavalinkManager] Raw WS setup error:", e.message);
|
||||
}
|
||||
@@ -0,0 +1,298 @@
|
||||
/**
|
||||
* @module src/music/PlayerEventsMixin
|
||||
* @description Dashboard event wiring concern for {@link PlayerManager}:
|
||||
* binds dashboard update/queue/message events onto spawned players,
|
||||
* forwards now-playing updates to Last.fm with scrobble scheduling, and
|
||||
* translates locale keys for message contexts.
|
||||
*
|
||||
* These methods are applied onto the PlayerManager class prototype via
|
||||
* {@link applyMixins} (see src/music/PlayerManager.mjs) — `this` is a
|
||||
* PlayerManager instance.
|
||||
*/
|
||||
|
||||
import { cleanId } from "../utils/Utils.mjs";
|
||||
import { getMessageGuildId } from "../ui/index.mjs";
|
||||
import { Dashboard } from "../dashboard/Dashboard.mjs";
|
||||
|
||||
// Module-level ID helpers from the original PlayerManager.mjs. They live in
|
||||
// this module (not the base file) because it is the shared leaf of the three
|
||||
// PlayerManager modules, which keeps the import graph acyclic:
|
||||
// PlayerManager.mjs → PlayerEventsMixin.mjs ← PlayerLifecycleMixin.mjs.
|
||||
/** @private @param {Player} player @param {object|null} [fallbackChannel=null] @returns {string} Cleaned guild ID. */
|
||||
function getPlayerGuildId(player, fallbackChannel = null) {
|
||||
return cleanId(
|
||||
player?._guildId ??
|
||||
fallbackChannel?.guildId ??
|
||||
fallbackChannel?.guild?.id ??
|
||||
fallbackChannel?.server_id ??
|
||||
fallbackChannel?.serverId
|
||||
);
|
||||
}
|
||||
|
||||
/** @private @param {Player} player @param {string|null} [fallbackChannelId=null] @returns {string} Cleaned channel ID. */
|
||||
function getPlayerChannelId(player, fallbackChannelId = null) {
|
||||
return cleanId(player?._channelId ?? player?._home247Channel ?? fallbackChannelId);
|
||||
}
|
||||
export { getPlayerGuildId, getPlayerChannelId };
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
* @description Player events mixin — applied to PlayerManager.
|
||||
*/
|
||||
const PlayerEventsMixin = {
|
||||
/** Bind dashboard update and message-sending events on a player. @this {import('./PlayerManager.mjs').PlayerManager} @param {Player} player @param {object} [context={}] @returns {Player} The same player, with events bound. */
|
||||
setupEvents(player, context = {}) {
|
||||
if (!player || player._dashboardEventsBound) return player;
|
||||
|
||||
Object.defineProperty(player, "_dashboardEventsBound", {
|
||||
value: true,
|
||||
configurable: true,
|
||||
enumerable: false,
|
||||
writable: true,
|
||||
});
|
||||
|
||||
const emit = (type, data) => {
|
||||
if (!this.dashboard?.enabled) return;
|
||||
this.dashboard.updatePlayer({ type, data }, player);
|
||||
};
|
||||
|
||||
const emitGlobal = (type) => {
|
||||
if (!this.dashboard?.enabled) return;
|
||||
this.dashboard.playerUpdate({ type }, player);
|
||||
};
|
||||
|
||||
const sendUserUpdates = (eventType) => {
|
||||
if (!this.dashboard?.enabled) return;
|
||||
const channelId = getPlayerChannelId(player, context.channelId);
|
||||
const channel = player.client?.channels?.get(channelId);
|
||||
const guild = player.client?.guilds?.get(cleanId(player._guildId ?? context.guildId));
|
||||
if (!guild) return;
|
||||
const voiceStates = guild.voice_states ?? guild.voiceStates ?? null;
|
||||
if (!voiceStates) return;
|
||||
const entries = Array.isArray(voiceStates)
|
||||
? voiceStates
|
||||
: typeof voiceStates.values === "function"
|
||||
? [...voiceStates.values()]
|
||||
: Object.values(voiceStates);
|
||||
for (const state of entries) {
|
||||
if (!state?.channelId && !state?.channel_id) continue;
|
||||
const stateChannelId = cleanId(state.channelId ?? state.channel_id);
|
||||
if (stateChannelId !== channelId) continue;
|
||||
const member = guild.members?.get?.(state.userId ?? state.user_id);
|
||||
if (!member?.user || member.user?.bot) continue;
|
||||
emit(eventType, member.user.id);
|
||||
this.dashboard.userUpdate({
|
||||
type: eventType,
|
||||
guildId: cleanId(player._guildId ?? context.guildId),
|
||||
channelId,
|
||||
}, member.user);
|
||||
}
|
||||
};
|
||||
|
||||
player.on("roomfetched", () => {
|
||||
emitGlobal("init");
|
||||
sendUserUpdates("join");
|
||||
});
|
||||
|
||||
player.on("startplay", (song) => {
|
||||
emit("startplay", Dashboard.convertVideo(song ?? player.queue?.current));
|
||||
emit("streamStartPlay", Date.now());
|
||||
this.dashboard.playerUpdate({ type: "startplay" }, player);
|
||||
|
||||
if (this._lastfm?.enabled && song) {
|
||||
this._handleLastFmStartPlay(player, song);
|
||||
}
|
||||
});
|
||||
|
||||
player.on("stopplay", () => {
|
||||
emit("stopplay", null);
|
||||
this.dashboard.playerUpdate({ type: "stopplay" }, player);
|
||||
});
|
||||
|
||||
player.on("playback", (playing) => {
|
||||
const elapsedMs = player._pausedAt
|
||||
? (player._pausedAt.getTime?.() ?? Number(player._pausedAt)) -
|
||||
(player.startedPlaying?.getTime?.() ?? Number(player.startedPlaying ?? 0))
|
||||
: Date.now() - (player.startedPlaying?.getTime?.() ?? Number(player.startedPlaying ?? 0));
|
||||
const type = playing ? "resume" : "pause";
|
||||
emit(type, { elapsedTime: Math.max(0, elapsedMs) });
|
||||
this.dashboard.playerUpdate({ type }, player);
|
||||
});
|
||||
|
||||
player.on("volume", (volume) => {
|
||||
emit("volume", volume);
|
||||
this.dashboard.playerUpdate({ type: "volume" }, player);
|
||||
});
|
||||
|
||||
player.on("filter", (filter) => {
|
||||
emit("filter", filter);
|
||||
});
|
||||
|
||||
player.on("update", (scope) => {
|
||||
this.dashboard.playerUpdate({ type: "update" }, player);
|
||||
});
|
||||
|
||||
player.on("autoleave", () => {
|
||||
sendUserUpdates("leave");
|
||||
emitGlobal("close");
|
||||
emit("stopplay", null);
|
||||
});
|
||||
|
||||
player.on("leave", () => {
|
||||
sendUserUpdates("leave");
|
||||
emitGlobal("close");
|
||||
emit("stopplay", null);
|
||||
});
|
||||
|
||||
player.queue?.on("queue", (queueEvent) => {
|
||||
const serialised = { type: queueEvent.type };
|
||||
switch (queueEvent.type) {
|
||||
case "add":
|
||||
serialised.data = {
|
||||
append: queueEvent.data?.append,
|
||||
data: Dashboard.convertVideo(queueEvent.data?.data),
|
||||
};
|
||||
break;
|
||||
case "addMany":
|
||||
serialised.data = {
|
||||
append: queueEvent.data?.append,
|
||||
tracks: (queueEvent.data?.tracks ?? []).map(v => Dashboard.convertVideo(v)),
|
||||
};
|
||||
break;
|
||||
case "remove":
|
||||
serialised.data = {
|
||||
index: queueEvent.data?.index,
|
||||
removed: Dashboard.convertVideo(queueEvent.data?.removed),
|
||||
old: (queueEvent.data?.old ?? []).map(v => Dashboard.convertVideo(v)),
|
||||
new: (queueEvent.data?.new ?? []).map(v => Dashboard.convertVideo(v)),
|
||||
};
|
||||
break;
|
||||
case "move":
|
||||
serialised.data = {
|
||||
from: queueEvent.data?.from,
|
||||
to: queueEvent.data?.to,
|
||||
track: Dashboard.convertVideo(queueEvent.data?.track),
|
||||
};
|
||||
break;
|
||||
case "shuffle":
|
||||
serialised.data = (queueEvent.data ?? []).map(v => Dashboard.convertVideo(v));
|
||||
break;
|
||||
case "update":
|
||||
serialised.data = {
|
||||
current: Dashboard.convertVideo(queueEvent.data?.current),
|
||||
old: Dashboard.convertVideo(queueEvent.data?.old),
|
||||
loop: queueEvent.data?.loop,
|
||||
};
|
||||
break;
|
||||
default:
|
||||
serialised.data = queueEvent.data;
|
||||
break;
|
||||
}
|
||||
|
||||
emit("queue", serialised);
|
||||
this.dashboard.playerUpdate({ type: "queue" }, player);
|
||||
});
|
||||
|
||||
return player;
|
||||
},
|
||||
|
||||
/** @private Translate a locale key for a message context. @this {import('./PlayerManager.mjs').PlayerManager} @param {object} message @param {string} key @param {object} [replacements={}] @returns {string} */
|
||||
_t(message, key, replacements = {}) {
|
||||
if (!this.locale) return key;
|
||||
const guildId = getMessageGuildId(message);
|
||||
return this.locale.translate(guildId, key, replacements);
|
||||
},
|
||||
|
||||
/** @private Handle Last.fm now-playing update and schedule scrobble timer. @this {import('./PlayerManager.mjs').PlayerManager} @param {Player} player @param {object} song */
|
||||
_handleLastFmStartPlay(player, song) {
|
||||
const lastfm = this._lastfm;
|
||||
if (!lastfm?.enabled) return;
|
||||
|
||||
const guildId = cleanId(player._guildId);
|
||||
if (!guildId) return;
|
||||
|
||||
const channelId = getPlayerChannelId(player);
|
||||
const humanUserIds = [];
|
||||
|
||||
if (this.voiceCache) {
|
||||
const users = this.voiceCache.getHumansInChannel(guildId, channelId);
|
||||
humanUserIds.push(...users);
|
||||
} else if (this.observedVoiceUsers) {
|
||||
for (const [uid, info] of this.observedVoiceUsers) {
|
||||
if (cleanId(info.guildId) === guildId && cleanId(info.channelId) === channelId) {
|
||||
humanUserIds.push(uid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const guild = player.client?.guilds?.get(guildId);
|
||||
if (guild) {
|
||||
const voiceStates = guild.voice_states ?? guild.voiceStates ?? null;
|
||||
if (voiceStates) {
|
||||
const entries = Array.isArray(voiceStates)
|
||||
? voiceStates
|
||||
: typeof voiceStates.values === "function"
|
||||
? [...voiceStates.values()]
|
||||
: Object.values(voiceStates ?? {});
|
||||
for (const state of entries) {
|
||||
const uid = state?.userId ?? state?.user_id;
|
||||
const chId = cleanId(state?.channelId ?? state?.channel_id);
|
||||
if (uid && chId === channelId) {
|
||||
const member = guild.members?.get?.(uid);
|
||||
if (member?.user?.bot) continue;
|
||||
if (!humanUserIds.includes(uid)) humanUserIds.push(uid);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const startedAtMs = player.startedPlaying;
|
||||
|
||||
const pendingKey = channelId;
|
||||
const existing = this._pendingScrobbleTimers.get(pendingKey);
|
||||
if (existing) {
|
||||
clearTimeout(existing.timer);
|
||||
this._pendingScrobbleTimers.delete(pendingKey);
|
||||
}
|
||||
|
||||
for (const userId of humanUserIds) {
|
||||
lastfm.updateNowPlaying(userId, song).catch(() => {});
|
||||
}
|
||||
|
||||
const durationMs = (() => {
|
||||
const d = song.duration;
|
||||
if (!d) return null;
|
||||
if (typeof d === "object" && d.seconds) return d.seconds * 1000;
|
||||
if (typeof d === "number") return d;
|
||||
return null;
|
||||
})();
|
||||
|
||||
if (durationMs && durationMs >= 30_000) {
|
||||
const thresholdMs = Math.min(
|
||||
durationMs * lastfm.scrobbleThreshold,
|
||||
lastfm.scrobbleMinMs
|
||||
);
|
||||
if (thresholdMs <= 600_000) {
|
||||
const timer = setTimeout(() => {
|
||||
this._pendingScrobbleTimers.delete(pendingKey);
|
||||
const current = player.queue?.getCurrent();
|
||||
if (!current || player._destroyed || player.leaving) return;
|
||||
if (current.title !== song.title || current.url !== song.url) return;
|
||||
if (player._paused) return;
|
||||
|
||||
const playedMs = Date.now() - (player.startedPlaying ?? startedAtMs ?? Date.now());
|
||||
if (lastfm.shouldScrobble(song, playedMs)) {
|
||||
for (const userId of humanUserIds) {
|
||||
lastfm.scrobble(userId, song, startedAtMs).catch(() => {});
|
||||
}
|
||||
}
|
||||
}, thresholdMs);
|
||||
|
||||
this._pendingScrobbleTimers.set(pendingKey, { timer, songUrl: song.url, startedAtMs });
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export default PlayerEventsMixin;
|
||||
export { PlayerEventsMixin };
|
||||
@@ -1,32 +1,28 @@
|
||||
/** @module src/PlayerManager @description Manages all Player instances. Handles player lifecycle (spawn, join, leave, destroy), voice channel resolution, dashboard events, and autoleave suppression for 24/7 channels. */
|
||||
/**
|
||||
* @module src/music/PlayerLifecycleMixin
|
||||
* @description Voice-channel resolution & player lifecycle concern for
|
||||
* {@link PlayerManager}: author voice-channel detection, interactive
|
||||
* voice-channel selection prompt, leave, saved-volume restore, and
|
||||
* spawn/join of Player instances (including join retries and the autoleave
|
||||
* / now-playing announcement handlers wired inside initPlayer).
|
||||
*
|
||||
* These methods are applied onto the PlayerManager class prototype via
|
||||
* {@link applyMixins} (see src/music/PlayerManager.mjs) — `this` is a
|
||||
* PlayerManager instance.
|
||||
*/
|
||||
|
||||
import Player from "./Player.mjs";
|
||||
import { Utils, cleanId } from "./Utils.mjs";
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
import { get247ChannelMode } from "./constants/Helpers247.mjs";
|
||||
import Player from "./player/index.mjs";
|
||||
import { cleanId } from "../utils/Utils.mjs";
|
||||
import { logger } from "../core/Logger.mjs";
|
||||
import { get247ChannelMode } from "../utils/Helpers247.mjs";
|
||||
import { EmbedBuilder, PermissionFlags } from "@fluxerjs/core";
|
||||
import { getVoiceManager } from "@fluxerjs/voice";
|
||||
import { getGlobalColor, getMessageGuildId } from "./MessageHandler.mjs";
|
||||
import { Dashboard } from "./dashboard/Dashboard.mjs";
|
||||
import { hasHumansInChannel, iterateVoiceStates } from "./constants/VoiceStateResolver.mjs";
|
||||
|
||||
|
||||
/** @private @param {Player} player @param {object|null} [fallbackChannel=null] @returns {string} Cleaned guild ID. */
|
||||
function getPlayerGuildId(player, fallbackChannel = null) {
|
||||
return cleanId(
|
||||
player?._guildId ??
|
||||
fallbackChannel?.guildId ??
|
||||
fallbackChannel?.guild?.id ??
|
||||
fallbackChannel?.server_id ??
|
||||
fallbackChannel?.serverId
|
||||
);
|
||||
}
|
||||
|
||||
/** @private @param {Player} player @param {string|null} [fallbackChannelId=null] @returns {string} Cleaned channel ID. */
|
||||
function getPlayerChannelId(player, fallbackChannelId = null) {
|
||||
return cleanId(player?._channelId ?? player?._home247Channel ?? fallbackChannelId);
|
||||
}
|
||||
import { getGlobalColor, getMessageGuildId } from "../ui/index.mjs";
|
||||
import { hasHumansInChannel, iterateVoiceStates } from "../voice/VoiceStateResolver.mjs";
|
||||
import { getPlayerChannelId } from "./PlayerEventsMixin.mjs";
|
||||
|
||||
// Module-level join/permission helpers from the original PlayerManager.mjs
|
||||
// (only initPlayer below uses them, so they stay private to this module).
|
||||
/** @private Check whether the bot has required voice permissions in a channel. @param {object} client @param {string} channelId @returns {boolean} True if the bot can connect, speak, and use VAD. */
|
||||
function botHasVoicePermissions(client, channelId) {
|
||||
try {
|
||||
@@ -70,287 +66,12 @@ function sanitizeJoinError(err, client = null, channelId = null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @class PlayerManager @description Manages all Player instances. Handles player lifecycle (spawn, join, leave, destroy), voice channel resolution, dashboard events, and autoleave suppression for 24/7 channels. */
|
||||
export class PlayerManager {
|
||||
/** @type {RemoteSettingsManager} */
|
||||
settings;
|
||||
|
||||
/** @type {CommandHandler} */
|
||||
commands;
|
||||
|
||||
/** @type {Map<string, Player>} Player instances keyed by channel ID. */
|
||||
playerMap = new Map();
|
||||
|
||||
/** @private @type {Map<string, Set<string>>} Guild ID → Set of channel IDs (for fast guild-player lookup). */
|
||||
_guildPlayerIndex = new Map();
|
||||
|
||||
/** @private @type {Set<string>} Channel IDs currently being joined. */
|
||||
_pendingJoins = new Set();
|
||||
|
||||
/** @private @type {Map<string, {timer: setTimeout, songUrl: string, startedAtMs: number}>} */
|
||||
_pendingScrobbleTimers = new Map();
|
||||
|
||||
/** @type {object} Full bot config. */
|
||||
config;
|
||||
|
||||
/** @type {object} Player-specific config (lavalink reference). */
|
||||
playerConfig;
|
||||
|
||||
/** @type {Locale|null} */
|
||||
locale = null;
|
||||
|
||||
/** @type {Dashboard|null} */
|
||||
dashboard = null;
|
||||
|
||||
/**
|
||||
* Create a new PlayerManager.
|
||||
* @param {RemoteSettingsManager} settings - The settings manager.
|
||||
* @param {CommandHandler} commands - The command handler.
|
||||
* @param {object} config - Configuration object.
|
||||
* @param {object} config.config - Full bot config.
|
||||
* @param {object} config.player - Player-specific config (lavalink, etc.).
|
||||
* @param {Dashboard} [config.dashboard] - Dashboard instance.
|
||||
* @param {Locale} [config.locale] - Locale manager.
|
||||
* @param {object} [config.timers] - Timer configuration.
|
||||
* @param {TrackOptionsManager} [config.trackOptions] - Track options manager.
|
||||
*/
|
||||
constructor(settings, commands, config) {
|
||||
this.commands = commands;
|
||||
this.settings = settings;
|
||||
this.config = config.config;
|
||||
this.playerConfig = config.player;
|
||||
this.dashboard = config.dashboard ?? null;
|
||||
this.locale = config.locale ?? null;
|
||||
this.timers = config.timers ?? {};
|
||||
this._lastfm = null;
|
||||
this.trackOptions = config.trackOptions ?? null;
|
||||
}
|
||||
|
||||
/** @private Index a player by guild and channel ID for fast lookups. @param {string} guildId @param {string} channelId */
|
||||
_indexPlayer(guildId, channelId) {
|
||||
const gId = cleanId(guildId);
|
||||
const cId = cleanId(channelId);
|
||||
if (!gId || !cId) return;
|
||||
let set = this._guildPlayerIndex.get(gId);
|
||||
if (!set) { set = new Set(); this._guildPlayerIndex.set(gId, set); }
|
||||
set.add(cId);
|
||||
}
|
||||
|
||||
/** @private Remove a player from the guild-player index. @param {string} guildId @param {string} channelId */
|
||||
_unindexPlayer(guildId, channelId) {
|
||||
const gId = cleanId(guildId);
|
||||
const cId = cleanId(channelId);
|
||||
if (!gId) return;
|
||||
const set = this._guildPlayerIndex.get(gId);
|
||||
if (set) {
|
||||
set.delete(cId);
|
||||
if (set.size === 0) this._guildPlayerIndex.delete(gId);
|
||||
}
|
||||
}
|
||||
|
||||
/** Get all active (non-destroyed) players for a guild. @param {string} guildId @returns {Array<[string, Player]>} Array of [channelId, Player] pairs. */
|
||||
getGuildPlayers(guildId) {
|
||||
const gId = cleanId(guildId);
|
||||
const set = this._guildPlayerIndex.get(gId);
|
||||
if (!set) return [];
|
||||
const result = [];
|
||||
for (const channelId of set) {
|
||||
const player = this.playerMap.get(channelId);
|
||||
if (!player || player._destroyed) {
|
||||
set.delete(channelId);
|
||||
continue;
|
||||
}
|
||||
result.push([channelId, player]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Find a player by both guild and channel. @param {string} guildId @param {string} channelId @returns {Player|null} */
|
||||
getPlayerByGuildAndChannel(guildId, channelId) {
|
||||
const cId = cleanId(channelId);
|
||||
const players = this.getGuildPlayers(guildId);
|
||||
for (const [mapChannelId, player] of players) {
|
||||
if (getPlayerChannelId(player, mapChannelId) === cId) return player;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Find a player by its channel ID across all guilds. @param {string} channelId @returns {Player|null} */
|
||||
getPlayerByChannelId(channelId) {
|
||||
const cId = cleanId(channelId);
|
||||
for (const [, channelSet] of this._guildPlayerIndex) {
|
||||
for (const mapChannelId of channelSet) {
|
||||
const player = this.playerMap.get(mapChannelId);
|
||||
if (player && getPlayerChannelId(player, mapChannelId) === cId) return player;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Bind dashboard update and message-sending events on a player. @param {Player} player @param {object} [context={}] @returns {Player} The same player, with events bound. */
|
||||
setupEvents(player, context = {}) {
|
||||
if (!player || player._dashboardEventsBound) return player;
|
||||
|
||||
Object.defineProperty(player, "_dashboardEventsBound", {
|
||||
value: true,
|
||||
configurable: true,
|
||||
enumerable: false,
|
||||
writable: true,
|
||||
});
|
||||
|
||||
const emit = (type, data) => {
|
||||
if (!this.dashboard?.enabled) return;
|
||||
this.dashboard.updatePlayer({ type, data }, player);
|
||||
};
|
||||
|
||||
const emitGlobal = (type) => {
|
||||
if (!this.dashboard?.enabled) return;
|
||||
this.dashboard.playerUpdate({ type }, player);
|
||||
};
|
||||
|
||||
const sendUserUpdates = (eventType) => {
|
||||
if (!this.dashboard?.enabled) return;
|
||||
const channelId = getPlayerChannelId(player, context.channelId);
|
||||
const channel = player.client?.channels?.get(channelId);
|
||||
const guild = player.client?.guilds?.get(cleanId(player._guildId ?? context.guildId));
|
||||
if (!guild) return;
|
||||
const voiceStates = guild.voice_states ?? guild.voiceStates ?? null;
|
||||
if (!voiceStates) return;
|
||||
const entries = Array.isArray(voiceStates)
|
||||
? voiceStates
|
||||
: typeof voiceStates.values === "function"
|
||||
? [...voiceStates.values()]
|
||||
: Object.values(voiceStates);
|
||||
for (const state of entries) {
|
||||
if (!state?.channelId && !state?.channel_id) continue;
|
||||
const stateChannelId = cleanId(state.channelId ?? state.channel_id);
|
||||
if (stateChannelId !== channelId) continue;
|
||||
const member = guild.members?.get?.(state.userId ?? state.user_id);
|
||||
if (!member?.user || member.user?.bot) continue;
|
||||
emit(eventType, member.user.id);
|
||||
this.dashboard.userUpdate({
|
||||
type: eventType,
|
||||
guildId: cleanId(player._guildId ?? context.guildId),
|
||||
channelId,
|
||||
}, member.user);
|
||||
}
|
||||
};
|
||||
|
||||
player.on("roomfetched", () => {
|
||||
emitGlobal("init");
|
||||
sendUserUpdates("join");
|
||||
});
|
||||
|
||||
player.on("startplay", (song) => {
|
||||
emit("startplay", Dashboard.convertVideo(song ?? player.queue?.current));
|
||||
emit("streamStartPlay", Date.now());
|
||||
this.dashboard.playerUpdate({ type: "startplay" }, player);
|
||||
|
||||
if (this._lastfm?.enabled && song) {
|
||||
this._handleLastFmStartPlay(player, song);
|
||||
}
|
||||
});
|
||||
|
||||
player.on("stopplay", () => {
|
||||
emit("stopplay", null);
|
||||
this.dashboard.playerUpdate({ type: "stopplay" }, player);
|
||||
});
|
||||
|
||||
player.on("playback", (playing) => {
|
||||
const elapsedMs = player._pausedAt
|
||||
? (player._pausedAt.getTime?.() ?? Number(player._pausedAt)) -
|
||||
(player.startedPlaying?.getTime?.() ?? Number(player.startedPlaying ?? 0))
|
||||
: Date.now() - (player.startedPlaying?.getTime?.() ?? Number(player.startedPlaying ?? 0));
|
||||
const type = playing ? "resume" : "pause";
|
||||
emit(type, { elapsedTime: Math.max(0, elapsedMs) });
|
||||
this.dashboard.playerUpdate({ type }, player);
|
||||
});
|
||||
|
||||
player.on("volume", (volume) => {
|
||||
emit("volume", volume);
|
||||
this.dashboard.playerUpdate({ type: "volume" }, player);
|
||||
});
|
||||
|
||||
player.on("filter", (filter) => {
|
||||
emit("filter", filter);
|
||||
});
|
||||
|
||||
player.on("update", (scope) => {
|
||||
this.dashboard.playerUpdate({ type: "update" }, player);
|
||||
});
|
||||
|
||||
player.on("autoleave", () => {
|
||||
sendUserUpdates("leave");
|
||||
emitGlobal("close");
|
||||
emit("stopplay", null);
|
||||
});
|
||||
|
||||
player.on("leave", () => {
|
||||
sendUserUpdates("leave");
|
||||
emitGlobal("close");
|
||||
emit("stopplay", null);
|
||||
});
|
||||
|
||||
player.queue?.on("queue", (queueEvent) => {
|
||||
const serialised = { type: queueEvent.type };
|
||||
switch (queueEvent.type) {
|
||||
case "add":
|
||||
serialised.data = {
|
||||
append: queueEvent.data?.append,
|
||||
data: Dashboard.convertVideo(queueEvent.data?.data),
|
||||
};
|
||||
break;
|
||||
case "addMany":
|
||||
serialised.data = {
|
||||
append: queueEvent.data?.append,
|
||||
tracks: (queueEvent.data?.tracks ?? []).map(v => Dashboard.convertVideo(v)),
|
||||
};
|
||||
break;
|
||||
case "remove":
|
||||
serialised.data = {
|
||||
index: queueEvent.data?.index,
|
||||
removed: Dashboard.convertVideo(queueEvent.data?.removed),
|
||||
old: (queueEvent.data?.old ?? []).map(v => Dashboard.convertVideo(v)),
|
||||
new: (queueEvent.data?.new ?? []).map(v => Dashboard.convertVideo(v)),
|
||||
};
|
||||
break;
|
||||
case "move":
|
||||
serialised.data = {
|
||||
from: queueEvent.data?.from,
|
||||
to: queueEvent.data?.to,
|
||||
track: Dashboard.convertVideo(queueEvent.data?.track),
|
||||
};
|
||||
break;
|
||||
case "shuffle":
|
||||
serialised.data = (queueEvent.data ?? []).map(v => Dashboard.convertVideo(v));
|
||||
break;
|
||||
case "update":
|
||||
serialised.data = {
|
||||
current: Dashboard.convertVideo(queueEvent.data?.current),
|
||||
old: Dashboard.convertVideo(queueEvent.data?.old),
|
||||
loop: queueEvent.data?.loop,
|
||||
};
|
||||
break;
|
||||
default:
|
||||
serialised.data = queueEvent.data;
|
||||
break;
|
||||
}
|
||||
|
||||
emit("queue", serialised);
|
||||
this.dashboard.playerUpdate({ type: "queue" }, player);
|
||||
});
|
||||
|
||||
return player;
|
||||
}
|
||||
|
||||
/** @private Translate a locale key for a message context. @param {object} message @param {string} key @param {object} [replacements={}] @returns {string} */
|
||||
_t(message, key, replacements = {}) {
|
||||
if (!this.locale) return key;
|
||||
const guildId = getMessageGuildId(message);
|
||||
return this.locale.translate(guildId, key, replacements);
|
||||
}
|
||||
|
||||
/** Detect which voice channel the message author is in. @async @param {object} message @param {object} settings @returns {Promise<{channelId: string|null, alreadyInVoice: boolean, hasHumans: boolean}>} */
|
||||
/**
|
||||
* @type {object}
|
||||
* @description Player lifecycle mixin — applied to PlayerManager.
|
||||
*/
|
||||
const PlayerLifecycleMixin = {
|
||||
/** Detect which voice channel the message author is in. @async @this {import('./PlayerManager.mjs').PlayerManager} @param {object} message @param {object} settings @returns {Promise<{channelId: string|null, alreadyInVoice: boolean, hasHumans: boolean}>} */
|
||||
async checkVoiceChannels(message, settings) {
|
||||
const guildId = message?.guildId ?? message?.channel?.guildId ?? getMessageGuildId(message);
|
||||
const userId = message?.author?.id ?? message?.member?.user?.id;
|
||||
@@ -415,94 +136,9 @@ export class PlayerManager {
|
||||
});
|
||||
|
||||
return { channelId, alreadyInVoice, hasHumans: hasHumansResult };
|
||||
}
|
||||
},
|
||||
|
||||
/** Get or spawn a player for the message's voice channel. @async @param {object} message @param {boolean} [promptJoin=true] @param {boolean} [verifyUser=true] @param {boolean} [shouldJoin=false] @returns {Promise<Player|null>} */
|
||||
async getPlayer(message, promptJoin = true, verifyUser = true, shouldJoin = false) {
|
||||
const guildId = getMessageGuildId(message);
|
||||
const cleanGuildId = cleanId(guildId);
|
||||
|
||||
const { channelId: userChannelId } = await this.checkVoiceChannels(message);
|
||||
const cleanUserChannelId = cleanId(userChannelId);
|
||||
|
||||
if (cleanUserChannelId) {
|
||||
const player = this.playerMap.get(cleanUserChannelId)
|
||||
?? this.getPlayerByGuildAndChannel(cleanGuildId, cleanUserChannelId);
|
||||
if (player) {
|
||||
player.textChannel = message.channel?.channel ?? message.channel;
|
||||
try {
|
||||
const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null;
|
||||
if (guildId && textChannelId) {
|
||||
this.settings.getServer(guildId)?.set("announcementChannelId", textChannelId);
|
||||
}
|
||||
} catch(e) {
|
||||
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
|
||||
}
|
||||
return player;
|
||||
}
|
||||
if (this._pendingJoins.has(cleanUserChannelId)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const serverPlayers = cleanGuildId
|
||||
? this.getGuildPlayers(cleanGuildId)
|
||||
: [];
|
||||
|
||||
if (serverPlayers.length > 0) {
|
||||
const channelList = serverPlayers.map(([chId]) => `<#${chId}>`).join(" or ");
|
||||
|
||||
if (!userChannelId) {
|
||||
if (!verifyUser) {
|
||||
const first = serverPlayers[0];
|
||||
first[1].textChannel = message.channel?.channel ?? message.channel;
|
||||
return first[1];
|
||||
}
|
||||
message.reply(this._t(message, "responses._common.noVoiceStrict"));
|
||||
return null;
|
||||
}
|
||||
|
||||
const match = serverPlayers.find(([, player]) =>
|
||||
getPlayerChannelId(player) === cleanUserChannelId
|
||||
);
|
||||
if (match) {
|
||||
match[1].textChannel = message.channel?.channel ?? message.channel;
|
||||
try {
|
||||
const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null;
|
||||
if (cleanGuildId && textChannelId) {
|
||||
this.settings.getServer(cleanGuildId)?.set("announcementChannelId", textChannelId);
|
||||
}
|
||||
} catch(e) {
|
||||
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
|
||||
}
|
||||
return match[1];
|
||||
}
|
||||
|
||||
if (shouldJoin) {
|
||||
return this.initPlayer(message, userChannelId);
|
||||
}
|
||||
|
||||
const prefix = this.commands.getPrefix(guildId);
|
||||
message.reply(this._t(message, "responses._common.alreadyInChannel", { channels: channelList, prefix }));
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!userChannelId) {
|
||||
if (shouldJoin) {
|
||||
return this.promptVC(message);
|
||||
}
|
||||
message.reply(this._t(message, "responses._common.noVoiceChannel"));
|
||||
return null;
|
||||
}
|
||||
|
||||
if (shouldJoin) {
|
||||
return this.initPlayer(message, userChannelId);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Prompt the user to select a voice channel via reactions or text input. @async @param {object} msg @returns {Promise<Player|false>} */
|
||||
/** Prompt the user to select a voice channel via reactions or text input. @async @this {import('./PlayerManager.mjs').PlayerManager} @param {object} msg @returns {Promise<Player|false>} */
|
||||
async promptVC(msg) {
|
||||
const { channelId: autoDetected } = await this.checkVoiceChannels(msg);
|
||||
if (autoDetected) {
|
||||
@@ -585,9 +221,9 @@ export class PlayerManager {
|
||||
this.initPlayer(m, channel).then(p => resolve(p));
|
||||
}, promptUser);
|
||||
});
|
||||
}
|
||||
},
|
||||
|
||||
/** Leave a voice channel, destroy the player, and send a confirmation. @async @param {object} msg @param {string} [cid] @returns {Promise<void>} */
|
||||
/** Leave a voice channel, destroy the player, and send a confirmation. @async @this {import('./PlayerManager.mjs').PlayerManager} @param {object} msg @param {string} [cid] @returns {Promise<void>} */
|
||||
async leave(msg, cid) {
|
||||
if (!cid) {
|
||||
const guildId = getMessageGuildId(msg);
|
||||
@@ -620,18 +256,18 @@ export class PlayerManager {
|
||||
}
|
||||
player.destroy();
|
||||
await msg.reply(this._t(msg, "responses._common.successfullyLeft"));
|
||||
}
|
||||
},
|
||||
|
||||
/** @private Restore saved volume for a player from guild settings. @param {Player} player @param {string} guildId */
|
||||
/** @private Restore saved volume for a player from guild settings. @this {import('./PlayerManager.mjs').PlayerManager} @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 a new Player, join the voice channel, and set up events. @async @param {object} message @param {string} cid @returns {Promise<Player|null>} The spawned player, or null on failure. */
|
||||
/** Create a new Player, join the voice channel, and set up events. @async @this {import('./PlayerManager.mjs').PlayerManager} @param {object} message @param {string} cid @returns {Promise<Player|null>} The spawned player, or null on failure. */
|
||||
async initPlayer(message, cid) {
|
||||
const channel = this.commands.client?.channels?.get(cid);
|
||||
|
||||
@@ -917,96 +553,8 @@ export class PlayerManager {
|
||||
player.destroy();
|
||||
return null;
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
/** @private Handle Last.fm now-playing update and schedule scrobble timer. @param {Player} player @param {object} song */
|
||||
_handleLastFmStartPlay(player, song) {
|
||||
const lastfm = this._lastfm;
|
||||
if (!lastfm?.enabled) return;
|
||||
|
||||
const guildId = cleanId(player._guildId);
|
||||
if (!guildId) return;
|
||||
|
||||
const channelId = getPlayerChannelId(player);
|
||||
const humanUserIds = [];
|
||||
|
||||
if (this.voiceCache) {
|
||||
const users = this.voiceCache.getHumansInChannel(guildId, channelId);
|
||||
humanUserIds.push(...users);
|
||||
} else if (this.observedVoiceUsers) {
|
||||
for (const [uid, info] of this.observedVoiceUsers) {
|
||||
if (cleanId(info.guildId) === guildId && cleanId(info.channelId) === channelId) {
|
||||
humanUserIds.push(uid);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const guild = player.client?.guilds?.get(guildId);
|
||||
if (guild) {
|
||||
const voiceStates = guild.voice_states ?? guild.voiceStates ?? null;
|
||||
if (voiceStates) {
|
||||
const entries = Array.isArray(voiceStates)
|
||||
? voiceStates
|
||||
: typeof voiceStates.values === "function"
|
||||
? [...voiceStates.values()]
|
||||
: Object.values(voiceStates ?? {});
|
||||
for (const state of entries) {
|
||||
const uid = state?.userId ?? state?.user_id;
|
||||
const chId = cleanId(state?.channelId ?? state?.channel_id);
|
||||
if (uid && chId === channelId) {
|
||||
const member = guild.members?.get?.(uid);
|
||||
if (member?.user?.bot) continue;
|
||||
if (!humanUserIds.includes(uid)) humanUserIds.push(uid);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const startedAtMs = player.startedPlaying;
|
||||
|
||||
const pendingKey = channelId;
|
||||
const existing = this._pendingScrobbleTimers.get(pendingKey);
|
||||
if (existing) {
|
||||
clearTimeout(existing.timer);
|
||||
this._pendingScrobbleTimers.delete(pendingKey);
|
||||
}
|
||||
|
||||
for (const userId of humanUserIds) {
|
||||
lastfm.updateNowPlaying(userId, song).catch(() => {});
|
||||
}
|
||||
|
||||
const durationMs = (() => {
|
||||
const d = song.duration;
|
||||
if (!d) return null;
|
||||
if (typeof d === "object" && d.seconds) return d.seconds * 1000;
|
||||
if (typeof d === "number") return d;
|
||||
return null;
|
||||
})();
|
||||
|
||||
if (durationMs && durationMs >= 30_000) {
|
||||
const thresholdMs = Math.min(
|
||||
durationMs * lastfm.scrobbleThreshold,
|
||||
lastfm.scrobbleMinMs
|
||||
);
|
||||
if (thresholdMs <= 600_000) {
|
||||
const timer = setTimeout(() => {
|
||||
this._pendingScrobbleTimers.delete(pendingKey);
|
||||
const current = player.queue?.getCurrent();
|
||||
if (!current || player._destroyed || player.leaving) return;
|
||||
if (current.title !== song.title || current.url !== song.url) return;
|
||||
if (player._paused) return;
|
||||
|
||||
const playedMs = Date.now() - (player.startedPlaying ?? startedAtMs ?? Date.now());
|
||||
if (lastfm.shouldScrobble(song, playedMs)) {
|
||||
for (const userId of humanUserIds) {
|
||||
lastfm.scrobble(userId, song, startedAtMs).catch(() => {});
|
||||
}
|
||||
}
|
||||
}, thresholdMs);
|
||||
|
||||
this._pendingScrobbleTimers.set(pendingKey, { timer, songUrl: song.url, startedAtMs });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
export default PlayerLifecycleMixin;
|
||||
export { PlayerLifecycleMixin };
|
||||
@@ -0,0 +1,229 @@
|
||||
/**
|
||||
* @module src/music/PlayerManager
|
||||
* @description Manages all Player instances. Handles player lifecycle (spawn,
|
||||
* join, leave, destroy), voice channel resolution, dashboard events, and
|
||||
* autoleave suppression for 24/7 channels.
|
||||
*
|
||||
* Base class: class fields, constructor, the guild/channel player index,
|
||||
* lookups and getPlayer. Dashboard event wiring and Last.fm scrobble
|
||||
* scheduling live in PlayerEventsMixin.mjs; voice-channel detection, channel
|
||||
* prompt, leave and player spawn/join live in PlayerLifecycleMixin.mjs.
|
||||
* Both mixins are applied to the class at the bottom of this file.
|
||||
*/
|
||||
|
||||
import Player from "./player/index.mjs";
|
||||
import { Utils, cleanId } from "../utils/Utils.mjs";
|
||||
import { logger } from "../core/Logger.mjs";
|
||||
import { getMessageGuildId } from "../ui/index.mjs";
|
||||
import { applyMixins } from "../utils/mixins.mjs";
|
||||
import PlayerEventsMixin, { getPlayerChannelId } from "./PlayerEventsMixin.mjs";
|
||||
import PlayerLifecycleMixin from "./PlayerLifecycleMixin.mjs";
|
||||
|
||||
|
||||
/** @class PlayerManager @description Manages all Player instances. Handles player lifecycle (spawn, join, leave, destroy), voice channel resolution, dashboard events, and autoleave suppression for 24/7 channels. */
|
||||
export class PlayerManager {
|
||||
/** @type {RemoteSettingsManager} */
|
||||
settings;
|
||||
|
||||
/** @type {CommandHandler} */
|
||||
commands;
|
||||
|
||||
/** @type {Map<string, Player>} Player instances keyed by channel ID. */
|
||||
playerMap = new Map();
|
||||
|
||||
/** @private @type {Map<string, Set<string>>} Guild ID → Set of channel IDs (for fast guild-player lookup). */
|
||||
_guildPlayerIndex = new Map();
|
||||
|
||||
/** @private @type {Set<string>} Channel IDs currently being joined. */
|
||||
_pendingJoins = new Set();
|
||||
|
||||
/** @private @type {Map<string, {timer: setTimeout, songUrl: string, startedAtMs: number}>} */
|
||||
_pendingScrobbleTimers = new Map();
|
||||
|
||||
/** @type {object} Full bot config. */
|
||||
config;
|
||||
|
||||
/** @type {object} Player-specific config (lavalink reference). */
|
||||
playerConfig;
|
||||
|
||||
/** @type {Locale|null} */
|
||||
locale = null;
|
||||
|
||||
/** @type {Dashboard|null} */
|
||||
dashboard = null;
|
||||
|
||||
/**
|
||||
* Create a new PlayerManager.
|
||||
* @param {RemoteSettingsManager} settings - The settings manager.
|
||||
* @param {CommandHandler} commands - The command handler.
|
||||
* @param {object} config - Configuration object.
|
||||
* @param {object} config.config - Full bot config.
|
||||
* @param {object} config.player - Player-specific config (lavalink, etc.).
|
||||
* @param {Dashboard} [config.dashboard] - Dashboard instance.
|
||||
* @param {Locale} [config.locale] - Locale manager.
|
||||
* @param {object} [config.timers] - Timer configuration.
|
||||
* @param {TrackOptionsManager} [config.trackOptions] - Track options manager.
|
||||
*/
|
||||
constructor(settings, commands, config) {
|
||||
this.commands = commands;
|
||||
this.settings = settings;
|
||||
this.config = config.config;
|
||||
this.playerConfig = config.player;
|
||||
this.dashboard = config.dashboard ?? null;
|
||||
this.locale = config.locale ?? null;
|
||||
this.timers = config.timers ?? {};
|
||||
this._lastfm = null;
|
||||
this.trackOptions = config.trackOptions ?? null;
|
||||
}
|
||||
|
||||
/** @private Index a player by guild and channel ID for fast lookups. @param {string} guildId @param {string} channelId */
|
||||
_indexPlayer(guildId, channelId) {
|
||||
const gId = cleanId(guildId);
|
||||
const cId = cleanId(channelId);
|
||||
if (!gId || !cId) return;
|
||||
let set = this._guildPlayerIndex.get(gId);
|
||||
if (!set) { set = new Set(); this._guildPlayerIndex.set(gId, set); }
|
||||
set.add(cId);
|
||||
}
|
||||
|
||||
/** @private Remove a player from the guild-player index. @param {string} guildId @param {string} channelId */
|
||||
_unindexPlayer(guildId, channelId) {
|
||||
const gId = cleanId(guildId);
|
||||
const cId = cleanId(channelId);
|
||||
if (!gId) return;
|
||||
const set = this._guildPlayerIndex.get(gId);
|
||||
if (set) {
|
||||
set.delete(cId);
|
||||
if (set.size === 0) this._guildPlayerIndex.delete(gId);
|
||||
}
|
||||
}
|
||||
|
||||
/** Get all active (non-destroyed) players for a guild. @param {string} guildId @returns {Array<[string, Player]>} Array of [channelId, Player] pairs. */
|
||||
getGuildPlayers(guildId) {
|
||||
const gId = cleanId(guildId);
|
||||
const set = this._guildPlayerIndex.get(gId);
|
||||
if (!set) return [];
|
||||
const result = [];
|
||||
for (const channelId of set) {
|
||||
const player = this.playerMap.get(channelId);
|
||||
if (!player || player._destroyed) {
|
||||
set.delete(channelId);
|
||||
continue;
|
||||
}
|
||||
result.push([channelId, player]);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/** Find a player by both guild and channel. @param {string} guildId @param {string} channelId @returns {Player|null} */
|
||||
getPlayerByGuildAndChannel(guildId, channelId) {
|
||||
const cId = cleanId(channelId);
|
||||
const players = this.getGuildPlayers(guildId);
|
||||
for (const [mapChannelId, player] of players) {
|
||||
if (getPlayerChannelId(player, mapChannelId) === cId) return player;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Find a player by its channel ID across all guilds. @param {string} channelId @returns {Player|null} */
|
||||
getPlayerByChannelId(channelId) {
|
||||
const cId = cleanId(channelId);
|
||||
for (const [, channelSet] of this._guildPlayerIndex) {
|
||||
for (const mapChannelId of channelSet) {
|
||||
const player = this.playerMap.get(mapChannelId);
|
||||
if (player && getPlayerChannelId(player, mapChannelId) === cId) return player;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Get or spawn a player for the message's voice channel. @async @param {object} message @param {boolean} [promptJoin=true] @param {boolean} [verifyUser=true] @param {boolean} [shouldJoin=false] @returns {Promise<Player|null>} */
|
||||
async getPlayer(message, promptJoin = true, verifyUser = true, shouldJoin = false) {
|
||||
const guildId = getMessageGuildId(message);
|
||||
const cleanGuildId = cleanId(guildId);
|
||||
|
||||
const { channelId: userChannelId } = await this.checkVoiceChannels(message);
|
||||
const cleanUserChannelId = cleanId(userChannelId);
|
||||
|
||||
if (cleanUserChannelId) {
|
||||
const player = this.playerMap.get(cleanUserChannelId)
|
||||
?? this.getPlayerByGuildAndChannel(cleanGuildId, cleanUserChannelId);
|
||||
if (player) {
|
||||
player.textChannel = message.channel?.channel ?? message.channel;
|
||||
try {
|
||||
const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null;
|
||||
if (guildId && textChannelId) {
|
||||
this.settings.getServer(guildId)?.set("announcementChannelId", textChannelId);
|
||||
}
|
||||
} catch(e) {
|
||||
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
|
||||
}
|
||||
return player;
|
||||
}
|
||||
if (this._pendingJoins.has(cleanUserChannelId)) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
const serverPlayers = cleanGuildId
|
||||
? this.getGuildPlayers(cleanGuildId)
|
||||
: [];
|
||||
|
||||
if (serverPlayers.length > 0) {
|
||||
const channelList = serverPlayers.map(([chId]) => `<#${chId}>`).join(" or ");
|
||||
|
||||
if (!userChannelId) {
|
||||
if (!verifyUser) {
|
||||
const first = serverPlayers[0];
|
||||
first[1].textChannel = message.channel?.channel ?? message.channel;
|
||||
return first[1];
|
||||
}
|
||||
message.reply(this._t(message, "responses._common.noVoiceStrict"));
|
||||
return null;
|
||||
}
|
||||
|
||||
const match = serverPlayers.find(([, player]) =>
|
||||
getPlayerChannelId(player) === cleanUserChannelId
|
||||
);
|
||||
if (match) {
|
||||
match[1].textChannel = message.channel?.channel ?? message.channel;
|
||||
try {
|
||||
const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null;
|
||||
if (cleanGuildId && textChannelId) {
|
||||
this.settings.getServer(cleanGuildId)?.set("announcementChannelId", textChannelId);
|
||||
}
|
||||
} catch(e) {
|
||||
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
|
||||
}
|
||||
return match[1];
|
||||
}
|
||||
|
||||
if (shouldJoin) {
|
||||
return this.initPlayer(message, userChannelId);
|
||||
}
|
||||
|
||||
const prefix = this.commands.getPrefix(guildId);
|
||||
message.reply(this._t(message, "responses._common.alreadyInChannel", { channels: channelList, prefix }));
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!userChannelId) {
|
||||
if (shouldJoin) {
|
||||
return this.promptVC(message);
|
||||
}
|
||||
message.reply(this._t(message, "responses._common.noVoiceChannel"));
|
||||
return null;
|
||||
}
|
||||
|
||||
if (shouldJoin) {
|
||||
return this.initPlayer(message, userChannelId);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
// Attach the split-out concerns: dashboard event wiring (PlayerEventsMixin)
|
||||
// and voice-channel detection / player lifecycle (PlayerLifecycleMixin).
|
||||
applyMixins(PlayerManager, PlayerEventsMixin, PlayerLifecycleMixin);
|
||||
@@ -0,0 +1,419 @@
|
||||
/** @module src/music/audio/FluxerAudioBridge @description Audio bridge for streaming Lavalink/NodeLink audio through Fluxer voice connections. 100% in-process — Opus encoding via prism-media (native/WASM), WebM muxing via WebMOpusMuxer. No FFmpeg processes. Supports MP3/AAC/radio streams via Lavalink resolve-through. Base class: lifecycle (play/stop/destroy), state getters, volume and cleanup. Stream pipeline building and Lavalink REST HTTP helpers live in the StreamPipeline/HttpStreams mixin modules applied at the bottom of this file. */
|
||||
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { Readable } from "node:stream";
|
||||
import { applyMixins } from "../../utils/mixins.mjs";
|
||||
import StreamPipeline from "./StreamPipeline.mjs";
|
||||
import HttpStreams from "./HttpStreams.mjs";
|
||||
|
||||
/** @type {number} @description livekit TrackKind.KIND_AUDIO — publications with this kind are managed by the bridge. */
|
||||
const TRACK_KIND_AUDIO = 1;
|
||||
|
||||
/** @extends {EventEmitter} */
|
||||
export class FluxerAudioBridge extends EventEmitter {
|
||||
_conn = null;
|
||||
_stream = null;
|
||||
_encoder = null;
|
||||
_sourceStream = null;
|
||||
_sourceReq = null;
|
||||
_playing = false;
|
||||
_stopped = false;
|
||||
_startedAt = 0;
|
||||
_currentUri = null;
|
||||
_lavalink = null;
|
||||
_playGeneration = 0;
|
||||
_durationTimer = null;
|
||||
_endResolve = null;
|
||||
_endReject = null;
|
||||
_usedTrackstream = false;
|
||||
|
||||
/** @type {boolean} @description Whether audio is currently playing. */
|
||||
get playing() { return this._playing; }
|
||||
/** @type {number} @description Timestamp (ms) when playback started. */
|
||||
get startedAt() { return this._startedAt; }
|
||||
/** @type {string|null} @description URI of the currently playing track. */
|
||||
get currentUri() { return this._currentUri; }
|
||||
|
||||
/** @param {LavalinkManager|null} lavalinkManager - LavalinkManager for trackstream/loadstream. */
|
||||
constructor(lavalinkManager = null) {
|
||||
super();
|
||||
this._lavalink = lavalinkManager;
|
||||
}
|
||||
|
||||
/**
|
||||
* Play a track through a Fluxer voice connection, entirely in-process.
|
||||
* Routing order:
|
||||
* 1. trackstream passthrough (seek=0, no filters) — NodeLink hands back a WebM/Opus
|
||||
* direct URL which the voice connection plays natively (zero re-encode).
|
||||
* 2. loadstream — NodeLink returns raw PCM (48k stereo s16le) with server-side
|
||||
* seek/filters; PCM is Opus-encoded in-process and muxed to WebM.
|
||||
* 3. direct URL fallback — magic-byte sniff: WebM passthrough or Ogg/Opus remux.
|
||||
* @param {object} conn - Fluxer voice connection
|
||||
* @param {object} trackInfo - Track metadata (encoded, title, url, guildId)
|
||||
* @param {object} [options]
|
||||
* @param {number} [options.seekSeconds=0]
|
||||
* @param {number} [options.durationMs=0]
|
||||
* @param {object} [options.filterPayload]
|
||||
* @returns {Promise<"finished"|"stopped">}
|
||||
*/
|
||||
async play(conn, trackInfo, options = {}) {
|
||||
this.stop();
|
||||
if (!conn) throw new Error("[AudioBridge] No voice connection provided");
|
||||
|
||||
this._unpublishStaleAudioTracks(conn);
|
||||
|
||||
const generation = ++this._playGeneration;
|
||||
this._conn = conn;
|
||||
this._playing = true;
|
||||
this._stopped = false;
|
||||
this._startedAt = Date.now();
|
||||
this._currentUri = trackInfo?.url ?? trackInfo?.title ?? "unknown";
|
||||
this._usedTrackstream = false;
|
||||
|
||||
const seekMs = Math.floor((options.seekSeconds ?? 0) * 1000);
|
||||
let durationMs = options.durationMs || 0;
|
||||
|
||||
try {
|
||||
if (seekMs === 0 && !options.filterPayload && trackInfo.encoded && this._lavalink) {
|
||||
try {
|
||||
const direct = await this._getTrackstreamUrl(trackInfo);
|
||||
if (direct?.url && /webm|opus/i.test(direct.format || "")) {
|
||||
this._usedTrackstream = true;
|
||||
logger.player("[AudioBridge] Passthrough webm/opus via trackstream (zero-copy): " + (trackInfo.title || "unknown"));
|
||||
|
||||
await conn.play(direct.url);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
if (durationMs > 0) await this._waitDuration(durationMs);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
if (this._playing && !this._stopped) {
|
||||
this._playing = false;
|
||||
logger.player("[AudioBridge] Track finished naturally (trackstream passthrough)");
|
||||
return "finished";
|
||||
}
|
||||
return "stopped";
|
||||
}
|
||||
if (direct?.url && this._lavalink && trackInfo.url && trackInfo.url.startsWith("http")) {
|
||||
logger.player("[AudioBridge] trackstream format " + (direct.format || "?") + " — resolving original source URL via Lavalink for fresh encoded track...");
|
||||
const freshEncoded = await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId);
|
||||
if (freshEncoded) {
|
||||
trackInfo.encoded = freshEncoded;
|
||||
logger.player("[AudioBridge] Fresh encoded track obtained — retrying trackstream for webm/opus...");
|
||||
try {
|
||||
const freshDirect = await this._getTrackstreamUrl(trackInfo);
|
||||
if (freshDirect?.url && /webm|opus/i.test(freshDirect.format || "")) {
|
||||
this._usedTrackstream = true;
|
||||
logger.player("[AudioBridge] Fresh trackstream is webm/opus — zero-copy passthrough: " + (trackInfo.title || "unknown"));
|
||||
await conn.play(freshDirect.url);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
if (durationMs > 0) await this._waitDuration(durationMs);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
if (this._playing && !this._stopped) {
|
||||
this._playing = false;
|
||||
logger.player("[AudioBridge] Track finished naturally (fresh trackstream passthrough)");
|
||||
return "finished";
|
||||
}
|
||||
return "stopped";
|
||||
}
|
||||
logger.player("[AudioBridge] Fresh trackstream also " + (freshDirect?.format || "?") + ", falling through to loadstream");
|
||||
} catch (e2) {
|
||||
logger.player("[AudioBridge] Fresh trackstream failed, falling through to loadstream: " + e2.message);
|
||||
}
|
||||
} else {
|
||||
logger.player("[AudioBridge] Could not resolve source URL via Lavalink, using original encoded track for loadstream");
|
||||
}
|
||||
} else {
|
||||
logger.player("[AudioBridge] trackstream format not opus/webm (" + (direct?.format || "?") + "), falling through to loadstream");
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[AudioBridge] Trackstream failed, falling back to loadstream: " + e.message);
|
||||
this._playing = true;
|
||||
this._stopped = false;
|
||||
this._startedAt = Date.now();
|
||||
}
|
||||
}
|
||||
|
||||
if (trackInfo.encoded && this._lavalink) {
|
||||
const loaded = await this._streamFromLoadstream(trackInfo, seekMs, options.filterPayload);
|
||||
if (generation !== this._playGeneration) {
|
||||
loaded.stream.destroy();
|
||||
return "stopped";
|
||||
}
|
||||
|
||||
const routed = await this._routeByMagic(loaded.stream);
|
||||
this._sourceStream = loaded.stream;
|
||||
this._sourceReq = loaded.req || null;
|
||||
|
||||
if (routed.kind === "webm") {
|
||||
logger.player("[AudioBridge] Playing loadstream webm/opus passthrough: " + (trackInfo.title || "unknown") +
|
||||
(seekMs > 0 ? " [seek: " + seekMs + "ms]" : ""));
|
||||
this._stream = routed.stream;
|
||||
await conn.play(routed.stream);
|
||||
} else if (routed.kind === "ogg") {
|
||||
logger.player("[AudioBridge] Playing loadstream ogg/opus (remux to webm): " + (trackInfo.title || "unknown"));
|
||||
const oggResult = await this._remuxOggToWebM(routed.stream);
|
||||
this._stream = oggResult;
|
||||
if (durationMs <= 0) durationMs = oggResult.getDurationMs();
|
||||
await conn.play(this._stream);
|
||||
} else {
|
||||
logger.player("[AudioBridge] Playing via loadstream PCM -> in-process Opus: " + (trackInfo.title || "unknown") +
|
||||
(seekMs > 0 ? " [seek: " + seekMs + "ms]" : "") +
|
||||
(options.filterPayload ? " [filters]" : ""));
|
||||
this._stream = this._buildPcmPipeline(routed.stream);
|
||||
await conn.play(this._stream);
|
||||
}
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
await this._awaitEnd(durationMs);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
if (this._playing && !this._stopped) {
|
||||
this._playing = false;
|
||||
logger.player("[AudioBridge] Track finished naturally (loadstream)");
|
||||
return "finished";
|
||||
}
|
||||
return "stopped";
|
||||
}
|
||||
|
||||
if (trackInfo.url && trackInfo.url.startsWith("http")) {
|
||||
logger.player("[AudioBridge] Route 3: Fetching directly: " + trackInfo.url.substring(0, 80) + "...");
|
||||
const response = await fetch(trackInfo.url, {
|
||||
headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)" },
|
||||
redirect: "follow",
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error("HTTP " + response.status + " for " + trackInfo.url);
|
||||
}
|
||||
const stream = Readable.fromWeb(response.body);
|
||||
this._sourceStream = stream;
|
||||
|
||||
const routed = await this._routeByMagic(stream);
|
||||
if (routed.kind === "webm") {
|
||||
logger.player("[AudioBridge] Route 3a: webm/opus passthrough: " + (trackInfo.title || "unknown"));
|
||||
this._stream = routed.stream;
|
||||
await conn.play(routed.stream);
|
||||
} else if (routed.kind === "ogg") {
|
||||
logger.player("[AudioBridge] Route 3b: ogg/opus remux to webm: " + (trackInfo.title || "unknown"));
|
||||
const oggResult = await this._remuxOggToWebM(routed.stream);
|
||||
this._stream = oggResult;
|
||||
await conn.play(this._stream);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
await new Promise(r => {
|
||||
if (this._stream.readableEnded) return r();
|
||||
const done = () => { this._stream.off("end", done); this._stream.off("close", done); r(); };
|
||||
this._stream.once("end", done);
|
||||
this._stream.once("close", done);
|
||||
});
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
const fullDurationMs = oggResult.getDurationMs();
|
||||
const elapsedMs = Date.now() - this._startedAt;
|
||||
const remainingMs = Math.max(0, fullDurationMs - elapsedMs);
|
||||
logger.player("[AudioBridge] Route 3b: OGG " + fullDurationMs + "ms total, " + elapsedMs + "ms elapsed, waiting " + remainingMs + "ms more");
|
||||
|
||||
if (remainingMs > 0) await this._awaitEnd(remainingMs);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
if (this._playing && !this._stopped) {
|
||||
this._playing = false;
|
||||
logger.player("[AudioBridge] Track finished naturally (direct URL, OGG remux)");
|
||||
return "finished";
|
||||
}
|
||||
return "stopped";
|
||||
} else {
|
||||
stream.destroy();
|
||||
this._sourceStream = null;
|
||||
logger.player("[AudioBridge] Route 3c: Direct stream is " + routed.kind + " (MP3/AAC?) — resolving through Lavalink...");
|
||||
|
||||
if (this._lavalink) {
|
||||
const encoded = await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId);
|
||||
if (encoded) {
|
||||
trackInfo.encoded = encoded;
|
||||
logger.player("[AudioBridge] Route 3c: Got encoded track from Lavalink, retrying via loadstream...");
|
||||
const loaded = await this._streamFromLoadstream(trackInfo, 0, null);
|
||||
if (generation !== this._playGeneration) {
|
||||
loaded.stream.destroy();
|
||||
return "stopped";
|
||||
}
|
||||
|
||||
const routed2 = await this._routeByMagic(loaded.stream);
|
||||
this._sourceStream = loaded.stream;
|
||||
this._sourceReq = loaded.req || null;
|
||||
|
||||
if (routed2.kind === "webm") {
|
||||
logger.player("[AudioBridge] Route 3c (Lavalink): webm/opus passthrough");
|
||||
this._stream = routed2.stream;
|
||||
await conn.play(routed2.stream);
|
||||
} else if (routed2.kind === "ogg") {
|
||||
logger.player("[AudioBridge] Route 3c (Lavalink): ogg/opus remux to webm");
|
||||
const oggResult3c = await this._remuxOggToWebM(routed2.stream);
|
||||
this._stream = oggResult3c;
|
||||
if (durationMs <= 0) durationMs = oggResult3c.getDurationMs();
|
||||
await conn.play(this._stream);
|
||||
} else {
|
||||
logger.player("[AudioBridge] Route 3c (Lavalink): PCM -> Opus -> WebM");
|
||||
this._stream = this._buildPcmPipeline(routed2.stream);
|
||||
await conn.play(this._stream);
|
||||
}
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
await this._awaitEnd(durationMs);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
if (this._playing && !this._stopped) {
|
||||
this._playing = false;
|
||||
logger.player("[AudioBridge] Track finished naturally (Route 3c Lavalink resolve)");
|
||||
return "finished";
|
||||
}
|
||||
return "stopped";
|
||||
}
|
||||
}
|
||||
|
||||
throw new Error(
|
||||
"[AudioBridge] Direct URL is not WebM/Opus or Ogg/Opus (" + routed.kind + "). " +
|
||||
"Lavalink resolve also failed or is unavailable. " +
|
||||
"Make sure your Lavalink/NodeLink node is running and can decode this stream format."
|
||||
);
|
||||
}
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
await this._awaitEnd(durationMs);
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
|
||||
if (this._playing && !this._stopped) {
|
||||
this._playing = false;
|
||||
logger.player("[AudioBridge] Track finished naturally (direct URL)");
|
||||
return "finished";
|
||||
}
|
||||
return "stopped";
|
||||
}
|
||||
|
||||
throw new Error("Could not get audio stream for: " + (trackInfo.title || trackInfo.url || "unknown"));
|
||||
|
||||
} catch (e) {
|
||||
if (generation !== this._playGeneration) return "stopped";
|
||||
if (this._stopped || !this._playing) return "stopped";
|
||||
this._playing = false;
|
||||
logger.error("[AudioBridge] Playback error: " + e.message);
|
||||
throw e;
|
||||
} finally {
|
||||
this._cleanup();
|
||||
}
|
||||
}
|
||||
|
||||
/** Stop current playback and clean up resources. */
|
||||
stop() {
|
||||
const wasPlaying = this._playing;
|
||||
this._stopped = true;
|
||||
this._playing = false;
|
||||
this._playGeneration++;
|
||||
|
||||
this._cleanup();
|
||||
|
||||
if (this._conn) {
|
||||
try { this._conn.stop(); } catch (_) {}
|
||||
this._unpublishStaleAudioTracks(this._conn);
|
||||
}
|
||||
|
||||
if (wasPlaying) {
|
||||
this.emit("stopped");
|
||||
logger.player("[AudioBridge] Playback stopped");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {object} conn - Fluxer voice connection
|
||||
* @param {string|null} [keepSid=null] - Track SID to keep (currently active publication)
|
||||
* @private
|
||||
*/
|
||||
_unpublishStaleAudioTracks(conn, keepSid = null) {
|
||||
try {
|
||||
const room = conn?.room;
|
||||
const participant = room?.localParticipant;
|
||||
if (!room?.isConnected || typeof participant?.unpublishTrack !== "function") return;
|
||||
|
||||
const publications = participant.trackPublications;
|
||||
if (!publications || typeof publications.entries !== "function") return;
|
||||
|
||||
for (const [sid, pub] of publications.entries()) {
|
||||
if (keepSid && sid === keepSid) continue;
|
||||
if (pub?.kind !== TRACK_KIND_AUDIO) continue;
|
||||
try {
|
||||
const p = participant.unpublishTrack(sid, true);
|
||||
if (p?.catch) p.catch(() => {});
|
||||
logger.player("[AudioBridge] Unpublished stale audio track: " + sid);
|
||||
} catch (_) {}
|
||||
}
|
||||
} catch (_) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the playback volume on the voice connection.
|
||||
* @param {number} percent - Volume 0–100.
|
||||
*/
|
||||
setVolume(percent) {
|
||||
if (this._conn) {
|
||||
try { this._conn.setVolume(percent); } catch (e) {
|
||||
logger.warn("[AudioBridge] setVolume error: " + e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @returns {number} Current volume percentage (0–100). */
|
||||
getVolume() {
|
||||
if (this._conn) {
|
||||
try { return this._conn.getVolume(); } catch (_) {}
|
||||
}
|
||||
return 100;
|
||||
}
|
||||
|
||||
/** @returns {boolean} Whether the voice connection is currently active. */
|
||||
isConnected() {
|
||||
if (this._conn) {
|
||||
try { return this._conn.isConnected(); } catch (_) {}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear timers, settle pending waits, and tear down the pipeline.
|
||||
* @private
|
||||
*/
|
||||
_cleanup() {
|
||||
if (this._durationTimer) { clearTimeout(this._durationTimer); this._durationTimer = null; }
|
||||
if (this._endResolve) {
|
||||
const resolve = this._endResolve;
|
||||
this._endResolve = null;
|
||||
this._endReject = null;
|
||||
resolve();
|
||||
}
|
||||
for (const s of [this._stream, this._encoder, this._sourceStream]) {
|
||||
if (s) {
|
||||
try { s.destroy(); } catch (_) {}
|
||||
}
|
||||
}
|
||||
if (this._sourceReq) {
|
||||
try { this._sourceReq.destroy(); } catch (_) {}
|
||||
}
|
||||
this._stream = null;
|
||||
this._encoder = null;
|
||||
this._sourceStream = null;
|
||||
this._sourceReq = null;
|
||||
}
|
||||
|
||||
/** Stop playback, release the voice connection, and remove all listeners. */
|
||||
destroy() {
|
||||
this.stop();
|
||||
this._conn = null;
|
||||
this._currentUri = null;
|
||||
this.removeAllListeners();
|
||||
}
|
||||
}
|
||||
|
||||
// Attach the split-out concerns: stream pipeline building/routing
|
||||
// (StreamPipeline) and Lavalink REST HTTP helpers (HttpStreams).
|
||||
applyMixins(FluxerAudioBridge, StreamPipeline, HttpStreams);
|
||||
@@ -0,0 +1,185 @@
|
||||
/**
|
||||
* @module src/music/audio/HttpStreams
|
||||
* @description HTTP helper concern for {@link FluxerAudioBridge}: GET-JSON
|
||||
* with redirect following and streaming GET with connect/idle timeouts,
|
||||
* used for the Lavalink/NodeLink REST endpoints (trackstream, loadstream,
|
||||
* loadtracks).
|
||||
*
|
||||
* These methods are applied onto the FluxerAudioBridge class prototype via
|
||||
* {@link module:src/utils/mixins.applyMixins} — `this` is a
|
||||
* FluxerAudioBridge instance.
|
||||
*/
|
||||
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
import http from "node:http";
|
||||
import https from "node:https";
|
||||
|
||||
/** @type {number} @description Maximum number of HTTP redirect hops to follow. */
|
||||
const MAX_REDIRECTS = 5;
|
||||
|
||||
/** @type {number} @description Timeout (ms) for HTTP requests to Lavalink REST endpoints (trackstream, loadtracks JSON). */
|
||||
const REST_REQUEST_TIMEOUT_MS = 15_000;
|
||||
|
||||
/** @type {number} @description Timeout (ms) to wait for the first byte from loadstream (Lavalink may need time to resolve HLS/external streams). */
|
||||
const LOADSTREAM_CONNECT_TIMEOUT_MS = 60_000;
|
||||
|
||||
/** @type {number} @description Idle timeout (ms) once loadstream data is flowing — if no data arrives for this long, abort. */
|
||||
const LOADSTREAM_IDLE_TIMEOUT_MS = 30_000;
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
* @description HTTP streams mixin — applied to FluxerAudioBridge.
|
||||
*/
|
||||
const HttpStreams = {
|
||||
/**
|
||||
* @param {string} url
|
||||
* @param {object} [headers]
|
||||
* @returns {Promise<object>}
|
||||
* @private
|
||||
*/
|
||||
_httpGetJson(url, headers = {}, _redirectCount = 0, timeoutMs = REST_REQUEST_TIMEOUT_MS) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (_redirectCount >= MAX_REDIRECTS) {
|
||||
return reject(new Error("Too many redirects (" + _redirectCount + ")"));
|
||||
}
|
||||
const urlObj = new URL(url);
|
||||
const client = urlObj.protocol === "https:" ? https : http;
|
||||
|
||||
const req = client.request({
|
||||
protocol: urlObj.protocol,
|
||||
host: urlObj.hostname,
|
||||
port: urlObj.port,
|
||||
path: urlObj.pathname + urlObj.search,
|
||||
method: "GET",
|
||||
headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)", ...headers },
|
||||
}, (res) => {
|
||||
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
||||
res.resume();
|
||||
let loc = res.headers.location;
|
||||
if (loc.startsWith("/")) loc = urlObj.protocol + "//" + urlObj.host + loc;
|
||||
return this._httpGetJson(loc, headers, _redirectCount + 1, timeoutMs).then(resolve, reject);
|
||||
}
|
||||
if (res.statusCode !== 200) {
|
||||
let body = "";
|
||||
res.on("data", (chunk) => { body += chunk; });
|
||||
res.on("end", () => {
|
||||
reject(new Error("HTTP " + res.statusCode + " for " + url + ": " + body.substring(0, 300)));
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
let data = "";
|
||||
res.on("data", (chunk) => { data += chunk; });
|
||||
res.on("end", () => {
|
||||
try {
|
||||
resolve(JSON.parse(data));
|
||||
} catch (e) {
|
||||
reject(new Error("Invalid JSON from trackstream: " + data.substring(0, 200)));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
req.on("socket", (socket) => {
|
||||
socket.on("error", () => {});
|
||||
});
|
||||
req.on("error", reject);
|
||||
req.setTimeout(timeoutMs, () => {
|
||||
req.destroy();
|
||||
reject(new Error("REST request timeout (" + timeoutMs / 1000 + "s)"));
|
||||
});
|
||||
req.end();
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* @param {string} url
|
||||
* @param {object} [headers]
|
||||
* @param {number} [_redirectCount=0]
|
||||
* @returns {Promise<{stream: Readable, inputFormat: string|null, req: http.ClientRequest}>}
|
||||
* @private
|
||||
*/
|
||||
_httpRequestStream(url, headers = {}, _redirectCount = 0) {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (_redirectCount >= MAX_REDIRECTS) {
|
||||
return reject(new Error("Too many redirects (" + _redirectCount + ")"));
|
||||
}
|
||||
|
||||
const urlObj = new URL(url);
|
||||
const client = urlObj.protocol === "https:" ? https : http;
|
||||
let firstByte = true;
|
||||
let connectTimer = null;
|
||||
let idleTimer = null;
|
||||
|
||||
const resetIdleTimeout = () => {
|
||||
if (idleTimer) clearTimeout(idleTimer);
|
||||
idleTimer = setTimeout(() => {
|
||||
req.destroy();
|
||||
reject(new Error("loadstream idle timeout (" + LOADSTREAM_IDLE_TIMEOUT_MS / 1000 + "s no data)"));
|
||||
}, LOADSTREAM_IDLE_TIMEOUT_MS);
|
||||
idleTimer.unref?.();
|
||||
};
|
||||
|
||||
const req = client.request({
|
||||
protocol: urlObj.protocol,
|
||||
host: urlObj.hostname,
|
||||
port: urlObj.port,
|
||||
path: urlObj.pathname + urlObj.search,
|
||||
method: "GET",
|
||||
headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)", ...headers },
|
||||
}, (res) => {
|
||||
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
|
||||
if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; }
|
||||
res.resume();
|
||||
let nextHeaders = headers;
|
||||
let loc = res.headers.location;
|
||||
if (loc.startsWith("/")) loc = urlObj.protocol + "//" + urlObj.host + loc;
|
||||
try {
|
||||
const redirectHost = new URL(loc).hostname;
|
||||
if (redirectHost !== urlObj.hostname) {
|
||||
const { Authorization, "Session-Id": _, ...safe } = headers;
|
||||
nextHeaders = safe;
|
||||
}
|
||||
} catch (_) {}
|
||||
return this._httpRequestStream(loc, nextHeaders, _redirectCount + 1).then(resolve, reject);
|
||||
}
|
||||
if (res.statusCode !== 200) {
|
||||
if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; }
|
||||
let body = "";
|
||||
res.on("data", (chunk) => { body += chunk; });
|
||||
res.on("end", () => {
|
||||
reject(new Error("HTTP " + res.statusCode + " for " + url + ": " + body.substring(0, 300)));
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; }
|
||||
resetIdleTimeout();
|
||||
res.once("data", () => resetIdleTimeout());
|
||||
|
||||
logger.player("[AudioBridge] loadstream response: " + res.statusCode + " content-type=" + (res.headers["content-type"] || "?"));
|
||||
resolve({ stream: res, inputFormat: res.headers["content-type"] || null, req });
|
||||
});
|
||||
|
||||
req.on("socket", (socket) => {
|
||||
socket.on("error", () => {});
|
||||
});
|
||||
|
||||
req.on("error", (err) => {
|
||||
if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; }
|
||||
if (idleTimer) { clearTimeout(idleTimer); idleTimer = null; }
|
||||
reject(err);
|
||||
});
|
||||
|
||||
connectTimer = setTimeout(() => {
|
||||
req.destroy();
|
||||
reject(new Error("loadstream connect timeout (" + LOADSTREAM_CONNECT_TIMEOUT_MS / 1000 + "s — Lavalink took too long to start stream)"));
|
||||
}, LOADSTREAM_CONNECT_TIMEOUT_MS);
|
||||
connectTimer.unref?.();
|
||||
|
||||
req.end();
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
export default HttpStreams;
|
||||
export { HttpStreams };
|
||||
@@ -0,0 +1,326 @@
|
||||
/**
|
||||
* @module src/music/audio/StreamPipeline
|
||||
* @description Stream pipeline concern for {@link FluxerAudioBridge}:
|
||||
* end-of-playback waiting, magic-byte routing, the in-process PCM -> Opus ->
|
||||
* WebM pipeline, Ogg/Opus remuxing, trackstream/loadstream URL handling and
|
||||
* Lavalink URL resolution.
|
||||
*
|
||||
* These methods are applied onto the FluxerAudioBridge class prototype via
|
||||
* {@link module:src/utils/mixins.applyMixins} — `this` is a
|
||||
* FluxerAudioBridge instance.
|
||||
*/
|
||||
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
import { WebMOpusMuxer, OPUS_FRAME_MS } from "./WebMOpusMuxer.mjs";
|
||||
import prismMedia from "prism-media";
|
||||
|
||||
const { Encoder: PrismOpusEncoder, OggDemuxer: PrismOggDemuxer } = prismMedia.opus;
|
||||
|
||||
/** @type {number} @description PCM sample rate expected from NodeLink loadstream (48kHz stereo s16le). */
|
||||
const PCM_RATE = 48000;
|
||||
/** @type {number} @description PCM channel count expected from NodeLink loadstream. */
|
||||
const PCM_CHANNELS = 2;
|
||||
/** @type {number} @description Opus frame size in samples per channel (20ms @ 48kHz). */
|
||||
const PCM_FRAME_SIZE = 960;
|
||||
/** @type {number} @description Opus encoding bitrate. */
|
||||
const OPUS_BITRATE = 128000;
|
||||
|
||||
/** @type {Buffer} @description WebM/Matroska EBML magic bytes. */
|
||||
const WEBM_MAGIC = Buffer.from([0x1a, 0x45, 0xdf, 0xa3]);
|
||||
/** @type {Buffer} @description OGG container magic bytes ("OggS"). */
|
||||
const OGG_MAGIC = Buffer.from("OggS", "ascii");
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
* @description Stream pipeline mixin — applied to FluxerAudioBridge.
|
||||
*/
|
||||
const StreamPipeline = {
|
||||
/**
|
||||
* Wait for playback end: duration timer for fixed-length tracks, pipeline
|
||||
* end event for live/radio streams (durationMs = 0). Rejects early on
|
||||
* pipeline errors so the player can skip to the next track.
|
||||
* @param {number} durationMs
|
||||
* @returns {Promise<void>}
|
||||
* @private
|
||||
*/
|
||||
_awaitEnd(durationMs) { return new Promise((resolve, reject) => {
|
||||
this._endResolve = resolve;
|
||||
this._endReject = reject;
|
||||
const failFast = (err) => {
|
||||
if (this._playing && !this._stopped) {
|
||||
this._playing = false;
|
||||
reject(err);
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
|
||||
if (durationMs > 0) {
|
||||
this._durationTimer = setTimeout(resolve, durationMs);
|
||||
} else {
|
||||
const stream = this._stream;
|
||||
if (!stream) return resolve();
|
||||
const onEnd = () => resolve();
|
||||
stream.once("end", onEnd);
|
||||
stream.once("close", onEnd);
|
||||
stream.once("error", failFast);
|
||||
}
|
||||
|
||||
if (this._sourceStream) {
|
||||
this._sourceStream.once("error", failFast);
|
||||
}
|
||||
if (this._encoder) {
|
||||
this._encoder.once("error", failFast);
|
||||
}
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Simple timed wait used by the trackstream passthrough route (no local
|
||||
* pipeline to watch). Resolves early if stopped.
|
||||
* @param {number} durationMs
|
||||
* @returns {Promise<void>}
|
||||
* @private
|
||||
*/
|
||||
_waitDuration(durationMs) {
|
||||
return new Promise((resolve) => {
|
||||
const timer = setTimeout(() => {
|
||||
this._durationTimer = null;
|
||||
resolve();
|
||||
}, durationMs);
|
||||
this._durationTimer = timer;
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Peek at the first bytes of a stream and classify it, pushing the peeked
|
||||
* bytes back so nothing is lost.
|
||||
* @param {Readable} stream
|
||||
* @returns {Promise<{stream: Readable, kind: "webm"|"ogg"|"pcm"}>}
|
||||
* @private
|
||||
*/
|
||||
async _routeByMagic(stream) {
|
||||
const head = await this._peek(stream, 4);
|
||||
if (head.length >= 4 && head.subarray(0, 4).equals(WEBM_MAGIC)) return { stream, kind: "webm" };
|
||||
if (head.length >= 4 && head.subarray(0, 4).equals(OGG_MAGIC)) return { stream, kind: "ogg" };
|
||||
return { stream, kind: "pcm" };
|
||||
},
|
||||
|
||||
/**
|
||||
* Read up to `n` bytes from a paused-mode stream, then unshift them.
|
||||
* @param {Readable} stream
|
||||
* @param {number} n
|
||||
* @returns {Promise<Buffer>}
|
||||
* @private
|
||||
*/
|
||||
_peek(stream, n) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const tryRead = () => {
|
||||
const chunks = [];
|
||||
let total = 0;
|
||||
let chunk;
|
||||
while (total < n && (chunk = stream.read()) !== null) {
|
||||
chunks.push(chunk);
|
||||
total += chunk.length;
|
||||
}
|
||||
if (total >= n || stream.readableEnded) {
|
||||
const buf = Buffer.concat(chunks);
|
||||
cleanup();
|
||||
if (buf.length > 0) stream.unshift(buf);
|
||||
resolve(buf.subarray(0, n));
|
||||
return;
|
||||
}
|
||||
};
|
||||
const onReadable = () => { cleanup(); tryRead(); };
|
||||
const onEnd = () => { cleanup(); tryRead(); };
|
||||
const onError = (err) => { cleanup(); reject(err); };
|
||||
const cleanup = () => {
|
||||
stream.off("readable", onReadable);
|
||||
stream.off("end", onEnd);
|
||||
stream.off("error", onError);
|
||||
};
|
||||
stream.once("readable", onReadable);
|
||||
stream.once("end", onEnd);
|
||||
stream.once("error", onError);
|
||||
tryRead();
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Build the in-process PCM -> Opus -> WebM pipeline.
|
||||
* @param {Readable} pcmStream - s16le 48kHz stereo byte stream
|
||||
* @returns {WebMOpusMuxer} - byte stream consumable by conn.play()
|
||||
* @private
|
||||
*/
|
||||
_buildPcmPipeline(pcmStream) {
|
||||
let encoder;
|
||||
try {
|
||||
encoder = new PrismOpusEncoder({
|
||||
rate: PCM_RATE,
|
||||
channels: PCM_CHANNELS,
|
||||
frameSize: PCM_FRAME_SIZE,
|
||||
});
|
||||
} catch (e) {
|
||||
pcmStream.destroy();
|
||||
throw new Error(
|
||||
"No Opus encoder available (" + e.message + "). Install one: npm install opusscript"
|
||||
);
|
||||
}
|
||||
try { encoder.setBitrate(OPUS_BITRATE); } catch (_) {}
|
||||
|
||||
const muxer = new WebMOpusMuxer({ sampleRate: PCM_RATE, channels: PCM_CHANNELS });
|
||||
this._encoder = encoder;
|
||||
|
||||
pcmStream.on("error", (err) => {
|
||||
logger.warn("[AudioBridge] PCM source error: " + err.message);
|
||||
encoder.destroy(err);
|
||||
});
|
||||
encoder.on("error", (err) => {
|
||||
muxer.destroy(err);
|
||||
});
|
||||
|
||||
pcmStream.pipe(encoder).pipe(muxer);
|
||||
return muxer;
|
||||
},
|
||||
|
||||
/**
|
||||
* Remux an Ogg/Opus stream into WebM/Opus (packet-level, no re-encode).
|
||||
* @param {Readable} oggStream
|
||||
* @returns {Promise<{stream: WebMOpusMuxer, getDurationMs: function}>}
|
||||
* @private
|
||||
*/
|
||||
async _remuxOggToWebM(oggStream) {
|
||||
const demuxer = new PrismOggDemuxer();
|
||||
const muxer = new WebMOpusMuxer();
|
||||
oggStream.on("error", (err) => demuxer.destroy(err));
|
||||
demuxer.on("error", (err) => muxer.destroy(err));
|
||||
let frameCount = 0;
|
||||
demuxer.on("data", () => { frameCount++; });
|
||||
const headPromise = new Promise((resolve, reject) => {
|
||||
demuxer.once("head", () => resolve());
|
||||
demuxer.once("error", (err) => reject(new Error("OGG demux: " + err.message)));
|
||||
oggStream.once("error", (err) => reject(new Error("OGG source: " + err.message)));
|
||||
});
|
||||
oggStream.pipe(demuxer).pipe(muxer);
|
||||
await headPromise;
|
||||
const wrapper = Object.create(muxer);
|
||||
wrapper.getDurationMs = () => frameCount * OPUS_FRAME_MS;
|
||||
return wrapper;
|
||||
},
|
||||
|
||||
/**
|
||||
* @param {object} trackInfo
|
||||
* @returns {Promise<{url: string, format: string}>}
|
||||
* @private
|
||||
*/
|
||||
async _getTrackstreamUrl(trackInfo) {
|
||||
const nlInfo = this._lavalink.getNodeLinkInfo?.();
|
||||
if (!nlInfo) throw new Error("NodeLink info not available");
|
||||
|
||||
const protocol = nlInfo.secure ? "https" : "http";
|
||||
const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port;
|
||||
|
||||
const headers = { "Authorization": nlInfo.password };
|
||||
if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId;
|
||||
if (trackInfo.guildId) headers["Guild-Id"] = trackInfo.guildId;
|
||||
|
||||
const params = "encodedTrack=" + encodeURIComponent(trackInfo.encoded);
|
||||
const url = baseUrl + "/v4/trackstream?" + params;
|
||||
|
||||
logger.player("[AudioBridge] Querying /v4/trackstream...");
|
||||
|
||||
const body = await this._httpGetJson(url, headers);
|
||||
|
||||
const directUrl = body?.url;
|
||||
if (!directUrl || typeof directUrl !== "string") {
|
||||
throw new Error("trackstream returned no URL");
|
||||
}
|
||||
|
||||
const format = body?.format || "";
|
||||
logger.player("[AudioBridge] trackstream: format=" + format + " url=" + directUrl.substring(0, 100) + "...");
|
||||
|
||||
return { url: directUrl, format };
|
||||
},
|
||||
|
||||
/**
|
||||
* @param {object} trackInfo
|
||||
* @param {number} [seekMs=0]
|
||||
* @param {object|null} [filterPayload]
|
||||
* @returns {Promise<{stream: Readable, inputFormat: string|null}>}
|
||||
* @private
|
||||
*/
|
||||
async _streamFromLoadstream(trackInfo, seekMs = 0, filterPayload = null) {
|
||||
const nlInfo = this._lavalink.getNodeLinkInfo?.();
|
||||
if (!nlInfo) {
|
||||
throw new Error("NodeLink info not available");
|
||||
}
|
||||
|
||||
const protocol = nlInfo.secure ? "https" : "http";
|
||||
const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port;
|
||||
|
||||
const headers = { "Authorization": nlInfo.password };
|
||||
if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId;
|
||||
if (trackInfo.guildId) headers["Guild-Id"] = trackInfo.guildId;
|
||||
|
||||
let baseParams = "encodedTrack=" + encodeURIComponent(trackInfo.encoded) + "&position=" + seekMs + "&volume=100";
|
||||
if (filterPayload) {
|
||||
baseParams += "&filters=" + encodeURIComponent(JSON.stringify(filterPayload));
|
||||
}
|
||||
|
||||
const url = baseUrl + "/v4/loadstream?" + baseParams;
|
||||
logger.player("[AudioBridge] Querying /v4/loadstream (seek: " + seekMs + "ms)...");
|
||||
|
||||
return this._httpRequestStream(url, headers);
|
||||
},
|
||||
|
||||
/**
|
||||
* Resolve a direct audio URL through Lavalink's /v4/loadtracks to get an encoded track.
|
||||
* This allows MP3/AAC radio streams and direct audio URLs to be played through
|
||||
* the loadstream pipeline without any FFmpeg dependency.
|
||||
* @param {string} url - The HTTP(S) audio stream URL to resolve.
|
||||
* @param {string} [guildId] - Optional guild ID for the request.
|
||||
* @returns {Promise<string|null>} The encoded track string, or null if resolution failed.
|
||||
* @private
|
||||
*/
|
||||
async _resolveUrlViaLavalink(url, guildId) {
|
||||
try {
|
||||
const nlInfo = this._lavalink.getNodeLinkInfo?.();
|
||||
if (!nlInfo) {
|
||||
logger.warn("[AudioBridge] _resolveUrlViaLavalink: no NodeLink info");
|
||||
return null;
|
||||
}
|
||||
|
||||
const protocol = nlInfo.secure ? "https" : "http";
|
||||
const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port;
|
||||
|
||||
const headers = { "Authorization": nlInfo.password };
|
||||
if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId;
|
||||
if (guildId) headers["Guild-Id"] = guildId;
|
||||
|
||||
const params = "identifier=" + encodeURIComponent(url);
|
||||
const loadtracksUrl = baseUrl + "/v4/loadtracks?" + params;
|
||||
|
||||
logger.player("[AudioBridge] Resolving URL via Lavalink /v4/loadtracks: " + url.substring(0, 80) + "...");
|
||||
|
||||
const body = await this._httpGetJson(loadtracksUrl, headers, 0, 30_000);
|
||||
|
||||
const track = body?.data?.tracks?.[0] ?? body?.tracks?.[0] ?? body?.data;
|
||||
const encoded = track?.encoded ?? track?.data;
|
||||
|
||||
if (encoded && typeof encoded === "string") {
|
||||
logger.player("[AudioBridge] Lavalink resolved URL to encoded track successfully");
|
||||
return encoded;
|
||||
}
|
||||
|
||||
const loadType = body?.loadType ?? body?.data?.loadType;
|
||||
logger.warn("[AudioBridge] Lavalink loadtracks returned no playable track (loadType=" + loadType + ")");
|
||||
return null;
|
||||
} catch (e) {
|
||||
logger.warn("[AudioBridge] _resolveUrlViaLavalink failed: " + e.message);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export default StreamPipeline;
|
||||
export { StreamPipeline };
|
||||
@@ -0,0 +1,107 @@
|
||||
/** @module constants/audio/Tuna */
|
||||
|
||||
import pkg from "follow-redirects";
|
||||
const { https } = pkg;
|
||||
|
||||
/**
|
||||
* Client for the Tuna (Voicemod) sound-effect API.
|
||||
* @class
|
||||
*/
|
||||
class Tuna {
|
||||
/** @private */ apiKey = null;
|
||||
|
||||
/**
|
||||
* @param {{ key: string }} auth - Object containing the API key.
|
||||
*/
|
||||
constructor(auth) {
|
||||
this.apiKey = auth.key;
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform an authenticated GET request to the Tuna API.
|
||||
* @private
|
||||
* @async
|
||||
* @param {string} path - API path (e.g. `"/v1/sounds/search"`).
|
||||
* @param {Object<string, *>} [params={}] - Query-string parameters.
|
||||
* @returns {Promise<object>} Parsed JSON response.
|
||||
*/
|
||||
get(path, params = {}) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const qs = new URLSearchParams(params).toString();
|
||||
const query = qs ? "?" + qs : "";
|
||||
const options = {
|
||||
method: "GET",
|
||||
hostname: "tuna-api.voicemod.net",
|
||||
path: path + query,
|
||||
headers: { "x-api-key": this.apiKey },
|
||||
maxRedirects: 20
|
||||
};
|
||||
const req = https.request(options, (res) => {
|
||||
const chunks = [];
|
||||
res.on("data", (chunk) => { chunks.push(chunk); });
|
||||
res.on("end", () => {
|
||||
try {
|
||||
resolve(JSON.parse(Buffer.concat(chunks).toString()));
|
||||
} catch (e) {
|
||||
reject(new Error(`Tuna API JSON parse error: ${e.message}`));
|
||||
}
|
||||
});
|
||||
});
|
||||
req.on("error", (error) => { reject(error); });
|
||||
req.setTimeout(15_000, () => {
|
||||
req.destroy();
|
||||
reject(new Error("Tuna API request timeout"));
|
||||
});
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for sound effects. Each result item gains a `download()` method
|
||||
* that returns the OGG audio stream.
|
||||
* @async
|
||||
* @param {string} query - Search term.
|
||||
* @param {number} [page=1]
|
||||
* @param {number} [size=10]
|
||||
* @returns {Promise<object>} Search results with enriched `items` array.
|
||||
*/
|
||||
search(query, page = 1, size = 10) {
|
||||
return this.get("/v1/sounds/search", { size, page, search: query }).then(results => {
|
||||
results.items = results.items.map(s => {
|
||||
const oggPath = s.oggPath;
|
||||
s.download = () => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = https.get(oggPath, { maxRedirects: 20 }, (r) => { resolve(r); });
|
||||
req.on("error", (err) => { reject(err); });
|
||||
req.setTimeout(15_000, () => { req.destroy(); reject(new Error("Tuna download timeout")); });
|
||||
});
|
||||
};
|
||||
return s;
|
||||
});
|
||||
return results;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a single sound effect by ID. The returned object gains a `download()`
|
||||
* method that returns the OGG audio stream.
|
||||
* @async
|
||||
* @param {string} id - Sound ID.
|
||||
* @returns {Promise<object>} Sound object with `download()` method.
|
||||
*/
|
||||
getSound(id) {
|
||||
return this.get("/v1/sounds/" + id).then(sound => {
|
||||
const oggPath = sound.oggPath;
|
||||
sound.download = () => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = https.get(oggPath, { maxRedirects: 20 }, (result) => { resolve(result); });
|
||||
req.on("error", (err) => { reject(err); });
|
||||
req.setTimeout(15_000, () => { req.destroy(); reject(new Error("Tuna download timeout")); });
|
||||
});
|
||||
};
|
||||
return sound;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default Tuna;
|
||||
@@ -0,0 +1,220 @@
|
||||
/** @module src/music/audio/WebMOpusMuxer @description Minimal streaming WebM/Matroska muxer for Opus packets. Produces streams consumable by prism-media's WebmDemuxer (what @fluxerjs/voice uses internally) — no FFmpeg required. */
|
||||
|
||||
import { Transform } from "node:stream";
|
||||
|
||||
/** @type {number} @description Opus frame duration in milliseconds (20ms = 960 samples @ 48kHz). */
|
||||
export const OPUS_FRAME_MS = 20;
|
||||
|
||||
/** @type {number} @description Blocks per cluster before a new Cluster element is started. */
|
||||
const BLOCKS_PER_CLUSTER = 250;
|
||||
|
||||
/** @type {number} @description Force a cluster flush when buffered blocks exceed this size. */
|
||||
const CLUSTER_FLUSH_BYTES = 64 * 1024;
|
||||
|
||||
/**
|
||||
* Encode a Matroska variable-length size integer (finite size).
|
||||
* @param {number} value - Size to encode (must be >= 0).
|
||||
* @returns {Buffer}
|
||||
*/
|
||||
function encodeSizeVint(value) {
|
||||
let length = 1;
|
||||
while (value > 2 ** (7 * length) - 1 && length < 8) length++;
|
||||
const buf = Buffer.alloc(length);
|
||||
for (let i = length - 1; i >= 0; i--) {
|
||||
buf[i] = value & 0xff;
|
||||
value = Math.floor(value / 256);
|
||||
}
|
||||
buf[0] |= 1 << (8 - length);
|
||||
return buf;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a single EBML element from an ID hex string and a payload Buffer.
|
||||
* @param {string} idHex - EBML element ID as hex (e.g. "1a45dfa3").
|
||||
* @param {Buffer} payload
|
||||
* @returns {Buffer}
|
||||
*/
|
||||
function element(idHex, payload) {
|
||||
return Buffer.concat([Buffer.from(idHex, "hex"), encodeSizeVint(payload.length), payload]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode an unsigned integer EBML payload using minimal bytes.
|
||||
* @param {number} value
|
||||
* @returns {Buffer}
|
||||
*/
|
||||
function uintPayload(value) {
|
||||
let bytes = 1;
|
||||
while (value >= 2 ** (8 * bytes)) bytes++;
|
||||
const buf = Buffer.alloc(bytes);
|
||||
buf.writeUIntBE(value, 0, bytes);
|
||||
return buf;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the OpusHead codec private data (Matroska-embedded OpusHead).
|
||||
* @param {number} sampleRate - Input sample rate (48000).
|
||||
* @param {number} channels - Channel count (2).
|
||||
* @returns {Buffer}
|
||||
*/
|
||||
export function buildOpusHead(sampleRate, channels) {
|
||||
const buf = Buffer.alloc(19);
|
||||
buf.write("OpusHead", 0, "ascii");
|
||||
buf.writeUInt8(1, 8); // version
|
||||
buf.writeUInt8(channels, 9);
|
||||
buf.writeUInt16LE(0, 10); // pre-skip (we encode ourselves; no trimming)
|
||||
buf.writeUInt32LE(sampleRate, 12);
|
||||
buf.writeInt16LE(0, 16); // output gain
|
||||
buf.writeUInt8(0, 18); // mapping family (mono/stereo)
|
||||
return buf;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the WebM stream header: EBML + Segment start + Info + Tracks.
|
||||
* The Segment element uses an unknown (streaming) size so clusters can be
|
||||
* appended indefinitely.
|
||||
* @param {number} sampleRate
|
||||
* @param {number} channels
|
||||
* @returns {Buffer}
|
||||
*/
|
||||
function buildHeader(sampleRate, channels) {
|
||||
const ebml = element("1a45dfa3", Buffer.concat([
|
||||
element("4286", uintPayload(1)), // EBMLVersion
|
||||
element("42f7", uintPayload(1)), // EBMLReadVersion
|
||||
element("42f2", uintPayload(4)), // EBMLMaxIDLength
|
||||
element("42f3", uintPayload(8)), // EBMLMaxSizeLength
|
||||
element("4282", Buffer.from("webm", "ascii")), // DocType
|
||||
element("4287", uintPayload(2)), // DocTypeVersion
|
||||
element("4285", uintPayload(2)), // DocTypeReadVersion
|
||||
]));
|
||||
|
||||
const info = element("1549a966", Buffer.concat([
|
||||
element("2ad7b1", uintPayload(1000000)), // TimecodeScale (1ms)
|
||||
element("4d80", Buffer.from("fluxer-remix", "ascii")),// MuxingApp
|
||||
element("5741", Buffer.from("fluxer-remix", "ascii")),// WritingApp
|
||||
]));
|
||||
|
||||
const floatBuf = Buffer.alloc(4);
|
||||
floatBuf.writeFloatBE(sampleRate, 0);
|
||||
const audio = element("e1", Buffer.concat([
|
||||
element("b5", floatBuf), // SamplingFrequency
|
||||
element("9f", uintPayload(channels)), // Channels
|
||||
]));
|
||||
|
||||
const trackEntry = element("ae", Buffer.concat([
|
||||
element("d7", uintPayload(1)), // TrackNumber (must be 1 — demuxer masks data[0] & 0xF)
|
||||
element("73c5", uintPayload(1)), // TrackUID
|
||||
element("83", uintPayload(2)), // TrackType: audio
|
||||
element("86", Buffer.from("A_OPUS", "ascii")), // CodecID
|
||||
element("63a2", buildOpusHead(sampleRate, channels)), // CodecPrivate: OpusHead
|
||||
audio,
|
||||
]));
|
||||
const tracks = element("1654ae6b", trackEntry);
|
||||
|
||||
// Streaming Segment size: a huge finite vint (0x01 + 7x0xFF = 2^56-1). The
|
||||
// canonical all-0xFF unknown-size marker is misparsed by prism-media's
|
||||
// vintLength (it reads 0xFF as a 1-byte vint), so we use this equivalent form.
|
||||
const segmentStart = Buffer.concat([
|
||||
Buffer.from("18538067", "hex"),
|
||||
Buffer.from([0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]),
|
||||
]);
|
||||
|
||||
return Buffer.concat([ebml, segmentStart, info, tracks]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a SimpleBlock element for one Opus packet.
|
||||
* @param {Buffer} packet - Raw Opus packet.
|
||||
* @param {number} relTimeMs - Cluster-relative timestamp in ms.
|
||||
* @returns {Buffer}
|
||||
*/
|
||||
function buildSimpleBlock(packet, relTimeMs) {
|
||||
const clamped = Math.max(-32768, Math.min(32767, relTimeMs));
|
||||
const header = Buffer.from([0x81, (clamped >> 8) & 0xff, clamped & 0xff, 0x80]);
|
||||
return element("a3", Buffer.concat([header, packet]));
|
||||
}
|
||||
|
||||
/**
|
||||
* Streaming WebM muxer: consumes Opus packets (object mode) and emits a
|
||||
* WebM/Opus byte stream compatible with prism-media's WebmDemuxer — the exact
|
||||
* format @fluxerjs/voice's VoiceConnection.play() expects as input.
|
||||
* @extends {Transform}
|
||||
*/
|
||||
export class WebMOpusMuxer extends Transform {
|
||||
/**
|
||||
* @param {object} [options]
|
||||
* @param {number} [options.sampleRate=48000]
|
||||
* @param {number} [options.channels=2]
|
||||
*/
|
||||
constructor(options = {}) {
|
||||
super({ writableObjectMode: true });
|
||||
this._sampleRate = options.sampleRate ?? 48000;
|
||||
this._channels = options.channels ?? 2;
|
||||
this._header = buildHeader(this._sampleRate, this._channels);
|
||||
this._blocks = [];
|
||||
this._blocksBytes = 0;
|
||||
this._blockIndex = 0;
|
||||
this._clusterIndex = 0;
|
||||
this._headerSent = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Feed one Opus packet into the current cluster.
|
||||
* @param {Buffer} packet
|
||||
*/
|
||||
_addBlock(packet) {
|
||||
if (!this._headerSent) {
|
||||
this.push(this._header);
|
||||
this._headerSent = true;
|
||||
}
|
||||
const relTime = (this._blockIndex % BLOCKS_PER_CLUSTER) * OPUS_FRAME_MS;
|
||||
const block = buildSimpleBlock(packet, relTime);
|
||||
this._blocks.push(block);
|
||||
this._blocksBytes += block.length;
|
||||
this._blockIndex++;
|
||||
if (this._blocks.length >= BLOCKS_PER_CLUSTER || this._blocksBytes >= CLUSTER_FLUSH_BYTES) {
|
||||
this._flushCluster();
|
||||
}
|
||||
}
|
||||
|
||||
/** Emit the current cluster as a complete EBML element. */
|
||||
_flushCluster() {
|
||||
if (this._blocks.length === 0) return;
|
||||
const timecode = element("e7", uintPayload(this._clusterIndex * BLOCKS_PER_CLUSTER * OPUS_FRAME_MS));
|
||||
const cluster = element("1f43b675", Buffer.concat([timecode, ...this._blocks]));
|
||||
this._blocks = [];
|
||||
this._blocksBytes = 0;
|
||||
this._clusterIndex++;
|
||||
this.push(cluster);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Buffer} packet
|
||||
* @param {string} _encoding
|
||||
* @param {Function} callback
|
||||
* @protected
|
||||
*/
|
||||
_transform(packet, _encoding, callback) {
|
||||
try {
|
||||
if (Buffer.isBuffer(packet) && packet.length > 0) {
|
||||
this._addBlock(packet);
|
||||
}
|
||||
callback();
|
||||
} catch (err) {
|
||||
callback(err);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Function} callback
|
||||
* @protected
|
||||
*/
|
||||
_final(callback) {
|
||||
try {
|
||||
this._flushCluster();
|
||||
callback();
|
||||
} catch (err) {
|
||||
callback(err);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* @module src/music/audio
|
||||
* @description Public surface of the audio layer (Fluxer voice bridge).
|
||||
*
|
||||
* Import map from the old layout:
|
||||
* - `src/FluxerAudioBridge.mjs` → this module (FluxerAudioBridge)
|
||||
*/
|
||||
|
||||
export { FluxerAudioBridge } from "./FluxerAudioBridge.mjs";
|
||||
@@ -0,0 +1,292 @@
|
||||
/**
|
||||
* @module src/music/player/DisplayMixin
|
||||
* @description User-facing rendering concern for {@link Player}: progress
|
||||
* bars, now-playing announcements, queue listing, thumbnails and duration
|
||||
* formatting.
|
||||
*
|
||||
* These methods are applied onto the Player class prototype via
|
||||
* {@link applyMixins} — `this` is a Player instance.
|
||||
*/
|
||||
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../../ui/index.mjs";
|
||||
import { Utils } from "../../utils/Utils.mjs";
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
import meta from "../probe.mjs";
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
* @description Display mixin — applied to Player.
|
||||
*/
|
||||
const DisplayMixin = {
|
||||
/**
|
||||
* @private Build a progress bar line for the current track.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {number} [length=15]
|
||||
* @returns {string}
|
||||
*/
|
||||
_createProgressBar(length = 15) {
|
||||
const current = this.queue.getCurrent();
|
||||
if (!current?.duration || !this.startedPlaying) {
|
||||
const total = this._getTrackDurationMs(current);
|
||||
if (total > 0) {
|
||||
return `${Utils.progressBar(0, total, length)} \`0:00 / ${Utils.prettifyMS(total)}\``;
|
||||
}
|
||||
return Utils.progressBar(0, 1, length);
|
||||
}
|
||||
|
||||
const totalMs = this._getTrackDurationMs(current);
|
||||
let elapsed = Date.now() - this.startedPlaying;
|
||||
if (this._paused && this._pausedAt) {
|
||||
elapsed = this._pausedAt - this.startedPlaying;
|
||||
}
|
||||
|
||||
if (totalMs > 0 && elapsed > totalMs) elapsed = totalMs;
|
||||
elapsed = Math.max(0, elapsed);
|
||||
|
||||
const bar = Utils.progressBar(elapsed, totalMs, length);
|
||||
const timeNow = Utils.prettifyMS(elapsed);
|
||||
const total = Utils.prettifyMS(totalMs);
|
||||
return `${bar} \`${timeNow} / ${total}\``;
|
||||
},
|
||||
|
||||
/**
|
||||
* @returns {string} Formatted name of the currently playing track.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
*/
|
||||
getCurrent() {
|
||||
const c = this.queue.getCurrent();
|
||||
if (!c) return "There's nothing playing at the moment.";
|
||||
return this.getVideoName(c);
|
||||
},
|
||||
|
||||
/**
|
||||
* Format a track object into a display name.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {object} vid
|
||||
* @param {boolean} [code=false]
|
||||
* @returns {string}
|
||||
*/
|
||||
getVideoName(vid, code = false) {
|
||||
if (!vid) return "Unknown";
|
||||
if (vid.type === "radio") {
|
||||
return code
|
||||
? `[Radio]: ${vid.title} - ${vid.author?.url || ""}`
|
||||
: `[Radio] [${vid.title} by ${vid.author?.name || "Unknown"}](${vid.author?.url || ""})`;
|
||||
}
|
||||
if (vid.type === "external" || vid.type === "stream") {
|
||||
return code
|
||||
? `${vid.title} - ${vid.url}`
|
||||
: `[${vid.title}](${vid.url})`;
|
||||
}
|
||||
const elapsed = this.getCurrentElapsedDuration();
|
||||
const total = this.getDuration(vid.duration);
|
||||
const link = vid.spotifyUrl || vid.url || "";
|
||||
return code
|
||||
? `${vid.title} (${elapsed}/${total})${link ? " - " + link : ""}`
|
||||
: `[${vid.title} (${elapsed}/${total})]${link ? "(" + link + ")" : ""}`;
|
||||
},
|
||||
|
||||
/**
|
||||
* @returns {string} Human-readable total remaining time for all queued tracks.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
*/
|
||||
getQueueRemainingTime() {
|
||||
let totalMs = 0;
|
||||
const current = this.queue.getCurrent();
|
||||
if (current?.duration && this.startedPlaying) {
|
||||
const totalMsCurrent = this._getTrackDurationMs(current);
|
||||
let elapsed = Date.now() - this.startedPlaying;
|
||||
if (this._paused && this._pausedAt) {
|
||||
elapsed = this._pausedAt - this.startedPlaying;
|
||||
}
|
||||
totalMs += Math.max(0, totalMsCurrent - elapsed);
|
||||
}
|
||||
for (const track of this.queue.data) {
|
||||
totalMs += this._getTrackDurationMs(track);
|
||||
}
|
||||
return Utils.prettifyMS(totalMs);
|
||||
},
|
||||
|
||||
/**
|
||||
* @returns {string} Elapsed time of the current track.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
*/
|
||||
getCurrentElapsedDuration() {
|
||||
if (!this.startedPlaying) return "0:00";
|
||||
const current = this.queue.getCurrent();
|
||||
const totalMs = this._getTrackDurationMs(current);
|
||||
|
||||
let elapsed = Date.now() - this.startedPlaying;
|
||||
if (this._paused && this._pausedAt) {
|
||||
elapsed = this._pausedAt - this.startedPlaying;
|
||||
}
|
||||
|
||||
if (totalMs > 0 && elapsed > totalMs) elapsed = totalMs;
|
||||
return Utils.prettifyMS(Math.max(0, elapsed));
|
||||
},
|
||||
|
||||
/**
|
||||
* Generate a text-based queue listing.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {number} [page=1]
|
||||
* @param {number} [pageSize=10]
|
||||
* @returns {string}
|
||||
*/
|
||||
list(page = 1, pageSize = 10) {
|
||||
const current = this.queue.getCurrent();
|
||||
const total = this.queue.size();
|
||||
let text = "";
|
||||
if (current) {
|
||||
const remaining = this.getQueueRemainingTime();
|
||||
text += `🎧 **Queue**\n`;
|
||||
text += `**${total} tracks** • ⏱️ ${remaining}\n`;
|
||||
text += `${this._createProgressBar()}\n\n`;
|
||||
text += `🎵 **Now Playing**\n`;
|
||||
text += `${this.getVideoName(current)}\n\n`;
|
||||
}
|
||||
if (total === 0) { if (!current) text += "--- Empty ---"; return text; }
|
||||
const { items, page: pg, totalPages, start } = this.queue.getPage(page, pageSize);
|
||||
items.forEach((vid, i) => {
|
||||
const index = String(start + i + 1).padStart(2, " ");
|
||||
const name = this.getVideoName({ ...vid, title: Utils.truncate(vid.title, 60) });
|
||||
text += `\`${index}.\` ${name}\n`;
|
||||
});
|
||||
text += `\nPage ${pg}/${totalPages} • Loop: ${this.queue.loop ? "🟢" : "🔴"}`;
|
||||
return text;
|
||||
},
|
||||
|
||||
/**
|
||||
* @async Build a now-playing info object for the current track, including
|
||||
* progress bar, volume, and loop states.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @returns {Promise<{msg: string, image?: string}>}
|
||||
*/
|
||||
async nowPlaying() {
|
||||
const current = this.queue.getCurrent();
|
||||
if (!current) return { msg: "There's nothing playing at the moment." };
|
||||
|
||||
const loopqueue = this.queue.loop ? "🔄" : "⏹️";
|
||||
const songloop = this.queue.songLoop ? "🔂" : "⏹️";
|
||||
const vol = `${Math.round((this.preferredVolume || 1) * 100)}%`;
|
||||
const autoplay = this._autoplay ? "🔁" : "⏹️";
|
||||
|
||||
const vcLine = this._channelId ? `🔊 <#${this._channelId}>\n` : "";
|
||||
|
||||
if (current.type === "radio") {
|
||||
try {
|
||||
const data = await meta(current.url);
|
||||
return {
|
||||
msg: `${vcLine}📻 **[${current.title}](${current.author?.url || current.url})**\n${current.description || ""}\n\n🎵 Now playing: ${data?.title || "Unknown"}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`,
|
||||
image: current.thumbnail
|
||||
};
|
||||
} catch (e) {
|
||||
logger.warn("[Player] Error:", e?.message);
|
||||
return {
|
||||
msg: `${vcLine}📻 **[${current.title}](${current.author?.url || current.url})**\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`,
|
||||
image: current.thumbnail
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (current.type === "external" || current.type === "stream") {
|
||||
const totalMs = this._getTrackDurationMs(current);
|
||||
let progressLine = "";
|
||||
|
||||
if (totalMs > 0) {
|
||||
progressLine = `\n${this._createProgressBar(20)}`;
|
||||
}
|
||||
return {
|
||||
msg: `${vcLine}🎵 **[${current.title}](${current.url})** by ${current.artist || "Unknown"}${progressLine}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`,
|
||||
image: current.thumbnail
|
||||
};
|
||||
}
|
||||
|
||||
const progressBar = this._createProgressBar(20);
|
||||
let trackOptLine = "";
|
||||
if (this._activeTrackOpt) {
|
||||
const optStart = Utils.prettifyMS(this._activeTrackOpt.startMs);
|
||||
const optEnd = this._activeTrackOpt.endMs > 0 ? Utils.prettifyMS(this._activeTrackOpt.endMs) : "end";
|
||||
trackOptLine = `\n✂️ Custom: ${optStart} → ${optEnd}`;
|
||||
}
|
||||
return {
|
||||
msg: `${vcLine}🎵 **[${current.title}](${current.spotifyUrl || current.url})**\n${progressBar}${trackOptLine}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`,
|
||||
image: current.thumbnail
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* @async Get the thumbnail of the currently playing track.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @returns {Promise<{msg: string, image: string|null}>}
|
||||
*/
|
||||
async getThumbnail() {
|
||||
const current = this.queue.getCurrent();
|
||||
if (!current) return { msg: "There's nothing playing at the moment.", image: null };
|
||||
if (!current.thumbnail) return { msg: "No thumbnail available.", image: null };
|
||||
return { msg: `Thumbnail of [${current.title}](${current.url}):`, image: current.thumbnail };
|
||||
},
|
||||
|
||||
/**
|
||||
* Format a track duration from various shapes.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {*} duration
|
||||
* @returns {string}
|
||||
*/
|
||||
getDuration(duration) {
|
||||
if (typeof duration === "object" && duration?.timestamp) return duration.timestamp;
|
||||
if (typeof duration === "object" && duration?.seconds != null) return Utils.formatSeconds(duration.seconds);
|
||||
if (typeof duration === "string" && duration.startsWith("PT")) return Utils.prettifyMS(Utils.parseISODuration(duration));
|
||||
return Utils.prettifyMS(duration);
|
||||
},
|
||||
|
||||
/**
|
||||
* @returns {string} Formatted duration of the currently playing track.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
*/
|
||||
getCurrentDuration() {
|
||||
const current = this.queue.getCurrent();
|
||||
if (!current?.duration) return "?:??";
|
||||
return this.getDuration(current.duration);
|
||||
},
|
||||
|
||||
/**
|
||||
* Emit a now-playing announcement for the given track.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {object} s
|
||||
*/
|
||||
announceSong(s) {
|
||||
if (!s) return;
|
||||
|
||||
if (s.type === "radio") {
|
||||
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
|
||||
? s.artists.map(a => a.url ? `[${a.name}](${a.url})` : a.name).join(" & ")
|
||||
: s.author?.url
|
||||
? `[${s.author.name}](${s.author.url})`
|
||||
: s.author?.name || null;
|
||||
|
||||
if (!author && (s.type === "external" || s.type === "stream")) {
|
||||
const desc = "🎵 Now playing [" + Utils.escapeMarkdown(s.title) + "](" + (s.url || "") + ") in <#" + (this._channelId || "") + ">";
|
||||
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] });
|
||||
return;
|
||||
}
|
||||
|
||||
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 || "Unknown",
|
||||
channel: this._channelId || "",
|
||||
}))] });
|
||||
},
|
||||
};
|
||||
|
||||
export default DisplayMixin;
|
||||
export { DisplayMixin };
|
||||
@@ -0,0 +1,631 @@
|
||||
/**
|
||||
* @module src/music/player/PlaybackMixin
|
||||
* @description Playback advancement concern for {@link Player}: track-end
|
||||
* handling, playNext generation guarding, bridge playback with Lavalink
|
||||
* pre-resolution, track-option timers, and lyrics.
|
||||
*
|
||||
* These methods are applied onto the Player class prototype via
|
||||
* {@link applyMixins} — `this` is a Player instance.
|
||||
*/
|
||||
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../../ui/index.mjs";
|
||||
import { Utils, cleanId } from "../../utils/Utils.mjs";
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
import meta from "../probe.mjs";
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
* @description Playback mixin — applied to Player.
|
||||
*/
|
||||
const PlaybackMixin = {
|
||||
/**
|
||||
* Handle the end of a track. Advances to the next song or starts the
|
||||
* inactivity timer (if not 24/7). For radio tracks, stops playback.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @private
|
||||
*/
|
||||
_handleTrackEnd() {
|
||||
const songData = this.queue.getCurrent();
|
||||
if (!songData) return;
|
||||
|
||||
this._clearTrackEndTimer();
|
||||
|
||||
if (songData.type === "radio") {
|
||||
logger.player(`[Player] Radio track ended: ${songData.title}`);
|
||||
this._lastPlayedTrack = this.queue.getCurrent() ?? songData;
|
||||
this.queue.current = null;
|
||||
this.emit("stopplay");
|
||||
if (!this._is247Enabled()) {
|
||||
this._startInactivityTimer();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this._paused) {
|
||||
this._lastPlayedTrack = this.queue.getCurrent() ?? songData;
|
||||
if (!this.queue.songLoop) this.queue.current = null;
|
||||
this._playingNext = false;
|
||||
this.playNext().catch(e => logger.error("[Player] auto-advance playNext error:", e.message));
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* @private Extract track duration in ms from various track data shapes.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {object} track
|
||||
* @returns {number}
|
||||
*/
|
||||
_getTrackDurationMs(track) {
|
||||
if (track?._durationMs != null && track._durationMs > 0) {
|
||||
return track._durationMs;
|
||||
}
|
||||
if (track?.duration) {
|
||||
if (typeof track.duration === "object" && track.duration?.seconds != null) {
|
||||
return track.duration.seconds * 1000;
|
||||
}
|
||||
if (typeof track.duration === "string" && track.duration.startsWith("PT")) {
|
||||
return Utils.parseISODuration(track.duration);
|
||||
}
|
||||
if (typeof track.duration === "number") return track.duration;
|
||||
}
|
||||
if (track?.info?.length) return track.info.length;
|
||||
if (track?.info?.duration != null) {
|
||||
if (typeof track.info.duration === "number") return track.info.duration;
|
||||
if (typeof track.info.duration === "object" && track.info.duration.seconds != null)
|
||||
return track.info.duration.seconds * 1000;
|
||||
}
|
||||
return 0;
|
||||
},
|
||||
|
||||
/**
|
||||
* @private Check if a track has played past 85% or within 15s of the end.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {object} track
|
||||
* @returns {boolean}
|
||||
*/
|
||||
_didTrackMostlyFinish(track) {
|
||||
const totalMs = this._getTrackDurationMs(track);
|
||||
if (!totalMs || !this.startedPlaying) return false;
|
||||
|
||||
const elapsedMs = Math.max(0, Date.now() - this.startedPlaying);
|
||||
const remainingMs = Math.max(0, totalMs - elapsedMs);
|
||||
|
||||
return elapsedMs / totalMs >= this.constructor.TRACK_MOSTLY_FINISHED_RATIO || remainingMs <= this.constructor.TRACK_MOSTLY_FINISHED_FLOOR_MS;
|
||||
},
|
||||
|
||||
/**
|
||||
* @async Advance to the next track. Guarded against overlapping runs: a
|
||||
* generation counter ensures an older run's cleanup never clears the
|
||||
* in-flight flag of a newer run (which previously allowed double-advances).
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async playNext() {
|
||||
if (this._playingNext) return;
|
||||
this._playingNext = true;
|
||||
const generation = (this._playNextGeneration = (this._playNextGeneration ?? 0) + 1);
|
||||
try { await this._doPlayNext(); }
|
||||
finally { if (generation === this._playNextGeneration) this._playingNext = false; }
|
||||
},
|
||||
|
||||
/**
|
||||
* @private @async Core logic for advancing to the next track: resolves
|
||||
* track options, announces, starts playback via the bridge, arms the
|
||||
* track-end timer, and handles the queue-end path.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
*/
|
||||
async _doPlayNext() {
|
||||
this._bridgeStop();
|
||||
|
||||
const currentBeforeNext = this.queue.getCurrent();
|
||||
if (currentBeforeNext) this._lastPlayedTrack = currentBeforeNext;
|
||||
const songData = this.queue.next();
|
||||
if (!songData) {
|
||||
this.emit("stopplay");
|
||||
this.emit("queueEnd");
|
||||
|
||||
if (!this._is247Enabled()) {
|
||||
this._startInactivityTimer();
|
||||
} else {
|
||||
logger.voice247("[Player] 24/7 enabled, staying in channel");
|
||||
}
|
||||
|
||||
if (!this._wasRadio && !this._queueEndedSent && !this._autoplay) {
|
||||
this._queueEndedSent = true;
|
||||
const prefix = this._getPrefix?.(this._guildId) ?? "%";
|
||||
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true });
|
||||
}
|
||||
this._wasRadio = false;
|
||||
return;
|
||||
}
|
||||
|
||||
this._stopInactivityTimer();
|
||||
this._wasRadio = songData.type === "radio";
|
||||
|
||||
if (!this._voiceConn || this.leaving) return;
|
||||
|
||||
if (this.preferredVolume !== 1 && this._voiceConn) {
|
||||
try { this._voiceConn.setVolume(this.preferredVolume * 100); } catch(_) {}
|
||||
}
|
||||
|
||||
if (!this._voiceConn || this.leaving) return;
|
||||
|
||||
this._activeTrackOpt = null;
|
||||
this._clearTrackEndTimer();
|
||||
|
||||
let trackOptMatch = null;
|
||||
try {
|
||||
trackOptMatch = await this._lookupTrackOptions(songData);
|
||||
} catch (e) {
|
||||
logger.warn("[Player] TrackOptions lookup error:", e.message);
|
||||
}
|
||||
|
||||
if (trackOptMatch) {
|
||||
this._activeTrackOpt = trackOptMatch;
|
||||
}
|
||||
|
||||
logger.player(`[Player:${this._guildId}] Playing: ${songData.title}`);
|
||||
|
||||
this.startedPlaying = Date.now();
|
||||
this._paused = false;
|
||||
this._pausedAt = null;
|
||||
this._queueEndedSent = false;
|
||||
this._consecutiveErrors = 0;
|
||||
|
||||
if (songData.type !== "radio" || !this._radioAnnounced) {
|
||||
this.announceSong(songData);
|
||||
if (songData.type === "radio") this._radioAnnounced = true;
|
||||
}
|
||||
this.emit("startplay", songData);
|
||||
|
||||
try {
|
||||
const playUri = songData.url;
|
||||
const seekSec = trackOptMatch?.startMs > 0 ? trackOptMatch.startMs / 1000 : 0;
|
||||
|
||||
if (!playUri || !Utils.isValidUrl(playUri)) {
|
||||
logger.warn(`[Player] No valid URL for track: ${songData.title} (url=${songData.url}), trying search...`);
|
||||
try {
|
||||
if (this._lavalink) {
|
||||
const result = await this._lavalink.search(songData.title, { source: "ytmsearch" });
|
||||
const track = result?.tracks?.[0];
|
||||
if (track?.info?.uri) {
|
||||
songData.url = track.info.uri;
|
||||
if (track.encoded) songData.encoded = track.encoded;
|
||||
await this._playTrackViaBridge(songData, { seekSeconds: seekSec });
|
||||
} else {
|
||||
throw new Error("No tracks found for title search");
|
||||
}
|
||||
} else {
|
||||
throw new Error("No Lavalink for fallback search");
|
||||
}
|
||||
} catch (searchErr) {
|
||||
logger.error("[Player] Could not resolve track:", searchErr?.message);
|
||||
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.couldNotGetStream", { title: songData.title }))] });
|
||||
this.emit("stopplay");
|
||||
if (!this._is247Enabled()) {
|
||||
this._startInactivityTimer();
|
||||
}
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
await this._playTrackViaBridge(songData, { seekSeconds: seekSec });
|
||||
}
|
||||
|
||||
if (trackOptMatch && trackOptMatch.endMs > 0) {
|
||||
const elapsedMs = Date.now() - this.startedPlaying;
|
||||
const remainingMs = trackOptMatch.endMs - elapsedMs;
|
||||
if (remainingMs > 0) {
|
||||
const match = trackOptMatch;
|
||||
this._trackEndTimer = setTimeout(() => this._onTrackEndTimeReached(match), remainingMs);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error("[Player] Play error:", err.message);
|
||||
if (!this._skipping && !this.leaving && !this._paused && songData.type !== "radio") {
|
||||
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.errorStreaming", { title: songData.title }))] });
|
||||
}
|
||||
if (!this._skipping && !this.leaving) {
|
||||
this._consecutiveErrors = (this._consecutiveErrors || 0) + 1;
|
||||
if (this._consecutiveErrors <= 3) {
|
||||
this._handleTrackEnd();
|
||||
} else {
|
||||
logger.error(`[Player] ${this._consecutiveErrors} consecutive play errors — stopping auto-advance`);
|
||||
this._consecutiveErrors = 0;
|
||||
this.emit("stopplay");
|
||||
if (!this._is247Enabled()) {
|
||||
this._startInactivityTimer();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* @private @async Play a track through the FluxerAudioBridge. For
|
||||
* radio/external tracks without an encoded payload, attempts Lavalink URL
|
||||
* resolution first so MP3/AAC streams can use the loadstream pipeline.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {object} songData
|
||||
* @param {object} [options={}]
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async _playTrackViaBridge(songData, options = {}) {
|
||||
if (!this._voiceConn || !this._audioBridge) {
|
||||
throw new Error("No voice connection or audio bridge available");
|
||||
}
|
||||
if (!songData?.encoded && !songData?.url) {
|
||||
throw new Error("No encoded track or URL for: " + (songData?.title ?? "unknown"));
|
||||
}
|
||||
|
||||
if (!songData.encoded && songData.url && songData.url.startsWith("http") && this._lavalink && songData.type !== "external") {
|
||||
try {
|
||||
const nlInfo = this._lavalink.getNodeLinkInfo?.();
|
||||
if (nlInfo) {
|
||||
const protocol = nlInfo.secure ? "https" : "http";
|
||||
const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port;
|
||||
const headers = { "Authorization": nlInfo.password };
|
||||
if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId;
|
||||
if (this._guildId) headers["Guild-Id"] = this._guildId;
|
||||
|
||||
const loadtracksUrl = baseUrl + "/v4/loadtracks?identifier=" + encodeURIComponent(songData.url);
|
||||
logger.player(`[Player] Pre-resolving ${songData.type || "external"} URL via Lavalink...`);
|
||||
|
||||
const body = await this._request(loadtracksUrl, { headers });
|
||||
const track = body?.data?.tracks?.[0] ?? body?.tracks?.[0] ?? body?.data;
|
||||
const encoded = track?.encoded ?? track?.data;
|
||||
|
||||
if (encoded && typeof encoded === "string") {
|
||||
songData.encoded = encoded;
|
||||
logger.player("[Player] Lavalink pre-resolve succeeded — track now has encoded payload");
|
||||
} else {
|
||||
logger.player("[Player] Lavalink pre-resolve: no encoded track returned, bridge will try direct URL");
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[Player] Lavalink pre-resolve failed (bridge will try direct URL): " + e.message);
|
||||
}
|
||||
}
|
||||
|
||||
this._audioBridge._conn = this._voiceConn;
|
||||
|
||||
const seekMs = Math.floor((options.seekSeconds ?? 0) * 1000);
|
||||
|
||||
const totalMs = this._getTrackDurationMs(songData);
|
||||
const durationMs = totalMs > 0 ? Math.max(0, totalMs - seekMs) : 0;
|
||||
|
||||
const result = await this._audioBridge.play(this._voiceConn, {
|
||||
encoded: songData.encoded,
|
||||
url: songData.url,
|
||||
title: songData.title,
|
||||
guildId: this._guildId,
|
||||
}, {
|
||||
seekSeconds: options.seekSeconds ?? 0,
|
||||
durationMs,
|
||||
videoId: songData.videoId || null,
|
||||
filterPayload: this.activeFilterPayload || null,
|
||||
});
|
||||
|
||||
if (result === "finished" && !this._skipping && !this.leaving && !this._paused) {
|
||||
this._handleTrackEnd();
|
||||
} else if (result === "stopped") {
|
||||
// Stopped intentionally (skip/seek/stop) — nothing to do.
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* @private Handle when a track option's end time is reached.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {object} match
|
||||
*/
|
||||
_onTrackEndTimeReached(match) {
|
||||
if (this._destroyed || this.leaving || !this._activeTrackOpt) return;
|
||||
logger.player(`[Player] TrackOptions: end time reached (${match.endMs}ms), skipping track`);
|
||||
this._activeTrackOpt = null;
|
||||
this._trackEndTimer = null;
|
||||
this._trackEndRemainingMs = null;
|
||||
this._skipping = true;
|
||||
this._bridgeStop();
|
||||
this._playingNext = false;
|
||||
this._lastPlayedTrack = this.queue.getCurrent() ?? this._lastPlayedTrack;
|
||||
this.emit("trackSkip", this._lastPlayedTrack);
|
||||
if (!this.queue.isEmpty() && !this.leaving) {
|
||||
this.playNext().catch(e => logger.error("[Player] TrackEnd playNext error:", e.message));
|
||||
} else {
|
||||
this.queue.current = null;
|
||||
if (!this._wasRadio && !this._queueEndedSent) {
|
||||
this._queueEndedSent = true;
|
||||
this.emit("queueEnd");
|
||||
if (!this._autoplay) {
|
||||
const prefix = this._getPrefix?.(this._guildId) ?? "%";
|
||||
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true });
|
||||
}
|
||||
}
|
||||
this.emit("stopplay");
|
||||
if (!this._is247Enabled()) {
|
||||
this._startInactivityTimer();
|
||||
}
|
||||
}
|
||||
this._skipping = false;
|
||||
},
|
||||
|
||||
/**
|
||||
* @private Clear the track-end timer.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
*/
|
||||
_clearTrackEndTimer() {
|
||||
if (this._trackEndTimer) {
|
||||
clearTimeout(this._trackEndTimer);
|
||||
this._trackEndTimer = null;
|
||||
}
|
||||
this._trackEndRemainingMs = null;
|
||||
},
|
||||
|
||||
/**
|
||||
* @private Pause the track-end timer, saving remaining time.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
*/
|
||||
_pauseTrackEndTimer() {
|
||||
if (!this._trackEndTimer || !this._activeTrackOpt || this._activeTrackOpt.endMs <= 0) return;
|
||||
clearTimeout(this._trackEndTimer);
|
||||
const elapsedMs = Date.now() - this.startedPlaying;
|
||||
this._trackEndRemainingMs = Math.max(0, this._activeTrackOpt.endMs - elapsedMs);
|
||||
this._trackEndTimer = null;
|
||||
},
|
||||
|
||||
/**
|
||||
* @private Resume the track-end timer.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
*/
|
||||
_resumeTrackEndTimer() {
|
||||
if (this._trackEndRemainingMs == null || this._trackEndRemainingMs <= 0 || !this._activeTrackOpt || this._activeTrackOpt.endMs <= 0) {
|
||||
this._trackEndRemainingMs = null;
|
||||
return;
|
||||
}
|
||||
const remainingMs = this._trackEndRemainingMs;
|
||||
const match = this._activeTrackOpt;
|
||||
this._trackEndTimer = setTimeout(() => this._onTrackEndTimeReached(match), remainingMs);
|
||||
this._trackEndRemainingMs = null;
|
||||
},
|
||||
|
||||
/**
|
||||
* @private Recalculate and restart the track-end timer (after a seek).
|
||||
* @this {import('./Player.mjs').Player}
|
||||
*/
|
||||
_recalcTrackEndTimer() {
|
||||
if (!this._activeTrackOpt || this._activeTrackOpt.endMs <= 0) return;
|
||||
this._clearTrackEndTimer();
|
||||
const elapsedMs = Date.now() - this.startedPlaying;
|
||||
const remainingMs = this._activeTrackOpt.endMs - elapsedMs;
|
||||
if (remainingMs <= 0) {
|
||||
this._onTrackEndTimeReached(this._activeTrackOpt);
|
||||
return;
|
||||
}
|
||||
const match = this._activeTrackOpt;
|
||||
this._trackEndTimer = setTimeout(() => this._onTrackEndTimeReached(match), remainingMs);
|
||||
},
|
||||
|
||||
/**
|
||||
* @async Seek to a specific position in the currently playing track.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {number} ms - Target position in milliseconds.
|
||||
* @returns {Promise<boolean>} True if seek succeeded, false otherwise.
|
||||
*/
|
||||
async seekToPosition(ms) {
|
||||
if (!this._voiceConn || !this.queue.getCurrent()) return false;
|
||||
|
||||
this._seeking = true;
|
||||
|
||||
try {
|
||||
this._bridgeStop();
|
||||
const current = this.queue.getCurrent();
|
||||
if (current?.url) {
|
||||
this.startedPlaying = Date.now() - ms;
|
||||
await this._playTrackViaBridge(current, { seekSeconds: ms / 1000 });
|
||||
}
|
||||
logger.player(`[Player] Seeked to ${ms}ms — adjusted startedPlaying`);
|
||||
|
||||
this._recalcTrackEndTimer();
|
||||
|
||||
return true;
|
||||
} catch (e) {
|
||||
this._seeking = false;
|
||||
logger.error("[Player] Seek failed:", e?.message);
|
||||
return false;
|
||||
} finally {
|
||||
this._seeking = false;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* @async Apply an audio filter to playback. Stores filter metadata for
|
||||
* dashboard tracking; filters are applied server-side by NodeLink on the
|
||||
* next track.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {object} filterPayload
|
||||
* @param {object|null} [filterMeta=null]
|
||||
* @returns {Promise<{ok: boolean, reason?: string, pending?: boolean}>}
|
||||
*/
|
||||
async applyFilter(filterPayload, filterMeta = null) {
|
||||
if (!this._guildId) {
|
||||
return { ok: false, reason: "Player not bound to a guild." };
|
||||
}
|
||||
|
||||
const current = this.queue.getCurrent();
|
||||
|
||||
this.activeFilter = filterMeta ?? null;
|
||||
this.activeFilterPayload = filterMeta ? filterPayload : null;
|
||||
this.emit("filter", this.activeFilter);
|
||||
|
||||
if (!current?.encoded || !this._voiceConn) {
|
||||
return { ok: true, pending: true };
|
||||
}
|
||||
|
||||
return { ok: true };
|
||||
},
|
||||
|
||||
/**
|
||||
* Clear any active audio filter.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
*/
|
||||
clearFilter() {
|
||||
this.activeFilter = null;
|
||||
this.activeFilterPayload = null;
|
||||
this.emit("filter", null);
|
||||
logger.warn("[Player] clearFilter: filters not supported in LiveKit mode");
|
||||
},
|
||||
|
||||
/**
|
||||
* @private @async Look up per-user track options for the humans currently
|
||||
* in the player's channel.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {object} songData
|
||||
* @returns {Promise<object|null>}
|
||||
*/
|
||||
async _lookupTrackOptions(songData) {
|
||||
if (!this.trackOptions || !songData || songData.type === "radio") return null;
|
||||
if (!this._guildId || !this._channelId) return null;
|
||||
|
||||
const userIds = [];
|
||||
if (this._voiceCache) {
|
||||
const humans = this._voiceCache.getHumansInChannel(
|
||||
cleanId(this._guildId),
|
||||
cleanId(this._channelId)
|
||||
);
|
||||
userIds.push(...humans);
|
||||
}
|
||||
|
||||
if (userIds.length === 0) {
|
||||
try {
|
||||
const guild = this.client?.guilds?.get?.(this._guildId);
|
||||
const voiceStates = guild?.voice_states ?? guild?.voiceStates;
|
||||
if (voiceStates) {
|
||||
const entries = Array.isArray(voiceStates) ? voiceStates
|
||||
: typeof voiceStates.values === "function" ? [...voiceStates.values()]
|
||||
: Object.values(voiceStates);
|
||||
for (const state of entries) {
|
||||
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(e) { logger.warn("[Player] Voice state lookup error:", e?.message); }
|
||||
}
|
||||
|
||||
if (userIds.length === 0) return null;
|
||||
|
||||
const match = await this.trackOptions.getBestMatchForChannel(userIds, songData);
|
||||
return match || null;
|
||||
},
|
||||
|
||||
/**
|
||||
* @private @async Auto-seek to a track options start position.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {object} match
|
||||
*/
|
||||
async _applyTrackOptionsSeek(match) {
|
||||
if (!match || match.startMs <= 0) return;
|
||||
const current = this.queue.getCurrent();
|
||||
if (!current?.url || !this._voiceConn || this.leaving) {
|
||||
logger.warn(`[Player] TrackOptions: cannot seek (encoded=${!!current?.encoded} lavalinkPlayer=${!!this.lavalinkPlayer} leaving=${this.leaving})`);
|
||||
return;
|
||||
}
|
||||
let seeked = false;
|
||||
for (let attempt = 0; attempt < 10; attempt++) {
|
||||
await Utils.sleep(500);
|
||||
try {
|
||||
const result = await this.seekToPosition(match.startMs);
|
||||
if (result) {
|
||||
seeked = true;
|
||||
logger.player(`[Player] TrackOptions: auto-seeked to ${match.startMs}ms for user ${match.userId} (attempt ${attempt + 1})`);
|
||||
break;
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn(`[Player] TrackOptions auto-seek attempt ${attempt + 1} error:`, e.message);
|
||||
}
|
||||
}
|
||||
if (!seeked) {
|
||||
logger.warn(`[Player] TrackOptions: auto-seek to ${match.startMs}ms failed after all retries`);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* @async Apply a track options match (custom start/end times) to the
|
||||
* currently playing track.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {object} match - Track options match with startMs and optional endMs.
|
||||
* @returns {Promise<boolean>} True if applied successfully, false otherwise.
|
||||
*/
|
||||
async applyTrackOption(match) {
|
||||
if (!match || !this._voiceConn || this._paused) return false;
|
||||
|
||||
this._clearTrackEndTimer();
|
||||
this._activeTrackOpt = null;
|
||||
|
||||
try {
|
||||
await this.seekToPosition(match.startMs || 0);
|
||||
} catch (e) {
|
||||
logger.warn("[Player] TrackOptions apply-seek error:", e.message);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (match.endMs > 0) {
|
||||
const elapsedMs = Date.now() - this.startedPlaying;
|
||||
const remainingMs = match.endMs - elapsedMs;
|
||||
if (remainingMs > 0) {
|
||||
this._activeTrackOpt = match;
|
||||
this._trackEndTimer = setTimeout(() => this._onTrackEndTimeReached(match), remainingMs);
|
||||
}
|
||||
} else {
|
||||
this._activeTrackOpt = match;
|
||||
}
|
||||
|
||||
return true;
|
||||
},
|
||||
|
||||
/**
|
||||
* @async Fetch lyrics for the currently playing track via the Lavalink
|
||||
* REST API.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @returns {Promise<{text: string, source: string, synced: boolean, lines: Array}|null>}
|
||||
*/
|
||||
async lyrics() {
|
||||
const current = this.queue.getCurrent();
|
||||
if (!current) return null;
|
||||
|
||||
const node = this._lavalink?.getNode?.() ?? null;
|
||||
|
||||
if (node) {
|
||||
try {
|
||||
const searchQuery = current.artists?.[0]?.name
|
||||
? `${current.title} ${current.artists[0].name}`
|
||||
: current.title;
|
||||
|
||||
const path = current.encoded
|
||||
? `/loadlyrics?encodedTrack=${encodeURIComponent(current.encoded)}`
|
||||
: `/loadlyrics?identifier=${encodeURIComponent(searchQuery)}`;
|
||||
|
||||
const results = await node.request(path);
|
||||
|
||||
if (results?.data?.lines?.length) {
|
||||
return {
|
||||
text: results.data.lines.map(l => l.text).join("\n"),
|
||||
source: "Lavalink",
|
||||
synced: results.data.lines.some(l => l.startTimeMs != null),
|
||||
lines: results.data.lines,
|
||||
};
|
||||
}
|
||||
} catch (e) {
|
||||
logger.player(`[Lyrics] Lavalink REST lyrics failed: ${e.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
},
|
||||
};
|
||||
|
||||
export default PlaybackMixin;
|
||||
export { PlaybackMixin };
|
||||
@@ -0,0 +1,993 @@
|
||||
/**
|
||||
* @module src/music/player/Player
|
||||
* @description Per-channel music player: voice connection lifecycle (join /
|
||||
* leave / destroy / rejoin), playback controls (pause, resume, skip, seek,
|
||||
* volume, filters), queue operations, 24/7 mode helpers and the inactivity
|
||||
* timer. Playback advancement, search and display rendering live in the
|
||||
* playback/search/display mixin modules applied at the bottom of this file.
|
||||
*/
|
||||
|
||||
import { getVoiceManager } from "@fluxerjs/voice";
|
||||
import { EventEmitter } from "node:events";
|
||||
import http from "node:http";
|
||||
import https from "node:https";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "../../ui/index.mjs";
|
||||
import { Utils, cleanId } from "../../utils/Utils.mjs";
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
import { get247ChannelMode } from "../../utils/Helpers247.mjs";
|
||||
import { hasHumansInChannel } from "../../voice/VoiceStateResolver.mjs";
|
||||
import { FluxerAudioBridge } from "../audio/FluxerAudioBridge.mjs";
|
||||
import { applyMixins } from "../../utils/mixins.mjs";
|
||||
import { Queue } from "./Queue.mjs";
|
||||
import PlaybackMixin from "./PlaybackMixin.mjs";
|
||||
import SearchMixin from "./SearchMixin.mjs";
|
||||
import DisplayMixin from "./DisplayMixin.mjs";
|
||||
|
||||
/**
|
||||
* @class Player
|
||||
* @description Main music player class. Manages voice connections, playback,
|
||||
* queue, filters, and search.
|
||||
* @extends {EventEmitter}
|
||||
*
|
||||
* Events:
|
||||
* - `"queue"` — queue mutation (proxied from the Queue)
|
||||
* - `"message"` — announcements `{ embeds: [...] }` (or a plain string)
|
||||
* - `"startplay"` / `"stopplay"` / `"queueEnd"` / `"trackSkip"`
|
||||
* - `"playback"` (paused state boolean), `"volume"`, `"filter"`
|
||||
* - `"autoleave"`, `"leave"`, `"roomfetched"`
|
||||
*/
|
||||
class Player extends EventEmitter {
|
||||
/** @private @type {object|null} The LiveKit voice connection. */
|
||||
_voiceConn = null;
|
||||
/** @private @type {FluxerAudioBridge|null} */
|
||||
_audioBridge = null;
|
||||
lavalinkPlayer = null;
|
||||
/** @type {object|null} Alias of _voiceConn (kept for dashboard/debug compat). */
|
||||
connection = null;
|
||||
/** @private @type {string|null} */
|
||||
_guildId = null;
|
||||
/** @private @type {string|null} */
|
||||
_channelId = null;
|
||||
/** @private @type {number|null} */
|
||||
_lastConnectedAt = null;
|
||||
/** @private @type {string|null} The home channel of a 24/7 spawn. */
|
||||
_home247Channel = null;
|
||||
|
||||
/** @type {Queue} */
|
||||
queue = null;
|
||||
client = null;
|
||||
settings = null;
|
||||
config = {};
|
||||
|
||||
/** @type {import('../LavalinkManager.mjs').LavalinkManager|null} */
|
||||
_lavalink = null;
|
||||
|
||||
leaving = false;
|
||||
_paused = false;
|
||||
_pausedAt = null;
|
||||
_playingNext = false;
|
||||
startedPlaying = null;
|
||||
/** @type {Map<string, Array>} Search sessions by key. */
|
||||
searches = new Map();
|
||||
_searchMaxSize = 50;
|
||||
_maxQueueSize = 10_000;
|
||||
resultLimit = 5;
|
||||
preferredVolume = 1;
|
||||
|
||||
_skipping = false;
|
||||
_seeking = false;
|
||||
_wasRadio = false;
|
||||
_radioAnnounced = false;
|
||||
_queueEndedSent = false;
|
||||
_lastPlayedTrack = null;
|
||||
|
||||
_autoplay = false;
|
||||
_autoplayHandler = null;
|
||||
|
||||
activeFilter = null;
|
||||
activeFilterPayload = null;
|
||||
|
||||
/** @type {number} Default inactivity timeout before auto-leave. */
|
||||
static INACTIVITY_DEFAULT_MS = 3 * 60 * 1000;
|
||||
/** @type {number} Track is considered finished past this ratio. */
|
||||
static TRACK_MOSTLY_FINISHED_RATIO = 0.85;
|
||||
/** @type {number} Or when less than this much time remains. */
|
||||
static TRACK_MOSTLY_FINISHED_FLOOR_MS = 15_000;
|
||||
/** @type {number} Hard radio safety timeout. */
|
||||
static RADIO_SAFETY_TIMEOUT_MS = 20 * 60 * 1000;
|
||||
|
||||
/** @private @type {Timeout|null} */
|
||||
_inactivityTimer = null;
|
||||
/** @private @type {number} */
|
||||
_inactivityLimit = Player.INACTIVITY_DEFAULT_MS;
|
||||
/** @private @type {boolean} */
|
||||
_pendingInactivityCheck = false;
|
||||
|
||||
/** @private @type {boolean} */
|
||||
_isJoining = false;
|
||||
/** @private @type {boolean} */
|
||||
_destroyed = false;
|
||||
/** @private @type {Timeout|null} */
|
||||
_rejoinTimer = null;
|
||||
|
||||
/**
|
||||
* @param {string} token - Bot authentication token (used internally).
|
||||
* @param {object} [opts={}] - Player configuration options.
|
||||
* @param {import('@fluxerjs/core').Client} [opts.client]
|
||||
* @param {object} [opts.config]
|
||||
* @param {import('../LavalinkManager.mjs').LavalinkManager} [opts.lavalink]
|
||||
* @param {import('../../db/Settings.mjs').RemoteSettingsManager} [opts.settingsMgr]
|
||||
* @param {Function} [opts.getPrefix]
|
||||
* @param {import('../../voice/VoiceStateCache.mjs').VoiceStateCache} [opts.observedVoiceUsers]
|
||||
* @param {import('../../voice/VoiceStateCache.mjs').VoiceStateCache} [opts.voiceCache]
|
||||
* @param {import('../../core/Locale.mjs').Locale} [opts.locale]
|
||||
* @param {import('../../services/TrackOptionsManager.mjs').TrackOptionsManager} [opts.trackOptions]
|
||||
*/
|
||||
constructor(token, opts = {}) {
|
||||
super();
|
||||
|
||||
this.queue = new Queue();
|
||||
this.queue.on("queue", (...args) => this.emit("queue", ...args));
|
||||
this.client = opts.client;
|
||||
this.config = opts.config ?? {};
|
||||
this.settings = opts.settings ?? null;
|
||||
this.settingsMgr = opts.settingsMgr ?? null;
|
||||
this._getPrefix = opts.getPrefix ?? null;
|
||||
this._observedVoiceUsers = opts.observedVoiceUsers ?? null;
|
||||
this._voiceCache = opts.voiceCache ?? null;
|
||||
this.locale = opts.locale ?? null;
|
||||
this.trackOptions = opts.trackOptions ?? null;
|
||||
this._activeTrackOpt = null;
|
||||
|
||||
this._lavalink = opts.lavalink ?? null;
|
||||
|
||||
this._audioBridge = new FluxerAudioBridge(opts.lavalink ?? null);
|
||||
this._audioBridge.on("error", (err) => {
|
||||
logger.error(`[Player] Audio bridge error (guild ${this._guildId}): ${err.message}`);
|
||||
});
|
||||
|
||||
const inactivityMs = this.config?.timers?.inactivityTimeout ?? this.config?.inactivityTimeout;
|
||||
if (inactivityMs !== undefined) {
|
||||
const parsed = Number(inactivityMs);
|
||||
if (!Number.isNaN(parsed) && parsed >= 0) {
|
||||
this._inactivityLimit = parsed;
|
||||
}
|
||||
}
|
||||
|
||||
if (this._lavalink) {
|
||||
this._onLavalinkPlayerDisconnect = (lavaPlayer) => {
|
||||
if (!lavaPlayer || String(lavaPlayer.guildId) !== String(this._guildId)) return;
|
||||
logger.lavalink("[Player] lavalink-client player disconnect (guild: " + this._guildId + ") — ignored (voice via LiveKit)");
|
||||
};
|
||||
this._lavalink.on("playerDisconnected", this._onLavalinkPlayerDisconnect);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether 24/7 mode is active for this player's current channel.
|
||||
* @returns {boolean} True if 24/7 is enabled.
|
||||
*/
|
||||
_is247Enabled() {
|
||||
return this._get247Mode() !== "off";
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the 24/7 mode for this player's current or home channel by
|
||||
* consulting the guild's stay_247 setting.
|
||||
* @returns {"on"|"off"} The 24/7 mode. Only "on" or "off" — no "auto".
|
||||
* @private
|
||||
*/
|
||||
_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 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 => cleanId(id)).filter(Boolean)
|
||||
: [cleanId(raw)].filter(Boolean);
|
||||
if (!channels.includes(channelId)) return "off";
|
||||
} else {
|
||||
return "off";
|
||||
}
|
||||
|
||||
return get247ChannelMode(serverSettings, channelId);
|
||||
}
|
||||
|
||||
/** @private @returns {string|null} The cleaned guild ID, or null if unresolvable. */
|
||||
_resolveGuildId() {
|
||||
const cleanGuild = cleanId(this._guildId ?? "");
|
||||
if (cleanGuild) return cleanGuild;
|
||||
|
||||
try {
|
||||
const channelId = this._channelId ?? this._home247Channel;
|
||||
if (channelId) {
|
||||
const ch = this.client?.channels?.get?.(channelId);
|
||||
const fromChannel = ch?.guildId ?? ch?.guild?.id ?? null;
|
||||
if (fromChannel) return cleanId(fromChannel);
|
||||
}
|
||||
} catch(e) { logger.warn("[Player] Guild resolution failed:", e?.message); }
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @private Restore saved volume from guild settings. */
|
||||
_restoreVolume() {
|
||||
if (!this._guildId) return;
|
||||
let savedVol = null;
|
||||
|
||||
if (this.settings?.get) {
|
||||
savedVol = this.settings.get("volume");
|
||||
} else if (this.settingsMgr?.getServer) {
|
||||
const set = this.settingsMgr.getServer(this._guildId);
|
||||
savedVol = set?.get?.("volume");
|
||||
} else if (this.client?.settings?.getServer) {
|
||||
savedVol = this.client.settings.getServer(this._guildId)?.get?.("volume");
|
||||
} else if (this.client?.settings?.get) {
|
||||
const s = this.client.settings.get(this._guildId);
|
||||
savedVol = s?.get?.("volume") ?? s?.volume;
|
||||
}
|
||||
|
||||
if (savedVol !== undefined && savedVol !== null) {
|
||||
const parsed = Number(savedVol);
|
||||
if (!Number.isNaN(parsed) && parsed > 0) {
|
||||
this.preferredVolume = Utils.clamp(parsed / 100, 0, 2);
|
||||
logger.player(`[Player] Restored volume ${savedVol}% for guild ${this._guildId}`);
|
||||
if (this._voiceConn) {
|
||||
try { this._voiceConn.setVolume(this.preferredVolume * 100); } catch (_) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @private @returns {boolean} Whether there are non-bot users in the channel. */
|
||||
_hasHumansInChannel() {
|
||||
return hasHumansInChannel({
|
||||
guildId: cleanId(this._guildId ?? ""),
|
||||
channelId: cleanId(this._channelId ?? ""),
|
||||
client: this.client,
|
||||
voiceCache: this._voiceCache,
|
||||
observedVoiceUsers: this._observedVoiceUsers,
|
||||
botId: this.client?.user?.id,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Start the inactivity timer. Skipped when 24/7 is active, the queue has
|
||||
* songs, or humans are present. The timer callback re-checks all
|
||||
* conditions before emitting autoleave.
|
||||
*/
|
||||
_startInactivityTimer() {
|
||||
this._stopInactivityTimer();
|
||||
if (this._inactivityLimit <= 0) return;
|
||||
|
||||
const mode = this._get247Mode();
|
||||
logger.inactivity(`[Player] Checking 24/7 mode for guild ${this._guildId}: ${mode}`);
|
||||
|
||||
if (mode === "on") {
|
||||
logger.inactivity(`[Player] 24/7 mode active for guild ${this._guildId}, skipping inactivity timer`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.queue?.getCurrent() || !this.queue?.isEmpty()) {
|
||||
logger.inactivity(`[Player] Queue has songs for guild ${this._guildId}, skipping inactivity timer`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._hasHumansInChannel()) {
|
||||
logger.inactivity(`[Player] Humans present in channel ${this._channelId}, skipping inactivity timer`);
|
||||
return;
|
||||
}
|
||||
|
||||
logger.inactivity(`[Player] Starting inactivity timer for guild ${this._guildId} (${this._inactivityLimit / 1000}s)`);
|
||||
this._inactivityTimer = setTimeout(() => {
|
||||
const currentMode = this._get247Mode();
|
||||
if (currentMode === "on") {
|
||||
logger.inactivity(`[Player] 24/7 mode enabled during inactivity wait, aborting leave`);
|
||||
return;
|
||||
}
|
||||
if (this.queue?.getCurrent() || !this.queue?.isEmpty()) {
|
||||
logger.inactivity("[Player] Song in queue during inactivity wait, aborting leave");
|
||||
return;
|
||||
}
|
||||
if (this._hasHumansInChannel()) {
|
||||
logger.inactivity("[Player] Human joined during inactivity wait, aborting leave");
|
||||
return;
|
||||
}
|
||||
logger.inactivity(`[Player] Guild ${this._guildId} inactive too long. Leaving.`);
|
||||
this.emit("autoleave");
|
||||
}, this._inactivityLimit);
|
||||
}
|
||||
|
||||
/** Clear the inactivity timer if running. */
|
||||
_stopInactivityTimer() {
|
||||
this._pendingInactivityCheck = false;
|
||||
if (this._inactivityTimer) {
|
||||
logger.inactivity(`[Player] Stopping inactivity timer for guild ${this._guildId}`);
|
||||
clearTimeout(this._inactivityTimer);
|
||||
this._inactivityTimer = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Schedule a 24/7 rejoin after a delay. Guards against destroyed players,
|
||||
* registered intentional leaves, and pending/duplicate joins.
|
||||
* @param {string} channelId - The channel to rejoin.
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @param {string} mode - The 24/7 mode ("on").
|
||||
* @private
|
||||
*/
|
||||
_schedule247Rejoin(channelId, guildId, mode) {
|
||||
const ctx = this.client?._remix;
|
||||
if (!ctx) {
|
||||
logger.warn(`[Player] Cannot schedule 24/7 rejoin for ${channelId} — no bot context`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (ctx.players?._pendingJoins?.has?.(channelId)) {
|
||||
logger.voice247(`[Player] 24/7 rejoin skipped for ${channelId} — join already pending`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (ctx.players?.playerMap?.has(channelId)) {
|
||||
const existing = ctx.players.playerMap.get(channelId);
|
||||
if (existing && !existing._destroyed && existing !== this) {
|
||||
logger.voice247(`[Player] 24/7 rejoin skipped for ${channelId} — another player already exists`);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
const rejoinDelay = ctx.config?.timers?.rejoin247Delay ?? 3_000;
|
||||
logger.voice247(`[Player] Scheduling 24/7 ${mode} rejoin for channel ${channelId} (guild ${guildId}) in ${rejoinDelay / 1000}s`);
|
||||
|
||||
this._rejoinTimer = setTimeout(() => {
|
||||
this._rejoinTimer = null;
|
||||
if (this._destroyed) {
|
||||
logger.voice247(`[Player] 24/7 rejoin cancelled — player destroyed`);
|
||||
return;
|
||||
}
|
||||
if (ctx.intentionalLeaves?.has(channelId)) {
|
||||
logger.voice247(`[Player] 24/7 rejoin cancelled — intentional leave registered`);
|
||||
return;
|
||||
}
|
||||
|
||||
ctx.gatewayHandler?._rejoinChannel?.(guildId, channelId).catch(err => {
|
||||
logger.warn(`[Player] 24/7 rejoin failed for channel ${channelId}:`, err?.message);
|
||||
});
|
||||
}, rejoinDelay);
|
||||
}
|
||||
|
||||
/**
|
||||
* @private Low-level HTTP(S) request helper with redirects and JSON parsing.
|
||||
* Used for Lavalink REST calls (pre-resolve, loadtracks).
|
||||
* @param {string} url
|
||||
* @param {object} [options={}]
|
||||
* @param {boolean} [returnStream=false]
|
||||
* @returns {Promise<object|null|import('node:stream').Readable>}
|
||||
*/
|
||||
async _request(url, options = {}, returnStream = false) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const fetchUrl = (target, _redirects = 0) => {
|
||||
const urlObj = new URL(target);
|
||||
const client = urlObj.protocol === "https:" ? https : http;
|
||||
|
||||
const req = client.request({
|
||||
protocol: urlObj.protocol,
|
||||
host: urlObj.hostname,
|
||||
port: urlObj.port,
|
||||
path: urlObj.pathname + urlObj.search,
|
||||
method: options.method || "GET",
|
||||
headers: {
|
||||
"User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)",
|
||||
"Accept": "*/*",
|
||||
...options.headers,
|
||||
},
|
||||
}, (res) => {
|
||||
if (returnStream) req.setTimeout(0);
|
||||
|
||||
if ([301, 302, 307, 308].includes(res.statusCode)) {
|
||||
let loc = res.headers.location;
|
||||
if (!loc) return reject(new Error("Redirect without location"));
|
||||
if (loc.startsWith("/")) loc = `${urlObj.protocol}//${urlObj.host}${loc}`;
|
||||
if (_redirects >= 5) return reject(new Error("Too many redirects"));
|
||||
const redirectUrl = new URL(loc);
|
||||
if (redirectUrl.host !== urlObj.host) {
|
||||
if (options.headers) delete options.headers.Authorization;
|
||||
}
|
||||
return fetchUrl(loc, _redirects + 1);
|
||||
}
|
||||
if (![200, 204, 206].includes(res.statusCode)) {
|
||||
res.resume();
|
||||
return reject(new Error(`HTTP ${res.statusCode}`));
|
||||
}
|
||||
if (returnStream) return resolve(res);
|
||||
|
||||
if (res.statusCode === 204) { res.resume(); return resolve(null); }
|
||||
|
||||
const chunks = [];
|
||||
res.on("data", d => chunks.push(d));
|
||||
res.on("end", () => {
|
||||
const raw = Buffer.concat(chunks).toString().trim();
|
||||
if (!raw) return resolve(null);
|
||||
try { resolve(JSON.parse(raw)); }
|
||||
catch (e) { reject(new Error(`JSON parse error from ${target}`)); }
|
||||
});
|
||||
});
|
||||
|
||||
req.on("error", reject);
|
||||
req.setTimeout(options.timeout || 60_000, () => {
|
||||
req.destroy();
|
||||
reject(new Error("Request timeout"));
|
||||
});
|
||||
if (options.body) req.write(options.body);
|
||||
req.end();
|
||||
};
|
||||
fetchUrl(url);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @async Join a voice channel via LiveKit. Sets up voice connection, event
|
||||
* listeners, and resumes playback if the queue has tracks.
|
||||
* @param {string} channelId - The voice channel ID to join.
|
||||
* @returns {Promise<void>}
|
||||
* @throws {Error} If the channel is not found, VoiceManager is unavailable, or connection fails.
|
||||
*/
|
||||
async join(channelId) {
|
||||
if (this._destroyed) return;
|
||||
|
||||
if (this._isJoining) {
|
||||
logger.player(`[Player] Busy joining. Ignoring: ${channelId}`);
|
||||
return;
|
||||
}
|
||||
if (this._voiceConn && this._channelId === channelId) {
|
||||
logger.player(`[Player] Already in channel: ${channelId}`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this._voiceConn) {
|
||||
logger.player("[Player] Cleaning up existing voice connection before join");
|
||||
this._bridgeStop();
|
||||
try { await this._voiceConn.disconnect(); } catch(e) { logger.warn("[Player] Existing voiceConn disconnect error:", e?.message); }
|
||||
this._voiceConn = null;
|
||||
this.connection = null;
|
||||
await Utils.sleep(500);
|
||||
}
|
||||
|
||||
this._isJoining = true;
|
||||
try {
|
||||
const channel = this.client?.channels?.get?.(channelId);
|
||||
if (!channel) throw new Error(`Channel not found: ${channelId}`);
|
||||
|
||||
if (this._lavalink) {
|
||||
logger.player(`[Player] Waiting for Lavalink node...`);
|
||||
await this._lavalink.waitForNode({ timeoutMs: 15_000 });
|
||||
}
|
||||
|
||||
this._channelId = channelId;
|
||||
this._guildId = cleanId(channel.guildId);
|
||||
this._lastConnectedAt = Date.now();
|
||||
this.leaving = false;
|
||||
|
||||
logger.player(`[Player] Joining channel ${channelId} via vm.join() (LiveKit)...`);
|
||||
const vm = getVoiceManager(this.client);
|
||||
if (!vm) {
|
||||
throw new Error("VoiceManager not available — call getVoiceManager(client) before login");
|
||||
}
|
||||
|
||||
let voiceConn;
|
||||
try {
|
||||
voiceConn = await vm.join(channel);
|
||||
} catch (e) {
|
||||
throw new Error(`vm.join() failed for channel ${channelId}: ${e.message}`);
|
||||
}
|
||||
|
||||
if (!voiceConn) {
|
||||
throw new Error(`vm.join() returned null for channel ${channelId}`);
|
||||
}
|
||||
|
||||
this._voiceConn = voiceConn;
|
||||
this.connection = voiceConn;
|
||||
|
||||
if (typeof voiceConn.isConnected === "function" && !voiceConn.isConnected()) {
|
||||
logger.player("[Player] Waiting for LiveKit room to connect...");
|
||||
await new Promise((resolve, reject) => {
|
||||
const timeout = setTimeout(() => reject(new Error("LiveKit connection timeout (15s)")), 15_000);
|
||||
const check = () => {
|
||||
try {
|
||||
if (voiceConn.isConnected()) { clearTimeout(timeout); return resolve(); }
|
||||
if (voiceConn.connectionState === 0) { clearTimeout(timeout); return resolve(); }
|
||||
} catch (_) { clearTimeout(timeout); return resolve(); }
|
||||
setTimeout(check, 200);
|
||||
};
|
||||
check();
|
||||
});
|
||||
await Utils.sleep(500);
|
||||
}
|
||||
|
||||
logger.player(`[Player] LiveKit voice connected (guild: ${this._guildId}, channel: ${channelId})` +
|
||||
` isConnected=${voiceConn.isConnected ? voiceConn.isConnected() : 'unknown'}`);
|
||||
|
||||
this._assertSelfDeaf(vm, channelId);
|
||||
|
||||
if (typeof voiceConn.on === "function") {
|
||||
// Self-deaf keeper: Fluxer's VoiceManager answers every
|
||||
// requestVoiceStateSync event (emitted by conn.stop()/stopVideo(),
|
||||
// which the audio bridge triggers on EVERY play() and stop()) with a
|
||||
// gateway VoiceStateUpdate that resets self_deaf to false — silently
|
||||
// un-deafening the bot the moment the first track starts and again on
|
||||
// every skip/stop/track-end. The manager registers its own sync
|
||||
// listener inside registerConnection() (before join() resolved), so
|
||||
// this listener runs AFTER it and our re-deafen state update wins.
|
||||
voiceConn.on("requestVoiceStateSync", () => {
|
||||
if (this.leaving || this._destroyed) return;
|
||||
this._assertSelfDeaf(vm, channelId);
|
||||
});
|
||||
|
||||
voiceConn.on("serverLeave", () => {
|
||||
if (this.leaving || this._destroyed) return;
|
||||
logger.player(`[Player] serverLeave received — Fluxer/LiveKit terminated session`);
|
||||
this._voiceConn = null;
|
||||
this.connection = null;
|
||||
this._paused = true;
|
||||
this._stopInactivityTimer();
|
||||
|
||||
const mode = this._get247Mode();
|
||||
const cId = cleanId(this._channelId ?? this._home247Channel ?? "");
|
||||
const gId = cleanId(this._guildId ?? "");
|
||||
|
||||
if (mode === "on") {
|
||||
logger.player("[Player] serverLeave in 24/7 mode — scheduling rejoin");
|
||||
this.emit("autoleave");
|
||||
if (cId && gId) this._schedule247Rejoin(cId, gId, mode);
|
||||
} else {
|
||||
logger.player("[Player] Unexpected serverLeave");
|
||||
this.emit("autoleave");
|
||||
}
|
||||
});
|
||||
|
||||
voiceConn.on("disconnect", () => {
|
||||
if (this.leaving || this._destroyed) return;
|
||||
logger.player(`[Player] Voice connection disconnected`);
|
||||
});
|
||||
}
|
||||
|
||||
this._restoreVolume();
|
||||
this.emit("roomfetched");
|
||||
logger.player(`[Player] Voice connected to ${channel.name || channelId}`);
|
||||
|
||||
if (!this.queue.isEmpty() && !this.queue.getCurrent()) {
|
||||
this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
|
||||
} else if (this.queue.isEmpty()) {
|
||||
this._pendingInactivityCheck = true;
|
||||
setTimeout(() => {
|
||||
if (!this._pendingInactivityCheck) return;
|
||||
this._pendingInactivityCheck = false;
|
||||
if (this.queue.isEmpty() && !this.queue.getCurrent()) {
|
||||
this._startInactivityTimer();
|
||||
}
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
const causeStr = e.cause ? ` (Cause: ${e.cause})` : "";
|
||||
logger.error("[Player] Join failed:", e.message, causeStr);
|
||||
|
||||
if (this._voiceConn) {
|
||||
try { await this._voiceConn.disconnect(); } catch(err) { logger.warn("[Player] voiceConn disconnect on join failure:", err?.message); }
|
||||
this._voiceConn = null;
|
||||
this.connection = null;
|
||||
}
|
||||
throw e;
|
||||
} finally {
|
||||
this._isJoining = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @async Leave the current voice channel. Stops playback, resets state, and
|
||||
* cleans up the voice connection.
|
||||
* @returns {Promise<boolean>} True if leave was successful, false otherwise.
|
||||
*/
|
||||
async leave() {
|
||||
if (!this._voiceConn && !this.connection) return false;
|
||||
try {
|
||||
this.leaving = true;
|
||||
this._stopInactivityTimer();
|
||||
this._clearTrackEndTimer();
|
||||
this._activeTrackOpt = null;
|
||||
|
||||
const channelId = this._channelId;
|
||||
|
||||
this._bridgeStop();
|
||||
|
||||
try {
|
||||
const vm = getVoiceManager(this.client);
|
||||
if (channelId) {
|
||||
vm.leaveChannel(channelId);
|
||||
logger.player("[Player] Left channel " + channelId + " via vm.leaveChannel()");
|
||||
}
|
||||
} catch(e) { logger.warn("[Player] Gateway leave error:", e?.message); }
|
||||
|
||||
if (this._voiceConn) {
|
||||
try { await this._voiceConn.disconnect(); } catch(e) { logger.warn("[Player] voiceConn disconnect error:", e?.message); }
|
||||
}
|
||||
|
||||
if (this._audioBridge) {
|
||||
this._audioBridge.stop();
|
||||
}
|
||||
|
||||
this.queue.reset();
|
||||
this._voiceConn = null;
|
||||
this.lavalinkPlayer = null;
|
||||
this.connection = null;
|
||||
this._paused = false;
|
||||
this._pausedAt = null;
|
||||
this._playingNext = false;
|
||||
this._autoplay = false;
|
||||
if (this._autoplayHandler) {
|
||||
this.removeListener("queueEnd", this._autoplayHandler);
|
||||
this._autoplayHandler = null;
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error("[Player] leave error:", e.message);
|
||||
this.leaving = false;
|
||||
return false;
|
||||
}
|
||||
this.leaving = false;
|
||||
this.emit("leave");
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fully destroy this player instance: clean up timers, listeners,
|
||||
* connections, and resources.
|
||||
*/
|
||||
destroy() {
|
||||
if (this._destroyed) return;
|
||||
this._destroyed = true;
|
||||
|
||||
this._clearTrackEndTimer();
|
||||
this._activeTrackOpt = null;
|
||||
|
||||
try {
|
||||
if (this._lavalink) {
|
||||
if (this._onLavalinkPlayerDisconnect) {
|
||||
try { this._lavalink.off("playerDisconnected", this._onLavalinkPlayerDisconnect); } catch(e) { /* best effort */ }
|
||||
this._onLavalinkPlayerDisconnect = null;
|
||||
}
|
||||
}
|
||||
this.leaving = true;
|
||||
this._stopInactivityTimer();
|
||||
if (this._rejoinTimer) { clearTimeout(this._rejoinTimer); this._rejoinTimer = null; }
|
||||
this._autoplay = false;
|
||||
if (this._autoplayHandler) {
|
||||
this.removeListener("queueEnd", this._autoplayHandler);
|
||||
this._autoplayHandler = null;
|
||||
}
|
||||
this.searches.clear();
|
||||
|
||||
this._bridgeStop();
|
||||
if (this._audioBridge) {
|
||||
this._audioBridge.destroy();
|
||||
this._audioBridge = null;
|
||||
}
|
||||
if (this._voiceConn) {
|
||||
try { this._voiceConn.disconnect(); } catch(e) { logger.warn("[Player] voiceConn disconnect in destroy:", e?.message); }
|
||||
this._voiceConn = null;
|
||||
}
|
||||
this.lavalinkPlayer = null;
|
||||
this.connection = null;
|
||||
|
||||
if (this._channelId) {
|
||||
try {
|
||||
const vm = getVoiceManager(this.client);
|
||||
vm.leaveChannel(this._channelId);
|
||||
} catch(e) { /* best effort */ }
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error("[Player] destroy error:", e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/** @type {boolean} Whether the player is currently paused. */
|
||||
get paused() { return this._paused; }
|
||||
|
||||
/**
|
||||
* Pause current playback.
|
||||
* @returns {string} Status message.
|
||||
*/
|
||||
pause() {
|
||||
if (!this._voiceConn || !this.queue.getCurrent())
|
||||
return ":negative_squared_cross_mark: There's nothing playing at the moment!";
|
||||
if (this._paused)
|
||||
return ":negative_squared_cross_mark: Already paused!";
|
||||
|
||||
this._bridgeStop();
|
||||
this._paused = true;
|
||||
this._pausedAt = Date.now();
|
||||
this._pauseTrackEndTimer();
|
||||
this.emit("playback", false);
|
||||
this._stopInactivityTimer();
|
||||
return ":pause_button: Paused";
|
||||
}
|
||||
|
||||
/**
|
||||
* Resume paused playback.
|
||||
* @returns {string} Status message.
|
||||
*/
|
||||
resume() {
|
||||
if (!this._voiceConn || !this.queue.getCurrent())
|
||||
return ":negative_squared_cross_mark: There's nothing playing at the moment!";
|
||||
if (!this._paused)
|
||||
return ":negative_squared_cross_mark: Not paused!";
|
||||
|
||||
if (this._pausedAt) {
|
||||
this.startedPlaying += (Date.now() - this._pausedAt);
|
||||
}
|
||||
|
||||
this._paused = false;
|
||||
this._pausedAt = null;
|
||||
this._resumeTrackEndTimer();
|
||||
this.emit("playback", true);
|
||||
this._stopInactivityTimer();
|
||||
|
||||
const current = this.queue.getCurrent();
|
||||
if (current?.url) {
|
||||
const elapsedMs = Date.now() - this.startedPlaying;
|
||||
this._playTrackViaBridge(current, { seekSeconds: elapsedMs / 1000 }).catch(e =>
|
||||
logger.error("[Player] Resume playback error:", e.message)
|
||||
);
|
||||
}
|
||||
return ":arrow_forward: Resumed";
|
||||
}
|
||||
|
||||
/**
|
||||
* Skip the current track and advance to the next. Emits "trackSkip" with
|
||||
* the skipped track so autoplay (when enabled) can replenish the queue.
|
||||
* @returns {string} Status message.
|
||||
*/
|
||||
skip() {
|
||||
if (!this._voiceConn || !this.queue.getCurrent())
|
||||
return ":negative_squared_cross_mark: There's nothing playing at the moment!";
|
||||
this._lastPlayedTrack = this.queue.getCurrent();
|
||||
this._skipping = true;
|
||||
this._radioAnnounced = false;
|
||||
this._activeTrackOpt = null;
|
||||
this._clearTrackEndTimer();
|
||||
this.queue.current = null;
|
||||
|
||||
this._bridgeStop();
|
||||
|
||||
this.emit("trackSkip", this._lastPlayedTrack);
|
||||
|
||||
if (this.queue.isEmpty() && !this._wasRadio && !this._queueEndedSent) {
|
||||
this._queueEndedSent = true;
|
||||
this.emit("queueEnd");
|
||||
if (!this._autoplay) {
|
||||
const prefix = this._getPrefix?.(this._guildId) ?? "%";
|
||||
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true });
|
||||
}
|
||||
}
|
||||
|
||||
this._playingNext = false;
|
||||
if (!this.queue.isEmpty() && !this.leaving) {
|
||||
this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
|
||||
} else {
|
||||
this.emit("stopplay");
|
||||
if (!this._is247Enabled()) {
|
||||
this._startInactivityTimer();
|
||||
}
|
||||
}
|
||||
|
||||
this._skipping = false;
|
||||
return ":track_next: Skipped";
|
||||
}
|
||||
|
||||
/**
|
||||
* Skip to a specific position in the queue.
|
||||
* @param {number} position - 1-based queue position.
|
||||
* @returns {string} Status message.
|
||||
*/
|
||||
skipTo(position) {
|
||||
if (!this._voiceConn || !this.queue.getCurrent())
|
||||
return ":negative_squared_cross_mark: There's nothing playing at the moment!";
|
||||
const idx = position - 1;
|
||||
if (idx < 0 || idx >= this.queue.size())
|
||||
return `:negative_squared_cross_mark: Position ${position} out of range (queue has ${this.queue.size()} tracks).`;
|
||||
this._lastPlayedTrack = this.queue.getCurrent();
|
||||
this.queue.data.splice(0, idx);
|
||||
this.queue.current = null;
|
||||
this._skipping = true;
|
||||
|
||||
this._bridgeStop();
|
||||
|
||||
this.emit("trackSkip", this._lastPlayedTrack);
|
||||
|
||||
if (this.queue.isEmpty() && !this._wasRadio && !this._queueEndedSent) {
|
||||
this._queueEndedSent = true;
|
||||
this.emit("queueEnd");
|
||||
if (!this._autoplay) {
|
||||
const prefix = this._getPrefix?.(this._guildId) ?? "%";
|
||||
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true });
|
||||
}
|
||||
}
|
||||
|
||||
this._playingNext = false;
|
||||
if (!this.queue.isEmpty() && !this.leaving) {
|
||||
this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
|
||||
} else {
|
||||
this.emit("stopplay");
|
||||
if (!this._is247Enabled()) {
|
||||
this._startInactivityTimer();
|
||||
}
|
||||
}
|
||||
|
||||
this._skipping = false;
|
||||
return `:track_next: Skipped to position ${position}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the playback volume.
|
||||
* @param {number} v - Volume as a decimal (0–2, where 1 = 100%).
|
||||
* @returns {string} Status message.
|
||||
*/
|
||||
setVolume(v) {
|
||||
this.preferredVolume = Utils.clamp(v, 0, 2);
|
||||
this.emit("volume", this.preferredVolume);
|
||||
if (this._voiceConn) {
|
||||
this._voiceConn.setVolume(this.preferredVolume * 100);
|
||||
}
|
||||
if (!this._voiceConn)
|
||||
return `Volume set to \`${Math.round(this.preferredVolume * 100)}%\` — will apply when connected.`;
|
||||
return `Volume changed to \`${Math.round(this.preferredVolume * 100)}%\`.`;
|
||||
}
|
||||
|
||||
/** @returns {boolean} Whether the queue is empty. */
|
||||
isEmpty() { return this.queue.isEmpty(); }
|
||||
|
||||
/**
|
||||
* Add a track to the queue with optional top-insert.
|
||||
* @param {object} d - Track data.
|
||||
* @param {boolean} [t=false] - Insert at the top of the queue.
|
||||
*/
|
||||
addToQueue(d, t) {
|
||||
if (this.queue.data.length >= this._maxQueueSize) {
|
||||
logger.warn(`[Player] Queue size cap reached (${this._maxQueueSize}) — dropping oldest track`);
|
||||
this.queue.data.shift();
|
||||
}
|
||||
this.queue.add(d, t);
|
||||
this.emit("update", "queue");
|
||||
this._stopInactivityTimer();
|
||||
}
|
||||
|
||||
/** Clear the queue and start the inactivity timer if nothing is playing. */
|
||||
clear() {
|
||||
this.queue.clear();
|
||||
this.emit("update", "queue");
|
||||
if (!this.queue.getCurrent()) {
|
||||
this._startInactivityTimer();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add multiple tracks to the queue.
|
||||
* @param {Array} t - Track data array.
|
||||
* @param {boolean} [top=false] - Insert at the top.
|
||||
* @returns {number} Number of tracks added.
|
||||
*/
|
||||
addManyToQueue(t, top = false) {
|
||||
if (!Array.isArray(t)) return 0;
|
||||
const overflow = (this.queue.data.length + t.length) - this._maxQueueSize;
|
||||
if (overflow > 0) {
|
||||
logger.warn(`[Player] Queue size cap (${this._maxQueueSize}) — dropping ${overflow} oldest tracks`);
|
||||
this.queue.data.splice(0, overflow);
|
||||
}
|
||||
const added = this.queue.addMany(t, top);
|
||||
this.emit("update", "queue");
|
||||
this._stopInactivityTimer();
|
||||
return added;
|
||||
}
|
||||
|
||||
/**
|
||||
* Shuffle the queue.
|
||||
* @returns {string} Status message.
|
||||
*/
|
||||
shuffle() {
|
||||
if (this.isEmpty()) return "There is nothing to shuffle in the queue.";
|
||||
this.queue.shuffle();
|
||||
this.emit("update", "queue");
|
||||
return ":twisted_rightwards_arrows: Shuffled queue";
|
||||
}
|
||||
|
||||
/**
|
||||
* Move a track from one position to another (1-based indices).
|
||||
* @param {number} from
|
||||
* @param {number} to
|
||||
* @returns {string} Result message.
|
||||
*/
|
||||
move(from, to) {
|
||||
if (this.queue.size() === 0) return "The queue is empty.";
|
||||
return this.queue.move(from - 1, to - 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* Toggle a loop mode.
|
||||
* @param {"song"|"queue"} choice
|
||||
* @returns {string}
|
||||
*/
|
||||
loop(choice) {
|
||||
if (!["song", "queue"].includes(choice))
|
||||
return `'${choice}' is not valid. Use \`song\` or \`queue\``;
|
||||
const state = this.queue.toggleLoop(choice);
|
||||
const name = choice.charAt(0).toUpperCase() + choice.slice(1);
|
||||
return state
|
||||
? `:repeat: ${name} loop activated`
|
||||
: `:arrow_right: ${name} loop disabled`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a track from the queue by index.
|
||||
* @param {number} index - 0-based.
|
||||
* @returns {string}
|
||||
* @throws {Error} If index is empty.
|
||||
*/
|
||||
remove(index) {
|
||||
if (index === undefined || index === null) throw new Error("Index can't be empty");
|
||||
const oldSize = this.queue.size();
|
||||
const msg = this.queue.remove(index);
|
||||
if (oldSize !== this.queue.size()) this.emit("update", "queue");
|
||||
|
||||
if (this.isEmpty() && !this.queue.getCurrent()) {
|
||||
this._startInactivityTimer();
|
||||
}
|
||||
return msg;
|
||||
}
|
||||
|
||||
/** @private Stop the audio bridge if currently playing. */
|
||||
_bridgeStop() {
|
||||
if (this._audioBridge?.playing) {
|
||||
this._audioBridge.stop();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @private Send the self-deafen voice state update. Best effort: the
|
||||
* VoiceManager silently no-ops when the connection has no connection_id
|
||||
* yet (missing from VoiceServerUpdate) — re-sent after every
|
||||
* requestVoiceStateSync so later attempts still land once it exists.
|
||||
* @param {object} vm - VoiceManager instance.
|
||||
* @param {string} channelId - Voice channel ID.
|
||||
*/
|
||||
_assertSelfDeaf(vm, channelId) {
|
||||
try {
|
||||
vm.updateVoiceState(channelId, { self_deaf: true, self_mute: false });
|
||||
} catch (e) {
|
||||
logger.warn("[Player] Self-deafen failed:", e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @private Translate a locale key for this player's guild.
|
||||
* @param {string} key
|
||||
* @param {object} [replacements={}]
|
||||
* @returns {string}
|
||||
*/
|
||||
_t(key, replacements = {}) {
|
||||
if (!this.locale) return key;
|
||||
return this.locale.translate(this._guildId, key, replacements);
|
||||
}
|
||||
}
|
||||
|
||||
// Attach the split-out concerns: playback advancement (PlaybackMixin), search
|
||||
// & queue-filling (SearchMixin), and user-facing rendering (DisplayMixin).
|
||||
applyMixins(Player, PlaybackMixin, SearchMixin, DisplayMixin);
|
||||
|
||||
export { Player as default, Player, Queue };
|
||||
@@ -0,0 +1,168 @@
|
||||
/**
|
||||
* @module src/music/player/Queue
|
||||
* @description Queue data structure: track list, loop modes (song/queue),
|
||||
* add/remove/move/shuffle/pagination, and queue events.
|
||||
*/
|
||||
|
||||
import { EventEmitter } from "node:events";
|
||||
import { Utils } from "../../utils/Utils.mjs";
|
||||
|
||||
/**
|
||||
* @class Queue
|
||||
* @description Internal queue data structure that tracks tracks, loop state,
|
||||
* and emits queue events.
|
||||
* @extends {EventEmitter}
|
||||
*
|
||||
* Events (all emitted as `"queue"` with `{ type, data }`):
|
||||
* - `update` — the current track advanced
|
||||
* - `remove` / `move` / `add` / `addMany` / `shuffle`
|
||||
*/
|
||||
export class Queue extends EventEmitter {
|
||||
/** @type {Array<object>} The queued track objects. */
|
||||
data = [];
|
||||
/** @type {object|null} The currently playing track. */
|
||||
current = null;
|
||||
/** @type {boolean} Whether queue loop is enabled. */
|
||||
loop = false;
|
||||
/** @type {boolean} Whether single-song loop is enabled. */
|
||||
songLoop = false;
|
||||
|
||||
/** Initialize an empty queue with no loop enabled. */
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
/** @returns {boolean} Whether the queue has no tracks. */
|
||||
isEmpty() { return this.data.length === 0; }
|
||||
/** @returns {number} Number of tracks in the queue (excluding current). */
|
||||
size() { return this.data.length; }
|
||||
|
||||
/**
|
||||
* Advance to the next track in the queue. If songLoop is active, returns
|
||||
* the current track. If queue loop is active, re-appends the current track.
|
||||
* @returns {object|null} The next track, or null if the queue is empty.
|
||||
*/
|
||||
next() {
|
||||
const previous = this.current;
|
||||
|
||||
if (this.songLoop && this.current) return this.current;
|
||||
if (this.loop && this.current) this.data.push(this.current);
|
||||
|
||||
if (this.isEmpty()) {
|
||||
this.current = null;
|
||||
return null;
|
||||
}
|
||||
|
||||
this.current = this.data.shift();
|
||||
this.emit("queue", {
|
||||
type: "update",
|
||||
data: { current: this.current, old: previous, loop: this.loop }
|
||||
});
|
||||
return this.current;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a track from the queue by index.
|
||||
* @param {number} idx - Zero-based index of the track to remove.
|
||||
* @returns {string} Result message indicating success or out-of-bounds error.
|
||||
*/
|
||||
remove(idx) {
|
||||
if (idx < 0 || idx >= this.data.length) return "Index out of bounds";
|
||||
const title = this.data[idx].title;
|
||||
const removed = this.data.splice(idx, 1);
|
||||
this.emit("queue", { type: "remove", data: { index: idx, old: this.data.slice(), removed, new: this.data } });
|
||||
return `Successfully removed **${title}** from the queue.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Move a track from one position to another (0-based indices).
|
||||
* @param {number} from - Source index.
|
||||
* @param {number} to - Destination index.
|
||||
* @returns {string} Result message indicating success or error.
|
||||
*/
|
||||
move(from, to) {
|
||||
if (from < 0 || from >= this.data.length) return "Source index out of bounds";
|
||||
if (to < 0 || to >= this.data.length) return "Target index out of bounds";
|
||||
if (from === to) return "Track is already in that position";
|
||||
const [track] = this.data.splice(from, 1);
|
||||
this.data.splice(to, 0, track);
|
||||
this.emit("queue", { type: "move", data: { from, to, track } });
|
||||
return `Moved **${track.title}** from position ${from + 1} to ${to + 1}.`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a single track to the queue.
|
||||
* @param {object} data - Track data object.
|
||||
* @param {boolean} [top=false] - If true, insert at the front of the queue.
|
||||
* @returns {number} The new length of the queue.
|
||||
*/
|
||||
add(data, top = false) {
|
||||
this.emit("queue", { type: "add", data: { append: !top, data } });
|
||||
return top ? this.data.unshift(data) : this.data.push(data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Add multiple tracks to the queue (up to 1000).
|
||||
* @param {Array<object>} tracks - Array of track data objects.
|
||||
* @param {boolean} [top=false] - If true, insert at the front of the queue.
|
||||
* @returns {number} Number of tracks actually added.
|
||||
*/
|
||||
addMany(tracks, top = false) {
|
||||
if (!tracks?.length) return 0;
|
||||
if (!Array.isArray(tracks)) tracks = [];
|
||||
const count = Math.min(tracks.length, 1000);
|
||||
if (top) {
|
||||
for (let i = count - 1; i >= 0; i--) this.data.unshift(tracks[i]);
|
||||
} else {
|
||||
for (let i = 0; i < count; i++) this.data.push(tracks[i]);
|
||||
}
|
||||
this.emit("queue", { type: "addMany", data: { append: !top, tracks: tracks.slice(0, count) } });
|
||||
return count;
|
||||
}
|
||||
|
||||
/** Remove all tracks from the queue. */
|
||||
clear() { this.data.length = 0; }
|
||||
/** Clear the queue and reset all state (current, loops). */
|
||||
reset() { this.clear(); this.current = null; this.songLoop = false; this.loop = false; }
|
||||
|
||||
/** @param {boolean} bool - Enable or disable song loop. */
|
||||
setSongLoop(bool) { this.songLoop = bool; }
|
||||
/** @param {boolean} bool - Enable or disable queue loop. */
|
||||
setLoop(bool) { this.loop = bool; }
|
||||
|
||||
/**
|
||||
* Toggle a loop mode on or off.
|
||||
* @param {"song"|"queue"} loop - The type of loop to toggle.
|
||||
* @returns {boolean|null} The new loop state, or null if the loop type is invalid.
|
||||
*/
|
||||
toggleLoop(loop) {
|
||||
if (loop === "song") { this.setSongLoop(!this.songLoop); return this.songLoop; }
|
||||
if (loop === "queue") { this.setLoop(!this.loop); return this.loop; }
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Shuffle the queue in place and emit a queue event. */
|
||||
shuffle() {
|
||||
Utils.shuffleArr(this.data);
|
||||
this.emit("queue", { type: "shuffle", data: this.data });
|
||||
}
|
||||
|
||||
/** @returns {object|null} The currently playing track. */
|
||||
getCurrent() { return this.current; }
|
||||
/** @returns {Array<object>} A copy of the queue array. */
|
||||
getQueue() { return this.data; }
|
||||
|
||||
/**
|
||||
* Get a paginated slice of the queue.
|
||||
* @param {number} [page=1] - 1-based page number (clamped to valid range).
|
||||
* @param {number} [pageSize=10] - Number of tracks per page.
|
||||
* @returns {object} Page result with items, page, totalPages, total, start.
|
||||
*/
|
||||
getPage(page = 1, pageSize = 10) {
|
||||
const total = this.data.length;
|
||||
const totalPages = Math.max(1, Math.ceil(total / pageSize));
|
||||
const safePage = Utils.clamp(page, 1, totalPages);
|
||||
const start = (safePage - 1) * pageSize;
|
||||
return { items: this.data.slice(start, start + pageSize), page: safePage, totalPages, total, start };
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,484 @@
|
||||
/**
|
||||
* @module src/music/player/SearchMixin
|
||||
* @description Search & queue-filling concern for {@link Player}: Lavalink
|
||||
* queries, search sessions with interactive selection, YouTube fallbacks,
|
||||
* radio/external track builders.
|
||||
*
|
||||
* These methods are applied onto the Player class prototype via
|
||||
* {@link applyMixins} — `this` is a Player instance.
|
||||
*/
|
||||
|
||||
import { EventEmitter } from "node:events";
|
||||
import { Utils } from "../../utils/Utils.mjs";
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
import { PROVIDERS, PROVIDER_NAMES } from "../providers.mjs";
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
* @description Search mixin — applied to Player.
|
||||
*/
|
||||
const SearchMixin = {
|
||||
/**
|
||||
* @async Resolve a free-text query or URL to track data via Lavalink for
|
||||
* internal consumers (autoplay, Last.fm). URL queries are loaded directly
|
||||
* (like play()) so playlist/mix URLs resolve to their full track lists.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {{query: string, provider?: string, trackMeta?: object}} opts
|
||||
* @returns {Promise<{type: "video"|"list"|"error", data?: object}|null>}
|
||||
*/
|
||||
async generalQuery({ query, provider = "yt", trackMeta = null }) {
|
||||
try {
|
||||
if (!this._lavalink) return { type: "error", data: "Audio node not ready." };
|
||||
await this._lavalink.waitForNode({ timeoutMs: 15_000 });
|
||||
const isUrl = typeof query === "string" && Utils.isValidUrl(query);
|
||||
const result = isUrl
|
||||
? await this._lavalink.search(query)
|
||||
: await this._lavalink.search(query, { source: this._getSource(provider) });
|
||||
const tracks = (result?.tracks ?? []).map(t => this._lcTrackToVideo(t, trackMeta)).filter(Boolean);
|
||||
if (!tracks.length) return null;
|
||||
return tracks.length === 1 ? { type: "video", data: tracks[0] } : { type: "list", data: tracks };
|
||||
} catch (err) {
|
||||
logger.warn("[Player] generalQuery failed:", err?.message);
|
||||
return { type: "error", data: err?.message ?? String(err) };
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* @async Search for tracks via Lavalink and store results for interactive
|
||||
* selection.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {string} query - The search query string.
|
||||
* @param {string} id - A unique key to identify this search session (e.g. message ID).
|
||||
* @param {string} [provider="ytm"] - The search provider key.
|
||||
* @returns {Promise<{m: string, count: number}>} Formatted result list message and track count.
|
||||
*/
|
||||
async fetchResults(query, id, provider = "ytm") {
|
||||
try {
|
||||
if (!this._lavalink) return { m: "Audio node not ready.", count: 0 };
|
||||
|
||||
await this._lavalink.waitForNode({ timeoutMs: 15_000 });
|
||||
|
||||
const source = this._getSource(provider);
|
||||
const result = await this._lavalink.search(query, { source });
|
||||
const lcTracks = result?.tracks ?? [];
|
||||
|
||||
const results = lcTracks.slice(0, this.resultLimit).map(t => this._lcTrackToVideo(t)).filter(Boolean);
|
||||
|
||||
let list = "Search results using **" + (PROVIDER_NAMES[provider] || "YouTube Music") + "**:\n\n";
|
||||
results.forEach((v, i) => {
|
||||
const url = v.url || "";
|
||||
const title = v.title || Utils.formatTrackInfo(v, false);
|
||||
const dur = v.duration ? this.getDuration(v.duration) : "?:??";
|
||||
list += (i + 1) + ". [" + title + "](" + url + ") - " + dur + "\n";
|
||||
});
|
||||
list += "\nSend the number of the result. Example: `2`\nSend 'x' to cancel.";
|
||||
|
||||
if (this.searches.size >= this._searchMaxSize) {
|
||||
const oldestKey = this.searches.keys().next().value;
|
||||
if (oldestKey !== undefined) this.searches.delete(oldestKey);
|
||||
}
|
||||
this.searches.set(id, results);
|
||||
|
||||
return { m: list, count: results.length };
|
||||
} catch (err) {
|
||||
return { m: "Error searching: " + err.message, count: 0 };
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Select a search result and add it to the queue.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {string} id
|
||||
* @param {number} [result=0]
|
||||
* @param {boolean} [next=false]
|
||||
* @returns {object|null}
|
||||
*/
|
||||
playResult(id, result = 0, next = false) {
|
||||
if (!this.searches.has(id)) return null;
|
||||
const searchResults = this.searches.get(id);
|
||||
if (!searchResults || !searchResults[result]) return null;
|
||||
|
||||
const res = searchResults[result];
|
||||
this.addToQueue(res, next);
|
||||
|
||||
this.searches.delete(id);
|
||||
|
||||
if (!this.queue.getCurrent()) {
|
||||
this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
|
||||
}
|
||||
return res;
|
||||
},
|
||||
|
||||
/**
|
||||
* Search and add a track to the top of the queue.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {string} query
|
||||
* @param {string} provider
|
||||
* @param {object} trackMeta
|
||||
* @returns {EventEmitter}
|
||||
*/
|
||||
playFirst(query, provider, trackMeta) { return this.play(query, true, provider, trackMeta); },
|
||||
|
||||
/**
|
||||
* @private Convert a Lavalink track to the internal track format.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {object} track
|
||||
* @param {object|null} [trackMeta=null]
|
||||
* @returns {object|null}
|
||||
*/
|
||||
_lcTrackToVideo(track, trackMeta = null) {
|
||||
if (!track || typeof track !== "object") return null;
|
||||
const info = track.info ?? track ?? {};
|
||||
|
||||
let ms = info.length ?? track.length ?? info.durationMs ?? 0;
|
||||
if (ms === 0 && info.duration != null) {
|
||||
if (typeof info.duration === "number") {
|
||||
ms = info.duration;
|
||||
} else if (typeof info.duration === "object" && info.duration.seconds != null) {
|
||||
ms = info.duration.seconds * 1000;
|
||||
}
|
||||
}
|
||||
|
||||
let trackUri = info.uri ?? ("https://www.youtube.com/watch?v=" + (info.identifier || ""));
|
||||
if (typeof trackUri === 'string' && trackUri.includes('music.youtube.com')) {
|
||||
trackUri = trackUri.replace('music.youtube.com', 'www.youtube.com');
|
||||
}
|
||||
const video = {
|
||||
videoId: info.identifier ?? "",
|
||||
encoded: track.encoded ?? info.encoded ?? "",
|
||||
sourceName: info.sourceName ?? "unknown",
|
||||
title: Utils.cleanTitle(info.title ?? "Unknown"),
|
||||
url: trackUri,
|
||||
thumbnail: info.artworkUrl ?? null,
|
||||
spotifyUrl: null,
|
||||
_durationMs: ms,
|
||||
duration: {
|
||||
timestamp: Utils.prettifyMS(ms),
|
||||
seconds: Math.floor(ms / 1000),
|
||||
},
|
||||
author: {
|
||||
name: info.author ?? "Unknown",
|
||||
url: info.uri ?? null,
|
||||
},
|
||||
artists: null,
|
||||
};
|
||||
if (trackMeta) {
|
||||
video.artist = trackMeta.artist ?? null;
|
||||
video.requestedArtist = trackMeta.artist ?? null;
|
||||
video.requestedTitle = trackMeta.name ?? trackMeta.title ?? null;
|
||||
video.lastfm = {
|
||||
source: trackMeta.source ?? "lastfm",
|
||||
artist: trackMeta.artist ?? null,
|
||||
name: trackMeta.name ?? trackMeta.title ?? null,
|
||||
url: trackMeta.url ?? "",
|
||||
};
|
||||
}
|
||||
return video;
|
||||
},
|
||||
|
||||
/**
|
||||
* @private Resolve a provider key to a Lavalink search prefix.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {string} provider
|
||||
* @returns {string}
|
||||
*/
|
||||
_getSource(provider) {
|
||||
return PROVIDERS[provider]?.prefix ?? (provider + "search");
|
||||
},
|
||||
|
||||
/**
|
||||
* Search for a track and add it to the queue. Handles URL loading with
|
||||
* YouTube normalization + oEmbed title fallback and playlist expansion.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {string} query
|
||||
* @param {boolean} [top=false]
|
||||
* @param {string} [provider]
|
||||
* @param {object} [trackMeta=null]
|
||||
* @returns {EventEmitter} Emits "message" events with status strings.
|
||||
*/
|
||||
play(query, top = false, provider, trackMeta = null) {
|
||||
const events = new EventEmitter();
|
||||
const source = this._getSource(provider || "ytm");
|
||||
const isUrl = Utils.isValidUrl(query);
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
if (!this._lavalink) {
|
||||
events.emit("message", "Audio node not ready yet.");
|
||||
return;
|
||||
}
|
||||
|
||||
await this._lavalink.waitForNode({ timeoutMs: 15_000 });
|
||||
|
||||
events.emit("message", "Searching...");
|
||||
|
||||
const ytId = Utils.extractYouTubeId(query);
|
||||
const canonicalYtUrl = ytId ? Utils.normalizeYouTubeUrl(query) : null;
|
||||
const searchQuery = (isUrl && canonicalYtUrl) ? canonicalYtUrl : query;
|
||||
|
||||
let result;
|
||||
try {
|
||||
if (isUrl) {
|
||||
result = await this._lavalink.search(searchQuery);
|
||||
} else {
|
||||
result = await this._lavalink.search(searchQuery, { source });
|
||||
}
|
||||
} catch (searchErr) {
|
||||
logger.warn("[Player] URL/primary search failed:", searchErr?.message);
|
||||
result = null;
|
||||
if (!isUrl) throw searchErr;
|
||||
}
|
||||
let lcTracks = result?.tracks ?? [];
|
||||
// Set when the only results we have came from the oEmbed title-search
|
||||
// fallback. That path resolves a SINGLE video (direct URL load was
|
||||
// bot-blocked), so its result list is a search page — NOT a playlist.
|
||||
// Bulk-queueing it would queue a bunch of "related" songs instead of
|
||||
// the one requested video (original fluxer bug reported by users).
|
||||
let fromTitleFallback = false;
|
||||
|
||||
if (isUrl && lcTracks.length === 0 && ytId) {
|
||||
const directBlocked = "YouTube blocked direct loading for this video (`Sign in to confirm you're not a bot`) — trying search fallback...";
|
||||
|
||||
if (searchQuery !== query) {
|
||||
events.emit("message", "Retrying with original URL...");
|
||||
try {
|
||||
const retry = await this._lavalink.search(query);
|
||||
lcTracks = retry?.tracks ?? [];
|
||||
} catch (_) { lcTracks = []; }
|
||||
}
|
||||
|
||||
if (lcTracks.length === 0) {
|
||||
events.emit("message", directBlocked);
|
||||
const title = await Utils.fetchYouTubeOEmbedTitle(ytId);
|
||||
if (title) {
|
||||
logger.player(`[Player] oEmbed fallback: resolved title "${title}" for ${ytId}`);
|
||||
for (const fallbackSource of ["ytsearch", "ytmsearch"]) {
|
||||
try {
|
||||
const fb = await this._lavalink.search(title, { source: fallbackSource });
|
||||
if (fb?.tracks?.length > 0) {
|
||||
lcTracks = fb.tracks;
|
||||
fromTitleFallback = true;
|
||||
break;
|
||||
}
|
||||
} catch (_) { /* try next source */ }
|
||||
}
|
||||
} else {
|
||||
logger.warn("[Player] oEmbed fallback: could not resolve title for " + ytId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (lcTracks.length === 0) {
|
||||
if (!isUrl && source !== "ytmsearch") {
|
||||
events.emit("message", "No results from primary source, trying YouTube Music...");
|
||||
const fallback = await this._lavalink.search(searchQuery, { source: "ytmsearch" });
|
||||
if (fallback?.tracks?.length > 0) {
|
||||
const video = this._lcTrackToVideo(fallback.tracks[0], trackMeta);
|
||||
if (video) {
|
||||
this.addToQueue(video, top);
|
||||
events.emit("message", "Successfully added [" + video.title + "](" + video.url + ") to the queue.");
|
||||
if (!this.queue.getCurrent()) {
|
||||
this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
events.emit("message", "**No results found for '" + query + "'.**");
|
||||
return;
|
||||
}
|
||||
|
||||
// Pick the track to queue. For a title-search fallback, prefer the
|
||||
// result that is the exact video the user requested (search may rank
|
||||
// covers/remixes first); otherwise take the first result.
|
||||
let firstTrack = lcTracks[0];
|
||||
if (fromTitleFallback && ytId) {
|
||||
firstTrack = lcTracks.find(t => (t?.info?.identifier ?? t?.identifier) === ytId) ?? lcTracks[0];
|
||||
if (firstTrack !== lcTracks[0]) {
|
||||
logger.player(`[Player] Search fallback: exact video match found for ${ytId}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Only a genuine playlist/mix URL load may bulk-queue. A title-search
|
||||
// fallback for a single video must queue exactly one track.
|
||||
if (isUrl && !fromTitleFallback && lcTracks.length > 1) {
|
||||
const videos = lcTracks.map(t => this._lcTrackToVideo(t, trackMeta)).filter(Boolean);
|
||||
this.addManyToQueue(videos, top);
|
||||
events.emit("message", "Successfully added **" + videos.length + "** songs to the queue.");
|
||||
} else {
|
||||
const video = this._lcTrackToVideo(firstTrack, trackMeta);
|
||||
if (video) {
|
||||
this.addToQueue(video, top);
|
||||
events.emit("message", "Successfully added [" + video.title + "](" + video.url + ") to the queue.");
|
||||
} else {
|
||||
events.emit("message", "**Failed to parse track data.**");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (!this.queue.getCurrent()) {
|
||||
this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error("[Player] play() search error:", err?.message);
|
||||
events.emit("message", err?.message || "An error occurred while loading the track.");
|
||||
}
|
||||
})();
|
||||
|
||||
return events;
|
||||
},
|
||||
|
||||
/**
|
||||
* @async Search for tracks via Lavalink and return raw track results.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {string} query
|
||||
* @param {string} [provider="ytm"]
|
||||
* @returns {Promise<Array<object>>}
|
||||
*/
|
||||
async search(query, provider = 'ytm') {
|
||||
if (!this._lavalink) return [];
|
||||
try {
|
||||
const source = this._getSource(provider);
|
||||
const result = await this._lavalink.search(query, { source });
|
||||
return result.tracks || [];
|
||||
} catch (e) {
|
||||
logger.error(`[Player] lavalink search error:`, e?.message);
|
||||
return [];
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* @private Build a radio-type track object.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {object} radio
|
||||
* @returns {object}
|
||||
*/
|
||||
_buildRadioTrack(radio) {
|
||||
return {
|
||||
type: "radio",
|
||||
title: radio.detailedName || radio.title || "Unknown Radio",
|
||||
description: Utils.truncate(radio.description || "", 200),
|
||||
url: radio.url,
|
||||
author: {
|
||||
name: radio.author?.name || "Unknown",
|
||||
url: radio.author?.url || radio.url,
|
||||
},
|
||||
thumbnail: radio.thumbnail ?? null,
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Add a radio stream to the queue.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {object} radio
|
||||
* @param {boolean} [top=false]
|
||||
*/
|
||||
playRadio(radio, top = false) {
|
||||
if (!radio?.url) { logger.error("[Player] Invalid radio data"); return; }
|
||||
this.addToQueue(this._buildRadioTrack(radio), top);
|
||||
if (!this.queue.getCurrent()) this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
|
||||
},
|
||||
|
||||
/**
|
||||
* @async Switch to a different radio stream, replacing any current radio tracks.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {object} radio - Radio object with url, title, author, thumbnail.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async switchRadio(radio) {
|
||||
if (!radio?.url) { logger.error("[Player] switchRadio: invalid radio data"); return; }
|
||||
|
||||
const newTrack = this._buildRadioTrack(radio);
|
||||
this.queue.data = this.queue.data.filter(t => t.type !== "radio");
|
||||
|
||||
if (!this.queue.getCurrent()) {
|
||||
this.queue.add(newTrack);
|
||||
this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
|
||||
return;
|
||||
}
|
||||
|
||||
this.queue.data.unshift(newTrack);
|
||||
this._skipping = true;
|
||||
this._radioAnnounced = false;
|
||||
this.queue.current = null;
|
||||
this._bridgeStop();
|
||||
this._playingNext = false;
|
||||
this._skipping = false;
|
||||
if (!this.leaving) this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
|
||||
},
|
||||
|
||||
/**
|
||||
* @private Build a direct-URL track object.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {string} url
|
||||
* @param {string} [title]
|
||||
* @param {string} [artist]
|
||||
* @param {string} [trackType="external"]
|
||||
* @returns {object}
|
||||
*/
|
||||
_buildExternalTrack(url, title = null, artist = null, trackType = "external") {
|
||||
const displayTitle = title || this._extractFilenameFromUrl(url);
|
||||
return {
|
||||
type: trackType,
|
||||
title: displayTitle,
|
||||
url: url,
|
||||
artist: artist || null,
|
||||
thumbnail: null,
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* @private Extract a display filename from a URL.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {string} url
|
||||
* @returns {string}
|
||||
*/
|
||||
_extractFilenameFromUrl(url) {
|
||||
try {
|
||||
const pathname = new URL(url).pathname;
|
||||
const filename = pathname.split("/").pop();
|
||||
if (filename && filename.includes(".")) {
|
||||
return decodeURIComponent(filename.replace(/\.[^.]+$/, "")) || "Stream";
|
||||
}
|
||||
} catch (_) {}
|
||||
return "External Stream";
|
||||
},
|
||||
|
||||
/**
|
||||
* Play a direct audio URL (MP3, OGG, AAC, stream, etc.) without Lavalink
|
||||
* search. The bridge handles decoding via Lavalink if needed.
|
||||
* @this {import('./Player.mjs').Player}
|
||||
* @param {string} url - Direct HTTP(S) audio URL.
|
||||
* @param {string} [title] - Optional display title.
|
||||
* @param {string} [artist] - Optional artist name.
|
||||
* @param {boolean} [top=false] - Insert at top of queue.
|
||||
* @param {string} [trackType="external"] - "external" or "stream".
|
||||
* @returns {EventEmitter} Emits "message" events with status strings.
|
||||
*/
|
||||
playExternal(url, title = null, artist = null, top = false, trackType = "external") {
|
||||
const events = new EventEmitter();
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
const track = this._buildExternalTrack(url, title, artist, trackType);
|
||||
this.addToQueue(track, top);
|
||||
events.emit("message", "Added **[" + track.title + "](" + url + ")** to the queue.");
|
||||
|
||||
if (!this.queue.getCurrent()) {
|
||||
this.playNext().catch(e => {
|
||||
logger.error("[Player] playExternal playNext error:", e.message);
|
||||
events.emit("message", "Error playing stream: " + e.message);
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
logger.error("[Player] playExternal error:", err?.message);
|
||||
events.emit("message", "Error: " + (err?.message || "Failed to add external stream."));
|
||||
}
|
||||
})();
|
||||
|
||||
return events;
|
||||
},
|
||||
};
|
||||
|
||||
export default SearchMixin;
|
||||
export { SearchMixin };
|
||||
@@ -0,0 +1,9 @@
|
||||
/**
|
||||
* @module src/music/player
|
||||
* @description Public surface of the per-channel player.
|
||||
*
|
||||
* Import map from the old layout:
|
||||
* - `src/Player.mjs` → this module (default export = Player)
|
||||
*/
|
||||
|
||||
export { default, Player, Queue } from "./Player.mjs";
|
||||
@@ -1,8 +1,8 @@
|
||||
/** @module src/probe @description Audio probing utilities using ffprobe to extract metadata from media files/streams. */
|
||||
/** @module src/music/probe @description Audio probing utilities using ffprobe to extract metadata from media files/streams. */
|
||||
|
||||
import ffprobe from "ffprobe-static";
|
||||
import { spawn } from "node:child_process";
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
import { logger } from "../core/Logger.mjs";
|
||||
|
||||
/** @type {number} @description Maximum time in milliseconds to wait for ffprobe to complete. */
|
||||
const PROBE_TIMEOUT_MS = 15_000;
|
||||
@@ -0,0 +1,122 @@
|
||||
/** @module src/music/providers */
|
||||
|
||||
/**
|
||||
* Map of provider shorthand keys to their Lavalink search prefix and display label.
|
||||
* Both short aliases (e.g. `scld`) and full names (e.g. `soundcloud`) map to the same
|
||||
* prefix/label pair.
|
||||
* @type {Object<string, { prefix: string, label: string }>}
|
||||
*/
|
||||
export const PROVIDERS = {
|
||||
yt: { prefix: "ytsearch", label: "YouTube" },
|
||||
ytm: { prefix: "ytmsearch", label: "YouTube Music" },
|
||||
scld: { prefix: "scsearch", label: "SoundCloud" },
|
||||
sc: { prefix: "scsearch", label: "SoundCloud" },
|
||||
sp: { prefix: "spsearch", label: "Spotify" },
|
||||
spotify: { prefix: "spsearch", label: "Spotify" },
|
||||
am: { prefix: "amsearch", label: "Apple Music" },
|
||||
apple: { prefix: "amsearch", label: "Apple Music" },
|
||||
dz: { prefix: "dzsearch", label: "Deezer" },
|
||||
deezer: { prefix: "dzsearch", label: "Deezer" },
|
||||
td: { prefix: "tdsearch", label: "Tidal" },
|
||||
tidal: { prefix: "tdsearch", label: "Tidal" },
|
||||
bc: { prefix: "bcsearch", label: "Bandcamp" },
|
||||
bandcamp: { prefix: "bcsearch", label: "Bandcamp" },
|
||||
adm: { prefix: "admsearch", label: "Audiomack" },
|
||||
audiomack: { prefix: "admsearch", label: "Audiomack" },
|
||||
gaana: { prefix: "gaanasearch", label: "Gaana" },
|
||||
js: { prefix: "jssearch", label: "JioSaavn" },
|
||||
jiosaavn: { prefix: "jssearch", label: "JioSaavn" },
|
||||
lf: { prefix: "lfsearch", label: "Last.fm" },
|
||||
lastfm: { prefix: "lfsearch", label: "Last.fm" },
|
||||
pd: { prefix: "pdsearch", label: "Pandora" },
|
||||
pandora: { prefix: "pdsearch", label: "Pandora" },
|
||||
vk: { prefix: "vksearch", label: "VK Music" },
|
||||
mc: { prefix: "mcsearch", label: "Mixcloud" },
|
||||
mixcloud: { prefix: "mcsearch", label: "Mixcloud" },
|
||||
nc: { prefix: "ncsearch", label: "NicoVideo" },
|
||||
nicovideo: { prefix: "ncsearch", label: "NicoVideo" },
|
||||
bb: { prefix: "bilibili", label: "Bilibili" },
|
||||
bilibili: { prefix: "bilibili", label: "Bilibili" },
|
||||
sh: { prefix: "shsearch", label: "Shazam" },
|
||||
shazam: { prefix: "shsearch", label: "Shazam" },
|
||||
sl: { prefix: "slsearch", label: "Songlink" },
|
||||
songlink: { prefix: "slsearch", label: "Songlink" },
|
||||
qb: { prefix: "qbsearch", label: "Qobuz" },
|
||||
qobuz: { prefix: "qbsearch", label: "Qobuz" },
|
||||
ym: { prefix: "ymsearch", label: "Yandex Music" },
|
||||
yandex: { prefix: "ymsearch", label: "Yandex Music" },
|
||||
au: { prefix: "ausearch", label: "Audius" },
|
||||
audius: { prefix: "ausearch", label: "Audius" },
|
||||
az: { prefix: "azsearch", label: "Amazon Music" },
|
||||
amazon: { prefix: "azsearch", label: "Amazon Music" },
|
||||
ag: { prefix: "agsearch", label: "Anghami" },
|
||||
anghami: { prefix: "agsearch", label: "Anghami" },
|
||||
bk: { prefix: "bksearch", label: "Bluesky" },
|
||||
bluesky: { prefix: "bksearch", label: "Bluesky" },
|
||||
ytrec: { prefix: "ytrec", label: "YouTube (recommended)" },
|
||||
sprec: { prefix: "sprec", label: "Spotify (recommended)" },
|
||||
dzrec: { prefix: "dzrec", label: "Deezer (recommended)" },
|
||||
tdrec: { prefix: "tdrec", label: "Tidal (recommended)" },
|
||||
jsrec: { prefix: "jsrec", label: "JioSaavn (recommended)" },
|
||||
vkrec: { prefix: "vkrec", label: "VK Music (recommended)" },
|
||||
gtts: { prefix: "gtts", label: "Google TTS" },
|
||||
tts: { prefix: "gtts", label: "Google TTS" },
|
||||
ftts: { prefix: "ftts", label: "Flowery TTS" },
|
||||
};
|
||||
|
||||
/**
|
||||
* Shorthand-to-label lookup derived from {@link PROVIDERS}.
|
||||
* @type {Object<string, string>}
|
||||
*/
|
||||
export const PROVIDER_NAMES = Object.fromEntries(
|
||||
Object.entries(PROVIDERS).map(([k, v]) => [k, v.label])
|
||||
);
|
||||
|
||||
/**
|
||||
* Complete list of accepted provider keys for command choices.
|
||||
* @type {string[]}
|
||||
*/
|
||||
export const PROVIDER_CHOICES = [
|
||||
"ytm", "yt", "scld", "sc",
|
||||
"sp", "spotify",
|
||||
"am", "apple",
|
||||
"dz", "deezer",
|
||||
"td", "tidal",
|
||||
"bc", "bandcamp",
|
||||
"adm", "audiomack",
|
||||
"gaana",
|
||||
"js", "jiosaavn",
|
||||
"lf", "lastfm",
|
||||
"pd", "pandora",
|
||||
"vk",
|
||||
"mc", "mixcloud",
|
||||
"nc", "nicovideo",
|
||||
"bb", "bilibili",
|
||||
"sh", "shazam",
|
||||
"sl", "songlink",
|
||||
"qb", "qobuz",
|
||||
"ym", "yandex",
|
||||
"au", "audius",
|
||||
"az", "amazon",
|
||||
"ag", "anghami",
|
||||
"bk", "bluesky",
|
||||
"ytrec", "sprec", "dzrec", "tdrec", "jsrec", "vkrec",
|
||||
"gtts", "tts", "ftts",
|
||||
];
|
||||
|
||||
/**
|
||||
* Parse an inline provider prefix from raw query text (e.g. `"yt: never gonna give you up"`).
|
||||
* If the prefix is recognised, splits into provider key and remaining query;
|
||||
* otherwise returns the full string as the query with `provider: null`.
|
||||
* @param {string} raw - The raw user input string.
|
||||
* @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() };
|
||||
}
|
||||
@@ -1,12 +1,12 @@
|
||||
/** @module src/FluxerListManager @description FluxerList API integration for fetching server/bot voter lists with caching. */
|
||||
/** @module src/services/FluxerListManager @description FluxerList API integration for fetching server/bot voter lists with caching. */
|
||||
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
import { logger } from "../core/Logger.mjs";
|
||||
import {
|
||||
FLUXERLIST,
|
||||
FLUXERLIST_AUTH,
|
||||
FLUXERLIST_LIMITS,
|
||||
buildFluxerListUrl,
|
||||
} from "./constants/API.mjs";
|
||||
} from "../utils/API.mjs";
|
||||
|
||||
/** @class FluxerListManager @description Fetches and caches voter lists from the FluxerList API for servers and bots. */
|
||||
export class FluxerListManager {
|
||||
@@ -1,6 +1,6 @@
|
||||
/** @module src/TrackOptionsManager @description Per-user track options (start/end timestamps) stored in MySQL. Provides caching, matching, and CRUD for track segments. */
|
||||
/** @module src/services/TrackOptionsManager @description Per-user track options (start/end timestamps) stored in MySQL. Provides caching, matching, and CRUD for track segments. */
|
||||
import mysql from "mysql2";
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
import { logger } from "../core/Logger.mjs";
|
||||
|
||||
const DEFAULT_ALIAS = "default";
|
||||
const MAX_ALIAS_LEN = 32;
|
||||
@@ -0,0 +1,287 @@
|
||||
/**
|
||||
* @module src/services/lastfm/LastFmManager
|
||||
* @description Last.fm API integration for scrobbling, now-playing updates,
|
||||
* loved tracks, and user session management with MySQL persistence.
|
||||
*
|
||||
* Base class of the split Last.fm manager: configuration, constructor, MySQL
|
||||
* pool + schema setup, multi-bot isolation (bot_id) and the small helpers
|
||||
* shared by every concern. User-session storage, scrobbling, track/artist/
|
||||
* album/tag queries, user chart queries and server statistics live in the
|
||||
* mixin modules applied to this class at the bottom of the file.
|
||||
*/
|
||||
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
import { normalizeTrackText } from "./constants.mjs";
|
||||
import { applyMixins } from "../../utils/mixins.mjs";
|
||||
import { parseLastFmUrl, isLastFmUrl } from "./urlUtils.mjs";
|
||||
import UserStoreMixin from "./UserStoreMixin.mjs";
|
||||
import ScrobblingMixin from "./ScrobblingMixin.mjs";
|
||||
import TrackQueriesMixin from "./TrackQueriesMixin.mjs";
|
||||
import UserQueriesMixin from "./UserQueriesMixin.mjs";
|
||||
import ServerStatsMixin from "./ServerStatsMixin.mjs";
|
||||
|
||||
/** @class LastFmManager @description Manages Last.fm user sessions, scrobbling, loved tracks, and top/recent track queries with MySQL persistence. */
|
||||
export class LastFmManager {
|
||||
|
||||
/** @param {object} config @param {string} config.apiKey @param {string} config.apiSecret @param {boolean} [config.enabled] @param {number} [config.scrobbleThreshold] @param {number} [config.scrobbleMinMs] @param {object} mysqlConfig */
|
||||
constructor(config, mysqlConfig) {
|
||||
this.apiKey = config?.apiKey ?? "";
|
||||
this.apiSecret = config?.apiSecret ?? "";
|
||||
this.enabled = config?.enabled !== false && !!(this.apiKey && this.apiSecret);
|
||||
this.scrobbleThreshold = config?.scrobbleThreshold ?? 0.5;
|
||||
this.scrobbleMinMs = config?.scrobbleMinMs ?? 240_000;
|
||||
|
||||
this._mysqlConfig = mysqlConfig;
|
||||
this._pool = null;
|
||||
|
||||
this.botId = null;
|
||||
this._hasBotIdColumn = false;
|
||||
|
||||
this._userCache = new Map();
|
||||
this._userCacheMax = 5000;
|
||||
|
||||
this._totalScrobblesCache = null;
|
||||
this._totalScrobblesCacheExpiry = 0;
|
||||
this._totalScrobblesInflight = null;
|
||||
|
||||
if (!this.enabled) {
|
||||
if (config?.enabled === false) {
|
||||
logger.settings("[LastFm] Disabled — \"enabled\" is set to false in config.");
|
||||
} else {
|
||||
logger.settings("[LastFm] Disabled — apiKey or apiSecret missing in config.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** @async Set the bot ID for multi-bot isolation. @param {string} id */
|
||||
async setBotId(id) {
|
||||
const changed = this.botId !== id;
|
||||
this.botId = id;
|
||||
if (changed) {
|
||||
await this._ensureBotIdColumn();
|
||||
this._userCache.clear();
|
||||
}
|
||||
}
|
||||
|
||||
/** @private @async Ensure the bot_id column exists and is part of the primary key. */
|
||||
async _ensureBotIdColumn() {
|
||||
if (this._hasBotIdColumn) return;
|
||||
const pool = await this._getPool();
|
||||
|
||||
const [cols] = await pool.execute(
|
||||
`SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_KEY FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'lastfm_users' AND COLUMN_NAME = 'bot_id'`
|
||||
);
|
||||
if (cols.length === 0) {
|
||||
logger.settings("[LastFm] Auto-migrating: adding bot_id column to lastfm_users...");
|
||||
await pool.execute("ALTER TABLE `lastfm_users` ADD COLUMN `bot_id` VARCHAR(32) NOT NULL DEFAULT ''");
|
||||
if (this.botId) {
|
||||
await pool.execute("UPDATE `lastfm_users` SET `bot_id` = ? WHERE `bot_id` = ''", [String(this.botId)]);
|
||||
}
|
||||
await pool.execute("ALTER TABLE `lastfm_users` DROP PRIMARY KEY, ADD PRIMARY KEY (user_id, bot_id)");
|
||||
logger.settings("[LastFm] Auto-migration complete: lastfm_users.bot_id added.");
|
||||
} else {
|
||||
const colInfo = cols[0];
|
||||
const isNullable = colInfo.IS_NULLABLE === 'YES';
|
||||
const isPK = colInfo.COLUMN_KEY === 'PRI';
|
||||
if (!isPK) {
|
||||
logger.settings("[LastFm] Fixing lastfm_users.bot_id: adding to primary key...");
|
||||
if (isNullable) {
|
||||
await pool.execute("UPDATE `lastfm_users` SET `bot_id` = '' WHERE `bot_id` IS NULL");
|
||||
await pool.execute("ALTER TABLE `lastfm_users` MODIFY COLUMN `bot_id` VARCHAR(32) NOT NULL DEFAULT ''");
|
||||
}
|
||||
if (this.botId) {
|
||||
await pool.execute("UPDATE `lastfm_users` SET `bot_id` = ? WHERE `bot_id` = ''", [String(this.botId)]);
|
||||
}
|
||||
await pool.execute("ALTER TABLE `lastfm_users` DROP PRIMARY KEY, ADD PRIMARY KEY (user_id, bot_id)");
|
||||
logger.settings("[LastFm] Fix complete: lastfm_users.bot_id added to primary key.");
|
||||
}
|
||||
}
|
||||
|
||||
const [statsCols] = await pool.execute(
|
||||
`SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_KEY FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'lastfm_stats' AND COLUMN_NAME = 'bot_id'`
|
||||
);
|
||||
if (statsCols.length === 0) {
|
||||
logger.settings("[LastFm] Auto-migrating: adding bot_id column to lastfm_stats...");
|
||||
await pool.execute("ALTER TABLE `lastfm_stats` ADD COLUMN `bot_id` VARCHAR(32) NOT NULL DEFAULT ''");
|
||||
if (this.botId) {
|
||||
await pool.execute("UPDATE `lastfm_stats` SET `bot_id` = ? WHERE `bot_id` = ''", [String(this.botId)]);
|
||||
}
|
||||
await pool.execute("ALTER TABLE `lastfm_stats` DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)");
|
||||
logger.settings("[LastFm] Auto-migration complete: lastfm_stats.bot_id added.");
|
||||
} else {
|
||||
const colInfo = statsCols[0];
|
||||
const isNullable = colInfo.IS_NULLABLE === 'YES';
|
||||
const isPK = colInfo.COLUMN_KEY === 'PRI';
|
||||
if (!isPK) {
|
||||
logger.settings("[LastFm] Fixing lastfm_stats.bot_id: adding to primary key...");
|
||||
if (isNullable) {
|
||||
await pool.execute("UPDATE `lastfm_stats` SET `bot_id` = '' WHERE `bot_id` IS NULL");
|
||||
await pool.execute("ALTER TABLE `lastfm_stats` MODIFY COLUMN `bot_id` VARCHAR(32) NOT NULL DEFAULT ''");
|
||||
}
|
||||
if (this.botId) {
|
||||
await pool.execute("UPDATE `lastfm_stats` SET `bot_id` = ? WHERE `bot_id` = ''", [String(this.botId)]);
|
||||
}
|
||||
await pool.execute("ALTER TABLE `lastfm_stats` DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)");
|
||||
logger.settings("[LastFm] Fix complete: lastfm_stats.bot_id added to primary key.");
|
||||
}
|
||||
}
|
||||
|
||||
this._hasBotIdColumn = true;
|
||||
}
|
||||
|
||||
/** @private @returns {{where: string, params: Array}} SQL filter fragment for bot_id. */
|
||||
_botIdFilter() {
|
||||
if (!this.botId || !this._hasBotIdColumn) return { where: "", params: [] };
|
||||
return { where: " AND bot_id = ?", params: [String(this.botId)] };
|
||||
}
|
||||
|
||||
/** @private @async Get or create the MySQL connection pool. @returns {Promise<object>} */
|
||||
async _getPool() {
|
||||
if (this._pool) return this._pool;
|
||||
const mysql = await import("mysql2/promise");
|
||||
this._pool = mysql.createPool({
|
||||
host: this._mysqlConfig.host,
|
||||
port: this._mysqlConfig.port ?? 3306,
|
||||
user: this._mysqlConfig.user,
|
||||
password: this._mysqlConfig.password,
|
||||
database: this._mysqlConfig.database,
|
||||
});
|
||||
await this._initTable();
|
||||
return this._pool;
|
||||
}
|
||||
|
||||
/** @private @async Create the lastfm_users and lastfm_stats tables if they don't exist. */
|
||||
async _initTable() {
|
||||
const pool = this._pool;
|
||||
await pool.execute(`
|
||||
CREATE TABLE IF NOT EXISTS \`lastfm_users\` (
|
||||
\`user_id\` VARCHAR(30) NOT NULL PRIMARY KEY,
|
||||
\`session_key\` VARCHAR(64) NOT NULL,
|
||||
\`username\` VARCHAR(64) NOT NULL DEFAULT '',
|
||||
\`scrobble\` TINYINT(1) NOT NULL DEFAULT 1,
|
||||
\`scrobble_count\` BIGINT NOT NULL DEFAULT 0,
|
||||
\`linked_at\` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
`);
|
||||
|
||||
await pool.execute(`
|
||||
CREATE TABLE IF NOT EXISTS \`lastfm_stats\` (
|
||||
\`id\` TINYINT(1) NOT NULL PRIMARY KEY DEFAULT 1,
|
||||
\`stored_scrobbles\` BIGINT NOT NULL DEFAULT 0,
|
||||
\`linked_users\` INT NOT NULL DEFAULT 0
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
`);
|
||||
await pool.execute(`
|
||||
INSERT IGNORE INTO \`lastfm_stats\` (id, stored_scrobbles, linked_users) VALUES (1, 0, 0)
|
||||
`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a Last.fm music URL into artist, track, and album components.
|
||||
* @param {string} url - The Last.fm URL to parse.
|
||||
* @returns {object|null} Parsed components { artist, track, album, url } or null if invalid.
|
||||
*/
|
||||
parseLastFmUrl(url) {
|
||||
return parseLastFmUrl(url);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a string is a valid Last.fm music URL.
|
||||
* @param {string} str - String to check.
|
||||
* @returns {boolean} True if the string is a Last.fm music URL.
|
||||
*/
|
||||
isLastFmUrl(str) {
|
||||
return isLastFmUrl(str);
|
||||
}
|
||||
|
||||
/** @private Throw if Last.fm integration is not enabled/configured. @throws {Error} If apiKey or apiSecret is missing. */
|
||||
_assertEnabled() {
|
||||
if (!this.enabled) throw new Error("Last.fm integration is not configured (missing apiKey/apiSecret).");
|
||||
}
|
||||
|
||||
/** @private Increment a user's scrobble_count in the database by 1 (fire-and-forget). @param {string} userId - The user ID. */
|
||||
_incrementScrobbleCount(userId) {
|
||||
if (!userId) return;
|
||||
const f = this._botIdFilter();
|
||||
this._getPool().then(pool => {
|
||||
pool.execute(
|
||||
`UPDATE lastfm_users SET scrobble_count = scrobble_count + 1 WHERE user_id = ?${f.where}`,
|
||||
[String(userId), ...f.params]
|
||||
).catch(e => { logger.warn("[LastFm] scrobble_count increment failed:", e?.message); });
|
||||
}).catch(e => { logger.warn("[LastFm] scrobble_count pool acquire failed:", e?.message); });
|
||||
}
|
||||
|
||||
/** @private Build a search query string from artist and title for playback. @param {string} artist - The artist name. @param {string} title - The track title. @returns {string} Combined search query. */
|
||||
_buildPlayQuery(artist, title) {
|
||||
const cleanArtist = String(artist ?? "").trim();
|
||||
const cleanTitle = String(title ?? "").trim();
|
||||
return [cleanTitle, cleanArtist].filter(Boolean).join(" ");
|
||||
}
|
||||
|
||||
/** @private Extract the best artist name from a track object, checking multiple possible fields. @param {object} track - Track object. @returns {string} The artist name. */
|
||||
_extractArtist(track) {
|
||||
const preservedArtist = track?.lastfm?.artist
|
||||
?? track?.requestedArtist
|
||||
?? track?.artist;
|
||||
if (preservedArtist) return preservedArtist;
|
||||
|
||||
return track.artists?.[0]?.name
|
||||
?? track.author?.name
|
||||
?? "Unknown Artist";
|
||||
}
|
||||
|
||||
/** @private Extract the best track title from a track object, checking multiple possible fields. @param {object} track - Track object. @returns {string} The track title. */
|
||||
_extractTitle(track) {
|
||||
return track?.lastfm?.name
|
||||
?? track?.requestedTitle
|
||||
?? track.title
|
||||
?? track.name
|
||||
?? "Unknown Track";
|
||||
}
|
||||
|
||||
/** @private Extract the duration in seconds from a track object, supporting number (ms), object with .seconds, ISO 8601, or plain seconds. @param {object} track - Track object. @returns {string|number} Duration in seconds, or empty string if unavailable. */
|
||||
_extractDurationSec(track) {
|
||||
if (!track.duration) return "";
|
||||
if (typeof track.duration === "object" && track.duration.seconds) return track.duration.seconds;
|
||||
if (typeof track.duration === "number") return Math.round(track.duration / 1000);
|
||||
if (typeof track.duration === "string") {
|
||||
const m = track.duration.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/);
|
||||
if (m) return ((+m[1] || 0) * 3600) + ((+m[2] || 0) * 60) + (+m[3] || 0);
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* Determine whether a track should be scrobbled based on playback time and duration.
|
||||
* @param {object} track - Track object with duration and title/artist info.
|
||||
* @param {number} playedMs - How many milliseconds the track has been playing.
|
||||
* @returns {boolean} True if the track meets the scrobble threshold.
|
||||
*/
|
||||
shouldScrobble(track, playedMs) {
|
||||
const durationMs = typeof track.duration === "object" && track.duration.seconds
|
||||
? track.duration.seconds * 1000
|
||||
: typeof track.duration === "number"
|
||||
? track.duration
|
||||
: null;
|
||||
|
||||
if (!durationMs || durationMs < 30_000) return false;
|
||||
|
||||
const normalizedTitle = normalizeTrackText(this._extractTitle(track));
|
||||
const normalizedArtist = normalizeTrackText(this._extractArtist(track));
|
||||
if (!normalizedTitle || !normalizedArtist) return false;
|
||||
|
||||
const thresholdMs = Math.min(durationMs * this.scrobbleThreshold, this.scrobbleMinMs);
|
||||
return playedMs >= thresholdMs;
|
||||
}
|
||||
}
|
||||
|
||||
// Attach the split-out concerns: user-session storage (UserStoreMixin),
|
||||
// scrobbling (ScrobblingMixin), track/artist/album/tag queries
|
||||
// (TrackQueriesMixin), per-user chart queries (UserQueriesMixin) and
|
||||
// server/guild statistics (ServerStatsMixin).
|
||||
applyMixins(LastFmManager, UserStoreMixin, ScrobblingMixin, TrackQueriesMixin, UserQueriesMixin, ServerStatsMixin);
|
||||
|
||||
// Keep the old import surface: commands used to import the URL helpers from
|
||||
// this module when it was a single file. (The class itself is exported by its
|
||||
// declaration above.)
|
||||
export { parseLastFmUrl, isLastFmUrl } from "./urlUtils.mjs";
|
||||
@@ -0,0 +1,98 @@
|
||||
/**
|
||||
* @module src/services/lastfm/ScrobblingMixin
|
||||
* @description Scrobbling concern for LastFmManager: now-playing updates, scrobble submissions and per-user scrobble-count syncing.
|
||||
*
|
||||
* These methods are applied onto the LastFmManager class prototype via
|
||||
* {@link applyMixins} — `this` is a LastFmManager instance.
|
||||
*/
|
||||
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
import { apiCall } from "./constants.mjs";
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
* @description Scrobbling mixin — applied to LastFmManager.
|
||||
*/
|
||||
const ScrobblingMixin = {
|
||||
/** @async Send a now-playing update to Last.fm for a user. @param {string} userId @param {object} track @param {string} track.title @param {string} [track.album] @param {number} [track.trackNumber] */
|
||||
async updateNowPlaying(userId, track) {
|
||||
if (!this.enabled) return;
|
||||
const user = await this.getUser(userId);
|
||||
if (!user || !user.scrobbleEnabled) return;
|
||||
|
||||
try {
|
||||
await apiCall(
|
||||
{
|
||||
method: "track.updatenowplaying",
|
||||
api_key: this.apiKey,
|
||||
sk: user.sessionKey,
|
||||
artist: this._extractArtist(track),
|
||||
track: this._extractTitle(track),
|
||||
album: track.album ?? "",
|
||||
duration: this._extractDurationSec(track),
|
||||
trackNumber: track.trackNumber ?? "",
|
||||
},
|
||||
this.apiSecret,
|
||||
true
|
||||
);
|
||||
} catch (err) {
|
||||
logger.warn(`[LastFm] updateNowPlaying failed for ${userId}: ${err.message}`);
|
||||
}
|
||||
},
|
||||
|
||||
/** @async Scrobble a track for a user. @param {string} userId @param {object} track @param {number} startedAtMs @param {string} track.title @param {string} [track.album] @param {number} [track.trackNumber] */
|
||||
async scrobble(userId, track, startedAtMs) {
|
||||
if (!this.enabled) return;
|
||||
const user = await this.getUser(userId);
|
||||
if (!user || !user.scrobbleEnabled) return;
|
||||
|
||||
try {
|
||||
await apiCall(
|
||||
{
|
||||
method: "track.scrobble",
|
||||
api_key: this.apiKey,
|
||||
sk: user.sessionKey,
|
||||
"artist[0]": this._extractArtist(track),
|
||||
"track[0]": this._extractTitle(track),
|
||||
"album[0]": track.album ?? "",
|
||||
"timestamp[0]": Math.floor(startedAtMs / 1000),
|
||||
"duration[0]": this._extractDurationSec(track),
|
||||
},
|
||||
this.apiSecret,
|
||||
true
|
||||
);
|
||||
logger.settings(`[LastFm] Scrobbled "${track.title}" for ${userId}`);
|
||||
|
||||
this._incrementScrobbleCount(userId);
|
||||
} catch (err) {
|
||||
logger.warn(`[LastFm] Scrobble failed for ${userId}: ${err.message}`);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Sync a user's scrobble count from Last.fm to the local database.
|
||||
* @async
|
||||
* @param {string} userId - The user ID.
|
||||
* @returns {Promise<number>} The synced scrobble count.
|
||||
*/
|
||||
async syncUserScrobbleCount(userId) {
|
||||
if (!this.enabled) return 0;
|
||||
try {
|
||||
const info = await this.getUserInfo(userId);
|
||||
const playcount = Number(info.playcount ?? 0);
|
||||
const pool = await this._getPool();
|
||||
const f = this._botIdFilter();
|
||||
await pool.execute(
|
||||
`UPDATE lastfm_users SET scrobble_count = ? WHERE user_id = ?${f.where}`,
|
||||
[String(playcount), String(userId), ...f.params]
|
||||
);
|
||||
return playcount;
|
||||
} catch (e) {
|
||||
logger.warn("[LastFm] Error:", e?.message);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
export default ScrobblingMixin;
|
||||
export { ScrobblingMixin };
|
||||
@@ -0,0 +1,460 @@
|
||||
/**
|
||||
* @module src/services/lastfm/ServerStatsMixin
|
||||
* @description Server/guild statistics concern for LastFmManager: who-knows lookups, user comparison, affinity and crowns, the scrobble leaderboard and global scrobble / linked-user totals.
|
||||
*
|
||||
* These methods are applied onto the LastFmManager class prototype via
|
||||
* {@link applyMixins} — `this` is a LastFmManager instance.
|
||||
*/
|
||||
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
* @description Server-stats mixin — applied to LastFmManager.
|
||||
*/
|
||||
const ServerStatsMixin = {
|
||||
/**
|
||||
* Get who knows an artist among a list of users, ranked by playcount.
|
||||
* @async
|
||||
* @param {string} artist - The artist name.
|
||||
* @param {Array<string>} userIds - Array of user IDs.
|
||||
* @returns {Promise<Array<{userId: string, username: string, playcount: number}>>} Users who know the artist, sorted by playcount descending.
|
||||
*/
|
||||
async getWhoKnows(artist, userIds) {
|
||||
if (!this.enabled) return [];
|
||||
if (!Array.isArray(userIds) || !userIds.length) return [];
|
||||
|
||||
const concurrency = 5;
|
||||
const results = [];
|
||||
|
||||
for (let i = 0; i < userIds.length; i += concurrency) {
|
||||
const batch = userIds.slice(i, i + concurrency);
|
||||
|
||||
const batchResults = await Promise.allSettled(
|
||||
batch.map(async (uid) => {
|
||||
const user = await this.getUser(uid);
|
||||
if (!user) return null;
|
||||
|
||||
try {
|
||||
const info = await this.getArtistInfo(artist, uid);
|
||||
const playcount = info?.userplaycount ?? 0;
|
||||
return {
|
||||
userId: uid,
|
||||
username: user.username,
|
||||
playcount,
|
||||
};
|
||||
} catch (e) {
|
||||
logger.warn("[LastFm] Error:", e?.message);
|
||||
return {
|
||||
userId: uid,
|
||||
username: user.username,
|
||||
playcount: 0,
|
||||
};
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
for (const r of batchResults) {
|
||||
if (r.status === "fulfilled" && r.value && r.value.playcount > 0) {
|
||||
results.push(r.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
results.sort((a, b) => b.playcount - a.playcount);
|
||||
return results;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get who knows a specific track among a list of users, ranked by playcount.
|
||||
* @async
|
||||
* @param {string} artist - The artist name.
|
||||
* @param {string} track - The track name.
|
||||
* @param {Array<string>} userIds - Array of user IDs.
|
||||
* @returns {Promise<Array<{userId: string, username: string, playcount: number}>>} Users who know the track, sorted by playcount descending.
|
||||
*/
|
||||
async getWhoKnowsTrack(artist, track, userIds) {
|
||||
if (!this.enabled) return [];
|
||||
if (!Array.isArray(userIds) || !userIds.length) return [];
|
||||
|
||||
const concurrency = 5;
|
||||
const results = [];
|
||||
|
||||
for (let i = 0; i < userIds.length; i += concurrency) {
|
||||
const batch = userIds.slice(i, i + concurrency);
|
||||
|
||||
const batchResults = await Promise.allSettled(
|
||||
batch.map(async (uid) => {
|
||||
const user = await this.getUser(uid);
|
||||
if (!user) return null;
|
||||
|
||||
try {
|
||||
const info = await this.getTrackInfo(artist, track, uid);
|
||||
const playcount = Number(info?.userplaycount ?? 0);
|
||||
return {
|
||||
userId: uid,
|
||||
username: user.username,
|
||||
playcount,
|
||||
};
|
||||
} catch (e) {
|
||||
logger.warn("[LastFm] Error:", e?.message);
|
||||
return {
|
||||
userId: uid,
|
||||
username: user.username,
|
||||
playcount: 0,
|
||||
};
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
for (const r of batchResults) {
|
||||
if (r.status === "fulfilled" && r.value && r.value.playcount > 0) {
|
||||
results.push(r.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
results.sort((a, b) => b.playcount - a.playcount);
|
||||
return results;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get who knows a specific album among a list of users, ranked by playcount.
|
||||
* @async
|
||||
* @param {string} artist - The artist name.
|
||||
* @param {string} album - The album name.
|
||||
* @param {Array<string>} userIds - Array of user IDs.
|
||||
* @returns {Promise<Array<{userId: string, username: string, playcount: number}>>} Users who know the album, sorted by playcount descending.
|
||||
*/
|
||||
async getWhoKnowsAlbum(artist, album, userIds) {
|
||||
if (!this.enabled) return [];
|
||||
if (!Array.isArray(userIds) || !userIds.length) return [];
|
||||
|
||||
const concurrency = 5;
|
||||
const results = [];
|
||||
|
||||
for (let i = 0; i < userIds.length; i += concurrency) {
|
||||
const batch = userIds.slice(i, i + concurrency);
|
||||
|
||||
const batchResults = await Promise.allSettled(
|
||||
batch.map(async (uid) => {
|
||||
const user = await this.getUser(uid);
|
||||
if (!user) return null;
|
||||
|
||||
try {
|
||||
const info = await this.getAlbumInfo(artist, album, uid);
|
||||
const playcount = Number(info?.userplaycount ?? 0);
|
||||
return {
|
||||
userId: uid,
|
||||
username: user.username,
|
||||
playcount,
|
||||
};
|
||||
} catch (e) {
|
||||
logger.warn("[LastFm] Error:", e?.message);
|
||||
return {
|
||||
userId: uid,
|
||||
username: user.username,
|
||||
playcount: 0,
|
||||
};
|
||||
}
|
||||
})
|
||||
);
|
||||
|
||||
for (const r of batchResults) {
|
||||
if (r.status === "fulfilled" && r.value && r.value.playcount > 0) {
|
||||
results.push(r.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
results.sort((a, b) => b.playcount - a.playcount);
|
||||
return results;
|
||||
},
|
||||
|
||||
/**
|
||||
* Compare two users' top artists and compute a match percentage.
|
||||
* @async
|
||||
* @param {string} userId1 - First user ID.
|
||||
* @param {string} userId2 - Second user ID.
|
||||
* @returns {Promise<object|null>} Comparison result with user1, user2, commonArtists, and matchPercentage, or null.
|
||||
*/
|
||||
async compareUsers(userId1, userId2) {
|
||||
if (!this.enabled) return null;
|
||||
|
||||
try {
|
||||
const user1Data = await this.getUser(userId1);
|
||||
const user2Data = await this.getUser(userId2);
|
||||
if (!user1Data || !user2Data) return null;
|
||||
|
||||
const [artists1, artists2] = await Promise.all([
|
||||
this.getTopArtists(userId1, "overall", 50),
|
||||
this.getTopArtists(userId2, "overall", 50),
|
||||
]);
|
||||
|
||||
const names1 = new Set(artists1.map(a => a.name.toLowerCase()));
|
||||
const names2 = new Set(artists2.map(a => a.name.toLowerCase()));
|
||||
|
||||
const commonNames = [...names1].filter(n => names2.has(n));
|
||||
const commonArtists = artists1
|
||||
.filter(a => names2.has(a.name.toLowerCase()))
|
||||
.map(a => ({
|
||||
name: a.name,
|
||||
url: a.url,
|
||||
playcount: a.playcount,
|
||||
}));
|
||||
|
||||
const totalUnique = new Set([...names1, ...names2]).size;
|
||||
const matchPercentage = totalUnique > 0
|
||||
? Math.round((commonNames.length / totalUnique) * 100)
|
||||
: 0;
|
||||
|
||||
return {
|
||||
user1: {
|
||||
username: user1Data.username,
|
||||
totalArtists: names1.size,
|
||||
},
|
||||
user2: {
|
||||
username: user2Data.username,
|
||||
totalArtists: names2.size,
|
||||
},
|
||||
commonArtists,
|
||||
matchPercentage,
|
||||
};
|
||||
} catch (e) {
|
||||
logger.warn("[LastFm] Error:", e?.message);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Get total scrobble count across all linked users (cached for 10 minutes).
|
||||
* @async
|
||||
* @param {number} [concurrency=3] - Number of concurrent user syncs.
|
||||
* @returns {Promise<number>} Total scrobble count.
|
||||
*/
|
||||
async getTotalScrobbles(concurrency = 3) {
|
||||
if (!this.enabled) return 0;
|
||||
|
||||
if (this._totalScrobblesCache !== null && Date.now() < this._totalScrobblesCacheExpiry) {
|
||||
return this._totalScrobblesCache;
|
||||
}
|
||||
|
||||
if (this._totalScrobblesInflight) return this._totalScrobblesInflight;
|
||||
|
||||
this._totalScrobblesInflight = this._refreshTotalScrobbles(concurrency);
|
||||
try {
|
||||
return await this._totalScrobblesInflight;
|
||||
} finally {
|
||||
this._totalScrobblesInflight = null;
|
||||
}
|
||||
},
|
||||
|
||||
/** @private @async Sync all users' scrobble counts from Last.fm and cache the total. @param {number} concurrency - Concurrent sync batch size. @returns {Promise<number>} Fresh total scrobble count. */
|
||||
async _refreshTotalScrobbles(concurrency) {
|
||||
try {
|
||||
const pool = await this._getPool();
|
||||
|
||||
const f = this._botIdFilter();
|
||||
const [rows] = await pool.execute(
|
||||
`SELECT user_id FROM lastfm_users WHERE 1=1${f.where}`,
|
||||
[...f.params]
|
||||
);
|
||||
|
||||
if (!rows.length) {
|
||||
this._totalScrobblesCache = 0;
|
||||
this._totalScrobblesCacheExpiry = Date.now() + 10 * 60 * 1000;
|
||||
return 0;
|
||||
}
|
||||
|
||||
const userIds = rows.map(r => r.user_id);
|
||||
|
||||
for (let i = 0; i < userIds.length; i += concurrency) {
|
||||
const batch = userIds.slice(i, i + concurrency);
|
||||
await Promise.allSettled(batch.map(uid => this.syncUserScrobbleCount(uid)));
|
||||
}
|
||||
|
||||
const [sumRows] = await pool.execute(
|
||||
`SELECT COALESCE(SUM(scrobble_count), 0) AS total FROM lastfm_users WHERE 1=1${f.where}`,
|
||||
[...f.params]
|
||||
);
|
||||
|
||||
const total = Number(sumRows[0]?.total ?? 0);
|
||||
this._totalScrobblesCache = total;
|
||||
this._totalScrobblesCacheExpiry = Date.now() + 10 * 60 * 1000;
|
||||
|
||||
logger.settings(`[LastFm] Total synced scrobbles across ${userIds.length} users: ${total}`);
|
||||
return total;
|
||||
} catch (err) {
|
||||
logger.warn(`[LastFm] _refreshTotalScrobbles failed: ${err.message}`);
|
||||
return this._totalScrobblesCache ?? 0;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the number of linked Last.fm users from the stats table.
|
||||
* @async
|
||||
* @returns {Promise<number>} Linked user count.
|
||||
*/
|
||||
async getLinkedUsersCount() {
|
||||
if (!this.enabled) return 0;
|
||||
try {
|
||||
const pool = await this._getPool();
|
||||
const f = this._botIdFilter();
|
||||
const [rows] = await pool.execute(
|
||||
`SELECT linked_users FROM lastfm_stats WHERE id = 1${f.where}`,
|
||||
[...f.params]
|
||||
);
|
||||
return Number(rows[0]?.linked_users ?? 0);
|
||||
} catch (e) {
|
||||
logger.warn("[LastFm] Error:", e?.message);
|
||||
return 0;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the scrobble leaderboard with pagination.
|
||||
* @async
|
||||
* @param {number} [page=0] - Zero-based page index.
|
||||
* @param {number} [perPage=10] - Number of entries per page.
|
||||
* @returns {Promise<{entries: Array<{userId: string, username: string, scrobbleCount: number}>, totalUsers: number, page: number, perPage: number, totalPages: number}>} Leaderboard data.
|
||||
*/
|
||||
async getLeaderboard(page = 0, perPage = 10) {
|
||||
if (!this.enabled) return { entries: [], totalUsers: 0, page: 0, perPage: 10, totalPages: 0 };
|
||||
|
||||
const pool = await this._getPool();
|
||||
const f = this._botIdFilter();
|
||||
|
||||
const [countRows] = await pool.execute(
|
||||
`SELECT COUNT(*) AS total FROM lastfm_users WHERE scrobble_count > 0${f.where}`,
|
||||
[...f.params]
|
||||
);
|
||||
const totalUsers = Number(countRows[0]?.total ?? 0);
|
||||
const totalPages = Math.max(1, Math.ceil(totalUsers / perPage));
|
||||
|
||||
page = Math.max(0, Math.min(page, totalPages - 1));
|
||||
|
||||
const offset = page * perPage;
|
||||
const [rows] = await pool.execute(
|
||||
`SELECT user_id, username, scrobble_count FROM lastfm_users WHERE scrobble_count > 0${f.where} ORDER BY scrobble_count DESC LIMIT ? OFFSET ?`,
|
||||
[...f.params, String(perPage), String(offset)]
|
||||
);
|
||||
|
||||
const entries = rows.map(r => ({
|
||||
userId: r.user_id,
|
||||
username: r.username || r.user_id,
|
||||
scrobbleCount: Number(r.scrobble_count),
|
||||
}));
|
||||
|
||||
return { entries, totalUsers, page, perPage, totalPages };
|
||||
},
|
||||
|
||||
/**
|
||||
* Compute affinity (common artists) between multiple users.
|
||||
* @async
|
||||
* @param {Array<string>} userIds - Array of user IDs (minimum 2).
|
||||
* @param {number} [limit=10] - Maximum number of affinity pairs to return.
|
||||
* @returns {Promise<Array<{users: string[], userIds: string[], matchCount: number, commonArtists: Array<{name: string, url: string, playcount: number}>}>>} Affinity pairs sorted by match count descending.
|
||||
*/
|
||||
async getAffinity(userIds, limit = 10) {
|
||||
if (!this.enabled) return [];
|
||||
if (!Array.isArray(userIds) || userIds.length < 2) return [];
|
||||
|
||||
const userArtistsMap = new Map();
|
||||
const concurrency = 5;
|
||||
|
||||
for (let i = 0; i < userIds.length; i += concurrency) {
|
||||
const batch = userIds.slice(i, i + concurrency);
|
||||
const results = await Promise.allSettled(
|
||||
batch.map(async (uid) => {
|
||||
const user = await this.getUser(uid);
|
||||
if (!user) return null;
|
||||
try {
|
||||
const artists = await this.getTopArtists(uid, "overall", 50);
|
||||
return { uid, username: user.username, artists };
|
||||
} catch (e) {
|
||||
logger.warn("[LastFm] Error:", e?.message);
|
||||
return null;
|
||||
}
|
||||
})
|
||||
);
|
||||
for (const r of results) {
|
||||
if (r.status === "fulfilled" && r.value) {
|
||||
userArtistsMap.set(r.value.uid, r.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const entries = [...userArtistsMap.values()];
|
||||
const affinityResults = [];
|
||||
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
for (let j = i + 1; j < entries.length; j++) {
|
||||
const a = entries[i];
|
||||
const b = entries[j];
|
||||
const namesA = new Set(a.artists.map(ar => ar.name.toLowerCase()));
|
||||
const namesB = new Set(b.artists.map(ar => ar.name.toLowerCase()));
|
||||
const common = [...namesA].filter(n => namesB.has(n));
|
||||
if (common.length > 0) {
|
||||
const commonArtists = a.artists
|
||||
.filter(ar => namesB.has(ar.name.toLowerCase()))
|
||||
.map(ar => ({ name: ar.name, url: ar.url, playcount: ar.playcount }));
|
||||
affinityResults.push({
|
||||
users: [a.username, b.username],
|
||||
userIds: [a.uid, b.uid],
|
||||
matchCount: common.length,
|
||||
commonArtists,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
affinityResults.sort((a, b) => b.matchCount - a.matchCount);
|
||||
return affinityResults.slice(0, limit);
|
||||
},
|
||||
|
||||
/**
|
||||
* Get a user's "crowns" — artists where they have the highest playcount among the given users.
|
||||
* @async
|
||||
* @param {string} userId - The user ID to check crowns for.
|
||||
* @param {Array<string>} userIds - Array of all user IDs to compare against.
|
||||
* @returns {Promise<Array<{artist: string, artistUrl: string, userPlaycount: number, nextBest: object|null, image: string}>>} Crown entries sorted by user playcount descending.
|
||||
*/
|
||||
async getCrowns(userId, userIds) {
|
||||
if (!this.enabled) return [];
|
||||
const user = await this.getUser(userId);
|
||||
if (!user) return [];
|
||||
try {
|
||||
const topArtists = await this.getTopArtists(userId, "overall", 50);
|
||||
const crowns = [];
|
||||
const concurrency = 3;
|
||||
|
||||
for (let i = 0; i < topArtists.length; i += concurrency) {
|
||||
const batch = topArtists.slice(i, i + concurrency);
|
||||
const results = await Promise.allSettled(
|
||||
batch.map(async (artist) => {
|
||||
const listeners = await this.getWhoKnows(artist.name, userIds);
|
||||
if (listeners.length > 0 && listeners[0].userId === String(userId)) {
|
||||
return {
|
||||
artist: artist.name,
|
||||
artistUrl: artist.url,
|
||||
userPlaycount: artist.playcount,
|
||||
nextBest: listeners.length > 1 ? listeners[1] : null,
|
||||
image: artist.image ?? "",
|
||||
};
|
||||
}
|
||||
return null;
|
||||
})
|
||||
);
|
||||
for (const r of results) {
|
||||
if (r.status === "fulfilled" && r.value) crowns.push(r.value);
|
||||
}
|
||||
}
|
||||
|
||||
crowns.sort((a, b) => b.userPlaycount - a.userPlaycount);
|
||||
return crowns;
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
}
|
||||
};
|
||||
|
||||
export default ServerStatsMixin;
|
||||
export { ServerStatsMixin };
|
||||
@@ -0,0 +1,795 @@
|
||||
/**
|
||||
* @module src/services/lastfm/TrackQueriesMixin
|
||||
* @description Read-only track / artist / album / tag / geo / chart Last.fm API queries (plus track search and love/unlove) for LastFmManager.
|
||||
*
|
||||
* These methods are applied onto the LastFmManager class prototype via
|
||||
* {@link applyMixins} — `this` is a LastFmManager instance.
|
||||
*/
|
||||
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
import { apiCall, normalizeTrackText } from "./constants.mjs";
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
* @description Track-queries mixin — applied to LastFmManager.
|
||||
*/
|
||||
const TrackQueriesMixin = {
|
||||
/** @async Get track info from Last.fm. @param {string} artist @param {string} track @param {string} [userId] @returns {Promise<object|null>} Track info object or null. */
|
||||
async getTrackInfo(artist, track, userId = null) {
|
||||
if (!this.enabled) return null;
|
||||
|
||||
const params = {
|
||||
method: "track.getinfo",
|
||||
api_key: this.apiKey,
|
||||
artist,
|
||||
track,
|
||||
};
|
||||
|
||||
if (userId) {
|
||||
const user = await this.getUser(userId);
|
||||
if (user) params.username = user.username;
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await apiCall(params, this.apiSecret);
|
||||
return data.track;
|
||||
} catch (e) {
|
||||
logger.warn("[LastFm] Error:", e?.message);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
/** @async Love a track on Last.fm. @param {string} userId @param {string} artist @param {string} track @throws {Error} If user not linked. */
|
||||
async loveTrack(userId, artist, track) {
|
||||
if (!this.enabled) return;
|
||||
const user = await this.getUser(userId);
|
||||
if (!user) throw new Error("NOT_LINKED");
|
||||
|
||||
await apiCall(
|
||||
{
|
||||
method: "track.love",
|
||||
api_key: this.apiKey,
|
||||
sk: user.sessionKey,
|
||||
artist,
|
||||
track,
|
||||
},
|
||||
this.apiSecret,
|
||||
true
|
||||
);
|
||||
},
|
||||
|
||||
/** @async Unlove a track on Last.fm. @param {string} userId @param {string} artist @param {string} track @throws {Error} If user not linked. */
|
||||
async unloveTrack(userId, artist, track) {
|
||||
if (!this.enabled) return;
|
||||
const user = await this.getUser(userId);
|
||||
if (!user) throw new Error("NOT_LINKED");
|
||||
|
||||
await apiCall(
|
||||
{
|
||||
method: "track.unlove",
|
||||
api_key: this.apiKey,
|
||||
sk: user.sessionKey,
|
||||
artist,
|
||||
track,
|
||||
},
|
||||
this.apiSecret,
|
||||
true
|
||||
);
|
||||
},
|
||||
|
||||
/** @async Search for tracks on Last.fm and score results by relevance. @param {string} query @param {number} [limit=10] @returns {Promise<Array<{artist: string, name: string, url: string, image: string}>|null>} */
|
||||
async searchTrack(query, limit = 10) {
|
||||
if (!this.enabled) return null;
|
||||
|
||||
const data = await apiCall(
|
||||
{
|
||||
method: "track.search",
|
||||
api_key: this.apiKey,
|
||||
track: query,
|
||||
limit,
|
||||
},
|
||||
this.apiSecret
|
||||
);
|
||||
|
||||
const matches = data?.results?.trackmatches?.track;
|
||||
const tracks = Array.isArray(matches)
|
||||
? matches
|
||||
: matches
|
||||
? [matches]
|
||||
: [];
|
||||
|
||||
if (!tracks.length) return null;
|
||||
|
||||
const normalizedQuery = normalizeTrackText(query);
|
||||
const queryTokens = normalizedQuery.split(" ").filter(Boolean);
|
||||
|
||||
const scored = tracks.map((track, index) => {
|
||||
const artist = String(track.artist ?? "").trim();
|
||||
const name = String(track.name ?? "").trim();
|
||||
const artistNorm = normalizeTrackText(artist);
|
||||
const nameNorm = normalizeTrackText(name);
|
||||
const combined = `${artistNorm} ${nameNorm}`.trim();
|
||||
|
||||
let score = 0;
|
||||
|
||||
if (combined === normalizedQuery) score += 50;
|
||||
if (combined.includes(normalizedQuery) && normalizedQuery) score += 25;
|
||||
if (normalizedQuery.includes(nameNorm) && nameNorm) score += 15;
|
||||
if (normalizedQuery.includes(artistNorm) && artistNorm) score += 12;
|
||||
|
||||
const overlap = queryTokens.filter(token => combined.includes(token)).length;
|
||||
score += overlap * 4;
|
||||
|
||||
const nameLower = name.toLowerCase();
|
||||
const artistLower = artist.toLowerCase();
|
||||
const urlLower = String(track.url ?? "").toLowerCase();
|
||||
const fullText = `${nameLower} ${artistLower} ${urlLower}`;
|
||||
|
||||
const negativePatterns = [
|
||||
/\bofficial (?:lyric|lyrics)\s*video\b/,
|
||||
/\bofficial video\b/,
|
||||
/\bofficial music video\b/,
|
||||
/\blyric video\b/,
|
||||
/\blyrics video\b/,
|
||||
/\bmusic video\b/,
|
||||
/\bofficial audio\b/,
|
||||
/\bvisuali[sz]er\b/,
|
||||
/\bkaraoke\b/,
|
||||
/\bcover\b/,
|
||||
/\bremix\b/,
|
||||
/\bacoustic\b/,
|
||||
/\blive\b/,
|
||||
/\bsped up\b/,
|
||||
/\bslowed\b/,
|
||||
/\breverb\b/,
|
||||
/\bnightcore\b/,
|
||||
/\b8d\b/,
|
||||
/\bclip officiel\b/,
|
||||
/\bvideo oficial\b/,
|
||||
/\bperformance\b/,
|
||||
];
|
||||
|
||||
for (const re of negativePatterns) {
|
||||
if (re.test(fullText)) {
|
||||
score -= 30;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const labelKeywords = [
|
||||
/\bpictures\b/i,
|
||||
/\banimation\b/i,
|
||||
/\brecords?\b/i,
|
||||
/\bstudios?\b/i,
|
||||
/\bentertainment\b/i,
|
||||
/\bproductions?\b/i,
|
||||
/\bmusic\s+(group|corp|inc|llc)\b/i,
|
||||
/\brecordings?\b/i,
|
||||
/\blabel\b/i,
|
||||
];
|
||||
for (const re of labelKeywords) {
|
||||
if (re.test(artist)) {
|
||||
score -= 20;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (/^["""].*["""]$/.test(name) || /["""]/.test(name)) {
|
||||
score -= 15;
|
||||
}
|
||||
|
||||
if (urlLower.includes("/_/")) {
|
||||
score += 5;
|
||||
}
|
||||
|
||||
return {
|
||||
index,
|
||||
score,
|
||||
track: {
|
||||
artist,
|
||||
name,
|
||||
url: track.url ?? "",
|
||||
},
|
||||
};
|
||||
});
|
||||
|
||||
scored.sort((a, b) => b.score - a.score || a.index - b.index);
|
||||
return scored[0]?.track ?? null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get similar tracks for a given artist and track from Last.fm.
|
||||
* @async
|
||||
* @param {string} artist - The artist name.
|
||||
* @param {string} track - The track name.
|
||||
* @param {number} [limit=5] - Maximum number of results.
|
||||
* @returns {Promise<Array<{artist: string, name: string, url: string, match: number}>>} Filtered similar tracks (match > 0.1).
|
||||
*/
|
||||
async getSimilarTracks(artist, track, limit = 5) {
|
||||
if (!this.enabled) return [];
|
||||
|
||||
try {
|
||||
const data = await apiCall(
|
||||
{
|
||||
method: "track.getsimilar",
|
||||
api_key: this.apiKey,
|
||||
artist,
|
||||
track,
|
||||
limit,
|
||||
},
|
||||
this.apiSecret
|
||||
);
|
||||
|
||||
return (data.similartracks?.track ?? []).map(t => ({
|
||||
artist: t.artist?.name ?? "Unknown",
|
||||
name: t.name,
|
||||
url: t.url ?? "",
|
||||
match: parseFloat(t.match ?? 0),
|
||||
})).filter(t => t.match > 0.1);
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
},
|
||||
|
||||
/**
|
||||
* Get detailed artist info from Last.fm.
|
||||
* @async
|
||||
* @param {string} artist - The artist name.
|
||||
* @param {string|null} [userId] - Optional user ID to include user playcount.
|
||||
* @returns {Promise<object|null>} Artist info object with name, url, image, tags, bio, stats, similar, and userplaycount, or null.
|
||||
*/
|
||||
async getArtistInfo(artist, userId = null) {
|
||||
if (!this.enabled) return null;
|
||||
|
||||
const params = {
|
||||
method: "artist.getinfo",
|
||||
api_key: this.apiKey,
|
||||
artist,
|
||||
};
|
||||
|
||||
if (userId) {
|
||||
const user = await this.getUser(userId);
|
||||
if (user) params.username = user.username;
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await apiCall(params, this.apiSecret);
|
||||
const a = data.artist;
|
||||
if (!a) return null;
|
||||
|
||||
return {
|
||||
name: a.name ?? "",
|
||||
url: a.url ?? "",
|
||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||
tags: (a.tags?.tag ?? []).map(t => t.name ?? t),
|
||||
bio: a.bio?.summary ?? a.bio?.content ?? "",
|
||||
stats: {
|
||||
listeners: Number(a.stats?.listeners ?? 0),
|
||||
playcount: Number(a.stats?.playcount ?? 0),
|
||||
},
|
||||
similar: (a.similar?.artist ?? []).map(s => ({
|
||||
name: s.name ?? "",
|
||||
url: s.url ?? "",
|
||||
image: s.image?.[2]?.["#text"] ?? s.image?.[1]?.["#text"] ?? "",
|
||||
})),
|
||||
userplaycount: a.stats?.userplaycount ? Number(a.stats.userplaycount) : null,
|
||||
};
|
||||
} catch (e) {
|
||||
logger.warn("[LastFm] Error:", e?.message);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Get detailed album info from Last.fm.
|
||||
* @async
|
||||
* @param {string} artist - The artist name.
|
||||
* @param {string} album - The album name.
|
||||
* @param {string|null} [userId] - Optional user ID to include user playcount.
|
||||
* @returns {Promise<object|null>} Album info object with name, artist, url, image, tags, tracks, and userplaycount, or null.
|
||||
*/
|
||||
async getAlbumInfo(artist, album, userId = null) {
|
||||
if (!this.enabled) return null;
|
||||
|
||||
const params = {
|
||||
method: "album.getinfo",
|
||||
api_key: this.apiKey,
|
||||
artist,
|
||||
album,
|
||||
};
|
||||
|
||||
if (userId) {
|
||||
const user = await this.getUser(userId);
|
||||
if (user) params.username = user.username;
|
||||
}
|
||||
|
||||
try {
|
||||
const data = await apiCall(params, this.apiSecret);
|
||||
const a = data.album;
|
||||
if (!a) return null;
|
||||
|
||||
return {
|
||||
name: a.name ?? "",
|
||||
artist: a.artist ?? "",
|
||||
url: a.url ?? "",
|
||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||
tags: (a.tags?.tag ?? []).map(t => t.name ?? t),
|
||||
tracks: (a.tracks?.track ?? []).map(t => ({
|
||||
name: t.name ?? "",
|
||||
url: t.url ?? "",
|
||||
duration: Number(t.duration ?? 0),
|
||||
playcount: Number(t.playcount ?? 0),
|
||||
})),
|
||||
userplaycount: a.userplaycount ? Number(a.userplaycount) : null,
|
||||
};
|
||||
} catch (e) {
|
||||
logger.warn("[LastFm] Error:", e?.message);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Get top tracks for an artist from Last.fm.
|
||||
* @async
|
||||
* @param {string} artist - The artist name.
|
||||
* @param {number} [limit=10] - Maximum number of results.
|
||||
* @returns {Promise<Array<{artist: string, name: string, url: string, playcount: number, image: string}>>} Top tracks.
|
||||
*/
|
||||
async getArtistTopTracks(artist, limit = 10) {
|
||||
if (!this.enabled) return [];
|
||||
|
||||
try {
|
||||
const data = await apiCall(
|
||||
{
|
||||
method: "artist.gettoptracks",
|
||||
api_key: this.apiKey,
|
||||
artist,
|
||||
limit,
|
||||
},
|
||||
this.apiSecret
|
||||
);
|
||||
|
||||
return (data.toptracks?.track ?? []).map(t => ({
|
||||
artist: t.artist?.name ?? artist,
|
||||
name: t.name ?? "",
|
||||
url: t.url ?? "",
|
||||
playcount: Number(t.playcount ?? 0),
|
||||
image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "",
|
||||
}));
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
},
|
||||
|
||||
/**
|
||||
* Get top albums for an artist from Last.fm.
|
||||
* @async
|
||||
* @param {string} artist - The artist name.
|
||||
* @param {number} [limit=10] - Maximum number of results.
|
||||
* @returns {Promise<Array<{name: string, artist: string, url: string, playcount: number, image: string}>>} Top albums.
|
||||
*/
|
||||
async getArtistTopAlbums(artist, limit = 10) {
|
||||
if (!this.enabled) return [];
|
||||
|
||||
try {
|
||||
const data = await apiCall(
|
||||
{
|
||||
method: "artist.gettopalbums",
|
||||
api_key: this.apiKey,
|
||||
artist,
|
||||
limit,
|
||||
},
|
||||
this.apiSecret
|
||||
);
|
||||
|
||||
return (data.topalbums?.album ?? []).map(a => ({
|
||||
name: a.name ?? "",
|
||||
artist: a.artist?.name ?? artist,
|
||||
url: a.url ?? "",
|
||||
playcount: Number(a.playcount ?? 0),
|
||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||
}));
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
},
|
||||
|
||||
/**
|
||||
* Get similar artists for a given artist from Last.fm.
|
||||
* @async
|
||||
* @param {string} artist - The artist name.
|
||||
* @param {number} [limit=10] - Maximum number of results.
|
||||
* @returns {Promise<Array<{name: string, url: string, image: string, match: number}>>} Similar artists.
|
||||
*/
|
||||
async getSimilarArtists(artist, limit = 10) {
|
||||
if (!this.enabled) return [];
|
||||
|
||||
try {
|
||||
const data = await apiCall(
|
||||
{
|
||||
method: "artist.getsimilar",
|
||||
api_key: this.apiKey,
|
||||
artist,
|
||||
limit,
|
||||
},
|
||||
this.apiSecret
|
||||
);
|
||||
|
||||
return (data.similarartists?.artist ?? []).map(a => ({
|
||||
name: a.name ?? "",
|
||||
url: a.url ?? "",
|
||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||
match: parseFloat(a.match ?? 0),
|
||||
}));
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
},
|
||||
|
||||
/**
|
||||
* Get information about a specific tag from Last.fm.
|
||||
* @async
|
||||
* @param {string} tag - The tag name.
|
||||
* @returns {Promise<object|null>} Tag info with name, url, reach, count, and summary, or null.
|
||||
*/
|
||||
async getTagInfo(tag) {
|
||||
if (!this.enabled) return null;
|
||||
|
||||
try {
|
||||
const data = await apiCall(
|
||||
{
|
||||
method: "tag.getinfo",
|
||||
api_key: this.apiKey,
|
||||
tag,
|
||||
},
|
||||
this.apiSecret
|
||||
);
|
||||
|
||||
const t = data.tag;
|
||||
if (!t) return null;
|
||||
|
||||
return {
|
||||
name: t.name ?? "",
|
||||
url: t.url ?? "",
|
||||
reach: Number(t.reach ?? 0),
|
||||
count: Number(t.taggings?.total ?? t.total ?? 0),
|
||||
summary: t.wiki?.summary ?? "",
|
||||
};
|
||||
} catch (e) {
|
||||
logger.warn("[LastFm] Error:", e?.message);
|
||||
return null;
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Get top tracks for a tag from Last.fm.
|
||||
* @async
|
||||
* @param {string} tag - The tag name.
|
||||
* @param {number} [limit=10] - Maximum number of results.
|
||||
* @returns {Promise<Array<{artist: string, name: string, url: string, playcount: number, image: string}>>} Tag's top tracks.
|
||||
*/
|
||||
async getTagTopTracks(tag, limit = 10) {
|
||||
if (!this.enabled) return [];
|
||||
|
||||
try {
|
||||
const data = await apiCall(
|
||||
{
|
||||
method: "tag.gettoptracks",
|
||||
api_key: this.apiKey,
|
||||
tag,
|
||||
limit,
|
||||
},
|
||||
this.apiSecret
|
||||
);
|
||||
|
||||
return (data.tracks?.track ?? []).map(t => ({
|
||||
artist: t.artist?.name ?? "Unknown",
|
||||
name: t.name ?? "",
|
||||
url: t.url ?? "",
|
||||
playcount: Number(t.playcount ?? 0),
|
||||
image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "",
|
||||
}));
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
},
|
||||
|
||||
/**
|
||||
* Get top artists for a tag from Last.fm.
|
||||
* @async
|
||||
* @param {string} tag - The tag name.
|
||||
* @param {number} [limit=10] - Maximum number of results.
|
||||
* @returns {Promise<Array<{name: string, url: string, playcount: number, image: string}>>} Tag's top artists.
|
||||
*/
|
||||
async getTagTopArtists(tag, limit = 10) {
|
||||
if (!this.enabled) return [];
|
||||
|
||||
try {
|
||||
const data = await apiCall(
|
||||
{
|
||||
method: "tag.gettopartists",
|
||||
api_key: this.apiKey,
|
||||
tag,
|
||||
limit,
|
||||
},
|
||||
this.apiSecret
|
||||
);
|
||||
|
||||
return (data.topartists?.artist ?? []).map(a => ({
|
||||
name: a.name ?? "",
|
||||
url: a.url ?? "",
|
||||
playcount: Number(a.playcount ?? 0),
|
||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||
}));
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
},
|
||||
|
||||
/**
|
||||
* Search for artists on Last.fm.
|
||||
* @async
|
||||
* @param {string} query - The search query.
|
||||
* @param {number} [limit=10] - Maximum number of results.
|
||||
* @returns {Promise<Array<{name: string, url: string, image: string, listeners: number}>>} Matching artists.
|
||||
*/
|
||||
async searchArtist(query, limit = 10) {
|
||||
if (!this.enabled) return [];
|
||||
|
||||
try {
|
||||
const data = await apiCall(
|
||||
{
|
||||
method: "artist.search",
|
||||
api_key: this.apiKey,
|
||||
artist: query,
|
||||
limit,
|
||||
},
|
||||
this.apiSecret
|
||||
);
|
||||
|
||||
const matches = data?.results?.artistmatches?.artist;
|
||||
const artists = Array.isArray(matches)
|
||||
? matches
|
||||
: matches
|
||||
? [matches]
|
||||
: [];
|
||||
|
||||
return artists.map(a => ({
|
||||
name: a.name ?? "",
|
||||
url: a.url ?? "",
|
||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||
listeners: Number(a.listeners ?? 0),
|
||||
}));
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
},
|
||||
|
||||
/**
|
||||
* Search for albums on Last.fm.
|
||||
* @async
|
||||
* @param {string} query - The search query.
|
||||
* @param {number} [limit=10] - Maximum number of results.
|
||||
* @returns {Promise<Array<{name: string, artist: string, url: string, image: string}>>} Matching albums.
|
||||
*/
|
||||
async searchAlbum(query, limit = 10) {
|
||||
if (!this.enabled) return [];
|
||||
|
||||
try {
|
||||
const data = await apiCall(
|
||||
{
|
||||
method: "album.search",
|
||||
api_key: this.apiKey,
|
||||
album: query,
|
||||
limit,
|
||||
},
|
||||
this.apiSecret
|
||||
);
|
||||
|
||||
const matches = data?.results?.albummatches?.album;
|
||||
const albums = Array.isArray(matches)
|
||||
? matches
|
||||
: matches
|
||||
? [matches]
|
||||
: [];
|
||||
|
||||
return albums.map(a => ({
|
||||
name: a.name ?? "",
|
||||
artist: a.artist ?? "",
|
||||
url: a.url ?? "",
|
||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||
}));
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
},
|
||||
|
||||
/**
|
||||
* Get top tags for an artist from Last.fm.
|
||||
* @async
|
||||
* @param {string} artist - The artist name.
|
||||
* @param {number} [limit=10] - Maximum number of results.
|
||||
* @returns {Promise<Array<{name: string, url: string, count: number}>>} Artist's top tags.
|
||||
*/
|
||||
async getArtistTopTags(artist, limit = 10) {
|
||||
if (!this.enabled) return [];
|
||||
try {
|
||||
const data = await apiCall({
|
||||
method: "artist.gettoptags",
|
||||
api_key: this.apiKey,
|
||||
artist,
|
||||
limit,
|
||||
}, this.apiSecret);
|
||||
return (data.toptags?.tag ?? []).map(t => ({
|
||||
name: t.name ?? "",
|
||||
url: t.url ?? "",
|
||||
count: Number(t.count ?? 0),
|
||||
}));
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
},
|
||||
|
||||
/**
|
||||
* Get top tags for an album from Last.fm.
|
||||
* @async
|
||||
* @param {string} artist - The artist name.
|
||||
* @param {string} album - The album name.
|
||||
* @param {number} [limit=10] - Maximum number of results.
|
||||
* @returns {Promise<Array<{name: string, url: string, count: number}>>} Album's top tags.
|
||||
*/
|
||||
async getAlbumTopTags(artist, album, limit = 10) {
|
||||
if (!this.enabled) return [];
|
||||
try {
|
||||
const data = await apiCall({
|
||||
method: "album.gettoptags",
|
||||
api_key: this.apiKey,
|
||||
artist,
|
||||
album,
|
||||
limit,
|
||||
}, this.apiSecret);
|
||||
return (data.toptags?.tag ?? []).map(t => ({
|
||||
name: t.name ?? "",
|
||||
url: t.url ?? "",
|
||||
count: Number(t.count ?? 0),
|
||||
}));
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
},
|
||||
|
||||
/**
|
||||
* Get top tags for a track from Last.fm.
|
||||
* @async
|
||||
* @param {string} artist - The artist name.
|
||||
* @param {string} track - The track name.
|
||||
* @param {number} [limit=10] - Maximum number of results.
|
||||
* @returns {Promise<Array<{name: string, url: string, count: number}>>} Track's top tags.
|
||||
*/
|
||||
async getTrackTopTags(artist, track, limit = 10) {
|
||||
if (!this.enabled) return [];
|
||||
try {
|
||||
const data = await apiCall({
|
||||
method: "track.gettoptags",
|
||||
api_key: this.apiKey,
|
||||
artist,
|
||||
track,
|
||||
limit,
|
||||
}, this.apiSecret);
|
||||
return (data.toptags?.tag ?? []).map(t => ({
|
||||
name: t.name ?? "",
|
||||
url: t.url ?? "",
|
||||
count: Number(t.count ?? 0),
|
||||
}));
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
},
|
||||
|
||||
/**
|
||||
* Get top albums for a tag from Last.fm.
|
||||
* @async
|
||||
* @param {string} tag - The tag name.
|
||||
* @param {number} [limit=10] - Maximum number of results.
|
||||
* @returns {Promise<Array<{name: string, artist: string, url: string, playcount: number, image: string}>>} Tag's top albums.
|
||||
*/
|
||||
async getTagTopAlbums(tag, limit = 10) {
|
||||
if (!this.enabled) return [];
|
||||
try {
|
||||
const data = await apiCall({
|
||||
method: "tag.gettopalbums",
|
||||
api_key: this.apiKey,
|
||||
tag,
|
||||
limit,
|
||||
}, this.apiSecret);
|
||||
return (data.albums?.album ?? []).map(a => ({
|
||||
name: a.name ?? "",
|
||||
artist: a.artist?.name ?? "Unknown",
|
||||
url: a.url ?? "",
|
||||
playcount: Number(a.playcount ?? 0),
|
||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||
}));
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
},
|
||||
|
||||
/**
|
||||
* Get top artists for a country from Last.fm.
|
||||
* @async
|
||||
* @param {string} country - The country name.
|
||||
* @param {number} [limit=10] - Maximum number of results.
|
||||
* @returns {Promise<Array<{name: string, url: string, listeners: number, image: string}>>} Country's top artists.
|
||||
*/
|
||||
async getGeoTopArtists(country, limit = 10) {
|
||||
if (!this.enabled) return [];
|
||||
try {
|
||||
const data = await apiCall({
|
||||
method: "geo.gettopartists",
|
||||
api_key: this.apiKey,
|
||||
country,
|
||||
limit,
|
||||
}, this.apiSecret);
|
||||
return (data.topartists?.artist ?? []).map(a => ({
|
||||
name: a.name ?? "",
|
||||
url: a.url ?? "",
|
||||
listeners: Number(a.listeners ?? 0),
|
||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||
}));
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
},
|
||||
|
||||
/**
|
||||
* Get top tracks for a country from Last.fm.
|
||||
* @async
|
||||
* @param {string} country - The country name.
|
||||
* @param {number} [limit=10] - Maximum number of results.
|
||||
* @returns {Promise<Array<{name: string, artist: string, url: string, listeners: number, image: string}>>} Country's top tracks.
|
||||
*/
|
||||
async getGeoTopTracks(country, limit = 10) {
|
||||
if (!this.enabled) return [];
|
||||
try {
|
||||
const data = await apiCall({
|
||||
method: "geo.gettoptracks",
|
||||
api_key: this.apiKey,
|
||||
country,
|
||||
limit,
|
||||
}, this.apiSecret);
|
||||
return (data.tracks?.track ?? []).map(t => ({
|
||||
name: t.name ?? "",
|
||||
artist: t.artist?.name ?? "Unknown",
|
||||
url: t.url ?? "",
|
||||
listeners: Number(t.listeners ?? 0),
|
||||
image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "",
|
||||
}));
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the global top tracks chart from Last.fm.
|
||||
* @async
|
||||
* @param {number} [limit=10] - Maximum number of results.
|
||||
* @returns {Promise<Array<{name: string, artist: string, url: string, listeners: number, playcount: number, image: string}>>} Global top tracks.
|
||||
*/
|
||||
async getChartTopTracks(limit = 10) {
|
||||
if (!this.enabled) return [];
|
||||
try {
|
||||
const data = await apiCall({
|
||||
method: "chart.gettoptracks",
|
||||
api_key: this.apiKey,
|
||||
limit,
|
||||
}, this.apiSecret);
|
||||
return (data.tracks?.track ?? []).map(t => ({
|
||||
name: t.name ?? "",
|
||||
artist: t.artist?.name ?? "Unknown",
|
||||
url: t.url ?? "",
|
||||
listeners: Number(t.listeners ?? 0),
|
||||
playcount: Number(t.playcount ?? 0),
|
||||
image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "",
|
||||
}));
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the global top artists chart from Last.fm.
|
||||
* @async
|
||||
* @param {number} [limit=10] - Maximum number of results.
|
||||
* @returns {Promise<Array<{name: string, url: string, listeners: number, playcount: number, image: string}>>} Global top artists.
|
||||
*/
|
||||
async getChartTopArtists(limit = 10) {
|
||||
if (!this.enabled) return [];
|
||||
try {
|
||||
const data = await apiCall({
|
||||
method: "chart.gettopartists",
|
||||
api_key: this.apiKey,
|
||||
limit,
|
||||
}, this.apiSecret);
|
||||
return (data.artists?.artist ?? []).map(a => ({
|
||||
name: a.name ?? "",
|
||||
url: a.url ?? "",
|
||||
listeners: Number(a.listeners ?? 0),
|
||||
playcount: Number(a.playcount ?? 0),
|
||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||
}));
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
}
|
||||
};
|
||||
|
||||
export default TrackQueriesMixin;
|
||||
export { TrackQueriesMixin };
|
||||
@@ -0,0 +1,593 @@
|
||||
/**
|
||||
* @module src/services/lastfm/UserQueriesMixin
|
||||
* @description Per-user Last.fm queries: loved / top / recent tracks, profile info, playlists (scraped), top albums & artists, playback category resolution and weekly charts.
|
||||
*
|
||||
* These methods are applied onto the LastFmManager class prototype via
|
||||
* {@link applyMixins} — `this` is a LastFmManager instance.
|
||||
*/
|
||||
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
import { apiCall } from "./constants.mjs";
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
* @description User-queries mixin — applied to LastFmManager.
|
||||
*/
|
||||
const UserQueriesMixin = {
|
||||
/** @async Get a user's loved tracks. @param {string} userId @param {number} [limit=20] @returns {Promise<Array<{artist: string, name: string, url: string, image: string}>>} @throws {Error} If user not linked. */
|
||||
async getLovedTracks(userId, limit = 20) {
|
||||
const user = await this.getUser(userId);
|
||||
if (!user) throw new Error("NOT_LINKED");
|
||||
|
||||
const data = await apiCall(
|
||||
{
|
||||
method: "user.getlovedtracks",
|
||||
api_key: this.apiKey,
|
||||
user: user.username,
|
||||
limit,
|
||||
},
|
||||
this.apiSecret
|
||||
);
|
||||
|
||||
return (data.lovedtracks?.track ?? []).map(t => ({
|
||||
artist: t.artist?.name ?? t.artist?.["#text"] ?? "Unknown",
|
||||
name: t.name,
|
||||
url: t.url,
|
||||
image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "",
|
||||
}));
|
||||
},
|
||||
|
||||
/** @async Get a user's top tracks. @param {string} userId @param {string} [period="overall"] @param {number} [limit=20] @returns {Promise<Array<{artist: string, name: string, url: string, playcount: number, image: string}>>} @throws {Error} If user not linked. */
|
||||
async getTopTracks(userId, period = "overall", limit = 20) {
|
||||
const user = await this.getUser(userId);
|
||||
if (!user) throw new Error("NOT_LINKED");
|
||||
|
||||
const data = await apiCall(
|
||||
{
|
||||
method: "user.gettoptracks",
|
||||
api_key: this.apiKey,
|
||||
user: user.username,
|
||||
period,
|
||||
limit,
|
||||
},
|
||||
this.apiSecret
|
||||
);
|
||||
|
||||
return (data.toptracks?.track ?? []).map(t => ({
|
||||
artist: t.artist?.name ?? "Unknown",
|
||||
name: t.name,
|
||||
url: t.url,
|
||||
playcount: t.playcount ?? 0,
|
||||
image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "",
|
||||
}));
|
||||
},
|
||||
|
||||
/** @async Get a user's recent tracks. @param {string} userId @param {number} [limit=20] @returns {Promise<Array<{artist: string, name: string, url: string, now: boolean, image: string}>>} @throws {Error} If user not linked. */
|
||||
async getRecentTracks(userId, limit = 20) {
|
||||
const user = await this.getUser(userId);
|
||||
if (!user) throw new Error("NOT_LINKED");
|
||||
|
||||
const data = await apiCall(
|
||||
{
|
||||
method: "user.getrecenttracks",
|
||||
api_key: this.apiKey,
|
||||
user: user.username,
|
||||
limit,
|
||||
},
|
||||
this.apiSecret
|
||||
);
|
||||
|
||||
return (data.recenttracks?.track ?? []).map(t => ({
|
||||
artist: t.artist?.["#text"] ?? t.artist?.name ?? "Unknown",
|
||||
name: t.name,
|
||||
url: t.url,
|
||||
now: t["@attr"]?.nowplaying === "true",
|
||||
image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "",
|
||||
}));
|
||||
},
|
||||
|
||||
/**
|
||||
* Get a user's top tags from Last.fm.
|
||||
* @async
|
||||
* @param {string} userId - The user ID.
|
||||
* @param {number} [limit=20] - Maximum number of results.
|
||||
* @returns {Promise<Array<{name: string, url: string, count: number}>>} Top tags.
|
||||
*/
|
||||
async getUserTopTags(userId, limit = 20) {
|
||||
if (!this.enabled) return [];
|
||||
|
||||
const user = await this.getUser(userId);
|
||||
if (!user) return [];
|
||||
|
||||
try {
|
||||
const data = await apiCall(
|
||||
{
|
||||
method: "user.gettoptags",
|
||||
api_key: this.apiKey,
|
||||
user: user.username,
|
||||
limit,
|
||||
},
|
||||
this.apiSecret
|
||||
);
|
||||
|
||||
return (data.toptags?.tag ?? []).map(t => ({
|
||||
name: t.name ?? "",
|
||||
url: t.url ?? "",
|
||||
count: Number(t.count ?? 0),
|
||||
}));
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
},
|
||||
|
||||
/**
|
||||
* Get the list of weekly chart periods for a user.
|
||||
* @async
|
||||
* @param {string} userId - The user ID.
|
||||
* @returns {Promise<Array<{from: number, to: number}>>} Weekly chart periods with Unix timestamps.
|
||||
*/
|
||||
async getUserWeeklyChartList(userId) {
|
||||
if (!this.enabled) return [];
|
||||
|
||||
const user = await this.getUser(userId);
|
||||
if (!user) return [];
|
||||
|
||||
try {
|
||||
const data = await apiCall(
|
||||
{
|
||||
method: "user.getweeklychartlist",
|
||||
api_key: this.apiKey,
|
||||
user: user.username,
|
||||
},
|
||||
this.apiSecret
|
||||
);
|
||||
|
||||
return (data.weeklychartlist?.chart ?? []).map(c => ({
|
||||
from: Number(c.from ?? 0),
|
||||
to: Number(c.to ?? 0),
|
||||
}));
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
},
|
||||
|
||||
/**
|
||||
* Get a user's Last.fm profile info.
|
||||
* @async
|
||||
* @param {string} userId - The user ID.
|
||||
* @returns {Promise<object>} The Last.fm user object.
|
||||
* @throws {Error} If user is not linked.
|
||||
*/
|
||||
async getUserInfo(userId) {
|
||||
const user = await this.getUser(userId);
|
||||
if (!user) throw new Error("NOT_LINKED");
|
||||
|
||||
const data = await apiCall(
|
||||
{
|
||||
method: "user.getinfo",
|
||||
api_key: this.apiKey,
|
||||
user: user.username,
|
||||
},
|
||||
this.apiSecret
|
||||
);
|
||||
|
||||
return data.user;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get a user's Last.fm playlists by scraping their profile page.
|
||||
* @async
|
||||
* @param {string} userId - The user ID.
|
||||
* @returns {Promise<Array<{id: string, title: string, url: string, trackCount: number}>>} User's playlists.
|
||||
* @throws {Error} If user is not linked or fetch fails.
|
||||
*/
|
||||
async getPlaylists(userId) {
|
||||
const user = await this.getUser(userId);
|
||||
if (!user) throw new Error("NOT_LINKED");
|
||||
|
||||
const profileUrl = `https://www.last.fm/user/${encodeURIComponent(user.username)}/playlists`;
|
||||
const res = await fetch(profileUrl, {
|
||||
headers: { "User-Agent": "RemixBot/1.0 (Last.fm Integration)" },
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to fetch profile page (HTTP ${res.status})`);
|
||||
}
|
||||
|
||||
const html = await res.text();
|
||||
const playlists = [];
|
||||
|
||||
const playlistRegex = /href="\/user\/[^/]+\/playlists\/(\d+)"[^>]*>([^<]+)<\/a>/gi;
|
||||
let match;
|
||||
while ((match = playlistRegex.exec(html)) !== null) {
|
||||
const id = match[1];
|
||||
const title = match[2].trim();
|
||||
if (title && id) {
|
||||
playlists.push({
|
||||
id,
|
||||
title,
|
||||
url: `https://www.last.fm/user/${user.username}/playlists/${id}`,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const countRegex = /(\d+)\s+track/gi;
|
||||
const counts = [];
|
||||
let cMatch;
|
||||
while ((cMatch = countRegex.exec(html)) !== null) {
|
||||
counts.push(+cMatch[1]);
|
||||
}
|
||||
playlists.forEach((pl, i) => {
|
||||
pl.trackCount = counts[i] ?? 0;
|
||||
});
|
||||
|
||||
return playlists;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get tracks from a user's Last.fm playlist by scraping the playlist page.
|
||||
* @async
|
||||
* @param {string} userId - The user ID.
|
||||
* @param {string|number} playlistId - Playlist number (1-based index) or URL.
|
||||
* @param {number} [limit=50] - Maximum number of tracks.
|
||||
* @returns {Promise<Array<{artist: string, name: string, url: string, image: string}>>} Playlist tracks.
|
||||
* @throws {Error} If user is not linked or playlist not found.
|
||||
*/
|
||||
async getPlaylistTracks(userId, playlistId, limit = 50) {
|
||||
const user = await this.getUser(userId);
|
||||
if (!user) throw new Error("NOT_LINKED");
|
||||
|
||||
let playlistUrl;
|
||||
|
||||
if (/^\d+$/.test(String(playlistId))) {
|
||||
const playlists = await this.getPlaylists(userId);
|
||||
const idx = +playlistId - 1;
|
||||
if (idx < 0 || idx >= playlists.length) {
|
||||
throw new Error(`Playlist #${playlistId} not found. You have ${playlists.length} playlist(s). Use the lastfm playlists command to see them.`);
|
||||
}
|
||||
playlistUrl = playlists[idx].url;
|
||||
} else if (String(playlistId).startsWith("http")) {
|
||||
playlistUrl = String(playlistId);
|
||||
} else {
|
||||
playlistUrl = `https://www.last.fm/user/${user.username}/playlists/${playlistId}`;
|
||||
}
|
||||
|
||||
const res = await fetch(playlistUrl, {
|
||||
headers: { "User-Agent": "RemixBot/1.0 (Last.fm Integration)" },
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
throw new Error(`Failed to fetch playlist page (HTTP ${res.status})`);
|
||||
}
|
||||
|
||||
const html = await res.text();
|
||||
const tracks = [];
|
||||
|
||||
const trackLinkRegex = /href="\/music\/([^"]+?)"[^>]*class="[^"]*(?:link-block-target|chartlist-name)[^"]*"[^>]*>([^<]+)<\/a>/gi;
|
||||
let tMatch;
|
||||
while ((tMatch = trackLinkRegex.exec(html)) !== null && tracks.length < limit) {
|
||||
const urlPath = decodeURIComponent(tMatch[1]);
|
||||
const name = tMatch[2].trim();
|
||||
const parts = urlPath.split("/");
|
||||
let artist = "Unknown";
|
||||
if (parts.length >= 1) {
|
||||
artist = parts[0].replace(/\+/g, " ");
|
||||
}
|
||||
|
||||
if (name && name !== "Unknown") {
|
||||
tracks.push({
|
||||
artist,
|
||||
name,
|
||||
url: `https://www.last.fm/music/${urlPath}`,
|
||||
image: "",
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if (!tracks.length) {
|
||||
const broadRegex = /href="\/music\/([^"]+)"[^>]*>([^<]{2,80})<\/a>/gi;
|
||||
const seen = new Set();
|
||||
let bMatch;
|
||||
while ((bMatch = broadRegex.exec(html)) !== null && tracks.length < limit) {
|
||||
const urlPath = decodeURIComponent(bMatch[1]);
|
||||
const name = bMatch[2].trim();
|
||||
const parts = urlPath.split("/");
|
||||
if (parts.length < 2) continue;
|
||||
if (seen.has(urlPath)) continue;
|
||||
seen.add(urlPath);
|
||||
|
||||
const artist = parts[0].replace(/\+/g, " ");
|
||||
const trackName = parts.length >= 3 && parts[1] === "_"
|
||||
? parts[2].replace(/\+/g, " ")
|
||||
: parts[1].replace(/\+/g, " ");
|
||||
|
||||
if (trackName && artist) {
|
||||
tracks.push({
|
||||
artist,
|
||||
name: trackName,
|
||||
url: `https://www.last.fm/music/${urlPath}`,
|
||||
image: "",
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return tracks;
|
||||
},
|
||||
|
||||
/**
|
||||
* Get a user's top albums from Last.fm.
|
||||
* @async
|
||||
* @param {string} userId - The user ID.
|
||||
* @param {string} [period="overall"] - Time period (7day, 1month, 3month, 6month, 12month, overall).
|
||||
* @param {number} [limit=20] - Maximum number of results.
|
||||
* @returns {Promise<Array<{artist: string, name: string, url: string, playcount: number, image: string}>>} Top albums.
|
||||
* @throws {Error} If user is not linked.
|
||||
*/
|
||||
async getTopAlbums(userId, period = "overall", limit = 20) {
|
||||
const user = await this.getUser(userId);
|
||||
if (!user) throw new Error("NOT_LINKED");
|
||||
|
||||
const data = await apiCall(
|
||||
{
|
||||
method: "user.gettopalbums",
|
||||
api_key: this.apiKey,
|
||||
user: user.username,
|
||||
period,
|
||||
limit,
|
||||
},
|
||||
this.apiSecret
|
||||
);
|
||||
|
||||
return (data.topalbums?.album ?? []).map(a => ({
|
||||
artist: a.artist?.name ?? "Unknown",
|
||||
name: a.name,
|
||||
url: a.url ?? "",
|
||||
playcount: a.playcount ?? 0,
|
||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||
}));
|
||||
},
|
||||
|
||||
/**
|
||||
* Get a user's top artists from Last.fm.
|
||||
* @async
|
||||
* @param {string} userId - The user ID.
|
||||
* @param {string} [period="overall"] - Time period (7day, 1month, 3month, 6month, 12month, overall).
|
||||
* @param {number} [limit=15] - Maximum number of results.
|
||||
* @returns {Promise<Array<{name: string, url: string, playcount: number, image: string}>>} Top artists.
|
||||
* @throws {Error} If user is not linked.
|
||||
*/
|
||||
async getTopArtists(userId, period = "overall", limit = 15) {
|
||||
const user = await this.getUser(userId);
|
||||
if (!user) throw new Error("NOT_LINKED");
|
||||
|
||||
const data = await apiCall(
|
||||
{
|
||||
method: "user.gettopartists",
|
||||
api_key: this.apiKey,
|
||||
user: user.username,
|
||||
period,
|
||||
limit,
|
||||
},
|
||||
this.apiSecret
|
||||
);
|
||||
|
||||
return (data.topartists?.artist ?? []).map(a => ({
|
||||
name: a.name,
|
||||
url: a.url ?? "",
|
||||
playcount: a.playcount ?? 0,
|
||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||
}));
|
||||
},
|
||||
|
||||
/**
|
||||
* Get tracks from a user's Last.fm data for playback based on category.
|
||||
* @async
|
||||
* @param {string} userId - The user ID.
|
||||
* @param {string} category - One of: loved, top, recent, playlist, albums, artists.
|
||||
* @param {object} [options={}] - Additional options.
|
||||
* @param {number} [options.limit] - Maximum number of tracks.
|
||||
* @param {string} [options.period] - Time period for top/albums/artists categories.
|
||||
* @param {string|number} [options.playlistId] - Playlist ID (required for playlist category).
|
||||
* @returns {Promise<{username: string, tracks: Array<{query: string, artist: string, name: string, url: string, image?: string}>}>} Tracks ready for playback.
|
||||
* @throws {Error} If user is not linked or category is unknown.
|
||||
*/
|
||||
async getTracksForPlay(userId, category, options = {}) {
|
||||
const user = await this.getUser(userId);
|
||||
if (!user) throw new Error("NOT_LINKED");
|
||||
|
||||
const limit = options.limit ?? 20;
|
||||
let tracks;
|
||||
|
||||
switch (category) {
|
||||
case "loved":
|
||||
tracks = await this.getLovedTracks(userId, limit);
|
||||
break;
|
||||
case "top":
|
||||
tracks = await this.getTopTracks(userId, options.period ?? "overall", limit);
|
||||
break;
|
||||
case "recent":
|
||||
tracks = await this.getRecentTracks(userId, limit);
|
||||
tracks = tracks.filter(t => !t.now);
|
||||
break;
|
||||
case "playlist":
|
||||
if (!options.playlistId) throw new Error("Playlist ID required. Use the lastfm playlists command to see your playlists, then use the lastfm play playlist command with a number.");
|
||||
tracks = await this.getPlaylistTracks(userId, options.playlistId, limit);
|
||||
break;
|
||||
case "albums":
|
||||
const albums = await this.getTopAlbums(userId, options.period ?? "overall", limit);
|
||||
tracks = albums.map(a => ({
|
||||
artist: a.artist,
|
||||
name: a.name,
|
||||
url: a.url,
|
||||
query: `${a.artist} ${a.name} album`,
|
||||
image: a.image ?? "",
|
||||
}));
|
||||
return {
|
||||
username: user.username,
|
||||
tracks,
|
||||
};
|
||||
case "artists":
|
||||
const topArtistsList = await this.getTopArtists(userId, options.period ?? "overall", limit);
|
||||
const artistTrackResults = [];
|
||||
const artistConcurrency = 3;
|
||||
for (let ai = 0; ai < topArtistsList.length; ai += artistConcurrency) {
|
||||
const artistBatch = topArtistsList.slice(ai, ai + artistConcurrency);
|
||||
const artistResults = await Promise.allSettled(
|
||||
artistBatch.map(async (ar) => {
|
||||
try {
|
||||
const topTracks = await this.getArtistTopTracks(ar.name, 3);
|
||||
return topTracks.map(t => ({
|
||||
artist: t.artist ?? ar.name,
|
||||
name: t.name,
|
||||
url: t.url,
|
||||
query: `${t.name} ${t.artist ?? ar.name}`,
|
||||
image: t.image ?? ar.image ?? "",
|
||||
}));
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
})
|
||||
);
|
||||
for (const r of artistResults) {
|
||||
if (r.status === "fulfilled" && r.value) {
|
||||
artistTrackResults.push(...r.value);
|
||||
}
|
||||
}
|
||||
}
|
||||
return {
|
||||
username: user.username,
|
||||
tracks: artistTrackResults.slice(0, limit * 3),
|
||||
};
|
||||
default:
|
||||
throw new Error(`Unknown Last.fm category: ${category}. Use loved, top, recent, playlist, albums, or artists.`);
|
||||
}
|
||||
|
||||
return {
|
||||
username: user.username,
|
||||
tracks: tracks.map(t => ({
|
||||
query: this._buildPlayQuery(t.artist, t.name),
|
||||
artist: t.artist,
|
||||
name: t.name,
|
||||
url: t.url ?? "",
|
||||
})),
|
||||
};
|
||||
},
|
||||
|
||||
/**
|
||||
* Get a user's Last.fm friends list.
|
||||
* @async
|
||||
* @param {string} userId - The user ID.
|
||||
* @param {number} [limit=20] - Maximum number of results.
|
||||
* @returns {Promise<Array<{name: string, url: string, image: string, realname: string, country: string}>>} Friends list.
|
||||
*/
|
||||
async getUserFriends(userId, limit = 20) {
|
||||
if (!this.enabled) return [];
|
||||
const user = await this.getUser(userId);
|
||||
if (!user) return [];
|
||||
try {
|
||||
const data = await apiCall({
|
||||
method: "user.getfriends",
|
||||
api_key: this.apiKey,
|
||||
user: user.username,
|
||||
limit,
|
||||
}, this.apiSecret);
|
||||
return (data.friends?.user ?? []).map(f => ({
|
||||
name: f.name ?? "",
|
||||
url: f.url ?? "",
|
||||
image: f.image?.[2]?.["#text"] ?? f.image?.[1]?.["#text"] ?? "",
|
||||
realname: f.realname ?? "",
|
||||
country: f.country ?? "",
|
||||
}));
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
},
|
||||
|
||||
/**
|
||||
* Get a user's weekly artist chart for a specific time range.
|
||||
* @async
|
||||
* @param {string} userId - The user ID.
|
||||
* @param {number|null} [from] - Start Unix timestamp.
|
||||
* @param {number|null} [to] - End Unix timestamp.
|
||||
* @returns {Promise<Array<{name: string, url: string, playcount: number, image: string}>>} Weekly artist chart.
|
||||
*/
|
||||
async getUserWeeklyArtistChart(userId, from = null, to = null) {
|
||||
if (!this.enabled) return [];
|
||||
const user = await this.getUser(userId);
|
||||
if (!user) return [];
|
||||
try {
|
||||
const params = {
|
||||
method: "user.getweeklyartistchart",
|
||||
api_key: this.apiKey,
|
||||
user: user.username,
|
||||
};
|
||||
if (from) params.from = from;
|
||||
if (to) params.to = to;
|
||||
const data = await apiCall(params, this.apiSecret);
|
||||
return (data.weeklyartistchart?.artist ?? []).map(a => ({
|
||||
name: a.name ?? "",
|
||||
url: a.url ?? "",
|
||||
playcount: Number(a.playcount ?? 0),
|
||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||
}));
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
},
|
||||
|
||||
/**
|
||||
* Get a user's weekly track chart for a specific time range.
|
||||
* @async
|
||||
* @param {string} userId - The user ID.
|
||||
* @param {number|null} [from] - Start Unix timestamp.
|
||||
* @param {number|null} [to] - End Unix timestamp.
|
||||
* @returns {Promise<Array<{name: string, artist: string, url: string, playcount: number, image: string}>>} Weekly track chart.
|
||||
*/
|
||||
async getUserWeeklyTrackChart(userId, from = null, to = null) {
|
||||
if (!this.enabled) return [];
|
||||
const user = await this.getUser(userId);
|
||||
if (!user) return [];
|
||||
try {
|
||||
const params = {
|
||||
method: "user.getweeklytrackchart",
|
||||
api_key: this.apiKey,
|
||||
user: user.username,
|
||||
};
|
||||
if (from) params.from = from;
|
||||
if (to) params.to = to;
|
||||
const data = await apiCall(params, this.apiSecret);
|
||||
return (data.weeklytrackchart?.track ?? []).map(t => ({
|
||||
name: t.name ?? "",
|
||||
artist: t.artist?.["#text"] ?? t.artist ?? "",
|
||||
url: t.url ?? "",
|
||||
playcount: Number(t.playcount ?? 0),
|
||||
image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "",
|
||||
}));
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
},
|
||||
|
||||
/**
|
||||
* Get a user's weekly album chart for a specific time range.
|
||||
* @async
|
||||
* @param {string} userId - The user ID.
|
||||
* @param {number|null} [from] - Start Unix timestamp.
|
||||
* @param {number|null} [to] - End Unix timestamp.
|
||||
* @returns {Promise<Array<{name: string, artist: string, url: string, playcount: number, image: string}>>} Weekly album chart.
|
||||
*/
|
||||
async getUserWeeklyAlbumChart(userId, from = null, to = null) {
|
||||
if (!this.enabled) return [];
|
||||
const user = await this.getUser(userId);
|
||||
if (!user) return [];
|
||||
try {
|
||||
const params = {
|
||||
method: "user.getweeklyalbumchart",
|
||||
api_key: this.apiKey,
|
||||
user: user.username,
|
||||
};
|
||||
if (from) params.from = from;
|
||||
if (to) params.to = to;
|
||||
const data = await apiCall(params, this.apiSecret);
|
||||
return (data.weeklyalbumchart?.album ?? []).map(a => ({
|
||||
name: a.name ?? "",
|
||||
artist: a.artist?.["#text"] ?? a.artist ?? "",
|
||||
url: a.url ?? "",
|
||||
playcount: Number(a.playcount ?? 0),
|
||||
image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "",
|
||||
}));
|
||||
} catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; }
|
||||
}
|
||||
};
|
||||
|
||||
export default UserQueriesMixin;
|
||||
export { UserQueriesMixin };
|
||||
@@ -0,0 +1,121 @@
|
||||
/**
|
||||
* @module src/services/lastfm/UserStoreMixin
|
||||
* @description User-session storage concern for LastFmManager: MySQL persistence of linked Last.fm accounts, the scrobble toggle and the auth token / URL / session exchange.
|
||||
*
|
||||
* These methods are applied onto the LastFmManager class prototype via
|
||||
* {@link applyMixins} — `this` is a LastFmManager instance.
|
||||
*/
|
||||
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
import { apiCall } from "./constants.mjs";
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
* @description User-store mixin — applied to LastFmManager.
|
||||
*/
|
||||
const UserStoreMixin = {
|
||||
/** @async Get a user's Last.fm session from cache or DB. @param {string} userId @returns {Promise<{sessionKey: string, username: string, scrobbleEnabled: boolean}|null>} */
|
||||
async getUser(userId) {
|
||||
const cached = this._userCache.get(userId);
|
||||
if (cached) return cached;
|
||||
|
||||
const pool = await this._getPool();
|
||||
const f = this._botIdFilter();
|
||||
const [rows] = await pool.execute(
|
||||
`SELECT session_key, username, scrobble FROM lastfm_users WHERE user_id = ?${f.where}`,
|
||||
[String(userId), ...f.params]
|
||||
);
|
||||
|
||||
if (!rows.length) return null;
|
||||
|
||||
const row = rows[0];
|
||||
const data = {
|
||||
sessionKey: row.session_key,
|
||||
username: row.username,
|
||||
scrobbleEnabled: !!row.scrobble,
|
||||
};
|
||||
this._userCache.set(userId, data);
|
||||
while (this._userCache.size > this._userCacheMax) {
|
||||
const oldestKey = this._userCache.keys().next().value;
|
||||
this._userCache.delete(oldestKey);
|
||||
}
|
||||
return data;
|
||||
},
|
||||
|
||||
/** @async Save or update a user's Last.fm session. @param {string} userId @param {string} sessionKey @param {string} username @returns {Promise<{sessionKey: string, username: string, scrobbleEnabled: boolean}>} */
|
||||
async saveUser(userId, sessionKey, username) {
|
||||
const pool = await this._getPool();
|
||||
const f = this._botIdFilter();
|
||||
await pool.execute(
|
||||
`INSERT INTO lastfm_users (user_id, session_key, username, scrobble${f.where ? ', bot_id' : ''})
|
||||
VALUES (?, ?, ?, 1${f.where ? ', ?' : ''})
|
||||
ON DUPLICATE KEY UPDATE session_key = VALUES(session_key), username = VALUES(username)`,
|
||||
[String(userId), sessionKey, username ?? "", ...f.params]
|
||||
);
|
||||
const data = { sessionKey, username: username ?? "", scrobbleEnabled: true };
|
||||
this._userCache.set(userId, data);
|
||||
while (this._userCache.size > this._userCacheMax) {
|
||||
const oldestKey = this._userCache.keys().next().value;
|
||||
this._userCache.delete(oldestKey);
|
||||
}
|
||||
|
||||
try {
|
||||
await pool.execute(
|
||||
`UPDATE lastfm_stats SET linked_users = linked_users + 1 WHERE id = 1${f.where} AND NOT EXISTS (SELECT 1 FROM (SELECT 1 FROM lastfm_users WHERE user_id = ?${f.where} AND linked_at < NOW()) AS tmp)`,
|
||||
[...f.params, String(userId), ...f.params]
|
||||
);
|
||||
} catch (e) {
|
||||
logger.warn("[LastFm] Stats update warning:", e?.message);
|
||||
}
|
||||
|
||||
return data;
|
||||
},
|
||||
|
||||
/** @async Remove a user's Last.fm session from cache and DB. @param {string} userId */
|
||||
async removeUser(userId) {
|
||||
const pool = await this._getPool();
|
||||
const f = this._botIdFilter();
|
||||
await pool.execute(`DELETE FROM lastfm_users WHERE user_id = ?${f.where}`, [String(userId), ...f.params]);
|
||||
this._userCache.delete(userId);
|
||||
},
|
||||
|
||||
/** @async Toggle scrobbling for a user. @param {string} userId @param {boolean} enabled */
|
||||
async setScrobble(userId, enabled) {
|
||||
const pool = await this._getPool();
|
||||
const f = this._botIdFilter();
|
||||
await pool.execute(
|
||||
`UPDATE lastfm_users SET scrobble = ? WHERE user_id = ?${f.where}`,
|
||||
[enabled ? 1 : 0, String(userId), ...f.params]
|
||||
);
|
||||
const cached = this._userCache.get(userId);
|
||||
if (cached) cached.scrobbleEnabled = enabled;
|
||||
},
|
||||
|
||||
/** @async Request a Last.fm auth token. @returns {Promise<string>} The auth token. @throws {Error} If Last.fm is not enabled. */
|
||||
async getAuthToken() {
|
||||
this._assertEnabled();
|
||||
const data = await apiCall(
|
||||
{ method: "auth.gettoken", api_key: this.apiKey },
|
||||
this.apiSecret
|
||||
);
|
||||
return data.token;
|
||||
},
|
||||
|
||||
/** Build the Last.fm auth URL for user authorization. @param {string} token @returns {string} */
|
||||
getAuthUrl(token) {
|
||||
return `https://www.last.fm/api/auth/?api_key=${this.apiKey}&token=${token}`;
|
||||
},
|
||||
|
||||
/** @async Exchange an auth token for a session. @param {string} token @returns {Promise<object>} The session object with key and name. @throws {Error} If Last.fm is not enabled. */
|
||||
async getSession(token) {
|
||||
this._assertEnabled();
|
||||
const data = await apiCall(
|
||||
{ method: "auth.getsession", api_key: this.apiKey, token },
|
||||
this.apiSecret
|
||||
);
|
||||
return data.session;
|
||||
}
|
||||
};
|
||||
|
||||
export default UserStoreMixin;
|
||||
export { UserStoreMixin };
|
||||
@@ -0,0 +1,55 @@
|
||||
/**
|
||||
* @module src/services/lastfm/constants
|
||||
* @description Constants and helpers shared by the Last.fm base class and all
|
||||
* mixin modules: the API endpoint, shared text normalisation, request signing
|
||||
* and the signed Last.fm API call wrapper. Kept in a dependency-free module so
|
||||
* the mixins never import the class file (no circular imports).
|
||||
*/
|
||||
|
||||
import crypto from "node:crypto";
|
||||
import { Utils } from "../../utils/Utils.mjs";
|
||||
|
||||
const BASE_URL = "https://ws.audioscrobbler.com/2.0/";
|
||||
|
||||
/** @private @param {string} value @returns {string} */
|
||||
function normalizeTrackText(value) {
|
||||
return Utils.normalizeText(value);
|
||||
}
|
||||
|
||||
/** @private Build an API signature per Last.fm auth spec. @param {object} params @param {string} apiSecret @returns {string} MD5 hex digest. */
|
||||
function buildSignature(params, apiSecret) {
|
||||
const sorted = Object.keys(params).sort();
|
||||
const str = sorted.map(k => k + params[k]).join("");
|
||||
return crypto.createHash("md5").update(str + apiSecret).digest("hex");
|
||||
}
|
||||
|
||||
/** @private Make an authenticated Last.fm API call. @async @param {object} params @param {string} apiSecret @param {boolean} [post=false] @returns {Promise<object>} @throws {Error} On HTTP or Last.fm API error. */
|
||||
async function apiCall(params, apiSecret, post = false) {
|
||||
const allParams = { ...params };
|
||||
allParams.api_sig = buildSignature(allParams, apiSecret);
|
||||
allParams.format = "json";
|
||||
|
||||
const url = post ? BASE_URL : `${BASE_URL}?${new URLSearchParams(allParams)}`;
|
||||
|
||||
const opts = post
|
||||
? {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/x-www-form-urlencoded" },
|
||||
body: new URLSearchParams(allParams).toString(),
|
||||
}
|
||||
: {};
|
||||
|
||||
const res = await fetch(url, opts);
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => "");
|
||||
throw new Error(`Last.fm HTTP ${res.status}: ${text.slice(0, 200)}`);
|
||||
}
|
||||
|
||||
const data = await res.json();
|
||||
if (data.error) {
|
||||
throw new Error(`Last.fm ${data.error}: ${data.message}`);
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
export { BASE_URL, normalizeTrackText, buildSignature, apiCall };
|
||||
@@ -0,0 +1,10 @@
|
||||
/**
|
||||
* @module src/services/lastfm
|
||||
* @description Public surface of the Last.fm service.
|
||||
*
|
||||
* Import map from the old layout:
|
||||
* - `src/LastFmManager.mjs` → LastFmManager.mjs (class) + urlUtils.mjs (URL helpers)
|
||||
*/
|
||||
|
||||
export { LastFmManager } from "./LastFmManager.mjs";
|
||||
export { parseLastFmUrl, isLastFmUrl } from "./urlUtils.mjs";
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* @module src/services/lastfm/urlUtils
|
||||
* @description Standalone Last.fm URL helpers: parsing music URLs into
|
||||
* artist/track/album components and Last.fm URL validation.
|
||||
*/
|
||||
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
|
||||
/**
|
||||
* Parse a Last.fm music URL into its components.
|
||||
* @param {string} url - The Last.fm URL to parse.
|
||||
* @returns {{artist: string, track: string|null, album: string|null, url: string}|null} Parsed components, or null if not a valid Last.fm music URL.
|
||||
*/
|
||||
export function parseLastFmUrl(url) {
|
||||
try {
|
||||
const u = new URL(url);
|
||||
if (!/^(?:www\.)?last\.fm$/i.test(u.hostname)) return null;
|
||||
|
||||
const match = u.pathname.match(/^\/music\/([^/]+)(?:\/([^/]+))?(?:\/([^/]+))?/);
|
||||
if (!match) return null;
|
||||
|
||||
const artist = decodeURIComponent(match[1].replace(/\+/g, " "));
|
||||
const segment2 = match[2] ? decodeURIComponent(match[2].replace(/\+/g, " ")) : null;
|
||||
const segment3 = match[3] ? decodeURIComponent(match[3].replace(/\+/g, " ")) : null;
|
||||
|
||||
let track = null;
|
||||
let album = null;
|
||||
|
||||
if (segment3) {
|
||||
album = segment2 === "_" ? null : segment2;
|
||||
track = segment3;
|
||||
} else if (segment2 && segment2 !== "_") {
|
||||
track = segment2;
|
||||
}
|
||||
|
||||
return { artist, track, album, url };
|
||||
} catch (e) {
|
||||
logger.warn("[LastFm] parseLastFmUrl error:", e?.message);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a string is a valid Last.fm music URL.
|
||||
* @param {string} str - String to check.
|
||||
* @returns {boolean} True if the string is a Last.fm URL with a /music/ path.
|
||||
*/
|
||||
export function isLastFmUrl(str) {
|
||||
if (!str || typeof str !== "string") return false;
|
||||
try {
|
||||
const u = new URL(str);
|
||||
return /^(?:www\.)?last\.fm$/i.test(u.hostname) && /^\/music\//i.test(u.pathname);
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
/**
|
||||
* @module src/ui/Embeds
|
||||
* @description Global embed color management plus message-shape helpers used
|
||||
* across the UI layer.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Parse a color value (hex string, 0x-prefixed string, or number) into an integer.
|
||||
* @param {string|number} value
|
||||
* @param {number} [fallback=0xe9196c]
|
||||
* @returns {number}
|
||||
*/
|
||||
export function parseColor(value, fallback = 0xe9196c) {
|
||||
if (!value) return fallback;
|
||||
if (typeof value === "number") return value;
|
||||
const cleaned = String(value).replace(/^#/, "").replace(/^0x/i, "");
|
||||
const n = parseInt(cleaned, 16);
|
||||
return isNaN(n) ? fallback : n;
|
||||
}
|
||||
|
||||
/** @private @type {number} */
|
||||
let _globalColor = 0xe9196c;
|
||||
|
||||
/**
|
||||
* Set the global embed color (accepts hex strings or numbers).
|
||||
* @param {string|number} value
|
||||
*/
|
||||
export function setGlobalColor(value) { _globalColor = parseColor(value); }
|
||||
|
||||
/**
|
||||
* @returns {number} The current global embed color.
|
||||
*/
|
||||
export function getGlobalColor() { return _globalColor; }
|
||||
|
||||
/**
|
||||
* Extract the guild ID from various message wrapper 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;
|
||||
}
|
||||
@@ -0,0 +1,254 @@
|
||||
/**
|
||||
* @module src/ui/HelpCommand
|
||||
* @description The rich tabbed help command (Home / Music / Utilities /
|
||||
* Support) rendered through RichPaginator, plus interception of plain-text
|
||||
* help aliases so both styles coexist.
|
||||
*/
|
||||
|
||||
import { RichPaginator } from "./Paginators.mjs";
|
||||
|
||||
/** @type {number} Maximum commands listed per page in the help paginator. */
|
||||
const HELP_CMDS_PER_PAGE = 10;
|
||||
/** @type {number} Help paginator session timeout in milliseconds. */
|
||||
const HELP_SESSION_MS = 30 * 1000;
|
||||
|
||||
/** @type {object[]} Tab definitions for the rich help. */
|
||||
const HELP_TABS = [
|
||||
{
|
||||
emoji: "🏠",
|
||||
title: "Home",
|
||||
header: "Home Page",
|
||||
static: true,
|
||||
},
|
||||
{
|
||||
emoji: "🎵",
|
||||
title: "Music",
|
||||
header: "Music Commands",
|
||||
categories: ["music"],
|
||||
},
|
||||
{
|
||||
emoji: "🔧",
|
||||
title: "Utilities",
|
||||
header: "Utility Commands",
|
||||
categories: ["util", "default"],
|
||||
},
|
||||
{
|
||||
emoji: "ℹ️",
|
||||
title: "Support",
|
||||
header: "Support Info",
|
||||
static: true,
|
||||
},
|
||||
];
|
||||
|
||||
/**
|
||||
* @private
|
||||
* @param {string} prefix
|
||||
* @returns {string}
|
||||
*/
|
||||
function _helpHomeContent(prefix) {
|
||||
return (
|
||||
"**Welcome to the Remix help page.**\n\n" +
|
||||
"Remix is an open-source music bot. It supports a variety of " +
|
||||
"streaming services and has many features.\n\n" +
|
||||
"We hope you enjoy using Remix!\n\n" +
|
||||
"To get started, just click on the reactions below to find out " +
|
||||
"more about the commands. In the case that reactions don't work " +
|
||||
"for you, there's also the possibility to look through them by " +
|
||||
`using \`${prefix}help <page number>\` :)\n\n` +
|
||||
`**Tip:** Click the tab emojis to switch sections.`
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @private
|
||||
* @returns {string}
|
||||
*/
|
||||
function _helpSupportContent() {
|
||||
return (
|
||||
"If you need help with anything or encounter any issues, hop over to " +
|
||||
"our support server **[Remix HQ](https://fluxer.gg/remix)**!\n" +
|
||||
"Alternatively, you can write a dm to any of the following people:\n\n" +
|
||||
"- **Fantic** (Community Manager)\n" +
|
||||
"- **Shadow** (Lead Developer)\n" +
|
||||
"- **NoLogicAlan** (Lead Developer)"
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* @private Build paginated content for a help category tab.
|
||||
* @param {object} tab
|
||||
* @param {Array} allCmds
|
||||
* @param {string} prefix
|
||||
* @returns {string[]}
|
||||
*/
|
||||
function _helpBuildCategoryPages(tab, allCmds, prefix) {
|
||||
const cmds = allCmds
|
||||
.filter(cmd => {
|
||||
if (cmd.requirements?.some(r => r.ownerOnly)) return false;
|
||||
return tab.categories?.includes(cmd.category ?? "default");
|
||||
})
|
||||
.sort((a, b) => a.name.localeCompare(b.name));
|
||||
|
||||
if (cmds.length === 0) return ["_No commands available._"];
|
||||
|
||||
const pages = [];
|
||||
for (let i = 0; i < cmds.length; i += HELP_CMDS_PER_PAGE) {
|
||||
const slice = cmds.slice(i, i + HELP_CMDS_PER_PAGE);
|
||||
let page = "";
|
||||
slice.forEach((cmd, j) => {
|
||||
const d = (cmd.description || "No description.").split("\n")[0];
|
||||
page += `${i + j + 1}. **${cmd.name}**: ${d}\n`;
|
||||
});
|
||||
page += `\nTo learn more about a command, run \`${prefix}help <command name>\`!`;
|
||||
if (cmds.length > HELP_CMDS_PER_PAGE)
|
||||
page += `\n\n**Tip:** Use ⬅️ ➡️ to scroll between pages.`;
|
||||
pages.push(page);
|
||||
}
|
||||
return pages;
|
||||
}
|
||||
|
||||
/**
|
||||
* @class HelpCommand
|
||||
* @description Rich paginated help command with tabbed navigation.
|
||||
*/
|
||||
export class HelpCommand {
|
||||
/**
|
||||
* @param {import('../commands/CommandHandler.mjs').CommandHandler} commandHandler
|
||||
* @param {import('./MessageHandler.mjs').MessageHandler} messageHandler
|
||||
* @param {Function} getSettingsFn
|
||||
*/
|
||||
constructor(commandHandler, messageHandler, getSettingsFn) {
|
||||
this._commands = commandHandler;
|
||||
this._messages = messageHandler;
|
||||
this._getSettings = getSettingsFn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register the help command, intercept invalid command replies, and
|
||||
* intercept help aliases so the rich help takes priority.
|
||||
*/
|
||||
register() {
|
||||
if (this._registered) return;
|
||||
this._registered = true;
|
||||
|
||||
const HELP_ALIASES = ["help", "h", "commands"];
|
||||
|
||||
this._commands.helpCommand = "\x00help";
|
||||
const _fmt = this._commands.format.bind(this._commands);
|
||||
this._commands.format = (text, guildId) =>
|
||||
_fmt(text, guildId).replace(/\x00help/g, "help");
|
||||
|
||||
const _reply = this._commands.replyHandler.bind(this._commands);
|
||||
this._commands.replyHandler = (message, msg) => {
|
||||
if (typeof message === "string" && message.toLowerCase().includes("unknown command")) {
|
||||
const content = msg?.content ?? msg?.message?.content ?? "";
|
||||
const guildId = msg?.channel?.channel?.guildId ?? msg?.message?.guildId;
|
||||
const prefix = this._commands.getPrefix(guildId);
|
||||
const botId = this._commands.client.user?.id;
|
||||
const ping = `<@${botId}>`;
|
||||
const pingBang = `<@!${botId}>`;
|
||||
let body = null;
|
||||
if (content.startsWith(prefix)) body = content.slice(prefix.length).trim();
|
||||
else if (content.startsWith(pingBang)) body = content.slice(pingBang.length).trim();
|
||||
else if (content.startsWith(ping)) body = content.slice(ping.length).trim();
|
||||
if (body !== null) {
|
||||
const first = body.split(/\s+/)[0]?.toLowerCase();
|
||||
if (HELP_ALIASES.includes(first)) return;
|
||||
}
|
||||
}
|
||||
return _reply(message, msg);
|
||||
};
|
||||
|
||||
const evict = () => {
|
||||
for (const alias of HELP_ALIASES) {
|
||||
const i = this._commands.commandNames.indexOf(alias);
|
||||
if (i !== -1) this._commands.commandNames.splice(i, 1);
|
||||
}
|
||||
const ci = this._commands.commands.findIndex(c =>
|
||||
c.aliases.some(a => HELP_ALIASES.includes(a.toLowerCase()))
|
||||
);
|
||||
if (ci !== -1) this._commands.commands.splice(ci, 1);
|
||||
};
|
||||
evict();
|
||||
const _add = this._commands.addCommand.bind(this._commands);
|
||||
this._commands.addCommand = (builder) => {
|
||||
const r = _add(builder);
|
||||
if (builder.aliases.some(a => HELP_ALIASES.includes(a.toLowerCase()))) evict();
|
||||
return r;
|
||||
};
|
||||
|
||||
this._messages.onMessage((msg) => {
|
||||
if (!msg?.content) return;
|
||||
const content = msg.content.trim();
|
||||
const guildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
const prefix = this._commands.getPrefix(guildId);
|
||||
const botId = this._commands.client.user?.id;
|
||||
const ping = `<@${botId}>`;
|
||||
const pingBang = `<@!${botId}>`;
|
||||
let body = null;
|
||||
if (content.startsWith(prefix)) body = content.slice(prefix.length).trim();
|
||||
else if (content.startsWith(pingBang)) body = content.slice(pingBang.length).trim();
|
||||
else if (content.startsWith(ping)) body = content.slice(ping.length).trim();
|
||||
if (body === null) return;
|
||||
|
||||
const args = body.split(/\s+/).map(s => s.trim()).filter(Boolean);
|
||||
const cmdName = (args[0] ?? "").toLowerCase();
|
||||
if (!HELP_ALIASES.includes(cmdName)) return;
|
||||
|
||||
this._handle(msg, args.slice(1), prefix);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @private Handle a help invocation: show command detail or paginated overview.
|
||||
* @param {import('./Wrappers.mjs').Message} msg
|
||||
* @param {string[]} args
|
||||
* @param {string} prefix
|
||||
*/
|
||||
_handle(msg, args, prefix) {
|
||||
const allCmds = this._commands.commands;
|
||||
const query = (args[0] ?? "").trim();
|
||||
|
||||
if (query && isNaN(Number(query))) {
|
||||
let currCmd = null;
|
||||
for (const word of [query, ...args.slice(1)]) {
|
||||
const pool = currCmd ? currCmd.subcommands : allCmds;
|
||||
const found = pool.find(c =>
|
||||
c.aliases.some(a => a.toLowerCase() === word.toLowerCase())
|
||||
);
|
||||
if (!found) {
|
||||
const guildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
msg.reply(this._commands.t(guildId, "cmdHandler.help.unknownCommand", { command: word, prefix }));
|
||||
return;
|
||||
}
|
||||
currCmd = found;
|
||||
}
|
||||
if (currCmd) {
|
||||
msg.reply(this._commands.helpHandler.getCommandHelp(currCmd, msg));
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
const startTab = query
|
||||
? Math.max(0, Math.min(HELP_TABS.length - 1, parseInt(query) - 1))
|
||||
: 0;
|
||||
|
||||
const paginator = new RichPaginator(msg, this._messages)
|
||||
.setTimeout(HELP_SESSION_MS)
|
||||
.setStartTab(startTab);
|
||||
|
||||
for (const tab of HELP_TABS) {
|
||||
if (tab.static) {
|
||||
const content = tab.title === "Home"
|
||||
? _helpHomeContent(prefix)
|
||||
: _helpSupportContent();
|
||||
paginator.addTab({ emoji: tab.emoji, title: tab.title, header: tab.header, content });
|
||||
} else {
|
||||
const pages = _helpBuildCategoryPages(tab, allCmds, prefix);
|
||||
paginator.addTab({ emoji: tab.emoji, title: tab.title, header: tab.header, pages });
|
||||
}
|
||||
}
|
||||
|
||||
paginator.send();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,583 @@
|
||||
/**
|
||||
* @module src/ui/MessageHandler
|
||||
* @description Central message/reaction plumbing: message-create events,
|
||||
* reaction observers, permission checks, and the reply/send/edit embed API
|
||||
* used by every command.
|
||||
*/
|
||||
|
||||
import { Client, Events, EmbedBuilder, PermissionFlags } from "@fluxerjs/core";
|
||||
import { logger } from "../core/Logger.mjs";
|
||||
import { Utils } from "../utils/Utils.mjs";
|
||||
import { Message, Channel } from "./Wrappers.mjs";
|
||||
import { getGlobalColor } from "./Embeds.mjs";
|
||||
import {
|
||||
REQUIRED_BOT_PERMISSIONS,
|
||||
CRITICAL_PERMISSIONS,
|
||||
OPTIONAL_PERMISSIONS,
|
||||
} from "./Permissions.mjs";
|
||||
|
||||
/**
|
||||
* @class MessageHandler
|
||||
* @description Handles message creation, reaction observation, permission
|
||||
* checking, and the shared reply/send/embed API.
|
||||
*/
|
||||
export class MessageHandler {
|
||||
/** @type {Client} */
|
||||
client;
|
||||
/** @type {Map<string, object>} Message ID → reaction observer data. */
|
||||
observedReactions;
|
||||
/** @type {Map<string, Array>} Channel ID → user message observer callbacks. */
|
||||
observedChannels;
|
||||
/** @type {object|null} Locale manager instance. */
|
||||
locale;
|
||||
|
||||
/**
|
||||
* @param {Client} client - The Fluxer client.
|
||||
*/
|
||||
constructor(client) {
|
||||
this.client = client;
|
||||
|
||||
this.observedReactions = new Map();
|
||||
this.observedChannels = new Map();
|
||||
|
||||
this.setupEvents();
|
||||
|
||||
this.client.on(Events.MessageCreate, (m) => {
|
||||
if (!this.observedChannels.has(m.channelId)) return;
|
||||
const data = this.observedChannels.get(m.channelId);
|
||||
const d = data.filter(e => e.id === m.author.id);
|
||||
if (d.length === 0) return;
|
||||
d.forEach(e => e.cb(new Message(m, this)));
|
||||
});
|
||||
}
|
||||
|
||||
/** @param {object} locale */
|
||||
setLocale(locale) { this.locale = locale; }
|
||||
|
||||
/**
|
||||
* Translate a locale key.
|
||||
* @param {string} guildId
|
||||
* @param {string} key
|
||||
* @param {object} [replacements={}]
|
||||
* @returns {string}
|
||||
*/
|
||||
t(guildId, key, replacements = {}) {
|
||||
if (!this.locale) return key;
|
||||
return this.locale.translate(guildId, key, replacements);
|
||||
}
|
||||
|
||||
/**
|
||||
* @private Register reaction add/remove event listeners.
|
||||
*/
|
||||
setupEvents() {
|
||||
const reactionUpdate = (payload) => {
|
||||
const { userId, messageId, emoji } = payload;
|
||||
const emojiId = emoji?.name ?? emoji?.id ?? emoji;
|
||||
const event = { user_id: userId, emoji_id: emojiId };
|
||||
|
||||
if (!this.observedReactions.has(messageId)) return;
|
||||
if (event.user_id === this.client.user?.id) return;
|
||||
const observer = this.observedReactions.get(messageId);
|
||||
if (!observer.reactions.includes(event.emoji_id)) return;
|
||||
if (observer.user && observer.user !== event.user_id) return;
|
||||
|
||||
const wrappedMsg = observer.msg ? new Message(observer.msg, this) : null;
|
||||
observer.cb(event, wrappedMsg);
|
||||
};
|
||||
this.client.on(Events.MessageReactionAdd, (payload) => reactionUpdate(payload));
|
||||
this.client.on(Events.MessageReactionRemove, (payload) => reactionUpdate(payload));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the permission keys the bot is missing in a channel.
|
||||
* @param {string[]} permissions
|
||||
* @param {object} channel
|
||||
* @returns {string[]}
|
||||
*/
|
||||
checkPermissions(permissions, channel) {
|
||||
if (!channel?.guild) return [];
|
||||
const me = channel.guild.members?.me ?? null;
|
||||
if (!me) {
|
||||
logger.warn("[MessageHandler] Cannot check permissions — guild.members.me is null");
|
||||
return [];
|
||||
}
|
||||
const perms = channel.permissionsFor?.(me) ?? null;
|
||||
if (!perms) {
|
||||
logger.warn("[MessageHandler] Cannot check permissions — channel.permissionsFor() unavailable");
|
||||
return [];
|
||||
}
|
||||
return permissions.filter(p => !perms.has(PermissionFlags[p] ?? p));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check all REQUIRED_BOT_PERMISSIONS and split into critical vs optional.
|
||||
* @param {object} channel
|
||||
* @returns {{missing: string[], criticalMissing: string[], optionalMissing: string[]}}
|
||||
*/
|
||||
checkAllBotPermissions(channel) {
|
||||
const allKeys = [...REQUIRED_BOT_PERMISSIONS.keys()];
|
||||
const missing = this.checkPermissions(allKeys, channel);
|
||||
return {
|
||||
missing,
|
||||
criticalMissing: missing.filter(p => CRITICAL_PERMISSIONS.includes(p)),
|
||||
optionalMissing: missing.filter(p => OPTIONAL_PERMISSIONS.includes(p)),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build an EmbedBuilder showing missing permissions.
|
||||
* @param {string[]} missingKeys
|
||||
* @param {string} guildId
|
||||
* @returns {EmbedBuilder}
|
||||
*/
|
||||
buildPermissionEmbed(missingKeys, guildId) {
|
||||
const criticalItems = [];
|
||||
const optionalItems = [];
|
||||
|
||||
for (const key of missingKeys) {
|
||||
const info = REQUIRED_BOT_PERMISSIONS.get(key);
|
||||
const isCritical = CRITICAL_PERMISSIONS.includes(key);
|
||||
const line = info
|
||||
? `**${info.name}** — ${info.desc}`
|
||||
: `**${key}**`;
|
||||
if (isCritical) {
|
||||
criticalItems.push("❌ " + line);
|
||||
} else {
|
||||
optionalItems.push("⚠️ " + line);
|
||||
}
|
||||
}
|
||||
|
||||
const embed = new EmbedBuilder().setColor(0xFF4444);
|
||||
|
||||
if (criticalItems.length > 0) {
|
||||
embed.setTitle(this.t(guildId, "responses.messages.missingCriticalPermsTitle"));
|
||||
embed.setDescription(
|
||||
this.t(guildId, "responses.messages.missingCriticalPermsDesc") + "\n\n" +
|
||||
criticalItems.join("\n")
|
||||
);
|
||||
} else if (optionalItems.length > 0) {
|
||||
embed.setTitle(this.t(guildId, "responses.messages.missingOptionalPermsTitle"));
|
||||
embed.setDescription(
|
||||
this.t(guildId, "responses.messages.missingOptionalPermsDesc") + "\n\n" +
|
||||
optionalItems.join("\n")
|
||||
);
|
||||
embed.setColor(0xFFA500);
|
||||
}
|
||||
|
||||
embed.setFooter({
|
||||
text: this.t(guildId, "responses.messages.permFooter")
|
||||
});
|
||||
|
||||
return embed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check permissions; send a DM or embed if missing.
|
||||
* @async
|
||||
* @param {string[]} permissions
|
||||
* @param {object} message
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
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 (e) { logger.warn("[MessageHandler] fetchMe failed:", e?.message); }
|
||||
}
|
||||
const missing = this.checkPermissions(permissions, message.channel ?? message.channel?.channel);
|
||||
if (missing.length === 0) return true;
|
||||
|
||||
if (missing.includes("SendMessages")) {
|
||||
try {
|
||||
const dm = await message.author.createDM();
|
||||
dm.send({
|
||||
embeds: [this.#embedify(this.t(message.guildId, "pagination.error.perms.messages", { channel: "<#" + message.channelId + ">" }))]
|
||||
});
|
||||
} catch (e) {
|
||||
logger.warn("[MessageHandler] Error sending message in DMs (" + message.author.id + "):", e.message);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
const permEmbed = this.buildPermissionEmbed(missing, message.guildId);
|
||||
try {
|
||||
await message.reply({ embeds: [permEmbed] }, { ping: false });
|
||||
} catch (e) {
|
||||
logger.warn("[MessageHandler] Failed to send permission embed:", e.message);
|
||||
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 (e) { logger.warn("[MessageHandler] Fallback permission reply failed:", e?.message); }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Register a listener for all incoming messages.
|
||||
* @param {Function} listener
|
||||
*/
|
||||
onMessage(listener) {
|
||||
this.client.on(Events.MessageCreate, (msg) => {
|
||||
listener(new Message(msg, this));
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a wrapped Message from cache by ID.
|
||||
* @param {string} id
|
||||
* @returns {Message|null}
|
||||
*/
|
||||
get(id) {
|
||||
for (const channel of this.client.channels.values()) {
|
||||
const msg = channel.messages?.get?.(id) ?? null;
|
||||
if (msg) return new Message(msg, this);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* @async Get a message from cache or fetch it from the API.
|
||||
* @param {string} id
|
||||
* @param {string} channelId
|
||||
* @returns {Promise<Message|null>}
|
||||
*/
|
||||
async getOrFetch(id, channelId) {
|
||||
const cached = this.get(id);
|
||||
if (cached) return cached;
|
||||
const channel = await this.client.channels.fetch(channelId).catch(() => null);
|
||||
if (!channel) return null;
|
||||
const raw = await channel.messages?.fetch?.(id);
|
||||
return raw ? new Message(raw, this) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a wrapped Channel by ID.
|
||||
* @param {string} id
|
||||
* @returns {Channel}
|
||||
*/
|
||||
getChannel(id) {
|
||||
const c = this.client.channels.get(id);
|
||||
return new Channel(c, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @async Get a channel from cache or fetch from the API.
|
||||
* @param {string} id
|
||||
* @returns {Promise<Channel>}
|
||||
*/
|
||||
async getOrFetchChannel(id) {
|
||||
const c = this.getChannel(id);
|
||||
if (c?.channel) return c;
|
||||
const raw = await this.client.channels.fetch(id).catch(() => undefined);
|
||||
return new Channel(raw, this);
|
||||
}
|
||||
|
||||
/**
|
||||
* Start observing reactions on a message.
|
||||
* @param {object} msg
|
||||
* @param {string[]} reactions
|
||||
* @param {Function} cb
|
||||
* @param {object} [user]
|
||||
* @returns {string} Observation ID.
|
||||
*/
|
||||
observeReactions(msg, reactions, cb, user) {
|
||||
this.observedReactions.set(msg.id, {
|
||||
reactions: reactions,
|
||||
user: (user) ? user.id : null,
|
||||
cb,
|
||||
msg,
|
||||
});
|
||||
return msg.id;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stop observing reactions.
|
||||
* @param {string} i - Observation ID.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
unobserveReactions(i) {
|
||||
return this.observedReactions.delete(i);
|
||||
}
|
||||
|
||||
/**
|
||||
* Observe messages from a specific user in a channel.
|
||||
* @param {string} userId
|
||||
* @param {object} channel
|
||||
* @param {Function} callback
|
||||
* @returns {string} Observation ID.
|
||||
*/
|
||||
observeUserMessagesChannel(userId, channel, callback) {
|
||||
const current = (this.observedChannels.get(channel.id) || []);
|
||||
const nonce = Utils.uid();
|
||||
current.push({
|
||||
id: userId,
|
||||
nonce: nonce,
|
||||
cb: callback
|
||||
});
|
||||
this.observedChannels.set(channel.id, current);
|
||||
return userId + ";" + channel.id + ";" + nonce;
|
||||
}
|
||||
|
||||
/**
|
||||
* @private Stop observing a user's messages in a channel.
|
||||
* @param {string} oid
|
||||
*/
|
||||
unobserveUserMessagesChannel(oid) {
|
||||
const [userId, channelId, nonce] = oid.split(";");
|
||||
const current = (this.observedChannels.get(channelId) || []);
|
||||
const idx = current.findIndex(e => e.id === userId && e.nonce === nonce);
|
||||
if (idx === -1) return;
|
||||
current.splice(idx, 1);
|
||||
if (current.length === 0) return this.observedChannels.delete(channelId);
|
||||
this.observedChannels.set(channelId, current);
|
||||
}
|
||||
|
||||
/**
|
||||
* @private Build an EmbedBuilder from text with optional title, thumbnail,
|
||||
* and author icon.
|
||||
* @param {string} [text=""]
|
||||
* @param {object} [options={}]
|
||||
* @param {string|number} [options.color]
|
||||
* @param {string} [options.title]
|
||||
* @param {string} [options.thumbnail]
|
||||
* @param {string} [options.icon_url]
|
||||
* @returns {EmbedBuilder}
|
||||
*/
|
||||
#embedify(text = "", options = {}) {
|
||||
const color = options.color ?? getGlobalColor();
|
||||
const builder = new EmbedBuilder()
|
||||
.setDescription("" + text)
|
||||
.setColor(color);
|
||||
|
||||
if (options.title) builder.setTitle(options.title);
|
||||
|
||||
if (options.thumbnail && Utils.isValidUrl(options.thumbnail)) {
|
||||
builder.setThumbnail(options.thumbnail);
|
||||
}
|
||||
|
||||
if (options.icon_url) {
|
||||
if (Utils.isValidUrl(options.icon_url)) {
|
||||
builder.setAuthor({ name: options.title || "\u200b", iconURL: options.icon_url });
|
||||
} else {
|
||||
builder.setAuthor({ name: options.title || "\u200b" });
|
||||
}
|
||||
}
|
||||
|
||||
return builder;
|
||||
}
|
||||
|
||||
/**
|
||||
* @private Create a message payload object with an embed.
|
||||
* @param {string} text
|
||||
* @param {object} [options={}]
|
||||
* @returns {{content: *, embeds: EmbedBuilder[]}}
|
||||
*/
|
||||
#createEmbed(text, options = {}) {
|
||||
return {
|
||||
content: options.content ?? undefined,
|
||||
embeds: [this.#embedify(text, options)],
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @async Reply to a message with permission checks.
|
||||
* @param {object} replyingTo
|
||||
* @param {string|object} message
|
||||
* @param {boolean} [mention=false]
|
||||
* @returns {Promise<Message|null>}
|
||||
*/
|
||||
async reply(replyingTo, message, mention = false) {
|
||||
if (!(await this.assertPermissions(["SendMessages", "EmbedLinks"], replyingTo))) return null;
|
||||
let opts;
|
||||
if (typeof message === "string") {
|
||||
opts = this.#createEmbed(message);
|
||||
} else {
|
||||
opts = { ...message };
|
||||
}
|
||||
return new Message(await replyingTo.reply(opts, { ping: false }), this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @async Reply with an embed.
|
||||
* @param {object} replyingTo
|
||||
* @param {string|object} message
|
||||
* @param {object} [options={}]
|
||||
* @returns {Promise<Message|null>}
|
||||
*/
|
||||
async replyEmbed(replyingTo, message, options = {}) {
|
||||
if (!(await this.assertPermissions(["SendMessages", "EmbedLinks"], replyingTo))) return null;
|
||||
|
||||
if (typeof message === "object" && Array.isArray(message.embeds)) {
|
||||
return new Message(await replyingTo.reply(message, { ping: false }), this);
|
||||
}
|
||||
|
||||
options = {
|
||||
mention: false,
|
||||
embed: {},
|
||||
...options
|
||||
};
|
||||
const content = (typeof message === "object") ? message.embedText : message;
|
||||
let payload = this.#createEmbed(content, options.embed);
|
||||
if (typeof message === "object") {
|
||||
const { embedText, ...rest } = message;
|
||||
payload = { ...payload, ...rest };
|
||||
}
|
||||
return new Message(await replyingTo.reply(payload, { ping: false }), this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @async Send a message to a channel.
|
||||
* @param {object} channel
|
||||
* @param {string|object} message
|
||||
* @returns {Promise<Message|null>}
|
||||
*/
|
||||
async sendMessage(channel, message) {
|
||||
if (this.checkPermissions(["SendMessages", "EmbedLinks"], channel).length !== 0) {
|
||||
logger.warn("[MessageHandler] Missing SendMessages/EmbedLinks permission in channel", channel.id);
|
||||
return null;
|
||||
}
|
||||
let opts;
|
||||
if (typeof message === "string") {
|
||||
opts = this.#createEmbed(message);
|
||||
} else {
|
||||
opts = message;
|
||||
}
|
||||
return new Message(await channel.send(opts), this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @async Send an embed to a channel.
|
||||
* @param {object} channel
|
||||
* @param {string|object} content
|
||||
* @param {object} [embedOptions={}]
|
||||
* @returns {Promise<Message|null>}
|
||||
*/
|
||||
async sendEmbed(channel, content, embedOptions = {}) {
|
||||
if (this.checkPermissions(["SendMessages", "EmbedLinks"], channel).length !== 0) {
|
||||
return this.sendMessage(channel, typeof content === "string" ? content : content?.embedText ?? "");
|
||||
}
|
||||
if (typeof content === "object" && Array.isArray(content.embeds)) {
|
||||
return new Message(await channel.send(content), this);
|
||||
}
|
||||
const text = (typeof content === "object") ? content.embedText : content;
|
||||
const payload = this.#createEmbed(text, embedOptions);
|
||||
if (typeof content === "object") {
|
||||
const { embedText, ...rest } = content;
|
||||
Object.assign(payload, rest);
|
||||
}
|
||||
return new Message(await channel.send(payload), this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @async Edit an existing message embed with retry on 502/503/504.
|
||||
* @param {object} message
|
||||
* @param {string|object} content
|
||||
* @param {object} [embedOptions={}]
|
||||
* @returns {Promise<Message|null>}
|
||||
*/
|
||||
async editEmbed(message, content, embedOptions = {}) {
|
||||
const RETRYABLE = new Set([502, 503, 504]);
|
||||
const MAX_ATTEMPTS = 3;
|
||||
const RETRY_DELAY_MS = 1500;
|
||||
|
||||
let payload;
|
||||
if (typeof content === "object" && Array.isArray(content.embeds)) {
|
||||
payload = content;
|
||||
} else {
|
||||
const text = (typeof content === "object") ? content.embedText : content;
|
||||
const embed = this.#embedify(text, embedOptions);
|
||||
payload = { embeds: [embed] };
|
||||
if (typeof content === "object") {
|
||||
const { embedText, ...rest } = content;
|
||||
payload = { ...payload, ...rest };
|
||||
}
|
||||
}
|
||||
|
||||
for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
|
||||
try {
|
||||
return new Message(await message.edit(payload), this);
|
||||
} catch (err) {
|
||||
if (err.code === "UNKNOWN_MESSAGE" || err.code === 10008) {
|
||||
logger.warn("[MessageHandler] editEmbed: Message no longer exists, skipping edit.");
|
||||
return null;
|
||||
}
|
||||
|
||||
if (RETRYABLE.has(err.statusCode) && attempt < MAX_ATTEMPTS) {
|
||||
logger.warn(`[MessageHandler] editEmbed: ${err.statusCode} on attempt ${attempt}/${MAX_ATTEMPTS}, retrying in ${RETRY_DELAY_MS}ms…`);
|
||||
await new Promise(r => setTimeout(r, RETRY_DELAY_MS));
|
||||
continue;
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @async Create a paginated message with arrow reactions.
|
||||
* @param {import('./Paginators.mjs').PageBuilder} builder
|
||||
* @param {Message} msg
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async initPagination(builder, msg) {
|
||||
const pages = builder.createPages();
|
||||
if (pages.length === 0) return;
|
||||
|
||||
const arrows = ["⬅️", "➡️"];
|
||||
const currPage = { n: 0 };
|
||||
const send = () => builder.getPage(currPage.n);
|
||||
|
||||
const m = await msg.reply(send());
|
||||
if (!m) return;
|
||||
|
||||
m.message.react(arrows[0]).catch(() => {});
|
||||
m.message.react(arrows[1]).catch(() => {});
|
||||
|
||||
const unobserve = m.onReaction(arrows, (e) => {
|
||||
if (e.emoji_id === arrows[0]) {
|
||||
currPage.n = Math.max(0, currPage.n - 1);
|
||||
} else {
|
||||
currPage.n = Math.min(pages.length - 1, currPage.n + 1);
|
||||
}
|
||||
m.edit(send()).catch(() => {});
|
||||
});
|
||||
|
||||
const guildId = msg.message?.guildId ?? null;
|
||||
setTimeout(() => {
|
||||
unobserve();
|
||||
m.edit(this.t(guildId, "pagination.embed.sclosedContent", { content: send() })).catch(() => {});
|
||||
}, 5 * 60 * 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* @async Join a voice channel using VoiceManager.
|
||||
* @param {string} channelId
|
||||
* @returns {Promise<object>}
|
||||
* @throws {Error} If channel not found or not a guild channel.
|
||||
*/
|
||||
async joinChannel(channelId) {
|
||||
const { getVoiceManager } = await import("@fluxerjs/voice");
|
||||
const channel = await this.client.channels.fetch(channelId).catch(() => null);
|
||||
if (!channel) throw new Error("Voice channel not found.");
|
||||
// Fluxer 3.0: isGuild() is ChannelType-based and replaces the 2.2
|
||||
// 'guildId' own-property duck check; the fallback keeps custom/stub
|
||||
// channel objects working.
|
||||
const isGuildChannel = channel.isGuild?.() ?? ("guildId" in channel);
|
||||
if (!isGuildChannel) throw new Error("Cannot join a non-guild voice channel.");
|
||||
const vm = getVoiceManager(this.client);
|
||||
if (!vm) throw new Error("VoiceManager not available.");
|
||||
const voiceConn = await vm.join(channel);
|
||||
// Self-deafen raw joins too (Player.join does this for playback
|
||||
// sessions): a music bot never listens, and Fluxer's VoiceManager resets
|
||||
// self_deaf on every requestVoiceStateSync (fired by conn.stop()) — the
|
||||
// re-assert listener keeps the deafened state for the connection's
|
||||
// lifetime. Best effort: updateVoiceState no-ops without connection_id.
|
||||
const deafen = () => {
|
||||
try {
|
||||
vm.updateVoiceState(channel.id, { self_deaf: true, self_mute: false });
|
||||
} catch (_) { /* best effort */ }
|
||||
};
|
||||
deafen();
|
||||
if (typeof voiceConn?.on === "function") voiceConn.on("requestVoiceStateSync", deafen);
|
||||
return voiceConn;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
/**
|
||||
* @module src/ui/Paginators
|
||||
* @description Pagination primitives: PageBuilder (line splitting with a
|
||||
* template form), RichPaginator (multi-tab embeds) and QueuePaginator
|
||||
* (two-arrow embed paging).
|
||||
*/
|
||||
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { logger } from "../core/Logger.mjs";
|
||||
import { Message } from "./Wrappers.mjs";
|
||||
import { getGlobalColor } from "./Embeds.mjs";
|
||||
|
||||
/**
|
||||
* @class PageBuilder
|
||||
* @description Splits content into pages with template-based formatting
|
||||
* ($maxPage / $currentPage / $content placeholders).
|
||||
*/
|
||||
export class PageBuilder {
|
||||
/** @type {string} Template form string. */
|
||||
form = "";
|
||||
/** @type {number} Maximum lines per page. */
|
||||
maxLinesPerPage = 2;
|
||||
/** @type {Array|string[]} Content lines or array items. */
|
||||
content = [];
|
||||
/** @type {boolean} Whether pages have been created. */
|
||||
initiated = false;
|
||||
/** @type {Array<Array>} Created page arrays. */
|
||||
pages = [];
|
||||
|
||||
/**
|
||||
* @param {string|Array} content - String to split by newlines or an array of items.
|
||||
*/
|
||||
constructor(content) {
|
||||
if (!Array.isArray(content)) {
|
||||
this.content = content.split("\n");
|
||||
return;
|
||||
}
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the template form string.
|
||||
* @param {string} form
|
||||
* @returns {PageBuilder}
|
||||
*/
|
||||
setForm(form) {
|
||||
this.form = form;
|
||||
this.initiated = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the maximum lines per page.
|
||||
* @param {number} [maxLinesPerPage=2]
|
||||
* @returns {PageBuilder}
|
||||
*/
|
||||
setMaxLines(maxLinesPerPage = 2) {
|
||||
this.maxLinesPerPage = maxLinesPerPage;
|
||||
this.initiated = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create page arrays from content. Lazily initialized.
|
||||
* @returns {Array<Array>}
|
||||
*/
|
||||
createPages() {
|
||||
if (this.initiated) return this.pages;
|
||||
|
||||
const lines = this.content;
|
||||
const pages = [];
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const n = Math.floor(i / this.maxLinesPerPage);
|
||||
if (!pages[n]) pages[n] = [];
|
||||
pages[n].push(lines[i]);
|
||||
}
|
||||
|
||||
this.pages = pages;
|
||||
this.initiated = true;
|
||||
return pages;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a formatted page string by index (0-based).
|
||||
* @param {number} n
|
||||
* @returns {string|null}
|
||||
*/
|
||||
getPage(n) {
|
||||
const pages = this.createPages();
|
||||
if (!pages[n]) return null;
|
||||
return this.form
|
||||
.replace(/\$maxPage/gi, pages.length)
|
||||
.replace(/\$currentPage/gi, n + 1)
|
||||
.replace(/\$currPage/gi, n + 1)
|
||||
.replace(/\$content/gi, pages[n].join("\n"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get raw page content by index (0-based) without template formatting.
|
||||
* @param {number} n
|
||||
* @returns {string|null}
|
||||
*/
|
||||
getContent(n) {
|
||||
const pages = this.createPages();
|
||||
if (!pages[n]) return null;
|
||||
return pages[n].join("\n");
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the total number of pages.
|
||||
* @returns {number}
|
||||
*/
|
||||
size() {
|
||||
return this.pages.length;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @class RichPaginator
|
||||
* @description Multi-tab paginated embed with tab and arrow navigation via
|
||||
* reactions. Closes the session after an inactivity timeout.
|
||||
*/
|
||||
export class RichPaginator {
|
||||
/**
|
||||
* @param {Message} msg
|
||||
* @param {import('./MessageHandler.mjs').MessageHandler} handler
|
||||
*/
|
||||
constructor(msg, handler) {
|
||||
this._msg = msg;
|
||||
this._handler = handler;
|
||||
this._tabs = [];
|
||||
this._prev = "⬅️";
|
||||
this._next = "➡️";
|
||||
this._timeout = 5 * 60 * 1000;
|
||||
this._color = getGlobalColor();
|
||||
this._state = { tab: 0, page: 0 };
|
||||
}
|
||||
|
||||
/** @param {number} ms @returns {RichPaginator} */
|
||||
setTimeout(ms) { this._timeout = ms; return this; }
|
||||
/** @param {number} color @returns {RichPaginator} */
|
||||
setColor(color) { this._color = color; return this; }
|
||||
/** @param {number} idx @returns {RichPaginator} */
|
||||
setStartTab(idx) { this._state.tab = idx; return this; }
|
||||
/** @param {string} prev @param {string} next @returns {RichPaginator} */
|
||||
setPrevNext(prev, next) { this._prev = prev; this._next = next; return this; }
|
||||
|
||||
/**
|
||||
* Add a tab to the paginator.
|
||||
* @param {object} tab
|
||||
* @param {string} tab.emoji
|
||||
* @param {string} tab.title
|
||||
* @param {string} tab.header
|
||||
* @param {string} [tab.content]
|
||||
* @param {string[]} [tab.pages]
|
||||
* @returns {RichPaginator}
|
||||
*/
|
||||
addTab(tab) {
|
||||
this._tabs.push({
|
||||
emoji: tab.emoji,
|
||||
title: tab.title,
|
||||
header: tab.header,
|
||||
pages: tab.pages ?? (tab.content != null ? [tab.content] : []),
|
||||
});
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* @private Build an embed for a given tab and sub-page.
|
||||
* @param {number} tabIdx
|
||||
* @param {number} pageIdx
|
||||
* @returns {EmbedBuilder}
|
||||
*/
|
||||
_buildEmbed(tabIdx, pageIdx) {
|
||||
const tab = this._tabs[tabIdx];
|
||||
const totalTabs = this._tabs.length;
|
||||
const totalPages = Math.max(1, tab.pages.length);
|
||||
const safePage = Math.max(0, Math.min(pageIdx, totalPages - 1));
|
||||
const content = tab.pages[safePage] ?? "";
|
||||
|
||||
const footerParts = [`Page ${tabIdx + 1}/${totalTabs}`];
|
||||
if (totalPages > 1) footerParts.push(`• Subpage ${safePage + 1}/${totalPages}`);
|
||||
|
||||
return new EmbedBuilder()
|
||||
.setColor(this._color)
|
||||
.setAuthor({ name: tab.header })
|
||||
.setTitle(tab.title)
|
||||
.setDescription(content)
|
||||
.setFooter({ text: footerParts.join(" ") });
|
||||
}
|
||||
|
||||
/**
|
||||
* @async Send the paginated embed and start observing reactions.
|
||||
* @returns {Promise<object|null>} The raw sent message.
|
||||
*/
|
||||
async send() {
|
||||
if (this._tabs.length === 0) return null;
|
||||
|
||||
const tabEmojis = this._tabs.map(t => t.emoji);
|
||||
const allReactions = [...tabEmojis, this._prev, this._next];
|
||||
|
||||
const nativeMsg = this._msg.message ?? this._msg;
|
||||
if (!nativeMsg?.reply) return null;
|
||||
|
||||
const rawMsg = await nativeMsg.reply(
|
||||
{ embeds: [this._buildEmbed(this._state.tab, this._state.page)] },
|
||||
{ ping: false }
|
||||
).catch(() => null);
|
||||
|
||||
if (!rawMsg) return null;
|
||||
|
||||
const guildId = (this._msg.channel?.guildId) ?? (this._msg.guildId) ?? null;
|
||||
|
||||
for (const emoji of allReactions) {
|
||||
await rawMsg.react(emoji).catch(() => {});
|
||||
}
|
||||
|
||||
const wrapped = new Message(rawMsg, this._handler);
|
||||
const state = this._state;
|
||||
const tabs = this._tabs;
|
||||
const prev = this._prev;
|
||||
const next = this._next;
|
||||
const buildEmbed = this._buildEmbed.bind(this);
|
||||
|
||||
const unobserve = wrapped.onReaction(allReactions, async (e) => {
|
||||
const emoji = e.emoji_id;
|
||||
|
||||
if (emoji === prev || emoji === next) {
|
||||
const tab = tabs[state.tab];
|
||||
const totalPages = Math.max(1, tab.pages.length);
|
||||
if (totalPages <= 1) return;
|
||||
state.page = emoji === prev
|
||||
? (state.page - 1 + totalPages) % totalPages
|
||||
: (state.page + 1) % totalPages;
|
||||
} else {
|
||||
const idx = tabEmojis.indexOf(emoji);
|
||||
if (idx === -1 || idx === state.tab) return;
|
||||
state.tab = idx;
|
||||
state.page = 0;
|
||||
}
|
||||
|
||||
rawMsg.edit({ embeds: [buildEmbed(state.tab, state.page)] }).catch(() => {});
|
||||
});
|
||||
|
||||
/** @private Clear all reactions on the paginator message. */
|
||||
const clearReactions = async () => {
|
||||
try {
|
||||
await rawMsg.removeAllReactions();
|
||||
return;
|
||||
} catch (e) {
|
||||
if (String(e?.message ?? e).includes("Message wasn't found") || e?.code === 10008) return;
|
||||
logger.warn("[RichPaginator] removeAllReactions failed:", e?.message ?? e);
|
||||
}
|
||||
for (const emoji of allReactions) {
|
||||
try {
|
||||
await rawMsg.removeReaction(emoji);
|
||||
} catch(e) {
|
||||
if (String(e?.message ?? e).includes("Message wasn't found") || e?.code === 10008) return;
|
||||
logger.warn("[MessageHandler] Error:", e?.message);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/** @private Close the pagination session, update footer, and clear reactions. */
|
||||
const closeSession = async () => {
|
||||
unobserve();
|
||||
const currentEmbed = buildEmbed(state.tab, state.page);
|
||||
if (!currentEmbed.footer) currentEmbed.footer = { text: "" };
|
||||
currentEmbed.footer.text += " • " + this._handler.t(guildId, "pagination.embed.sclosedTitle");
|
||||
rawMsg.edit({ embeds: [currentEmbed] }).catch(() => {});
|
||||
await clearReactions();
|
||||
};
|
||||
|
||||
let timer = setTimeout(closeSession, this._timeout);
|
||||
|
||||
/** @private Reset the inactivity timer. */
|
||||
const resetTimer = () => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(closeSession, this._timeout);
|
||||
};
|
||||
|
||||
const origHandler = wrapped.handler.observedReactions.get(rawMsg.id);
|
||||
if (origHandler) {
|
||||
const origCb = origHandler.cb;
|
||||
origHandler.cb = (e, m) => { resetTimer(); origCb(e, m); };
|
||||
}
|
||||
|
||||
return rawMsg;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @class QueuePaginator
|
||||
* @description Simple two-arrow paginator for queue embeds with page count.
|
||||
*/
|
||||
export class QueuePaginator {
|
||||
/**
|
||||
* @param {Message} msg
|
||||
* @param {import('./MessageHandler.mjs').MessageHandler} handler
|
||||
* @param {Client} client
|
||||
*/
|
||||
constructor(msg, handler, client) {
|
||||
this._msg = msg;
|
||||
this._handler = handler;
|
||||
this._client = client;
|
||||
this._timeout = 30 * 1000;
|
||||
this._prev = "⬅️";
|
||||
this._next = "➡️";
|
||||
}
|
||||
|
||||
/** @param {number} ms @returns {QueuePaginator} */
|
||||
setTimeout(ms) { this._timeout = ms; return this; }
|
||||
/** @param {string} prev @param {string} next @returns {QueuePaginator} */
|
||||
setPrevNext(prev, next) { this._prev = prev; this._next = next; return this; }
|
||||
|
||||
/**
|
||||
* @async Send the paginated embed and observe arrow reactions.
|
||||
* @param {Function} buildEmbed - Function that takes a 1-based page number and returns an EmbedBuilder.
|
||||
* @param {number} totalPages
|
||||
* @param {number} [startPage=1]
|
||||
* @returns {Promise<object|null>} The raw sent message.
|
||||
*/
|
||||
async send(buildEmbed, totalPages, startPage = 1) {
|
||||
const state = { page: Math.max(1, Math.min(startPage, totalPages)) };
|
||||
const nativeMsg = this._msg.message ?? this._msg;
|
||||
if (!nativeMsg?.reply) return null;
|
||||
const rawMsg = await nativeMsg.reply(
|
||||
{ embeds: [buildEmbed(state.page)] },
|
||||
{ ping: false }
|
||||
).catch(() => null);
|
||||
|
||||
if (!rawMsg) return null;
|
||||
|
||||
const guildId = (this._msg.channel?.guildId) ?? (this._msg.guildId) ?? null;
|
||||
|
||||
if (totalPages <= 1) return rawMsg;
|
||||
|
||||
const prev = this._prev;
|
||||
const next = this._next;
|
||||
|
||||
await rawMsg.react(prev).catch(() => {});
|
||||
await rawMsg.react(next).catch(() => {});
|
||||
|
||||
/** @private Clear all reactions on the paginator message. */
|
||||
const clearReactions = async () => {
|
||||
try {
|
||||
await rawMsg.removeAllReactions();
|
||||
} catch (e) {
|
||||
// Message deleted — nothing left to clean up.
|
||||
if (String(e?.message ?? e).includes("Message wasn't found") || e?.code === 10008) return;
|
||||
for (const emoji of [prev, next]) {
|
||||
try {
|
||||
await rawMsg.removeReaction(emoji);
|
||||
} catch(e) {
|
||||
if (String(e?.message ?? e).includes("Message wasn't found") || e?.code === 10008) return;
|
||||
logger.warn("[MessageHandler] Error:", e?.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
/** @private Close the pagination session, update footer, and clear reactions. */
|
||||
const closeSession = async () => {
|
||||
unobserve();
|
||||
const embed = buildEmbed(state.page);
|
||||
const closedLabel = this._handler.t(guildId, "pagination.embed.sclosedTitle");
|
||||
if (embed.footer && typeof embed.footer.text === "string") {
|
||||
embed.footer.text += " • " + closedLabel;
|
||||
} else {
|
||||
embed.footer = { text: closedLabel };
|
||||
}
|
||||
rawMsg.edit({ embeds: [embed] }).catch(() => {});
|
||||
await clearReactions();
|
||||
};
|
||||
|
||||
let timer = setTimeout(closeSession, this._timeout);
|
||||
/** @private Reset the inactivity timer. */
|
||||
const resetTimer = () => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(closeSession, this._timeout);
|
||||
};
|
||||
|
||||
const wrapped = new Message(rawMsg, this._handler);
|
||||
const unobserve = wrapped.onReaction([prev, next], (e) => {
|
||||
resetTimer();
|
||||
state.page = e.emoji_id === prev
|
||||
? (state.page <= 1 ? totalPages : state.page - 1)
|
||||
: (state.page >= totalPages ? 1 : state.page + 1);
|
||||
rawMsg.edit({ embeds: [buildEmbed(state.page)] }).catch(() => {});
|
||||
});
|
||||
|
||||
return rawMsg;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* @module src/ui/Permissions
|
||||
* @description Bot permission requirements for full functionality, split into
|
||||
* critical (bot cannot operate without) and optional (UX improvements).
|
||||
*/
|
||||
|
||||
/**
|
||||
* Required bot permissions with human-readable names and descriptions.
|
||||
* @type {Map<string, {name: string, desc: string}>}
|
||||
*/
|
||||
export const REQUIRED_BOT_PERMISSIONS = Object.freeze(new Map([
|
||||
["ViewChannel", { name: "View Channels", desc: "See channels and read their content" }],
|
||||
["SendMessages", { name: "Send Messages", desc: "Respond to commands and send messages" }],
|
||||
["EmbedLinks", { name: "Embed Links", desc: "Send rich embed messages (bot responses, now playing, etc.)" }],
|
||||
["AddReactions", { name: "Add Reactions", desc: "Add pagination reactions (help pages, queue, etc.)" }],
|
||||
["ReadMessageHistory", { name: "Read Message History", desc: "Read previous messages for context" }],
|
||||
["ManageMessages", { name: "Manage Messages", desc: "Pin messages, clean up bot responses" }],
|
||||
["AttachFiles", { name: "Attach Files", desc: "Send files and thumbnails" }],
|
||||
["Connect", { name: "Connect (Join Voice)", desc: "Join voice channels to play music" }],
|
||||
["Speak", { name: "Speak", desc: "Stream audio in voice channels" }],
|
||||
]));
|
||||
|
||||
/** @type {string[]} Permission keys that are strictly required for the bot to function. */
|
||||
export const CRITICAL_PERMISSIONS = ["ViewChannel", "SendMessages", "EmbedLinks", "Connect", "Speak"];
|
||||
|
||||
/** @type {string[]} Permission keys that are optional but improve the user experience. */
|
||||
export const OPTIONAL_PERMISSIONS = ["AddReactions", "ReadMessageHistory", "ManageMessages", "AttachFiles"];
|
||||
@@ -0,0 +1,191 @@
|
||||
/**
|
||||
* @module src/ui/Wrappers
|
||||
* @description Message and Channel wrappers providing reply/edit/reaction
|
||||
* observation helpers on top of the raw @fluxerjs/core objects.
|
||||
*/
|
||||
|
||||
/**
|
||||
* @class Channel
|
||||
* @description Wrapper around a raw channel object providing helpers for
|
||||
* sending messages and observing per-user messages.
|
||||
*/
|
||||
export class Channel {
|
||||
/** @type {object} The raw channel object. */
|
||||
channel;
|
||||
/** @type {import('./MessageHandler.mjs').MessageHandler} */
|
||||
handler;
|
||||
|
||||
/**
|
||||
* @param {object} channel
|
||||
* @param {import('./MessageHandler.mjs').MessageHandler} handler
|
||||
*/
|
||||
constructor(channel, handler) {
|
||||
this.channel = channel;
|
||||
this.handler = handler;
|
||||
}
|
||||
|
||||
/** @returns {object|null} The guild this channel belongs to. */
|
||||
get server() { return this.channel?.guild ?? null; }
|
||||
/** @returns {object|null} Alias for server (guild). */
|
||||
get guild() { return this.channel?.guild ?? null; }
|
||||
/** @returns {boolean} Whether this channel is a voice channel. */
|
||||
get isVoice() { return this.channel?.isVoiceBased?.() ?? false; }
|
||||
/** @returns {string} The channel ID. */
|
||||
get id() { return this.channel?.id; }
|
||||
/** @returns {string|null} The guild ID. */
|
||||
get guildId() { return this.channel?.guildId ?? null; }
|
||||
/** @returns {string|null} Alias for guildId. */
|
||||
get serverId() { return this.guildId; }
|
||||
|
||||
/**
|
||||
* Observe messages from a specific user in this channel.
|
||||
* @param {Function} callback
|
||||
* @param {object} user
|
||||
* @returns {Function} Unobserve function.
|
||||
*/
|
||||
onMessageUser(callback, user) {
|
||||
const resolvedUserId = user?.id
|
||||
?? user?._id
|
||||
?? user?.user?.id
|
||||
?? null;
|
||||
const resolvedChannel = this.channel ?? null;
|
||||
if (!resolvedUserId || !resolvedChannel?.id) {
|
||||
return () => {};
|
||||
}
|
||||
const oid = this.handler.observeUserMessagesChannel(resolvedUserId, resolvedChannel, callback);
|
||||
return () => {
|
||||
this.handler.unobserveUserMessagesChannel(oid);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a message to this channel.
|
||||
* @param {string|object} content
|
||||
* @returns {Promise<import('./Wrappers.mjs').Message|null>}
|
||||
*/
|
||||
sendMessage(content) {
|
||||
return this.handler.sendMessage(this.channel, content);
|
||||
}
|
||||
|
||||
/**
|
||||
* Alias for sendMessage.
|
||||
* @param {string|object} content
|
||||
* @returns {Promise<import('./Wrappers.mjs').Message|null>}
|
||||
*/
|
||||
send(content) {
|
||||
return this.handler.sendMessage(this.channel, content);
|
||||
}
|
||||
|
||||
/**
|
||||
* Send an embed to this channel.
|
||||
* @param {string|object} content
|
||||
* @param {object} [embedOptions={}]
|
||||
* @returns {Promise<import('./Wrappers.mjs').Message|null>}
|
||||
*/
|
||||
sendEmbed(content, embedOptions = {}) {
|
||||
return this.handler.sendEmbed(this.channel, content, embedOptions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Join this voice channel.
|
||||
* @async
|
||||
* @returns {Promise<object>}
|
||||
* @throws {Error} If not a voice channel.
|
||||
*/
|
||||
join() {
|
||||
if (!this.isVoice) throw new Error("Cannot join a text channel. Attempting to 'join' into channel `" + this.channel?.id + "`");
|
||||
return this.handler.joinChannel(this.channel.id);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @class Message
|
||||
* @description Wrapper around a raw message object providing helpers for
|
||||
* replying, editing, and reaction observation.
|
||||
*/
|
||||
export class Message {
|
||||
/** @type {object} */
|
||||
message;
|
||||
/** @type {import('./MessageHandler.mjs').MessageHandler} */
|
||||
handler;
|
||||
|
||||
/**
|
||||
* @param {object} message
|
||||
* @param {import('./MessageHandler.mjs').MessageHandler} handler
|
||||
*/
|
||||
constructor(message, handler) {
|
||||
this.message = message;
|
||||
this.handler = handler;
|
||||
}
|
||||
|
||||
/** @returns {string} The raw message content. */
|
||||
get content() { return this.message.content; }
|
||||
/** @returns {string} The message ID. */
|
||||
get id() { return this.message.id; }
|
||||
/** @returns {object} The author object. */
|
||||
get author() { return this.message.author; }
|
||||
/** @returns {string} The author's user ID. */
|
||||
get authorId() { return this.message.author?.id; }
|
||||
/** @returns {object|null} The guild member, if available. */
|
||||
get member() { return this.message.member ?? null; }
|
||||
/** @returns {Channel} The wrapped channel this message was sent in. */
|
||||
get channel() { return this.handler.getChannel(this.message.channelId); }
|
||||
|
||||
/**
|
||||
* Observe reactions on this message.
|
||||
* @param {string[]} reactions
|
||||
* @param {Function} callback
|
||||
* @param {object} [user=null] - Restrict observation to one user.
|
||||
* @returns {Function} Unobserve function.
|
||||
*/
|
||||
onReaction(reactions, callback, user = null) {
|
||||
const oid = this.handler.observeReactions(this.message, reactions, callback, user);
|
||||
return () => {
|
||||
this.handler.unobserveReactions(oid);
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Reply to this message.
|
||||
* @param {string|object} content
|
||||
* @param {boolean} [mention=false]
|
||||
* @returns {Promise<Message|null>}
|
||||
*/
|
||||
reply(content, mention = false) {
|
||||
return this.handler.reply(this.message, content, mention);
|
||||
}
|
||||
|
||||
/**
|
||||
* Reply to this message with an embed.
|
||||
* @param {string|object} content
|
||||
* @param {boolean} [mention=false]
|
||||
* @param {object} [embedOptions={}]
|
||||
* @returns {Promise<Message|null>}
|
||||
*/
|
||||
replyEmbed(content, mention = false, embedOptions = {}) {
|
||||
return this.handler.replyEmbed(this.message, content, {
|
||||
mention,
|
||||
embed: embedOptions
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Edit this message's embed.
|
||||
* @param {string|object} content
|
||||
* @param {object} [embedOptions={}]
|
||||
* @returns {Promise<Message|null>}
|
||||
*/
|
||||
editEmbed(content, embedOptions = {}) {
|
||||
return this.handler.editEmbed(this.message, content, embedOptions);
|
||||
}
|
||||
|
||||
/**
|
||||
* Alias for editEmbed.
|
||||
* @param {string|object} content
|
||||
* @param {object} [embedOptions={}]
|
||||
* @returns {Promise<Message|null>}
|
||||
*/
|
||||
edit(content, embedOptions = {}) {
|
||||
return this.handler.editEmbed(this.message, content, embedOptions);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* @module src/ui
|
||||
* @description Public surface of the message/embed UI layer.
|
||||
*
|
||||
* Import map from the old layout:
|
||||
* - `src/MessageHandler.mjs` → this module
|
||||
*/
|
||||
|
||||
export { REQUIRED_BOT_PERMISSIONS, CRITICAL_PERMISSIONS, OPTIONAL_PERMISSIONS } from "./Permissions.mjs";
|
||||
export { parseColor, setGlobalColor, getGlobalColor, getMessageGuildId } from "./Embeds.mjs";
|
||||
export { Message, Channel } from "./Wrappers.mjs";
|
||||
export { MessageHandler } from "./MessageHandler.mjs";
|
||||
export { PageBuilder, RichPaginator, QueuePaginator } from "./Paginators.mjs";
|
||||
export { HelpCommand } from "./HelpCommand.mjs";
|
||||
export { cleanId } from "../utils/Utils.mjs";
|
||||
@@ -0,0 +1,100 @@
|
||||
/** @module src/utils/API */
|
||||
|
||||
/**
|
||||
* FluxerList API configuration.
|
||||
* @namespace FLUXERLIST
|
||||
*/
|
||||
export const FLUXERLIST = {
|
||||
/** Base URL for the FluxerList REST API. @type {string} */
|
||||
BASE_URL: "https://fluxerlist.com/api/v1",
|
||||
|
||||
/** Public FluxerList website URL. @type {string} */
|
||||
SITE_URL: "https://fluxerlist.com",
|
||||
|
||||
/** API endpoint path templates. @type {{ SERVER_VOTERS: string, BOT_VOTERS: string }} */
|
||||
ENDPOINTS: {
|
||||
SERVER_VOTERS: "/servers/:id/voters",
|
||||
|
||||
BOT_VOTERS: "/bots/:id/voters",
|
||||
},
|
||||
|
||||
/** Accepted resource type identifiers. @type {string[]} */
|
||||
RESOURCE_TYPES: ["server", "bot"],
|
||||
|
||||
/** Thumbnail API base URL. @type {string} */
|
||||
THUMBNAIL: "https://fluxerlist.com/api/v1",
|
||||
};
|
||||
|
||||
/**
|
||||
* FluxerList authentication helpers.
|
||||
* @namespace FLUXERLIST_AUTH
|
||||
*/
|
||||
export const FLUXERLIST_AUTH = {
|
||||
/** HTTP header name for auth. @type {string} */
|
||||
HEADER: "Authorization",
|
||||
|
||||
/** Required API key prefix. @type {string} */
|
||||
KEY_PREFIX: "fl_",
|
||||
|
||||
/**
|
||||
* Format an API key as a Bearer token, prepending the prefix if needed.
|
||||
* @param {string} apiKey - Raw or prefixed API key.
|
||||
* @returns {string} `Bearer fl_...` string.
|
||||
*/
|
||||
bearer(apiKey) {
|
||||
const key = apiKey.startsWith(FLUXERLIST_AUTH.KEY_PREFIX)
|
||||
? apiKey
|
||||
: FLUXERLIST_AUTH.KEY_PREFIX + apiKey;
|
||||
return `Bearer ${key}`;
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* FluxerList pagination and cache limits.
|
||||
* @namespace FLUXERLIST_LIMITS
|
||||
*/
|
||||
export const FLUXERLIST_LIMITS = {
|
||||
/** Default page number. @type {number} */
|
||||
DEFAULT_PAGE: 1,
|
||||
|
||||
/** Default items-per-page. @type {number} */
|
||||
DEFAULT_LIMIT: 50,
|
||||
|
||||
/** Maximum allowed items-per-page. @type {number} */
|
||||
MAX_LIMIT: 100,
|
||||
|
||||
/** Cache time-to-live in milliseconds. @type {number} */
|
||||
CACHE_TTL_MS: 5 * 60 * 1000,
|
||||
};
|
||||
|
||||
/**
|
||||
* Build a full FluxerList API URL by substituting `:id` in the endpoint and appending query params.
|
||||
* @param {string} endpoint - Endpoint template (e.g. `"/servers/:id/voters"`).
|
||||
* @param {string} resourceId - Value to substitute for `:id`.
|
||||
* @param {{ page?: number, limit?: number }} [queryParams={}]
|
||||
* @returns {string} Fully qualified URL.
|
||||
*/
|
||||
export function buildFluxerListUrl(endpoint, resourceId, queryParams = {}) {
|
||||
const path = endpoint.replace(":id", encodeURIComponent(resourceId));
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (queryParams.page) params.set("page", String(queryParams.page));
|
||||
if (queryParams.limit) {
|
||||
const clamped = Math.min(Math.max(1, queryParams.limit), FLUXERLIST_LIMITS.MAX_LIMIT);
|
||||
params.set("limit", String(clamped));
|
||||
}
|
||||
|
||||
const qs = params.toString();
|
||||
return `${FLUXERLIST.BASE_URL}${path}${qs ? "?" + qs : ""}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a FluxerList vote link for a server or bot.
|
||||
* @param {"server"|"bot"} type - Resource type.
|
||||
* @param {string} resourceId - The server/bot ID.
|
||||
* @returns {string} Absolute URL to the vote page.
|
||||
*/
|
||||
export function buildVoteLink(type, resourceId) {
|
||||
const path = type === "server" ? "servers" : "bots";
|
||||
return `${FLUXERLIST.SITE_URL}/${path}/${resourceId}`;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/** @module src/utils/Helpers247 */
|
||||
|
||||
/**
|
||||
* Simplified 24/7 helpers — single mode (on/off), no per-channel modes.
|
||||
* get247ChannelMode is used by Player.mjs, PlayerManager.mjs, GatewayHandler.mjs, leave.mjs.
|
||||
* remove247ChannelMode and set247ChannelMode are kept as no-ops for backward compat
|
||||
* (original files in the zip still import them).
|
||||
*/
|
||||
|
||||
/**
|
||||
* Check if a channel has 24/7 enabled.
|
||||
* @param {object} set - ServerSettings instance
|
||||
* @param {string} channelId
|
||||
* @returns {"on"|"off"}
|
||||
*/
|
||||
export function get247ChannelMode(set, channelId) {
|
||||
if (!set?.get) return "off";
|
||||
const raw = set.get("stay_247");
|
||||
if (!raw || raw === "none") return "off";
|
||||
const channels = Array.isArray(raw)
|
||||
? raw.map(id => String(id).trim()).filter(Boolean)
|
||||
: [String(raw).trim()];
|
||||
return channels.includes(channelId) ? "on" : "off";
|
||||
}
|
||||
|
||||
/**
|
||||
* No-op: per-channel modes removed. Kept for backward compatibility.
|
||||
* Original GatewayHandler.mjs and index.mjs still import this.
|
||||
*/
|
||||
export function remove247ChannelMode(set, channelId, currentChannels) {
|
||||
// No-op: modes no longer exist, stay_247 array is managed directly.
|
||||
}
|
||||
|
||||
/**
|
||||
* No-op: per-channel modes removed. Kept for backward compatibility.
|
||||
*/
|
||||
export function set247ChannelMode(set, channelId, mode) {
|
||||
// No-op: modes no longer exist.
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* @module src/utils/ShardingUtils
|
||||
* @description Shard-aware gateway helpers that work identically on Fluxer.js
|
||||
* 2.2 (plain single process) and 3.0 (optionally sharded via
|
||||
* `@fluxerjs/sharding`).
|
||||
*
|
||||
* When the bot boots through the root `shard.mjs` supervisor, every child
|
||||
* process is forked by a {@link ShardingManager} with the
|
||||
* `FLUXER_SHARD_IDS` / `FLUXER_SHARD_COUNT` / `FLUXER_SHARD_PROCESS_ID` env
|
||||
* vars set, and `Bot.mjs` attaches the child-side `ShardClientUtil` as
|
||||
* `client.shard` before login. These helpers read that state to:
|
||||
* - route guild-scoped gateway payloads (opcode 4 voice joins/leaves) to
|
||||
* the shard that owns the guild,
|
||||
* - fan presence updates out to every gateway shard connected in this
|
||||
* process,
|
||||
* - enumerate the raw WebSocket socket of every local shard (2.2 exposed
|
||||
* a `ws.shards` Map property; 3.0 exposes `getShards()`/`getShard()`
|
||||
* methods and no property).
|
||||
*
|
||||
* In plain single-process mode (`npm start` / `node index.mjs`) every helper
|
||||
* degrades to the exact pre-sharding behavior — shard 0 and a one-element
|
||||
* shard list — so callers never need to know whether the bot is sharded.
|
||||
*/
|
||||
|
||||
/**
|
||||
* True when this process was forked by an `@fluxerjs/sharding`
|
||||
* ShardingManager (root `shard.mjs`). Detection requires both the manager
|
||||
* env var and a live IPC channel (`process.send`); manually exporting
|
||||
* FLUXER_* variables does not activate sharding.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isShardedProcess() {
|
||||
return process.env.FLUXER_SHARD_IDS !== undefined &&
|
||||
typeof process.send === "function";
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the gateway shard that owns a guild. Under a ShardingManager the
|
||||
* child-side `client.shard.shardIdForGuildId()` computes the assignment
|
||||
* (`(guild_id >> 22) % shard_count`, matching the gateway); otherwise the
|
||||
* bot runs a single gateway shard and the answer is always 0.
|
||||
* @param {object} client - The Fluxer client instance.
|
||||
* @param {string|number|null} guildId - The guild ID to route for.
|
||||
* @returns {number} The owning shard id (0 when not sharded).
|
||||
*/
|
||||
export function shardIdForGuild(client, guildId) {
|
||||
try {
|
||||
const shardUtil = client?.shard;
|
||||
if (shardUtil && typeof shardUtil.shardIdForGuildId === "function") {
|
||||
const id = shardUtil.shardIdForGuildId(String(guildId ?? ""));
|
||||
if (Number.isInteger(id) && id >= 0) return id;
|
||||
}
|
||||
} catch {
|
||||
// fall through to the single-process default
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the client's shard map in a 2.2- and 3.0-compatible way.
|
||||
* Fluxer 3.0 exposes `getShards()` on the WebSocketManager (the 2.2 `shards`
|
||||
* Map property is gone), and `client.ws` itself is a throwing getter before
|
||||
* login on 3.0, so every access here is guarded.
|
||||
* @param {object} client - The Fluxer client instance.
|
||||
* @returns {Array<Array<number, object>>} [id, shard] entries; empty when the
|
||||
* gateway is not connected yet or no shards are running in this process.
|
||||
*/
|
||||
export function getLocalShards(client) {
|
||||
try {
|
||||
const ws = client?.ws;
|
||||
if (!ws) return [];
|
||||
const map = typeof ws.getShards === "function" ? ws.getShards() : ws.shards;
|
||||
if (map && typeof map.entries === "function") {
|
||||
return [...map.entries()].filter(([id]) => Number.isInteger(id));
|
||||
}
|
||||
} catch {
|
||||
// Fluxer 3.0: client.ws throws before login — treat as "no shards yet".
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Ids of the gateway shards connected in this process. Defaults to `[0]`
|
||||
* (single-process behavior) when no shard map is available yet.
|
||||
* @param {object} client - The Fluxer client instance.
|
||||
* @returns {number[]}
|
||||
*/
|
||||
export function localShardIds(client) {
|
||||
const ids = getLocalShards(client).map(([id]) => id);
|
||||
return ids.length > 0 ? ids : [0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Raw WebSocket socket of every gateway shard connected in this process
|
||||
* (used by the raw-socket listeners in GatewayHandler and LavalinkManager).
|
||||
* 2.2-style code read `client.ws.shards.get(0).ws`; this generalises it to
|
||||
* all local shards for sharded children.
|
||||
* @param {object} client - The Fluxer client instance.
|
||||
* @returns {Array<object>} Raw socket objects (may be empty).
|
||||
*/
|
||||
export function localShardSockets(client) {
|
||||
const out = [];
|
||||
for (const [, shard] of getLocalShards(client)) {
|
||||
const wsObj = shard?.ws ?? null;
|
||||
if (wsObj) out.push(wsObj);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up a single shard handle by id, 2.2- and 3.0-compatible.
|
||||
* @param {object} client - The Fluxer client instance.
|
||||
* @param {number} [shardId=0] - The shard id to fetch.
|
||||
* @returns {object|null} The shard handle, or null when unavailable.
|
||||
*/
|
||||
export function getShard(client, shardId = 0) {
|
||||
try {
|
||||
const ws = client?.ws;
|
||||
if (!ws) return null;
|
||||
if (typeof ws.getShard === "function") return ws.getShard(shardId) ?? null;
|
||||
return ws.shards?.get?.(shardId) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One-line sharding description for startup logs.
|
||||
* @param {object} [client] - The Fluxer client instance (optional).
|
||||
* @returns {string} e.g. "process 2, gateway shards 4,5 of 8" or
|
||||
* "single process (unsharded)".
|
||||
*/
|
||||
export function describeSharding(client) {
|
||||
if (!isShardedProcess()) return "single process (unsharded)";
|
||||
const ids = String(process.env.FLUXER_SHARD_IDS ?? "0");
|
||||
const count = Number(process.env.FLUXER_SHARD_COUNT ?? "1") || 1;
|
||||
const pid = process.env.FLUXER_SHARD_PROCESS_ID ?? ids.split(",")[0] ?? "0";
|
||||
const live = localShardIds(client);
|
||||
return `process ${pid}, gateway shards ${ids} of ${count} (connected: ${live.join(", ")})`;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/** @module src/utils/UI */
|
||||
|
||||
/** Hex color string for error embeds. @type {string} */
|
||||
export const ERROR_COLOR = "#ff0000";
|
||||
|
||||
/** Numeric hex color for warning embeds. @type {number} */
|
||||
export const WARN_COLOR = 0xFFAA00;
|
||||
|
||||
/** Numeric hex color for success embeds. @type {number} */
|
||||
export const SUCCESS_COLOR = 0x00CC66;
|
||||
|
||||
/** Numeric hex color for danger/critical embeds. @type {number} */
|
||||
export const DANGER_COLOR = 0xFF4444;
|
||||
|
||||
/** Auto-remove reaction collectors after this many ms. @type {number} */
|
||||
export const EMOJI_REMOVE_TIMEOUT = 60_000;
|
||||
|
||||
/** Session idle timeout in ms. @type {number} */
|
||||
export const SESSION_TIMEOUT = 30_000;
|
||||
|
||||
/** Number emoji map for selection menus (indices 1-10). @type {string[]} */
|
||||
export const NUMBER_EMOJIS = [
|
||||
"1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣",
|
||||
"6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟",
|
||||
];
|
||||
|
||||
/** Emoji used to cancel a selection. @type {string} */
|
||||
export const CANCEL_EMOJI = "❌";
|
||||
|
||||
/** Emoji for previous-page navigation. @type {string} */
|
||||
export const PREV_EMOJI = "⬅️";
|
||||
|
||||
/** Emoji for next-page navigation. @type {string} */
|
||||
export const NEXT_EMOJI = "➡️";
|
||||
|
||||
/** Maximum allowed volume value. @type {number} */
|
||||
export const MAX_VOLUME = 200;
|
||||
@@ -1,7 +1,7 @@
|
||||
/** @module src/Utils @description General-purpose utility functions for formatting, validation, string manipulation, and ID cleaning. */
|
||||
/** @module src/utils/Utils @description General-purpose utility functions for formatting, validation, string manipulation, and ID cleaning. */
|
||||
|
||||
import { escapeMarkdown as _escapeMarkdown, truncate as _truncate } from "@fluxerjs/util";
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
import { logger } from "../core/Logger.mjs";
|
||||
|
||||
/**
|
||||
* Strip all non-digit characters from a value to extract a Snowflake/numeric ID.
|
||||
@@ -138,7 +138,7 @@ export class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape Discord markdown special characters in text.
|
||||
* Escape markdown special characters in text.
|
||||
* @param {string} text - The text to escape.
|
||||
* @returns {string} Escaped text, or empty string if falsy.
|
||||
*/
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* @module src/utils/mixins
|
||||
* @description Minimal mixin helper used to split large classes across
|
||||
* multiple files while keeping a single runtime class and public API.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copy the methods of each mixin onto the target class prototype.
|
||||
*
|
||||
* Use this when a class has grown across many concerns (playback, search,
|
||||
* display, …): define each concern as a plain object of methods in its own
|
||||
* module and apply them onto the class. All methods share the same `this`,
|
||||
* so behaviour is identical to a single-file class.
|
||||
*
|
||||
* Rules:
|
||||
* - Methods defined directly on the base class always win (never overridden).
|
||||
* - Later mixins override earlier mixins for the same method name.
|
||||
*
|
||||
* @param {Function} target - The base class to extend.
|
||||
* @param {...object} mixins - Objects of instance methods.
|
||||
* @returns {Function} The target class (for chaining).
|
||||
*/
|
||||
export function applyMixins(target, ...mixins) {
|
||||
const baseOwned = new Set(Object.getOwnPropertyNames(target.prototype));
|
||||
for (const mixin of mixins) {
|
||||
for (const [name, value] of Object.entries(mixin)) {
|
||||
if (typeof value !== "function") continue;
|
||||
if (baseOwned.has(name)) continue;
|
||||
target.prototype[name] = value;
|
||||
}
|
||||
}
|
||||
return target;
|
||||
}
|
||||
@@ -0,0 +1,589 @@
|
||||
/** @module src/voice/VoiceStateCache */
|
||||
|
||||
import { logger } from "../core/Logger.mjs";
|
||||
import { cleanId } from "../utils/Utils.mjs";
|
||||
|
||||
/**
|
||||
* LRU-backed cache mapping users (and bots) to their voice-channel locations.
|
||||
* Supports O(1) lookups by guild+user or guild+channel and implements the
|
||||
* Map-like interface (`get`, `set`, `delete`, `has`, `forEach`, `entries`, `keys`, `values`).
|
||||
* @class
|
||||
*/
|
||||
export class VoiceStateCache {
|
||||
/**
|
||||
* @param {object} [opts]
|
||||
* @param {number} [opts.maxUsers=50000] - Max cached human user entries.
|
||||
* @param {number} [opts.maxBots=10000] - Max cached bot user entries.
|
||||
*/
|
||||
constructor(opts = {}) {
|
||||
this.userLocations = new Map();
|
||||
this.channelMembers = new Map();
|
||||
|
||||
this.botLocations = new Map();
|
||||
this.botChannelMembers = new Map();
|
||||
|
||||
this._maxUsers = opts.maxUsers ?? 50_000;
|
||||
this._maxBots = opts.maxBots ?? 10_000;
|
||||
this._lruUserKeys = [];
|
||||
this._lruBotKeys = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a composite user key for storage.
|
||||
* @param {string} guildId
|
||||
* @param {string} userId
|
||||
* @returns {string}
|
||||
*/
|
||||
static userKey(guildId, userId) {
|
||||
return `${cleanId(guildId)}:${cleanId(userId)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a composite channel key for storage.
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
* @returns {string}
|
||||
*/
|
||||
static channelKey(guildId, channelId) {
|
||||
return `${cleanId(guildId)}:${cleanId(channelId)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Update (or remove) a user's voice-channel location in the cache.
|
||||
* When `channelId` is provided the user is added; when `null`/falsy the user is removed.
|
||||
* Automatically evicts LRU entries when capacity is exceeded.
|
||||
* @param {{ guildId: string, userId: string, channelId: string|null, isBot?: boolean }} opts
|
||||
*/
|
||||
updateUser({ guildId, userId, channelId, isBot = false }) {
|
||||
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;
|
||||
const channelIdx = isBot ? this.botChannelMembers : this.channelMembers;
|
||||
const maxEntries = isBot ? this._maxBots : this._maxUsers;
|
||||
const lruKeys = isBot ? this._lruBotKeys : this._lruUserKeys;
|
||||
const uKey = VoiceStateCache.userKey(cleanGuild, cleanUser);
|
||||
|
||||
const prev = locations.get(uKey);
|
||||
if (prev) {
|
||||
const prevCKey = VoiceStateCache.channelKey(prev.guildId, prev.channelId);
|
||||
const prevSet = channelIdx.get(prevCKey);
|
||||
if (prevSet) {
|
||||
prevSet.delete(cleanUser);
|
||||
if (prevSet.size === 0) channelIdx.delete(prevCKey);
|
||||
}
|
||||
}
|
||||
|
||||
if (cleanChannel) {
|
||||
const cKey = VoiceStateCache.channelKey(cleanGuild, cleanChannel);
|
||||
let set = channelIdx.get(cKey);
|
||||
if (!set) { set = new Set(); channelIdx.set(cKey, set); }
|
||||
set.add(cleanUser);
|
||||
|
||||
locations.delete(uKey);
|
||||
locations.set(uKey, { channelId: cleanChannel, guildId: cleanGuild, userId: cleanUser });
|
||||
|
||||
const lruIdx = lruKeys.indexOf(uKey);
|
||||
if (lruIdx !== -1) lruKeys.splice(lruIdx, 1);
|
||||
lruKeys.push(uKey);
|
||||
|
||||
while (locations.size > maxEntries) {
|
||||
let evicted = false;
|
||||
for (let i = 0; i < lruKeys.length; i++) {
|
||||
const evictKey = lruKeys[i];
|
||||
if (evictKey === uKey) continue;
|
||||
|
||||
const evictEntry = locations.get(evictKey);
|
||||
if (evictEntry) {
|
||||
const evictCKey = VoiceStateCache.channelKey(evictEntry.guildId, evictEntry.channelId);
|
||||
const evictSet = channelIdx.get(evictCKey);
|
||||
if (evictSet) {
|
||||
evictSet.delete(evictEntry.userId);
|
||||
if (evictSet.size === 0) channelIdx.delete(evictCKey);
|
||||
}
|
||||
locations.delete(evictKey);
|
||||
}
|
||||
lruKeys.splice(i, 1);
|
||||
evicted = true;
|
||||
break;
|
||||
}
|
||||
if (!evicted) break;
|
||||
}
|
||||
} else {
|
||||
locations.delete(uKey);
|
||||
const idx = lruKeys.indexOf(uKey);
|
||||
if (idx !== -1) lruKeys.splice(idx, 1);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether any human users are cached in the given channel.
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
* @returns {boolean}
|
||||
*/
|
||||
hasHumansInChannel(guildId, channelId) {
|
||||
const cKey = VoiceStateCache.channelKey(guildId, channelId);
|
||||
const set = this.channelMembers.get(cKey);
|
||||
return set ? set.size > 0 : false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the count of human users cached in the given channel.
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
* @returns {number}
|
||||
*/
|
||||
getHumanCount(guildId, channelId) {
|
||||
const cKey = VoiceStateCache.channelKey(guildId, channelId);
|
||||
const set = this.channelMembers.get(cKey);
|
||||
return set ? set.size : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the array of human user IDs cached in the given channel.
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
* @returns {string[]}
|
||||
*/
|
||||
getHumansInChannel(guildId, channelId) {
|
||||
const cKey = VoiceStateCache.channelKey(guildId, channelId);
|
||||
const set = this.channelMembers.get(cKey);
|
||||
return set ? [...set] : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the channel ID a human user is currently in, or `null`.
|
||||
* @param {string} guildId
|
||||
* @param {string} userId
|
||||
* @returns {string|null}
|
||||
*/
|
||||
getUserChannel(guildId, userId) {
|
||||
const uKey = VoiceStateCache.userKey(guildId, userId);
|
||||
const loc = this.userLocations.get(uKey);
|
||||
return loc ? loc.channelId : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a human user exists in the cache for the given guild.
|
||||
* @param {string} guildId
|
||||
* @param {string} userId
|
||||
* @returns {boolean}
|
||||
*/
|
||||
hasUser(guildId, userId) {
|
||||
return this.userLocations.has(VoiceStateCache.userKey(guildId, userId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the full location record for a human user.
|
||||
* @param {string} guildId
|
||||
* @param {string} userId
|
||||
* @returns {{ channelId: string, guildId: string, userId: string }|undefined}
|
||||
*/
|
||||
getUserLocation(guildId, userId) {
|
||||
return this.userLocations.get(VoiceStateCache.userKey(guildId, userId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Seed a user into the cache only if not already present.
|
||||
* @param {string} guildId
|
||||
* @param {string} userId
|
||||
* @param {string} channelId
|
||||
* @param {boolean} [isBot=false]
|
||||
*/
|
||||
seedUser(guildId, userId, channelId, isBot = false) {
|
||||
const uKey = VoiceStateCache.userKey(guildId, userId);
|
||||
const locations = isBot ? this.botLocations : this.userLocations;
|
||||
if (locations.has(uKey)) return;
|
||||
this.updateUser({ guildId, userId, channelId, isBot });
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all cached entries (human and bot) for a given guild.
|
||||
* @param {string} guildId
|
||||
*/
|
||||
removeGuild(guildId) {
|
||||
const cleanGuild = cleanId(guildId);
|
||||
const prefix = cleanGuild + ":";
|
||||
|
||||
|
||||
const userKeysToRemove = [];
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
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);
|
||||
}
|
||||
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)) 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);
|
||||
}
|
||||
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));
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all cached entries (human and bot) for a specific channel.
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
*/
|
||||
removeChannel(guildId, channelId) {
|
||||
const cKey = VoiceStateCache.channelKey(guildId, channelId);
|
||||
|
||||
const humanSet = this.channelMembers.get(cKey);
|
||||
if (humanSet) {
|
||||
for (const userId of humanSet) {
|
||||
const uKey = VoiceStateCache.userKey(guildId, userId);
|
||||
const loc = this.userLocations.get(uKey);
|
||||
if (loc && loc.channelId === cleanId(channelId)) {
|
||||
this.userLocations.delete(uKey);
|
||||
}
|
||||
}
|
||||
this.channelMembers.delete(cKey);
|
||||
}
|
||||
|
||||
const botSet = this.botChannelMembers.get(cKey);
|
||||
if (botSet) {
|
||||
for (const userId of botSet) {
|
||||
const uKey = VoiceStateCache.userKey(guildId, userId);
|
||||
const loc = this.botLocations.get(uKey);
|
||||
if (loc && loc.channelId === cleanId(channelId)) {
|
||||
this.botLocations.delete(uKey);
|
||||
}
|
||||
}
|
||||
this.botChannelMembers.delete(cKey);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove specific users from a guild's cache.
|
||||
* @param {string} guildId
|
||||
* @param {string[]} userIds
|
||||
* @param {boolean} [botsOnly=false] - If `true`, only purge bot entries.
|
||||
*/
|
||||
purgeUsersInGuild(guildId, userIds, botsOnly = false) {
|
||||
const cleanGuild = cleanId(guildId);
|
||||
|
||||
if (!botsOnly) {
|
||||
for (const userId of userIds) {
|
||||
const uKey = VoiceStateCache.userKey(cleanGuild, userId);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const userId of userIds) {
|
||||
const uKey = VoiceStateCache.userKey(cleanGuild, userId);
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Number of cached human users.
|
||||
* @type {number}
|
||||
*/
|
||||
get observedVoiceUsersSize() { return this.userLocations.size; }
|
||||
|
||||
/**
|
||||
* Number of cached bot users.
|
||||
* @type {number}
|
||||
*/
|
||||
get observedVoiceBotsSize() { return this.botLocations.size; }
|
||||
|
||||
/**
|
||||
* Iterate over all cached human user entries as `[userId, { channelId, guildId }]` pairs.
|
||||
* @yields {[string, { channelId: string, guildId: string }]}
|
||||
*/
|
||||
*iterateHumanUsers() {
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
yield [loc.userId, { channelId: loc.channelId, guildId: loc.guildId }];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate over all cached bot user entries as `[compositeKey, { channelId, guildId }]` pairs.
|
||||
* @yields {[string, { channelId: string, guildId: string }]}
|
||||
*/
|
||||
*iterateBotUsers() {
|
||||
for (const [uKey, loc] of this.botLocations) {
|
||||
yield [uKey, { channelId: loc.channelId, guildId: loc.guildId }];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the location record for a human user. If `guildId` is omitted, performs a linear scan.
|
||||
* @param {string} userId
|
||||
* @param {string|null} [guildId]
|
||||
* @returns {{ channelId: string, guildId: string }|undefined}
|
||||
*/
|
||||
getHumanUser(userId, guildId = null) {
|
||||
if (guildId) {
|
||||
return this.userLocations.get(VoiceStateCache.userKey(guildId, userId));
|
||||
}
|
||||
const cleanUser = cleanId(userId);
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
if (loc.userId === cleanUser) return { channelId: loc.channelId, guildId: loc.guildId };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a human user's voice location via `updateUser`.
|
||||
* @param {string} userId
|
||||
* @param {{ guildId: string, channelId: string }} info
|
||||
*/
|
||||
setHumanUser(userId, info) {
|
||||
const guildId = info.guildId;
|
||||
const channelId = info.channelId;
|
||||
if (guildId && channelId) {
|
||||
this.updateUser({ guildId, userId, channelId, isBot: false });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a bot user's voice location via `updateUser`.
|
||||
* @param {string} compositeKey - `guildId:userId` composite key.
|
||||
* @param {{ guildId: string, channelId: string }} info
|
||||
*/
|
||||
setBotUser(compositeKey, info) {
|
||||
const guildId = info.guildId;
|
||||
const channelId = info.channelId;
|
||||
const userId = compositeKey.split(":").pop();
|
||||
if (guildId && channelId && userId) {
|
||||
this.updateUser({ guildId, userId, channelId, isBot: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a human user from the cache. If `guildId` is omitted, scans all entries.
|
||||
* @param {string} userId
|
||||
* @param {string|null} [guildId]
|
||||
*/
|
||||
deleteHumanUser(userId, guildId = null) {
|
||||
if (guildId) {
|
||||
this.updateUser({ guildId, userId, channelId: null, isBot: false });
|
||||
} else {
|
||||
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 });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a bot user from the cache by its composite key.
|
||||
* @param {string} compositeKey - `guildId:userId` composite key.
|
||||
*/
|
||||
deleteBotUser(compositeKey) {
|
||||
const parts = compositeKey.split(":");
|
||||
const guildId = parts[0];
|
||||
const userId = parts[1];
|
||||
if (guildId && userId) {
|
||||
this.updateUser({ guildId, userId, channelId: null, isBot: true });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a human user exists in the cache. If `guildId` is omitted, scans all entries.
|
||||
* @param {string} userId
|
||||
* @param {string|null} [guildId]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
hasHumanUser(userId, guildId = null) {
|
||||
if (guildId) {
|
||||
return this.userLocations.has(VoiceStateCache.userKey(guildId, userId));
|
||||
}
|
||||
const cleanUser = cleanId(userId);
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
if (loc.userId === cleanUser) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a bot user exists in the cache by composite key.
|
||||
* @param {string} compositeKey - `guildId:userId` composite key.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
hasBotUser(compositeKey) {
|
||||
return this.botLocations.has(compositeKey);
|
||||
}
|
||||
|
||||
/**
|
||||
* Implement the iterable protocol over human user entries.
|
||||
* @yields {[string, { channelId: string, guildId: string }]}
|
||||
*/
|
||||
*[Symbol.iterator]() {
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
yield [loc.userId, { channelId: loc.channelId, guildId: loc.guildId }];
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Number of cached human users (Map-like `.size`).
|
||||
* @type {number}
|
||||
*/
|
||||
get size() { return this.userLocations.size; }
|
||||
|
||||
/**
|
||||
* Map-like `has` — checks if a human user is cached.
|
||||
* @param {string} userId
|
||||
* @param {string} [guildId]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
has(userId, guildId) {
|
||||
if (guildId !== undefined) {
|
||||
return this.userLocations.has(VoiceStateCache.userKey(guildId, userId));
|
||||
}
|
||||
const cleanUser = cleanId(userId);
|
||||
for (const [, loc] of this.userLocations) {
|
||||
if (loc.userId === cleanUser) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map-like `get` — retrieve a human user's location.
|
||||
* @param {string} userId
|
||||
* @param {string} [guildId]
|
||||
* @returns {{ channelId: string, guildId: string }|undefined}
|
||||
*/
|
||||
get(userId, guildId) {
|
||||
if (guildId !== undefined) {
|
||||
const loc = this.userLocations.get(VoiceStateCache.userKey(guildId, userId));
|
||||
return loc ? { channelId: loc.channelId, guildId: loc.guildId } : undefined;
|
||||
}
|
||||
const cleanUser = cleanId(userId);
|
||||
for (const [, loc] of this.userLocations) {
|
||||
if (loc.userId === cleanUser) return { channelId: loc.channelId, guildId: loc.guildId };
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map-like `set` — upsert a human user's location.
|
||||
* @param {string} userId
|
||||
* @param {{ guildId: string, channelId: string }} info
|
||||
*/
|
||||
set(userId, info) {
|
||||
const guildId = info?.guildId;
|
||||
const channelId = info?.channelId;
|
||||
if (guildId && channelId) {
|
||||
this.updateUser({ guildId, userId, channelId, isBot: false });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Map-like `delete` — remove a human user. If `guildId` is omitted, removes all matching entries.
|
||||
* @param {string} userId
|
||||
* @param {string} [guildId]
|
||||
*/
|
||||
delete(userId, guildId) {
|
||||
if (guildId !== undefined) {
|
||||
this.updateUser({ guildId, userId, channelId: null, isBot: false });
|
||||
} else {
|
||||
const cleanUser = cleanId(userId);
|
||||
const toRemove = [];
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
if (loc.userId === cleanUser) toRemove.push(loc);
|
||||
}
|
||||
for (const loc of toRemove) {
|
||||
this.updateUser({ guildId: loc.guildId, userId: cleanUser, channelId: null, isBot: false });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Map-like `forEach` — iterate over human user entries.
|
||||
* @param {function(string, { channelId: string, guildId: string }, VoiceStateCache): void} fn
|
||||
*/
|
||||
forEach(fn) {
|
||||
for (const [userId, info] of this) {
|
||||
fn(userId, info, this);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Map-like `entries` iterator.
|
||||
* @yields {[string, { channelId: string, guildId: string }]}
|
||||
*/
|
||||
*entries() {
|
||||
yield* this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Map-like `keys` iterator.
|
||||
* @yields {string}
|
||||
*/
|
||||
*keys() {
|
||||
for (const [userId] of this) {
|
||||
yield userId;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Map-like `values` iterator.
|
||||
* @yields {{ channelId: string, guildId: string }}
|
||||
*/
|
||||
*values() {
|
||||
for (const [, info] of this) {
|
||||
yield info;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Diagnostic statistics for the cache.
|
||||
* @type {{ humanUsers: number, botUsers: number, humanChannels: number, botChannels: number, lruUserKeysLen: number, lruBotKeysLen: number }}
|
||||
*/
|
||||
get stats() {
|
||||
return {
|
||||
humanUsers: this.userLocations.size,
|
||||
botUsers: this.botLocations.size,
|
||||
humanChannels: this.channelMembers.size,
|
||||
botChannels: this.botChannelMembers.size,
|
||||
lruUserKeysLen: this._lruUserKeys.length,
|
||||
lruBotKeysLen: this._lruBotKeys.length,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
/** @module src/voice/VoiceStateResolver */
|
||||
|
||||
import { logger } from "../core/Logger.mjs";
|
||||
|
||||
/**
|
||||
* Iterate over a guild's voice states, normalising different data shapes.
|
||||
* Yields objects with `{ userId, channelId, isBot }` for each member in a voice channel.
|
||||
* @param {object} guild - guild object with a `voice_states` property.
|
||||
* @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 any non-bot humans are currently in a voice channel.
|
||||
* Checks, in order: VoiceStateCache → ObservedVoiceUsers → guild voice_states → LiveKit participants.
|
||||
* @param {object} opts
|
||||
* @param {string} opts.guildId
|
||||
* @param {string} opts.channelId
|
||||
* @param {object} [opts.client] - client with `guilds`.
|
||||
* @param {VoiceStateCache} [opts.voiceCache]
|
||||
* @param {Map} [opts.observedVoiceUsers]
|
||||
* @param {object} [opts.room] - LiveKit room with `remoteParticipants`.
|
||||
* @param {string} [opts.botId]
|
||||
* @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 the set of channel IDs that contain at least one human user.
|
||||
* @param {object} guild - guild object.
|
||||
* @returns {Set<string>}
|
||||
*/
|
||||
export function getChannelsWithHumans(guild) {
|
||||
const channels = new Set();
|
||||
for (const vs of iterateVoiceStates(guild)) {
|
||||
if (!vs.isBot) channels.add(vs.channelId);
|
||||
}
|
||||
return channels;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the list of user IDs present in a specific voice channel.
|
||||
* @param {object} guild - guild object.
|
||||
* @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;
|
||||
}
|
||||
@@ -0,0 +1,602 @@
|
||||
/**
|
||||
* @module src/voice/gateway/GatewayHandler
|
||||
* @description Handles all gateway events relevant to voice state
|
||||
* tracking, 24/7 mode, boot recovery, presence rotation, and permission
|
||||
* checks. Base class file: constructor & state, raw WS listener, presence
|
||||
* rotation, event registration, READY sequencing and 24/7 boot recovery.
|
||||
* Voice-state routing, guild sync and rejoin management live in sibling
|
||||
* mixin modules applied onto the prototype at the bottom of this file.
|
||||
*/
|
||||
import { Events, GatewayOpcodes } from "@fluxerjs/core";
|
||||
import { logger, _wsErrorCooldown } from "../../core/Logger.mjs";
|
||||
import { ServerSettings } from "../../db/Settings.mjs";
|
||||
import { get247ChannelMode, remove247ChannelMode } from "../../utils/Helpers247.mjs";
|
||||
import { cleanId } from "../../utils/Utils.mjs";
|
||||
import * as ShardingUtils from "../../utils/ShardingUtils.mjs";
|
||||
import { iterateVoiceStates, hasHumansInChannel, getChannelsWithHumans } from "../VoiceStateResolver.mjs";
|
||||
import { applyMixins } from "../../utils/mixins.mjs";
|
||||
import VoiceStateRouting from "./VoiceStateRouting.mjs";
|
||||
import GuildSync from "./GuildSync.mjs";
|
||||
import RejoinManager from "./RejoinManager.mjs";
|
||||
|
||||
const RAW_GATEWAY_INTEREST =
|
||||
/"(?:t|op)":\s*(?:"(?:VOICE_STATE_UPDATE|VOICE_SERVER_UPDATE|GUILD_CREATE|READY|RESUMED)"|(?:7|9|10|12)\b)/;
|
||||
|
||||
/** @class GatewayHandler @description Handles all gateway events relevant to voice state tracking, 24/7 mode, boot recovery, presence rotation, and permission checks. Key responsibilities include voice state cache seeding and updates, bot move-away detection with 24/7 rejoin scheduling, boot recovery with sequential rejoin of 24/7 channels, inactivity timer management on human join/leave, and guild create/delete handling with startup grace period. */
|
||||
class GatewayHandler {
|
||||
/**
|
||||
* Create a new GatewayHandler.
|
||||
* @param {import('../../core/Bot.mjs').Remix} remix - The bot context.
|
||||
*/
|
||||
constructor(remix) {
|
||||
this.remix = remix;
|
||||
|
||||
const timers = remix.config.timers ?? {};
|
||||
this.T = {
|
||||
aloneCheckDebounce: timers.aloneCheckDebounce ?? 500,
|
||||
rejoin247Delay: timers.rejoin247Delay ?? 3_000,
|
||||
};
|
||||
|
||||
this.presenceContents = remix.config.presenceContents ?? [];
|
||||
this.presenceInterval = remix.config.presenceInterval ?? 30_000;
|
||||
|
||||
this.wsListenerAttached = false;
|
||||
this.presenceTimer = null;
|
||||
this.presenceIndex = 0;
|
||||
|
||||
this._prevVoiceState = new Map();
|
||||
|
||||
this._deferredGuildDeletes = new Map();
|
||||
this._startupDeleteGraceMs = 15_000;
|
||||
this._inStartupGrace = true;
|
||||
this._deferredDeleteCount = 0;
|
||||
|
||||
this._lastReadyAt = 0;
|
||||
this._wsReconnectGraceMs = 30_000;
|
||||
this._moveEvidenceWindowMs = 10_000;
|
||||
}
|
||||
|
||||
/** @private @type {Set<string>} @description Channel IDs currently being rejoined (duplicate guard). */
|
||||
_rejoinInProgress = new Set();
|
||||
|
||||
/** @private @type {Map<string, number>} @description Channel ID → retry count for exponential backoff. */
|
||||
_rejoinAttempts = new Map();
|
||||
|
||||
/** @private @type {boolean} @description Whether boot recovery is actively rejoining 24/7 channels. */
|
||||
_bootRecoveryActive = false;
|
||||
|
||||
/** @type {number} @description Maximum number of rejoin retry attempts per channel. */
|
||||
static MAX_REJOIN_RETRIES = 3;
|
||||
|
||||
/**
|
||||
* Check whether a WebSocket reconnect happened recently (within 30s).
|
||||
* Used to treat transient disconnects as non-24/7-requiring.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isWsReconnectRecent() {
|
||||
if (!this._lastReadyAt) return false;
|
||||
return Date.now() - this._lastReadyAt < this._wsReconnectGraceMs;
|
||||
}
|
||||
|
||||
/** @private Build a composite bot key for voice state tracking. @param {string} userId @param {string} guildId @returns {string|null} */
|
||||
getObservedVoiceBotKey(userId, guildId) {
|
||||
const cleanUserId = cleanId(userId ?? "");
|
||||
const cleanGuildId = cleanId(guildId ?? "");
|
||||
return cleanUserId && cleanGuildId ? `${cleanGuildId}:${cleanUserId}` : cleanUserId || null;
|
||||
}
|
||||
|
||||
/** @private Build a previous voice state lookup key. @param {string} userId @param {string} guildId @returns {string|null} */
|
||||
getPrevVoiceStateKey(userId, guildId) {
|
||||
const cleanUserId = cleanId(userId ?? "");
|
||||
const cleanGuildId = cleanId(guildId ?? "");
|
||||
return cleanUserId && cleanGuildId ? `${cleanGuildId}:${cleanUserId}` : null;
|
||||
}
|
||||
|
||||
/** Find a previous voice state entry for a user. @param {string} userId @param {string|null} [guildId=null] @returns {{key: string|null, value: object|null}} */
|
||||
findPrevVoiceStateEntry(userId, guildId = null) {
|
||||
const directKey = this.getPrevVoiceStateKey(userId, guildId);
|
||||
if (directKey && this._prevVoiceState.has(directKey)) {
|
||||
return { key: directKey, value: this._prevVoiceState.get(directKey) };
|
||||
}
|
||||
|
||||
const cleanUserId = cleanId(userId ?? "");
|
||||
if (!cleanUserId) return { key: null, value: null };
|
||||
|
||||
for (const [key, value] of this._prevVoiceState) {
|
||||
if (key.endsWith(`:${cleanUserId}`)) {
|
||||
return { key, value };
|
||||
}
|
||||
}
|
||||
|
||||
return { key: null, value: null };
|
||||
}
|
||||
|
||||
/** Attach a raw WebSocket listener to cache VOICE_SERVER_UPDATE events. @private */
|
||||
attachRawListener() {
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
|
||||
try {
|
||||
// Fluxer 3.0 + sharding: the ws manager exposes shards via getShards()
|
||||
// (2.2 used a `shards` Map property) and a sharded child owns several
|
||||
// shards — track the raw socket of EVERY local shard, not just shard 0.
|
||||
const wsObjs = ShardingUtils.localShardSockets(client);
|
||||
|
||||
if (!remix._rawGatewayWsObjs) remix._rawGatewayWsObjs = new Set();
|
||||
const attached = remix._rawGatewayWsObjs;
|
||||
|
||||
// Detach listeners from sockets that went away (reconnects).
|
||||
for (const old of attached) {
|
||||
if (wsObjs.includes(old)) continue;
|
||||
try {
|
||||
if (typeof old.removeEventListener === "function") {
|
||||
old.removeEventListener("message", remix._rawGatewayMessageListener ?? remix._rawGatewayHandler);
|
||||
old.removeEventListener("error", remix._rawGatewayErrorHandler);
|
||||
} else if (typeof old.off === "function") {
|
||||
old.off("message", remix._rawGatewayMessageListener ?? remix._rawGatewayHandler);
|
||||
old.off("error", remix._rawGatewayErrorHandler);
|
||||
}
|
||||
} catch(e) { logger.warn("[Gateway] Failed to detach old WS listener:", e?.message); }
|
||||
attached.delete(old);
|
||||
}
|
||||
|
||||
let attachedNew = false;
|
||||
|
||||
// Create the shared raw-socket handlers once (stateless parsers
|
||||
// shared by every local shard socket).
|
||||
if (!remix._rawGatewayHandler) {
|
||||
remix._rawGatewayHandler = (data) => {
|
||||
try {
|
||||
if (typeof data === "string" && !RAW_GATEWAY_INTEREST.test(data)) return;
|
||||
const payload = typeof data === "string" ? JSON.parse(data) : data;
|
||||
|
||||
if (payload?.op === GatewayOpcodes.GatewayError || payload?.op === 12) {
|
||||
logger.warn("[Gateway] GatewayError (12) received from Fluxer:", payload.d);
|
||||
}
|
||||
|
||||
if (payload?.op === GatewayOpcodes.Hello || payload?.op === 10) {
|
||||
logger.player(`[Gateway] HELLO received (heartbeat ${payload.d?.heartbeat_interval ?? "unknown"}ms)`);
|
||||
}
|
||||
if (payload?.op === GatewayOpcodes.Reconnect || payload?.op === 7) {
|
||||
logger.warn("[Gateway] RECONNECT requested by gateway.");
|
||||
}
|
||||
if (payload?.op === GatewayOpcodes.InvalidSession || payload?.op === 9) {
|
||||
logger.warn("[Gateway] INVALID_SESSION received from gateway.");
|
||||
}
|
||||
|
||||
if (payload?.op !== 0) return;
|
||||
|
||||
if (payload.t === "READY") {
|
||||
logger.player(`[Gateway] READY received (session ${payload.d?.session_id ?? "unknown"})`);
|
||||
const readyGuilds = payload.d?.guilds;
|
||||
if (Array.isArray(readyGuilds)) {
|
||||
for (const g of readyGuilds) {
|
||||
const gId = g?.id;
|
||||
if (!gId || !Array.isArray(g.voice_states)) continue;
|
||||
for (const state of g.voice_states) {
|
||||
const userId = state.user_id;
|
||||
const channelId = state.channel_id;
|
||||
if (!userId || !channelId) continue;
|
||||
const isBot = state.member?.user?.bot ?? false;
|
||||
remix.voiceCache.updateUser({ guildId: gId, userId, channelId, isBot });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (payload.t === "RESUMED") {
|
||||
logger.player("[Gateway] RESUMED received from gateway.");
|
||||
}
|
||||
|
||||
if (payload.t === "GUILD_CREATE") {
|
||||
const d = payload.d;
|
||||
const gId = d?.id;
|
||||
const voiceStates = d?.voice_states;
|
||||
if (gId && Array.isArray(voiceStates) && voiceStates.length > 0) {
|
||||
for (const state of voiceStates) {
|
||||
const userId = state.user_id;
|
||||
const channelId = state.channel_id;
|
||||
if (!userId || !channelId) continue;
|
||||
const isBot = state.member?.user?.bot ?? false;
|
||||
remix.voiceCache.updateUser({ guildId: gId, userId, channelId, isBot });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (payload.t === "VOICE_SERVER_UPDATE") {
|
||||
logger.voiceState(`[Gateway] VOICE_SERVER_UPDATE guild=${payload.d?.guild_id ?? "dm"} endpoint=${payload.d?.endpoint ?? "unknown"}`);
|
||||
}
|
||||
|
||||
if (payload.t === "VOICE_STATE_UPDATE") {
|
||||
const d = payload.d;
|
||||
const userId = d?.user_id;
|
||||
const channelId = d?.channel_id ?? null;
|
||||
const guildId = d?.guild_id;
|
||||
const isBot = d?.member?.user?.bot ?? false;
|
||||
if (!userId) return;
|
||||
if (channelId) {
|
||||
remix.voiceCache.updateUser({ guildId, userId, channelId, isBot });
|
||||
} else {
|
||||
remix.voiceCache.updateUser({ guildId, userId, channelId: null, isBot });
|
||||
}
|
||||
}
|
||||
} catch(e) { logger.warn("[Gateway] Raw gateway handler error:", e?.message); }
|
||||
};
|
||||
|
||||
remix._rawGatewayErrorHandler = (errOrEvent) => {
|
||||
if (typeof errOrEvent?.preventDefault === "function") errOrEvent.preventDefault();
|
||||
const err = errOrEvent?.error ?? errOrEvent?.message ?? errOrEvent;
|
||||
const now = Date.now();
|
||||
if (now - _wsErrorCooldown.lastLogged < _wsErrorCooldown.COOLDOWN_MS) return;
|
||||
_wsErrorCooldown.lastLogged = now;
|
||||
logger.warn("[Gateway] Raw WS socket error (will reconnect):", err?.message ?? err);
|
||||
};
|
||||
remix._rawGatewayMessageListener = (event) => remix._rawGatewayHandler(event?.data ?? event);
|
||||
}
|
||||
|
||||
for (const wsObj of wsObjs) {
|
||||
if (attached.has(wsObj)) continue;
|
||||
|
||||
if (typeof wsObj.addEventListener === "function") {
|
||||
wsObj.addEventListener("message", remix._rawGatewayMessageListener);
|
||||
wsObj.addEventListener("error", remix._rawGatewayErrorHandler);
|
||||
} else if (typeof wsObj.on === "function") {
|
||||
wsObj.on("message", remix._rawGatewayMessageListener);
|
||||
wsObj.on("error", remix._rawGatewayErrorHandler);
|
||||
}
|
||||
|
||||
attached.add(wsObj);
|
||||
attachedNew = true;
|
||||
}
|
||||
|
||||
// Legacy singular field kept in sync (first socket) for compatibility.
|
||||
remix._rawGatewayWsObj = wsObjs[0] ?? null;
|
||||
this.wsListenerAttached = attached.size > 0;
|
||||
if (attachedNew) {
|
||||
logger.player("[Gateway] Raw WS listener attached to new socket.");
|
||||
}
|
||||
} catch(e) { logger.warn("[Gateway] attachRawListener failed:", e?.message); }
|
||||
}
|
||||
|
||||
/** Rotate the bot's presence/status text at a configured interval. @private */
|
||||
setupPresenceRotation() {
|
||||
if (this.presenceContents.length === 0) return;
|
||||
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
|
||||
const setPresence = () => {
|
||||
const entry = this.presenceContents[this.presenceIndex];
|
||||
|
||||
const isObj = typeof entry === "object" && entry !== null;
|
||||
|
||||
const custom_status = {};
|
||||
if (isObj) {
|
||||
if (entry.text) custom_status.text = entry.text;
|
||||
if (entry.emoji_name) custom_status.emoji_name = entry.emoji_name;
|
||||
if (entry.emoji_id) custom_status.emoji_id = entry.emoji_id;
|
||||
} else {
|
||||
custom_status.text = String(entry);
|
||||
}
|
||||
|
||||
const presence = {
|
||||
status: "online",
|
||||
mobile: false,
|
||||
afk: false,
|
||||
custom_status,
|
||||
};
|
||||
|
||||
if (isObj && entry.activity) {
|
||||
presence.activities = [{
|
||||
name: entry.activity.name ?? "music",
|
||||
type: entry.activity.type ?? 0,
|
||||
url: entry.activity.url ?? undefined,
|
||||
}];
|
||||
}
|
||||
|
||||
// Fluxer 3.0: client.ws is a throwing getter when the gateway is not
|
||||
// connected (2.2 exposed a plain optional). The raw opcode-3 payload
|
||||
// below stays in wire format (custom_status) because it bypasses
|
||||
// ClientUser.setPresence() and hits the shard directly.
|
||||
// Sharded children fan the update out to every gateway shard in this
|
||||
// process (presence is per shard); single process = shard 0 as before.
|
||||
try {
|
||||
if (client.ws?.send) {
|
||||
for (const id of ShardingUtils.localShardIds(client)) {
|
||||
client.ws.send(id, { op: GatewayOpcodes.PresenceUpdate, d: presence });
|
||||
}
|
||||
} else {
|
||||
const shard = ShardingUtils.getShard(client, 0);
|
||||
if (shard) shard.send({ op: GatewayOpcodes.PresenceUpdate, d: presence });
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[Presence] Gateway not ready, skipping rotation update:", e?.message);
|
||||
}
|
||||
this.presenceIndex = (this.presenceIndex + 1) % this.presenceContents.length;
|
||||
};
|
||||
setPresence();
|
||||
if (this.presenceTimer) clearInterval(this.presenceTimer);
|
||||
this.presenceTimer = setInterval(setPresence, this.presenceInterval);
|
||||
}
|
||||
|
||||
/**
|
||||
* Register all gateway event handlers (GuildCreate, GuildDelete, VoiceStateUpdate, VoiceStatesSync).
|
||||
* Called once during bot initialisation.
|
||||
*/
|
||||
setupEventHandlers() {
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
|
||||
client.on(Events.GuildCreate, async (guild) => {
|
||||
const guildId = guild?.id ?? guild?._id;
|
||||
if (!guildId) return;
|
||||
|
||||
const deferred = this._deferredGuildDeletes.get(guildId);
|
||||
if (deferred) {
|
||||
clearTimeout(deferred.timer);
|
||||
this._deferredGuildDeletes.delete(guildId);
|
||||
logger.guild(
|
||||
`[GuildDelete] Cancelled deferred cleanup for server ${guildId} — ` +
|
||||
`guild came back (GuildCreate received during grace period).`
|
||||
);
|
||||
}
|
||||
|
||||
const voiceStatesRaw =
|
||||
guild.voice_states ??
|
||||
guild.voiceStates ??
|
||||
null;
|
||||
|
||||
if (voiceStatesRaw) {
|
||||
const newUserIds = new Set();
|
||||
for (const vs of iterateVoiceStates(guild)) {
|
||||
newUserIds.add(vs.userId);
|
||||
}
|
||||
remix.voiceCache.purgeUsersInGuild(guildId, newUserIds);
|
||||
}
|
||||
if (voiceStatesRaw) {
|
||||
for (const vs of iterateVoiceStates(guild)) {
|
||||
remix.voiceCache.updateUser({ guildId, userId: vs.userId, channelId: vs.channelId, isBot: vs.isBot });
|
||||
}
|
||||
}
|
||||
|
||||
if (!remix.settingsMgr.guilds.has(guildId)) {
|
||||
logger.guild(`[GuildCreate] (Re-)joined server ${guildId} — initialising settings.`);
|
||||
try {
|
||||
const cleanGuildId = cleanId(guildId);
|
||||
if (!cleanGuildId) throw new Error("Invalid guildId: " + guildId);
|
||||
const res = await remix.settingsMgr.selectGuild(cleanGuildId);
|
||||
if (res?.results?.length) {
|
||||
const row = res.results[0];
|
||||
const server = new ServerSettings(guildId, remix.settingsMgr);
|
||||
const parsed = (typeof row.data === "string") ? JSON.parse(row.data) : row.data;
|
||||
server.deserialize(parsed);
|
||||
server.checkDefaults(remix.settingsMgr.defaults);
|
||||
remix.settingsMgr.guilds.set(guildId, server);
|
||||
logger.guild(`[GuildCreate] Restored existing settings for server ${guildId}.`);
|
||||
} else {
|
||||
const server = new ServerSettings(guildId, remix.settingsMgr);
|
||||
server.checkDefaults(remix.settingsMgr.defaults);
|
||||
remix.settingsMgr.guilds.set(guildId, server);
|
||||
await remix.settingsMgr.create(guildId, server);
|
||||
logger.guild(`[GuildCreate] Fresh settings initialised for server ${guildId}.`);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn("[GuildCreate] Settings init failed for", guildId, err.message);
|
||||
}
|
||||
}
|
||||
|
||||
this._checkGuildPermissions(guild, guildId).catch(e => logger.warn("[GuildCreate] Permission check error for", guildId, e.message));
|
||||
|
||||
});
|
||||
|
||||
client.on(Events.GuildDelete, (guild) => {
|
||||
const guildId = guild?.id ?? guild?._id;
|
||||
if (!guildId) return;
|
||||
|
||||
if (this._inStartupGrace) {
|
||||
this._deferredDeleteCount++;
|
||||
if (this._deferredDeleteCount <= 3) {
|
||||
logger.guild(
|
||||
`[GuildDelete] Deferring cleanup for server ${guildId} ` +
|
||||
`(startup grace — will confirm after ${this._startupDeleteGraceMs / 1000}s).`
|
||||
);
|
||||
}
|
||||
const existing = this._deferredGuildDeletes.get(guildId);
|
||||
if (existing) clearTimeout(existing.timer);
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
this._deferredGuildDeletes.delete(guildId);
|
||||
this._processGuildDelete(guildId);
|
||||
}, this._startupDeleteGraceMs);
|
||||
|
||||
this._deferredGuildDeletes.set(guildId, { guild, timer });
|
||||
return;
|
||||
}
|
||||
|
||||
logger.guild(`[GuildDelete] Received GuildDelete for server ${guildId}.`);
|
||||
this._processGuildDelete(guildId);
|
||||
});
|
||||
|
||||
client.on(Events.VoiceStateUpdate, async (data) => {
|
||||
this._handleVoiceStateUpdate(data);
|
||||
});
|
||||
|
||||
client.on(Events.VoiceStatesSync, (data) => {
|
||||
this._handleVoiceStatesSync(data);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Called when the bot receives the READY event.
|
||||
* Seeds voice states, starts presence rotation, ends startup grace period,
|
||||
* and begins 24/7 boot recovery.
|
||||
*/
|
||||
onReady() {
|
||||
this._lastReadyAt = Date.now();
|
||||
this.seedVoiceStatesFromGuilds();
|
||||
this.seedGuildsFromRest().catch(e => logger.warn("[onReady] seedGuildsFromRest error:", e.message));
|
||||
this.attachRawListener();
|
||||
|
||||
this.setupPresenceRotation();
|
||||
|
||||
setTimeout(() => {
|
||||
this._inStartupGrace = false;
|
||||
const pending = this._deferredGuildDeletes.size;
|
||||
if (pending > 0) {
|
||||
logger.guild(
|
||||
`[GuildDelete] Startup grace period ended. ` +
|
||||
`${pending} deferred deletion(s) confirmed — cleaning up.`
|
||||
);
|
||||
} else {
|
||||
logger.guild(`[GuildDelete] Startup grace period ended. No deferred deletions.`);
|
||||
}
|
||||
if (this._deferredDeleteCount > 3) {
|
||||
logger.guild(
|
||||
`[GuildDelete] (Suppressed ${this._deferredDeleteCount - 3} deferral log lines for brevity)`
|
||||
);
|
||||
}
|
||||
}, this._startupDeleteGraceMs);
|
||||
|
||||
this.rejoin247Channels();
|
||||
}
|
||||
|
||||
/**
|
||||
* Boot recovery: sequentially rejoin all saved 24/7 channels.
|
||||
* Sets _bootRecoveryActive=true to suppress fake move events during the process.
|
||||
* Cleans up missing channels from settings to prevent repeated failures.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async rejoin247Channels() {
|
||||
this._bootRecoveryActive = true;
|
||||
try {
|
||||
await this._rejoin247ChannelsInner();
|
||||
} catch (err) {
|
||||
logger.warn("[BootRecovery] 24/7 boot recovery crashed:", err?.message ?? err);
|
||||
} finally {
|
||||
this._bootRecoveryActive = false;
|
||||
}
|
||||
}
|
||||
|
||||
/** @private Inner boot-recovery loop. The flag reset is handled by the caller's finally block. */
|
||||
async _rejoin247ChannelsInner() {
|
||||
const { remix } = this;
|
||||
const channelsToRejoin = [];
|
||||
|
||||
for (const [guildId, serverSettings] of remix.settingsMgr.guilds) {
|
||||
const raw = serverSettings.get("stay_247");
|
||||
if (!raw || raw === "none") continue;
|
||||
|
||||
const rawArr = Array.isArray(raw) ? raw : [raw];
|
||||
const channels = rawArr
|
||||
.map(id => cleanId(id))
|
||||
.filter(id => id.length >= 15 && id.length <= 22);
|
||||
|
||||
for (const channelId of channels) {
|
||||
const mode = get247ChannelMode(serverSettings, channelId);
|
||||
if (mode === "on") {
|
||||
channelsToRejoin.push({ guildId, channelId, mode });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (channelsToRejoin.length === 0) {
|
||||
logger.voice247("[BootRecovery] No 24/7 channels to rejoin.");
|
||||
return;
|
||||
}
|
||||
|
||||
logger.voice247(
|
||||
`[BootRecovery] Found ${channelsToRejoin.length} 24/7 channel(s) to rejoin: ` +
|
||||
channelsToRejoin.map(c => `${c.channelId}(${c.mode})`).join(", ")
|
||||
);
|
||||
|
||||
const baseStagger = remix.config?.timers?.bootRejoinStagger ?? 5_000;
|
||||
|
||||
for (let i = 0; i < channelsToRejoin.length; i++) {
|
||||
const { guildId, channelId, mode } = channelsToRejoin[i];
|
||||
|
||||
if (i > 0) {
|
||||
let staggerDelay = baseStagger;
|
||||
if (i >= 8) staggerDelay = baseStagger * 2;
|
||||
else if (i >= 4) staggerDelay = Math.round(baseStagger * 1.5);
|
||||
logger.voice247(`[BootRecovery] Waiting ${staggerDelay / 1000}s before rejoining next channel...`);
|
||||
await new Promise(resolve => setTimeout(resolve, staggerDelay));
|
||||
}
|
||||
|
||||
const existing = remix.players.playerMap.get(channelId);
|
||||
if (existing && !existing._destroyed) {
|
||||
logger.voice247(`[BootRecovery] Channel ${channelId} already has a player — skipping.`);
|
||||
continue;
|
||||
}
|
||||
if (remix.players._pendingJoins?.has?.(channelId)) {
|
||||
logger.voice247(`[BootRecovery] Channel ${channelId} already has a pending join — skipping.`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const channelObj = remix.client?.channels?.get?.(channelId);
|
||||
if (!channelObj) {
|
||||
logger.warn(
|
||||
`[BootRecovery] Channel ${channelId} in guild ${guildId} no longer exists — ` +
|
||||
`removing from 24/7 settings to prevent repeated failures.`
|
||||
);
|
||||
try {
|
||||
const set = remix.settingsMgr.getServer(guildId);
|
||||
if (set) {
|
||||
const raw = set.get("stay_247");
|
||||
const arr = Array.isArray(raw) ? raw : raw ? [raw] : [];
|
||||
const filtered = arr.filter(id => id && id !== "none" && cleanId(id) !== channelId);
|
||||
const remainingSet = new Set(filtered.map(id => cleanId(id)));
|
||||
remove247ChannelMode(set, channelId, remainingSet);
|
||||
set.set("stay_247", filtered.length > 0 ? filtered : "none");
|
||||
}
|
||||
} catch (cleanupErr) {
|
||||
logger.warn(`[BootRecovery] Failed to auto-remove missing channel ${channelId} from 24/7:`, cleanupErr?.message);
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (channelObj.type !== 2) {
|
||||
logger.warn(
|
||||
`[BootRecovery] Channel ${channelId} in guild ${guildId} is not a voice channel (type: ${channelObj.type}) — skipping.`
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
const guildHasActivePlayer = [...remix.players.playerMap.values()]
|
||||
.some(p => !p._destroyed && cleanId(p._guildId ?? "") === guildId);
|
||||
if (guildHasActivePlayer && i > 0) {
|
||||
const extraDelay = 3_000;
|
||||
logger.voice247(
|
||||
`[BootRecovery] Guild ${guildId} already has an active player — ` +
|
||||
`waiting extra ${extraDelay / 1000}s to avoid move-disconnect.`
|
||||
);
|
||||
await new Promise(resolve => setTimeout(resolve, extraDelay));
|
||||
}
|
||||
|
||||
logger.voice247(
|
||||
`[BootRecovery] Rejoining channel ${channelId} in guild ${guildId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]`
|
||||
);
|
||||
|
||||
const player = await this._attemptRejoin(channelId, guildId, 3, 5_000, "BootRecovery");
|
||||
|
||||
if (player) {
|
||||
logger.voice247(
|
||||
`[BootRecovery] Successfully rejoined channel ${channelId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]`
|
||||
);
|
||||
} else {
|
||||
logger.warn(
|
||||
`[BootRecovery] Failed to rejoin channel ${channelId} in guild ${guildId} after retries — ` +
|
||||
`keeping 24/7 setting intact, will retry on next disconnect/restart.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
logger.voice247(
|
||||
`[BootRecovery] Boot recovery complete. ${channelsToRejoin.length} channel(s) processed.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Attach the split-out concerns: voice-state routing (VoiceStateRouting),
|
||||
// guild sync & seeding (GuildSync), and 24/7 rejoin management (RejoinManager).
|
||||
applyMixins(GatewayHandler, VoiceStateRouting, GuildSync, RejoinManager);
|
||||
|
||||
export { GatewayHandler };
|
||||
@@ -0,0 +1,391 @@
|
||||
/**
|
||||
* @module src/voice/gateway/GuildSync
|
||||
* @description Guild synchronisation concern for {@link GatewayHandler}:
|
||||
* bot permission checks on guild create, voice-state cache seeding
|
||||
* (VoiceManager, guild cache, VoiceStateCache, LiveKit participants), REST
|
||||
* guild-cache stubbing for guilds without GUILD_CREATE, and confirmed
|
||||
* guild-delete cleanup.
|
||||
*
|
||||
* These methods are applied onto the GatewayHandler class prototype via
|
||||
* {@link applyMixins} — `this` is a GatewayHandler instance.
|
||||
*/
|
||||
|
||||
import { getVoiceManager } from "@fluxerjs/voice";
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
import { REQUIRED_BOT_PERMISSIONS } from "../../ui/index.mjs";
|
||||
import { cleanId } from "../../utils/Utils.mjs";
|
||||
import { iterateVoiceStates } from "../VoiceStateResolver.mjs";
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
* @description Guild sync mixin — applied to GatewayHandler.
|
||||
*/
|
||||
const GuildSync = {
|
||||
/**
|
||||
* Check and warn about missing bot permissions in a guild.
|
||||
* Sends an embed to the system channel if critical or optional perms are missing.
|
||||
* @param {object} guild - The guild object.
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @returns {Promise<void>}
|
||||
* @private
|
||||
*/
|
||||
async _checkGuildPermissions(guild, guildId) {
|
||||
const { remix } = this;
|
||||
|
||||
try {
|
||||
if (guild.members && !guild.members.me) {
|
||||
await guild.members.fetchMe();
|
||||
}
|
||||
} catch (e) { logger.warn("[GatewayHandler] fetchMe failed:", e?.message); }
|
||||
|
||||
const channels = guild.channels;
|
||||
if (!channels) return;
|
||||
|
||||
let targetChannel = null;
|
||||
if (guild.systemChannelId) {
|
||||
targetChannel = channels.get?.(guild.systemChannelId) ?? null;
|
||||
}
|
||||
if (!targetChannel) {
|
||||
for (const ch of (channels.values?.() ?? [])) {
|
||||
if (ch.isTextBased?.() || ch.type === 0 || ch.type === "GUILD_TEXT") {
|
||||
targetChannel = ch;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!targetChannel) return;
|
||||
|
||||
const result = remix.messages.checkAllBotPermissions(targetChannel);
|
||||
if (result.missing.length === 0) return;
|
||||
|
||||
const missingNames = result.missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k);
|
||||
if (result.criticalMissing.length > 0) {
|
||||
logger.warn(
|
||||
`[GuildCreate] Server ${guildId} is missing CRITICAL bot permissions: ${result.criticalMissing.join(", ")}\n` +
|
||||
` All missing: ${missingNames.join(", ")}`
|
||||
);
|
||||
} else {
|
||||
logger.guild(
|
||||
`[GuildCreate] Server ${guildId} is missing optional permissions: ${result.optionalMissing.join(", ")}`
|
||||
);
|
||||
}
|
||||
|
||||
try {
|
||||
const permEmbed = remix.messages.buildPermissionEmbed(result.missing, guildId);
|
||||
await targetChannel.send({ embeds: [permEmbed], allowedMentions: { parse: [] } });
|
||||
} catch (e) {
|
||||
logger.warn(`[GuildCreate] Cannot send permission warning to server ${guildId}: ${e.message}`);
|
||||
try {
|
||||
const t = this.remix.locale?.translate?.bind(this.remix.locale);
|
||||
const guildIdStr = cleanId(guildId);
|
||||
await targetChannel.send({
|
||||
content: t ? t(guildIdStr, "responses.gateway.missingPermsFallback", { perms: missingNames.join("**, **") }) :
|
||||
"⚠️ I'm missing permissions I need to work properly! Missing: **" + missingNames.join("**, **") + "**. Please ask a server administrator to grant these permissions in Server Settings → Roles.",
|
||||
allowedMentions: { parse: [] },
|
||||
});
|
||||
} catch (e) {
|
||||
logger.warn(`[GuildCreate] Cannot send ANY notification to server ${guildId} — bot is missing SendMessages permission:`, e?.message);
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Seed the voice state cache from VoiceManager or guild cache on startup.
|
||||
* @private
|
||||
*/
|
||||
seedVoiceStatesFromGuilds() {
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
|
||||
try {
|
||||
const vm = getVoiceManager(client);
|
||||
if (vm?.voiceStates && vm.voiceStates.size > 0) {
|
||||
let totalHumans = 0;
|
||||
let totalBots = 0;
|
||||
for (const [guildId, userMap] of vm.voiceStates) {
|
||||
if (!userMap || typeof userMap.forEach !== "function") continue;
|
||||
const cleanGuildId = cleanId(guildId);
|
||||
if (!cleanGuildId) continue;
|
||||
userMap.forEach((channelId, userId) => {
|
||||
if (!userId || !channelId) return;
|
||||
const botId = client.user?.id;
|
||||
if (userId === botId) {
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuildId, userId, channelId, isBot: true });
|
||||
totalBots++;
|
||||
} else {
|
||||
const guild = client.guilds.get(cleanGuildId) ?? client.guilds.get(guildId);
|
||||
const member = guild?.members?.get?.(userId);
|
||||
const isBot = member?.user?.bot ?? false;
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuildId, userId, channelId, isBot });
|
||||
if (isBot) totalBots++;
|
||||
else totalHumans++;
|
||||
}
|
||||
});
|
||||
}
|
||||
logger.voiceState(
|
||||
`[Seed] Seeded from VoiceManager.voiceStates — ` +
|
||||
`${totalHumans} humans, ${totalBots} bots across ${vm.voiceStates.size} guilds. ` +
|
||||
`Cache now: ${remix.voiceCache.observedVoiceUsersSize} humans, ${remix.voiceCache.observedVoiceBotsSize} bots.`
|
||||
);
|
||||
return;
|
||||
}
|
||||
logger.voiceState(`[Seed] VoiceManager.voiceStates is empty (${vm?.voiceStates?.size ?? "null"} guilds). ` +
|
||||
`This is expected if no users were in voice when the bot started. ` +
|
||||
`VoiceStatesSync handler will populate the cache as guilds become available.`);
|
||||
} catch (e) {
|
||||
logger.voiceState(`[Seed] VoiceManager seeding failed: ${e?.message} — falling back to guild cache.`);
|
||||
}
|
||||
|
||||
for (const [gId, guild] of client.guilds) {
|
||||
for (const vs of iterateVoiceStates(guild)) {
|
||||
remix.voiceCache.updateUser({ guildId: gId, userId: vs.userId, channelId: vs.channelId, isBot: vs.isBot });
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Re-seed voice states for a specific channel from multiple sources.
|
||||
* Checks VoiceManager, guild cache, VoiceStateCache, and LiveKit participants.
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @param {string} channelId - The channel ID.
|
||||
* @returns {number} Number of humans found in the channel.
|
||||
*/
|
||||
reseedVoiceStatesForChannel(guildId, channelId) {
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
|
||||
const cleanGuild = cleanId(guildId);
|
||||
const cleanChannel = cleanId(channelId);
|
||||
if (!cleanGuild || !cleanChannel) return 0;
|
||||
|
||||
let humansFound = 0;
|
||||
const botId = client.user?.id;
|
||||
|
||||
try {
|
||||
const vm = getVoiceManager(client);
|
||||
if (vm?.voiceStates) {
|
||||
const guildVoiceMap = vm.voiceStates.get(cleanGuild) ?? vm.voiceStates.get(guildId);
|
||||
if (guildVoiceMap && typeof guildVoiceMap.forEach === "function") {
|
||||
guildVoiceMap.forEach((userChannelId, userId) => {
|
||||
if (!userId || !userChannelId) return;
|
||||
const userChannel = cleanId(userChannelId);
|
||||
if (userChannel !== cleanChannel) return;
|
||||
if (userId === botId) {
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: true });
|
||||
} else {
|
||||
const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId);
|
||||
const member = guild?.members?.get?.(userId);
|
||||
const isBot = member?.user?.bot ?? false;
|
||||
if (isBot) {
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: true });
|
||||
} else {
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: false });
|
||||
humansFound++;
|
||||
logger.voiceState(
|
||||
`[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild}) via VoiceManager`
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
if (botId) {
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true });
|
||||
}
|
||||
|
||||
logger.voiceState(
|
||||
`[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` +
|
||||
`found ${humansFound} human(s) via VoiceManager, observedVoiceUsers size now ${remix.voiceCache.observedVoiceUsersSize}`
|
||||
);
|
||||
|
||||
if (humansFound > 0) return humansFound;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
logger.voiceState(`[Reseed] VoiceManager lookup failed: ${e?.message} — falling back.`);
|
||||
}
|
||||
|
||||
const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId);
|
||||
if (!guild) {
|
||||
logger.voiceState(
|
||||
`[Reseed] Guild ${cleanGuild} not in cache — cannot reseed voice states.`
|
||||
);
|
||||
} else {
|
||||
for (const vs of iterateVoiceStates(guild)) {
|
||||
if (vs.isBot) continue;
|
||||
if (vs.channelId === cleanChannel) {
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId: vs.userId, channelId: vs.channelId, isBot: false });
|
||||
humansFound++;
|
||||
logger.voiceState(
|
||||
`[Reseed] Found human ${vs.userId} in channel ${cleanChannel} (guild ${cleanGuild})`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (botId) {
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true });
|
||||
}
|
||||
|
||||
if (humansFound > 0) {
|
||||
logger.voiceState(
|
||||
`[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` +
|
||||
`found ${humansFound} human(s), observedVoiceUsers size now ${remix.voiceCache.observedVoiceUsersSize}`
|
||||
);
|
||||
return humansFound;
|
||||
}
|
||||
}
|
||||
|
||||
if (humansFound === 0 && remix.voiceCache) {
|
||||
const humans = remix.voiceCache.getHumansInChannel(cleanGuild, cleanChannel);
|
||||
for (const uid of humans) {
|
||||
humansFound++;
|
||||
logger.voiceState(
|
||||
`[Reseed] Found human ${uid} in channel ${cleanChannel} (guild ${cleanGuild}) via VoiceStateCache`
|
||||
);
|
||||
}
|
||||
|
||||
if (botId) {
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true });
|
||||
}
|
||||
}
|
||||
|
||||
if (humansFound === 0) {
|
||||
try {
|
||||
const player = remix.players.playerMap.get(cleanChannel);
|
||||
const room = player?.connection?.room;
|
||||
if (room?.isConnected && room.remoteParticipants) {
|
||||
for (const [, participant] of room.remoteParticipants) {
|
||||
const userId = participant?.identity ?? participant?.sid;
|
||||
if (userId) {
|
||||
humansFound++;
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: false });
|
||||
logger.voiceState(
|
||||
`[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild}) via LiveKit participants`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
logger.voiceState(`[Reseed] LiveKit participant fallback error: ${e?.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
logger.voiceState(
|
||||
`[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` +
|
||||
`found ${humansFound} human(s), observedVoiceUsers size now ${remix.voiceCache.observedVoiceUsersSize}`
|
||||
);
|
||||
|
||||
return humansFound;
|
||||
},
|
||||
|
||||
/** @async @private Fetch all guilds the bot is in via REST and create stub entries in the client cache for any missing guilds. This ensures settings and 24/7 lookups work even for guilds that haven't sent GUILD_CREATE yet. */
|
||||
async seedGuildsFromRest() {
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
|
||||
try {
|
||||
let after = null;
|
||||
let added = 0;
|
||||
|
||||
while (true) {
|
||||
const url = "/users/@me/guilds?limit=200" + (after ? "&after=" + after : "");
|
||||
const chunk = await client.rest.get(url);
|
||||
|
||||
if (!Array.isArray(chunk) || chunk.length === 0) break;
|
||||
|
||||
for (const g of chunk) {
|
||||
const id = g?.id;
|
||||
if (!id) continue;
|
||||
if (!client.guilds.has(id)) {
|
||||
try {
|
||||
const Guild = this._getGuildClass();
|
||||
if (Guild) {
|
||||
const stub = new Guild(client, { id, name: g.name ?? "unknown" });
|
||||
stub._stub = true;
|
||||
client.guilds.set(id, stub);
|
||||
} else {
|
||||
client.guilds.set(id, {
|
||||
id,
|
||||
name: g.name ?? "unknown",
|
||||
_stub: true,
|
||||
members: { set: () => {}, get: () => undefined, has: () => false, me: null },
|
||||
channels: { set: () => {}, get: () => undefined, has: () => false },
|
||||
roles: { set: () => {}, get: () => undefined, has: () => false },
|
||||
emojis: { set: () => {}, get: () => undefined, has: () => false },
|
||||
stickers: { set: () => {}, get: () => undefined, has: () => false },
|
||||
});
|
||||
}
|
||||
} catch (stubErr) {
|
||||
logger.guild(`[GuildSeed] Guild constructor failed for ${id}, using safe stub: ${stubErr?.message}`);
|
||||
client.guilds.set(id, {
|
||||
id,
|
||||
name: g.name ?? "unknown",
|
||||
_stub: true,
|
||||
members: { set: () => {}, get: () => undefined, has: () => false, me: null },
|
||||
channels: { set: () => {}, get: () => undefined, has: () => false },
|
||||
roles: { set: () => {}, get: () => undefined, has: () => false },
|
||||
emojis: { set: () => {}, get: () => undefined, has: () => false },
|
||||
stickers: { set: () => {}, get: () => undefined, has: () => false },
|
||||
});
|
||||
}
|
||||
added++;
|
||||
}
|
||||
}
|
||||
|
||||
if (chunk.length < 200) break;
|
||||
after = chunk[chunk.length - 1].id;
|
||||
}
|
||||
|
||||
if (added > 0) {
|
||||
logger.guild(`[GuildSeed] Added ${added} missing guild stub(s) from REST. Total: ${client.guilds.size}`);
|
||||
} else {
|
||||
logger.guild(`[GuildSeed] All guilds already cached. Total: ${client.guilds.size}`);
|
||||
}
|
||||
} catch (err) {
|
||||
logger.warn("[GuildSeed] REST guild seeding failed:", err?.message ?? err);
|
||||
}
|
||||
},
|
||||
|
||||
/** @private @returns {Function|null} The Guild constructor class. */
|
||||
_getGuildClass() {
|
||||
if (this._GuildClass) return this._GuildClass;
|
||||
try {
|
||||
const { client } = this.remix;
|
||||
for (const guild of client.guilds.values()) {
|
||||
if (guild && !guild._stub && typeof guild.constructor === 'function' && guild.constructor.name === 'Guild') {
|
||||
this._GuildClass = guild.constructor;
|
||||
return this._GuildClass;
|
||||
}
|
||||
}
|
||||
} catch(e) { logger.warn("[Gateway] _getGuildClass failed:", e?.message); }
|
||||
this._GuildClass = null;
|
||||
return null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Process a confirmed guild deletion. Cleans up voice cache and previous state.
|
||||
* Does NOT delete 24/7 settings (preserved for re-invite).
|
||||
* @param {string} guildId - The deleted guild ID.
|
||||
* @private
|
||||
*/
|
||||
_processGuildDelete(guildId) {
|
||||
const { remix } = this;
|
||||
const cleanGuildId = cleanId(guildId);
|
||||
|
||||
logger.guild(
|
||||
`[GuildDelete] Received GuildDelete for server ${guildId} — ` +
|
||||
`skipping removal (24/7 removal system disabled). ` +
|
||||
`Settings and players are preserved. If the server truly removed the bot, ` +
|
||||
`the GuildCreate handler will re-initialise on re-invite.`
|
||||
);
|
||||
|
||||
remix.voiceCache.removeGuild(cleanGuildId);
|
||||
for (const [stateKey, info] of [...this._prevVoiceState]) {
|
||||
if (cleanId(info.guildId) === cleanGuildId)
|
||||
this._prevVoiceState.delete(stateKey);
|
||||
}
|
||||
remix._announcementChannelCache?.delete(guildId);
|
||||
},
|
||||
};
|
||||
|
||||
export default GuildSync;
|
||||
export { GuildSync };
|
||||
@@ -0,0 +1,169 @@
|
||||
/**
|
||||
* @module src/voice/gateway/RejoinManager
|
||||
* @description Rejoin concern for {@link GatewayHandler}: 24/7 channel
|
||||
* rejoin with exponential-backoff retries, duplicate-join guarding, and
|
||||
* guild move-in-progress detection. The MAX_REJOIN_RETRIES static lives on
|
||||
* the base GatewayHandler class (imported below).
|
||||
*
|
||||
* These methods are applied onto the GatewayHandler class prototype via
|
||||
* {@link applyMixins} — `this` is a GatewayHandler instance.
|
||||
*/
|
||||
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
import { cleanId } from "../../utils/Utils.mjs";
|
||||
import { GatewayHandler } from "./GatewayHandler.mjs";
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
* @description Rejoin manager mixin — applied to GatewayHandler.
|
||||
*/
|
||||
const RejoinManager = {
|
||||
/**
|
||||
* Attempt to spawn a player for a channel with exponential-backoff retries.
|
||||
* @param {string} channelId - The target channel ID.
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @param {number} [maxRetries=3] - Maximum retry attempts.
|
||||
* @param {number} [baseDelay=5000] - Base delay in ms (doubled each retry).
|
||||
* @param {string} [context='Rejoin'] - Label for log messages.
|
||||
* @returns {Promise<Player|null>} The spawned player, or null if all retries failed.
|
||||
* @private
|
||||
*/
|
||||
async _attemptRejoin(channelId, guildId, maxRetries = 3, baseDelay = 5_000, context = 'Rejoin') {
|
||||
for (let attempt = 1; attempt <= maxRetries; attempt++) {
|
||||
try {
|
||||
const player = await this.remix._spawnPlayer(guildId, channelId);
|
||||
this.reseedVoiceStatesForChannel(guildId, channelId);
|
||||
logger.voice247(
|
||||
`[${context}] Successfully rejoined channel ${channelId}` +
|
||||
(attempt > 1 ? ` (after ${attempt - 1} retry/retries)` : '')
|
||||
);
|
||||
return player;
|
||||
} catch (err) {
|
||||
const errMsg = err?.message ?? String(err);
|
||||
const isTrackTimeout = errMsg.includes("track publication timed out")
|
||||
|| errMsg.includes("lavalink player create failed")
|
||||
|| errMsg.includes("Failed to create audio player")
|
||||
|| errMsg.includes("internal error");
|
||||
|
||||
if (isTrackTimeout && attempt < maxRetries) {
|
||||
const backoffMs = baseDelay * Math.pow(2, attempt - 1);
|
||||
logger.warn(
|
||||
`[${context}] Track publication failed for channel ${channelId} (attempt ${attempt}/${maxRetries}) — ` +
|
||||
`retrying in ${backoffMs / 1000}s: ${errMsg}`
|
||||
);
|
||||
await new Promise(resolve => setTimeout(resolve, backoffMs));
|
||||
continue;
|
||||
}
|
||||
|
||||
logger.warn(
|
||||
`[${context}] Failed to rejoin channel ${channelId} (attempt ${attempt}/${maxRetries}): ${errMsg}` +
|
||||
(attempt > 1 ? ` (after ${attempt} attempts)` : '')
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Safely rejoin a 24/7 channel. Guards against duplicate joins,
|
||||
* intentional leaves, missing channels, and pending joins.
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @param {string} channelId - The target channel ID.
|
||||
* @returns {Promise<Player|null>} The spawned player, or null if skipped.
|
||||
* @private
|
||||
*/
|
||||
async _rejoinChannel(guildId, channelId) {
|
||||
const { remix } = this;
|
||||
const cleanGuildId = cleanId(guildId);
|
||||
const cleanChannelId = cleanId(channelId);
|
||||
|
||||
if (this._rejoinInProgress.has(cleanChannelId)) {
|
||||
logger.voice247(`[Rejoin] Channel ${cleanChannelId} rejoin already in progress — skipping.`);
|
||||
return;
|
||||
}
|
||||
|
||||
const existing = remix.players.playerMap.get(cleanChannelId);
|
||||
if (existing && !existing._destroyed) {
|
||||
logger.voice247(`[Rejoin] Channel ${cleanChannelId} already has a player — skipping.`);
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
return;
|
||||
}
|
||||
|
||||
if (remix.players._pendingJoins?.has?.(cleanChannelId)) {
|
||||
logger.voice247(`[Rejoin] Channel ${cleanChannelId} already has a pending join — skipping.`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (remix.intentionalLeaves.has(cleanChannelId)) {
|
||||
logger.voice247(`[Rejoin] Channel ${cleanChannelId} was intentionally left — skipping.`);
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
return;
|
||||
}
|
||||
|
||||
const channel = remix.client?.channels?.get?.(cleanChannelId);
|
||||
if (!channel) {
|
||||
logger.voice247(`[Rejoin] Channel ${cleanChannelId} no longer exists — skipping.`);
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
return;
|
||||
}
|
||||
|
||||
this._rejoinInProgress.add(cleanChannelId);
|
||||
|
||||
const maxRetries = GatewayHandler.MAX_REJOIN_RETRIES;
|
||||
logger.voice247(
|
||||
`[Rejoin] Attempting to rejoin channel ${cleanChannelId} in guild ${cleanGuildId}...`
|
||||
);
|
||||
|
||||
try {
|
||||
const player = await this._attemptRejoin(cleanChannelId, cleanGuildId, maxRetries, 5_000, "Rejoin");
|
||||
if (player) {
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
} else {
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
}
|
||||
return player;
|
||||
} finally {
|
||||
this._rejoinInProgress.delete(cleanChannelId);
|
||||
}
|
||||
},
|
||||
|
||||
/** @private Check whether a guild currently has a move in progress (recently connected player or pending join). Used to suppress false positive disconnect-rejoin loops. @param {string} guildId - The guild ID. @param {string} oldChannelId - The channel the bot just left. @returns {boolean} True if a move is in progress within the evidence window. */
|
||||
_isGuildMoveInProgress(guildId, oldChannelId) {
|
||||
const { remix } = this;
|
||||
const cleanGuild = cleanId(guildId);
|
||||
const cleanOld = cleanId(oldChannelId);
|
||||
if (!cleanGuild || !cleanOld) return false;
|
||||
|
||||
const now = Date.now();
|
||||
const activePlayers = [...remix.players.playerMap.values()].filter(
|
||||
p => !p._destroyed && cleanId(p._guildId ?? "") === cleanGuild
|
||||
);
|
||||
|
||||
for (const player of activePlayers) {
|
||||
const playerChannel = cleanId(player._channelId ?? "");
|
||||
if (!playerChannel || playerChannel === cleanOld) continue;
|
||||
const connectedAt = player._lastConnectedAt ?? 0;
|
||||
if (now - connectedAt < this._moveEvidenceWindowMs) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
if (remix.players._pendingJoins) {
|
||||
for (const pendingId of remix.players._pendingJoins) {
|
||||
const cleanPending = cleanId(pendingId);
|
||||
if (cleanPending && cleanPending !== cleanOld) {
|
||||
const pendingChannel = remix.client?.channels?.get?.(cleanPending);
|
||||
if (pendingChannel && cleanId(pendingChannel.guildId ?? "") === cleanGuild) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
},
|
||||
};
|
||||
|
||||
export default RejoinManager;
|
||||
export { RejoinManager };
|
||||
@@ -0,0 +1,435 @@
|
||||
/**
|
||||
* @module src/voice/gateway/VoiceStateRouting
|
||||
* @description Voice-state routing concern for {@link GatewayHandler}:
|
||||
* VOICE_STATE_UPDATE dispatch (human vs. bot paths), VOICE_STATES_SYNC bulk
|
||||
* seeding, previous-state map maintenance, voice cache updates, inactivity
|
||||
* timers on human join/leave, dashboard updates, and 24/7 bot move-away /
|
||||
* disconnect handling.
|
||||
*
|
||||
* These methods are applied onto the GatewayHandler class prototype via
|
||||
* {@link applyMixins} — `this` is a GatewayHandler instance.
|
||||
*/
|
||||
|
||||
import { logger } from "../../core/Logger.mjs";
|
||||
import { get247ChannelMode } from "../../utils/Helpers247.mjs";
|
||||
import { VoiceStateCache } from "../VoiceStateCache.mjs";
|
||||
import { cleanId } from "../../utils/Utils.mjs";
|
||||
|
||||
/**
|
||||
* @type {object}
|
||||
* @description Voice-state routing mixin — applied to GatewayHandler.
|
||||
*/
|
||||
const VoiceStateRouting = {
|
||||
/**
|
||||
* Main handler for VOICE_STATE_UPDATE events. Routes to human or bot sub-handlers.
|
||||
* @param {object} data - The voice state update payload from the gateway.
|
||||
* @returns {Promise<void>}
|
||||
* @private
|
||||
*/
|
||||
async _handleVoiceStateUpdate(data) {
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
|
||||
const userId = data?.user_id;
|
||||
if (!userId) return;
|
||||
|
||||
const newChannelId = data?.channel_id ?? null;
|
||||
const vsuGuildId = data?.guild_id;
|
||||
const isBot = data?.member?.user?.bot ?? null;
|
||||
|
||||
|
||||
const prevEntry = this.findPrevVoiceStateEntry(userId, vsuGuildId);
|
||||
const prev = prevEntry.value;
|
||||
const prevSameGuild = prev &&
|
||||
cleanId(prev.guildId ?? "") === cleanId(vsuGuildId ?? "");
|
||||
const oldChannelId = prevSameGuild ? (prev?.channelId ?? null) : null;
|
||||
|
||||
|
||||
this._updatePreviousStates(userId, vsuGuildId, oldChannelId, newChannelId, isBot, prevEntry, prev);
|
||||
this._updateVoiceStateCache(userId, vsuGuildId, oldChannelId, newChannelId, isBot, prev);
|
||||
|
||||
|
||||
const { player, playerGuildId, homeChannelId } = this._findAffectedPlayer(vsuGuildId, oldChannelId, newChannelId);
|
||||
|
||||
const isBotUser = isBot === true && userId === client.user?.id;
|
||||
|
||||
if (!isBotUser) {
|
||||
|
||||
this._handleInactivityOnVoiceChange(player, playerGuildId, homeChannelId, userId, oldChannelId, newChannelId, vsuGuildId, data);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
this._handleBotVoiceChange(player, playerGuildId, homeChannelId, oldChannelId, newChannelId, vsuGuildId, data);
|
||||
},
|
||||
|
||||
/** Handle VoiceStatesSync bulk event from the gateway. @param {object} data - Sync payload with voiceStates array. @private */
|
||||
_handleVoiceStatesSync(data) {
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
const guildId = data?.guildId;
|
||||
if (!guildId || !Array.isArray(data?.voiceStates)) return;
|
||||
|
||||
const botId = client.user?.id;
|
||||
let humansAdded = 0;
|
||||
let botsAdded = 0;
|
||||
|
||||
for (const vs of data.voiceStates) {
|
||||
const userId = vs.user_id;
|
||||
const channelId = vs.channel_id;
|
||||
if (!userId || !channelId) continue;
|
||||
|
||||
const isBot = vs.member?.user?.bot ?? (userId === botId);
|
||||
|
||||
remix.voiceCache.updateUser({ guildId, userId, channelId, isBot });
|
||||
if (isBot) {
|
||||
botsAdded++;
|
||||
} else {
|
||||
humansAdded++;
|
||||
}
|
||||
}
|
||||
|
||||
if (humansAdded > 0 || botsAdded > 0) {
|
||||
logger.voiceState(
|
||||
`[VoiceStatesSync] Guild ${guildId}: seeded ${humansAdded} humans, ${botsAdded} bots ` +
|
||||
`(${data.voiceStates.length} total states).`
|
||||
);
|
||||
}
|
||||
},
|
||||
|
||||
/** @private Update the voice state cache for a user joining/leaving. @param {string} userId @param {string} guildId @param {string|null} oldChannelId @param {string|null} newChannelId @param {boolean} isBot @param {object|null} prev */
|
||||
_updateVoiceStateCache(userId, guildId, oldChannelId, newChannelId, isBot, prev) {
|
||||
const { remix } = this;
|
||||
|
||||
if (newChannelId) {
|
||||
remix.voiceCache.updateUser({ guildId: guildId ?? prev?.guildId, userId, channelId: newChannelId, isBot: isBot === true });
|
||||
} else {
|
||||
const resolvedGuildId = guildId ?? prev?.guildId;
|
||||
if (resolvedGuildId) {
|
||||
remix.voiceCache.deleteHumanUser(userId, resolvedGuildId);
|
||||
remix.voiceCache.deleteBotUser(VoiceStateCache.userKey(resolvedGuildId, userId));
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
/** @private Update the previous-voice-state map and evict stale entries. @param {string} userId @param {string} guildId @param {string|null} oldChannelId @param {string|null} newChannelId @param {boolean} isBot @param {object} prevEntry @param {object|null} prev */
|
||||
_updatePreviousStates(userId, guildId, oldChannelId, newChannelId, isBot, prevEntry, prev) {
|
||||
const { remix } = this;
|
||||
const prevKey = prevEntry.key;
|
||||
const nextKey = this.getPrevVoiceStateKey(userId, guildId ?? prev?.guildId);
|
||||
|
||||
if (newChannelId) {
|
||||
if (prevKey && prevKey !== nextKey) {
|
||||
const prevGuildPart = prevKey.split(":")[0];
|
||||
const nextGuildPart = nextKey.split(":")[0];
|
||||
if (prevGuildPart === nextGuildPart) {
|
||||
this._prevVoiceState.delete(prevKey);
|
||||
}
|
||||
}
|
||||
if (nextKey && this._prevVoiceState.size >= 10_000 && !this._prevVoiceState.has(nextKey)) {
|
||||
const evictKey = this._prevVoiceState.keys().next().value;
|
||||
const evictEntry = this._prevVoiceState.get(evictKey);
|
||||
this._prevVoiceState.delete(evictKey);
|
||||
if (evictEntry) {
|
||||
const evictGuildId = evictEntry.guildId;
|
||||
const evictUserId = evictKey.split(":")[1];
|
||||
if (evictGuildId && evictUserId) {
|
||||
const currentLoc = remix.voiceCache.getUserLocation(evictGuildId, evictUserId);
|
||||
if (currentLoc && currentLoc.channelId === evictEntry.channelId) {
|
||||
remix.voiceCache.updateUser({ guildId: evictGuildId, userId: evictUserId, channelId: null, isBot: evictEntry.isBot ?? false });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (nextKey) this._prevVoiceState.set(nextKey, { channelId: newChannelId, guildId: guildId ?? prev?.guildId, isBot: isBot === true });
|
||||
} else {
|
||||
if (prevKey) this._prevVoiceState.delete(prevKey);
|
||||
}
|
||||
},
|
||||
|
||||
/** @private Find a player affected by a voice state change. @param {string} guildId @param {string|null} oldChannelId @param {string|null} newChannelId @returns {{player: Player|null, playerGuildId: string|null, homeChannelId: string|null}} */
|
||||
_findAffectedPlayer(guildId, oldChannelId, newChannelId) {
|
||||
const { remix } = this;
|
||||
|
||||
|
||||
if (oldChannelId) {
|
||||
const cleanOld = cleanId(oldChannelId);
|
||||
const player = remix.players.playerMap.get(cleanOld);
|
||||
if (player) {
|
||||
return { player, playerGuildId: player._guildId, homeChannelId: player._home247Channel };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (newChannelId) {
|
||||
const cleanNew = cleanId(newChannelId);
|
||||
const player = remix.players.playerMap.get(cleanNew);
|
||||
if (player) {
|
||||
return { player, playerGuildId: player._guildId, homeChannelId: player._home247Channel };
|
||||
}
|
||||
}
|
||||
|
||||
return { player: null, playerGuildId: null, homeChannelId: null };
|
||||
},
|
||||
|
||||
/** @private Manage inactivity timers when a human joins or leaves a voice channel. @param {Player|null} player @param {string|null} playerGuildId @param {string|null} homeChannelId @param {string} userId @param {string|null} oldChannelId @param {string|null} newChannelId @param {string} vsuGuildId @param {object} vsu */
|
||||
async _handleInactivityOnVoiceChange(player, playerGuildId, homeChannelId, userId, oldChannelId, newChannelId, vsuGuildId, vsu) {
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
const resolvedGuildId = vsuGuildId ?? playerGuildId;
|
||||
if (!resolvedGuildId) return;
|
||||
|
||||
if (newChannelId) {
|
||||
try {
|
||||
const cleanId247 = cleanId(newChannelId);
|
||||
const player247 = remix.players.playerMap.get(cleanId247);
|
||||
if (player247 && typeof player247._stopInactivityTimer === "function") {
|
||||
logger.voiceState(`[VoiceState] Human joined 247 channel ${cleanId247}, stopping inactivity timer`);
|
||||
player247._stopInactivityTimer();
|
||||
}
|
||||
} catch(e) { logger.warn("[VoiceState] 247 inactivity timer stop failed:", e?.message); }
|
||||
}
|
||||
|
||||
if (oldChannelId && oldChannelId !== newChannelId) {
|
||||
try {
|
||||
const cleanOld = cleanId(oldChannelId);
|
||||
const oldPlayer = remix.players.playerMap.get(cleanOld);
|
||||
if (oldPlayer && typeof oldPlayer._startInactivityTimer === "function") {
|
||||
setTimeout(() => {
|
||||
if (!oldPlayer._hasHumansInChannel()) {
|
||||
logger.voiceState(`[VoiceState] Last human left ${cleanOld}, starting inactivity timer`);
|
||||
oldPlayer._startInactivityTimer();
|
||||
}
|
||||
}, this.T.aloneCheckDebounce);
|
||||
}
|
||||
} catch(e) { logger.warn("[VoiceState] Inactivity timer start failed:", e?.message); }
|
||||
}
|
||||
|
||||
if (newChannelId) {
|
||||
try {
|
||||
const cleanChId = cleanId(newChannelId);
|
||||
const newPlayer = remix.players.playerMap.get(cleanChId);
|
||||
if (newPlayer && typeof newPlayer._stopInactivityTimer === "function") {
|
||||
logger.voiceState(`[VoiceState] Human joined ${cleanChId}, stopping inactivity timer`);
|
||||
newPlayer._stopInactivityTimer();
|
||||
}
|
||||
} catch(e) { logger.warn("[VoiceState] Inactivity timer stop failed:", e?.message); }
|
||||
}
|
||||
|
||||
if (remix.dashboard?.enabled) {
|
||||
try {
|
||||
let userObj = vsu?.member?.user;
|
||||
if (!userObj) {
|
||||
try { userObj = await client.users.fetch(userId).catch(() => null); } catch(e) { logger.warn("[VoiceState] Dashboard user fetch failed:", e?.message); }
|
||||
}
|
||||
if (userObj) {
|
||||
const details = {
|
||||
type: newChannelId ? "join" : "leave",
|
||||
guildId: resolvedGuildId,
|
||||
channelId: newChannelId ?? null,
|
||||
oldChannelId: oldChannelId ?? null,
|
||||
};
|
||||
remix.dashboard.updateUser(details, userObj);
|
||||
}
|
||||
|
||||
const refChannel = newChannelId ?? oldChannelId;
|
||||
const cleanId_ref = refChannel ? cleanId(refChannel) : null;
|
||||
|
||||
if (cleanId_ref) {
|
||||
const dashPlayer = remix.players.playerMap.get(cleanId_ref);
|
||||
if (dashPlayer) {
|
||||
const eventType = newChannelId ? "join" : "leave";
|
||||
remix.dashboard.updatePlayer({
|
||||
type: eventType,
|
||||
data: userId,
|
||||
}, dashPlayer);
|
||||
|
||||
remix.dashboard.playerUpdate({
|
||||
type: eventType,
|
||||
}, dashPlayer);
|
||||
}
|
||||
}
|
||||
} catch(e) { logger.warn("[VoiceState] Dashboard update failed:", e?.message); }
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Handle a voice state update for the bot itself.
|
||||
* Detects move-away from 24/7 channels and unexpected disconnects.
|
||||
* @param {Player|null} player - The affected player (if any).
|
||||
* @param {string|null} playerGuildId - The guild ID from the player.
|
||||
* @param {string|null} homeChannelId - The 24/7 home channel ID from the player.
|
||||
* @param {string|null} oldChannelId - The channel the bot was in.
|
||||
* @param {string|null} newChannelId - The channel the bot moved to (null if disconnected).
|
||||
* @param {string} vsuGuildId - The guild ID from the VSU event.
|
||||
* @param {object} vsu - The raw VSU payload.
|
||||
* @private
|
||||
*/
|
||||
_handleBotVoiceChange(player, playerGuildId, homeChannelId, oldChannelId, newChannelId, vsuGuildId, vsu) {
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
const guildId = vsuGuildId;
|
||||
|
||||
if (newChannelId && guildId && oldChannelId && oldChannelId !== newChannelId) {
|
||||
// During boot recovery, ignore move events — the recovery loop handles rejoining.
|
||||
if (this._bootRecoveryActive) {
|
||||
logger.voice247(
|
||||
`[247] Ignoring bot move ${cleanId(oldChannelId)} → ${cleanId(newChannelId)} during boot recovery.`
|
||||
);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const cleanNew = cleanId(newChannelId);
|
||||
const cleanOld = cleanId(oldChannelId);
|
||||
|
||||
// Check if old channel is a saved 24/7 channel
|
||||
const oldIs247 = (() => {
|
||||
try {
|
||||
const set = remix.settingsMgr.getServer(guildId);
|
||||
return get247ChannelMode(set, cleanOld) === "on";
|
||||
} catch (_) { return false; }
|
||||
})();
|
||||
|
||||
// Check if new channel is a saved 24/7 channel or has a pending spawn
|
||||
const newChannelSaved = (() => {
|
||||
try {
|
||||
const set = remix.settingsMgr.getServer(guildId);
|
||||
return get247ChannelMode(set, cleanNew) === "on";
|
||||
} catch (_) { return false; }
|
||||
})();
|
||||
const newChannelPendingSpawn = remix.players?._pendingJoins?.has?.(cleanNew) || false;
|
||||
|
||||
const existingPlayer = remix.players.playerMap.get(cleanOld);
|
||||
|
||||
if (oldIs247 && existingPlayer) {
|
||||
// Old channel is 24/7 — bot physically moved away, so the voice
|
||||
// connection to old channel is dead. Destroy the old player and
|
||||
// schedule a fresh rejoin so it gets a new live connection.
|
||||
logger.voice247(
|
||||
`[247] Bot moved away from 24/7 channel ${cleanOld} → ${cleanNew}. ` +
|
||||
`Destroying stale player, scheduling rejoin for ${cleanOld}.`
|
||||
);
|
||||
remix.players.playerMap.delete(cleanOld);
|
||||
const homeCh = cleanId(existingPlayer._home247Channel ?? "");
|
||||
if (homeCh && homeCh !== cleanOld) remix.players.playerMap.delete(homeCh);
|
||||
try { existingPlayer.destroy(); } catch (_) {}
|
||||
const rejoinDelay = this.T.rejoin247Delay ?? 3_000;
|
||||
setTimeout(() => {
|
||||
this._rejoinChannel(cleanId(guildId), cleanOld).catch(err => {
|
||||
logger.warn(`[247] Failed to rejoin ${cleanOld} after move-away:`, err.message);
|
||||
});
|
||||
}, rejoinDelay);
|
||||
} else if (newChannelSaved || newChannelPendingSpawn) {
|
||||
// New channel is already 24/7 or being spawned — keep both, don't rekey.
|
||||
logger.voice247(
|
||||
`[247] Keeping both channels ${cleanOld} and ${cleanNew} ` +
|
||||
`(saved=${newChannelSaved} pending=${newChannelPendingSpawn})`
|
||||
);
|
||||
} else if (existingPlayer && cleanNew !== cleanOld) {
|
||||
// Neither channel is 24/7 — safe to rekey the player.
|
||||
const targetChannel = client.channels.get(cleanNew)
|
||||
?? client.channels.get?.(cleanNew)
|
||||
?? null;
|
||||
const targetGuildId = cleanId(targetChannel?.guildId ?? targetChannel?.guild?.id ?? guildId ?? "");
|
||||
|
||||
const playerAtNewKey = remix.players.playerMap.get(cleanNew);
|
||||
if (!playerAtNewKey || playerAtNewKey === existingPlayer) {
|
||||
remix.players.playerMap.delete(cleanOld);
|
||||
remix.players.playerMap.set(cleanNew, existingPlayer);
|
||||
existingPlayer._channelId = cleanNew;
|
||||
existingPlayer._home247Channel = cleanNew;
|
||||
if (targetGuildId) existingPlayer._guildId = targetGuildId;
|
||||
logger.voice247(`[247] Re-keyed playerMap ${cleanOld} → ${cleanNew}`);
|
||||
} else {
|
||||
logger.voice247(
|
||||
`[247] Skipped re-key ${cleanOld} → ${cleanNew} (new key occupied by another player)`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Simplified 24/7: stay_247 list only changes via !247 command.
|
||||
// Do NOT auto-add/remove channels on bot move.
|
||||
} catch (e) {
|
||||
logger.warn("[247] Bot move handler failed:", e.message);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
if (!newChannelId && oldChannelId && guildId) {
|
||||
try {
|
||||
const cleanOld = cleanId(oldChannelId);
|
||||
const cleanGuild = cleanId(guildId);
|
||||
|
||||
if (this._inStartupGrace) {
|
||||
const bootPlayer = remix.players.playerMap.get(cleanOld);
|
||||
if (bootPlayer && !bootPlayer._destroyed) {
|
||||
logger.voiceState(
|
||||
`[VoiceState] Bot disconnected from ${cleanOld} during startup grace — ` +
|
||||
`player still active, ignoring stale disconnect.`
|
||||
);
|
||||
} else {
|
||||
logger.voiceState(
|
||||
`[VoiceState] Bot disconnected from ${cleanOld} during startup grace — ` +
|
||||
`deferring until grace period ends.`
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (remix.intentionalLeaves.has(cleanOld)) {
|
||||
logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — intentional leave.`);
|
||||
} else if (this._isGuildMoveInProgress(cleanGuild, cleanOld)) {
|
||||
logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — guild move in progress, skipping.`);
|
||||
} else if (this._bootRecoveryActive) {
|
||||
logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — boot recovery active, skipping.`);
|
||||
} else {
|
||||
const set = remix.settingsMgr.getServer(guildId);
|
||||
const mode = set ? get247ChannelMode(set, cleanOld) : "off";
|
||||
const wsInduced = this.isWsReconnectRecent();
|
||||
|
||||
if (mode === "on" || wsInduced) {
|
||||
const reason = wsInduced && mode !== "on"
|
||||
? `WS reconnect detected (${Math.round((Date.now() - this._lastReadyAt) / 1000)}s ago) — treating as transient, scheduling rejoin`
|
||||
: `24/7 mode — scheduling rejoin`;
|
||||
logger.voice247(
|
||||
`[VoiceState] Bot unexpectedly disconnected from ${cleanOld} — ${reason}.`
|
||||
);
|
||||
const discPlayer = remix.players.playerMap.get(cleanOld);
|
||||
if (discPlayer && !discPlayer._destroyed) {
|
||||
remix.players.playerMap.delete(cleanOld);
|
||||
const homeChannel = cleanId(discPlayer._home247Channel ?? "");
|
||||
if (homeChannel && homeChannel !== cleanOld) {
|
||||
remix.players.playerMap.delete(homeChannel);
|
||||
}
|
||||
try { discPlayer.destroy(); } catch(e) { logger.warn("[VoiceState] Player destroy failed:", e?.message); }
|
||||
const pendingScrobble = remix.players._pendingScrobbleTimers?.get(cleanOld);
|
||||
if (pendingScrobble) {
|
||||
clearTimeout(pendingScrobble.timer);
|
||||
remix.players._pendingScrobbleTimers.delete(cleanOld);
|
||||
}
|
||||
}
|
||||
const rejoinDelay = this.T.rejoin247Delay ?? 3_000;
|
||||
setTimeout(() => {
|
||||
this._rejoinChannel(cleanGuild, cleanOld).catch(err => {
|
||||
logger.warn(`[VoiceState] Failed to rejoin ${cleanOld} after disconnect:`, err.message);
|
||||
});
|
||||
}, rejoinDelay);
|
||||
} else {
|
||||
const leavePlayer = remix.players.playerMap.get(cleanOld);
|
||||
if (leavePlayer && !leavePlayer.leaving && !leavePlayer._destroyed) {
|
||||
logger.voiceState(
|
||||
`[VoiceState] Bot disconnected from ${cleanOld} (24/7 mode: ${mode}) — emitting autoleave.`
|
||||
);
|
||||
leavePlayer.emit("autoleave");
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[VoiceState] Bot disconnect handler failed:", e.message);
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
|
||||
export default VoiceStateRouting;
|
||||
export { VoiceStateRouting };
|
||||
@@ -0,0 +1,8 @@
|
||||
/**
|
||||
* @module src/voice/gateway
|
||||
* @description Barrel for the gateway layer: re-exports the GatewayHandler
|
||||
* base class with its applied mixins (VoiceStateRouting, GuildSync,
|
||||
* RejoinManager).
|
||||
*/
|
||||
|
||||
export { GatewayHandler } from "./GatewayHandler.mjs";
|
||||
Reference in new issue
Block a user