mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-23 21:52:45 -05:00
initial push to remix-bot/fluxer
This commit is contained in:
commit
2820cc881c
63 files changed
+16005
No files matched your search
@@ -0,0 +1,753 @@
|
||||
import { pathToFileURL } from "node:url";
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
import { Utils } from "./Utils.mjs";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { Message, MessageHandler, PageBuilder } from "./MessageHandler.mjs";
|
||||
import { Client, PermissionFlags } from "@fluxerjs/core";
|
||||
import { SettingsManager } from "./Settings.mjs";
|
||||
import path from "node:path";
|
||||
import * as fs from "node:fs";
|
||||
|
||||
export class CommandBuilder {
|
||||
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 = [];
|
||||
|
||||
this.uid = Utils.uid();
|
||||
|
||||
this.subcommandError = "Invalid subcommand. Try one of the following options: `$previousCmd <$cmdlist>`";
|
||||
/** @type {CommandBuilder} */
|
||||
this.parent = null;
|
||||
}
|
||||
setName(n) { this.name = n; this.aliases.push(n.toLowerCase()); return this; }
|
||||
setDescription(d) { this.description = d; return this; }
|
||||
setId(id) { this.id = id; return this; }
|
||||
get command() { return (this.parent) ? this.parent.command + " " + this.name : this.name; }
|
||||
setRequirement(config) { let req = config(new CommandRequirement()); this.requirements.push(req); return this; }
|
||||
addSubcommand(config) { let sub = config(new CommandBuilder()); sub.parent = this; this.subcommands.push(sub); return this; }
|
||||
addStringOption(config, flag = false) { this.options.push(config(Option.create("string", flag))); return this; }
|
||||
addNumberOption(config, flag = false) { this.options.push(config(Option.create("number", flag))); return this; }
|
||||
addBooleanOption(config, flag = false) { this.options.push(config(Option.create("boolean", flag))); return this; }
|
||||
addChannelOption(config, flag = false) { this.options.push(config(Option.create("channel", flag))); return this; }
|
||||
addUserOption(config, flag = false) { this.options.push(config(Option.create("user", flag))); return this; }
|
||||
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;
|
||||
}
|
||||
addChoiceOption(config, flag = false) { this.options.push(config(Option.create("choice", flag))); return this; }
|
||||
addAlias(alias) { if (this.aliases.findIndex(e => e === alias.toLowerCase()) !== -1) return this; this.aliases.push(alias.toLowerCase()); return this; }
|
||||
addAliases(...aliases) { aliases.forEach((a) => this.addAlias(a)); return this; }
|
||||
setCategory(cat) { this.category = cat; return this; }
|
||||
addExamples(...examples) { this.examples.push(...examples); return this; }
|
||||
}
|
||||
|
||||
export class CommandRequirement {
|
||||
ownerOnly = false;
|
||||
constructor() {
|
||||
this.permissions = [];
|
||||
this.permissionError = "You don't have the needed permissions to run this command!";
|
||||
return this;
|
||||
}
|
||||
setOwnerOnly(bool) { this.ownerOnly = bool; return this; }
|
||||
/**
|
||||
* @param {string} p Fluxer permission string (discord.js-style, e.g. "ManageChannels", "ManageGuild")
|
||||
*/
|
||||
addPermission(p) { this.permissions.push(p); return this; }
|
||||
addPermissions(...p) { this.permissions.push(...p); return this; }
|
||||
getPermissions() { return (this.ownerOnly) ? [...this.permissions, "Owner-only command"] : this.permissions; }
|
||||
setPermissionError(e) { this.permissionError = e; return this; }
|
||||
}
|
||||
|
||||
export class Option {
|
||||
// Fluxer uses discord.js-like channel mentions: <#id> and user mentions <@id>
|
||||
channelRegex = /^<#(?<id>\d+)>/;
|
||||
userRegex = /^<@!?(?<id>\d+)>/;
|
||||
idRegex = /^(?<id>\d+)/;
|
||||
|
||||
/** @type {Function} */
|
||||
dynamicDefault;
|
||||
|
||||
constructor(type = "string") {
|
||||
this.name = null;
|
||||
this.description = null;
|
||||
this.required = false;
|
||||
this.id = null;
|
||||
this.uid = Utils.uid();
|
||||
this.type = type;
|
||||
this.tError = null;
|
||||
this.aliases = [null];
|
||||
this.choices = [];
|
||||
this.translations = {};
|
||||
this.defaultValue = null;
|
||||
this.dynamicDefault = null;
|
||||
}
|
||||
|
||||
static create(type, flag = false) {
|
||||
return (!flag) ? new Option(type) : new Flag(type);
|
||||
}
|
||||
|
||||
setName(n) { this.name = n; this.aliases[0] = n; return this; }
|
||||
setDescription(d) { this.description = d; return this; }
|
||||
setRequired(r) { this.required = r; return this; }
|
||||
setId(id) { this.id = id; return this; }
|
||||
setType(t) { this.type = t; return this; }
|
||||
addFlagAliases(...a) { this.aliases.push(...a); return this; }
|
||||
addChoice(c) { if (this.type !== "choice") throw new Error(".addChoice is only available for choice options!"); this.choices.push(c); return this; }
|
||||
addChoices(...cs) { if (this.type !== "choice") throw new Error(".addChoices is only available for choice options!"); cs.forEach(c => this.addChoice(c)); return this; }
|
||||
setDefault(value) { this.defaultValue = value; return this; }
|
||||
setDynamicDefault(callback) { this.dynamicDefault = callback; return this; }
|
||||
|
||||
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}
|
||||
*/
|
||||
validateInput(i, client, msg, type) {
|
||||
switch (type || this.type) {
|
||||
case "text":
|
||||
case "string":
|
||||
return !!i;
|
||||
case "number":
|
||||
return !isNaN(i) && !isNaN(parseFloat(i));
|
||||
case "boolean":
|
||||
return i === "0" || i === "1" || i?.toLowerCase() === "true" || i?.toLowerCase() === "false";
|
||||
case "choice":
|
||||
return this.choices.includes(i);
|
||||
case "user":
|
||||
return this.userRegex.test(i) || this.idRegex.test(i);
|
||||
case "channel":
|
||||
if (i === undefined) return false;
|
||||
return this.channelRegex.test(i) || this.idRegex.test(i) || client.channels.cache.some(c => c.name === i);
|
||||
case "voiceChannel": {
|
||||
if (!i) return false;
|
||||
const results = this.channelRegex.exec(i) ?? this.idRegex.exec(i);
|
||||
const guildId = msg?.channel?.guildId ?? msg?.guildId;
|
||||
|
||||
// dry-run eval mode
|
||||
if (guildId === "eval") return (results) ? results.groups["id"] : i;
|
||||
|
||||
const voiceTypes = [2, 13]; // GuildVoice and GuildStageVoice
|
||||
const byName = msg?.guild?.channels?.cache?.find(c => c.name === i && voiceTypes.includes(c.type));
|
||||
const cObj = results
|
||||
? client.channels.cache.get(results.groups["id"])
|
||||
: (byName ?? null);
|
||||
return cObj ? voiceTypes.includes(cObj.type) : false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {string} i
|
||||
* @param {Client} client
|
||||
* @param {import("@fluxerjs/core").Message} msg
|
||||
* @param {string} [type]
|
||||
* @returns {string|number|boolean}
|
||||
*/
|
||||
formatInput(i, client, msg, type) {
|
||||
switch (type || this.type) {
|
||||
case "text":
|
||||
case "string":
|
||||
return i;
|
||||
case "number":
|
||||
return parseFloat(i);
|
||||
case "boolean":
|
||||
return i?.toLowerCase() === "true" || i === "1";
|
||||
case "choice":
|
||||
return i;
|
||||
case "user": {
|
||||
const rs = this.userRegex.exec(i) ?? this.idRegex.exec(i);
|
||||
return rs?.groups["id"] ?? null;
|
||||
}
|
||||
case "channel": {
|
||||
const results = this.channelRegex.exec(i) ?? this.idRegex.exec(i);
|
||||
const channel = client.channels.cache.find(c => c.name === i);
|
||||
return results ? results.groups["id"] : (channel ? channel.id : null);
|
||||
}
|
||||
case "voiceChannel": {
|
||||
const r = this.channelRegex.exec(i) ?? this.idRegex.exec(i);
|
||||
const guildId = msg?.channel?.guildId ?? msg?.guildId;
|
||||
if (guildId === "eval") return r ? r.groups["id"] : (i || null);
|
||||
const voiceTypes = [2, 13];
|
||||
const c = msg?.guild?.channels?.cache?.find(c => c.name === i && voiceTypes.includes(c.type));
|
||||
return r ? r.groups["id"] : (c ? c.id : null);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
get typeError() {
|
||||
if (this.tError) return this.tError;
|
||||
switch (this.type) {
|
||||
case "choice":
|
||||
return "Invalid value '$currValue'. The option `" + this.name + "` has to be one of the following options: \n- " + this.choices.join("\n- ") + "\nSchematic: `$previousCmd <" + this.type + ">`";
|
||||
case "voiceChannel":
|
||||
case "channel":
|
||||
return "Invalid value '$currValue'. The option `" + this.name + "` has to be a channel mention, id, or name.\nSchematic: `$previousCmd <" + this.type + ">`";
|
||||
default:
|
||||
return "Invalid value '$currValue'. The option `" + this.name + "` has to be of type `" + this.type + "`.\nSchematic: `$previousCmd <" + this.type + ">`";
|
||||
}
|
||||
}
|
||||
set typeError(e) { this.tError = e; }
|
||||
}
|
||||
|
||||
export class Flag extends Option {
|
||||
constructor(type = "string") {
|
||||
if (type === "text") throw new Error("Flags can't be of type 'text'!");
|
||||
super(type);
|
||||
}
|
||||
}
|
||||
|
||||
export class PrefixManager {
|
||||
/** @type {SettingsManager} */
|
||||
settings;
|
||||
constructor(settings) { this.settings = settings; }
|
||||
getPrefix(guildId) { return this.settings.getServer(guildId).get("prefix"); }
|
||||
}
|
||||
|
||||
export class HelpHandler {
|
||||
/** @type {CommandHandler} */
|
||||
commands;
|
||||
commandsPerPage = 5;
|
||||
|
||||
paginationHandler = (msg, helpHandler, cmds) => {
|
||||
let form = "Available Commands (page $currentPage/$maxPage): \n\n$content";
|
||||
form += "\n\nRun `$prefix$helpCmd <command>` to learn more about it. You can also include subcommands.\n";
|
||||
form += "For example: `$prefix$helpCmd settings get`\n\n";
|
||||
form += "Tip: Use the arrows beneath this message to turn pages, or specify the required page by using `$prefix$helpCmd <page number>`";
|
||||
|
||||
const contents = cmds.map((cmd, i) => {
|
||||
return (i + 1) + ". **" + cmd.name + "**: " + (cmd.description || "").split("\n")[0];
|
||||
});
|
||||
|
||||
const pages = new PageBuilder(contents)
|
||||
.setForm(helpHandler.commands.format(form, msg.message.guildId))
|
||||
.setMaxLines(helpHandler.commandsPerPage);
|
||||
|
||||
helpHandler.commands.messages.initPagination(pages, msg);
|
||||
return null;
|
||||
}
|
||||
|
||||
customHelpHandler = null;
|
||||
|
||||
constructor(commands) { this.commands = commands; }
|
||||
|
||||
static capitalise(string) {
|
||||
if (string.length < 1) return string;
|
||||
if (string.length === 1) return string.toUpperCase();
|
||||
return string.charAt(0).toUpperCase() + string.slice(1);
|
||||
}
|
||||
|
||||
userCommands(cmds) {
|
||||
return (cmds || this.commands.commands).filter(c =>
|
||||
c.requirements.findIndex(r => r.ownerOnly) === -1
|
||||
);
|
||||
}
|
||||
|
||||
pageNumber() {
|
||||
return Math.ceil(this.commands.commands.length / this.commandsPerPage);
|
||||
}
|
||||
|
||||
help(message) {
|
||||
if (this.customHelpHandler) return this.customHelpHandler(message);
|
||||
if (this.paginationHandler) return this.genHelp(null, message, true);
|
||||
return this.getHelpPage(0, message);
|
||||
}
|
||||
|
||||
getHelpPage(n, msg, cmds = null) {
|
||||
if (!cmds) cmds = this.commands.commands;
|
||||
if (!(this.commandsPerPage < cmds.length)) return this.genHelp(null, msg, false, cmds);
|
||||
let offset = this.commandsPerPage * n;
|
||||
const commands = cmds.slice(offset, offset + this.commandsPerPage);
|
||||
let max = Math.ceil(cmds.length / this.commandsPerPage);
|
||||
return this.genHelp({ curr: n + 1, max, offset }, msg, false, commands);
|
||||
}
|
||||
|
||||
genHelp(page, msg, paginate = false, cmds = null) {
|
||||
cmds = this.userCommands(cmds);
|
||||
if (this.paginationHandler && msg && paginate) return this.paginationHandler(msg, this, cmds);
|
||||
|
||||
let p = (page) ? ` (page ${page.curr}/${page.max})` : "";
|
||||
const indexOffset = (page) ? page.offset : 0;
|
||||
let content = "Available Commands" + p + ": \n\n";
|
||||
if (page && page.curr !== 1) content += (indexOffset) + ". [...]\n";
|
||||
cmds.forEach((cmd, i) => { content += (i + 1 + indexOffset) + ". **" + cmd.name + "**: " + cmd.description + "\n"; });
|
||||
if (page && page.curr !== page.max) content += (cmds.length + indexOffset) + ". [...]\n";
|
||||
content += "\nRun `$prefix$helpCmd <command>` to learn more about it. You can also include subcommands.\n";
|
||||
content += "For example: `$prefix$helpCmd command subcommandName`";
|
||||
if (page) content += "\n\nTip: Turn pages by using `$prefix$helpCmd <page number>`";
|
||||
|
||||
return this.commands.format(content, msg.message.guildId);
|
||||
}
|
||||
|
||||
commandDescription(command) { return command.description; }
|
||||
|
||||
commandUsage(cmd, msg) {
|
||||
if (cmd.subcommands.length > 0) {
|
||||
return this.commands.format("$prefix" + cmd.command, msg.message.guildId) + " <" + cmd.subcommands.map(e => e.name).join(" | ") + "> [...]";
|
||||
}
|
||||
let options = this.commands.format("$prefix" + cmd.command, msg.message.guildId);
|
||||
cmd.options.forEach(o => {
|
||||
if (o.type === "text") return;
|
||||
if (o instanceof Flag)
|
||||
return options += (o.type === "choice") ? "-" + o.aliases[0] + " <" + o.choices.join(" | ") + ">" : " -" + o.aliases[0] + " '" + o.type + "'";
|
||||
options += (o.type === "choice") ? " <" + o.choices.join(" |") + ">" : " '" + o.name + ": " + o.type + "'";
|
||||
});
|
||||
let o = cmd.options.find(e => e.type === "text");
|
||||
if (o) options += "'" + o.name + ": " + o.type + "'";
|
||||
return options.trim();
|
||||
}
|
||||
|
||||
getCommandHelp(command, msg) {
|
||||
let content = `${HelpHandler.capitalise(command.name)}\n`;
|
||||
content += this.commandDescription(command, msg) + "\n\n";
|
||||
content += "Usage: \n💻 `" + this.commandUsage(command, msg) + "`\n\n";
|
||||
if (command.examples.length > 0)
|
||||
content += "Example(s): \n- `" + command.examples.map(e => this.commands.format(e, msg.message.guildId)).join("`\n- `") + "`\n\n";
|
||||
if (command.aliases.length > 1) {
|
||||
content += "Aliases: \n";
|
||||
command.aliases.forEach(alias => { content += "- " + alias + "\n"; });
|
||||
content += "\n";
|
||||
}
|
||||
if (command.subcommands.length > 0) {
|
||||
content += "Subcommands: \n";
|
||||
command.subcommands.forEach(s => {
|
||||
content += "- " + s.name + ": " + (this.commandDescription(s, msg) || "").split("\n")[0] + ((s.options.length > 0) ? "; (`" + s.options.length + " option(s)`)" : "") + "\n";
|
||||
});
|
||||
content += "\n";
|
||||
} else if (command.options.length > 0) {
|
||||
content += "Arguments: \n";
|
||||
command.options.forEach(o => {
|
||||
const optional = ((o.required) ? "" : "?");
|
||||
const flag = (o instanceof Flag) ? "-" : "";
|
||||
if (o.type === "choice") {
|
||||
content += "- **" + flag + o.name + "**" + optional + ": " + (o.description || "").split("\n")[0] + ";\n - Allowed values: `" + o.choices.join("`, `") + "`\n - Aliases: `" + o.aliases.join("`, `") + "`\n";
|
||||
} else {
|
||||
content += "- **" + flag + o.name + "**" + optional + ": " + (o.description || "").split("\n")[0] + "\n - Aliases: `" + o.aliases.join("`, `") + "`\n";
|
||||
}
|
||||
content += "\n";
|
||||
});
|
||||
content += "\n";
|
||||
}
|
||||
if (command.requirements.length > 0) {
|
||||
content += "Requirements: \n";
|
||||
command.requirements.forEach(r => {
|
||||
content += "- " + r.getPermissions().map(e => "Permission `" + e + "`").join("\n- ");
|
||||
});
|
||||
}
|
||||
return content.trim();
|
||||
}
|
||||
}
|
||||
|
||||
export class CommandHandler extends EventEmitter {
|
||||
onPing = null;
|
||||
pingPrefix = true;
|
||||
owners = [];
|
||||
|
||||
/** @type {MessageHandler} */
|
||||
messages;
|
||||
/** @type {Client} */
|
||||
client;
|
||||
/** @type {PrefixManager} */
|
||||
prefixes;
|
||||
/** @type {HelpHandler} */
|
||||
helpHandler;
|
||||
|
||||
commandNames = [];
|
||||
/** @type {CommandBuilder[]} */
|
||||
commands = [];
|
||||
|
||||
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.";
|
||||
|
||||
constructor(handler, prefix = "!") {
|
||||
super();
|
||||
this.messages = handler;
|
||||
this.client = handler.client;
|
||||
this.prefix = prefix;
|
||||
this.helpHandler = new HelpHandler(this);
|
||||
this.helpCommand = "help";
|
||||
this.replyHandler = (message, msg) => {
|
||||
msg.replyEmbed(this.format(message, msg.channel.channel.guildId));
|
||||
};
|
||||
this.messages.onMessage(this.messageHandler.bind(this));
|
||||
}
|
||||
|
||||
getPrefix(guildId) { return this.prefixes.getPrefix(guildId); }
|
||||
setPingPrefix(bool) { this.pingPrefix = bool; }
|
||||
setPrefixManager(manager) { this.prefixes = manager; }
|
||||
setHelpHandler(handler) { this.helpHandler = handler; }
|
||||
|
||||
format(text, guildId) {
|
||||
const prefix = (!guildId) ? this.prefix : this.getPrefix(guildId);
|
||||
return text
|
||||
.replace(/\$prefix/gi, prefix)
|
||||
.replace(/\$helpCmd/gi, this.helpCommand);
|
||||
}
|
||||
|
||||
removeCommand(command) {
|
||||
command.aliases.forEach(a => {
|
||||
const idx = this.commandNames.indexOf(a);
|
||||
if (idx !== -1) this.commandNames.splice(idx, 1);
|
||||
});
|
||||
const idx = this.commands.findIndex(c => c.uid === command.uid);
|
||||
if (idx !== -1) this.commands.splice(idx, 1);
|
||||
}
|
||||
|
||||
messageHandler(msg) {
|
||||
if (!msg || !msg.content) return;
|
||||
const trimmed = msg.content.trim();
|
||||
if (/^<@!?\d+>$/.test(trimmed)) {
|
||||
// Only respond if the bot itself was pinged
|
||||
const botId = this.client.user?.id;
|
||||
if (botId && (trimmed === `<@${botId}>` || trimmed === `<@!${botId}>`)) {
|
||||
return this.onPing?.(msg);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const guildId = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
const prefix = this.getPrefix(guildId);
|
||||
const ping = `<@${this.client.user?.id}>`;
|
||||
const pingBang = `<@!${this.client.user?.id}>`;
|
||||
if (!(msg.content.startsWith(prefix) || msg.content.startsWith(ping) || msg.content.startsWith(pingBang))) return;
|
||||
|
||||
const len = msg.content.startsWith(prefix) ? prefix.length : (msg.content.startsWith(pingBang) ? pingBang.length : ping.length);
|
||||
const args = msg.content.slice(len).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim());
|
||||
|
||||
if (!args[0]) return;
|
||||
|
||||
if (args[0] === this.helpCommand) {
|
||||
if (!args[1]) {
|
||||
const res = this.helpHandler.help(msg);
|
||||
return (typeof res === "string") ? this.replyHandler(res, msg) : undefined;
|
||||
}
|
||||
if (args.length > 1 && Utils.isNumber(args[1])) {
|
||||
const pageNumber = parseInt(args[1]);
|
||||
if (pageNumber < 1 || pageNumber > this.helpHandler.pageNumber()) return this.replyHandler("`" + pageNumber + "` is not a valid page number!", msg);
|
||||
return this.replyHandler(this.helpHandler.getHelpPage(pageNumber - 1, msg), msg);
|
||||
}
|
||||
if (args.length <= 2) {
|
||||
let idx = this.commands.findIndex(e => e.aliases.some(al => al.toLowerCase() === args[1].toLowerCase()));
|
||||
if (idx === -1) return this.replyHandler("Unknown command `$prefix" + args[1] + "`!", msg);
|
||||
return this.replyHandler(this.helpHandler.getCommandHelp(this.commands[idx], msg), msg);
|
||||
}
|
||||
let currCmd = null;
|
||||
let prefix2 = "";
|
||||
for (let i = 0; i < args.slice(1).length; i++) {
|
||||
let a = args.slice(1)[i];
|
||||
let curr = (currCmd) ? currCmd.subcommands : this.commands;
|
||||
let idx = curr.findIndex(e => e.aliases.some(al => al.toLowerCase() === a.toLowerCase()));
|
||||
if (idx === -1) return this.replyHandler("Unknown command `$prefix" + prefix2 + a + "`!", msg);
|
||||
currCmd = curr[idx];
|
||||
prefix2 += a + " ";
|
||||
}
|
||||
return this.replyHandler(this.helpHandler.getCommandHelp(currCmd, msg), msg);
|
||||
}
|
||||
|
||||
if (!this.commandNames.includes(args[0].toLowerCase())) {
|
||||
this.replyHandler("Unknown Command. Use `$prefix$helpCmd` to view all possible commands.", msg);
|
||||
return;
|
||||
}
|
||||
return this.processCommand(this.commands.find(e => e.aliases.includes(args[0].toLowerCase())), args, msg);
|
||||
}
|
||||
|
||||
processCommand(cmd, args, msg, previous = false, external = false) {
|
||||
// Guard first — cmd could be undefined if called from an edge case
|
||||
if (!cmd) return logger.warn("[CommandHandler.processCommand] Invalid case: `cmd` falsy.");
|
||||
if (cmd.requirements.length > 0 && !external) {
|
||||
if (!this.assertRequirements(cmd, msg)) return;
|
||||
}
|
||||
if (previous === false) previous = this.format("$prefix" + cmd.name, msg.channel?.channel?.guildId);
|
||||
if (!external) this.emit("command", { command: cmd, message: msg });
|
||||
|
||||
if (cmd.subcommands.length !== 0) {
|
||||
const idx = cmd.subcommands.findIndex(el => {
|
||||
if (!args[1]) return false;
|
||||
return el.name.toLowerCase() === args[1].toLowerCase();
|
||||
});
|
||||
if (idx === -1) {
|
||||
const list = cmd.subcommands.map(s => s.name).join(" | ");
|
||||
const e = "Invalid subcommand. Try one of the following options: `$previousCmd <$cmdlist>`".replace(/\$previousCmd/gi, previous).replace(/\$cmdList/gi, list);
|
||||
return (!external) ? this.replyHandler(e, msg) : e;
|
||||
}
|
||||
return this.processCommand(cmd.subcommands[idx], args.slice(1), msg, previous + this.format(" " + cmd.subcommands[idx].name), external);
|
||||
}
|
||||
|
||||
const opts = [];
|
||||
const texts = [];
|
||||
|
||||
const collectArguments = (index, currVal, as) => {
|
||||
const lastChar = currVal.charAt(currVal.length - 1);
|
||||
if (lastChar === '"') return { args: as, index };
|
||||
const a = args[++index];
|
||||
if (!a) return null;
|
||||
as.push(a);
|
||||
return collectArguments(index, a, as);
|
||||
};
|
||||
|
||||
const options = cmd.options.slice().sort((a, b) => {
|
||||
const aText = (a.type === "text") ? 1 : 2;
|
||||
const bText = (b.type === "text") ? 1 : 2;
|
||||
return aText - bText;
|
||||
});
|
||||
|
||||
const STRING_TYPES = ["string", "text", "channel", "voiceChannel"];
|
||||
const usedOptions = [];
|
||||
let usedArgumentCount = 0;
|
||||
|
||||
for (let i = 0, argIndex = 1; i < options.length; i++) {
|
||||
if (options[i] instanceof Flag) i++;
|
||||
const o = options[i];
|
||||
if (o?.type === "text") { texts.push(o); continue; }
|
||||
if ((args[argIndex] || "").startsWith("-")) {
|
||||
const flagName = args[argIndex].slice(1);
|
||||
const op = cmd.options.find(e => e.aliases.includes(flagName));
|
||||
if (!op) {
|
||||
const error = this.invalidFlagError.replace(/\$previousCmd/gi, previous).replace(/\$invalidFlag/gi, "-" + flagName);
|
||||
return (!external) ? this.replyHandler(error, msg) : error;
|
||||
}
|
||||
previous += " " + args[argIndex];
|
||||
let value = args[++argIndex];
|
||||
if ((value || "").startsWith('"') && (STRING_TYPES.includes(op.type))) {
|
||||
const data = collectArguments(argIndex, value, [value]);
|
||||
if (!data) return this.replyHandler(this.textWrapError.replace(/\$value/gi, args.slice(argIndex).join(" ")).replace(/\$quote/gi, args[argIndex].charAt(0)), msg);
|
||||
argIndex += data.index - argIndex;
|
||||
value = data.args.join(" ").slice(1, data.args.join(" ").length - 1);
|
||||
}
|
||||
argIndex++;
|
||||
i--;
|
||||
const valid = op.validateInput(value, this.client, msg.message);
|
||||
if (!valid && (op.required || !op.empty(value))) {
|
||||
const e = op.typeError.replace(/\$previousCmd/gi, previous).replace(/\$currValue/gi, value);
|
||||
return (!external) ? this.replyHandler(e, msg) : e;
|
||||
}
|
||||
usedArgumentCount += 2;
|
||||
previous += " " + value;
|
||||
opts.push({ value: op.formatInput(value, this.client, msg.message), name: op.name, id: op.id, uid: op.uid });
|
||||
usedOptions.push(op.uid);
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!o) continue;
|
||||
if (opts.findIndex(op => op.uid === o.uid) !== -1) continue;
|
||||
let value = args[argIndex];
|
||||
if ((args[argIndex] || "").startsWith('"') && (STRING_TYPES.includes(o.type))) {
|
||||
const data = collectArguments(argIndex, args[argIndex], [args[argIndex]]);
|
||||
if (!data) return this.replyHandler(this.textWrapError.replace(/\$value/gi, args.slice(argIndex).join(" ")).replace(/\$quote/gi, args[argIndex].charAt(0)), msg);
|
||||
argIndex += data.index - argIndex;
|
||||
value = data.args.join(" ");
|
||||
value = value.slice(1, value.length - 1);
|
||||
}
|
||||
let valid = o.validateInput(value, this.client, msg.message);
|
||||
if (!valid && o.dynamicDefault) {
|
||||
value = o.dynamicDefault(this.client, msg);
|
||||
valid = o.validateInput(value, this.client, msg.message);
|
||||
}
|
||||
if (!valid && (o.required || !o.empty(value))) {
|
||||
const e = o.typeError.replace(/\$previousCmd/gi, previous).replace(/\$currValue/gi, value);
|
||||
return (!external) ? this.replyHandler(e, msg) : e;
|
||||
}
|
||||
if (o.empty(value)) value = o.defaultValue;
|
||||
opts.push({ value: o.formatInput(value, this.client, msg.message), name: o.name, id: o.id, uid: o.uid });
|
||||
usedOptions.push(o.uid);
|
||||
previous += " " + value;
|
||||
argIndex++;
|
||||
usedArgumentCount++;
|
||||
}
|
||||
|
||||
if (texts.length > 0) {
|
||||
let o = texts[0];
|
||||
let text = args.slice(usedArgumentCount + 1).join(" ");
|
||||
if (o.required && !o.validateInput(text, this.client, msg.message)) {
|
||||
let e = o.typeError.replace(/\$previousCmd/gi, previous).replace(/\$currValue/gi, text);
|
||||
return (!external) ? this.replyHandler(e, msg) : e;
|
||||
}
|
||||
const quote = (['"', "'"].includes(text.charAt(0))) ? text.charAt(0) : null;
|
||||
if (quote && text.charAt(text.length - 1) === quote) text = text.slice(1, text.length - 1);
|
||||
opts.push({ name: o.name, value: text, id: o.id, uid: o.uid });
|
||||
usedOptions.push(o.uid);
|
||||
}
|
||||
|
||||
options.filter(o => !usedOptions.includes(o.uid)).forEach(o => {
|
||||
if (!o.defaultValue) return;
|
||||
opts.push({ name: o.name, value: o.defaultValue, id: o.id, uid: o.uid });
|
||||
});
|
||||
|
||||
const commandRunData = {
|
||||
command: cmd,
|
||||
commandId: cmd.id,
|
||||
options: opts,
|
||||
message: msg,
|
||||
get: function (oName) { return this.options.find(o => o.name === oName); },
|
||||
getById: function (id) { return this.options.find(o => o.id === id); }
|
||||
};
|
||||
if (!external) this.emit("run", commandRunData);
|
||||
return commandRunData;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks requirements using fluxerjs (discord.js-like) permission API.
|
||||
*/
|
||||
assertRequirements(cmd, msg) {
|
||||
const authorId = msg.message?.author?.id;
|
||||
const isOwner = this.owners.includes(authorId);
|
||||
|
||||
for (let i = 0; i < cmd.requirements.length; i++) {
|
||||
let req = cmd.requirements[i];
|
||||
if (req.ownerOnly && !isOwner) return false;
|
||||
if (req.permissions.length > 0 && !isOwner) {
|
||||
const guild = msg.message?.guild ?? null;
|
||||
if (!guild) continue;
|
||||
|
||||
const member = guild.members.get(authorId) ?? null;
|
||||
if (member?.permissions) {
|
||||
// cached — check directly
|
||||
const missing = req.permissions.filter(p => !member.permissions.has(PermissionFlags[p] ?? p));
|
||||
if (missing.length > 0) {
|
||||
this.replyHandler(req.permissionError, msg);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// not cached — fetch async and re-run
|
||||
guild.fetchMember(authorId).then(member => {
|
||||
const missing = req.permissions.filter(p => !member.permissions.has(PermissionFlags[p] ?? p));
|
||||
if (missing.length > 0) {
|
||||
this.replyHandler(req.permissionError, msg);
|
||||
} else {
|
||||
// Re-parse args the same way messageHandler does so quoted args survive.
|
||||
const guildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
const prefix2 = this.getPrefix(guildId2);
|
||||
const rawContent = msg.message.content;
|
||||
const len2 = rawContent.startsWith(prefix2) ? prefix2.length : 0;
|
||||
const args = rawContent.slice(len2).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim());
|
||||
// Pass external=true to skip re-checking requirements and avoid
|
||||
// re-entering the fetch loop if the member is still not cached.
|
||||
this.processCommand(cmd, args, msg, false, true);
|
||||
}
|
||||
}).catch(() => this.replyHandler(req.permissionError, msg));
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
validateInput(type, i, m) { return (new Option()).validateInput(i, this.client, m, type); }
|
||||
formatInput(type, i, m) { return (new Option()).formatInput(i, this.client, m, type); }
|
||||
|
||||
addCommand(builder) {
|
||||
this.commandNames.push(...builder.aliases);
|
||||
this.commands.push(builder);
|
||||
this.commands.sort((a, b) => {
|
||||
let A = a.name.toUpperCase();
|
||||
let B = b.name.toUpperCase();
|
||||
return (A < B) ? -1 : (A > B) ? 1 : 0;
|
||||
});
|
||||
return this.commands;
|
||||
}
|
||||
}
|
||||
|
||||
export class CommandLoader {
|
||||
/** @type {CommandHandler} */
|
||||
commands;
|
||||
/** @type {Map<string, string>} */
|
||||
commandFiles = new Map();
|
||||
/** @type {Map<string, Function>} */
|
||||
runnables = new Map();
|
||||
context;
|
||||
|
||||
constructor(commands, context) {
|
||||
this.commands = commands;
|
||||
this.context = context;
|
||||
this.context.loader ??= this;
|
||||
// expose loader helpers on context so reload.js can use them
|
||||
this.context.commandFiles = this.commandFiles;
|
||||
this.context.runnables = this.runnables;
|
||||
|
||||
this.commands.on("run", (data) => {
|
||||
if (!this.runnables.has(data.command.uid)) return;
|
||||
const runFc = this.runnables.get(data.command.uid);
|
||||
try {
|
||||
const result = runFc.call(this.context, data.message, data);
|
||||
if (result && typeof result.catch === "function") {
|
||||
result.catch(e => {
|
||||
const id = Utils.uid();
|
||||
logger.error("Error running command; error id #" + id, e);
|
||||
data.message.replyEmbed("An error occurred. Error id: `#" + id + "`");
|
||||
});
|
||||
}
|
||||
} catch (e) {
|
||||
const id = Utils.uid();
|
||||
logger.error("Error running command; error id #" + id, e);
|
||||
data.message.replyEmbed("An error occurred. Error id: `#" + id + "`");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 }
|
||||
*/
|
||||
canonData(cData) {
|
||||
if (cData.command !== undefined) {
|
||||
return {
|
||||
command: cData.command,
|
||||
run: cData.run,
|
||||
exportDef: cData.exportDef ?? cData.export ?? null
|
||||
};
|
||||
}
|
||||
const d = cData.default ?? cData;
|
||||
return {
|
||||
command: d.command,
|
||||
run: d.run,
|
||||
exportDef: d.exportDef ?? d.export ?? null
|
||||
};
|
||||
}
|
||||
|
||||
loadFromDir(dir) {
|
||||
const files = fs.readdirSync(dir)
|
||||
.filter(f => !f.startsWith(".") && (f.endsWith(".js") || f.endsWith(".mjs")));
|
||||
|
||||
return Promise.all(files.map(async commandFile => {
|
||||
const file = path.join(dir, commandFile);
|
||||
|
||||
const cData = this.canonData(await import(pathToFileURL(file).href));
|
||||
|
||||
const builder = (typeof cData.command === "function")
|
||||
? cData.command.call(this.context)
|
||||
: cData.command;
|
||||
|
||||
if (!builder) return logger.warn("No builder returned. Skipping '" + commandFile + "'");
|
||||
|
||||
if (cData.exportDef)
|
||||
this.context[cData.exportDef.name] = cData.exportDef.object;
|
||||
|
||||
this.commands.addCommand(builder);
|
||||
this.commandFiles.set(builder.uid, file);
|
||||
|
||||
if (!cData.run) return;
|
||||
|
||||
this.runnables.set(builder.uid, cData.run);
|
||||
builder.subcommands.forEach(sub => {
|
||||
this.runnables.set(sub.uid, cData.run);
|
||||
});
|
||||
}));
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,284 @@
|
||||
/**
|
||||
* MoonlinkManager.mjs
|
||||
*
|
||||
* Wraps moonlink.js Manager with a custom connector for Fluxer.
|
||||
* FIXED: Correct payload format for packetUpdate
|
||||
*/
|
||||
|
||||
import { Manager } from "moonlink.js";
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { Events } from "@fluxerjs/core";
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// MoonlinkManager ──────────────────────────────────────────────────────────────
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
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); // reconnects temporarily stack listeners during re-init
|
||||
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),
|
||||
},
|
||||
});
|
||||
|
||||
// Set up voice state forwarding from Fluxer to moonlink
|
||||
this._setupVoiceForwarding(client);
|
||||
|
||||
// Forward key events
|
||||
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);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Send voice payload to Discord via Fluxer's WebSocket
|
||||
* @param {string} guildId
|
||||
* @param {{ op: number, d: object }} payload
|
||||
* @private
|
||||
*/
|
||||
_sendPayload(guildId, payload) {
|
||||
try {
|
||||
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
|
||||
* @param {import("@fluxerjs/core").Client} client
|
||||
* @private
|
||||
*/
|
||||
_setupVoiceForwarding(client) {
|
||||
// @fluxerjs/core emits VoiceStateUpdate with a SINGLE argument:
|
||||
// (data: GatewayVoiceStateUpdateDispatchData) — raw gateway snake_case fields.
|
||||
// This is NOT discord.js style (oldState, newState).
|
||||
client.on(Events.VoiceStateUpdate, (data) => {
|
||||
try {
|
||||
// data is the raw GatewayVoiceStateUpdateDispatchData — always snake_case
|
||||
const guildId = data.guild_id;
|
||||
if (!guildId) {
|
||||
logger.warn("[MoonlinkManager] voiceStateUpdate: No guild_id found in data", data);
|
||||
return;
|
||||
}
|
||||
|
||||
// Build the proper payload format that moonlink expects:
|
||||
// { op: 0, t: "VOICE_STATE_UPDATE", d: { guild_id, user_id, channel_id, ... } }
|
||||
const payload = {
|
||||
op: 0, // Dispatch
|
||||
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);
|
||||
}
|
||||
});
|
||||
|
||||
// Raw WS — only for VOICE_SERVER_UPDATE (VOICE_STATE_UPDATE is handled above via Events listener)
|
||||
// Store the handler reference so we can remove the stale listener before re-attaching
|
||||
// on gateway reconnects. Without this, each reconnect stacks another handler on the socket.
|
||||
const attachRawWs = () => {
|
||||
try {
|
||||
const shard0 = client.ws?.shards?.get?.(0);
|
||||
const wsObj = shard0?.ws ?? null;
|
||||
if (!wsObj) return;
|
||||
|
||||
// Remove previous handler if any
|
||||
if (this._rawWsHandler) {
|
||||
try {
|
||||
if (typeof wsObj.removeEventListener === "function") wsObj.removeEventListener("message", this._rawWsHandler);
|
||||
else if (typeof wsObj.off === "function") wsObj.off("message", this._rawWsHandler);
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
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 (_) {}
|
||||
};
|
||||
|
||||
if (typeof wsObj.addEventListener === "function") {
|
||||
wsObj.addEventListener("message", this._rawWsHandler);
|
||||
} else if (typeof wsObj.on === "function") {
|
||||
wsObj.on("message", this._rawWsHandler);
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[MoonlinkManager] Raw WS setup error:", e.message);
|
||||
}
|
||||
};
|
||||
|
||||
attachRawWs();
|
||||
// Re-attach after every gateway reconnect so the new socket gets the listener
|
||||
client.on(Events.Ready, attachRawWs);
|
||||
}
|
||||
|
||||
/**
|
||||
* Call after client.login() resolves and client.user.id is available.
|
||||
* Safe to call on every reconnect — removes stale internal listeners before re-init
|
||||
* to prevent the MaxListenersExceededWarning that moonlink.js triggers by adding
|
||||
* a new nodeReady/nodeConnected listener to the node socket on every init() call.
|
||||
* @param {string} clientId
|
||||
*/
|
||||
async init(clientId) {
|
||||
// Raise the limit on both this emitter and the internal manager so reconnects
|
||||
// don't spam MaxListenersExceededWarning while we're between socket teardown
|
||||
// and the re-init completing.
|
||||
this.setMaxListeners(50);
|
||||
try { this.manager.setMaxListeners?.(50); } catch (_) {}
|
||||
|
||||
// Strip any stale nodeReady listeners the previous init() call registered
|
||||
// so they don't stack up across gateway reconnects.
|
||||
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 (_) {}
|
||||
|
||||
await this.manager.init(clientId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Search for tracks. Returns a moonlink SearchResult.
|
||||
* @param {string} query
|
||||
* @param {string} [source] e.g. "ytmsearch", "spsearch"
|
||||
* @param {*} [requester]
|
||||
*/
|
||||
search(query, source, requester) {
|
||||
return this.manager.search({ query, source, requester });
|
||||
}
|
||||
|
||||
/**
|
||||
* Get or create a moonlink Player for a guild.
|
||||
* @param {{ guildId: string, voiceChannelId: string, textChannelId?: string, volume?: number }} opts
|
||||
* @returns {import("moonlink.js").Player}
|
||||
*/
|
||||
createPlayer(opts) {
|
||||
return this.manager.players.create(opts);
|
||||
}
|
||||
|
||||
/**
|
||||
* Get an existing player by guildId.
|
||||
* @param {string} guildId
|
||||
* @returns {import("moonlink.js").Player|undefined}
|
||||
*/
|
||||
getPlayer(guildId) {
|
||||
return this.manager.players.get(guildId);
|
||||
}
|
||||
|
||||
destroy() {
|
||||
try {
|
||||
for (const node of this.manager.nodes.nodes.values()) {
|
||||
node.socket?.close?.();
|
||||
}
|
||||
} catch (_) {}
|
||||
}
|
||||
}
|
||||
+1606
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,382 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
import Player from "./Player.mjs";
|
||||
import { CommandHandler } from "./CommandHandler.mjs";
|
||||
import { Message } from "./MessageHandler.mjs";
|
||||
import { SettingsManager } from "./Settings.mjs";
|
||||
import { Utils } from "./Utils.mjs";
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getGlobalColor } from "./MessageHandler.mjs";
|
||||
|
||||
/** Helper — build a plain embed payload from a description string */
|
||||
function mkEmbed(desc) {
|
||||
return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).toJSON()] };
|
||||
}
|
||||
|
||||
export class PlayerManager {
|
||||
/** @type {SettingsManager} */
|
||||
settings;
|
||||
|
||||
/** @type {CommandHandler} */
|
||||
commands;
|
||||
|
||||
/** @type {Map<string, Player>} */
|
||||
playerMap = new Map();
|
||||
|
||||
/** @type {Object} */
|
||||
config;
|
||||
|
||||
/** @type {Object} */
|
||||
playerConfig;
|
||||
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
constructor(settings, commands, config) {
|
||||
this.commands = commands;
|
||||
this.settings = settings;
|
||||
this.config = config.config;
|
||||
this.playerConfig = config.player;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Voice Channel Detection
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Attempt to detect the voice channel a user is currently in.
|
||||
* @param {Message} message
|
||||
* @returns {string|null} Voice channel ID or null
|
||||
*/
|
||||
checkVoiceChannels(message) {
|
||||
if (!message) return null;
|
||||
|
||||
const userId = message.author?.id;
|
||||
const serverId = message.channel?.server_id ??
|
||||
message.channel?.serverId ??
|
||||
message.message?.server_id ??
|
||||
message.message?.serverId;
|
||||
|
||||
if (!userId) return null;
|
||||
|
||||
// Fallback: find any existing player in this server
|
||||
if (serverId) {
|
||||
for (const [channelId] of this.playerMap) {
|
||||
const channel = this.commands.client?.channels?.get(channelId) ??
|
||||
this.commands.client?.channels?.cache?.get(channelId);
|
||||
if (channel?.guildId === serverId || channel?.server_id === serverId || channel?.serverId === serverId) {
|
||||
return channelId;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Player Retrieval
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
const serverId = message.channel?.server_id ??
|
||||
message.channel?.serverId ??
|
||||
message.message?.server_id ??
|
||||
message.message?.serverId;
|
||||
|
||||
const userChannelId = this.checkVoiceChannels(message);
|
||||
|
||||
if (userChannelId) {
|
||||
const player = this.playerMap.get(userChannelId);
|
||||
if (player) {
|
||||
player.textChannel = message.channel;
|
||||
return player;
|
||||
}
|
||||
}
|
||||
|
||||
const serverPlayers = serverId
|
||||
? [...this.playerMap.entries()].filter(([chId]) => {
|
||||
const ch = this.commands.client?.channels?.get(chId) ??
|
||||
this.commands.client?.channels?.cache?.get(chId);
|
||||
return ch?.guildId === serverId || ch?.server_id === serverId || ch?.serverId === serverId;
|
||||
})
|
||||
: [];
|
||||
|
||||
if (serverPlayers.length > 0) {
|
||||
const channelList = serverPlayers.map(([chId]) => `<#${chId}>`).join(" or ");
|
||||
|
||||
if (!userChannelId) {
|
||||
message.replyEmbed(mkEmbed(`⚠️ Please join ${channelList} to use this command.`));
|
||||
return null;
|
||||
}
|
||||
|
||||
const match = serverPlayers.find(([chId]) => chId === userChannelId);
|
||||
if (match) {
|
||||
match[1].textChannel = message.channel;
|
||||
return match[1];
|
||||
}
|
||||
|
||||
message.replyEmbed(mkEmbed(`⚠️ I'm already playing in ${channelList}. Join that channel.`));
|
||||
return null;
|
||||
}
|
||||
|
||||
if (!userChannelId) {
|
||||
message.replyEmbed(mkEmbed("⚠️ Please join a voice channel first."));
|
||||
return null;
|
||||
}
|
||||
|
||||
if (shouldJoin) {
|
||||
return new Promise((resolve) => {
|
||||
this.initPlayer(message, userChannelId, (p) => resolve(p));
|
||||
});
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Channel Selection Prompt
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Prompt the user to select a voice channel.
|
||||
* @param {Message} msg
|
||||
* @returns {Promise<string|false>}
|
||||
*/
|
||||
async promptVC(msg) {
|
||||
const autoDetected = this.checkVoiceChannels(msg);
|
||||
if (autoDetected) {
|
||||
return new Promise(resolve => this.initPlayer(msg, autoDetected, () => resolve(autoDetected)));
|
||||
}
|
||||
|
||||
const serverId = msg.channel?.server_id ?? msg.channel?.serverId;
|
||||
const allChannels = serverId
|
||||
? [...(this.commands.client?.channels?.values?.() ??
|
||||
this.commands.client?.channels?.cache?.values?.() ?? [])]
|
||||
.filter(c => {
|
||||
const cServerId = c.server_id ?? c.serverId;
|
||||
return cServerId === serverId && c.channel_type === "VoiceChannel";
|
||||
})
|
||||
: [];
|
||||
|
||||
const reactions = ["1️⃣","2️⃣","3️⃣","4️⃣","5️⃣","6️⃣","7️⃣","8️⃣","9️⃣"];
|
||||
const channelArr = allChannels.slice(0, 9);
|
||||
|
||||
let channelSelection = "";
|
||||
if (channelArr.length > 0) {
|
||||
channelSelection = "Please select one of the following channels by clicking on the reactions below\n\n";
|
||||
channelArr.forEach((c, i) => { channelSelection += `${i + 1}. <#${c._id ?? c.id}>\n`; });
|
||||
}
|
||||
|
||||
const selectionMsg = await msg.replyEmbed(mkEmbed(
|
||||
(channelSelection ? channelSelection + "\n**..or**" : "Please") +
|
||||
" send a message with the voice channel! (Mention/Id/Name)\nSend 'x' to cancel."
|
||||
));
|
||||
|
||||
return new Promise(resolve => {
|
||||
let unsubscribeReactions;
|
||||
let unsubscribeMessages;
|
||||
|
||||
const cleanup = () => {
|
||||
unsubscribeMessages?.();
|
||||
unsubscribeReactions?.();
|
||||
};
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
cleanup();
|
||||
msg.replyEmbed(mkEmbed("⏱️ Voice selection timed out."));
|
||||
resolve(false);
|
||||
}, 30_000);
|
||||
|
||||
if (typeof selectionMsg?.onReaction === "function" && channelArr.length > 0) {
|
||||
unsubscribeReactions = selectionMsg.onReaction(
|
||||
reactions.slice(0, channelArr.length),
|
||||
(e) => {
|
||||
const idx = reactions.indexOf(e.emoji_id ?? e.emoji?.id ?? e.emoji);
|
||||
const channel = channelArr[idx];
|
||||
if (!channel) return;
|
||||
clearTimeout(timeout);
|
||||
cleanup();
|
||||
const cid = channel._id ?? channel.id;
|
||||
this.initPlayer(msg, cid, () => resolve(cid));
|
||||
},
|
||||
msg.author
|
||||
);
|
||||
}
|
||||
|
||||
unsubscribeMessages = msg.channel.onMessageUser((m) => {
|
||||
const content = m.content?.toLowerCase() ?? "";
|
||||
if (content === "x") {
|
||||
clearTimeout(timeout);
|
||||
cleanup();
|
||||
m.replyEmbed(mkEmbed("Cancelled!"));
|
||||
resolve(false);
|
||||
return;
|
||||
}
|
||||
if (!this.commands.validateInput("voiceChannel", m.content, m)) {
|
||||
m.replyEmbed(mkEmbed("Invalid voice channel. Try again or type `x`."));
|
||||
return;
|
||||
}
|
||||
const channel = this.commands.formatInput("voiceChannel", m.content, m);
|
||||
clearTimeout(timeout);
|
||||
cleanup();
|
||||
this.initPlayer(m, channel, () => resolve(channel));
|
||||
}, msg.author);
|
||||
});
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Leave
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Make the player leave its current voice channel.
|
||||
* @param {Message} msg
|
||||
* @param {string} [cid]
|
||||
*/
|
||||
async leave(msg, cid) {
|
||||
if (!cid) {
|
||||
const serverId = msg.channel?.server_id ?? msg.channel?.serverId ??
|
||||
msg.message?.server_id ?? msg.message?.serverId;
|
||||
if (serverId) {
|
||||
cid = [...this.playerMap.keys()].find((id) => {
|
||||
const ch = this.commands.client?.channels?.get(id) ??
|
||||
this.commands.client?.channels?.cache?.get(id);
|
||||
return ch?.guildId === serverId || ch?.server_id === serverId || ch?.serverId === serverId;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const player = cid ? this.playerMap.get(cid) : null;
|
||||
if (!player) return msg.replyEmbed(mkEmbed("I'm not in a voice channel."));
|
||||
|
||||
this.playerMap.delete(cid);
|
||||
await msg.replyEmbed(mkEmbed("✅ Successfully Left"));
|
||||
await player.leave();
|
||||
player.destroy();
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Player Initialisation
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Create and register a new Player for the given voice channel.
|
||||
* @param {Message} message
|
||||
* @param {string} cid - Voice channel ID
|
||||
* @param {Function} [cb]
|
||||
*/
|
||||
initPlayer(message, cid, cb = () => {}) {
|
||||
const channel = this.commands.client?.channels?.get(cid) ??
|
||||
this.commands.client?.channels?.cache?.get(cid);
|
||||
|
||||
if (!channel) {
|
||||
return message.replyEmbed(mkEmbed(
|
||||
`Couldn't find the channel \`${cid}\`\nUse the help command to learn more about this.`
|
||||
));
|
||||
}
|
||||
|
||||
const isVoice = channel.channel_type === "VoiceChannel" ||
|
||||
channel.type === "VoiceChannel" ||
|
||||
channel.type === 2;
|
||||
|
||||
if (!isVoice) {
|
||||
return message.replyEmbed(mkEmbed("❌ Please join a **voice channel** first before using this command!"));
|
||||
}
|
||||
|
||||
if (this.playerMap.has(cid)) {
|
||||
const existing = this.playerMap.get(cid);
|
||||
existing.textChannel = message.channel;
|
||||
cb(existing);
|
||||
return message.replyEmbed(mkEmbed(`Already joined <#${cid}>.`));
|
||||
}
|
||||
|
||||
const player = new Player(this.config.token, {
|
||||
...this.playerConfig,
|
||||
client: this.commands.client,
|
||||
config: this.config,
|
||||
nodelink: this.config.nodelink,
|
||||
moonlink: this.playerConfig?.moonlink ?? null,
|
||||
settingsMgr: this.settings,
|
||||
observedVoiceUsers: this.observedVoiceUsers ?? null,
|
||||
});
|
||||
|
||||
player.textChannel = message.channel;
|
||||
|
||||
player.on("autoleave", () => {
|
||||
const ch = player.textChannel;
|
||||
const serverId = ch?.server_id ?? ch?.serverId ?? ch?.guild?.id;
|
||||
const is247 = (() => {
|
||||
try {
|
||||
const raw = this.settings.getServer(serverId)?.get("stay_247");
|
||||
return raw && raw !== "none";
|
||||
} catch (_) { return false; }
|
||||
})();
|
||||
const prefix = (() => {
|
||||
try {
|
||||
return this.settings.getServer(serverId)?.get("prefix") ?? "%";
|
||||
} catch (_) { return "%"; }
|
||||
})();
|
||||
const desc = is247
|
||||
? `Left channel <#${cid}> because of inactivity.`
|
||||
: `Left channel <#${cid}> because of inactivity.\nIf you want me to stay in voice, use \`${prefix}247 on/auto\``;
|
||||
ch?.sendEmbed(mkEmbed(desc));
|
||||
this.playerMap.delete(cid);
|
||||
player.destroy();
|
||||
});
|
||||
|
||||
player.on("leave", () => {});
|
||||
|
||||
player.on("message", (m) => {
|
||||
const ch = player.textChannel;
|
||||
const serverId = ch?.server_id ?? ch?.serverId ?? ch?.guild?.id;
|
||||
const raw = this.settings.getServer(serverId)?.get("songAnnouncements");
|
||||
const disabled = raw === false || raw === 0 ||
|
||||
["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim());
|
||||
if (disabled) return;
|
||||
ch?.sendEmbed(typeof m === "object" && Array.isArray(m.embeds) ? m : mkEmbed(m));
|
||||
});
|
||||
|
||||
this.playerMap.set(cid, player);
|
||||
|
||||
(async () => {
|
||||
const statusMsg = await message.replyEmbed(mkEmbed("⏳ Joining Channel..."));
|
||||
try {
|
||||
await player.join(cid);
|
||||
await statusMsg.editEmbed(mkEmbed(`✅ Successfully joined <#${cid}>`));
|
||||
|
||||
const serverId = message.channel?.server_id ?? message.channel?.serverId;
|
||||
if (serverId) {
|
||||
const savedVol = this.settings.getServer(serverId)?.get("volume");
|
||||
if (savedVol !== undefined && savedVol !== null) {
|
||||
const vol = Number(savedVol);
|
||||
if (!isNaN(vol)) player.setVolume(vol / 100);
|
||||
}
|
||||
}
|
||||
|
||||
cb(player);
|
||||
} catch (err) {
|
||||
await statusMsg.editEmbed(mkEmbed(`❌ Failed to join: ${err.message}`)).catch(() => {});
|
||||
this.playerMap.delete(cid);
|
||||
player.destroy();
|
||||
}
|
||||
})();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,199 @@
|
||||
import fs from "node:fs";
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
import mysql from "mysql";
|
||||
import { EventEmitter } from "node:events";
|
||||
|
||||
export class ServerSettings {
|
||||
id;
|
||||
manager;
|
||||
data = {};
|
||||
|
||||
constructor(id, mgr) {
|
||||
this.id = id;
|
||||
this.manager = mgr;
|
||||
this.loadDefaults();
|
||||
}
|
||||
set(key, value) { this.data[key] = value; this.manager.update(this, key); }
|
||||
get(key) { return this.data[key]; }
|
||||
reset(key) { return this.set(key, this.manager.defaults[key]); }
|
||||
getAll() { return this.data; }
|
||||
loadDefaults() { for (let key in this.manager.defaults) { this.data[key] = this.manager.defaults[key]; } }
|
||||
deserialize(json) { for (let k in json) { if (k === "id") continue; this.data[k] = json[k]; } }
|
||||
|
||||
// was `if (!this.data[key])` which clobbered valid falsy values like 0, false, ""
|
||||
checkDefaults(d) { for (let key in d) { if (this.data[key] === undefined) this.data[key] = d[key]; } }
|
||||
|
||||
get serializationData() { return { ...this.data, id: this.id }; }
|
||||
serialize() { return this.serializationData; }
|
||||
serializeObject() { return this.serializationData; }
|
||||
}
|
||||
|
||||
/** @deprecated Use RemoteSettingsManager instead */
|
||||
export class SettingsManager {
|
||||
guilds = new Map();
|
||||
storagePath = "./storage/settings.json";
|
||||
defaults = {};
|
||||
descriptions = {};
|
||||
|
||||
constructor(storagePath = null) {
|
||||
if (storagePath) this.storagePath = storagePath;
|
||||
this.load();
|
||||
}
|
||||
loadDefaultsSync(filePath) {
|
||||
const d = fs.readFileSync(filePath, "utf8");
|
||||
const parsed = JSON.parse(d);
|
||||
this.descriptions = parsed.descriptions;
|
||||
this.defaults = parsed.values;
|
||||
}
|
||||
load() {
|
||||
if (!fs.existsSync(this.storagePath)) {
|
||||
fs.writeFileSync(this.storagePath, JSON.stringify({ guilds: [] }));
|
||||
}
|
||||
const json = JSON.parse(fs.readFileSync(this.storagePath, "utf8"));
|
||||
const entries = json.guilds || json.servers || [];
|
||||
entries.forEach((s) => {
|
||||
const server = new ServerSettings(s.id, this);
|
||||
server.deserialize(s);
|
||||
server.checkDefaults(this.defaults);
|
||||
this.guilds.set(s.id, server);
|
||||
});
|
||||
}
|
||||
save() {
|
||||
const s = [];
|
||||
this.guilds.forEach((val) => { s.push(val.serialize()); });
|
||||
fs.writeFileSync(this.storagePath, JSON.stringify({ guilds: s }));
|
||||
}
|
||||
saveAsync() {
|
||||
return new Promise((res) => {
|
||||
const s = [];
|
||||
this.guilds.forEach((val) => { s.push(val.serializeObject()); });
|
||||
fs.writeFile(this.storagePath, JSON.stringify({ guilds: s }), () => { res(); });
|
||||
});
|
||||
}
|
||||
update(server, key) {
|
||||
if (!this.guilds.has(server.id)) this.guilds.set(server.id, server);
|
||||
const s = this.guilds.get(server.id);
|
||||
s.data[key] = server.data[key];
|
||||
}
|
||||
isOption(key) { return key in this.defaults; }
|
||||
hasServer(id) { return this.guilds.has(id); }
|
||||
getServer(id) {
|
||||
if (this.guilds.has(id)) return this.guilds.get(id);
|
||||
// Create AND store so any .set() calls on the returned object are persisted.
|
||||
// Previously this returned a detached instance, causing settings writes to silently disappear.
|
||||
const server = new ServerSettings(id, this);
|
||||
server.checkDefaults(this.defaults);
|
||||
this.guilds.set(id, server);
|
||||
return server;
|
||||
}
|
||||
}
|
||||
|
||||
export class RemoteSettingsManager extends EventEmitter {
|
||||
guilds = new Map();
|
||||
descriptions = {};
|
||||
defaults = {};
|
||||
db = null;
|
||||
|
||||
// track retry count and apply exponential backoff on load failures
|
||||
_loadAttempts = 0;
|
||||
|
||||
constructor(config, defaultsPath) {
|
||||
super();
|
||||
this.db = mysql.createPool({ connectionLimit: 15, ...config });
|
||||
if (defaultsPath) this.loadDefaultsSync(defaultsPath);
|
||||
this.load();
|
||||
}
|
||||
|
||||
query(q) {
|
||||
return new Promise(res => {
|
||||
this.db.query(q, (error, results, fields) => { res({ error, results, fields }); });
|
||||
});
|
||||
}
|
||||
|
||||
async load() {
|
||||
const res = await this.query("SELECT * FROM settings");
|
||||
if (res.error) {
|
||||
this._loadAttempts++;
|
||||
// exponential backoff with a cap of 30s instead of forever-at-2s
|
||||
const delay = Math.min(1000 * Math.pow(2, this._loadAttempts - 1), 30_000);
|
||||
logger.error("[Settings] Init error (attempt", this._loadAttempts, "retrying in", delay + "ms):", res.error);
|
||||
return setTimeout(() => { this.load(); }, delay);
|
||||
}
|
||||
this._loadAttempts = 0;
|
||||
res.results.forEach((r) => {
|
||||
const server = new ServerSettings(r.id, this);
|
||||
server.deserialize(JSON.parse(r.data));
|
||||
server.checkDefaults(this.defaults);
|
||||
this.guilds.set(server.id, server);
|
||||
});
|
||||
this.emit("ready");
|
||||
}
|
||||
|
||||
async remoteUpdate(server, key) {
|
||||
const val = server.data[key];
|
||||
// Arrays/objects must go through remoteSave — JSON_SET with scalar
|
||||
// interpolation corrupts arrays by merging IDs into one number on read-back.
|
||||
if (Array.isArray(val) || (typeof val === "object" && val !== null)) {
|
||||
return this.remoteSave(server);
|
||||
}
|
||||
// Use mysql.escape() for every user-supplied value to prevent SQL injection.
|
||||
const escapedPath = mysql.escape(`$.${key}`);
|
||||
const escapedVal = 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}`);
|
||||
if (r.error) logger.error("[Settings] remoteUpdate error:", r.error);
|
||||
}
|
||||
|
||||
async remoteSave(server) {
|
||||
const escapedData = mysql.escape(JSON.stringify(server.data));
|
||||
const escapedId = mysql.escape(server.id);
|
||||
const r = await this.query(`UPDATE settings SET data = ${escapedData} WHERE id=${escapedId}`);
|
||||
if (r.error) logger.error("[Settings] remoteSave error:", r.error);
|
||||
}
|
||||
|
||||
loadDefaultsSync(filePath) {
|
||||
const d = fs.readFileSync(filePath, "utf8");
|
||||
const parsed = JSON.parse(d);
|
||||
this.descriptions = parsed.descriptions;
|
||||
this.defaults = parsed.values;
|
||||
}
|
||||
|
||||
async saveAsync() {
|
||||
await Promise.allSettled([...this.guilds.values()].map(v => this.remoteSave(v)));
|
||||
}
|
||||
|
||||
async create(id, server) {
|
||||
const escapedId = mysql.escape(id);
|
||||
const escapedData = mysql.escape(JSON.stringify(server.data));
|
||||
const r = await this.query(`INSERT INTO settings (id, data) VALUES (${escapedId}, ${escapedData})`);
|
||||
if (r.error) logger.error("[Settings] create error:", r.error);
|
||||
}
|
||||
|
||||
update(server, key) {
|
||||
if (!this.guilds.has(server.id)) { this.guilds.set(server.id, server); this.create(server.id, server); }
|
||||
const s = this.guilds.get(server.id);
|
||||
s.data[key] = server.data[key];
|
||||
this.remoteUpdate(server, key);
|
||||
}
|
||||
|
||||
isOption(key) { return key in this.defaults; }
|
||||
hasServer(id) { return this.guilds.has(id); }
|
||||
|
||||
getServer(id) {
|
||||
if (!this.guilds.has(id)) {
|
||||
// Return a fresh object but don't register it yet;
|
||||
// update() will call create() on the first real write.
|
||||
return new ServerSettings(id, this);
|
||||
}
|
||||
return this.guilds.get(id);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop a server from the in-memory cache without touching the DB row.
|
||||
* This lets settings be restored automatically if the bot is re-invited.
|
||||
* @param {string} id - Guild / server ID
|
||||
*/
|
||||
removeServer(id) {
|
||||
this.guilds.delete(id);
|
||||
}
|
||||
}
|
||||
+511
@@ -0,0 +1,511 @@
|
||||
/**
|
||||
* Utils.mjs — Utility functions for the music bot
|
||||
* @module Utils
|
||||
*/
|
||||
|
||||
/**
|
||||
* @class Utils
|
||||
* @description Static utility methods for time formatting, array manipulation,
|
||||
* string processing, and validation used across the music bot.
|
||||
*/
|
||||
export class Utils {
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
// Time & Duration
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Format milliseconds to human-readable time string (H:MM:SS or M:SS)
|
||||
* @param {number} milliseconds - Duration in milliseconds
|
||||
* @returns {string} Formatted time string
|
||||
* @example Utils.prettifyMS(125000) // "2:05"
|
||||
* @example Utils.prettifyMS(3661000) // "1:01:01"
|
||||
*/
|
||||
static prettifyMS(milliseconds) {
|
||||
if (!milliseconds || milliseconds < 0 || !isFinite(milliseconds)) {
|
||||
return "0:00";
|
||||
}
|
||||
|
||||
const totalSeconds = Math.floor(milliseconds / 1000);
|
||||
const hours = Math.floor(totalSeconds / 3600);
|
||||
const minutes = Math.floor((totalSeconds % 3600) / 60);
|
||||
const seconds = totalSeconds % 60;
|
||||
|
||||
const pad = (n) => String(n).padStart(2, "0");
|
||||
|
||||
return hours > 0
|
||||
? `${hours}:${pad(minutes)}:${pad(seconds)}`
|
||||
: `${minutes}:${pad(seconds)}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse duration string (H:MM:SS or M:SS) to milliseconds
|
||||
* @param {string} str - Duration string
|
||||
* @returns {number} Milliseconds, 0 if invalid
|
||||
*/
|
||||
static parseDuration(str) {
|
||||
if (!str || typeof str !== "string") return 0;
|
||||
|
||||
const parts = str.split(":").map((s) => parseInt(s.trim(), 10)).reverse();
|
||||
if (parts.some(isNaN) || parts.some(n => n < 0)) return 0;
|
||||
|
||||
let ms = 0;
|
||||
if (parts[0] !== undefined) ms += parts[0] * 1000; // seconds
|
||||
if (parts[1] !== undefined) ms += parts[1] * 60 * 1000; // minutes
|
||||
if (parts[2] !== undefined) ms += parts[2] * 3600 * 1000; // hours
|
||||
|
||||
return ms;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format seconds to MM:SS (for NodeLink duration compatibility)
|
||||
* @param {number} seconds - Duration in seconds
|
||||
* @returns {string} Formatted time
|
||||
*/
|
||||
static formatSeconds(seconds) {
|
||||
if (!seconds || seconds < 0 || !isFinite(seconds)) return "0:00";
|
||||
return this.prettifyMS(seconds * 1000);
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
// Array Manipulation
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Shuffles array in-place using Fisher-Yates algorithm
|
||||
* @template T
|
||||
* @param {T[]} array - Array to shuffle
|
||||
* @returns {T[]} Same array reference (shuffled)
|
||||
*/
|
||||
static shuffleArr(array) {
|
||||
if (!Array.isArray(array) || array.length < 2) return array;
|
||||
|
||||
for (let i = array.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
[array[i], array[j]] = [array[j], array[i]];
|
||||
}
|
||||
return array;
|
||||
}
|
||||
|
||||
/**
|
||||
* Get random element from array
|
||||
* @template T
|
||||
* @param {T[]} array - Source array
|
||||
* @returns {T | undefined} Random element or undefined if empty
|
||||
*/
|
||||
static randomElement(array) {
|
||||
if (!Array.isArray(array) || array.length === 0) return undefined;
|
||||
return array[Math.floor(Math.random() * array.length)];
|
||||
}
|
||||
|
||||
/**
|
||||
* Chunk array into smaller arrays
|
||||
* @template T
|
||||
* @param {T[]} array - Array to chunk
|
||||
* @param {number} size - Chunk size (minimum 1)
|
||||
* @returns {T[][]} Array of chunks
|
||||
*/
|
||||
static chunk(array, size) {
|
||||
if (!Array.isArray(array) || size < 1) return [];
|
||||
const chunks = [];
|
||||
for (let i = 0; i < array.length; i += size) {
|
||||
chunks.push(array.slice(i, i + size));
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove duplicates from array (primitive values only)
|
||||
* @template T
|
||||
* @param {T[]} array - Array with potential duplicates
|
||||
* @returns {T[]} New array without duplicates
|
||||
*/
|
||||
static unique(array) {
|
||||
if (!Array.isArray(array)) return [];
|
||||
return [...new Set(array)];
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
// String Formatting
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
static truncate(str, maxLen = 100, suffix = "...") {
|
||||
if (!str || typeof str !== "string") return "";
|
||||
if (str.length <= maxLen) return str;
|
||||
if (maxLen <= suffix.length) return str.substring(0, maxLen);
|
||||
return str.substring(0, maxLen - suffix.length) + suffix;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
static cleanTitle(title) {
|
||||
if (!title || typeof title !== "string") return "Unknown";
|
||||
|
||||
return title
|
||||
.replace(/\s*[\(\[][^\)\]]*(?:feat|ft|featuring|remix|edit|version|prod|official|audio|video|lyrics|visualizer)[^\)\]]*[\)\]]/gi, "")
|
||||
.replace(/\s*-\s*(?:feat|ft|featuring)\.?.*/gi, "")
|
||||
.replace(/\s*\|.*$/g, "") // Remove pipe and everything after
|
||||
.replace(/\s*【.*?】/g, "") // Remove Japanese brackets
|
||||
.replace(/\s*\[.*?\]/g, "") // Remove square brackets
|
||||
.replace(/\s*\(.*?\)/g, "") // Remove parentheses
|
||||
.replace(/\s{2,}/g, " ") // Collapse multiple spaces
|
||||
.trim();
|
||||
}
|
||||
|
||||
/**
|
||||
* Sanitize string for safe filename
|
||||
* @param {string} str - Input string
|
||||
* @param {number} [maxLen=50] - Maximum length
|
||||
* @returns {string} Safe filename
|
||||
*/
|
||||
static sanitizeFilename(str, maxLen = 50) {
|
||||
if (!str || typeof str !== "string") return "unknown";
|
||||
return str
|
||||
.replace(/[^a-z0-9\u4e00-\u9fa5]/gi, "_") // Keep CJK chars too
|
||||
.replace(/_{2,}/g, "_")
|
||||
.substring(0, maxLen)
|
||||
.replace(/^_+|_+$/g, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape markdown characters for Discord
|
||||
* @param {string} text - Raw text
|
||||
* @returns {string} Escaped text
|
||||
*/
|
||||
static escapeMarkdown(text) {
|
||||
if (!text || typeof text !== "string") return "";
|
||||
return text
|
||||
.replace(/\\/g, "\\\\")
|
||||
.replace(/`/g, "\\`")
|
||||
.replace(/\*/g, "\\*")
|
||||
.replace(/_/g, "\\_")
|
||||
.replace(/~/g, "\\~")
|
||||
.replace(/\|/g, "\\|");
|
||||
}
|
||||
|
||||
/**
|
||||
* Format number with commas (e.g., 1,000,000)
|
||||
* @param {number} num - Number to format
|
||||
* @returns {string} Formatted number
|
||||
*/
|
||||
static formatNumber(num) {
|
||||
if (num === null || num === undefined || isNaN(num)) return "0";
|
||||
return num.toLocaleString();
|
||||
}
|
||||
|
||||
/**
|
||||
* Format bytes to human readable (KB, MB, GB)
|
||||
* @param {number} bytes - Bytes to format
|
||||
* @param {number} [decimals=2] - Decimal places
|
||||
* @returns {string} Human readable size
|
||||
*/
|
||||
static formatBytes(bytes, decimals = 2) {
|
||||
if (!bytes || bytes === 0) return "0 Bytes";
|
||||
if (bytes < 0) return "Unknown";
|
||||
|
||||
const k = 1024;
|
||||
const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB"];
|
||||
const i = Math.min(Math.floor(Math.log(bytes) / Math.log(k)), sizes.length - 1);
|
||||
|
||||
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${sizes[i]}`;
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
// ID Generation
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Generate random unique ID
|
||||
* @param {number} [length=16] - Desired length of ID (8-32 recommended)
|
||||
* @returns {string} Random ID
|
||||
*/
|
||||
static uid(length = 16) {
|
||||
const targetLen = Math.max(8, Math.min(length, 32));
|
||||
|
||||
const timestamp = Date.now().toString(36).toUpperCase();
|
||||
let random = "";
|
||||
|
||||
// Generate enough random data
|
||||
while ((timestamp + random).length < targetLen) {
|
||||
random += Math.random().toString(36).substring(2).toUpperCase();
|
||||
}
|
||||
|
||||
return (timestamp + random).substring(0, targetLen);
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate UUID v4 (RFC4122 compliant)
|
||||
* @returns {string} UUID string
|
||||
*/
|
||||
static uuid() {
|
||||
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
|
||||
const r = (Math.random() * 16) | 0;
|
||||
const v = c === "x" ? r : (r & 0x3) | 0x8;
|
||||
return v.toString(16);
|
||||
});
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
// Validation & Safety (CRITICAL for worker.mjs compatibility)
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Check if a string represents a finite number
|
||||
* @param {string} str
|
||||
* @returns {boolean}
|
||||
*/
|
||||
static isNumber(str) {
|
||||
if (str === null || str === undefined || str === "") return false;
|
||||
return !isNaN(str) && isFinite(str);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
static isValidUrl(str) {
|
||||
if (!str || typeof str !== "string") return false;
|
||||
try {
|
||||
new URL(str);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
static clamp(num, min, max) {
|
||||
if (isNaN(num)) return min;
|
||||
return Math.max(min, Math.min(max, num));
|
||||
}
|
||||
|
||||
/**
|
||||
* Safe JSON parse with fallback
|
||||
* @template T
|
||||
* @param {string} str - JSON string
|
||||
* @param {T} [fallback=null] - Fallback value on error
|
||||
* @returns {T | null} Parsed object or fallback
|
||||
*/
|
||||
static safeJsonParse(str, fallback = null) {
|
||||
if (!str || typeof str !== "string") return fallback;
|
||||
try {
|
||||
return JSON.parse(str);
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
// Async Utilities
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Sleep/delay promise
|
||||
* @param {number} ms - Milliseconds to sleep
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
static sleep(ms) {
|
||||
return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Retry an async operation with exponential backoff
|
||||
* @template T
|
||||
* @param {() => Promise<T>} fn - Function to retry
|
||||
* @param {number} [attempts=3] - Max retry attempts
|
||||
* @param {number} [delay=1000] - Initial delay in ms
|
||||
* @param {number} [backoff=2] - Backoff multiplier
|
||||
* @returns {Promise<T>}
|
||||
*/
|
||||
static async retry(fn, attempts = 3, delay = 1000, backoff = 2) {
|
||||
if (typeof fn !== "function") {
|
||||
throw new TypeError("First argument must be a function");
|
||||
}
|
||||
|
||||
let lastError;
|
||||
for (let i = 0; i < attempts; i++) {
|
||||
try {
|
||||
return await fn();
|
||||
} catch (err) {
|
||||
lastError = err;
|
||||
if (i < attempts - 1) {
|
||||
await this.sleep(delay * Math.pow(backoff, i));
|
||||
}
|
||||
}
|
||||
}
|
||||
throw lastError;
|
||||
}
|
||||
|
||||
/**
|
||||
* Timeout wrapper for promises
|
||||
* @template T
|
||||
* @param {Promise<T>} promise - Promise to wrap
|
||||
* @param {number} ms - Timeout in milliseconds
|
||||
* @param {string} [message="Operation timed out"] - Error message
|
||||
* @returns {Promise<T>}
|
||||
*/
|
||||
static timeout(promise, ms, message = "Operation timed out") {
|
||||
const timeoutPromise = new Promise((_, reject) => {
|
||||
setTimeout(() => reject(new Error(message)), ms);
|
||||
});
|
||||
return Promise.race([promise, timeoutPromise]);
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
// Object Utilities
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Deep clone an object (JSON method - not suitable for circular refs)
|
||||
* @template T
|
||||
* @param {T} obj - Object to clone
|
||||
* @returns {T} Cloned object
|
||||
*/
|
||||
static deepClone(obj) {
|
||||
if (obj === null || typeof obj !== "object") return obj;
|
||||
try {
|
||||
return JSON.parse(JSON.stringify(obj));
|
||||
} catch {
|
||||
return obj;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Pick specific keys from object
|
||||
* @template T, K
|
||||
* @param {T} obj - Source object
|
||||
* @param {K[]} keys - Keys to pick
|
||||
* @returns {Pick<T, K>} New object with picked keys
|
||||
*/
|
||||
static pick(obj, keys) {
|
||||
if (!obj || typeof obj !== "object") return {};
|
||||
const result = {};
|
||||
for (const key of keys) {
|
||||
if (key in obj) result[key] = obj[key];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Omit specific keys from object
|
||||
* @template T, K
|
||||
* @param {T} obj - Source object
|
||||
* @param {K[]} keys - Keys to omit
|
||||
* @returns {Omit<T, K>} New object without omitted keys
|
||||
*/
|
||||
static omit(obj, keys) {
|
||||
if (!obj || typeof obj !== "object") return {};
|
||||
const result = { ...obj };
|
||||
for (const key of keys) {
|
||||
delete result[key];
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
// Music-Specific Helpers
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* 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
|
||||
*/
|
||||
static progressBar(
|
||||
current,
|
||||
total,
|
||||
length = 15,
|
||||
filledChar = "▬",
|
||||
emptyChar = "▬",
|
||||
indicator = "🔘"
|
||||
) {
|
||||
let progress;
|
||||
if (total !== undefined && total > 0) {
|
||||
progress = this.clamp(current / total, 0, 1);
|
||||
} else {
|
||||
progress = this.clamp(current, 0, 1);
|
||||
}
|
||||
|
||||
const position = Math.floor(progress * length);
|
||||
let bar = "";
|
||||
|
||||
for (let i = 0; i < length; i++) {
|
||||
if (i === position) {
|
||||
bar += indicator;
|
||||
} else if (i < position) {
|
||||
bar += filledChar;
|
||||
} else {
|
||||
bar += emptyChar;
|
||||
}
|
||||
}
|
||||
|
||||
return bar;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format track info for display
|
||||
* @param {object} track - Track object
|
||||
* @param {boolean} [includeDuration=true] - Include duration
|
||||
* @returns {string} Formatted string
|
||||
*/
|
||||
static formatTrackInfo(track, includeDuration = true) {
|
||||
if (!track) return "Unknown Track";
|
||||
|
||||
const title = this.cleanTitle(track.title || "Unknown");
|
||||
const author = track.author?.name || track.author || "Unknown Artist";
|
||||
|
||||
if (includeDuration && track.duration) {
|
||||
const duration = typeof track.duration === "number"
|
||||
? this.prettifyMS(track.duration)
|
||||
: track.duration.timestamp || track.duration.seconds
|
||||
? this.formatSeconds(track.duration.seconds)
|
||||
: "?:??";
|
||||
return `${title} - ${author} [${duration}]`;
|
||||
}
|
||||
|
||||
return `${title} - ${author}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse YouTube-like ISO duration (PT4M13S) to milliseconds
|
||||
* @param {string} isoDuration - ISO 8601 duration
|
||||
* @returns {number} Milliseconds
|
||||
*/
|
||||
static parseISODuration(isoDuration) {
|
||||
if (!isoDuration || typeof isoDuration !== "string") return 0;
|
||||
|
||||
const match = isoDuration.match(
|
||||
/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?/
|
||||
);
|
||||
if (!match) return 0;
|
||||
|
||||
const hours = parseInt(match[1] || 0, 10);
|
||||
const minutes = parseInt(match[2] || 0, 10);
|
||||
const seconds = parseFloat(match[3] || 0);
|
||||
|
||||
return (hours * 3600 + minutes * 60 + seconds) * 1000;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Logger — configurable console output for Fluxer.
|
||||
*
|
||||
* Categories (all under config.logging):
|
||||
* enabled — master switch; false silences everything except errors
|
||||
* player — voice connect/disconnect, stream start, volume restore
|
||||
* inactivity — alone-check, inactivity timer, human detection
|
||||
* voice247 — 24/7 rejoin, auto-save channel, intentional leave skip
|
||||
* voiceState — raw VOICE_STATE_UPDATE events (human join/leave detection)
|
||||
* 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
|
||||
* errors — always on; console.error calls (cannot be disabled)
|
||||
*/
|
||||
|
||||
let _config = null;
|
||||
|
||||
/**
|
||||
* Call once at startup with the loaded config object.
|
||||
* @param {object} config
|
||||
*/
|
||||
export function initLogger(config) {
|
||||
_config = config?.logging ?? {};
|
||||
}
|
||||
|
||||
function isEnabled(category) {
|
||||
if (!_config) return true; // default on if not yet initialised
|
||||
if (_config.enabled === false) return false;
|
||||
// If the category key is missing, default to true
|
||||
return _config[category] !== false;
|
||||
}
|
||||
|
||||
function ts() {
|
||||
return new Date().toISOString().replace("T", " ").slice(0, 19);
|
||||
}
|
||||
|
||||
export const logger = {
|
||||
// ── always-on (errors / warnings critical to operation) ──────────────────
|
||||
error(tag, ...args) {
|
||||
console.error(`[${ts()}] ${tag}`, ...args);
|
||||
},
|
||||
warn(tag, ...args) {
|
||||
// warnings are on unless master switch is off
|
||||
if (_config?.enabled === false) return;
|
||||
console.warn(`[${ts()}] ${tag}`, ...args);
|
||||
},
|
||||
|
||||
// ── categorised logs ─────────────────────────────────────────────────────
|
||||
player(...args) { if (isEnabled("player")) console.log(`[${ts()}]`, ...args); },
|
||||
inactivity(...args) { if (isEnabled("inactivity")) console.log(`[${ts()}]`, ...args); },
|
||||
voice247(...args) { if (isEnabled("voice247")) console.log(`[${ts()}]`, ...args); },
|
||||
voiceState(...args) { if (isEnabled("voiceState")) console.log(`[${ts()}]`, ...args); },
|
||||
mediaplayer(...args) { if (isEnabled("mediaplayer")) console.log(`[${ts()}]`, ...args); },
|
||||
commands(...args) { if (isEnabled("commands")) console.log(`[${ts()}]`, ...args); },
|
||||
guild(...args) { if (isEnabled("guild")) console.log(`[${ts()}]`, ...args); },
|
||||
recovery(...args) { if (isEnabled("recovery")) console.log(`[${ts()}]`, ...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); },
|
||||
aloneCheck(...args) { if (isEnabled("inactivity")) console.log(`[${ts()}]`, ...args); },
|
||||
};
|
||||
@@ -0,0 +1,77 @@
|
||||
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 = [];
|
||||
|
||||
constructor(streamOptions) {
|
||||
super(streamOptions);
|
||||
}
|
||||
_transform(chunk, _enc, cb) {
|
||||
if (!this.ffmpeg) { 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".split(" ");
|
||||
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 "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()); });
|
||||
p.stdio[4].write(Buffer.alloc(1024, 0));
|
||||
p.stdout.pipe(open.process.stdio[open.pipes[0]]);
|
||||
const pipeNumber = open.pipes[0].valueOf();
|
||||
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) throw "Impossible case detected. Damaged node structure.";
|
||||
open.children.splice(idx, 1);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default StreamMerger;
|
||||
@@ -0,0 +1,57 @@
|
||||
import { https } from "follow-redirects";
|
||||
|
||||
class Tuna {
|
||||
apiKey = null;
|
||||
constructor(auth) {
|
||||
this.apiKey = auth.key;
|
||||
}
|
||||
get(path, params = {}) {
|
||||
return new Promise((resolve, rej) => {
|
||||
var query = "";
|
||||
for (let key in params) {
|
||||
query += ((query.length === 0) ? "?" : "&") + key + "=" + encodeURIComponent(params[key]);
|
||||
}
|
||||
var options = {
|
||||
method: "GET",
|
||||
hostname: "tuna-api.voicemod.net",
|
||||
path: path + query,
|
||||
headers: { "x-api-key": this.apiKey },
|
||||
maxRedirects: 20
|
||||
};
|
||||
var req = https.request(options, function(res) {
|
||||
var chunks = [];
|
||||
res.on("data", (chunk) => { chunks.push(chunk); });
|
||||
res.on("end", () => { resolve(JSON.parse(Buffer.concat(chunks).toString())); });
|
||||
res.on("error", (error) => { rej(error); });
|
||||
});
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
search(query, page = 1, size = 10) {
|
||||
return new Promise(async res => {
|
||||
const results = await this.get("/v1/sounds/search", { size, page, search: query });
|
||||
results.items = results.items.map(s => {
|
||||
s.download = function() {
|
||||
return new Promise(resolve => {
|
||||
https.get(this.oggPath, (r) => { resolve(r); });
|
||||
});
|
||||
};
|
||||
return s;
|
||||
});
|
||||
res(results);
|
||||
});
|
||||
}
|
||||
getSound(id) {
|
||||
return new Promise(async res => {
|
||||
const sound = await this.get("/v1/sounds/" + id);
|
||||
sound.download = function() {
|
||||
return new Promise(res => {
|
||||
https.get(this.oggPath, (result) => { res(result); });
|
||||
});
|
||||
};
|
||||
res(sound);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export default Tuna;
|
||||
@@ -0,0 +1,103 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
export const PROVIDERS = {
|
||||
// ── Standard search ──────────────────────────────────────────────────────
|
||||
yt: { prefix: "ytsearch", label: "YouTube" },
|
||||
ytm: { prefix: "ytmsearch", label: "YouTube Music" },
|
||||
scld: { prefix: "scsearch", label: "SoundCloud" },
|
||||
sc: { prefix: "scsearch", label: "SoundCloud" },
|
||||
sp: { prefix: "spsearch", label: "Spotify" },
|
||||
spotify: { prefix: "spsearch", label: "Spotify" },
|
||||
am: { prefix: "amsearch", label: "Apple Music" },
|
||||
apple: { prefix: "amsearch", label: "Apple Music" },
|
||||
dz: { prefix: "dzsearch", label: "Deezer" },
|
||||
deezer: { prefix: "dzsearch", label: "Deezer" },
|
||||
td: { prefix: "tdsearch", label: "Tidal" },
|
||||
tidal: { prefix: "tdsearch", label: "Tidal" },
|
||||
bc: { prefix: "bcsearch", label: "Bandcamp" },
|
||||
bandcamp: { prefix: "bcsearch", label: "Bandcamp" },
|
||||
adm: { prefix: "admsearch", label: "Audiomack" },
|
||||
audiomack: { prefix: "admsearch", label: "Audiomack" },
|
||||
gaana: { prefix: "gaanasearch", label: "Gaana" },
|
||||
js: { prefix: "jssearch", label: "JioSaavn" },
|
||||
jiosaavn: { prefix: "jssearch", label: "JioSaavn" },
|
||||
lf: { prefix: "lfsearch", label: "Last.fm" },
|
||||
lastfm: { prefix: "lfsearch", label: "Last.fm" },
|
||||
pd: { prefix: "pdsearch", label: "Pandora" },
|
||||
pandora: { prefix: "pdsearch", label: "Pandora" },
|
||||
vk: { prefix: "vksearch", label: "VK Music" },
|
||||
mc: { prefix: "mcsearch", label: "Mixcloud" },
|
||||
mixcloud: { prefix: "mcsearch", label: "Mixcloud" },
|
||||
nc: { prefix: "ncsearch", label: "NicoVideo" },
|
||||
nicovideo: { prefix: "ncsearch", label: "NicoVideo" },
|
||||
bb: { prefix: "bilibili", label: "Bilibili" },
|
||||
bilibili: { prefix: "bilibili", label: "Bilibili" },
|
||||
sh: { prefix: "shsearch", label: "Shazam" },
|
||||
shazam: { prefix: "shsearch", label: "Shazam" },
|
||||
sl: { prefix: "slsearch", label: "Songlink" },
|
||||
songlink: { prefix: "slsearch", label: "Songlink" },
|
||||
qb: { prefix: "qbsearch", label: "Qobuz" },
|
||||
qobuz: { prefix: "qbsearch", label: "Qobuz" },
|
||||
ym: { prefix: "ymsearch", label: "Yandex Music" },
|
||||
yandex: { prefix: "ymsearch", label: "Yandex Music" },
|
||||
au: { prefix: "ausearch", label: "Audius" },
|
||||
audius: { prefix: "ausearch", label: "Audius" },
|
||||
az: { prefix: "azsearch", label: "Amazon Music" },
|
||||
amazon: { prefix: "azsearch", label: "Amazon Music" },
|
||||
ag: { prefix: "agsearch", label: "Anghami" },
|
||||
anghami: { prefix: "agsearch", label: "Anghami" },
|
||||
bk: { prefix: "bksearch", label: "Bluesky" },
|
||||
bluesky: { prefix: "bksearch", label: "Bluesky" },
|
||||
// ── Recommendations ──────────────────────────────────────────────────────
|
||||
ytrec: { prefix: "ytrec", label: "YouTube (recommended)" },
|
||||
sprec: { prefix: "sprec", label: "Spotify (recommended)" },
|
||||
dzrec: { prefix: "dzrec", label: "Deezer (recommended)" },
|
||||
tdrec: { prefix: "tdrec", label: "Tidal (recommended)" },
|
||||
jsrec: { prefix: "jsrec", label: "JioSaavn (recommended)" },
|
||||
vkrec: { prefix: "vkrec", label: "VK Music (recommended)" },
|
||||
// ── TTS ──────────────────────────────────────────────────────────────────
|
||||
gtts: { prefix: "gtts", label: "Google TTS" },
|
||||
tts: { prefix: "gtts", label: "Google TTS" },
|
||||
ftts: { prefix: "ftts", label: "Flowery TTS" },
|
||||
};
|
||||
|
||||
/** Label-only map — convenience alias for display use (e.g. Player.mjs). */
|
||||
export const PROVIDER_NAMES = Object.fromEntries(
|
||||
Object.entries(PROVIDERS).map(([k, v]) => [k, v.label])
|
||||
);
|
||||
|
||||
export const PROVIDER_CHOICES = [
|
||||
"ytm", "yt", "scld", "sc",
|
||||
"sp", "spotify",
|
||||
"am", "apple",
|
||||
"dz", "deezer",
|
||||
"td", "tidal",
|
||||
"bc", "bandcamp",
|
||||
"adm", "audiomack",
|
||||
"gaana",
|
||||
"js", "jiosaavn",
|
||||
"lf", "lastfm",
|
||||
"pd", "pandora",
|
||||
"vk",
|
||||
"mc", "mixcloud",
|
||||
"nc", "nicovideo",
|
||||
"bb", "bilibili",
|
||||
"sh", "shazam",
|
||||
"sl", "songlink",
|
||||
"qb", "qobuz",
|
||||
"ym", "yandex",
|
||||
"au", "audius",
|
||||
"az", "amazon",
|
||||
"ag", "anghami",
|
||||
"bk", "bluesky",
|
||||
"ytrec", "sprec", "dzrec", "tdrec", "jsrec", "vkrec",
|
||||
"gtts", "tts", "ftts",
|
||||
];
|
||||
@@ -0,0 +1,43 @@
|
||||
import ffprobe from "ffprobe-static";
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
export default function probe(file) {
|
||||
return new Promise((res, rej) => {
|
||||
// Pass args as an array — splitting a string on " " breaks paths that contain spaces.
|
||||
const args = [
|
||||
"-hide_banner",
|
||||
"-show_entries", "format_tags:format=duration",
|
||||
"-print_format", "json",
|
||||
"-i", file,
|
||||
];
|
||||
const proc = spawn(ffprobe.path, args);
|
||||
const chunks = [];
|
||||
const errChunks = [];
|
||||
|
||||
proc.stdout.on("data", (d) => { chunks.push(d); });
|
||||
proc.stderr.on("data", (d) => { errChunks.push(d); });
|
||||
|
||||
proc.on("error", (err) => {
|
||||
rej(new Error("[probe] Failed to spawn ffprobe: " + err.message));
|
||||
});
|
||||
|
||||
proc.on("close", (code) => {
|
||||
try {
|
||||
const raw = Buffer.concat(chunks).toString();
|
||||
if (!raw.trim()) {
|
||||
const errMsg = Buffer.concat(errChunks).toString().trim();
|
||||
return rej(new Error("[probe] ffprobe produced no output" + (errMsg ? ": " + errMsg : "")));
|
||||
}
|
||||
const data = JSON.parse(raw);
|
||||
res({
|
||||
album: data.format?.tags?.album,
|
||||
artist: data.format?.tags?.artist,
|
||||
title: data.format?.tags?.StreamTitle || data.format?.tags?.title || "Unknown",
|
||||
duration: (data.format?.duration ?? 0) * 1000
|
||||
});
|
||||
} catch (e) {
|
||||
rej(new Error("[probe] Failed to parse ffprobe output: " + e.message));
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
+362
@@ -0,0 +1,362 @@
|
||||
/**
|
||||
* worker.mjs — NodeLink REST edition (moonlink.js session-aware)
|
||||
*
|
||||
* Track resolution runs in a Worker thread so it never blocks the main loop.
|
||||
* The Manager's active session ID is forwarded via workerData so all REST
|
||||
* requests carry the correct Session-Id header (populated by moonlink.js).
|
||||
*
|
||||
* No direct moonlink.js import here — Worker threads can't share the Manager
|
||||
* instance, so we call NodeLink REST directly (same protocol moonlink uses).
|
||||
*/
|
||||
|
||||
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";
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// NodeLink Configuration (forwarded from Player via workerData)
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
const nl = workerData?.data?.nodelink ?? {};
|
||||
const NL_HOST = nl.host ?? "localhost";
|
||||
const NL_PORT = nl.port ?? 3000;
|
||||
const NL_PASSWORD = nl.password ?? "youshallnotpass";
|
||||
const NL_SESSION_ID = nl.sessionId ?? null; // provided by moonlink.js Manager
|
||||
const NL_GUILD_ID = workerData?.data?.guildId ?? null;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// HTTP Helper
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Make a GET request to NodeLink and return the parsed JSON body.
|
||||
* @param {string} path - API path (e.g. "/v4/loadtracks?identifier=…")
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
function nlGet(path) {
|
||||
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: NL_PASSWORD,
|
||||
...(NL_SESSION_ID ? { "Session-Id": NL_SESSION_ID } : {}),
|
||||
...(NL_GUILD_ID ? { "Guild-Id": NL_GUILD_ID } : {}),
|
||||
}
|
||||
},
|
||||
(res) => {
|
||||
const chunks = [];
|
||||
res.on("data", d => chunks.push(d));
|
||||
res.on("end", () => {
|
||||
try {
|
||||
resolve(JSON.parse(Buffer.concat(chunks).toString()));
|
||||
} 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"));
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Call NodeLink /v4/loadtracks.
|
||||
* @param {string} identifier
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
async function loadTracks(identifier) {
|
||||
return nlGet(`/v4/loadtracks?identifier=${encodeURIComponent(identifier)}`);
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// Track Conversion
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* 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,
|
||||
};
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// Provider Configuration (imported from constants/providers.mjs)
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
const TYPE_MODIFIERS = ["track","playlist","album","artist","channel","user"];
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// YTUtils Class
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
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"; }
|
||||
|
||||
_buildIdentifier(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}:track:${query}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean YouTube Radio/Mix URLs to extract just the video
|
||||
* YouTube Radio URLs (list=RD...) often cause metadata mismatches
|
||||
*/
|
||||
_cleanYouTubeUrl(url) {
|
||||
try {
|
||||
const urlObj = new URL(url);
|
||||
|
||||
// Check if it's a YouTube Radio/Mix URL
|
||||
const list = urlObj.searchParams.get("list");
|
||||
if (list && list.startsWith("RD")) {
|
||||
// Extract just the video ID and create clean URL
|
||||
const videoId = urlObj.searchParams.get("v");
|
||||
if (videoId) {
|
||||
logger.worker(`[Worker] Cleaning YouTube Radio URL, extracted video: ${videoId}`);
|
||||
return `https://www.youtube.com/watch?v=${videoId}`;
|
||||
}
|
||||
}
|
||||
|
||||
// Remove start_radio parameter if present
|
||||
if (urlObj.searchParams.has("start_radio")) {
|
||||
urlObj.searchParams.delete("start_radio");
|
||||
return urlObj.toString();
|
||||
}
|
||||
|
||||
return url;
|
||||
} catch (e) {
|
||||
return url;
|
||||
}
|
||||
}
|
||||
|
||||
async getResults(query, limit = 5, provider = "ytm") {
|
||||
const id = this.isValidUrl(query) ? query : this._buildIdentifier(provider, query);
|
||||
const data = await loadTracks(id);
|
||||
|
||||
let tracks = [];
|
||||
if (data.loadType === "search") tracks = data.data ?? [];
|
||||
else if (data.loadType === "track") tracks = [data.data];
|
||||
else if (data.loadType === "playlist") tracks = data.data?.tracks ?? [];
|
||||
|
||||
const validTracks = tracks.filter(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.length || info.length === 0) return false;
|
||||
return true;
|
||||
});
|
||||
|
||||
const resultTracks = validTracks.length > 0 ? validTracks : tracks;
|
||||
return { data: resultTracks.slice(0, limit).map(trackToVideo) };
|
||||
}
|
||||
|
||||
async getVideoData(query, provider = "ytm") {
|
||||
// Handle URLs (including YouTube Radio/Mix)
|
||||
if (this.isValidUrl(query)) {
|
||||
this.emit("message", "Loading...");
|
||||
|
||||
// Clean YouTube Radio URLs to prevent metadata mismatches
|
||||
const cleanedUrl = this._cleanYouTubeUrl(query);
|
||||
if (cleanedUrl !== query) {
|
||||
logger.worker(`[Worker] URL cleaned: ${query} -> ${cleanedUrl}`);
|
||||
}
|
||||
|
||||
let data;
|
||||
try {
|
||||
data = await loadTracks(cleanedUrl);
|
||||
} catch (e) {
|
||||
this.emit("message", `**Failed to load: ${e.message}**`);
|
||||
return { type: "error", data: null, error: e.message };
|
||||
}
|
||||
|
||||
// Handle playlist results
|
||||
if (data.loadType === "playlist") {
|
||||
const tracks = (data.data?.tracks ?? []).map(trackToVideo);
|
||||
tracks.forEach(t => { t.playlistName = data.data?.info?.name ?? null; });
|
||||
this.emit("message", `Successfully added **${tracks.length}** songs to the queue.`);
|
||||
return { type: "list", data: tracks };
|
||||
}
|
||||
|
||||
// Handle single track
|
||||
if (data.loadType === "track") {
|
||||
const video = trackToVideo(data.data);
|
||||
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
|
||||
return { type: "video", data: video };
|
||||
}
|
||||
|
||||
// Handle search results (take first)
|
||||
if (data.loadType === "search" && data.data?.length) {
|
||||
const video = trackToVideo(data.data[0]);
|
||||
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
|
||||
return { type: "video", data: video };
|
||||
}
|
||||
|
||||
// No recognizable loadType
|
||||
this.emit("message", `**Could not load that URL.** (loadType: ${data.loadType || "unknown"})`);
|
||||
return { type: "error", data: null, error: "Unknown loadType: " + (data.loadType || "none") };
|
||||
}
|
||||
|
||||
// Handle search queries (non-URLs)
|
||||
this.emit("message", `Searching ${this._providerLabel(provider)}...`);
|
||||
|
||||
let data;
|
||||
try {
|
||||
data = await loadTracks(this._buildIdentifier(provider, query));
|
||||
} catch (e) {
|
||||
this.emit("message", `**Search failed: ${e.message}**`);
|
||||
return { type: "error", data: null, error: e.message };
|
||||
}
|
||||
|
||||
// Handle search results
|
||||
if (data.loadType === "search" && data.data?.length) {
|
||||
const validTrack = data.data.find(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 (!info.length || info.length === 0) return false;
|
||||
return true;
|
||||
});
|
||||
const trackToUse = validTrack || data.data[0];
|
||||
const video = trackToVideo(trackToUse);
|
||||
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
|
||||
return { type: "video", data: video };
|
||||
}
|
||||
|
||||
// Handle playlist from search
|
||||
if (data.loadType === "playlist") {
|
||||
const tracks = (data.data?.tracks ?? []).map(trackToVideo);
|
||||
if (tracks.length > 0) {
|
||||
this.emit("message", `Successfully added **${tracks.length}** songs to the queue.`);
|
||||
return { type: "list", data: tracks };
|
||||
}
|
||||
}
|
||||
|
||||
// Single track from search
|
||||
if (data.loadType === "track") {
|
||||
const video = trackToVideo(data.data);
|
||||
this.emit("message", `Successfully added [${video.title}](${video.url}) to the queue.`);
|
||||
return { type: "video", data: video };
|
||||
}
|
||||
|
||||
// Nothing found
|
||||
this.emit("message", `**No results found for '${query}'.**`);
|
||||
return { type: "error", data: null, error: "No results found" };
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// Worker Entry Point
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
const jobId = workerData?.jobId;
|
||||
const data = workerData?.data;
|
||||
|
||||
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) => {
|
||||
if (jobId === "dev") { logger.worker("[Message]", m); return; }
|
||||
post("message", m);
|
||||
});
|
||||
|
||||
utils.on("error", (m) => {
|
||||
if (jobId === "dev") { logger.worker("[Error]", m); return; }
|
||||
post("error", m);
|
||||
});
|
||||
|
||||
(async () => {
|
||||
if (jobId === "dev") {
|
||||
try {
|
||||
const result = await utils.getVideoData("Neoni funeral", "ytm");
|
||||
logger.worker("[Worker result]", result);
|
||||
} catch (e) {
|
||||
logger.error("[Worker error]", e);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
switch (jobId) {
|
||||
case "generalQuery": {
|
||||
const result = await utils.getVideoData(data.query, data.provider);
|
||||
post("finished", result);
|
||||
break;
|
||||
}
|
||||
case "searchResults": {
|
||||
const result = await utils.getResults(data.query, data.resultCount, data.provider);
|
||||
post("finished", result);
|
||||
break;
|
||||
}
|
||||
case "search": {
|
||||
const result = await utils.getVideoData(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