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:
NoLogicAlan committed 2026-09-09 02:04:33 +03:00
1 parent 0f085a6ae4
commit 253d11cd57
150 files changed
+19935 -16894

No files matched your search

+620
View File
@@ -0,0 +1,620 @@
/** @module src/music/LavalinkManager @description Manages Lavalink/NodeLink connection, voice forwarding, and audio search functionality. */
import { LavalinkManager as LavalinkClientManager, NodeType } from "lavalink-client";
import { logger, _wsErrorCooldown } from "../core/Logger.mjs";
import { EventEmitter } from "node:events";
import { Events } from "@fluxerjs/core";
import { getVoiceManager } from "@fluxerjs/voice";
import * as ShardingUtils from "../utils/ShardingUtils.mjs";
/** @class LavalinkManager @description Manages Lavalink/NodeLink connection, voice forwarding, and audio search functionality. Wraps the lavalink-client library and provides node lifecycle management, search, player creation, and WebSocket payload interception. @extends {EventEmitter} */
export class LavalinkManager extends EventEmitter {
/** @type {LavalinkClientManager} @description The underlying lavalink-client manager instance. */
lavalink = null;
/** @type {string|null} @description Current Lavalink session ID. */
_sessionId = null;
/** @type {object} @description Bot client reference. */
_client = null;
/** @type {object} @description Node configuration (id, host, port, password, secure). */
_nodeCfg = null;
/** @type {boolean} @description Whether a node is currently connected. */
_nodeConnected = false;
/** @private @type {Set<string>} @description Guild IDs with pending leave requests. */
_pendingLeaves = new Set();
/** @private @type {Map<string, object>} @description Cached VOICE_SERVER_UPDATE payloads keyed by guild ID. */
_cachedVoiceServerUpdates = new Map();
/** Create a new LavalinkManager and initialize the underlying lavalink-client connection. @param {object} nodeCfg - Node configuration (id, host, port, password, secure). @param {object} client - bot client instance. @param {object} user - Bot user object with id and username. */
constructor(nodeCfg, client, user) {
super();
this.setMaxListeners(50);
this._nodeCfg = nodeCfg;
this._client = client;
const requestSignalTimeoutMS = Number(nodeCfg.requestTimeout ?? 60_000);
this.lavalink = new LavalinkClientManager({
nodes: [
{
id: nodeCfg.id ?? "main",
host: nodeCfg.host ?? "localhost",
port: nodeCfg.port ?? 2333,
authorization:nodeCfg.password ?? "youshallnotpass",
secure: nodeCfg.secure ?? false,
nodeType: NodeType.NodeLink,
requestSignalTimeoutMS: Number.isFinite(requestSignalTimeoutMS) ? requestSignalTimeoutMS : 60_000,
},
],
client: {
id: user?.id ?? "0",
username: user?.username ?? "bot",
},
sendToShard: (guildId, payload) => {
this._sendPayload(guildId, payload);
},
autoSkip: true,
playerOptions: {
volumeDecrementer: 1,
},
});
this._setupVoiceForwarding(client);
this._setupLavalinkEvents();
}
/** @private Set up internal Lavalink event forwarding (node connect/disconnect/error, track events). */
_setupLavalinkEvents() {
const nodeMgr = this.lavalink.nodeManager ?? this.lavalink.nodes;
if (nodeMgr) {
try {
nodeMgr.on("error", (node, err) => {
logger.error("[Lavalink] NodeManager error:", node?.id, err?.message ?? err);
});
nodeMgr.on("connect", (node) => {
this._nodeConnected = true;
logger.lavalink("[Lavalink] Node connected (nodeManager): " + node.id);
});
nodeMgr.on("disconnect", (node, reason) => {
this._nodeConnected = false;
logger.warn("[Lavalink] Node disconnected (nodeManager):", node?.id, reason);
});
nodeMgr.on("reconnect", (node) => {
this._nodeConnected = true;
logger.lavalink("[Lavalink] Node reconnecting (nodeManager): " + node.id);
});
} catch (e) {
logger.warn("[Lavalink] nodeManager event setup error:", e?.message);
}
} else {
logger.warn("[Lavalink] Neither nodeManager nor nodes found on lavalink-client instance");
}
this.lavalink.on("nodeConnect", (node) => {
this._nodeConnected = true;
logger.lavalink("[Lavalink] Node connected (manager): " + node.id);
});
this.lavalink.on("nodeReconnect", (node) => {
this._nodeConnected = true;
logger.lavalink("[Lavalink] Node reconnecting (manager): " + node.id);
});
this.lavalink.on("nodeDisconnect", (node, reason) => {
this._nodeConnected = false;
logger.warn("[Lavalink] Node disconnected (manager):", node.id, reason);
});
this.lavalink.on("nodeError", (node, err) => {
logger.error("[Lavalink] Node error (manager):", node.id, err?.message ?? err);
});
this.lavalink.on("playerCreate", (player) => {
logger.lavalink(`[Lavalink] Player created: ${player.guildId}`);
});
this.lavalink.on("playerDestroy", (player) => {
logger.lavalink(`[Lavalink] Player destroyed: ${player.guildId}`);
});
this.lavalink.on("trackStart", (player, track) => {
this.emit("trackStart", player, track);
});
this.lavalink.on("trackEnd", (player, track, payload) => {
const reason = payload?.reason ?? "FINISHED";
this.emit("trackEnd", player, track, reason);
});
this.lavalink.on("queueEnd", (player) => {
this.emit("queueEnd", player);
});
this.lavalink.on("playerDisconnect", (player) => {
this.emit("playerDisconnected", player);
});
this.lavalink.on("playerMove", (player, oldChannelId, newChannelId) => {
logger.lavalink(
`[Lavalink] Player moved in ${player.guildId}: ${oldChannelId} → ${newChannelId}`
);
});
}
/** @private Intercept and forward gateway payloads to Lavalink. Blocks op4 voice joins (handled by vm.join). */
_sendPayload(guildId, payload) {
try {
if (payload?.op === 4 && payload?.d) {
const d = payload.d;
const channelId = d.channel_id;
if (channelId) {
logger.lavalink(
"[LavalinkManager] sendToShard op4 join BLOCKED — voice joins go through vm.join() in Player.join()"
);
return;
} else {
const guildKey = String(guildId);
if (!this._pendingLeaves.has(guildKey)) {
logger.lavalink("[LavalinkManager] sendToShard op4 leave BLOCKED — no explicit leave request for guild " + guildKey);
return;
}
this._pendingLeaves.delete(guildKey);
const vm = getVoiceManager(this._client);
if (vm) {
logger.lavalink("[LavalinkManager] sendToShard op4: routing voice leave via vm.leaveChannel");
try {
const player = this.lavalink?.players?.get?.(guildKey);
const chId = player?.voiceChannelId;
if (chId) {
vm.leaveChannel(chId);
}
return;
} catch (e) {
logger.warn("[LavalinkManager] vm.leaveChannel failed:", e.message);
}
}
}
}
// Fluxer 3.0 sharding: gateway payloads are guild-scoped — route to the
// shard that owns this guild (single process: always shard 0, as before).
const targetShardId = ShardingUtils.shardIdForGuild(this._client, guildId);
if (typeof this._client?.ws?.send === "function") {
this._client.ws.send(targetShardId, payload);
return;
}
const shard = ShardingUtils.getShard(this._client, targetShardId);
if (!shard) {
logger.warn("[LavalinkManager] No WebSocket shard available");
return;
}
if (typeof shard.send === "function") {
shard.send(payload);
} else if (shard.ws?.send) {
shard.ws.send(JSON.stringify(payload));
} else {
logger.warn("[LavalinkManager] Cannot send - no valid send method found");
}
} catch (e) {
logger.warn("[LavalinkManager] Send error:", e.message);
}
}
/** @private Attach raw WebSocket listeners to cache VOICE_SERVER_UPDATE events and handle errors. */
_setupVoiceForwarding(client) {
const attachRawWs = () => {
try {
// Fluxer 3.0 + sharding: getShards() replaces the 2.2 `shards` Map
// property, and a sharded child owns several shards — track the raw
// socket of EVERY local shard, not just shard 0.
const wsObjs = ShardingUtils.localShardSockets(client);
if (wsObjs.length === 0) return;
if (!this._rawWsObjs) this._rawWsObjs = new Set();
const attached = this._rawWsObjs;
// Detach listeners from sockets that went away (reconnects).
for (const old of attached) {
if (wsObjs.includes(old)) continue;
try {
if (typeof old.removeEventListener === "function") {
old.removeEventListener(
"message",
this._rawWsMessageListener ?? this._rawWsHandler
);
old.removeEventListener("error", this._rawWsErrorHandler);
} else if (typeof old.off === "function") {
old.off(
"message",
this._rawWsMessageListener ?? this._rawWsHandler
);
old.off("error", this._rawWsErrorHandler);
}
} catch (e) {
logger.warn(
"[LavalinkManager] Raw WS listener cleanup:",
e?.message
);
}
attached.delete(old);
}
// Create the shared handlers once (stateless parsers).
if (!this._rawWsHandler) {
const botId = this._client?.user?.id;
let _vsuLogCooldown = 0;
let _vsuBotLogCooldown = 0;
this._rawWsHandler = (rawData) => {
try {
const text = typeof rawData === "string" ? rawData : rawData?.data;
const payload = typeof text === "string" ? JSON.parse(text) : rawData;
if (payload?.t === "VOICE_SERVER_UPDATE") {
if (!payload.d?.guild_id) {
logger.warn(
"[LavalinkManager] VOICE_SERVER_UPDATE: Missing guild_id",
payload
);
return;
}
const guildKey = String(payload.d.guild_id);
const now = Date.now();
logger.lavalink("[LavalinkManager] VOICE_SERVER_UPDATE for guild " + guildKey +
" endpoint=" + (payload.d.endpoint || "none") +
" token=" + (typeof payload.d.token === "string" ? payload.d.token.substring(0, 12) + "..." : "none"));
if (now - _vsuLogCooldown > 5_000) {
_vsuLogCooldown = now;
}
this._cachedVoiceServerUpdates.set(guildKey, payload);
if (this._cachedVoiceServerUpdates.size > 500) {
const oldest = this._cachedVoiceServerUpdates.keys().next().value;
if (oldest !== undefined) this._cachedVoiceServerUpdates.delete(oldest);
}
}
} catch (e) {
logger.warn(
"[LavalinkManager] Raw WS message parse error:",
e?.message
);
}
};
this._rawWsErrorHandler = (errOrEvent) => {
if (typeof errOrEvent?.preventDefault === "function")
errOrEvent.preventDefault();
const err = errOrEvent?.error ?? errOrEvent?.message ?? errOrEvent;
const now = Date.now();
if (now - _wsErrorCooldown.lastLogged < _wsErrorCooldown.COOLDOWN_MS)
return;
_wsErrorCooldown.lastLogged = now;
logger.warn(
"[LavalinkManager] Raw WS socket error (will reconnect):",
err?.message ?? err
);
};
this._rawWsMessageListener = (event) =>
this._rawWsHandler(event?.data ?? event);
}
for (const wsObj of wsObjs) {
if (attached.has(wsObj)) continue;
if (typeof wsObj.addEventListener === "function") {
wsObj.addEventListener("message", this._rawWsMessageListener);
wsObj.addEventListener("error", this._rawWsErrorHandler);
} else if (typeof wsObj.on === "function") {
wsObj.on("message", this._rawWsMessageListener);
wsObj.on("error", this._rawWsErrorHandler);
}
attached.add(wsObj);
}
// Legacy singular field kept in sync (first socket).
this._rawWsObj = wsObjs[0] ?? null;
} catch (e) {
logger.warn("[LavalinkManager] Raw WS setup error:", e.message);
}
};
if (this.lavalink) {
logger.lavalink("[LavalinkManager] lavalink.sendRawData type: " + typeof this.lavalink.sendRawData);
logger.lavalink("[LavalinkManager] lavalink players type: " + typeof this.lavalink.players);
try {
const pSize = this.lavalink.players?.size ?? this.lavalink.players?.length ?? "unknown";
logger.lavalink("[LavalinkManager] lavalink players size: " + pSize);
} catch(_) {}
}
attachRawWs();
client.on(Events.Ready, attachRawWs);
}
/** @private Forward a raw payload to the Lavalink node via sendRawData. */
_forwardToLavalink(payload, guildKey, label) {
try {
if (typeof this.lavalink.sendRawData !== "function") {
logger.error("[LavalinkManager] sendRawData is NOT a function! type=" + typeof this.lavalink.sendRawData);
return;
}
const player = this.lavalink.players?.get?.(guildKey);
logger.lavalink("[LavalinkManager] _forwardToLavalink " + label +
" guild=" + guildKey +
" playerExists=" + !!player +
" playerConnected=" + (player?.connected ?? "noPlayer"));
this.lavalink.sendRawData(payload);
const playerAfter = this.lavalink.players?.get?.(guildKey);
if (playerAfter) {
const vs = playerAfter.voiceServer;
logger.lavalink("[LavalinkManager] After sendRawData(" + label + "):" +
" voiceServer=" + (vs ? "endpoint=" + (vs.endpoint || "none") : "none") +
" connected=" + (playerAfter.connected ?? "undefined"));
} else {
logger.lavalink("[LavalinkManager] After sendRawData(" + label + "): player not found!");
}
} catch (e) {
logger.error("[LavalinkManager] _forwardToLavalink(" + label + ") error:", e.message, e.stack?.substring(0, 200));
}
}
/**
* Replay a cached VOICE_SERVER_UPDATE payload to the Lavalink node.
* @param {string} guildId - The guild ID.
* @returns {boolean} True if a cached update was found and replayed.
*/
replayVoiceServerUpdate(guildId) {
const guildKey = String(guildId);
const cached = this._cachedVoiceServerUpdates.get(guildKey);
if (!cached) {
logger.lavalink("[LavalinkManager] No cached VOICE_SERVER_UPDATE to replay for guild " + guildKey);
return false;
}
try {
logger.lavalink("[LavalinkManager] Replaying cached VOICE_SERVER_UPDATE for guild " + guildKey);
this.lavalink.sendRawData(cached);
return true;
} catch (e) {
logger.warn("[LavalinkManager] Replay VOICE_SERVER_UPDATE error:", e.message);
return false;
}
}
/** @async Initialize the Lavalink connection. Sets up session handling, registers node connect listeners, and warns if the node is unreachable after 3 seconds. @returns {Promise<void>} */
async init() {
this.setMaxListeners(50);
try {
this.lavalink?.setMaxListeners?.(50);
} catch (e) {
logger.warn("[Lavalink] init setMaxListeners:", e?.message);
}
const cfg = this._nodeCfg;
logger.lavalink(
`[Lavalink] Initializing — node: ${cfg?.id ?? "main"} @ ${cfg?.host ?? "localhost"}:${cfg?.port ?? 2333} (secure: ${cfg?.secure ?? false}, type: NodeLink)`
);
try {
this.lavalink.init({
id: this._client?.user?.id ?? "0",
username: this._client?.user?.username ?? "bot",
});
} catch (e) {
logger.warn("[Lavalink] init error:", e?.message);
}
const onNodeConnect = (node) => {
this._nodeConnected = true;
try {
node.updateSession(true, 300_000);
this._sessionId = node.sessionId ?? this._sessionId;
logger.lavalink(
"[Lavalink] Node ready: " + node.id + " | session: " + this._sessionId
);
this.emit("ready", this._sessionId);
} catch (e) {
logger.warn(
"[Lavalink] nodeConnect handler error:",
e?.message
);
}
};
this.lavalink.on("nodeConnect", onNodeConnect);
setTimeout(() => {
if (!this._nodeConnected) {
const h = cfg?.host || "localhost";
const p = cfg?.port || 2333;
logger.warn(
"[Lavalink] Node at " + h + ":" + p + " is NOT connected yet. " +
"Make sure your NodeLink/Lavalink server is running. " +
"The bot will retry when a voice join is attempted."
);
}
}, 3_000);
}
/** @async Search for tracks on the Lavalink node. Tries player-based search first, then falls back to direct node lookup. @param {string} query - The search query string or URL. @param {object} [options] - Search options. @param {string} [options.source] - Lavalink source identifier (e.g. 'ytmsearch'). @param {string} [options.requester] - Requester identifier. @returns {Promise<object>} Lavalink search result with tracks array. @throws {Error} If no connected node is available. */
async search(query, options = {}) {
try {
const players = this.lavalink?.players;
if (players?.size > 0) {
const firstPlayer = players.values?.().next?.().value;
if (firstPlayer?.node) {
logger.lavalink("[Lavalink] search via player.node for guild " + firstPlayer.guildId);
if (options.source) {
return firstPlayer.node.search({ query, source: options.source });
}
return firstPlayer.node.search(query);
}
}
} catch (_) { /* fall through to node-based search */ }
const node = this._getConnectedNode();
if (node) {
logger.lavalink("[Lavalink] search via _getConnectedNode()");
if (options.source) {
return node.search({ query, source: options.source });
}
return node.search(query);
}
try {
const nodes = this.lavalink?.nodes;
const nodeId = this._nodeCfg?.id ?? "main";
const node = nodes?.get?.(nodeId) ?? nodes?.cache?.get?.(nodeId);
if (node) {
logger.lavalink("[Lavalink] search via fallback node.get()");
if (options.source) {
return node.search({ query, source: options.source });
}
return node.search(query);
}
} catch (_) {}
throw new Error("No connected Lavalink node available for search");
}
/** Get the Lavalink player for a guild. @param {string} guildId - The guild ID. @returns {object|null} The Lavalink player, or null if not found. */
getPlayer(guildId) {
return this.lavalink.players.get(String(guildId));
}
/** Close all node WebSocket connections and clean up. */
destroy() {
try {
for (const [id, node] of this.lavalink?.nodes?.cache?.entries?.() ?? []) {
try {
node.socket?.close?.();
} catch (e) {
logger.warn(`[Lavalink] destroy node ${id}:`, e?.message);
}
}
} catch (e) {
logger.warn("[Lavalink] destroy:", e?.message);
}
}
/** Check whether at least one Lavalink node is currently connected. @returns {boolean} */
hasConnectedNode() {
return this._nodeConnected === true;
}
/** @async Wait for a Lavalink node to become connected. Polls at 1-second intervals until connected or timeout. @param {object} [options] - Wait options. @param {number} [options.timeoutMs=15000] - Maximum time to wait in milliseconds. @param {number} [options.intervalMs=1000] - Polling interval in milliseconds. @returns {Promise<void>} Resolves when a node is connected. @throws {Error} If timeout is reached without a connected node. */
waitForNode(options = {}) {
const timeoutMs = options.timeoutMs ?? 15_000;
const intervalMs = options.intervalMs ?? 1_000;
const host = this._nodeCfg?.host || "???";
const port = this._nodeCfg?.port || 2333;
const errMsg =
"[LavalinkManager] No Lavalink node connected after " +
Math.round(timeoutMs / 1000) + "s. " +
"Is your NodeLink/Lavalink server running at " + host + ":" + port + "? " +
"Check: 1) Server is started, 2) Host/port/password are correct in config.json -> nodelink";
return new Promise((resolve, reject) => {
if (this._nodeConnected) return resolve();
let elapsed = 0;
const timer = setInterval(() => {
elapsed += intervalMs;
if (this._nodeConnected) {
clearInterval(timer);
return resolve();
}
if (elapsed >= timeoutMs) {
clearInterval(timer);
reject(new Error(errMsg));
}
}, intervalMs);
timer.unref?.();
});
}
/** @private Get a connected Lavalink node, trying multiple strategies (cache, get, leastUsedNodes, leastLoadNodes). @returns {object|null} A connected node instance, or null if none available. */
_getConnectedNode() {
try {
const nodes = this.lavalink?.nodeManager ?? this.lavalink?.nodes;
if (!nodes) return null;
let store = nodes.cache ?? null;
if (store && typeof store.get === "function" && this._nodeConnected) {
const nodeId = this._nodeCfg?.id ?? "main";
const node = store.get(nodeId);
if (node) return node;
if (store.size > 0) {
const first = store.values?.().next?.().value;
if (first) return first;
}
}
if (typeof nodes.get === "function" && this._nodeConnected) {
const nodeId = this._nodeCfg?.id ?? "main";
const node = nodes.get(nodeId);
if (node) return node;
if (nodes.size > 0) {
const first = nodes.values?.().next?.().value;
if (first) return first;
}
}
if (this._nodeConnected) {
try {
const arr = nodes.leastUsedNodes?.();
if (arr?.length) return arr[0];
} catch (_) {}
try {
const arr = nodes.leastLoadNodes?.();
if (arr?.length) return arr[0];
} catch (_) {}
}
return null;
} catch (e) {
return null;
}
}
/** Get a connected Lavalink node. Public alias for _getConnectedNode. @returns {object|null} A connected node instance, or null. */
getNode() {
return this._getConnectedNode();
}
/** @type {string|null} @description Current Lavalink session ID. */
get sessionId() {
return this._sessionId;
}
/**
* Mark a guild as having a pending leave request so the intercepted op4 leave is allowed through.
* @param {string} guildId - The guild ID.
*/
requestLeave(guildId) {
if (guildId) this._pendingLeaves.add(String(guildId));
}
/** Get connection info for the configured NodeLink node. Useful for health checks and dashboard display. @returns {{host: string, port: number, sessionId: string|null, secure: boolean, password: string}|null} Connection info object, or null if no config. */
getNodeLinkInfo() {
const cfg = this._nodeCfg;
if (!cfg) return null;
return {
host: cfg.host ?? "localhost",
port: cfg.port ?? 2333,
sessionId: this._sessionId ?? null,
secure: cfg.secure ?? false,
password: cfg.password ?? "youshallnotpass",
};
}
}
+298
View File
@@ -0,0 +1,298 @@
/**
* @module src/music/PlayerEventsMixin
* @description Dashboard event wiring concern for {@link PlayerManager}:
* binds dashboard update/queue/message events onto spawned players,
* forwards now-playing updates to Last.fm with scrobble scheduling, and
* translates locale keys for message contexts.
*
* These methods are applied onto the PlayerManager class prototype via
* {@link applyMixins} (see src/music/PlayerManager.mjs) — `this` is a
* PlayerManager instance.
*/
import { cleanId } from "../utils/Utils.mjs";
import { getMessageGuildId } from "../ui/index.mjs";
import { Dashboard } from "../dashboard/Dashboard.mjs";
// Module-level ID helpers from the original PlayerManager.mjs. They live in
// this module (not the base file) because it is the shared leaf of the three
// PlayerManager modules, which keeps the import graph acyclic:
// PlayerManager.mjs → PlayerEventsMixin.mjs ← PlayerLifecycleMixin.mjs.
/** @private @param {Player} player @param {object|null} [fallbackChannel=null] @returns {string} Cleaned guild ID. */
function getPlayerGuildId(player, fallbackChannel = null) {
return cleanId(
player?._guildId ??
fallbackChannel?.guildId ??
fallbackChannel?.guild?.id ??
fallbackChannel?.server_id ??
fallbackChannel?.serverId
);
}
/** @private @param {Player} player @param {string|null} [fallbackChannelId=null] @returns {string} Cleaned channel ID. */
function getPlayerChannelId(player, fallbackChannelId = null) {
return cleanId(player?._channelId ?? player?._home247Channel ?? fallbackChannelId);
}
export { getPlayerGuildId, getPlayerChannelId };
/**
* @type {object}
* @description Player events mixin — applied to PlayerManager.
*/
const PlayerEventsMixin = {
/** Bind dashboard update and message-sending events on a player. @this {import('./PlayerManager.mjs').PlayerManager} @param {Player} player @param {object} [context={}] @returns {Player} The same player, with events bound. */
setupEvents(player, context = {}) {
if (!player || player._dashboardEventsBound) return player;
Object.defineProperty(player, "_dashboardEventsBound", {
value: true,
configurable: true,
enumerable: false,
writable: true,
});
const emit = (type, data) => {
if (!this.dashboard?.enabled) return;
this.dashboard.updatePlayer({ type, data }, player);
};
const emitGlobal = (type) => {
if (!this.dashboard?.enabled) return;
this.dashboard.playerUpdate({ type }, player);
};
const sendUserUpdates = (eventType) => {
if (!this.dashboard?.enabled) return;
const channelId = getPlayerChannelId(player, context.channelId);
const channel = player.client?.channels?.get(channelId);
const guild = player.client?.guilds?.get(cleanId(player._guildId ?? context.guildId));
if (!guild) return;
const voiceStates = guild.voice_states ?? guild.voiceStates ?? null;
if (!voiceStates) return;
const entries = Array.isArray(voiceStates)
? voiceStates
: typeof voiceStates.values === "function"
? [...voiceStates.values()]
: Object.values(voiceStates);
for (const state of entries) {
if (!state?.channelId && !state?.channel_id) continue;
const stateChannelId = cleanId(state.channelId ?? state.channel_id);
if (stateChannelId !== channelId) continue;
const member = guild.members?.get?.(state.userId ?? state.user_id);
if (!member?.user || member.user?.bot) continue;
emit(eventType, member.user.id);
this.dashboard.userUpdate({
type: eventType,
guildId: cleanId(player._guildId ?? context.guildId),
channelId,
}, member.user);
}
};
player.on("roomfetched", () => {
emitGlobal("init");
sendUserUpdates("join");
});
player.on("startplay", (song) => {
emit("startplay", Dashboard.convertVideo(song ?? player.queue?.current));
emit("streamStartPlay", Date.now());
this.dashboard.playerUpdate({ type: "startplay" }, player);
if (this._lastfm?.enabled && song) {
this._handleLastFmStartPlay(player, song);
}
});
player.on("stopplay", () => {
emit("stopplay", null);
this.dashboard.playerUpdate({ type: "stopplay" }, player);
});
player.on("playback", (playing) => {
const elapsedMs = player._pausedAt
? (player._pausedAt.getTime?.() ?? Number(player._pausedAt)) -
(player.startedPlaying?.getTime?.() ?? Number(player.startedPlaying ?? 0))
: Date.now() - (player.startedPlaying?.getTime?.() ?? Number(player.startedPlaying ?? 0));
const type = playing ? "resume" : "pause";
emit(type, { elapsedTime: Math.max(0, elapsedMs) });
this.dashboard.playerUpdate({ type }, player);
});
player.on("volume", (volume) => {
emit("volume", volume);
this.dashboard.playerUpdate({ type: "volume" }, player);
});
player.on("filter", (filter) => {
emit("filter", filter);
});
player.on("update", (scope) => {
this.dashboard.playerUpdate({ type: "update" }, player);
});
player.on("autoleave", () => {
sendUserUpdates("leave");
emitGlobal("close");
emit("stopplay", null);
});
player.on("leave", () => {
sendUserUpdates("leave");
emitGlobal("close");
emit("stopplay", null);
});
player.queue?.on("queue", (queueEvent) => {
const serialised = { type: queueEvent.type };
switch (queueEvent.type) {
case "add":
serialised.data = {
append: queueEvent.data?.append,
data: Dashboard.convertVideo(queueEvent.data?.data),
};
break;
case "addMany":
serialised.data = {
append: queueEvent.data?.append,
tracks: (queueEvent.data?.tracks ?? []).map(v => Dashboard.convertVideo(v)),
};
break;
case "remove":
serialised.data = {
index: queueEvent.data?.index,
removed: Dashboard.convertVideo(queueEvent.data?.removed),
old: (queueEvent.data?.old ?? []).map(v => Dashboard.convertVideo(v)),
new: (queueEvent.data?.new ?? []).map(v => Dashboard.convertVideo(v)),
};
break;
case "move":
serialised.data = {
from: queueEvent.data?.from,
to: queueEvent.data?.to,
track: Dashboard.convertVideo(queueEvent.data?.track),
};
break;
case "shuffle":
serialised.data = (queueEvent.data ?? []).map(v => Dashboard.convertVideo(v));
break;
case "update":
serialised.data = {
current: Dashboard.convertVideo(queueEvent.data?.current),
old: Dashboard.convertVideo(queueEvent.data?.old),
loop: queueEvent.data?.loop,
};
break;
default:
serialised.data = queueEvent.data;
break;
}
emit("queue", serialised);
this.dashboard.playerUpdate({ type: "queue" }, player);
});
return player;
},
/** @private Translate a locale key for a message context. @this {import('./PlayerManager.mjs').PlayerManager} @param {object} message @param {string} key @param {object} [replacements={}] @returns {string} */
_t(message, key, replacements = {}) {
if (!this.locale) return key;
const guildId = getMessageGuildId(message);
return this.locale.translate(guildId, key, replacements);
},
/** @private Handle Last.fm now-playing update and schedule scrobble timer. @this {import('./PlayerManager.mjs').PlayerManager} @param {Player} player @param {object} song */
_handleLastFmStartPlay(player, song) {
const lastfm = this._lastfm;
if (!lastfm?.enabled) return;
const guildId = cleanId(player._guildId);
if (!guildId) return;
const channelId = getPlayerChannelId(player);
const humanUserIds = [];
if (this.voiceCache) {
const users = this.voiceCache.getHumansInChannel(guildId, channelId);
humanUserIds.push(...users);
} else if (this.observedVoiceUsers) {
for (const [uid, info] of this.observedVoiceUsers) {
if (cleanId(info.guildId) === guildId && cleanId(info.channelId) === channelId) {
humanUserIds.push(uid);
}
}
}
const guild = player.client?.guilds?.get(guildId);
if (guild) {
const voiceStates = guild.voice_states ?? guild.voiceStates ?? null;
if (voiceStates) {
const entries = Array.isArray(voiceStates)
? voiceStates
: typeof voiceStates.values === "function"
? [...voiceStates.values()]
: Object.values(voiceStates ?? {});
for (const state of entries) {
const uid = state?.userId ?? state?.user_id;
const chId = cleanId(state?.channelId ?? state?.channel_id);
if (uid && chId === channelId) {
const member = guild.members?.get?.(uid);
if (member?.user?.bot) continue;
if (!humanUserIds.includes(uid)) humanUserIds.push(uid);
}
}
}
}
const startedAtMs = player.startedPlaying;
const pendingKey = channelId;
const existing = this._pendingScrobbleTimers.get(pendingKey);
if (existing) {
clearTimeout(existing.timer);
this._pendingScrobbleTimers.delete(pendingKey);
}
for (const userId of humanUserIds) {
lastfm.updateNowPlaying(userId, song).catch(() => {});
}
const durationMs = (() => {
const d = song.duration;
if (!d) return null;
if (typeof d === "object" && d.seconds) return d.seconds * 1000;
if (typeof d === "number") return d;
return null;
})();
if (durationMs && durationMs >= 30_000) {
const thresholdMs = Math.min(
durationMs * lastfm.scrobbleThreshold,
lastfm.scrobbleMinMs
);
if (thresholdMs <= 600_000) {
const timer = setTimeout(() => {
this._pendingScrobbleTimers.delete(pendingKey);
const current = player.queue?.getCurrent();
if (!current || player._destroyed || player.leaving) return;
if (current.title !== song.title || current.url !== song.url) return;
if (player._paused) return;
const playedMs = Date.now() - (player.startedPlaying ?? startedAtMs ?? Date.now());
if (lastfm.shouldScrobble(song, playedMs)) {
for (const userId of humanUserIds) {
lastfm.scrobble(userId, song, startedAtMs).catch(() => {});
}
}
}, thresholdMs);
this._pendingScrobbleTimers.set(pendingKey, { timer, songUrl: song.url, startedAtMs });
}
}
},
};
export default PlayerEventsMixin;
export { PlayerEventsMixin };
+560
View File
@@ -0,0 +1,560 @@
/**
* @module src/music/PlayerLifecycleMixin
* @description Voice-channel resolution & player lifecycle concern for
* {@link PlayerManager}: author voice-channel detection, interactive
* voice-channel selection prompt, leave, saved-volume restore, and
* spawn/join of Player instances (including join retries and the autoleave
* / now-playing announcement handlers wired inside initPlayer).
*
* These methods are applied onto the PlayerManager class prototype via
* {@link applyMixins} (see src/music/PlayerManager.mjs) — `this` is a
* PlayerManager instance.
*/
import Player from "./player/index.mjs";
import { cleanId } from "../utils/Utils.mjs";
import { logger } from "../core/Logger.mjs";
import { get247ChannelMode } from "../utils/Helpers247.mjs";
import { EmbedBuilder, PermissionFlags } from "@fluxerjs/core";
import { getVoiceManager } from "@fluxerjs/voice";
import { getGlobalColor, getMessageGuildId } from "../ui/index.mjs";
import { hasHumansInChannel, iterateVoiceStates } from "../voice/VoiceStateResolver.mjs";
import { getPlayerChannelId } from "./PlayerEventsMixin.mjs";
// Module-level join/permission helpers from the original PlayerManager.mjs
// (only initPlayer below uses them, so they stay private to this module).
/** @private Check whether the bot has required voice permissions in a channel. @param {object} client @param {string} channelId @returns {boolean} True if the bot can connect, speak, and use VAD. */
function botHasVoicePermissions(client, channelId) {
try {
const channel = client?.channels?.get?.(channelId);
if (!channel) return true;
const me = channel.guild?.members?.me;
if (!me) return true;
const perms = me.permissionsIn?.(channel);
if (!perms) return true;
if (perms.has(PermissionFlags.Administrator)) return true;
return perms.has(PermissionFlags.Connect)
&& perms.has(PermissionFlags.Speak)
&& perms.has(PermissionFlags.UseVad);
} catch (e) {
logger.warn("[PlayerManager] botHasVoicePermissions check failed:", e?.message);
return true;
}
}
/** @private Classify a join error into a known error code for user-facing messages. @param {Error} err @param {object} [client=null] @param {string} [channelId=null] @returns {string|null} Error code ('PERMISSION'|'NOT_FOUND'|'TIMEOUT'|'SESSION_RACE') or null. */
function sanitizeJoinError(err, client = null, channelId = null) {
const msg = String(err?.message ?? err ?? "");
if (msg.includes("401") || msg.includes("Unauthorized")) {
if (client && channelId && !botHasVoicePermissions(client, channelId)) {
return "PERMISSION";
}
return "SESSION_RACE";
}
if (msg.includes("permission") || msg.includes("Permission")) {
if (client && channelId && !botHasVoicePermissions(client, channelId)) {
return "PERMISSION";
}
return "SESSION_RACE";
}
if (msg.includes("not found") || msg.includes("Unknown channel")) {
return "NOT_FOUND";
}
if (msg.includes("timeout") || msg.includes("timed out")) {
return "TIMEOUT";
}
return null;
}
/**
* @type {object}
* @description Player lifecycle mixin — applied to PlayerManager.
*/
const PlayerLifecycleMixin = {
/** Detect which voice channel the message author is in. @async @this {import('./PlayerManager.mjs').PlayerManager} @param {object} message @param {object} settings @returns {Promise<{channelId: string|null, alreadyInVoice: boolean, hasHumans: boolean}>} */
async checkVoiceChannels(message, settings) {
const guildId = message?.guildId ?? message?.channel?.guildId ?? getMessageGuildId(message);
const userId = message?.author?.id ?? message?.member?.user?.id;
const cleanGuildId = cleanId(guildId);
if (!guildId || !userId) return { channelId: null, alreadyInVoice: false, hasHumans: false };
const guild = this.commands?.client?.guilds?.get?.(cleanGuildId);
if (this.voiceCache) {
const observed = this.voiceCache.getUserLocation(cleanGuildId, userId);
if (observed && observed.channelId) {
const alreadyInVoice = this.playerMap.has(cleanId(observed.channelId));
const hasHumans = this.voiceCache.hasHumansInChannel(cleanGuildId, cleanId(observed.channelId));
return { channelId: observed.channelId, alreadyInVoice, hasHumans };
}
}
let channelId = message?.member?.voice?.channelId ?? null;
if (!channelId && guild) {
for (const vs of iterateVoiceStates(guild)) {
if (vs.userId === String(userId) && !vs.isBot) {
channelId = vs.channelId;
break;
}
}
}
if (!channelId) {
try {
const vm = getVoiceManager(this.commands?.client);
channelId = vm?.getVoiceChannelId?.(guildId, userId) ?? null;
} catch (e) {
logger.warn("[PlayerManager] VoiceManager lookup failed:", e?.message);
}
}
if (!channelId && this.voiceCache) {
const loc = this.voiceCache.getHumanUser(userId);
if (loc && cleanId(loc.guildId) === cleanGuildId) {
channelId = loc.channelId;
}
}
if (!channelId) return { channelId: null, alreadyInVoice: false, hasHumans: false };
const alreadyInVoice = this.playerMap.has(cleanId(channelId));
const hasHumansResult = hasHumansInChannel({
guildId: cleanGuildId,
channelId: cleanId(channelId),
client: this.commands?.client,
voiceCache: this.voiceCache,
observedVoiceUsers: this.observedVoiceUsers,
room: this.playerMap.get(cleanId(channelId))?.connection?.room,
botId: this.commands?.client?.user?.id,
});
return { channelId, alreadyInVoice, hasHumans: hasHumansResult };
},
/** Prompt the user to select a voice channel via reactions or text input. @async @this {import('./PlayerManager.mjs').PlayerManager} @param {object} msg @returns {Promise<Player|false>} */
async promptVC(msg) {
const { channelId: autoDetected } = await this.checkVoiceChannels(msg);
if (autoDetected) {
return this.initPlayer(msg, autoDetected);
}
const guildId = getMessageGuildId(msg);
const cleanGuildId = cleanId(guildId);
const allChannels = cleanGuildId
? [...(this.commands.client?.channels?.values?.() ?? [])]
.filter(c => {
const channelGuildId = cleanId(c.guildId ?? c.guild?.id ?? c.server_id ?? c.serverId);
const isVoice = c.type === 2;
return channelGuildId === cleanGuildId && isVoice;
})
: [];
const reactions = ["1️⃣","2️⃣","3️⃣","4️⃣","5️⃣","6️⃣","7️⃣","8️⃣","9️⃣"];
const channelArr = allChannels.slice(0, 9);
let channelSelection = "";
if (channelArr.length > 0) {
channelSelection = this._t(msg, "responses._common.voiceSelectionPrompt") + "\n\n";
channelArr.forEach((c, i) => { channelSelection += `${i + 1}. <#${c._id ?? c.id}>\n`; });
}
const hint = this._t(msg, "responses._common.voiceSelectionHint");
const selectionMsg = await msg.reply(
(channelSelection ? channelSelection + "\n**..or** " + hint : "Please " + hint)
);
return new Promise(resolve => {
let unsubscribeReactions;
let unsubscribeMessages;
const promptUser = msg.author ?? msg.message?.author ?? null;
const cleanup = () => {
unsubscribeMessages?.();
unsubscribeReactions?.();
};
const timeout = setTimeout(() => {
cleanup();
msg.reply(this._t(msg, "responses._common.voiceSelectionTimedOut"));
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).then(p => resolve(p));
},
promptUser
);
}
unsubscribeMessages = msg.channel.onMessageUser((m) => {
const content = m.content?.toLowerCase() ?? "";
if (content === "x") {
clearTimeout(timeout);
cleanup();
m.reply(this._t(m, "voice.join.cancelled"));
resolve(false);
return;
}
if (!this.commands.validateInput("voiceChannel", m.content, m)) {
m.reply(this._t(m, "responses._common.voiceSelectionInvalid"));
return;
}
const channel = this.commands.formatInput("voiceChannel", m.content, m);
clearTimeout(timeout);
cleanup();
this.initPlayer(m, channel).then(p => resolve(p));
}, promptUser);
});
},
/** Leave a voice channel, destroy the player, and send a confirmation. @async @this {import('./PlayerManager.mjs').PlayerManager} @param {object} msg @param {string} [cid] @returns {Promise<void>} */
async leave(msg, cid) {
if (!cid) {
const guildId = getMessageGuildId(msg);
if (guildId) {
const guildPlayers = this.getGuildPlayers(cleanId(guildId));
if (guildPlayers.length > 0) {
const [, firstPlayer] = guildPlayers[0];
cid = getPlayerChannelId(firstPlayer, guildPlayers[0][0]) || guildPlayers[0][0];
}
}
}
const cleanChannelId = cleanId(cid);
const player = cleanChannelId
? this.playerMap.get(cleanChannelId) ??
this.getPlayerByChannelId(cleanChannelId)
: null;
if (!player) return msg.reply(this._t(msg, "responses._common.notInVoice"));
const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId;
this.playerMap.delete(activeChannelId);
this._unindexPlayer(player._guildId, activeChannelId);
const pendingScrobble = this._pendingScrobbleTimers.get(activeChannelId);
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this._pendingScrobbleTimers.delete(activeChannelId); }
if (activeChannelId !== cleanChannelId) this.playerMap.delete(cleanChannelId);
try {
await player.leave();
} catch (e) {
logger.warn("[PlayerManager] leave() error (non-fatal):", e.message);
}
player.destroy();
await msg.reply(this._t(msg, "responses._common.successfullyLeft"));
},
/** @private Restore saved volume for a player from guild settings. @this {import('./PlayerManager.mjs').PlayerManager} @param {Player} player @param {string} guildId */
_restorePlayerVolume(player, guildId) {
const savedVol = this.settings?.getServer?.(guildId)?.get?.("volume");
if (savedVol !== undefined && savedVol !== null) {
const vol = Number(savedVol);
if (!isNaN(vol)) player.setVolume(vol / 100);
}
},
/** Create a new Player, join the voice channel, and set up events. @async @this {import('./PlayerManager.mjs').PlayerManager} @param {object} message @param {string} cid @returns {Promise<Player|null>} The spawned player, or null on failure. */
async initPlayer(message, cid) {
const channel = this.commands.client?.channels?.get(cid);
if (!channel) {
message.reply(
this._t(message, "responses.join.channelNotFound", { channel: cid })
);
return null;
}
const isVoice = channel.type === 2;
if (!isVoice) {
message.reply(this._t(message, "responses._common.voiceChannelRequired"));
return null;
}
if (!botHasVoicePermissions(this.commands?.client, cid)) {
message.reply(
this._t(message, "responses.join.joinFailedPerms", { channel: `<#${cleanId(cid)}>` })
);
return null;
}
const cleanChannelId = cleanId(cid);
const existing = this.playerMap.get(cleanChannelId)
?? this.getPlayerByChannelId(cleanChannelId);
if (existing) {
existing.textChannel = message.channel?.channel ?? message.channel;
try {
const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null;
const existingGuildId = getMessageGuildId(message);
if (existingGuildId && textChannelId) {
this.settings.getServer(existingGuildId)?.set("announcementChannelId", textChannelId);
}
} catch(e) {
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
}
message.reply(this._t(message, "responses.join.alreadyJoined", { channel: cid }));
return existing;
}
if (this._pendingJoins.has(cleanChannelId)) {
message.reply(this._t(message, "responses.join.joining"));
return null;
}
this._pendingJoins.add(cleanChannelId);
const player = new Player(this.config.token, {
...this.playerConfig,
client: this.commands.client,
config: this.config,
lavalink: this.playerConfig?.lavalink ?? null,
settingsMgr: this.settings,
getPrefix: (guildId) => this.commands.getPrefix(guildId),
observedVoiceUsers: this.observedVoiceUsers ?? null,
voiceCache: this.voiceCache ?? null,
locale: this.locale ?? null,
trackOptions: this.trackOptions ?? null,
});
player.textChannel = message.channel?.channel ?? message.channel;
try {
const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null;
const newGuildId = getMessageGuildId(message);
if (newGuildId && textChannelId) {
this.settings.getServer(newGuildId)?.set("announcementChannelId", textChannelId);
}
} catch(e) {
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
}
this.setupEvents(player, {
channelId: cleanChannelId,
guildId: cleanId(channel.guildId ?? getMessageGuildId(message)),
});
player.on("autoleave", () => {
const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId;
const homeChannelId = cleanId(player._home247Channel) || activeChannelId;
const ch = player.textChannel;
const guildId = cleanId(player._guildId ?? ch?.guildId ?? ch?.guild?.id ?? getMessageGuildId({ channel: ch }));
const raw247 = (() => {
try { return this.settings.getServer(guildId)?.get("stay_247"); } catch (e) { logger.warn("[PlayerManager] Failed to read 24/7 setting:", e?.message); return null; }
})();
const isIn247List = (() => {
if (!raw247 || raw247 === "none") return false;
const channels = Array.isArray(raw247)
? raw247.map(id => cleanId(id)).filter(Boolean)
: [cleanId(raw247)].filter(Boolean);
return channels.includes(homeChannelId) || channels.includes(activeChannelId);
})();
const matchChannel = isIn247List
? (channels247list => channels247list.includes(homeChannelId) ? homeChannelId : activeChannelId)(
Array.isArray(raw247) ? raw247.map(id => cleanId(id)) : [cleanId(raw247)]
)
: null;
const mode247 = matchChannel
? get247ChannelMode(this.settings.getServer(guildId), matchChannel)
: "off";
if (mode247 === "on") {
logger.inactivity(`[PlayerManager] autoleave suppressed for 24/7 channel ${activeChannelId} (guild ${guildId})`);
return;
}
if (player._hasHumansInChannel()) {
logger.inactivity(`[PlayerManager] autoleave suppressed — humans still in channel ${activeChannelId} (guild ${guildId})`);
return;
}
if (player.queue?.getCurrent() || !player.queue?.isEmpty()) {
logger.inactivity(`[PlayerManager] autoleave suppressed — queue has songs in channel ${activeChannelId} (guild ${guildId})`);
return;
}
this.playerMap.delete(activeChannelId);
this._unindexPlayer(player._guildId, activeChannelId);
const pendingScrobble = this._pendingScrobbleTimers.get(activeChannelId);
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this._pendingScrobbleTimers.delete(activeChannelId); }
if (activeChannelId !== cleanChannelId) this.playerMap.delete(cleanChannelId);
if (homeChannelId !== activeChannelId) this.playerMap.delete(homeChannelId);
player.destroy();
const prefix = this.commands.getPrefix(guildId);
const desc = this.locale?.translate(guildId, "responses.join.autoLeaveInactive", { channel: activeChannelId, prefix })
?? `Left channel <#${activeChannelId}> because of inactivity.\nIf you want me to stay in voice, use \`${prefix}247\``;
const autoleaveChMgr = this.commands?.client?.channels ?? null;
let leaveCh = (ch && typeof ch === "object" && typeof ch.send !== "function" && ch.id &&
autoleaveChMgr && typeof autoleaveChMgr.send === "function")
? (() => { const t = { id: ch.id, type: ch.type }; t.send = (o) => autoleaveChMgr.send(ch.id, o); return t; })()
: ch;
if (typeof leaveCh?.send === "function") {
leaveCh.send({ embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)], allowedMentions: { parse: [] } }).catch(err => {
if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) {
logger.warn(`[PlayerManager] Cannot send autoleave message in channel ${leaveCh.id} — missing permissions`);
}
});
}
});
player.on("message", (m) => {
const unwrapChannel = (c) =>
(c && typeof c === "object" && c.channel && typeof c.channel === "object") ? c.channel : c;
const chMgr = this.commands?.client?.channels ?? null;
const canPostById = (c) => !!c?.id && !!chMgr && typeof chMgr.send === "function";
const asSendable = (c) => {
if (!c || typeof c === "string" || typeof c.send === "function") return c;
if (!canPostById(c)) return c;
const target = { id: c.id, type: c.type };
target.isTextBased = () => true;
target.send = (options) => chMgr.send(c.id, options);
return target;
};
const isTextChannel = (c) => {
c = unwrapChannel(c);
if (!c) return false;
if (c.type === undefined || c.type === null) return false;
const voiceTypes = [2, 13, "GUILD_VOICE", "GUILD_STAGE_VOICE", "STAGE", "voice", "stage"];
if (voiceTypes.includes(c.type)) return canPostById(c);
if (typeof c.isTextBased === "function") return c.isTextBased();
const textTypes = [0, 5, 10, 11, 12, "GUILD_TEXT", "GUILD_ANNOUNCEMENT", "text"];
if (textTypes.includes(c.type)) return true;
logger.warn(`[PlayerManager] isTextChannel: unknown channel type=${c.type} id=${c.id}, rejecting`);
return false;
};
let ch = asSendable(unwrapChannel(player.textChannel));
const guildId = cleanId(player._guildId ?? ch?.guildId ?? ch?.guild?.id ?? getMessageGuildId({ channel: ch }));
const raw = this.settings.getServer(guildId)?.get("songAnnouncements");
const disabled = raw === false || raw === 0 ||
["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim());
if (disabled) return;
if (!isTextChannel(ch)) {
try {
const serverSettings = this.settings.getServer(guildId);
const savedAnnChId = serverSettings?.get?.("announcementChannelId");
if (savedAnnChId) {
const resolved = this.commands?.client?.channels?.get?.(cleanId(savedAnnChId)) ?? null;
if (isTextChannel(resolved)) ch = asSendable(resolved);
}
} catch(e) {
logger.warn("[PlayerManager] Failed to resolve announcement channel:", e?.message);
}
}
if (!isTextChannel(ch)) {
try {
const guild = this.commands?.client?.guilds?.get?.(guildId);
if (guild?.systemChannelId) {
const resolved = guild.channels?.get?.(guild.systemChannelId) ?? null;
if (isTextChannel(resolved)) ch = asSendable(resolved);
}
} catch(e) {
logger.warn("[PlayerManager] Failed to resolve system channel:", e?.message);
}
}
if (!isTextChannel(ch)) {
try {
const guild = this.commands?.client?.guilds?.get?.(guildId);
if (guild?.channels) {
for (const c of (guild.channels.values?.() ?? [])) {
if (isTextChannel(c)) {
ch = asSendable(c);
break;
}
}
}
} catch(e) {
logger.warn("[PlayerManager] Failed to find fallback text channel:", e?.message);
}
}
if (!isTextChannel(ch)) {
logger.warn(`[PlayerManager] Could not resolve any text channel to send now-playing announcement (guild ${guildId})`);
return;
}
if (!player.textChannel || !isTextChannel(player.textChannel)) player.textChannel = ch;
const payload = typeof m === "object" && Array.isArray(m.embeds)
? { ...m, allowedMentions: { parse: [] } }
: { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(m)], allowedMentions: { parse: [] } };
ch = asSendable(ch);
ch.send(payload).catch(err => {
if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) {
logger.warn(`[PlayerManager] Cannot send player message in channel ${ch.id} — missing permissions`);
} else {
logger.warn(`[PlayerManager] Failed to send player message in channel ${ch.id}:`, err?.message ?? err);
}
});
});
const statusMsg = await message.reply(this._t(message, "responses.join.joining"));
try {
await player.join(cid);
this.playerMap.set(cleanChannelId, player);
this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
this._pendingJoins.delete(cleanChannelId);
await statusMsg.edit(this._t(message, "responses.join.joined", { channel: cid }));
const guildId = cleanId(channel.guildId ?? getMessageGuildId(message));
this._restorePlayerVolume(player, guildId);
return player;
} catch (err) {
this._pendingJoins.delete(cleanChannelId);
const errCode = sanitizeJoinError(err, this.commands?.client, cleanChannelId);
let errorMsg;
if (errCode === "SESSION_RACE") {
logger.warn(`[PlayerManager] Stale voice session detected for channel ${cleanChannelId}, retrying in 2s...`);
try {
await new Promise(r => setTimeout(r, 2_000));
await player.join(cid);
this.playerMap.set(cleanChannelId, player);
this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
await statusMsg.edit(this._t(message, "responses.join.joined", { channel: cid }));
const retryGuildId = cleanId(channel.guildId ?? getMessageGuildId(message));
this._restorePlayerVolume(player, retryGuildId);
return player;
} catch (retryErr) {
logger.warn(`[PlayerManager] Retry also failed for channel ${cleanChannelId}: ${retryErr.message}`);
errorMsg = this._t(message, "responses.join.joinFailedGeneric");
}
} else if (errCode === "PERMISSION") {
errorMsg = this._t(message, "responses.join.joinFailedPerms", { channel: `<#${cleanChannelId}>` });
} else if (errCode === "NOT_FOUND") {
errorMsg = this._t(message, "responses.join.joinFailedNotFound");
} else if (errCode === "TIMEOUT") {
errorMsg = this._t(message, "responses.join.joinFailed");
} else {
errorMsg = this._t(message, "responses.join.joinFailed", { error: err.message });
}
await statusMsg.edit(errorMsg).catch(() => {});
this.playerMap.delete(cleanChannelId);
this._unindexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
player.destroy();
return null;
}
},
};
export default PlayerLifecycleMixin;
export { PlayerLifecycleMixin };
+229
View File
@@ -0,0 +1,229 @@
/**
* @module src/music/PlayerManager
* @description Manages all Player instances. Handles player lifecycle (spawn,
* join, leave, destroy), voice channel resolution, dashboard events, and
* autoleave suppression for 24/7 channels.
*
* Base class: class fields, constructor, the guild/channel player index,
* lookups and getPlayer. Dashboard event wiring and Last.fm scrobble
* scheduling live in PlayerEventsMixin.mjs; voice-channel detection, channel
* prompt, leave and player spawn/join live in PlayerLifecycleMixin.mjs.
* Both mixins are applied to the class at the bottom of this file.
*/
import Player from "./player/index.mjs";
import { Utils, cleanId } from "../utils/Utils.mjs";
import { logger } from "../core/Logger.mjs";
import { getMessageGuildId } from "../ui/index.mjs";
import { applyMixins } from "../utils/mixins.mjs";
import PlayerEventsMixin, { getPlayerChannelId } from "./PlayerEventsMixin.mjs";
import PlayerLifecycleMixin from "./PlayerLifecycleMixin.mjs";
/** @class PlayerManager @description Manages all Player instances. Handles player lifecycle (spawn, join, leave, destroy), voice channel resolution, dashboard events, and autoleave suppression for 24/7 channels. */
export class PlayerManager {
/** @type {RemoteSettingsManager} */
settings;
/** @type {CommandHandler} */
commands;
/** @type {Map<string, Player>} Player instances keyed by channel ID. */
playerMap = new Map();
/** @private @type {Map<string, Set<string>>} Guild ID → Set of channel IDs (for fast guild-player lookup). */
_guildPlayerIndex = new Map();
/** @private @type {Set<string>} Channel IDs currently being joined. */
_pendingJoins = new Set();
/** @private @type {Map<string, {timer: setTimeout, songUrl: string, startedAtMs: number}>} */
_pendingScrobbleTimers = new Map();
/** @type {object} Full bot config. */
config;
/** @type {object} Player-specific config (lavalink reference). */
playerConfig;
/** @type {Locale|null} */
locale = null;
/** @type {Dashboard|null} */
dashboard = null;
/**
* Create a new PlayerManager.
* @param {RemoteSettingsManager} settings - The settings manager.
* @param {CommandHandler} commands - The command handler.
* @param {object} config - Configuration object.
* @param {object} config.config - Full bot config.
* @param {object} config.player - Player-specific config (lavalink, etc.).
* @param {Dashboard} [config.dashboard] - Dashboard instance.
* @param {Locale} [config.locale] - Locale manager.
* @param {object} [config.timers] - Timer configuration.
* @param {TrackOptionsManager} [config.trackOptions] - Track options manager.
*/
constructor(settings, commands, config) {
this.commands = commands;
this.settings = settings;
this.config = config.config;
this.playerConfig = config.player;
this.dashboard = config.dashboard ?? null;
this.locale = config.locale ?? null;
this.timers = config.timers ?? {};
this._lastfm = null;
this.trackOptions = config.trackOptions ?? null;
}
/** @private Index a player by guild and channel ID for fast lookups. @param {string} guildId @param {string} channelId */
_indexPlayer(guildId, channelId) {
const gId = cleanId(guildId);
const cId = cleanId(channelId);
if (!gId || !cId) return;
let set = this._guildPlayerIndex.get(gId);
if (!set) { set = new Set(); this._guildPlayerIndex.set(gId, set); }
set.add(cId);
}
/** @private Remove a player from the guild-player index. @param {string} guildId @param {string} channelId */
_unindexPlayer(guildId, channelId) {
const gId = cleanId(guildId);
const cId = cleanId(channelId);
if (!gId) return;
const set = this._guildPlayerIndex.get(gId);
if (set) {
set.delete(cId);
if (set.size === 0) this._guildPlayerIndex.delete(gId);
}
}
/** Get all active (non-destroyed) players for a guild. @param {string} guildId @returns {Array<[string, Player]>} Array of [channelId, Player] pairs. */
getGuildPlayers(guildId) {
const gId = cleanId(guildId);
const set = this._guildPlayerIndex.get(gId);
if (!set) return [];
const result = [];
for (const channelId of set) {
const player = this.playerMap.get(channelId);
if (!player || player._destroyed) {
set.delete(channelId);
continue;
}
result.push([channelId, player]);
}
return result;
}
/** Find a player by both guild and channel. @param {string} guildId @param {string} channelId @returns {Player|null} */
getPlayerByGuildAndChannel(guildId, channelId) {
const cId = cleanId(channelId);
const players = this.getGuildPlayers(guildId);
for (const [mapChannelId, player] of players) {
if (getPlayerChannelId(player, mapChannelId) === cId) return player;
}
return null;
}
/** Find a player by its channel ID across all guilds. @param {string} channelId @returns {Player|null} */
getPlayerByChannelId(channelId) {
const cId = cleanId(channelId);
for (const [, channelSet] of this._guildPlayerIndex) {
for (const mapChannelId of channelSet) {
const player = this.playerMap.get(mapChannelId);
if (player && getPlayerChannelId(player, mapChannelId) === cId) return player;
}
}
return null;
}
/** Get or spawn a player for the message's voice channel. @async @param {object} message @param {boolean} [promptJoin=true] @param {boolean} [verifyUser=true] @param {boolean} [shouldJoin=false] @returns {Promise<Player|null>} */
async getPlayer(message, promptJoin = true, verifyUser = true, shouldJoin = false) {
const guildId = getMessageGuildId(message);
const cleanGuildId = cleanId(guildId);
const { channelId: userChannelId } = await this.checkVoiceChannels(message);
const cleanUserChannelId = cleanId(userChannelId);
if (cleanUserChannelId) {
const player = this.playerMap.get(cleanUserChannelId)
?? this.getPlayerByGuildAndChannel(cleanGuildId, cleanUserChannelId);
if (player) {
player.textChannel = message.channel?.channel ?? message.channel;
try {
const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null;
if (guildId && textChannelId) {
this.settings.getServer(guildId)?.set("announcementChannelId", textChannelId);
}
} catch(e) {
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
}
return player;
}
if (this._pendingJoins.has(cleanUserChannelId)) {
return null;
}
}
const serverPlayers = cleanGuildId
? this.getGuildPlayers(cleanGuildId)
: [];
if (serverPlayers.length > 0) {
const channelList = serverPlayers.map(([chId]) => `<#${chId}>`).join(" or ");
if (!userChannelId) {
if (!verifyUser) {
const first = serverPlayers[0];
first[1].textChannel = message.channel?.channel ?? message.channel;
return first[1];
}
message.reply(this._t(message, "responses._common.noVoiceStrict"));
return null;
}
const match = serverPlayers.find(([, player]) =>
getPlayerChannelId(player) === cleanUserChannelId
);
if (match) {
match[1].textChannel = message.channel?.channel ?? message.channel;
try {
const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null;
if (cleanGuildId && textChannelId) {
this.settings.getServer(cleanGuildId)?.set("announcementChannelId", textChannelId);
}
} catch(e) {
logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message);
}
return match[1];
}
if (shouldJoin) {
return this.initPlayer(message, userChannelId);
}
const prefix = this.commands.getPrefix(guildId);
message.reply(this._t(message, "responses._common.alreadyInChannel", { channels: channelList, prefix }));
return null;
}
if (!userChannelId) {
if (shouldJoin) {
return this.promptVC(message);
}
message.reply(this._t(message, "responses._common.noVoiceChannel"));
return null;
}
if (shouldJoin) {
return this.initPlayer(message, userChannelId);
}
return null;
}
}
// Attach the split-out concerns: dashboard event wiring (PlayerEventsMixin)
// and voice-channel detection / player lifecycle (PlayerLifecycleMixin).
applyMixins(PlayerManager, PlayerEventsMixin, PlayerLifecycleMixin);
+419
View File
@@ -0,0 +1,419 @@
/** @module src/music/audio/FluxerAudioBridge @description Audio bridge for streaming Lavalink/NodeLink audio through Fluxer voice connections. 100% in-process — Opus encoding via prism-media (native/WASM), WebM muxing via WebMOpusMuxer. No FFmpeg processes. Supports MP3/AAC/radio streams via Lavalink resolve-through. Base class: lifecycle (play/stop/destroy), state getters, volume and cleanup. Stream pipeline building and Lavalink REST HTTP helpers live in the StreamPipeline/HttpStreams mixin modules applied at the bottom of this file. */
import { logger } from "../../core/Logger.mjs";
import { EventEmitter } from "node:events";
import { Readable } from "node:stream";
import { applyMixins } from "../../utils/mixins.mjs";
import StreamPipeline from "./StreamPipeline.mjs";
import HttpStreams from "./HttpStreams.mjs";
/** @type {number} @description livekit TrackKind.KIND_AUDIO — publications with this kind are managed by the bridge. */
const TRACK_KIND_AUDIO = 1;
/** @extends {EventEmitter} */
export class FluxerAudioBridge extends EventEmitter {
_conn = null;
_stream = null;
_encoder = null;
_sourceStream = null;
_sourceReq = null;
_playing = false;
_stopped = false;
_startedAt = 0;
_currentUri = null;
_lavalink = null;
_playGeneration = 0;
_durationTimer = null;
_endResolve = null;
_endReject = null;
_usedTrackstream = false;
/** @type {boolean} @description Whether audio is currently playing. */
get playing() { return this._playing; }
/** @type {number} @description Timestamp (ms) when playback started. */
get startedAt() { return this._startedAt; }
/** @type {string|null} @description URI of the currently playing track. */
get currentUri() { return this._currentUri; }
/** @param {LavalinkManager|null} lavalinkManager - LavalinkManager for trackstream/loadstream. */
constructor(lavalinkManager = null) {
super();
this._lavalink = lavalinkManager;
}
/**
* Play a track through a Fluxer voice connection, entirely in-process.
* Routing order:
* 1. trackstream passthrough (seek=0, no filters) — NodeLink hands back a WebM/Opus
* direct URL which the voice connection plays natively (zero re-encode).
* 2. loadstream — NodeLink returns raw PCM (48k stereo s16le) with server-side
* seek/filters; PCM is Opus-encoded in-process and muxed to WebM.
* 3. direct URL fallback — magic-byte sniff: WebM passthrough or Ogg/Opus remux.
* @param {object} conn - Fluxer voice connection
* @param {object} trackInfo - Track metadata (encoded, title, url, guildId)
* @param {object} [options]
* @param {number} [options.seekSeconds=0]
* @param {number} [options.durationMs=0]
* @param {object} [options.filterPayload]
* @returns {Promise<"finished"|"stopped">}
*/
async play(conn, trackInfo, options = {}) {
this.stop();
if (!conn) throw new Error("[AudioBridge] No voice connection provided");
this._unpublishStaleAudioTracks(conn);
const generation = ++this._playGeneration;
this._conn = conn;
this._playing = true;
this._stopped = false;
this._startedAt = Date.now();
this._currentUri = trackInfo?.url ?? trackInfo?.title ?? "unknown";
this._usedTrackstream = false;
const seekMs = Math.floor((options.seekSeconds ?? 0) * 1000);
let durationMs = options.durationMs || 0;
try {
if (seekMs === 0 && !options.filterPayload && trackInfo.encoded && this._lavalink) {
try {
const direct = await this._getTrackstreamUrl(trackInfo);
if (direct?.url && /webm|opus/i.test(direct.format || "")) {
this._usedTrackstream = true;
logger.player("[AudioBridge] Passthrough webm/opus via trackstream (zero-copy): " + (trackInfo.title || "unknown"));
await conn.play(direct.url);
if (generation !== this._playGeneration) return "stopped";
if (durationMs > 0) await this._waitDuration(durationMs);
if (generation !== this._playGeneration) return "stopped";
if (this._playing && !this._stopped) {
this._playing = false;
logger.player("[AudioBridge] Track finished naturally (trackstream passthrough)");
return "finished";
}
return "stopped";
}
if (direct?.url && this._lavalink && trackInfo.url && trackInfo.url.startsWith("http")) {
logger.player("[AudioBridge] trackstream format " + (direct.format || "?") + " — resolving original source URL via Lavalink for fresh encoded track...");
const freshEncoded = await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId);
if (freshEncoded) {
trackInfo.encoded = freshEncoded;
logger.player("[AudioBridge] Fresh encoded track obtained — retrying trackstream for webm/opus...");
try {
const freshDirect = await this._getTrackstreamUrl(trackInfo);
if (freshDirect?.url && /webm|opus/i.test(freshDirect.format || "")) {
this._usedTrackstream = true;
logger.player("[AudioBridge] Fresh trackstream is webm/opus — zero-copy passthrough: " + (trackInfo.title || "unknown"));
await conn.play(freshDirect.url);
if (generation !== this._playGeneration) return "stopped";
if (durationMs > 0) await this._waitDuration(durationMs);
if (generation !== this._playGeneration) return "stopped";
if (this._playing && !this._stopped) {
this._playing = false;
logger.player("[AudioBridge] Track finished naturally (fresh trackstream passthrough)");
return "finished";
}
return "stopped";
}
logger.player("[AudioBridge] Fresh trackstream also " + (freshDirect?.format || "?") + ", falling through to loadstream");
} catch (e2) {
logger.player("[AudioBridge] Fresh trackstream failed, falling through to loadstream: " + e2.message);
}
} else {
logger.player("[AudioBridge] Could not resolve source URL via Lavalink, using original encoded track for loadstream");
}
} else {
logger.player("[AudioBridge] trackstream format not opus/webm (" + (direct?.format || "?") + "), falling through to loadstream");
}
} catch (e) {
logger.warn("[AudioBridge] Trackstream failed, falling back to loadstream: " + e.message);
this._playing = true;
this._stopped = false;
this._startedAt = Date.now();
}
}
if (trackInfo.encoded && this._lavalink) {
const loaded = await this._streamFromLoadstream(trackInfo, seekMs, options.filterPayload);
if (generation !== this._playGeneration) {
loaded.stream.destroy();
return "stopped";
}
const routed = await this._routeByMagic(loaded.stream);
this._sourceStream = loaded.stream;
this._sourceReq = loaded.req || null;
if (routed.kind === "webm") {
logger.player("[AudioBridge] Playing loadstream webm/opus passthrough: " + (trackInfo.title || "unknown") +
(seekMs > 0 ? " [seek: " + seekMs + "ms]" : ""));
this._stream = routed.stream;
await conn.play(routed.stream);
} else if (routed.kind === "ogg") {
logger.player("[AudioBridge] Playing loadstream ogg/opus (remux to webm): " + (trackInfo.title || "unknown"));
const oggResult = await this._remuxOggToWebM(routed.stream);
this._stream = oggResult;
if (durationMs <= 0) durationMs = oggResult.getDurationMs();
await conn.play(this._stream);
} else {
logger.player("[AudioBridge] Playing via loadstream PCM -> in-process Opus: " + (trackInfo.title || "unknown") +
(seekMs > 0 ? " [seek: " + seekMs + "ms]" : "") +
(options.filterPayload ? " [filters]" : ""));
this._stream = this._buildPcmPipeline(routed.stream);
await conn.play(this._stream);
}
if (generation !== this._playGeneration) return "stopped";
await this._awaitEnd(durationMs);
if (generation !== this._playGeneration) return "stopped";
if (this._playing && !this._stopped) {
this._playing = false;
logger.player("[AudioBridge] Track finished naturally (loadstream)");
return "finished";
}
return "stopped";
}
if (trackInfo.url && trackInfo.url.startsWith("http")) {
logger.player("[AudioBridge] Route 3: Fetching directly: " + trackInfo.url.substring(0, 80) + "...");
const response = await fetch(trackInfo.url, {
headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)" },
redirect: "follow",
});
if (!response.ok) {
throw new Error("HTTP " + response.status + " for " + trackInfo.url);
}
const stream = Readable.fromWeb(response.body);
this._sourceStream = stream;
const routed = await this._routeByMagic(stream);
if (routed.kind === "webm") {
logger.player("[AudioBridge] Route 3a: webm/opus passthrough: " + (trackInfo.title || "unknown"));
this._stream = routed.stream;
await conn.play(routed.stream);
} else if (routed.kind === "ogg") {
logger.player("[AudioBridge] Route 3b: ogg/opus remux to webm: " + (trackInfo.title || "unknown"));
const oggResult = await this._remuxOggToWebM(routed.stream);
this._stream = oggResult;
await conn.play(this._stream);
if (generation !== this._playGeneration) return "stopped";
await new Promise(r => {
if (this._stream.readableEnded) return r();
const done = () => { this._stream.off("end", done); this._stream.off("close", done); r(); };
this._stream.once("end", done);
this._stream.once("close", done);
});
if (generation !== this._playGeneration) return "stopped";
const fullDurationMs = oggResult.getDurationMs();
const elapsedMs = Date.now() - this._startedAt;
const remainingMs = Math.max(0, fullDurationMs - elapsedMs);
logger.player("[AudioBridge] Route 3b: OGG " + fullDurationMs + "ms total, " + elapsedMs + "ms elapsed, waiting " + remainingMs + "ms more");
if (remainingMs > 0) await this._awaitEnd(remainingMs);
if (generation !== this._playGeneration) return "stopped";
if (this._playing && !this._stopped) {
this._playing = false;
logger.player("[AudioBridge] Track finished naturally (direct URL, OGG remux)");
return "finished";
}
return "stopped";
} else {
stream.destroy();
this._sourceStream = null;
logger.player("[AudioBridge] Route 3c: Direct stream is " + routed.kind + " (MP3/AAC?) — resolving through Lavalink...");
if (this._lavalink) {
const encoded = await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId);
if (encoded) {
trackInfo.encoded = encoded;
logger.player("[AudioBridge] Route 3c: Got encoded track from Lavalink, retrying via loadstream...");
const loaded = await this._streamFromLoadstream(trackInfo, 0, null);
if (generation !== this._playGeneration) {
loaded.stream.destroy();
return "stopped";
}
const routed2 = await this._routeByMagic(loaded.stream);
this._sourceStream = loaded.stream;
this._sourceReq = loaded.req || null;
if (routed2.kind === "webm") {
logger.player("[AudioBridge] Route 3c (Lavalink): webm/opus passthrough");
this._stream = routed2.stream;
await conn.play(routed2.stream);
} else if (routed2.kind === "ogg") {
logger.player("[AudioBridge] Route 3c (Lavalink): ogg/opus remux to webm");
const oggResult3c = await this._remuxOggToWebM(routed2.stream);
this._stream = oggResult3c;
if (durationMs <= 0) durationMs = oggResult3c.getDurationMs();
await conn.play(this._stream);
} else {
logger.player("[AudioBridge] Route 3c (Lavalink): PCM -> Opus -> WebM");
this._stream = this._buildPcmPipeline(routed2.stream);
await conn.play(this._stream);
}
if (generation !== this._playGeneration) return "stopped";
await this._awaitEnd(durationMs);
if (generation !== this._playGeneration) return "stopped";
if (this._playing && !this._stopped) {
this._playing = false;
logger.player("[AudioBridge] Track finished naturally (Route 3c Lavalink resolve)");
return "finished";
}
return "stopped";
}
}
throw new Error(
"[AudioBridge] Direct URL is not WebM/Opus or Ogg/Opus (" + routed.kind + "). " +
"Lavalink resolve also failed or is unavailable. " +
"Make sure your Lavalink/NodeLink node is running and can decode this stream format."
);
}
if (generation !== this._playGeneration) return "stopped";
await this._awaitEnd(durationMs);
if (generation !== this._playGeneration) return "stopped";
if (this._playing && !this._stopped) {
this._playing = false;
logger.player("[AudioBridge] Track finished naturally (direct URL)");
return "finished";
}
return "stopped";
}
throw new Error("Could not get audio stream for: " + (trackInfo.title || trackInfo.url || "unknown"));
} catch (e) {
if (generation !== this._playGeneration) return "stopped";
if (this._stopped || !this._playing) return "stopped";
this._playing = false;
logger.error("[AudioBridge] Playback error: " + e.message);
throw e;
} finally {
this._cleanup();
}
}
/** Stop current playback and clean up resources. */
stop() {
const wasPlaying = this._playing;
this._stopped = true;
this._playing = false;
this._playGeneration++;
this._cleanup();
if (this._conn) {
try { this._conn.stop(); } catch (_) {}
this._unpublishStaleAudioTracks(this._conn);
}
if (wasPlaying) {
this.emit("stopped");
logger.player("[AudioBridge] Playback stopped");
}
}
/**
* @param {object} conn - Fluxer voice connection
* @param {string|null} [keepSid=null] - Track SID to keep (currently active publication)
* @private
*/
_unpublishStaleAudioTracks(conn, keepSid = null) {
try {
const room = conn?.room;
const participant = room?.localParticipant;
if (!room?.isConnected || typeof participant?.unpublishTrack !== "function") return;
const publications = participant.trackPublications;
if (!publications || typeof publications.entries !== "function") return;
for (const [sid, pub] of publications.entries()) {
if (keepSid && sid === keepSid) continue;
if (pub?.kind !== TRACK_KIND_AUDIO) continue;
try {
const p = participant.unpublishTrack(sid, true);
if (p?.catch) p.catch(() => {});
logger.player("[AudioBridge] Unpublished stale audio track: " + sid);
} catch (_) {}
}
} catch (_) {
}
}
/**
* Set the playback volume on the voice connection.
* @param {number} percent - Volume 0–100.
*/
setVolume(percent) {
if (this._conn) {
try { this._conn.setVolume(percent); } catch (e) {
logger.warn("[AudioBridge] setVolume error: " + e.message);
}
}
}
/** @returns {number} Current volume percentage (0–100). */
getVolume() {
if (this._conn) {
try { return this._conn.getVolume(); } catch (_) {}
}
return 100;
}
/** @returns {boolean} Whether the voice connection is currently active. */
isConnected() {
if (this._conn) {
try { return this._conn.isConnected(); } catch (_) {}
}
return false;
}
/**
* Clear timers, settle pending waits, and tear down the pipeline.
* @private
*/
_cleanup() {
if (this._durationTimer) { clearTimeout(this._durationTimer); this._durationTimer = null; }
if (this._endResolve) {
const resolve = this._endResolve;
this._endResolve = null;
this._endReject = null;
resolve();
}
for (const s of [this._stream, this._encoder, this._sourceStream]) {
if (s) {
try { s.destroy(); } catch (_) {}
}
}
if (this._sourceReq) {
try { this._sourceReq.destroy(); } catch (_) {}
}
this._stream = null;
this._encoder = null;
this._sourceStream = null;
this._sourceReq = null;
}
/** Stop playback, release the voice connection, and remove all listeners. */
destroy() {
this.stop();
this._conn = null;
this._currentUri = null;
this.removeAllListeners();
}
}
// Attach the split-out concerns: stream pipeline building/routing
// (StreamPipeline) and Lavalink REST HTTP helpers (HttpStreams).
applyMixins(FluxerAudioBridge, StreamPipeline, HttpStreams);
+185
View File
@@ -0,0 +1,185 @@
/**
* @module src/music/audio/HttpStreams
* @description HTTP helper concern for {@link FluxerAudioBridge}: GET-JSON
* with redirect following and streaming GET with connect/idle timeouts,
* used for the Lavalink/NodeLink REST endpoints (trackstream, loadstream,
* loadtracks).
*
* These methods are applied onto the FluxerAudioBridge class prototype via
* {@link module:src/utils/mixins.applyMixins} — `this` is a
* FluxerAudioBridge instance.
*/
import { logger } from "../../core/Logger.mjs";
import http from "node:http";
import https from "node:https";
/** @type {number} @description Maximum number of HTTP redirect hops to follow. */
const MAX_REDIRECTS = 5;
/** @type {number} @description Timeout (ms) for HTTP requests to Lavalink REST endpoints (trackstream, loadtracks JSON). */
const REST_REQUEST_TIMEOUT_MS = 15_000;
/** @type {number} @description Timeout (ms) to wait for the first byte from loadstream (Lavalink may need time to resolve HLS/external streams). */
const LOADSTREAM_CONNECT_TIMEOUT_MS = 60_000;
/** @type {number} @description Idle timeout (ms) once loadstream data is flowing — if no data arrives for this long, abort. */
const LOADSTREAM_IDLE_TIMEOUT_MS = 30_000;
/**
* @type {object}
* @description HTTP streams mixin — applied to FluxerAudioBridge.
*/
const HttpStreams = {
/**
* @param {string} url
* @param {object} [headers]
* @returns {Promise<object>}
* @private
*/
_httpGetJson(url, headers = {}, _redirectCount = 0, timeoutMs = REST_REQUEST_TIMEOUT_MS) {
return new Promise((resolve, reject) => {
if (_redirectCount >= MAX_REDIRECTS) {
return reject(new Error("Too many redirects (" + _redirectCount + ")"));
}
const urlObj = new URL(url);
const client = urlObj.protocol === "https:" ? https : http;
const req = client.request({
protocol: urlObj.protocol,
host: urlObj.hostname,
port: urlObj.port,
path: urlObj.pathname + urlObj.search,
method: "GET",
headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)", ...headers },
}, (res) => {
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
res.resume();
let loc = res.headers.location;
if (loc.startsWith("/")) loc = urlObj.protocol + "//" + urlObj.host + loc;
return this._httpGetJson(loc, headers, _redirectCount + 1, timeoutMs).then(resolve, reject);
}
if (res.statusCode !== 200) {
let body = "";
res.on("data", (chunk) => { body += chunk; });
res.on("end", () => {
reject(new Error("HTTP " + res.statusCode + " for " + url + ": " + body.substring(0, 300)));
});
return;
}
let data = "";
res.on("data", (chunk) => { data += chunk; });
res.on("end", () => {
try {
resolve(JSON.parse(data));
} catch (e) {
reject(new Error("Invalid JSON from trackstream: " + data.substring(0, 200)));
}
});
});
req.on("socket", (socket) => {
socket.on("error", () => {});
});
req.on("error", reject);
req.setTimeout(timeoutMs, () => {
req.destroy();
reject(new Error("REST request timeout (" + timeoutMs / 1000 + "s)"));
});
req.end();
});
},
/**
* @param {string} url
* @param {object} [headers]
* @param {number} [_redirectCount=0]
* @returns {Promise<{stream: Readable, inputFormat: string|null, req: http.ClientRequest}>}
* @private
*/
_httpRequestStream(url, headers = {}, _redirectCount = 0) {
return new Promise((resolve, reject) => {
if (_redirectCount >= MAX_REDIRECTS) {
return reject(new Error("Too many redirects (" + _redirectCount + ")"));
}
const urlObj = new URL(url);
const client = urlObj.protocol === "https:" ? https : http;
let firstByte = true;
let connectTimer = null;
let idleTimer = null;
const resetIdleTimeout = () => {
if (idleTimer) clearTimeout(idleTimer);
idleTimer = setTimeout(() => {
req.destroy();
reject(new Error("loadstream idle timeout (" + LOADSTREAM_IDLE_TIMEOUT_MS / 1000 + "s no data)"));
}, LOADSTREAM_IDLE_TIMEOUT_MS);
idleTimer.unref?.();
};
const req = client.request({
protocol: urlObj.protocol,
host: urlObj.hostname,
port: urlObj.port,
path: urlObj.pathname + urlObj.search,
method: "GET",
headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)", ...headers },
}, (res) => {
if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) {
if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; }
res.resume();
let nextHeaders = headers;
let loc = res.headers.location;
if (loc.startsWith("/")) loc = urlObj.protocol + "//" + urlObj.host + loc;
try {
const redirectHost = new URL(loc).hostname;
if (redirectHost !== urlObj.hostname) {
const { Authorization, "Session-Id": _, ...safe } = headers;
nextHeaders = safe;
}
} catch (_) {}
return this._httpRequestStream(loc, nextHeaders, _redirectCount + 1).then(resolve, reject);
}
if (res.statusCode !== 200) {
if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; }
let body = "";
res.on("data", (chunk) => { body += chunk; });
res.on("end", () => {
reject(new Error("HTTP " + res.statusCode + " for " + url + ": " + body.substring(0, 300)));
});
return;
}
if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; }
resetIdleTimeout();
res.once("data", () => resetIdleTimeout());
logger.player("[AudioBridge] loadstream response: " + res.statusCode + " content-type=" + (res.headers["content-type"] || "?"));
resolve({ stream: res, inputFormat: res.headers["content-type"] || null, req });
});
req.on("socket", (socket) => {
socket.on("error", () => {});
});
req.on("error", (err) => {
if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; }
if (idleTimer) { clearTimeout(idleTimer); idleTimer = null; }
reject(err);
});
connectTimer = setTimeout(() => {
req.destroy();
reject(new Error("loadstream connect timeout (" + LOADSTREAM_CONNECT_TIMEOUT_MS / 1000 + "s — Lavalink took too long to start stream)"));
}, LOADSTREAM_CONNECT_TIMEOUT_MS);
connectTimer.unref?.();
req.end();
});
},
};
export default HttpStreams;
export { HttpStreams };
+326
View File
@@ -0,0 +1,326 @@
/**
* @module src/music/audio/StreamPipeline
* @description Stream pipeline concern for {@link FluxerAudioBridge}:
* end-of-playback waiting, magic-byte routing, the in-process PCM -> Opus ->
* WebM pipeline, Ogg/Opus remuxing, trackstream/loadstream URL handling and
* Lavalink URL resolution.
*
* These methods are applied onto the FluxerAudioBridge class prototype via
* {@link module:src/utils/mixins.applyMixins} — `this` is a
* FluxerAudioBridge instance.
*/
import { logger } from "../../core/Logger.mjs";
import { WebMOpusMuxer, OPUS_FRAME_MS } from "./WebMOpusMuxer.mjs";
import prismMedia from "prism-media";
const { Encoder: PrismOpusEncoder, OggDemuxer: PrismOggDemuxer } = prismMedia.opus;
/** @type {number} @description PCM sample rate expected from NodeLink loadstream (48kHz stereo s16le). */
const PCM_RATE = 48000;
/** @type {number} @description PCM channel count expected from NodeLink loadstream. */
const PCM_CHANNELS = 2;
/** @type {number} @description Opus frame size in samples per channel (20ms @ 48kHz). */
const PCM_FRAME_SIZE = 960;
/** @type {number} @description Opus encoding bitrate. */
const OPUS_BITRATE = 128000;
/** @type {Buffer} @description WebM/Matroska EBML magic bytes. */
const WEBM_MAGIC = Buffer.from([0x1a, 0x45, 0xdf, 0xa3]);
/** @type {Buffer} @description OGG container magic bytes ("OggS"). */
const OGG_MAGIC = Buffer.from("OggS", "ascii");
/**
* @type {object}
* @description Stream pipeline mixin — applied to FluxerAudioBridge.
*/
const StreamPipeline = {
/**
* Wait for playback end: duration timer for fixed-length tracks, pipeline
* end event for live/radio streams (durationMs = 0). Rejects early on
* pipeline errors so the player can skip to the next track.
* @param {number} durationMs
* @returns {Promise<void>}
* @private
*/
_awaitEnd(durationMs) { return new Promise((resolve, reject) => {
this._endResolve = resolve;
this._endReject = reject;
const failFast = (err) => {
if (this._playing && !this._stopped) {
this._playing = false;
reject(err);
} else {
resolve();
}
};
if (durationMs > 0) {
this._durationTimer = setTimeout(resolve, durationMs);
} else {
const stream = this._stream;
if (!stream) return resolve();
const onEnd = () => resolve();
stream.once("end", onEnd);
stream.once("close", onEnd);
stream.once("error", failFast);
}
if (this._sourceStream) {
this._sourceStream.once("error", failFast);
}
if (this._encoder) {
this._encoder.once("error", failFast);
}
});
},
/**
* Simple timed wait used by the trackstream passthrough route (no local
* pipeline to watch). Resolves early if stopped.
* @param {number} durationMs
* @returns {Promise<void>}
* @private
*/
_waitDuration(durationMs) {
return new Promise((resolve) => {
const timer = setTimeout(() => {
this._durationTimer = null;
resolve();
}, durationMs);
this._durationTimer = timer;
});
},
/**
* Peek at the first bytes of a stream and classify it, pushing the peeked
* bytes back so nothing is lost.
* @param {Readable} stream
* @returns {Promise<{stream: Readable, kind: "webm"|"ogg"|"pcm"}>}
* @private
*/
async _routeByMagic(stream) {
const head = await this._peek(stream, 4);
if (head.length >= 4 && head.subarray(0, 4).equals(WEBM_MAGIC)) return { stream, kind: "webm" };
if (head.length >= 4 && head.subarray(0, 4).equals(OGG_MAGIC)) return { stream, kind: "ogg" };
return { stream, kind: "pcm" };
},
/**
* Read up to `n` bytes from a paused-mode stream, then unshift them.
* @param {Readable} stream
* @param {number} n
* @returns {Promise<Buffer>}
* @private
*/
_peek(stream, n) {
return new Promise((resolve, reject) => {
const tryRead = () => {
const chunks = [];
let total = 0;
let chunk;
while (total < n && (chunk = stream.read()) !== null) {
chunks.push(chunk);
total += chunk.length;
}
if (total >= n || stream.readableEnded) {
const buf = Buffer.concat(chunks);
cleanup();
if (buf.length > 0) stream.unshift(buf);
resolve(buf.subarray(0, n));
return;
}
};
const onReadable = () => { cleanup(); tryRead(); };
const onEnd = () => { cleanup(); tryRead(); };
const onError = (err) => { cleanup(); reject(err); };
const cleanup = () => {
stream.off("readable", onReadable);
stream.off("end", onEnd);
stream.off("error", onError);
};
stream.once("readable", onReadable);
stream.once("end", onEnd);
stream.once("error", onError);
tryRead();
});
},
/**
* Build the in-process PCM -> Opus -> WebM pipeline.
* @param {Readable} pcmStream - s16le 48kHz stereo byte stream
* @returns {WebMOpusMuxer} - byte stream consumable by conn.play()
* @private
*/
_buildPcmPipeline(pcmStream) {
let encoder;
try {
encoder = new PrismOpusEncoder({
rate: PCM_RATE,
channels: PCM_CHANNELS,
frameSize: PCM_FRAME_SIZE,
});
} catch (e) {
pcmStream.destroy();
throw new Error(
"No Opus encoder available (" + e.message + "). Install one: npm install opusscript"
);
}
try { encoder.setBitrate(OPUS_BITRATE); } catch (_) {}
const muxer = new WebMOpusMuxer({ sampleRate: PCM_RATE, channels: PCM_CHANNELS });
this._encoder = encoder;
pcmStream.on("error", (err) => {
logger.warn("[AudioBridge] PCM source error: " + err.message);
encoder.destroy(err);
});
encoder.on("error", (err) => {
muxer.destroy(err);
});
pcmStream.pipe(encoder).pipe(muxer);
return muxer;
},
/**
* Remux an Ogg/Opus stream into WebM/Opus (packet-level, no re-encode).
* @param {Readable} oggStream
* @returns {Promise<{stream: WebMOpusMuxer, getDurationMs: function}>}
* @private
*/
async _remuxOggToWebM(oggStream) {
const demuxer = new PrismOggDemuxer();
const muxer = new WebMOpusMuxer();
oggStream.on("error", (err) => demuxer.destroy(err));
demuxer.on("error", (err) => muxer.destroy(err));
let frameCount = 0;
demuxer.on("data", () => { frameCount++; });
const headPromise = new Promise((resolve, reject) => {
demuxer.once("head", () => resolve());
demuxer.once("error", (err) => reject(new Error("OGG demux: " + err.message)));
oggStream.once("error", (err) => reject(new Error("OGG source: " + err.message)));
});
oggStream.pipe(demuxer).pipe(muxer);
await headPromise;
const wrapper = Object.create(muxer);
wrapper.getDurationMs = () => frameCount * OPUS_FRAME_MS;
return wrapper;
},
/**
* @param {object} trackInfo
* @returns {Promise<{url: string, format: string}>}
* @private
*/
async _getTrackstreamUrl(trackInfo) {
const nlInfo = this._lavalink.getNodeLinkInfo?.();
if (!nlInfo) throw new Error("NodeLink info not available");
const protocol = nlInfo.secure ? "https" : "http";
const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port;
const headers = { "Authorization": nlInfo.password };
if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId;
if (trackInfo.guildId) headers["Guild-Id"] = trackInfo.guildId;
const params = "encodedTrack=" + encodeURIComponent(trackInfo.encoded);
const url = baseUrl + "/v4/trackstream?" + params;
logger.player("[AudioBridge] Querying /v4/trackstream...");
const body = await this._httpGetJson(url, headers);
const directUrl = body?.url;
if (!directUrl || typeof directUrl !== "string") {
throw new Error("trackstream returned no URL");
}
const format = body?.format || "";
logger.player("[AudioBridge] trackstream: format=" + format + " url=" + directUrl.substring(0, 100) + "...");
return { url: directUrl, format };
},
/**
* @param {object} trackInfo
* @param {number} [seekMs=0]
* @param {object|null} [filterPayload]
* @returns {Promise<{stream: Readable, inputFormat: string|null}>}
* @private
*/
async _streamFromLoadstream(trackInfo, seekMs = 0, filterPayload = null) {
const nlInfo = this._lavalink.getNodeLinkInfo?.();
if (!nlInfo) {
throw new Error("NodeLink info not available");
}
const protocol = nlInfo.secure ? "https" : "http";
const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port;
const headers = { "Authorization": nlInfo.password };
if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId;
if (trackInfo.guildId) headers["Guild-Id"] = trackInfo.guildId;
let baseParams = "encodedTrack=" + encodeURIComponent(trackInfo.encoded) + "&position=" + seekMs + "&volume=100";
if (filterPayload) {
baseParams += "&filters=" + encodeURIComponent(JSON.stringify(filterPayload));
}
const url = baseUrl + "/v4/loadstream?" + baseParams;
logger.player("[AudioBridge] Querying /v4/loadstream (seek: " + seekMs + "ms)...");
return this._httpRequestStream(url, headers);
},
/**
* Resolve a direct audio URL through Lavalink's /v4/loadtracks to get an encoded track.
* This allows MP3/AAC radio streams and direct audio URLs to be played through
* the loadstream pipeline without any FFmpeg dependency.
* @param {string} url - The HTTP(S) audio stream URL to resolve.
* @param {string} [guildId] - Optional guild ID for the request.
* @returns {Promise<string|null>} The encoded track string, or null if resolution failed.
* @private
*/
async _resolveUrlViaLavalink(url, guildId) {
try {
const nlInfo = this._lavalink.getNodeLinkInfo?.();
if (!nlInfo) {
logger.warn("[AudioBridge] _resolveUrlViaLavalink: no NodeLink info");
return null;
}
const protocol = nlInfo.secure ? "https" : "http";
const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port;
const headers = { "Authorization": nlInfo.password };
if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId;
if (guildId) headers["Guild-Id"] = guildId;
const params = "identifier=" + encodeURIComponent(url);
const loadtracksUrl = baseUrl + "/v4/loadtracks?" + params;
logger.player("[AudioBridge] Resolving URL via Lavalink /v4/loadtracks: " + url.substring(0, 80) + "...");
const body = await this._httpGetJson(loadtracksUrl, headers, 0, 30_000);
const track = body?.data?.tracks?.[0] ?? body?.tracks?.[0] ?? body?.data;
const encoded = track?.encoded ?? track?.data;
if (encoded && typeof encoded === "string") {
logger.player("[AudioBridge] Lavalink resolved URL to encoded track successfully");
return encoded;
}
const loadType = body?.loadType ?? body?.data?.loadType;
logger.warn("[AudioBridge] Lavalink loadtracks returned no playable track (loadType=" + loadType + ")");
return null;
} catch (e) {
logger.warn("[AudioBridge] _resolveUrlViaLavalink failed: " + e.message);
return null;
}
},
};
export default StreamPipeline;
export { StreamPipeline };
+107
View File
@@ -0,0 +1,107 @@
/** @module constants/audio/Tuna */
import pkg from "follow-redirects";
const { https } = pkg;
/**
* Client for the Tuna (Voicemod) sound-effect API.
* @class
*/
class Tuna {
/** @private */ apiKey = null;
/**
* @param {{ key: string }} auth - Object containing the API key.
*/
constructor(auth) {
this.apiKey = auth.key;
}
/**
* Perform an authenticated GET request to the Tuna API.
* @private
* @async
* @param {string} path - API path (e.g. `"/v1/sounds/search"`).
* @param {Object<string, *>} [params={}] - Query-string parameters.
* @returns {Promise<object>} Parsed JSON response.
*/
get(path, params = {}) {
return new Promise((resolve, reject) => {
const qs = new URLSearchParams(params).toString();
const query = qs ? "?" + qs : "";
const options = {
method: "GET",
hostname: "tuna-api.voicemod.net",
path: path + query,
headers: { "x-api-key": this.apiKey },
maxRedirects: 20
};
const req = https.request(options, (res) => {
const chunks = [];
res.on("data", (chunk) => { chunks.push(chunk); });
res.on("end", () => {
try {
resolve(JSON.parse(Buffer.concat(chunks).toString()));
} catch (e) {
reject(new Error(`Tuna API JSON parse error: ${e.message}`));
}
});
});
req.on("error", (error) => { reject(error); });
req.setTimeout(15_000, () => {
req.destroy();
reject(new Error("Tuna API request timeout"));
});
req.end();
});
}
/**
* Search for sound effects. Each result item gains a `download()` method
* that returns the OGG audio stream.
* @async
* @param {string} query - Search term.
* @param {number} [page=1]
* @param {number} [size=10]
* @returns {Promise<object>} Search results with enriched `items` array.
*/
search(query, page = 1, size = 10) {
return this.get("/v1/sounds/search", { size, page, search: query }).then(results => {
results.items = results.items.map(s => {
const oggPath = s.oggPath;
s.download = () => {
return new Promise((resolve, reject) => {
const req = https.get(oggPath, { maxRedirects: 20 }, (r) => { resolve(r); });
req.on("error", (err) => { reject(err); });
req.setTimeout(15_000, () => { req.destroy(); reject(new Error("Tuna download timeout")); });
});
};
return s;
});
return results;
});
}
/**
* Fetch a single sound effect by ID. The returned object gains a `download()`
* method that returns the OGG audio stream.
* @async
* @param {string} id - Sound ID.
* @returns {Promise<object>} Sound object with `download()` method.
*/
getSound(id) {
return this.get("/v1/sounds/" + id).then(sound => {
const oggPath = sound.oggPath;
sound.download = () => {
return new Promise((resolve, reject) => {
const req = https.get(oggPath, { maxRedirects: 20 }, (result) => { resolve(result); });
req.on("error", (err) => { reject(err); });
req.setTimeout(15_000, () => { req.destroy(); reject(new Error("Tuna download timeout")); });
});
};
return sound;
});
}
}
export default Tuna;
+220
View File
@@ -0,0 +1,220 @@
/** @module src/music/audio/WebMOpusMuxer @description Minimal streaming WebM/Matroska muxer for Opus packets. Produces streams consumable by prism-media's WebmDemuxer (what @fluxerjs/voice uses internally) — no FFmpeg required. */
import { Transform } from "node:stream";
/** @type {number} @description Opus frame duration in milliseconds (20ms = 960 samples @ 48kHz). */
export const OPUS_FRAME_MS = 20;
/** @type {number} @description Blocks per cluster before a new Cluster element is started. */
const BLOCKS_PER_CLUSTER = 250;
/** @type {number} @description Force a cluster flush when buffered blocks exceed this size. */
const CLUSTER_FLUSH_BYTES = 64 * 1024;
/**
* Encode a Matroska variable-length size integer (finite size).
* @param {number} value - Size to encode (must be >= 0).
* @returns {Buffer}
*/
function encodeSizeVint(value) {
let length = 1;
while (value > 2 ** (7 * length) - 1 && length < 8) length++;
const buf = Buffer.alloc(length);
for (let i = length - 1; i >= 0; i--) {
buf[i] = value & 0xff;
value = Math.floor(value / 256);
}
buf[0] |= 1 << (8 - length);
return buf;
}
/**
* Build a single EBML element from an ID hex string and a payload Buffer.
* @param {string} idHex - EBML element ID as hex (e.g. "1a45dfa3").
* @param {Buffer} payload
* @returns {Buffer}
*/
function element(idHex, payload) {
return Buffer.concat([Buffer.from(idHex, "hex"), encodeSizeVint(payload.length), payload]);
}
/**
* Encode an unsigned integer EBML payload using minimal bytes.
* @param {number} value
* @returns {Buffer}
*/
function uintPayload(value) {
let bytes = 1;
while (value >= 2 ** (8 * bytes)) bytes++;
const buf = Buffer.alloc(bytes);
buf.writeUIntBE(value, 0, bytes);
return buf;
}
/**
* Build the OpusHead codec private data (Matroska-embedded OpusHead).
* @param {number} sampleRate - Input sample rate (48000).
* @param {number} channels - Channel count (2).
* @returns {Buffer}
*/
export function buildOpusHead(sampleRate, channels) {
const buf = Buffer.alloc(19);
buf.write("OpusHead", 0, "ascii");
buf.writeUInt8(1, 8); // version
buf.writeUInt8(channels, 9);
buf.writeUInt16LE(0, 10); // pre-skip (we encode ourselves; no trimming)
buf.writeUInt32LE(sampleRate, 12);
buf.writeInt16LE(0, 16); // output gain
buf.writeUInt8(0, 18); // mapping family (mono/stereo)
return buf;
}
/**
* Build the WebM stream header: EBML + Segment start + Info + Tracks.
* The Segment element uses an unknown (streaming) size so clusters can be
* appended indefinitely.
* @param {number} sampleRate
* @param {number} channels
* @returns {Buffer}
*/
function buildHeader(sampleRate, channels) {
const ebml = element("1a45dfa3", Buffer.concat([
element("4286", uintPayload(1)), // EBMLVersion
element("42f7", uintPayload(1)), // EBMLReadVersion
element("42f2", uintPayload(4)), // EBMLMaxIDLength
element("42f3", uintPayload(8)), // EBMLMaxSizeLength
element("4282", Buffer.from("webm", "ascii")), // DocType
element("4287", uintPayload(2)), // DocTypeVersion
element("4285", uintPayload(2)), // DocTypeReadVersion
]));
const info = element("1549a966", Buffer.concat([
element("2ad7b1", uintPayload(1000000)), // TimecodeScale (1ms)
element("4d80", Buffer.from("fluxer-remix", "ascii")),// MuxingApp
element("5741", Buffer.from("fluxer-remix", "ascii")),// WritingApp
]));
const floatBuf = Buffer.alloc(4);
floatBuf.writeFloatBE(sampleRate, 0);
const audio = element("e1", Buffer.concat([
element("b5", floatBuf), // SamplingFrequency
element("9f", uintPayload(channels)), // Channels
]));
const trackEntry = element("ae", Buffer.concat([
element("d7", uintPayload(1)), // TrackNumber (must be 1 — demuxer masks data[0] & 0xF)
element("73c5", uintPayload(1)), // TrackUID
element("83", uintPayload(2)), // TrackType: audio
element("86", Buffer.from("A_OPUS", "ascii")), // CodecID
element("63a2", buildOpusHead(sampleRate, channels)), // CodecPrivate: OpusHead
audio,
]));
const tracks = element("1654ae6b", trackEntry);
// Streaming Segment size: a huge finite vint (0x01 + 7x0xFF = 2^56-1). The
// canonical all-0xFF unknown-size marker is misparsed by prism-media's
// vintLength (it reads 0xFF as a 1-byte vint), so we use this equivalent form.
const segmentStart = Buffer.concat([
Buffer.from("18538067", "hex"),
Buffer.from([0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]),
]);
return Buffer.concat([ebml, segmentStart, info, tracks]);
}
/**
* Build a SimpleBlock element for one Opus packet.
* @param {Buffer} packet - Raw Opus packet.
* @param {number} relTimeMs - Cluster-relative timestamp in ms.
* @returns {Buffer}
*/
function buildSimpleBlock(packet, relTimeMs) {
const clamped = Math.max(-32768, Math.min(32767, relTimeMs));
const header = Buffer.from([0x81, (clamped >> 8) & 0xff, clamped & 0xff, 0x80]);
return element("a3", Buffer.concat([header, packet]));
}
/**
* Streaming WebM muxer: consumes Opus packets (object mode) and emits a
* WebM/Opus byte stream compatible with prism-media's WebmDemuxer — the exact
* format @fluxerjs/voice's VoiceConnection.play() expects as input.
* @extends {Transform}
*/
export class WebMOpusMuxer extends Transform {
/**
* @param {object} [options]
* @param {number} [options.sampleRate=48000]
* @param {number} [options.channels=2]
*/
constructor(options = {}) {
super({ writableObjectMode: true });
this._sampleRate = options.sampleRate ?? 48000;
this._channels = options.channels ?? 2;
this._header = buildHeader(this._sampleRate, this._channels);
this._blocks = [];
this._blocksBytes = 0;
this._blockIndex = 0;
this._clusterIndex = 0;
this._headerSent = false;
}
/**
* Feed one Opus packet into the current cluster.
* @param {Buffer} packet
*/
_addBlock(packet) {
if (!this._headerSent) {
this.push(this._header);
this._headerSent = true;
}
const relTime = (this._blockIndex % BLOCKS_PER_CLUSTER) * OPUS_FRAME_MS;
const block = buildSimpleBlock(packet, relTime);
this._blocks.push(block);
this._blocksBytes += block.length;
this._blockIndex++;
if (this._blocks.length >= BLOCKS_PER_CLUSTER || this._blocksBytes >= CLUSTER_FLUSH_BYTES) {
this._flushCluster();
}
}
/** Emit the current cluster as a complete EBML element. */
_flushCluster() {
if (this._blocks.length === 0) return;
const timecode = element("e7", uintPayload(this._clusterIndex * BLOCKS_PER_CLUSTER * OPUS_FRAME_MS));
const cluster = element("1f43b675", Buffer.concat([timecode, ...this._blocks]));
this._blocks = [];
this._blocksBytes = 0;
this._clusterIndex++;
this.push(cluster);
}
/**
* @param {Buffer} packet
* @param {string} _encoding
* @param {Function} callback
* @protected
*/
_transform(packet, _encoding, callback) {
try {
if (Buffer.isBuffer(packet) && packet.length > 0) {
this._addBlock(packet);
}
callback();
} catch (err) {
callback(err);
}
}
/**
* @param {Function} callback
* @protected
*/
_final(callback) {
try {
this._flushCluster();
callback();
} catch (err) {
callback(err);
}
}
}
+9
View File
@@ -0,0 +1,9 @@
/**
* @module src/music/audio
* @description Public surface of the audio layer (Fluxer voice bridge).
*
* Import map from the old layout:
* - `src/FluxerAudioBridge.mjs` → this module (FluxerAudioBridge)
*/
export { FluxerAudioBridge } from "./FluxerAudioBridge.mjs";
+292
View File
@@ -0,0 +1,292 @@
/**
* @module src/music/player/DisplayMixin
* @description User-facing rendering concern for {@link Player}: progress
* bars, now-playing announcements, queue listing, thumbnails and duration
* formatting.
*
* These methods are applied onto the Player class prototype via
* {@link applyMixins} — `this` is a Player instance.
*/
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../../ui/index.mjs";
import { Utils } from "../../utils/Utils.mjs";
import { logger } from "../../core/Logger.mjs";
import meta from "../probe.mjs";
/**
* @type {object}
* @description Display mixin — applied to Player.
*/
const DisplayMixin = {
/**
* @private Build a progress bar line for the current track.
* @this {import('./Player.mjs').Player}
* @param {number} [length=15]
* @returns {string}
*/
_createProgressBar(length = 15) {
const current = this.queue.getCurrent();
if (!current?.duration || !this.startedPlaying) {
const total = this._getTrackDurationMs(current);
if (total > 0) {
return `${Utils.progressBar(0, total, length)} \`0:00 / ${Utils.prettifyMS(total)}\``;
}
return Utils.progressBar(0, 1, length);
}
const totalMs = this._getTrackDurationMs(current);
let elapsed = Date.now() - this.startedPlaying;
if (this._paused && this._pausedAt) {
elapsed = this._pausedAt - this.startedPlaying;
}
if (totalMs > 0 && elapsed > totalMs) elapsed = totalMs;
elapsed = Math.max(0, elapsed);
const bar = Utils.progressBar(elapsed, totalMs, length);
const timeNow = Utils.prettifyMS(elapsed);
const total = Utils.prettifyMS(totalMs);
return `${bar} \`${timeNow} / ${total}\``;
},
/**
* @returns {string} Formatted name of the currently playing track.
* @this {import('./Player.mjs').Player}
*/
getCurrent() {
const c = this.queue.getCurrent();
if (!c) return "There's nothing playing at the moment.";
return this.getVideoName(c);
},
/**
* Format a track object into a display name.
* @this {import('./Player.mjs').Player}
* @param {object} vid
* @param {boolean} [code=false]
* @returns {string}
*/
getVideoName(vid, code = false) {
if (!vid) return "Unknown";
if (vid.type === "radio") {
return code
? `[Radio]: ${vid.title} - ${vid.author?.url || ""}`
: `[Radio] [${vid.title} by ${vid.author?.name || "Unknown"}](${vid.author?.url || ""})`;
}
if (vid.type === "external" || vid.type === "stream") {
return code
? `${vid.title} - ${vid.url}`
: `[${vid.title}](${vid.url})`;
}
const elapsed = this.getCurrentElapsedDuration();
const total = this.getDuration(vid.duration);
const link = vid.spotifyUrl || vid.url || "";
return code
? `${vid.title} (${elapsed}/${total})${link ? " - " + link : ""}`
: `[${vid.title} (${elapsed}/${total})]${link ? "(" + link + ")" : ""}`;
},
/**
* @returns {string} Human-readable total remaining time for all queued tracks.
* @this {import('./Player.mjs').Player}
*/
getQueueRemainingTime() {
let totalMs = 0;
const current = this.queue.getCurrent();
if (current?.duration && this.startedPlaying) {
const totalMsCurrent = this._getTrackDurationMs(current);
let elapsed = Date.now() - this.startedPlaying;
if (this._paused && this._pausedAt) {
elapsed = this._pausedAt - this.startedPlaying;
}
totalMs += Math.max(0, totalMsCurrent - elapsed);
}
for (const track of this.queue.data) {
totalMs += this._getTrackDurationMs(track);
}
return Utils.prettifyMS(totalMs);
},
/**
* @returns {string} Elapsed time of the current track.
* @this {import('./Player.mjs').Player}
*/
getCurrentElapsedDuration() {
if (!this.startedPlaying) return "0:00";
const current = this.queue.getCurrent();
const totalMs = this._getTrackDurationMs(current);
let elapsed = Date.now() - this.startedPlaying;
if (this._paused && this._pausedAt) {
elapsed = this._pausedAt - this.startedPlaying;
}
if (totalMs > 0 && elapsed > totalMs) elapsed = totalMs;
return Utils.prettifyMS(Math.max(0, elapsed));
},
/**
* Generate a text-based queue listing.
* @this {import('./Player.mjs').Player}
* @param {number} [page=1]
* @param {number} [pageSize=10]
* @returns {string}
*/
list(page = 1, pageSize = 10) {
const current = this.queue.getCurrent();
const total = this.queue.size();
let text = "";
if (current) {
const remaining = this.getQueueRemainingTime();
text += `🎧 **Queue**\n`;
text += `**${total} tracks** • ⏱️ ${remaining}\n`;
text += `${this._createProgressBar()}\n\n`;
text += `🎵 **Now Playing**\n`;
text += `${this.getVideoName(current)}\n\n`;
}
if (total === 0) { if (!current) text += "--- Empty ---"; return text; }
const { items, page: pg, totalPages, start } = this.queue.getPage(page, pageSize);
items.forEach((vid, i) => {
const index = String(start + i + 1).padStart(2, " ");
const name = this.getVideoName({ ...vid, title: Utils.truncate(vid.title, 60) });
text += `\`${index}.\` ${name}\n`;
});
text += `\nPage ${pg}/${totalPages} • Loop: ${this.queue.loop ? "🟢" : "🔴"}`;
return text;
},
/**
* @async Build a now-playing info object for the current track, including
* progress bar, volume, and loop states.
* @this {import('./Player.mjs').Player}
* @returns {Promise<{msg: string, image?: string}>}
*/
async nowPlaying() {
const current = this.queue.getCurrent();
if (!current) return { msg: "There's nothing playing at the moment." };
const loopqueue = this.queue.loop ? "🔄" : "⏹️";
const songloop = this.queue.songLoop ? "🔂" : "⏹️";
const vol = `${Math.round((this.preferredVolume || 1) * 100)}%`;
const autoplay = this._autoplay ? "🔁" : "⏹️";
const vcLine = this._channelId ? `🔊 <#${this._channelId}>\n` : "";
if (current.type === "radio") {
try {
const data = await meta(current.url);
return {
msg: `${vcLine}📻 **[${current.title}](${current.author?.url || current.url})**\n${current.description || ""}\n\n🎵 Now playing: ${data?.title || "Unknown"}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`,
image: current.thumbnail
};
} catch (e) {
logger.warn("[Player] Error:", e?.message);
return {
msg: `${vcLine}📻 **[${current.title}](${current.author?.url || current.url})**\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`,
image: current.thumbnail
};
}
}
if (current.type === "external" || current.type === "stream") {
const totalMs = this._getTrackDurationMs(current);
let progressLine = "";
if (totalMs > 0) {
progressLine = `\n${this._createProgressBar(20)}`;
}
return {
msg: `${vcLine}🎵 **[${current.title}](${current.url})** by ${current.artist || "Unknown"}${progressLine}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`,
image: current.thumbnail
};
}
const progressBar = this._createProgressBar(20);
let trackOptLine = "";
if (this._activeTrackOpt) {
const optStart = Utils.prettifyMS(this._activeTrackOpt.startMs);
const optEnd = this._activeTrackOpt.endMs > 0 ? Utils.prettifyMS(this._activeTrackOpt.endMs) : "end";
trackOptLine = `\n✂️ Custom: ${optStart} → ${optEnd}`;
}
return {
msg: `${vcLine}🎵 **[${current.title}](${current.spotifyUrl || current.url})**\n${progressBar}${trackOptLine}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`,
image: current.thumbnail
};
},
/**
* @async Get the thumbnail of the currently playing track.
* @this {import('./Player.mjs').Player}
* @returns {Promise<{msg: string, image: string|null}>}
*/
async getThumbnail() {
const current = this.queue.getCurrent();
if (!current) return { msg: "There's nothing playing at the moment.", image: null };
if (!current.thumbnail) return { msg: "No thumbnail available.", image: null };
return { msg: `Thumbnail of [${current.title}](${current.url}):`, image: current.thumbnail };
},
/**
* Format a track duration from various shapes.
* @this {import('./Player.mjs').Player}
* @param {*} duration
* @returns {string}
*/
getDuration(duration) {
if (typeof duration === "object" && duration?.timestamp) return duration.timestamp;
if (typeof duration === "object" && duration?.seconds != null) return Utils.formatSeconds(duration.seconds);
if (typeof duration === "string" && duration.startsWith("PT")) return Utils.prettifyMS(Utils.parseISODuration(duration));
return Utils.prettifyMS(duration);
},
/**
* @returns {string} Formatted duration of the currently playing track.
* @this {import('./Player.mjs').Player}
*/
getCurrentDuration() {
const current = this.queue.getCurrent();
if (!current?.duration) return "?:??";
return this.getDuration(current.duration);
},
/**
* Emit a now-playing announcement for the given track.
* @this {import('./Player.mjs').Player}
* @param {object} s
*/
announceSong(s) {
if (!s) return;
if (s.type === "radio") {
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses.radio.nowPlaying", {
title: Utils.escapeMarkdown(s.title),
author: s.author?.name || "Unknown",
url: s.author?.url || "",
channel: this._channelId || "",
}))] });
return;
}
const author = s.artists
? s.artists.map(a => a.url ? `[${a.name}](${a.url})` : a.name).join(" & ")
: s.author?.url
? `[${s.author.name}](${s.author.url})`
: s.author?.name || null;
if (!author && (s.type === "external" || s.type === "stream")) {
const desc = "🎵 Now playing [" + Utils.escapeMarkdown(s.title) + "](" + (s.url || "") + ") in <#" + (this._channelId || "") + ">";
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] });
return;
}
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses.play.nowPlaying", {
title: Utils.escapeMarkdown(s.title),
url: s.spotifyUrl || s.url,
author: author || "Unknown",
channel: this._channelId || "",
}))] });
},
};
export default DisplayMixin;
export { DisplayMixin };
+631
View File
@@ -0,0 +1,631 @@
/**
* @module src/music/player/PlaybackMixin
* @description Playback advancement concern for {@link Player}: track-end
* handling, playNext generation guarding, bridge playback with Lavalink
* pre-resolution, track-option timers, and lyrics.
*
* These methods are applied onto the Player class prototype via
* {@link applyMixins} — `this` is a Player instance.
*/
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../../ui/index.mjs";
import { Utils, cleanId } from "../../utils/Utils.mjs";
import { logger } from "../../core/Logger.mjs";
import meta from "../probe.mjs";
/**
* @type {object}
* @description Playback mixin — applied to Player.
*/
const PlaybackMixin = {
/**
* Handle the end of a track. Advances to the next song or starts the
* inactivity timer (if not 24/7). For radio tracks, stops playback.
* @this {import('./Player.mjs').Player}
* @private
*/
_handleTrackEnd() {
const songData = this.queue.getCurrent();
if (!songData) return;
this._clearTrackEndTimer();
if (songData.type === "radio") {
logger.player(`[Player] Radio track ended: ${songData.title}`);
this._lastPlayedTrack = this.queue.getCurrent() ?? songData;
this.queue.current = null;
this.emit("stopplay");
if (!this._is247Enabled()) {
this._startInactivityTimer();
}
return;
}
if (!this._paused) {
this._lastPlayedTrack = this.queue.getCurrent() ?? songData;
if (!this.queue.songLoop) this.queue.current = null;
this._playingNext = false;
this.playNext().catch(e => logger.error("[Player] auto-advance playNext error:", e.message));
}
},
/**
* @private Extract track duration in ms from various track data shapes.
* @this {import('./Player.mjs').Player}
* @param {object} track
* @returns {number}
*/
_getTrackDurationMs(track) {
if (track?._durationMs != null && track._durationMs > 0) {
return track._durationMs;
}
if (track?.duration) {
if (typeof track.duration === "object" && track.duration?.seconds != null) {
return track.duration.seconds * 1000;
}
if (typeof track.duration === "string" && track.duration.startsWith("PT")) {
return Utils.parseISODuration(track.duration);
}
if (typeof track.duration === "number") return track.duration;
}
if (track?.info?.length) return track.info.length;
if (track?.info?.duration != null) {
if (typeof track.info.duration === "number") return track.info.duration;
if (typeof track.info.duration === "object" && track.info.duration.seconds != null)
return track.info.duration.seconds * 1000;
}
return 0;
},
/**
* @private Check if a track has played past 85% or within 15s of the end.
* @this {import('./Player.mjs').Player}
* @param {object} track
* @returns {boolean}
*/
_didTrackMostlyFinish(track) {
const totalMs = this._getTrackDurationMs(track);
if (!totalMs || !this.startedPlaying) return false;
const elapsedMs = Math.max(0, Date.now() - this.startedPlaying);
const remainingMs = Math.max(0, totalMs - elapsedMs);
return elapsedMs / totalMs >= this.constructor.TRACK_MOSTLY_FINISHED_RATIO || remainingMs <= this.constructor.TRACK_MOSTLY_FINISHED_FLOOR_MS;
},
/**
* @async Advance to the next track. Guarded against overlapping runs: a
* generation counter ensures an older run's cleanup never clears the
* in-flight flag of a newer run (which previously allowed double-advances).
* @this {import('./Player.mjs').Player}
* @returns {Promise<void>}
*/
async playNext() {
if (this._playingNext) return;
this._playingNext = true;
const generation = (this._playNextGeneration = (this._playNextGeneration ?? 0) + 1);
try { await this._doPlayNext(); }
finally { if (generation === this._playNextGeneration) this._playingNext = false; }
},
/**
* @private @async Core logic for advancing to the next track: resolves
* track options, announces, starts playback via the bridge, arms the
* track-end timer, and handles the queue-end path.
* @this {import('./Player.mjs').Player}
*/
async _doPlayNext() {
this._bridgeStop();
const currentBeforeNext = this.queue.getCurrent();
if (currentBeforeNext) this._lastPlayedTrack = currentBeforeNext;
const songData = this.queue.next();
if (!songData) {
this.emit("stopplay");
this.emit("queueEnd");
if (!this._is247Enabled()) {
this._startInactivityTimer();
} else {
logger.voice247("[Player] 24/7 enabled, staying in channel");
}
if (!this._wasRadio && !this._queueEndedSent && !this._autoplay) {
this._queueEndedSent = true;
const prefix = this._getPrefix?.(this._guildId) ?? "%";
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true });
}
this._wasRadio = false;
return;
}
this._stopInactivityTimer();
this._wasRadio = songData.type === "radio";
if (!this._voiceConn || this.leaving) return;
if (this.preferredVolume !== 1 && this._voiceConn) {
try { this._voiceConn.setVolume(this.preferredVolume * 100); } catch(_) {}
}
if (!this._voiceConn || this.leaving) return;
this._activeTrackOpt = null;
this._clearTrackEndTimer();
let trackOptMatch = null;
try {
trackOptMatch = await this._lookupTrackOptions(songData);
} catch (e) {
logger.warn("[Player] TrackOptions lookup error:", e.message);
}
if (trackOptMatch) {
this._activeTrackOpt = trackOptMatch;
}
logger.player(`[Player:${this._guildId}] Playing: ${songData.title}`);
this.startedPlaying = Date.now();
this._paused = false;
this._pausedAt = null;
this._queueEndedSent = false;
this._consecutiveErrors = 0;
if (songData.type !== "radio" || !this._radioAnnounced) {
this.announceSong(songData);
if (songData.type === "radio") this._radioAnnounced = true;
}
this.emit("startplay", songData);
try {
const playUri = songData.url;
const seekSec = trackOptMatch?.startMs > 0 ? trackOptMatch.startMs / 1000 : 0;
if (!playUri || !Utils.isValidUrl(playUri)) {
logger.warn(`[Player] No valid URL for track: ${songData.title} (url=${songData.url}), trying search...`);
try {
if (this._lavalink) {
const result = await this._lavalink.search(songData.title, { source: "ytmsearch" });
const track = result?.tracks?.[0];
if (track?.info?.uri) {
songData.url = track.info.uri;
if (track.encoded) songData.encoded = track.encoded;
await this._playTrackViaBridge(songData, { seekSeconds: seekSec });
} else {
throw new Error("No tracks found for title search");
}
} else {
throw new Error("No Lavalink for fallback search");
}
} catch (searchErr) {
logger.error("[Player] Could not resolve track:", searchErr?.message);
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.couldNotGetStream", { title: songData.title }))] });
this.emit("stopplay");
if (!this._is247Enabled()) {
this._startInactivityTimer();
}
return;
}
} else {
await this._playTrackViaBridge(songData, { seekSeconds: seekSec });
}
if (trackOptMatch && trackOptMatch.endMs > 0) {
const elapsedMs = Date.now() - this.startedPlaying;
const remainingMs = trackOptMatch.endMs - elapsedMs;
if (remainingMs > 0) {
const match = trackOptMatch;
this._trackEndTimer = setTimeout(() => this._onTrackEndTimeReached(match), remainingMs);
}
}
} catch (err) {
logger.error("[Player] Play error:", err.message);
if (!this._skipping && !this.leaving && !this._paused && songData.type !== "radio") {
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.errorStreaming", { title: songData.title }))] });
}
if (!this._skipping && !this.leaving) {
this._consecutiveErrors = (this._consecutiveErrors || 0) + 1;
if (this._consecutiveErrors <= 3) {
this._handleTrackEnd();
} else {
logger.error(`[Player] ${this._consecutiveErrors} consecutive play errors — stopping auto-advance`);
this._consecutiveErrors = 0;
this.emit("stopplay");
if (!this._is247Enabled()) {
this._startInactivityTimer();
}
}
}
}
},
/**
* @private @async Play a track through the FluxerAudioBridge. For
* radio/external tracks without an encoded payload, attempts Lavalink URL
* resolution first so MP3/AAC streams can use the loadstream pipeline.
* @this {import('./Player.mjs').Player}
* @param {object} songData
* @param {object} [options={}]
* @returns {Promise<void>}
*/
async _playTrackViaBridge(songData, options = {}) {
if (!this._voiceConn || !this._audioBridge) {
throw new Error("No voice connection or audio bridge available");
}
if (!songData?.encoded && !songData?.url) {
throw new Error("No encoded track or URL for: " + (songData?.title ?? "unknown"));
}
if (!songData.encoded && songData.url && songData.url.startsWith("http") && this._lavalink && songData.type !== "external") {
try {
const nlInfo = this._lavalink.getNodeLinkInfo?.();
if (nlInfo) {
const protocol = nlInfo.secure ? "https" : "http";
const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port;
const headers = { "Authorization": nlInfo.password };
if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId;
if (this._guildId) headers["Guild-Id"] = this._guildId;
const loadtracksUrl = baseUrl + "/v4/loadtracks?identifier=" + encodeURIComponent(songData.url);
logger.player(`[Player] Pre-resolving ${songData.type || "external"} URL via Lavalink...`);
const body = await this._request(loadtracksUrl, { headers });
const track = body?.data?.tracks?.[0] ?? body?.tracks?.[0] ?? body?.data;
const encoded = track?.encoded ?? track?.data;
if (encoded && typeof encoded === "string") {
songData.encoded = encoded;
logger.player("[Player] Lavalink pre-resolve succeeded — track now has encoded payload");
} else {
logger.player("[Player] Lavalink pre-resolve: no encoded track returned, bridge will try direct URL");
}
}
} catch (e) {
logger.warn("[Player] Lavalink pre-resolve failed (bridge will try direct URL): " + e.message);
}
}
this._audioBridge._conn = this._voiceConn;
const seekMs = Math.floor((options.seekSeconds ?? 0) * 1000);
const totalMs = this._getTrackDurationMs(songData);
const durationMs = totalMs > 0 ? Math.max(0, totalMs - seekMs) : 0;
const result = await this._audioBridge.play(this._voiceConn, {
encoded: songData.encoded,
url: songData.url,
title: songData.title,
guildId: this._guildId,
}, {
seekSeconds: options.seekSeconds ?? 0,
durationMs,
videoId: songData.videoId || null,
filterPayload: this.activeFilterPayload || null,
});
if (result === "finished" && !this._skipping && !this.leaving && !this._paused) {
this._handleTrackEnd();
} else if (result === "stopped") {
// Stopped intentionally (skip/seek/stop) — nothing to do.
}
},
/**
* @private Handle when a track option's end time is reached.
* @this {import('./Player.mjs').Player}
* @param {object} match
*/
_onTrackEndTimeReached(match) {
if (this._destroyed || this.leaving || !this._activeTrackOpt) return;
logger.player(`[Player] TrackOptions: end time reached (${match.endMs}ms), skipping track`);
this._activeTrackOpt = null;
this._trackEndTimer = null;
this._trackEndRemainingMs = null;
this._skipping = true;
this._bridgeStop();
this._playingNext = false;
this._lastPlayedTrack = this.queue.getCurrent() ?? this._lastPlayedTrack;
this.emit("trackSkip", this._lastPlayedTrack);
if (!this.queue.isEmpty() && !this.leaving) {
this.playNext().catch(e => logger.error("[Player] TrackEnd playNext error:", e.message));
} else {
this.queue.current = null;
if (!this._wasRadio && !this._queueEndedSent) {
this._queueEndedSent = true;
this.emit("queueEnd");
if (!this._autoplay) {
const prefix = this._getPrefix?.(this._guildId) ?? "%";
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true });
}
}
this.emit("stopplay");
if (!this._is247Enabled()) {
this._startInactivityTimer();
}
}
this._skipping = false;
},
/**
* @private Clear the track-end timer.
* @this {import('./Player.mjs').Player}
*/
_clearTrackEndTimer() {
if (this._trackEndTimer) {
clearTimeout(this._trackEndTimer);
this._trackEndTimer = null;
}
this._trackEndRemainingMs = null;
},
/**
* @private Pause the track-end timer, saving remaining time.
* @this {import('./Player.mjs').Player}
*/
_pauseTrackEndTimer() {
if (!this._trackEndTimer || !this._activeTrackOpt || this._activeTrackOpt.endMs <= 0) return;
clearTimeout(this._trackEndTimer);
const elapsedMs = Date.now() - this.startedPlaying;
this._trackEndRemainingMs = Math.max(0, this._activeTrackOpt.endMs - elapsedMs);
this._trackEndTimer = null;
},
/**
* @private Resume the track-end timer.
* @this {import('./Player.mjs').Player}
*/
_resumeTrackEndTimer() {
if (this._trackEndRemainingMs == null || this._trackEndRemainingMs <= 0 || !this._activeTrackOpt || this._activeTrackOpt.endMs <= 0) {
this._trackEndRemainingMs = null;
return;
}
const remainingMs = this._trackEndRemainingMs;
const match = this._activeTrackOpt;
this._trackEndTimer = setTimeout(() => this._onTrackEndTimeReached(match), remainingMs);
this._trackEndRemainingMs = null;
},
/**
* @private Recalculate and restart the track-end timer (after a seek).
* @this {import('./Player.mjs').Player}
*/
_recalcTrackEndTimer() {
if (!this._activeTrackOpt || this._activeTrackOpt.endMs <= 0) return;
this._clearTrackEndTimer();
const elapsedMs = Date.now() - this.startedPlaying;
const remainingMs = this._activeTrackOpt.endMs - elapsedMs;
if (remainingMs <= 0) {
this._onTrackEndTimeReached(this._activeTrackOpt);
return;
}
const match = this._activeTrackOpt;
this._trackEndTimer = setTimeout(() => this._onTrackEndTimeReached(match), remainingMs);
},
/**
* @async Seek to a specific position in the currently playing track.
* @this {import('./Player.mjs').Player}
* @param {number} ms - Target position in milliseconds.
* @returns {Promise<boolean>} True if seek succeeded, false otherwise.
*/
async seekToPosition(ms) {
if (!this._voiceConn || !this.queue.getCurrent()) return false;
this._seeking = true;
try {
this._bridgeStop();
const current = this.queue.getCurrent();
if (current?.url) {
this.startedPlaying = Date.now() - ms;
await this._playTrackViaBridge(current, { seekSeconds: ms / 1000 });
}
logger.player(`[Player] Seeked to ${ms}ms — adjusted startedPlaying`);
this._recalcTrackEndTimer();
return true;
} catch (e) {
this._seeking = false;
logger.error("[Player] Seek failed:", e?.message);
return false;
} finally {
this._seeking = false;
}
},
/**
* @async Apply an audio filter to playback. Stores filter metadata for
* dashboard tracking; filters are applied server-side by NodeLink on the
* next track.
* @this {import('./Player.mjs').Player}
* @param {object} filterPayload
* @param {object|null} [filterMeta=null]
* @returns {Promise<{ok: boolean, reason?: string, pending?: boolean}>}
*/
async applyFilter(filterPayload, filterMeta = null) {
if (!this._guildId) {
return { ok: false, reason: "Player not bound to a guild." };
}
const current = this.queue.getCurrent();
this.activeFilter = filterMeta ?? null;
this.activeFilterPayload = filterMeta ? filterPayload : null;
this.emit("filter", this.activeFilter);
if (!current?.encoded || !this._voiceConn) {
return { ok: true, pending: true };
}
return { ok: true };
},
/**
* Clear any active audio filter.
* @this {import('./Player.mjs').Player}
*/
clearFilter() {
this.activeFilter = null;
this.activeFilterPayload = null;
this.emit("filter", null);
logger.warn("[Player] clearFilter: filters not supported in LiveKit mode");
},
/**
* @private @async Look up per-user track options for the humans currently
* in the player's channel.
* @this {import('./Player.mjs').Player}
* @param {object} songData
* @returns {Promise<object|null>}
*/
async _lookupTrackOptions(songData) {
if (!this.trackOptions || !songData || songData.type === "radio") return null;
if (!this._guildId || !this._channelId) return null;
const userIds = [];
if (this._voiceCache) {
const humans = this._voiceCache.getHumansInChannel(
cleanId(this._guildId),
cleanId(this._channelId)
);
userIds.push(...humans);
}
if (userIds.length === 0) {
try {
const guild = this.client?.guilds?.get?.(this._guildId);
const voiceStates = guild?.voice_states ?? guild?.voiceStates;
if (voiceStates) {
const entries = Array.isArray(voiceStates) ? voiceStates
: typeof voiceStates.values === "function" ? [...voiceStates.values()]
: Object.values(voiceStates);
for (const state of entries) {
const ch = cleanId(state?.channelId ?? state?.channel_id ?? "");
if (ch === cleanId(this._channelId)) {
const uid = state?.userId ?? state?.user_id;
const member = guild?.members?.get?.(uid);
if (uid && !member?.user?.bot) userIds.push(uid);
}
}
}
} catch(e) { logger.warn("[Player] Voice state lookup error:", e?.message); }
}
if (userIds.length === 0) return null;
const match = await this.trackOptions.getBestMatchForChannel(userIds, songData);
return match || null;
},
/**
* @private @async Auto-seek to a track options start position.
* @this {import('./Player.mjs').Player}
* @param {object} match
*/
async _applyTrackOptionsSeek(match) {
if (!match || match.startMs <= 0) return;
const current = this.queue.getCurrent();
if (!current?.url || !this._voiceConn || this.leaving) {
logger.warn(`[Player] TrackOptions: cannot seek (encoded=${!!current?.encoded} lavalinkPlayer=${!!this.lavalinkPlayer} leaving=${this.leaving})`);
return;
}
let seeked = false;
for (let attempt = 0; attempt < 10; attempt++) {
await Utils.sleep(500);
try {
const result = await this.seekToPosition(match.startMs);
if (result) {
seeked = true;
logger.player(`[Player] TrackOptions: auto-seeked to ${match.startMs}ms for user ${match.userId} (attempt ${attempt + 1})`);
break;
}
} catch (e) {
logger.warn(`[Player] TrackOptions auto-seek attempt ${attempt + 1} error:`, e.message);
}
}
if (!seeked) {
logger.warn(`[Player] TrackOptions: auto-seek to ${match.startMs}ms failed after all retries`);
}
},
/**
* @async Apply a track options match (custom start/end times) to the
* currently playing track.
* @this {import('./Player.mjs').Player}
* @param {object} match - Track options match with startMs and optional endMs.
* @returns {Promise<boolean>} True if applied successfully, false otherwise.
*/
async applyTrackOption(match) {
if (!match || !this._voiceConn || this._paused) return false;
this._clearTrackEndTimer();
this._activeTrackOpt = null;
try {
await this.seekToPosition(match.startMs || 0);
} catch (e) {
logger.warn("[Player] TrackOptions apply-seek error:", e.message);
return false;
}
if (match.endMs > 0) {
const elapsedMs = Date.now() - this.startedPlaying;
const remainingMs = match.endMs - elapsedMs;
if (remainingMs > 0) {
this._activeTrackOpt = match;
this._trackEndTimer = setTimeout(() => this._onTrackEndTimeReached(match), remainingMs);
}
} else {
this._activeTrackOpt = match;
}
return true;
},
/**
* @async Fetch lyrics for the currently playing track via the Lavalink
* REST API.
* @this {import('./Player.mjs').Player}
* @returns {Promise<{text: string, source: string, synced: boolean, lines: Array}|null>}
*/
async lyrics() {
const current = this.queue.getCurrent();
if (!current) return null;
const node = this._lavalink?.getNode?.() ?? null;
if (node) {
try {
const searchQuery = current.artists?.[0]?.name
? `${current.title} ${current.artists[0].name}`
: current.title;
const path = current.encoded
? `/loadlyrics?encodedTrack=${encodeURIComponent(current.encoded)}`
: `/loadlyrics?identifier=${encodeURIComponent(searchQuery)}`;
const results = await node.request(path);
if (results?.data?.lines?.length) {
return {
text: results.data.lines.map(l => l.text).join("\n"),
source: "Lavalink",
synced: results.data.lines.some(l => l.startTimeMs != null),
lines: results.data.lines,
};
}
} catch (e) {
logger.player(`[Lyrics] Lavalink REST lyrics failed: ${e.message}`);
}
}
return null;
},
};
export default PlaybackMixin;
export { PlaybackMixin };
+993
View File
@@ -0,0 +1,993 @@
/**
* @module src/music/player/Player
* @description Per-channel music player: voice connection lifecycle (join /
* leave / destroy / rejoin), playback controls (pause, resume, skip, seek,
* volume, filters), queue operations, 24/7 mode helpers and the inactivity
* timer. Playback advancement, search and display rendering live in the
* playback/search/display mixin modules applied at the bottom of this file.
*/
import { getVoiceManager } from "@fluxerjs/voice";
import { EventEmitter } from "node:events";
import http from "node:http";
import https from "node:https";
import { EmbedBuilder } from "@fluxerjs/core";
import { getGlobalColor } from "../../ui/index.mjs";
import { Utils, cleanId } from "../../utils/Utils.mjs";
import { logger } from "../../core/Logger.mjs";
import { get247ChannelMode } from "../../utils/Helpers247.mjs";
import { hasHumansInChannel } from "../../voice/VoiceStateResolver.mjs";
import { FluxerAudioBridge } from "../audio/FluxerAudioBridge.mjs";
import { applyMixins } from "../../utils/mixins.mjs";
import { Queue } from "./Queue.mjs";
import PlaybackMixin from "./PlaybackMixin.mjs";
import SearchMixin from "./SearchMixin.mjs";
import DisplayMixin from "./DisplayMixin.mjs";
/**
* @class Player
* @description Main music player class. Manages voice connections, playback,
* queue, filters, and search.
* @extends {EventEmitter}
*
* Events:
* - `"queue"` — queue mutation (proxied from the Queue)
* - `"message"` — announcements `{ embeds: [...] }` (or a plain string)
* - `"startplay"` / `"stopplay"` / `"queueEnd"` / `"trackSkip"`
* - `"playback"` (paused state boolean), `"volume"`, `"filter"`
* - `"autoleave"`, `"leave"`, `"roomfetched"`
*/
class Player extends EventEmitter {
/** @private @type {object|null} The LiveKit voice connection. */
_voiceConn = null;
/** @private @type {FluxerAudioBridge|null} */
_audioBridge = null;
lavalinkPlayer = null;
/** @type {object|null} Alias of _voiceConn (kept for dashboard/debug compat). */
connection = null;
/** @private @type {string|null} */
_guildId = null;
/** @private @type {string|null} */
_channelId = null;
/** @private @type {number|null} */
_lastConnectedAt = null;
/** @private @type {string|null} The home channel of a 24/7 spawn. */
_home247Channel = null;
/** @type {Queue} */
queue = null;
client = null;
settings = null;
config = {};
/** @type {import('../LavalinkManager.mjs').LavalinkManager|null} */
_lavalink = null;
leaving = false;
_paused = false;
_pausedAt = null;
_playingNext = false;
startedPlaying = null;
/** @type {Map<string, Array>} Search sessions by key. */
searches = new Map();
_searchMaxSize = 50;
_maxQueueSize = 10_000;
resultLimit = 5;
preferredVolume = 1;
_skipping = false;
_seeking = false;
_wasRadio = false;
_radioAnnounced = false;
_queueEndedSent = false;
_lastPlayedTrack = null;
_autoplay = false;
_autoplayHandler = null;
activeFilter = null;
activeFilterPayload = null;
/** @type {number} Default inactivity timeout before auto-leave. */
static INACTIVITY_DEFAULT_MS = 3 * 60 * 1000;
/** @type {number} Track is considered finished past this ratio. */
static TRACK_MOSTLY_FINISHED_RATIO = 0.85;
/** @type {number} Or when less than this much time remains. */
static TRACK_MOSTLY_FINISHED_FLOOR_MS = 15_000;
/** @type {number} Hard radio safety timeout. */
static RADIO_SAFETY_TIMEOUT_MS = 20 * 60 * 1000;
/** @private @type {Timeout|null} */
_inactivityTimer = null;
/** @private @type {number} */
_inactivityLimit = Player.INACTIVITY_DEFAULT_MS;
/** @private @type {boolean} */
_pendingInactivityCheck = false;
/** @private @type {boolean} */
_isJoining = false;
/** @private @type {boolean} */
_destroyed = false;
/** @private @type {Timeout|null} */
_rejoinTimer = null;
/**
* @param {string} token - Bot authentication token (used internally).
* @param {object} [opts={}] - Player configuration options.
* @param {import('@fluxerjs/core').Client} [opts.client]
* @param {object} [opts.config]
* @param {import('../LavalinkManager.mjs').LavalinkManager} [opts.lavalink]
* @param {import('../../db/Settings.mjs').RemoteSettingsManager} [opts.settingsMgr]
* @param {Function} [opts.getPrefix]
* @param {import('../../voice/VoiceStateCache.mjs').VoiceStateCache} [opts.observedVoiceUsers]
* @param {import('../../voice/VoiceStateCache.mjs').VoiceStateCache} [opts.voiceCache]
* @param {import('../../core/Locale.mjs').Locale} [opts.locale]
* @param {import('../../services/TrackOptionsManager.mjs').TrackOptionsManager} [opts.trackOptions]
*/
constructor(token, opts = {}) {
super();
this.queue = new Queue();
this.queue.on("queue", (...args) => this.emit("queue", ...args));
this.client = opts.client;
this.config = opts.config ?? {};
this.settings = opts.settings ?? null;
this.settingsMgr = opts.settingsMgr ?? null;
this._getPrefix = opts.getPrefix ?? null;
this._observedVoiceUsers = opts.observedVoiceUsers ?? null;
this._voiceCache = opts.voiceCache ?? null;
this.locale = opts.locale ?? null;
this.trackOptions = opts.trackOptions ?? null;
this._activeTrackOpt = null;
this._lavalink = opts.lavalink ?? null;
this._audioBridge = new FluxerAudioBridge(opts.lavalink ?? null);
this._audioBridge.on("error", (err) => {
logger.error(`[Player] Audio bridge error (guild ${this._guildId}): ${err.message}`);
});
const inactivityMs = this.config?.timers?.inactivityTimeout ?? this.config?.inactivityTimeout;
if (inactivityMs !== undefined) {
const parsed = Number(inactivityMs);
if (!Number.isNaN(parsed) && parsed >= 0) {
this._inactivityLimit = parsed;
}
}
if (this._lavalink) {
this._onLavalinkPlayerDisconnect = (lavaPlayer) => {
if (!lavaPlayer || String(lavaPlayer.guildId) !== String(this._guildId)) return;
logger.lavalink("[Player] lavalink-client player disconnect (guild: " + this._guildId + ") — ignored (voice via LiveKit)");
};
this._lavalink.on("playerDisconnected", this._onLavalinkPlayerDisconnect);
}
}
/**
* Check whether 24/7 mode is active for this player's current channel.
* @returns {boolean} True if 24/7 is enabled.
*/
_is247Enabled() {
return this._get247Mode() !== "off";
}
/**
* Resolve the 24/7 mode for this player's current or home channel by
* consulting the guild's stay_247 setting.
* @returns {"on"|"off"} The 24/7 mode. Only "on" or "off" — no "auto".
* @private
*/
_get247Mode() {
if (!this._guildId) return "off";
const serverSettings = this.settingsMgr?.getServer?.(this._guildId)
?? this.settings
?? this.client?.settings?.getServer?.(this._guildId);
if (!serverSettings?.get) return "off";
const channelId = cleanId(this._home247Channel ?? this._channelId ?? "");
if (!channelId) return "off";
const raw = serverSettings.get("stay_247");
if (raw && raw !== "none") {
const channels = Array.isArray(raw)
? raw.map(id => cleanId(id)).filter(Boolean)
: [cleanId(raw)].filter(Boolean);
if (!channels.includes(channelId)) return "off";
} else {
return "off";
}
return get247ChannelMode(serverSettings, channelId);
}
/** @private @returns {string|null} The cleaned guild ID, or null if unresolvable. */
_resolveGuildId() {
const cleanGuild = cleanId(this._guildId ?? "");
if (cleanGuild) return cleanGuild;
try {
const channelId = this._channelId ?? this._home247Channel;
if (channelId) {
const ch = this.client?.channels?.get?.(channelId);
const fromChannel = ch?.guildId ?? ch?.guild?.id ?? null;
if (fromChannel) return cleanId(fromChannel);
}
} catch(e) { logger.warn("[Player] Guild resolution failed:", e?.message); }
return null;
}
/** @private Restore saved volume from guild settings. */
_restoreVolume() {
if (!this._guildId) return;
let savedVol = null;
if (this.settings?.get) {
savedVol = this.settings.get("volume");
} else if (this.settingsMgr?.getServer) {
const set = this.settingsMgr.getServer(this._guildId);
savedVol = set?.get?.("volume");
} else if (this.client?.settings?.getServer) {
savedVol = this.client.settings.getServer(this._guildId)?.get?.("volume");
} else if (this.client?.settings?.get) {
const s = this.client.settings.get(this._guildId);
savedVol = s?.get?.("volume") ?? s?.volume;
}
if (savedVol !== undefined && savedVol !== null) {
const parsed = Number(savedVol);
if (!Number.isNaN(parsed) && parsed > 0) {
this.preferredVolume = Utils.clamp(parsed / 100, 0, 2);
logger.player(`[Player] Restored volume ${savedVol}% for guild ${this._guildId}`);
if (this._voiceConn) {
try { this._voiceConn.setVolume(this.preferredVolume * 100); } catch (_) {}
}
}
}
}
/** @private @returns {boolean} Whether there are non-bot users in the channel. */
_hasHumansInChannel() {
return hasHumansInChannel({
guildId: cleanId(this._guildId ?? ""),
channelId: cleanId(this._channelId ?? ""),
client: this.client,
voiceCache: this._voiceCache,
observedVoiceUsers: this._observedVoiceUsers,
botId: this.client?.user?.id,
});
}
/**
* Start the inactivity timer. Skipped when 24/7 is active, the queue has
* songs, or humans are present. The timer callback re-checks all
* conditions before emitting autoleave.
*/
_startInactivityTimer() {
this._stopInactivityTimer();
if (this._inactivityLimit <= 0) return;
const mode = this._get247Mode();
logger.inactivity(`[Player] Checking 24/7 mode for guild ${this._guildId}: ${mode}`);
if (mode === "on") {
logger.inactivity(`[Player] 24/7 mode active for guild ${this._guildId}, skipping inactivity timer`);
return;
}
if (this.queue?.getCurrent() || !this.queue?.isEmpty()) {
logger.inactivity(`[Player] Queue has songs for guild ${this._guildId}, skipping inactivity timer`);
return;
}
if (this._hasHumansInChannel()) {
logger.inactivity(`[Player] Humans present in channel ${this._channelId}, skipping inactivity timer`);
return;
}
logger.inactivity(`[Player] Starting inactivity timer for guild ${this._guildId} (${this._inactivityLimit / 1000}s)`);
this._inactivityTimer = setTimeout(() => {
const currentMode = this._get247Mode();
if (currentMode === "on") {
logger.inactivity(`[Player] 24/7 mode enabled during inactivity wait, aborting leave`);
return;
}
if (this.queue?.getCurrent() || !this.queue?.isEmpty()) {
logger.inactivity("[Player] Song in queue during inactivity wait, aborting leave");
return;
}
if (this._hasHumansInChannel()) {
logger.inactivity("[Player] Human joined during inactivity wait, aborting leave");
return;
}
logger.inactivity(`[Player] Guild ${this._guildId} inactive too long. Leaving.`);
this.emit("autoleave");
}, this._inactivityLimit);
}
/** Clear the inactivity timer if running. */
_stopInactivityTimer() {
this._pendingInactivityCheck = false;
if (this._inactivityTimer) {
logger.inactivity(`[Player] Stopping inactivity timer for guild ${this._guildId}`);
clearTimeout(this._inactivityTimer);
this._inactivityTimer = null;
}
}
/**
* Schedule a 24/7 rejoin after a delay. Guards against destroyed players,
* registered intentional leaves, and pending/duplicate joins.
* @param {string} channelId - The channel to rejoin.
* @param {string} guildId - The guild ID.
* @param {string} mode - The 24/7 mode ("on").
* @private
*/
_schedule247Rejoin(channelId, guildId, mode) {
const ctx = this.client?._remix;
if (!ctx) {
logger.warn(`[Player] Cannot schedule 24/7 rejoin for ${channelId} — no bot context`);
return;
}
if (ctx.players?._pendingJoins?.has?.(channelId)) {
logger.voice247(`[Player] 24/7 rejoin skipped for ${channelId} — join already pending`);
return;
}
if (ctx.players?.playerMap?.has(channelId)) {
const existing = ctx.players.playerMap.get(channelId);
if (existing && !existing._destroyed && existing !== this) {
logger.voice247(`[Player] 24/7 rejoin skipped for ${channelId} — another player already exists`);
return;
}
}
const rejoinDelay = ctx.config?.timers?.rejoin247Delay ?? 3_000;
logger.voice247(`[Player] Scheduling 24/7 ${mode} rejoin for channel ${channelId} (guild ${guildId}) in ${rejoinDelay / 1000}s`);
this._rejoinTimer = setTimeout(() => {
this._rejoinTimer = null;
if (this._destroyed) {
logger.voice247(`[Player] 24/7 rejoin cancelled — player destroyed`);
return;
}
if (ctx.intentionalLeaves?.has(channelId)) {
logger.voice247(`[Player] 24/7 rejoin cancelled — intentional leave registered`);
return;
}
ctx.gatewayHandler?._rejoinChannel?.(guildId, channelId).catch(err => {
logger.warn(`[Player] 24/7 rejoin failed for channel ${channelId}:`, err?.message);
});
}, rejoinDelay);
}
/**
* @private Low-level HTTP(S) request helper with redirects and JSON parsing.
* Used for Lavalink REST calls (pre-resolve, loadtracks).
* @param {string} url
* @param {object} [options={}]
* @param {boolean} [returnStream=false]
* @returns {Promise<object|null|import('node:stream').Readable>}
*/
async _request(url, options = {}, returnStream = false) {
return new Promise((resolve, reject) => {
const fetchUrl = (target, _redirects = 0) => {
const urlObj = new URL(target);
const client = urlObj.protocol === "https:" ? https : http;
const req = client.request({
protocol: urlObj.protocol,
host: urlObj.hostname,
port: urlObj.port,
path: urlObj.pathname + urlObj.search,
method: options.method || "GET",
headers: {
"User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)",
"Accept": "*/*",
...options.headers,
},
}, (res) => {
if (returnStream) req.setTimeout(0);
if ([301, 302, 307, 308].includes(res.statusCode)) {
let loc = res.headers.location;
if (!loc) return reject(new Error("Redirect without location"));
if (loc.startsWith("/")) loc = `${urlObj.protocol}//${urlObj.host}${loc}`;
if (_redirects >= 5) return reject(new Error("Too many redirects"));
const redirectUrl = new URL(loc);
if (redirectUrl.host !== urlObj.host) {
if (options.headers) delete options.headers.Authorization;
}
return fetchUrl(loc, _redirects + 1);
}
if (![200, 204, 206].includes(res.statusCode)) {
res.resume();
return reject(new Error(`HTTP ${res.statusCode}`));
}
if (returnStream) return resolve(res);
if (res.statusCode === 204) { res.resume(); return resolve(null); }
const chunks = [];
res.on("data", d => chunks.push(d));
res.on("end", () => {
const raw = Buffer.concat(chunks).toString().trim();
if (!raw) return resolve(null);
try { resolve(JSON.parse(raw)); }
catch (e) { reject(new Error(`JSON parse error from ${target}`)); }
});
});
req.on("error", reject);
req.setTimeout(options.timeout || 60_000, () => {
req.destroy();
reject(new Error("Request timeout"));
});
if (options.body) req.write(options.body);
req.end();
};
fetchUrl(url);
});
}
/**
* @async Join a voice channel via LiveKit. Sets up voice connection, event
* listeners, and resumes playback if the queue has tracks.
* @param {string} channelId - The voice channel ID to join.
* @returns {Promise<void>}
* @throws {Error} If the channel is not found, VoiceManager is unavailable, or connection fails.
*/
async join(channelId) {
if (this._destroyed) return;
if (this._isJoining) {
logger.player(`[Player] Busy joining. Ignoring: ${channelId}`);
return;
}
if (this._voiceConn && this._channelId === channelId) {
logger.player(`[Player] Already in channel: ${channelId}`);
return;
}
if (this._voiceConn) {
logger.player("[Player] Cleaning up existing voice connection before join");
this._bridgeStop();
try { await this._voiceConn.disconnect(); } catch(e) { logger.warn("[Player] Existing voiceConn disconnect error:", e?.message); }
this._voiceConn = null;
this.connection = null;
await Utils.sleep(500);
}
this._isJoining = true;
try {
const channel = this.client?.channels?.get?.(channelId);
if (!channel) throw new Error(`Channel not found: ${channelId}`);
if (this._lavalink) {
logger.player(`[Player] Waiting for Lavalink node...`);
await this._lavalink.waitForNode({ timeoutMs: 15_000 });
}
this._channelId = channelId;
this._guildId = cleanId(channel.guildId);
this._lastConnectedAt = Date.now();
this.leaving = false;
logger.player(`[Player] Joining channel ${channelId} via vm.join() (LiveKit)...`);
const vm = getVoiceManager(this.client);
if (!vm) {
throw new Error("VoiceManager not available — call getVoiceManager(client) before login");
}
let voiceConn;
try {
voiceConn = await vm.join(channel);
} catch (e) {
throw new Error(`vm.join() failed for channel ${channelId}: ${e.message}`);
}
if (!voiceConn) {
throw new Error(`vm.join() returned null for channel ${channelId}`);
}
this._voiceConn = voiceConn;
this.connection = voiceConn;
if (typeof voiceConn.isConnected === "function" && !voiceConn.isConnected()) {
logger.player("[Player] Waiting for LiveKit room to connect...");
await new Promise((resolve, reject) => {
const timeout = setTimeout(() => reject(new Error("LiveKit connection timeout (15s)")), 15_000);
const check = () => {
try {
if (voiceConn.isConnected()) { clearTimeout(timeout); return resolve(); }
if (voiceConn.connectionState === 0) { clearTimeout(timeout); return resolve(); }
} catch (_) { clearTimeout(timeout); return resolve(); }
setTimeout(check, 200);
};
check();
});
await Utils.sleep(500);
}
logger.player(`[Player] LiveKit voice connected (guild: ${this._guildId}, channel: ${channelId})` +
` isConnected=${voiceConn.isConnected ? voiceConn.isConnected() : 'unknown'}`);
this._assertSelfDeaf(vm, channelId);
if (typeof voiceConn.on === "function") {
// Self-deaf keeper: Fluxer's VoiceManager answers every
// requestVoiceStateSync event (emitted by conn.stop()/stopVideo(),
// which the audio bridge triggers on EVERY play() and stop()) with a
// gateway VoiceStateUpdate that resets self_deaf to false — silently
// un-deafening the bot the moment the first track starts and again on
// every skip/stop/track-end. The manager registers its own sync
// listener inside registerConnection() (before join() resolved), so
// this listener runs AFTER it and our re-deafen state update wins.
voiceConn.on("requestVoiceStateSync", () => {
if (this.leaving || this._destroyed) return;
this._assertSelfDeaf(vm, channelId);
});
voiceConn.on("serverLeave", () => {
if (this.leaving || this._destroyed) return;
logger.player(`[Player] serverLeave received — Fluxer/LiveKit terminated session`);
this._voiceConn = null;
this.connection = null;
this._paused = true;
this._stopInactivityTimer();
const mode = this._get247Mode();
const cId = cleanId(this._channelId ?? this._home247Channel ?? "");
const gId = cleanId(this._guildId ?? "");
if (mode === "on") {
logger.player("[Player] serverLeave in 24/7 mode — scheduling rejoin");
this.emit("autoleave");
if (cId && gId) this._schedule247Rejoin(cId, gId, mode);
} else {
logger.player("[Player] Unexpected serverLeave");
this.emit("autoleave");
}
});
voiceConn.on("disconnect", () => {
if (this.leaving || this._destroyed) return;
logger.player(`[Player] Voice connection disconnected`);
});
}
this._restoreVolume();
this.emit("roomfetched");
logger.player(`[Player] Voice connected to ${channel.name || channelId}`);
if (!this.queue.isEmpty() && !this.queue.getCurrent()) {
this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
} else if (this.queue.isEmpty()) {
this._pendingInactivityCheck = true;
setTimeout(() => {
if (!this._pendingInactivityCheck) return;
this._pendingInactivityCheck = false;
if (this.queue.isEmpty() && !this.queue.getCurrent()) {
this._startInactivityTimer();
}
}, 3000);
}
} catch (e) {
const causeStr = e.cause ? ` (Cause: ${e.cause})` : "";
logger.error("[Player] Join failed:", e.message, causeStr);
if (this._voiceConn) {
try { await this._voiceConn.disconnect(); } catch(err) { logger.warn("[Player] voiceConn disconnect on join failure:", err?.message); }
this._voiceConn = null;
this.connection = null;
}
throw e;
} finally {
this._isJoining = false;
}
}
/**
* @async Leave the current voice channel. Stops playback, resets state, and
* cleans up the voice connection.
* @returns {Promise<boolean>} True if leave was successful, false otherwise.
*/
async leave() {
if (!this._voiceConn && !this.connection) return false;
try {
this.leaving = true;
this._stopInactivityTimer();
this._clearTrackEndTimer();
this._activeTrackOpt = null;
const channelId = this._channelId;
this._bridgeStop();
try {
const vm = getVoiceManager(this.client);
if (channelId) {
vm.leaveChannel(channelId);
logger.player("[Player] Left channel " + channelId + " via vm.leaveChannel()");
}
} catch(e) { logger.warn("[Player] Gateway leave error:", e?.message); }
if (this._voiceConn) {
try { await this._voiceConn.disconnect(); } catch(e) { logger.warn("[Player] voiceConn disconnect error:", e?.message); }
}
if (this._audioBridge) {
this._audioBridge.stop();
}
this.queue.reset();
this._voiceConn = null;
this.lavalinkPlayer = null;
this.connection = null;
this._paused = false;
this._pausedAt = null;
this._playingNext = false;
this._autoplay = false;
if (this._autoplayHandler) {
this.removeListener("queueEnd", this._autoplayHandler);
this._autoplayHandler = null;
}
} catch (e) {
logger.error("[Player] leave error:", e.message);
this.leaving = false;
return false;
}
this.leaving = false;
this.emit("leave");
return true;
}
/**
* Fully destroy this player instance: clean up timers, listeners,
* connections, and resources.
*/
destroy() {
if (this._destroyed) return;
this._destroyed = true;
this._clearTrackEndTimer();
this._activeTrackOpt = null;
try {
if (this._lavalink) {
if (this._onLavalinkPlayerDisconnect) {
try { this._lavalink.off("playerDisconnected", this._onLavalinkPlayerDisconnect); } catch(e) { /* best effort */ }
this._onLavalinkPlayerDisconnect = null;
}
}
this.leaving = true;
this._stopInactivityTimer();
if (this._rejoinTimer) { clearTimeout(this._rejoinTimer); this._rejoinTimer = null; }
this._autoplay = false;
if (this._autoplayHandler) {
this.removeListener("queueEnd", this._autoplayHandler);
this._autoplayHandler = null;
}
this.searches.clear();
this._bridgeStop();
if (this._audioBridge) {
this._audioBridge.destroy();
this._audioBridge = null;
}
if (this._voiceConn) {
try { this._voiceConn.disconnect(); } catch(e) { logger.warn("[Player] voiceConn disconnect in destroy:", e?.message); }
this._voiceConn = null;
}
this.lavalinkPlayer = null;
this.connection = null;
if (this._channelId) {
try {
const vm = getVoiceManager(this.client);
vm.leaveChannel(this._channelId);
} catch(e) { /* best effort */ }
}
} catch (e) {
logger.error("[Player] destroy error:", e.message);
}
}
/** @type {boolean} Whether the player is currently paused. */
get paused() { return this._paused; }
/**
* Pause current playback.
* @returns {string} Status message.
*/
pause() {
if (!this._voiceConn || !this.queue.getCurrent())
return ":negative_squared_cross_mark: There's nothing playing at the moment!";
if (this._paused)
return ":negative_squared_cross_mark: Already paused!";
this._bridgeStop();
this._paused = true;
this._pausedAt = Date.now();
this._pauseTrackEndTimer();
this.emit("playback", false);
this._stopInactivityTimer();
return ":pause_button: Paused";
}
/**
* Resume paused playback.
* @returns {string} Status message.
*/
resume() {
if (!this._voiceConn || !this.queue.getCurrent())
return ":negative_squared_cross_mark: There's nothing playing at the moment!";
if (!this._paused)
return ":negative_squared_cross_mark: Not paused!";
if (this._pausedAt) {
this.startedPlaying += (Date.now() - this._pausedAt);
}
this._paused = false;
this._pausedAt = null;
this._resumeTrackEndTimer();
this.emit("playback", true);
this._stopInactivityTimer();
const current = this.queue.getCurrent();
if (current?.url) {
const elapsedMs = Date.now() - this.startedPlaying;
this._playTrackViaBridge(current, { seekSeconds: elapsedMs / 1000 }).catch(e =>
logger.error("[Player] Resume playback error:", e.message)
);
}
return ":arrow_forward: Resumed";
}
/**
* Skip the current track and advance to the next. Emits "trackSkip" with
* the skipped track so autoplay (when enabled) can replenish the queue.
* @returns {string} Status message.
*/
skip() {
if (!this._voiceConn || !this.queue.getCurrent())
return ":negative_squared_cross_mark: There's nothing playing at the moment!";
this._lastPlayedTrack = this.queue.getCurrent();
this._skipping = true;
this._radioAnnounced = false;
this._activeTrackOpt = null;
this._clearTrackEndTimer();
this.queue.current = null;
this._bridgeStop();
this.emit("trackSkip", this._lastPlayedTrack);
if (this.queue.isEmpty() && !this._wasRadio && !this._queueEndedSent) {
this._queueEndedSent = true;
this.emit("queueEnd");
if (!this._autoplay) {
const prefix = this._getPrefix?.(this._guildId) ?? "%";
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true });
}
}
this._playingNext = false;
if (!this.queue.isEmpty() && !this.leaving) {
this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
} else {
this.emit("stopplay");
if (!this._is247Enabled()) {
this._startInactivityTimer();
}
}
this._skipping = false;
return ":track_next: Skipped";
}
/**
* Skip to a specific position in the queue.
* @param {number} position - 1-based queue position.
* @returns {string} Status message.
*/
skipTo(position) {
if (!this._voiceConn || !this.queue.getCurrent())
return ":negative_squared_cross_mark: There's nothing playing at the moment!";
const idx = position - 1;
if (idx < 0 || idx >= this.queue.size())
return `:negative_squared_cross_mark: Position ${position} out of range (queue has ${this.queue.size()} tracks).`;
this._lastPlayedTrack = this.queue.getCurrent();
this.queue.data.splice(0, idx);
this.queue.current = null;
this._skipping = true;
this._bridgeStop();
this.emit("trackSkip", this._lastPlayedTrack);
if (this.queue.isEmpty() && !this._wasRadio && !this._queueEndedSent) {
this._queueEndedSent = true;
this.emit("queueEnd");
if (!this._autoplay) {
const prefix = this._getPrefix?.(this._guildId) ?? "%";
this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true });
}
}
this._playingNext = false;
if (!this.queue.isEmpty() && !this.leaving) {
this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
} else {
this.emit("stopplay");
if (!this._is247Enabled()) {
this._startInactivityTimer();
}
}
this._skipping = false;
return `:track_next: Skipped to position ${position}`;
}
/**
* Set the playback volume.
* @param {number} v - Volume as a decimal (0–2, where 1 = 100%).
* @returns {string} Status message.
*/
setVolume(v) {
this.preferredVolume = Utils.clamp(v, 0, 2);
this.emit("volume", this.preferredVolume);
if (this._voiceConn) {
this._voiceConn.setVolume(this.preferredVolume * 100);
}
if (!this._voiceConn)
return `Volume set to \`${Math.round(this.preferredVolume * 100)}%\` — will apply when connected.`;
return `Volume changed to \`${Math.round(this.preferredVolume * 100)}%\`.`;
}
/** @returns {boolean} Whether the queue is empty. */
isEmpty() { return this.queue.isEmpty(); }
/**
* Add a track to the queue with optional top-insert.
* @param {object} d - Track data.
* @param {boolean} [t=false] - Insert at the top of the queue.
*/
addToQueue(d, t) {
if (this.queue.data.length >= this._maxQueueSize) {
logger.warn(`[Player] Queue size cap reached (${this._maxQueueSize}) — dropping oldest track`);
this.queue.data.shift();
}
this.queue.add(d, t);
this.emit("update", "queue");
this._stopInactivityTimer();
}
/** Clear the queue and start the inactivity timer if nothing is playing. */
clear() {
this.queue.clear();
this.emit("update", "queue");
if (!this.queue.getCurrent()) {
this._startInactivityTimer();
}
}
/**
* Add multiple tracks to the queue.
* @param {Array} t - Track data array.
* @param {boolean} [top=false] - Insert at the top.
* @returns {number} Number of tracks added.
*/
addManyToQueue(t, top = false) {
if (!Array.isArray(t)) return 0;
const overflow = (this.queue.data.length + t.length) - this._maxQueueSize;
if (overflow > 0) {
logger.warn(`[Player] Queue size cap (${this._maxQueueSize}) — dropping ${overflow} oldest tracks`);
this.queue.data.splice(0, overflow);
}
const added = this.queue.addMany(t, top);
this.emit("update", "queue");
this._stopInactivityTimer();
return added;
}
/**
* Shuffle the queue.
* @returns {string} Status message.
*/
shuffle() {
if (this.isEmpty()) return "There is nothing to shuffle in the queue.";
this.queue.shuffle();
this.emit("update", "queue");
return ":twisted_rightwards_arrows: Shuffled queue";
}
/**
* Move a track from one position to another (1-based indices).
* @param {number} from
* @param {number} to
* @returns {string} Result message.
*/
move(from, to) {
if (this.queue.size() === 0) return "The queue is empty.";
return this.queue.move(from - 1, to - 1);
}
/**
* Toggle a loop mode.
* @param {"song"|"queue"} choice
* @returns {string}
*/
loop(choice) {
if (!["song", "queue"].includes(choice))
return `'${choice}' is not valid. Use \`song\` or \`queue\``;
const state = this.queue.toggleLoop(choice);
const name = choice.charAt(0).toUpperCase() + choice.slice(1);
return state
? `:repeat: ${name} loop activated`
: `:arrow_right: ${name} loop disabled`;
}
/**
* Remove a track from the queue by index.
* @param {number} index - 0-based.
* @returns {string}
* @throws {Error} If index is empty.
*/
remove(index) {
if (index === undefined || index === null) throw new Error("Index can't be empty");
const oldSize = this.queue.size();
const msg = this.queue.remove(index);
if (oldSize !== this.queue.size()) this.emit("update", "queue");
if (this.isEmpty() && !this.queue.getCurrent()) {
this._startInactivityTimer();
}
return msg;
}
/** @private Stop the audio bridge if currently playing. */
_bridgeStop() {
if (this._audioBridge?.playing) {
this._audioBridge.stop();
}
}
/**
* @private Send the self-deafen voice state update. Best effort: the
* VoiceManager silently no-ops when the connection has no connection_id
* yet (missing from VoiceServerUpdate) — re-sent after every
* requestVoiceStateSync so later attempts still land once it exists.
* @param {object} vm - VoiceManager instance.
* @param {string} channelId - Voice channel ID.
*/
_assertSelfDeaf(vm, channelId) {
try {
vm.updateVoiceState(channelId, { self_deaf: true, self_mute: false });
} catch (e) {
logger.warn("[Player] Self-deafen failed:", e.message);
}
}
/**
* @private Translate a locale key for this player's guild.
* @param {string} key
* @param {object} [replacements={}]
* @returns {string}
*/
_t(key, replacements = {}) {
if (!this.locale) return key;
return this.locale.translate(this._guildId, key, replacements);
}
}
// Attach the split-out concerns: playback advancement (PlaybackMixin), search
// & queue-filling (SearchMixin), and user-facing rendering (DisplayMixin).
applyMixins(Player, PlaybackMixin, SearchMixin, DisplayMixin);
export { Player as default, Player, Queue };
+168
View File
@@ -0,0 +1,168 @@
/**
* @module src/music/player/Queue
* @description Queue data structure: track list, loop modes (song/queue),
* add/remove/move/shuffle/pagination, and queue events.
*/
import { EventEmitter } from "node:events";
import { Utils } from "../../utils/Utils.mjs";
/**
* @class Queue
* @description Internal queue data structure that tracks tracks, loop state,
* and emits queue events.
* @extends {EventEmitter}
*
* Events (all emitted as `"queue"` with `{ type, data }`):
* - `update` — the current track advanced
* - `remove` / `move` / `add` / `addMany` / `shuffle`
*/
export class Queue extends EventEmitter {
/** @type {Array<object>} The queued track objects. */
data = [];
/** @type {object|null} The currently playing track. */
current = null;
/** @type {boolean} Whether queue loop is enabled. */
loop = false;
/** @type {boolean} Whether single-song loop is enabled. */
songLoop = false;
/** Initialize an empty queue with no loop enabled. */
constructor() {
super();
}
/** @returns {boolean} Whether the queue has no tracks. */
isEmpty() { return this.data.length === 0; }
/** @returns {number} Number of tracks in the queue (excluding current). */
size() { return this.data.length; }
/**
* Advance to the next track in the queue. If songLoop is active, returns
* the current track. If queue loop is active, re-appends the current track.
* @returns {object|null} The next track, or null if the queue is empty.
*/
next() {
const previous = this.current;
if (this.songLoop && this.current) return this.current;
if (this.loop && this.current) this.data.push(this.current);
if (this.isEmpty()) {
this.current = null;
return null;
}
this.current = this.data.shift();
this.emit("queue", {
type: "update",
data: { current: this.current, old: previous, loop: this.loop }
});
return this.current;
}
/**
* Remove a track from the queue by index.
* @param {number} idx - Zero-based index of the track to remove.
* @returns {string} Result message indicating success or out-of-bounds error.
*/
remove(idx) {
if (idx < 0 || idx >= this.data.length) return "Index out of bounds";
const title = this.data[idx].title;
const removed = this.data.splice(idx, 1);
this.emit("queue", { type: "remove", data: { index: idx, old: this.data.slice(), removed, new: this.data } });
return `Successfully removed **${title}** from the queue.`;
}
/**
* Move a track from one position to another (0-based indices).
* @param {number} from - Source index.
* @param {number} to - Destination index.
* @returns {string} Result message indicating success or error.
*/
move(from, to) {
if (from < 0 || from >= this.data.length) return "Source index out of bounds";
if (to < 0 || to >= this.data.length) return "Target index out of bounds";
if (from === to) return "Track is already in that position";
const [track] = this.data.splice(from, 1);
this.data.splice(to, 0, track);
this.emit("queue", { type: "move", data: { from, to, track } });
return `Moved **${track.title}** from position ${from + 1} to ${to + 1}.`;
}
/**
* Add a single track to the queue.
* @param {object} data - Track data object.
* @param {boolean} [top=false] - If true, insert at the front of the queue.
* @returns {number} The new length of the queue.
*/
add(data, top = false) {
this.emit("queue", { type: "add", data: { append: !top, data } });
return top ? this.data.unshift(data) : this.data.push(data);
}
/**
* Add multiple tracks to the queue (up to 1000).
* @param {Array<object>} tracks - Array of track data objects.
* @param {boolean} [top=false] - If true, insert at the front of the queue.
* @returns {number} Number of tracks actually added.
*/
addMany(tracks, top = false) {
if (!tracks?.length) return 0;
if (!Array.isArray(tracks)) tracks = [];
const count = Math.min(tracks.length, 1000);
if (top) {
for (let i = count - 1; i >= 0; i--) this.data.unshift(tracks[i]);
} else {
for (let i = 0; i < count; i++) this.data.push(tracks[i]);
}
this.emit("queue", { type: "addMany", data: { append: !top, tracks: tracks.slice(0, count) } });
return count;
}
/** Remove all tracks from the queue. */
clear() { this.data.length = 0; }
/** Clear the queue and reset all state (current, loops). */
reset() { this.clear(); this.current = null; this.songLoop = false; this.loop = false; }
/** @param {boolean} bool - Enable or disable song loop. */
setSongLoop(bool) { this.songLoop = bool; }
/** @param {boolean} bool - Enable or disable queue loop. */
setLoop(bool) { this.loop = bool; }
/**
* Toggle a loop mode on or off.
* @param {"song"|"queue"} loop - The type of loop to toggle.
* @returns {boolean|null} The new loop state, or null if the loop type is invalid.
*/
toggleLoop(loop) {
if (loop === "song") { this.setSongLoop(!this.songLoop); return this.songLoop; }
if (loop === "queue") { this.setLoop(!this.loop); return this.loop; }
return null;
}
/** Shuffle the queue in place and emit a queue event. */
shuffle() {
Utils.shuffleArr(this.data);
this.emit("queue", { type: "shuffle", data: this.data });
}
/** @returns {object|null} The currently playing track. */
getCurrent() { return this.current; }
/** @returns {Array<object>} A copy of the queue array. */
getQueue() { return this.data; }
/**
* Get a paginated slice of the queue.
* @param {number} [page=1] - 1-based page number (clamped to valid range).
* @param {number} [pageSize=10] - Number of tracks per page.
* @returns {object} Page result with items, page, totalPages, total, start.
*/
getPage(page = 1, pageSize = 10) {
const total = this.data.length;
const totalPages = Math.max(1, Math.ceil(total / pageSize));
const safePage = Utils.clamp(page, 1, totalPages);
const start = (safePage - 1) * pageSize;
return { items: this.data.slice(start, start + pageSize), page: safePage, totalPages, total, start };
}
}
+484
View File
@@ -0,0 +1,484 @@
/**
* @module src/music/player/SearchMixin
* @description Search & queue-filling concern for {@link Player}: Lavalink
* queries, search sessions with interactive selection, YouTube fallbacks,
* radio/external track builders.
*
* These methods are applied onto the Player class prototype via
* {@link applyMixins} — `this` is a Player instance.
*/
import { EventEmitter } from "node:events";
import { Utils } from "../../utils/Utils.mjs";
import { logger } from "../../core/Logger.mjs";
import { PROVIDERS, PROVIDER_NAMES } from "../providers.mjs";
/**
* @type {object}
* @description Search mixin — applied to Player.
*/
const SearchMixin = {
/**
* @async Resolve a free-text query or URL to track data via Lavalink for
* internal consumers (autoplay, Last.fm). URL queries are loaded directly
* (like play()) so playlist/mix URLs resolve to their full track lists.
* @this {import('./Player.mjs').Player}
* @param {{query: string, provider?: string, trackMeta?: object}} opts
* @returns {Promise<{type: "video"|"list"|"error", data?: object}|null>}
*/
async generalQuery({ query, provider = "yt", trackMeta = null }) {
try {
if (!this._lavalink) return { type: "error", data: "Audio node not ready." };
await this._lavalink.waitForNode({ timeoutMs: 15_000 });
const isUrl = typeof query === "string" && Utils.isValidUrl(query);
const result = isUrl
? await this._lavalink.search(query)
: await this._lavalink.search(query, { source: this._getSource(provider) });
const tracks = (result?.tracks ?? []).map(t => this._lcTrackToVideo(t, trackMeta)).filter(Boolean);
if (!tracks.length) return null;
return tracks.length === 1 ? { type: "video", data: tracks[0] } : { type: "list", data: tracks };
} catch (err) {
logger.warn("[Player] generalQuery failed:", err?.message);
return { type: "error", data: err?.message ?? String(err) };
}
},
/**
* @async Search for tracks via Lavalink and store results for interactive
* selection.
* @this {import('./Player.mjs').Player}
* @param {string} query - The search query string.
* @param {string} id - A unique key to identify this search session (e.g. message ID).
* @param {string} [provider="ytm"] - The search provider key.
* @returns {Promise<{m: string, count: number}>} Formatted result list message and track count.
*/
async fetchResults(query, id, provider = "ytm") {
try {
if (!this._lavalink) return { m: "Audio node not ready.", count: 0 };
await this._lavalink.waitForNode({ timeoutMs: 15_000 });
const source = this._getSource(provider);
const result = await this._lavalink.search(query, { source });
const lcTracks = result?.tracks ?? [];
const results = lcTracks.slice(0, this.resultLimit).map(t => this._lcTrackToVideo(t)).filter(Boolean);
let list = "Search results using **" + (PROVIDER_NAMES[provider] || "YouTube Music") + "**:\n\n";
results.forEach((v, i) => {
const url = v.url || "";
const title = v.title || Utils.formatTrackInfo(v, false);
const dur = v.duration ? this.getDuration(v.duration) : "?:??";
list += (i + 1) + ". [" + title + "](" + url + ") - " + dur + "\n";
});
list += "\nSend the number of the result. Example: `2`\nSend 'x' to cancel.";
if (this.searches.size >= this._searchMaxSize) {
const oldestKey = this.searches.keys().next().value;
if (oldestKey !== undefined) this.searches.delete(oldestKey);
}
this.searches.set(id, results);
return { m: list, count: results.length };
} catch (err) {
return { m: "Error searching: " + err.message, count: 0 };
}
},
/**
* Select a search result and add it to the queue.
* @this {import('./Player.mjs').Player}
* @param {string} id
* @param {number} [result=0]
* @param {boolean} [next=false]
* @returns {object|null}
*/
playResult(id, result = 0, next = false) {
if (!this.searches.has(id)) return null;
const searchResults = this.searches.get(id);
if (!searchResults || !searchResults[result]) return null;
const res = searchResults[result];
this.addToQueue(res, next);
this.searches.delete(id);
if (!this.queue.getCurrent()) {
this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
}
return res;
},
/**
* Search and add a track to the top of the queue.
* @this {import('./Player.mjs').Player}
* @param {string} query
* @param {string} provider
* @param {object} trackMeta
* @returns {EventEmitter}
*/
playFirst(query, provider, trackMeta) { return this.play(query, true, provider, trackMeta); },
/**
* @private Convert a Lavalink track to the internal track format.
* @this {import('./Player.mjs').Player}
* @param {object} track
* @param {object|null} [trackMeta=null]
* @returns {object|null}
*/
_lcTrackToVideo(track, trackMeta = null) {
if (!track || typeof track !== "object") return null;
const info = track.info ?? track ?? {};
let ms = info.length ?? track.length ?? info.durationMs ?? 0;
if (ms === 0 && info.duration != null) {
if (typeof info.duration === "number") {
ms = info.duration;
} else if (typeof info.duration === "object" && info.duration.seconds != null) {
ms = info.duration.seconds * 1000;
}
}
let trackUri = info.uri ?? ("https://www.youtube.com/watch?v=" + (info.identifier || ""));
if (typeof trackUri === 'string' && trackUri.includes('music.youtube.com')) {
trackUri = trackUri.replace('music.youtube.com', 'www.youtube.com');
}
const video = {
videoId: info.identifier ?? "",
encoded: track.encoded ?? info.encoded ?? "",
sourceName: info.sourceName ?? "unknown",
title: Utils.cleanTitle(info.title ?? "Unknown"),
url: trackUri,
thumbnail: info.artworkUrl ?? null,
spotifyUrl: null,
_durationMs: ms,
duration: {
timestamp: Utils.prettifyMS(ms),
seconds: Math.floor(ms / 1000),
},
author: {
name: info.author ?? "Unknown",
url: info.uri ?? null,
},
artists: null,
};
if (trackMeta) {
video.artist = trackMeta.artist ?? null;
video.requestedArtist = trackMeta.artist ?? null;
video.requestedTitle = trackMeta.name ?? trackMeta.title ?? null;
video.lastfm = {
source: trackMeta.source ?? "lastfm",
artist: trackMeta.artist ?? null,
name: trackMeta.name ?? trackMeta.title ?? null,
url: trackMeta.url ?? "",
};
}
return video;
},
/**
* @private Resolve a provider key to a Lavalink search prefix.
* @this {import('./Player.mjs').Player}
* @param {string} provider
* @returns {string}
*/
_getSource(provider) {
return PROVIDERS[provider]?.prefix ?? (provider + "search");
},
/**
* Search for a track and add it to the queue. Handles URL loading with
* YouTube normalization + oEmbed title fallback and playlist expansion.
* @this {import('./Player.mjs').Player}
* @param {string} query
* @param {boolean} [top=false]
* @param {string} [provider]
* @param {object} [trackMeta=null]
* @returns {EventEmitter} Emits "message" events with status strings.
*/
play(query, top = false, provider, trackMeta = null) {
const events = new EventEmitter();
const source = this._getSource(provider || "ytm");
const isUrl = Utils.isValidUrl(query);
(async () => {
try {
if (!this._lavalink) {
events.emit("message", "Audio node not ready yet.");
return;
}
await this._lavalink.waitForNode({ timeoutMs: 15_000 });
events.emit("message", "Searching...");
const ytId = Utils.extractYouTubeId(query);
const canonicalYtUrl = ytId ? Utils.normalizeYouTubeUrl(query) : null;
const searchQuery = (isUrl && canonicalYtUrl) ? canonicalYtUrl : query;
let result;
try {
if (isUrl) {
result = await this._lavalink.search(searchQuery);
} else {
result = await this._lavalink.search(searchQuery, { source });
}
} catch (searchErr) {
logger.warn("[Player] URL/primary search failed:", searchErr?.message);
result = null;
if (!isUrl) throw searchErr;
}
let lcTracks = result?.tracks ?? [];
// Set when the only results we have came from the oEmbed title-search
// fallback. That path resolves a SINGLE video (direct URL load was
// bot-blocked), so its result list is a search page — NOT a playlist.
// Bulk-queueing it would queue a bunch of "related" songs instead of
// the one requested video (original fluxer bug reported by users).
let fromTitleFallback = false;
if (isUrl && lcTracks.length === 0 && ytId) {
const directBlocked = "YouTube blocked direct loading for this video (`Sign in to confirm you're not a bot`) — trying search fallback...";
if (searchQuery !== query) {
events.emit("message", "Retrying with original URL...");
try {
const retry = await this._lavalink.search(query);
lcTracks = retry?.tracks ?? [];
} catch (_) { lcTracks = []; }
}
if (lcTracks.length === 0) {
events.emit("message", directBlocked);
const title = await Utils.fetchYouTubeOEmbedTitle(ytId);
if (title) {
logger.player(`[Player] oEmbed fallback: resolved title "${title}" for ${ytId}`);
for (const fallbackSource of ["ytsearch", "ytmsearch"]) {
try {
const fb = await this._lavalink.search(title, { source: fallbackSource });
if (fb?.tracks?.length > 0) {
lcTracks = fb.tracks;
fromTitleFallback = true;
break;
}
} catch (_) { /* try next source */ }
}
} else {
logger.warn("[Player] oEmbed fallback: could not resolve title for " + ytId);
}
}
}
if (lcTracks.length === 0) {
if (!isUrl && source !== "ytmsearch") {
events.emit("message", "No results from primary source, trying YouTube Music...");
const fallback = await this._lavalink.search(searchQuery, { source: "ytmsearch" });
if (fallback?.tracks?.length > 0) {
const video = this._lcTrackToVideo(fallback.tracks[0], trackMeta);
if (video) {
this.addToQueue(video, top);
events.emit("message", "Successfully added [" + video.title + "](" + video.url + ") to the queue.");
if (!this.queue.getCurrent()) {
this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
}
return;
}
}
}
events.emit("message", "**No results found for '" + query + "'.**");
return;
}
// Pick the track to queue. For a title-search fallback, prefer the
// result that is the exact video the user requested (search may rank
// covers/remixes first); otherwise take the first result.
let firstTrack = lcTracks[0];
if (fromTitleFallback && ytId) {
firstTrack = lcTracks.find(t => (t?.info?.identifier ?? t?.identifier) === ytId) ?? lcTracks[0];
if (firstTrack !== lcTracks[0]) {
logger.player(`[Player] Search fallback: exact video match found for ${ytId}`);
}
}
// Only a genuine playlist/mix URL load may bulk-queue. A title-search
// fallback for a single video must queue exactly one track.
if (isUrl && !fromTitleFallback && lcTracks.length > 1) {
const videos = lcTracks.map(t => this._lcTrackToVideo(t, trackMeta)).filter(Boolean);
this.addManyToQueue(videos, top);
events.emit("message", "Successfully added **" + videos.length + "** songs to the queue.");
} else {
const video = this._lcTrackToVideo(firstTrack, trackMeta);
if (video) {
this.addToQueue(video, top);
events.emit("message", "Successfully added [" + video.title + "](" + video.url + ") to the queue.");
} else {
events.emit("message", "**Failed to parse track data.**");
return;
}
}
if (!this.queue.getCurrent()) {
this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
}
} catch (err) {
logger.error("[Player] play() search error:", err?.message);
events.emit("message", err?.message || "An error occurred while loading the track.");
}
})();
return events;
},
/**
* @async Search for tracks via Lavalink and return raw track results.
* @this {import('./Player.mjs').Player}
* @param {string} query
* @param {string} [provider="ytm"]
* @returns {Promise<Array<object>>}
*/
async search(query, provider = 'ytm') {
if (!this._lavalink) return [];
try {
const source = this._getSource(provider);
const result = await this._lavalink.search(query, { source });
return result.tracks || [];
} catch (e) {
logger.error(`[Player] lavalink search error:`, e?.message);
return [];
}
},
/**
* @private Build a radio-type track object.
* @this {import('./Player.mjs').Player}
* @param {object} radio
* @returns {object}
*/
_buildRadioTrack(radio) {
return {
type: "radio",
title: radio.detailedName || radio.title || "Unknown Radio",
description: Utils.truncate(radio.description || "", 200),
url: radio.url,
author: {
name: radio.author?.name || "Unknown",
url: radio.author?.url || radio.url,
},
thumbnail: radio.thumbnail ?? null,
};
},
/**
* Add a radio stream to the queue.
* @this {import('./Player.mjs').Player}
* @param {object} radio
* @param {boolean} [top=false]
*/
playRadio(radio, top = false) {
if (!radio?.url) { logger.error("[Player] Invalid radio data"); return; }
this.addToQueue(this._buildRadioTrack(radio), top);
if (!this.queue.getCurrent()) this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
},
/**
* @async Switch to a different radio stream, replacing any current radio tracks.
* @this {import('./Player.mjs').Player}
* @param {object} radio - Radio object with url, title, author, thumbnail.
* @returns {Promise<void>}
*/
async switchRadio(radio) {
if (!radio?.url) { logger.error("[Player] switchRadio: invalid radio data"); return; }
const newTrack = this._buildRadioTrack(radio);
this.queue.data = this.queue.data.filter(t => t.type !== "radio");
if (!this.queue.getCurrent()) {
this.queue.add(newTrack);
this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
return;
}
this.queue.data.unshift(newTrack);
this._skipping = true;
this._radioAnnounced = false;
this.queue.current = null;
this._bridgeStop();
this._playingNext = false;
this._skipping = false;
if (!this.leaving) this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
},
/**
* @private Build a direct-URL track object.
* @this {import('./Player.mjs').Player}
* @param {string} url
* @param {string} [title]
* @param {string} [artist]
* @param {string} [trackType="external"]
* @returns {object}
*/
_buildExternalTrack(url, title = null, artist = null, trackType = "external") {
const displayTitle = title || this._extractFilenameFromUrl(url);
return {
type: trackType,
title: displayTitle,
url: url,
artist: artist || null,
thumbnail: null,
};
},
/**
* @private Extract a display filename from a URL.
* @this {import('./Player.mjs').Player}
* @param {string} url
* @returns {string}
*/
_extractFilenameFromUrl(url) {
try {
const pathname = new URL(url).pathname;
const filename = pathname.split("/").pop();
if (filename && filename.includes(".")) {
return decodeURIComponent(filename.replace(/\.[^.]+$/, "")) || "Stream";
}
} catch (_) {}
return "External Stream";
},
/**
* Play a direct audio URL (MP3, OGG, AAC, stream, etc.) without Lavalink
* search. The bridge handles decoding via Lavalink if needed.
* @this {import('./Player.mjs').Player}
* @param {string} url - Direct HTTP(S) audio URL.
* @param {string} [title] - Optional display title.
* @param {string} [artist] - Optional artist name.
* @param {boolean} [top=false] - Insert at top of queue.
* @param {string} [trackType="external"] - "external" or "stream".
* @returns {EventEmitter} Emits "message" events with status strings.
*/
playExternal(url, title = null, artist = null, top = false, trackType = "external") {
const events = new EventEmitter();
(async () => {
try {
const track = this._buildExternalTrack(url, title, artist, trackType);
this.addToQueue(track, top);
events.emit("message", "Added **[" + track.title + "](" + url + ")** to the queue.");
if (!this.queue.getCurrent()) {
this.playNext().catch(e => {
logger.error("[Player] playExternal playNext error:", e.message);
events.emit("message", "Error playing stream: " + e.message);
});
}
} catch (err) {
logger.error("[Player] playExternal error:", err?.message);
events.emit("message", "Error: " + (err?.message || "Failed to add external stream."));
}
})();
return events;
},
};
export default SearchMixin;
export { SearchMixin };
+9
View File
@@ -0,0 +1,9 @@
/**
* @module src/music/player
* @description Public surface of the per-channel player.
*
* Import map from the old layout:
* - `src/Player.mjs` → this module (default export = Player)
*/
export { default, Player, Queue } from "./Player.mjs";
+74
View File
@@ -0,0 +1,74 @@
/** @module src/music/probe @description Audio probing utilities using ffprobe to extract metadata from media files/streams. */
import ffprobe from "ffprobe-static";
import { spawn } from "node:child_process";
import { logger } from "../core/Logger.mjs";
/** @type {number} @description Maximum time in milliseconds to wait for ffprobe to complete. */
const PROBE_TIMEOUT_MS = 15_000;
/**
* Probe a media file or stream URL for metadata using ffprobe.
* Extracts album, artist, title, and duration.
* @param {string} file - File path or stream URL to probe.
* @returns {Promise<{album: string, artist: string, title: string, duration: number}>} Parsed metadata.
* @throws {Error} If ffprobe times out, fails to spawn, or produces unparseable output.
*/
export default function probe(file) {
return new Promise((res, rej) => {
const args = [
"-hide_banner",
"-show_entries", "format_tags:format=duration",
"-print_format", "json",
"-i", file,
];
const proc = spawn(ffprobe.path, args);
const chunks = [];
const errChunks = [];
let settled = false;
const cleanup = () => {
settled = true;
clearTimeout(timeoutHandle);
if (proc.exitCode === null && !proc.killed) {
try { proc.kill(); } catch(e) { logger.warn("[probe] kill error:", e?.message); }
}
};
const timeoutHandle = setTimeout(() => {
if (settled) return;
cleanup();
rej(new Error("[probe] ffprobe timed out after " + (PROBE_TIMEOUT_MS / 1000) + "s"));
}, PROBE_TIMEOUT_MS);
proc.stdout.on("data", (d) => { chunks.push(d); });
proc.stderr.on("data", (d) => { errChunks.push(d); });
proc.on("error", (err) => {
if (settled) return;
cleanup();
rej(new Error("[probe] Failed to spawn ffprobe: " + err.message));
});
proc.on("close", (code) => {
if (settled) return;
cleanup();
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));
}
});
});
}
+122
View File
@@ -0,0 +1,122 @@
/** @module src/music/providers */
/**
* Map of provider shorthand keys to their Lavalink search prefix and display label.
* Both short aliases (e.g. `scld`) and full names (e.g. `soundcloud`) map to the same
* prefix/label pair.
* @type {Object<string, { prefix: string, label: string }>}
*/
export const PROVIDERS = {
yt: { prefix: "ytsearch", label: "YouTube" },
ytm: { prefix: "ytmsearch", label: "YouTube Music" },
scld: { prefix: "scsearch", label: "SoundCloud" },
sc: { prefix: "scsearch", label: "SoundCloud" },
sp: { prefix: "spsearch", label: "Spotify" },
spotify: { prefix: "spsearch", label: "Spotify" },
am: { prefix: "amsearch", label: "Apple Music" },
apple: { prefix: "amsearch", label: "Apple Music" },
dz: { prefix: "dzsearch", label: "Deezer" },
deezer: { prefix: "dzsearch", label: "Deezer" },
td: { prefix: "tdsearch", label: "Tidal" },
tidal: { prefix: "tdsearch", label: "Tidal" },
bc: { prefix: "bcsearch", label: "Bandcamp" },
bandcamp: { prefix: "bcsearch", label: "Bandcamp" },
adm: { prefix: "admsearch", label: "Audiomack" },
audiomack: { prefix: "admsearch", label: "Audiomack" },
gaana: { prefix: "gaanasearch", label: "Gaana" },
js: { prefix: "jssearch", label: "JioSaavn" },
jiosaavn: { prefix: "jssearch", label: "JioSaavn" },
lf: { prefix: "lfsearch", label: "Last.fm" },
lastfm: { prefix: "lfsearch", label: "Last.fm" },
pd: { prefix: "pdsearch", label: "Pandora" },
pandora: { prefix: "pdsearch", label: "Pandora" },
vk: { prefix: "vksearch", label: "VK Music" },
mc: { prefix: "mcsearch", label: "Mixcloud" },
mixcloud: { prefix: "mcsearch", label: "Mixcloud" },
nc: { prefix: "ncsearch", label: "NicoVideo" },
nicovideo: { prefix: "ncsearch", label: "NicoVideo" },
bb: { prefix: "bilibili", label: "Bilibili" },
bilibili: { prefix: "bilibili", label: "Bilibili" },
sh: { prefix: "shsearch", label: "Shazam" },
shazam: { prefix: "shsearch", label: "Shazam" },
sl: { prefix: "slsearch", label: "Songlink" },
songlink: { prefix: "slsearch", label: "Songlink" },
qb: { prefix: "qbsearch", label: "Qobuz" },
qobuz: { prefix: "qbsearch", label: "Qobuz" },
ym: { prefix: "ymsearch", label: "Yandex Music" },
yandex: { prefix: "ymsearch", label: "Yandex Music" },
au: { prefix: "ausearch", label: "Audius" },
audius: { prefix: "ausearch", label: "Audius" },
az: { prefix: "azsearch", label: "Amazon Music" },
amazon: { prefix: "azsearch", label: "Amazon Music" },
ag: { prefix: "agsearch", label: "Anghami" },
anghami: { prefix: "agsearch", label: "Anghami" },
bk: { prefix: "bksearch", label: "Bluesky" },
bluesky: { prefix: "bksearch", label: "Bluesky" },
ytrec: { prefix: "ytrec", label: "YouTube (recommended)" },
sprec: { prefix: "sprec", label: "Spotify (recommended)" },
dzrec: { prefix: "dzrec", label: "Deezer (recommended)" },
tdrec: { prefix: "tdrec", label: "Tidal (recommended)" },
jsrec: { prefix: "jsrec", label: "JioSaavn (recommended)" },
vkrec: { prefix: "vkrec", label: "VK Music (recommended)" },
gtts: { prefix: "gtts", label: "Google TTS" },
tts: { prefix: "gtts", label: "Google TTS" },
ftts: { prefix: "ftts", label: "Flowery TTS" },
};
/**
* Shorthand-to-label lookup derived from {@link PROVIDERS}.
* @type {Object<string, string>}
*/
export const PROVIDER_NAMES = Object.fromEntries(
Object.entries(PROVIDERS).map(([k, v]) => [k, v.label])
);
/**
* Complete list of accepted provider keys for command choices.
* @type {string[]}
*/
export const PROVIDER_CHOICES = [
"ytm", "yt", "scld", "sc",
"sp", "spotify",
"am", "apple",
"dz", "deezer",
"td", "tidal",
"bc", "bandcamp",
"adm", "audiomack",
"gaana",
"js", "jiosaavn",
"lf", "lastfm",
"pd", "pandora",
"vk",
"mc", "mixcloud",
"nc", "nicovideo",
"bb", "bilibili",
"sh", "shazam",
"sl", "songlink",
"qb", "qobuz",
"ym", "yandex",
"au", "audius",
"az", "amazon",
"ag", "anghami",
"bk", "bluesky",
"ytrec", "sprec", "dzrec", "tdrec", "jsrec", "vkrec",
"gtts", "tts", "ftts",
];
/**
* Parse an inline provider prefix from raw query text (e.g. `"yt: never gonna give you up"`).
* If the prefix is recognised, splits into provider key and remaining query;
* otherwise returns the full string as the query with `provider: null`.
* @param {string} raw - The raw user input string.
* @returns {{ provider: string|null, query: string }}
*/
export function parseInlineProvider(raw) {
const match = raw.match(/^([a-z]+):\s*(.+)$/i);
if (!match) return { provider: null, query: raw.trim() };
const maybeProvider = match[1].toLowerCase();
if (PROVIDER_CHOICES.includes(maybeProvider)) {
return { provider: maybeProvider, query: match[2].trim() };
}
return { provider: null, query: raw.trim() };
}