mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-23 21:52:45 -05:00
cleannnn
This commit is contained in:
1 parent
05fb38aabd
commit
bc1fe82919
43 files changed
+122
-1784
No files matched your search
+2
-25
@@ -70,7 +70,6 @@ export class CommandRequirement {
|
||||
}
|
||||
|
||||
export class Option {
|
||||
// Fluxer uses channel mentions: <#id> and user mentions <@id>
|
||||
channelRegex = /^<#(?<id>\d+)>/;
|
||||
userRegex = /^<@!?(?<id>\d+)>/;
|
||||
idRegex = /^(?<id>\d+)/;
|
||||
@@ -141,10 +140,9 @@ export class Option {
|
||||
const results = this.channelRegex.exec(i) ?? this.idRegex.exec(i);
|
||||
const guildId = msg?.channel?.guildId ?? msg?.guildId;
|
||||
|
||||
// dry-run eval mode
|
||||
if (guildId === "eval") return (results) ? results.groups["id"] : i;
|
||||
|
||||
const voiceTypes = [2, 13]; // GuildVoice and GuildStageVoice
|
||||
const voiceTypes = [2, 13];
|
||||
const byName = msg?.guild?.channels?.find(c => c.name === i && voiceTypes.includes(c.type));
|
||||
const cObj = results
|
||||
? client.channels.get(results.groups["id"])
|
||||
@@ -381,11 +379,8 @@ export class CommandHandler extends EventEmitter {
|
||||
invalidFlagError = "Invalid flag `$invalidFlag`. It doesn't match any options on this command.\n`$previousCmd $invalidFlag`";
|
||||
textWrapError = "Malformed string `$value`: Missing a closing quote character (`$quote`) after the desired string.";
|
||||
|
||||
// Per-user rate limiting: userId → timestamp of last processed command
|
||||
// Prevents command spam that could saturate worker threads and fill the searches Map.
|
||||
// Owners are exempt so they can always use debug/reload commands.
|
||||
_cmdCooldowns = new Map();
|
||||
_cmdCooldownMs = 1500; // 1.5 seconds between commands per user
|
||||
_cmdCooldownMs = 1500;
|
||||
|
||||
constructor(handler, prefix = "!") {
|
||||
super();
|
||||
@@ -439,7 +434,6 @@ export class CommandHandler extends EventEmitter {
|
||||
if (!msg || !msg.content) return;
|
||||
const trimmed = msg.content.trim();
|
||||
if (/^<@!?\d+>$/.test(trimmed)) {
|
||||
// Only respond if the bot itself was pinged
|
||||
const botId = this.client.user?.id;
|
||||
if (botId && (trimmed === `<@${botId}>` || trimmed === `<@!${botId}>`)) {
|
||||
return this.onPing?.(msg);
|
||||
@@ -447,16 +441,12 @@ export class CommandHandler extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
// Per-user rate limit — skip spam commands silently.
|
||||
// Owners are always exempt so %reload and %eval are never blocked.
|
||||
const userId = msg.message?.author?.id ?? msg.author?.id;
|
||||
if (userId && !this.owners.includes(userId)) {
|
||||
const now = Date.now();
|
||||
const last = this._cmdCooldowns.get(userId) ?? 0;
|
||||
if (now - last < this._cmdCooldownMs) return;
|
||||
this._cmdCooldowns.set(userId, now);
|
||||
// Evict stale entries periodically to keep the Map from growing unbounded.
|
||||
// 500 entries × 8 bytes ≈ negligible, but good hygiene on busy bots.
|
||||
if (this._cmdCooldowns.size > 500) {
|
||||
const cutoff = now - this._cmdCooldownMs * 2;
|
||||
for (const [uid, ts] of this._cmdCooldowns) {
|
||||
@@ -513,12 +503,8 @@ export class CommandHandler extends EventEmitter {
|
||||
}
|
||||
|
||||
processCommand(cmd, args, msg, previous = false, external = false) {
|
||||
// Guard first — cmd could be undefined if called from an edge case
|
||||
if (!cmd) return logger.warn("[CommandHandler.processCommand] Invalid case: `cmd` falsy.");
|
||||
|
||||
// Check if the bot itself has the critical permissions it needs in this channel.
|
||||
// This runs BEFORE user-requirement checks so the user gets a clear error
|
||||
// about what the bot is missing, rather than a generic 403 crash later.
|
||||
if (!external) {
|
||||
const channel = msg.channel?.channel ?? msg.channel;
|
||||
if (channel?.guild) {
|
||||
@@ -528,7 +514,6 @@ export class CommandHandler extends EventEmitter {
|
||||
try {
|
||||
msg.message?.reply?.({ embeds: [permEmbed] }, { ping: false });
|
||||
} catch (_) {
|
||||
// Last resort: plain text
|
||||
try {
|
||||
const names = botPermResult.missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k);
|
||||
msg.message?.reply?.("I'm missing critical permissions: **" + names.join("**, **") + "**. Ask an admin to fix this.", { ping: false });
|
||||
@@ -689,16 +674,12 @@ export class CommandHandler extends EventEmitter {
|
||||
|
||||
const member = guild.members.get(authorId) ?? null;
|
||||
if (member?.permissions) {
|
||||
// cached — check directly
|
||||
const missing = req.permissions.filter(p => !member.permissions.has(PermissionFlags[p] ?? p));
|
||||
if (missing.length > 0) {
|
||||
this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// not cached — fetch async and re-run
|
||||
// guild.fetchMember(id) is a Fluxer shorthand; guild.members.fetch(id) is the
|
||||
// standard compatible form. Try both so either API name works.
|
||||
const fetchPromise = typeof guild.fetchMember === "function"
|
||||
? guild.fetchMember(authorId)
|
||||
: typeof guild.members?.fetch === "function"
|
||||
@@ -709,14 +690,11 @@ export class CommandHandler extends EventEmitter {
|
||||
if (missing.length > 0) {
|
||||
this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg);
|
||||
} else {
|
||||
// Re-parse args the same way messageHandler does so quoted args survive.
|
||||
const guildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId;
|
||||
const prefix2 = this.getPrefix(guildId2);
|
||||
const rawContent = msg.message.content;
|
||||
const len2 = rawContent.startsWith(prefix2) ? prefix2.length : 0;
|
||||
const args = rawContent.slice(len2).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim());
|
||||
// Pass external=true to skip re-checking requirements and avoid
|
||||
// re-entering the fetch loop if the member is still not cached.
|
||||
this.processCommand(cmd, args, msg, false, true);
|
||||
}
|
||||
}).catch(() => this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg));
|
||||
@@ -755,7 +733,6 @@ export class CommandLoader {
|
||||
this.commands = commands;
|
||||
this.context = context;
|
||||
this.context.loader ??= this;
|
||||
// expose loader helpers on context so reload.js can use them
|
||||
this.context.commandFiles = this.commandFiles;
|
||||
this.context.runnables = this.runnables;
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* - In-memory response caching with configurable TTL
|
||||
* - Graceful error handling (401/403 auth errors, network failures)
|
||||
*
|
||||
* FluxerList API docs: https://fluxerlist.com/api/v1
|
||||
* FluxerList API docs: https:
|
||||
*/
|
||||
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
@@ -18,7 +18,6 @@ import {
|
||||
buildFluxerListUrl,
|
||||
} from "./constants/API.mjs";
|
||||
|
||||
// ── FluxerListManager ───────────────────────────────────────────────────────────
|
||||
|
||||
export class FluxerListManager {
|
||||
/**
|
||||
@@ -37,7 +36,6 @@ export class FluxerListManager {
|
||||
this.botSlug = config?.botSlug ?? config?.botId ?? "";
|
||||
this.enabled = !!this.apiKey;
|
||||
|
||||
// In-memory cache: Map<cacheKey, { data, expiresAt }>
|
||||
this._cache = new Map();
|
||||
|
||||
if (!this.enabled) {
|
||||
@@ -47,7 +45,6 @@ export class FluxerListManager {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Cache helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Generate a cache key from the request parameters.
|
||||
@@ -88,7 +85,6 @@ export class FluxerListManager {
|
||||
expiresAt: Date.now() + (ttlMs ?? FLUXERLIST_LIMITS.CACHE_TTL_MS),
|
||||
});
|
||||
|
||||
// Evict stale entries periodically to prevent unbounded growth
|
||||
if (this._cache.size > 200) {
|
||||
const now = Date.now();
|
||||
for (const [k, v] of this._cache) {
|
||||
@@ -97,7 +93,6 @@ export class FluxerListManager {
|
||||
}
|
||||
}
|
||||
|
||||
// ── API calls ───────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Fetch the list of voters for a server or bot.
|
||||
@@ -122,7 +117,6 @@ export class FluxerListManager {
|
||||
const page = options.page ?? FLUXERLIST_LIMITS.DEFAULT_PAGE;
|
||||
const limit = options.limit ?? FLUXERLIST_LIMITS.DEFAULT_LIMIT;
|
||||
|
||||
// Check cache first
|
||||
const cacheKey = this._cacheKey(type, resourceId, page, limit);
|
||||
if (!options.skipCache) {
|
||||
const cached = this._getCached(cacheKey);
|
||||
@@ -132,14 +126,12 @@ export class FluxerListManager {
|
||||
}
|
||||
}
|
||||
|
||||
// Build request URL
|
||||
const endpoint = type === "server"
|
||||
? FLUXERLIST.ENDPOINTS.SERVER_VOTERS
|
||||
: FLUXERLIST.ENDPOINTS.BOT_VOTERS;
|
||||
|
||||
const url = buildFluxerListUrl(endpoint, resourceId, { page, limit });
|
||||
|
||||
// Make the API call
|
||||
const res = await fetch(url, {
|
||||
method: "GET",
|
||||
headers: {
|
||||
@@ -149,7 +141,6 @@ export class FluxerListManager {
|
||||
},
|
||||
});
|
||||
|
||||
// Handle HTTP errors
|
||||
if (res.status === 401) {
|
||||
throw new Error("Invalid FluxerList API key. Check your config.json fluxerlist.apiKey.");
|
||||
}
|
||||
@@ -167,12 +158,10 @@ export class FluxerListManager {
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
// Validate response shape
|
||||
if (typeof data.total !== "number" || !Array.isArray(data.voters)) {
|
||||
throw new Error("Unexpected FluxerList API response format.");
|
||||
}
|
||||
|
||||
// Cache the result
|
||||
this._setCached(cacheKey, data);
|
||||
|
||||
logger.settings(`[FluxerList] Fetched ${data.voters.length} voters for ${type} ${resourceId} (page ${page}, total ${data.total})`);
|
||||
@@ -217,21 +206,18 @@ export class FluxerListManager {
|
||||
let allVoters = [];
|
||||
let total = Infinity;
|
||||
|
||||
// Safety: max 50 pages to prevent runaway loops
|
||||
while (allVoters.length < total && page <= 50) {
|
||||
const data = await this.getVoters(type, id, { page, limit, skipCache: options.skipCache });
|
||||
allVoters = allVoters.concat(data.voters);
|
||||
total = data.total;
|
||||
page++;
|
||||
|
||||
// If we got fewer results than the limit, we've reached the last page
|
||||
if (data.voters.length < limit) break;
|
||||
}
|
||||
|
||||
return allVoters;
|
||||
}
|
||||
|
||||
// ── Internal ────────────────────────────────────────────────────────────────
|
||||
|
||||
_assertEnabled() {
|
||||
if (!this.enabled) {
|
||||
|
||||
+5
-241
@@ -21,41 +21,22 @@ export class GatewayHandler {
|
||||
constructor(remix) {
|
||||
this.remix = remix;
|
||||
|
||||
// ── Timers config (kept local — derived from remix.config) ───────────────
|
||||
const timers = remix.config.timers ?? {};
|
||||
this.T = {
|
||||
aloneCheckDebounce: timers.aloneCheckDebounce ?? 500,
|
||||
rejoin247Delay: timers.rejoin247Delay ?? 3_000,
|
||||
};
|
||||
|
||||
// ── Presence rotation config ─────────────────────────────────────────────
|
||||
this.presenceContents = remix.config.presenceContents ?? [];
|
||||
this.presenceInterval = remix.config.presenceInterval ?? 30_000;
|
||||
|
||||
// ── One-time setup guards (persist across reconnects) ─────────────────────
|
||||
this.wsListenerAttached = false;
|
||||
this.presenceTimer = null;
|
||||
this.presenceIndex = 0;
|
||||
|
||||
// ── Previous voice state per-user (for detecting channel moves) ───────────
|
||||
/** @type {Map<string, {channelId, guildId}>} guildId:userId → state */
|
||||
this._prevVoiceState = new Map();
|
||||
|
||||
// ── Startup GuildDelete deferral ───────────────────────────────────────
|
||||
// Fluxer's GUILD_DELETE does NOT expose the `unavailable` flag, so we
|
||||
// cannot distinguish "bot was kicked" from "guild is temporarily
|
||||
// unavailable." During startup, the gateway sends GUILD_DELETE for
|
||||
// guilds that went offline while the bot was down, followed immediately
|
||||
// by GUILD_CREATE when they come back. If we process GuildDelete
|
||||
// immediately, we wipe in-memory state (settings cache, player map,
|
||||
// voice observations) for guilds the bot IS still in, then GuildCreate
|
||||
// has to re-load everything from DB — wasting time and causing scary
|
||||
// "bot removed from server" log messages for guilds that are fine.
|
||||
//
|
||||
// Solution: During a startup grace period, buffer GuildDelete events
|
||||
// and only process them after the grace period expires. If a GuildCreate
|
||||
// arrives for the same guild before the grace period ends, we cancel the
|
||||
// deferred cleanup because the guild is still active.
|
||||
/** @type {Map<string, {guild, timer}>} guildId → deferred cleanup data */
|
||||
this._deferredGuildDeletes = new Map();
|
||||
/** @type {number} How long to defer GuildDelete processing during startup (ms) */
|
||||
@@ -66,7 +47,6 @@ export class GatewayHandler {
|
||||
this._deferredDeleteCount = 0;
|
||||
}
|
||||
|
||||
// ── Voice-state key helpers ──────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Generate a composite key for bots in the observedVoiceBots map.
|
||||
@@ -102,7 +82,6 @@ export class GatewayHandler {
|
||||
return { key: null, value: null };
|
||||
}
|
||||
|
||||
// ── Guild permission check on join ────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Check if the bot has all required permissions in a newly joined guild.
|
||||
@@ -115,25 +94,21 @@ export class GatewayHandler {
|
||||
async _checkGuildPermissions(guild, guildId) {
|
||||
const { remix } = this;
|
||||
|
||||
// Ensure the bot's member is cached so we can check permissions
|
||||
try {
|
||||
if (guild.members && !guild.members.me) {
|
||||
await guild.members.fetchMe();
|
||||
}
|
||||
} catch (_) { /* fetch failed — we'll still try */ }
|
||||
|
||||
// Find a text channel to check permissions in (prefer system channel)
|
||||
const channels = guild.channels;
|
||||
if (!channels) return;
|
||||
|
||||
let targetChannel = null;
|
||||
// Try system channel first
|
||||
if (guild.systemChannelId) {
|
||||
targetChannel = channels.get?.(guild.systemChannelId)
|
||||
?? channels.cache?.get?.(guild.systemChannelId)
|
||||
?? null;
|
||||
}
|
||||
// Fall back to first text channel the bot can see
|
||||
if (!targetChannel) {
|
||||
for (const ch of (channels.values?.() ?? [])) {
|
||||
if (ch.isTextBased?.() || ch.type === 0 || ch.type === "GUILD_TEXT") {
|
||||
@@ -145,9 +120,8 @@ export class GatewayHandler {
|
||||
if (!targetChannel) return;
|
||||
|
||||
const result = remix.messages.checkAllBotPermissions(targetChannel);
|
||||
if (result.missing.length === 0) return; // All good!
|
||||
if (result.missing.length === 0) return;
|
||||
|
||||
// Log the missing permissions
|
||||
const missingNames = result.missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k);
|
||||
if (result.criticalMissing.length > 0) {
|
||||
logger.warn(
|
||||
@@ -160,12 +134,10 @@ export class GatewayHandler {
|
||||
);
|
||||
}
|
||||
|
||||
// Try to send a permission warning embed to the channel
|
||||
try {
|
||||
const permEmbed = remix.messages.buildPermissionEmbed(result.missing, guildId);
|
||||
await targetChannel.send({ embeds: [permEmbed] });
|
||||
} catch (e) {
|
||||
// Can't send embed (missing SendMessages/EmbedLinks) — try plain text
|
||||
logger.warn(`[GuildCreate] Cannot send permission warning to server ${guildId}: ${e.message}`);
|
||||
try {
|
||||
await targetChannel.send(
|
||||
@@ -174,13 +146,11 @@ export class GatewayHandler {
|
||||
"Please ask a server administrator to grant these permissions in Server Settings → Roles."
|
||||
);
|
||||
} catch (_) {
|
||||
// Completely blocked — can't notify the server at all. The log message above is the only recourse.
|
||||
logger.warn(`[GuildCreate] Cannot send ANY notification to server ${guildId} — bot is missing SendMessages permission.`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Voice-state seeding from guild cache ─────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Seed observedVoiceUsers / observedVoiceBots from all cached guild voice
|
||||
@@ -190,27 +160,19 @@ export class GatewayHandler {
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
|
||||
// ── Primary source: @fluxerjs/voice VoiceManager.voiceStates ────────────
|
||||
// The VoiceManager populates its voiceStates Map from VOICE_STATES_SYNC
|
||||
// and VOICE_STATE_UPDATE gateway events. This is the most reliable source
|
||||
// because it works regardless of whether guild.voice_states is populated
|
||||
// by @fluxerjs/core (which it often isn't on Fluxer).
|
||||
try {
|
||||
const vm = getVoiceManager(client);
|
||||
if (vm?.voiceStates) {
|
||||
// voiceStates is a Map<guildId, Map<userId, channelId|null>>
|
||||
for (const [guildId, userMap] of vm.voiceStates) {
|
||||
if (!userMap || typeof userMap.forEach !== "function") continue;
|
||||
const cleanGuildId = String(guildId).replace(/\D/g, "");
|
||||
if (!cleanGuildId) continue;
|
||||
userMap.forEach((channelId, userId) => {
|
||||
if (!userId || !channelId) return;
|
||||
// The bot's own ID is included in voiceStates — track it as a bot
|
||||
const botId = client.user?.id;
|
||||
if (userId === botId) {
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuildId, userId, channelId, isBot: true });
|
||||
} else {
|
||||
// Check if this user is a bot via the members cache
|
||||
const guild = client.guilds.get(cleanGuildId) ?? client.guilds.get(guildId);
|
||||
const member = guild?.members?.get?.(userId);
|
||||
const isBot = member?.user?.bot ?? false;
|
||||
@@ -226,14 +188,12 @@ export class GatewayHandler {
|
||||
`[Seed] Seeded from VoiceManager.voiceStates — ` +
|
||||
`${remix.voiceCache.observedVoiceUsersSize} humans, ${remix.voiceCache.observedVoiceBotsSize} bots tracked.`
|
||||
);
|
||||
return; // VoiceManager is the primary source — skip fallback
|
||||
return;
|
||||
}
|
||||
} catch (e) {
|
||||
logger.voiceState(`[Seed] VoiceManager seeding failed: ${e?.message} — falling back to guild cache.`);
|
||||
}
|
||||
|
||||
// ── Fallback: guild.voice_states cache ──────────────────────────────────
|
||||
// Only used if VoiceManager is unavailable (shouldn't happen in normal ops).
|
||||
for (const [gId, guild] of client.guilds) {
|
||||
const voiceStatesRaw =
|
||||
guild.voice_states ??
|
||||
@@ -265,7 +225,6 @@ export class GatewayHandler {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Reseed voice states for a specific channel ─────────────────────────────
|
||||
|
||||
/**
|
||||
* Re-read the guild's voice_states cache and update observedVoiceUsers
|
||||
@@ -293,7 +252,6 @@ export class GatewayHandler {
|
||||
let humansFound = 0;
|
||||
const botId = client.user?.id;
|
||||
|
||||
// ── Primary source: @fluxerjs/voice VoiceManager.voiceStates ────────────
|
||||
try {
|
||||
const vm = getVoiceManager(client);
|
||||
if (vm?.voiceStates) {
|
||||
@@ -321,7 +279,6 @@ export class GatewayHandler {
|
||||
}
|
||||
});
|
||||
|
||||
// Update the bot's own entry
|
||||
if (botId) {
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true });
|
||||
}
|
||||
@@ -331,7 +288,6 @@ export class GatewayHandler {
|
||||
`found ${humansFound} human(s) via VoiceManager, observedVoiceUsers size now ${remix.voiceCache.observedVoiceUsersSize}`
|
||||
);
|
||||
|
||||
// If VoiceManager found humans, skip fallbacks
|
||||
if (humansFound > 0) return humansFound;
|
||||
}
|
||||
}
|
||||
@@ -339,7 +295,6 @@ export class GatewayHandler {
|
||||
logger.voiceState(`[Reseed] VoiceManager lookup failed: ${e?.message} — falling back.`);
|
||||
}
|
||||
|
||||
// ── Fallback: guild.voice_states cache ──────────────────────────────────
|
||||
const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId);
|
||||
if (!guild) {
|
||||
logger.voiceState(
|
||||
@@ -388,7 +343,6 @@ export class GatewayHandler {
|
||||
}
|
||||
}
|
||||
|
||||
// Update bot's own entry
|
||||
if (botId) {
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true });
|
||||
}
|
||||
@@ -403,9 +357,7 @@ export class GatewayHandler {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Fallback: VoiceStateCache (was observedVoiceUsers) ────────────────
|
||||
if (humansFound === 0 && remix.voiceCache) {
|
||||
// O(1) lookup via channelMembers index instead of full scan
|
||||
const humans = remix.voiceCache.getHumansInChannel(cleanGuild, cleanChannel);
|
||||
for (const uid of humans) {
|
||||
humansFound++;
|
||||
@@ -414,13 +366,11 @@ export class GatewayHandler {
|
||||
);
|
||||
}
|
||||
|
||||
// Update bot's own entry
|
||||
if (botId) {
|
||||
remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true });
|
||||
}
|
||||
}
|
||||
|
||||
// ── Last resort: LiveKit remote participants ────────────────────────────
|
||||
if (humansFound === 0) {
|
||||
try {
|
||||
const player = remix.players.playerMap.get(cleanChannel);
|
||||
@@ -450,7 +400,6 @@ export class GatewayHandler {
|
||||
return humansFound;
|
||||
}
|
||||
|
||||
// ── Raw WebSocket gateway listener ───────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Attach a raw "message" listener to the shard-0 WebSocket so we can
|
||||
@@ -467,7 +416,6 @@ export class GatewayHandler {
|
||||
const shard0 = client.ws?.shards?.get?.(0);
|
||||
const wsObj = shard0?.ws ?? null;
|
||||
|
||||
// Remove listener from the previous socket if it's a different object
|
||||
if (this.wsListenerAttached && remix._rawGatewayWsObj && remix._rawGatewayWsObj !== wsObj) {
|
||||
try {
|
||||
if (typeof remix._rawGatewayWsObj.removeEventListener === "function") {
|
||||
@@ -501,7 +449,6 @@ export class GatewayHandler {
|
||||
|
||||
if (payload?.op !== 0) return;
|
||||
|
||||
// READY — seed voice states from unavailable-guilds summary
|
||||
if (payload.t === "READY") {
|
||||
logger.player(`[Gateway] READY received (session ${payload.d?.session_id ?? "unknown"})`);
|
||||
const readyGuilds = payload.d?.guilds;
|
||||
@@ -579,7 +526,6 @@ export class GatewayHandler {
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
// ── Presence rotation ───────────────────────────────────────────────────────
|
||||
|
||||
setupPresenceRotation() {
|
||||
if (this.presenceContents.length === 0) return;
|
||||
@@ -590,9 +536,6 @@ export class GatewayHandler {
|
||||
const setPresence = () => {
|
||||
const entry = this.presenceContents[this.presenceIndex];
|
||||
|
||||
// Support both plain strings and rich objects:
|
||||
// String: "Ping for Prefix"
|
||||
// Object: { text: "...", emoji_name: "🎵", activity: { name: "kyun.sh", type: 2 } }
|
||||
const isObj = typeof entry === "object" && entry !== null;
|
||||
|
||||
const custom_status = {};
|
||||
@@ -611,7 +554,6 @@ export class GatewayHandler {
|
||||
custom_status,
|
||||
};
|
||||
|
||||
// Add activity (e.g. "Listening to kyun.sh") if provided
|
||||
if (isObj && entry.activity) {
|
||||
presence.activities = [{
|
||||
name: entry.activity.name ?? "music",
|
||||
@@ -633,7 +575,6 @@ export class GatewayHandler {
|
||||
this.presenceTimer = setInterval(setPresence, this.presenceInterval);
|
||||
}
|
||||
|
||||
// ── Fluxer event handlers ─────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Register all high-level Fluxer event listeners on the Fluxer client.
|
||||
@@ -643,16 +584,10 @@ export class GatewayHandler {
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
|
||||
// ── GUILD_CREATE ────────────────────────────────────────────────────────
|
||||
// Voice-state seeding + settings init for new/re-joined servers.
|
||||
client.on(Events.GuildCreate, async (guild) => {
|
||||
const guildId = guild?.id ?? guild?._id;
|
||||
if (!guildId) return;
|
||||
|
||||
// ── Cancel any deferred GuildDelete for this guild ────────────────
|
||||
// If we got GuildDelete → GuildCreate for the same guild during the
|
||||
// startup grace period, the guild was temporarily unavailable, not
|
||||
// actually kicked. Cancel the deferred cleanup timer.
|
||||
const deferred = this._deferredGuildDeletes.get(guildId);
|
||||
if (deferred) {
|
||||
clearTimeout(deferred.timer);
|
||||
@@ -663,20 +598,12 @@ export class GatewayHandler {
|
||||
);
|
||||
}
|
||||
|
||||
// Part 1: Voice state population
|
||||
// Only purge stale entries if the GUILD_CREATE actually contains
|
||||
// voice_states data. If voice_states is empty, the guild may just
|
||||
// not provide voice state data in GUILD_CREATE (common on Fluxer),
|
||||
// and purging would destroy data we collected from VOICE_STATE_UPDATE
|
||||
// events. Only purge entries for users that appear in the new
|
||||
// voice_states data (so we can replace them with fresh data).
|
||||
const voiceStatesRaw =
|
||||
guild.voice_states ??
|
||||
guild.voiceStates ??
|
||||
null;
|
||||
|
||||
if (voiceStatesRaw) {
|
||||
// Build a set of user IDs from the new voice_states data
|
||||
const newUserIds = new Set();
|
||||
if (!Array.isArray(voiceStatesRaw) && typeof voiceStatesRaw === "object"
|
||||
&& typeof voiceStatesRaw.values !== "function") {
|
||||
@@ -693,11 +620,6 @@ export class GatewayHandler {
|
||||
}
|
||||
}
|
||||
|
||||
// Only purge entries for users/bots that are being replaced by new data.
|
||||
// Previously, ALL observedVoiceBots entries for the guild were deleted,
|
||||
// which removed the bot's own entry that was set up during recovery.
|
||||
// Now we only delete entries for bots whose user ID appears in the new
|
||||
// voice_states data, matching the same logic used for observedVoiceUsers.
|
||||
remix.voiceCache.purgeUsersInGuild(guildId, newUserIds);
|
||||
}
|
||||
if (voiceStatesRaw) {
|
||||
@@ -726,7 +648,6 @@ export class GatewayHandler {
|
||||
}
|
||||
}
|
||||
|
||||
// Part 2: Settings init for new/re-joined servers
|
||||
if (!remix.settingsMgr.guilds.has(guildId)) {
|
||||
logger.guild(`[GuildCreate] (Re-)joined server ${guildId} — initialising settings.`);
|
||||
try {
|
||||
@@ -736,8 +657,6 @@ export class GatewayHandler {
|
||||
if (res?.results?.length) {
|
||||
const row = res.results[0];
|
||||
const server = new ServerSettings(guildId, remix.settingsMgr);
|
||||
// mysql2 may return JSON columns as already-parsed objects;
|
||||
// only JSON.parse when the value is still a string.
|
||||
const parsed = (typeof row.data === "string") ? JSON.parse(row.data) : row.data;
|
||||
server.deserialize(parsed);
|
||||
server.checkDefaults(remix.settingsMgr.defaults);
|
||||
@@ -755,41 +674,27 @@ export class GatewayHandler {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Bot permission check ────────────────────────────────────────────
|
||||
// After the bot joins a server, check if it has the required permissions
|
||||
// in the first available text channel. If critical permissions are missing,
|
||||
// log a warning and try to notify the server via system channel.
|
||||
this._checkGuildPermissions(guild, guildId);
|
||||
|
||||
});
|
||||
|
||||
// ── GUILD_DELETE ────────────────────────────────────────────────────────
|
||||
client.on(Events.GuildDelete, (guild) => {
|
||||
const guildId = guild?.id ?? guild?._id;
|
||||
if (!guildId) return;
|
||||
|
||||
// ── Startup deferral ──────────────────────────────────────────────
|
||||
// During startup, the gateway may send GUILD_DELETE for guilds that
|
||||
// are temporarily unavailable (not actually kicked). If we process
|
||||
// these immediately, we wipe settings/players for guilds that will
|
||||
// come back via GUILD_CREATE moments later. Defer cleanup during
|
||||
// the startup grace period; if GuildCreate arrives first, cancel.
|
||||
if (this._inStartupGrace) {
|
||||
this._deferredDeleteCount++;
|
||||
// Only log the first few deferrals individually, then suppress
|
||||
if (this._deferredDeleteCount <= 3) {
|
||||
logger.guild(
|
||||
`[GuildDelete] Deferring cleanup for server ${guildId} ` +
|
||||
`(startup grace — will confirm after ${this._startupDeleteGraceMs / 1000}s).`
|
||||
);
|
||||
}
|
||||
// Cancel any existing deferred timer for this guild
|
||||
const existing = this._deferredGuildDeletes.get(guildId);
|
||||
if (existing) clearTimeout(existing.timer);
|
||||
|
||||
const timer = setTimeout(() => {
|
||||
this._deferredGuildDeletes.delete(guildId);
|
||||
// Grace period expired without GuildCreate — this guild is really gone
|
||||
this._processGuildDelete(guildId);
|
||||
}, this._startupDeleteGraceMs);
|
||||
|
||||
@@ -797,12 +702,10 @@ export class GatewayHandler {
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Runtime (after startup grace) — process immediately ─────────
|
||||
logger.guild(`[GuildDelete] Removed from server ${guildId} — cleaning up.`);
|
||||
this._processGuildDelete(guildId);
|
||||
});
|
||||
|
||||
// ── VOICE_STATE_UPDATE ──────────────────────────────────────────────────
|
||||
client.on(Events.VoiceStateUpdate, async (data) => {
|
||||
this._handleVoiceStateUpdate(data);
|
||||
});
|
||||
@@ -824,26 +727,16 @@ export class GatewayHandler {
|
||||
const guildId = data?.guild_id;
|
||||
const isBot = data?.member?.user?.bot ?? null;
|
||||
|
||||
// Capture old channel BEFORE updating prev state
|
||||
const prevEntry = this.findPrevVoiceStateEntry(userId, guildId);
|
||||
const prev = prevEntry.value;
|
||||
// Only treat as a channel move if the previous state is from the SAME guild.
|
||||
// Cross-guild previous states are NOT moves — the bot can be in multiple
|
||||
// guilds' voice channels simultaneously. Without this check, concurrent
|
||||
// 24/7 recovery triggers a cascading re-key that destroys all but the
|
||||
// last guild's playerMap entry.
|
||||
const prevSameGuild = prev &&
|
||||
String(prev.guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, "");
|
||||
const oldChannelId = prevSameGuild ? (prev?.channelId ?? null) : null;
|
||||
const prevKey = prevEntry.key;
|
||||
|
||||
// Update prev state
|
||||
const nextKey = this.getPrevVoiceStateKey(userId, guildId ?? prev?.guildId);
|
||||
if (channelId) {
|
||||
if (prevKey && prevKey !== nextKey) {
|
||||
// Only delete the previous entry if it's from the SAME guild.
|
||||
// The bot can be in multiple guilds' voice channels simultaneously,
|
||||
// so we must preserve cross-guild entries.
|
||||
const prevGuildPart = prevKey.split(":")[0];
|
||||
const nextGuildPart = nextKey.split(":")[0];
|
||||
if (prevGuildPart === nextGuildPart) {
|
||||
@@ -854,17 +747,11 @@ export class GatewayHandler {
|
||||
const evictKey = this._prevVoiceState.keys().next().value;
|
||||
const evictEntry = this._prevVoiceState.get(evictKey);
|
||||
this._prevVoiceState.delete(evictKey);
|
||||
// When evicting a stale prevVoiceState entry, also clean up the
|
||||
// corresponding VoiceStateCache entry so it doesn't hold a stale
|
||||
// channel mapping that could cause incorrect "channel move" detection
|
||||
// on the next voice state update for that user.
|
||||
if (evictEntry) {
|
||||
const evictGuildId = evictEntry.guildId;
|
||||
const evictUserId = evictKey.split(":")[1];
|
||||
if (evictGuildId && evictUserId) {
|
||||
const currentLoc = remix.voiceCache.getUserLocation(evictGuildId, evictUserId);
|
||||
// Only remove from voiceCache if the user is still in the evicted
|
||||
// channel — if they've moved since, the cache is already correct.
|
||||
if (currentLoc && currentLoc.channelId === evictEntry.channelId) {
|
||||
remix.voiceCache.updateUser({ guildId: evictGuildId, userId: evictUserId, channelId: null, isBot: false });
|
||||
}
|
||||
@@ -876,11 +763,9 @@ export class GatewayHandler {
|
||||
if (prevKey) this._prevVoiceState.delete(prevKey);
|
||||
}
|
||||
|
||||
// Always update/delete the voice maps
|
||||
if (channelId) {
|
||||
remix.voiceCache.updateUser({ guildId: guildId ?? prev?.guildId, userId, channelId, isBot: isBot === true });
|
||||
} else {
|
||||
// User left voice — remove from both human and bot indexes
|
||||
const resolvedGuildId = guildId ?? prev?.guildId;
|
||||
remix.voiceCache.deleteHumanUser(userId, resolvedGuildId);
|
||||
remix.voiceCache.deleteBotUser(VoiceStateCache.userKey(resolvedGuildId, userId));
|
||||
@@ -889,7 +774,6 @@ export class GatewayHandler {
|
||||
const isBotUser = isBot === true && userId === client.user?.id;
|
||||
|
||||
if (!isBotUser) {
|
||||
// ── Human user logic ──────────────────────────────────────────────────
|
||||
const resolvedGuildId = guildId ?? prev?.guildId;
|
||||
if (!resolvedGuildId) return;
|
||||
|
||||
@@ -904,7 +788,6 @@ export class GatewayHandler {
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
// Human LEFT a voice channel
|
||||
if (oldChannelId && oldChannelId !== channelId) {
|
||||
try {
|
||||
const cleanOld = String(oldChannelId).replace(/\D/g, "");
|
||||
@@ -920,7 +803,6 @@ export class GatewayHandler {
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
// Human JOINED the bot's channel
|
||||
if (channelId) {
|
||||
try {
|
||||
const cleanId = String(channelId).replace(/\D/g, "");
|
||||
@@ -932,7 +814,6 @@ export class GatewayHandler {
|
||||
} catch (_) {}
|
||||
}
|
||||
|
||||
// Dashboard update
|
||||
if (remix.dashboard?.enabled) {
|
||||
try {
|
||||
const userObj = data?.member?.user;
|
||||
@@ -940,7 +821,6 @@ export class GatewayHandler {
|
||||
try { await client.users.fetch(userId).catch(() => {}); } catch (_) {}
|
||||
}
|
||||
if (userObj) {
|
||||
// Send user update on the global :users channel
|
||||
const details = {
|
||||
type: channelId ? "join" : "leave",
|
||||
guildId: resolvedGuildId,
|
||||
@@ -950,22 +830,18 @@ export class GatewayHandler {
|
||||
remix.dashboard.updateUser(details, userObj);
|
||||
}
|
||||
|
||||
// Send per-player channel events for join/leave
|
||||
const refChannel = channelId ?? oldChannelId;
|
||||
const cleanId_ref = refChannel ? String(refChannel).replace(/\D/g, "") : null;
|
||||
|
||||
if (cleanId_ref) {
|
||||
const player = remix.players.playerMap.get(cleanId_ref);
|
||||
if (player) {
|
||||
// Send "join" or "leave" on the per-player channel
|
||||
// (standard format: { type, data } where data = userId)
|
||||
const eventType = channelId ? "join" : "leave";
|
||||
remix.dashboard.updatePlayer({
|
||||
type: eventType,
|
||||
data: userId,
|
||||
}, player);
|
||||
|
||||
// Also update the global players channel with current player state
|
||||
remix.dashboard.playerUpdate({
|
||||
type: eventType,
|
||||
}, player);
|
||||
@@ -977,19 +853,14 @@ export class GatewayHandler {
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Bot-only logic below ───────────────────────────────────────────────
|
||||
|
||||
const activeGuildPlayers = [...remix.players.playerMap.entries()].filter(([, player]) =>
|
||||
String(player?._guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, "")
|
||||
);
|
||||
const multiVoiceGuild = activeGuildPlayers.length > 1;
|
||||
|
||||
// Bot moved channels — auto-save 247 setting
|
||||
if (channelId && guildId && oldChannelId && oldChannelId !== channelId) {
|
||||
try {
|
||||
// For multi-voice guilds, only re-key if we can unambiguously match
|
||||
// the player by oldChannelId. Previously this skipped entirely for
|
||||
// multi-voice guilds, which broke recovery for all channels.
|
||||
const cleanId = String(channelId).replace(/\D/g, "");
|
||||
const cleanOld = String(oldChannelId).replace(/\D/g, "");
|
||||
const moveSet = remix.settingsMgr.getServer(guildId);
|
||||
@@ -1039,10 +910,6 @@ export class GatewayHandler {
|
||||
let rekeyed = false;
|
||||
if (existingPlayer && cleanId !== cleanOld) {
|
||||
if (newChannelAlreadySaved || newChannelPendingSpawn) {
|
||||
// Multi-voice case: joining/spawning another channel in the same
|
||||
// guild can look like a move event for the bot user. In that
|
||||
// situation we must NOT re-key the old player or rewrite stay_247,
|
||||
// otherwise one saved channel gets collapsed into the newer one.
|
||||
logger.voice247(
|
||||
`[247] Keeping both channels ${cleanOld} and ${cleanId} ` +
|
||||
`(saved=${newChannelAlreadySaved} pending=${newChannelPendingSpawn})`
|
||||
@@ -1050,13 +917,8 @@ export class GatewayHandler {
|
||||
rekeyed = false;
|
||||
} else
|
||||
if (guildIsAmbiguous) {
|
||||
// Multi-voice guild: we need to re-key the playerMap so that
|
||||
// lookups by the new channelId work. First check that no OTHER
|
||||
// player is already using the new channelId as its key.
|
||||
const playerAtNewKey = remix.players.playerMap.get(cleanId);
|
||||
if (playerAtNewKey && playerAtNewKey !== existingPlayer) {
|
||||
// Another player already uses the new key — update the moved
|
||||
// player's channel fields but don't re-key to avoid collision.
|
||||
existingPlayer._channelId = cleanId;
|
||||
existingPlayer._home247Channel = cleanId;
|
||||
if (targetGuildId) existingPlayer._guildId = targetGuildId;
|
||||
@@ -1067,7 +929,6 @@ export class GatewayHandler {
|
||||
`new key occupied by another player — skipped re-key)`
|
||||
);
|
||||
} else {
|
||||
// Safe to re-key: no collision
|
||||
remix.players.playerMap.delete(cleanOld);
|
||||
remix.players.playerMap.set(cleanId, existingPlayer);
|
||||
existingPlayer._channelId = cleanId;
|
||||
@@ -1080,29 +941,14 @@ export class GatewayHandler {
|
||||
);
|
||||
}
|
||||
} else if (playerGuildId && targetGuildId && playerGuildId !== targetGuildId) {
|
||||
// If there's no player for the old channel in playerMap, this is a
|
||||
// stale "move" from a pre-restart voice state — the bot was in
|
||||
// cleanOld before the restart, but recovery already spawned a
|
||||
// player for the new channel (cleanId) or a different channel.
|
||||
// In this case, just update the observed bot state without re-keying.
|
||||
if (!existingPlayer) {
|
||||
logger.voice247(
|
||||
`[247] Stale cross-guild move ${cleanOld} → ${cleanId} ` +
|
||||
`(no player in playerMap for old channel — updating bot state only)`
|
||||
);
|
||||
} else {
|
||||
// There IS a player in the old channel but the guilds don't match.
|
||||
// This can happen during recovery when voice state data is
|
||||
// inconsistent. Instead of refusing outright, check if the player
|
||||
// in the old channel actually belongs to the target guild (the
|
||||
// playerGuildId might be stale from before restart).
|
||||
// If the target channel's guild matches the VOICE_STATE_UPDATE's
|
||||
// guild, update the player's guildId and re-key.
|
||||
const vsuGuildId = String(guildId ?? "").replace(/\D/g, "");
|
||||
if (vsuGuildId && targetGuildId === vsuGuildId) {
|
||||
// The VOICE_STATE_UPDATE guild matches the target channel —
|
||||
// this is likely a stale playerGuildId from before restart.
|
||||
// Safe to update the player's guild and re-key.
|
||||
existingPlayer._guildId = targetGuildId;
|
||||
existingPlayer._channelId = cleanId;
|
||||
existingPlayer._home247Channel = cleanId;
|
||||
@@ -1146,7 +992,6 @@ export class GatewayHandler {
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Multi-voice guard ──────────────────────────────────────────
|
||||
const currentGuildPlayers = [...remix.players.playerMap.values()].filter(p =>
|
||||
String(p?._guildId ?? "").replace(/\D/g, "") === String(guildId ?? "").replace(/\D/g, "")
|
||||
);
|
||||
@@ -1166,12 +1011,10 @@ export class GatewayHandler {
|
||||
return;
|
||||
}
|
||||
|
||||
// Single-voice guild: genuine move — replace old channel with new.
|
||||
channels.delete(cleanOld);
|
||||
channels.add(cleanId);
|
||||
set.set("stay_247", [...channels]);
|
||||
|
||||
// Move the per-channel mode from old → new channel
|
||||
const modes = set.get("stay_247_modes");
|
||||
if (modes && typeof modes === "object" && !Array.isArray(modes)) {
|
||||
if (modes[cleanOld] && !modes[cleanId]) {
|
||||
@@ -1189,19 +1032,11 @@ export class GatewayHandler {
|
||||
}
|
||||
}
|
||||
|
||||
// Bot disconnected unexpectedly — handle based on 24/7 mode:
|
||||
// %247 auto → clean up old player and schedule rejoin (always stays in voice)
|
||||
// %247 on → emit autoleave (only rejoins on reboot, not on disconnect)
|
||||
// off → emit autoleave
|
||||
if (!channelId && oldChannelId && guildId) {
|
||||
try {
|
||||
const cleanOld = String(oldChannelId).replace(/\D/g, "");
|
||||
const cleanGuild = String(guildId).replace(/\D/g, "");
|
||||
|
||||
// During boot recovery, stale voice state events may arrive from
|
||||
// deferred GuildDelete processing. If the bot just joined this channel
|
||||
// as part of 24/7 boot recovery, the player is still good — skip
|
||||
// the autoleave/rejoin logic to avoid disrupting a healthy connection.
|
||||
if (this._inStartupGrace) {
|
||||
const bootPlayer = remix.players.playerMap.get(cleanOld);
|
||||
if (bootPlayer && !bootPlayer._destroyed) {
|
||||
@@ -1221,12 +1056,8 @@ export class GatewayHandler {
|
||||
if (remix.intentionalLeaves.has(cleanOld)) {
|
||||
logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — intentional leave.`);
|
||||
} else if (remix.revoice?._intentionalDisconnects?.has?.(cleanOld)) {
|
||||
// The player's destroy() or FluxerRevoice internally marked this
|
||||
// disconnect as intentional (e.g. cleaning up a stale connection
|
||||
// during a rejoin). Don't schedule another rejoin.
|
||||
logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — intentional (revoice).`);
|
||||
} else {
|
||||
// Check 24/7 mode for this channel
|
||||
const set = remix.settingsMgr.getServer(guildId);
|
||||
const mode = set ? get247ChannelMode(set, cleanOld) : "off";
|
||||
|
||||
@@ -1236,25 +1067,18 @@ export class GatewayHandler {
|
||||
);
|
||||
const player = remix.players.playerMap.get(cleanOld);
|
||||
if (player && !player._destroyed) {
|
||||
// Remove from player map first to prevent stale lookups
|
||||
remix.players.playerMap.delete(cleanOld);
|
||||
// Also clean up any alternate keys
|
||||
const homeChannel = String(player._home247Channel ?? "").replace(/\D/g, "");
|
||||
if (homeChannel && homeChannel !== cleanOld) {
|
||||
remix.players.playerMap.delete(homeChannel);
|
||||
}
|
||||
// Destroy the player (stops media, disconnects room)
|
||||
try { player.destroy(); } catch (_) {}
|
||||
// Clean up pending scrobble timer if any
|
||||
const pendingScrobble = remix.players._pendingScrobbleTimers?.get(cleanOld);
|
||||
if (pendingScrobble) {
|
||||
clearTimeout(pendingScrobble.timer);
|
||||
remix.players._pendingScrobbleTimers.delete(cleanOld);
|
||||
}
|
||||
}
|
||||
// Schedule rejoin with delay to avoid overwhelming LiveKit.
|
||||
// The delay also gives the Fluxer gateway time to process the
|
||||
// leave signal before we attempt a new VOICE_STATE_UPDATE.
|
||||
const rejoinDelay = this.T.rejoin247Delay ?? 3_000;
|
||||
setTimeout(() => {
|
||||
this._rejoinChannel(cleanGuild, cleanOld).catch(err => {
|
||||
@@ -1262,7 +1086,6 @@ export class GatewayHandler {
|
||||
});
|
||||
}, rejoinDelay);
|
||||
} else {
|
||||
// %247 on or off: just emit autoleave (no reconnect on disconnect)
|
||||
const player = remix.players.playerMap.get(cleanOld);
|
||||
if (player && !player.leaving && !player._destroyed) {
|
||||
logger.voiceState(
|
||||
@@ -1278,7 +1101,6 @@ export class GatewayHandler {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Rejoin a single channel after disconnect (for %247 auto) ──────────────
|
||||
|
||||
/** @type {Set<string>} Channel IDs currently being rejoined (dedup guard) */
|
||||
_rejoinInProgress = new Set();
|
||||
@@ -1306,13 +1128,11 @@ export class GatewayHandler {
|
||||
const cleanGuildId = String(guildId).replace(/\D/g, "");
|
||||
const cleanChannelId = String(channelId).replace(/\D/g, "");
|
||||
|
||||
// ── Deduplication: prevent concurrent rejoin for the same channel ──────
|
||||
if (this._rejoinInProgress.has(cleanChannelId)) {
|
||||
logger.voice247(`[Rejoin] Channel ${cleanChannelId} rejoin already in progress — skipping.`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't rejoin if there's already a player for this channel
|
||||
const existing = remix.players.playerMap.get(cleanChannelId);
|
||||
if (existing && !existing._destroyed) {
|
||||
logger.voice247(`[Rejoin] Channel ${cleanChannelId} already has a player — skipping.`);
|
||||
@@ -1320,20 +1140,17 @@ export class GatewayHandler {
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't rejoin if a join is already pending
|
||||
if (remix.players._pendingJoins?.has?.(cleanChannelId)) {
|
||||
logger.voice247(`[Rejoin] Channel ${cleanChannelId} already has a pending join — skipping.`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't rejoin if the bot was intentionally disconnected
|
||||
if (remix.intentionalLeaves.has(cleanChannelId)) {
|
||||
logger.voice247(`[Rejoin] Channel ${cleanChannelId} was intentionally left — skipping.`);
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify the channel still exists
|
||||
const channel = remix.client?.channels?.get?.(cleanChannelId);
|
||||
if (!channel) {
|
||||
logger.voice247(`[Rejoin] Channel ${cleanChannelId} no longer exists — skipping.`);
|
||||
@@ -1341,7 +1158,6 @@ export class GatewayHandler {
|
||||
return;
|
||||
}
|
||||
|
||||
// Mark as in-progress to prevent concurrent attempts
|
||||
this._rejoinInProgress.add(cleanChannelId);
|
||||
|
||||
const maxRetries = GatewayHandler.MAX_REJOIN_RETRIES;
|
||||
@@ -1354,7 +1170,6 @@ export class GatewayHandler {
|
||||
logger.voice247(`[Rejoin] Successfully rejoined channel ${cleanChannelId}`);
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
|
||||
// Reseed voice states so we know about humans in the channel
|
||||
this.reseedVoiceStatesForChannel(cleanGuildId, cleanChannelId);
|
||||
|
||||
return player;
|
||||
@@ -1365,8 +1180,6 @@ export class GatewayHandler {
|
||||
|| errMsg.includes("Failed to create MediaPlayer");
|
||||
|
||||
if (isTrackTimeout && attempt < maxRetries) {
|
||||
// Track publication timeout — likely transient (LiveKit overloaded).
|
||||
// Retry with exponential backoff: 5s, 10s, 20s
|
||||
const backoffMs = 5_000 * Math.pow(2, attempt - 1);
|
||||
logger.voice247(
|
||||
`[Rejoin] Track publication failed for channel ${cleanChannelId} (attempt ${attempt}/${maxRetries}) — ` +
|
||||
@@ -1384,14 +1197,11 @@ export class GatewayHandler {
|
||||
);
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
|
||||
// If all retries exhausted, the channel will be picked up on next
|
||||
// bot reboot via BootRecovery (for both %247 auto and %247 on).
|
||||
} finally {
|
||||
this._rejoinInProgress.delete(cleanChannelId);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Called from Events.Ready ─────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Invoke after the bot has connected and Moonlink has been initialised.
|
||||
@@ -1425,14 +1235,7 @@ export class GatewayHandler {
|
||||
for (const g of chunk) {
|
||||
const id = g?.id;
|
||||
if (!id) continue;
|
||||
// Only add if not already cached by Fluxer
|
||||
if (!client.guilds.has(id)) {
|
||||
// Insert a proper Guild instance (not a plain object) so that
|
||||
// gateway handlers like MESSAGE_CREATE can safely access
|
||||
// guild.members.set(), guild.channels, etc. without crashing.
|
||||
// A plain { id, name, _stub: true } stub caused:
|
||||
// TypeError: Cannot read properties of undefined (reading 'set')
|
||||
// because guild.members was undefined.
|
||||
try {
|
||||
const Guild = this._getGuildClass();
|
||||
if (Guild) {
|
||||
@@ -1440,8 +1243,6 @@ export class GatewayHandler {
|
||||
stub._stub = true;
|
||||
client.guilds.set(id, stub);
|
||||
} else {
|
||||
// Fallback: create a safe stub with empty collections
|
||||
// so that gateway handlers don't crash on .set() calls
|
||||
client.guilds.set(id, {
|
||||
id,
|
||||
name: g.name ?? "unknown",
|
||||
@@ -1454,7 +1255,6 @@ export class GatewayHandler {
|
||||
});
|
||||
}
|
||||
} catch (stubErr) {
|
||||
// If Guild constructor fails (e.g. missing data), use safe stub
|
||||
logger.guild(`[GuildSeed] Guild constructor failed for ${id}, using safe stub: ${stubErr?.message}`);
|
||||
client.guilds.set(id, {
|
||||
id,
|
||||
@@ -1493,9 +1293,6 @@ export class GatewayHandler {
|
||||
_getGuildClass() {
|
||||
if (this._GuildClass) return this._GuildClass;
|
||||
try {
|
||||
// The Guild class is exported from @fluxerjs/core but not as a named
|
||||
// export we can easily import. Instead, look at an existing guild
|
||||
// in the cache and use its constructor.
|
||||
const { client } = this.remix;
|
||||
for (const guild of client.guilds.values()) {
|
||||
if (guild && !guild._stub && typeof guild.constructor === 'function' && guild.constructor.name === 'Guild') {
|
||||
@@ -1510,14 +1307,11 @@ export class GatewayHandler {
|
||||
|
||||
onReady() {
|
||||
this.seedVoiceStatesFromGuilds();
|
||||
this.seedGuildsFromRest(); // fill in guilds Fluxer didn't cache via GUILD_CREATE
|
||||
this.seedGuildsFromRest();
|
||||
this.attachRawListener();
|
||||
|
||||
this.setupPresenceRotation();
|
||||
|
||||
// End the startup grace period after the configured delay.
|
||||
// Any deferred GuildDelete events that weren't cancelled by a GuildCreate
|
||||
// will be processed at this point.
|
||||
setTimeout(() => {
|
||||
this._inStartupGrace = false;
|
||||
const pending = this._deferredGuildDeletes.size;
|
||||
@@ -1529,7 +1323,6 @@ export class GatewayHandler {
|
||||
} else {
|
||||
logger.guild(`[GuildDelete] Startup grace period ended. No deferred deletions.`);
|
||||
}
|
||||
// Log suppressed count if we had more than 3 deferred deletes
|
||||
if (this._deferredDeleteCount > 3) {
|
||||
logger.guild(
|
||||
`[GuildDelete] (Suppressed ${this._deferredDeleteCount - 3} deferral log lines for brevity)`
|
||||
@@ -1537,7 +1330,6 @@ export class GatewayHandler {
|
||||
}
|
||||
}, this._startupDeleteGraceMs);
|
||||
|
||||
// ── Boot 24/7 auto-rejoin ──────────────────────────────────────────────
|
||||
this.rejoin247Channels();
|
||||
}
|
||||
|
||||
@@ -1555,7 +1347,6 @@ export class GatewayHandler {
|
||||
const { remix } = this;
|
||||
const channelsToRejoin = [];
|
||||
|
||||
// Collect all 24/7 channels from settings (both "auto" and "on" modes)
|
||||
for (const [guildId, serverSettings] of remix.settingsMgr.guilds) {
|
||||
const raw = serverSettings.get("stay_247");
|
||||
if (!raw || raw === "none") continue;
|
||||
@@ -1567,7 +1358,6 @@ export class GatewayHandler {
|
||||
|
||||
for (const channelId of channels) {
|
||||
const mode = get247ChannelMode(serverSettings, channelId);
|
||||
// Rejoin both "auto" and "on" channels on boot
|
||||
if (mode === "auto" || mode === "on") {
|
||||
channelsToRejoin.push({ guildId, channelId, mode });
|
||||
}
|
||||
@@ -1597,7 +1387,6 @@ export class GatewayHandler {
|
||||
await new Promise(resolve => setTimeout(resolve, staggerDelay));
|
||||
}
|
||||
|
||||
// Don't rejoin if already has a player or pending join
|
||||
const existing = remix.players.playerMap.get(channelId);
|
||||
if (existing && !existing._destroyed) {
|
||||
logger.voice247(`[BootRecovery] Channel ${channelId} already has a player — skipping.`);
|
||||
@@ -1608,10 +1397,6 @@ export class GatewayHandler {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Pre-validate: check if the channel still exists and is a voice channel.
|
||||
// On Fluxer, if a channel was deleted while the bot was offline, the 24/7
|
||||
// setting still references it but the channel is gone. Without this check,
|
||||
// _spawnPlayer throws "Channel not found" every boot.
|
||||
const channelObj = remix.client?.channels?.get?.(channelId);
|
||||
if (!channelObj) {
|
||||
logger.warn(
|
||||
@@ -1639,10 +1424,6 @@ export class GatewayHandler {
|
||||
continue;
|
||||
}
|
||||
|
||||
// If this guild already has an active 24/7 player from a previous
|
||||
// iteration, joining another channel in the same guild may cause the
|
||||
// Fluxer gateway to "move" the bot (disconnect from the first channel).
|
||||
// Add extra delay to let the previous connection stabilize.
|
||||
const guildHasActivePlayer = [...remix.players.playerMap.values()]
|
||||
.some(p => !p._destroyed && String(p._guildId ?? "").replace(/\D/g, "") === guildId);
|
||||
if (guildHasActivePlayer && i > 0) {
|
||||
@@ -1666,14 +1447,13 @@ export class GatewayHandler {
|
||||
try {
|
||||
const player = await remix._spawnPlayer(guildId, channelId);
|
||||
|
||||
// Reseed voice states so we know about humans in the channel
|
||||
this.reseedVoiceStatesForChannel(guildId, channelId);
|
||||
|
||||
logger.voice247(
|
||||
`[BootRecovery] Successfully rejoined channel ${channelId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]` +
|
||||
(bootRetries > 0 ? ` (after ${bootRetries} retry/retries)` : '')
|
||||
);
|
||||
break; // success — move to next channel
|
||||
break;
|
||||
} catch (err) {
|
||||
bootRetries++;
|
||||
const errMsg = err?.message ?? String(err);
|
||||
@@ -1697,9 +1477,6 @@ export class GatewayHandler {
|
||||
(bootRetries > 1 ? ` (after ${bootRetries} attempts)` : '')
|
||||
);
|
||||
|
||||
// Auto-cleanup: if all retries exhausted due to track publication
|
||||
// failure, remove the channel from 24/7 so it doesn't block boot
|
||||
// recovery on every restart.
|
||||
if (isTrackTimeout && bootRetries >= BOOT_MAX_RETRIES) {
|
||||
try {
|
||||
const set = remix.settingsMgr.getServer(guildId);
|
||||
@@ -1724,7 +1501,7 @@ export class GatewayHandler {
|
||||
}
|
||||
}
|
||||
|
||||
break; // non-retryable error or max retries exhausted
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1734,7 +1511,6 @@ export class GatewayHandler {
|
||||
);
|
||||
}
|
||||
|
||||
// ── GuildDelete cleanup (extracted for deferred processing) ────────────────
|
||||
|
||||
/**
|
||||
* Perform the actual cleanup for a guild that the bot was removed from.
|
||||
@@ -1745,27 +1521,15 @@ export class GatewayHandler {
|
||||
_processGuildDelete(guildId) {
|
||||
const { remix } = this;
|
||||
const cleanGuildId = String(guildId).replace(/\D/g, "");
|
||||
// During startup grace batch, suppress individual cleanup logs to reduce spam
|
||||
const batchMode = this._deferredDeleteCount > 3;
|
||||
|
||||
// Protect 24/7 voice connections from GuildDelete cleanup ──
|
||||
// During startup, the gateway sends GuildDelete for guilds that are
|
||||
// temporarily unavailable. If we destroy players for 24/7 channels,
|
||||
// BootRecovery has to rejoin from scratch, causing audio interruption.
|
||||
// Instead, skip destroying players that have an active 24/7 mode
|
||||
// and still have a healthy LiveKit room connection — the guild will
|
||||
// come back via GuildCreate, and the voice connection stays alive.
|
||||
for (const [channelId, player] of remix.players.playerMap) {
|
||||
if (String(player._guildId ?? "").replace(/\D/g, "") !== cleanGuildId) continue;
|
||||
|
||||
// Check if this player is a 24/7 channel with an active connection
|
||||
const is247 = player._is247Enabled();
|
||||
const roomAlive = player.connection?.room?.isConnected ?? false;
|
||||
|
||||
if (is247 && roomAlive) {
|
||||
// The LiveKit room is still connected and this is a 24/7 channel.
|
||||
// The GuildDelete is stale (guild is temporarily unavailable).
|
||||
// Keep the player alive — the guild will come back via GuildCreate.
|
||||
if (!batchMode) {
|
||||
logger.guild(
|
||||
`[GuildDelete] Preserving 24/7 player for channel ${channelId} ` +
|
||||
|
||||
+19
-100
@@ -8,7 +8,7 @@
|
||||
* - Fetch loved / top / recent tracks for %play lastfm loved/top/recent
|
||||
* - Per-user session key storage in MySQL table `lastfm_users`
|
||||
*
|
||||
* Last.fm API docs: https://www.last.fm/api
|
||||
* Last.fm API docs: https:
|
||||
*/
|
||||
|
||||
import crypto from "node:crypto";
|
||||
@@ -25,18 +25,14 @@ function normalizeTrackText(value) {
|
||||
.toLowerCase();
|
||||
}
|
||||
|
||||
// ── Helpers ────────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Build the API signature required by Last.fm for authenticated calls.
|
||||
* See: https://www.last.fm/api/authspec#_8-signing-calls
|
||||
* See: https:
|
||||
*/
|
||||
function buildSignature(params, apiSecret) {
|
||||
// 1. Sort all parameter keys alphabetically
|
||||
const sorted = Object.keys(params).sort();
|
||||
// 2. Concatenate key+value pairs
|
||||
const str = sorted.map(k => k + params[k]).join("");
|
||||
// 3. Append secret
|
||||
return crypto.createHash("md5").update(str + apiSecret).digest("hex");
|
||||
}
|
||||
|
||||
@@ -48,11 +44,9 @@ function buildSignature(params, apiSecret) {
|
||||
* @returns {Promise<object>} Parsed JSON response
|
||||
*/
|
||||
async function apiCall(params, apiSecret, post = false) {
|
||||
// Per Last.fm spec: format must NOT be included in the signature.
|
||||
// See: https://www.last.fm/api/authspec#_8-signing-calls
|
||||
const allParams = { ...params };
|
||||
allParams.api_sig = buildSignature(allParams, apiSecret);
|
||||
allParams.format = "json"; // add AFTER signature
|
||||
allParams.format = "json";
|
||||
|
||||
const url = post ? BASE_URL : `${BASE_URL}?${new URLSearchParams(allParams)}`;
|
||||
|
||||
@@ -77,7 +71,6 @@ async function apiCall(params, apiSecret, post = false) {
|
||||
return data;
|
||||
}
|
||||
|
||||
// ── LastFmManager ──────────────────────────────────────────────────────────────
|
||||
|
||||
export class LastFmManager {
|
||||
/**
|
||||
@@ -88,10 +81,9 @@ export class LastFmManager {
|
||||
this.apiKey = config?.apiKey ?? "";
|
||||
this.apiSecret = config?.apiSecret ?? "";
|
||||
this.enabled = !!(this.apiKey && this.apiSecret);
|
||||
this.scrobbleThreshold = config?.scrobbleThreshold ?? 0.5; // fraction of track duration
|
||||
this.scrobbleMinMs = config?.scrobbleMinMs ?? 240_000; // 4 min fallback
|
||||
this.scrobbleThreshold = config?.scrobbleThreshold ?? 0.5;
|
||||
this.scrobbleMinMs = config?.scrobbleMinMs ?? 240_000;
|
||||
|
||||
// MySQL pool (lazy-created on first query)
|
||||
this._mysqlConfig = mysqlConfig;
|
||||
this._pool = null;
|
||||
|
||||
@@ -100,10 +92,8 @@ export class LastFmManager {
|
||||
/** @type {boolean} Whether the bot_id column exists in the lastfm tables */
|
||||
this._hasBotIdColumn = false;
|
||||
|
||||
// In-memory user cache: Map<userId, { sessionKey, username, scrobbleEnabled }>
|
||||
this._userCache = new Map();
|
||||
|
||||
// Cache for total synced scrobbles (sum of all users' lifetime scrobble counts)
|
||||
this._totalScrobblesCache = null;
|
||||
this._totalScrobblesCacheExpiry = 0;
|
||||
this._totalScrobblesInflight = null;
|
||||
@@ -113,12 +103,10 @@ export class LastFmManager {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Bot ID isolation ─────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Set the bot ID for multi-bot database isolation.
|
||||
* Ensures bot_id column exists in lastfm tables, then clears caches.
|
||||
* @param {string} id - The bot's Discord user ID
|
||||
*/
|
||||
async setBotId(id) {
|
||||
const changed = this.botId !== id;
|
||||
@@ -139,22 +127,18 @@ export class LastFmManager {
|
||||
if (this._hasBotIdColumn) return;
|
||||
const pool = await this._getPool();
|
||||
|
||||
// ── lastfm_users ──────────────────────────────────────────────────────
|
||||
const [cols] = await pool.execute(
|
||||
`SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_KEY FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'lastfm_users' AND COLUMN_NAME = 'bot_id'`
|
||||
);
|
||||
if (cols.length === 0) {
|
||||
logger.settings("[LastFm] Auto-migrating: adding bot_id column to lastfm_users...");
|
||||
// NOT NULL DEFAULT '' — PK columns can't be NULL in MySQL
|
||||
await pool.execute("ALTER TABLE `lastfm_users` ADD COLUMN `bot_id` VARCHAR(32) NOT NULL DEFAULT ''");
|
||||
// Claim existing rows for the current bot
|
||||
if (this.botId) {
|
||||
await pool.execute("UPDATE `lastfm_users` SET `bot_id` = ? WHERE `bot_id` = ''", [String(this.botId)]);
|
||||
}
|
||||
await pool.execute("ALTER TABLE `lastfm_users` DROP PRIMARY KEY, ADD PRIMARY KEY (user_id, bot_id)");
|
||||
logger.settings("[LastFm] Auto-migration complete: lastfm_users.bot_id added.");
|
||||
} else {
|
||||
// Column exists — check if it's part of the PK
|
||||
const colInfo = cols[0];
|
||||
const isNullable = colInfo.IS_NULLABLE === 'YES';
|
||||
const isPK = colInfo.COLUMN_KEY === 'PRI';
|
||||
@@ -172,7 +156,6 @@ export class LastFmManager {
|
||||
}
|
||||
}
|
||||
|
||||
// ── lastfm_stats ──────────────────────────────────────────────────────
|
||||
const [statsCols] = await pool.execute(
|
||||
`SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_KEY FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'lastfm_stats' AND COLUMN_NAME = 'bot_id'`
|
||||
);
|
||||
@@ -215,11 +198,9 @@ export class LastFmManager {
|
||||
return { where: " AND bot_id = ?", params: [String(this.botId)] };
|
||||
}
|
||||
|
||||
// ── MySQL ──────────────────────────────────────────────────────────────────
|
||||
|
||||
async _getPool() {
|
||||
if (this._pool) return this._pool;
|
||||
// Dynamic import so we don't crash if mysql2 isn't needed
|
||||
const mysql = await import("mysql2/promise");
|
||||
this._pool = mysql.createPool({
|
||||
host: this._mysqlConfig.host,
|
||||
@@ -245,14 +226,11 @@ export class LastFmManager {
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
`);
|
||||
|
||||
// Auto-migrate: add scrobble_count column if it doesn't exist (existing tables)
|
||||
try {
|
||||
await pool.execute("ALTER TABLE \`lastfm_users\` ADD COLUMN \`scrobble_count\` BIGINT NOT NULL DEFAULT 0 AFTER \`scrobble\`");
|
||||
} catch {
|
||||
// Column already exists — ignore
|
||||
}
|
||||
|
||||
// Stats table — single row tracking global scrobble counts
|
||||
await pool.execute(`
|
||||
CREATE TABLE IF NOT EXISTS \`lastfm_stats\` (
|
||||
\`id\` TINYINT(1) NOT NULL PRIMARY KEY DEFAULT 1,
|
||||
@@ -260,13 +238,11 @@ export class LastFmManager {
|
||||
\`linked_users\` INT NOT NULL DEFAULT 0
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
|
||||
`);
|
||||
// Ensure the single row exists
|
||||
await pool.execute(`
|
||||
INSERT IGNORE INTO \`lastfm_stats\` (id, stored_scrobbles, linked_users) VALUES (1, 0, 0)
|
||||
`);
|
||||
}
|
||||
|
||||
// ── User persistence ───────────────────────────────────────────────────────
|
||||
|
||||
async getUser(userId) {
|
||||
const cached = this._userCache.get(userId);
|
||||
@@ -303,14 +279,12 @@ export class LastFmManager {
|
||||
const data = { sessionKey, username: username ?? "", scrobbleEnabled: true };
|
||||
this._userCache.set(userId, data);
|
||||
|
||||
// Increment linked_users counter (only on new links, not re-links)
|
||||
try {
|
||||
await pool.execute(
|
||||
`UPDATE lastfm_stats SET linked_users = linked_users + 1 WHERE id = 1${f.where} AND NOT EXISTS (SELECT 1 FROM (SELECT 1 FROM lastfm_users WHERE user_id = ?${f.where} AND linked_at < NOW()) AS tmp)`,
|
||||
[...f.params, String(userId), ...f.params]
|
||||
);
|
||||
} catch {
|
||||
// Non-critical — don't fail the save
|
||||
}
|
||||
|
||||
return data;
|
||||
@@ -334,7 +308,6 @@ export class LastFmManager {
|
||||
if (cached) cached.scrobbleEnabled = enabled;
|
||||
}
|
||||
|
||||
// ── Auth flow ──────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Step 1: Get an auth token. The user must visit the Last.fm auth URL to approve it.
|
||||
@@ -366,10 +339,9 @@ export class LastFmManager {
|
||||
{ method: "auth.getsession", api_key: this.apiKey, token },
|
||||
this.apiSecret
|
||||
);
|
||||
return data.session; // { key, name }
|
||||
return data.session;
|
||||
}
|
||||
|
||||
// ── Scrobbling ─────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Send a "now playing" notification to Last.fm (does NOT count as a scrobble).
|
||||
@@ -393,7 +365,7 @@ export class LastFmManager {
|
||||
trackNumber: track.trackNumber ?? "",
|
||||
},
|
||||
this.apiSecret,
|
||||
true // POST
|
||||
true
|
||||
);
|
||||
} catch (err) {
|
||||
logger.warn(`[LastFm] updateNowPlaying failed for ${userId}: ${err.message}`);
|
||||
@@ -422,22 +394,19 @@ export class LastFmManager {
|
||||
"duration[0]": this._extractDurationSec(track),
|
||||
},
|
||||
this.apiSecret,
|
||||
true // POST
|
||||
true
|
||||
);
|
||||
logger.settings(`[LastFm] Scrobbled "${track.title}" for ${userId}`);
|
||||
|
||||
// Increment stored scrobbles counter (non-blocking)
|
||||
this._incrementScrobbleCount(userId);
|
||||
} catch (err) {
|
||||
logger.warn(`[LastFm] Scrobble failed for ${userId}: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
// ── User data (for play command) ──────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Get the user's loved tracks.
|
||||
* @param {string} userId - Discord/Fluxer user ID
|
||||
* @param {number} [limit=20] - Max tracks to return
|
||||
* @returns {Promise<Array<{ artist, name, url, image }>>}
|
||||
*/
|
||||
@@ -534,7 +503,6 @@ export class LastFmManager {
|
||||
track,
|
||||
};
|
||||
|
||||
// If user is linked, include their username for personal playcount
|
||||
if (userId) {
|
||||
const user = await this.getUser(userId);
|
||||
if (user) params.username = user.username;
|
||||
@@ -591,7 +559,6 @@ export class LastFmManager {
|
||||
|
||||
let score = 0;
|
||||
|
||||
// ── Positive matching ────────────────────────────────────────────────
|
||||
if (combined === normalizedQuery) score += 50;
|
||||
if (combined.includes(normalizedQuery) && normalizedQuery) score += 25;
|
||||
if (normalizedQuery.includes(nameNorm) && nameNorm) score += 15;
|
||||
@@ -600,10 +567,6 @@ export class LastFmManager {
|
||||
const overlap = queryTokens.filter(token => combined.includes(token)).length;
|
||||
score += overlap * 4;
|
||||
|
||||
// ── Penalize non-song results ────────────────────────────────────────
|
||||
// Track names that contain these phrases are usually lyric videos,
|
||||
// official videos, or other non-song entries that shouldn't be the
|
||||
// top result when a user is searching for the actual song.
|
||||
const nameLower = name.toLowerCase();
|
||||
const artistLower = artist.toLowerCase();
|
||||
const urlLower = String(track.url ?? "").toLowerCase();
|
||||
@@ -616,7 +579,7 @@ export class LastFmManager {
|
||||
/\blyric video\b/,
|
||||
/\blyrics video\b/,
|
||||
/\bmusic video\b/,
|
||||
/\bofficial audio\b/, // some entries are titled "Official Audio" on last.fm
|
||||
/\bofficial audio\b/,
|
||||
/\bvisuali[sz]er\b/,
|
||||
/\bkaraoke\b/,
|
||||
/\bcover\b/,
|
||||
@@ -628,20 +591,18 @@ export class LastFmManager {
|
||||
/\breverb\b/,
|
||||
/\bnightcore\b/,
|
||||
/\b8d\b/,
|
||||
/\bclip officiel\b/, // French official video
|
||||
/\bvideo oficial\b/, // Spanish/Portuguese official video
|
||||
/\bclip officiel\b/,
|
||||
/\bvideo oficial\b/,
|
||||
/\bperformance\b/,
|
||||
];
|
||||
|
||||
for (const re of negativePatterns) {
|
||||
if (re.test(fullText)) {
|
||||
score -= 30;
|
||||
break; // only penalize once per track
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Penalize results where the artist is a label/production company
|
||||
// instead of the actual artist (e.g. "Sony Pictures Animation")
|
||||
const labelKeywords = [
|
||||
/\bpictures\b/i,
|
||||
/\banimation\b/i,
|
||||
@@ -660,17 +621,12 @@ export class LastFmManager {
|
||||
}
|
||||
}
|
||||
|
||||
// Penalize results where the track name is wrapped in quotes
|
||||
// (e.g. '"Soda Pop" Official Lyric Video' — the quotes indicate
|
||||
// it's a video title, not the actual track name)
|
||||
if (/^["""].*["""]$/.test(name) || /["""]/.test(name)) {
|
||||
score -= 15;
|
||||
}
|
||||
|
||||
// Prefer results that have a clean /music/Artist/_/Track URL format
|
||||
// (actual tracks) over /music/Artist/Track+Extra+Stuff (video entries)
|
||||
if (urlLower.includes("/_/")) {
|
||||
score += 5; // Clean track URL format
|
||||
score += 5;
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -691,10 +647,10 @@ export class LastFmManager {
|
||||
/**
|
||||
* Parse a Last.fm music URL and extract artist and track info.
|
||||
* Supports:
|
||||
* https://www.last.fm/music/Drake/ICEMAN/Make+Them+Cry
|
||||
* https://www.last.fm/music/SAJA+BOYS/_/Soda+Pop
|
||||
* https://www.last.fm/music/Drake/_/Make+Them+Cry ("_" = album placeholder)
|
||||
* https://www.last.fm/music/Drake (artist only)
|
||||
* https:
|
||||
* https:
|
||||
* https:
|
||||
* https:
|
||||
*
|
||||
* @param {string} url
|
||||
* @returns {{ artist: string, track: string|null, album: string|null, url: string } | null}
|
||||
@@ -704,8 +660,6 @@ export class LastFmManager {
|
||||
const u = new URL(url);
|
||||
if (!/^(?:www\.)?last\.fm$/i.test(u.hostname)) return null;
|
||||
|
||||
// Path format: /music/Artist[/Album][/Track]
|
||||
// Or: /music/Artist/_/Track (underscore = album placeholder)
|
||||
const match = u.pathname.match(/^\/music\/([^/]+)(?:\/([^/]+))?(?:\/([^/]+))?/);
|
||||
if (!match) return null;
|
||||
|
||||
@@ -717,11 +671,9 @@ export class LastFmManager {
|
||||
let album = null;
|
||||
|
||||
if (segment3) {
|
||||
// /music/Artist/Album/Track or /music/Artist/_/Track
|
||||
album = segment2 === "_" ? null : segment2;
|
||||
track = segment3;
|
||||
} else if (segment2 && segment2 !== "_") {
|
||||
// /music/Artist/Track (no album segment)
|
||||
track = segment2;
|
||||
}
|
||||
|
||||
@@ -765,7 +717,6 @@ export class LastFmManager {
|
||||
return data.user;
|
||||
}
|
||||
|
||||
// ── Playlists & Albums ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Get a list of the user's Last.fm playlists by scraping their profile page.
|
||||
@@ -790,9 +741,6 @@ export class LastFmManager {
|
||||
const html = await res.text();
|
||||
const playlists = [];
|
||||
|
||||
// Parse playlist links from the HTML
|
||||
// Last.fm playlist links look like: /user/USERNAME/playlists/123456
|
||||
// Each playlist item has a .playlist-item or similar container
|
||||
const playlistRegex = /href="\/user\/[^/]+\/playlists\/(\d+)"[^>]*>([^<]+)<\/a>/gi;
|
||||
let match;
|
||||
while ((match = playlistRegex.exec(html)) !== null) {
|
||||
@@ -807,14 +755,12 @@ export class LastFmManager {
|
||||
}
|
||||
}
|
||||
|
||||
// Try to extract track counts (e.g. "12 tracks" or "1 track")
|
||||
const countRegex = /(\d+)\s+track/gi;
|
||||
const counts = [];
|
||||
let cMatch;
|
||||
while ((cMatch = countRegex.exec(html)) !== null) {
|
||||
counts.push(+cMatch[1]);
|
||||
}
|
||||
// Pair counts with playlists (order should match)
|
||||
playlists.forEach((pl, i) => {
|
||||
pl.trackCount = counts[i] ?? 0;
|
||||
});
|
||||
@@ -837,10 +783,9 @@ export class LastFmManager {
|
||||
|
||||
let playlistUrl;
|
||||
|
||||
// If playlistId is a number, look up the playlist URL from the user's playlists
|
||||
if (/^\d+$/.test(String(playlistId))) {
|
||||
const playlists = await this.getPlaylists(userId);
|
||||
const idx = +playlistId - 1; // 1-based to 0-based
|
||||
const idx = +playlistId - 1;
|
||||
if (idx < 0 || idx >= playlists.length) {
|
||||
throw new Error(`Playlist #${playlistId} not found. You have ${playlists.length} playlist(s). Use \`%lastfm playlists\` to see them.`);
|
||||
}
|
||||
@@ -848,11 +793,9 @@ export class LastFmManager {
|
||||
} else if (String(playlistId).startsWith("http")) {
|
||||
playlistUrl = String(playlistId);
|
||||
} else {
|
||||
// Assume it's a playlist ID slug — build the URL
|
||||
playlistUrl = `https://www.last.fm/user/${user.username}/playlists/${playlistId}`;
|
||||
}
|
||||
|
||||
// Scrape the playlist page for track info
|
||||
const res = await fetch(playlistUrl, {
|
||||
headers: { "User-Agent": "RemixBot/1.0 (Last.fm Integration)" },
|
||||
});
|
||||
@@ -864,24 +807,18 @@ export class LastFmManager {
|
||||
const html = await res.text();
|
||||
const tracks = [];
|
||||
|
||||
// Last.fm playlist pages contain track items with:
|
||||
// <a href="/music/Artist/Track" class="...">Track Name</a>
|
||||
// We extract artist and track from the URL pattern /music/Artist+Name/Track+Name
|
||||
const trackLinkRegex = /href="\/music\/([^"]+?)"[^>]*class="[^"]*(?:link-block-target|chartlist-name)[^"]*"[^>]*>([^<]+)<\/a>/gi;
|
||||
let tMatch;
|
||||
while ((tMatch = trackLinkRegex.exec(html)) !== null && tracks.length < limit) {
|
||||
const urlPath = decodeURIComponent(tMatch[1]);
|
||||
const name = tMatch[2].trim();
|
||||
// URL format: /music/Artist+Name/Track+Name or /music/Artist+Name/_/Track+Name
|
||||
const parts = urlPath.split("/");
|
||||
let artist = "Unknown";
|
||||
if (parts.length >= 1) {
|
||||
artist = parts[0].replace(/\+/g, " ");
|
||||
}
|
||||
if (parts.length >= 3 && parts[1] === "_") {
|
||||
// /music/Artist/_/Track format
|
||||
} else if (parts.length >= 2) {
|
||||
// /music/Artist/Track format — the track name from URL
|
||||
}
|
||||
|
||||
if (name && name !== "Unknown") {
|
||||
@@ -894,7 +831,6 @@ export class LastFmManager {
|
||||
}
|
||||
}
|
||||
|
||||
// Fallback: try a broader regex if the first one didn't find anything
|
||||
if (!tracks.length) {
|
||||
const broadRegex = /href="\/music\/([^"]+)"[^>]*>([^<]{2,80})<\/a>/gi;
|
||||
const seen = new Set();
|
||||
@@ -902,7 +838,6 @@ export class LastFmManager {
|
||||
while ((bMatch = broadRegex.exec(html)) !== null && tracks.length < limit) {
|
||||
const urlPath = decodeURIComponent(bMatch[1]);
|
||||
const name = bMatch[2].trim();
|
||||
// Only include actual track links (Artist/Track or Artist/_/Track)
|
||||
const parts = urlPath.split("/");
|
||||
if (parts.length < 2) continue;
|
||||
if (seen.has(urlPath)) continue;
|
||||
@@ -958,7 +893,6 @@ export class LastFmManager {
|
||||
}));
|
||||
}
|
||||
|
||||
// ── Play helper (for %lastfm play and %play lastfm:loved etc.) ─────────────
|
||||
|
||||
/**
|
||||
* Fetch tracks from Last.fm by category and return search queries
|
||||
@@ -988,7 +922,6 @@ export class LastFmManager {
|
||||
break;
|
||||
case "recent":
|
||||
tracks = await this.getRecentTracks(userId, limit);
|
||||
// Filter out "now playing" entries (they have no finished timestamp)
|
||||
tracks = tracks.filter(t => !t.now);
|
||||
break;
|
||||
case "playlist":
|
||||
@@ -996,13 +929,11 @@ export class LastFmManager {
|
||||
tracks = await this.getPlaylistTracks(userId, options.playlistId, limit);
|
||||
break;
|
||||
case "albums":
|
||||
// Top albums — we fetch albums, then for each album we use the album name + artist as search query
|
||||
const albums = await this.getTopAlbums(userId, options.period ?? "overall", limit);
|
||||
tracks = albums.map(a => ({
|
||||
artist: a.artist,
|
||||
name: a.name,
|
||||
url: a.url,
|
||||
// For albums, search the album name + artist to get the full album
|
||||
query: `${a.artist} ${a.name} album`,
|
||||
image: a.image ?? "",
|
||||
}));
|
||||
@@ -1025,7 +956,6 @@ export class LastFmManager {
|
||||
};
|
||||
}
|
||||
|
||||
// ── Global stats ────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Get the total lifetime scrobbles across ALL linked Last.fm users.
|
||||
@@ -1038,12 +968,10 @@ export class LastFmManager {
|
||||
async getTotalScrobbles(concurrency = 3) {
|
||||
if (!this.enabled) return 0;
|
||||
|
||||
// Return cached value if still fresh
|
||||
if (this._totalScrobblesCache !== null && Date.now() < this._totalScrobblesCacheExpiry) {
|
||||
return this._totalScrobblesCache;
|
||||
}
|
||||
|
||||
// Deduplicate concurrent calls
|
||||
if (this._totalScrobblesInflight) return this._totalScrobblesInflight;
|
||||
|
||||
this._totalScrobblesInflight = this._refreshTotalScrobbles(concurrency);
|
||||
@@ -1061,7 +989,6 @@ export class LastFmManager {
|
||||
try {
|
||||
const pool = await this._getPool();
|
||||
|
||||
// Get all linked user IDs
|
||||
const f = this._botIdFilter();
|
||||
const [rows] = await pool.execute(
|
||||
`SELECT user_id FROM lastfm_users WHERE 1=1${f.where}`,
|
||||
@@ -1074,16 +1001,13 @@ export class LastFmManager {
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Sync each user's scrobble count from the Last.fm API (with concurrency limit)
|
||||
const userIds = rows.map(r => r.user_id);
|
||||
|
||||
// Batch the sync calls to avoid overloading the Last.fm API
|
||||
for (let i = 0; i < userIds.length; i += concurrency) {
|
||||
const batch = userIds.slice(i, i + concurrency);
|
||||
await Promise.allSettled(batch.map(uid => this.syncUserScrobbleCount(uid)));
|
||||
}
|
||||
|
||||
// Now sum up all scrobble_count values from the DB
|
||||
const [sumRows] = await pool.execute(
|
||||
`SELECT COALESCE(SUM(scrobble_count), 0) AS total FROM lastfm_users WHERE 1=1${f.where}`,
|
||||
[...f.params]
|
||||
@@ -1097,7 +1021,6 @@ export class LastFmManager {
|
||||
return total;
|
||||
} catch (err) {
|
||||
logger.warn(`[LastFm] _refreshTotalScrobbles failed: ${err.message}`);
|
||||
// Return stale cache if available, otherwise 0
|
||||
return this._totalScrobblesCache ?? 0;
|
||||
}
|
||||
}
|
||||
@@ -1133,7 +1056,6 @@ export class LastFmManager {
|
||||
const pool = await this._getPool();
|
||||
const f = this._botIdFilter();
|
||||
|
||||
// Get total count
|
||||
const [countRows] = await pool.execute(
|
||||
`SELECT COUNT(*) AS total FROM lastfm_users WHERE scrobble_count > 0${f.where}`,
|
||||
[...f.params]
|
||||
@@ -1141,7 +1063,6 @@ export class LastFmManager {
|
||||
const totalUsers = Number(countRows[0]?.total ?? 0);
|
||||
const totalPages = Math.max(1, Math.ceil(totalUsers / perPage));
|
||||
|
||||
// Clamp page
|
||||
page = Math.max(0, Math.min(page, totalPages - 1));
|
||||
|
||||
const offset = page * perPage;
|
||||
@@ -1183,7 +1104,6 @@ export class LastFmManager {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Internal helpers ───────────────────────────────────────────────────────
|
||||
|
||||
_assertEnabled() {
|
||||
if (!this.enabled) throw new Error("Last.fm integration is not configured (missing apiKey/apiSecret).");
|
||||
@@ -1231,7 +1151,6 @@ export class LastFmManager {
|
||||
|
||||
_extractDurationSec(track) {
|
||||
if (!track.duration) return "";
|
||||
// Duration can be: { seconds: N }, "PT3M0S", or milliseconds number
|
||||
if (typeof track.duration === "object" && track.duration.seconds) return track.duration.seconds;
|
||||
if (typeof track.duration === "number") return Math.round(track.duration / 1000);
|
||||
if (typeof track.duration === "string") {
|
||||
@@ -1253,7 +1172,7 @@ export class LastFmManager {
|
||||
? track.duration
|
||||
: null;
|
||||
|
||||
if (!durationMs || durationMs < 30_000) return false; // too short
|
||||
if (!durationMs || durationMs < 30_000) return false;
|
||||
|
||||
const normalizedTitle = normalizeTrackText(this._extractTitle(track));
|
||||
const normalizedArtist = normalizeTrackText(this._extractArtist(track));
|
||||
|
||||
+9
-66
@@ -31,7 +31,6 @@ export const OPTIONAL_PERMISSIONS = ["AddReactions", "ReadMessageHistory", "Mana
|
||||
export function parseColor(value, fallback = 0xe9196c) {
|
||||
if (!value) return fallback;
|
||||
if (typeof value === "number") return value;
|
||||
// Strip leading # ("#ff0000" → "ff0000") or 0x prefix ("0xe9196c" → "e9196c")
|
||||
const cleaned = String(value).replace(/^#/, "").replace(/^0x/i, "");
|
||||
const n = parseInt(cleaned, 16);
|
||||
return isNaN(n) ? fallback : n;
|
||||
@@ -92,7 +91,6 @@ export class MessageHandler {
|
||||
|
||||
setupEvents() {
|
||||
const reactionUpdate = (reaction, user) => {
|
||||
// fluxerjs reaction events pass a MessageReaction and a User
|
||||
const messageId = reaction.message?.id ?? reaction.messageId;
|
||||
const emoji = reaction.emoji?.name ?? reaction.emoji?.id ?? reaction.emoji;
|
||||
const event = { user_id: user.id, emoji_id: emoji };
|
||||
@@ -118,19 +116,17 @@ export class MessageHandler {
|
||||
* @returns {string[]} Missing permission flag keys.
|
||||
*/
|
||||
checkPermissions(permissions, channel) {
|
||||
if (!channel?.guild) return []; // DMs — no guild perms
|
||||
if (!channel?.guild) return [];
|
||||
const me = channel.guild.members?.me ?? null;
|
||||
if (!me) {
|
||||
logger.warn("[MessageHandler] Cannot check permissions — guild.members.me is null");
|
||||
return []; // can't verify
|
||||
return [];
|
||||
}
|
||||
const perms = channel.permissionsFor?.(me) ?? null;
|
||||
if (!perms) {
|
||||
logger.warn("[MessageHandler] Cannot check permissions — channel.permissionsFor() unavailable");
|
||||
return []; // can't verify
|
||||
return [];
|
||||
}
|
||||
// Convert string names (e.g. "SendMessages") to numeric PermissionFlags values,
|
||||
// same as CommandHandler.assertRequirements does.
|
||||
return permissions.filter(p => !perms.has(PermissionFlags[p] ?? p));
|
||||
}
|
||||
|
||||
@@ -177,7 +173,7 @@ export class MessageHandler {
|
||||
}
|
||||
}
|
||||
|
||||
const embed = new EmbedBuilder().setColor(0xFF4444); // Red for errors
|
||||
const embed = new EmbedBuilder().setColor(0xFF4444);
|
||||
|
||||
if (criticalItems.length > 0) {
|
||||
embed.setTitle("Missing Permissions — Bot Cannot Work Properly");
|
||||
@@ -192,7 +188,7 @@ export class MessageHandler {
|
||||
"Some features may not work without these permissions, but the bot can still play music.\n\n" +
|
||||
optionalItems.join("\n")
|
||||
);
|
||||
embed.setColor(0xFFA500); // Orange for warnings
|
||||
embed.setColor(0xFFA500);
|
||||
}
|
||||
|
||||
embed.setFooter({
|
||||
@@ -209,7 +205,6 @@ export class MessageHandler {
|
||||
* @returns {Promise<boolean>} If all permissions are given.
|
||||
*/
|
||||
async assertPermissions(permissions, message) {
|
||||
// Ensure bot's guild member is cached before checking
|
||||
const guild = message.guild ?? await message.client?.guilds?.resolve?.(message.guildId);
|
||||
if (guild && !guild.members?.me) {
|
||||
try { await guild.members.fetchMe(); } catch (_) { /* fetch failed, checkPermissions will warn */ }
|
||||
@@ -229,12 +224,10 @@ export class MessageHandler {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Build a rich embed listing what's missing and why
|
||||
const permEmbed = this.buildPermissionEmbed(missing, message.guildId);
|
||||
try {
|
||||
await message.reply({ embeds: [permEmbed] }, { ping: false });
|
||||
} catch (e) {
|
||||
// If reply fails (e.g. also missing EmbedLinks), fall back to plain text
|
||||
logger.warn("[MessageHandler] Failed to send permission embed:", e.message);
|
||||
try {
|
||||
const names = missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k);
|
||||
@@ -264,8 +257,6 @@ export class MessageHandler {
|
||||
* @returns {Message|null}
|
||||
*/
|
||||
get(id) {
|
||||
// channel.messages is a MessageManager — @fluxerjs/core may not expose it.
|
||||
// Guard with optional chaining so the loop is a no-op if the property is absent.
|
||||
for (const channel of this.client.channels.values()) {
|
||||
const msg = channel.messages?.get?.(id) ?? null;
|
||||
if (msg) return new Message(msg, this);
|
||||
@@ -283,8 +274,6 @@ export class MessageHandler {
|
||||
const cached = this.get(id);
|
||||
if (cached) return cached;
|
||||
const channel = await this.client.channels.fetch(channelId);
|
||||
// channel.fetchMessage() is the @fluxerjs/core method.
|
||||
// Fall back to the channel.messages.fetch() if the former is absent.
|
||||
const raw = typeof channel.fetchMessage === "function"
|
||||
? await channel.fetchMessage(id)
|
||||
: await channel.messages?.fetch?.(id);
|
||||
@@ -390,7 +379,6 @@ export class MessageHandler {
|
||||
if (!(await this.assertPermissions(["SendMessages", "EmbedLinks"], replyingTo))) return null;
|
||||
let opts;
|
||||
if (typeof message === "string") {
|
||||
// Auto-wrap plain text in an embed (matches old replyEmbed behavior)
|
||||
opts = this.#createEmbed(message, replyingTo);
|
||||
} else {
|
||||
opts = { ...message };
|
||||
@@ -407,7 +395,6 @@ export class MessageHandler {
|
||||
async replyEmbed(replyingTo, message, options = {}) {
|
||||
if (!(await this.assertPermissions(["SendMessages", "EmbedLinks"], replyingTo))) return null;
|
||||
|
||||
// Raw embed payload — pass straight through without re-wrapping
|
||||
if (typeof message === "object" && Array.isArray(message.embeds)) {
|
||||
return new Message(await replyingTo.reply(message, { ping: false }), this);
|
||||
}
|
||||
@@ -438,7 +425,6 @@ export class MessageHandler {
|
||||
}
|
||||
let opts;
|
||||
if (typeof message === "string") {
|
||||
// Auto-wrap plain text in an embed (matches old sendEmbed behavior)
|
||||
opts = this.#createEmbed(message, channel);
|
||||
} else {
|
||||
opts = message;
|
||||
@@ -456,7 +442,6 @@ export class MessageHandler {
|
||||
if (this.checkPermissions(["SendMessages", "EmbedLinks"], channel).length !== 0) {
|
||||
return this.sendMessage(channel, typeof content === "string" ? content : content?.embedText ?? "");
|
||||
}
|
||||
// Raw embed payload — pass straight through without re-wrapping
|
||||
if (typeof content === "object" && Array.isArray(content.embeds)) {
|
||||
return new Message(await channel.send(content), this);
|
||||
}
|
||||
@@ -476,12 +461,10 @@ export class MessageHandler {
|
||||
* @returns {Promise<Message>}
|
||||
*/
|
||||
async editEmbed(message, content, embedOptions = {}) {
|
||||
// Transient HTTP status codes worth retrying (gateway/server hiccups).
|
||||
const RETRYABLE = new Set([502, 503, 504]);
|
||||
const MAX_ATTEMPTS = 3;
|
||||
const RETRY_DELAY_MS = 1500;
|
||||
|
||||
// Build the payload once, outside the retry loop.
|
||||
let payload;
|
||||
if (typeof content === "object" && Array.isArray(content.embeds)) {
|
||||
payload = content;
|
||||
@@ -499,13 +482,11 @@ export class MessageHandler {
|
||||
try {
|
||||
return new Message(await message.edit(payload), this);
|
||||
} catch (err) {
|
||||
// Message was deleted — nothing to edit, bail silently.
|
||||
if (err.code === "UNKNOWN_MESSAGE" || err.code === 10008) {
|
||||
logger.warn("[MessageHandler] editEmbed: Message no longer exists, skipping edit.");
|
||||
return null;
|
||||
}
|
||||
|
||||
// Retry on transient gateway errors (502/503/504).
|
||||
if (RETRYABLE.has(err.statusCode) && attempt < MAX_ATTEMPTS) {
|
||||
logger.warn(`[MessageHandler] editEmbed: ${err.statusCode} on attempt ${attempt}/${MAX_ATTEMPTS}, retrying in ${RETRY_DELAY_MS}ms…`);
|
||||
await new Promise(r => setTimeout(r, RETRY_DELAY_MS));
|
||||
@@ -545,7 +526,6 @@ export class MessageHandler {
|
||||
m.edit(send()).catch(() => {});
|
||||
});
|
||||
|
||||
// Auto-close after 5 minutes
|
||||
const guildId = msg.message?.guildId ?? null;
|
||||
setTimeout(() => {
|
||||
unobserve();
|
||||
@@ -561,7 +541,6 @@ export class MessageHandler {
|
||||
const { joinVoiceChannel } = await import("@fluxerjs/voice");
|
||||
const channel = await this.client.channels.fetch(channelId);
|
||||
if (!channel || !("guildId" in channel)) throw new Error("Cannot join a non-guild voice channel.");
|
||||
// @fluxerjs/voice API: joinVoiceChannel(client, channel) — NOT the old object style
|
||||
return joinVoiceChannel(this.client, channel);
|
||||
}
|
||||
}
|
||||
@@ -777,13 +756,13 @@ export class PageBuilder {
|
||||
|
||||
setForm(form) {
|
||||
this.form = form;
|
||||
this.initiated = false; // reset so createPages() rebuilds if called again
|
||||
this.initiated = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
setMaxLines(maxLinesPerPage = 2) {
|
||||
this.maxLinesPerPage = maxLinesPerPage;
|
||||
this.initiated = false; // reset so createPages() rebuilds with new page size
|
||||
this.initiated = false;
|
||||
return this;
|
||||
}
|
||||
|
||||
@@ -912,7 +891,6 @@ export class RichPaginator {
|
||||
const tabEmojis = this._tabs.map(t => t.emoji);
|
||||
const allReactions = [...tabEmojis, this._prev, this._next];
|
||||
|
||||
// Send initial embed
|
||||
const nativeMsg = this._msg.message ?? this._msg;
|
||||
if (!nativeMsg?.reply) return null;
|
||||
|
||||
@@ -925,7 +903,6 @@ export class RichPaginator {
|
||||
|
||||
const guildId = (this._msg.channel?.guildId) ?? (this._msg.guildId) ?? null;
|
||||
|
||||
// Add reactions
|
||||
for (const emoji of allReactions) {
|
||||
await rawMsg.react(emoji).catch(() => {});
|
||||
}
|
||||
@@ -964,7 +941,6 @@ export class RichPaginator {
|
||||
} catch (e) {
|
||||
logger.warn("[RichPaginator] removeAllReactions failed:", e?.message ?? e);
|
||||
}
|
||||
// Fallback: remove each bot reaction individually
|
||||
for (const emoji of allReactions) {
|
||||
try {
|
||||
await rawMsg.removeReaction(emoji);
|
||||
@@ -972,10 +948,8 @@ export class RichPaginator {
|
||||
}
|
||||
};
|
||||
|
||||
// Timer resets on every reaction interaction
|
||||
const closeSession = async () => {
|
||||
unobserve();
|
||||
// Update footer to show session closed
|
||||
const currentEmbed = buildEmbed(state.tab, state.page);
|
||||
if (!currentEmbed.footer) currentEmbed.footer = { text: "" };
|
||||
currentEmbed.footer.text += " • " + this._handler.t(guildId, "pagination.embed.sclosedTitle");
|
||||
@@ -990,7 +964,6 @@ export class RichPaginator {
|
||||
timer = setTimeout(closeSession, this._timeout);
|
||||
};
|
||||
|
||||
// Wrap reaction handler to reset timer on each interaction
|
||||
const origHandler = wrapped.handler.observedReactions.get(rawMsg.id);
|
||||
if (origHandler) {
|
||||
const origCb = origHandler.cb;
|
||||
@@ -1051,7 +1024,6 @@ export class QueuePaginator {
|
||||
|
||||
const guildId = (this._msg.channel?.guildId) ?? (this._msg.guildId) ?? null;
|
||||
|
||||
// No arrows needed for single page
|
||||
if (totalPages <= 1) return rawMsg;
|
||||
|
||||
const prev = this._prev;
|
||||
@@ -1108,26 +1080,10 @@ export class QueuePaginator {
|
||||
}
|
||||
}
|
||||
|
||||
// ─── HelpCommand ──────────────────────────────────────────────────────────────
|
||||
// Self-contained help command — no help.mjs needed.
|
||||
//
|
||||
// Usage in index.mjs (inside the Remix constructor, after commands are set up):
|
||||
//
|
||||
// import { HelpCommand } from "./src/MessageHandler.mjs";
|
||||
//
|
||||
// new HelpCommand(this.handler, this.messages, (msg) => this.getSettings(msg))
|
||||
// .register();
|
||||
//
|
||||
// That's it. %help, %h, and %commands all work automatically.
|
||||
// The \x00help hack in index.mjs and the commands.helpCommand override are
|
||||
// no longer needed — remove them both.
|
||||
|
||||
const HELP_CMDS_PER_PAGE = 10;
|
||||
const HELP_SESSION_MS = 30 * 1000; // 30 seconds
|
||||
const HELP_SESSION_MS = 30 * 1000;
|
||||
|
||||
// ── Tab definitions ───────────────────────────────────────────────────────────
|
||||
// Add or remove tabs here. `categories` maps to cmd.category values set via
|
||||
// .setCategory() on CommandBuilder. `static: true` renders a hand-written page.
|
||||
const HELP_TABS = [
|
||||
{
|
||||
emoji: "🏠",
|
||||
@@ -1227,26 +1183,19 @@ export class HelpCommand {
|
||||
* Call once during bot startup, after commands have been loaded.
|
||||
*/
|
||||
register() {
|
||||
// Guard: if register() is called more than once (e.g. via hot-reload), bail out.
|
||||
// A second call would stack another MessageCreate listener and re-wrap the format/reply
|
||||
// handlers a second time, causing duplicate help responses and doubled logic.
|
||||
if (this._registered) return;
|
||||
this._registered = true;
|
||||
|
||||
const HELP_ALIASES = ["help", "h", "commands"];
|
||||
|
||||
// Neutralize built-in help interceptor
|
||||
this._commands.helpCommand = "\x00help";
|
||||
const _fmt = this._commands.format.bind(this._commands);
|
||||
this._commands.format = (text, guildId) =>
|
||||
_fmt(text, guildId).replace(/\x00help/g, "help");
|
||||
|
||||
// Intercept replyHandler to swallow the "Unknown Command" error
|
||||
// that CommandHandler emits when it sees %help but can't find it.
|
||||
const _reply = this._commands.replyHandler.bind(this._commands);
|
||||
this._commands.replyHandler = (message, msg) => {
|
||||
if (typeof message === "string" && message.toLowerCase().includes("unknown command")) {
|
||||
// Check if the triggering command was a help alias — if so, drop it silently
|
||||
const content = msg?.content ?? msg?.message?.content ?? "";
|
||||
const guildId = msg?.channel?.channel?.guildId ?? msg?.message?.guildId;
|
||||
const prefix = this._commands.getPrefix(guildId);
|
||||
@@ -1259,13 +1208,12 @@ export class HelpCommand {
|
||||
else if (content.startsWith(ping)) body = content.slice(ping.length).trim();
|
||||
if (body !== null) {
|
||||
const first = body.split(/\s+/)[0]?.toLowerCase();
|
||||
if (HELP_ALIASES.includes(first)) return; // silently drop
|
||||
if (HELP_ALIASES.includes(first)) return;
|
||||
}
|
||||
}
|
||||
return _reply(message, msg);
|
||||
};
|
||||
|
||||
// Safety evict in case help.mjs is still present
|
||||
const evict = () => {
|
||||
for (const alias of HELP_ALIASES) {
|
||||
const i = this._commands.commandNames.indexOf(alias);
|
||||
@@ -1284,7 +1232,6 @@ export class HelpCommand {
|
||||
return r;
|
||||
};
|
||||
|
||||
// Our sole listener for help
|
||||
this._messages.onMessage((msg) => {
|
||||
if (!msg?.content) return;
|
||||
const content = msg.content.trim();
|
||||
@@ -1307,15 +1254,12 @@ export class HelpCommand {
|
||||
});
|
||||
}
|
||||
|
||||
// ── Internal handler ───────────────────────────────────────────────────────
|
||||
|
||||
_handle(msg, args, prefix) {
|
||||
const allCmds = this._commands.commands;
|
||||
const query = (args[0] ?? "").trim();
|
||||
|
||||
// ── Specific command lookup (%help play, %help settings get, …) ──────────
|
||||
if (query && isNaN(Number(query))) {
|
||||
// Walk subcommands: %help settings get → finds "settings" then "get"
|
||||
let currCmd = null;
|
||||
for (const word of [query, ...args.slice(1)]) {
|
||||
const pool = currCmd ? currCmd.subcommands : allCmds;
|
||||
@@ -1335,7 +1279,6 @@ export class HelpCommand {
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Tab jump by number (%help 2 → open tab index 1) ──────────────────────
|
||||
const startTab = query
|
||||
? Math.max(0, Math.min(HELP_TABS.length - 1, parseInt(query) - 1))
|
||||
: 0;
|
||||
|
||||
@@ -9,9 +9,6 @@ import { logger } from "./constants/Logger.mjs";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { Events } from "@fluxerjs/core";
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// MoonlinkManager ──────────────────────────────────────────────────────────────
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
export class MoonlinkManager extends EventEmitter {
|
||||
/** @type {Manager} */
|
||||
|
||||
+11
-208
@@ -36,8 +36,6 @@ function mkEmbed(desc) {
|
||||
/** NodeLink default password — centralised so it doesn't need to be hardcoded in two places. */
|
||||
const NL_DEFAULT_PASSWORD = "youshallnotpass";
|
||||
|
||||
// Cache compiled sanitize regexes keyed by "host:port:password" to avoid
|
||||
// rebuilding identical RegExp objects on every error path.
|
||||
const _sanitizeCache = new Map();
|
||||
|
||||
/**
|
||||
@@ -69,14 +67,13 @@ function sanitizeError(msg, nl = {}) {
|
||||
const ep = password.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
||||
regexes.push(new RegExp(ep, "g"));
|
||||
}
|
||||
// Cap cache size — in practice there's only one NodeLink config, but guard anyway
|
||||
if (_sanitizeCache.size >= 20) _sanitizeCache.clear();
|
||||
_sanitizeCache.set(cacheKey, regexes);
|
||||
}
|
||||
|
||||
let s = String(msg);
|
||||
for (const re of regexes) {
|
||||
re.lastIndex = 0; // reset stateful global regexes between calls
|
||||
re.lastIndex = 0;
|
||||
s = s.replace(re, re.source.includes("redacted") ? "[redacted]" : "[internal]");
|
||||
}
|
||||
return s;
|
||||
@@ -87,19 +84,15 @@ function isIgnorableMediaStateError(err) {
|
||||
return msg.includes("InvalidState") || msg.includes("failed to capture frame") || msg.includes("capture frame");
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// PlayerWorkerPool — persistent worker pool to avoid spawning a new Node.js
|
||||
// isolate (~40 MB V8 heap) for every search/play command.
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class PlayerWorkerPool {
|
||||
constructor(size, workerPath, nlConfig = {}) {
|
||||
this._size = size;
|
||||
this._workerPath = workerPath;
|
||||
this._nlConfig = nlConfig;
|
||||
this._workers = []; // { worker, busy, _currentJobKey }
|
||||
this._queue = []; // { jobKey, msg, resolve, reject, onMessage }
|
||||
this._pending = new Map(); // jobKey → { resolve, reject, onMessage }
|
||||
this._workers = [];
|
||||
this._queue = [];
|
||||
this._pending = new Map();
|
||||
this._jobCounter = 0;
|
||||
|
||||
for (let i = 0; i < size; i++) this._spawn();
|
||||
@@ -109,8 +102,6 @@ class PlayerWorkerPool {
|
||||
const worker = new Worker(this._workerPath, {
|
||||
workerData: {
|
||||
poolMode: true,
|
||||
// Pass NodeLink config so the module-level nlGet fallback
|
||||
// has the correct host/port/password if _nlGet is ever null.
|
||||
data: { nodelink: this._nlConfig ?? {} }
|
||||
}
|
||||
});
|
||||
@@ -141,9 +132,6 @@ class PlayerWorkerPool {
|
||||
});
|
||||
|
||||
worker.on("error", (err) => {
|
||||
// Release only the job currently assigned to THIS worker.
|
||||
// Iterating all _pending would incorrectly reject in-flight jobs
|
||||
// from other workers, leaving those workers stuck busy=true forever.
|
||||
if (entry._currentJobKey != null) {
|
||||
const cb = this._pending.get(entry._currentJobKey);
|
||||
if (cb) {
|
||||
@@ -153,7 +141,6 @@ class PlayerWorkerPool {
|
||||
entry._currentJobKey = null;
|
||||
}
|
||||
entry.busy = false;
|
||||
// Replace dead worker
|
||||
const errIdx = this._workers.indexOf(entry);
|
||||
if (errIdx !== -1) this._workers.splice(errIdx, 1);
|
||||
this._spawn();
|
||||
@@ -207,9 +194,6 @@ class PlayerWorkerPool {
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// Queue Class
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
export class Queue extends EventEmitter {
|
||||
data = [];
|
||||
@@ -308,50 +292,37 @@ export class Queue extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// Player Class
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
export default class Player extends EventEmitter {
|
||||
/** @type {import("revoice.js").VoiceConnection|null} */
|
||||
connection = null;
|
||||
_guildId = null;
|
||||
_channelId = null;
|
||||
// The channel this player was originally spawned/assigned to for 247 mode.
|
||||
// Set externally by spawnPlayer after joining. Used by _is247Enabled() so
|
||||
// that even if the bot is temporarily in a transit channel (e.g. "move"),
|
||||
// the player knows its intended home channel and can check 247 correctly.
|
||||
_home247Channel = null;
|
||||
|
||||
// Components
|
||||
queue = null;
|
||||
client = null;
|
||||
settings = null;
|
||||
config = {};
|
||||
// revoice.js instances
|
||||
/** @type {import("revoice.js").MediaPlayer|null} */
|
||||
_mediaPlayer = null;
|
||||
/** @type {import("./constants/FluxerRevoice.mjs").FluxerRevoice|null} Shared FluxerRevoice instance (injected from Remix) */
|
||||
_revoice = null;
|
||||
|
||||
// moonlink.js manager reference (set by PlayerManager)
|
||||
/** @type {import("./MoonlinkManager.mjs").MoonlinkManager|null} */
|
||||
_moonlink = null;
|
||||
|
||||
// Playback state
|
||||
leaving = false;
|
||||
_paused = false;
|
||||
_pausedAt = null; // track exact moment of pause for clock sync
|
||||
_pausedAt = null;
|
||||
_playingNext = false;
|
||||
startedPlaying = null;
|
||||
// searches Map with max-size eviction to prevent memory leak on busy servers.
|
||||
searches = new Map();
|
||||
_searchMaxSize = 50;
|
||||
_maxQueueSize = 10_000; // Max tracks in queue to prevent unbounded memory growth
|
||||
_maxQueueSize = 10_000;
|
||||
resultLimit = 5;
|
||||
preferredVolume = 1;
|
||||
|
||||
// Streaming state
|
||||
_streamingStopped = false;
|
||||
_skipping = false;
|
||||
_currentPassthrough = null;
|
||||
@@ -359,22 +330,17 @@ export default class Player extends EventEmitter {
|
||||
_radioAnnounced = false;
|
||||
_queueEndedSent = false;
|
||||
|
||||
// Active audio filter — { key, label, payload } or null
|
||||
activeFilter = null;
|
||||
activeFilterPayload = null;
|
||||
|
||||
// Inactivity timeout
|
||||
_inactivityTimer = null;
|
||||
_inactivityLimit = 3 * 60 * 1000; // 3 min default
|
||||
_pendingInactivityCheck = false; // Guard to prevent race between join() timer and reseed
|
||||
_inactivityLimit = 3 * 60 * 1000;
|
||||
_pendingInactivityCheck = false;
|
||||
|
||||
// Join mutex — prevents concurrent join() calls from racing each other
|
||||
_isJoining = false;
|
||||
|
||||
// destroyed flag — prevents playback/worker spawn after destroy()
|
||||
_destroyed = false;
|
||||
|
||||
// NodeLink config (kept for direct stream URL building; session managed by moonlink)
|
||||
_nl = {
|
||||
host: "localhost",
|
||||
port: 3000,
|
||||
@@ -395,14 +361,12 @@ export default class Player extends EventEmitter {
|
||||
this._voiceCache = opts.voiceCache ?? null;
|
||||
this.locale = opts.locale ?? null;
|
||||
|
||||
// Merge NodeLink config (for stream URL building)
|
||||
this._nl = {
|
||||
...this._nl,
|
||||
...(this.config?.nodelink ?? {}),
|
||||
...(opts.nodelink ?? {}),
|
||||
};
|
||||
|
||||
// Set inactivity limit
|
||||
const inactivityMs = this.config?.timers?.inactivityTimeout ?? this.config?.inactivityTimeout;
|
||||
if (inactivityMs !== undefined) {
|
||||
const parsed = Number(inactivityMs);
|
||||
@@ -411,13 +375,10 @@ export default class Player extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// moonlink.js manager reference — injected by PlayerManager
|
||||
this._moonlink = opts.moonlink ?? null;
|
||||
|
||||
// revoice.js shared instance — injected by PlayerManager
|
||||
this._revoice = opts.revoice ?? null;
|
||||
|
||||
// Robust session sync that handles stale sessions
|
||||
if (this._moonlink) {
|
||||
this._onMoonlinkReady = (sessionId) => {
|
||||
const oldId = this._nl.sessionId;
|
||||
@@ -427,7 +388,6 @@ export default class Player extends EventEmitter {
|
||||
}
|
||||
};
|
||||
this._moonlink.on("ready", this._onMoonlinkReady);
|
||||
// Immediate sync if moonlink is already ready
|
||||
const existingSession = this._moonlink.getLiveSessionId?.() ?? this._moonlink.sessionId;
|
||||
if (existingSession) {
|
||||
this._nl.sessionId = existingSession;
|
||||
@@ -435,9 +395,6 @@ export default class Player extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// 24/7 Mode Check
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Check if 24/7 mode is enabled for this player's channel.
|
||||
@@ -467,22 +424,16 @@ export default class Player extends EventEmitter {
|
||||
? raw.map(id => String(id).replace(/\D/g, "")).filter(Boolean)
|
||||
: [String(raw).replace(/\D/g, "")];
|
||||
|
||||
// Use the home channel this player was assigned to for 247 — this is
|
||||
// set by spawnPlayer and doesn't change when the bot is temporarily
|
||||
// moved to a transit channel. This gives a per-player 247 check that
|
||||
// works correctly with multi-voice-per-guild setups.
|
||||
const homeChannel = this._home247Channel
|
||||
? String(this._home247Channel).replace(/\D/g, "")
|
||||
: null;
|
||||
const currentChannel = String(this._channelId ?? "").replace(/\D/g, "");
|
||||
|
||||
// Determine which channel to check the mode for
|
||||
const matchChannel = channels.includes(homeChannel) ? homeChannel
|
||||
: channels.includes(currentChannel) ? currentChannel
|
||||
: null;
|
||||
if (!matchChannel) return "off";
|
||||
|
||||
// Per-channel mode lookup: each channel can have its own on/auto/off
|
||||
return get247ChannelMode(set, matchChannel);
|
||||
};
|
||||
|
||||
@@ -502,7 +453,6 @@ export default class Player extends EventEmitter {
|
||||
const cleanGuild = String(this._guildId ?? "").replace(/\D/g, "");
|
||||
if (cleanGuild) return cleanGuild;
|
||||
|
||||
// Fallback: resolve from the channel object
|
||||
try {
|
||||
const channelId = this._channelId ?? this._home247Channel;
|
||||
if (channelId) {
|
||||
@@ -515,10 +465,6 @@ export default class Player extends EventEmitter {
|
||||
return null;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Volume Restore
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
_restoreVolume() {
|
||||
if (!this._guildId) return;
|
||||
@@ -545,21 +491,16 @@ export default class Player extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Inactivity Timer
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
_hasHumansInChannel() {
|
||||
if (!this._channelId || !this._guildId) return false;
|
||||
const cleanChan = String(this._channelId).replace(/\D/g, "");
|
||||
const cleanGuild = String(this._guildId).replace(/\D/g, "");
|
||||
|
||||
// O(1) lookup via VoiceStateCache channelMembers index
|
||||
if (this._voiceCache && this._voiceCache.hasHumansInChannel(cleanGuild, cleanChan)) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Legacy fallback: iterate observedVoiceUsers (O(n))
|
||||
try {
|
||||
const voiceUsers = this._observedVoiceUsers;
|
||||
if (voiceUsers && typeof voiceUsers.iterateHumanUsers === "function") {
|
||||
@@ -570,7 +511,6 @@ export default class Player extends EventEmitter {
|
||||
) return true;
|
||||
}
|
||||
} else if (voiceUsers) {
|
||||
// Raw Map fallback (shouldn't happen with new code)
|
||||
for (const [, info] of voiceUsers) {
|
||||
if (
|
||||
String(info.guildId ?? "").replace(/\D/g, "") === cleanGuild &&
|
||||
@@ -600,7 +540,6 @@ export default class Player extends EventEmitter {
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
// LiveKit participant fallback
|
||||
try {
|
||||
const room = this.connection?.room;
|
||||
if (room?.isConnected && room.remoteParticipants) {
|
||||
@@ -622,17 +561,11 @@ export default class Player extends EventEmitter {
|
||||
const mode = this._get247Mode();
|
||||
logger.inactivity(`[Player] Checking 24/7 mode for guild ${this._guildId}: ${mode}`);
|
||||
|
||||
// %247 auto: bot always stays in voice, never start inactivity timer
|
||||
// %247 on: bot stays in voice permanently — never start inactivity timer
|
||||
// %247 off: bot leaves when alone — timer is allowed
|
||||
if (mode === "auto" || mode === "on") {
|
||||
logger.inactivity(`[Player] 24/7 ${mode} mode active for guild ${this._guildId}, skipping inactivity timer`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't start the inactivity timer if there is a song currently playing
|
||||
// or songs waiting in the queue — the bot should stay as long as there's
|
||||
// music to play, even if no humans are currently in the channel.
|
||||
if (this.queue?.getCurrent() || !this.queue?.isEmpty()) {
|
||||
logger.inactivity(`[Player] Queue has songs for guild ${this._guildId}, skipping inactivity timer`);
|
||||
return;
|
||||
@@ -645,8 +578,6 @@ export default class Player extends EventEmitter {
|
||||
|
||||
logger.inactivity(`[Player] Starting inactivity timer for guild ${this._guildId} (${this._inactivityLimit / 1000}s)`);
|
||||
this._inactivityTimer = setTimeout(() => {
|
||||
// Re-check all conditions before leaving — they may have changed while
|
||||
// the timer was running (user joined, 24/7 enabled, song queued, etc.)
|
||||
const currentMode = this._get247Mode();
|
||||
if (currentMode === "auto" || currentMode === "on") {
|
||||
logger.inactivity(`[Player] 24/7 ${currentMode} mode enabled during inactivity wait, aborting leave`);
|
||||
@@ -666,8 +597,6 @@ export default class Player extends EventEmitter {
|
||||
}
|
||||
|
||||
_stopInactivityTimer() {
|
||||
// Also cancel any pending inactivity check that Player.join() scheduled.
|
||||
// Clearing the flag prevents that delayed check from restarting the timer.
|
||||
this._pendingInactivityCheck = false;
|
||||
if (this._inactivityTimer) {
|
||||
logger.inactivity(`[Player] Stopping inactivity timer for guild ${this._guildId}`);
|
||||
@@ -676,9 +605,6 @@ export default class Player extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// MediaPlayer Management
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
async _ensureMediaPlayer() {
|
||||
if (this._destroyed) return false;
|
||||
@@ -731,7 +657,7 @@ export default class Player extends EventEmitter {
|
||||
e?.message?.includes("InvalidState") ||
|
||||
e?.message?.includes("failed to capture frame")
|
||||
) {
|
||||
return; // race condition on skip/leave — safe to swallow
|
||||
return;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
@@ -790,14 +716,10 @@ export default class Player extends EventEmitter {
|
||||
logger.error("[Player] Error stopping media player:", e.message);
|
||||
}
|
||||
|
||||
// Null the reference so the native revoice.js/LiveKit object can be GC'd.
|
||||
this._mediaPlayer = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// HTTP/Stream Helpers
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
async _request(url, options = {}, returnStream = false) {
|
||||
return new Promise((resolve, reject) => {
|
||||
@@ -825,7 +747,6 @@ export default class Player extends EventEmitter {
|
||||
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"));
|
||||
// Strip auth header on cross-origin redirects
|
||||
const redirectUrl = new URL(loc);
|
||||
if (redirectUrl.host !== urlObj.host) {
|
||||
delete options.headers?.Authorization;
|
||||
@@ -893,9 +814,6 @@ export default class Player extends EventEmitter {
|
||||
return elapsedMs / totalMs >= 0.85 || remainingMs <= 15_000;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Audio Streaming (revoice.js)
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
async _streamViaRevoice(url, inputOptions = []) {
|
||||
if (this._streamingStopped) return;
|
||||
@@ -938,7 +856,6 @@ export default class Player extends EventEmitter {
|
||||
const onFfmpegError = (err) => {
|
||||
const ffMsg = err?.message ?? String(err);
|
||||
|
||||
// treat SIGKILL as graceful — _stopMediaPlayer() always kills FFmpeg with SIGKILL.
|
||||
const isGracefulKill =
|
||||
ffMsg.includes("aborted") ||
|
||||
ffMsg.includes("Input stream error") ||
|
||||
@@ -952,12 +869,10 @@ export default class Player extends EventEmitter {
|
||||
return resolve();
|
||||
}
|
||||
cleanup();
|
||||
// If we deliberately stopped (skip/leave), resolve silently
|
||||
if (this._streamingStopped || this._skipping) return resolve();
|
||||
return reject(new Error(`FFmpeg stream ended early: ${ffMsg}`));
|
||||
}
|
||||
|
||||
// Genuine unexpected FFmpeg error
|
||||
logger.error("[Player] FFmpeg error:", ffMsg);
|
||||
cleanup();
|
||||
if (this._streamingStopped || this._skipping) return resolve();
|
||||
@@ -990,11 +905,10 @@ export default class Player extends EventEmitter {
|
||||
return reject(e);
|
||||
}
|
||||
|
||||
// Dynamic safety timeout based on track duration.
|
||||
const trackDuration = this._getTrackDurationMs(currentTrack);
|
||||
const safetyMs = (trackDuration > 0 && currentTrack?.type !== "radio")
|
||||
? trackDuration + 15_000
|
||||
: 20 * 60 * 1000; // default 20 min for radio/unknown
|
||||
: 20 * 60 * 1000;
|
||||
|
||||
const safetyTimer = setTimeout(() => {
|
||||
logger.warn(`[Player] Stream safety timeout hit (${Math.round(safetyMs/1000)}s) — advancing queue`);
|
||||
@@ -1044,7 +958,6 @@ export default class Player extends EventEmitter {
|
||||
|
||||
if (url.includes("/v4/loadstream")) {
|
||||
logger.player(`[Player] NodeLink loadStream PCM active`);
|
||||
// Raw PCM from NodeLink — tell FFmpeg the input format
|
||||
const pcmInputOpts = ["-f", "s16le", "-ar", "48000", "-ac", "2"];
|
||||
return await this._streamViaRevoice(url, pcmInputOpts);
|
||||
}
|
||||
@@ -1065,9 +978,6 @@ export default class Player extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Voice Connection (revoice.js)
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
async join(channelId) {
|
||||
if (this._destroyed) return;
|
||||
@@ -1082,13 +992,9 @@ export default class Player extends EventEmitter {
|
||||
logger.player(`[Player] Already in channel: ${channelId}`);
|
||||
return;
|
||||
}
|
||||
// Connection is dead — clean up. No auto-reconnect; the caller
|
||||
// must explicitly re-join if they want to reconnect.
|
||||
logger.player(`[Player] Dead connection detected for ${channelId}, cleaning up`);
|
||||
try { this.connection.removeAllListeners(); } catch (_) {}
|
||||
|
||||
// Use FluxerRevoice's channel-specific leave instead of raw
|
||||
// vm.updateVoiceState(guildId, null) which nukes ALL guild channels.
|
||||
if (this._revoice && this._channelId) {
|
||||
try { this._revoice.markIntentionalDisconnect(this._channelId); } catch (_) {}
|
||||
try { this._revoice._leaveGateway(this._channelId, this._guildId ?? this._resolveGuildId()); } catch (_) {}
|
||||
@@ -1109,8 +1015,6 @@ export default class Player extends EventEmitter {
|
||||
logger.mediaplayer("[Player] Cleaning up existing connection before join");
|
||||
try { this.connection.removeAllListeners(); } catch (_) {}
|
||||
|
||||
// Use FluxerRevoice's channel-specific leave instead of raw
|
||||
// vm.updateVoiceState(guildId, null) which nukes ALL guild channels.
|
||||
if (this._revoice && this._channelId) {
|
||||
try { this._revoice.markIntentionalDisconnect(this._channelId); } catch (_) {}
|
||||
try { this._revoice._leaveGateway(this._channelId, this._guildId ?? this._resolveGuildId()); } catch (_) {}
|
||||
@@ -1121,20 +1025,11 @@ export default class Player extends EventEmitter {
|
||||
await this.connection.disconnect();
|
||||
} catch (_) {}
|
||||
|
||||
// Brief wait so the gateway processes the leave before we join a
|
||||
// new channel. FluxerRevoice adds its own _globalJoinDelay too.
|
||||
await Utils.sleep(500);
|
||||
this.connection = null;
|
||||
this._mediaPlayer = null;
|
||||
}
|
||||
|
||||
// ── FluxerRevoice join ─────────────────────────────────────────────
|
||||
// Use the FluxerRevoice instance to join the voice channel via the
|
||||
// Fluxer gateway. FluxerRevoice sends a VOICE_STATE_UPDATE through
|
||||
// the gateway, receives VOICE_SERVER_UPDATE with LiveKit credentials,
|
||||
// then creates a FluxerVoiceConnection wrapping a LiveKit Room.
|
||||
// The FluxerVoiceConnection is API-compatible with revoice.js's
|
||||
// VoiceConnection (has .room, .disconnect(), .leave(), events).
|
||||
if (!this._revoice) {
|
||||
throw new Error("FluxerRevoice instance not available — cannot join voice channel");
|
||||
}
|
||||
@@ -1154,19 +1049,10 @@ export default class Player extends EventEmitter {
|
||||
|
||||
logger.mediaplayer(`[Player] FluxerVoiceConnection obtained (isConnected: ${room.isConnected}, connectionState: ${room.connectionState})`);
|
||||
|
||||
// ── Wait for the room to be connected ──────────────────────────────
|
||||
// FluxerRevoice already waits for the LiveKit room to be ready before
|
||||
// resolving the join() promise, but we add a safety net for slow
|
||||
// LiveKit servers.
|
||||
// Uses the correct @livekit/rtc-node API:
|
||||
// room.isConnected — boolean getter
|
||||
// room.connectionState — ConnectionState enum
|
||||
// RoomEvent.ConnectionStateChanged — fires with ConnectionState value
|
||||
let connected = false;
|
||||
let settled = false;
|
||||
|
||||
try {
|
||||
// If already connected (FluxerRevoice.wait usually resolves this), skip
|
||||
if (room.isConnected) {
|
||||
connected = true;
|
||||
settled = true;
|
||||
@@ -1182,7 +1068,6 @@ export default class Player extends EventEmitter {
|
||||
const timeout = setTimeout(() => {
|
||||
if (settled) return;
|
||||
cleanup();
|
||||
// Use room.isConnected as the source of truth
|
||||
if (room.isConnected) {
|
||||
connected = true;
|
||||
settled = true;
|
||||
@@ -1190,7 +1075,6 @@ export default class Player extends EventEmitter {
|
||||
} else if (!room.isConnected && (room.connectionState === ConnectionState.CONN_DISCONNECTED || room.connectionState === 0)) {
|
||||
reject(new Error(`LiveKit disconnected (connectionState: ${room.connectionState})`));
|
||||
} else {
|
||||
// Still connecting or indeterminate — optimistically proceed
|
||||
connected = true;
|
||||
settled = true;
|
||||
resolve();
|
||||
@@ -1226,7 +1110,6 @@ export default class Player extends EventEmitter {
|
||||
}
|
||||
}, 500);
|
||||
|
||||
// Immediate check using correct API
|
||||
if (room.isConnected) {
|
||||
connected = true;
|
||||
settled = true;
|
||||
@@ -1248,9 +1131,6 @@ export default class Player extends EventEmitter {
|
||||
logger.mediaplayer("[Player] Room ready via FluxerRevoice, proceeding to MediaPlayer");
|
||||
}
|
||||
|
||||
// ── VoiceConnection event handlers ──────────────────────────────────
|
||||
// FluxerVoiceConnection emits "disconnect" on unexpected
|
||||
// disconnection and "autoleave" when the room empties.
|
||||
connection.on("error", (err) => {
|
||||
if (this.connection !== connection) {
|
||||
try { connection.removeAllListeners(); } catch (_) {}
|
||||
@@ -1262,9 +1142,6 @@ export default class Player extends EventEmitter {
|
||||
.catch(() => {})
|
||||
.finally(() => {
|
||||
if (this.leaving || this._destroyed) return;
|
||||
// %247 on/auto: don't autoleave on voice errors — stop the media
|
||||
// player but stay in the channel. The GatewayHandler will
|
||||
// detect the state change and schedule a rejoin if needed.
|
||||
if (mode === "auto" || mode === "on") {
|
||||
logger.inactivity(`[Player] Voice error in 24/7 ${mode} mode — staying in channel, not autoleaving`);
|
||||
return;
|
||||
@@ -1281,16 +1158,9 @@ export default class Player extends EventEmitter {
|
||||
if (!this.leaving && !this._destroyed) {
|
||||
const mode = this._get247Mode();
|
||||
if (mode === "auto" || mode === "on") {
|
||||
// %247 auto/on: Do NOT emit autoleave on unexpected disconnect.
|
||||
// The GatewayHandler will detect the bot's voice state change
|
||||
// and schedule a rejoin. Emitting autoleave here would cause
|
||||
// the player to be destroyed before the rejoin can be scheduled,
|
||||
// and creates a race condition where both Player.mjs AND
|
||||
// GatewayHandler try to handle the disconnect simultaneously.
|
||||
logger.mediaplayer(`[Player] Unexpected disconnect detected (24/7 ${mode}) — stopping media player, GatewayHandler will schedule rejoin`);
|
||||
this._stopMediaPlayer().catch(() => {});
|
||||
} else {
|
||||
// %247 off: emit autoleave as normal.
|
||||
logger.mediaplayer("[Player] Unexpected disconnect detected");
|
||||
this._stopMediaPlayer()
|
||||
.catch(() => {})
|
||||
@@ -1303,8 +1173,6 @@ export default class Player extends EventEmitter {
|
||||
|
||||
connection.on("autoleave", () => {
|
||||
if (this.connection !== connection) return;
|
||||
// Check 24/7 mode before forwarding the autoleave — for 24/7 channels
|
||||
// the bot should never leave due to an empty room.
|
||||
const mode = this._get247Mode();
|
||||
if (mode === "auto" || mode === "on") {
|
||||
logger.mediaplayer(`[Player] Auto-leave suppressed for 24/7 ${mode} channel (room empty but staying)`);
|
||||
@@ -1316,7 +1184,6 @@ export default class Player extends EventEmitter {
|
||||
}
|
||||
});
|
||||
|
||||
// Send self-deaf voice state update via @fluxerjs/voice if available
|
||||
try {
|
||||
const vm = getVoiceManager(this.client);
|
||||
vm.updateVoiceState(channelId, { self_deaf: true, self_mute: false });
|
||||
@@ -1349,7 +1216,6 @@ export default class Player extends EventEmitter {
|
||||
logger.error("[Player] Join failed:", e.message, causeStr);
|
||||
|
||||
if (e.message?.includes("401") || e.message?.includes("Unauthorized")) {
|
||||
// Track 401 errors for logging purposes
|
||||
logger.warn(`[Player] Join failed with 401 Unauthorized for guild ${this._guildId}`);
|
||||
}
|
||||
|
||||
@@ -1375,7 +1241,6 @@ export default class Player extends EventEmitter {
|
||||
this._mediaPlayer = null;
|
||||
}
|
||||
|
||||
// Clean up from FluxerRevoice connections map before disconnecting
|
||||
const channelId = this._channelId;
|
||||
if (this._revoice && channelId) {
|
||||
try {
|
||||
@@ -1425,10 +1290,6 @@ export default class Player extends EventEmitter {
|
||||
const connToDestroy = this.connection;
|
||||
this.connection = null;
|
||||
this._mediaPlayer = null;
|
||||
// Mark the disconnect as intentional BEFORE disconnecting so that
|
||||
// the RoomEvent.Disconnected handler in FluxerRevoice (and the
|
||||
// VoiceState bot-disconnect handler in GatewayHandler) do NOT treat
|
||||
// this as an unexpected drop and schedule a spurious rejoin.
|
||||
if (this._revoice && this._channelId) {
|
||||
try { this._revoice.markIntentionalDisconnect(this._channelId); } catch (_) {}
|
||||
}
|
||||
@@ -1448,9 +1309,6 @@ export default class Player extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Playback Controls
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
get paused() { return this._paused; }
|
||||
|
||||
@@ -1460,7 +1318,7 @@ export default class Player extends EventEmitter {
|
||||
if (this._paused)
|
||||
return ":negative_squared_cross_mark: Already paused!";
|
||||
this._paused = true;
|
||||
this._pausedAt = Date.now(); // Capture freeze moment
|
||||
this._pausedAt = Date.now();
|
||||
this._mediaPlayer?.pause();
|
||||
this.emit("playback", false);
|
||||
this._stopInactivityTimer();
|
||||
@@ -1473,7 +1331,6 @@ export default class Player extends EventEmitter {
|
||||
if (!this._paused)
|
||||
return ":negative_squared_cross_mark: Not paused!";
|
||||
|
||||
// Adjust start time by the duration of the pause
|
||||
if (this._pausedAt) {
|
||||
this.startedPlaying += (Date.now() - this._pausedAt);
|
||||
}
|
||||
@@ -1532,7 +1389,6 @@ export default class Player extends EventEmitter {
|
||||
this.queue.current = null;
|
||||
this._skipping = true;
|
||||
|
||||
// If the queue is now empty after splicing, send queue-end immediately.
|
||||
if (this.queue.isEmpty() && !this._wasRadio && !this._queueEndedSent) {
|
||||
this._queueEndedSent = true;
|
||||
const prefix = (() => {
|
||||
@@ -1557,15 +1413,11 @@ export default class Player extends EventEmitter {
|
||||
}
|
||||
}).catch(e => logger.error("[Player] skipTo stop error:", e.message))
|
||||
.finally(() => {
|
||||
// Always reset _skipping — even if _stopMediaPlayer() threw.
|
||||
this._skipping = false;
|
||||
});
|
||||
return `:track_next: Skipped to position ${position}`;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Volume Control
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
setVolume(v) {
|
||||
this.preferredVolume = Utils.clamp(v, 0, 2);
|
||||
@@ -1576,9 +1428,6 @@ export default class Player extends EventEmitter {
|
||||
return `Volume changed to \`${Math.round(this.preferredVolume * 100)}%\`.`;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Audio Filter Control
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
async applyFilter(filterPayload, meta = null) {
|
||||
const guildId = this._guildId;
|
||||
@@ -1620,15 +1469,6 @@ export default class Player extends EventEmitter {
|
||||
this.activeFilterPayload = meta ? filterPayload : null;
|
||||
this.emit("filter", this.activeFilter);
|
||||
|
||||
// Restart the current stream so the loadstream URL picks up the new filters.
|
||||
// The PATCH only updates NodeLink's player state — it does NOT modify the
|
||||
// currently-streaming PCM pipe. Without restarting, the audio won't change.
|
||||
//
|
||||
// Guard: only restart if we're mid-playback (startedPlaying is set) AND
|
||||
// _doPlayNext is NOT in progress. When _doPlayNext calls applyFilter()
|
||||
// before starting a new track, startedPlaying hasn't been set yet and
|
||||
// _doPlayNext itself handles the stream — firing _replayWithFilters here
|
||||
// would cause the same song to play twice simultaneously.
|
||||
if (current?.encoded && this.connection && !this.leaving && !this._streamingStopped && this.startedPlaying && !this._playingNext) {
|
||||
const elapsed = this.startedPlaying ? (Date.now() - this.startedPlaying) : 0;
|
||||
const positionMs = Math.max(0, elapsed);
|
||||
@@ -1653,28 +1493,23 @@ export default class Player extends EventEmitter {
|
||||
const current = this.queue.getCurrent();
|
||||
if (!current?.encoded || !this.connection || this.leaving) return;
|
||||
|
||||
// Stop the current stream (kills FFmpeg + passthrough)
|
||||
this._streamingStopped = true;
|
||||
await this._stopMediaPlayer().catch(() => {});
|
||||
this._streamingStopped = false;
|
||||
|
||||
// _stopMediaPlayer sets _mediaPlayer to null — must recreate before streaming
|
||||
const hasPlayer = await this._ensureMediaPlayer();
|
||||
if (!hasPlayer) {
|
||||
logger.warn("[Player] _replayWithFilters: could not recreate MediaPlayer");
|
||||
return;
|
||||
}
|
||||
|
||||
// Restore volume on the fresh player
|
||||
if (this.preferredVolume !== 1) {
|
||||
this._mediaPlayer.setVolume(this.preferredVolume);
|
||||
}
|
||||
|
||||
// Build a fresh loadstream URL — include filters so NodeLink applies them server-side
|
||||
const nlBase = `http://${this._nl.host}:${this._nl.port}`;
|
||||
let streamUrl = `${nlBase}/v4/loadstream?encodedTrack=${encodeURIComponent(current.encoded)}&position=${positionMs}&volume=100`;
|
||||
|
||||
// Append active filter payload to the URL so NodeLink processes them
|
||||
if (this.activeFilterPayload) {
|
||||
streamUrl += `&filters=${encodeURIComponent(JSON.stringify(this.activeFilterPayload))}`;
|
||||
}
|
||||
@@ -1686,14 +1521,10 @@ export default class Player extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Queue Management
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
isEmpty() { return this.queue.isEmpty(); }
|
||||
|
||||
addToQueue(d, t) {
|
||||
// Enforce queue size cap to prevent unbounded memory growth
|
||||
if (this.queue.data.length >= this._maxQueueSize) {
|
||||
logger.warn(`[Player] Queue size cap reached (${this._maxQueueSize}) — dropping oldest track`);
|
||||
this.queue.data.shift();
|
||||
@@ -1713,7 +1544,6 @@ export default class Player extends EventEmitter {
|
||||
|
||||
addManyToQueue(t, top = false) {
|
||||
if (!Array.isArray(t)) return 0;
|
||||
// Enforce queue size cap
|
||||
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`);
|
||||
@@ -1759,22 +1589,17 @@ export default class Player extends EventEmitter {
|
||||
return msg;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Display Helpers
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
_createProgressBar(length = 15) {
|
||||
const current = this.queue.getCurrent();
|
||||
if (!current?.duration || !this.startedPlaying) return Utils.progressBar(0, 1, length);
|
||||
|
||||
// Common elapsed calculation
|
||||
const totalMs = this._getTrackDurationMs(current);
|
||||
let elapsed = Date.now() - this.startedPlaying;
|
||||
if (this._paused && this._pausedAt) {
|
||||
elapsed = this._pausedAt - this.startedPlaying;
|
||||
}
|
||||
|
||||
// Clamp to ensure 1:58/1:30 doesn't happen
|
||||
if (totalMs > 0 && elapsed > totalMs) elapsed = totalMs;
|
||||
elapsed = Math.max(0, elapsed);
|
||||
|
||||
@@ -1837,7 +1662,6 @@ export default class Player extends EventEmitter {
|
||||
elapsed = this._pausedAt - this.startedPlaying;
|
||||
}
|
||||
|
||||
// Clamp UI to total duration
|
||||
if (totalMs > 0 && elapsed > totalMs) elapsed = totalMs;
|
||||
return Utils.prettifyMS(Math.max(0, elapsed));
|
||||
}
|
||||
@@ -1954,9 +1778,6 @@ export default class Player extends EventEmitter {
|
||||
})));
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Worker Management
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
_workerPool = null;
|
||||
|
||||
@@ -1985,9 +1806,6 @@ export default class Player extends EventEmitter {
|
||||
);
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Public Play Methods
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
async fetchResults(query, id, provider = "ytm") {
|
||||
try {
|
||||
@@ -2074,9 +1892,6 @@ export default class Player extends EventEmitter {
|
||||
return events;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Radio track builder
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
_buildRadioTrack(radio) {
|
||||
return {
|
||||
@@ -2120,9 +1935,6 @@ export default class Player extends EventEmitter {
|
||||
if (!this.leaving) this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Core Playback
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
async playNext() {
|
||||
if (this._playingNext) return;
|
||||
@@ -2182,8 +1994,6 @@ export default class Player extends EventEmitter {
|
||||
if (!room || !room.isConnected) {
|
||||
const cs = room?.connectionState;
|
||||
const mode = this._get247Mode();
|
||||
// For 24/7 channels, don't autoleave on dead room — put the song back
|
||||
// and wait for the GatewayHandler to schedule a rejoin.
|
||||
if (mode === "auto" || mode === "on") {
|
||||
logger.mediaplayer(`[Player] Room not connected (isConnected: ${room?.isConnected}, connectionState: ${cs}) in 24/7 ${mode} mode — deferring autoleave, waiting for rejoin.`);
|
||||
if (songData) {
|
||||
@@ -2236,7 +2046,6 @@ export default class Player extends EventEmitter {
|
||||
const positionMs = 0;
|
||||
streamUrl = `${nlBase}/v4/loadstream?encodedTrack=${encodeURIComponent(songData.encoded)}&position=${positionMs}&volume=100`;
|
||||
|
||||
// Append active filters so NodeLink applies them server-side
|
||||
if (this.activeFilterPayload) {
|
||||
streamUrl += `&filters=${encodeURIComponent(JSON.stringify(this.activeFilterPayload))}`;
|
||||
}
|
||||
@@ -2273,7 +2082,6 @@ export default class Player extends EventEmitter {
|
||||
|
||||
logger.player(`[Player:${this._guildId}] Streaming: ${songData.title}`);
|
||||
|
||||
// Reset all timing flags
|
||||
this.startedPlaying = Date.now();
|
||||
this._paused = false;
|
||||
this._pausedAt = null;
|
||||
@@ -2299,8 +2107,6 @@ export default class Player extends EventEmitter {
|
||||
|
||||
if (!this.leaving && !this._skipping) {
|
||||
if (songData.type === "radio") {
|
||||
// Radio track ended — do NOT auto-retry/re-queue.
|
||||
// The user must manually restart if they want to continue.
|
||||
logger.player(`[Player] Radio stream ended: ${songData.title}`);
|
||||
this.queue.current = null;
|
||||
this._streamingStopped = true;
|
||||
@@ -2320,9 +2126,6 @@ export default class Player extends EventEmitter {
|
||||
this._skipping = false;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Lyrics
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
async lyrics() {
|
||||
const current = this.queue.getCurrent();
|
||||
|
||||
+10
-146
@@ -65,26 +65,15 @@ function getPlayerChannelId(player, fallbackChannelId = null) {
|
||||
function botHasVoicePermissions(client, channelId) {
|
||||
try {
|
||||
const channel = client?.channels?.get?.(channelId);
|
||||
if (!channel) return true; // can't check — assume yes, let gateway decide
|
||||
if (!channel) return true;
|
||||
const me = channel.guild?.members?.me;
|
||||
if (!me) return true; // not cached — assume yes
|
||||
// FluxerJS uses member.permissionsIn(channel), NOT channel.permissionsFor(member).
|
||||
// The permissionsFor method does not exist in FluxerJS (it's a Discord.js API).
|
||||
// permissionsIn computes base perms + channel overwrites, and expands Administrator
|
||||
// to ALL_PERMISSIONS_BIGINT — so Admin bots always pass every has() check.
|
||||
if (!me) return true;
|
||||
const perms = me.permissionsIn?.(channel);
|
||||
if (!perms) return true; // can't read perms — assume yes
|
||||
// FluxerJS PermissionFlags (from @fluxerjs/util):
|
||||
// Administrator = 1n << 3n (0x8)
|
||||
// ViewChannel = 1n << 10n (0x400)
|
||||
// Connect = 1n << 20n (0x100000)
|
||||
// Speak = 1n << 21n (0x200000)
|
||||
// Administrator short-circuit: Admin bypasses all channel restrictions.
|
||||
if (!perms) return true;
|
||||
if (perms.has(0x8)) return true;
|
||||
// Bot must be able to see the channel, connect to it, and speak in it.
|
||||
return perms.has(0x400) && perms.has(0x100000) && perms.has(0x200000);
|
||||
} catch (_) {
|
||||
return true; // can't check — assume yes
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,11 +93,9 @@ function botHasVoicePermissions(client, channelId) {
|
||||
function sanitizeJoinError(err, client = null, channelId = null) {
|
||||
const msg = String(err?.message ?? err ?? "");
|
||||
if (msg.includes("401") || msg.includes("Unauthorized")) {
|
||||
// Gateway said 401 — but is it a real permission issue or a stale session?
|
||||
if (client && channelId && !botHasVoicePermissions(client, channelId)) {
|
||||
return "PERMISSION"; // bot genuinely lacks Connect/Speak
|
||||
return "PERMISSION";
|
||||
}
|
||||
// Bot has the permissions — this is a stale session race, not a real denial
|
||||
return "SESSION_RACE";
|
||||
}
|
||||
if (msg.includes("permission") || msg.includes("Permission")) {
|
||||
@@ -123,7 +110,7 @@ function sanitizeJoinError(err, client = null, channelId = null) {
|
||||
if (msg.includes("timeout") || msg.includes("timed out")) {
|
||||
return "TIMEOUT";
|
||||
}
|
||||
return null; // unknown — fall back to raw message
|
||||
return null;
|
||||
}
|
||||
|
||||
export class PlayerManager {
|
||||
@@ -173,12 +160,9 @@ export class PlayerManager {
|
||||
this.dashboard = config.dashboard ?? null;
|
||||
this.locale = config.locale ?? null;
|
||||
this.timers = config.timers ?? {};
|
||||
this._lastfm = null; // Set later by Remix class after init
|
||||
this._lastfm = null;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Guild→Player Reverse Index — O(1) lookups instead of O(n) scans
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Add a channel to the guild→player reverse index.
|
||||
@@ -226,7 +210,7 @@ export class PlayerManager {
|
||||
for (const channelId of set) {
|
||||
const player = this.playerMap.get(channelId);
|
||||
if (!player || player._destroyed) {
|
||||
set.delete(channelId); // prune stale entry
|
||||
set.delete(channelId);
|
||||
continue;
|
||||
}
|
||||
result.push([channelId, player]);
|
||||
@@ -256,7 +240,6 @@ export class PlayerManager {
|
||||
*/
|
||||
getPlayerByChannelId(channelId) {
|
||||
const cId = cleanId(channelId);
|
||||
// Try all guild indexes
|
||||
for (const [, channelSet] of this._guildPlayerIndex) {
|
||||
for (const mapChannelId of channelSet) {
|
||||
const player = this.playerMap.get(mapChannelId);
|
||||
@@ -292,34 +275,18 @@ export class PlayerManager {
|
||||
writable: true,
|
||||
});
|
||||
|
||||
// ── Per-player channel: standard { type, data } format ────────
|
||||
// The backend PlayerManager.setupEvents() expects:
|
||||
// { type: "startplay", data: serialisedVideo }
|
||||
// { type: "stopplay", data: null }
|
||||
// { type: "pause", data: { elapsedTime: ms } }
|
||||
// { type: "resume", data: { elapsedTime: ms } }
|
||||
// { type: "volume", data: number }
|
||||
// { type: "queue", data: serialisedQueueEvent }
|
||||
// { type: "join", data: userId }
|
||||
// { type: "leave", data: userId }
|
||||
|
||||
const emit = (type, data) => {
|
||||
if (!this.dashboard?.enabled) return;
|
||||
this.dashboard.updatePlayer({ type, data }, player);
|
||||
};
|
||||
|
||||
// ── Global channel: lifecycle events ──────────────────────────────────
|
||||
// The backend PlayerManager.initChannels() expects:
|
||||
// { type: "init", player: serialisedPlayer } — when player connects
|
||||
// { type: "close", player: serialisedPlayer } — when player disconnects
|
||||
|
||||
const emitGlobal = (type) => {
|
||||
if (!this.dashboard?.enabled) return;
|
||||
this.dashboard.playerUpdate({ type }, player);
|
||||
};
|
||||
|
||||
// Broadcast user list changes to the global :users channel when
|
||||
// someone joins or leaves the player's voice channel.
|
||||
const sendUserUpdates = (eventType) => {
|
||||
if (!this.dashboard?.enabled) return;
|
||||
const channelId = getPlayerChannelId(player, context.channelId);
|
||||
@@ -339,10 +306,7 @@ export class PlayerManager {
|
||||
if (stateChannelId !== channelId) continue;
|
||||
const member = guild.members?.get?.(state.userId ?? state.user_id);
|
||||
if (!member?.user || member.user?.bot) continue;
|
||||
// Send per-player channel "join"/"leave" event with just the user ID
|
||||
// (matching standard format where data = userId string)
|
||||
emit(eventType, member.user.id);
|
||||
// Also send global user update
|
||||
this.dashboard.userUpdate({
|
||||
type: eventType,
|
||||
guildId: cleanId(player._guildId ?? context.guildId),
|
||||
@@ -351,24 +315,17 @@ export class PlayerManager {
|
||||
}
|
||||
};
|
||||
|
||||
// ── Player event handlers ─────────────────────────────────────────────
|
||||
|
||||
player.on("roomfetched", () => {
|
||||
// Player connected — send "init" on the global channel
|
||||
emitGlobal("init");
|
||||
sendUserUpdates("join");
|
||||
});
|
||||
|
||||
player.on("startplay", (song) => {
|
||||
// Send the serialised video to the per-player channel
|
||||
emit("startplay", Dashboard.convertVideo(song ?? player.queue?.current));
|
||||
// Emit streamStartPlay with current timestamp so the backend can
|
||||
// calculate elapsed time accurately (standard behaviour)
|
||||
emit("streamStartPlay", Date.now());
|
||||
// Also broadcast on global channel for full state update
|
||||
this.dashboard.playerUpdate({ type: "startplay" }, player);
|
||||
|
||||
// ── Last.fm: now-playing notification + deferred scrobble ────────────
|
||||
if (this._lastfm?.enabled && song) {
|
||||
this._handleLastFmStartPlay(player, song);
|
||||
}
|
||||
@@ -380,7 +337,6 @@ export class PlayerManager {
|
||||
});
|
||||
|
||||
player.on("playback", (playing) => {
|
||||
// Sends "pause" or "resume" with { elapsedTime } — match that format
|
||||
const elapsedMs = player._pausedAt
|
||||
? (player._pausedAt.getTime?.() ?? Number(player._pausedAt)) -
|
||||
(player.startedPlaying?.getTime?.() ?? Number(player.startedPlaying ?? 0))
|
||||
@@ -396,37 +352,28 @@ export class PlayerManager {
|
||||
});
|
||||
|
||||
player.on("filter", (filter) => {
|
||||
// Filter events are Fluxer-specific.
|
||||
// Send as a custom event type; the backend will ignore unknown types.
|
||||
emit("filter", filter);
|
||||
});
|
||||
|
||||
player.on("update", (scope) => {
|
||||
// Generic update — send full player state on global channel
|
||||
this.dashboard.playerUpdate({ type: "update" }, player);
|
||||
});
|
||||
|
||||
player.on("message", (message) => {
|
||||
// No per-player equivalent — skip, only global broadcast
|
||||
});
|
||||
|
||||
player.on("autoleave", () => {
|
||||
sendUserUpdates("leave");
|
||||
// Send "close" on global channel so backend removes the player
|
||||
emitGlobal("close");
|
||||
emit("stopplay", null);
|
||||
});
|
||||
|
||||
player.on("leave", () => {
|
||||
sendUserUpdates("leave");
|
||||
// Send "close" on global channel so backend removes the player
|
||||
emitGlobal("close");
|
||||
emit("stopplay", null);
|
||||
});
|
||||
|
||||
// ── Queue event handler ───────────────────────────────────────────────
|
||||
// Queue events must be serialised with Dashboard.convertVideo() to match
|
||||
// the format the backend Queue.update() method expects.
|
||||
|
||||
player.queue?.on("queue", (queueEvent) => {
|
||||
const serialised = { type: queueEvent.type };
|
||||
@@ -469,7 +416,6 @@ export class PlayerManager {
|
||||
};
|
||||
break;
|
||||
default:
|
||||
// Unknown queue event — pass through as-is
|
||||
serialised.data = queueEvent.data;
|
||||
break;
|
||||
}
|
||||
@@ -494,9 +440,6 @@ export class PlayerManager {
|
||||
return this.locale.translate(guildId, key, replacements);
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Voice Channel Detection
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Attempt to detect the voice channel a user is currently in.
|
||||
@@ -516,7 +459,6 @@ export class PlayerManager {
|
||||
const seedObserved = (channelId) => {
|
||||
const cleanChannelId = cleanId(channelId);
|
||||
if (!cleanChannelId) return null;
|
||||
// Use voiceCache (O(1) with guildId) or fall back to observedVoiceUsers
|
||||
const cache = this.voiceCache ?? this.observedVoiceUsers;
|
||||
if (cache && !cache.has(userId, cleanGuild)) {
|
||||
cache.set(userId, { channelId: cleanChannelId, guildId: cleanGuild });
|
||||
@@ -539,10 +481,6 @@ export class PlayerManager {
|
||||
if (seeded) return seeded;
|
||||
} catch (_) {}
|
||||
|
||||
// ── Fallback: VoiceManager.voiceStates direct lookup ────────────────
|
||||
// After a reboot, getVoiceChannelId() may return null if the
|
||||
// VoiceManager hasn't synced yet, but voiceStates (populated from
|
||||
// READY / GUILD_CREATE raw gateway events) may already have the data.
|
||||
try {
|
||||
const vm = getVoiceManager(this.commands.client);
|
||||
if (vm?.voiceStates) {
|
||||
@@ -596,10 +534,6 @@ export class PlayerManager {
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
// ── Fallback: match user to any active player in the guild ──────────
|
||||
// After a reboot with 24/7, voice states may not be fully populated.
|
||||
// If the guild has active players, check if any of them have the user
|
||||
// as a remote participant in their LiveKit room.
|
||||
const liveGuildPlayers = [...this.playerMap.entries()].filter(([channelId, player]) => {
|
||||
const fallbackChannel =
|
||||
this.commands.client?.channels?.get?.(channelId) ??
|
||||
@@ -609,8 +543,6 @@ export class PlayerManager {
|
||||
if (liveGuildPlayers.length === 1) {
|
||||
return getPlayerChannelId(liveGuildPlayers[0][1], liveGuildPlayers[0][0]) || cleanId(liveGuildPlayers[0][0]);
|
||||
}
|
||||
// Multiple players — try LiveKit remote participants to find which
|
||||
// channel the user is actually in.
|
||||
if (liveGuildPlayers.length > 1) {
|
||||
for (const [mapKey, player] of liveGuildPlayers) {
|
||||
try {
|
||||
@@ -630,9 +562,6 @@ export class PlayerManager {
|
||||
return null;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Player Retrieval
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Get or create a player for the user's voice channel.
|
||||
@@ -662,9 +591,8 @@ export class PlayerManager {
|
||||
} catch (_) {}
|
||||
return player;
|
||||
}
|
||||
// Also check if a join is in-progress for this channel
|
||||
if (this._pendingJoins.has(cleanUserChannelId)) {
|
||||
return null; // A player is being created — caller should retry
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -676,8 +604,6 @@ export class PlayerManager {
|
||||
const channelList = serverPlayers.map(([chId]) => `<#${chId}>`).join(" or ");
|
||||
|
||||
if (!userChannelId) {
|
||||
// verifyUser=false: allow controlling the bot without being in voice
|
||||
// (e.g. volume, clear, remove — admin-style controls).
|
||||
if (!verifyUser) {
|
||||
const first = serverPlayers[0];
|
||||
first[1].textChannel = message.channel;
|
||||
@@ -701,7 +627,6 @@ export class PlayerManager {
|
||||
return match[1];
|
||||
}
|
||||
|
||||
// User is in a different channel than existing players.
|
||||
if (shouldJoin) {
|
||||
return new Promise((resolve) => {
|
||||
this.initPlayer(message, userChannelId, (p) => resolve(p));
|
||||
@@ -719,7 +644,6 @@ export class PlayerManager {
|
||||
|
||||
if (!userChannelId) {
|
||||
if (shouldJoin) {
|
||||
// Auto-detect failed — fall back to interactive channel selection prompt
|
||||
return this.promptVC(message);
|
||||
}
|
||||
message.reply(mkEmbed(this._t(message, "responses._common.noVoiceChannel")));
|
||||
@@ -735,9 +659,6 @@ export class PlayerManager {
|
||||
return null;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Channel Selection Prompt
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Prompt the user to select a voice channel.
|
||||
@@ -828,9 +749,6 @@ export class PlayerManager {
|
||||
});
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Leave
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Make the player leave its current voice channel.
|
||||
@@ -859,13 +777,9 @@ export class PlayerManager {
|
||||
const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId;
|
||||
this.playerMap.delete(activeChannelId);
|
||||
this._unindexPlayer(player._guildId, activeChannelId);
|
||||
// Clean up pending scrobble timer
|
||||
const pendingScrobble = this._pendingScrobbleTimers.get(activeChannelId);
|
||||
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this._pendingScrobbleTimers.delete(activeChannelId); }
|
||||
if (activeChannelId !== cleanChannelId) this.playerMap.delete(cleanChannelId);
|
||||
// Leave the voice channel BEFORE confirming to the user.
|
||||
// Previously, the reply was sent first, which meant the user saw "successfully left"
|
||||
// even if player.leave() subsequently threw an error.
|
||||
try {
|
||||
await player.leave();
|
||||
} catch (e) {
|
||||
@@ -875,9 +789,6 @@ export class PlayerManager {
|
||||
await msg.reply(mkEmbed(this._t(msg, "responses._common.successfullyLeft")));
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Player Initialisation
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Create and register a new Player for the given voice channel.
|
||||
@@ -900,11 +811,6 @@ export class PlayerManager {
|
||||
return message.reply(mkEmbed(this._t(message, "responses._common.voiceChannelRequired")));
|
||||
}
|
||||
|
||||
// Pre-check: verify the bot actually has Connect + Speak permission on the
|
||||
// voice channel BEFORE sending VOICE_STATE_UPDATE to the gateway. This
|
||||
// avoids a confusing 401 roundtrip when the bot genuinely lacks permission,
|
||||
// and makes the error message accurate instead of relying on the gateway's
|
||||
// ambiguous 401 (which can also mean "stale session").
|
||||
if (!botHasVoicePermissions(this.commands?.client, cid)) {
|
||||
return message.reply(mkEmbed(
|
||||
this._t(message, "responses.join.joinFailedPerms", { channel: `<#${cleanId(cid)}>` })
|
||||
@@ -919,7 +825,6 @@ export class PlayerManager {
|
||||
cb(existing);
|
||||
return message.reply(mkEmbed(this._t(message, "responses.join.alreadyJoined", { channel: cid })));
|
||||
}
|
||||
// Also block if a join is already in-progress for this channel
|
||||
if (this._pendingJoins.has(cleanChannelId)) {
|
||||
return message.reply(mkEmbed(this._t(message, "responses.join.joining")));
|
||||
}
|
||||
@@ -950,7 +855,6 @@ export class PlayerManager {
|
||||
const ch = player.textChannel;
|
||||
const guildId = cleanId(player._guildId ?? ch?.guildId ?? ch?.guild?.id ?? getMessageGuildId({ channel: ch }));
|
||||
|
||||
// Check 24/7 settings for this channel (per-channel mode)
|
||||
const raw247 = (() => {
|
||||
try { return this.settings.getServer(guildId)?.get("stay_247"); } catch (_) { return null; }
|
||||
})();
|
||||
@@ -962,7 +866,6 @@ export class PlayerManager {
|
||||
return channels.includes(homeChannelId) || channels.includes(activeChannelId);
|
||||
})();
|
||||
|
||||
// Per-channel mode: check the mode for this specific channel
|
||||
const matchChannel = isIn247List
|
||||
? (channels247list => channels247list.includes(homeChannelId) ? homeChannelId : activeChannelId)(
|
||||
Array.isArray(raw247) ? raw247.map(id => String(id).replace(/\D/g, "")) : [String(raw247).replace(/\D/g, "")]
|
||||
@@ -972,13 +875,6 @@ export class PlayerManager {
|
||||
? get247ChannelMode(this.settings.getServer(guildId), matchChannel)
|
||||
: "off";
|
||||
|
||||
// ── Safety guard: re-validate before destroying ────────────────────
|
||||
// Even if autoleave was emitted, don't destroy the player if:
|
||||
// 1. 24/7 mode is "on" or "auto" (bot should never leave)
|
||||
// 2. Humans are still in the channel
|
||||
// 3. There are songs in the queue or currently playing
|
||||
// This catches cases where the autoleave event was emitted from a
|
||||
// code path that didn't check these conditions (e.g. old timers).
|
||||
if (mode247 === "auto" || mode247 === "on") {
|
||||
logger.inactivity(`[PlayerManager] autoleave suppressed for 24/7 ${mode247} channel ${activeChannelId} (guild ${guildId})`);
|
||||
return;
|
||||
@@ -992,20 +888,14 @@ export class PlayerManager {
|
||||
return;
|
||||
}
|
||||
|
||||
// Remove player from map and destroy
|
||||
this.playerMap.delete(activeChannelId);
|
||||
this._unindexPlayer(player._guildId, activeChannelId);
|
||||
// Clean up pending scrobble timer
|
||||
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();
|
||||
|
||||
// Notify the channel that the bot left.
|
||||
// For %247 on: bot will rejoin on reboot (but not on disconnect)
|
||||
// For %247 auto: bot will rejoin automatically after disconnect
|
||||
// For non-247: user must manually re-invoke the join command
|
||||
const prefix = (() => {
|
||||
try { return this.settings.getServer(guildId)?.get("prefix") ?? "%"; } catch (_) { return "%"; }
|
||||
})();
|
||||
@@ -1041,8 +931,6 @@ export class PlayerManager {
|
||||
["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim());
|
||||
if (disabled) return;
|
||||
|
||||
// If textChannel is not set (e.g. after reboot recovery via _spawnPlayer),
|
||||
// resolve it from the saved announcementChannelId or guild channels
|
||||
if (!ch || typeof ch.send !== "function") {
|
||||
try {
|
||||
const serverSettings = this.settings.getServer(guildId);
|
||||
@@ -1075,7 +963,6 @@ export class PlayerManager {
|
||||
}
|
||||
if (!ch || typeof ch.send !== "function") return;
|
||||
|
||||
// Cache the resolved channel so future announcements don't need to re-resolve
|
||||
if (!player.textChannel) player.textChannel = ch;
|
||||
|
||||
ch.send(typeof m === "object" && Array.isArray(m.embeds) ? m : mkEmbed(m)).catch(err => {
|
||||
@@ -1085,15 +972,12 @@ export class PlayerManager {
|
||||
});
|
||||
});
|
||||
|
||||
// _pendingJoins was already added earlier (right after duplicate check)
|
||||
|
||||
(async () => {
|
||||
const statusMsg = await message.reply(mkEmbed(this._t(message, "responses.join.joining")));
|
||||
try {
|
||||
await player.join(cid);
|
||||
|
||||
// Only add to playerMap after join succeeds — this prevents phantom
|
||||
// entries from inflating the player count.
|
||||
this.playerMap.set(cleanChannelId, player);
|
||||
this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
|
||||
this._pendingJoins.delete(cleanChannelId);
|
||||
@@ -1116,19 +1000,15 @@ export class PlayerManager {
|
||||
const errCode = sanitizeJoinError(err, this.commands?.client, cleanChannelId);
|
||||
let errorMsg;
|
||||
if (errCode === "SESSION_RACE") {
|
||||
// Stale session — retry once after a short delay so the gateway can
|
||||
// clean up the previous voice session.
|
||||
logger.warn(`[PlayerManager] Stale voice session detected for channel ${cleanChannelId}, retrying in 2s...`);
|
||||
try {
|
||||
await new Promise(r => setTimeout(r, 2_000));
|
||||
// Clean up any leftover state before retrying
|
||||
if (player._revoice && player._channelId) {
|
||||
try { player._revoice._leaveGateway(player._channelId, player._guildId ?? player._resolveGuildId()); } catch (_) {}
|
||||
try { player._revoice.deleteConnection(player._channelId); } catch (_) {}
|
||||
}
|
||||
await player.join(cid);
|
||||
|
||||
// Retry succeeded
|
||||
this.playerMap.set(cleanChannelId, player);
|
||||
this._indexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
|
||||
await statusMsg.edit(mkEmbed(this._t(message, "responses.join.joined", { channel: cid })));
|
||||
@@ -1165,9 +1045,6 @@ export class PlayerManager {
|
||||
})();
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Last.fm Scrobbling
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Handle the "startplay" event for Last.fm: send now-playing notification
|
||||
@@ -1184,16 +1061,13 @@ export class PlayerManager {
|
||||
const guildId = cleanId(player._guildId);
|
||||
if (!guildId) return;
|
||||
|
||||
// Find all human users in the voice channel
|
||||
const channelId = getPlayerChannelId(player);
|
||||
const humanUserIds = [];
|
||||
|
||||
// Use VoiceStateCache O(1) channel index instead of iterating all users
|
||||
if (this.voiceCache) {
|
||||
const users = this.voiceCache.getHumansInChannel(guildId, channelId);
|
||||
humanUserIds.push(...users);
|
||||
} else if (this.observedVoiceUsers) {
|
||||
// Legacy fallback (VoiceStateCache is iterable via [Symbol.iterator])
|
||||
for (const [uid, info] of this.observedVoiceUsers) {
|
||||
if (cleanId(info.guildId) === guildId && cleanId(info.channelId) === channelId) {
|
||||
humanUserIds.push(uid);
|
||||
@@ -1201,7 +1075,6 @@ export class PlayerManager {
|
||||
}
|
||||
}
|
||||
|
||||
// Also check guild voice states as fallback
|
||||
const guild = player.client?.guilds?.get(guildId);
|
||||
if (guild) {
|
||||
const voiceStates = guild.voice_states ?? guild.voiceStates ?? null;
|
||||
@@ -1215,7 +1088,6 @@ export class PlayerManager {
|
||||
const uid = state?.userId ?? state?.user_id;
|
||||
const chId = cleanId(state?.channelId ?? state?.channel_id);
|
||||
if (uid && chId === channelId) {
|
||||
// Skip bots
|
||||
const member = guild.members?.get?.(uid);
|
||||
if (member?.user?.bot) continue;
|
||||
if (!humanUserIds.includes(uid)) humanUserIds.push(uid);
|
||||
@@ -1226,9 +1098,6 @@ export class PlayerManager {
|
||||
|
||||
const startedAtMs = player.startedPlaying;
|
||||
|
||||
// ── Cancel any previous pending scrobble timer for this channel ───────
|
||||
// Prevents duplicate scrobbles when startplay fires multiple times
|
||||
// (e.g. recovery rejoining, track restart, queue loop).
|
||||
const pendingKey = channelId;
|
||||
const existing = this._pendingScrobbleTimers.get(pendingKey);
|
||||
if (existing) {
|
||||
@@ -1236,12 +1105,10 @@ export class PlayerManager {
|
||||
this._pendingScrobbleTimers.delete(pendingKey);
|
||||
}
|
||||
|
||||
// Send now-playing for each linked user
|
||||
for (const userId of humanUserIds) {
|
||||
lastfm.updateNowPlaying(userId, song).catch(() => {});
|
||||
}
|
||||
|
||||
// Schedule deferred scrobble after threshold
|
||||
const durationMs = (() => {
|
||||
const d = song.duration;
|
||||
if (!d) return null;
|
||||
@@ -1255,15 +1122,13 @@ export class PlayerManager {
|
||||
durationMs * lastfm.scrobbleThreshold,
|
||||
lastfm.scrobbleMinMs
|
||||
);
|
||||
// Don't schedule if threshold is too far out (cap at 10 min)
|
||||
if (thresholdMs <= 600_000) {
|
||||
const timer = setTimeout(() => {
|
||||
this._pendingScrobbleTimers.delete(pendingKey);
|
||||
// Only scrobble if the same song is still playing
|
||||
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; // don't scrobble if paused
|
||||
if (player._paused) return;
|
||||
|
||||
const playedMs = Date.now() - (player.startedPlaying ?? startedAtMs ?? Date.now());
|
||||
if (lastfm.shouldScrobble(song, playedMs)) {
|
||||
@@ -1273,7 +1138,6 @@ export class PlayerManager {
|
||||
}
|
||||
}, thresholdMs);
|
||||
|
||||
// Store the timer so we can cancel it if startplay fires again
|
||||
this._pendingScrobbleTimers.set(pendingKey, { timer, songUrl: song.url, startedAtMs });
|
||||
}
|
||||
}
|
||||
|
||||
+3
-51
@@ -3,8 +3,6 @@ import { logger } from "./constants/Logger.mjs";
|
||||
import mysql from "mysql2";
|
||||
import { EventEmitter } from "node:events";
|
||||
|
||||
// Re-export the abstract SettingsManager base class so JSDoc type hints and
|
||||
// the migrate script can import it from a single canonical path.
|
||||
export { SettingsManager } from "../settings/Settings.mjs";
|
||||
|
||||
export class ServerSettings {
|
||||
@@ -24,7 +22,6 @@ export class ServerSettings {
|
||||
loadDefaults() { for (let key in this.manager.defaults) { this.data[key] = this.manager.defaults[key]; } }
|
||||
deserialize(json) { for (let k in json) { if (k === "id") continue; this.data[k] = json[k]; } }
|
||||
|
||||
// was `if (!this.data[key])` which clobbered valid falsy values like 0, false, ""
|
||||
checkDefaults(d) { for (let key in d) { if (this.data[key] === undefined) this.data[key] = d[key]; } }
|
||||
|
||||
get serializationData() { return { ...this.data, id: this.id }; }
|
||||
@@ -42,22 +39,15 @@ export class RemoteSettingsManager extends EventEmitter {
|
||||
/** @type {boolean} Whether the bot_id column exists in the settings table */
|
||||
_hasBotIdColumn = false;
|
||||
|
||||
// track retry count and apply exponential backoff on load failures
|
||||
_loadAttempts = 0;
|
||||
/** @type {Promise|null} Tracks the in-flight load() so setBotId() can wait for it */
|
||||
_loadPromise = null;
|
||||
// Per-server debounce timers: serverId → NodeJS.Timeout
|
||||
// Batches rapid set() calls (e.g. 24/7 mode changes that write stay_247 + stay_247_mode)
|
||||
// into a single remoteSave() 80ms after the last write, rather than firing one UPDATE
|
||||
// per key.
|
||||
_debounceTimers = new Map();
|
||||
|
||||
constructor(config, defaultsPath, botId = null) {
|
||||
super();
|
||||
this.botId = botId;
|
||||
this.db = mysql.createPool({ connectionLimit: 15, ...config });
|
||||
// Without this listener, any pool-level error (connection drop, timeout, protocol error)
|
||||
// fires an unhandled 'error' event which crashes the entire process with no log output.
|
||||
this.db.on("error", (err) => {
|
||||
logger.error("[DB] MySQL pool error:", err.code ?? err.message);
|
||||
});
|
||||
@@ -78,9 +68,8 @@ export class RemoteSettingsManager extends EventEmitter {
|
||||
* when two bots tried to INSERT rows for the same guild.
|
||||
*/
|
||||
async _ensureBotIdColumn() {
|
||||
if (this._hasBotIdColumn) return; // already verified column + PK
|
||||
if (this._hasBotIdColumn) return;
|
||||
|
||||
// Check if bot_id column exists and its properties
|
||||
const res = await this.query(
|
||||
`SELECT COLUMN_NAME, IS_NULLABLE, COLUMN_KEY FROM information_schema.COLUMNS `
|
||||
+ `WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'settings' AND COLUMN_NAME = 'bot_id'`
|
||||
@@ -92,11 +81,8 @@ export class RemoteSettingsManager extends EventEmitter {
|
||||
}
|
||||
|
||||
if (res.results.length === 0) {
|
||||
// ── Column doesn't exist: add it and update PK ─────────────────────
|
||||
logger.settings("[Settings] Auto-migrating: adding bot_id column to settings table...");
|
||||
|
||||
// NOT NULL DEFAULT '' — primary key columns can't be NULL in MySQL.
|
||||
// Existing rows get bot_id = '' which we'll claim for the current bot.
|
||||
const alterRes = await this.query(
|
||||
`ALTER TABLE settings ADD COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''`
|
||||
);
|
||||
@@ -105,22 +91,18 @@ export class RemoteSettingsManager extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
// Claim all existing rows for the current bot before updating PK.
|
||||
// This preserves existing settings (prefix, volume, etc.) instead of
|
||||
// leaving them orphaned with bot_id = ''.
|
||||
if (this.botId) {
|
||||
await this.query(
|
||||
`UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''`
|
||||
);
|
||||
}
|
||||
|
||||
// Update primary key from (id) to (id, bot_id)
|
||||
const pkRes = await this.query(
|
||||
`ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)`
|
||||
);
|
||||
if (pkRes.error) {
|
||||
logger.error("[Settings] Failed to update primary key:", pkRes.error);
|
||||
return; // Don't set flag — bot_id features can't work without composite PK
|
||||
return;
|
||||
}
|
||||
|
||||
this._hasBotIdColumn = true;
|
||||
@@ -128,41 +110,34 @@ export class RemoteSettingsManager extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
|
||||
// ── Column already exists: verify it's in the primary key ─────────────
|
||||
const colInfo = res.results[0];
|
||||
const isNullable = colInfo.IS_NULLABLE === 'YES';
|
||||
const isPrimaryKey = colInfo.COLUMN_KEY === 'PRI';
|
||||
|
||||
if (isPrimaryKey) {
|
||||
// Column exists and is part of composite PK — all good
|
||||
this._hasBotIdColumn = true;
|
||||
return;
|
||||
}
|
||||
|
||||
// Column exists but is NOT in PK — the ALTER TABLE PK update must have
|
||||
// failed previously (likely because the column had NULL values).
|
||||
logger.settings("[Settings] Fixing bot_id column: adding to primary key...");
|
||||
|
||||
// Step 1: Replace NULLs with empty string (PK columns can't be NULL)
|
||||
if (isNullable) {
|
||||
await this.query(`UPDATE settings SET bot_id = '' WHERE bot_id IS NULL`);
|
||||
await this.query(`ALTER TABLE settings MODIFY COLUMN bot_id VARCHAR(32) NOT NULL DEFAULT ''`);
|
||||
}
|
||||
|
||||
// Step 2: Claim unclaimed rows (bot_id = '') for the current bot
|
||||
if (this.botId) {
|
||||
await this.query(
|
||||
`UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''`
|
||||
);
|
||||
}
|
||||
|
||||
// Step 3: Update primary key
|
||||
const pkRes = await this.query(
|
||||
`ALTER TABLE settings DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)`
|
||||
);
|
||||
if (pkRes.error) {
|
||||
logger.error("[Settings] Failed to update primary key:", pkRes.error);
|
||||
return; // Don't set flag — can't use bot_id without composite PK
|
||||
return;
|
||||
}
|
||||
|
||||
this._hasBotIdColumn = true;
|
||||
@@ -180,14 +155,9 @@ export class RemoteSettingsManager extends EventEmitter {
|
||||
const changed = this.botId !== id;
|
||||
this.botId = id;
|
||||
if (changed) {
|
||||
// Wait for the initial load to finish before clearing and reloading
|
||||
if (this._loadPromise) await this._loadPromise;
|
||||
// Ensure the DB schema supports bot_id before querying with it
|
||||
await this._ensureBotIdColumn();
|
||||
|
||||
// Claim any unclaimed legacy rows (bot_id = '') for this bot.
|
||||
// This handles the case where the column was already properly set up
|
||||
// (e.g. by another bot's migration) but legacy rows weren't claimed yet.
|
||||
if (this._hasBotIdColumn && this.botId) {
|
||||
const claimRes = await this.query(
|
||||
`UPDATE settings SET bot_id = ${mysql.escape(String(this.botId))} WHERE bot_id = ''`
|
||||
@@ -197,7 +167,6 @@ export class RemoteSettingsManager extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// Reload with the new botId so we pick up this bot's rows
|
||||
this.guilds.clear();
|
||||
this._loadPromise = this.load();
|
||||
await this._loadPromise;
|
||||
@@ -247,7 +216,6 @@ export class RemoteSettingsManager extends EventEmitter {
|
||||
const res = await this.query(`SELECT * FROM settings WHERE 1=1${this._botIdWhere()}`);
|
||||
if (res.error) {
|
||||
this._loadAttempts++;
|
||||
// exponential backoff with a cap of 30s instead of forever-at-2s
|
||||
const delay = Math.min(1000 * Math.pow(2, this._loadAttempts - 1), 30_000);
|
||||
logger.error("[Settings] Init error (attempt", this._loadAttempts, "retrying in", delay + "ms):", res.error);
|
||||
return setTimeout(() => { this.load().catch(err => logger.error("[Settings] Retry load error:", err?.message ?? err)); }, delay);
|
||||
@@ -256,8 +224,6 @@ export class RemoteSettingsManager extends EventEmitter {
|
||||
res.results.forEach((r) => {
|
||||
try {
|
||||
const server = new ServerSettings(r.id, this);
|
||||
// mysql2 may return JSON columns as already-parsed objects;
|
||||
// only JSON.parse when the value is still a string.
|
||||
const parsed = (typeof r.data === "string") ? JSON.parse(r.data) : r.data;
|
||||
server.deserialize(parsed);
|
||||
server.checkDefaults(this.defaults);
|
||||
@@ -271,14 +237,9 @@ export class RemoteSettingsManager extends EventEmitter {
|
||||
|
||||
async remoteUpdate(server, key) {
|
||||
const val = server.data[key];
|
||||
// Arrays/objects must go through remoteSave — JSON_SET with scalar
|
||||
// interpolation corrupts arrays by merging IDs into one number on read-back.
|
||||
if (Array.isArray(val) || (typeof val === "object" && val !== null)) {
|
||||
return this.remoteSave(server);
|
||||
}
|
||||
// Use mysql.escape() for every user-supplied value to prevent SQL injection.
|
||||
// Preserve native boolean/number types — mysql.escape(String(false)) stores "false"
|
||||
// (a truthy string) which breaks strict equality checks like songAnnouncements === false.
|
||||
const escapedPath = mysql.escape(`$.${key}`);
|
||||
const escapedVal = (typeof val === "boolean" || typeof val === "number")
|
||||
? mysql.escape(val)
|
||||
@@ -316,8 +277,6 @@ export class RemoteSettingsManager extends EventEmitter {
|
||||
const escapedId = mysql.escape(id);
|
||||
const escapedData = mysql.escape(JSON.stringify(server.data));
|
||||
const bi = this._botIdInsert();
|
||||
// INSERT IGNORE: if the row already exists (race condition or failed
|
||||
// migration), silently skip instead of crashing with ER_DUP_ENTRY.
|
||||
const r = await this.query(
|
||||
`INSERT IGNORE INTO settings (id, data${bi.col}) VALUES (${escapedId}, ${escapedData}${bi.val})`
|
||||
);
|
||||
@@ -328,9 +287,6 @@ export class RemoteSettingsManager extends EventEmitter {
|
||||
if (!this.guilds.has(server.id)) { this.guilds.set(server.id, server); this.create(server.id, server); }
|
||||
const s = this.guilds.get(server.id);
|
||||
s.data[key] = server.data[key];
|
||||
// Debounce: collapse rapid successive set() calls (e.g. stay_247 + stay_247_mode written
|
||||
// together) into a single remoteSave() 80ms after the last write for this server.
|
||||
// This prevents N parallel UPDATE queries when multiple keys change in one command handler.
|
||||
const existing = this._debounceTimers.get(server.id);
|
||||
if (existing) clearTimeout(existing);
|
||||
this._debounceTimers.set(server.id, setTimeout(() => {
|
||||
@@ -344,8 +300,6 @@ export class RemoteSettingsManager extends EventEmitter {
|
||||
|
||||
getServer(id) {
|
||||
if (!this.guilds.has(id)) {
|
||||
// Return a fresh object but don't register it yet;
|
||||
// update() will call create() on the first real write.
|
||||
return new ServerSettings(id, this);
|
||||
}
|
||||
return this.guilds.get(id);
|
||||
@@ -357,8 +311,6 @@ export class RemoteSettingsManager extends EventEmitter {
|
||||
* @param {string} id - Guild / server ID
|
||||
*/
|
||||
removeServer(id) {
|
||||
// Clear any pending debounce timer so it doesn't fire after the guild is gone
|
||||
// and attempt a DB write for a server that no longer belongs to us.
|
||||
const timer = this._debounceTimers.get(id);
|
||||
if (timer) {
|
||||
clearTimeout(timer);
|
||||
|
||||
+11
-40
@@ -9,16 +9,13 @@
|
||||
* string processing, and validation used across the music bot.
|
||||
*/
|
||||
export class Utils {
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
// Time & Duration
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Format milliseconds to human-readable time string (H:MM:SS or M:SS)
|
||||
* @param {number} milliseconds - Duration in milliseconds
|
||||
* @returns {string} Formatted time string
|
||||
* @example Utils.prettifyMS(125000) // "2:05"
|
||||
* @example Utils.prettifyMS(3661000) // "1:01:01"
|
||||
* @example Utils.prettifyMS(125000)
|
||||
* @example Utils.prettifyMS(3661000)
|
||||
*/
|
||||
static prettifyMS(milliseconds) {
|
||||
if (!milliseconds || milliseconds < 0 || !isFinite(milliseconds)) {
|
||||
@@ -49,9 +46,9 @@ export class Utils {
|
||||
if (parts.some(isNaN) || parts.some(n => n < 0)) return 0;
|
||||
|
||||
let ms = 0;
|
||||
if (parts[0] !== undefined) ms += parts[0] * 1000; // seconds
|
||||
if (parts[1] !== undefined) ms += parts[1] * 60 * 1000; // minutes
|
||||
if (parts[2] !== undefined) ms += parts[2] * 3600 * 1000; // hours
|
||||
if (parts[0] !== undefined) ms += parts[0] * 1000;
|
||||
if (parts[1] !== undefined) ms += parts[1] * 60 * 1000;
|
||||
if (parts[2] !== undefined) ms += parts[2] * 3600 * 1000;
|
||||
|
||||
return ms;
|
||||
}
|
||||
@@ -66,9 +63,6 @@ export class Utils {
|
||||
return this.prettifyMS(seconds * 1000);
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
// Array Manipulation
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Shuffles array in-place using Fisher-Yates algorithm
|
||||
@@ -124,9 +118,6 @@ export class Utils {
|
||||
return [...new Set(array)];
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
// String Formatting
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Truncate text with ellipsis
|
||||
@@ -154,11 +145,11 @@ export class Utils {
|
||||
return title
|
||||
.replace(/\s*[\(\[][^\)\]]*(?:feat|ft|featuring|remix|edit|version|prod|official|audio|video|lyrics|visualizer)[^\)\]]*[\)\]]/gi, "")
|
||||
.replace(/\s*-\s*(?:feat|ft|featuring)\.?.*/gi, "")
|
||||
.replace(/\s*\|.*$/g, "") // Remove pipe and everything after
|
||||
.replace(/\s*【.*?】/g, "") // Remove Japanese brackets
|
||||
.replace(/\s*\[.*?\]/g, "") // Remove square brackets
|
||||
.replace(/\s*\(.*?\)/g, "") // Remove parentheses
|
||||
.replace(/\s{2,}/g, " ") // Collapse multiple spaces
|
||||
.replace(/\s*\|.*$/g, "")
|
||||
.replace(/\s*【.*?】/g, "")
|
||||
.replace(/\s*\[.*?\]/g, "")
|
||||
.replace(/\s*\(.*?\)/g, "")
|
||||
.replace(/\s{2,}/g, " ")
|
||||
.trim();
|
||||
}
|
||||
|
||||
@@ -171,14 +162,13 @@ export class Utils {
|
||||
static sanitizeFilename(str, maxLen = 50) {
|
||||
if (!str || typeof str !== "string") return "unknown";
|
||||
return str
|
||||
.replace(/[^a-z0-9\u4e00-\u9fa5]/gi, "_") // Keep CJK chars too
|
||||
.replace(/[^a-z0-9\u4e00-\u9fa5]/gi, "_")
|
||||
.replace(/_{2,}/g, "_")
|
||||
.substring(0, maxLen)
|
||||
.replace(/^_+|_+$/g, "");
|
||||
}
|
||||
|
||||
/**
|
||||
* Escape markdown characters for Discord
|
||||
* @param {string} text - Raw text
|
||||
* @returns {string} Escaped text
|
||||
*/
|
||||
@@ -220,9 +210,6 @@ export class Utils {
|
||||
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(decimals))} ${sizes[i]}`;
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
// ID Generation
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Generate random unique ID
|
||||
@@ -235,7 +222,6 @@ export class Utils {
|
||||
const timestamp = Date.now().toString(36).toUpperCase();
|
||||
let random = "";
|
||||
|
||||
// Generate enough random data
|
||||
while ((timestamp + random).length < targetLen) {
|
||||
random += Math.random().toString(36).substring(2).toUpperCase();
|
||||
}
|
||||
@@ -255,9 +241,6 @@ export class Utils {
|
||||
});
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
// Validation & Safety (CRITICAL for worker.mjs compatibility)
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Check if a string represents a finite number
|
||||
@@ -313,9 +296,6 @@ export class Utils {
|
||||
}
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
// Async Utilities
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Sleep/delay promise
|
||||
@@ -363,9 +343,6 @@ export class Utils {
|
||||
* @returns {Promise<T>}
|
||||
*/
|
||||
static timeout(promise, ms, message = "Operation timed out") {
|
||||
// Always clear the timeout timer once the race settles — whether promise wins or
|
||||
// the timeout wins. Without this, every successful call leaks a live timer for the
|
||||
// full `ms` duration, holding the timer handle in the event loop and bloating heap.
|
||||
let timerId;
|
||||
const timeoutPromise = new Promise((_, reject) => {
|
||||
timerId = setTimeout(() => reject(new Error(message)), ms);
|
||||
@@ -373,9 +350,6 @@ export class Utils {
|
||||
return Promise.race([promise, timeoutPromise]).finally(() => clearTimeout(timerId));
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
// Object Utilities
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Deep clone an object (JSON method - not suitable for circular refs)
|
||||
@@ -424,9 +398,6 @@ export class Utils {
|
||||
return result;
|
||||
}
|
||||
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
// Music-Specific Helpers
|
||||
// ═════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Create progress bar string
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
* Edit only here; FluxerListManager.mjs and commands/vote.mjs import from this file.
|
||||
*/
|
||||
|
||||
// ── FluxerList API ──────────────────────────────────────────────────────────────
|
||||
|
||||
export const FLUXERLIST = {
|
||||
/** Base URL for all FluxerList API v1 endpoints */
|
||||
|
||||
@@ -32,62 +32,37 @@ import { joinVoiceChannel, getVoiceManager } from "@fluxerjs/voice";
|
||||
import { logger } from "./Logger.mjs";
|
||||
|
||||
{
|
||||
// ── LiveKit SDK log suppression ──────────────────────────────────────────
|
||||
// The LiveKit Node.js SDK (via pino) emits verbose JSON and human-readable
|
||||
// log lines that flood the console. We monkey-patch console.log and
|
||||
// process.stdout.write to silently drop lines from the "lk-rtc" logger.
|
||||
//
|
||||
// Guard: only patch once even if the module is imported multiple times
|
||||
// (e.g. during hot-reload). The global symbol ensures idempotency.
|
||||
if (!globalThis.__fluxerLiveKitLogPatchApplied) {
|
||||
globalThis.__fluxerLiveKitLogPatchApplied = true;
|
||||
|
||||
const _originalConsoleLog = console.log;
|
||||
console.log = function (...args) {
|
||||
// Fast path: if the first arg is a string that looks like a pino JSON log
|
||||
if (args.length === 1 && typeof args[0] === "string" && args[0].startsWith("{")) {
|
||||
try {
|
||||
const parsed = JSON.parse(args[0]);
|
||||
// Drop pino logs from LiveKit SDK ("lk-rtc" name)
|
||||
if (parsed.name === "lk-rtc") return;
|
||||
} catch (_) {
|
||||
// Not valid JSON — pass through
|
||||
}
|
||||
}
|
||||
// Suppress LiveKit SDK's human-readable log lines:
|
||||
// [voice LiveKitRtc] connected to room
|
||||
// [voice LiveKitRtc] Room disconnected
|
||||
// [voice LiveKitRtc] emitting disconnect
|
||||
// [voice LiveKitRtc] Room reconnecting...
|
||||
// [voice LiveKitRtc] Room reconnected
|
||||
if (args.length >= 1 && typeof args[0] === "string" && args[0].includes("[voice LiveKitRtc]")) {
|
||||
return; // silently drop
|
||||
return;
|
||||
}
|
||||
_originalConsoleLog.apply(console, args);
|
||||
};
|
||||
|
||||
// ── Also monkey-patch process.stdout.write ──────────────────────────────
|
||||
// Pino writes directly to process.stdout.write, bypassing console.log
|
||||
// entirely. This is the primary path for the JSON log lines like:
|
||||
// {"level":20,"time":1778784504183,"pid":961949,"name":"lk-rtc",...}
|
||||
// We intercept these and silently drop them.
|
||||
const _originalStdoutWrite = process.stdout.write.bind(process.stdout);
|
||||
process.stdout.write = function (chunk, encoding, callback) {
|
||||
// Only intercept string chunks that look like pino JSON logs
|
||||
if (typeof chunk === "string" && chunk.startsWith("{")) {
|
||||
try {
|
||||
// Fast check: does it contain lk-rtc before full parse?
|
||||
if (chunk.includes('"lk-rtc"')) {
|
||||
const parsed = JSON.parse(chunk);
|
||||
if (parsed.name === "lk-rtc") {
|
||||
// Silently drop — call callback to signal "written" so pino doesn't stall
|
||||
if (typeof encoding === "function") { encoding(); }
|
||||
else if (typeof callback === "function") { callback(); }
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch (_) {
|
||||
// Not valid JSON — pass through
|
||||
}
|
||||
}
|
||||
return _originalStdoutWrite(chunk, encoding, callback);
|
||||
@@ -95,26 +70,18 @@ import { logger } from "./Logger.mjs";
|
||||
}
|
||||
}
|
||||
|
||||
// ConnectionState enum values for reference:
|
||||
// ConnectionState.CONN_DISCONNECTED = 0
|
||||
// ConnectionState.CONN_CONNECTED = 1
|
||||
// ConnectionState.CONN_RECONNECTING = 2
|
||||
|
||||
/** Helper: returns a human-readable label for a ConnectionState value */
|
||||
function stateLabel(cs) {
|
||||
if (cs === ConnectionState?.CONN_CONNECTED) return "CONN_CONNECTED";
|
||||
if (cs === ConnectionState?.CONN_DISCONNECTED) return "CONN_DISCONNECTED";
|
||||
if (cs === ConnectionState?.CONN_RECONNECTING) return "CONN_RECONNECTING";
|
||||
// Fallback for numeric values if enum import fails
|
||||
if (cs === 1) return "CONN_CONNECTED(1)";
|
||||
if (cs === 0) return "CONN_DISCONNECTED(0)";
|
||||
if (cs === 2) return "CONN_RECONNECTING(2)";
|
||||
return String(cs);
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// FluxerVoiceConnection — compatible with revoice.js VoiceConnection
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* A voice connection that wraps a LiveKit Room obtained via the Fluxer
|
||||
@@ -132,12 +99,11 @@ export class FluxerVoiceConnection extends EventEmitter {
|
||||
/** @type {Room|null} */
|
||||
room = null;
|
||||
channelId = null;
|
||||
_voice = null; // parent FluxerRevoice instance
|
||||
_connected = false; // internal flag, set by events
|
||||
_users = []; // internal, derived from parent FluxerRevoice.users
|
||||
_voice = null;
|
||||
_connected = false;
|
||||
_users = [];
|
||||
_destroyed = false;
|
||||
|
||||
// @fluxerjs/voice native connection reference (for proper disconnect)
|
||||
_nativeConn = null;
|
||||
|
||||
/**
|
||||
@@ -159,7 +125,6 @@ export class FluxerVoiceConnection extends EventEmitter {
|
||||
this._voice = voice;
|
||||
this.room = opts.room ?? null;
|
||||
this._nativeConn = opts.nativeConnection ?? null;
|
||||
// Use room.isConnected (boolean getter) — the correct Node.js SDK API
|
||||
this._connected = !!(this.room && this.room.isConnected);
|
||||
}
|
||||
|
||||
@@ -170,7 +135,6 @@ export class FluxerVoiceConnection extends EventEmitter {
|
||||
*/
|
||||
get connected() {
|
||||
if (this._destroyed) return false;
|
||||
// Prefer the LiveKit Room's own isConnected getter (source of truth)
|
||||
if (this.room) return this.room.isConnected;
|
||||
return this._connected;
|
||||
}
|
||||
@@ -186,29 +150,20 @@ export class FluxerVoiceConnection extends EventEmitter {
|
||||
*/
|
||||
async disconnect() {
|
||||
if (this._destroyed) return;
|
||||
// Mark this as an intentional disconnect so the RoomEvent.Disconnected
|
||||
// handler can log it correctly
|
||||
if (this._voice && this.channelId) {
|
||||
this._voice.markIntentionalDisconnect(this.channelId);
|
||||
// Prefer a channel-scoped gateway leave before tearing down the room.
|
||||
// The native disconnect path can be guild-scoped in some environments,
|
||||
// which drops every voice connection in the guild.
|
||||
const guildId = this._voice._resolveGuildForChannel?.(this.channelId) ?? null;
|
||||
this._voice._leaveGateway?.(this.channelId, guildId);
|
||||
}
|
||||
this._destroyed = true;
|
||||
this._connected = false;
|
||||
|
||||
// Close the LiveKit room directly after sending the leave signal.
|
||||
// This keeps the disconnect scoped to the target channel.
|
||||
if (this.room) {
|
||||
try {
|
||||
await this.room.disconnect();
|
||||
} catch (e) {
|
||||
// Room may already be closed
|
||||
}
|
||||
} else if (this._nativeConn && typeof this._nativeConn.disconnect === "function") {
|
||||
// Fallback only when no room object is available.
|
||||
try {
|
||||
await this._nativeConn.disconnect();
|
||||
} catch (e) {
|
||||
@@ -228,33 +183,27 @@ export class FluxerVoiceConnection extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// FluxerRevoice — drop-in replacement for revoice.js Revoice
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Revoice-compatible class that uses the Fluxer gateway for voice joins.
|
||||
*
|
||||
* Usage (drop-in for `new Revoice(token)`):
|
||||
*
|
||||
* // Before (third-party API — 401 on Fluxer):
|
||||
*
|
||||
* this.revoice = new Revoice(config.token);
|
||||
*
|
||||
* // After (Fluxer API — works on Fluxer):
|
||||
*
|
||||
* this.revoice = new FluxerRevoice(client);
|
||||
*/
|
||||
export class FluxerRevoice extends EventEmitter {
|
||||
/** @type {import("@fluxerjs/core").Client} */
|
||||
client = null;
|
||||
connections = new Map();
|
||||
// Unified users map: keyed by "channelId:userId", value is { id, connectedTo }
|
||||
// This is the single source of truth; connection.users is derived from it.
|
||||
users = new Map();
|
||||
|
||||
/** @type {Map<string, Promise>} */
|
||||
_guildJoinQueue = new Map();
|
||||
|
||||
// ── Global join queue ──────────────────────────────────────────────────────
|
||||
/** @type {Promise} Global join serializer — only one join at a time across all guilds */
|
||||
_globalJoinQueue = Promise.resolve();
|
||||
/** @type {number} Minimum delay between ANY two joins (ms), even across guilds.
|
||||
@@ -304,7 +253,6 @@ export class FluxerRevoice extends EventEmitter {
|
||||
*/
|
||||
markIntentionalDisconnect(channelId) {
|
||||
this._intentionalDisconnects.add(String(channelId));
|
||||
// Auto-clear after 10 seconds as safety net
|
||||
setTimeout(() => this._intentionalDisconnects.delete(String(channelId)), 10_000);
|
||||
}
|
||||
|
||||
@@ -331,11 +279,6 @@ export class FluxerRevoice extends EventEmitter {
|
||||
|
||||
const guildForLeave = guildId ?? this._resolveGuildForChannel(channelId);
|
||||
|
||||
// ── Method 1 (PREFERRED): Use vm.leaveChannel(channelId) ──────────
|
||||
// This sends a channel-specific VOICE_STATE_UPDATE that only leaves
|
||||
// the specified channel, preserving all other voice connections in
|
||||
// the same guild. This is critical for multi-voice / 24/7 setups
|
||||
// where the bot may be in several channels simultaneously.
|
||||
if (typeof vm.leaveChannel === "function") {
|
||||
try {
|
||||
vm.leaveChannel(channelId);
|
||||
@@ -346,10 +289,6 @@ export class FluxerRevoice extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Method 2: Use vm.leave(guildId) — guild-level fallback ─────────
|
||||
// WARNING: This disconnects ALL voice channels in the guild, not just
|
||||
// the target channel. Only used when leaveChannel() is unavailable.
|
||||
// The caller must handle rejoining other 24/7 channels if needed.
|
||||
if (guildForLeave && typeof vm.leave === "function") {
|
||||
try {
|
||||
vm.leave(guildForLeave);
|
||||
@@ -360,12 +299,8 @@ export class FluxerRevoice extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Method 3: Use vm.updateVoiceState() as last resort ─────────────
|
||||
if (typeof vm.updateVoiceState === "function") {
|
||||
if (guildForLeave) {
|
||||
// NEVER send an unscoped updateVoiceState(null, opts) because it
|
||||
// tells the gateway to leave ALL guilds' voice channels, causing
|
||||
// cascading disconnections across all active voice connections.
|
||||
try {
|
||||
vm.updateVoiceState(guildForLeave, null, { self_deaf: false, self_mute: false });
|
||||
logger.player(`[FluxerRevoice] Sent gateway leave via updateVoiceState() for guild ${guildForLeave}`);
|
||||
@@ -407,19 +342,15 @@ export class FluxerRevoice extends EventEmitter {
|
||||
* @param {FluxerVoiceConnection} existing
|
||||
*/
|
||||
async _destroyStaleConnection(channelId, existing) {
|
||||
// 1. Remove from map immediately so no other code can get this dead ref
|
||||
this.connections.delete(channelId);
|
||||
// Mark as intentional so the LiveKit disconnect handler logs correctly
|
||||
this.markIntentionalDisconnect(channelId);
|
||||
const staleGuildId = this._resolveGuildForChannel(channelId);
|
||||
this._leaveGateway(channelId, staleGuildId);
|
||||
|
||||
// 2. Close the LiveKit Room directly
|
||||
if (existing.room) {
|
||||
try {
|
||||
await existing.room.disconnect();
|
||||
} catch (_) {
|
||||
// Room may already be closed
|
||||
}
|
||||
} else if (existing._nativeConn && typeof existing._nativeConn.disconnect === "function") {
|
||||
try {
|
||||
@@ -429,7 +360,6 @@ export class FluxerRevoice extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Mark as destroyed and clean up listeners
|
||||
existing._destroyed = true;
|
||||
existing._connected = false;
|
||||
try { existing.removeAllListeners(); } catch (_) {}
|
||||
@@ -448,17 +378,13 @@ export class FluxerRevoice extends EventEmitter {
|
||||
*/
|
||||
async join(channelId, _leaveIfEmpty = false) {
|
||||
const joinOperation = async () => {
|
||||
// Small gap between joins to let the gateway process the previous
|
||||
// session's cleanup. This runs BEFORE the actual join logic.
|
||||
await new Promise(r => setTimeout(r, this._globalJoinDelay));
|
||||
return await this._joinInternal(channelId, _leaveIfEmpty);
|
||||
};
|
||||
|
||||
// Chain onto the global queue: our join only starts after the previous
|
||||
// one has fully completed (or failed). We store the new tail of the chain.
|
||||
const prevQueue = this._globalJoinQueue;
|
||||
const ourResult = prevQueue.then(() => joinOperation());
|
||||
this._globalJoinQueue = ourResult.catch(() => {}); // don't break chain on error
|
||||
this._globalJoinQueue = ourResult.catch(() => {});
|
||||
return await ourResult;
|
||||
}
|
||||
|
||||
@@ -471,7 +397,6 @@ export class FluxerRevoice extends EventEmitter {
|
||||
* @returns {Promise<FluxerVoiceConnection>}
|
||||
*/
|
||||
async _joinInternal(channelId, _leaveIfEmpty = false) {
|
||||
// Resolve the guild ID for this channel
|
||||
let guildId = null;
|
||||
try {
|
||||
const ch = this.client.channels?.get?.(channelId);
|
||||
@@ -480,10 +405,6 @@ export class FluxerRevoice extends EventEmitter {
|
||||
|
||||
if (this.connections.has(channelId)) {
|
||||
const existing = this.connections.get(channelId);
|
||||
// If the existing connection is still alive, reuse it.
|
||||
// If the LiveKit room disconnected, the connection is stale — clean it
|
||||
// up fully and rejoin instead of returning a dead connection that will
|
||||
// fail with "LiveKit disconnected (connectionState: 0)".
|
||||
if (existing && !existing._destroyed && existing.room && existing.room.isConnected) {
|
||||
logger.player(`[FluxerRevoice] Already connected to ${channelId}, returning existing connection`);
|
||||
return existing;
|
||||
@@ -498,7 +419,6 @@ export class FluxerRevoice extends EventEmitter {
|
||||
|
||||
logger.player(`[FluxerRevoice] Joining channel ${channelId} via Fluxer gateway...`);
|
||||
|
||||
// Fetch the channel object from the client cache (or REST)
|
||||
let channel = this.client.channels?.get?.(channelId);
|
||||
if (!channel) {
|
||||
try {
|
||||
@@ -511,17 +431,8 @@ export class FluxerRevoice extends EventEmitter {
|
||||
throw new Error(`Channel not found: ${channelId}`);
|
||||
}
|
||||
|
||||
// Resolve the guild ID for this channel (used for guild-scoped leave signals)
|
||||
const channelGuildId = guildId ?? channel?.guildId ?? channel?.guild?.id ?? null;
|
||||
|
||||
// Use @fluxerjs/voice to join the channel via the Fluxer gateway.
|
||||
// This handles the VOICE_STATE_UPDATE → VOICE_SERVER_UPDATE flow
|
||||
// and creates a LiveKit connection with the returned credentials.
|
||||
//
|
||||
// Permission validation is handled upstream in PlayerManager via
|
||||
// botHasVoicePermissions() — real permission errors are caught before
|
||||
// we even reach this point. If we get a 401 here, it's a stale session,
|
||||
// and PlayerManager's sanitizeJoinError will handle the retry.
|
||||
let nativeConnection;
|
||||
try {
|
||||
nativeConnection = await joinVoiceChannel(this.client, channel);
|
||||
@@ -535,17 +446,13 @@ export class FluxerRevoice extends EventEmitter {
|
||||
|
||||
logger.player(`[FluxerRevoice] Gateway join successful for ${channelId}`);
|
||||
|
||||
// The @fluxerjs/voice connection wraps a LiveKit Room.
|
||||
// Extract it so we can use it with revoice.js's MediaPlayer.
|
||||
let room = null;
|
||||
|
||||
// Try to get the LiveKit Room from the native connection
|
||||
if (nativeConnection.room) {
|
||||
room = nativeConnection.room;
|
||||
logger.player(`[FluxerRevoice] Got LiveKit room from native connection (isConnected: ${room.isConnected}, connectionState: ${stateLabel(room.connectionState)})`);
|
||||
}
|
||||
|
||||
// (non-LiveKit) which we don't support for music playback.
|
||||
if (!room) {
|
||||
try { await nativeConnection.disconnect(); } catch (_) {}
|
||||
throw new Error(
|
||||
@@ -554,16 +461,10 @@ export class FluxerRevoice extends EventEmitter {
|
||||
);
|
||||
}
|
||||
|
||||
// ── Wait for the room to be connected ────────────────────────────────
|
||||
// Use room.isConnected (boolean) and room.connectionState (enum) which
|
||||
// are the correct APIs in @livekit/rtc-node Node.js SDK.
|
||||
// Also listen for the ConnectionStateChanged event for immediate feedback.
|
||||
const maxWait = 10_000;
|
||||
const startTime = Date.now();
|
||||
|
||||
// If already connected, skip the wait loop
|
||||
if (!room.isConnected) {
|
||||
// Listen for the ConnectionStateChanged event to resolve faster
|
||||
let eventResolved = false;
|
||||
const statePromise = new Promise((resolve) => {
|
||||
const handler = (cs) => {
|
||||
@@ -575,30 +476,25 @@ export class FluxerRevoice extends EventEmitter {
|
||||
} else if (cs === ConnectionState?.CONN_DISCONNECTED || cs === 0) {
|
||||
eventResolved = true;
|
||||
room.off(RoomEvent.ConnectionStateChanged, handler);
|
||||
resolve(); // resolve so we can check isConnected below
|
||||
resolve();
|
||||
}
|
||||
};
|
||||
room.on(RoomEvent.ConnectionStateChanged, handler);
|
||||
});
|
||||
|
||||
// Poll + event race
|
||||
while (!room.isConnected && (Date.now() - startTime) < maxWait) {
|
||||
// Wait for either the event to fire or a 200ms poll interval
|
||||
await Promise.race([
|
||||
statePromise,
|
||||
new Promise(r => setTimeout(r, 200)),
|
||||
]);
|
||||
|
||||
// Check if connected
|
||||
if (room.isConnected) break;
|
||||
|
||||
// Check if disconnected (dead state)
|
||||
const cs = room.connectionState;
|
||||
if (cs === ConnectionState?.CONN_DISCONNECTED || cs === 0) break;
|
||||
}
|
||||
}
|
||||
|
||||
// Final state check using the correct API
|
||||
const finalConnected = room.isConnected;
|
||||
const finalCS = room.connectionState;
|
||||
|
||||
@@ -609,15 +505,11 @@ export class FluxerRevoice extends EventEmitter {
|
||||
|
||||
logger.player(`[FluxerRevoice] LiveKit room ready (isConnected: ${finalConnected}, connectionState: ${stateLabel(finalCS)})`);
|
||||
|
||||
// Create our FluxerVoiceConnection wrapper
|
||||
const connection = new FluxerVoiceConnection(channelId, this, {
|
||||
room,
|
||||
nativeConnection,
|
||||
});
|
||||
|
||||
// ── LiveKit room event forwarding ──────────────────────────────────
|
||||
// Forward LiveKit events to FluxerVoiceConnection events so
|
||||
// Player.mjs's connection.on("disconnect") etc. still work.
|
||||
|
||||
room.on(RoomEvent.Disconnected, (reason) => {
|
||||
const isIntentional = this._intentionalDisconnects.has(String(channelId));
|
||||
@@ -627,17 +519,11 @@ export class FluxerRevoice extends EventEmitter {
|
||||
connection._connected = false;
|
||||
connection._destroyed = true;
|
||||
|
||||
// Remove from connections map so the next join() creates a fresh
|
||||
// connection instead of returning this dead one.
|
||||
this.connections.delete(channelId);
|
||||
|
||||
if (!isIntentional) {
|
||||
// Unexpected disconnects still need a gateway leave signal so the
|
||||
// next join gets a fresh voice session.
|
||||
this._leaveGateway(channelId, channelGuildId);
|
||||
|
||||
// Best-effort cleanup for the native wrapper. Skip this on intentional
|
||||
// leaves because it can collapse multi-voice into a guild-wide leave.
|
||||
if (nativeConnection && typeof nativeConnection.disconnect === "function") {
|
||||
try { nativeConnection.disconnect(); } catch (_) {}
|
||||
}
|
||||
@@ -646,16 +532,12 @@ export class FluxerRevoice extends EventEmitter {
|
||||
connection.emit("disconnect");
|
||||
});
|
||||
|
||||
// No automatic reconnection handling — if the LiveKit room disconnects
|
||||
// unexpectedly, the connection is considered dead. The caller (Player.mjs)
|
||||
// will emit "autoleave" and the user must manually rejoin if desired.
|
||||
|
||||
room.on(RoomEvent.ParticipantConnected, (participant) => {
|
||||
const userId = participant?.identity ?? participant?.sid;
|
||||
if (userId) {
|
||||
const uKey = `${channelId}:${userId}`;
|
||||
this.users.set(uKey, { id: userId, connectedTo: channelId });
|
||||
// Derive connection.users from the unified map (single source of truth)
|
||||
connection._users = [...this.users.values()].filter(u => u.connectedTo === channelId);
|
||||
connection.emit("userjoin", userId);
|
||||
}
|
||||
@@ -666,19 +548,15 @@ export class FluxerRevoice extends EventEmitter {
|
||||
if (userId) {
|
||||
const uKey = `${channelId}:${userId}`;
|
||||
this.users.delete(uKey);
|
||||
// Derive connection.users from the unified map
|
||||
connection._users = [...this.users.values()].filter(u => u.connectedTo === channelId);
|
||||
connection.emit("userleave", userId);
|
||||
}
|
||||
});
|
||||
|
||||
// Track the connection
|
||||
this.connections.set(channelId, connection);
|
||||
|
||||
// Auto-leave when room empties (if requested)
|
||||
if (_leaveIfEmpty) {
|
||||
connection.on("userleave", () => {
|
||||
// Only trigger autoleave if no remote participants remain
|
||||
const remoteCount = room.remoteParticipants?.size ?? 0;
|
||||
if (remoteCount === 0) {
|
||||
logger.player(`[FluxerRevoice] Room empty, triggering autoleave for ${channelId}`);
|
||||
|
||||
@@ -27,7 +27,6 @@ export function get247ChannelMode(set, channelId) {
|
||||
const perChannel = modes[channelId];
|
||||
if (perChannel === "on" || perChannel === "auto" || perChannel === "off") return perChannel;
|
||||
}
|
||||
// Fallback: guild-wide mode (legacy)
|
||||
const guildMode = set.get("stay_247_mode") ?? "off";
|
||||
return guildMode;
|
||||
}
|
||||
@@ -44,7 +43,6 @@ export function set247ChannelMode(set, channelId, mode) {
|
||||
if (!modes || typeof modes !== "object" || Array.isArray(modes)) modes = {};
|
||||
modes[channelId] = mode;
|
||||
set.set("stay_247_modes", modes);
|
||||
// Also update guild-wide mode for backward compat
|
||||
set.set("stay_247_mode", mode);
|
||||
}
|
||||
|
||||
|
||||
@@ -48,7 +48,6 @@ export class Locale {
|
||||
return;
|
||||
}
|
||||
|
||||
// Auto-discover all .json files in the locales directory
|
||||
let files;
|
||||
try {
|
||||
files = readdirSync(LOCALES_DIR).filter(f => f.endsWith(".json"));
|
||||
@@ -93,11 +92,9 @@ export class Locale {
|
||||
_getLocaleData(guildId) {
|
||||
if (!guildId) return this.locales.get(this.defaultLocale) ?? {};
|
||||
|
||||
// Check cache first
|
||||
const cached = this._resolved.get(guildId);
|
||||
if (cached) return cached;
|
||||
|
||||
// Resolve locale from guild settings
|
||||
let code = this.defaultLocale;
|
||||
try {
|
||||
const serverSettings = this.settingsMgr?.guilds?.get?.(guildId);
|
||||
@@ -151,22 +148,17 @@ export class Locale {
|
||||
* @returns {string} Translated string, or the key itself if not found
|
||||
*/
|
||||
translate(guildId, key, replacements = {}) {
|
||||
// Resolve locale data for this guild (uses cache internally)
|
||||
const localeData = this._getLocaleData(guildId);
|
||||
|
||||
// Try guild's locale first
|
||||
let value = this._resolve(localeData, key);
|
||||
|
||||
// Fallback to English if not found in guild locale
|
||||
if (value === undefined) {
|
||||
value = this._resolve(this.locales.get(this.defaultLocale) ?? {}, key);
|
||||
}
|
||||
|
||||
// If still not found, return the key so devs can see what's missing
|
||||
if (value === undefined) return key;
|
||||
if (typeof value !== "string") return key;
|
||||
|
||||
// Replace {{placeholder}} patterns
|
||||
for (const [placeholder, val] of Object.entries(replacements)) {
|
||||
value = value.replace(
|
||||
new RegExp(`\\{\\{${placeholder}\\}\\}`, "g"),
|
||||
|
||||
@@ -30,9 +30,8 @@ export function initLogger(config) {
|
||||
}
|
||||
|
||||
function isEnabled(category) {
|
||||
if (!_config) return true; // default on if not yet initialised
|
||||
if (!_config) return true;
|
||||
if (_config.enabled === false) return false;
|
||||
// If the category key is missing, default to true
|
||||
return _config[category] !== false;
|
||||
}
|
||||
|
||||
@@ -41,17 +40,14 @@ function ts() {
|
||||
}
|
||||
|
||||
export const logger = {
|
||||
// ── always-on (errors / warnings critical to operation) ──────────────────
|
||||
error(tag, ...args) {
|
||||
console.error(`[${ts()}] ${tag}`, ...args);
|
||||
},
|
||||
warn(tag, ...args) {
|
||||
// warnings are on unless master switch is off
|
||||
if (_config?.enabled === false) return;
|
||||
console.warn(`[${ts()}] ${tag}`, ...args);
|
||||
},
|
||||
|
||||
// ── categorised logs ─────────────────────────────────────────────────────
|
||||
player(...args) { if (isEnabled("player")) console.log(`[${ts()}]`, ...args); },
|
||||
inactivity(...args) { if (isEnabled("inactivity")) console.log(`[${ts()}]`, ...args); },
|
||||
voice247(...args) { if (isEnabled("voice247")) console.log(`[${ts()}]`, ...args); },
|
||||
|
||||
@@ -28,19 +28,16 @@ export class VoiceStateCache {
|
||||
* @param {number} [opts.maxBots=10000] Max bot entries before LRU eviction
|
||||
*/
|
||||
constructor(opts = {}) {
|
||||
// ── Human users ──────────────────────────────────────────────────────
|
||||
/** @type {Map<string, {channelId, guildId, userId}>} keyed "guildId:userId" */
|
||||
this.userLocations = new Map();
|
||||
/** @type {Map<string, Set<string>>} keyed "guildId:channelId", values are userIds */
|
||||
this.channelMembers = new Map();
|
||||
|
||||
// ── Bot users ────────────────────────────────────────────────────────
|
||||
/** @type {Map<string, {channelId, guildId, userId}>} keyed "guildId:userId" */
|
||||
this.botLocations = new Map();
|
||||
/** @type {Map<string, Set<string>>} keyed "guildId:channelId", values are userIds */
|
||||
this.botChannelMembers = new Map();
|
||||
|
||||
// ── LRU tracking ─────────────────────────────────────────────────────
|
||||
this._maxUsers = opts.maxUsers ?? 50_000;
|
||||
this._maxBots = opts.maxBots ?? 10_000;
|
||||
/** @type {string[]} MRU-first list of user location keys */
|
||||
@@ -49,7 +46,6 @@ export class VoiceStateCache {
|
||||
this._lruBotKeys = [];
|
||||
}
|
||||
|
||||
// ── Key helpers ──────────────────────────────────────────────────────────
|
||||
|
||||
/** Build composite key "guildId:userId" (both cleaned to digits only) */
|
||||
static userKey(guildId, userId) {
|
||||
@@ -61,7 +57,6 @@ export class VoiceStateCache {
|
||||
return `${String(guildId ?? "").replace(/\D/g, "")}:${String(channelId ?? "").replace(/\D/g, "")}`;
|
||||
}
|
||||
|
||||
// ── Core update (unified — called by both raw WS and high-level handler) ─
|
||||
|
||||
/**
|
||||
* Update voice state for a user.
|
||||
@@ -84,7 +79,6 @@ export class VoiceStateCache {
|
||||
const lruKeys = isBot ? this._lruBotKeys : this._lruUserKeys;
|
||||
const uKey = VoiceStateCache.userKey(cleanGuild, cleanUser);
|
||||
|
||||
// ── Remove from previous channel index ───────────────────────────────
|
||||
const prev = locations.get(uKey);
|
||||
if (prev) {
|
||||
const prevCKey = VoiceStateCache.channelKey(prev.guildId, prev.channelId);
|
||||
@@ -96,33 +90,21 @@ export class VoiceStateCache {
|
||||
}
|
||||
|
||||
if (cleanChannel) {
|
||||
// ── Add to new channel index ───────────────────────────────────────
|
||||
const cKey = VoiceStateCache.channelKey(cleanGuild, cleanChannel);
|
||||
let set = channelIdx.get(cKey);
|
||||
if (!set) { set = new Set(); channelIdx.set(cKey, set); }
|
||||
set.add(cleanUser);
|
||||
|
||||
// ── Update location map ────────────────────────────────────────────
|
||||
locations.set(uKey, { channelId: cleanChannel, guildId: cleanGuild, userId: cleanUser });
|
||||
|
||||
// ── LRU: move to most-recently-used position ──────────────────────
|
||||
// JavaScript Maps maintain insertion order, so delete + re-insert
|
||||
// is O(1) amortized instead of O(n) with indexOf + splice on an array.
|
||||
// We keep the _lruUserKeys / _lruBotKeys arrays as fast eviction queues
|
||||
// but use the Map's own key order for O(1) move-to-front.
|
||||
if (locations.has(uKey)) {
|
||||
// Re-insert to move to end (most recently used) — O(1)
|
||||
locations.delete(uKey);
|
||||
locations.set(uKey, { channelId: cleanChannel, guildId: cleanGuild, userId: cleanUser });
|
||||
}
|
||||
|
||||
// ── Evict if over cap ──────────────────────────────────────────────
|
||||
// Use the Map's insertion order to find the oldest entry (first key).
|
||||
// This is O(1) per eviction instead of popping from an array.
|
||||
while (locations.size > maxEntries) {
|
||||
const evictKey = locations.keys().next().value;
|
||||
if (evictKey === uKey) {
|
||||
// Don't evict the entry we just added — re-insert at end and move to next
|
||||
const evictVal = locations.get(evictKey);
|
||||
locations.delete(evictKey);
|
||||
locations.set(evictKey, evictVal);
|
||||
@@ -138,20 +120,16 @@ export class VoiceStateCache {
|
||||
}
|
||||
locations.delete(evictKey);
|
||||
}
|
||||
// Also remove from LRU key list if present
|
||||
const lruIdx = lruKeys.indexOf(evictKey);
|
||||
if (lruIdx !== -1) lruKeys.splice(lruIdx, 1);
|
||||
}
|
||||
} else {
|
||||
// ── User left voice — remove from location map ─────────────────────
|
||||
locations.delete(uKey);
|
||||
// Remove from LRU list
|
||||
const idx = lruKeys.indexOf(uKey);
|
||||
if (idx !== -1) lruKeys.splice(idx, 1);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Query methods ────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Check if there are any human users in a specific channel.
|
||||
@@ -242,11 +220,10 @@ export class VoiceStateCache {
|
||||
seedUser(guildId, userId, channelId, isBot = false) {
|
||||
const uKey = VoiceStateCache.userKey(guildId, userId);
|
||||
const locations = isBot ? this.botLocations : this.userLocations;
|
||||
if (locations.has(uKey)) return; // already tracked — don't overwrite
|
||||
if (locations.has(uKey)) return;
|
||||
this.updateUser({ guildId, userId, channelId, isBot });
|
||||
}
|
||||
|
||||
// ── Bulk operations ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Remove all entries for a specific guild (used on GuildDelete).
|
||||
@@ -257,7 +234,6 @@ export class VoiceStateCache {
|
||||
const cleanGuild = String(guildId).replace(/\D/g, "");
|
||||
const prefix = cleanGuild + ":";
|
||||
|
||||
// Humans
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
if (uKey.startsWith(prefix)) {
|
||||
const cKey = VoiceStateCache.channelKey(loc.guildId, loc.channelId);
|
||||
@@ -266,14 +242,11 @@ export class VoiceStateCache {
|
||||
this.userLocations.delete(uKey);
|
||||
}
|
||||
}
|
||||
// Clean up channel member sets for this guild
|
||||
for (const [cKey, set] of this.channelMembers) {
|
||||
if (cKey.startsWith(prefix)) this.channelMembers.delete(cKey);
|
||||
}
|
||||
// Clean LRU
|
||||
this._lruUserKeys = this._lruUserKeys.filter(k => !k.startsWith(prefix));
|
||||
|
||||
// Bots
|
||||
for (const [uKey, loc] of this.botLocations) {
|
||||
if (uKey.startsWith(prefix)) {
|
||||
const cKey = VoiceStateCache.channelKey(loc.guildId, loc.channelId);
|
||||
@@ -297,13 +270,11 @@ export class VoiceStateCache {
|
||||
removeChannel(guildId, channelId) {
|
||||
const cKey = VoiceStateCache.channelKey(guildId, channelId);
|
||||
|
||||
// Humans
|
||||
const humanSet = this.channelMembers.get(cKey);
|
||||
if (humanSet) {
|
||||
for (const userId of humanSet) {
|
||||
const uKey = VoiceStateCache.userKey(guildId, userId);
|
||||
const loc = this.userLocations.get(uKey);
|
||||
// Only delete if the user is still in THIS channel (not moved)
|
||||
if (loc && loc.channelId === String(channelId).replace(/\D/g, "")) {
|
||||
this.userLocations.delete(uKey);
|
||||
}
|
||||
@@ -311,7 +282,6 @@ export class VoiceStateCache {
|
||||
this.channelMembers.delete(cKey);
|
||||
}
|
||||
|
||||
// Bots
|
||||
const botSet = this.botChannelMembers.get(cKey);
|
||||
if (botSet) {
|
||||
for (const userId of botSet) {
|
||||
@@ -337,7 +307,6 @@ export class VoiceStateCache {
|
||||
const cleanGuild = String(guildId).replace(/\D/g, "");
|
||||
|
||||
if (!botsOnly) {
|
||||
// Purge human entries
|
||||
for (const userId of userIds) {
|
||||
const uKey = VoiceStateCache.userKey(cleanGuild, userId);
|
||||
const loc = this.userLocations.get(uKey);
|
||||
@@ -350,7 +319,6 @@ export class VoiceStateCache {
|
||||
}
|
||||
}
|
||||
|
||||
// Purge bot entries
|
||||
for (const userId of userIds) {
|
||||
const uKey = VoiceStateCache.userKey(cleanGuild, userId);
|
||||
const loc = this.botLocations.get(uKey);
|
||||
@@ -363,9 +331,6 @@ export class VoiceStateCache {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Backward-compatible accessors ────────────────────────────────────────
|
||||
// These provide the same interface as the old raw Maps so that existing
|
||||
// code (dashboard, commands) doesn't need to be rewritten immediately.
|
||||
|
||||
/**
|
||||
* Get the "observedVoiceUsers" size (human count).
|
||||
@@ -386,7 +351,6 @@ export class VoiceStateCache {
|
||||
*/
|
||||
*iterateHumanUsers() {
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
// Yield the userId (not composite key) as first element for compat
|
||||
yield [loc.userId, { channelId: loc.channelId, guildId: loc.guildId }];
|
||||
}
|
||||
}
|
||||
@@ -415,7 +379,6 @@ export class VoiceStateCache {
|
||||
if (guildId) {
|
||||
return this.userLocations.get(VoiceStateCache.userKey(guildId, userId));
|
||||
}
|
||||
// Legacy fallback: scan for first match
|
||||
const cleanUser = String(userId).replace(/\D/g, "");
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
if (loc.userId === cleanUser) return { channelId: loc.channelId, guildId: loc.guildId };
|
||||
@@ -446,7 +409,6 @@ export class VoiceStateCache {
|
||||
setBotUser(compositeKey, info) {
|
||||
const guildId = info.guildId;
|
||||
const channelId = info.channelId;
|
||||
// Extract userId from composite key (format: "guildId:userId")
|
||||
const userId = compositeKey.split(":").pop();
|
||||
if (guildId && channelId && userId) {
|
||||
this.updateUser({ guildId, userId, channelId, isBot: true });
|
||||
@@ -464,7 +426,6 @@ export class VoiceStateCache {
|
||||
if (guildId) {
|
||||
this.updateUser({ guildId, userId, channelId: null, isBot: false });
|
||||
} else {
|
||||
// Legacy: remove from ALL guilds
|
||||
const cleanUser = String(userId).replace(/\D/g, "");
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
if (loc.userId === cleanUser) {
|
||||
@@ -501,7 +462,6 @@ export class VoiceStateCache {
|
||||
if (guildId) {
|
||||
return this.userLocations.has(VoiceStateCache.userKey(guildId, userId));
|
||||
}
|
||||
// Legacy: scan
|
||||
const cleanUser = String(userId).replace(/\D/g, "");
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
if (loc.userId === cleanUser) return true;
|
||||
@@ -520,10 +480,6 @@ export class VoiceStateCache {
|
||||
return this.botLocations.has(compositeKey);
|
||||
}
|
||||
|
||||
// ── Map-compatible iteration ─────────────────────────────────────────────
|
||||
// Allows `for (const [uid, info] of voiceCache)` to work the same as
|
||||
// `for (const [uid, info] of observedVoiceUsers)` on a raw Map.
|
||||
// Delegates to iterateHumanUsers() so the yielded shape matches.
|
||||
|
||||
/**
|
||||
* Default iterator — iterates human users.
|
||||
@@ -553,7 +509,6 @@ export class VoiceStateCache {
|
||||
if (guildId !== undefined) {
|
||||
return this.userLocations.has(VoiceStateCache.userKey(guildId, userId));
|
||||
}
|
||||
// Legacy: scan for first match by userId only
|
||||
const cleanUser = String(userId).replace(/\D/g, "");
|
||||
for (const [, loc] of this.userLocations) {
|
||||
if (loc.userId === cleanUser) return true;
|
||||
@@ -575,7 +530,6 @@ export class VoiceStateCache {
|
||||
const loc = this.userLocations.get(VoiceStateCache.userKey(guildId, userId));
|
||||
return loc ? { channelId: loc.channelId, guildId: loc.guildId } : undefined;
|
||||
}
|
||||
// Legacy: scan for first match by userId only
|
||||
const cleanUser = String(userId).replace(/\D/g, "");
|
||||
for (const [, loc] of this.userLocations) {
|
||||
if (loc.userId === cleanUser) return { channelId: loc.channelId, guildId: loc.guildId };
|
||||
@@ -607,7 +561,6 @@ export class VoiceStateCache {
|
||||
if (guildId !== undefined) {
|
||||
this.updateUser({ guildId, userId, channelId: null, isBot: false });
|
||||
} else {
|
||||
// Legacy: remove from ALL guilds
|
||||
const cleanUser = String(userId).replace(/\D/g, "");
|
||||
const toRemove = [];
|
||||
for (const [uKey, loc] of this.userLocations) {
|
||||
@@ -655,7 +608,6 @@ export class VoiceStateCache {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Debug / stats ────────────────────────────────────────────────────────
|
||||
|
||||
get stats() {
|
||||
return {
|
||||
|
||||
@@ -9,7 +9,6 @@
|
||||
*/
|
||||
|
||||
export const PROVIDERS = {
|
||||
// ── Standard search ──────────────────────────────────────────────────────
|
||||
yt: { prefix: "ytsearch", label: "YouTube" },
|
||||
ytm: { prefix: "ytmsearch", label: "YouTube Music" },
|
||||
scld: { prefix: "scsearch", label: "SoundCloud" },
|
||||
@@ -56,14 +55,12 @@ export const PROVIDERS = {
|
||||
anghami: { prefix: "agsearch", label: "Anghami" },
|
||||
bk: { prefix: "bksearch", label: "Bluesky" },
|
||||
bluesky: { prefix: "bksearch", label: "Bluesky" },
|
||||
// ── Recommendations ──────────────────────────────────────────────────────
|
||||
ytrec: { prefix: "ytrec", label: "YouTube (recommended)" },
|
||||
sprec: { prefix: "sprec", label: "Spotify (recommended)" },
|
||||
dzrec: { prefix: "dzrec", label: "Deezer (recommended)" },
|
||||
tdrec: { prefix: "tdrec", label: "Tidal (recommended)" },
|
||||
jsrec: { prefix: "jsrec", label: "JioSaavn (recommended)" },
|
||||
vkrec: { prefix: "vkrec", label: "VK Music (recommended)" },
|
||||
// ── TTS ──────────────────────────────────────────────────────────────────
|
||||
gtts: { prefix: "gtts", label: "Google TTS" },
|
||||
tts: { prefix: "gtts", label: "Google TTS" },
|
||||
ftts: { prefix: "ftts", label: "Flowery TTS" },
|
||||
|
||||
+7
-106
@@ -8,7 +8,7 @@ import { logger } from "../constants/Logger.mjs";
|
||||
|
||||
export class Dashboard {
|
||||
enabled = false;
|
||||
expiryTime = 1000 * 60 * 60 * 6; // 6 hours — login code expiry
|
||||
expiryTime = 1000 * 60 * 60 * 6;
|
||||
|
||||
/**
|
||||
* @param {Remix} remix
|
||||
@@ -23,8 +23,6 @@ export class Dashboard {
|
||||
|
||||
if (!this.enabled) return this;
|
||||
|
||||
// DatabaseManager for login code verification (optional — only needed if
|
||||
// the backend uses the bot-based login flow instead of Fluxer OAuth2)
|
||||
if (opts.mysql) {
|
||||
this.db = new DatabaseManager(opts.mysql);
|
||||
}
|
||||
@@ -55,10 +53,9 @@ export class Dashboard {
|
||||
const guild = await this.remix.client.guilds.fetch(data.key);
|
||||
if (!guild) return { error: "Server not found" };
|
||||
const member = await guild.members.fetch(data.accessor).catch(() => null);
|
||||
const channels = await guild.fetchChannels(); // execute before converting the guild, see caching
|
||||
const channels = await guild.fetchChannels();
|
||||
const server = Dashboard.convertServer(guild);
|
||||
if (!member) {
|
||||
// Non-member should not see any channels — return error instead of leaking all
|
||||
return { error: "You are not a member of this server" };
|
||||
}
|
||||
server.channels = server.channels.filter(c => {
|
||||
@@ -79,8 +76,6 @@ export class Dashboard {
|
||||
}
|
||||
|
||||
case "allServers": {
|
||||
// Auth check: owners see all servers, non-owners see only shared servers
|
||||
//if (data.accessor && this.remix.handler?.owners?.includes?.(data.accessor)) {
|
||||
try {
|
||||
const guilds = await this.remix.client.user.fetchGuilds();
|
||||
return guilds.map(g => Dashboard.convertServer(g));
|
||||
@@ -89,14 +84,12 @@ export class Dashboard {
|
||||
logger.dashboard("[Dashboard] allServers error:", id, e);
|
||||
return [];
|
||||
}
|
||||
//}
|
||||
if (data.accessor) {
|
||||
try {
|
||||
const accessorUser = await this.remix.client.users.fetch(data.accessor).catch(() => null);
|
||||
if (accessorUser) return await this.remix.getSharedServers(accessorUser);
|
||||
} catch (_) {}
|
||||
}
|
||||
// Always return an array — backend does .findIndex() on result
|
||||
return [];
|
||||
}
|
||||
|
||||
@@ -120,23 +113,16 @@ export class Dashboard {
|
||||
});
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// ── Bot ID isolation ──────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Set the bot ID for multi-bot Redis namespace isolation.
|
||||
* Updates the Redis platform string so each bot uses its own channel namespace.
|
||||
* @param {string} botId - The bot's Discord user ID
|
||||
*/
|
||||
setBotId(botId) {
|
||||
if (!this.enabled || !this.redis) return;
|
||||
// Use "fluxer_<botId>" as the platform so each bot's Redis messages
|
||||
// are isolated. The dashboard backend must also be configured to match.
|
||||
this.redis.platform = `fluxer`;
|
||||
}
|
||||
|
||||
// Dashboard Function Dispatch
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* @param {Object} params
|
||||
@@ -159,9 +145,6 @@ export class Dashboard {
|
||||
if (!user) return { error: "Invalid user" };
|
||||
let voiceChannel, textChannel;
|
||||
try {
|
||||
// Fluxer.js uses channels.get() for cached lookup and channels.fetch()
|
||||
// for REST fetch. Try fetch first (more reliable for uncached channels),
|
||||
// fall back to get (cache-only).
|
||||
const chMgr = this.remix.client.channels;
|
||||
if (typeof chMgr.fetch === "function") {
|
||||
voiceChannel = await chMgr.fetch(params.data.channel);
|
||||
@@ -172,19 +155,15 @@ export class Dashboard {
|
||||
}
|
||||
if (!voiceChannel) return { error: "Voice channel not found" };
|
||||
|
||||
// Validate textChannel: if it's a voice channel (type === 2) or missing,
|
||||
// find a suitable text channel from the guild instead
|
||||
const isText = (ch) => ch && (ch.type === 0 || ch.type === 5 || ch.type === 13 ||
|
||||
(typeof ch.isText === "function" && ch.isText()));
|
||||
|
||||
if (!isText(textChannel)) {
|
||||
// Auto-pick a text channel from the guild
|
||||
const guild = this.remix.client.guilds.get(voiceChannel.guildId);
|
||||
if (guild?.channels) {
|
||||
const channelValues = typeof guild.channels.values === "function"
|
||||
? [...guild.channels.values()]
|
||||
: Array.isArray(guild.channels) ? guild.channels : Object.values(guild.channels);
|
||||
// Prefer system channel, then first text channel
|
||||
const sysCh = guild.systemChannelId
|
||||
? channelValues.find(c => (c.id ?? c._id) === guild.systemChannelId && isText(c))
|
||||
: null;
|
||||
@@ -192,29 +171,22 @@ export class Dashboard {
|
||||
}
|
||||
if (!textChannel) {
|
||||
logger.dashboard("[Dashboard] No text channel found for guild", voiceChannel.guildId, "— voice channel will be used as fallback");
|
||||
textChannel = voiceChannel; // last resort — _sendToTextChannel will handle it
|
||||
textChannel = voiceChannel;
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
logger.dashboard("[Dashboard] Error:", e);
|
||||
return { error: "Invalid Channel" };
|
||||
}
|
||||
// Verify the user has permission to join the voice channel
|
||||
const authErr = await this._authorizeUserInGuild(user, voiceChannel.guildId);
|
||||
if (authErr) return { error: authErr };
|
||||
if (this.remix.players.playerMap.has(voiceChannel.id)) {
|
||||
// Bot is already in this channel — just add the user to the player's
|
||||
// user list so the backend PlayerManager and SocketHandler can track
|
||||
// them for real-time updates and multi-user dashboard support.
|
||||
const existingPlayer = this.remix.players.playerMap.get(voiceChannel.id);
|
||||
if (existingPlayer && user && !existingPlayer._dashboardUsers) {
|
||||
existingPlayer._dashboardUsers = [];
|
||||
}
|
||||
if (existingPlayer && user && !existingPlayer._dashboardUsers.includes(String(user.id))) {
|
||||
existingPlayer._dashboardUsers.push(String(user.id));
|
||||
// Publish a "join" event on the player's per-channel Redis topic
|
||||
// so the backend PlayerManager adds this user to the player's users
|
||||
// list and the SocketHandler subscribes them.
|
||||
try {
|
||||
const pubChannel = this.remix.redis?.publisher ?? this.remix.redis;
|
||||
if (pubChannel && typeof pubChannel.publish === "function") {
|
||||
@@ -227,17 +199,12 @@ export class Dashboard {
|
||||
}
|
||||
return { message: "Already Connected" };
|
||||
}
|
||||
// Build a minimal fake message that satisfies PlayerManager.initPlayer().
|
||||
// player.textChannel is set to message.channel, so it MUST be the real
|
||||
// textChannel object (which has .send()) — not a wrapper. Without this,
|
||||
// ch?.send throws "not a function" when announceSong fires.
|
||||
const fakeMsg = {
|
||||
channel: textChannel,
|
||||
message: { guildId: voiceChannel.guildId },
|
||||
reply: async () => ({ edit: async () => {}, catch: () => {} }),
|
||||
};
|
||||
this.remix.players.initPlayer(fakeMsg, voiceChannel.id);
|
||||
// Track this dashboard user on the player for multi-user support
|
||||
const newPlayer = this.remix.players.playerMap.get(voiceChannel.id);
|
||||
if (newPlayer && user) {
|
||||
if (!newPlayer._dashboardUsers) newPlayer._dashboardUsers = [];
|
||||
@@ -303,7 +270,6 @@ export class Dashboard {
|
||||
player.playRadio(radio);
|
||||
return { message: "Adding radio station" };
|
||||
}
|
||||
// Sanitize: reject obviously malicious patterns
|
||||
if (/^(javascript|data|vbscript):/i.test(query.trim())) {
|
||||
return { error: "Invalid query protocol" };
|
||||
}
|
||||
@@ -316,11 +282,8 @@ export class Dashboard {
|
||||
}
|
||||
|
||||
case "voiceState": {
|
||||
// Return the user's current voice channel (if any)
|
||||
if (!user) return { channel: null };
|
||||
const userId = String(user.id).replace(/\D/g, "");
|
||||
// Check VoiceStateCache first (most reliable for Fluxer)
|
||||
// Uses O(1) lookup via iterateHumanUsers() / [Symbol.iterator]
|
||||
if (this.remix.voiceCache) {
|
||||
for (const [mapUserId, info] of this.remix.voiceCache) {
|
||||
if (String(mapUserId).replace(/\D/g, "") === userId && info.channelId) {
|
||||
@@ -333,7 +296,6 @@ export class Dashboard {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Fallback: check all guilds for the user's voice state
|
||||
const guilds = this.remix.client.guilds;
|
||||
const guildValues = guilds && typeof guilds.values === "function"
|
||||
? [...guilds.values()] : guilds ? Object.values(guilds) : [];
|
||||
@@ -358,22 +320,16 @@ export class Dashboard {
|
||||
|
||||
case "leave": {
|
||||
if (!user) return { error: "Invalid user" };
|
||||
// Support both params.data.channel and params.data.player for
|
||||
// backward compatibility with different backend versions.
|
||||
const playerId = params.data.channel ?? params.data.player;
|
||||
const player = this._getPlayerById(playerId);
|
||||
if (!player) return { error: "Player not found" };
|
||||
const authErr = await this._authorizeUserInGuild(user, player._guildId);
|
||||
if (authErr) return { error: authErr };
|
||||
// Remove this user from the dashboard users list
|
||||
if (player._dashboardUsers && user) {
|
||||
const idx = player._dashboardUsers.indexOf(String(user.id));
|
||||
if (idx !== -1) player._dashboardUsers.splice(idx, 1);
|
||||
}
|
||||
// If there are still dashboard users connected, don't destroy the player
|
||||
// — just remove this user. The player stays active for other users.
|
||||
if (player._dashboardUsers && player._dashboardUsers.length > 0) {
|
||||
// Publish a leave event for this user on the player channel
|
||||
try {
|
||||
const pubChannel = this.remix.dashboard?.redis?.client ?? this.remix.redis?.client;
|
||||
if (pubChannel && typeof pubChannel.publish === "function") {
|
||||
@@ -398,7 +354,6 @@ export class Dashboard {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Authorization helpers ──────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Check if a user is a bot owner, or is in the same voice channel as the player.
|
||||
@@ -416,14 +371,12 @@ export class Dashboard {
|
||||
|
||||
const observed = this.remix.voiceCache;
|
||||
if (observed) {
|
||||
// O(1) lookup: check if user is in the same channel as the player
|
||||
const guildId = String(player._guildId ?? "").replace(/\D/g, "");
|
||||
const userLoc = observed.get(cleanUserId, guildId || undefined);
|
||||
if (userLoc) {
|
||||
const infoChannelId = String(userLoc.channelId ?? "").replace(/\D/g, "");
|
||||
if (infoChannelId === cleanChanId) return null;
|
||||
}
|
||||
// Legacy scan fallback (user might not have guildId)
|
||||
for (const [mapUserId, info] of observed) {
|
||||
if (String(mapUserId).replace(/\D/g, "") === cleanUserId) {
|
||||
const infoChannelId = String(info.channelId ?? "").replace(/\D/g, "");
|
||||
@@ -468,14 +421,11 @@ export class Dashboard {
|
||||
?? null;
|
||||
}
|
||||
|
||||
// ── Static converters ─────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* @param {import("@fluxerjs/core").User} user
|
||||
*/
|
||||
static convertUser(user) {
|
||||
// Build avatar URL using fluxerusercontent.com CDN pattern
|
||||
// user.avatar is the avatar hash string; user.id is the user ID
|
||||
let avatarUrl = "";
|
||||
if (user.avatar) {
|
||||
avatarUrl = `https://fluxerusercontent.com/avatars/${user.id}/${user.avatar}.webp`;
|
||||
@@ -484,7 +434,6 @@ export class Dashboard {
|
||||
} else if (typeof user.avatarURL === "function") {
|
||||
try { avatarUrl = user.avatarURL() ?? ""; } catch (_) {}
|
||||
}
|
||||
// Fallback to default avatar if no custom avatar
|
||||
if (!avatarUrl && user.discriminator) {
|
||||
avatarUrl = `https://fluxerusercontent.com/embed/avatars/${parseInt(user.discriminator || "0") % 5}.png`;
|
||||
}
|
||||
@@ -528,8 +477,6 @@ export class Dashboard {
|
||||
static convertChannel(channel) {
|
||||
const type = channel.type ?? 0;
|
||||
const isVoice = channel.isVoice?.() ?? (type === 2) ?? false;
|
||||
// Discord channel types: 0=text, 1=DM, 2=voice, 3=group DM, 4=category,
|
||||
// 5=announcement, 13=stage, 15=form, 16=forum, 17=media
|
||||
const isCategory = type === 4;
|
||||
const isText = !isVoice && !isCategory && (
|
||||
type === 0 || type === 5 || type === 13 ||
|
||||
@@ -582,10 +529,8 @@ export class Dashboard {
|
||||
: [];
|
||||
const allChannels = channelValues
|
||||
.map(Dashboard.convertChannel)
|
||||
.filter(c => !c.isCategory); // exclude categories — they are not joinable
|
||||
.filter(c => !c.isCategory);
|
||||
|
||||
// Build icon URL using fluxerusercontent.com CDN pattern
|
||||
// guild.icon is the icon hash string; guild.id is the server ID
|
||||
let iconUrl = null;
|
||||
if (guild.icon) {
|
||||
iconUrl = `https://fluxerusercontent.com/icons/${guild.id}/${guild.icon}.webp`;
|
||||
@@ -601,7 +546,6 @@ export class Dashboard {
|
||||
description: guild.description ?? null,
|
||||
ownerId: guild.ownerId,
|
||||
channels: allChannels,
|
||||
// Frontend expects voiceChannels array for server list display
|
||||
voiceChannels: allChannels.filter(c => c.isVoice),
|
||||
};
|
||||
}
|
||||
@@ -611,7 +555,6 @@ export class Dashboard {
|
||||
* @param {import("@fluxerjs/core").Guild} guild
|
||||
*/
|
||||
static convertServerSummary(guild) {
|
||||
// Build icon URL using fluxerusercontent.com CDN pattern
|
||||
let iconUrl = null;
|
||||
if (guild.icon) {
|
||||
iconUrl = `https://fluxerusercontent.com/icons/${guild.id}/${guild.icon}.webp`;
|
||||
@@ -637,7 +580,6 @@ export class Dashboard {
|
||||
const cleanChannelId = channelId ? String(channelId).replace(/\D/g, "") : "";
|
||||
const cleanGuildId = player._guildId ? String(player._guildId).replace(/\D/g, "") : "";
|
||||
|
||||
// Null-guard: player.queue can be null during teardown
|
||||
const queue = player.queue ?? { loop: false, songLoop: false, current: null, data: [] };
|
||||
|
||||
return {
|
||||
@@ -665,14 +607,8 @@ export class Dashboard {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Fallback: VoiceStateCache (seeded from READY/GUILD_CREATE).
|
||||
// After a bot reload, guild.voice_states may only contain the bot's
|
||||
// own voice state, while VoiceStateCache has ALL humans who were
|
||||
// already in voice when the bot reconnected.
|
||||
// Try O(1) channel lookup first, then fall back to iteration.
|
||||
const vc = player._voiceCache ?? player._observedVoiceUsers;
|
||||
if (vc && cleanChannelId && cleanGuildId) {
|
||||
// O(1) lookup via getHumansInChannel
|
||||
if (typeof vc.getHumansInChannel === "function") {
|
||||
const channelHumans = vc.getHumansInChannel(cleanGuildId, cleanChannelId);
|
||||
for (const hid of channelHumans) {
|
||||
@@ -683,13 +619,11 @@ export class Dashboard {
|
||||
seen.add(hid);
|
||||
}
|
||||
} else {
|
||||
// Legacy iteration fallback
|
||||
for (const [mapUserId, info] of vc) {
|
||||
if (seen.has(mapUserId)) continue;
|
||||
const infoCh = String(info.channelId ?? "").replace(/\D/g, "");
|
||||
const infoG = String(info.guildId ?? "").replace(/\D/g, "");
|
||||
if (infoCh === cleanChannelId && infoG === cleanGuildId) {
|
||||
// Skip the bot itself
|
||||
const botId = player.client?.user?.id;
|
||||
if (botId && String(mapUserId) === String(botId)) continue;
|
||||
ids.push(String(mapUserId));
|
||||
@@ -698,7 +632,6 @@ export class Dashboard {
|
||||
}
|
||||
}
|
||||
}
|
||||
// Merge dashboard users (connected via web UI but not necessarily in Discord voice)
|
||||
if (player._dashboardUsers) {
|
||||
for (const du of player._dashboardUsers) {
|
||||
if (!seen.has(du)) { ids.push(du); seen.add(du); }
|
||||
@@ -707,9 +640,6 @@ export class Dashboard {
|
||||
return ids;
|
||||
})(),
|
||||
channel: channel ? Dashboard.convertChannel(channel) : null,
|
||||
// Use lightweight server summary to avoid serializing hundreds of channels
|
||||
// per player update. The frontend should fetch full server details via
|
||||
// the "server" request type when needed.
|
||||
server: guild ? Dashboard.convertServerSummary(guild) : null,
|
||||
};
|
||||
}
|
||||
@@ -750,30 +680,7 @@ export class Dashboard {
|
||||
};
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Pub/Sub broadcast helpers
|
||||
//
|
||||
// CRITICAL: The backend (backend-master) expects standard message
|
||||
// formats on both the global :players channel and the per-player
|
||||
// :player_{channelId} channel. The formats are:
|
||||
//
|
||||
// Global (:players):
|
||||
// { type: "init", player: serialisedPlayer } — when bot joins a VC
|
||||
// { type: "close", player: serialisedPlayer } — when bot leaves a VC
|
||||
//
|
||||
// Per-player (:player_{channelId}):
|
||||
// { type: "startplay", data: serialisedVideo }
|
||||
// { type: "streamStartPlay", data: timestamp }
|
||||
// { type: "stopplay", data: null }
|
||||
// { type: "pause", data: { elapsedTime: ms } }
|
||||
// { type: "resume", data: { elapsedTime: ms } }
|
||||
// { type: "volume", data: number }
|
||||
// { type: "queue", data: serialisedQueueEvent }
|
||||
// { type: "join", data: userId }
|
||||
// { type: "leave", data: userId }
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
// Debounce map for playerUpdate — prevents flooding Redis with rapid updates.
|
||||
_playerUpdateTimers = new Map();
|
||||
|
||||
/**
|
||||
@@ -796,8 +703,6 @@ export class Dashboard {
|
||||
if (!this.enabled) return;
|
||||
const key = player._channelId ?? player._guildId ?? "unknown";
|
||||
|
||||
// For "init" and "close" events, send immediately (no debounce) — the
|
||||
// backend relies on these for player lifecycle management.
|
||||
if (details.type === "init" || details.type === "close") {
|
||||
try {
|
||||
const serialised = Dashboard.convertPlayer(player);
|
||||
@@ -811,13 +716,12 @@ export class Dashboard {
|
||||
return;
|
||||
}
|
||||
|
||||
// All other events are debounced to avoid flooding Redis.
|
||||
if (this._playerUpdateTimers.has(key)) {
|
||||
clearTimeout(this._playerUpdateTimers.get(key));
|
||||
}
|
||||
this._playerUpdateTimers.set(key, setTimeout(() => {
|
||||
this._playerUpdateTimers.delete(key);
|
||||
if (player._destroyed) return; // skip destroyed players
|
||||
if (player._destroyed) return;
|
||||
try {
|
||||
const serialised = Dashboard.convertPlayer(player);
|
||||
this.redis.send(this.redis.platform + ":players", JSON.stringify({
|
||||
@@ -877,9 +781,6 @@ export class Dashboard {
|
||||
this.redis.send(channel, JSON.stringify(details));
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Login Confirmation (for backend-based DM code verification flow)
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Verify a login code submitted by a user via DM.
|
||||
@@ -906,13 +807,13 @@ export class Dashboard {
|
||||
if (res.length === 0) return "If this is a valid code, it was not created for your account.";
|
||||
|
||||
for (let i = 0; i < res.length; i++) {
|
||||
if (res[i].verified) continue; // skip already-verified codes (double guard)
|
||||
if (res[i].verified) continue;
|
||||
if (await this.db.compareHash(code, res[i].token)) {
|
||||
if (Date.now() - this.expiryTime > (new Date(res[i].createdAt)).getTime()) {
|
||||
return "Login token expired";
|
||||
}
|
||||
await this.db.execute("UPDATE login_codes SET verified=true WHERE id=?", [res[i].id]);
|
||||
return null; // success
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -15,8 +15,6 @@ export class DatabaseManager {
|
||||
connectionLimit: 15,
|
||||
...config,
|
||||
});
|
||||
// Without this listener, unhandled pool-level errors (connection drops,
|
||||
// timeouts) fire an unhandled 'error' event which crashes the process.
|
||||
this.db.on("error", (err) => {
|
||||
logger.error("[DashboardDB] MySQL pool error:", err.code ?? err.message);
|
||||
});
|
||||
|
||||
@@ -8,7 +8,6 @@ import { logger } from "../constants/Logger.mjs";
|
||||
*/
|
||||
const DEFAULT_RETRY_STRATEGY = (options) => {
|
||||
if (options.totalRetryTime > 60_000) {
|
||||
// Stop retrying after 60s total — something is fundamentally wrong
|
||||
return new Error("Redis reconnection exhausted after 60s");
|
||||
}
|
||||
return Math.min(options.attempt * 500, 5_000);
|
||||
|
||||
+1
-2
@@ -1,11 +1,10 @@
|
||||
import ffprobe from "ffprobe-static";
|
||||
import { spawn } from "node:child_process";
|
||||
|
||||
const PROBE_TIMEOUT_MS = 15_000; // 15 seconds
|
||||
const PROBE_TIMEOUT_MS = 15_000;
|
||||
|
||||
export default function probe(file) {
|
||||
return new Promise((res, rej) => {
|
||||
// Pass args as an array — splitting a string on " " breaks paths that contain spaces.
|
||||
const args = [
|
||||
"-hide_banner",
|
||||
"-show_entries", "format_tags:format=duration",
|
||||
|
||||
+2
-47
@@ -12,22 +12,15 @@ import { Utils } from "./Utils.mjs";
|
||||
import { PROVIDERS } from "./constants/providers.mjs";
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// NodeLink Configuration (forwarded from Player via workerData)
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
const nl = workerData?.data?.nodelink ?? {};
|
||||
const NL_HOST = nl.host ?? "localhost";
|
||||
const NL_PORT = nl.port ?? 3000;
|
||||
// Shared default — must match NL_DEFAULT_PASSWORD in Player.mjs
|
||||
const NL_DEFAULT_PASSWORD = "youshallnotpass";
|
||||
const NL_PASSWORD = nl.password ?? NL_DEFAULT_PASSWORD;
|
||||
const NL_SESSION_ID = nl.sessionId ?? null; // provided by moonlink.js Manager
|
||||
const NL_SESSION_ID = nl.sessionId ?? null;
|
||||
const NL_GUILD_ID = workerData?.data?.guildId ?? null;
|
||||
|
||||
// ─── Error sanitizer ──────────────────────────────────────────────────────────
|
||||
// Compile regexes once at module load (constants are fixed for the worker's lifetime).
|
||||
// Re-compiling on every sanitizeError() call was wasteful and identical each time.
|
||||
const _sanitizeRegexes = (() => {
|
||||
const r = [];
|
||||
if (NL_HOST && NL_HOST !== "localhost") {
|
||||
@@ -43,21 +36,16 @@ const _sanitizeRegexes = (() => {
|
||||
return r;
|
||||
})();
|
||||
|
||||
// Strips the NodeLink host, port, and password from any string so they are
|
||||
// never shown to end-users in messages.
|
||||
function sanitizeError(msg) {
|
||||
if (!msg) return msg;
|
||||
let s = String(msg);
|
||||
for (const { re, sub } of _sanitizeRegexes) {
|
||||
re.lastIndex = 0; // reset stateful global regexes between calls
|
||||
re.lastIndex = 0;
|
||||
s = s.replace(re, sub);
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// HTTP Helper
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Make a GET request to NodeLink and return the parsed JSON body.
|
||||
@@ -109,9 +97,6 @@ async function loadTracks(identifier, nlGetFn = nlGet) {
|
||||
return nlGetFn(`/v4/loadtracks?identifier=${encodeURIComponent(identifier)}`);
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// Track Conversion
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Convert a NodeLink track object to the internal video format.
|
||||
@@ -157,15 +142,9 @@ function tokenizeMatchText(value) {
|
||||
return normalizeMatchText(value).split(" ").filter(Boolean);
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// Provider Configuration (imported from constants/providers.mjs)
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
const TYPE_MODIFIERS = ["track","playlist","album","artist","channel","user"];
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// YTUtils Class
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
class YTUtils extends EventEmitter {
|
||||
constructor() { super(); }
|
||||
@@ -206,10 +185,8 @@ class YTUtils extends EventEmitter {
|
||||
try {
|
||||
const urlObj = new URL(url);
|
||||
|
||||
// Check if it's a YouTube Radio/Mix URL
|
||||
const list = urlObj.searchParams.get("list");
|
||||
if (list && list.startsWith("RD")) {
|
||||
// Extract just the video ID and create clean URL
|
||||
const videoId = urlObj.searchParams.get("v");
|
||||
if (videoId) {
|
||||
logger.worker(`[Worker] Cleaning YouTube Radio URL, extracted video: ${videoId}`);
|
||||
@@ -217,7 +194,6 @@ class YTUtils extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// Remove start_radio parameter if present
|
||||
if (urlObj.searchParams.has("start_radio")) {
|
||||
urlObj.searchParams.delete("start_radio");
|
||||
return urlObj.toString();
|
||||
@@ -387,11 +363,9 @@ class YTUtils extends EventEmitter {
|
||||
async getVideoData(query, provider = "ytm", trackMeta = null) {
|
||||
const request = this._buildRequestContext(query, trackMeta);
|
||||
|
||||
// Handle URLs (including YouTube Radio/Mix)
|
||||
if (this.isValidUrl(query)) {
|
||||
this.emit("message", "Loading...");
|
||||
|
||||
// Clean YouTube Radio URLs to prevent metadata mismatches
|
||||
const cleanedUrl = this._cleanYouTubeUrl(query);
|
||||
if (cleanedUrl !== query) {
|
||||
logger.worker(`[Worker] URL cleaned: ${query} -> ${cleanedUrl}`);
|
||||
@@ -405,7 +379,6 @@ class YTUtils extends EventEmitter {
|
||||
return { type: "error", data: null, error: sanitizeError(e.message) };
|
||||
}
|
||||
|
||||
// Handle playlist results
|
||||
if (data.loadType === "playlist") {
|
||||
const tracks = (data.data?.tracks ?? []).map(track => this._applyTrackMeta(trackToVideo(track), trackMeta));
|
||||
tracks.forEach(t => { t.playlistName = data.data?.info?.name ?? null; });
|
||||
@@ -413,7 +386,6 @@ class YTUtils extends EventEmitter {
|
||||
return { type: "list", data: tracks };
|
||||
}
|
||||
|
||||
// Handle single track
|
||||
if (data.loadType === "track" && data.data) {
|
||||
const video = this._applyTrackMeta(trackToVideo(data.data), trackMeta);
|
||||
if (!video) return { type: "error", data: "Failed to parse track data." };
|
||||
@@ -426,7 +398,6 @@ class YTUtils extends EventEmitter {
|
||||
return { type: "error", data: "Empty track data returned." };
|
||||
}
|
||||
|
||||
// Handle search results (take first)
|
||||
if (data.loadType === "search" && data.data?.length) {
|
||||
const bestTrack = this._pickBestTrack(data.data, provider, request) ?? data.data[0];
|
||||
const video = this._applyTrackMeta(trackToVideo(bestTrack), trackMeta);
|
||||
@@ -434,12 +405,10 @@ class YTUtils extends EventEmitter {
|
||||
return { type: "video", data: video };
|
||||
}
|
||||
|
||||
// No recognizable loadType
|
||||
this.emit("message", `**Could not load that URL.** (loadType: ${data.loadType || "unknown"})`);
|
||||
return { type: "error", data: null, error: "Unknown loadType: " + (data.loadType || "none") };
|
||||
}
|
||||
|
||||
// Handle search queries (non-URLs)
|
||||
this.emit("message", `Searching ${this._providerLabel(provider)}...`);
|
||||
|
||||
let data;
|
||||
@@ -450,7 +419,6 @@ class YTUtils extends EventEmitter {
|
||||
return { type: "error", data: null, error: sanitizeError(e.message) };
|
||||
}
|
||||
|
||||
// Handle search results
|
||||
if (data.loadType === "search" && data.data?.length) {
|
||||
const trackToUse = this._pickBestTrack(data.data, provider, request) ?? data.data[0];
|
||||
const video = this._applyTrackMeta(trackToVideo(trackToUse), trackMeta);
|
||||
@@ -458,7 +426,6 @@ class YTUtils extends EventEmitter {
|
||||
return { type: "video", data: video };
|
||||
}
|
||||
|
||||
// Handle playlist from search
|
||||
if (data.loadType === "playlist") {
|
||||
const tracks = (data.data?.tracks ?? []).map(track => this._applyTrackMeta(trackToVideo(track), trackMeta));
|
||||
if (tracks.length > 0) {
|
||||
@@ -467,7 +434,6 @@ class YTUtils extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
// Single track from search
|
||||
if (data.loadType === "track" && data.data) {
|
||||
const video = this._applyTrackMeta(trackToVideo(data.data), trackMeta);
|
||||
if (!video) return { type: "error", data: "Failed to parse track data." };
|
||||
@@ -480,22 +446,15 @@ class YTUtils extends EventEmitter {
|
||||
return { type: "error", data: "Empty track data returned." };
|
||||
}
|
||||
|
||||
// Nothing found
|
||||
this.emit("message", `**No results found for '${query}'.**`);
|
||||
return { type: "error", data: null, error: "No results found" };
|
||||
}
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// Worker Entry Point
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
const jobId = workerData?.jobId;
|
||||
const data = workerData?.data;
|
||||
|
||||
// ─── Pool mode ────────────────────────────────────────────────────────────────
|
||||
// When spawned by PlayerWorkerPool, the worker stays alive and handles multiple
|
||||
// jobs via parentPort messages instead of exiting after one.
|
||||
if (workerData?.poolMode) {
|
||||
const utils = new YTUtils();
|
||||
|
||||
@@ -518,8 +477,6 @@ if (workerData?.poolMode) {
|
||||
const NL_SID_job = nl.sessionId ?? null;
|
||||
const NL_GID_job = jData?.guildId ?? null;
|
||||
|
||||
// Build a job-scoped request helper so pool workers handle different
|
||||
// nodelink configs per job (useful when the session ID rotates).
|
||||
const nlGetJob = (path) => new Promise((resolve, reject) => {
|
||||
const isHttps = NL_PORT_job === 443;
|
||||
const mod = isHttps ? https : http;
|
||||
@@ -577,10 +534,8 @@ if (workerData?.poolMode) {
|
||||
}
|
||||
});
|
||||
|
||||
// Keep the worker alive — don't exit, the pool will terminate() when done.
|
||||
}
|
||||
|
||||
// ─── Legacy single-job mode (fallback / dev) ──────────────────────────────────
|
||||
else {
|
||||
|
||||
if (!jobId) {
|
||||
|
||||
Reference in new issue
Block a user