diff --git a/.gitignore b/.gitignore index 3e0efe9..f83126f 100644 --- a/.gitignore +++ b/.gitignore @@ -1,5 +1,6 @@ config.json .env +node_modules/ storage/stats-cache.json storage/locales/user/ *.log diff --git a/commands/leave.mjs b/commands/leave.mjs index 2e5749a..69bf57e 100644 --- a/commands/leave.mjs +++ b/commands/leave.mjs @@ -101,9 +101,17 @@ export async function run(msg, data) { const id = cleanId(p._channelId ?? mapKey); return id ? `<#${id}>` : "\`unknown\`"; }); + if (!client?.channels?.get?.(targetChannelId)) { + return msg.reply( + this.t(msg, "responses.leave.specifyChannel", { + channels: channelList.map(c => `• ${c}`).join("\n"), + prefix: this.handler.getPrefix(msg.message?.guildId ?? msg.channel?.guild?.id) + }) + ); + } return msg.reply( this.t(msg, "responses.leave.noPlayerInChannel", { - channel: `<#${targetChannelId}>`, + channel: targetChannelId, channels: channelList.map(c => `• ${c}`).join("\n") }) ); diff --git a/src/constants/API.mjs b/src/constants/API.mjs deleted file mode 100644 index 18cb431..0000000 --- a/src/constants/API.mjs +++ /dev/null @@ -1,100 +0,0 @@ -/** @module constants/API */ - -/** - * FluxerList API configuration. - * @namespace FLUXERLIST - */ -export const FLUXERLIST = { - /** Base URL for the FluxerList REST API. @type {string} */ - BASE_URL: "https://fluxerlist.com/api/v1", - - /** Public FluxerList website URL. @type {string} */ - SITE_URL: "https://fluxerlist.com", - - /** API endpoint path templates. @type {{ SERVER_VOTERS: string, BOT_VOTERS: string }} */ - ENDPOINTS: { - SERVER_VOTERS: "/servers/:id/voters", - - BOT_VOTERS: "/bots/:id/voters", - }, - - /** Accepted resource type identifiers. @type {string[]} */ - RESOURCE_TYPES: ["server", "bot"], - - /** Thumbnail API base URL. @type {string} */ - THUMBNAIL: "https://fluxerlist.com/api/v1", -}; - -/** - * FluxerList authentication helpers. - * @namespace FLUXERLIST_AUTH - */ -export const FLUXERLIST_AUTH = { - /** HTTP header name for auth. @type {string} */ - HEADER: "Authorization", - - /** Required API key prefix. @type {string} */ - KEY_PREFIX: "fl_", - - /** - * Format an API key as a Bearer token, prepending the prefix if needed. - * @param {string} apiKey - Raw or prefixed API key. - * @returns {string} `Bearer fl_...` string. - */ - bearer(apiKey) { - const key = apiKey.startsWith(FLUXERLIST_AUTH.KEY_PREFIX) - ? apiKey - : FLUXERLIST_AUTH.KEY_PREFIX + apiKey; - return `Bearer ${key}`; - }, -}; - -/** - * FluxerList pagination and cache limits. - * @namespace FLUXERLIST_LIMITS - */ -export const FLUXERLIST_LIMITS = { - /** Default page number. @type {number} */ - DEFAULT_PAGE: 1, - - /** Default items-per-page. @type {number} */ - DEFAULT_LIMIT: 50, - - /** Maximum allowed items-per-page. @type {number} */ - MAX_LIMIT: 100, - - /** Cache time-to-live in milliseconds. @type {number} */ - CACHE_TTL_MS: 5 * 60 * 1000, -}; - -/** - * Build a full FluxerList API URL by substituting `:id` in the endpoint and appending query params. - * @param {string} endpoint - Endpoint template (e.g. `"/servers/:id/voters"`). - * @param {string} resourceId - Value to substitute for `:id`. - * @param {{ page?: number, limit?: number }} [queryParams={}] - * @returns {string} Fully qualified URL. - */ -export function buildFluxerListUrl(endpoint, resourceId, queryParams = {}) { - const path = endpoint.replace(":id", encodeURIComponent(resourceId)); - const params = new URLSearchParams(); - - if (queryParams.page) params.set("page", String(queryParams.page)); - if (queryParams.limit) { - const clamped = Math.min(Math.max(1, queryParams.limit), FLUXERLIST_LIMITS.MAX_LIMIT); - params.set("limit", String(clamped)); - } - - const qs = params.toString(); - return `${FLUXERLIST.BASE_URL}${path}${qs ? "?" + qs : ""}`; -} - -/** - * Build a FluxerList vote link for a server or bot. - * @param {"server"|"bot"} type - Resource type. - * @param {string} resourceId - The server/bot ID. - * @returns {string} Absolute URL to the vote page. - */ -export function buildVoteLink(type, resourceId) { - const path = type === "server" ? "servers" : "bots"; - return `${FLUXERLIST.SITE_URL}/${path}/${resourceId}`; -} diff --git a/src/constants/Helpers247.mjs b/src/constants/Helpers247.mjs deleted file mode 100644 index 7199844..0000000 --- a/src/constants/Helpers247.mjs +++ /dev/null @@ -1,39 +0,0 @@ -/** @module constants/Helpers247 */ - -/** - * Simplified 24/7 helpers — single mode (on/off), no per-channel modes. - * get247ChannelMode is used by Player.mjs, PlayerManager.mjs, GatewayHandler.mjs, leave.mjs. - * remove247ChannelMode and set247ChannelMode are kept as no-ops for backward compat - * (original files in the zip still import them). - */ - -/** - * Check if a channel has 24/7 enabled. - * @param {object} set - ServerSettings instance - * @param {string} channelId - * @returns {"on"|"off"} - */ -export function get247ChannelMode(set, channelId) { - if (!set?.get) return "off"; - const raw = set.get("stay_247"); - if (!raw || raw === "none") return "off"; - const channels = Array.isArray(raw) - ? raw.map(id => String(id).trim()).filter(Boolean) - : [String(raw).trim()]; - return channels.includes(channelId) ? "on" : "off"; -} - -/** - * No-op: per-channel modes removed. Kept for backward compatibility. - * Original GatewayHandler.mjs and index.mjs still import this. - */ -export function remove247ChannelMode(set, channelId, currentChannels) { - // No-op: modes no longer exist, stay_247 array is managed directly. -} - -/** - * No-op: per-channel modes removed. Kept for backward compatibility. - */ -export function set247ChannelMode(set, channelId, mode) { - // No-op: modes no longer exist. -} \ No newline at end of file diff --git a/src/constants/Locale.mjs b/src/constants/Locale.mjs deleted file mode 100644 index ffef32e..0000000 --- a/src/constants/Locale.mjs +++ /dev/null @@ -1,210 +0,0 @@ -/** @module constants/Locale */ - -import { readFileSync, readdirSync, existsSync } from "fs"; -import path from "path"; -import { fileURLToPath } from "url"; -import { logger } from "./Logger.mjs"; - -/** @private */ -const __dirname = path.dirname(fileURLToPath(import.meta.url)); -/** @private */ -const LOCALES_DIR = path.resolve(__dirname, "../../storage/locales/bot"); - -/** - * Locale/i18n manager that loads JSON locale files from disk and provides - * dot-notation key lookups with `{{placeholder}}` and `$prefix` substitution. - * @class - */ -export class Locale { - /** - * @param {string} [defaultPrefix="%"] - Fallback prefix used when no prefix - * resolver is registered and the settings manager yields no prefix. - */ - constructor(defaultPrefix = "%") { - /** @private */ this.locales = new Map(); - /** @private */ this._resolved = new Map(); - /** @type {string} */ this.defaultLocale = "en"; - /** @private */ this.settingsMgr = null; - /** @private */ this._getPrefixFn = null; - /** @private */ this._defaultPrefix = defaultPrefix; - /** @private */ this._maxResolvedCache = 5000; - } - - /** - * Bind a settings manager so the locale resolver can look up per-guild locale preferences. - * @param {object} settingsMgr - Settings manager exposing `guilds.get(guildId)`. - */ - bind(settingsMgr) { - this.settingsMgr = settingsMgr; - } - - /** - * Load all `.json` locale files from the locales directory. - * Clears any previously loaded data and the resolved-cache. - */ - load() { - this.locales.clear(); - this._resolved.clear(); - - if (!existsSync(LOCALES_DIR)) { - logger.warn("[Locale] Locales directory not found:", LOCALES_DIR); - return; - } - - let files; - try { - files = readdirSync(LOCALES_DIR).filter(f => f.endsWith(".json")); - } catch (e) { - logger.warn("[Locale] Failed to read locales directory:", e.message); - return; - } - - for (const file of files) { - const filePath = path.join(LOCALES_DIR, file); - const code = file.replace(".json", ""); - try { - const data = JSON.parse(readFileSync(filePath, "utf8")); - this.locales.set(code, data); - } catch (e) { - logger.warn("[Locale] Failed to load " + file + ":", e.message); - } - } - - logger.info("[Locale] Loaded " + this.locales.size + " locale(s): " + [...this.locales.keys()].join(", ")); - } - - /** - * Return the set of loaded locale codes. - * @returns {Set} - */ - availableLocales() { - return new Set(this.locales.keys()); - } - - /** - * Resolve the locale data object for a guild, using per-guild settings or falling - * back to the default locale. Results are cached with an LRU-style cap. - * @private - * @param {string} guildId - * @returns {object} The locale data object. - */ - _getLocaleData(guildId) { - if (!guildId) return this.locales.get(this.defaultLocale) ?? {}; - - const cached = this._resolved.get(guildId); - if (cached) return cached; - - let code = this.defaultLocale; - try { - const serverSettings = this.settingsMgr?.guilds?.get?.(guildId); - if (serverSettings) { - const setting = serverSettings.get("locale"); - if (setting && this.locales.has(setting)) { - code = setting; - } - } - } catch(e) { logger.warn("[Locale] Error:", e?.message); } - - const data = this.locales.get(code) ?? this.locales.get(this.defaultLocale) ?? {}; - this._resolved.set(guildId, data); - - while (this._resolved.size > this._maxResolvedCache) { - const oldestKey = this._resolved.keys().next().value; - this._resolved.delete(oldestKey); - } - - return data; - } - - /** - * Invalidate the resolved-cache for a specific guild or all guilds. - * @param {string} [guildId] - Omit to clear the entire cache. - */ - invalidateCache(guildId) { - if (guildId) { - this._resolved.delete(guildId); - } else { - this._resolved.clear(); - } - } - - /** - * Register a custom prefix resolver function. - * @param {function(string): string} fn - Receives `guildId`, returns the prefix string. - */ - setPrefixResolver(fn) { - this._getPrefixFn = fn; - } - - /** - * Resolve the command prefix for a guild. - * @private - * @param {string} guildId - * @returns {string} - */ - _getPrefix(guildId) { - if (this._getPrefixFn) return this._getPrefixFn(guildId); - try { - const serverSettings = this.settingsMgr?.getServer?.(guildId); - if (serverSettings) { - const prefix = serverSettings.get("prefix"); - if (prefix) return prefix; - } - } catch(e) { logger.warn("[Locale] Error:", e?.message); } - return this._defaultPrefix || "!"; - } - - /** - * Resolve a dot-notation key against a nested object. - * @private - * @param {object} obj - * @param {string} key - e.g. "commands.play.description" - * @returns {*} - */ - _resolve(obj, key) { - const parts = key.split("."); - let current = obj; - for (const part of parts) { - if (current == null || typeof current !== "object") return undefined; - current = current[part]; - } - return current; - } - - /** - * Translate a locale key for a guild, applying `{{placeholder}}` replacements - * and `$prefix` substitution. Falls back to the default locale, then the raw key. - * @param {string} guildId - * @param {string} key - Dot-notation locale key. - * @param {Object} [replacements={}] - Placeholder values to substitute. - * @returns {string} The translated (or fallback) string. - */ - translate(guildId, key, replacements = {}) { - const localeData = this._getLocaleData(guildId); - - let value = this._resolve(localeData, key); - - if (value === undefined) { - value = this._resolve(this.locales.get(this.defaultLocale) ?? {}, key); - } - - if (value === undefined) return key; - if (typeof value !== "string") return key; - - for (const [placeholder, val] of Object.entries(replacements)) { - const escaped = placeholder.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); - const replacement = String(val ?? ""); - value = value.replace( - new RegExp(`\\{\\{${escaped}\\}\\}`, "g"), - () => replacement - ); - } - - if (value.includes("$prefix")) { - const prefix = this._getPrefix(guildId); - value = value.replace(/\$prefix/gi, prefix); - } - - return value; - } -} diff --git a/src/constants/Logger.mjs b/src/constants/Logger.mjs deleted file mode 100644 index 783164e..0000000 --- a/src/constants/Logger.mjs +++ /dev/null @@ -1,145 +0,0 @@ -/** @module constants/Logger */ - -/** @private */ -let _config = null; - -/** - * Initialize the logger with a configuration object. - * @param {object} [config] - Application configuration object. - * @param {object} [config.logging] - Logging-specific configuration. - */ -export function initLogger(config) { - _config = config?.logging ?? {}; -} - -/** - * Check whether a given log category is enabled. - * @private - * @param {string} category - The log category name (e.g. "player", "voice"). - * @returns {boolean} `true` if the category is enabled (or no config is loaded). - */ -function isEnabled(category) { - if (!_config) return true; - if (_config.enabled === false) return false; - return _config[category] !== false; -} - -/** - * Return an ISO-8601 timestamp string truncated to seconds. - * @private - * @returns {string} Timestamp in `YYYY-MM-DD HH:MM:SS` format. - */ -function ts() { - return new Date().toISOString().replace("T", " ").slice(0, 19); -} - -/** - * Cooldown state for WebSocket error logging to avoid spam. - * @type {{ lastLogged: number, COOLDOWN_MS: number }} - */ -export const _wsErrorCooldown = { lastLogged: 0, COOLDOWN_MS: 15_000 }; - -/** - * Structured logger exposing category-gated log methods. - * @namespace logger - */ -export const logger = { - /** - * Log an error message (always emitted regardless of config). - * @param {string} tag - A tag identifying the source (e.g. "[Player]"). - * @param {...*} args - Additional values to log. - */ - error(tag, ...args) { - console.error(`[${ts()}] ${tag}`, ...args); - }, - /** - * Log a warning message. Honours `logging.warn` override when logging is disabled. - * @param {string} tag - A tag identifying the source. - * @param {...*} args - Additional values to log. - */ - warn(tag, ...args) { - if (!_config) { console.warn(`[${ts()}] ${tag}`, ...args); return; } - if (_config.enabled === false && _config.warn !== true) return; - console.warn(`[${ts()}] ${tag}`, ...args); - }, - /** - * Log an info message. Suppressed when `logging.enabled === false`. - * @param {string} tag - A tag identifying the source. - * @param {...*} args - Additional values to log. - */ - info(tag, ...args) { - if (_config?.enabled === false) return; - console.log(`[${ts()}] ${tag}`, ...args); - }, - - /** - * Category-gated player log. - * @param {...*} args - */ - player(...args) { if (isEnabled("player")) console.log(`[${ts()}]`, ...args); }, - /** - * Category-gated inactivity log. - * @param {...*} args - */ - inactivity(...args) { if (isEnabled("inactivity")) console.log(`[${ts()}]`, ...args); }, - /** - * Category-gated voice 24/7 log. - * @param {...*} args - */ - voice247(...args) { if (isEnabled("voice247")) console.log(`[${ts()}]`, ...args); }, - /** - * Category-gated voice-state log. - * @param {...*} args - */ - voiceState(...args) { if (isEnabled("voiceState")) console.log(`[${ts()}]`, ...args); }, - /** - * Category-gated media-player log. - * @param {...*} args - */ - mediaplayer(...args) { if (isEnabled("mediaplayer")) console.log(`[${ts()}]`, ...args); }, - /** - * Category-gated commands log. - * @param {...*} args - */ - commands(...args) { if (isEnabled("commands")) console.log(`[${ts()}]`, ...args); }, - /** - * Category-gated guild log. - * @param {...*} args - */ - guild(...args) { if (isEnabled("guild")) console.log(`[${ts()}]`, ...args); }, - /** - * Category-gated recovery log. - * @param {...*} args - */ - recovery(...args) { if (isEnabled("recovery")) console.log(`[${ts()}]`, ...args); }, - /** - * Category-gated settings log. - * @param {...*} args - */ - settings(...args) { if (isEnabled("settings")) console.log(`[${ts()}]`, ...args); }, - /** - * Category-gated lavalink log. - * @param {...*} args - */ - lavalink(...args) { if (isEnabled("lavalink")) console.log(`[${ts()}]`, ...args); }, - /** - * Category-gated alone-check log. - * @param {...*} args - */ - aloneCheck(...args) { if (isEnabled("aloneCheck")) console.log(`[${ts()}]`, ...args); }, - /** - * Category-gated voice log. - * @param {...*} args - */ - voice(...args) { if (isEnabled("voice")) console.log(`[${ts()}]`, ...args); }, - /** - * Category-gated dashboard log. - * @param {...*} args - */ - dashboard(...args) { if (isEnabled("dashboard")) console.log(`[${ts()}]`, ...args); }, - /** - * Category-gated redis log. - * @param {...*} args - */ - redis(...args) { if (isEnabled("redis")) console.log(`[${ts()}]`, ...args); }, -}; diff --git a/src/constants/UI.mjs b/src/constants/UI.mjs deleted file mode 100644 index 19fb946..0000000 --- a/src/constants/UI.mjs +++ /dev/null @@ -1,37 +0,0 @@ -/** @module constants/UI */ - -/** Hex color string for error embeds. @type {string} */ -export const ERROR_COLOR = "#ff0000"; - -/** Numeric hex color for warning embeds. @type {number} */ -export const WARN_COLOR = 0xFFAA00; - -/** Numeric hex color for success embeds. @type {number} */ -export const SUCCESS_COLOR = 0x00CC66; - -/** Numeric hex color for danger/critical embeds. @type {number} */ -export const DANGER_COLOR = 0xFF4444; - -/** Auto-remove reaction collectors after this many ms. @type {number} */ -export const EMOJI_REMOVE_TIMEOUT = 60_000; - -/** Session idle timeout in ms. @type {number} */ -export const SESSION_TIMEOUT = 30_000; - -/** Number emoji map for selection menus (indices 1-10). @type {string[]} */ -export const NUMBER_EMOJIS = [ - "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", - "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟", -]; - -/** Emoji used to cancel a selection. @type {string} */ -export const CANCEL_EMOJI = "❌"; - -/** Emoji for previous-page navigation. @type {string} */ -export const PREV_EMOJI = "⬅️"; - -/** Emoji for next-page navigation. @type {string} */ -export const NEXT_EMOJI = "➡️"; - -/** Maximum allowed volume value. @type {number} */ -export const MAX_VOLUME = 200; diff --git a/src/constants/VoiceStateCache.mjs b/src/constants/VoiceStateCache.mjs deleted file mode 100644 index 0835c12..0000000 --- a/src/constants/VoiceStateCache.mjs +++ /dev/null @@ -1,589 +0,0 @@ -/** @module constants/VoiceStateCache */ - -import { logger } from "./Logger.mjs"; -import { cleanId } from "../Utils.mjs"; - -/** - * LRU-backed cache mapping users (and bots) to their voice-channel locations. - * Supports O(1) lookups by guild+user or guild+channel and implements the - * Map-like interface (`get`, `set`, `delete`, `has`, `forEach`, `entries`, `keys`, `values`). - * @class - */ -export class VoiceStateCache { - /** - * @param {object} [opts] - * @param {number} [opts.maxUsers=50000] - Max cached human user entries. - * @param {number} [opts.maxBots=10000] - Max cached bot user entries. - */ - constructor(opts = {}) { - this.userLocations = new Map(); - this.channelMembers = new Map(); - - this.botLocations = new Map(); - this.botChannelMembers = new Map(); - - this._maxUsers = opts.maxUsers ?? 50_000; - this._maxBots = opts.maxBots ?? 10_000; - this._lruUserKeys = []; - this._lruBotKeys = []; - } - - /** - * Build a composite user key for storage. - * @param {string} guildId - * @param {string} userId - * @returns {string} - */ - static userKey(guildId, userId) { - return `${cleanId(guildId)}:${cleanId(userId)}`; - } - - /** - * Build a composite channel key for storage. - * @param {string} guildId - * @param {string} channelId - * @returns {string} - */ - static channelKey(guildId, channelId) { - return `${cleanId(guildId)}:${cleanId(channelId)}`; - } - - /** - * Update (or remove) a user's voice-channel location in the cache. - * When `channelId` is provided the user is added; when `null`/falsy the user is removed. - * Automatically evicts LRU entries when capacity is exceeded. - * @param {{ guildId: string, userId: string, channelId: string|null, isBot?: boolean }} opts - */ - updateUser({ guildId, userId, channelId, isBot = false }) { - const cleanGuild = cleanId(guildId); - const cleanUser = cleanId(userId); - const cleanChannel = channelId ? cleanId(channelId) : null; - if (!cleanGuild || !cleanUser) return; - - const locations = isBot ? this.botLocations : this.userLocations; - const channelIdx = isBot ? this.botChannelMembers : this.channelMembers; - const maxEntries = isBot ? this._maxBots : this._maxUsers; - const lruKeys = isBot ? this._lruBotKeys : this._lruUserKeys; - const uKey = VoiceStateCache.userKey(cleanGuild, cleanUser); - - const prev = locations.get(uKey); - if (prev) { - const prevCKey = VoiceStateCache.channelKey(prev.guildId, prev.channelId); - const prevSet = channelIdx.get(prevCKey); - if (prevSet) { - prevSet.delete(cleanUser); - if (prevSet.size === 0) channelIdx.delete(prevCKey); - } - } - - if (cleanChannel) { - const cKey = VoiceStateCache.channelKey(cleanGuild, cleanChannel); - let set = channelIdx.get(cKey); - if (!set) { set = new Set(); channelIdx.set(cKey, set); } - set.add(cleanUser); - - locations.delete(uKey); - locations.set(uKey, { channelId: cleanChannel, guildId: cleanGuild, userId: cleanUser }); - - const lruIdx = lruKeys.indexOf(uKey); - if (lruIdx !== -1) lruKeys.splice(lruIdx, 1); - lruKeys.push(uKey); - - while (locations.size > maxEntries) { - let evicted = false; - for (let i = 0; i < lruKeys.length; i++) { - const evictKey = lruKeys[i]; - if (evictKey === uKey) continue; - - const evictEntry = locations.get(evictKey); - if (evictEntry) { - const evictCKey = VoiceStateCache.channelKey(evictEntry.guildId, evictEntry.channelId); - const evictSet = channelIdx.get(evictCKey); - if (evictSet) { - evictSet.delete(evictEntry.userId); - if (evictSet.size === 0) channelIdx.delete(evictCKey); - } - locations.delete(evictKey); - } - lruKeys.splice(i, 1); - evicted = true; - break; - } - if (!evicted) break; - } - } else { - locations.delete(uKey); - const idx = lruKeys.indexOf(uKey); - if (idx !== -1) lruKeys.splice(idx, 1); - } - } - - /** - * Check whether any human users are cached in the given channel. - * @param {string} guildId - * @param {string} channelId - * @returns {boolean} - */ - hasHumansInChannel(guildId, channelId) { - const cKey = VoiceStateCache.channelKey(guildId, channelId); - const set = this.channelMembers.get(cKey); - return set ? set.size > 0 : false; - } - - /** - * Get the count of human users cached in the given channel. - * @param {string} guildId - * @param {string} channelId - * @returns {number} - */ - getHumanCount(guildId, channelId) { - const cKey = VoiceStateCache.channelKey(guildId, channelId); - const set = this.channelMembers.get(cKey); - return set ? set.size : 0; - } - - /** - * Get the array of human user IDs cached in the given channel. - * @param {string} guildId - * @param {string} channelId - * @returns {string[]} - */ - getHumansInChannel(guildId, channelId) { - const cKey = VoiceStateCache.channelKey(guildId, channelId); - const set = this.channelMembers.get(cKey); - return set ? [...set] : []; - } - - /** - * Get the channel ID a human user is currently in, or `null`. - * @param {string} guildId - * @param {string} userId - * @returns {string|null} - */ - getUserChannel(guildId, userId) { - const uKey = VoiceStateCache.userKey(guildId, userId); - const loc = this.userLocations.get(uKey); - return loc ? loc.channelId : null; - } - - /** - * Check whether a human user exists in the cache for the given guild. - * @param {string} guildId - * @param {string} userId - * @returns {boolean} - */ - hasUser(guildId, userId) { - return this.userLocations.has(VoiceStateCache.userKey(guildId, userId)); - } - - /** - * Get the full location record for a human user. - * @param {string} guildId - * @param {string} userId - * @returns {{ channelId: string, guildId: string, userId: string }|undefined} - */ - getUserLocation(guildId, userId) { - return this.userLocations.get(VoiceStateCache.userKey(guildId, userId)); - } - - /** - * Seed a user into the cache only if not already present. - * @param {string} guildId - * @param {string} userId - * @param {string} channelId - * @param {boolean} [isBot=false] - */ - seedUser(guildId, userId, channelId, isBot = false) { - const uKey = VoiceStateCache.userKey(guildId, userId); - const locations = isBot ? this.botLocations : this.userLocations; - if (locations.has(uKey)) return; - this.updateUser({ guildId, userId, channelId, isBot }); - } - - /** - * Remove all cached entries (human and bot) for a given guild. - * @param {string} guildId - */ - removeGuild(guildId) { - const cleanGuild = cleanId(guildId); - const prefix = cleanGuild + ":"; - - - const userKeysToRemove = []; - for (const [uKey, loc] of this.userLocations) { - if (uKey.startsWith(prefix)) userKeysToRemove.push(uKey); - } - for (const uKey of userKeysToRemove) { - const loc = this.userLocations.get(uKey); - if (loc) { - const cKey = VoiceStateCache.channelKey(loc.guildId, loc.channelId); - const set = this.channelMembers.get(cKey); - if (set) { set.delete(loc.userId); if (set.size === 0) this.channelMembers.delete(cKey); } - } - this.userLocations.delete(uKey); - } - const channelKeysToRemove = []; - for (const [cKey] of this.channelMembers) { - if (cKey.startsWith(prefix)) channelKeysToRemove.push(cKey); - } - for (const cKey of channelKeysToRemove) this.channelMembers.delete(cKey); - this._lruUserKeys = this._lruUserKeys.filter(k => !k.startsWith(prefix)); - - const botKeysToRemove = []; - for (const [uKey, loc] of this.botLocations) { - if (uKey.startsWith(prefix)) botKeysToRemove.push(uKey); - } - for (const uKey of botKeysToRemove) { - const loc = this.botLocations.get(uKey); - if (loc) { - const cKey = VoiceStateCache.channelKey(loc.guildId, loc.channelId); - const set = this.botChannelMembers.get(cKey); - if (set) { set.delete(loc.userId); if (set.size === 0) this.botChannelMembers.delete(cKey); } - } - this.botLocations.delete(uKey); - } - const botChannelKeysToRemove = []; - for (const [cKey] of this.botChannelMembers) { - if (cKey.startsWith(prefix)) botChannelKeysToRemove.push(cKey); - } - for (const cKey of botChannelKeysToRemove) this.botChannelMembers.delete(cKey); - this._lruBotKeys = this._lruBotKeys.filter(k => !k.startsWith(prefix)); - } - - /** - * Remove all cached entries (human and bot) for a specific channel. - * @param {string} guildId - * @param {string} channelId - */ - removeChannel(guildId, channelId) { - const cKey = VoiceStateCache.channelKey(guildId, channelId); - - 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); - if (loc && loc.channelId === cleanId(channelId)) { - this.userLocations.delete(uKey); - } - } - this.channelMembers.delete(cKey); - } - - const botSet = this.botChannelMembers.get(cKey); - if (botSet) { - for (const userId of botSet) { - const uKey = VoiceStateCache.userKey(guildId, userId); - const loc = this.botLocations.get(uKey); - if (loc && loc.channelId === cleanId(channelId)) { - this.botLocations.delete(uKey); - } - } - this.botChannelMembers.delete(cKey); - } - } - - /** - * Remove specific users from a guild's cache. - * @param {string} guildId - * @param {string[]} userIds - * @param {boolean} [botsOnly=false] - If `true`, only purge bot entries. - */ - purgeUsersInGuild(guildId, userIds, botsOnly = false) { - const cleanGuild = cleanId(guildId); - - if (!botsOnly) { - for (const userId of userIds) { - const uKey = VoiceStateCache.userKey(cleanGuild, userId); - const loc = this.userLocations.get(uKey); - if (loc) { - const cKey = VoiceStateCache.channelKey(loc.guildId, loc.channelId); - const set = this.channelMembers.get(cKey); - if (set) { set.delete(loc.userId); if (set.size === 0) this.channelMembers.delete(cKey); } - this.userLocations.delete(uKey); - } - } - } - - for (const userId of userIds) { - const uKey = VoiceStateCache.userKey(cleanGuild, userId); - const loc = this.botLocations.get(uKey); - if (loc) { - const cKey = VoiceStateCache.channelKey(loc.guildId, loc.channelId); - const set = this.botChannelMembers.get(cKey); - if (set) { set.delete(loc.userId); if (set.size === 0) this.botChannelMembers.delete(cKey); } - this.botLocations.delete(uKey); - } - } - } - - /** - * Number of cached human users. - * @type {number} - */ - get observedVoiceUsersSize() { return this.userLocations.size; } - - /** - * Number of cached bot users. - * @type {number} - */ - get observedVoiceBotsSize() { return this.botLocations.size; } - - /** - * Iterate over all cached human user entries as `[userId, { channelId, guildId }]` pairs. - * @yields {[string, { channelId: string, guildId: string }]} - */ - *iterateHumanUsers() { - for (const [uKey, loc] of this.userLocations) { - yield [loc.userId, { channelId: loc.channelId, guildId: loc.guildId }]; - } - } - - /** - * Iterate over all cached bot user entries as `[compositeKey, { channelId, guildId }]` pairs. - * @yields {[string, { channelId: string, guildId: string }]} - */ - *iterateBotUsers() { - for (const [uKey, loc] of this.botLocations) { - yield [uKey, { channelId: loc.channelId, guildId: loc.guildId }]; - } - } - - /** - * Get the location record for a human user. If `guildId` is omitted, performs a linear scan. - * @param {string} userId - * @param {string|null} [guildId] - * @returns {{ channelId: string, guildId: string }|undefined} - */ - getHumanUser(userId, guildId = null) { - if (guildId) { - return this.userLocations.get(VoiceStateCache.userKey(guildId, userId)); - } - const cleanUser = cleanId(userId); - for (const [uKey, loc] of this.userLocations) { - if (loc.userId === cleanUser) return { channelId: loc.channelId, guildId: loc.guildId }; - } - return undefined; - } - - /** - * Set a human user's voice location via `updateUser`. - * @param {string} userId - * @param {{ guildId: string, channelId: string }} info - */ - setHumanUser(userId, info) { - const guildId = info.guildId; - const channelId = info.channelId; - if (guildId && channelId) { - this.updateUser({ guildId, userId, channelId, isBot: false }); - } - } - - /** - * Set a bot user's voice location via `updateUser`. - * @param {string} compositeKey - `guildId:userId` composite key. - * @param {{ guildId: string, channelId: string }} info - */ - setBotUser(compositeKey, info) { - const guildId = info.guildId; - const channelId = info.channelId; - const userId = compositeKey.split(":").pop(); - if (guildId && channelId && userId) { - this.updateUser({ guildId, userId, channelId, isBot: true }); - } - } - - /** - * Remove a human user from the cache. If `guildId` is omitted, scans all entries. - * @param {string} userId - * @param {string|null} [guildId] - */ - deleteHumanUser(userId, guildId = null) { - if (guildId) { - this.updateUser({ guildId, userId, channelId: null, isBot: false }); - } else { - const cleanUser = cleanId(userId); - for (const [uKey, loc] of this.userLocations) { - if (loc.userId === cleanUser) { - this.updateUser({ guildId: loc.guildId, userId: cleanUser, channelId: null, isBot: false }); - } - } - } - } - - /** - * Remove a bot user from the cache by its composite key. - * @param {string} compositeKey - `guildId:userId` composite key. - */ - deleteBotUser(compositeKey) { - const parts = compositeKey.split(":"); - const guildId = parts[0]; - const userId = parts[1]; - if (guildId && userId) { - this.updateUser({ guildId, userId, channelId: null, isBot: true }); - } - } - - /** - * Check whether a human user exists in the cache. If `guildId` is omitted, scans all entries. - * @param {string} userId - * @param {string|null} [guildId] - * @returns {boolean} - */ - hasHumanUser(userId, guildId = null) { - if (guildId) { - return this.userLocations.has(VoiceStateCache.userKey(guildId, userId)); - } - const cleanUser = cleanId(userId); - for (const [uKey, loc] of this.userLocations) { - if (loc.userId === cleanUser) return true; - } - return false; - } - - /** - * Check whether a bot user exists in the cache by composite key. - * @param {string} compositeKey - `guildId:userId` composite key. - * @returns {boolean} - */ - hasBotUser(compositeKey) { - return this.botLocations.has(compositeKey); - } - - /** - * Implement the iterable protocol over human user entries. - * @yields {[string, { channelId: string, guildId: string }]} - */ - *[Symbol.iterator]() { - for (const [uKey, loc] of this.userLocations) { - yield [loc.userId, { channelId: loc.channelId, guildId: loc.guildId }]; - } - } - - /** - * Number of cached human users (Map-like `.size`). - * @type {number} - */ - get size() { return this.userLocations.size; } - - /** - * Map-like `has` — checks if a human user is cached. - * @param {string} userId - * @param {string} [guildId] - * @returns {boolean} - */ - has(userId, guildId) { - if (guildId !== undefined) { - return this.userLocations.has(VoiceStateCache.userKey(guildId, userId)); - } - const cleanUser = cleanId(userId); - for (const [, loc] of this.userLocations) { - if (loc.userId === cleanUser) return true; - } - return false; - } - - /** - * Map-like `get` — retrieve a human user's location. - * @param {string} userId - * @param {string} [guildId] - * @returns {{ channelId: string, guildId: string }|undefined} - */ - get(userId, guildId) { - if (guildId !== undefined) { - const loc = this.userLocations.get(VoiceStateCache.userKey(guildId, userId)); - return loc ? { channelId: loc.channelId, guildId: loc.guildId } : undefined; - } - const cleanUser = cleanId(userId); - for (const [, loc] of this.userLocations) { - if (loc.userId === cleanUser) return { channelId: loc.channelId, guildId: loc.guildId }; - } - return undefined; - } - - /** - * Map-like `set` — upsert a human user's location. - * @param {string} userId - * @param {{ guildId: string, channelId: string }} info - */ - set(userId, info) { - const guildId = info?.guildId; - const channelId = info?.channelId; - if (guildId && channelId) { - this.updateUser({ guildId, userId, channelId, isBot: false }); - } - } - - /** - * Map-like `delete` — remove a human user. If `guildId` is omitted, removes all matching entries. - * @param {string} userId - * @param {string} [guildId] - */ - delete(userId, guildId) { - if (guildId !== undefined) { - this.updateUser({ guildId, userId, channelId: null, isBot: false }); - } else { - const cleanUser = cleanId(userId); - const toRemove = []; - for (const [uKey, loc] of this.userLocations) { - if (loc.userId === cleanUser) toRemove.push(loc); - } - for (const loc of toRemove) { - this.updateUser({ guildId: loc.guildId, userId: cleanUser, channelId: null, isBot: false }); - } - } - } - - /** - * Map-like `forEach` — iterate over human user entries. - * @param {function(string, { channelId: string, guildId: string }, VoiceStateCache): void} fn - */ - forEach(fn) { - for (const [userId, info] of this) { - fn(userId, info, this); - } - } - - /** - * Map-like `entries` iterator. - * @yields {[string, { channelId: string, guildId: string }]} - */ - *entries() { - yield* this; - } - - /** - * Map-like `keys` iterator. - * @yields {string} - */ - *keys() { - for (const [userId] of this) { - yield userId; - } - } - - /** - * Map-like `values` iterator. - * @yields {{ channelId: string, guildId: string }} - */ - *values() { - for (const [, info] of this) { - yield info; - } - } - - /** - * Diagnostic statistics for the cache. - * @type {{ humanUsers: number, botUsers: number, humanChannels: number, botChannels: number, lruUserKeysLen: number, lruBotKeysLen: number }} - */ - get stats() { - return { - humanUsers: this.userLocations.size, - botUsers: this.botLocations.size, - humanChannels: this.channelMembers.size, - botChannels: this.botChannelMembers.size, - lruUserKeysLen: this._lruUserKeys.length, - lruBotKeysLen: this._lruBotKeys.length, - }; - } -} diff --git a/src/constants/VoiceStateResolver.mjs b/src/constants/VoiceStateResolver.mjs deleted file mode 100644 index 87a1d2c..0000000 --- a/src/constants/VoiceStateResolver.mjs +++ /dev/null @@ -1,138 +0,0 @@ -/** @module constants/VoiceStateResolver */ - -import { logger } from "./Logger.mjs"; - -/** - * Iterate over a guild's voice states, normalising different data shapes. - * Yields objects with `{ userId, channelId, isBot }` for each member in a voice channel. - * @param {object} guild - Fluxer guild object with a `voice_states` property. - * @yields {{ userId: string, channelId: string, isBot: boolean }} - */ -export function* iterateVoiceStates(guild) { - if (!guild) return; - - const voiceStates = guild.voice_states; - if (!voiceStates) return; - - let entries; - try { - if (Array.isArray(voiceStates)) { - entries = voiceStates; - } else if (typeof voiceStates.values === "function") { - entries = voiceStates.values(); - } else if (typeof voiceStates[Symbol.iterator] === "function") { - entries = voiceStates; - } else { - entries = Object.values(voiceStates); - } - } catch (e) { - logger.warn("[VoiceStateResolver] Failed to enumerate voice states:", e?.message); - return; - } - - for (const state of entries) { - if (!state) continue; - const userId = state.userId ?? state.user_id; - const channelId = state.channelId ?? state.channel_id; - if (!userId || !channelId) continue; - - const member = guild.members?.get?.(userId); - const isBot = member?.user?.bot ?? false; - - yield { userId: String(userId), channelId: String(channelId), isBot }; - } -} - -/** - * Check whether any non-bot humans are currently in a voice channel. - * Checks, in order: VoiceStateCache → ObservedVoiceUsers → guild voice_states → LiveKit participants. - * @param {object} opts - * @param {string} opts.guildId - * @param {string} opts.channelId - * @param {object} [opts.client] - Fluxer client with `guilds`. - * @param {VoiceStateCache} [opts.voiceCache] - * @param {Map} [opts.observedVoiceUsers] - * @param {object} [opts.room] - LiveKit room with `remoteParticipants`. - * @param {string} [opts.botId] - * @returns {boolean} - */ -export function hasHumansInChannel({ guildId, channelId, client, voiceCache, observedVoiceUsers, room, botId }) { - if (!channelId || !guildId) return false; - - - if (voiceCache && typeof voiceCache.hasHumansInChannel === "function") { - if (voiceCache.hasHumansInChannel(guildId, channelId)) return true; - } - - - if (observedVoiceUsers) { - try { - const iterator = typeof observedVoiceUsers.iterateHumanUsers === "function" - ? observedVoiceUsers.iterateHumanUsers() - : observedVoiceUsers.entries(); - - for (const [, info] of iterator) { - const gId = String(info.guildId ?? ""); - const cId = String(info.channelId ?? ""); - if (gId === guildId && cId === channelId) return true; - } - } catch (e) { - logger.warn("[VoiceStateResolver] ObservedVoiceUsers check failed:", e?.message); - } - } - - - if (client) { - try { - const guild = client.guilds?.get?.(guildId); - if (guild) { - for (const vs of iterateVoiceStates(guild)) { - if (vs.channelId === channelId && !vs.isBot) return true; - } - } - } catch (e) { - logger.warn("[VoiceStateResolver] Guild voice_states check failed:", e?.message); - } - } - - - if (room?.isConnected && room.remoteParticipants) { - try { - for (const [, participant] of room.remoteParticipants) { - const pId = participant?.identity || participant?.sid; - if (pId && pId !== botId) return true; - } - } catch (e) { - logger.warn("[VoiceStateResolver] LiveKit participants check failed:", e?.message); - } - } - - return false; -} - -/** - * Get the set of channel IDs that contain at least one human user. - * @param {object} guild - Fluxer guild object. - * @returns {Set} - */ -export function getChannelsWithHumans(guild) { - const channels = new Set(); - for (const vs of iterateVoiceStates(guild)) { - if (!vs.isBot) channels.add(vs.channelId); - } - return channels; -} - -/** - * Get the list of user IDs present in a specific voice channel. - * @param {object} guild - Fluxer guild object. - * @param {string} channelId - * @returns {string[]} - */ -export function getUsersInChannel(guild, channelId) { - const users = []; - for (const vs of iterateVoiceStates(guild)) { - if (vs.channelId === channelId) users.push(vs.userId); - } - return users; -} diff --git a/src/constants/audio/Tuna.mjs b/src/constants/audio/Tuna.mjs deleted file mode 100644 index 0702b39..0000000 --- a/src/constants/audio/Tuna.mjs +++ /dev/null @@ -1,107 +0,0 @@ -/** @module constants/audio/Tuna */ - -import pkg from "follow-redirects"; -const { https } = pkg; - -/** - * Client for the Tuna (Voicemod) sound-effect API. - * @class - */ -class Tuna { - /** @private */ apiKey = null; - - /** - * @param {{ key: string }} auth - Object containing the API key. - */ - constructor(auth) { - this.apiKey = auth.key; - } - - /** - * Perform an authenticated GET request to the Tuna API. - * @private - * @async - * @param {string} path - API path (e.g. `"/v1/sounds/search"`). - * @param {Object} [params={}] - Query-string parameters. - * @returns {Promise} Parsed JSON response. - */ - get(path, params = {}) { - return new Promise((resolve, reject) => { - const qs = new URLSearchParams(params).toString(); - const query = qs ? "?" + qs : ""; - const options = { - method: "GET", - hostname: "tuna-api.voicemod.net", - path: path + query, - headers: { "x-api-key": this.apiKey }, - maxRedirects: 20 - }; - const req = https.request(options, (res) => { - const chunks = []; - res.on("data", (chunk) => { chunks.push(chunk); }); - res.on("end", () => { - try { - resolve(JSON.parse(Buffer.concat(chunks).toString())); - } catch (e) { - reject(new Error(`Tuna API JSON parse error: ${e.message}`)); - } - }); - }); - req.on("error", (error) => { reject(error); }); - req.setTimeout(15_000, () => { - req.destroy(); - reject(new Error("Tuna API request timeout")); - }); - req.end(); - }); - } - - /** - * Search for sound effects. Each result item gains a `download()` method - * that returns the OGG audio stream. - * @async - * @param {string} query - Search term. - * @param {number} [page=1] - * @param {number} [size=10] - * @returns {Promise} Search results with enriched `items` array. - */ - search(query, page = 1, size = 10) { - return this.get("/v1/sounds/search", { size, page, search: query }).then(results => { - results.items = results.items.map(s => { - const oggPath = s.oggPath; - s.download = () => { - return new Promise((resolve, reject) => { - const req = https.get(oggPath, { maxRedirects: 20 }, (r) => { resolve(r); }); - req.on("error", (err) => { reject(err); }); - req.setTimeout(15_000, () => { req.destroy(); reject(new Error("Tuna download timeout")); }); - }); - }; - return s; - }); - return results; - }); - } - - /** - * Fetch a single sound effect by ID. The returned object gains a `download()` - * method that returns the OGG audio stream. - * @async - * @param {string} id - Sound ID. - * @returns {Promise} Sound object with `download()` method. - */ - getSound(id) { - return this.get("/v1/sounds/" + id).then(sound => { - const oggPath = sound.oggPath; - sound.download = () => { - return new Promise((resolve, reject) => { - const req = https.get(oggPath, { maxRedirects: 20 }, (result) => { resolve(result); }); - req.on("error", (err) => { reject(err); }); - req.setTimeout(15_000, () => { req.destroy(); reject(new Error("Tuna download timeout")); }); - }); - }; - return sound; - }); - } -} - -export default Tuna; diff --git a/src/constants/audio/WebMOpusMuxer.mjs b/src/constants/audio/WebMOpusMuxer.mjs deleted file mode 100644 index b6b52c3..0000000 --- a/src/constants/audio/WebMOpusMuxer.mjs +++ /dev/null @@ -1,220 +0,0 @@ -/** @module src/constants/audio/WebMOpusMuxer @description Minimal streaming WebM/Matroska muxer for Opus packets. Produces streams consumable by prism-media's WebmDemuxer (what @fluxerjs/voice uses internally) — no FFmpeg required. */ - -import { Transform } from "node:stream"; - -/** @type {number} @description Opus frame duration in milliseconds (20ms = 960 samples @ 48kHz). */ -export const OPUS_FRAME_MS = 20; - -/** @type {number} @description Blocks per cluster before a new Cluster element is started. */ -const BLOCKS_PER_CLUSTER = 250; - -/** @type {number} @description Force a cluster flush when buffered blocks exceed this size. */ -const CLUSTER_FLUSH_BYTES = 64 * 1024; - -/** - * Encode a Matroska variable-length size integer (finite size). - * @param {number} value - Size to encode (must be >= 0). - * @returns {Buffer} - */ -function encodeSizeVint(value) { - let length = 1; - while (value > 2 ** (7 * length) - 1 && length < 8) length++; - const buf = Buffer.alloc(length); - for (let i = length - 1; i >= 0; i--) { - buf[i] = value & 0xff; - value = Math.floor(value / 256); - } - buf[0] |= 1 << (8 - length); - return buf; -} - -/** - * Build a single EBML element from an ID hex string and a payload Buffer. - * @param {string} idHex - EBML element ID as hex (e.g. "1a45dfa3"). - * @param {Buffer} payload - * @returns {Buffer} - */ -function element(idHex, payload) { - return Buffer.concat([Buffer.from(idHex, "hex"), encodeSizeVint(payload.length), payload]); -} - -/** - * Encode an unsigned integer EBML payload using minimal bytes. - * @param {number} value - * @returns {Buffer} - */ -function uintPayload(value) { - let bytes = 1; - while (value >= 2 ** (8 * bytes)) bytes++; - const buf = Buffer.alloc(bytes); - buf.writeUIntBE(value, 0, bytes); - return buf; -} - -/** - * Build the OpusHead codec private data (Matroska-embedded OpusHead). - * @param {number} sampleRate - Input sample rate (48000). - * @param {number} channels - Channel count (2). - * @returns {Buffer} - */ -export function buildOpusHead(sampleRate, channels) { - const buf = Buffer.alloc(19); - buf.write("OpusHead", 0, "ascii"); - buf.writeUInt8(1, 8); // version - buf.writeUInt8(channels, 9); - buf.writeUInt16LE(0, 10); // pre-skip (we encode ourselves; no trimming) - buf.writeUInt32LE(sampleRate, 12); - buf.writeInt16LE(0, 16); // output gain - buf.writeUInt8(0, 18); // mapping family (mono/stereo) - return buf; -} - -/** - * Build the WebM stream header: EBML + Segment start + Info + Tracks. - * The Segment element uses an unknown (streaming) size so clusters can be - * appended indefinitely. - * @param {number} sampleRate - * @param {number} channels - * @returns {Buffer} - */ -function buildHeader(sampleRate, channels) { - const ebml = element("1a45dfa3", Buffer.concat([ - element("4286", uintPayload(1)), // EBMLVersion - element("42f7", uintPayload(1)), // EBMLReadVersion - element("42f2", uintPayload(4)), // EBMLMaxIDLength - element("42f3", uintPayload(8)), // EBMLMaxSizeLength - element("4282", Buffer.from("webm", "ascii")), // DocType - element("4287", uintPayload(2)), // DocTypeVersion - element("4285", uintPayload(2)), // DocTypeReadVersion - ])); - - const info = element("1549a966", Buffer.concat([ - element("2ad7b1", uintPayload(1000000)), // TimecodeScale (1ms) - element("4d80", Buffer.from("fluxer-remix", "ascii")),// MuxingApp - element("5741", Buffer.from("fluxer-remix", "ascii")),// WritingApp - ])); - - const floatBuf = Buffer.alloc(4); - floatBuf.writeFloatBE(sampleRate, 0); - const audio = element("e1", Buffer.concat([ - element("b5", floatBuf), // SamplingFrequency - element("9f", uintPayload(channels)), // Channels - ])); - - const trackEntry = element("ae", Buffer.concat([ - element("d7", uintPayload(1)), // TrackNumber (must be 1 — demuxer masks data[0] & 0xF) - element("73c5", uintPayload(1)), // TrackUID - element("83", uintPayload(2)), // TrackType: audio - element("86", Buffer.from("A_OPUS", "ascii")), // CodecID - element("63a2", buildOpusHead(sampleRate, channels)), // CodecPrivate: OpusHead - audio, - ])); - const tracks = element("1654ae6b", trackEntry); - - // Streaming Segment size: a huge finite vint (0x01 + 7x0xFF = 2^56-1). The - // canonical all-0xFF unknown-size marker is misparsed by prism-media's - // vintLength (it reads 0xFF as a 1-byte vint), so we use this equivalent form. - const segmentStart = Buffer.concat([ - Buffer.from("18538067", "hex"), - Buffer.from([0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), - ]); - - return Buffer.concat([ebml, segmentStart, info, tracks]); -} - -/** - * Build a SimpleBlock element for one Opus packet. - * @param {Buffer} packet - Raw Opus packet. - * @param {number} relTimeMs - Cluster-relative timestamp in ms. - * @returns {Buffer} - */ -function buildSimpleBlock(packet, relTimeMs) { - const clamped = Math.max(-32768, Math.min(32767, relTimeMs)); - const header = Buffer.from([0x81, (clamped >> 8) & 0xff, clamped & 0xff, 0x80]); - return element("a3", Buffer.concat([header, packet])); -} - -/** - * Streaming WebM muxer: consumes Opus packets (object mode) and emits a - * WebM/Opus byte stream compatible with prism-media's WebmDemuxer — the exact - * format @fluxerjs/voice's VoiceConnection.play() expects as input. - * @extends {Transform} - */ -export class WebMOpusMuxer extends Transform { - /** - * @param {object} [options] - * @param {number} [options.sampleRate=48000] - * @param {number} [options.channels=2] - */ - constructor(options = {}) { - super({ writableObjectMode: true }); - this._sampleRate = options.sampleRate ?? 48000; - this._channels = options.channels ?? 2; - this._header = buildHeader(this._sampleRate, this._channels); - this._blocks = []; - this._blocksBytes = 0; - this._blockIndex = 0; - this._clusterIndex = 0; - this._headerSent = false; - } - - /** - * Feed one Opus packet into the current cluster. - * @param {Buffer} packet - */ - _addBlock(packet) { - if (!this._headerSent) { - this.push(this._header); - this._headerSent = true; - } - const relTime = (this._blockIndex % BLOCKS_PER_CLUSTER) * OPUS_FRAME_MS; - const block = buildSimpleBlock(packet, relTime); - this._blocks.push(block); - this._blocksBytes += block.length; - this._blockIndex++; - if (this._blocks.length >= BLOCKS_PER_CLUSTER || this._blocksBytes >= CLUSTER_FLUSH_BYTES) { - this._flushCluster(); - } - } - - /** Emit the current cluster as a complete EBML element. */ - _flushCluster() { - if (this._blocks.length === 0) return; - const timecode = element("e7", uintPayload(this._clusterIndex * BLOCKS_PER_CLUSTER * OPUS_FRAME_MS)); - const cluster = element("1f43b675", Buffer.concat([timecode, ...this._blocks])); - this._blocks = []; - this._blocksBytes = 0; - this._clusterIndex++; - this.push(cluster); - } - - /** - * @param {Buffer} packet - * @param {string} _encoding - * @param {Function} callback - * @protected - */ - _transform(packet, _encoding, callback) { - try { - if (Buffer.isBuffer(packet) && packet.length > 0) { - this._addBlock(packet); - } - callback(); - } catch (err) { - callback(err); - } - } - - /** - * @param {Function} callback - * @protected - */ - _final(callback) { - try { - this._flushCluster(); - callback(); - } catch (err) { - callback(err); - } - } -} diff --git a/src/constants/providers.mjs b/src/constants/providers.mjs deleted file mode 100644 index e836e03..0000000 --- a/src/constants/providers.mjs +++ /dev/null @@ -1,122 +0,0 @@ -/** @module constants/providers */ - -/** - * Map of provider shorthand keys to their Lavalink search prefix and display label. - * Both short aliases (e.g. `scld`) and full names (e.g. `soundcloud`) map to the same - * prefix/label pair. - * @type {Object} - */ -export const PROVIDERS = { - yt: { prefix: "ytsearch", label: "YouTube" }, - ytm: { prefix: "ytmsearch", label: "YouTube Music" }, - scld: { prefix: "scsearch", label: "SoundCloud" }, - sc: { prefix: "scsearch", label: "SoundCloud" }, - sp: { prefix: "spsearch", label: "Spotify" }, - spotify: { prefix: "spsearch", label: "Spotify" }, - am: { prefix: "amsearch", label: "Apple Music" }, - apple: { prefix: "amsearch", label: "Apple Music" }, - dz: { prefix: "dzsearch", label: "Deezer" }, - deezer: { prefix: "dzsearch", label: "Deezer" }, - td: { prefix: "tdsearch", label: "Tidal" }, - tidal: { prefix: "tdsearch", label: "Tidal" }, - bc: { prefix: "bcsearch", label: "Bandcamp" }, - bandcamp: { prefix: "bcsearch", label: "Bandcamp" }, - adm: { prefix: "admsearch", label: "Audiomack" }, - audiomack: { prefix: "admsearch", label: "Audiomack" }, - gaana: { prefix: "gaanasearch", label: "Gaana" }, - js: { prefix: "jssearch", label: "JioSaavn" }, - jiosaavn: { prefix: "jssearch", label: "JioSaavn" }, - lf: { prefix: "lfsearch", label: "Last.fm" }, - lastfm: { prefix: "lfsearch", label: "Last.fm" }, - pd: { prefix: "pdsearch", label: "Pandora" }, - pandora: { prefix: "pdsearch", label: "Pandora" }, - vk: { prefix: "vksearch", label: "VK Music" }, - mc: { prefix: "mcsearch", label: "Mixcloud" }, - mixcloud: { prefix: "mcsearch", label: "Mixcloud" }, - nc: { prefix: "ncsearch", label: "NicoVideo" }, - nicovideo: { prefix: "ncsearch", label: "NicoVideo" }, - bb: { prefix: "bilibili", label: "Bilibili" }, - bilibili: { prefix: "bilibili", label: "Bilibili" }, - sh: { prefix: "shsearch", label: "Shazam" }, - shazam: { prefix: "shsearch", label: "Shazam" }, - sl: { prefix: "slsearch", label: "Songlink" }, - songlink: { prefix: "slsearch", label: "Songlink" }, - qb: { prefix: "qbsearch", label: "Qobuz" }, - qobuz: { prefix: "qbsearch", label: "Qobuz" }, - ym: { prefix: "ymsearch", label: "Yandex Music" }, - yandex: { prefix: "ymsearch", label: "Yandex Music" }, - au: { prefix: "ausearch", label: "Audius" }, - audius: { prefix: "ausearch", label: "Audius" }, - az: { prefix: "azsearch", label: "Amazon Music" }, - amazon: { prefix: "azsearch", label: "Amazon Music" }, - ag: { prefix: "agsearch", label: "Anghami" }, - anghami: { prefix: "agsearch", label: "Anghami" }, - bk: { prefix: "bksearch", label: "Bluesky" }, - bluesky: { prefix: "bksearch", label: "Bluesky" }, - ytrec: { prefix: "ytrec", label: "YouTube (recommended)" }, - sprec: { prefix: "sprec", label: "Spotify (recommended)" }, - dzrec: { prefix: "dzrec", label: "Deezer (recommended)" }, - tdrec: { prefix: "tdrec", label: "Tidal (recommended)" }, - jsrec: { prefix: "jsrec", label: "JioSaavn (recommended)" }, - vkrec: { prefix: "vkrec", label: "VK Music (recommended)" }, - gtts: { prefix: "gtts", label: "Google TTS" }, - tts: { prefix: "gtts", label: "Google TTS" }, - ftts: { prefix: "ftts", label: "Flowery TTS" }, -}; - -/** - * Shorthand-to-label lookup derived from {@link PROVIDERS}. - * @type {Object} - */ -export const PROVIDER_NAMES = Object.fromEntries( - Object.entries(PROVIDERS).map(([k, v]) => [k, v.label]) -); - -/** - * Complete list of accepted provider keys for command choices. - * @type {string[]} - */ -export const PROVIDER_CHOICES = [ - "ytm", "yt", "scld", "sc", - "sp", "spotify", - "am", "apple", - "dz", "deezer", - "td", "tidal", - "bc", "bandcamp", - "adm", "audiomack", - "gaana", - "js", "jiosaavn", - "lf", "lastfm", - "pd", "pandora", - "vk", - "mc", "mixcloud", - "nc", "nicovideo", - "bb", "bilibili", - "sh", "shazam", - "sl", "songlink", - "qb", "qobuz", - "ym", "yandex", - "au", "audius", - "az", "amazon", - "ag", "anghami", - "bk", "bluesky", - "ytrec", "sprec", "dzrec", "tdrec", "jsrec", "vkrec", - "gtts", "tts", "ftts", -]; - -/** - * Parse an inline provider prefix from raw query text (e.g. `"yt: never gonna give you up"`). - * If the prefix is recognised, splits into provider key and remaining query; - * otherwise returns the full string as the query with `provider: null`. - * @param {string} raw - The raw user input string. - * @returns {{ provider: string|null, query: string }} - */ -export function parseInlineProvider(raw) { - const match = raw.match(/^([a-z]+):\s*(.+)$/i); - if (!match) return { provider: null, query: raw.trim() }; - const maybeProvider = match[1].toLowerCase(); - if (PROVIDER_CHOICES.includes(maybeProvider)) { - return { provider: maybeProvider, query: match[2].trim() }; - } - return { provider: null, query: raw.trim() }; -} diff --git a/src/music/PlayerLifecycleMixin.mjs b/src/music/PlayerLifecycleMixin.mjs index 852c115..f1987f7 100644 --- a/src/music/PlayerLifecycleMixin.mjs +++ b/src/music/PlayerLifecycleMixin.mjs @@ -287,7 +287,7 @@ const PlayerLifecycleMixin = { if (!botHasVoicePermissions(this.commands?.client, cid)) { message.reply( - this._t(message, "responses.join.joinFailedPerms", { channel: `<#${cleanId(cid)}>` }) + this._t(message, "responses.join.joinFailedPerms", { channel: cleanId(cid) }) ); return null; } @@ -539,7 +539,7 @@ const PlayerLifecycleMixin = { errorMsg = this._t(message, "responses.join.joinFailedGeneric"); } } else if (errCode === "PERMISSION") { - errorMsg = this._t(message, "responses.join.joinFailedPerms", { channel: `<#${cleanChannelId}>` }); + errorMsg = this._t(message, "responses.join.joinFailedPerms", { channel: cleanChannelId }); } else if (errCode === "NOT_FOUND") { errorMsg = this._t(message, "responses.join.joinFailedNotFound"); } else if (errCode === "TIMEOUT") {