mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-23 21:52:45 -05:00
no comment still working on it
This commit is contained in:
1 parent
cea0014e18
commit
e11fca151c
87 files changed
+5710
-10182
No files matched your search
+105
-99
@@ -1,8 +1,4 @@
|
||||
/**
|
||||
* @file CommandHandler.mjs — CommandHandler — registers, resolves, and dispatches slash and prefix commands with option parsing and requirements
|
||||
* @module src.CommandHandler
|
||||
*/
|
||||
|
||||
/** @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";
|
||||
@@ -13,20 +9,16 @@ import { SettingsManager } from "./Settings.mjs";
|
||||
import path from "node:path";
|
||||
import * as fs from "node:fs";
|
||||
|
||||
/**
|
||||
* CommandBuilder class.
|
||||
*/
|
||||
/** @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 = [];
|
||||
/** @type {CommandBuilder[]} */
|
||||
this.subcommands = [];
|
||||
/** @type {Option[]} */
|
||||
this.options = [];
|
||||
/** @type {CommandRequirement[]} */
|
||||
this.requirements = [];
|
||||
this.category = "default";
|
||||
this.examples = [];
|
||||
@@ -34,59 +26,78 @@ export class CommandBuilder {
|
||||
this.uid = Utils.uid();
|
||||
|
||||
this.subcommandError = "Invalid subcommand. Try one of the following options: `$previousCmd <$cmdlist>`";
|
||||
/** @type {CommandBuilder} */
|
||||
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; }
|
||||
}
|
||||
|
||||
/**
|
||||
* CommandRequirement class.
|
||||
*/
|
||||
/** @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 Fluxer permission string (ManageChannels", "ManageGuild")
|
||||
*/
|
||||
/** @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; }
|
||||
}
|
||||
|
||||
/**
|
||||
* Option class.
|
||||
*/
|
||||
/** @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) {
|
||||
@@ -95,6 +106,7 @@ export class Option {
|
||||
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('`, `') + '`';
|
||||
@@ -102,6 +114,7 @@ export class Option {
|
||||
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(' | ') + ' | ...';
|
||||
@@ -110,12 +123,10 @@ export class Option {
|
||||
userRegex = /^<@!?(?<id>\d+)>/;
|
||||
idRegex = /^(?<id>\d+)/;
|
||||
|
||||
/** @type {Function} */
|
||||
/** @type {Function|null} Dynamic default value resolver. */
|
||||
dynamicDefault;
|
||||
|
||||
/**
|
||||
* @param {string} [type="string"] Option value type — "string", "number", "boolean", "channel", "user", or "text"
|
||||
*/
|
||||
/** Create a new Option. @param {string} [type="string"] */
|
||||
constructor(type = "string") {
|
||||
this.name = null;
|
||||
this.description = null;
|
||||
@@ -131,33 +142,39 @@ export class Option {
|
||||
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")));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} i
|
||||
* @param {Client} client
|
||||
* @param {import("@fluxerjs/core").Message} msg
|
||||
* @param {string} [type]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
/** 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":
|
||||
@@ -189,13 +206,7 @@ export class Option {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} i
|
||||
* @param {Client} client
|
||||
* @param {import("@fluxerjs/core").Message} msg
|
||||
* @param {string} [type]
|
||||
* @returns {string|number|boolean}
|
||||
*/
|
||||
/** 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":
|
||||
@@ -227,6 +238,7 @@ export class Option {
|
||||
}
|
||||
}
|
||||
|
||||
/** Generate a type-error message for this option. @returns {string} */
|
||||
get typeError() {
|
||||
if (this.tError) return this.tError;
|
||||
switch (this.type) {
|
||||
@@ -243,49 +255,42 @@ export class Option {
|
||||
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; }
|
||||
}
|
||||
|
||||
/**
|
||||
* Flag class.
|
||||
*/
|
||||
/** @class Flag @description A flag-type option that cannot be text. Extends Option. */
|
||||
export class Flag extends Option {
|
||||
/**
|
||||
* @param {string} [type="string"] Flag value type — anything Option supports except "text"
|
||||
*/
|
||||
/** 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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PrefixManager class.
|
||||
*/
|
||||
/** @class PrefixManager @description Manages per-guild command prefixes (falling back to config or default). */
|
||||
export class PrefixManager {
|
||||
/** @type {SettingsManager} */
|
||||
/** @type {RemoteSettingsManager} */
|
||||
settings;
|
||||
/** @type {string|null} Prefix from config.json — used as fallback when DB has no value */
|
||||
/** @type {string|null} */
|
||||
configPrefix;
|
||||
/**
|
||||
* @param {SettingsManager} settings Settings manager used to look up per-guild prefixes
|
||||
* @param {string|null} [configPrefix=null] Fallback prefix from config.json when no DB value exists
|
||||
*/
|
||||
/** @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 ?? "%";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* HelpHandler class.
|
||||
*/
|
||||
/** @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");
|
||||
@@ -302,35 +307,39 @@ export class HelpHandler {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @type {Function|null} Custom help handler function override. */
|
||||
customHelpHandler = null;
|
||||
|
||||
/**
|
||||
* @param {CommandBuilder[]} commands Loaded command list to generate help pages from
|
||||
*/
|
||||
/** @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);
|
||||
@@ -340,6 +349,7 @@ export class HelpHandler {
|
||||
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);
|
||||
@@ -357,8 +367,10 @@ export class HelpHandler {
|
||||
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(" | ") + "> [...]";
|
||||
@@ -375,6 +387,7 @@ export class HelpHandler {
|
||||
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`;
|
||||
@@ -420,39 +433,33 @@ export class HelpHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* CommandHandler class.
|
||||
*/
|
||||
/** @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 = [];
|
||||
|
||||
/** @type {MessageHandler} */
|
||||
messages;
|
||||
/** @type {Client} */
|
||||
client;
|
||||
/** @type {PrefixManager} */
|
||||
prefixes;
|
||||
/** @type {HelpHandler} */
|
||||
helpHandler;
|
||||
|
||||
commandNames = [];
|
||||
/** @type {CommandBuilder[]} */
|
||||
commands = [];
|
||||
|
||||
/** @type {import('./constants/Locale.mjs').Locale|null} */
|
||||
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 MessageHandler instance to listen for incoming messages on
|
||||
* @param {string} [prefix="%"] Default command prefix used when no per-guild prefix is set
|
||||
*/
|
||||
/** @param {MessageHandler} handler - The message handler instance. @param {string} [prefix="%"] - Default command prefix. */
|
||||
constructor(handler, prefix = "%") {
|
||||
super();
|
||||
this.messages = handler;
|
||||
@@ -466,25 +473,24 @@ export class CommandHandler extends EventEmitter {
|
||||
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; }
|
||||
/** @param {import('./constants/Locale.mjs').Locale} locale */
|
||||
/** Set the locale manager. @param {object} locale */
|
||||
setLocale(locale) { this.locale = locale; }
|
||||
|
||||
/**
|
||||
* Translate a locale key for a given guild.
|
||||
* @param {string} guildId
|
||||
* @param {string} key
|
||||
* @param {Object} [replacements={}]
|
||||
* @returns {string}
|
||||
*/
|
||||
/** 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
|
||||
@@ -492,6 +498,7 @@ export class CommandHandler extends EventEmitter {
|
||||
.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);
|
||||
@@ -501,6 +508,7 @@ export class CommandHandler extends EventEmitter {
|
||||
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();
|
||||
@@ -574,6 +582,7 @@ export class CommandHandler extends EventEmitter {
|
||||
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.");
|
||||
|
||||
@@ -619,6 +628,7 @@ export class CommandHandler extends EventEmitter {
|
||||
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 };
|
||||
@@ -733,9 +743,7 @@ export class CommandHandler extends EventEmitter {
|
||||
return commandRunData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks requirements using fluxerjs permission API.
|
||||
*/
|
||||
/** 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);
|
||||
@@ -781,9 +789,12 @@ export class CommandHandler extends EventEmitter {
|
||||
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);
|
||||
@@ -802,10 +813,12 @@ export class CommandHandler extends EventEmitter {
|
||||
}).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);
|
||||
@@ -818,22 +831,18 @@ export class CommandHandler extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* CommandLoader class.
|
||||
*/
|
||||
/** @class CommandLoader @description Dynamically loads command files from a directory, registers builders, and binds run handlers. */
|
||||
export class CommandLoader {
|
||||
/** @type {CommandHandler} */
|
||||
/** @type {CommandHandler} Reference to the command handler. */
|
||||
commands;
|
||||
/** @type {Map<string, string>} */
|
||||
/** @type {Map<string, string>} Command UID → file path. */
|
||||
commandFiles = new Map();
|
||||
/** @type {Map<string, Function>} */
|
||||
/** @type {Map<string, Function>} Command UID → run function. */
|
||||
runnables = new Map();
|
||||
/** @type {object} Shared context (the bot instance). */
|
||||
context;
|
||||
|
||||
/**
|
||||
* @param {Map<string, CommandBuilder>} commands Map that loaded commands will be registered into
|
||||
* @param {Object} context Shared context object (client, settings, locale, etc.) passed to command factories
|
||||
*/
|
||||
/** @param {CommandHandler} commands @param {object} context - Bot context object. */
|
||||
constructor(commands, context) {
|
||||
this.commands = commands;
|
||||
this.context = context;
|
||||
@@ -865,11 +874,7 @@ export class CommandLoader {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalise both ESM named-export shape and legacy default-export shape.
|
||||
* Named ESM: export const command; export function run; export const exportDef
|
||||
* Legacy CJS: module.exports = { command, run, export }
|
||||
*/
|
||||
/** Normalize a module export to { command, run, exportDef }. @param {object} cData @returns {object} */
|
||||
canonData(cData) {
|
||||
if (cData.command !== undefined) {
|
||||
return {
|
||||
@@ -886,6 +891,7 @@ export class CommandLoader {
|
||||
};
|
||||
}
|
||||
|
||||
/** @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")));
|
||||
|
||||
@@ -0,0 +1,644 @@
|
||||
/** @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. */
|
||||
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
import { WebMOpusMuxer } 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 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");
|
||||
|
||||
/** @extends {EventEmitter} */
|
||||
export class FluxerAudioBridge extends EventEmitter {
|
||||
_conn = null;
|
||||
_stream = null;
|
||||
_encoder = null;
|
||||
_sourceStream = 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");
|
||||
|
||||
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);
|
||||
const durationMs = options.durationMs || 0;
|
||||
|
||||
try {
|
||||
// --- Route 1: trackstream passthrough (no re-encode at all) ---
|
||||
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";
|
||||
}
|
||||
logger.player("[AudioBridge] trackstream format not opus/webm (" + (direct?.format || "?") + "), using loadstream");
|
||||
} catch (e) {
|
||||
logger.warn("[AudioBridge] Trackstream failed, falling back to loadstream: " + e.message);
|
||||
this._playing = true;
|
||||
this._stopped = false;
|
||||
this._startedAt = Date.now();
|
||||
}
|
||||
}
|
||||
|
||||
// --- Route 2: loadstream (PCM -> in-process Opus encode -> WebM) ---
|
||||
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;
|
||||
|
||||
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"));
|
||||
this._stream = await this._remuxOggToWebM(routed.stream);
|
||||
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";
|
||||
}
|
||||
|
||||
// --- Route 3: direct URL fallback (magic sniff: webm passthrough / ogg remux) ---
|
||||
if (trackInfo.url && trackInfo.url.startsWith("http")) {
|
||||
logger.player("[AudioBridge] 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") {
|
||||
this._stream = routed.stream;
|
||||
await conn.play(routed.stream);
|
||||
} else if (routed.kind === "ogg") {
|
||||
this._stream = await this._remuxOggToWebM(routed.stream);
|
||||
await conn.play(this._stream);
|
||||
} else {
|
||||
throw new Error(
|
||||
"[AudioBridge] Direct URL is not WebM/Opus or Ogg/Opus (" + routed.kind + "). " +
|
||||
"Resolve the track through the Lavalink node instead — in-process playback has no FFmpeg decoder."
|
||||
);
|
||||
}
|
||||
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 {
|
||||
// No duration info (radio/live): wait until the WebM stream is fully consumed.
|
||||
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;
|
||||
}
|
||||
waitForMore();
|
||||
};
|
||||
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<WebMOpusMuxer>}
|
||||
* @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));
|
||||
// Wait for the OpusHead so we reject non-Opus OGG early with a clear error.
|
||||
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;
|
||||
return muxer;
|
||||
}
|
||||
|
||||
/**
|
||||
* @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);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} url
|
||||
* @param {object} [headers]
|
||||
* @returns {Promise<object>}
|
||||
* @private
|
||||
*/
|
||||
_httpGetJson(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;
|
||||
|
||||
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).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("error", reject);
|
||||
req.setTimeout(15_000, () => {
|
||||
req.destroy();
|
||||
reject(new Error("trackstream timeout (15s)"));
|
||||
});
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} url
|
||||
* @param {object} [headers]
|
||||
* @param {number} [_redirectCount=0]
|
||||
* @returns {Promise<{stream: Readable, inputFormat: string|null}>}
|
||||
* @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;
|
||||
|
||||
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 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) {
|
||||
let body = "";
|
||||
res.on("data", (chunk) => { body += chunk; });
|
||||
res.on("end", () => {
|
||||
reject(new Error("HTTP " + res.statusCode + " for " + url + ": " + body.substring(0, 300)));
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
logger.player("[AudioBridge] loadstream response: " + res.statusCode + " content-type=" + (res.headers["content-type"] || "?"));
|
||||
resolve({ stream: res, inputFormat: res.headers["content-type"] || null });
|
||||
});
|
||||
|
||||
req.on("error", reject);
|
||||
req.setTimeout(30_000, () => {
|
||||
req.destroy();
|
||||
reject(new Error("loadstream timeout (30s)"));
|
||||
});
|
||||
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 (_) {}
|
||||
}
|
||||
|
||||
if (wasPlaying) {
|
||||
this.emit("stopped");
|
||||
logger.player("[AudioBridge] Playback stopped");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 (_) {}
|
||||
}
|
||||
}
|
||||
this._stream = null;
|
||||
this._encoder = null;
|
||||
this._sourceStream = null;
|
||||
}
|
||||
|
||||
/** Stop playback, release the voice connection, and remove all listeners. */
|
||||
destroy() {
|
||||
this.stop();
|
||||
this._conn = null;
|
||||
this._currentUri = null;
|
||||
this.removeAllListeners();
|
||||
}
|
||||
}
|
||||
+11
-80
@@ -1,19 +1,4 @@
|
||||
/**
|
||||
* @file FluxerListManager.mjs — FluxerListManager — FluxerList bot listing API client for vote checking and server stats
|
||||
* @module src.FluxerListManager
|
||||
*/
|
||||
|
||||
/**
|
||||
* FluxerListManager.mjs — FluxerList API client for voter data queries.
|
||||
*
|
||||
* Features:
|
||||
* - Fetch paginated voter lists for servers and bots
|
||||
* - Bearer token authentication (fl_ prefixed API keys)
|
||||
* - In-memory response caching with configurable TTL
|
||||
* - Graceful error handling (401/403 auth errors, network failures)
|
||||
*
|
||||
* FluxerList API docs: https://fluxerlist.com/api/v1
|
||||
*/
|
||||
/** @module src/FluxerListManager @description FluxerList API integration for fetching server/bot voter lists with caching. */
|
||||
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
import {
|
||||
@@ -23,18 +8,9 @@ import {
|
||||
buildFluxerListUrl,
|
||||
} from "./constants/API.mjs";
|
||||
|
||||
/**
|
||||
* FluxerListManager class.
|
||||
*/
|
||||
/** @class FluxerListManager @description Fetches and caches voter lists from the FluxerList API for servers and bots. */
|
||||
export class FluxerListManager {
|
||||
/**
|
||||
* @param {object} config - The `fluxerlist` section from config.json
|
||||
* @param {string} [config.apiKey] - FluxerList API key (prefixed with fl_)
|
||||
* @param {string} [config.serverId] - Default server ID or slug for voter queries
|
||||
* @param {string} [config.botId] - Default bot ID or slug for voter queries
|
||||
* @param {string} [config.serverSlug] - Server URL slug for website links (e.g. "remix-hq")
|
||||
* @param {string} [config.botSlug] - Bot URL slug for website links (e.g. "remix")
|
||||
*/
|
||||
/** @param {object} [config={}] @param {string} [config.apiKey] @param {string} [config.serverId] @param {string} [config.botId] @param {string} [config.serverSlug] @param {string} [config.botSlug] */
|
||||
constructor(config = {}) {
|
||||
this.apiKey = config?.apiKey ?? "";
|
||||
this.serverId = config?.serverId ?? "";
|
||||
@@ -52,23 +28,12 @@ export class FluxerListManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a cache key from the request parameters.
|
||||
* @param {"server"|"bot"} type
|
||||
* @param {string} id
|
||||
* @param {number} page
|
||||
* @param {number} limit
|
||||
* @returns {string}
|
||||
*/
|
||||
/** @private @param {string} type @param {string} id @param {number} page @param {number} limit @returns {string} */
|
||||
_cacheKey(type, id, page, limit) {
|
||||
return `${type}:${id}:p${page}:l${limit}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a cached response if still fresh.
|
||||
* @param {string} key
|
||||
* @returns {object|null}
|
||||
*/
|
||||
/** @private @param {string} key @returns {object|null} */
|
||||
_getCached(key) {
|
||||
const entry = this._cache.get(key);
|
||||
if (!entry) return null;
|
||||
@@ -79,12 +44,7 @@ export class FluxerListManager {
|
||||
return entry.data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Store a response in the cache with the configured TTL.
|
||||
* @param {string} key
|
||||
* @param {object} data
|
||||
* @param {number} [ttlMs] - Override TTL in milliseconds
|
||||
*/
|
||||
/** @private @param {string} key @param {object} data @param {number} [ttlMs] */
|
||||
_setCached(key, data, ttlMs) {
|
||||
this._cache.set(key, {
|
||||
data,
|
||||
@@ -99,18 +59,7 @@ export class FluxerListManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch the list of voters for a server or bot.
|
||||
*
|
||||
* @param {"server"|"bot"} type - Resource type
|
||||
* @param {string} [id] - Server or bot ID or slug (falls back to config default)
|
||||
* @param {object} [options]
|
||||
* @param {number} [options.page=1] - Page number (1-based)
|
||||
* @param {number} [options.limit=50] - Results per page (max 100)
|
||||
* @param {boolean} [options.skipCache=false] - Bypass cache and fetch fresh data
|
||||
* @returns {Promise<{ total: number, page: number, limit: number, voters: Array<{ username: string, fluxerId: number, votedAt: string }> }>}
|
||||
* @throws {Error} If the API key is missing or the request fails
|
||||
*/
|
||||
/** @async Fetch voters from FluxerList API. @param {"server"|"bot"} type @param {string} [id] @param {object} [options={}] @param {number} [options.page] @param {number} [options.limit] @param {boolean} [options.skipCache] @returns {Promise<object>} @throws {Error} On auth, not-found, or HTTP errors. */
|
||||
async getVoters(type, id, options = {}) {
|
||||
this._assertEnabled();
|
||||
|
||||
@@ -173,36 +122,17 @@ export class FluxerListManager {
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience: fetch voters for a server.
|
||||
* @param {string} [id] - Server ID or slug (falls back to config default)
|
||||
* @param {object} [options] - Same as getVoters options
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
/** @async @param {string} [id] @param {object} [options] @returns {Promise<object>} */
|
||||
async getServerVoters(id, options = {}) {
|
||||
return this.getVoters("server", id, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convenience: fetch voters for a bot.
|
||||
* @param {string} [id] - Bot ID or slug (falls back to config default)
|
||||
* @param {object} [options] - Same as getVoters options
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
/** @async @param {string} [id] @param {object} [options] @returns {Promise<object>} */
|
||||
async getBotVoters(id, options = {}) {
|
||||
return this.getVoters("bot", id, options);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch ALL voters across all pages for a resource.
|
||||
* Use with caution on resources with many voters — this makes multiple API calls.
|
||||
*
|
||||
* @param {"server"|"bot"} type
|
||||
* @param {string} [id] - Resource ID or slug
|
||||
* @param {object} [options]
|
||||
* @param {number} [options.limit=100] - Results per page (uses max to minimize calls)
|
||||
* @returns {Promise<Array<{ username: string, fluxerId: number, votedAt: string }>>}
|
||||
*/
|
||||
/** @async Fetch all pages of voters for a resource. @param {"server"|"bot"} type @param {string} [id] @param {object} [options] @returns {Promise<Array>} */
|
||||
async getAllVoters(type, id, options = {}) {
|
||||
this._assertEnabled();
|
||||
|
||||
@@ -223,6 +153,7 @@ export class FluxerListManager {
|
||||
return allVoters;
|
||||
}
|
||||
|
||||
/** @private @throws {Error} If not configured. */
|
||||
_assertEnabled() {
|
||||
if (!this.enabled) {
|
||||
throw new Error("FluxerList integration is not configured (missing apiKey in config.json).");
|
||||
|
||||
+150
-323
@@ -1,8 +1,4 @@
|
||||
/**
|
||||
* @file GatewayHandler.mjs — GatewayHandler — processes raw WebSocket events for voice state tracking, 24/7 recovery, and guild lifecycle
|
||||
* @module src.GatewayHandler
|
||||
*/
|
||||
|
||||
/** @module src/GatewayHandler @description Handles all Discord gateway events relevant to voice state tracking, 24/7 mode, boot recovery, presence rotation, and permission checks. */
|
||||
import { Events, GatewayOpcodes } from "@fluxerjs/core";
|
||||
import { getVoiceManager } from "@fluxerjs/voice";
|
||||
import { logger, _wsErrorCooldown } from "./constants/Logger.mjs";
|
||||
@@ -13,16 +9,11 @@ import { REQUIRED_BOT_PERMISSIONS } from "./MessageHandler.mjs";
|
||||
import { cleanId } from "./Utils.mjs";
|
||||
import { iterateVoiceStates, hasHumansInChannel, getChannelsWithHumans } from "./constants/VoiceStateResolver.mjs";
|
||||
|
||||
/**
|
||||
* GatewayHandler — manages raw WebSocket gateway events, voice-state tracking,
|
||||
* presence rotation, and high-level Fluxer event handlers (GuildCreate,
|
||||
* GuildDelete, VoiceStateUpdate).
|
||||
*
|
||||
* Extracted from index.mjs to reduce the Remix constructor footprint.
|
||||
*/
|
||||
/** @class GatewayHandler @description Handles all Discord 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. */
|
||||
export class GatewayHandler {
|
||||
/**
|
||||
* @param {import('../../index.mjs').Remix} remix The running bot instance.
|
||||
* Create a new GatewayHandler.
|
||||
* @param {import('../index.mjs').Remix} remix - The bot context.
|
||||
*/
|
||||
constructor(remix) {
|
||||
this.remix = remix;
|
||||
@@ -40,31 +31,21 @@ export class GatewayHandler {
|
||||
this.presenceTimer = null;
|
||||
this.presenceIndex = 0;
|
||||
|
||||
/** @type {Map<string, {channelId, guildId}>} guildId:userId → state */
|
||||
this._prevVoiceState = new Map();
|
||||
|
||||
/** @type {Map<string, {guild, timer}>} guildId → deferred cleanup data */
|
||||
this._deferredGuildDeletes = new Map();
|
||||
/** @type {number} How long to defer GuildDelete processing during startup (ms) */
|
||||
this._startupDeleteGraceMs = 15_000;
|
||||
/** @type {boolean} Whether we're still in the startup grace period */
|
||||
this._inStartupGrace = true;
|
||||
/** @type {number} Counter for deferred deletions (used for batch summary log) */
|
||||
this._deferredDeleteCount = 0;
|
||||
|
||||
/** @type {number} Timestamp of the last Events.Ready fire (initial + reconnects). 0 = never. */
|
||||
this._lastReadyAt = 0;
|
||||
/** @type {number} Window after a Ready event during which voice disconnects are treated as WS-induced (ms). */
|
||||
this._wsReconnectGraceMs = 30_000;
|
||||
/** @type {number} How recently another player in the same guild must have connected to count as move evidence, vs. a long-stable second 24/7 channel (ms). */
|
||||
this._moveEvidenceWindowMs = 10_000;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a voice disconnect was likely caused by a recent WS reconnect
|
||||
* rather than a user-initiated leave. Uses the time since the last Events.Ready
|
||||
* fire as the signal — if the bot just re-identified, any voice session
|
||||
* invalidation is almost certainly WS-induced.
|
||||
* Check whether a WebSocket reconnect happened recently (within 30s).
|
||||
* Used to treat transient disconnects as non-24/7-requiring.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isWsReconnectRecent() {
|
||||
@@ -72,22 +53,21 @@ export class GatewayHandler {
|
||||
return Date.now() - this._lastReadyAt < this._wsReconnectGraceMs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a composite key for bots in the observedVoiceBots map.
|
||||
* Bots can be in multiple guilds so we namespace by guildId.
|
||||
*/
|
||||
/** @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)) {
|
||||
@@ -107,12 +87,12 @@ export class GatewayHandler {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if the bot has all required permissions in a newly joined guild.
|
||||
* If critical permissions are missing, log a warning and attempt to send
|
||||
* a notification to the guild's system channel (or first text channel).
|
||||
*
|
||||
* @param {import('@fluxerjs/core').Guild} guild
|
||||
* @param {string} guildId
|
||||
* 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;
|
||||
@@ -175,8 +155,8 @@ export class GatewayHandler {
|
||||
}
|
||||
|
||||
/**
|
||||
* Seed observedVoiceUsers / observedVoiceBots from all cached guild voice
|
||||
* states. Called once on Ready after the guild cache is populated.
|
||||
* Seed the voice state cache from VoiceManager or guild cache on startup.
|
||||
* @private
|
||||
*/
|
||||
seedVoiceStatesFromGuilds() {
|
||||
const { remix } = this;
|
||||
@@ -229,19 +209,11 @@ export class GatewayHandler {
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-read the guild's voice_states cache and update observedVoiceUsers
|
||||
* for any human users found in the specified channel.
|
||||
*
|
||||
* This is crucial after bot recovery: when the bot restarts and rejoins a
|
||||
* voice channel, the initial `seedVoiceStatesFromGuilds()` may have run
|
||||
* before the guild cache was fully populated, or before the bot received
|
||||
* VOICE_STATE_UPDATE events for users already in the channel. Calling
|
||||
* this after a player joins ensures the bot knows about humans who were
|
||||
* already present.
|
||||
*
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
* @returns {number} Number of human users found in the channel.
|
||||
* 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;
|
||||
@@ -370,13 +342,7 @@ export class GatewayHandler {
|
||||
return humansFound;
|
||||
}
|
||||
|
||||
/**
|
||||
* Attach a raw "message" listener to the shard-0 WebSocket so we can
|
||||
* process gateway opcodes (READY, GUILD_CREATE, VOICE_STATE_UPDATE, etc.)
|
||||
* before @fluxerjs/core emits its high-level events.
|
||||
*
|
||||
* Safe to call on every reconnect — will detach from the old socket first.
|
||||
*/
|
||||
/** Attach a raw WebSocket listener to cache VOICE_SERVER_UPDATE events. @private */
|
||||
attachRawListener() {
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
@@ -500,6 +466,7 @@ export class GatewayHandler {
|
||||
} 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;
|
||||
|
||||
@@ -549,8 +516,8 @@ export class GatewayHandler {
|
||||
}
|
||||
|
||||
/**
|
||||
* Register all high-level Fluxer event listeners on the Fluxer client.
|
||||
* Call once during bot startup.
|
||||
* Register all gateway event handlers (GuildCreate, GuildDelete, VoiceStateUpdate, VoiceStatesSync).
|
||||
* Called once during bot initialisation.
|
||||
*/
|
||||
setupEventHandlers() {
|
||||
const { remix } = this;
|
||||
@@ -656,9 +623,10 @@ export class GatewayHandler {
|
||||
}
|
||||
|
||||
/**
|
||||
* Main voice state update dispatcher — calls focused sub-handlers.
|
||||
* Parses the raw VOICE_STATE_UPDATE payload, computes the old channel,
|
||||
* then delegates to specialised methods.
|
||||
* 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;
|
||||
@@ -697,15 +665,7 @@ export class GatewayHandler {
|
||||
this._handleBotVoiceChange(player, playerGuildId, homeChannelId, oldChannelId, newChannelId, vsuGuildId, data);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle bulk voice state sync from GUILD_CREATE or READY.
|
||||
* Populates VoiceStateCache with all users currently in voice channels
|
||||
* for a guild. This is the PRIMARY way the bot learns about users who
|
||||
* were already in voice when the bot started (before it receives any
|
||||
* individual VOICE_STATE_UPDATE events).
|
||||
*
|
||||
* @param {{ guildId: string, voiceStates: Array<{user_id: string, channel_id: string|null, member?: {user?: {bot?: boolean}}}> }} data
|
||||
*/
|
||||
/** 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;
|
||||
@@ -739,10 +699,7 @@ export class GatewayHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the voice state cache when users move between channels.
|
||||
* Adds users to the cache on join, removes them on leave.
|
||||
*/
|
||||
/** @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;
|
||||
|
||||
@@ -757,10 +714,7 @@ export class GatewayHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Update the previous state map (LRU eviction).
|
||||
* Maintains a bounded map of previous voice states for computing oldChannelId.
|
||||
*/
|
||||
/** @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;
|
||||
@@ -795,12 +749,7 @@ export class GatewayHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Find which player is affected by this voice state change.
|
||||
* Checks both old and new channels for an existing player.
|
||||
*
|
||||
* @returns {{ player: object|null, playerGuildId: string|null, homeChannelId: string|null }}
|
||||
*/
|
||||
/** @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;
|
||||
|
||||
@@ -825,10 +774,7 @@ export class GatewayHandler {
|
||||
return { player: null, playerGuildId: null, homeChannelId: null };
|
||||
}
|
||||
|
||||
/**
|
||||
* Manage inactivity timers when humans join/leave voice channels.
|
||||
* Also handles dashboard updates for human voice state changes.
|
||||
*/
|
||||
/** @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;
|
||||
@@ -910,8 +856,16 @@ export class GatewayHandler {
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the bot being moved to a different channel or disconnected.
|
||||
* Covers 24/7 re-key on move and auto-rejoin / autoleave on disconnect.
|
||||
* 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;
|
||||
@@ -919,175 +873,86 @@ export class GatewayHandler {
|
||||
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 cleanNew = cleanId(newChannelId);
|
||||
const cleanOld = cleanId(oldChannelId);
|
||||
const moveSet = remix.settingsMgr.getServer(guildId);
|
||||
const moveRaw = moveSet?.get("stay_247");
|
||||
const saved247Channels = (!moveRaw || moveRaw === "none")
|
||||
? []
|
||||
: Array.isArray(moveRaw)
|
||||
? moveRaw.map(id => cleanId(id)).filter(id => id.length >= 15)
|
||||
: [cleanId(moveRaw)].filter(id => id.length >= 15);
|
||||
|
||||
if (saved247Channels.length > 1) {
|
||||
logger.voice247(
|
||||
`[247] Ignoring move-style bot voice update ${cleanOld} → ${cleanNew} ` +
|
||||
`because guild ${guildId} already has multiple saved 24/7 channels ` +
|
||||
`[${saved247Channels.join(", ")}]`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const existingPlayer = remix.players.playerMap.get(cleanOld);
|
||||
const newChannelAlreadySaved = (() => {
|
||||
// Check if old channel is a saved 24/7 channel
|
||||
const oldIs247 = (() => {
|
||||
try {
|
||||
const set = remix.settingsMgr.getServer(guildId);
|
||||
const raw = set?.get("stay_247");
|
||||
if (!raw || raw === "none") return false;
|
||||
const saved = Array.isArray(raw)
|
||||
? raw.map(id => cleanId(id)).filter(id => id.length >= 15)
|
||||
: [cleanId(raw)].filter(id => id.length >= 15);
|
||||
return saved.includes(cleanNew);
|
||||
} catch (_) {
|
||||
return false;
|
||||
}
|
||||
return get247ChannelMode(set, cleanOld) === "on";
|
||||
} catch (_) { return false; }
|
||||
})();
|
||||
const newChannelPendingSpawn =
|
||||
remix.players?._pendingJoins?.has?.(cleanNew) ||
|
||||
false;
|
||||
const targetChannel = client.channels.get(cleanNew)
|
||||
?? client.channels.get?.(cleanNew)
|
||||
?? null;
|
||||
const targetGuildId = cleanId(targetChannel?.guildId ?? targetChannel?.guild?.id ?? guildId ?? "");
|
||||
const playerGuildIdLocal = cleanId(existingPlayer?._guildId ?? "");
|
||||
const guildPlayers = [...remix.players.playerMap.entries()].filter(([, p]) =>
|
||||
cleanId(p?._guildId ?? "") === cleanId(guildId ?? "")
|
||||
);
|
||||
const guildIsAmbiguous = guildPlayers.length > 1;
|
||||
|
||||
let rekeyed = false;
|
||||
if (existingPlayer && cleanNew !== cleanOld) {
|
||||
if (newChannelAlreadySaved || newChannelPendingSpawn) {
|
||||
logger.voice247(
|
||||
`[247] Keeping both channels ${cleanOld} and ${cleanNew} ` +
|
||||
`(saved=${newChannelAlreadySaved} pending=${newChannelPendingSpawn})`
|
||||
);
|
||||
rekeyed = false;
|
||||
} else
|
||||
if (guildIsAmbiguous) {
|
||||
const playerAtNewKey = remix.players.playerMap.get(cleanNew);
|
||||
if (playerAtNewKey && playerAtNewKey !== existingPlayer) {
|
||||
existingPlayer._channelId = cleanNew;
|
||||
existingPlayer._home247Channel = cleanNew;
|
||||
if (targetGuildId) existingPlayer._guildId = targetGuildId;
|
||||
rekeyed = false;
|
||||
logger.voice247(
|
||||
`[247] Updated player channel ${cleanOld} → ${cleanNew} ` +
|
||||
`(guild ${guildId} has ${guildPlayers.length} active players, ` +
|
||||
`new key occupied by another player — skipped re-key)`
|
||||
);
|
||||
} else {
|
||||
remix.players.playerMap.delete(cleanOld);
|
||||
remix.players.playerMap.set(cleanNew, existingPlayer);
|
||||
existingPlayer._channelId = cleanNew;
|
||||
existingPlayer._home247Channel = cleanNew;
|
||||
if (targetGuildId) existingPlayer._guildId = targetGuildId;
|
||||
rekeyed = true;
|
||||
logger.voice247(
|
||||
`[247] Re-keyed playerMap ${cleanOld} → ${cleanNew} ` +
|
||||
`(guild ${guildId} has ${guildPlayers.length} active players)`
|
||||
);
|
||||
}
|
||||
} else if (playerGuildIdLocal && targetGuildId && playerGuildIdLocal !== targetGuildId) {
|
||||
if (!existingPlayer) {
|
||||
logger.voice247(
|
||||
`[247] Stale cross-guild move ${cleanOld} → ${cleanNew} ` +
|
||||
`(no player in playerMap for old channel — updating bot state only)`
|
||||
);
|
||||
} else {
|
||||
const vsuGuildIdClean = cleanId(guildId ?? "");
|
||||
if (vsuGuildIdClean && targetGuildId === vsuGuildIdClean) {
|
||||
existingPlayer._guildId = targetGuildId;
|
||||
existingPlayer._channelId = cleanNew;
|
||||
existingPlayer._home247Channel = cleanNew;
|
||||
remix.players.playerMap.delete(cleanOld);
|
||||
remix.players.playerMap.set(cleanNew, existingPlayer);
|
||||
rekeyed = true;
|
||||
logger.voice247(
|
||||
`[247] Fixed stale guild during recovery: re-keyed ${cleanOld} → ${cleanNew} ` +
|
||||
`(playerGuild ${playerGuildIdLocal} → ${targetGuildId})`
|
||||
);
|
||||
} else {
|
||||
logger.warn(
|
||||
`[247] Refused cross-guild re-key ${cleanOld} → ${cleanNew} ` +
|
||||
`(playerGuild=${playerGuildIdLocal} targetGuild=${targetGuildId})`
|
||||
);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// 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;
|
||||
rekeyed = true;
|
||||
logger.voice247(`[247] Re-keyed playerMap ${cleanOld} → ${cleanNew}`);
|
||||
}
|
||||
}
|
||||
|
||||
const set = remix.settingsMgr.getServer(guildId);
|
||||
const raw = set?.get("stay_247");
|
||||
if ((rekeyed || existingPlayer) && raw && raw !== "none") {
|
||||
const channels = Array.isArray(raw)
|
||||
? new Set(raw.map(id => cleanId(id)).filter(id => id.length >= 15))
|
||||
: new Set();
|
||||
if (channels.has(cleanOld) && cleanOld !== cleanNew && cleanNew.length >= 15) {
|
||||
if (channels.has(cleanNew) || newChannelAlreadySaved || newChannelPendingSpawn) {
|
||||
logger.voice247(
|
||||
`[247] Preserved stay_247 channels ${cleanOld} and ${cleanNew} ` +
|
||||
`(saved=${channels.has(cleanNew) || newChannelAlreadySaved} pending=${newChannelPendingSpawn})`
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
const currentGuildPlayers = [...remix.players.playerMap.values()].filter(p =>
|
||||
cleanId(p?._guildId ?? "") === cleanId(guildId ?? "")
|
||||
} else {
|
||||
logger.voice247(
|
||||
`[247] Skipped re-key ${cleanOld} → ${cleanNew} (new key occupied by another player)`
|
||||
);
|
||||
if (currentGuildPlayers.length > 1) {
|
||||
if (!channels.has(cleanNew)) {
|
||||
channels.add(cleanNew);
|
||||
set.set("stay_247", [...channels]);
|
||||
const modes2 = set.get("stay_247_modes");
|
||||
if (modes2 && typeof modes2 === "object" && !Array.isArray(modes2) && !modes2[cleanNew]) {
|
||||
modes2[cleanNew] = modes2[cleanOld] ?? "auto";
|
||||
set.set("stay_247_modes", modes2);
|
||||
}
|
||||
logger.voice247(
|
||||
`[247] Added stay_247 channel ${cleanNew} (kept ${cleanOld}) — guild has ${currentGuildPlayers.length} active players`
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
channels.delete(cleanOld);
|
||||
channels.add(cleanNew);
|
||||
set.set("stay_247", [...channels]);
|
||||
|
||||
const modes = set.get("stay_247_modes");
|
||||
if (modes && typeof modes === "object" && !Array.isArray(modes)) {
|
||||
if (modes[cleanOld] && !modes[cleanNew]) {
|
||||
modes[cleanNew] = modes[cleanOld];
|
||||
}
|
||||
delete modes[cleanOld];
|
||||
set.set("stay_247_modes", modes);
|
||||
}
|
||||
|
||||
logger.voice247(`[247] Updated stay_247: ${cleanOld} → ${cleanNew}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 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] Failed to auto-save channel:", e.message);
|
||||
logger.warn("[247] Bot move handler failed:", e.message);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1115,8 +980,6 @@ export class GatewayHandler {
|
||||
|
||||
if (remix.intentionalLeaves.has(cleanOld)) {
|
||||
logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — intentional leave.`);
|
||||
} else if (remix.revoice?._intentionalDisconnects?.has?.(cleanOld)) {
|
||||
logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — intentional (revoice).`);
|
||||
} else if (this._isGuildMoveInProgress(cleanGuild, cleanOld)) {
|
||||
logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — guild move in progress, skipping.`);
|
||||
} else if (this._bootRecoveryActive) {
|
||||
@@ -1126,10 +989,10 @@ export class GatewayHandler {
|
||||
const mode = set ? get247ChannelMode(set, cleanOld) : "off";
|
||||
const wsInduced = this.isWsReconnectRecent();
|
||||
|
||||
if (mode === "auto" || wsInduced) {
|
||||
const reason = wsInduced && mode !== "auto"
|
||||
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 auto mode — cleaning up and scheduling rejoin`;
|
||||
: `24/7 mode — scheduling rejoin`;
|
||||
logger.voice247(
|
||||
`[VoiceState] Bot unexpectedly disconnected from ${cleanOld} — ${reason}.`
|
||||
);
|
||||
@@ -1169,31 +1032,29 @@ export class GatewayHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/** @type {Set<string>} Channel IDs currently being rejoined (dedup guard) */
|
||||
/** @private @type {Set<string>} @description Channel IDs currently being rejoined (duplicate guard). */
|
||||
_rejoinInProgress = new Set();
|
||||
|
||||
/** @type {Map<string, number>} Channel IDs with retry attempt counts */
|
||||
/** @private @type {Map<string, number>} @description Channel ID → retry count for exponential backoff. */
|
||||
_rejoinAttempts = new Map();
|
||||
|
||||
/** @type {boolean} Whether boot recovery (rejoin247Channels) is currently running */
|
||||
/** @private @type {boolean} @description Whether boot recovery is actively rejoining 24/7 channels. */
|
||||
_bootRecoveryActive = false;
|
||||
|
||||
/** @type {number} Maximum number of rejoin retry attempts */
|
||||
/** @type {number} @description Maximum number of rejoin retry attempts per channel. */
|
||||
static MAX_REJOIN_RETRIES = 3;
|
||||
|
||||
/**
|
||||
* Shared rejoin attempt logic with exponential backoff retry.
|
||||
* Used by both _rejoinChannel (disconnect recovery) and
|
||||
* rejoin247Channels (boot recovery).
|
||||
*
|
||||
* @param {string} channelId - Clean channel ID
|
||||
* @param {string} guildId - Clean guild ID
|
||||
* @param {number} [maxRetries=3] Maximum retry attempts
|
||||
* @param {number} [baseDelay=5000] Base delay for exponential backoff (ms)
|
||||
* @param {string} [context="Rejoin"] Log context prefix
|
||||
* @returns {Promise<object|null>} The spawned player, or null on failure
|
||||
* 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") {
|
||||
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);
|
||||
@@ -1206,8 +1067,8 @@ export class GatewayHandler {
|
||||
} catch (err) {
|
||||
const errMsg = err?.message ?? String(err);
|
||||
const isTrackTimeout = errMsg.includes("track publication timed out")
|
||||
|| errMsg.includes("publishToRoom failed")
|
||||
|| errMsg.includes("Failed to create MediaPlayer")
|
||||
|| errMsg.includes("lavalink player create failed")
|
||||
|| errMsg.includes("Failed to create audio player")
|
||||
|| errMsg.includes("internal error");
|
||||
|
||||
if (isTrackTimeout && attempt < maxRetries) {
|
||||
@@ -1231,14 +1092,12 @@ export class GatewayHandler {
|
||||
}
|
||||
|
||||
/**
|
||||
* Rejoin a voice channel after an unexpected disconnect.
|
||||
* Used by the %247 auto mode to automatically reconnect.
|
||||
*
|
||||
* Includes deduplication (prevents concurrent rejoin for the same channel)
|
||||
* and delegates retry logic to _attemptRejoin.
|
||||
*
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
* 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;
|
||||
@@ -1268,12 +1127,6 @@ export class GatewayHandler {
|
||||
return;
|
||||
}
|
||||
|
||||
if (remix.revoice?._intentionalDisconnects?.has?.(cleanChannelId)) {
|
||||
logger.voice247(`[Rejoin] Channel ${cleanChannelId} was intentionally left (revoice) — skipping.`);
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
return;
|
||||
}
|
||||
|
||||
const channel = remix.client?.channels?.get?.(cleanChannelId);
|
||||
if (!channel) {
|
||||
logger.voice247(`[Rejoin] Channel ${cleanChannelId} no longer exists — skipping.`);
|
||||
@@ -1301,16 +1154,7 @@ export class GatewayHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a guild-move operation is currently in progress for the
|
||||
* given guild and old channel. During a move, Fluxer sends two
|
||||
* VoiceStateUpdate events (leave old + join new) in rapid succession;
|
||||
* the "leave" should NOT be treated as an unexpected disconnect.
|
||||
*
|
||||
* @param {string} guildId The guild ID to check
|
||||
* @param {string} oldChannelId The channel the bot appears to have left
|
||||
* @returns {boolean} True if a move is in progress and the disconnect should be ignored
|
||||
*/
|
||||
/** @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);
|
||||
@@ -1346,21 +1190,7 @@ export class GatewayHandler {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Invoke after the bot has connected and Moonlink has been initialised.
|
||||
* Seeds voice states, attaches raw WS listener, kicks off presence rotation,
|
||||
* and rejoins 24/7 channels with staggered delays to avoid overwhelming
|
||||
* the LiveKit server.
|
||||
*/
|
||||
/**
|
||||
* Paginate /users/@me/guilds via REST and add any guilds that Fluxer
|
||||
* didn't cache (because their GUILD_CREATE was never received) as
|
||||
* lightweight stubs into client.guilds. This ensures guild count and
|
||||
* any guild-map lookups reflect the real server count.
|
||||
*
|
||||
* Stubs only carry { id, name } — enough for counting and ID lookups.
|
||||
* They are skipped if a full guild object is already in the cache.
|
||||
*/
|
||||
/** @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;
|
||||
@@ -1428,11 +1258,7 @@ export class GatewayHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Try to get the Guild class from @fluxerjs/core so we can create proper
|
||||
* Guild instances for stubs instead of plain objects.
|
||||
* Returns null if the class can't be resolved.
|
||||
*/
|
||||
/** @private @returns {Function|null} The Guild constructor class. */
|
||||
_getGuildClass() {
|
||||
if (this._GuildClass) return this._GuildClass;
|
||||
try {
|
||||
@@ -1448,6 +1274,11 @@ export class GatewayHandler {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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();
|
||||
@@ -1478,14 +1309,10 @@ export class GatewayHandler {
|
||||
}
|
||||
|
||||
/**
|
||||
* Rejoin all 24/7 channels after boot with staggered delays.
|
||||
*
|
||||
* Both %247 auto and %247 on channels are rejoined because:
|
||||
* %247 auto: always stays in voice (disconnect + reboot)
|
||||
* %247 on: only on reboot, not on disconnect
|
||||
*
|
||||
* Channels are rejoined one at a time with a delay between each to
|
||||
* avoid overwhelming the LiveKit server with concurrent track publications.
|
||||
* 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;
|
||||
@@ -1503,7 +1330,7 @@ export class GatewayHandler {
|
||||
|
||||
for (const channelId of channels) {
|
||||
const mode = get247ChannelMode(serverSettings, channelId);
|
||||
if (mode === "auto" || mode === "on") {
|
||||
if (mode === "on") {
|
||||
channelsToRejoin.push({ guildId, channelId, mode });
|
||||
}
|
||||
}
|
||||
@@ -1603,14 +1430,14 @@ export class GatewayHandler {
|
||||
`[BootRecovery] Boot recovery complete. ${channelsToRejoin.length} channel(s) processed.`
|
||||
);
|
||||
|
||||
setTimeout(() => { this._bootRecoveryActive = false; }, 15_000);
|
||||
this._bootRecoveryActive = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Perform the actual cleanup for a guild that the bot was removed from.
|
||||
* Extracted from the GuildDelete handler so it can be called after the
|
||||
* startup grace period expires.
|
||||
* @param {string} guildId
|
||||
* 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;
|
||||
|
||||
+262
-325
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,599 @@
|
||||
/** @module src/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 { EventEmitter } from "node:events";
|
||||
import { Events } from "@fluxerjs/core";
|
||||
import { getVoiceManager } from "@fluxerjs/voice";
|
||||
|
||||
/** @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 {
|
||||
/** @type {LavalinkClientManager} @description The underlying lavalink-client manager instance. */
|
||||
lavalink = null;
|
||||
/** @type {string|null} @description Current Lavalink session ID. */
|
||||
_sessionId = null;
|
||||
/** @type {object} @description Bot client reference. */
|
||||
_client = null;
|
||||
/** @type {object} @description Node configuration (id, host, port, password, secure). */
|
||||
_nodeCfg = null;
|
||||
/** @type {boolean} @description Whether a node is currently connected. */
|
||||
_nodeConnected = false;
|
||||
/** @private @type {Set<string>} @description Guild IDs with pending leave requests. */
|
||||
_pendingLeaves = new Set();
|
||||
/** @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. */
|
||||
constructor(nodeCfg, client, user) {
|
||||
super();
|
||||
this.setMaxListeners(50);
|
||||
this._nodeCfg = nodeCfg;
|
||||
this._client = client;
|
||||
const requestSignalTimeoutMS = Number(nodeCfg.requestTimeout ?? 60_000);
|
||||
|
||||
this.lavalink = new LavalinkClientManager({
|
||||
nodes: [
|
||||
{
|
||||
id: nodeCfg.id ?? "main",
|
||||
host: nodeCfg.host ?? "localhost",
|
||||
port: nodeCfg.port ?? 2333,
|
||||
authorization:nodeCfg.password ?? "youshallnotpass",
|
||||
secure: nodeCfg.secure ?? false,
|
||||
nodeType: NodeType.NodeLink,
|
||||
requestSignalTimeoutMS: Number.isFinite(requestSignalTimeoutMS) ? requestSignalTimeoutMS : 60_000,
|
||||
},
|
||||
],
|
||||
client: {
|
||||
id: user?.id ?? "0",
|
||||
username: user?.username ?? "bot",
|
||||
},
|
||||
sendToShard: (guildId, payload) => {
|
||||
this._sendPayload(guildId, payload);
|
||||
},
|
||||
autoSkip: true,
|
||||
playerOptions: {
|
||||
volumeDecrementer: 1,
|
||||
},
|
||||
});
|
||||
|
||||
this._setupVoiceForwarding(client);
|
||||
this._setupLavalinkEvents();
|
||||
}
|
||||
|
||||
/** @private Set up internal Lavalink event forwarding (node connect/disconnect/error, track events). */
|
||||
_setupLavalinkEvents() {
|
||||
|
||||
const nodeMgr = this.lavalink.nodeManager ?? this.lavalink.nodes;
|
||||
if (nodeMgr) {
|
||||
try {
|
||||
nodeMgr.on("error", (node, err) => {
|
||||
logger.error("[Lavalink] NodeManager error:", node?.id, err?.message ?? err);
|
||||
});
|
||||
nodeMgr.on("connect", (node) => {
|
||||
this._nodeConnected = true;
|
||||
logger.lavalink("[Lavalink] Node connected (nodeManager): " + node.id);
|
||||
});
|
||||
nodeMgr.on("disconnect", (node, reason) => {
|
||||
this._nodeConnected = false;
|
||||
logger.warn("[Lavalink] Node disconnected (nodeManager):", node?.id, reason);
|
||||
});
|
||||
nodeMgr.on("reconnect", (node) => {
|
||||
this._nodeConnected = true;
|
||||
logger.lavalink("[Lavalink] Node reconnecting (nodeManager): " + node.id);
|
||||
});
|
||||
} catch (e) {
|
||||
logger.warn("[Lavalink] nodeManager event setup error:", e?.message);
|
||||
}
|
||||
} else {
|
||||
logger.warn("[Lavalink] Neither nodeManager nor nodes found on lavalink-client instance");
|
||||
}
|
||||
|
||||
this.lavalink.on("nodeConnect", (node) => {
|
||||
this._nodeConnected = true;
|
||||
logger.lavalink("[Lavalink] Node connected (manager): " + node.id);
|
||||
});
|
||||
|
||||
this.lavalink.on("nodeReconnect", (node) => {
|
||||
this._nodeConnected = true;
|
||||
logger.lavalink("[Lavalink] Node reconnecting (manager): " + node.id);
|
||||
});
|
||||
|
||||
this.lavalink.on("nodeDisconnect", (node, reason) => {
|
||||
this._nodeConnected = false;
|
||||
logger.warn("[Lavalink] Node disconnected (manager):", node.id, reason);
|
||||
});
|
||||
|
||||
this.lavalink.on("nodeError", (node, err) => {
|
||||
logger.error("[Lavalink] Node error (manager):", node.id, err?.message ?? err);
|
||||
});
|
||||
|
||||
|
||||
this.lavalink.on("playerCreate", (player) => {
|
||||
logger.lavalink(`[Lavalink] Player created: ${player.guildId}`);
|
||||
});
|
||||
|
||||
this.lavalink.on("playerDestroy", (player) => {
|
||||
logger.lavalink(`[Lavalink] Player destroyed: ${player.guildId}`);
|
||||
});
|
||||
|
||||
this.lavalink.on("trackStart", (player, track) => {
|
||||
this.emit("trackStart", player, track);
|
||||
});
|
||||
|
||||
this.lavalink.on("trackEnd", (player, track, payload) => {
|
||||
const reason = payload?.reason ?? "FINISHED";
|
||||
this.emit("trackEnd", player, track, reason);
|
||||
});
|
||||
|
||||
this.lavalink.on("queueEnd", (player) => {
|
||||
this.emit("queueEnd", player);
|
||||
});
|
||||
|
||||
this.lavalink.on("playerDisconnect", (player) => {
|
||||
this.emit("playerDisconnected", player);
|
||||
});
|
||||
|
||||
this.lavalink.on("playerMove", (player, oldChannelId, newChannelId) => {
|
||||
logger.lavalink(
|
||||
`[Lavalink] Player moved in ${player.guildId}: ${oldChannelId} → ${newChannelId}`
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
/** @private Intercept and forward gateway payloads to Lavalink. Blocks op4 voice joins (handled by vm.join). */
|
||||
_sendPayload(guildId, payload) {
|
||||
try {
|
||||
if (payload?.op === 4 && payload?.d) {
|
||||
const d = payload.d;
|
||||
const channelId = d.channel_id;
|
||||
|
||||
if (channelId) {
|
||||
logger.lavalink(
|
||||
"[LavalinkManager] sendToShard op4 join BLOCKED — voice joins go through vm.join() in Player.join()"
|
||||
);
|
||||
return;
|
||||
} else {
|
||||
const guildKey = String(guildId);
|
||||
if (!this._pendingLeaves.has(guildKey)) {
|
||||
logger.lavalink("[LavalinkManager] sendToShard op4 leave BLOCKED — no explicit leave request for guild " + guildKey);
|
||||
return;
|
||||
}
|
||||
this._pendingLeaves.delete(guildKey);
|
||||
|
||||
const vm = getVoiceManager(this._client);
|
||||
if (vm) {
|
||||
logger.lavalink("[LavalinkManager] sendToShard op4: routing voice leave via vm.leaveChannel");
|
||||
try {
|
||||
const player = this.lavalink?.players?.get?.(guildKey);
|
||||
const chId = player?.voiceChannelId;
|
||||
if (chId) {
|
||||
vm.leaveChannel(chId);
|
||||
}
|
||||
return;
|
||||
} catch (e) {
|
||||
logger.warn("[LavalinkManager] vm.leaveChannel failed:", e.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof this._client?.ws?.send === "function") {
|
||||
this._client.ws.send(0, payload);
|
||||
return;
|
||||
}
|
||||
|
||||
const shard = this._client?.ws?.shards?.get?.(0);
|
||||
if (!shard) {
|
||||
logger.warn("[LavalinkManager] No WebSocket shard available");
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof shard.send === "function") {
|
||||
shard.send(payload);
|
||||
} else if (shard.ws?.send) {
|
||||
shard.ws.send(JSON.stringify(payload));
|
||||
} else {
|
||||
logger.warn("[LavalinkManager] Cannot send - no valid send method found");
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[LavalinkManager] Send error:", e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/** @private Attach raw WebSocket listeners to cache VOICE_SERVER_UPDATE events and handle errors. */
|
||||
_setupVoiceForwarding(client) {
|
||||
|
||||
const attachRawWs = () => {
|
||||
try {
|
||||
const shard0 = client.ws?.shards?.get?.(0);
|
||||
const wsObj = shard0?.ws ?? null;
|
||||
if (!wsObj) return;
|
||||
|
||||
if (this._rawWsHandler && this._rawWsObj && this._rawWsObj !== wsObj) {
|
||||
try {
|
||||
if (typeof this._rawWsObj.removeEventListener === "function") {
|
||||
this._rawWsObj.removeEventListener(
|
||||
"message",
|
||||
this._rawWsMessageListener ?? this._rawWsHandler
|
||||
);
|
||||
this._rawWsObj.removeEventListener("error", this._rawWsErrorHandler);
|
||||
} else if (typeof this._rawWsObj.off === "function") {
|
||||
this._rawWsObj.off(
|
||||
"message",
|
||||
this._rawWsMessageListener ?? this._rawWsHandler
|
||||
);
|
||||
this._rawWsObj.off("error", this._rawWsErrorHandler);
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn(
|
||||
"[LavalinkManager] Raw WS listener cleanup:",
|
||||
e?.message
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (wsObj === this._rawWsObj) return;
|
||||
|
||||
const botId = this._client?.user?.id;
|
||||
let _vsuLogCooldown = 0;
|
||||
let _vsuBotLogCooldown = 0;
|
||||
this._rawWsHandler = (rawData) => {
|
||||
try {
|
||||
const text = typeof rawData === "string" ? rawData : rawData?.data;
|
||||
const payload = typeof text === "string" ? JSON.parse(text) : rawData;
|
||||
|
||||
if (payload?.t === "VOICE_SERVER_UPDATE") {
|
||||
if (!payload.d?.guild_id) {
|
||||
logger.warn(
|
||||
"[LavalinkManager] VOICE_SERVER_UPDATE: Missing guild_id",
|
||||
payload
|
||||
);
|
||||
return;
|
||||
}
|
||||
const guildKey = String(payload.d.guild_id);
|
||||
const now = Date.now();
|
||||
logger.lavalink("[LavalinkManager] VOICE_SERVER_UPDATE for guild " + guildKey +
|
||||
" endpoint=" + (payload.d.endpoint || "none") +
|
||||
" token=" + (typeof payload.d.token === "string" ? payload.d.token.substring(0, 12) + "..." : "none"));
|
||||
if (now - _vsuLogCooldown > 5_000) {
|
||||
_vsuLogCooldown = now;
|
||||
}
|
||||
this._cachedVoiceServerUpdates.set(guildKey, payload);
|
||||
if (this._cachedVoiceServerUpdates.size > 500) {
|
||||
const oldest = this._cachedVoiceServerUpdates.keys().next().value;
|
||||
if (oldest !== undefined) this._cachedVoiceServerUpdates.delete(oldest);
|
||||
}
|
||||
}
|
||||
|
||||
} catch (e) {
|
||||
logger.warn(
|
||||
"[LavalinkManager] Raw WS message parse error:",
|
||||
e?.message
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
this._rawWsErrorHandler = (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(
|
||||
"[LavalinkManager] Raw WS socket error (will reconnect):",
|
||||
err?.message ?? err
|
||||
);
|
||||
};
|
||||
|
||||
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;
|
||||
} catch (e) {
|
||||
logger.warn("[LavalinkManager] Raw WS setup error:", e.message);
|
||||
}
|
||||
};
|
||||
|
||||
if (this.lavalink) {
|
||||
logger.lavalink("[LavalinkManager] lavalink.sendRawData type: " + typeof this.lavalink.sendRawData);
|
||||
logger.lavalink("[LavalinkManager] lavalink players type: " + typeof this.lavalink.players);
|
||||
try {
|
||||
const pSize = this.lavalink.players?.size ?? this.lavalink.players?.length ?? "unknown";
|
||||
logger.lavalink("[LavalinkManager] lavalink players size: " + pSize);
|
||||
} catch(_) {}
|
||||
}
|
||||
|
||||
attachRawWs();
|
||||
client.on(Events.Ready, attachRawWs);
|
||||
}
|
||||
|
||||
/** @private Forward a raw payload to the Lavalink node via sendRawData. */
|
||||
_forwardToLavalink(payload, guildKey, label) {
|
||||
try {
|
||||
if (typeof this.lavalink.sendRawData !== "function") {
|
||||
logger.error("[LavalinkManager] sendRawData is NOT a function! type=" + typeof this.lavalink.sendRawData);
|
||||
return;
|
||||
}
|
||||
|
||||
const player = this.lavalink.players?.get?.(guildKey);
|
||||
logger.lavalink("[LavalinkManager] _forwardToLavalink " + label +
|
||||
" guild=" + guildKey +
|
||||
" playerExists=" + !!player +
|
||||
" playerConnected=" + (player?.connected ?? "noPlayer"));
|
||||
|
||||
this.lavalink.sendRawData(payload);
|
||||
|
||||
const playerAfter = this.lavalink.players?.get?.(guildKey);
|
||||
if (playerAfter) {
|
||||
const vs = playerAfter.voiceServer;
|
||||
logger.lavalink("[LavalinkManager] After sendRawData(" + label + "):" +
|
||||
" voiceServer=" + (vs ? "endpoint=" + (vs.endpoint || "none") : "none") +
|
||||
" connected=" + (playerAfter.connected ?? "undefined"));
|
||||
} else {
|
||||
logger.lavalink("[LavalinkManager] After sendRawData(" + label + "): player not found!");
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error("[LavalinkManager] _forwardToLavalink(" + label + ") error:", e.message, e.stack?.substring(0, 200));
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* Replay a cached VOICE_SERVER_UPDATE payload to the Lavalink node.
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @returns {boolean} True if a cached update was found and replayed.
|
||||
*/
|
||||
replayVoiceServerUpdate(guildId) {
|
||||
const guildKey = String(guildId);
|
||||
const cached = this._cachedVoiceServerUpdates.get(guildKey);
|
||||
if (!cached) {
|
||||
logger.lavalink("[LavalinkManager] No cached VOICE_SERVER_UPDATE to replay for guild " + guildKey);
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
logger.lavalink("[LavalinkManager] Replaying cached VOICE_SERVER_UPDATE for guild " + guildKey);
|
||||
this.lavalink.sendRawData(cached);
|
||||
return true;
|
||||
} catch (e) {
|
||||
logger.warn("[LavalinkManager] Replay VOICE_SERVER_UPDATE error:", e.message);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** @async Initialize the Lavalink connection. Sets up session handling, registers node connect listeners, and warns if the node is unreachable after 3 seconds. @returns {Promise<void>} */
|
||||
async init() {
|
||||
this.setMaxListeners(50);
|
||||
try {
|
||||
this.lavalink?.setMaxListeners?.(50);
|
||||
} catch (e) {
|
||||
logger.warn("[Lavalink] init setMaxListeners:", e?.message);
|
||||
}
|
||||
|
||||
const cfg = this._nodeCfg;
|
||||
logger.lavalink(
|
||||
`[Lavalink] Initializing — node: ${cfg?.id ?? "main"} @ ${cfg?.host ?? "localhost"}:${cfg?.port ?? 2333} (secure: ${cfg?.secure ?? false}, type: NodeLink)`
|
||||
);
|
||||
|
||||
try {
|
||||
this.lavalink.init({
|
||||
id: this._client?.user?.id ?? "0",
|
||||
username: this._client?.user?.username ?? "bot",
|
||||
});
|
||||
} catch (e) {
|
||||
logger.warn("[Lavalink] init error:", e?.message);
|
||||
}
|
||||
|
||||
const onNodeConnect = (node) => {
|
||||
this._nodeConnected = true;
|
||||
try {
|
||||
node.updateSession(true, 300_000);
|
||||
this._sessionId = node.sessionId ?? this._sessionId;
|
||||
logger.lavalink(
|
||||
"[Lavalink] Node ready: " + node.id + " | session: " + this._sessionId
|
||||
);
|
||||
this.emit("ready", this._sessionId);
|
||||
} catch (e) {
|
||||
logger.warn(
|
||||
"[Lavalink] nodeConnect handler error:",
|
||||
e?.message
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
this.lavalink.on("nodeConnect", onNodeConnect);
|
||||
|
||||
setTimeout(() => {
|
||||
if (!this._nodeConnected) {
|
||||
const h = cfg?.host || "localhost";
|
||||
const p = cfg?.port || 2333;
|
||||
logger.warn(
|
||||
"[Lavalink] Node at " + h + ":" + p + " is NOT connected yet. " +
|
||||
"Make sure your NodeLink/Lavalink server is running. " +
|
||||
"The bot will retry when a voice join is attempted."
|
||||
);
|
||||
}
|
||||
}, 3_000);
|
||||
}
|
||||
/** @async Search for tracks on the Lavalink node. Tries player-based search first, then falls back to direct node lookup. @param {string} query - The search query string or URL. @param {object} [options] - Search options. @param {string} [options.source] - Lavalink source identifier (e.g. 'ytmsearch'). @param {string} [options.requester] - Requester identifier. @returns {Promise<object>} Lavalink search result with tracks array. @throws {Error} If no connected node is available. */
|
||||
async search(query, options = {}) {
|
||||
try {
|
||||
const players = this.lavalink?.players;
|
||||
if (players?.size > 0) {
|
||||
const firstPlayer = players.values?.().next?.().value;
|
||||
if (firstPlayer?.node) {
|
||||
logger.lavalink("[Lavalink] search via player.node for guild " + firstPlayer.guildId);
|
||||
if (options.source) {
|
||||
return firstPlayer.node.search({ query, source: options.source });
|
||||
}
|
||||
return firstPlayer.node.search(query);
|
||||
}
|
||||
}
|
||||
} catch (_) { /* fall through to node-based search */ }
|
||||
|
||||
const node = this._getConnectedNode();
|
||||
if (node) {
|
||||
logger.lavalink("[Lavalink] search via _getConnectedNode()");
|
||||
if (options.source) {
|
||||
return node.search({ query, source: options.source });
|
||||
}
|
||||
return node.search(query);
|
||||
}
|
||||
|
||||
try {
|
||||
const nodes = this.lavalink?.nodes;
|
||||
const nodeId = this._nodeCfg?.id ?? "main";
|
||||
const node = nodes?.get?.(nodeId) ?? nodes?.cache?.get?.(nodeId);
|
||||
if (node) {
|
||||
logger.lavalink("[Lavalink] search via fallback node.get()");
|
||||
if (options.source) {
|
||||
return node.search({ query, source: options.source });
|
||||
}
|
||||
return node.search(query);
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
throw new Error("No connected Lavalink node available for search");
|
||||
}
|
||||
|
||||
/** Get the Lavalink player for a guild. @param {string} guildId - The guild ID. @returns {object|null} The Lavalink player, or null if not found. */
|
||||
getPlayer(guildId) {
|
||||
return this.lavalink.players.get(String(guildId));
|
||||
}
|
||||
|
||||
/** Close all node WebSocket connections and clean up. */
|
||||
destroy() {
|
||||
try {
|
||||
for (const [id, node] of this.lavalink?.nodes?.cache?.entries?.() ?? []) {
|
||||
try {
|
||||
node.socket?.close?.();
|
||||
} catch (e) {
|
||||
logger.warn(`[Lavalink] destroy node ${id}:`, e?.message);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[Lavalink] destroy:", e?.message);
|
||||
}
|
||||
}
|
||||
|
||||
/** Check whether at least one Lavalink node is currently connected. @returns {boolean} */
|
||||
hasConnectedNode() {
|
||||
return this._nodeConnected === true;
|
||||
}
|
||||
|
||||
/** @async Wait for a Lavalink node to become connected. Polls at 1-second intervals until connected or timeout. @param {object} [options] - Wait options. @param {number} [options.timeoutMs=15000] - Maximum time to wait in milliseconds. @param {number} [options.intervalMs=1000] - Polling interval in milliseconds. @returns {Promise<void>} Resolves when a node is connected. @throws {Error} If timeout is reached without a connected node. */
|
||||
waitForNode(options = {}) {
|
||||
const timeoutMs = options.timeoutMs ?? 15_000;
|
||||
const intervalMs = options.intervalMs ?? 1_000;
|
||||
const host = this._nodeCfg?.host || "???";
|
||||
const port = this._nodeCfg?.port || 2333;
|
||||
const errMsg =
|
||||
"[LavalinkManager] No Lavalink node connected after " +
|
||||
Math.round(timeoutMs / 1000) + "s. " +
|
||||
"Is your NodeLink/Lavalink server running at " + host + ":" + port + "? " +
|
||||
"Check: 1) Server is started, 2) Host/port/password are correct in config.json -> nodelink";
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
if (this._nodeConnected) return resolve();
|
||||
|
||||
let elapsed = 0;
|
||||
const timer = setInterval(() => {
|
||||
elapsed += intervalMs;
|
||||
if (this._nodeConnected) {
|
||||
clearInterval(timer);
|
||||
return resolve();
|
||||
}
|
||||
if (elapsed >= timeoutMs) {
|
||||
clearInterval(timer);
|
||||
reject(new Error(errMsg));
|
||||
}
|
||||
}, intervalMs);
|
||||
timer.unref?.();
|
||||
});
|
||||
}
|
||||
|
||||
/** @private Get a connected Lavalink node, trying multiple strategies (cache, get, leastUsedNodes, leastLoadNodes). @returns {object|null} A connected node instance, or null if none available. */
|
||||
_getConnectedNode() {
|
||||
try {
|
||||
const nodes = this.lavalink?.nodeManager ?? this.lavalink?.nodes;
|
||||
if (!nodes) return null;
|
||||
|
||||
let store = nodes.cache ?? null;
|
||||
if (store && typeof store.get === "function" && this._nodeConnected) {
|
||||
const nodeId = this._nodeCfg?.id ?? "main";
|
||||
const node = store.get(nodeId);
|
||||
if (node) return node;
|
||||
if (store.size > 0) {
|
||||
const first = store.values?.().next?.().value;
|
||||
if (first) return first;
|
||||
}
|
||||
}
|
||||
|
||||
if (typeof nodes.get === "function" && this._nodeConnected) {
|
||||
const nodeId = this._nodeCfg?.id ?? "main";
|
||||
const node = nodes.get(nodeId);
|
||||
if (node) return node;
|
||||
if (nodes.size > 0) {
|
||||
const first = nodes.values?.().next?.().value;
|
||||
if (first) return first;
|
||||
}
|
||||
}
|
||||
|
||||
if (this._nodeConnected) {
|
||||
try {
|
||||
const arr = nodes.leastUsedNodes?.();
|
||||
if (arr?.length) return arr[0];
|
||||
} catch (_) {}
|
||||
try {
|
||||
const arr = nodes.leastLoadNodes?.();
|
||||
if (arr?.length) return arr[0];
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
return null;
|
||||
} catch (e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** Get a connected Lavalink node. Public alias for _getConnectedNode. @returns {object|null} A connected node instance, or null. */
|
||||
getNode() {
|
||||
return this._getConnectedNode();
|
||||
}
|
||||
|
||||
/** @type {string|null} @description Current Lavalink session ID. */
|
||||
get sessionId() {
|
||||
return this._sessionId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark a guild as having a pending leave request so the intercepted op4 leave is allowed through.
|
||||
* @param {string} guildId - The guild ID.
|
||||
*/
|
||||
requestLeave(guildId) {
|
||||
if (guildId) this._pendingLeaves.add(String(guildId));
|
||||
}
|
||||
|
||||
/** Get connection info for the configured NodeLink node. Useful for health checks and dashboard display. @returns {{host: string, port: number, sessionId: string|null, secure: boolean, password: string}|null} Connection info object, or null if no config. */
|
||||
getNodeLinkInfo() {
|
||||
const cfg = this._nodeCfg;
|
||||
if (!cfg) return null;
|
||||
return {
|
||||
host: cfg.host ?? "localhost",
|
||||
port: cfg.port ?? 2333,
|
||||
sessionId: this._sessionId ?? null,
|
||||
secure: cfg.secure ?? false,
|
||||
password: cfg.password ?? "youshallnotpass",
|
||||
};
|
||||
}
|
||||
}
|
||||
+111
-319
@@ -1,19 +1,10 @@
|
||||
/**
|
||||
* @file MessageHandler.mjs — MessageHandler — wraps Fluxer messages with reply helpers, embed builders, permission checks, and voice state utilities
|
||||
* @module src.MessageHandler
|
||||
*/
|
||||
/** @module src/MessageHandler @description Message creation, reaction observation, permission checking, pagination, and command help display. */
|
||||
|
||||
import { Client, Events, EmbedBuilder, PermissionFlags } from "@fluxerjs/core";
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
import { Utils } from "./Utils.mjs";
|
||||
|
||||
/**
|
||||
* All permissions the bot needs to function correctly, mapped to
|
||||
* human-readable names and explanations.
|
||||
* Ordered by importance — text perms first, then voice perms.
|
||||
*
|
||||
* @type {ReadonlyMap<string, { name: string, desc: string }>}
|
||||
*/
|
||||
/** @type {Map<string, {name: string, desc: string}>} @description Required bot permissions with human-readable names and descriptions. */
|
||||
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" }],
|
||||
@@ -26,13 +17,13 @@ export const REQUIRED_BOT_PERMISSIONS = Object.freeze(new Map([
|
||||
["Speak", { name: "Speak", desc: "Stream audio in voice channels" }],
|
||||
]));
|
||||
|
||||
/** Permission flag keys that are absolutely critical — bot cannot work without these. */
|
||||
/** @type {string[]} @description Permission keys that are strictly required for the bot to function. */
|
||||
export const CRITICAL_PERMISSIONS = ["ViewChannel", "SendMessages", "EmbedLinks", "Connect", "Speak"];
|
||||
|
||||
/** Permission flag keys that are nice-to-have but bot can partially work without. */
|
||||
/** @type {string[]} @description Permission keys that are optional but improve the user experience. */
|
||||
export const OPTIONAL_PERMISSIONS = ["AddReactions", "ReadMessageHistory", "ManageMessages", "AttachFiles"];
|
||||
|
||||
/** Parse a color value from config — accepts hex string "0xe9196c", "#e9196c", or number */
|
||||
/** Parse a color value (hex string, 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;
|
||||
@@ -41,31 +32,17 @@ export function parseColor(value, fallback = 0xe9196c) {
|
||||
return isNaN(n) ? fallback : n;
|
||||
}
|
||||
|
||||
/** Global embed color — set once at startup from config */
|
||||
/** @private */
|
||||
let _globalColor = 0xe9196c;
|
||||
/**
|
||||
* setGlobalColor function.
|
||||
* @param {{*}} value
|
||||
* @returns {*}
|
||||
*/
|
||||
/** Set the global embed color. @param {string|number} value */
|
||||
export function setGlobalColor(value) { _globalColor = parseColor(value); }
|
||||
/**
|
||||
* getGlobalColor function.
|
||||
* @returns {*}
|
||||
*/
|
||||
/** @returns {number} The current global embed color. */
|
||||
export function getGlobalColor() { return _globalColor; }
|
||||
|
||||
/**
|
||||
* Strip non-digit characters from a value, returning a clean ID string.
|
||||
* Re-exported from Utils.mjs for backward compatibility.
|
||||
*/
|
||||
/** Re-export of {@link cleanId} from Utils for convenience. @type {function} */
|
||||
export { cleanId } from "./Utils.mjs";
|
||||
|
||||
/**
|
||||
* Resolve a guild ID from various message-like shapes.
|
||||
* @param {object} message
|
||||
* @returns {string|null}
|
||||
*/
|
||||
/** 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 ??
|
||||
@@ -78,25 +55,18 @@ export function getMessageGuildId(message) {
|
||||
null;
|
||||
}
|
||||
|
||||
/**
|
||||
* MessageHandler class.
|
||||
*/
|
||||
/** @class MessageHandler @description Handles message creation, reaction observation, permission checking, and pagination. */
|
||||
export class MessageHandler {
|
||||
/**
|
||||
* Fluxer.js client instance
|
||||
* @type {Client}
|
||||
* @public
|
||||
*/
|
||||
/** @type {Client} */
|
||||
client;
|
||||
/** @type {Map<string, object>} Message ID → reaction observer data. */
|
||||
observedReactions;
|
||||
/** @type {Map<string, string[]>} */
|
||||
/** @type {Map<string, Array>} Channel ID → user message observer callbacks. */
|
||||
observedChannels;
|
||||
/** @type {import('./constants/Locale.mjs').Locale} */
|
||||
/** @type {object|null} Locale manager instance. */
|
||||
locale;
|
||||
|
||||
/**
|
||||
* @param {Client} client
|
||||
*/
|
||||
/** @param {Client} client - The Discord client. */
|
||||
constructor(client) {
|
||||
this.client = client;
|
||||
|
||||
@@ -114,21 +84,16 @@ export class MessageHandler {
|
||||
});
|
||||
}
|
||||
|
||||
/** @param {import('./constants/Locale.mjs').Locale} locale */
|
||||
/** Set the locale manager. @param {object} locale */
|
||||
setLocale(locale) { this.locale = locale; }
|
||||
|
||||
/**
|
||||
* Translate a locale key for a given guild.
|
||||
* @param {string} guildId
|
||||
* @param {string} key
|
||||
* @param {Object} [replacements={}]
|
||||
* @returns {string}
|
||||
*/
|
||||
/** 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;
|
||||
@@ -148,13 +113,7 @@ export class MessageHandler {
|
||||
this.client.on(Events.MessageReactionRemove, (payload) => reactionUpdate(payload));
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if the bot has the specified permissions in a specific channel.
|
||||
*
|
||||
* @param {string[]} permissions An array of permission flag keys to check for.
|
||||
* @param {BaseChannel} channel The channel to check the permissions in.
|
||||
* @returns {string[]} Missing permission flag keys.
|
||||
*/
|
||||
/** Return the permission keys the bot is missing in a channel. @param {string[]} permissions @param {object} channel @returns {string[]} Missing permission keys. */
|
||||
checkPermissions(permissions, channel) {
|
||||
if (!channel?.guild) return [];
|
||||
const me = channel.guild.members?.me ?? null;
|
||||
@@ -170,14 +129,7 @@ export class MessageHandler {
|
||||
return permissions.filter(p => !perms.has(PermissionFlags[p] ?? p));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check ALL required bot permissions in a channel.
|
||||
* Returns an object with critical vs optional missing permissions
|
||||
* so the caller can decide how severe the problem is.
|
||||
*
|
||||
* @param {BaseChannel} channel The channel to check.
|
||||
* @returns {{ missing: string[], criticalMissing: string[], optionalMissing: string[] }}
|
||||
*/
|
||||
/** 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);
|
||||
@@ -188,14 +140,7 @@ export class MessageHandler {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a rich permission-error embed listing all missing permissions
|
||||
* with human-readable names and explanations.
|
||||
*
|
||||
* @param {string[]} missingKeys Permission flag keys that are missing.
|
||||
* @param {string} [guildId] Guild ID for locale translation.
|
||||
* @returns {EmbedBuilder}
|
||||
*/
|
||||
/** Build an EmbedBuilder showing missing permissions. @param {string[]} missingKeys @param {string} guildId @returns {EmbedBuilder} */
|
||||
buildPermissionEmbed(missingKeys, guildId) {
|
||||
const criticalItems = [];
|
||||
const optionalItems = [];
|
||||
@@ -237,11 +182,7 @@ export class MessageHandler {
|
||||
return embed;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} permissions Permissions to check for.
|
||||
* @param {FluxerMessage} message The message to reply to in case of missing permissions.
|
||||
* @returns {Promise<boolean>} If all permissions are given.
|
||||
*/
|
||||
/** 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) {
|
||||
@@ -275,25 +216,14 @@ export class MessageHandler {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* @callback MessageListener
|
||||
* @param {Message} message
|
||||
*/
|
||||
/**
|
||||
* Listen for new messages
|
||||
* @param {MessageListener} listener
|
||||
*/
|
||||
/** 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 cached message by id.
|
||||
* @param {string} id
|
||||
* @returns {Message|null}
|
||||
*/
|
||||
/** 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;
|
||||
@@ -302,12 +232,7 @@ export class MessageHandler {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Either gets a message from cache or fetches it.
|
||||
* @param {string} id message id
|
||||
* @param {string} channelId channel id
|
||||
* @returns {Promise<Message>}
|
||||
*/
|
||||
/** @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;
|
||||
@@ -317,20 +242,13 @@ export class MessageHandler {
|
||||
return raw ? new Message(raw, this) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a cached channel by id.
|
||||
* @param {string} id channel id
|
||||
* @returns {Channel}
|
||||
*/
|
||||
/** 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} id
|
||||
* @returns {Promise<Channel>}
|
||||
*/
|
||||
/** @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;
|
||||
@@ -338,6 +256,7 @@ export class MessageHandler {
|
||||
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,
|
||||
@@ -347,16 +266,12 @@ export class MessageHandler {
|
||||
});
|
||||
return msg.id;
|
||||
}
|
||||
/** Stop observing reactions. @param {string} i - Observation ID. @returns {boolean} */
|
||||
unobserveReactions(i) {
|
||||
return this.observedReactions.delete(i);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} userId
|
||||
* @param {BaseChannel} channel
|
||||
* @param {MessageListener} callback
|
||||
* @returns {string}
|
||||
*/
|
||||
/** 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();
|
||||
@@ -368,6 +283,7 @@ export class MessageHandler {
|
||||
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) || []);
|
||||
@@ -378,6 +294,7 @@ export class MessageHandler {
|
||||
this.observedChannels.set(channelId, current);
|
||||
}
|
||||
|
||||
/** @private Build an EmbedBuilder from text with optional title, thumbnail, and icon. @param {string} [text=""] @param {object} [options={}] @param {string} [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()
|
||||
@@ -401,6 +318,7 @@ export class MessageHandler {
|
||||
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,
|
||||
@@ -408,12 +326,7 @@ export class MessageHandler {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {FluxerMessage} replyingTo
|
||||
* @param {string|Object} message
|
||||
* @param {boolean} mention
|
||||
* @returns {Promise<Message>}
|
||||
*/
|
||||
/** @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;
|
||||
@@ -425,12 +338,7 @@ export class MessageHandler {
|
||||
return new Message(await replyingTo.reply(opts, { ping: false }), this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {FluxerMessage} replyingTo
|
||||
* @param {string|Object} message
|
||||
* @param {Object} options
|
||||
* @returns {Promise<Message>}
|
||||
*/
|
||||
/** @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;
|
||||
|
||||
@@ -452,11 +360,7 @@ export class MessageHandler {
|
||||
return new Message(await replyingTo.reply(payload, { ping: false }), this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {BaseChannel} channel
|
||||
* @param {string|Object} message
|
||||
* @returns {Promise<Message>}
|
||||
*/
|
||||
/** @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);
|
||||
@@ -471,12 +375,7 @@ export class MessageHandler {
|
||||
return new Message(await channel.send(opts), this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {BaseChannel} channel
|
||||
* @param {string|Object} content
|
||||
* @param {Object} embedOptions
|
||||
* @returns {Promise<Message>}
|
||||
*/
|
||||
/** @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 ?? "");
|
||||
@@ -493,12 +392,7 @@ export class MessageHandler {
|
||||
return new Message(await channel.send(payload), this);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {FluxerMessage} message
|
||||
* @param {string|Object} content
|
||||
* @param {Object} embedOptions
|
||||
* @returns {Promise<Message>}
|
||||
*/
|
||||
/** @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;
|
||||
@@ -537,11 +431,7 @@ export class MessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize paginated messages.
|
||||
* @param {PageBuilder} builder
|
||||
* @param {Message} msg
|
||||
*/
|
||||
/** @async Create a paginated message with arrow reactions. @param {PageBuilder} builder @param {Message} msg @returns {Promise<void>} */
|
||||
async initPagination(builder, msg) {
|
||||
const pages = builder.createPages();
|
||||
if (pages.length === 0) return;
|
||||
@@ -572,13 +462,7 @@ export class MessageHandler {
|
||||
}, 5 * 60 * 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Join a voice channel using the documented VoiceManager.join() API.
|
||||
* Reference: https://fluxer.js.org/v/latest/guides/voice
|
||||
*
|
||||
* @param {string} channelId
|
||||
* @returns {Promise<import("@fluxerjs/voice").VoiceConnectionLike>}
|
||||
*/
|
||||
/** @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);
|
||||
@@ -590,57 +474,45 @@ export class MessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Channel class.
|
||||
*/
|
||||
/** @class Channel @description Wrapper around a Discord channel object providing helpers for sending messages and observing users. */
|
||||
export class Channel {
|
||||
/**
|
||||
* The actual underlying fluxer.js channel instance
|
||||
* @type {import("@fluxerjs/core").BaseChannel}
|
||||
*/
|
||||
/** @type {object} The raw channel object. */
|
||||
channel;
|
||||
/** @type {MessageHandler} */
|
||||
handler;
|
||||
|
||||
/**
|
||||
* @param {import("@fluxerjs/core").BaseChannel} channel
|
||||
* @param {MessageHandler} handler
|
||||
*/
|
||||
/** @param {object} channel @param {MessageHandler} handler */
|
||||
constructor(channel, handler) {
|
||||
this.channel = channel;
|
||||
this.handler = handler;
|
||||
}
|
||||
|
||||
/** @type {Guild} */
|
||||
/** @returns {object|null} The guild this channel belongs to. */
|
||||
get server() {
|
||||
return this.channel?.guild ?? null;
|
||||
}
|
||||
/** @type {Guild} */
|
||||
/** @returns {object|null} Alias for server (guild). */
|
||||
get guild() {
|
||||
return this.channel?.guild ?? null;
|
||||
}
|
||||
/** @type {boolean} */
|
||||
/** @returns {boolean} Whether this channel is a voice channel. */
|
||||
get isVoice() {
|
||||
return this.channel?.isVoiceBased?.() ?? false;
|
||||
}
|
||||
/** @type {string} */
|
||||
/** @returns {string} The channel ID. */
|
||||
get id() {
|
||||
return this.channel?.id;
|
||||
}
|
||||
/** @type {string} */
|
||||
/** @returns {string|null} The guild ID. */
|
||||
get guildId() {
|
||||
return this.channel?.guildId ?? null;
|
||||
}
|
||||
/** @type {string} */
|
||||
/** @returns {string|null} Alias for guildId. */
|
||||
get serverId() {
|
||||
return this.guildId;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {MessageListener} callback
|
||||
* @param {User} user
|
||||
* @returns {Function}
|
||||
*/
|
||||
/** 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
|
||||
@@ -656,92 +528,67 @@ export class Channel {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string|Object} content
|
||||
* @returns {Promise<Message>}
|
||||
*/
|
||||
/** Send a message to this channel. @param {string|object} content @returns {Promise<Message|null>} */
|
||||
sendMessage(content) {
|
||||
return this.handler.sendMessage(this.channel, content);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string|Object} content
|
||||
* @returns {Promise<Message>}
|
||||
*/
|
||||
/** Alias for sendMessage. @param {string|object} content @returns {Promise<Message|null>} */
|
||||
send(content) {
|
||||
return this.handler.sendMessage(this.channel, content);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string|Object} content
|
||||
* @param {Object} embedOptions
|
||||
* @returns {Promise<Message>}
|
||||
*/
|
||||
/** Send an embed to this channel. @param {string|object} content @param {object} [embedOptions={}] @returns {Promise<Message|null>} */
|
||||
sendEmbed(content, embedOptions = {}) {
|
||||
return this.handler.sendEmbed(this.channel, content, embedOptions);
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {Promise<import("@fluxerjs/voice").VoiceConnection>}
|
||||
*/
|
||||
/** 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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Message class.
|
||||
*/
|
||||
/** @class Message @description Wrapper around a Discord message providing helpers for replying, editing, and reaction observation. */
|
||||
export class Message {
|
||||
/**
|
||||
* The actual underlying message instance
|
||||
* @type {import("@fluxerjs/core").Message}
|
||||
*/
|
||||
/** @type {object} */
|
||||
message;
|
||||
/** @type {MessageHandler} */
|
||||
handler;
|
||||
|
||||
/**
|
||||
* @param {import("@fluxerjs/core").Message} message Underlying raw Fluxer.js message instance
|
||||
* @param {MessageHandler} handler Owning MessageHandler, used for replies, pagination, and reaction observers
|
||||
*/
|
||||
/** @param {object} message @param {MessageHandler} handler */
|
||||
constructor(message, handler) {
|
||||
this.message = message;
|
||||
this.handler = handler;
|
||||
}
|
||||
|
||||
/** @type {string} */
|
||||
/** @returns {string} The raw message content. */
|
||||
get content() {
|
||||
return this.message.content;
|
||||
}
|
||||
/** @type {string} */
|
||||
/** @returns {string} The message ID. */
|
||||
get id() {
|
||||
return this.message.id;
|
||||
}
|
||||
/** @type {User} */
|
||||
/** @returns {object} The author object. */
|
||||
get author() {
|
||||
return this.message.author;
|
||||
}
|
||||
/** @type {string} */
|
||||
/** @returns {string} The author's user ID. */
|
||||
get authorId() {
|
||||
return this.message.author?.id;
|
||||
}
|
||||
/** @type {GuildMember|null} */
|
||||
/** @returns {object|null} The guild member, if available. */
|
||||
get member() {
|
||||
return this.message.member ?? null;
|
||||
}
|
||||
/** @type {Channel} */
|
||||
/** @returns {Channel} The wrapped channel this message was sent in. */
|
||||
get channel() {
|
||||
return this.handler.getChannel(this.message.channelId);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string[]} reactions
|
||||
* @param {function} callback
|
||||
* @param {User} [user]
|
||||
* @returns {function} unobserve
|
||||
*/
|
||||
/** Observe reactions on this message. @param {string[]} reactions @param {Function} callback @param {object} [user=null] @returns {Function} Unobserve function. */
|
||||
onReaction(reactions, callback, user = null) {
|
||||
const oid = this.handler.observeReactions(this.message, reactions, callback, user);
|
||||
return () => {
|
||||
@@ -749,21 +596,12 @@ export class Message {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string|Object} content
|
||||
* @param {boolean} mention
|
||||
* @returns {Promise<Message>}
|
||||
*/
|
||||
/** 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string|Object} content
|
||||
* @param {boolean} mention
|
||||
* @param {Object} embedOptions
|
||||
* @returns {Promise<Message>}
|
||||
*/
|
||||
/** 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,
|
||||
@@ -771,39 +609,31 @@ export class Message {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string|Object} content
|
||||
* @param {Object} embedOptions
|
||||
* @returns {Promise<Message>}
|
||||
*/
|
||||
/** 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string|Object} content
|
||||
* @param {Object} embedOptions
|
||||
* @returns {Promise<Message>}
|
||||
*/
|
||||
/** 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);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* PageBuilder class.
|
||||
*/
|
||||
/** @class PageBuilder @description Splits content into pages with template-based formatting. */
|
||||
export class PageBuilder {
|
||||
/** @type {string} Template form string with $maxPage, $currentPage, $content placeholders. */
|
||||
form = "";
|
||||
/** @type {number} Maximum lines per page. */
|
||||
maxLinesPerPage = 2;
|
||||
/** @type {string[]} */
|
||||
/** @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|string[]} content
|
||||
*/
|
||||
/** @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");
|
||||
@@ -812,18 +642,21 @@ export class PageBuilder {
|
||||
this.content = content;
|
||||
}
|
||||
|
||||
/** Set the template form string with $maxPage, $currentPage, $content placeholders. @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 cached pages if already created. @returns {Array<Array>} */
|
||||
createPages() {
|
||||
if (this.initiated) return this.pages;
|
||||
|
||||
@@ -840,10 +673,7 @@ export class PageBuilder {
|
||||
return pages;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} n
|
||||
* @returns {string|null}
|
||||
*/
|
||||
/** 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;
|
||||
@@ -854,38 +684,22 @@ export class PageBuilder {
|
||||
.replace(/\$content/gi, pages[n].join("\n"));
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} n
|
||||
* @returns {string|null}
|
||||
*/
|
||||
/** 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");
|
||||
}
|
||||
|
||||
/** @returns {number} */
|
||||
/** Get the total number of pages. @returns {number} */
|
||||
size() {
|
||||
return this.pages.length;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* RichPaginator — tabbed embed pagination with reaction controls.
|
||||
*
|
||||
* Usage:
|
||||
* new RichPaginator(msg, handler)
|
||||
* .setTimeout(5 * 60 * 1000)
|
||||
* .addTab({ emoji: "🏠", title: "Home", header: "Home Page", content: "..." })
|
||||
* .addTab({ emoji: "🎵", title: "Music", header: "Music Commands", pages: ["page1", "page2"] })
|
||||
* .setPrevNext("⬅️", "➡️")
|
||||
* .send();
|
||||
*/
|
||||
/** @class RichPaginator @description Multi-tab paginated embed with tab and arrow navigation via reactions. */
|
||||
export class RichPaginator {
|
||||
/**
|
||||
* @param {Message} msg
|
||||
* @param {MessageHandler} handler
|
||||
*/
|
||||
/** @param {Message} msg @param {MessageHandler} handler */
|
||||
constructor(msg, handler) {
|
||||
this._msg = msg;
|
||||
this._handler = handler;
|
||||
@@ -897,24 +711,19 @@ export class RichPaginator {
|
||||
this._state = { tab: 0, page: 0 };
|
||||
}
|
||||
|
||||
/** @param {number} ms */
|
||||
/** Set the session timeout duration. @param {number} ms @returns {RichPaginator} */
|
||||
setTimeout(ms) { this._timeout = ms; return this; }
|
||||
|
||||
/** @param {number} color */
|
||||
/** Set the embed color. @param {number} color @returns {RichPaginator} */
|
||||
setColor(color) { this._color = color; return this; }
|
||||
|
||||
/** @param {string} startTab index (0-based) */
|
||||
/** Set the initially selected tab index. @param {number} idx @returns {RichPaginator} */
|
||||
setStartTab(idx) { this._state.tab = idx; return this; }
|
||||
|
||||
/** @param {string} prev @param {string} next */
|
||||
/** Set the previous/next arrow emoji strings. @param {string} prev @param {string} next @returns {RichPaginator} */
|
||||
setPrevNext(prev, next) { this._prev = prev; this._next = next; return this; }
|
||||
|
||||
/**
|
||||
* Add a tab.
|
||||
* @param {{ emoji: string, title: string, header: string, content?: string, pages?: string[] }} tab
|
||||
* content — single static string (no pagination)
|
||||
* pages — array of strings, one per page (enables prev/next)
|
||||
*/
|
||||
/** 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,
|
||||
@@ -925,6 +734,7 @@ export class RichPaginator {
|
||||
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;
|
||||
@@ -943,6 +753,7 @@ export class RichPaginator {
|
||||
.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;
|
||||
|
||||
@@ -992,6 +803,7 @@ export class RichPaginator {
|
||||
rawMsg.edit({ embeds: [buildEmbed(state.tab, state.page)] }).catch(() => {});
|
||||
});
|
||||
|
||||
/** @private Clear all reactions on the paginator message. */
|
||||
const clearReactions = async () => {
|
||||
try {
|
||||
await rawMsg.removeAllReactions();
|
||||
@@ -1006,6 +818,7 @@ export class RichPaginator {
|
||||
}
|
||||
};
|
||||
|
||||
/** @private Close the pagination session, update footer, and clear reactions. */
|
||||
const closeSession = async () => {
|
||||
unobserve();
|
||||
const currentEmbed = buildEmbed(state.tab, state.page);
|
||||
@@ -1017,6 +830,7 @@ export class RichPaginator {
|
||||
|
||||
let timer = setTimeout(closeSession, this._timeout);
|
||||
|
||||
/** @private Reset the inactivity timer. */
|
||||
const resetTimer = () => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(closeSession, this._timeout);
|
||||
@@ -1032,23 +846,9 @@ export class RichPaginator {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* QueuePaginator — rich embed pagination for the queue/list command.
|
||||
*
|
||||
* Usage:
|
||||
* new QueuePaginator(msg, handler, client)
|
||||
* .setTimeout(30_000)
|
||||
* .setColor(0xe9196c)
|
||||
* .send(buildEmbedFn, totalPages, startPage);
|
||||
*
|
||||
* buildEmbedFn(page) must return a raw embed object { color, author, title, description, footer }
|
||||
*/
|
||||
/** @class QueuePaginator @description Simple two-arrow paginator for queue embeds with page count. */
|
||||
export class QueuePaginator {
|
||||
/**
|
||||
* @param {Message} msg
|
||||
* @param {MessageHandler} handler
|
||||
* @param {Client} client
|
||||
*/
|
||||
/** @param {Message} msg @param {MessageHandler} handler @param {Client} client */
|
||||
constructor(msg, handler, client) {
|
||||
this._msg = msg;
|
||||
this._handler = handler;
|
||||
@@ -1058,17 +858,13 @@ export class QueuePaginator {
|
||||
this._next = "➡️";
|
||||
}
|
||||
|
||||
/** @param {number} ms */
|
||||
/** Set the session timeout duration. @param {number} ms @returns {QueuePaginator} */
|
||||
setTimeout(ms) { this._timeout = ms; return this; }
|
||||
|
||||
/** @param {string} prev @param {string} next */
|
||||
/** Set the previous/next arrow emoji strings. @param {string} prev @param {string} next @returns {QueuePaginator} */
|
||||
setPrevNext(prev, next) { this._prev = prev; this._next = next; return this; }
|
||||
|
||||
/**
|
||||
* @param {function(page: number): object} buildEmbed - returns a raw embed object
|
||||
* @param {number} totalPages
|
||||
* @param {number} [startPage=1]
|
||||
*/
|
||||
/** @async Send the paginated embed and observe arrow reactions. @param {Function} buildEmbed - Function that takes a 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;
|
||||
@@ -1094,6 +890,7 @@ export class QueuePaginator {
|
||||
const channelId = rawMsg.channelId ?? rawMsg.channel_id ?? rawMsg.channel?.id;
|
||||
const msgId = rawMsg.id;
|
||||
|
||||
/** @private Clear all reactions on the paginator message. */
|
||||
const clearReactions = async () => {
|
||||
try {
|
||||
await rawMsg.removeAllReactions();
|
||||
@@ -1106,6 +903,7 @@ export class QueuePaginator {
|
||||
}
|
||||
};
|
||||
|
||||
/** @private Close the pagination session, update footer, and clear reactions. */
|
||||
const closeSession = async () => {
|
||||
unobserve();
|
||||
const embed = buildEmbed(state.page);
|
||||
@@ -1120,6 +918,7 @@ export class QueuePaginator {
|
||||
};
|
||||
|
||||
let timer = setTimeout(closeSession, this._timeout);
|
||||
/** @private Reset the inactivity timer. */
|
||||
const resetTimer = () => {
|
||||
clearTimeout(timer);
|
||||
timer = setTimeout(closeSession, this._timeout);
|
||||
@@ -1138,7 +937,9 @@ export class QueuePaginator {
|
||||
}
|
||||
}
|
||||
|
||||
/** @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;
|
||||
|
||||
const HELP_TABS = [
|
||||
@@ -1168,6 +969,7 @@ const HELP_TABS = [
|
||||
},
|
||||
];
|
||||
|
||||
/** @private @param {string} prefix @returns {string} */
|
||||
function _helpHomeContent(prefix) {
|
||||
return (
|
||||
"**Welcome to the Remix help page.**\n\n" +
|
||||
@@ -1182,6 +984,7 @@ function _helpHomeContent(prefix) {
|
||||
);
|
||||
}
|
||||
|
||||
/** @private @returns {string} */
|
||||
function _helpSupportContent() {
|
||||
return (
|
||||
"If you need help with anything or encounter any issues, hop over to " +
|
||||
@@ -1193,6 +996,7 @@ function _helpSupportContent() {
|
||||
);
|
||||
}
|
||||
|
||||
/** @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 => {
|
||||
@@ -1219,29 +1023,16 @@ function _helpBuildCategoryPages(tab, allCmds, prefix) {
|
||||
return pages;
|
||||
}
|
||||
|
||||
/**
|
||||
* HelpCommand class.
|
||||
*/
|
||||
/** @class HelpCommand @description Rich paginated help command with tabbed navigation (Home, Music, Utilities, Support). */
|
||||
export class HelpCommand {
|
||||
/**
|
||||
* @param {import("./CommandHandler.mjs").CommandHandler} commandHandler
|
||||
* @param {MessageHandler} messageHandler
|
||||
* @param {function(msg: Message): import("./Settings.mjs").SettingsManager} getSettingsFn
|
||||
* Called with a Message to retrieve that guild's settings.
|
||||
* In index.mjs this is: (msg) => this.getSettings(msg)
|
||||
*/
|
||||
/** @param {CommandHandler} commandHandler @param {MessageHandler} messageHandler @param {Function} getSettingsFn */
|
||||
constructor(commandHandler, messageHandler, getSettingsFn) {
|
||||
this._commands = commandHandler;
|
||||
this._messages = messageHandler;
|
||||
this._getSettings = getSettingsFn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers the help command with the CommandHandler and intercepts
|
||||
* incoming messages whose first word is "help", "h", or "commands".
|
||||
*
|
||||
* Call once during bot startup, after commands have been loaded.
|
||||
*/
|
||||
/** Register the help command, intercept invalid command replies, and intercept help aliases. */
|
||||
register() {
|
||||
if (this._registered) return;
|
||||
this._registered = true;
|
||||
@@ -1314,6 +1105,7 @@ export class HelpCommand {
|
||||
});
|
||||
}
|
||||
|
||||
/** @private Handle a help invocation: show command detail or paginated overview. @param {Message} msg @param {string[]} args @param {string} prefix */
|
||||
_handle(msg, args, prefix) {
|
||||
const allCmds = this._commands.commands;
|
||||
const query = (args[0] ?? "").trim();
|
||||
|
||||
@@ -1,301 +0,0 @@
|
||||
/**
|
||||
* @file MoonlinkManager.mjs — MoonlinkManager — wraps moonlink.js for track search, session management, and voice packet forwarding to NodeLink
|
||||
* @module src.MoonlinkManager
|
||||
*/
|
||||
|
||||
/**
|
||||
* MoonlinkManager.mjs
|
||||
*
|
||||
* Wraps moonlink.js Manager with a custom connector for Fluxer.
|
||||
*/
|
||||
|
||||
import { Manager } from "moonlink.js";
|
||||
import { logger, _wsErrorCooldown } from "./constants/Logger.mjs";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { Events } from "@fluxerjs/core";
|
||||
|
||||
/**
|
||||
* MoonlinkManager class.
|
||||
*/
|
||||
export class MoonlinkManager extends EventEmitter {
|
||||
/** @type {Manager} */
|
||||
manager = null;
|
||||
/** @type {string|null} */
|
||||
sessionId = null;
|
||||
/** @type {import("@fluxerjs/core").Client} */
|
||||
_client = null;
|
||||
|
||||
/**
|
||||
* @param {{ host: string, port: number, password: string, secure?: boolean }} nodeCfg
|
||||
* @param {import("@fluxerjs/core").Client} client
|
||||
*/
|
||||
constructor(nodeCfg, client) {
|
||||
super();
|
||||
this.setMaxListeners(50);
|
||||
this._nodeCfg = nodeCfg;
|
||||
this._client = client;
|
||||
|
||||
this.manager = new Manager({
|
||||
nodes: [
|
||||
{
|
||||
host: nodeCfg.host ?? "localhost",
|
||||
port: nodeCfg.port ?? 3000,
|
||||
password: nodeCfg.password ?? "youshallnotpass",
|
||||
secure: nodeCfg.secure ?? false,
|
||||
identifier: "main",
|
||||
}
|
||||
],
|
||||
options: {
|
||||
resume: true,
|
||||
resumeTimeout: 60_000,
|
||||
defaultPlayer: {
|
||||
volume: 100,
|
||||
selfDeaf: true,
|
||||
selfMute: false,
|
||||
autoPlay: false,
|
||||
autoLeave: false,
|
||||
},
|
||||
search: {
|
||||
defaultPlatform: "ytmsearch",
|
||||
},
|
||||
send: (guildId, payload) => this._sendPayload(guildId, payload),
|
||||
},
|
||||
});
|
||||
|
||||
this._setupVoiceForwarding(client);
|
||||
|
||||
this.manager.on("nodeReady", (node) => {
|
||||
this.sessionId = node.sessionId ?? null;
|
||||
logger.moonlink(`[Moonlink] Node ready: ${node.identifier} | session: ${this.sessionId}`);
|
||||
this.emit("ready", this.sessionId);
|
||||
});
|
||||
|
||||
this.manager.on("nodeConnected", (node) => {
|
||||
logger.moonlink(`[Moonlink] Node connected: ${node.identifier}`);
|
||||
});
|
||||
|
||||
this.manager.on("nodeDisconnect", (node, reason) => {
|
||||
logger.warn("[Moonlink] Node disconnected:", node.identifier, reason);
|
||||
});
|
||||
|
||||
this.manager.on("nodeError", (node, err) => {
|
||||
logger.error("[Moonlink] Node error:", node.identifier, err?.message ?? err);
|
||||
});
|
||||
|
||||
this.manager.on("trackStart", (player, track) => {
|
||||
this.emit("trackStart", player, track);
|
||||
});
|
||||
|
||||
this.manager.on("trackEnd", (player, track, reason) => {
|
||||
this.emit("trackEnd", player, track, reason);
|
||||
});
|
||||
|
||||
this.manager.on("queueEnd", (player) => {
|
||||
this.emit("queueEnd", player);
|
||||
});
|
||||
|
||||
this.manager.on("playerDisconnected", (player) => {
|
||||
this.emit("playerDisconnected", player);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the current live session ID from the connected node.
|
||||
* Walks active nodes to find a valid session, fallback to cached.
|
||||
* @returns {string|null}
|
||||
*/
|
||||
getLiveSessionId() {
|
||||
try {
|
||||
for (const node of this.manager.nodes?.nodes?.values?.() ?? []) {
|
||||
if (node.sessionId) return node.sessionId;
|
||||
if (node.ws?.sessionId) return node.ws.sessionId;
|
||||
}
|
||||
} catch(e) { logger.warn("[Moonlink] getLiveSessionId:", e?.message); }
|
||||
return this.sessionId;
|
||||
}
|
||||
|
||||
/**
|
||||
* Send voice payload to Fluxer's WebSocket.
|
||||
*
|
||||
* moonlink.js v5 passes the full gateway payload object (with `op` and `d` keys).
|
||||
* Fluxer's client-level `ws.send()` handles serialization internally, so we
|
||||
* pass the raw object. The native-WebSocket fallback path (line with
|
||||
* `JSON.stringify`) is kept for edge cases where only the raw ws is available.
|
||||
*
|
||||
* @param {string} guildId
|
||||
* @param {{ op: number, d: object }} payload
|
||||
* @private
|
||||
*/
|
||||
_sendPayload(guildId, payload) {
|
||||
try {
|
||||
if (typeof this._client?.ws?.send === "function") {
|
||||
this._client.ws.send(0, payload);
|
||||
return;
|
||||
}
|
||||
|
||||
const shard = this._client?.ws?.shards?.get?.(0);
|
||||
if (!shard) {
|
||||
logger.warn("[MoonlinkManager] No WebSocket shard available");
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof shard.send === "function") {
|
||||
shard.send(payload);
|
||||
} else if (shard.ws?.send) {
|
||||
shard.ws.send(JSON.stringify(payload));
|
||||
} else {
|
||||
logger.warn("[MoonlinkManager] Cannot send - no valid send method found");
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[MoonlinkManager] Send error:", e.message);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Forward voice state updates from Fluxer to moonlink.
|
||||
*
|
||||
* moonlink.js v5 expects raw gateway payloads via `packetUpdate()`:
|
||||
* - VOICE_STATE_UPDATE → { op: 0, t: "VOICE_STATE_UPDATE", d: {...} }
|
||||
* - VOICE_SERVER_UPDATE → { op: 0, t: "VOICE_SERVER_UPDATE", d: {...} }
|
||||
*
|
||||
* VOICE_STATE_UPDATE comes from the Fluxer `VoiceStateUpdate` event.
|
||||
* VOICE_SERVER_UPDATE must be intercepted from the raw WebSocket stream because
|
||||
* Fluxer does not emit a dedicated event for it.
|
||||
*
|
||||
* @param {import("@fluxerjs/core").Client} client
|
||||
* @private
|
||||
*/
|
||||
_setupVoiceForwarding(client) {
|
||||
client.on(Events.VoiceStateUpdate, (data) => {
|
||||
try {
|
||||
const guildId = data.guild_id;
|
||||
if (!guildId) {
|
||||
logger.warn("[MoonlinkManager] voiceStateUpdate: No guild_id found in data", data);
|
||||
return;
|
||||
}
|
||||
|
||||
const payload = {
|
||||
op: 0,
|
||||
t: "VOICE_STATE_UPDATE",
|
||||
d: {
|
||||
guild_id: guildId,
|
||||
channel_id: data.channel_id ?? null,
|
||||
user_id: data.user_id,
|
||||
session_id: data.session_id ?? "",
|
||||
deaf: data.deaf ?? false,
|
||||
mute: data.mute ?? false,
|
||||
self_deaf: data.self_deaf ?? false,
|
||||
self_mute: data.self_mute ?? false,
|
||||
self_stream: data.self_stream ?? false,
|
||||
self_video: data.self_video ?? false,
|
||||
suppress: data.suppress ?? false,
|
||||
member: data.member ?? null,
|
||||
}
|
||||
};
|
||||
|
||||
this.manager.packetUpdate(payload);
|
||||
} catch (e) {
|
||||
logger.warn("[MoonlinkManager] voiceStateUpdate forward error:", e.message);
|
||||
}
|
||||
});
|
||||
|
||||
const attachRawWs = () => {
|
||||
try {
|
||||
const shard0 = client.ws?.shards?.get?.(0);
|
||||
const wsObj = shard0?.ws ?? null;
|
||||
if (!wsObj) return;
|
||||
if (this._rawWsHandler && this._rawWsObj && this._rawWsObj !== wsObj) {
|
||||
try {
|
||||
if (typeof this._rawWsObj.removeEventListener === "function") {
|
||||
this._rawWsObj.removeEventListener("message", this._rawWsMessageListener ?? this._rawWsHandler);
|
||||
this._rawWsObj.removeEventListener("error", this._rawWsErrorHandler);
|
||||
} else if (typeof this._rawWsObj.off === "function") {
|
||||
this._rawWsObj.off("message", this._rawWsMessageListener ?? this._rawWsHandler);
|
||||
this._rawWsObj.off("error", this._rawWsErrorHandler);
|
||||
}
|
||||
} catch(e) { logger.warn("[Moonlink] Raw WS listener cleanup:", e?.message); }
|
||||
}
|
||||
|
||||
if (wsObj === this._rawWsObj) return;
|
||||
|
||||
this._rawWsHandler = (rawData) => {
|
||||
try {
|
||||
const text = typeof rawData === "string" ? rawData : rawData?.data;
|
||||
const payload = typeof text === "string" ? JSON.parse(text) : rawData;
|
||||
if (payload?.t === "VOICE_SERVER_UPDATE") {
|
||||
if (!payload.d?.guild_id) {
|
||||
logger.warn("[MoonlinkManager] VOICE_SERVER_UPDATE: Missing guild_id", payload);
|
||||
return;
|
||||
}
|
||||
this.manager.packetUpdate(payload);
|
||||
}
|
||||
} catch(e) { logger.warn("[Moonlink] Raw WS message parse error:", e?.message); }
|
||||
};
|
||||
|
||||
this._rawWsErrorHandler = (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("[MoonlinkManager] Raw WS socket error (will reconnect):", err?.message ?? err);
|
||||
};
|
||||
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;
|
||||
} catch (e) {
|
||||
logger.warn("[MoonlinkManager] Raw WS setup error:", e.message);
|
||||
}
|
||||
};
|
||||
|
||||
attachRawWs();
|
||||
client.on(Events.Ready, attachRawWs);
|
||||
}
|
||||
|
||||
async init(clientId) {
|
||||
this.setMaxListeners(50);
|
||||
try { this.manager.setMaxListeners?.(50); } catch(e) { logger.warn("[Moonlink] init setMaxListeners:", e?.message); }
|
||||
|
||||
try {
|
||||
for (const node of this.manager.nodes?.nodes?.values?.() ?? []) {
|
||||
const sock = node.socket ?? node.ws ?? null;
|
||||
if (sock && typeof sock.removeAllListeners === "function") {
|
||||
sock.removeAllListeners("open");
|
||||
sock.removeAllListeners("close");
|
||||
sock.removeAllListeners("error");
|
||||
sock.removeAllListeners("message");
|
||||
}
|
||||
}
|
||||
} catch(e) { logger.warn("[Moonlink] init socket cleanup:", e?.message); }
|
||||
|
||||
await this.manager.init(clientId);
|
||||
}
|
||||
|
||||
search(query, source, requester) {
|
||||
return this.manager.search({ query, source, requester });
|
||||
}
|
||||
|
||||
createPlayer(opts) {
|
||||
return this.manager.players.create(opts);
|
||||
}
|
||||
|
||||
getPlayer(guildId) {
|
||||
return this.manager.players.get(guildId);
|
||||
}
|
||||
|
||||
destroy() {
|
||||
try {
|
||||
for (const node of this.manager.nodes?.nodes?.values?.() ?? []) {
|
||||
node.socket?.close?.();
|
||||
}
|
||||
} catch(e) { logger.warn("[Moonlink] destroy:", e?.message); }
|
||||
}
|
||||
}
|
||||
+680
-1461
File diff suppressed because it is too large.
Load diff
+70
-179
@@ -1,14 +1,4 @@
|
||||
/**
|
||||
* @file PlayerManager.mjs — PlayerManager — creates, caches, and routes Player instances per voice channel across all guilds
|
||||
* @module src.PlayerManager
|
||||
*/
|
||||
|
||||
/**
|
||||
* PlayerManager.mjs — Manages voice channel players across servers
|
||||
*
|
||||
* Updated for moonlink.js: passes the MoonlinkManager instance into every
|
||||
* new Player so it can resolve tracks and retrieve session IDs.
|
||||
*/
|
||||
/** @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. */
|
||||
|
||||
import Player from "./Player.mjs";
|
||||
import { Utils, cleanId } from "./Utils.mjs";
|
||||
@@ -21,6 +11,7 @@ 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 ??
|
||||
@@ -31,20 +22,12 @@ function getPlayerGuildId(player, fallbackChannel = null) {
|
||||
);
|
||||
}
|
||||
|
||||
/** @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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the bot actually has the Connect permission on a specific
|
||||
* voice channel. This uses @fluxerjs/core's PermissionFlags to test the
|
||||
* bitfield directly, rather than relying on gateway error messages which
|
||||
* conflate real permission denials with stale-session 401s.
|
||||
*
|
||||
* @param {import('@fluxerjs/core').Client} client
|
||||
* @param {string} channelId
|
||||
* @returns {boolean} true if the bot has Connect (and Speak) on the channel
|
||||
*/
|
||||
/** @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 {
|
||||
const channel = client?.channels?.get?.(channelId);
|
||||
@@ -63,19 +46,7 @@ function botHasVoicePermissions(client, channelId) {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize raw voice-join error messages into user-friendly text.
|
||||
*
|
||||
* IMPORTANT: A 401/"permission" error from the gateway does NOT always mean
|
||||
* the bot lacks the Connect permission. The Fluxer gateway can also return 401
|
||||
* when the bot's previous voice session hasn't been cleaned up yet (stale
|
||||
* session race). In that case the bot DOES have Connect — it's a transient
|
||||
* error, not a real permission denial.
|
||||
*
|
||||
* To tell the difference, we check the actual channel permissions using
|
||||
* botHasVoicePermissions(). If the bot HAS Connect but got 401, it's a
|
||||
* stale session ("SESSION_RACE"), not a real permission error ("PERMISSION").
|
||||
*/
|
||||
/** @private Classify a join error into a known error code for user-facing messages. @param {Error} err @param {object} [client=null] @param {string} [channelId=null] @returns {string|null} Error code ('PERMISSION'|'NOT_FOUND'|'TIMEOUT'|'SESSION_RACE') or null. */
|
||||
function sanitizeJoinError(err, client = null, channelId = null) {
|
||||
const msg = String(err?.message ?? err ?? "");
|
||||
if (msg.includes("401") || msg.includes("Unauthorized")) {
|
||||
@@ -99,47 +70,49 @@ function sanitizeJoinError(err, client = null, channelId = null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* PlayerManager class.
|
||||
*/
|
||||
/** @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 {SettingsManager} */
|
||||
/** @type {RemoteSettingsManager} */
|
||||
settings;
|
||||
|
||||
/** @type {CommandHandler} */
|
||||
commands;
|
||||
|
||||
/** @type {Map<string, Player>} Keyed by cleaned channel ID */
|
||||
/** @type {Map<string, Player>} Player instances keyed by channel ID. */
|
||||
playerMap = new Map();
|
||||
|
||||
/** @type {Map<string, Set<string>>} Reverse index: guildId → Set<channelId> for O(1) guild lookups */
|
||||
/** @private @type {Map<string, Set<string>>} Guild ID → Set of channel IDs (for fast guild-player lookup). */
|
||||
_guildPlayerIndex = new Map();
|
||||
|
||||
/** @type {Set<string>} Channel IDs currently being joined (not yet in playerMap) */
|
||||
/** @private @type {Set<string>} Channel IDs currently being joined. */
|
||||
_pendingJoins = new Set();
|
||||
|
||||
/** @type {Map<string, {timer, songUrl, startedAtMs}>} Pending scrobble timers keyed by channel ID.
|
||||
* Prevents duplicate scrobbles when startplay fires multiple times. */
|
||||
/** @private @type {Map<string, {timer: setTimeout, songUrl: string, startedAtMs: number}>} */
|
||||
_pendingScrobbleTimers = new Map();
|
||||
|
||||
/** @type {Object} */
|
||||
/** @type {object} Full bot config. */
|
||||
config;
|
||||
|
||||
/** @type {Object} */
|
||||
/** @type {object} Player-specific config (lavalink reference). */
|
||||
playerConfig;
|
||||
|
||||
/** @type {import("./constants/Locale.mjs").Locale|null} */
|
||||
/** @type {Locale|null} */
|
||||
locale = null;
|
||||
|
||||
/** @type {import("./dashboard/Dashboard.mjs").Dashboard|null} */
|
||||
/** @type {Dashboard|null} */
|
||||
dashboard = null;
|
||||
|
||||
/**
|
||||
* @param {SettingsManager} settings
|
||||
* @param {CommandHandler} commands
|
||||
* @param {Object} config
|
||||
* @param {Object} config.config - Parsed config.json
|
||||
* @param {Object} config.player - Config data passed to new Player instances
|
||||
* 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;
|
||||
@@ -153,12 +126,7 @@ export class PlayerManager {
|
||||
this.trackOptions = config.trackOptions ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a channel to the guild→player reverse index.
|
||||
* Called after a successful player join.
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
*/
|
||||
/** @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);
|
||||
@@ -168,12 +136,7 @@ export class PlayerManager {
|
||||
set.add(cId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a channel from the guild→player reverse index.
|
||||
* Called on player leave/destroy.
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
*/
|
||||
/** @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);
|
||||
@@ -185,12 +148,7 @@ export class PlayerManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all [channelId, Player] entries for a guild.
|
||||
* Uses the reverse index for O(1) guild lookup instead of O(n) scan.
|
||||
* @param {string} guildId
|
||||
* @returns {Array<[string, Player]>}
|
||||
*/
|
||||
/** 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);
|
||||
@@ -207,13 +165,8 @@ export class PlayerManager {
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a player by guildId and channelId using the reverse index.
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
* @returns {Player|null}
|
||||
*/
|
||||
getPlayerByGuildAndChannel(guildId, channelId) {
|
||||
/** 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) {
|
||||
@@ -222,12 +175,8 @@ export class PlayerManager {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a player by channelId alone (scans guild index first, then fallback).
|
||||
* @param {string} channelId
|
||||
* @returns {Player|null}
|
||||
*/
|
||||
getPlayerByChannelId(channelId) {
|
||||
/** 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) {
|
||||
@@ -238,22 +187,7 @@ export class PlayerManager {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Forward player lifecycle/state events to the dashboard pub/sub channels.
|
||||
*
|
||||
* IMPORTANT: Events are sent in standard { type, data } format so
|
||||
* the backend (backend-master) PlayerManager can parse them correctly.
|
||||
*
|
||||
* Two channels are used:
|
||||
* {platform}:players — global, for init/close lifecycle events
|
||||
* {platform}:player_{id} — per-player, for playback/queue/volume events
|
||||
*
|
||||
* @param {Player} player
|
||||
* @param {Object} [context]
|
||||
* @param {string|null} [context.channelId]
|
||||
* @param {string|null} [context.guildId]
|
||||
* @returns {Player}
|
||||
*/
|
||||
/** 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;
|
||||
|
||||
@@ -409,25 +343,14 @@ export class PlayerManager {
|
||||
return player;
|
||||
}
|
||||
|
||||
/**
|
||||
* Translate a locale key using the message's guild locale.
|
||||
* @param {Object} message
|
||||
* @param {string} key
|
||||
* @param {Object} [replacements={}]
|
||||
* @returns {string}
|
||||
*/
|
||||
/** @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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Attempt to detect the voice channel a user is currently in.
|
||||
* @param {Message} message
|
||||
* @param {Object} [settings]
|
||||
* @returns {Promise<{channelId: string|null, alreadyInVoice: boolean, hasHumans: boolean}>}
|
||||
*/
|
||||
/** 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}>} */
|
||||
async checkVoiceChannels(message, settings) {
|
||||
const guildId = message?.guildId ?? message?.channel?.guildId ?? getMessageGuildId(message);
|
||||
const userId = message?.author?.id ?? message?.member?.user?.id;
|
||||
@@ -494,15 +417,8 @@ export class PlayerManager {
|
||||
return { channelId, alreadyInVoice, hasHumans: hasHumansResult };
|
||||
}
|
||||
|
||||
/**
|
||||
* Get or create a player for the user's voice channel.
|
||||
* @param {Message} 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) {
|
||||
/** 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);
|
||||
|
||||
@@ -586,11 +502,7 @@ export class PlayerManager {
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Prompt the user to select a voice channel.
|
||||
* @param {Message} msg
|
||||
* @returns {Promise<string|false>}
|
||||
*/
|
||||
/** Prompt the user to select a voice channel via reactions or text input. @async @param {object} msg @returns {Promise<Player|false>} */
|
||||
async promptVC(msg) {
|
||||
const { channelId: autoDetected } = await this.checkVoiceChannels(msg);
|
||||
if (autoDetected) {
|
||||
@@ -675,11 +587,7 @@ export class PlayerManager {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Make the player leave its current voice channel.
|
||||
* @param {Message} msg
|
||||
* @param {string} [cid]
|
||||
*/
|
||||
/** Leave a voice channel, destroy the player, and send a confirmation. @async @param {object} msg @param {string} [cid] @returns {Promise<void>} */
|
||||
async leave(msg, cid) {
|
||||
if (!cid) {
|
||||
const guildId = getMessageGuildId(msg);
|
||||
@@ -714,11 +622,7 @@ export class PlayerManager {
|
||||
await msg.reply(this._t(msg, "responses._common.successfullyLeft"));
|
||||
}
|
||||
|
||||
/**
|
||||
* Restore saved volume for a player from server settings.
|
||||
* @param {Player} player
|
||||
* @param {string} guildId
|
||||
*/
|
||||
/** @private Restore saved volume for a player from guild settings. @param {Player} player @param {string} guildId */
|
||||
_restorePlayerVolume(player, guildId) {
|
||||
const savedVol = this.settings?.getServer?.(guildId)?.get?.("volume");
|
||||
if (savedVol !== undefined && savedVol !== null) {
|
||||
@@ -727,12 +631,7 @@ export class PlayerManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create and register a new Player for the given voice channel.
|
||||
* @param {Message} message
|
||||
* @param {string} cid - Voice channel ID
|
||||
* @returns {Promise<Player|null>}
|
||||
*/
|
||||
/** 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. */
|
||||
async initPlayer(message, cid) {
|
||||
const channel = this.commands.client?.channels?.get(cid);
|
||||
|
||||
@@ -775,9 +674,7 @@ export class PlayerManager {
|
||||
...this.playerConfig,
|
||||
client: this.commands.client,
|
||||
config: this.config,
|
||||
nodelink: this.config.nodelink,
|
||||
moonlink: this.playerConfig?.moonlink ?? null,
|
||||
revoice: this.playerConfig?.revoice ?? null,
|
||||
lavalink: this.playerConfig?.lavalink ?? null,
|
||||
settingsMgr: this.settings,
|
||||
getPrefix: (guildId) => this.commands.getPrefix(guildId),
|
||||
observedVoiceUsers: this.observedVoiceUsers ?? null,
|
||||
@@ -818,8 +715,8 @@ export class PlayerManager {
|
||||
? get247ChannelMode(this.settings.getServer(guildId), matchChannel)
|
||||
: "off";
|
||||
|
||||
if (mode247 === "auto" || mode247 === "on") {
|
||||
logger.inactivity(`[PlayerManager] autoleave suppressed for 24/7 ${mode247} channel ${activeChannelId} (guild ${guildId})`);
|
||||
if (mode247 === "on") {
|
||||
logger.inactivity(`[PlayerManager] autoleave suppressed for 24/7 channel ${activeChannelId} (guild ${guildId})`);
|
||||
return;
|
||||
}
|
||||
if (player._hasHumansInChannel()) {
|
||||
@@ -841,17 +738,8 @@ export class PlayerManager {
|
||||
|
||||
const prefix = this.commands.getPrefix(guildId);
|
||||
|
||||
let desc;
|
||||
if (mode247 === "on") {
|
||||
desc = this.locale?.translate(guildId, "responses.join.autoLeave247On", { channel: `<#${activeChannelId}>`, prefix })
|
||||
?? `Left channel <#${activeChannelId}> because of inactivity.\nI'll rejoin automatically when the bot restarts (${prefix}247 on mode).`;
|
||||
} else if (mode247 === "auto") {
|
||||
desc = this.locale?.translate(guildId, "responses.join.autoLeave247Auto", { channel: `<#${activeChannelId}>`, prefix })
|
||||
?? `Left channel <#${activeChannelId}> — reconnecting automatically (${prefix}247 auto mode)...`;
|
||||
} else {
|
||||
desc = this.locale?.translate(guildId, "responses.join.autoLeaveInactive247", { channel: `<#${activeChannelId}>`, prefix })
|
||||
?? `Left channel <#${activeChannelId}> because of inactivity.\nIf you want me to stay in voice, use \`${prefix}247 on/auto\``;
|
||||
}
|
||||
const desc = this.locale?.translate(guildId, "responses.join.autoLeaveInactive", { channel: `<#${activeChannelId}>`, prefix })
|
||||
?? `Left channel <#${activeChannelId}> because of inactivity.\nIf you want me to stay in voice, use \`${prefix}247\``;
|
||||
if (typeof ch?.send === "function") {
|
||||
ch.send({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)], allowedMentions: { parse: [] } }).catch(err => {
|
||||
if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) {
|
||||
@@ -862,6 +750,18 @@ export class PlayerManager {
|
||||
});
|
||||
|
||||
player.on("message", (m) => {
|
||||
const isTextChannel = (c) => {
|
||||
if (!c) return false;
|
||||
if (c.type === undefined || c.type === null) return false;
|
||||
const voiceTypes = [2, 13, "GUILD_VOICE", "GUILD_STAGE_VOICE", "STAGE", "voice", "stage"];
|
||||
if (voiceTypes.includes(c.type)) return false;
|
||||
if (typeof c.isTextBased === "function") return c.isTextBased();
|
||||
const textTypes = [0, 5, 10, 11, 12, "GUILD_TEXT", "GUILD_ANNOUNCEMENT", "text"];
|
||||
if (textTypes.includes(c.type)) return true;
|
||||
logger.warn(`[PlayerManager] isTextChannel: unknown channel type=${c.type} id=${c.id}, rejecting`);
|
||||
return false;
|
||||
};
|
||||
|
||||
let ch = player.textChannel;
|
||||
const guildId = cleanId(player._guildId ?? ch?.guildId ?? ch?.guild?.id ?? getMessageGuildId({ channel: ch }));
|
||||
|
||||
@@ -870,33 +770,35 @@ export class PlayerManager {
|
||||
["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim());
|
||||
if (disabled) return;
|
||||
|
||||
if (!ch || typeof ch.send !== "function") {
|
||||
if (!isTextChannel(ch)) {
|
||||
try {
|
||||
const serverSettings = this.settings.getServer(guildId);
|
||||
const savedAnnChId = serverSettings?.get?.("announcementChannelId");
|
||||
if (savedAnnChId) {
|
||||
ch = this.commands?.client?.channels?.get?.(cleanId(savedAnnChId)) ?? null;
|
||||
const resolved = this.commands?.client?.channels?.get?.(cleanId(savedAnnChId)) ?? null;
|
||||
if (isTextChannel(resolved)) ch = resolved;
|
||||
}
|
||||
} catch(e) {
|
||||
logger.warn("[PlayerManager] Failed to resolve announcement channel:", e?.message);
|
||||
}
|
||||
}
|
||||
if (!ch || typeof ch.send !== "function") {
|
||||
if (!isTextChannel(ch)) {
|
||||
try {
|
||||
const guild = this.commands?.client?.guilds?.get?.(guildId);
|
||||
if (guild?.systemChannelId) {
|
||||
ch = guild.channels?.get?.(guild.systemChannelId) ?? null;
|
||||
const resolved = guild.channels?.get?.(guild.systemChannelId) ?? null;
|
||||
if (isTextChannel(resolved)) ch = resolved;
|
||||
}
|
||||
} catch(e) {
|
||||
logger.warn("[PlayerManager] Failed to resolve system channel:", e?.message);
|
||||
}
|
||||
}
|
||||
if (!ch || typeof ch.send !== "function") {
|
||||
if (!isTextChannel(ch)) {
|
||||
try {
|
||||
const guild = this.commands?.client?.guilds?.get?.(guildId);
|
||||
if (guild?.channels) {
|
||||
for (const c of (guild.channels.values?.() ?? [])) {
|
||||
if (c.isTextBased?.() || c.type === 0 || c.type === "GUILD_TEXT") {
|
||||
if (isTextChannel(c)) {
|
||||
ch = c;
|
||||
break;
|
||||
}
|
||||
@@ -906,12 +808,12 @@ export class PlayerManager {
|
||||
logger.warn("[PlayerManager] Failed to find fallback text channel:", e?.message);
|
||||
}
|
||||
}
|
||||
if (!ch || typeof ch.send !== "function") {
|
||||
logger.warn(`[PlayerManager] Could not resolve any channel to send now-playing announcement (guild ${guildId})`);
|
||||
if (!isTextChannel(ch)) {
|
||||
logger.warn(`[PlayerManager] Could not resolve any text channel to send now-playing announcement (guild ${guildId})`);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!player.textChannel) player.textChannel = ch;
|
||||
if (!player.textChannel || !isTextChannel(player.textChannel)) player.textChannel = ch;
|
||||
|
||||
const payload = typeof m === "object" && Array.isArray(m.embeds)
|
||||
? { ...m, allowedMentions: { parse: [] } }
|
||||
@@ -948,10 +850,6 @@ export class PlayerManager {
|
||||
logger.warn(`[PlayerManager] Stale voice session detected for channel ${cleanChannelId}, retrying in 2s...`);
|
||||
try {
|
||||
await new Promise(r => setTimeout(r, 2_000));
|
||||
if (player._revoice && player._channelId) {
|
||||
try { player._revoice._leaveGateway(player._channelId, player._guildId ?? player._resolveGuildId()); } catch(e) { logger.warn("[PlayerManager] Failed to leave gateway during retry:", e?.message); }
|
||||
try { player._revoice.deleteConnection(player._channelId); } catch(e) { logger.warn("[PlayerManager] Failed to delete connection during retry:", e?.message); }
|
||||
}
|
||||
await player.join(cid);
|
||||
|
||||
this.playerMap.set(cleanChannelId, player);
|
||||
@@ -982,14 +880,7 @@ export class PlayerManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the "startplay" event for Last.fm: send now-playing notification
|
||||
* to all linked users in the voice channel, and schedule a deferred scrobble
|
||||
* after the track has played for long enough (50% duration or 4 min).
|
||||
*
|
||||
* @param {Player} player
|
||||
* @param {Object} song - Track object
|
||||
*/
|
||||
/** @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;
|
||||
|
||||
+284
-122
@@ -1,184 +1,280 @@
|
||||
/**
|
||||
* @file Settings.mjs — Settings — abstract base class and RemoteSettingsManager for per-server configuration backed by SQLite
|
||||
* @module src.Settings
|
||||
* @module src/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.
|
||||
*/
|
||||
|
||||
import fs from "node:fs";
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
import mysql from "mysql2";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
|
||||
/**
|
||||
* Abstract base class for settings managers.
|
||||
* Provides the interface that all concrete settings managers must implement.
|
||||
* Base settings manager providing defaults, descriptions, and key utilities.
|
||||
* Subclassed by RemoteSettingsManager for MySQL-backed persistence.
|
||||
* @extends {EventEmitter}
|
||||
*/
|
||||
export class SettingsManager extends EventEmitter {
|
||||
/** @abstract @type {Object} */
|
||||
/** @type {object} Default setting values keyed by setting name. */
|
||||
defaults;
|
||||
/** @abstract */
|
||||
update(server, key) { }
|
||||
/** @abstract @returns {ServerSettings} */
|
||||
getServer(id) { }
|
||||
/** @abstract @returns {boolean} */
|
||||
hasServer(id) { }
|
||||
/** @abstract @returns {boolean} */
|
||||
isOption(key) { }
|
||||
|
||||
/** @type {object} Setting descriptions keyed by setting name. */
|
||||
descriptions;
|
||||
|
||||
/** @type {Set<string>} Internal keys hidden from getPublicKeys(). */
|
||||
internalKeys;
|
||||
|
||||
/**
|
||||
* Mark setting keys as internal (hidden from getPublicKeys).
|
||||
* @param {...string} keys - Setting key names to mark internal.
|
||||
*/
|
||||
markInternal(...keys) {
|
||||
if (!this.internalKeys) this.internalKeys = new Set();
|
||||
for (const k of keys) this.internalKeys.add(k);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a setting key is internal.
|
||||
* @param {string} key - The setting key to check.
|
||||
* @returns {boolean} True if the key is marked internal.
|
||||
*/
|
||||
isInternal(key) {
|
||||
return this.internalKeys?.has(key) ?? false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a setting key exists in defaults.
|
||||
* @param {string} key - The setting key.
|
||||
* @returns {boolean} True if the key is a known setting.
|
||||
*/
|
||||
isOption(key) { return key in this.defaults; }
|
||||
|
||||
/**
|
||||
* Get all non-internal setting keys.
|
||||
* @returns {string[]} Array of public-facing setting key names.
|
||||
*/
|
||||
getPublicKeys() {
|
||||
return Object.keys(this.defaults).filter(k => !this.isInternal(k));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* ServerSettings class.
|
||||
* Per-guild settings container. Delegates persistence to a RemoteSettingsManager.
|
||||
* All mutations call manager.update() which triggers a debounced DB write.
|
||||
*/
|
||||
export class ServerSettings {
|
||||
/** @type {string} The guild ID. */
|
||||
id;
|
||||
|
||||
/** @type {RemoteSettingsManager} The parent settings manager. */
|
||||
manager;
|
||||
|
||||
/** @type {object} Key-value store of current setting values. */
|
||||
data = {};
|
||||
|
||||
/**
|
||||
* @param {string} id Guild ID these settings belong to
|
||||
* @param {SettingsManager} mgr Owning settings manager, used for defaults and persistence
|
||||
* Create a new ServerSettings instance for a guild.
|
||||
* @param {string} id - The guild ID.
|
||||
* @param {RemoteSettingsManager} mgr - The parent settings manager.
|
||||
*/
|
||||
constructor(id, mgr) {
|
||||
this.id = id;
|
||||
this.manager = mgr;
|
||||
this.loadDefaults();
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a setting value and trigger a debounced database write.
|
||||
* @param {string} key - The setting key.
|
||||
* @param {*} value - The new value.
|
||||
*/
|
||||
set(key, value) { this.data[key] = value; this.manager.update(this, key); }
|
||||
|
||||
/**
|
||||
* Get a setting value.
|
||||
* @param {string} key - The setting key.
|
||||
* @returns {*} The current value, or undefined if not set.
|
||||
*/
|
||||
get(key) { return this.data[key]; }
|
||||
|
||||
/**
|
||||
* Reset a setting to its default value and persist the change.
|
||||
* @param {string} key - The setting key to reset.
|
||||
* @returns {*} The default value.
|
||||
*/
|
||||
reset(key) { return this.set(key, this.manager.defaults[key]); }
|
||||
getAll() { return this.data; }
|
||||
loadDefaults() { for (let key in this.manager.defaults) { this.data[key] = this.manager.defaults[key]; } }
|
||||
|
||||
checkDefaults(d) { for (let key in d) { if (this.data[key] === undefined) this.data[key] = d[key]; } }
|
||||
/**
|
||||
* Get a shallow copy of all current setting values.
|
||||
* @returns {object} Plain object with all key-value pairs.
|
||||
*/
|
||||
getAll() { return { ...this.data }; }
|
||||
|
||||
deserialize(json) { for (let k in json) { if (k === "id") continue; this.data[k] = json[k]; } }
|
||||
/**
|
||||
* Load all default values from the manager into this.data.
|
||||
*/
|
||||
loadDefaults() { for (const key in this.manager.defaults) this.data[key] = this.manager.defaults[key]; }
|
||||
|
||||
/**
|
||||
* Fill in any missing keys from a defaults object without overwriting existing values.
|
||||
* @param {object} d - Defaults object to check against.
|
||||
*/
|
||||
checkDefaults(d) { for (const key in d) { if (this.data[key] === undefined) this.data[key] = d[key]; } }
|
||||
|
||||
/**
|
||||
* Restore settings from a parsed JSON object (skips the 'id' field).
|
||||
* @param {object} json - Key-value pairs to restore.
|
||||
*/
|
||||
deserialize(json) { for (const k in json) { if (k === 'id') continue; this.data[k] = json[k]; } }
|
||||
|
||||
/**
|
||||
* Get a serializable copy of settings data including the guild ID.
|
||||
* @returns {object} Plain object suitable for JSON.stringify.
|
||||
*/
|
||||
get serializationData() { return { ...this.data, id: this.id }; }
|
||||
|
||||
/** @returns {object} Alias for serializationData. */
|
||||
serialize() { return this.serializationData; }
|
||||
|
||||
/** @returns {object} Alias for serializationData. */
|
||||
serializeObject() { return this.serializationData; }
|
||||
}
|
||||
|
||||
/**
|
||||
* RemoteSettingsManager class.
|
||||
* MySQL-backed settings manager. Loads all guild settings at startup,
|
||||
* persists changes with an 80ms debounce per guild, and supports multi-bot
|
||||
* operation via a `bot_id` column.
|
||||
*
|
||||
* @extends {SettingsManager}
|
||||
* @fires SettingsManager#ready - Emitted after the initial DB load completes.
|
||||
*/
|
||||
export class RemoteSettingsManager extends SettingsManager {
|
||||
/** @type {Map<string, ServerSettings>} Cached guild settings keyed by guild ID. */
|
||||
guilds = new Map();
|
||||
descriptions = {};
|
||||
defaults = {};
|
||||
|
||||
/** @type {import('mysql2').Pool} MySQL connection pool. */
|
||||
db = null;
|
||||
/** @type {string|null} Bot user ID — used to isolate rows per-bot in shared databases */
|
||||
|
||||
/** @type {string|null} Current bot user ID for multi-bot support. */
|
||||
botId = null;
|
||||
/** @type {boolean} Whether the bot_id column exists in the settings table */
|
||||
|
||||
/** @private @type {boolean} Whether the bot_id column has been verified. */
|
||||
_hasBotIdColumn = false;
|
||||
|
||||
/** @private */
|
||||
_loadAttempts = 0;
|
||||
/** @type {Promise|null} Tracks the in-flight load() so setBotId() can wait for it */
|
||||
|
||||
/** @private @type {Promise|null} Pending initial load promise. */
|
||||
_loadPromise = null;
|
||||
|
||||
/** @private @type {Map<string, setTimeout>} Debounce timers keyed by guild ID. */
|
||||
_debounceTimers = new Map();
|
||||
|
||||
/** @private @type {boolean} True after shutdown() is called. */
|
||||
_shuttingDown = false;
|
||||
|
||||
/**
|
||||
* @param {Object} config MySQL connection config passed to mysql2's createPool
|
||||
* @param {string} defaultsPath Filesystem path to the JSON file with default guild settings
|
||||
* @param {string|null} [botId=null] Bot user ID for multi-bot row isolation, or null for single-bot mode
|
||||
* Create a new RemoteSettingsManager backed by a MySQL pool.
|
||||
* @param {object} config - mysql2 pool configuration (host, user, password, database).
|
||||
* @param {string} defaultsPath - Path to a JSON file with default values and descriptions.
|
||||
* @param {string|null} [botId=null] - The bot user ID for multi-bot support.
|
||||
*/
|
||||
constructor(config, defaultsPath, botId = null) {
|
||||
super();
|
||||
this.botId = botId;
|
||||
this.db = mysql.createPool({ connectionLimit: 15, ...config });
|
||||
this.db.on("error", (err) => {
|
||||
logger.error("[DB] MySQL pool error:", err.code ?? err.message);
|
||||
this.db.on('error', (err) => {
|
||||
logger.error('[DB] MySQL pool error:', err.code ?? err.message);
|
||||
});
|
||||
if (defaultsPath) this.loadDefaultsSync(defaultsPath);
|
||||
this._loadPromise = this.load().catch(err => logger.error("[Settings] Initial load failed:", err?.message ?? err));
|
||||
this._loadPromise = this.load().catch(err =>
|
||||
logger.error('[Settings] Initial load failed:', err?.message ?? err)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the `bot_id` column exists in the settings table AND is
|
||||
* part of the primary key. If the column is missing, auto-migrate by
|
||||
* adding it (NOT NULL DEFAULT '') and updating the primary key to (id, bot_id).
|
||||
* If the column exists but isn't in the PK (previous failed migration),
|
||||
* fix the NULL values and retry the PK update.
|
||||
* Stop all pending debounced writes. Call before process exit.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async shutdown() {
|
||||
this._shuttingDown = true;
|
||||
for (const [, timer] of this._debounceTimers) clearTimeout(timer);
|
||||
this._debounceTimers.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a raw MySQL query and wrap the callback in a promise.
|
||||
* @param {string} q - SQL query string.
|
||||
* @returns {Promise<{error: Error|null, results: any[], fields: any}>}
|
||||
*/
|
||||
query(q) {
|
||||
return new Promise(res => {
|
||||
this.db.query(q, (error, results, fields) => { res({ error, results, fields }); });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure the `bot_id` column exists in the settings table and is part of the primary key.
|
||||
* Auto-migrates legacy tables that lack the column.
|
||||
* @returns {Promise<void>}
|
||||
* @private
|
||||
*/
|
||||
async _ensureBotIdColumn() {
|
||||
if (this._hasBotIdColumn) return;
|
||||
|
||||
const res = await this.query(
|
||||
`SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_KEY FROM information_schema.COLUMNS `
|
||||
+ `WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'settings' AND COLUMN_NAME = 'bot_id'`
|
||||
);
|
||||
|
||||
if (res.error) {
|
||||
logger.error("[Settings] Failed to check bot_id column:", res.error);
|
||||
logger.error('[Settings] Failed to check bot_id column:', res.error);
|
||||
return;
|
||||
}
|
||||
|
||||
if (res.results.length === 0) {
|
||||
logger.settings("[Settings] Auto-migrating: adding bot_id column to settings table...");
|
||||
|
||||
const alterRes = await this.query(
|
||||
`ALTER TABLE settings ADD COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''`
|
||||
);
|
||||
logger.settings('[Settings] Auto-migrating: adding bot_id column to settings table...');
|
||||
const alterRes = await this.query(`ALTER TABLE settings ADD COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''`);
|
||||
if (alterRes.error) {
|
||||
logger.error("[Settings] Failed to add bot_id column:", alterRes.error);
|
||||
logger.error('[Settings] Failed to add bot_id column:', alterRes.error);
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.botId) {
|
||||
await this.query(
|
||||
`UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''`
|
||||
);
|
||||
await this.query(`UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''`);
|
||||
}
|
||||
|
||||
const pkRes = await this.query(
|
||||
`ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)`
|
||||
);
|
||||
const pkRes = await this.query(`ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)`);
|
||||
if (pkRes.error) {
|
||||
logger.error("[Settings] Failed to update primary key:", pkRes.error);
|
||||
logger.error('[Settings] Failed to update primary key:', pkRes.error);
|
||||
return;
|
||||
}
|
||||
|
||||
this._hasBotIdColumn = true;
|
||||
logger.settings("[Settings] Auto-migration complete: bot_id column added.");
|
||||
logger.settings('[Settings] Auto-migration complete: bot_id column added.');
|
||||
return;
|
||||
}
|
||||
|
||||
const colInfo = res.results[0];
|
||||
const isNullable = colInfo.IS_NULLABLE === 'YES';
|
||||
const isPrimaryKey = colInfo.COLUMN_KEY === 'PRI';
|
||||
|
||||
if (isPrimaryKey) {
|
||||
if (colInfo.COLUMN_KEY === 'PRI') {
|
||||
this._hasBotIdColumn = true;
|
||||
return;
|
||||
}
|
||||
|
||||
logger.settings("[Settings] Fixing bot_id column: adding to primary key...");
|
||||
|
||||
if (isNullable) {
|
||||
logger.settings('[Settings] Fixing bot_id column: adding to primary key...');
|
||||
if (colInfo.IS_NULLABLE === 'YES') {
|
||||
await this.query(`UPDATE settings SET bot_id = '' WHERE bot_id IS NULL`);
|
||||
await this.query(`ALTER TABLE settings MODIFY COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''`);
|
||||
}
|
||||
|
||||
if (this.botId) {
|
||||
await this.query(
|
||||
`UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''`
|
||||
);
|
||||
await this.query(`UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''`);
|
||||
}
|
||||
|
||||
const pkRes = await this.query(
|
||||
`ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)`
|
||||
);
|
||||
const pkRes = await this.query(`ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)`);
|
||||
if (pkRes.error) {
|
||||
logger.error("[Settings] Failed to update primary key:", pkRes.error);
|
||||
logger.error('[Settings] Failed to update primary key:', pkRes.error);
|
||||
return;
|
||||
}
|
||||
|
||||
this._hasBotIdColumn = true;
|
||||
logger.settings("[Settings] Fix complete: bot_id column added to primary key.");
|
||||
logger.settings('[Settings] Fix complete: bot_id column added to primary key.');
|
||||
}
|
||||
|
||||
/**
|
||||
* Set or update the bot ID used for database row isolation.
|
||||
* Called after login when the bot user ID becomes available.
|
||||
* @param {string} id
|
||||
* Set the bot ID and claim any orphaned settings rows (bot_id = '').
|
||||
* @param {string} id - The bot user ID.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async setBotId(id) {
|
||||
const changed = this.botId !== id;
|
||||
@@ -186,7 +282,6 @@ export class RemoteSettingsManager extends SettingsManager {
|
||||
if (changed) {
|
||||
if (this._loadPromise) await this._loadPromise;
|
||||
await this._ensureBotIdColumn();
|
||||
|
||||
if (this._hasBotIdColumn && this.botId) {
|
||||
const claimRes = await this.query(
|
||||
`UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''`
|
||||
@@ -195,133 +290,200 @@ export class RemoteSettingsManager extends SettingsManager {
|
||||
logger.settings(`[Settings] Claimed ${claimRes.results.affectedRows} legacy row(s) for bot ${this.botId}`);
|
||||
}
|
||||
}
|
||||
|
||||
this.guilds.clear();
|
||||
this._loadPromise = this.load();
|
||||
await this._loadPromise;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a SQL WHERE fragment filtering by the current bot_id.
|
||||
* @returns {string} SQL fragment (empty string if bot_id not set or column unverified).
|
||||
* @private
|
||||
*/
|
||||
_botIdWhere() {
|
||||
if (!this.botId || !this._hasBotIdColumn) return "";
|
||||
if (!this.botId || !this._hasBotIdColumn) return '';
|
||||
return ` AND bot_id = ${mysql.escape(String(this.botId))}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build SQL column/value fragments for bot_id in INSERT statements.
|
||||
* @returns {{col: string, val: string}} SQL fragments (empty strings if bot_id not applicable).
|
||||
* @private
|
||||
*/
|
||||
_botIdInsert() {
|
||||
if (!this.botId || !this._hasBotIdColumn) return { col: "", val: "" };
|
||||
return { col: ", bot_id", val: `, ${mysql.escape(String(this.botId))}` };
|
||||
if (!this.botId || !this._hasBotIdColumn) return { col: '', val: '' };
|
||||
return { col: ', bot_id', val: `, ${mysql.escape(String(this.botId))}` };
|
||||
}
|
||||
|
||||
selectGuild(guildId) {
|
||||
/**
|
||||
* Fetch the settings row for a single guild.
|
||||
* @param {string} guildId - The guild ID.
|
||||
* @returns {Promise<{error: Error|null, results: any[], fields: any}>}
|
||||
*/
|
||||
async selectGuild(guildId) {
|
||||
const escapedId = mysql.escape(String(guildId));
|
||||
return this.query(`SELECT * FROM settings WHERE id=${escapedId}${this._botIdWhere()}`);
|
||||
}
|
||||
|
||||
query(q) {
|
||||
return new Promise(res => {
|
||||
this.db.query(q, (error, results, fields) => { res({ error, results, fields }); });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Load all guild settings from the database. Retries with exponential backoff on failure.
|
||||
* Emits 'ready' when complete.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async load() {
|
||||
const res = await this.query(`SELECT * FROM settings WHERE 1=1${this._botIdWhere()}`);
|
||||
if (res.error) {
|
||||
this._loadAttempts++;
|
||||
const delay = Math.min(1000 * Math.pow(2, this._loadAttempts - 1), 30_000);
|
||||
logger.error("[Settings] Init error (attempt", this._loadAttempts, "retrying in", delay + "ms):", res.error);
|
||||
logger.error('[Settings] Init error (attempt', this._loadAttempts, 'retrying in', delay + 'ms):', res.error);
|
||||
return new Promise((resolve) => { setTimeout(() => { this.load().then(resolve).catch(resolve); }, delay); });
|
||||
}
|
||||
this._loadAttempts = 0;
|
||||
res.results.forEach((r) => {
|
||||
try {
|
||||
const server = new ServerSettings(r.id, this);
|
||||
const parsed = (typeof r.data === "string") ? JSON.parse(r.data) : r.data;
|
||||
const parsed = (typeof r.data === 'string') ? JSON.parse(r.data) : r.data;
|
||||
server.deserialize(parsed);
|
||||
server.checkDefaults(this.defaults);
|
||||
this.guilds.set(server.id, server);
|
||||
} catch (e) {
|
||||
logger.error("[Settings] Failed to parse settings for server", r.id, ":", e.message);
|
||||
logger.error('[Settings] Failed to parse settings for server', r.id, ':', e.message);
|
||||
}
|
||||
});
|
||||
this.emit("ready");
|
||||
this.emit('ready');
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist a single key change via MySQL JSON_SET. Falls back to a full blob save for arrays/objects.
|
||||
* @param {ServerSettings} server - The guild settings instance.
|
||||
* @param {string} key - The changed key.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async remoteUpdate(server, key) {
|
||||
if (this._shuttingDown) return;
|
||||
const val = server.data[key];
|
||||
if (Array.isArray(val) || (typeof val === "object" && val !== null)) {
|
||||
if (Array.isArray(val) || (typeof val === 'object' && val !== null)) {
|
||||
return this.remoteSave(server);
|
||||
}
|
||||
const escapedPath = mysql.escape(`$.${key}`);
|
||||
const escapedVal = (typeof val === "boolean" || typeof val === "number")
|
||||
? mysql.escape(val)
|
||||
: mysql.escape(String(val));
|
||||
const escapedId = mysql.escape(server.id);
|
||||
const r = await this.query(`UPDATE settings SET data = JSON_SET(data, ${escapedPath}, ${escapedVal}) WHERE id=${escapedId}${this._botIdWhere()}`);
|
||||
if (r.error) logger.error("[Settings] remoteUpdate error:", r.error);
|
||||
const jsonVal = JSON.stringify(val);
|
||||
const escapedVal = mysql.escape(jsonVal);
|
||||
const escapedId = mysql.escape(server.id);
|
||||
const r = await this.query(`UPDATE settings SET data = JSON_SET(data, ${escapedPath}, CAST(${escapedVal} AS JSON)) WHERE id=${escapedId}${this._botIdWhere()}`);
|
||||
if (r.error) logger.error('[Settings] remoteUpdate error:', r.error);
|
||||
}
|
||||
|
||||
/**
|
||||
* Persist the entire guild settings blob to the database.
|
||||
* @param {ServerSettings} server - The guild settings instance.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async remoteSave(server) {
|
||||
if (this._shuttingDown) return;
|
||||
const escapedData = mysql.escape(JSON.stringify(server.data));
|
||||
const escapedId = mysql.escape(server.id);
|
||||
const escapedId = mysql.escape(server.id);
|
||||
const r = await this.query(`UPDATE settings SET data = ${escapedData} WHERE id=${escapedId}${this._botIdWhere()}`);
|
||||
if (r.error) logger.error("[Settings] remoteSave error:", r.error);
|
||||
if (r.error) logger.error('[Settings] remoteSave error:', r.error);
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronously load default values and descriptions from a JSON file.
|
||||
* @param {string} filePath - Path to the JSON file.
|
||||
*/
|
||||
loadDefaultsSync(filePath) {
|
||||
try {
|
||||
const d = fs.readFileSync(filePath, "utf8");
|
||||
const d = fs.readFileSync(filePath, 'utf8');
|
||||
const parsed = JSON.parse(d);
|
||||
this.descriptions = parsed.descriptions;
|
||||
this.defaults = parsed.values;
|
||||
this.descriptions = parsed.descriptions ?? {};
|
||||
this.defaults = parsed.values ?? {};
|
||||
if (parsed.internal) this.markInternal(...parsed.internal);
|
||||
} catch (e) {
|
||||
logger.error("[Settings] Failed to load defaults from", filePath, ":", e.message);
|
||||
logger.error('[Settings] Failed to load defaults from', filePath, ':', e.message);
|
||||
this.descriptions = {};
|
||||
this.defaults = {};
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Save all guild settings to the database in parallel.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async saveAsync() {
|
||||
await Promise.allSettled([...this.guilds.values()].map(v => this.remoteSave(v)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Insert a new settings row for a guild. Uses INSERT IGNORE to avoid duplicate-key errors.
|
||||
* @param {string} id - The guild ID.
|
||||
* @param {ServerSettings} server - The settings instance.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async create(id, server) {
|
||||
const escapedId = mysql.escape(id);
|
||||
if (this._shuttingDown) return;
|
||||
const escapedId = mysql.escape(id);
|
||||
const escapedData = mysql.escape(JSON.stringify(server.data));
|
||||
const bi = this._botIdInsert();
|
||||
const r = await this.query(
|
||||
`INSERT IGNORE INTO settings (id, data${bi.col}) VALUES (${escapedId}, ${escapedData}${bi.val})`
|
||||
);
|
||||
if (r.error) logger.error("[Settings] create error:", r.error);
|
||||
if (r.error) logger.error('[Settings] create error:', r.error);
|
||||
}
|
||||
|
||||
/**
|
||||
* Queue a debounced database write for a single key change (80ms delay per guild).
|
||||
* If the guild is not yet cached, it is added and a CREATE is issued.
|
||||
* @param {ServerSettings} server - The guild settings instance.
|
||||
* @param {string} key - The changed key.
|
||||
*/
|
||||
update(server, key) {
|
||||
if (!this.guilds.has(server.id)) { this.guilds.set(server.id, server); this.create(server.id, server).catch(e => logger.error("[Settings] create error in update:", e.message)); }
|
||||
if (this._shuttingDown) return;
|
||||
if (!this.guilds.has(server.id)) {
|
||||
this.guilds.set(server.id, server);
|
||||
this.create(server.id, server).catch(e => logger.error('[Settings] create error in update:', e.message));
|
||||
}
|
||||
const s = this.guilds.get(server.id);
|
||||
s.data[key] = server.data[key];
|
||||
const existing = this._debounceTimers.get(server.id);
|
||||
if (existing) clearTimeout(existing);
|
||||
this._debounceTimers.set(server.id, setTimeout(() => {
|
||||
this._debounceTimers.delete(server.id);
|
||||
this.remoteSave(s);
|
||||
const target = this.guilds.get(server.id);
|
||||
if (target) this.remoteUpdate(target, key);
|
||||
}, 80));
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a setting key exists in defaults.
|
||||
* @param {string} key - The setting key.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
isOption(key) { return key in this.defaults; }
|
||||
|
||||
/**
|
||||
* Check whether a guild has cached settings.
|
||||
* @param {string} id - The guild ID.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
hasServer(id) { return this.guilds.has(id); }
|
||||
|
||||
/**
|
||||
* Get settings for a guild. Returns a fresh ServerSettings (with defaults) if not cached.
|
||||
* @param {string} id - The guild ID.
|
||||
* @returns {ServerSettings}
|
||||
*/
|
||||
getServer(id) {
|
||||
if (!this.guilds.has(id)) {
|
||||
return new ServerSettings(id, this);
|
||||
}
|
||||
if (!this.guilds.has(id)) return new ServerSettings(id, this);
|
||||
return this.guilds.get(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a guild from the cache and cancel any pending debounced writes.
|
||||
* @param {string} id - The guild ID.
|
||||
*/
|
||||
removeServer(id) {
|
||||
const timer = this._debounceTimers.get(id);
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
this._debounceTimers.delete(id);
|
||||
}
|
||||
if (timer) { clearTimeout(timer); this._debounceTimers.delete(id); }
|
||||
this.guilds.delete(id);
|
||||
}
|
||||
}
|
||||
+25
-11
@@ -1,29 +1,28 @@
|
||||
/**
|
||||
* @file TrackOptionsManager.mjs — TrackOptionsManager — SQLite-backed per-track options storage for auto-seek and end-time timers
|
||||
* @module src.TrackOptionsManager
|
||||
*/
|
||||
|
||||
/** @module src/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";
|
||||
|
||||
const DEFAULT_ALIAS = "default";
|
||||
const MAX_ALIAS_LEN = 32;
|
||||
|
||||
/**
|
||||
* TrackOptionsManager class.
|
||||
*/
|
||||
/** @class TrackOptionsManager @description Manages per-user track options (start/end timestamps, aliases) stored in MySQL. Provides caching, best-match lookup, and CRUD operations. */
|
||||
export class TrackOptionsManager {
|
||||
/** @type {import('mysql2').Pool} */
|
||||
db = null;
|
||||
/** @type {string|null} */
|
||||
botId = null;
|
||||
/** @private */
|
||||
_hasTable = false;
|
||||
/** @private */
|
||||
_ready = false;
|
||||
/** @private */
|
||||
_readyPromise = null;
|
||||
/** @private @type {Map<string, object>} */
|
||||
_cache = new Map();
|
||||
/** @private @type {number} */
|
||||
_cacheMaxSize = 2000;
|
||||
|
||||
/**
|
||||
* @param {Object} mysqlConfig MySQL connection config passed to mysql2's createPool
|
||||
*/
|
||||
/** @param {object} mysqlConfig - MySQL connection config. */
|
||||
constructor(mysqlConfig) {
|
||||
this.db = mysql.createPool({ connectionLimit: 10, ...mysqlConfig });
|
||||
this.db.on("error", (err) => {
|
||||
@@ -32,10 +31,12 @@ export class TrackOptionsManager {
|
||||
this._readyPromise = this._ensureTable();
|
||||
}
|
||||
|
||||
/** @async Wait for the table to be ready. @returns {Promise<void>} */
|
||||
async ready() {
|
||||
await this._readyPromise;
|
||||
}
|
||||
|
||||
/** @private @async Ensure the track_options table exists with proper schema. */
|
||||
async _ensureTable() {
|
||||
try {
|
||||
await this._query(
|
||||
@@ -62,6 +63,7 @@ export class TrackOptionsManager {
|
||||
}
|
||||
}
|
||||
|
||||
/** @private @async Migrate from old schema (single unique key) to new (with alias column). */
|
||||
async _migrateOldTable() {
|
||||
try {
|
||||
const cols = await this._query(`SHOW COLUMNS FROM track_options LIKE 'alias'`);
|
||||
@@ -75,10 +77,12 @@ export class TrackOptionsManager {
|
||||
}
|
||||
}
|
||||
|
||||
/** @async Set the bot ID for multi-bot isolation. @param {string} id */
|
||||
async setBotId(id) {
|
||||
this.botId = id;
|
||||
}
|
||||
|
||||
/** @private Execute a raw SQL query. @param {string} q @returns {Promise<Array>} */
|
||||
_query(q) {
|
||||
return new Promise((resolve, reject) => {
|
||||
this.db.query(q, (error, results) => {
|
||||
@@ -88,22 +92,26 @@ export class TrackOptionsManager {
|
||||
});
|
||||
}
|
||||
|
||||
/** @private @returns {string} SQL WHERE clause fragment for bot_id. */
|
||||
_botIdWhere() {
|
||||
if (!this.botId) return "";
|
||||
return ` AND bot_id = ${mysql.escape(String(this.botId))}`;
|
||||
}
|
||||
|
||||
/** @private @returns {{col: string, val: string}} SQL column and value fragments for bot_id INSERT. */
|
||||
_botIdInsert() {
|
||||
if (!this.botId) return { col: "", val: "" };
|
||||
return { col: ", bot_id", val: `, ${mysql.escape(String(this.botId))}` };
|
||||
}
|
||||
|
||||
/** Sanitize an alias to alphanumeric, lowercase, max MAX_ALIAS_LEN chars. @param {*} raw @returns {string} */
|
||||
static sanitizeAlias(raw) {
|
||||
if (!raw || typeof raw !== "string") return DEFAULT_ALIAS;
|
||||
const cleaned = raw.replace(/[^a-zA-Z0-9_-]/g, "").toLowerCase().slice(0, MAX_ALIAS_LEN);
|
||||
return cleaned || DEFAULT_ALIAS;
|
||||
}
|
||||
|
||||
/** Build a unique identifier for a track from its URL or artist-title combination. @param {object} track @returns {string|null} */
|
||||
static makeTrackIdentifier(track) {
|
||||
if (!track) return null;
|
||||
if (track.url) {
|
||||
@@ -122,6 +130,7 @@ export class TrackOptionsManager {
|
||||
return null;
|
||||
}
|
||||
|
||||
/** @async Save or update a track option. @param {string} userId @param {object} track @param {number} startMs @param {number} endMs @param {string} [alias] @returns {Promise<{identifier: string, startMs: number, endMs: number, alias: string}|null>} */
|
||||
async set(userId, track, startMs, endMs, alias = DEFAULT_ALIAS) {
|
||||
await this.ready();
|
||||
const identifier = TrackOptionsManager.makeTrackIdentifier(track);
|
||||
@@ -145,6 +154,7 @@ export class TrackOptionsManager {
|
||||
}
|
||||
}
|
||||
|
||||
/** @async Get a user's track option for a track. @param {string} userId @param {object} track @param {string} [alias] @returns {Promise<{startMs: number, endMs: number, title: string, alias: string}|null>} */
|
||||
async get(userId, track, alias = DEFAULT_ALIAS) {
|
||||
await this.ready();
|
||||
const identifier = TrackOptionsManager.makeTrackIdentifier(track);
|
||||
@@ -177,6 +187,7 @@ export class TrackOptionsManager {
|
||||
}
|
||||
}
|
||||
|
||||
/** @async Get all track options for a track for a user. @param {string} userId @param {object} track @returns {Promise<Array>} */
|
||||
async getAllForTrack(userId, track) {
|
||||
await this.ready();
|
||||
const identifier = TrackOptionsManager.makeTrackIdentifier(track);
|
||||
@@ -193,6 +204,7 @@ export class TrackOptionsManager {
|
||||
}
|
||||
}
|
||||
|
||||
/** @async Remove track option(s) for a user. @param {string} userId @param {object} track @param {string|null} [alias] @returns {Promise<boolean>} Whether a row was deleted. */
|
||||
async remove(userId, track, alias = null) {
|
||||
await this.ready();
|
||||
const identifier = TrackOptionsManager.makeTrackIdentifier(track);
|
||||
@@ -220,6 +232,7 @@ export class TrackOptionsManager {
|
||||
}
|
||||
}
|
||||
|
||||
/** @async List all track options for a user. @param {string} userId @param {number} [limit=25] @returns {Promise<Array>} */
|
||||
async list(userId, limit = 25) {
|
||||
await this.ready();
|
||||
try {
|
||||
@@ -233,6 +246,7 @@ export class TrackOptionsManager {
|
||||
}
|
||||
}
|
||||
|
||||
/** @async Find the first matching track option among a set of users. @param {string[]} userIds @param {object} track @param {string} [alias] @returns {Promise<{startMs: number, endMs: number, title: string, alias: string, userId: string}|null>} */
|
||||
async getBestMatchForChannel(userIds, track, alias = DEFAULT_ALIAS) {
|
||||
await this.ready();
|
||||
const identifier = TrackOptionsManager.makeTrackIdentifier(track);
|
||||
|
||||
+72
-92
@@ -1,40 +1,24 @@
|
||||
/**
|
||||
* @file Utils.mjs — Utility class with static helpers — text normalization, markdown escaping, duration parsing, and string truncation
|
||||
* @module src.Utils
|
||||
*/
|
||||
|
||||
/**
|
||||
* Utils.mjs — Music bot utility functions
|
||||
* @module Utils
|
||||
*
|
||||
* Internal helpers delegate to @fluxerjs/util where available
|
||||
* (escapeMarkdown, truncate) with additional null-safety guards.
|
||||
*/
|
||||
/** @module src/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";
|
||||
|
||||
/**
|
||||
* Strip non-digit characters from a value, returning a clean ID string.
|
||||
* Replaces the inline `String(x).replace(/\D/g, "")` pattern used 97+ times.
|
||||
* @param {string|number} value
|
||||
* @returns {string}
|
||||
* Strip all non-digit characters from a value to extract a Snowflake/numeric ID.
|
||||
* @param {*} value - The value to clean (string, number, or null/undefined).
|
||||
* @returns {string} The numeric portion of the value, or empty string if none.
|
||||
*/
|
||||
export function cleanId(value) {
|
||||
return String(value ?? "").replace(/\D/g, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* @class Utils
|
||||
* @description Static utility methods for time formatting, array manipulation,
|
||||
* string processing, and validation used across the music bot.
|
||||
*/
|
||||
/** @class Utils @description Collection of static utility methods for formatting, parsing, and string manipulation. */
|
||||
export class Utils {
|
||||
|
||||
/**
|
||||
* Format milliseconds to human-readable time string (H:MM:SS or M:SS)
|
||||
* @param {number} milliseconds - Duration in milliseconds
|
||||
* @returns {string} Formatted time string
|
||||
* Format a duration in milliseconds to a human-readable string (e.g. "1:23:45").
|
||||
* @param {number} milliseconds - Duration in milliseconds.
|
||||
* @returns {string} Formatted duration string.
|
||||
*/
|
||||
static prettifyMS(milliseconds) {
|
||||
if (!milliseconds || milliseconds < 0 || !isFinite(milliseconds)) {
|
||||
@@ -54,9 +38,9 @@ export class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse duration string (H:MM:SS or M:SS or raw seconds) to milliseconds.
|
||||
* @param {string} str - Duration string
|
||||
* @returns {number} Milliseconds, 0 if invalid
|
||||
* Parse a duration string (e.g. "1:30", "1:30:00", "90") into milliseconds.
|
||||
* @param {string} str - Duration string in mm:ss, hh:mm:ss, or plain seconds.
|
||||
* @returns {number} Duration in milliseconds, or 0 if unparseable.
|
||||
*/
|
||||
static parseDuration(str) {
|
||||
if (!str || typeof str !== "string") return 0;
|
||||
@@ -78,9 +62,9 @@ export class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Format seconds to MM:SS (for NodeLink duration compatibility)
|
||||
* @param {number} seconds - Duration in seconds
|
||||
* @returns {string} Formatted time
|
||||
* Format seconds into a human-readable duration string.
|
||||
* @param {number} seconds - Duration in seconds.
|
||||
* @returns {string} Formatted duration string.
|
||||
*/
|
||||
static formatSeconds(seconds) {
|
||||
if (!seconds || seconds < 0 || !isFinite(seconds)) return "0:00";
|
||||
@@ -88,10 +72,9 @@ export class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Shuffles array in-place using Fisher-Yates algorithm
|
||||
* @template T
|
||||
* @param {T[]} array - Array to shuffle
|
||||
* @returns {T[]} Same array reference (shuffled)
|
||||
* Fisher-Yates in-place shuffle of an array.
|
||||
* @param {Array} array - The array to shuffle (mutated in place).
|
||||
* @returns {Array} The same array, shuffled.
|
||||
*/
|
||||
static shuffleArr(array) {
|
||||
if (!Array.isArray(array) || array.length < 2) return array;
|
||||
@@ -104,11 +87,11 @@ export class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Truncate text with ellipsis
|
||||
* @param {string} str - String to truncate
|
||||
* @param {number} [maxLen=100] - Maximum length
|
||||
* @param {string} [suffix="..."] - Suffix to add
|
||||
* @returns {string} Truncated string
|
||||
* Truncate a string to a maximum length, appending a suffix if truncated.
|
||||
* @param {string} str - The string to truncate.
|
||||
* @param {number} [maxLen=100] - Maximum character length.
|
||||
* @param {string} [suffix="..."] - Suffix to append when truncated.
|
||||
* @returns {string} Truncated string.
|
||||
*/
|
||||
static truncate(str, maxLen = 100, suffix = "...") {
|
||||
if (!str || typeof str !== "string") return "";
|
||||
@@ -118,10 +101,9 @@ export class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean song title by removing common suffixes/prefixes for better matching
|
||||
* Used for lyrics search and display normalization
|
||||
* @param {string} title - Raw title
|
||||
* @returns {string} Cleaned title
|
||||
* Clean a track title by removing common noise patterns (feat, remix, lyrics, etc.).
|
||||
* @param {string} title - The raw track title.
|
||||
* @returns {string} Cleaned title.
|
||||
*/
|
||||
static cleanTitle(title) {
|
||||
if (!title || typeof title !== "string") return "Unknown";
|
||||
@@ -156,10 +138,9 @@ export class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape markdown formatting characters.
|
||||
* Delegates to @fluxerjs/util escapeMarkdown.
|
||||
* @param {string} text - Raw text
|
||||
* @returns {string} Escaped text
|
||||
* Escape Discord markdown special characters in text.
|
||||
* @param {string} text - The text to escape.
|
||||
* @returns {string} Escaped text, or empty string if falsy.
|
||||
*/
|
||||
static escapeMarkdown(text) {
|
||||
if (!text || typeof text !== "string") return "";
|
||||
@@ -167,9 +148,9 @@ export class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Format number with commas (e.g., 1,000,000)
|
||||
* @param {number} num - Number to format
|
||||
* @returns {string} Formatted number
|
||||
* Format a number with locale-aware thousand separators.
|
||||
* @param {number} num - The number to format.
|
||||
* @returns {string} Formatted number string.
|
||||
*/
|
||||
static formatNumber(num) {
|
||||
if (num === null || num === undefined || isNaN(num)) return "0";
|
||||
@@ -177,9 +158,9 @@ export class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate random unique ID
|
||||
* @param {number} [length=16] - Desired length of ID (8-32 recommended)
|
||||
* @returns {string} Random ID
|
||||
* Generate a unique ID string based on timestamp and random characters.
|
||||
* @param {number} [length=16] - Target length of the ID (clamped 8–32).
|
||||
* @returns {string} A unique alphanumeric ID.
|
||||
*/
|
||||
static uid(length = 16) {
|
||||
const targetLen = Math.max(8, Math.min(length, 32));
|
||||
@@ -195,9 +176,9 @@ export class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a value represents a finite number
|
||||
* @param {string|number} str
|
||||
* @returns {boolean}
|
||||
* Check whether a value is a valid finite number or numeric string.
|
||||
* @param {*} str - Value to check.
|
||||
* @returns {boolean} True if the value is a valid number.
|
||||
*/
|
||||
static isNumber(str) {
|
||||
if (str === null || str === undefined || str === "") return false;
|
||||
@@ -207,10 +188,9 @@ export class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if value is a valid URL
|
||||
* Used by worker.mjs YTUtils.isValidUrl
|
||||
* @param {string} str - String to check
|
||||
* @returns {boolean} True if valid URL
|
||||
* Check whether a string is a valid URL.
|
||||
* @param {string} str - String to check.
|
||||
* @returns {boolean} True if the string is a valid URL.
|
||||
*/
|
||||
static isValidUrl(str) {
|
||||
if (!str || typeof str !== "string") return false;
|
||||
@@ -223,11 +203,11 @@ export class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Clamp number between min and max
|
||||
* @param {number} num - Number to clamp
|
||||
* @param {number} min - Minimum value
|
||||
* @param {number} max - Maximum value
|
||||
* @returns {number} Clamped value
|
||||
* Clamp a number between a minimum and maximum value.
|
||||
* @param {number} num - The number to clamp.
|
||||
* @param {number} min - Minimum value.
|
||||
* @param {number} max - Maximum value.
|
||||
* @returns {number} Clamped value.
|
||||
*/
|
||||
static clamp(num, min, max) {
|
||||
if (isNaN(num)) return min;
|
||||
@@ -235,8 +215,8 @@ export class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Sleep/delay promise
|
||||
* @param {number} ms - Milliseconds to sleep
|
||||
* Return a promise that resolves after a specified delay.
|
||||
* @param {number} ms - Delay in milliseconds.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
static sleep(ms) {
|
||||
@@ -244,12 +224,12 @@ export class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Timeout wrapper for promises
|
||||
* Wrap a promise with a timeout. Rejects if the promise does not settle in time.
|
||||
* @template T
|
||||
* @param {Promise<T>} promise - Promise to wrap
|
||||
* @param {number} ms - Timeout in milliseconds
|
||||
* @param {string} [message="Operation timed out"] - Error message
|
||||
* @returns {Promise<T>}
|
||||
* @param {Promise<T>} promise - The promise to wrap.
|
||||
* @param {number} ms - Timeout in milliseconds.
|
||||
* @param {string} [message="Operation timed out"] - Rejection message.
|
||||
* @returns {Promise<T>} The original promise result, or rejection on timeout.
|
||||
*/
|
||||
static timeout(promise, ms, message = "Operation timed out") {
|
||||
let timerId;
|
||||
@@ -260,14 +240,14 @@ export class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Create progress bar string
|
||||
* @param {number} current - Current position in ms or 0-1 ratio
|
||||
* @param {number} [total] - Total duration in ms (if omitted, current is treated as 0-1 ratio)
|
||||
* @param {number} [length=15] - Bar length in characters
|
||||
* @param {string} [filledChar="━"] - Filled character
|
||||
* @param {string} [emptyChar="─"] - Empty character
|
||||
* @param {string} [indicator="⬤"] - Position indicator
|
||||
* @returns {string} Progress bar string
|
||||
* Generate a text-based progress bar.
|
||||
* @param {number} current - Current progress value or ratio.
|
||||
* @param {number} [total] - Total value. If omitted, current is treated as a 0–1 ratio.
|
||||
* @param {number} [length=15] - Bar length in characters.
|
||||
* @param {string} [filledChar="━"] - Character for the filled portion.
|
||||
* @param {string} [emptyChar="─"] - Character for the empty portion.
|
||||
* @param {string} [indicator="⬤"] - Character for the current position indicator.
|
||||
* @returns {string} The progress bar string.
|
||||
*/
|
||||
static progressBar(
|
||||
current,
|
||||
@@ -301,10 +281,10 @@ export class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Format track info for display
|
||||
* @param {object} track - Track object
|
||||
* @param {boolean} [includeDuration=true] - Include duration
|
||||
* @returns {string} Formatted string
|
||||
* Format a track object into a display string with title, artist, and optional duration.
|
||||
* @param {object} track - Track object with title, author, and optional duration.
|
||||
* @param {boolean} [includeDuration=true] - Whether to include the duration.
|
||||
* @returns {string} Formatted track info string.
|
||||
*/
|
||||
static formatTrackInfo(track, includeDuration = true) {
|
||||
if (!track) return "Unknown Track";
|
||||
@@ -325,9 +305,9 @@ export class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse YouTube-like ISO duration (PT4M13S) to milliseconds
|
||||
* @param {string} isoDuration - ISO 8601 duration
|
||||
* @returns {number} Milliseconds
|
||||
* Parse an ISO 8601 duration string (e.g. "PT1H30M45S") into milliseconds.
|
||||
* @param {string} isoDuration - The ISO duration string.
|
||||
* @returns {number} Duration in milliseconds, or 0 if unparseable.
|
||||
*/
|
||||
static parseISODuration(isoDuration) {
|
||||
if (!isoDuration || typeof isoDuration !== "string") return 0;
|
||||
@@ -345,11 +325,11 @@ export class Utils {
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize text for fuzzy matching: NFKD, strip non-word chars, collapse whitespace, lowercase.
|
||||
* Replaces the duplicated normalizeMatchText / normalizeTrackText functions.
|
||||
* @param {string} value - Raw text to normalize
|
||||
* @param {boolean} [cleanFirst=false] - Run cleanTitle() first (for worker.mjs title matching)
|
||||
* @returns {string} Normalized text
|
||||
* Normalize text by stripping non-alphanumeric characters, lowercasing, and trimming.
|
||||
* Optionally cleans the title first using cleanTitle.
|
||||
* @param {string} value - The text to normalize.
|
||||
* @param {boolean} [cleanFirst=false] - Whether to run cleanTitle before normalizing.
|
||||
* @returns {string} Normalized lowercase text.
|
||||
*/
|
||||
static normalizeText(value, cleanFirst = false) {
|
||||
let text = String(value ?? "");
|
||||
|
||||
+34
-42
@@ -1,52 +1,45 @@
|
||||
/**
|
||||
* @file API.mjs — API constants — FluxerList API endpoints, authentication headers, pagination defaults, and cache TTL values
|
||||
* @module src.constants.API
|
||||
*/
|
||||
/** @module constants/API */
|
||||
|
||||
/**
|
||||
* API.mjs — Single source of truth for all external API constants.
|
||||
*
|
||||
* FLUXERLIST — FluxerList vote-tracking API configuration & endpoints
|
||||
* FLUXERLIST_AUTH — Authentication header format & key prefix
|
||||
* FLUXERLIST_LIMITS — Pagination & rate limit defaults
|
||||
*
|
||||
* Edit only here; FluxerListManager.mjs and commands/vote.mjs import from this file.
|
||||
* FluxerList API configuration.
|
||||
* @namespace FLUXERLIST
|
||||
*/
|
||||
|
||||
export const FLUXERLIST = {
|
||||
/** Base URL for all FluxerList API v1 endpoints */
|
||||
/** Base URL for the FluxerList REST API. @type {string} */
|
||||
BASE_URL: "https://fluxerlist.com/api/v1",
|
||||
|
||||
/** FluxerList website base URL (for vote links, profiles, etc.) */
|
||||
/** Public FluxerList website URL. @type {string} */
|
||||
SITE_URL: "https://fluxerlist.com",
|
||||
|
||||
/** Available endpoint paths — append :id and query params at call time */
|
||||
/** API endpoint path templates. @type {{ SERVER_VOTERS: string, BOT_VOTERS: string }} */
|
||||
ENDPOINTS: {
|
||||
/** GET /api/v1/servers/:id/voters — voters for a server */
|
||||
SERVER_VOTERS: "/servers/:id/voters",
|
||||
|
||||
/** GET /api/v1/bots/:id/voters — voters for a bot */
|
||||
BOT_VOTERS: "/bots/:id/voters",
|
||||
},
|
||||
|
||||
/** Resource types supported by the API (used in command choices) */
|
||||
/** Accepted resource type identifiers. @type {string[]} */
|
||||
RESOURCE_TYPES: ["server", "bot"],
|
||||
|
||||
/** Thumbnail image for vote embeds (FluxerList branding) */
|
||||
/** Thumbnail API base URL. @type {string} */
|
||||
THUMBNAIL: "https://fluxerlist.com/api/v1",
|
||||
};
|
||||
|
||||
/**
|
||||
* FluxerList authentication helpers.
|
||||
* @namespace FLUXERLIST_AUTH
|
||||
*/
|
||||
export const FLUXERLIST_AUTH = {
|
||||
/** Header name for API key authentication */
|
||||
/** HTTP header name for auth. @type {string} */
|
||||
HEADER: "Authorization",
|
||||
|
||||
/** Prefix prepended to all FluxerList API keys */
|
||||
/** Required API key prefix. @type {string} */
|
||||
KEY_PREFIX: "fl_",
|
||||
|
||||
/**
|
||||
* Build the Authorization header value.
|
||||
* @param {string} apiKey - The raw API key (with or without the fl_ prefix)
|
||||
* @returns {string} Header value in "Bearer fl_xxx" format
|
||||
* 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)
|
||||
@@ -56,29 +49,30 @@ export const FLUXERLIST_AUTH = {
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* FluxerList pagination and cache limits.
|
||||
* @namespace FLUXERLIST_LIMITS
|
||||
*/
|
||||
export const FLUXERLIST_LIMITS = {
|
||||
/** Default page number when none is specified */
|
||||
/** Default page number. @type {number} */
|
||||
DEFAULT_PAGE: 1,
|
||||
|
||||
/** Default number of results per page */
|
||||
/** Default items-per-page. @type {number} */
|
||||
DEFAULT_LIMIT: 50,
|
||||
|
||||
/** Maximum number of results per page (API enforced) */
|
||||
/** Maximum allowed items-per-page. @type {number} */
|
||||
MAX_LIMIT: 100,
|
||||
|
||||
/** Cache TTL in milliseconds for voter list responses (5 min) */
|
||||
/** Cache time-to-live in milliseconds. @type {number} */
|
||||
CACHE_TTL_MS: 5 * 60 * 1000,
|
||||
};
|
||||
|
||||
/**
|
||||
* Build a full FluxerList API URL by replacing :id in the endpoint path.
|
||||
*
|
||||
* @param {string} endpoint - One of FLUXERLIST.ENDPOINTS values (e.g. "/servers/:id/voters")
|
||||
* @param {string} resourceId - The server or bot ID or slug to substitute for :id
|
||||
* @param {object} [queryParams] - Optional query parameters
|
||||
* @param {number} [queryParams.page] - Page number (default: 1)
|
||||
* @param {number} [queryParams.limit] - Results per page, max 100 (default: 50)
|
||||
* @returns {string} Full URL ready for fetch()
|
||||
* 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));
|
||||
@@ -95,12 +89,10 @@ export function buildFluxerListUrl(endpoint, resourceId, queryParams = {}) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the vote/profile link for a resource on FluxerList.
|
||||
* Both vote and profile links share the same URL pattern.
|
||||
*
|
||||
* @param {"server"|"bot"} type - Resource type
|
||||
* @param {string} resourceId - The server or bot ID or slug
|
||||
* @returns {string} URL to the resource page on FluxerList
|
||||
* 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";
|
||||
|
||||
@@ -1,711 +0,0 @@
|
||||
/**
|
||||
* @file FluxerRevoice.mjs — FluxerRevoice — voice connection adapter that bridges Fluxer gateway with LiveKit rooms, replacing revoice.js API calls
|
||||
* @module src.constants.FluxerRevoice
|
||||
*/
|
||||
|
||||
/**
|
||||
* FluxerRevoice.mjs — Revoice-compatible adapter that uses the Fluxer API
|
||||
*
|
||||
* This module provides the same interface as revoice.js's `Revoice` class
|
||||
* but uses the Fluxer gateway (via @fluxerjs/voice) to obtain LiveKit
|
||||
* credentials instead of POSTing to a third-party REST API.
|
||||
*
|
||||
* Why this exists:
|
||||
* revoice.js internally calls `POST /channels/{id}/join_call` on
|
||||
* a third-party API with an `X-Bot-Token` header. A Fluxer
|
||||
* bot token is NOT valid on that API, resulting in a 401.
|
||||
* Fluxer's voice join flow instead uses the gateway WebSocket:
|
||||
* 1. Bot sends VOICE_STATE_UPDATE opcode
|
||||
* 2. Gateway responds with VOICE_STATE_UPDATE (ack)
|
||||
* 3. Gateway sends VOICE_SERVER_UPDATE with { endpoint, token }
|
||||
* 4. The endpoint/token are LiveKit credentials
|
||||
*
|
||||
* This adapter wraps @fluxerjs/voice's VoiceManager.join() and returns
|
||||
* a `FluxerVoiceConnection` that is API-compatible with revoice.js's
|
||||
* `VoiceConnection`, so Player.mjs and MediaPlayer work unchanged.
|
||||
*
|
||||
* Reference: https://fluxer.js.org/v/latest/guides/voice
|
||||
*
|
||||
* IMPORTANT: @livekit/rtc-node (Node.js SDK) does NOT have `room.state`.
|
||||
* ✅ room.isConnected — boolean getter (true when connected)
|
||||
* ✅ room.connectionState — ConnectionState enum getter
|
||||
* (CONN_DISCONNECTED = 0, CONN_CONNECTED = 1, CONN_RECONNECTING = 2)
|
||||
* ❌ room.state — does NOT exist (that's the browser SDK API)
|
||||
*/
|
||||
|
||||
import { EventEmitter } from "node:events";
|
||||
import { getVoiceManager } from "@fluxerjs/voice";
|
||||
import { cleanId } from "../Utils.mjs";
|
||||
|
||||
export const ConnectionState = Object.freeze({
|
||||
CONN_DISCONNECTED: 0,
|
||||
CONN_CONNECTED: 1,
|
||||
CONN_RECONNECTING: 2,
|
||||
});
|
||||
|
||||
export const LKRoomEvent = Object.freeze({
|
||||
ConnectionStateChanged: "connectionStateChanged",
|
||||
Disconnected: "disconnected",
|
||||
ParticipantConnected: "participantConnected",
|
||||
ParticipantDisconnected:"participantDisconnected",
|
||||
});
|
||||
|
||||
import { logger } from "./Logger.mjs";
|
||||
|
||||
/**
|
||||
* LiveKit log filter — intercepts LiveKit SDK noise without monkey-patching
|
||||
* console.log or process.stdout globally. Applied per-room by setting
|
||||
* the room's logger to a filtered version.
|
||||
*/
|
||||
const LIVEKIT_LOG_PREFIXES = ["[voice LiveKitRtc]", "lk-rtc"];
|
||||
|
||||
const LIVEKIT_NOISY_PATTERNS = [
|
||||
"Room reconnecting",
|
||||
"Room reconnected",
|
||||
"Room disconnected",
|
||||
"emitting disconnect",
|
||||
"emitting reconnecting",
|
||||
"emitting reconnected",
|
||||
"Connect callback received",
|
||||
"signal reconnecting",
|
||||
"signal reconnected",
|
||||
"resume requested",
|
||||
"restart requested",
|
||||
];
|
||||
|
||||
let _liveKitLogInstalled = false;
|
||||
|
||||
function isLiveKitLogMessage(...args) {
|
||||
if (args.length === 1 && typeof args[0] === "string") {
|
||||
if (args[0].startsWith("{")) {
|
||||
try {
|
||||
const parsed = JSON.parse(args[0]);
|
||||
if (parsed.name === "lk-rtc") return true;
|
||||
} catch (e) { logger.warn("[FluxerRevoice] Error parsing livekit args:", e?.message); }
|
||||
}
|
||||
if (LIVEKIT_LOG_PREFIXES.some(p => args[0].includes(p))) return true;
|
||||
if (LIVEKIT_NOISY_PATTERNS.some(p => args[0].includes(p))) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Install a permanent console.log/info filter that suppresses LiveKit SDK noise.
|
||||
* Called once on FluxerRevoice construction. Unlike withSuppressedLiveKitLogs
|
||||
* (which is scoped to a callback), this persists for the lifetime of the process.
|
||||
*/
|
||||
function installLiveKitLogFilter() {
|
||||
if (_liveKitLogInstalled) return;
|
||||
_liveKitLogInstalled = true;
|
||||
|
||||
const origLog = console.log;
|
||||
const origInfo = console.info;
|
||||
|
||||
const filteredLog = function (...args) {
|
||||
if (isLiveKitLogMessage(...args)) return;
|
||||
return origLog.apply(console, args);
|
||||
};
|
||||
const filteredInfo = function (...args) {
|
||||
if (isLiveKitLogMessage(...args)) return;
|
||||
return origInfo.apply(console, args);
|
||||
};
|
||||
|
||||
console.log = filteredLog;
|
||||
console.info = filteredInfo;
|
||||
}
|
||||
|
||||
/**
|
||||
* Temporarily suppress LiveKit SDK log noise during room setup.
|
||||
* Unlike the old global monkey-patch, this is scoped to a callback
|
||||
* and restores the original console.log when done.
|
||||
*/
|
||||
function withSuppressedLiveKitLogs(fn) {
|
||||
const origLog = console.log;
|
||||
console.log = function (...args) {
|
||||
if (isLiveKitLogMessage(...args)) return;
|
||||
origLog.apply(console, args);
|
||||
};
|
||||
try {
|
||||
return fn();
|
||||
} finally {
|
||||
console.log = origLog;
|
||||
}
|
||||
}
|
||||
|
||||
/** Helper: returns a human-readable label for a ConnectionState value */
|
||||
function stateLabel(cs) {
|
||||
if (cs === ConnectionState.CONN_CONNECTED) return "CONN_CONNECTED";
|
||||
if (cs === ConnectionState.CONN_DISCONNECTED) return "CONN_DISCONNECTED";
|
||||
if (cs === ConnectionState.CONN_RECONNECTING) return "CONN_RECONNECTING";
|
||||
if (cs === 1) return "CONN_CONNECTED(1)";
|
||||
if (cs === 0) return "CONN_DISCONNECTED(0)";
|
||||
if (cs === 2) return "CONN_RECONNECTING(2)";
|
||||
return String(cs);
|
||||
}
|
||||
|
||||
/**
|
||||
* A voice connection that wraps a LiveKit Room obtained via the Fluxer
|
||||
* gateway. Exposes the same interface as revoice.js's VoiceConnection:
|
||||
*
|
||||
* .room — LiveKit Room
|
||||
* .channelId — the voice channel ID
|
||||
* .connected — boolean (getter, reads from room.isConnected)
|
||||
* .users — array (minimal; real tracking is via observedVoiceUsers)
|
||||
* .disconnect() — tear down the LiveKit connection
|
||||
* .leave() — alias for disconnect()
|
||||
* Events: "disconnect", "error", "autoleave"
|
||||
*/
|
||||
export class FluxerVoiceConnection extends EventEmitter {
|
||||
/** @type {any} LiveKit Room instance from @fluxerjs/voice */
|
||||
room = null;
|
||||
channelId = null;
|
||||
_voice = null;
|
||||
_connected = false;
|
||||
_users = [];
|
||||
_destroyed = false;
|
||||
|
||||
_nativeConn = null;
|
||||
|
||||
/**
|
||||
* Users currently in this voice channel.
|
||||
* Derived from the parent FluxerRevoice's unified users map (single source of truth).
|
||||
* This prevents the old divergence bug where the array and Map could get out of sync.
|
||||
*/
|
||||
get users() {
|
||||
return this._users;
|
||||
}
|
||||
|
||||
set users(val) {
|
||||
this._users = Array.isArray(val) ? val : [];
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} channelId Voice channel ID this connection is bound to
|
||||
* @param {FluxerRevoice} voice Parent FluxerRevoice instance that owns the join queue and users map
|
||||
* @param {Object} [opts={}] Connection options
|
||||
* @param {any} [opts.room] LiveKit Room instance, if already available at construction time
|
||||
*/
|
||||
constructor(channelId, voice, opts = {}) {
|
||||
super();
|
||||
this.channelId = channelId;
|
||||
this._voice = voice;
|
||||
this.room = opts.room ?? null;
|
||||
this._nativeConn = opts.nativeConnection ?? null;
|
||||
this._connected = !!(this.room && this.room.isConnected);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this connection is currently alive.
|
||||
* Reads from the LiveKit Room's `isConnected` boolean getter,
|
||||
* which is the correct API in @livekit/rtc-node (Node.js SDK).
|
||||
*/
|
||||
get connected() {
|
||||
if (this._destroyed) return false;
|
||||
if (this.room) return this.room.isConnected;
|
||||
return this._connected;
|
||||
}
|
||||
|
||||
set connected(val) {
|
||||
this._connected = !!val;
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnect from the voice channel.
|
||||
* Tries the @fluxerjs/voice native disconnect first, then falls back
|
||||
* to closing the LiveKit Room directly.
|
||||
*/
|
||||
async disconnect() {
|
||||
if (this._destroyed) return;
|
||||
if (this._voice && this.channelId) {
|
||||
this._voice.markIntentionalDisconnect(this.channelId);
|
||||
const guildId = this._voice._resolveGuildForChannel?.(this.channelId) ?? null;
|
||||
this._voice._leaveGateway?.(this.channelId, guildId);
|
||||
}
|
||||
this._destroyed = true;
|
||||
this._connected = false;
|
||||
|
||||
if (this.room) {
|
||||
try {
|
||||
await this.room.disconnect();
|
||||
} catch (e) {
|
||||
logger.warn("[FluxerVoiceConnection] Room disconnect error:", e?.message);
|
||||
}
|
||||
}
|
||||
if (this._nativeConn && typeof this._nativeConn.disconnect === "function") {
|
||||
try {
|
||||
await this._nativeConn.disconnect();
|
||||
} catch (e) {
|
||||
logger.warn("[FluxerVoiceConnection] Native disconnect error:", e?.message);
|
||||
}
|
||||
}
|
||||
|
||||
this.emit("disconnect");
|
||||
this.removeAllListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
* Leave — alias for disconnect (matches revoice.js VoiceConnection API).
|
||||
*/
|
||||
async leave() {
|
||||
return this.disconnect();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoice-compatible class that uses the Fluxer gateway for voice joins.
|
||||
*
|
||||
* Usage (drop-in for `new Revoice(token)`):
|
||||
*
|
||||
*
|
||||
* this.revoice = new Revoice(config.token);
|
||||
*
|
||||
*
|
||||
* this.revoice = new FluxerRevoice(client);
|
||||
*/
|
||||
export class FluxerRevoice extends EventEmitter {
|
||||
/** @type {import("@fluxerjs/core").Client} */
|
||||
client = null;
|
||||
connections = new Map();
|
||||
users = new Map();
|
||||
|
||||
/** @type {Map<string, Promise>} */
|
||||
_guildJoinQueue = new Map();
|
||||
|
||||
/** @type {Promise} Global join serializer — only one join at a time across all guilds */
|
||||
_globalJoinQueue = Promise.resolve();
|
||||
/** @type {number} Minimum delay between ANY two joins (ms), even across guilds.
|
||||
* This delay runs AFTER the previous join completes and BEFORE the next
|
||||
* one starts, giving the Fluxer gateway time to clean up the previous
|
||||
* voice session. */
|
||||
_globalJoinDelay = 1500;
|
||||
|
||||
/** @type {Set<string>} Channel IDs where disconnect is expected (bot-initiated) */
|
||||
_intentionalDisconnects = new Set();
|
||||
|
||||
/** @type {Map<string, NodeJS.Timeout>} Per-channel timeout tokens for intentional disconnect marks */
|
||||
_intentionalDisconnectTokens = new Map();
|
||||
|
||||
/** @type {FluxerRevoice|null} Singleton instance */
|
||||
static _instance = null;
|
||||
|
||||
/**
|
||||
* Get or create the singleton FluxerRevoice instance.
|
||||
* @param {import("@fluxerjs/core").Client} client
|
||||
* @returns {FluxerRevoice}
|
||||
*/
|
||||
static getInstance(client) {
|
||||
if (!FluxerRevoice._instance) {
|
||||
FluxerRevoice._instance = new FluxerRevoice(client);
|
||||
}
|
||||
return FluxerRevoice._instance;
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("@fluxerjs/core").Client} client Fluxer client used to resolve channels/guilds and send gateway leave signals
|
||||
*/
|
||||
constructor(client) {
|
||||
super();
|
||||
if (FluxerRevoice._instance && FluxerRevoice._instance !== this) {
|
||||
logger.warn(
|
||||
`[FluxerRevoice] Duplicate instance detected! Use FluxerRevoice.getInstance().`
|
||||
);
|
||||
}
|
||||
if (!client) throw new Error("FluxerRevoice requires a Fluxer client instance");
|
||||
this.client = client;
|
||||
if (!FluxerRevoice._instance) FluxerRevoice._instance = this;
|
||||
installLiveKitLogFilter();
|
||||
logger.player("[FluxerRevoice] Instance created with Fluxer client.");
|
||||
}
|
||||
|
||||
/**
|
||||
* Mark a channel as expecting an intentional disconnect so the
|
||||
* LKRoomEvent.Disconnected handler can log it correctly.
|
||||
* @param {string} channelId
|
||||
*/
|
||||
markIntentionalDisconnect(channelId) {
|
||||
const key = String(channelId);
|
||||
this._intentionalDisconnects.add(key);
|
||||
const prev = this._intentionalDisconnectTokens.get(key);
|
||||
if (prev) clearTimeout(prev);
|
||||
this._intentionalDisconnectTokens.set(key, setTimeout(() => {
|
||||
this._intentionalDisconnects.delete(key);
|
||||
this._intentionalDisconnectTokens.delete(key);
|
||||
}, 10_000));
|
||||
const cleanChannelId = cleanId(key);
|
||||
if (this.client?._remix?.intentionalLeaves && !this.client._remix.intentionalLeaves.has(cleanChannelId)) {
|
||||
this.client._remix.intentionalLeaves.set(cleanChannelId, setTimeout(() => {
|
||||
this.client._remix.intentionalLeaves.delete(cleanChannelId);
|
||||
}, 10_000));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Send a channel-specific leave signal to the Fluxer gateway so it
|
||||
* knows the bot is no longer in the given channel. Without this, the
|
||||
* gateway may think the bot is still connected and won't send a fresh
|
||||
* VOICE_SERVER_UPDATE on the next VoiceManager.join() call, causing the
|
||||
* rejoin to hang or fail.
|
||||
*
|
||||
* IMPORTANT: Only uses channel-specific leave (vm.leaveChannel).
|
||||
* Guild-level leave (vm.leave / vm.updateVoiceState with null channel)
|
||||
* disconnects ALL voice channels in that guild, which is catastrophic
|
||||
* for multi-voice setups where the bot is in multiple channels with
|
||||
* 24/7 enabled. If vm.leaveChannel is unavailable, the gateway leave
|
||||
* is skipped entirely rather than risk disconnecting other channels.
|
||||
*
|
||||
* @param {string} channelId — The channel ID to leave
|
||||
* @param {string} [guildId] — Unused, kept for API compatibility
|
||||
*/
|
||||
_leaveGateway(channelId, guildId = null) {
|
||||
try {
|
||||
const vm = getVoiceManager(this.client);
|
||||
if (!vm) return;
|
||||
|
||||
if (typeof vm.leaveChannel === "function") {
|
||||
try {
|
||||
vm.leaveChannel(channelId);
|
||||
logger.player(`[FluxerRevoice] Sent channel-specific gateway leave via vm.leaveChannel() for channel ${channelId}`);
|
||||
return;
|
||||
} catch (e) {
|
||||
logger.warn(`[FluxerRevoice] vm.leaveChannel() failed for channel ${channelId}: ${e?.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
logger.warn(
|
||||
`[FluxerRevoice] No channel-specific leave API available for channel ${channelId}. ` +
|
||||
`Skipping gateway leave to avoid disconnecting other voice channels in the guild.`
|
||||
);
|
||||
} catch (e) {
|
||||
logger.warn(`[FluxerRevoice] Gateway leave signal failed for ${channelId}: ${e?.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the guild ID for a given channel ID from the client cache.
|
||||
* @param {string} channelId
|
||||
* @returns {string|null}
|
||||
*/
|
||||
_resolveGuildForChannel(channelId) {
|
||||
try {
|
||||
const ch = this.client.channels?.get?.(channelId);
|
||||
return ch?.guildId ?? ch?.guild?.id ?? null;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Fully tear down a stale FluxerVoiceConnection: disconnect the native
|
||||
* @fluxerjs/voice connection, close the LiveKit room, remove from the
|
||||
* connections map, and send a gateway leave signal.
|
||||
*
|
||||
* @param {string} channelId
|
||||
* @param {FluxerVoiceConnection} existing
|
||||
*/
|
||||
async _destroyStaleConnection(channelId, existing) {
|
||||
this.connections.delete(channelId);
|
||||
this.markIntentionalDisconnect(channelId);
|
||||
const staleGuildId = this._resolveGuildForChannel(channelId);
|
||||
this._leaveGateway(channelId, staleGuildId);
|
||||
|
||||
if (existing.room) {
|
||||
try {
|
||||
await existing.room.disconnect();
|
||||
} catch (e) {
|
||||
logger.warn("[FluxerRevoice] Stale room disconnect error:", e?.message);
|
||||
}
|
||||
}
|
||||
if (existing._nativeConn && typeof existing._nativeConn.disconnect === "function") {
|
||||
try {
|
||||
await existing._nativeConn.disconnect();
|
||||
} catch (e) {
|
||||
logger.warn(`[FluxerRevoice] Stale native disconnect error for ${channelId}: ${e?.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
existing._destroyed = true;
|
||||
existing._connected = false;
|
||||
try { existing.removeAllListeners(); } catch (e) { logger.warn("[FluxerRevoice] Error removing listeners:", e?.message); }
|
||||
}
|
||||
|
||||
/**
|
||||
* Join a voice channel using the Fluxer gateway.
|
||||
*
|
||||
* This sends a VOICE_STATE_UPDATE through the Fluxer gateway, receives
|
||||
* VOICE_SERVER_UPDATE with LiveKit credentials, then connects to the
|
||||
* LiveKit room — the same flow @fluxerjs/voice uses internally.
|
||||
*
|
||||
* @param {string} channelId — The voice channel ID to join
|
||||
* @param {boolean} [_leaveIfEmpty=false] — Not used (compatibility param)
|
||||
* @returns {Promise<FluxerVoiceConnection>}
|
||||
*/
|
||||
async join(channelId, _leaveIfEmpty = false) {
|
||||
const joinOperation = async () => {
|
||||
await new Promise(r => setTimeout(r, this._globalJoinDelay));
|
||||
return await this._joinInternal(channelId, _leaveIfEmpty);
|
||||
};
|
||||
|
||||
const prevQueue = this._globalJoinQueue;
|
||||
const ourResult = prevQueue.then(() => joinOperation());
|
||||
this._globalJoinQueue = ourResult.catch((err) => {
|
||||
logger.warn("[FluxerRevoice] Previous join in queue failed:", err?.message ?? err);
|
||||
});
|
||||
return await ourResult;
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal join implementation — called by join() through the global queue.
|
||||
* Do NOT call this directly; always use join() to ensure serialization.
|
||||
*
|
||||
* @param {string} channelId
|
||||
* @param {boolean} _leaveIfEmpty
|
||||
* @returns {Promise<FluxerVoiceConnection>}
|
||||
*/
|
||||
async _joinInternal(channelId, _leaveIfEmpty = false) {
|
||||
let guildId = null;
|
||||
try {
|
||||
const ch = this.client.channels?.get?.(channelId);
|
||||
guildId = ch?.guildId ?? ch?.guild?.id ?? null;
|
||||
} catch (e) {
|
||||
logger.debug("[FluxerRevoice] Could not resolve guild for channel:", e?.message);
|
||||
}
|
||||
|
||||
if (this.connections.has(channelId)) {
|
||||
const existing = this.connections.get(channelId);
|
||||
if (existing && !existing._destroyed && existing.room && existing.room.isConnected) {
|
||||
logger.player(`[FluxerRevoice] Already connected to ${channelId}, returning existing connection`);
|
||||
return existing;
|
||||
}
|
||||
logger.player(
|
||||
`[FluxerRevoice] Stale connection for ${channelId} ` +
|
||||
`(isConnected: ${existing?.room?.isConnected ?? false}, ` +
|
||||
`destroyed: ${existing?._destroyed ?? true}) — cleaning up and rejoining`
|
||||
);
|
||||
await this._destroyStaleConnection(channelId, existing);
|
||||
}
|
||||
|
||||
logger.player(`[FluxerRevoice] Joining channel ${channelId} via Fluxer gateway...`);
|
||||
|
||||
let channel = this.client.channels?.get?.(channelId);
|
||||
if (!channel) {
|
||||
try {
|
||||
channel = await this.client.channels.fetch(channelId);
|
||||
} catch (e) {
|
||||
throw new Error(`Could not fetch channel ${channelId}: ${e.message}`);
|
||||
}
|
||||
}
|
||||
if (!channel) {
|
||||
throw new Error(`Channel not found: ${channelId}`);
|
||||
}
|
||||
|
||||
const channelGuildId = guildId ?? channel?.guildId ?? channel?.guild?.id ?? null;
|
||||
|
||||
const vm = getVoiceManager(this.client);
|
||||
if (!vm) {
|
||||
throw new Error(`Fluxer voice join failed for ${channelId}: VoiceManager not available — call getVoiceManager(client) before login`);
|
||||
}
|
||||
|
||||
let nativeConnection;
|
||||
try {
|
||||
nativeConnection = await vm.join(channel);
|
||||
} catch (e) {
|
||||
throw new Error(`Fluxer voice join failed for ${channelId}: ${e.message}`);
|
||||
}
|
||||
|
||||
if (!nativeConnection) {
|
||||
throw new Error(`Fluxer voice join returned null for ${channelId}`);
|
||||
}
|
||||
|
||||
logger.player(`[FluxerRevoice] Gateway join successful for ${channelId}`);
|
||||
|
||||
let room = null;
|
||||
|
||||
if (nativeConnection.room) {
|
||||
room = nativeConnection.room;
|
||||
logger.player(`[FluxerRevoice] Got LiveKit room from native connection (isConnected: ${room.isConnected}, connectionState: ${stateLabel(room.connectionState)})`);
|
||||
}
|
||||
|
||||
|
||||
if (room && typeof room.setLogger === "function") {
|
||||
try {
|
||||
room.setLogger({
|
||||
debug: () => {},
|
||||
info: () => {},
|
||||
warn: (...args) => { if (!isLiveKitLogMessage(...args)) logger.warn("[LiveKit]", ...args); },
|
||||
error: (...args) => logger.error("[LiveKit]", ...args),
|
||||
});
|
||||
} catch (e) { logger.warn("[FluxerRevoice] Error creating LiveKit logger adapter:", e?.message); }
|
||||
}
|
||||
|
||||
if (!room) {
|
||||
try { await nativeConnection.disconnect(); } catch (e) {
|
||||
logger.warn("[FluxerRevoice] Cleanup disconnect error:", e?.message);
|
||||
}
|
||||
throw new Error(
|
||||
`Fluxer voice connection for ${channelId} does not expose a LiveKit Room. ` +
|
||||
`Music playback requires a LiveKit-based voice server.`
|
||||
);
|
||||
}
|
||||
|
||||
const maxWait = 10_000;
|
||||
const startTime = Date.now();
|
||||
|
||||
if (!room.isConnected) {
|
||||
let eventResolved = false;
|
||||
const statePromise = new Promise((resolve) => {
|
||||
const handler = (cs) => {
|
||||
if (eventResolved) return;
|
||||
if (cs === ConnectionState.CONN_CONNECTED || cs === 1) {
|
||||
eventResolved = true;
|
||||
room.off(LKRoomEvent.ConnectionStateChanged, handler);
|
||||
resolve();
|
||||
} else if (cs === ConnectionState.CONN_DISCONNECTED || cs === 0) {
|
||||
eventResolved = true;
|
||||
room.off(LKRoomEvent.ConnectionStateChanged, handler);
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
room.on(LKRoomEvent.ConnectionStateChanged, handler);
|
||||
});
|
||||
|
||||
while (!room.isConnected && (Date.now() - startTime) < maxWait) {
|
||||
await Promise.race([
|
||||
statePromise,
|
||||
new Promise(r => setTimeout(r, 200)),
|
||||
]);
|
||||
|
||||
if (room.isConnected) break;
|
||||
|
||||
const cs = room.connectionState;
|
||||
if (cs === ConnectionState.CONN_DISCONNECTED || cs === 0) break;
|
||||
}
|
||||
}
|
||||
|
||||
const finalConnected = room.isConnected;
|
||||
const finalCS = room.connectionState;
|
||||
|
||||
if (!finalConnected && (finalCS === ConnectionState.CONN_DISCONNECTED || finalCS === 0)) {
|
||||
try { await nativeConnection.disconnect(); } catch (e) {
|
||||
logger.warn("[FluxerRevoice] Cleanup disconnect error:", e?.message);
|
||||
}
|
||||
throw new Error(`LiveKit room in disconnected state: ${stateLabel(finalCS)}`);
|
||||
}
|
||||
|
||||
logger.player(`[FluxerRevoice] LiveKit room ready (isConnected: ${finalConnected}, connectionState: ${stateLabel(finalCS)})`);
|
||||
|
||||
|
||||
const connection = withSuppressedLiveKitLogs(() => {
|
||||
const conn = new FluxerVoiceConnection(channelId, this, {
|
||||
room,
|
||||
nativeConnection,
|
||||
});
|
||||
|
||||
room.on(LKRoomEvent.ConnectionStateChanged, (cs) => {
|
||||
if (cs === ConnectionState.CONN_RECONNECTING || cs === 2) {
|
||||
logger.player(`[FluxerRevoice] Room reconnecting for channel ${channelId}`);
|
||||
} else if (cs === ConnectionState.CONN_CONNECTED || cs === 1) {
|
||||
if (conn._destroyed) return;
|
||||
conn._connected = true;
|
||||
logger.player(`[FluxerRevoice] Room (re)connected for channel ${channelId}`);
|
||||
}
|
||||
});
|
||||
|
||||
room.on(LKRoomEvent.Disconnected, (reason) => {
|
||||
if (conn._destroyed) return;
|
||||
const isIntentional = this._intentionalDisconnects.has(String(channelId));
|
||||
const reasonLabel = isIntentional ? "intentional" : (reason ?? "unexpected");
|
||||
logger.player(`[FluxerRevoice] Room disconnected: ${reasonLabel}`);
|
||||
conn._connected = false;
|
||||
conn._destroyed = true;
|
||||
|
||||
this.connections.delete(channelId);
|
||||
|
||||
if (!isIntentional) {
|
||||
this._leaveGateway(channelId, channelGuildId);
|
||||
|
||||
if (nativeConnection && typeof nativeConnection.disconnect === "function") {
|
||||
try { nativeConnection.disconnect(); } catch (e) {
|
||||
logger.warn("[FluxerRevoice] Native disconnect error:", e?.message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (conn.listenerCount("disconnect") > 0) {
|
||||
conn.emit("disconnect");
|
||||
}
|
||||
});
|
||||
|
||||
room.on(LKRoomEvent.ParticipantConnected, (participant) => {
|
||||
const userId = participant?.identity ?? participant?.sid;
|
||||
if (userId) {
|
||||
const uKey = `${channelId}:${userId}`;
|
||||
this.users.set(uKey, { id: userId, connectedTo: channelId });
|
||||
conn._users = [...this.users.values()].filter(u => u.connectedTo === channelId);
|
||||
conn.emit("userjoin", userId);
|
||||
}
|
||||
});
|
||||
|
||||
room.on(LKRoomEvent.ParticipantDisconnected, (participant) => {
|
||||
const userId = participant?.identity ?? participant?.sid;
|
||||
if (userId) {
|
||||
const uKey = `${channelId}:${userId}`;
|
||||
this.users.delete(uKey);
|
||||
conn._users = [...this.users.values()].filter(u => u.connectedTo === channelId);
|
||||
conn.emit("userleave", userId);
|
||||
}
|
||||
});
|
||||
|
||||
/*
|
||||
* Handle the VoiceManager's serverLeave event, which fires when
|
||||
* the Fluxer/LiveKit server terminates the session server-side.
|
||||
* Without this handler the bot never learns the session is dead,
|
||||
* leading to "validate request timed out" on the next join attempt.
|
||||
*
|
||||
* Reference: https://fluxer.js.org/v/latest/guides/voice
|
||||
* "If using LiveKit, the server may emit serverLeave.
|
||||
* Listen and reconnect if needed."
|
||||
*/
|
||||
if (nativeConnection && typeof nativeConnection.on === "function") {
|
||||
nativeConnection.on("serverLeave", () => {
|
||||
if (conn._destroyed) return;
|
||||
logger.player(`[FluxerRevoice] serverLeave received for channel ${channelId} — cleaning up`);
|
||||
conn._connected = false;
|
||||
conn._destroyed = true;
|
||||
this.connections.delete(channelId);
|
||||
this._leaveGateway(channelId, channelGuildId);
|
||||
if (room) {
|
||||
try { room.disconnect().catch(() => {}); } catch (_) { /* already gone */ }
|
||||
}
|
||||
if (conn.listenerCount("disconnect") > 0) {
|
||||
conn.emit("disconnect");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
this.connections.set(channelId, conn);
|
||||
|
||||
if (_leaveIfEmpty) {
|
||||
conn.on("userleave", () => {
|
||||
const remoteCount = room.remoteParticipants?.size ?? 0;
|
||||
if (remoteCount === 0) {
|
||||
logger.player(`[FluxerRevoice] Room empty, triggering autoleave for ${channelId}`);
|
||||
conn.emit("autoleave");
|
||||
this.connections.delete(channelId);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return conn;
|
||||
});
|
||||
|
||||
return connection;
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a connection from the map (called during player leave/cleanup).
|
||||
* @param {string} channelId
|
||||
*/
|
||||
deleteConnection(channelId) {
|
||||
this.connections.delete(channelId);
|
||||
}
|
||||
}
|
||||
@@ -1,72 +1,39 @@
|
||||
/** @module constants/Helpers247 */
|
||||
|
||||
/**
|
||||
* @file Helpers247.mjs — Helpers247 — per-channel 24/7 mode management (on/auto/off) with guild-wide backward compatibility
|
||||
* @module src.constants.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).
|
||||
*/
|
||||
|
||||
/**
|
||||
* Shared 24/7 mode helpers.
|
||||
*
|
||||
* The per-channel mode map (`stay_247_modes`) stores each channel's 24/7 mode
|
||||
* independently so a guild can have channel A on "on" and channel B on "auto".
|
||||
*
|
||||
* Format in settings:
|
||||
* stay_247_modes: { "1483577390731942416": "on", "1478011355626209606": "auto" }
|
||||
*
|
||||
* For backward compatibility, `stay_247_mode` (guild-wide string) is still
|
||||
* written when any channel is updated. All reads go through
|
||||
* `get247ChannelMode()` which prefers the per-channel entry and falls back
|
||||
* to the guild-wide value.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Get the 24/7 mode for a specific channel.
|
||||
*
|
||||
* @param {{ get: (key: string) => any }} set ServerSettings instance
|
||||
* @param {string} channelId Clean (digits-only) channel ID
|
||||
* @returns {"on"|"auto"|"off"}
|
||||
* 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 modes = set.get("stay_247_modes");
|
||||
if (modes && typeof modes === "object" && !Array.isArray(modes)) {
|
||||
const perChannel = modes[channelId];
|
||||
if (perChannel === "on" || perChannel === "auto" || perChannel === "off") return perChannel;
|
||||
}
|
||||
const guildMode = set.get("stay_247_mode") ?? "off";
|
||||
return guildMode;
|
||||
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";
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the 24/7 mode for a specific channel.
|
||||
*
|
||||
* @param {{ get: (key: string) => any, set: (key: string, value: any) => void }} set
|
||||
* @param {string} channelId Clean (digits-only) channel ID
|
||||
* @param {"on"|"auto"|"off"} mode
|
||||
*/
|
||||
export function set247ChannelMode(set, channelId, mode) {
|
||||
let modes = set.get("stay_247_modes");
|
||||
if (!modes || typeof modes !== "object" || Array.isArray(modes)) modes = {};
|
||||
modes[channelId] = mode;
|
||||
set.set("stay_247_modes", modes);
|
||||
set.set("stay_247_mode", mode);
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a channel from the per-channel modes map.
|
||||
*
|
||||
* @param {{ get: (key: string) => any, set: (key: string, value: any) => void }} set
|
||||
* @param {string} channelId Clean channel ID
|
||||
* @param {Set<string>} currentChannels Current set of all 247 channels for this guild
|
||||
* 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) {
|
||||
let modes = set.get("stay_247_modes");
|
||||
if (!modes || typeof modes !== "object" || Array.isArray(modes)) return;
|
||||
delete modes[channelId];
|
||||
set.set("stay_247_modes", modes);
|
||||
if (!currentChannels || currentChannels.size === 0) {
|
||||
set.set("stay_247_mode", "off");
|
||||
} else {
|
||||
const firstChannel = [...currentChannels][0];
|
||||
set.set("stay_247_mode", modes[firstChannel] ?? "auto");
|
||||
}
|
||||
// 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.
|
||||
}
|
||||
+42
-51
@@ -1,53 +1,46 @@
|
||||
/**
|
||||
* @file Locale.mjs — Locale — i18n system loading JSON locale files with per-guild language settings and template variable interpolation
|
||||
* @module src.constants.Locale
|
||||
*/
|
||||
/** @module constants/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");
|
||||
|
||||
/**
|
||||
* Lightweight i18n locale loader.
|
||||
*
|
||||
* Loads all JSON files from storage/locales/bot/ at startup and provides
|
||||
* a `t(guildId, key, replacements?)` translation function.
|
||||
*
|
||||
* Usage in commands (where `this` is the Remix bot instance):
|
||||
* this.t(msg, "responses.play.noResults")
|
||||
* this.t(msg, "responses.clear.cleared", { count: 5 })
|
||||
* 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 {
|
||||
constructor() {
|
||||
/** @type {Map<string, Object>} locale code → parsed JSON */
|
||||
this.locales = new Map();
|
||||
/** @type {Map<string, Object>} guildId → locale JSON (resolved & cached) */
|
||||
this._resolved = new Map();
|
||||
/** Default fallback locale */
|
||||
this.defaultLocale = "en";
|
||||
/** settingsMgr reference — set after construction via bind() */
|
||||
this.settingsMgr = null;
|
||||
/** getPrefix callback — set by CommandHandler so prefix logic lives in one place */
|
||||
this._getPrefixFn = null;
|
||||
/** Maximum guild locale cache size */
|
||||
this._maxResolvedCache = 5000;
|
||||
/**
|
||||
* @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 translate() can look up per-guild locale settings.
|
||||
* @param {object} settingsMgr - RemoteSettingsManager instance
|
||||
* 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 locale JSON files from the locales directory.
|
||||
* Call once at startup after config is available.
|
||||
* Load all `.json` locale files from the locales directory.
|
||||
* Clears any previously loaded data and the resolved-cache.
|
||||
*/
|
||||
load() {
|
||||
this.locales.clear();
|
||||
@@ -81,8 +74,7 @@ export class Locale {
|
||||
}
|
||||
|
||||
/**
|
||||
* Return the set of available locale codes.
|
||||
* Useful for validation (e.g. the settings command).
|
||||
* Return the set of loaded locale codes.
|
||||
* @returns {Set<string>}
|
||||
*/
|
||||
availableLocales() {
|
||||
@@ -90,12 +82,11 @@ export class Locale {
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the locale data for a guild.
|
||||
* Checks the per-guild "locale" setting from the DB, falls back to English.
|
||||
* Results are cached per guildId.
|
||||
*
|
||||
* 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}
|
||||
* @returns {object} The locale data object.
|
||||
*/
|
||||
_getLocaleData(guildId) {
|
||||
if (!guildId) return this.locales.get(this.defaultLocale) ?? {};
|
||||
@@ -126,8 +117,8 @@ export class Locale {
|
||||
}
|
||||
|
||||
/**
|
||||
* Clear the resolved locale cache (call when locale setting changes).
|
||||
* @param {string} [guildId] - Specific guild to invalidate, or omit for all.
|
||||
* Invalidate the resolved-cache for a specific guild or all guilds.
|
||||
* @param {string} [guildId] - Omit to clear the entire cache.
|
||||
*/
|
||||
invalidateCache(guildId) {
|
||||
if (guildId) {
|
||||
@@ -138,17 +129,16 @@ export class Locale {
|
||||
}
|
||||
|
||||
/**
|
||||
* Set the prefix resolver callback. Called once by CommandHandler at startup
|
||||
* so that all prefix resolution goes through CommandHandler.getPrefix().
|
||||
* @param {(guildId: string) => string} fn
|
||||
* Register a custom prefix resolver function.
|
||||
* @param {function(string): string} fn - Receives `guildId`, returns the prefix string.
|
||||
*/
|
||||
setPrefixResolver(fn) {
|
||||
this._getPrefixFn = fn;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the per-guild prefix. Delegates to CommandHandler.getPrefix() when
|
||||
* available, otherwise falls back to a direct settings lookup.
|
||||
* Resolve the command prefix for a guild.
|
||||
* @private
|
||||
* @param {string} guildId
|
||||
* @returns {string}
|
||||
*/
|
||||
@@ -165,9 +155,10 @@ export class Locale {
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up a dotted key in a nested object.
|
||||
* @param {Object} obj
|
||||
* @param {string} key e.g. "responses.play.noResults"
|
||||
* 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) {
|
||||
@@ -181,12 +172,12 @@ export class Locale {
|
||||
}
|
||||
|
||||
/**
|
||||
* Translate a key with optional {{placeholder}} replacements.
|
||||
*
|
||||
* 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 Dotted key, e.g. "responses.play.noResults"
|
||||
* @param {Object} [replacements={}] e.g. { count: 5, channel: "#general" }
|
||||
* @returns {string} Translated string, or the key itself if not found
|
||||
* @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);
|
||||
|
||||
+94
-36
@@ -1,87 +1,145 @@
|
||||
/**
|
||||
* @file Logger.mjs — Logger — categorized logging (info, warn, error, voice, player) with timestamp formatting and module prefixes
|
||||
* @module src.constants.Logger
|
||||
*/
|
||||
|
||||
/**
|
||||
* Logger — configurable console output for Fluxer.
|
||||
*
|
||||
* Categories (all under config.logging):
|
||||
* enabled — master switch; false silences everything except errors and warns
|
||||
* warn — when enabled=false, set true to keep showing warnings (default: hidden)
|
||||
* player — voice connect/disconnect, stream start, volume restore
|
||||
* inactivity — alone-check, inactivity timer, human detection
|
||||
* aloneCheck — periodic alone-check scan logs (separate from inactivity)
|
||||
* voice247 — 24/7 rejoin, auto-save channel, intentional leave skip
|
||||
* voiceState — raw VOICE_STATE_UPDATE events (human join/leave detection)
|
||||
* voice — checkVoiceChannels debug logs
|
||||
* mediaplayer — MediaPlayer publish, LiveKit room state, connection recovery
|
||||
* commands — command load, module load, error IDs
|
||||
* guild — GuildCreate / GuildDelete lifecycle
|
||||
* recovery — session save/restore on reboot
|
||||
* settings — settings DB load, remote update errors
|
||||
* worker — worker URL cleaning, result logging
|
||||
* moonlink — moonlink node events
|
||||
* dashboard — dashboard request handler, player updates
|
||||
* redis — Redis pub/sub connection events
|
||||
* errors — always on; console.error calls (cannot be disabled)
|
||||
*/
|
||||
/** @module constants/Logger */
|
||||
|
||||
/** @private */
|
||||
let _config = null;
|
||||
|
||||
/**
|
||||
* Call once at startup with the loaded config object.
|
||||
* @param {object} config
|
||||
* 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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared cooldown state for WebSocket transport error logging.
|
||||
* Prevents the same WS close event from being logged by multiple
|
||||
* listeners (shard handler, GatewayHandler, MoonlinkManager).
|
||||
* All three share this timestamp so only the first logs.
|
||||
* Cooldown state for WebSocket error logging to avoid spam.
|
||||
* @type {{ lastLogged: number, COOLDOWN_MS: number }}
|
||||
*/
|
||||
export const _wsErrorCooldown = { lastLogged: 0, COOLDOWN_MS: 15_000 };
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
console.error(`[${ts()}] ${tag}`, ...args);
|
||||
},
|
||||
/**
|
||||
* 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) { console.warn(`[${ts()}] ${tag}`, ...args); return; }
|
||||
if (_config.enabled === false && _config.warn !== true) return;
|
||||
console.warn(`[${ts()}] ${tag}`, ...args);
|
||||
},
|
||||
/**
|
||||
* 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); },
|
||||
worker(...args) { if (isEnabled("worker")) console.log(`[${ts()}]`, ...args); },
|
||||
moonlink(...args) { if (isEnabled("moonlink")) 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); },
|
||||
};
|
||||
+13
-21
@@ -1,45 +1,37 @@
|
||||
/**
|
||||
* @file UI.mjs — UI constants — shared color values, emoji arrays, timeout durations, and volume limits used across commands and embeds
|
||||
* @module src.constants.UI
|
||||
*/
|
||||
/** @module constants/UI */
|
||||
|
||||
/**
|
||||
* UI.mjs — Shared UI constants used across commands and embeds.
|
||||
*
|
||||
* Centralises emoji arrays, timeout values, and colour constants
|
||||
* that were previously duplicated across many command files.
|
||||
*/
|
||||
|
||||
/** Error embed colour — used everywhere instead of hardcoding "#ff0000". */
|
||||
/** Hex color string for error embeds. @type {string} */
|
||||
export const ERROR_COLOR = "#ff0000";
|
||||
|
||||
/** Warning/highlight colour for diagnostic and debug embeds. */
|
||||
/** Numeric hex color for warning embeds. @type {number} */
|
||||
export const WARN_COLOR = 0xFFAA00;
|
||||
|
||||
/** Success colour for diagnostic embeds. */
|
||||
/** Numeric hex color for success embeds. @type {number} */
|
||||
export const SUCCESS_COLOR = 0x00CC66;
|
||||
|
||||
/** Failure/danger colour for diagnostic embeds (same as ERROR_COLOR but numeric). */
|
||||
/** Numeric hex color for danger/critical embeds. @type {number} */
|
||||
export const DANGER_COLOR = 0xFF4444;
|
||||
|
||||
/** Default timeout (ms) before removing navigation reactions from embeds. */
|
||||
/** Auto-remove reaction collectors after this many ms. @type {number} */
|
||||
export const EMOJI_REMOVE_TIMEOUT = 60_000;
|
||||
|
||||
/** Default inactivity timeout (ms) for interactive embed sessions. */
|
||||
/** Session idle timeout in ms. @type {number} */
|
||||
export const SESSION_TIMEOUT = 30_000;
|
||||
|
||||
/** Number emojis for search/radio selection menus. */
|
||||
/** Number emoji map for selection menus (indices 1-10). @type {string[]} */
|
||||
export const NUMBER_EMOJIS = [
|
||||
"1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣",
|
||||
"6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟",
|
||||
];
|
||||
|
||||
/** Cancel emoji for selection menus. */
|
||||
/** Emoji used to cancel a selection. @type {string} */
|
||||
export const CANCEL_EMOJI = "❌";
|
||||
|
||||
/** Navigation emojis for paginated embeds. */
|
||||
/** 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 percentage. */
|
||||
/** Maximum allowed volume value. @type {number} */
|
||||
export const MAX_VOLUME = 200;
|
||||
@@ -1,78 +1,58 @@
|
||||
/**
|
||||
* @file VoiceStateCache.mjs — VoiceStateCache — O(1) composite-keyed LRU cache for voice state lookups with dual indexes (user→channel, channel→users)
|
||||
* @module src.constants.VoiceStateCache
|
||||
*/
|
||||
|
||||
/**
|
||||
* VoiceStateCache — O(1) voice-state lookups with bounded memory.
|
||||
*
|
||||
* Replaces the raw `observedVoiceUsers` / `observedVoiceBots` Maps with a
|
||||
* composite-keyed, indexed, LRU-evicted cache that supports:
|
||||
*
|
||||
* • O(1) lookup: "is anyone in channel X?" → channelMembers.get(guildId, channelId)
|
||||
* • O(1) lookup: "what channel is user X in?" → userLocations.get(guildId, userId)
|
||||
* • O(1) lookup: "how many humans in channel X?" → channelMembers.get(...).size
|
||||
* • Bounded memory via LRU eviction (default 50 000 entries)
|
||||
* • Composite keys (guildId:userId) so multi-guild users don't overwrite
|
||||
* • Single update function used by both raw WS and high-level handlers
|
||||
*
|
||||
* Data structures:
|
||||
* userLocations — Map<"guildId:userId", {channelId, guildId, userId}>
|
||||
* channelMembers — Map<"guildId:channelId", Set<userId>>
|
||||
* botLocations — Map<"guildId:userId", {channelId, guildId, userId}>
|
||||
* botChannelMembers — Map<"guildId:channelId", Set<userId>>
|
||||
* _lruOrder — String[] (most-recently-updated keys, for eviction)
|
||||
*/
|
||||
/** @module constants/VoiceStateCache */
|
||||
|
||||
import { logger } from "./Logger.mjs";
|
||||
import { cleanId } from "../Utils.mjs";
|
||||
|
||||
/**
|
||||
* VoiceStateCache class.
|
||||
* 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 human entries before LRU eviction
|
||||
* @param {number} [opts.maxBots=10000] Max bot entries before LRU eviction
|
||||
* @param {number} [opts.maxUsers=50000] - Max cached human user entries.
|
||||
* @param {number} [opts.maxBots=10000] - Max cached bot user entries.
|
||||
*/
|
||||
constructor(opts = {}) {
|
||||
/** @type {Map<string, {channelId, guildId, userId}>} keyed "guildId:userId" */
|
||||
this.userLocations = new Map();
|
||||
/** @type {Map<string, Set<string>>} keyed "guildId:channelId", values are userIds */
|
||||
this.channelMembers = new Map();
|
||||
|
||||
/** @type {Map<string, {channelId, guildId, userId}>} keyed "guildId:userId" */
|
||||
this.botLocations = new Map();
|
||||
/** @type {Map<string, Set<string>>} keyed "guildId:channelId", values are userIds */
|
||||
this.botChannelMembers = new Map();
|
||||
|
||||
this._maxUsers = opts.maxUsers ?? 50_000;
|
||||
this._maxBots = opts.maxBots ?? 10_000;
|
||||
/** @type {string[]} MRU-first list of user location keys */
|
||||
this._lruUserKeys = [];
|
||||
/** @type {string[]} MRU-first list of bot location keys */
|
||||
this._lruBotKeys = [];
|
||||
}
|
||||
|
||||
/** Build composite key "guildId:userId" (both cleaned to digits only) */
|
||||
/**
|
||||
* 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 composite key "guildId:channelId" (both cleaned to digits only) */
|
||||
/**
|
||||
* 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 voice state for a user.
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {string} params.guildId
|
||||
* @param {string} params.userId
|
||||
* @param {string|null} params.channelId null = user left voice
|
||||
* @param {boolean} [params.isBot=false]
|
||||
* 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);
|
||||
@@ -139,9 +119,7 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if there are any human users in a specific channel.
|
||||
* O(1) via channelMembers index.
|
||||
*
|
||||
* Check whether any human users are cached in the given channel.
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
* @returns {boolean}
|
||||
@@ -153,9 +131,7 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the number of human users in a specific channel.
|
||||
* O(1) via channelMembers index.
|
||||
*
|
||||
* Get the count of human users cached in the given channel.
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
* @returns {number}
|
||||
@@ -167,9 +143,7 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all human userIds in a specific channel.
|
||||
* O(1) lookup + Set iteration.
|
||||
*
|
||||
* Get the array of human user IDs cached in the given channel.
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
* @returns {string[]}
|
||||
@@ -181,9 +155,7 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the channelId a human user is currently in (within a specific guild).
|
||||
* O(1) via userLocations index.
|
||||
*
|
||||
* Get the channel ID a human user is currently in, or `null`.
|
||||
* @param {string} guildId
|
||||
* @param {string} userId
|
||||
* @returns {string|null}
|
||||
@@ -195,8 +167,7 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a human user is tracked in a specific guild.
|
||||
*
|
||||
* Check whether a human user exists in the cache for the given guild.
|
||||
* @param {string} guildId
|
||||
* @param {string} userId
|
||||
* @returns {boolean}
|
||||
@@ -206,19 +177,17 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get user location info (channelId, guildId) for a human user.
|
||||
*
|
||||
* Get the full location record for a human user.
|
||||
* @param {string} guildId
|
||||
* @param {string} userId
|
||||
* @returns {{channelId: string, guildId: string, userId: string}|undefined}
|
||||
* @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).
|
||||
*
|
||||
* Seed a user into the cache only if not already present.
|
||||
* @param {string} guildId
|
||||
* @param {string} userId
|
||||
* @param {string} channelId
|
||||
@@ -232,8 +201,7 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove all entries for a specific guild (used on GuildDelete).
|
||||
*
|
||||
* Remove all cached entries (human and bot) for a given guild.
|
||||
* @param {string} guildId
|
||||
*/
|
||||
removeGuild(guildId) {
|
||||
@@ -283,8 +251,7 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a specific channel's index entries (used when a player leaves).
|
||||
*
|
||||
* Remove all cached entries (human and bot) for a specific channel.
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
*/
|
||||
@@ -317,12 +284,10 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Selectively remove entries for users whose IDs appear in a given set
|
||||
* (used during GuildCreate to purge stale entries being replaced).
|
||||
*
|
||||
* Remove specific users from a guild's cache.
|
||||
* @param {string} guildId
|
||||
* @param {Set<string>} userIds User IDs whose entries should be purged
|
||||
* @param {boolean} [botsOnly=false] Only purge bot entries
|
||||
* @param {string[]} userIds
|
||||
* @param {boolean} [botsOnly=false] - If `true`, only purge bot entries.
|
||||
*/
|
||||
purgeUsersInGuild(guildId, userIds, botsOnly = false) {
|
||||
const cleanGuild = cleanId(guildId);
|
||||
@@ -353,21 +318,20 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the "observedVoiceUsers" size (human count).
|
||||
* Backward-compat with `this.observedVoiceUsers.size`
|
||||
* Number of cached human users.
|
||||
* @type {number}
|
||||
*/
|
||||
get observedVoiceUsersSize() { return this.userLocations.size; }
|
||||
|
||||
/**
|
||||
* Get the "observedVoiceBots" size.
|
||||
* Backward-compat with `this.observedVoiceBots.size`
|
||||
* Number of cached bot users.
|
||||
* @type {number}
|
||||
*/
|
||||
get observedVoiceBotsSize() { return this.botLocations.size; }
|
||||
|
||||
/**
|
||||
* Iterate over all human user locations.
|
||||
* Yields [compositeKey, {channelId, guildId, userId}] — same shape as Map entries.
|
||||
* Backward-compat with `for (const [uid, info] of this.observedVoiceUsers)`.
|
||||
* 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) {
|
||||
@@ -376,9 +340,8 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Iterate over all bot user locations.
|
||||
* Yields [compositeKey, {channelId, guildId, userId}].
|
||||
* Backward-compat with `for (const [uid, info] of this.observedVoiceBots)`.
|
||||
* 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) {
|
||||
@@ -387,13 +350,10 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get a human user's location by userId and guildId.
|
||||
* If guildId is provided, uses O(1) composite key.
|
||||
* If guildId is null, falls back to O(n) scan (legacy compat).
|
||||
*
|
||||
* Get the location record for a human user. If `guildId` is omitted, performs a linear scan.
|
||||
* @param {string} userId
|
||||
* @param {string|null} [guildId=null]
|
||||
* @returns {{channelId: string, guildId: string}|undefined}
|
||||
* @param {string|null} [guildId]
|
||||
* @returns {{ channelId: string, guildId: string }|undefined}
|
||||
*/
|
||||
getHumanUser(userId, guildId = null) {
|
||||
if (guildId) {
|
||||
@@ -407,10 +367,9 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a human user's location (backward-compat with observedVoiceUsers.set).
|
||||
*
|
||||
* Set a human user's voice location via `updateUser`.
|
||||
* @param {string} userId
|
||||
* @param {{channelId: string, guildId: string}} info
|
||||
* @param {{ guildId: string, channelId: string }} info
|
||||
*/
|
||||
setHumanUser(userId, info) {
|
||||
const guildId = info.guildId;
|
||||
@@ -421,10 +380,9 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Set a bot user's location (backward-compat with observedVoiceBots.set).
|
||||
*
|
||||
* @param {string} compositeKey "guildId:userId" composite key
|
||||
* @param {{channelId: string, guildId: string}} info
|
||||
* 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;
|
||||
@@ -436,11 +394,9 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a human user by userId (scans all guilds if no guildId given).
|
||||
* Backward-compat with observedVoiceUsers.delete(userId).
|
||||
*
|
||||
* Remove a human user from the cache. If `guildId` is omitted, scans all entries.
|
||||
* @param {string} userId
|
||||
* @param {string|null} [guildId=null]
|
||||
* @param {string|null} [guildId]
|
||||
*/
|
||||
deleteHumanUser(userId, guildId = null) {
|
||||
if (guildId) {
|
||||
@@ -456,10 +412,8 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Delete a bot user by composite key.
|
||||
* Backward-compat with observedVoiceBots.delete(compositeKey).
|
||||
*
|
||||
* @param {string} compositeKey "guildId:userId"
|
||||
* Remove a bot user from the cache by its composite key.
|
||||
* @param {string} compositeKey - `guildId:userId` composite key.
|
||||
*/
|
||||
deleteBotUser(compositeKey) {
|
||||
const parts = compositeKey.split(":");
|
||||
@@ -471,11 +425,9 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a human user exists in the cache.
|
||||
* Backward-compat with observedVoiceUsers.has(userId).
|
||||
*
|
||||
* Check whether a human user exists in the cache. If `guildId` is omitted, scans all entries.
|
||||
* @param {string} userId
|
||||
* @param {string|null} [guildId=null]
|
||||
* @param {string|null} [guildId]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
hasHumanUser(userId, guildId = null) {
|
||||
@@ -490,10 +442,8 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a bot user exists in the cache.
|
||||
* Backward-compat with observedVoiceBots.has(compositeKey).
|
||||
*
|
||||
* @param {string} compositeKey
|
||||
* Check whether a bot user exists in the cache by composite key.
|
||||
* @param {string} compositeKey - `guildId:userId` composite key.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
hasBotUser(compositeKey) {
|
||||
@@ -501,8 +451,8 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Default iterator — iterates human users.
|
||||
* Yields [userId, {channelId, guildId}] — same shape as old observedVoiceUsers Map.
|
||||
* Implement the iterable protocol over human user entries.
|
||||
* @yields {[string, { channelId: string, guildId: string }]}
|
||||
*/
|
||||
*[Symbol.iterator]() {
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
@@ -511,15 +461,13 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Backward-compat with `observedVoiceUsers.size`.
|
||||
* Number of cached human users (Map-like `.size`).
|
||||
* @type {number}
|
||||
*/
|
||||
get size() { return this.userLocations.size; }
|
||||
|
||||
/**
|
||||
* Backward-compat with `observedVoiceUsers.has(userId)`.
|
||||
* If called with a single argument (userId), scans all guilds.
|
||||
* If called with two arguments (userId, guildId), does O(1) lookup.
|
||||
*
|
||||
* Map-like `has` — checks if a human user is cached.
|
||||
* @param {string} userId
|
||||
* @param {string} [guildId]
|
||||
* @returns {boolean}
|
||||
@@ -536,13 +484,10 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Backward-compat with `observedVoiceUsers.get(userId)`.
|
||||
* If called with a single argument (userId), returns first match across all guilds.
|
||||
* If called with two arguments (userId, guildId), does O(1) lookup.
|
||||
*
|
||||
* Map-like `get` — retrieve a human user's location.
|
||||
* @param {string} userId
|
||||
* @param {string} [guildId]
|
||||
* @returns {{channelId: string, guildId: string}|undefined}
|
||||
* @returns {{ channelId: string, guildId: string }|undefined}
|
||||
*/
|
||||
get(userId, guildId) {
|
||||
if (guildId !== undefined) {
|
||||
@@ -557,10 +502,9 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Backward-compat with `observedVoiceUsers.set(userId, {channelId, guildId})`.
|
||||
*
|
||||
* Map-like `set` — upsert a human user's location.
|
||||
* @param {string} userId
|
||||
* @param {{channelId: string, guildId: string}} info
|
||||
* @param {{ guildId: string, channelId: string }} info
|
||||
*/
|
||||
set(userId, info) {
|
||||
const guildId = info?.guildId;
|
||||
@@ -571,8 +515,7 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Backward-compat with `observedVoiceUsers.delete(userId)`.
|
||||
*
|
||||
* Map-like `delete` — remove a human user. If `guildId` is omitted, removes all matching entries.
|
||||
* @param {string} userId
|
||||
* @param {string} [guildId]
|
||||
*/
|
||||
@@ -592,9 +535,8 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Backward-compat with `observedVoiceUsers.forEach(fn)`.
|
||||
*
|
||||
* @param {Function} fn callback(userId, info, cache)
|
||||
* 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) {
|
||||
@@ -603,14 +545,16 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Backward-compat with `observedVoiceUsers.entries()`.
|
||||
* Map-like `entries` iterator.
|
||||
* @yields {[string, { channelId: string, guildId: string }]}
|
||||
*/
|
||||
*entries() {
|
||||
yield* this;
|
||||
}
|
||||
|
||||
/**
|
||||
* Backward-compat with `observedVoiceUsers.keys()`.
|
||||
* Map-like `keys` iterator.
|
||||
* @yields {string}
|
||||
*/
|
||||
*keys() {
|
||||
for (const [userId] of this) {
|
||||
@@ -619,7 +563,8 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
/**
|
||||
* Backward-compat with `observedVoiceUsers.values()`.
|
||||
* Map-like `values` iterator.
|
||||
* @yields {{ channelId: string, guildId: string }}
|
||||
*/
|
||||
*values() {
|
||||
for (const [, info] of this) {
|
||||
@@ -627,6 +572,10 @@ export class VoiceStateCache {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,
|
||||
|
||||
@@ -1,26 +1,11 @@
|
||||
/**
|
||||
* @file VoiceStateResolver.mjs — VoiceStateResolver — unified voice state enumeration across Map/Array/Object guild voice_states with human-detection fallbacks
|
||||
* @module src.constants.VoiceStateResolver
|
||||
*/
|
||||
|
||||
/**
|
||||
* VoiceStateResolver.mjs — Unified voice state enumeration.
|
||||
*
|
||||
* Eliminates the 12+ duplicated voice-state-iteration blocks scattered
|
||||
* across Player.mjs, PlayerManager.mjs, GatewayHandler.mjs, and Dashboard.mjs.
|
||||
*
|
||||
* Fluxer's guild.voice_states can be a Map, an Array, or a plain Object
|
||||
* depending on the client version and cache state. This module normalises
|
||||
* all three into a single iteration interface.
|
||||
*/
|
||||
/** @module constants/VoiceStateResolver */
|
||||
|
||||
import { logger } from "./Logger.mjs";
|
||||
|
||||
/**
|
||||
* Iterate over all voice states for a guild, yielding objects with
|
||||
* { userId, channelId, isBot } regardless of the underlying data structure.
|
||||
*
|
||||
* @param {import("@fluxerjs/core").Guild} guild
|
||||
* 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.
|
||||
* @yields {{ userId: string, channelId: string, isBot: boolean }}
|
||||
*/
|
||||
export function* iterateVoiceStates(guild) {
|
||||
@@ -59,18 +44,16 @@ export function* iterateVoiceStates(guild) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a guild's voice channel contains any non-bot users.
|
||||
* Uses three fallback strategies: VoiceStateCache, guild.voice_states,
|
||||
* and LiveKit remote participants.
|
||||
*
|
||||
* 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 - Clean guild ID
|
||||
* @param {string} opts.channelId - Clean channel ID
|
||||
* @param {object} [opts.client] - Fluxer client (for guild cache)
|
||||
* @param {object} [opts.voiceCache] - VoiceStateCache instance
|
||||
* @param {Map} [opts.observedVoiceUsers] - Observed voice users map
|
||||
* @param {object} [opts.room] - LiveKit Room (for remote participants)
|
||||
* @param {string} [opts.botId] - Bot user ID (to exclude from LiveKit check)
|
||||
* @param {string} opts.guildId
|
||||
* @param {string} opts.channelId
|
||||
* @param {object} [opts.client] - Discord 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 }) {
|
||||
@@ -128,10 +111,9 @@ export function hasHumansInChannel({ guildId, channelId, client, voiceCache, obs
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all channel IDs that have at least one human user in voice.
|
||||
*
|
||||
* @param {import("@fluxerjs/core").Guild} guild
|
||||
* @returns {Set<string>} Set of channel IDs with human users
|
||||
* Get the set of channel IDs that contain at least one human user.
|
||||
* @param {object} guild - Discord guild object.
|
||||
* @returns {Set<string>}
|
||||
*/
|
||||
export function getChannelsWithHumans(guild) {
|
||||
const channels = new Set();
|
||||
@@ -142,9 +124,8 @@ export function getChannelsWithHumans(guild) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Get all user IDs in a specific voice channel (including bots).
|
||||
*
|
||||
* @param {import("@fluxerjs/core").Guild} guild
|
||||
* Get the list of user IDs present in a specific voice channel.
|
||||
* @param {object} guild - Discord guild object.
|
||||
* @param {string} channelId
|
||||
* @returns {string[]}
|
||||
*/
|
||||
|
||||
@@ -1,102 +0,0 @@
|
||||
/**
|
||||
* @file StreamMerger.mjs — StreamMerger — Transform stream that mixes multiple audio inputs through FFmpeg amix filter
|
||||
* @module src.constants.audio.StreamMerger
|
||||
*/
|
||||
|
||||
/**
|
||||
* StreamMerger extends Transform to mix multiple audio streams into one
|
||||
* using FFmpeg’s amix filter. Supports dynamic stream addition with
|
||||
* a tree-based node structure for managing merge slots.
|
||||
*/
|
||||
import { logger } from "../Logger.mjs";
|
||||
import ffmpeg from "ffmpeg-static";
|
||||
import { Transform } from "node:stream";
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
class StreamMerger extends Transform {
|
||||
ffmpegPath = ffmpeg;
|
||||
ffmpeg = null;
|
||||
streamTree = [];
|
||||
|
||||
/**
|
||||
* @param {import("node:stream").TransformOptions} streamOptions Options forwarded to the underlying Transform stream
|
||||
*/
|
||||
constructor(streamOptions) {
|
||||
super(streamOptions);
|
||||
}
|
||||
_transform(chunk, _enc, cb) {
|
||||
if (!this.ffmpeg) { this.push(chunk); return cb(); }
|
||||
if (!this.ffmpeg.stdio?.[3]?.writable) { this.push(chunk); return cb(); }
|
||||
this.ffmpeg.stdio[3].write(chunk);
|
||||
cb();
|
||||
}
|
||||
pipe(stream) {
|
||||
return super.pipe(stream);
|
||||
}
|
||||
setupBaseFfmpeg() {
|
||||
this.ffmpeg = this.spawnFfmpeg();
|
||||
this.ffmpeg.stderr.on("data", (chunk) => { logger.mediaplayer("[ffmpeg]", chunk.toString().trim()); });
|
||||
this.ffmpeg.stdout.on("data", (chunk) => { this.push(chunk); });
|
||||
}
|
||||
spawnFfmpeg() {
|
||||
const args = [
|
||||
"-i", "pipe:3",
|
||||
"-re", "-i", "pipe:4",
|
||||
"-vn",
|
||||
"-fflags", "nobuffer",
|
||||
"-filter_complex", "amix=inputs=2:duration=longest",
|
||||
"pipe:1",
|
||||
];
|
||||
return spawn(this.ffmpegPath, args, {
|
||||
windowsHide: true,
|
||||
stdio: ["pipe", "pipe", "pipe", "pipe", "pipe"]
|
||||
});
|
||||
}
|
||||
findOpenNode() {
|
||||
if (this.streamTree.length === 0) {
|
||||
this.streamTree.push({ process: this.ffmpeg, pipes: [4], available: true, children: [] });
|
||||
return this.streamTree[0];
|
||||
}
|
||||
const findChild = (node) => {
|
||||
if (node.available) return node;
|
||||
for (const child of node.children) {
|
||||
const c = findChild(child);
|
||||
if (c) return c;
|
||||
}
|
||||
return null;
|
||||
};
|
||||
for (const node of this.streamTree) {
|
||||
const firstChild = findChild(node);
|
||||
if (firstChild) return firstChild;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
addStream(s) {
|
||||
if (!this.ffmpeg) this.setupBaseFfmpeg();
|
||||
const open = this.findOpenNode();
|
||||
if (!open) throw new Error("Impossible case detected. No free merge node found.");
|
||||
const p = this.spawnFfmpeg();
|
||||
const node = { process: p, pipes: [4], available: true, parent: open, children: [] };
|
||||
open.children.push(node);
|
||||
s.pipe(p.stdio[3]);
|
||||
p.stderr.on("data", (c) => { logger.mediaplayer("[ffmpeg]", c.toString().trim()); });
|
||||
/* Write initial silence to prime the ffmpeg stdin pipe (required for amix to detect the input). */
|
||||
p.stdio[4].write(Buffer.alloc(1024, 0));
|
||||
p.stdout.pipe(open.process.stdio[open.pipes[0]]);
|
||||
const pipeNumber = open.pipes[0];
|
||||
open.pipes.splice(0, 1);
|
||||
if (open.pipes.length === 0) open.available = false;
|
||||
p.on("exit", () => {
|
||||
open.pipes.push(pipeNumber);
|
||||
open.available = true;
|
||||
const idx = open.children.findIndex(c => c === node);
|
||||
if (idx === -1) {
|
||||
logger.warn("[StreamMerger] Damaged node structure — child not found in parent on exit.");
|
||||
} else {
|
||||
open.children.splice(idx, 1);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default StreamMerger;
|
||||
@@ -1,24 +1,30 @@
|
||||
/**
|
||||
* @file Tuna.mjs — Tuna — Voicemod Tuna API client for sound effect search and download
|
||||
* @module src.constants.audio.Tuna
|
||||
*/
|
||||
/** @module constants/audio/Tuna */
|
||||
|
||||
/**
|
||||
* Tuna API client for searching and downloading sound effects
|
||||
* from the Voicemod Tuna service (tuna-api.voicemod.net).
|
||||
*/
|
||||
import pkg from "follow-redirects";
|
||||
const { https } = pkg;
|
||||
|
||||
/**
|
||||
* Client for the Tuna (Voicemod) sound-effect API.
|
||||
* @class
|
||||
*/
|
||||
class Tuna {
|
||||
apiKey = null;
|
||||
/** @private */ apiKey = null;
|
||||
|
||||
/**
|
||||
* @param {Object} auth Auth config
|
||||
* @param {string} auth.key Voicemod Tuna API key
|
||||
* @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();
|
||||
@@ -49,6 +55,16 @@ class Tuna {
|
||||
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 => {
|
||||
@@ -65,6 +81,14 @@ class Tuna {
|
||||
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;
|
||||
|
||||
@@ -0,0 +1,220 @@
|
||||
/** @module src/constants/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);
|
||||
}
|
||||
}
|
||||
}
|
||||
+17
-15
@@ -1,18 +1,11 @@
|
||||
/**
|
||||
* @file providers.mjs — Music provider definitions — source names, emoji icons, choice lists, and inline provider parsing for search commands
|
||||
* @module src.constants.providers
|
||||
*/
|
||||
/** @module constants/providers */
|
||||
|
||||
/**
|
||||
* providers.mjs — Single source of truth for all provider data.
|
||||
*
|
||||
* PROVIDERS — full map: { prefix, label } — used by worker.mjs for search
|
||||
* PROVIDER_NAMES — derived label-only map — used by Player.mjs for display
|
||||
* PROVIDER_CHOICES — ordered list of valid keys — used by command option builders
|
||||
*
|
||||
* Edit only here; worker.mjs and Player.mjs import from this file.
|
||||
* 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" },
|
||||
@@ -71,11 +64,18 @@ export const PROVIDERS = {
|
||||
ftts: { prefix: "ftts", label: "Flowery TTS" },
|
||||
};
|
||||
|
||||
/** Label-only map — convenience alias for display use (e.g. Player.mjs). */
|
||||
/**
|
||||
* 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",
|
||||
@@ -105,8 +105,10 @@ export const PROVIDER_CHOICES = [
|
||||
];
|
||||
|
||||
/**
|
||||
* Parse an inline provider prefix from a query string (e.g. "sp: song name").
|
||||
* @param {string} raw
|
||||
* 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) {
|
||||
|
||||
+95
-76
@@ -1,6 +1,8 @@
|
||||
/**
|
||||
* @file Dashboard.mjs — Dashboard — web dashboard backend with player status API, guild listing, and bot statistics endpoints
|
||||
* @module src.dashboard.Dashboard
|
||||
* @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.
|
||||
*/
|
||||
|
||||
import { CommandBuilder, CommandHandler, Option } from "../CommandHandler.mjs";
|
||||
@@ -13,18 +15,23 @@ import { logger } from "../constants/Logger.mjs";
|
||||
import { iterateVoiceStates } from "../constants/VoiceStateResolver.mjs";
|
||||
|
||||
/**
|
||||
* Dashboard class.
|
||||
* @class
|
||||
* @description Orchestrates the web dashboard: wires up Redis request/response handling,
|
||||
* converts Discord data for the frontend, and exposes remote control functions.
|
||||
*/
|
||||
export 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;
|
||||
|
||||
/**
|
||||
* @param {Remix} remix
|
||||
* @param {Object} opts
|
||||
* @param {boolean} opts.enabled Whether the Dashboard is enabled and connections should be attempted
|
||||
* @param {Object} opts.redis Connection options passed directly to redis createClient
|
||||
* @param {Object} [opts.mysql] MySQL connection config for login code verification
|
||||
* Create a new Dashboard instance.
|
||||
* @param {object} remix - The main bot (Remix) instance.
|
||||
* @param {object} opts - Dashboard options.
|
||||
* @param {boolean} [opts.enabled] - Whether the dashboard is enabled.
|
||||
* @param {object} [opts.redis] - Redis connection options.
|
||||
* @param {object} [opts.mysql] - MySQL connection options for the dashboard database.
|
||||
*/
|
||||
constructor(remix, opts) {
|
||||
this.enabled = opts?.enabled;
|
||||
@@ -129,8 +136,8 @@ export class Dashboard {
|
||||
|
||||
|
||||
/**
|
||||
* Set the bot ID for multi-bot Redis namespace isolation.
|
||||
* Updates the Redis platform string so each bot uses its own channel namespace.
|
||||
* Set the bot ID for the Redis platform prefix.
|
||||
* @param {string} botId - The bot's Discord user ID.
|
||||
*/
|
||||
setBotId(botId) {
|
||||
if (!this.enabled || !this.redis) return;
|
||||
@@ -139,10 +146,13 @@ export class Dashboard {
|
||||
|
||||
|
||||
/**
|
||||
* @param {Object} params
|
||||
* @param {string} params.func
|
||||
* @param {any} params.data
|
||||
* @returns {Promise<any>}
|
||||
* 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;
|
||||
@@ -367,10 +377,12 @@ export class Dashboard {
|
||||
|
||||
|
||||
/**
|
||||
* Check if a user is a bot owner, or is in the same voice channel as the player.
|
||||
* @param {import("@fluxerjs/core").User|null} user
|
||||
* @param {Player} player
|
||||
* @returns {string|null} Error message, or null if authorized
|
||||
* 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;
|
||||
@@ -400,10 +412,13 @@ export class Dashboard {
|
||||
}
|
||||
|
||||
/**
|
||||
* Verify the user has permission to perform an action in the target guild.
|
||||
* @param {import("@fluxerjs/core").User} user
|
||||
* @param {string} guildId
|
||||
* @returns {Promise<string|null>} Error message, or null if authorized
|
||||
* 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;
|
||||
@@ -420,9 +435,10 @@ export class Dashboard {
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a player by its channel ID (key in playerMap)
|
||||
* @param {string} id
|
||||
* @returns {Player|null}
|
||||
* 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)
|
||||
@@ -434,7 +450,10 @@ export class Dashboard {
|
||||
|
||||
|
||||
/**
|
||||
* @param {import("@fluxerjs/core").User} user
|
||||
* 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 = "";
|
||||
@@ -459,7 +478,10 @@ export class Dashboard {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Object} vid Track object stored in the fluxer Queue
|
||||
* 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;
|
||||
@@ -483,7 +505,11 @@ export class Dashboard {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("@fluxerjs/core").GuildChannel} channel
|
||||
* 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;
|
||||
@@ -524,7 +550,10 @@ export class Dashboard {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("@fluxerjs/core").Guild} guild
|
||||
* 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;
|
||||
@@ -558,8 +587,10 @@ export class Dashboard {
|
||||
}
|
||||
|
||||
/**
|
||||
* Lightweight server summary for player payloads.
|
||||
* @param {import("@fluxerjs/core").Guild} guild
|
||||
* 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;
|
||||
@@ -578,7 +609,11 @@ export class Dashboard {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Player} player
|
||||
* 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;
|
||||
@@ -648,7 +683,10 @@ export class Dashboard {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {Option} opt
|
||||
* 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 {
|
||||
@@ -664,8 +702,11 @@ export class Dashboard {
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {CommandBuilder} com
|
||||
* @param {CommandHandler} commands
|
||||
* 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 {
|
||||
@@ -684,23 +725,14 @@ export class Dashboard {
|
||||
}
|
||||
|
||||
|
||||
/** @private */
|
||||
_playerUpdateTimers = new Map();
|
||||
|
||||
/**
|
||||
* Global player update (broadcast to all dashboard listeners on {platform}:players).
|
||||
*
|
||||
* Used for two purposes:
|
||||
* 1. Lifecycle events: { type: "init" } / { type: "close" } — the backend
|
||||
* PlayerManager uses these to add/remove Player objects.
|
||||
* 2. Full state broadcast: any other type — the full serialised player is
|
||||
* included so dashboard frontends can update their UI.
|
||||
*
|
||||
* Debounced: rapid successive calls for the same player are coalesced
|
||||
* into a single publish every 500ms.
|
||||
*
|
||||
* @param {Object} details Must include a `type` field (e.g. "init", "close",
|
||||
* "startplay", "stopplay", etc.) and may include a `data` field.
|
||||
* @param {Player} player
|
||||
* Broadcast a player state update to the dashboard via Redis.
|
||||
* Debounces non-init/close updates by 500ms.
|
||||
* @param {object} details - The update payload (e.g. `{ type: 'song' }`).
|
||||
* @param {object} player - The Player instance that changed.
|
||||
*/
|
||||
playerUpdate(details, player) {
|
||||
if (!this.enabled) return;
|
||||
@@ -738,20 +770,9 @@ export class Dashboard {
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-player channel update (sent to {platform}:player_{channelId}).
|
||||
*
|
||||
* The backend PlayerManager.setupEvents() expects messages in the format:
|
||||
* { type: "<eventType>", data: <payload> }
|
||||
*
|
||||
* This method accepts details in that standard format directly.
|
||||
*
|
||||
* @param {Object} details Must include `type` and optionally `data`.
|
||||
* Examples:
|
||||
* { type: "startplay", data: convertVideo(song) }
|
||||
* { type: "pause", data: { elapsedTime: 12345 } }
|
||||
* { type: "queue", data: serialisedQueueEvent }
|
||||
* { type: "join", data: userId }
|
||||
* @param {Player} player
|
||||
* Send a lightweight update to the player-specific Redis channel.
|
||||
* @param {object} details - The update payload.
|
||||
* @param {object} player - The Player instance.
|
||||
*/
|
||||
updatePlayer(details, player) {
|
||||
if (!this.enabled) return;
|
||||
@@ -760,9 +781,9 @@ export class Dashboard {
|
||||
}
|
||||
|
||||
/**
|
||||
* Global user update (sent to {platform}:users).
|
||||
* @param {Object} details
|
||||
* @param {import("@fluxerjs/core").User} user
|
||||
* Broadcast a user update to the global users Redis channel.
|
||||
* @param {object} details - The update payload.
|
||||
* @param {object} user - The Discord user.
|
||||
*/
|
||||
userUpdate(details, user) {
|
||||
if (!this.enabled) return;
|
||||
@@ -774,9 +795,9 @@ export class Dashboard {
|
||||
}
|
||||
|
||||
/**
|
||||
* Per-user channel update (sent to {platform}:user_{userId}).
|
||||
* @param {Object} details
|
||||
* @param {import("@fluxerjs/core").User} user
|
||||
* Send a lightweight update to the user-specific Redis channel.
|
||||
* @param {object} details - The update payload.
|
||||
* @param {object} user - The Discord user.
|
||||
*/
|
||||
updateUser(details, user) {
|
||||
if (!this.enabled) return;
|
||||
@@ -786,13 +807,11 @@ export class Dashboard {
|
||||
|
||||
|
||||
/**
|
||||
* Verify a login code submitted by a user via DM.
|
||||
* The backend stores the code in MySQL; this method compares the supplied
|
||||
* code against the stored (bcrypt-hashed) value.
|
||||
*
|
||||
* @param {string} user User ID
|
||||
* @param {string} code Plain-text code supplied by the user
|
||||
* @returns {Promise<string|null>} null on success, error message on failure
|
||||
* 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.";
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* @file DatabaseManager.mjs — DatabaseManager — SQLite database manager for the web dashboard's persistent storage
|
||||
* @module src.dashboard.DatabaseManager
|
||||
* @module dashboard/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";
|
||||
@@ -8,12 +9,14 @@ import { createPool } from "mysql2/promise";
|
||||
import { logger } from "../constants/Logger.mjs";
|
||||
|
||||
/**
|
||||
* DatabaseManager — MySQL pool for dashboard login codes and API tokens.
|
||||
* Adapted for use with the Fluxer bot.
|
||||
* @class
|
||||
* @description Wraps a mysql2 connection pool with convenience methods for
|
||||
* parameterised queries and bcrypt hash operations.
|
||||
*/
|
||||
export class DatabaseManager {
|
||||
/**
|
||||
* @param {import("mysql2/promise").PoolOptions} config
|
||||
* Create a new DatabaseManager.
|
||||
* @param {object} config - mysql2 pool configuration (host, user, password, database, etc.).
|
||||
*/
|
||||
constructor(config) {
|
||||
this.db = createPool({
|
||||
@@ -26,19 +29,21 @@ export class DatabaseManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute a raw SQL query.
|
||||
* @param {string} query
|
||||
* @returns {Promise<[import("mysql2/promise").QueryResult, import("mysql2/promise").FieldPacket[]]>}
|
||||
* 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 parameterized SQL query.
|
||||
* @param {string} query
|
||||
* @param {any[]} [data]
|
||||
* @returns {Promise<import("mysql2/promise").QueryResult>}
|
||||
* 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);
|
||||
@@ -46,9 +51,10 @@ export class DatabaseManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* Hash a plaintext string using bcrypt.
|
||||
* @param {string} plain
|
||||
* @returns {Promise<string>}
|
||||
* 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);
|
||||
@@ -57,16 +63,17 @@ export class DatabaseManager {
|
||||
|
||||
/**
|
||||
* Compare a plaintext string against a bcrypt hash.
|
||||
* @param {string} plain
|
||||
* @param {string} hashed
|
||||
* @returns {Promise<boolean>}
|
||||
* @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);
|
||||
}
|
||||
|
||||
/**
|
||||
* Gracefully close the connection pool.
|
||||
* Close the underlying MySQL connection pool.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
close() {
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
/**
|
||||
* @file RedisHandler.mjs — RedisHandler — Redis pub/sub handler for cross-process dashboard state synchronization
|
||||
* @module src.dashboard.RedisHandler
|
||||
* @module dashboard/RedisHandler
|
||||
* @description Redis pub/sub handler for the dashboard. Maintains a main publisher client
|
||||
* and a subscriber client. Receives JSON requests on the "request" channel,
|
||||
* dispatches them to a user-supplied handler, and publishes results on "response".
|
||||
*/
|
||||
|
||||
import { createClient } from "redis";
|
||||
import { logger } from "../constants/Logger.mjs";
|
||||
|
||||
/**
|
||||
* Default retry strategy: exponential backoff starting at 500ms, max 5s, max 20 retries.
|
||||
* @param {Object} options
|
||||
* @returns {number} Delay in ms before next retry, or an Error to stop retrying
|
||||
* 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.
|
||||
*/
|
||||
const DEFAULT_RETRY_STRATEGY = (options) => {
|
||||
if (options.totalRetryTime > 60_000) {
|
||||
@@ -19,22 +23,25 @@ const DEFAULT_RETRY_STRATEGY = (options) => {
|
||||
};
|
||||
|
||||
/**
|
||||
* RedisHandler class.
|
||||
* @class
|
||||
* @description Manages dual Redis connections (publisher + subscriber) for real-time
|
||||
* dashboard communication via pub/sub.
|
||||
*/
|
||||
export class RedisHandler {
|
||||
/** @type {string} Platform prefix used for Redis channel names. */
|
||||
platform = "fluxer";
|
||||
|
||||
/** @type {import("redis").RedisClientType|null} */
|
||||
/** @type {import('redis').RedisClientType|null} The main (publisher) Redis client. */
|
||||
client = null;
|
||||
/** @type {import("redis").RedisClientType|null} */
|
||||
/** @type {import('redis').RedisClientType|null} The subscriber Redis client. */
|
||||
subscriber = null;
|
||||
/** Whether the handler has been explicitly destroyed */
|
||||
/** @private @type {boolean} Whether the handler has been destroyed. */
|
||||
_destroyed = false;
|
||||
|
||||
/**
|
||||
* @param {Object} opts
|
||||
* @param {import("redis").RedisClientOptions} opts Redis client options
|
||||
* @param {string} [opts.platform] Platform identifier for channel namespacing
|
||||
* Create a new RedisHandler and immediately begin connecting.
|
||||
* @param {object} [opts={}] - Redis connection options (passed to `createClient`).
|
||||
* @param {string} [opts.platform] - Platform prefix for channels.
|
||||
*/
|
||||
constructor(opts = {}) {
|
||||
this.platform = opts.platform ?? "fluxer";
|
||||
@@ -61,8 +68,10 @@ export class RedisHandler {
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect both publisher and subscriber with reconnection support.
|
||||
* Wrapped in a method so it can be called once from the constructor.
|
||||
* Connect both the publisher and subscriber clients, then subscribe
|
||||
* to the "request" and "info" channels and start the ping interval.
|
||||
* @private
|
||||
* @async
|
||||
*/
|
||||
async _connect() {
|
||||
try {
|
||||
@@ -113,12 +122,8 @@ export class RedisHandler {
|
||||
}
|
||||
|
||||
/**
|
||||
* Send the "connected" announcement to the backend.
|
||||
* Delayed by 5 seconds so the bot has time to initialise players,
|
||||
* recovery manager, and Moonlink before the backend starts sending
|
||||
* requests like fetchPlayers. Without this delay the backend's
|
||||
* initChannels() fires before the bot's playerMap is populated,
|
||||
* causing "Redis request timed out" errors and a retry loop.
|
||||
* Send a "connected" info message to the dashboard after a 5-second debounce.
|
||||
* @returns {void}
|
||||
*/
|
||||
readyMessage() {
|
||||
if (this._destroyed) return;
|
||||
@@ -135,9 +140,10 @@ export class RedisHandler {
|
||||
|
||||
/**
|
||||
* Publish a message to a Redis channel.
|
||||
* @param {string} channel
|
||||
* @param {string} message
|
||||
* @returns {Promise<number>} Number of subscribers that received the message
|
||||
* No-op if the handler is destroyed or the client is not ready.
|
||||
* @param {string} channel - The Redis channel to publish to.
|
||||
* @param {string} message - The message string to send.
|
||||
* @returns {Promise<number>} Number of subscribers that received the message.
|
||||
*/
|
||||
send(channel, message) {
|
||||
if (this._destroyed || !this.client?.isReady) return Promise.resolve(0);
|
||||
@@ -147,24 +153,20 @@ export class RedisHandler {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* @callback RequestCallback
|
||||
* @param {Object} data
|
||||
* @param {string} data.type
|
||||
* @returns {Promise<Object>}
|
||||
*/
|
||||
/** @type {Function|null} The current request handler function. */
|
||||
handleRequest;
|
||||
|
||||
/**
|
||||
* @param {RequestCallback} handler
|
||||
* Set the handler function invoked for incoming "request" payloads.
|
||||
* @param {Function} handler - Async function `(data) => result`.
|
||||
*/
|
||||
setRequestHandler(handler) {
|
||||
this.handleRequest = handler;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gracefully close both Redis connections.
|
||||
* Should be called on process shutdown to avoid abrupt connection drops.
|
||||
* Gracefully close both Redis connections and stop all internal timers.
|
||||
* @async
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async destroy() {
|
||||
|
||||
+9
-4
@@ -1,14 +1,19 @@
|
||||
/**
|
||||
* @file probe.mjs — Health probe — monitors NodeLink and LiveKit endpoint availability
|
||||
* @module src.probe
|
||||
*/
|
||||
/** @module src/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";
|
||||
|
||||
/** @type {number} @description Maximum time in milliseconds to wait for ffprobe to complete. */
|
||||
const PROBE_TIMEOUT_MS = 15_000;
|
||||
|
||||
/**
|
||||
* Probe a media file or stream URL for metadata using ffprobe.
|
||||
* Extracts album, artist, title, and duration.
|
||||
* @param {string} file - File path or stream URL to probe.
|
||||
* @returns {Promise<{album: string, artist: string, title: string, duration: number}>} Parsed metadata.
|
||||
* @throws {Error} If ffprobe times out, fails to spawn, or produces unparseable output.
|
||||
*/
|
||||
export default function probe(file) {
|
||||
return new Promise((res, rej) => {
|
||||
const args = [
|
||||
|
||||
-757
@@ -1,757 +0,0 @@
|
||||
/**
|
||||
* @file worker.mjs — Worker thread module — handles track search jobs via NodeLink REST API with provider fallback chains
|
||||
* @module src.worker
|
||||
*/
|
||||
|
||||
/**
|
||||
* worker.mjs — NodeLink REST edition (moonlink.js session-aware)
|
||||
*/
|
||||
|
||||
import { workerData, parentPort } from "worker_threads";
|
||||
import { EventEmitter } from "events";
|
||||
import http from "http";
|
||||
import https from "https";
|
||||
import { Utils } from "./Utils.mjs";
|
||||
import { PROVIDERS } from "./constants/providers.mjs";
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
|
||||
const NL_DEFAULT_PASSWORD = "youshallnotpass";
|
||||
|
||||
const nl = workerData?.data?.nodelink ?? {};
|
||||
const NL_HOST = nl.host ?? "localhost";
|
||||
const NL_PORT = nl.port ?? 3000;
|
||||
|
||||
const NL_PASSWORD = nl.password ?? NL_DEFAULT_PASSWORD;
|
||||
const NL_SESSION_ID = nl.sessionId ?? null;
|
||||
const NL_GUILD_ID = workerData?.data?.guildId ?? null;
|
||||
|
||||
const _sanitizeRegexes = (() => {
|
||||
const r = [];
|
||||
if (NL_HOST && NL_HOST !== "localhost") {
|
||||
const eh = NL_HOST.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
r.push({ re: new RegExp(`https?://${eh}(:\\d+)?[^\\s"']*`, "gi"), sub: "[internal]" });
|
||||
r.push({ re: new RegExp(`${eh}:${NL_PORT}`, "g"), sub: "[internal]" });
|
||||
}
|
||||
r.push({ re: new RegExp(`https?://localhost:${NL_PORT}[^\\s"']*`, "gi"), sub: "[internal]" });
|
||||
if (NL_PASSWORD && NL_PASSWORD !== NL_DEFAULT_PASSWORD) {
|
||||
const ep = NL_PASSWORD.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
r.push({ re: new RegExp(ep, "g"), sub: "[redacted]" });
|
||||
}
|
||||
return r;
|
||||
})();
|
||||
|
||||
function sanitizeError(msg) {
|
||||
if (!msg) return msg;
|
||||
let s = String(msg);
|
||||
for (const { re, sub } of _sanitizeRegexes) {
|
||||
re.lastIndex = 0;
|
||||
s = s.replace(re, sub);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* HTTP GET to NodeLink. Rejects on non-2xx so callers never mistake
|
||||
* an auth/server error for a legitimate empty-result response.
|
||||
* @param {string} path
|
||||
* @param {string} password
|
||||
* @param {string|null} sessionId
|
||||
* @param {string|null} guildId
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
function nlRequest(path, password, sessionId, guildId) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const isHttps = NL_PORT === 443;
|
||||
const mod = isHttps ? https : http;
|
||||
const protocol = isHttps ? "https" : "http";
|
||||
|
||||
const req = mod.get(
|
||||
`${protocol}://${NL_HOST}:${NL_PORT}${path}`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: password,
|
||||
...(sessionId ? { "Session-Id": sessionId } : {}),
|
||||
...(guildId ? { "Guild-Id": guildId } : {}),
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
const chunks = [];
|
||||
res.on("data", d => chunks.push(d));
|
||||
res.on("end", () => {
|
||||
const body = Buffer.concat(chunks).toString();
|
||||
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
let detail = "";
|
||||
try {
|
||||
const parsed = JSON.parse(body);
|
||||
detail = parsed.error ?? parsed.message ?? "";
|
||||
} catch (_) {
|
||||
detail = body.slice(0, 200);
|
||||
}
|
||||
return reject(new Error(`NodeLink HTTP ${res.statusCode}${detail ? ": " + detail : ""}`));
|
||||
}
|
||||
|
||||
try {
|
||||
resolve(JSON.parse(body));
|
||||
} catch (e) {
|
||||
reject(new Error(`NodeLink JSON parse error: ${e.message}`));
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
req.on("error", reject);
|
||||
req.setTimeout(30_000, () => {
|
||||
req.destroy();
|
||||
reject(new Error("NodeLink request timeout"));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/** Worker-thread-level NodeLink GET (uses global credentials). */
|
||||
function nlGet(path) {
|
||||
return nlRequest(path, NL_PASSWORD, NL_SESSION_ID, NL_GUILD_ID);
|
||||
}
|
||||
|
||||
/**
|
||||
* Call NodeLink /v4/loadtracks.
|
||||
* @param {string} identifier
|
||||
* @param {function} getFn
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
async function loadTracks(identifier, getFn = nlGet) {
|
||||
return getFn(`/v4/loadtracks?identifier=${encodeURIComponent(identifier)}`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a NodeLink track object to the internal video format.
|
||||
* @param {object} track
|
||||
* @returns {object|null}
|
||||
*/
|
||||
function trackToVideo(track) {
|
||||
if (!track || typeof track !== "object") return null;
|
||||
|
||||
const info = track.info ?? {};
|
||||
const ms = info.length ?? 0;
|
||||
|
||||
return {
|
||||
videoId: info.identifier ?? "",
|
||||
encoded: track.encoded ?? "",
|
||||
sourceName: info.sourceName ?? "unknown",
|
||||
title: Utils.cleanTitle(info.title ?? "Unknown"),
|
||||
url: info.uri ?? `https://www.youtube.com/watch?v=${info.identifier}`,
|
||||
thumbnail: info.artworkUrl ?? null,
|
||||
spotifyUrl: null,
|
||||
duration: {
|
||||
timestamp: Utils.prettifyMS(ms),
|
||||
seconds: Math.floor(ms / 1000),
|
||||
},
|
||||
author: {
|
||||
name: info.author ?? "Unknown",
|
||||
url: info.uri ?? null,
|
||||
},
|
||||
artists: null,
|
||||
};
|
||||
}
|
||||
|
||||
function normalizeMatchText(value) {
|
||||
return Utils.normalizeText(value, true);
|
||||
}
|
||||
|
||||
function tokenizeMatchText(value) {
|
||||
return normalizeMatchText(value).split(" ").filter(Boolean);
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract an array of track objects from any NodeLink loadTracks response,
|
||||
* regardless of loadType. Returns [] for empty/error/unknown responses.
|
||||
* @param {object} data - NodeLink /v4/loadtracks response
|
||||
* @returns {object[]}
|
||||
*/
|
||||
function extractTracks(data) {
|
||||
if (!data || !data.loadType) return [];
|
||||
|
||||
switch (data.loadType) {
|
||||
case "track":
|
||||
return data.data ? [data.data] : [];
|
||||
case "search":
|
||||
return Array.isArray(data.data) ? data.data : [];
|
||||
case "playlist":
|
||||
return data.data?.tracks ?? [];
|
||||
case "empty":
|
||||
case "error":
|
||||
return [];
|
||||
default:
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
const TYPE_MODIFIERS = ["track", "playlist", "album", "artist", "channel", "user"];
|
||||
|
||||
class YTUtils extends EventEmitter {
|
||||
constructor() {
|
||||
super();
|
||||
}
|
||||
|
||||
isValidUrl(str) { return Utils.isValidUrl(str); }
|
||||
_prefix(p) { return PROVIDERS[p]?.prefix ?? "ytmsearch"; }
|
||||
_providerLabel(p) { return PROVIDERS[p]?.label ?? "YouTube Music"; }
|
||||
_isAudioPreferredProvider(p) { return p === "ytm"; }
|
||||
|
||||
/**
|
||||
* Build all identifier variants to try for a given provider + query.
|
||||
* Different NodeLink source plugins accept different identifier formats.
|
||||
* Some handle `<prefix>:<query>`, others only handle `<prefix>:track:<query>`.
|
||||
* We return both variants so the caller can try each in order.
|
||||
* @param {string} provider
|
||||
* @param {string} query
|
||||
* @returns {string[]}
|
||||
*/
|
||||
_buildIdentifiers(provider, query) {
|
||||
const prefix = this._prefix(provider);
|
||||
|
||||
const colonIdx = query.indexOf(":");
|
||||
if (colonIdx !== -1) {
|
||||
const maybeType = query.slice(0, colonIdx).toLowerCase();
|
||||
if (TYPE_MODIFIERS.includes(maybeType)) {
|
||||
return [`${prefix}:${query}`];
|
||||
}
|
||||
}
|
||||
|
||||
return [
|
||||
`${prefix}:${query}`,
|
||||
`${prefix}:track:${query}`,
|
||||
];
|
||||
}
|
||||
|
||||
_buildRequestContext(query, trackMeta = null) {
|
||||
let requestedTitle = trackMeta?.name ?? trackMeta?.title ?? query;
|
||||
let requestedArtist = trackMeta?.artist ?? "";
|
||||
|
||||
if (!trackMeta) {
|
||||
const dashMatch = String(query).match(/^(.+?)\s+[-–—]\s+(.+)$/);
|
||||
if (dashMatch) {
|
||||
requestedArtist = dashMatch[1].trim();
|
||||
requestedTitle = dashMatch[2].trim();
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
normalizedTitle: normalizeMatchText(requestedTitle),
|
||||
normalizedArtist: normalizeMatchText(requestedArtist),
|
||||
queryTokens: tokenizeMatchText(query),
|
||||
titleTokens: tokenizeMatchText(requestedTitle),
|
||||
artistTokens: tokenizeMatchText(requestedArtist),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean YouTube Radio/Mix URLs to extract just the video ID.
|
||||
* YouTube Radio URLs (list=RD...) often cause metadata mismatches.
|
||||
* @param {string} url
|
||||
* @returns {string}
|
||||
*/
|
||||
_cleanYouTubeUrl(url) {
|
||||
try {
|
||||
const urlObj = new URL(url);
|
||||
|
||||
const list = urlObj.searchParams.get("list");
|
||||
if (list && list.startsWith("RD")) {
|
||||
const videoId = urlObj.searchParams.get("v");
|
||||
if (videoId) {
|
||||
logger.worker(`[Worker] Cleaned YouTube Radio URL, extracted video: ${videoId}`);
|
||||
return `https://www.youtube.com/watch?v=${videoId}`;
|
||||
}
|
||||
}
|
||||
|
||||
if (urlObj.searchParams.has("start_radio")) {
|
||||
urlObj.searchParams.delete("start_radio");
|
||||
return urlObj.toString();
|
||||
}
|
||||
|
||||
return url;
|
||||
} catch (_) {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
_isPlayableTrack(track) {
|
||||
const info = track?.info ?? {};
|
||||
const uri = info.uri || "";
|
||||
if (uri.includes("/channel/")) return false;
|
||||
if (uri.includes("/c/") && !uri.includes("/watch")) return false;
|
||||
if (uri.includes("/playlist?")) return false;
|
||||
if (uri.includes("/user/")) return false;
|
||||
if (info.isStream) return false;
|
||||
if (!info.length || info.length <= 0) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
_scoreTrackForAudio(track, provider = "ytm", request = null) {
|
||||
if (!this._isPlayableTrack(track)) return Number.NEGATIVE_INFINITY;
|
||||
|
||||
const info = track?.info ?? {};
|
||||
const title = String(info.title ?? "").toLowerCase();
|
||||
const author = String(info.author ?? "").toLowerCase();
|
||||
const uri = String(info.uri ?? "").toLowerCase();
|
||||
const source = String(info.sourceName ?? "").toLowerCase();
|
||||
const text = `${title} ${author} ${uri} ${source}`;
|
||||
|
||||
let score = 0;
|
||||
|
||||
const positiveHints = [
|
||||
/\bofficial audio\b/,
|
||||
/\baudio\b/,
|
||||
/\bsong\b/,
|
||||
/\bprovided to youtube by\b/,
|
||||
/\btopic\b/,
|
||||
/\bart track\b/,
|
||||
/\blyrics?\b/,
|
||||
];
|
||||
|
||||
const negativeHints = [
|
||||
/\bofficial music video\b/,
|
||||
/\bmusic video\b/,
|
||||
/\bofficial video\b/,
|
||||
/\bvideo\b/,
|
||||
/\bmv\b/,
|
||||
/\bvisuali[sz]er\b/,
|
||||
/\blive\b/,
|
||||
/\bperformance\b/,
|
||||
/\bconcert\b/,
|
||||
/\bkaraoke\b/,
|
||||
/\bsped up\b/,
|
||||
/\bslowed\b/,
|
||||
/\breverb\b/,
|
||||
/\bnightcore\b/,
|
||||
/\b8d\b/,
|
||||
/\bremix\b/,
|
||||
/\bcover\b/,
|
||||
/\bfan cam\b/,
|
||||
];
|
||||
|
||||
if (this._isAudioPreferredProvider(provider)) {
|
||||
for (const re of positiveHints) {
|
||||
if (re.test(text)) score += 3;
|
||||
}
|
||||
for (const re of negativeHints) {
|
||||
if (re.test(text)) score -= 4;
|
||||
}
|
||||
|
||||
if (author.endsWith(" - topic") || author.includes("topic")) score += 4;
|
||||
if (uri.includes("music.youtube.com")) score += 3;
|
||||
if (source === "youtube music") score += 3;
|
||||
}
|
||||
|
||||
if (request) {
|
||||
const normalizedTitle = normalizeMatchText(info.title);
|
||||
const normalizedAuthor = normalizeMatchText(info.author);
|
||||
const fullText = `${normalizedTitle} ${normalizedAuthor} ${normalizeMatchText(info.uri)} ${normalizeMatchText(info.sourceName)}`.trim();
|
||||
|
||||
if (request.normalizedTitle) {
|
||||
if (normalizedTitle === request.normalizedTitle) score += 30;
|
||||
else if (normalizedTitle.includes(request.normalizedTitle)) score += 18;
|
||||
else score -= 6;
|
||||
}
|
||||
|
||||
if (request.normalizedArtist) {
|
||||
if (normalizedAuthor === request.normalizedArtist) score += 20;
|
||||
else if (normalizedAuthor.includes(request.normalizedArtist)) score += 12;
|
||||
else score -= 8;
|
||||
}
|
||||
|
||||
if (request.queryTokens.length) {
|
||||
const overlap = request.queryTokens.filter(token => fullText.includes(token)).length;
|
||||
score += overlap * 2;
|
||||
}
|
||||
|
||||
if (request.titleTokens.length) {
|
||||
const titleOverlap = request.titleTokens.filter(token => normalizedTitle.includes(token)).length;
|
||||
score += titleOverlap * 4;
|
||||
}
|
||||
|
||||
if (request.artistTokens.length) {
|
||||
const artistOverlap = request.artistTokens.filter(token => normalizedAuthor.includes(token)).length;
|
||||
score += artistOverlap * 5;
|
||||
}
|
||||
}
|
||||
|
||||
return score;
|
||||
}
|
||||
|
||||
_pickBestTrack(tracks, provider = "ytm", request = null) {
|
||||
const playable = tracks.filter(track => this._isPlayableTrack(track));
|
||||
const candidates = playable.length > 0 ? playable : tracks;
|
||||
if (!candidates.length) return null;
|
||||
|
||||
return candidates
|
||||
.map((track, index) => ({ track, index, score: this._scoreTrackForAudio(track, provider, request) }))
|
||||
.sort((a, b) => b.score - a.score || a.index - b.index)[0]
|
||||
?.track ?? null;
|
||||
}
|
||||
|
||||
_rankTracks(tracks, provider = "ytm", request = null) {
|
||||
const playable = tracks.filter(track => this._isPlayableTrack(track));
|
||||
const candidates = playable.length > 0 ? playable : tracks;
|
||||
|
||||
return candidates
|
||||
.map((track, index) => ({ track, index, score: this._scoreTrackForAudio(track, provider, request) }))
|
||||
.sort((a, b) => b.score - a.score || a.index - b.index)
|
||||
.map(item => item.track);
|
||||
}
|
||||
|
||||
_applyTrackMeta(video, trackMeta = null) {
|
||||
if (!video || !trackMeta) return video;
|
||||
|
||||
return {
|
||||
...video,
|
||||
artist: trackMeta.artist ?? video.artist ?? null,
|
||||
requestedArtist: trackMeta.artist ?? video.requestedArtist ?? null,
|
||||
requestedTitle: trackMeta.name ?? trackMeta.title ?? video.requestedTitle ?? null,
|
||||
lastfm: {
|
||||
source: trackMeta.source ?? "lastfm",
|
||||
artist: trackMeta.artist ?? null,
|
||||
name: trackMeta.name ?? trackMeta.title ?? null,
|
||||
url: trackMeta.url ?? "",
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Return an ordered list of providers to try when searching.
|
||||
* The requested provider is first; if it returns no results we fall
|
||||
* back to YouTube Music, then YouTube.
|
||||
* @param {string} provider
|
||||
* @returns {string[]}
|
||||
*/
|
||||
_getFallbackChain(provider) {
|
||||
const chain = [provider];
|
||||
if (provider !== "ytm") chain.push("ytm");
|
||||
if (provider !== "yt") chain.push("yt");
|
||||
return chain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Search a single provider using multiple identifier formats.
|
||||
* Different NodeLink source plugins accept different identifier formats,
|
||||
* so we try each variant until one returns results.
|
||||
* @param {string} provider
|
||||
* @param {string} query
|
||||
* @returns {Promise<object[]|null>} Array of tracks, or null if this provider has no results at all.
|
||||
*/
|
||||
async _searchProvider(provider, query) {
|
||||
const identifiers = this._buildIdentifiers(provider, query);
|
||||
|
||||
for (const id of identifiers) {
|
||||
let data;
|
||||
try {
|
||||
data = await loadTracks(id, this._nlGet ?? nlGet);
|
||||
} catch (e) {
|
||||
logger.worker(`[Worker] _searchProvider: loadTracks failed for ${provider} (${id}): ${e.message}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
const tracks = extractTracks(data);
|
||||
if (tracks.length > 0) {
|
||||
return tracks;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for multiple results (used by search command).
|
||||
* @param {string} query
|
||||
* @param {number} limit
|
||||
* @param {string} provider
|
||||
* @param {object|null} trackMeta
|
||||
* @returns {Promise<{data: object[]}>}
|
||||
*/
|
||||
async getResults(query, limit = 5, provider = "ytm", trackMeta = null) {
|
||||
const request = this._buildRequestContext(query, trackMeta);
|
||||
const providers = this._getFallbackChain(provider);
|
||||
|
||||
for (const prov of providers) {
|
||||
const id = this.isValidUrl(query) ? query : null;
|
||||
|
||||
let tracks;
|
||||
if (id) {
|
||||
let data;
|
||||
try {
|
||||
data = await loadTracks(id, this._nlGet ?? nlGet);
|
||||
} catch (e) {
|
||||
logger.worker("[Worker] getResults loadTracks failed:", e?.message);
|
||||
continue;
|
||||
}
|
||||
tracks = extractTracks(data);
|
||||
} else {
|
||||
tracks = await this._searchProvider(prov, query);
|
||||
}
|
||||
|
||||
if (tracks && tracks.length > 0) {
|
||||
const resultTracks = this._rankTracks(tracks, prov, request);
|
||||
return { data: resultTracks.slice(0, limit).map(track => this._applyTrackMeta(trackToVideo(track), trackMeta)) };
|
||||
}
|
||||
|
||||
logger.worker(`[Worker] getResults: no results from ${prov}, trying fallback...`);
|
||||
}
|
||||
|
||||
return { data: [] };
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for a single track (used by play command).
|
||||
* Tries multiple identifier formats per provider, then falls back
|
||||
* through the provider chain until a result is found.
|
||||
* @param {string} query
|
||||
* @param {string} provider
|
||||
* @param {object|null} trackMeta
|
||||
* @returns {Promise<{type: string, data: *, error?: string}>}
|
||||
*/
|
||||
async getVideoData(query, provider = "ytm", trackMeta = null) {
|
||||
const request = this._buildRequestContext(query, trackMeta);
|
||||
|
||||
if (this.isValidUrl(query)) {
|
||||
return this._loadUrl(query, provider, request, trackMeta);
|
||||
}
|
||||
|
||||
return this._searchByQuery(query, provider, request, trackMeta);
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle URL-based track loading.
|
||||
* @private
|
||||
*/
|
||||
async _loadUrl(query, provider, request, trackMeta) {
|
||||
this.emit("message", "Loading...");
|
||||
|
||||
const cleanedUrl = this._cleanYouTubeUrl(query);
|
||||
if (cleanedUrl !== query) {
|
||||
logger.worker(`[Worker] URL cleaned: ${query} -> ${cleanedUrl}`);
|
||||
}
|
||||
|
||||
let data;
|
||||
try {
|
||||
data = await loadTracks(cleanedUrl, this._nlGet ?? nlGet);
|
||||
} catch (e) {
|
||||
this.emit("message", `**Failed to load that track.**`);
|
||||
return { type: "error", data: null, error: sanitizeError(e.message) };
|
||||
}
|
||||
|
||||
if (data.loadType === "empty") {
|
||||
this.emit("message", `**No results found for that URL.**`);
|
||||
return { type: "error", data: null, error: "No results found (empty)" };
|
||||
}
|
||||
|
||||
if (data.loadType === "track" && data.data) {
|
||||
const video = this._applyTrackMeta(trackToVideo(data.data), trackMeta);
|
||||
if (!video) return { type: "error", data: "Failed to parse track data." };
|
||||
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
|
||||
return { type: "video", data: video };
|
||||
}
|
||||
|
||||
if (data.loadType === "playlist") {
|
||||
const tracks = (data.data?.tracks ?? []).map(track => this._applyTrackMeta(trackToVideo(track), trackMeta));
|
||||
tracks.forEach(t => { t.playlistName = data.data?.info?.name ?? null; });
|
||||
if (tracks.length > 0) {
|
||||
this.emit("message", `Successfully added **${tracks.length}** songs to the queue.`);
|
||||
return { type: "list", data: tracks };
|
||||
}
|
||||
this.emit("message", `**Playlist was empty.**`);
|
||||
return { type: "error", data: null, error: "Playlist was empty" };
|
||||
}
|
||||
|
||||
if (data.loadType === "search") {
|
||||
if (data.data?.length) {
|
||||
const bestTrack = this._pickBestTrack(data.data, provider, request) ?? data.data[0];
|
||||
const video = this._applyTrackMeta(trackToVideo(bestTrack), trackMeta);
|
||||
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
|
||||
return { type: "video", data: video };
|
||||
}
|
||||
this.emit("message", `**Search returned no results for that URL.**`);
|
||||
return { type: "error", data: null, error: "Search returned 0 results for URL" };
|
||||
}
|
||||
|
||||
this.emit("message", `**Could not load that URL.** (loadType: ${data.loadType || "unknown"})`);
|
||||
return { type: "error", data: null, error: "Unknown loadType: " + (data.loadType || "none") };
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle text-based search across provider fallback chain.
|
||||
* For each provider, tries all identifier variants before giving up.
|
||||
* @private
|
||||
*/
|
||||
async _searchByQuery(query, provider, request, trackMeta) {
|
||||
const providers = this._getFallbackChain(provider);
|
||||
let lastError = null;
|
||||
|
||||
for (const prov of providers) {
|
||||
this.emit("message", `Searching ${this._providerLabel(prov)}...`);
|
||||
|
||||
const tracks = await this._searchProvider(prov, query);
|
||||
|
||||
if (tracks && tracks.length > 0) {
|
||||
const trackToUse = this._pickBestTrack(tracks, prov, request) ?? tracks[0];
|
||||
const video = this._applyTrackMeta(trackToVideo(trackToUse), trackMeta);
|
||||
if (video) {
|
||||
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
|
||||
return { type: "video", data: video };
|
||||
}
|
||||
lastError = "Failed to parse track data.";
|
||||
continue;
|
||||
}
|
||||
|
||||
logger.worker(`[Worker] No results from ${prov}`);
|
||||
}
|
||||
|
||||
this.emit("message", `**No results found for '${query}'.**`);
|
||||
return { type: "error", data: null, error: lastError ?? "No results found" };
|
||||
}
|
||||
}
|
||||
|
||||
const jobId = workerData?.jobId;
|
||||
const data = workerData?.data;
|
||||
|
||||
if (workerData?.poolMode) {
|
||||
const utils = new YTUtils();
|
||||
|
||||
const post = (jobKey, event, payload) => {
|
||||
parentPort.postMessage(JSON.stringify({ jobKey, event, data: payload }));
|
||||
};
|
||||
|
||||
parentPort.on("message", async (raw) => {
|
||||
let parsed;
|
||||
try { parsed = typeof raw === "string" ? JSON.parse(raw) : raw; }
|
||||
catch (_) { return; }
|
||||
|
||||
const { jobKey, jobId: jId, data: jData } = parsed;
|
||||
if (!jobKey || !jId) return;
|
||||
|
||||
const nlJob = jData?.nodelink ?? {};
|
||||
const nlHostJob = nlJob.host ?? "localhost";
|
||||
const nlPortJob = nlJob.port ?? 3000;
|
||||
const nlPassJob = nlJob.password ?? NL_DEFAULT_PASSWORD;
|
||||
const nlSidJob = nlJob.sessionId ?? null;
|
||||
const nlGidJob = jData?.guildId ?? null;
|
||||
|
||||
const nlGetJob = (path) => new Promise((resolve, reject) => {
|
||||
const isHttps = nlPortJob === 443;
|
||||
const mod = isHttps ? https : http;
|
||||
const protocol = isHttps ? "https" : "http";
|
||||
const req = mod.get(
|
||||
`${protocol}://${nlHostJob}:${nlPortJob}${path}`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: nlPassJob,
|
||||
...(nlSidJob ? { "Session-Id": nlSidJob } : {}),
|
||||
...(nlGidJob ? { "Guild-Id": nlGidJob } : {}),
|
||||
},
|
||||
},
|
||||
(res) => {
|
||||
const chunks = [];
|
||||
res.on("data", d => chunks.push(d));
|
||||
res.on("end", () => {
|
||||
const body = Buffer.concat(chunks).toString();
|
||||
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
let detail = "";
|
||||
try {
|
||||
const parsed = JSON.parse(body);
|
||||
detail = parsed.error ?? parsed.message ?? "";
|
||||
} catch (_) {
|
||||
detail = body.slice(0, 200);
|
||||
}
|
||||
return reject(new Error(`NodeLink HTTP ${res.statusCode}${detail ? ": " + detail : ""}`));
|
||||
}
|
||||
|
||||
try { resolve(JSON.parse(body)); }
|
||||
catch (e) { reject(new Error(`NodeLink JSON parse error: ${e.message}`)); }
|
||||
});
|
||||
},
|
||||
);
|
||||
req.on("error", reject);
|
||||
req.setTimeout(30_000, () => { req.destroy(); reject(new Error("NodeLink request timeout")); });
|
||||
});
|
||||
|
||||
const jobUtils = new YTUtils();
|
||||
jobUtils._nlGet = nlGetJob;
|
||||
|
||||
jobUtils.on("message", (m) => post(jobKey, "message", m));
|
||||
jobUtils.on("error", (m) => post(jobKey, "error", m));
|
||||
|
||||
try {
|
||||
let result;
|
||||
switch (jId) {
|
||||
case "generalQuery":
|
||||
result = await jobUtils.getVideoData(jData.query, jData.provider, jData.trackMeta);
|
||||
break;
|
||||
case "searchResults":
|
||||
result = await jobUtils.getResults(jData.query, jData.resultCount, jData.provider, jData.trackMeta);
|
||||
break;
|
||||
case "search":
|
||||
result = await jobUtils.getVideoData(jData.query ?? String(jData), "ytm");
|
||||
result = result?.data ?? null;
|
||||
break;
|
||||
default:
|
||||
post(jobKey, "error", `Unknown jobId: ${jId}`);
|
||||
return;
|
||||
}
|
||||
post(jobKey, "finished", result);
|
||||
} catch (err) {
|
||||
post(jobKey, "error", err.message);
|
||||
} finally {
|
||||
jobUtils.removeAllListeners();
|
||||
}
|
||||
});
|
||||
|
||||
} else {
|
||||
|
||||
if (!jobId) {
|
||||
logger.error("No jobId provided to worker");
|
||||
process.exit(1);
|
||||
}
|
||||
|
||||
const utils = new YTUtils();
|
||||
|
||||
const post = (event, payload) => {
|
||||
parentPort.postMessage(JSON.stringify({ event, data: payload }));
|
||||
};
|
||||
|
||||
utils.on("message", (m) => {
|
||||
post("message", m);
|
||||
});
|
||||
|
||||
utils.on("error", (m) => {
|
||||
post("error", m);
|
||||
});
|
||||
|
||||
(async () => {
|
||||
try {
|
||||
switch (jobId) {
|
||||
case "generalQuery": {
|
||||
const result = await utils.getVideoData(data.query, data.provider, data.trackMeta);
|
||||
post("finished", result);
|
||||
break;
|
||||
}
|
||||
case "searchResults": {
|
||||
const result = await utils.getResults(data.query, data.resultCount, data.provider, data.trackMeta);
|
||||
post("finished", result);
|
||||
break;
|
||||
}
|
||||
case "search": {
|
||||
const result = await utils.getVideoData(data.query ?? String(data), "ytm");
|
||||
post("finished", result?.data ?? null);
|
||||
break;
|
||||
}
|
||||
default:
|
||||
logger.error("Invalid jobId:", jobId);
|
||||
post("error", `Unknown jobId: ${jobId}`);
|
||||
}
|
||||
} catch (err) {
|
||||
post("error", err.message);
|
||||
} finally {
|
||||
process.exit(0);
|
||||
}
|
||||
})();
|
||||
}
|
||||
Reference in new issue
Block a user