mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-23 21:52:45 -05:00
Remix — the complete rewrite
Upgrades the bot from fluxerjs 2.2 to 3.0 and restructures everything into a layered architecture (~28K lines): Dependencies: - @fluxerjs/core, util, voice: ^2.2.0 -> ^3.0.0 (typed events, PartialMessage payloads, camelCase API) - @fluxerjs/sharding ^3.0.0 added — built-in sharding mode (shard.mjs, one process per shard) - @discordjs/opus dropped — opusscript + prism-media cover encoding Architecture: - commands: every command split into submodules (player, lastfm, settings, debug) with a shared CommandBuilder/Loader/Handler core - ui: embeds, paginators, help command, permission checks - voice: gateway event routing, rejoin/247 boot recovery, state resolver - music: player split into Queue/Search/Playback/Display mixins, stream pipeline + WebM/Opus muxer (no FFmpeg needed) - dashboard: Redis pub/sub, RPC handlers, serializers - db: MySQL manager + per-guild settings - services: LastFm manager split into focused mixins - utils: sharding, 24/7 helpers, API client Runtime fixes over v2: - Redis v5 reconnect: capped numeric backoff (0.5s ramp to 15s), never exhausts, auto-recovers when the server comes back - Redis main/subscriber clients connect in parallel; clean shutdown - Logger storm guard: identical error/warn lines deduped in a 60s window - self-deaf fix on voice join - config example uses redis://127.0.0.1 (avoids IPv6 ENETUNREACH) Housekeeping: dead code removed (Tuna.mjs + follow-redirects dep), .gitignore added (config.json, .env, node_modules, runtime state).
This commit is contained in:
1 parent
0f085a6ae4
commit
253d11cd57
150 files changed
+19935
-16894
No files matched your search
@@ -0,0 +1,100 @@
|
||||
/** @module src/utils/API */
|
||||
|
||||
/**
|
||||
* FluxerList API configuration.
|
||||
* @namespace FLUXERLIST
|
||||
*/
|
||||
export const FLUXERLIST = {
|
||||
/** Base URL for the FluxerList REST API. @type {string} */
|
||||
BASE_URL: "https://fluxerlist.com/api/v1",
|
||||
|
||||
/** Public FluxerList website URL. @type {string} */
|
||||
SITE_URL: "https://fluxerlist.com",
|
||||
|
||||
/** API endpoint path templates. @type {{ SERVER_VOTERS: string, BOT_VOTERS: string }} */
|
||||
ENDPOINTS: {
|
||||
SERVER_VOTERS: "/servers/:id/voters",
|
||||
|
||||
BOT_VOTERS: "/bots/:id/voters",
|
||||
},
|
||||
|
||||
/** Accepted resource type identifiers. @type {string[]} */
|
||||
RESOURCE_TYPES: ["server", "bot"],
|
||||
|
||||
/** Thumbnail API base URL. @type {string} */
|
||||
THUMBNAIL: "https://fluxerlist.com/api/v1",
|
||||
};
|
||||
|
||||
/**
|
||||
* FluxerList authentication helpers.
|
||||
* @namespace FLUXERLIST_AUTH
|
||||
*/
|
||||
export const FLUXERLIST_AUTH = {
|
||||
/** HTTP header name for auth. @type {string} */
|
||||
HEADER: "Authorization",
|
||||
|
||||
/** Required API key prefix. @type {string} */
|
||||
KEY_PREFIX: "fl_",
|
||||
|
||||
/**
|
||||
* Format an API key as a Bearer token, prepending the prefix if needed.
|
||||
* @param {string} apiKey - Raw or prefixed API key.
|
||||
* @returns {string} `Bearer fl_...` string.
|
||||
*/
|
||||
bearer(apiKey) {
|
||||
const key = apiKey.startsWith(FLUXERLIST_AUTH.KEY_PREFIX)
|
||||
? apiKey
|
||||
: FLUXERLIST_AUTH.KEY_PREFIX + apiKey;
|
||||
return `Bearer ${key}`;
|
||||
},
|
||||
};
|
||||
|
||||
/**
|
||||
* FluxerList pagination and cache limits.
|
||||
* @namespace FLUXERLIST_LIMITS
|
||||
*/
|
||||
export const FLUXERLIST_LIMITS = {
|
||||
/** Default page number. @type {number} */
|
||||
DEFAULT_PAGE: 1,
|
||||
|
||||
/** Default items-per-page. @type {number} */
|
||||
DEFAULT_LIMIT: 50,
|
||||
|
||||
/** Maximum allowed items-per-page. @type {number} */
|
||||
MAX_LIMIT: 100,
|
||||
|
||||
/** Cache time-to-live in milliseconds. @type {number} */
|
||||
CACHE_TTL_MS: 5 * 60 * 1000,
|
||||
};
|
||||
|
||||
/**
|
||||
* Build a full FluxerList API URL by substituting `:id` in the endpoint and appending query params.
|
||||
* @param {string} endpoint - Endpoint template (e.g. `"/servers/:id/voters"`).
|
||||
* @param {string} resourceId - Value to substitute for `:id`.
|
||||
* @param {{ page?: number, limit?: number }} [queryParams={}]
|
||||
* @returns {string} Fully qualified URL.
|
||||
*/
|
||||
export function buildFluxerListUrl(endpoint, resourceId, queryParams = {}) {
|
||||
const path = endpoint.replace(":id", encodeURIComponent(resourceId));
|
||||
const params = new URLSearchParams();
|
||||
|
||||
if (queryParams.page) params.set("page", String(queryParams.page));
|
||||
if (queryParams.limit) {
|
||||
const clamped = Math.min(Math.max(1, queryParams.limit), FLUXERLIST_LIMITS.MAX_LIMIT);
|
||||
params.set("limit", String(clamped));
|
||||
}
|
||||
|
||||
const qs = params.toString();
|
||||
return `${FLUXERLIST.BASE_URL}${path}${qs ? "?" + qs : ""}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build a FluxerList vote link for a server or bot.
|
||||
* @param {"server"|"bot"} type - Resource type.
|
||||
* @param {string} resourceId - The server/bot ID.
|
||||
* @returns {string} Absolute URL to the vote page.
|
||||
*/
|
||||
export function buildVoteLink(type, resourceId) {
|
||||
const path = type === "server" ? "servers" : "bots";
|
||||
return `${FLUXERLIST.SITE_URL}/${path}/${resourceId}`;
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
/** @module src/utils/Helpers247 */
|
||||
|
||||
/**
|
||||
* Simplified 24/7 helpers — single mode (on/off), no per-channel modes.
|
||||
* get247ChannelMode is used by Player.mjs, PlayerManager.mjs, GatewayHandler.mjs, leave.mjs.
|
||||
* remove247ChannelMode and set247ChannelMode are kept as no-ops for backward compat
|
||||
* (original files in the zip still import them).
|
||||
*/
|
||||
|
||||
/**
|
||||
* Check if a channel has 24/7 enabled.
|
||||
* @param {object} set - ServerSettings instance
|
||||
* @param {string} channelId
|
||||
* @returns {"on"|"off"}
|
||||
*/
|
||||
export function get247ChannelMode(set, channelId) {
|
||||
if (!set?.get) return "off";
|
||||
const raw = set.get("stay_247");
|
||||
if (!raw || raw === "none") return "off";
|
||||
const channels = Array.isArray(raw)
|
||||
? raw.map(id => String(id).trim()).filter(Boolean)
|
||||
: [String(raw).trim()];
|
||||
return channels.includes(channelId) ? "on" : "off";
|
||||
}
|
||||
|
||||
/**
|
||||
* No-op: per-channel modes removed. Kept for backward compatibility.
|
||||
* Original GatewayHandler.mjs and index.mjs still import this.
|
||||
*/
|
||||
export function remove247ChannelMode(set, channelId, currentChannels) {
|
||||
// No-op: modes no longer exist, stay_247 array is managed directly.
|
||||
}
|
||||
|
||||
/**
|
||||
* No-op: per-channel modes removed. Kept for backward compatibility.
|
||||
*/
|
||||
export function set247ChannelMode(set, channelId, mode) {
|
||||
// No-op: modes no longer exist.
|
||||
}
|
||||
@@ -0,0 +1,140 @@
|
||||
/**
|
||||
* @module src/utils/ShardingUtils
|
||||
* @description Shard-aware gateway helpers that work identically on Fluxer.js
|
||||
* 2.2 (plain single process) and 3.0 (optionally sharded via
|
||||
* `@fluxerjs/sharding`).
|
||||
*
|
||||
* When the bot boots through the root `shard.mjs` supervisor, every child
|
||||
* process is forked by a {@link ShardingManager} with the
|
||||
* `FLUXER_SHARD_IDS` / `FLUXER_SHARD_COUNT` / `FLUXER_SHARD_PROCESS_ID` env
|
||||
* vars set, and `Bot.mjs` attaches the child-side `ShardClientUtil` as
|
||||
* `client.shard` before login. These helpers read that state to:
|
||||
* - route guild-scoped gateway payloads (opcode 4 voice joins/leaves) to
|
||||
* the shard that owns the guild,
|
||||
* - fan presence updates out to every gateway shard connected in this
|
||||
* process,
|
||||
* - enumerate the raw WebSocket socket of every local shard (2.2 exposed
|
||||
* a `ws.shards` Map property; 3.0 exposes `getShards()`/`getShard()`
|
||||
* methods and no property).
|
||||
*
|
||||
* In plain single-process mode (`npm start` / `node index.mjs`) every helper
|
||||
* degrades to the exact pre-sharding behavior — shard 0 and a one-element
|
||||
* shard list — so callers never need to know whether the bot is sharded.
|
||||
*/
|
||||
|
||||
/**
|
||||
* True when this process was forked by an `@fluxerjs/sharding`
|
||||
* ShardingManager (root `shard.mjs`). Detection requires both the manager
|
||||
* env var and a live IPC channel (`process.send`); manually exporting
|
||||
* FLUXER_* variables does not activate sharding.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isShardedProcess() {
|
||||
return process.env.FLUXER_SHARD_IDS !== undefined &&
|
||||
typeof process.send === "function";
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the gateway shard that owns a guild. Under a ShardingManager the
|
||||
* child-side `client.shard.shardIdForGuildId()` computes the assignment
|
||||
* (`(guild_id >> 22) % shard_count`, matching the gateway); otherwise the
|
||||
* bot runs a single gateway shard and the answer is always 0.
|
||||
* @param {object} client - The Fluxer client instance.
|
||||
* @param {string|number|null} guildId - The guild ID to route for.
|
||||
* @returns {number} The owning shard id (0 when not sharded).
|
||||
*/
|
||||
export function shardIdForGuild(client, guildId) {
|
||||
try {
|
||||
const shardUtil = client?.shard;
|
||||
if (shardUtil && typeof shardUtil.shardIdForGuildId === "function") {
|
||||
const id = shardUtil.shardIdForGuildId(String(guildId ?? ""));
|
||||
if (Number.isInteger(id) && id >= 0) return id;
|
||||
}
|
||||
} catch {
|
||||
// fall through to the single-process default
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the client's shard map in a 2.2- and 3.0-compatible way.
|
||||
* Fluxer 3.0 exposes `getShards()` on the WebSocketManager (the 2.2 `shards`
|
||||
* Map property is gone), and `client.ws` itself is a throwing getter before
|
||||
* login on 3.0, so every access here is guarded.
|
||||
* @param {object} client - The Fluxer client instance.
|
||||
* @returns {Array<Array<number, object>>} [id, shard] entries; empty when the
|
||||
* gateway is not connected yet or no shards are running in this process.
|
||||
*/
|
||||
export function getLocalShards(client) {
|
||||
try {
|
||||
const ws = client?.ws;
|
||||
if (!ws) return [];
|
||||
const map = typeof ws.getShards === "function" ? ws.getShards() : ws.shards;
|
||||
if (map && typeof map.entries === "function") {
|
||||
return [...map.entries()].filter(([id]) => Number.isInteger(id));
|
||||
}
|
||||
} catch {
|
||||
// Fluxer 3.0: client.ws throws before login — treat as "no shards yet".
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Ids of the gateway shards connected in this process. Defaults to `[0]`
|
||||
* (single-process behavior) when no shard map is available yet.
|
||||
* @param {object} client - The Fluxer client instance.
|
||||
* @returns {number[]}
|
||||
*/
|
||||
export function localShardIds(client) {
|
||||
const ids = getLocalShards(client).map(([id]) => id);
|
||||
return ids.length > 0 ? ids : [0];
|
||||
}
|
||||
|
||||
/**
|
||||
* Raw WebSocket socket of every gateway shard connected in this process
|
||||
* (used by the raw-socket listeners in GatewayHandler and LavalinkManager).
|
||||
* 2.2-style code read `client.ws.shards.get(0).ws`; this generalises it to
|
||||
* all local shards for sharded children.
|
||||
* @param {object} client - The Fluxer client instance.
|
||||
* @returns {Array<object>} Raw socket objects (may be empty).
|
||||
*/
|
||||
export function localShardSockets(client) {
|
||||
const out = [];
|
||||
for (const [, shard] of getLocalShards(client)) {
|
||||
const wsObj = shard?.ws ?? null;
|
||||
if (wsObj) out.push(wsObj);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Look up a single shard handle by id, 2.2- and 3.0-compatible.
|
||||
* @param {object} client - The Fluxer client instance.
|
||||
* @param {number} [shardId=0] - The shard id to fetch.
|
||||
* @returns {object|null} The shard handle, or null when unavailable.
|
||||
*/
|
||||
export function getShard(client, shardId = 0) {
|
||||
try {
|
||||
const ws = client?.ws;
|
||||
if (!ws) return null;
|
||||
if (typeof ws.getShard === "function") return ws.getShard(shardId) ?? null;
|
||||
return ws.shards?.get?.(shardId) ?? null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* One-line sharding description for startup logs.
|
||||
* @param {object} [client] - The Fluxer client instance (optional).
|
||||
* @returns {string} e.g. "process 2, gateway shards 4,5 of 8" or
|
||||
* "single process (unsharded)".
|
||||
*/
|
||||
export function describeSharding(client) {
|
||||
if (!isShardedProcess()) return "single process (unsharded)";
|
||||
const ids = String(process.env.FLUXER_SHARD_IDS ?? "0");
|
||||
const count = Number(process.env.FLUXER_SHARD_COUNT ?? "1") || 1;
|
||||
const pid = process.env.FLUXER_SHARD_PROCESS_ID ?? ids.split(",")[0] ?? "0";
|
||||
const live = localShardIds(client);
|
||||
return `process ${pid}, gateway shards ${ids} of ${count} (connected: ${live.join(", ")})`;
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
/** @module src/utils/UI */
|
||||
|
||||
/** Hex color string for error embeds. @type {string} */
|
||||
export const ERROR_COLOR = "#ff0000";
|
||||
|
||||
/** Numeric hex color for warning embeds. @type {number} */
|
||||
export const WARN_COLOR = 0xFFAA00;
|
||||
|
||||
/** Numeric hex color for success embeds. @type {number} */
|
||||
export const SUCCESS_COLOR = 0x00CC66;
|
||||
|
||||
/** Numeric hex color for danger/critical embeds. @type {number} */
|
||||
export const DANGER_COLOR = 0xFF4444;
|
||||
|
||||
/** Auto-remove reaction collectors after this many ms. @type {number} */
|
||||
export const EMOJI_REMOVE_TIMEOUT = 60_000;
|
||||
|
||||
/** Session idle timeout in ms. @type {number} */
|
||||
export const SESSION_TIMEOUT = 30_000;
|
||||
|
||||
/** Number emoji map for selection menus (indices 1-10). @type {string[]} */
|
||||
export const NUMBER_EMOJIS = [
|
||||
"1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣",
|
||||
"6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟",
|
||||
];
|
||||
|
||||
/** Emoji used to cancel a selection. @type {string} */
|
||||
export const CANCEL_EMOJI = "❌";
|
||||
|
||||
/** Emoji for previous-page navigation. @type {string} */
|
||||
export const PREV_EMOJI = "⬅️";
|
||||
|
||||
/** Emoji for next-page navigation. @type {string} */
|
||||
export const NEXT_EMOJI = "➡️";
|
||||
|
||||
/** Maximum allowed volume value. @type {number} */
|
||||
export const MAX_VOLUME = 200;
|
||||
@@ -0,0 +1,422 @@
|
||||
/** @module src/utils/Utils @description General-purpose utility functions for formatting, validation, string manipulation, and ID cleaning. */
|
||||
|
||||
import { escapeMarkdown as _escapeMarkdown, truncate as _truncate } from "@fluxerjs/util";
|
||||
import { logger } from "../core/Logger.mjs";
|
||||
|
||||
/**
|
||||
* Strip all non-digit characters from a value to extract a Snowflake/numeric ID.
|
||||
* @param {*} value - The value to clean (string, number, or null/undefined).
|
||||
* @returns {string} The numeric portion of the value, or empty string if none.
|
||||
*/
|
||||
export function cleanId(value) {
|
||||
return String(value ?? "").replace(/\D/g, "");
|
||||
}
|
||||
|
||||
/** @class Utils @description Collection of static utility methods for formatting, parsing, and string manipulation. */
|
||||
export class Utils {
|
||||
|
||||
/**
|
||||
* Format a duration in milliseconds to a human-readable string (e.g. "1:23:45").
|
||||
* @param {number} milliseconds - Duration in milliseconds.
|
||||
* @returns {string} Formatted duration string.
|
||||
*/
|
||||
static prettifyMS(milliseconds) {
|
||||
if (!milliseconds || milliseconds < 0 || !isFinite(milliseconds)) {
|
||||
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 a duration string (e.g. "1:30", "1:30:00", "90") into milliseconds.
|
||||
* @param {string} str - Duration string in mm:ss, hh:mm:ss, or plain seconds.
|
||||
* @returns {number} Duration in milliseconds, or 0 if unparseable.
|
||||
*/
|
||||
static parseDuration(str) {
|
||||
if (!str || typeof str !== "string") return 0;
|
||||
str = str.trim();
|
||||
|
||||
if (/^\d+$/.test(str)) {
|
||||
return parseInt(str, 10) * 1000;
|
||||
}
|
||||
|
||||
const parts = str.split(":").map((s) => parseInt(s.trim(), 10)).reverse();
|
||||
if (parts.some(isNaN) || parts.some(n => n < 0)) return 0;
|
||||
|
||||
let ms = 0;
|
||||
if (parts[0] !== undefined) ms += parts[0] * 1000;
|
||||
if (parts[1] !== undefined) ms += parts[1] * 60 * 1000;
|
||||
if (parts[2] !== undefined) ms += parts[2] * 3600 * 1000;
|
||||
|
||||
return ms;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format seconds into a human-readable duration string.
|
||||
* @param {number} seconds - Duration in seconds.
|
||||
* @returns {string} Formatted duration string.
|
||||
*/
|
||||
static formatSeconds(seconds) {
|
||||
if (!seconds || seconds < 0 || !isFinite(seconds)) return "0:00";
|
||||
return this.prettifyMS(seconds * 1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* Fisher-Yates in-place shuffle of an array.
|
||||
* @param {Array} array - The array to shuffle (mutated in place).
|
||||
* @returns {Array} The same array, shuffled.
|
||||
*/
|
||||
static shuffleArr(array) {
|
||||
if (!Array.isArray(array) || array.length < 2) return array;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Truncate a string to a maximum length, appending a suffix if truncated.
|
||||
* @param {string} str - The string to truncate.
|
||||
* @param {number} [maxLen=100] - Maximum character length.
|
||||
* @param {string} [suffix="..."] - Suffix to append when truncated.
|
||||
* @returns {string} Truncated string.
|
||||
*/
|
||||
static truncate(str, maxLen = 100, suffix = "...") {
|
||||
if (!str || typeof str !== "string") return "";
|
||||
if (str.length <= maxLen) return str;
|
||||
if (maxLen <= suffix.length) return str.substring(0, maxLen);
|
||||
return str.substring(0, maxLen - suffix.length) + suffix;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean a track title by removing common noise patterns (feat, remix, lyrics, etc.).
|
||||
* @param {string} title - The raw track title.
|
||||
* @returns {string} Cleaned title.
|
||||
*/
|
||||
static cleanTitle(title) {
|
||||
if (!title || typeof title !== "string") return "Unknown";
|
||||
|
||||
let cleaned = title;
|
||||
for (let pass = 0; pass < 3; pass++) {
|
||||
const prev = cleaned;
|
||||
cleaned = cleaned
|
||||
.replace(/\s*\([^()]*\)/g, (match) => {
|
||||
const inner = match.toLowerCase();
|
||||
if (/(?:feat|ft|featuring|remix|edit|version|prod|official|audio|video|lyrics|visualizer|deluxe|explicit|clean|radio|instrumental|acoustic|extended|mono|stereo|remaster)/.test(inner)) {
|
||||
return "";
|
||||
}
|
||||
return match;
|
||||
})
|
||||
.replace(/\s*\[[^\[\]]*\]/g, (match) => {
|
||||
const inner = match.toLowerCase();
|
||||
if (/(?:feat|ft|featuring|remix|edit|version|prod|official|audio|video|lyrics|visualizer|deluxe|explicit|clean|radio|instrumental|acoustic|extended|remaster)/.test(inner)) {
|
||||
return "";
|
||||
}
|
||||
return match;
|
||||
});
|
||||
if (cleaned === prev) break;
|
||||
}
|
||||
|
||||
return cleaned
|
||||
.replace(/\s*-\s*(?:feat|ft|featuring)\.?.*/gi, "")
|
||||
.replace(/\s*\|.*$/g, "")
|
||||
.replace(/\s*【.*?】/g, "")
|
||||
.replace(/\s{2,}/g, " ")
|
||||
.trim() || "Unknown";
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape markdown special characters in text.
|
||||
* @param {string} text - The text to escape.
|
||||
* @returns {string} Escaped text, or empty string if falsy.
|
||||
*/
|
||||
static escapeMarkdown(text) {
|
||||
if (!text || typeof text !== "string") return "";
|
||||
return _escapeMarkdown(text);
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a number with locale-aware thousand separators.
|
||||
* @param {number} num - The number to format.
|
||||
* @returns {string} Formatted number string.
|
||||
*/
|
||||
static formatNumber(num) {
|
||||
if (num === null || num === undefined || isNaN(num)) return "0";
|
||||
return num.toLocaleString("en-US");
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a unique ID string based on timestamp and random characters.
|
||||
* @param {number} [length=16] - Target length of the ID (clamped 8–32).
|
||||
* @returns {string} A unique alphanumeric ID.
|
||||
*/
|
||||
static uid(length = 16) {
|
||||
const targetLen = Math.max(8, Math.min(length, 32));
|
||||
|
||||
const timestamp = Date.now().toString(36).toUpperCase();
|
||||
let random = "";
|
||||
|
||||
while ((timestamp + random).length < targetLen) {
|
||||
random += Math.random().toString(36).substring(2).toUpperCase();
|
||||
}
|
||||
|
||||
return (timestamp + random).substring(0, targetLen);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a value is a valid finite number or numeric string.
|
||||
* @param {*} str - Value to check.
|
||||
* @returns {boolean} True if the value is a valid number.
|
||||
*/
|
||||
static isNumber(str) {
|
||||
if (str === null || str === undefined || str === "") return false;
|
||||
if (typeof str === "number") return !isNaN(str) && isFinite(str);
|
||||
if (typeof str !== "string") return false;
|
||||
const trimmed = str.trim();
|
||||
if (trimmed === "") return false;
|
||||
return !isNaN(trimmed) && isFinite(trimmed);
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether a string is a valid URL.
|
||||
* @param {string} str - String to check.
|
||||
* @returns {boolean} True if the string is a valid URL.
|
||||
*/
|
||||
static isValidUrl(str) {
|
||||
if (!str || typeof str !== "string") return false;
|
||||
try {
|
||||
new URL(str);
|
||||
return true;
|
||||
} catch (e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract an 11-character YouTube video ID from any common YouTube URL form
|
||||
* (youtu.be short links, watch?v=, /shorts/, /embed/, /live/, music.youtube.com).
|
||||
* Tracking parameters (si, feature, utm_*) are irrelevant — only the ID matters.
|
||||
* @param {string} str - Candidate URL or raw ID.
|
||||
* @returns {string|null} The video ID, or null if none could be extracted.
|
||||
*/
|
||||
static extractYouTubeId(str) {
|
||||
if (!str || typeof str !== "string") return null;
|
||||
const trimmed = str.trim();
|
||||
|
||||
if (/^[A-Za-z0-9_-]{11}$/.test(trimmed)) return trimmed;
|
||||
|
||||
let url;
|
||||
try { url = new URL(trimmed); } catch (_) { return null; }
|
||||
|
||||
const host = url.hostname.replace(/^www\./i, "").toLowerCase();
|
||||
if (host === "youtu.be") {
|
||||
const id = url.pathname.split("/").filter(Boolean)[0] ?? "";
|
||||
return /^[A-Za-z0-9_-]{11}$/.test(id) ? id : null;
|
||||
}
|
||||
if (host === "youtube.com" || host === "music.youtube.com" || host === "youtube-nocookie.com") {
|
||||
const v = url.searchParams.get("v");
|
||||
if (v && /^[A-Za-z0-9_-]{11}$/.test(v)) return v;
|
||||
const parts = url.pathname.split("/").filter(Boolean);
|
||||
const idx = parts.findIndex(p => ["shorts", "embed", "live", "v"].includes(p.toLowerCase()));
|
||||
if (idx !== -1 && parts[idx + 1] && /^[A-Za-z0-9_-]{11}$/.test(parts[idx + 1])) {
|
||||
return parts[idx + 1];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Build the canonical YouTube watch URL from any YouTube URL form.
|
||||
* Strips share/tracking parameters (si, feature, utm_*, etc.) which some
|
||||
* audio nodes mishandle and which break NodeLink's resolver cache reuse.
|
||||
* @param {string} str - Candidate URL.
|
||||
* @returns {string|null} Canonical URL like https://www.youtube.com/watch?v=<id>, or null.
|
||||
*/
|
||||
static normalizeYouTubeUrl(str) {
|
||||
const id = Utils.extractYouTubeId(str);
|
||||
return id ? "https://www.youtube.com/watch?v=" + id : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a YouTube video's title via the public oEmbed endpoint.
|
||||
* oEmbed is served from YouTube's edge and is NOT subject to the
|
||||
* "Sign in to confirm you're not a bot" gating that blocks datacenter-IP
|
||||
* player/stream requests — so it works even when NodeLink's YouTube
|
||||
* source is bot-blocked. Used as a last-resort fallback to search by title.
|
||||
* @param {string} videoIdOrUrl - Video ID or any YouTube URL form.
|
||||
* @param {number} [timeoutMs=5000] - Request timeout in milliseconds.
|
||||
* @returns {Promise<string|null>} The video title, or null on failure.
|
||||
*/
|
||||
static async fetchYouTubeOEmbedTitle(videoIdOrUrl, timeoutMs = 5000) {
|
||||
const id = Utils.extractYouTubeId(videoIdOrUrl);
|
||||
if (!id) return null;
|
||||
try {
|
||||
const target = "https://www.youtube.com/watch?v=" + id;
|
||||
const res = await fetch(
|
||||
"https://www.youtube.com/oembed?url=" + encodeURIComponent(target) + "&format=json",
|
||||
{
|
||||
headers: { "User-Agent": "Mozilla/5.0 (compatible; RemixBot/1.0)" },
|
||||
signal: AbortSignal.timeout(timeoutMs),
|
||||
}
|
||||
);
|
||||
if (!res.ok) return null;
|
||||
const data = await res.json();
|
||||
const title = typeof data?.title === "string" ? data.title.trim() : "";
|
||||
return title || null;
|
||||
} catch (_) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Clamp a number between a minimum and maximum value.
|
||||
* @param {number} num - The number to clamp.
|
||||
* @param {number} min - Minimum value.
|
||||
* @param {number} max - Maximum value.
|
||||
* @returns {number} Clamped value.
|
||||
*/
|
||||
static clamp(num, min, max) {
|
||||
if (isNaN(num)) return min;
|
||||
return Math.max(min, Math.min(max, num));
|
||||
}
|
||||
|
||||
/**
|
||||
* Return a promise that resolves after a specified delay.
|
||||
* @param {number} ms - Delay in milliseconds.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
static sleep(ms) {
|
||||
return new Promise((resolve) => setTimeout(resolve, Math.max(0, ms)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Wrap a promise with a timeout. Rejects if the promise does not settle in time.
|
||||
* @template T
|
||||
* @param {Promise<T>} promise - The promise to wrap.
|
||||
* @param {number} ms - Timeout in milliseconds.
|
||||
* @param {string} [message="Operation timed out"] - Rejection message.
|
||||
* @returns {Promise<T>} The original promise result, or rejection on timeout.
|
||||
*/
|
||||
static timeout(promise, ms, message = "Operation timed out") {
|
||||
let timerId;
|
||||
const timeoutPromise = new Promise((_, reject) => {
|
||||
timerId = setTimeout(() => reject(new Error(message)), ms);
|
||||
});
|
||||
return Promise.race([promise, timeoutPromise]).finally(() => clearTimeout(timerId));
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a text-based progress bar.
|
||||
* @param {number} current - Current progress value or ratio.
|
||||
* @param {number} [total] - Total value. If omitted, current is treated as a 0–1 ratio.
|
||||
* @param {number} [length=15] - Bar length in characters.
|
||||
* @param {string} [filledChar="━"] - Character for the filled portion.
|
||||
* @param {string} [emptyChar="─"] - Character for the empty portion.
|
||||
* @param {string} [indicator="⬤"] - Character for the current position indicator.
|
||||
* @returns {string} The progress bar string.
|
||||
*/
|
||||
static progressBar(
|
||||
current,
|
||||
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.min(Math.floor(progress * length), length - 1);
|
||||
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 a track object into a display string with title, artist, and optional duration.
|
||||
* @param {object} track - Track object with title, author, and optional duration.
|
||||
* @param {boolean} [includeDuration=true] - Whether to include the duration.
|
||||
* @returns {string} Formatted track info string.
|
||||
*/
|
||||
static formatTrackInfo(track, includeDuration = true) {
|
||||
if (!track) return "Unknown Track";
|
||||
|
||||
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 an ISO 8601 duration string (e.g. "PT1H30M45S") into milliseconds.
|
||||
* @param {string} isoDuration - The ISO duration string.
|
||||
* @returns {number} Duration in milliseconds, or 0 if unparseable.
|
||||
*/
|
||||
static parseISODuration(isoDuration) {
|
||||
if (!isoDuration || typeof isoDuration !== "string") return 0;
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize text by stripping non-alphanumeric characters, lowercasing, and trimming.
|
||||
* Optionally cleans the title first using cleanTitle.
|
||||
* @param {string} value - The text to normalize.
|
||||
* @param {boolean} [cleanFirst=false] - Whether to run cleanTitle before normalizing.
|
||||
* @returns {string} Normalized lowercase text.
|
||||
*/
|
||||
static normalizeText(value, cleanFirst = false) {
|
||||
let text = String(value ?? "");
|
||||
if (cleanFirst) text = this.cleanTitle(text);
|
||||
return text
|
||||
.normalize("NFKD")
|
||||
.replace(/[^\w\s]+/g, " ")
|
||||
.replace(/\s+/g, " ")
|
||||
.trim()
|
||||
.toLowerCase();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* @module src/utils/mixins
|
||||
* @description Minimal mixin helper used to split large classes across
|
||||
* multiple files while keeping a single runtime class and public API.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copy the methods of each mixin onto the target class prototype.
|
||||
*
|
||||
* Use this when a class has grown across many concerns (playback, search,
|
||||
* display, …): define each concern as a plain object of methods in its own
|
||||
* module and apply them onto the class. All methods share the same `this`,
|
||||
* so behaviour is identical to a single-file class.
|
||||
*
|
||||
* Rules:
|
||||
* - Methods defined directly on the base class always win (never overridden).
|
||||
* - Later mixins override earlier mixins for the same method name.
|
||||
*
|
||||
* @param {Function} target - The base class to extend.
|
||||
* @param {...object} mixins - Objects of instance methods.
|
||||
* @returns {Function} The target class (for chaining).
|
||||
*/
|
||||
export function applyMixins(target, ...mixins) {
|
||||
const baseOwned = new Set(Object.getOwnPropertyNames(target.prototype));
|
||||
for (const mixin of mixins) {
|
||||
for (const [name, value] of Object.entries(mixin)) {
|
||||
if (typeof value !== "function") continue;
|
||||
if (baseOwned.has(name)) continue;
|
||||
target.prototype[name] = value;
|
||||
}
|
||||
}
|
||||
return target;
|
||||
}
|
||||
Reference in new issue
Block a user