From 253d11cd5734ec9d87cc61e14d4f610bc4e7afe2 Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Wed, 9 Sep 2026 02:04:33 +0300 Subject: [PATCH] =?UTF-8?q?Remix=20=E2=80=94=20the=20complete=20rewrite?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Upgrades the bot from fluxerjs 2.2 to 3.0 and restructures everything into a layered architecture (~28K lines): Dependencies: - @fluxerjs/core, util, voice: ^2.2.0 -> ^3.0.0 (typed events, PartialMessage payloads, camelCase API) - @fluxerjs/sharding ^3.0.0 added — built-in sharding mode (shard.mjs, one process per shard) - @discordjs/opus dropped — opusscript + prism-media cover encoding Architecture: - commands: every command split into submodules (player, lastfm, settings, debug) with a shared CommandBuilder/Loader/Handler core - ui: embeds, paginators, help command, permission checks - voice: gateway event routing, rejoin/247 boot recovery, state resolver - music: player split into Queue/Search/Playback/Display mixins, stream pipeline + WebM/Opus muxer (no FFmpeg needed) - dashboard: Redis pub/sub, RPC handlers, serializers - db: MySQL manager + per-guild settings - services: LastFm manager split into focused mixins - utils: sharding, 24/7 helpers, API client Runtime fixes over v2: - Redis v5 reconnect: capped numeric backoff (0.5s ramp to 15s), never exhausts, auto-recovers when the server comes back - Redis main/subscriber clients connect in parallel; clean shutdown - Logger storm guard: identical error/warn lines deduped in a 60s window - self-deaf fix on voice join - config example uses redis://127.0.0.1 (avoids IPv6 ENETUNREACH) Housekeeping: dead code removed (Tuna.mjs + follow-redirects dep), .gitignore added (config.json, .env, node_modules, runtime state). --- .gitignore | 15 +- README.md | 265 +- commands/autoplay.mjs | 6 +- commands/clear.mjs | 4 +- commands/debug.mjs | 623 +--- commands/debug/consts.mjs | 10 + commands/debug/gateway.mjs | 134 + commands/debug/rejoin.mjs | 259 ++ commands/debug/voiceDiagnostic.mjs | 236 ++ commands/eval.mjs | 10 +- commands/filter.mjs | 10 +- commands/forceleave.mjs | 4 +- commands/invite.mjs | 4 +- commands/join.mjs | 4 +- commands/lastfm.mjs | 2542 +---------------- commands/lastfm/account.mjs | 245 ++ commands/lastfm/discovery.mjs | 372 +++ commands/lastfm/help.mjs | 99 + commands/lastfm/index.mjs | 16 + commands/lastfm/info.mjs | 505 ++++ commands/lastfm/listening.mjs | 358 +++ commands/lastfm/playback.mjs | 326 +++ commands/lastfm/shared.mjs | 80 + commands/lastfm/tags.mjs | 337 +++ commands/lastfm/whoknows.mjs | 525 ++++ commands/leave.mjs | 8 +- commands/list.mjs | 4 +- commands/loop.mjs | 4 +- commands/lyrics.mjs | 10 +- commands/move.mjs | 2 +- commands/np.mjs | 4 +- commands/pause.mjs | 4 +- commands/play.mjs | 12 +- commands/player.mjs | 291 +- commands/player/consts.mjs | 38 + commands/player/embed.mjs | 96 + commands/player/index.mjs | 10 + commands/player/lyrics.mjs | 166 ++ commands/playnext.mjs | 6 +- commands/radio.mjs | 8 +- commands/reload.mjs | 4 +- commands/remove.mjs | 2 +- commands/resume.mjs | 4 +- commands/search.mjs | 10 +- commands/seek.mjs | 8 +- commands/servers.mjs | 8 +- commands/settings.mjs | 463 +-- commands/settings/channels247.mjs | 198 ++ commands/settings/setters.mjs | 136 + commands/settings/utils.mjs | 146 + commands/shuffle.mjs | 4 +- commands/skip.mjs | 4 +- commands/stats.mjs | 50 +- commands/support.mjs | 4 +- commands/test.mjs | 6 +- commands/thumbnail.mjs | 4 +- commands/trackopt.mjs | 10 +- commands/volume.mjs | 6 +- commands/volumedefault.mjs | 6 +- commands/vote.mjs | 12 +- config_example.json | 10 +- docker/Dockerfile | 2 +- docker/docker-entrypoint.sh | 4 + index.mjs | 1037 +------ package-lock.json | 1741 ----------- package.json | 9 +- settings/README.md | 4 +- settings/Settings.mjs | 2 +- settings/migrate.mjs | 4 +- shard.mjs | 157 + src/CommandHandler.mjs | 927 ------ src/FluxerAudioBridge.mjs | 879 ------ src/GatewayHandler.mjs | 1473 ---------- src/LastFmManager.mjs | 2324 --------------- src/MessageHandler.mjs | 1164 -------- src/Player.mjs | 2105 -------------- src/commands/CommandBuilder.mjs | 166 ++ src/commands/CommandHandler.mjs | 569 ++++ src/commands/CommandLoader.mjs | 123 + src/commands/HelpHandler.mjs | 203 ++ src/commands/Option.mjs | 279 ++ src/commands/PrefixManager.mjs | 35 + src/commands/index.mjs | 14 + src/constants/VoiceStateResolver.mjs | 8 +- src/core/Bot.mjs | 588 ++++ src/core/BotVoiceMixin.mjs | 511 ++++ src/core/Locale.mjs | 210 ++ src/core/Logger.mjs | 199 ++ src/dashboard/Dashboard.mjs | 668 +---- src/dashboard/RedisHandler.mjs | 134 +- src/dashboard/RpcHandlersMixin.mjs | 362 +++ src/dashboard/Serializers.mjs | 300 ++ src/dashboard/index.mjs | 6 + src/db/DatabaseManager.mjs | 82 + src/{ => db}/Settings.mjs | 4 +- src/{ => music}/LavalinkManager.mjs | 71 +- src/music/PlayerEventsMixin.mjs | 298 ++ .../PlayerLifecycleMixin.mjs} | 530 +--- src/music/PlayerManager.mjs | 229 ++ src/music/audio/FluxerAudioBridge.mjs | 419 +++ src/music/audio/HttpStreams.mjs | 185 ++ src/music/audio/StreamPipeline.mjs | 326 +++ src/music/audio/Tuna.mjs | 107 + src/music/audio/WebMOpusMuxer.mjs | 220 ++ src/music/audio/index.mjs | 9 + src/music/player/DisplayMixin.mjs | 292 ++ src/music/player/PlaybackMixin.mjs | 631 ++++ src/music/player/Player.mjs | 993 +++++++ src/music/player/Queue.mjs | 168 ++ src/music/player/SearchMixin.mjs | 484 ++++ src/music/player/index.mjs | 9 + src/{ => music}/probe.mjs | 4 +- src/music/providers.mjs | 122 + src/{ => services}/FluxerListManager.mjs | 6 +- src/{ => services}/TrackOptionsManager.mjs | 4 +- src/services/lastfm/LastFmManager.mjs | 287 ++ src/services/lastfm/ScrobblingMixin.mjs | 98 + src/services/lastfm/ServerStatsMixin.mjs | 460 +++ src/services/lastfm/TrackQueriesMixin.mjs | 795 ++++++ src/services/lastfm/UserQueriesMixin.mjs | 593 ++++ src/services/lastfm/UserStoreMixin.mjs | 121 + src/services/lastfm/constants.mjs | 55 + src/services/lastfm/index.mjs | 10 + src/services/lastfm/urlUtils.mjs | 56 + src/ui/Embeds.mjs | 50 + src/ui/HelpCommand.mjs | 254 ++ src/ui/MessageHandler.mjs | 583 ++++ src/ui/Paginators.mjs | 394 +++ src/ui/Permissions.mjs | 27 + src/ui/Wrappers.mjs | 191 ++ src/ui/index.mjs | 15 + src/utils/API.mjs | 100 + src/utils/Helpers247.mjs | 39 + src/utils/ShardingUtils.mjs | 140 + src/utils/UI.mjs | 37 + src/{ => utils}/Utils.mjs | 6 +- src/utils/mixins.mjs | 33 + src/voice/VoiceStateCache.mjs | 589 ++++ src/voice/VoiceStateResolver.mjs | 138 + src/voice/gateway/GatewayHandler.mjs | 602 ++++ src/voice/gateway/GuildSync.mjs | 391 +++ src/voice/gateway/RejoinManager.mjs | 169 ++ src/voice/gateway/VoiceStateRouting.mjs | 435 +++ src/voice/gateway/index.mjs | 8 + storage/locales/bot/ar-SA.json | 1 + storage/locales/bot/ckb.json | 1 + storage/locales/bot/de-DE.json | 1 + storage/locales/bot/en.json | 1 + storage/locales/bot/pt-BR.json | 1 + storage/locales/bot/tr.json | 1 + 150 files changed, 19935 insertions(+), 16894 deletions(-) create mode 100644 commands/debug/consts.mjs create mode 100644 commands/debug/gateway.mjs create mode 100644 commands/debug/rejoin.mjs create mode 100644 commands/debug/voiceDiagnostic.mjs create mode 100644 commands/lastfm/account.mjs create mode 100644 commands/lastfm/discovery.mjs create mode 100644 commands/lastfm/help.mjs create mode 100644 commands/lastfm/index.mjs create mode 100644 commands/lastfm/info.mjs create mode 100644 commands/lastfm/listening.mjs create mode 100644 commands/lastfm/playback.mjs create mode 100644 commands/lastfm/shared.mjs create mode 100644 commands/lastfm/tags.mjs create mode 100644 commands/lastfm/whoknows.mjs create mode 100644 commands/player/consts.mjs create mode 100644 commands/player/embed.mjs create mode 100644 commands/player/index.mjs create mode 100644 commands/player/lyrics.mjs create mode 100644 commands/settings/channels247.mjs create mode 100644 commands/settings/setters.mjs create mode 100644 commands/settings/utils.mjs delete mode 100644 package-lock.json create mode 100644 shard.mjs delete mode 100644 src/CommandHandler.mjs delete mode 100644 src/FluxerAudioBridge.mjs delete mode 100644 src/GatewayHandler.mjs delete mode 100644 src/LastFmManager.mjs delete mode 100644 src/MessageHandler.mjs delete mode 100644 src/Player.mjs create mode 100644 src/commands/CommandBuilder.mjs create mode 100644 src/commands/CommandHandler.mjs create mode 100644 src/commands/CommandLoader.mjs create mode 100644 src/commands/HelpHandler.mjs create mode 100644 src/commands/Option.mjs create mode 100644 src/commands/PrefixManager.mjs create mode 100644 src/commands/index.mjs create mode 100644 src/core/Bot.mjs create mode 100644 src/core/BotVoiceMixin.mjs create mode 100644 src/core/Locale.mjs create mode 100644 src/core/Logger.mjs create mode 100644 src/dashboard/RpcHandlersMixin.mjs create mode 100644 src/dashboard/Serializers.mjs create mode 100644 src/dashboard/index.mjs create mode 100644 src/db/DatabaseManager.mjs rename src/{ => db}/Settings.mjs (99%) rename src/{ => music}/LavalinkManager.mjs (90%) create mode 100644 src/music/PlayerEventsMixin.mjs rename src/{PlayerManager.mjs => music/PlayerLifecycleMixin.mjs} (54%) create mode 100644 src/music/PlayerManager.mjs create mode 100644 src/music/audio/FluxerAudioBridge.mjs create mode 100644 src/music/audio/HttpStreams.mjs create mode 100644 src/music/audio/StreamPipeline.mjs create mode 100644 src/music/audio/Tuna.mjs create mode 100644 src/music/audio/WebMOpusMuxer.mjs create mode 100644 src/music/audio/index.mjs create mode 100644 src/music/player/DisplayMixin.mjs create mode 100644 src/music/player/PlaybackMixin.mjs create mode 100644 src/music/player/Player.mjs create mode 100644 src/music/player/Queue.mjs create mode 100644 src/music/player/SearchMixin.mjs create mode 100644 src/music/player/index.mjs rename src/{ => music}/probe.mjs (93%) create mode 100644 src/music/providers.mjs rename src/{ => services}/FluxerListManager.mjs (96%) rename src/{ => services}/TrackOptionsManager.mjs (98%) create mode 100644 src/services/lastfm/LastFmManager.mjs create mode 100644 src/services/lastfm/ScrobblingMixin.mjs create mode 100644 src/services/lastfm/ServerStatsMixin.mjs create mode 100644 src/services/lastfm/TrackQueriesMixin.mjs create mode 100644 src/services/lastfm/UserQueriesMixin.mjs create mode 100644 src/services/lastfm/UserStoreMixin.mjs create mode 100644 src/services/lastfm/constants.mjs create mode 100644 src/services/lastfm/index.mjs create mode 100644 src/services/lastfm/urlUtils.mjs create mode 100644 src/ui/Embeds.mjs create mode 100644 src/ui/HelpCommand.mjs create mode 100644 src/ui/MessageHandler.mjs create mode 100644 src/ui/Paginators.mjs create mode 100644 src/ui/Permissions.mjs create mode 100644 src/ui/Wrappers.mjs create mode 100644 src/ui/index.mjs create mode 100644 src/utils/API.mjs create mode 100644 src/utils/Helpers247.mjs create mode 100644 src/utils/ShardingUtils.mjs create mode 100644 src/utils/UI.mjs rename src/{ => utils}/Utils.mjs (98%) create mode 100644 src/utils/mixins.mjs create mode 100644 src/voice/VoiceStateCache.mjs create mode 100644 src/voice/VoiceStateResolver.mjs create mode 100644 src/voice/gateway/GatewayHandler.mjs create mode 100644 src/voice/gateway/GuildSync.mjs create mode 100644 src/voice/gateway/RejoinManager.mjs create mode 100644 src/voice/gateway/VoiceStateRouting.mjs create mode 100644 src/voice/gateway/index.mjs diff --git a/.gitignore b/.gitignore index 9929f2f..3e0efe9 100644 --- a/.gitignore +++ b/.gitignore @@ -1,8 +1,9 @@ -node_modules/ -storage/data config.json -settings.json -remix-settings.json -test_data/ -*.code-workspace -.idea/ +.env +storage/stats-cache.json +storage/locales/user/ +*.log +logs/ +.DS_Store +Thumbs.db +.idea \ No newline at end of file diff --git a/README.md b/README.md index 1ce0f91..167712e 100644 --- a/README.md +++ b/README.md @@ -42,6 +42,7 @@ - [Dashboard Setup (Optional)](#-dashboard-setup-optional) - [Configuration Reference](#-configuration-reference) - [Project Architecture](#-project-architecture) +- [The Layered Codebase](#-the-layered-codebase) - [Localization](#-localization) - [Scripts](#-npm-scripts) - [Credits](#-credits--license) @@ -54,6 +55,37 @@ Remix is a free and open-source music bot for [Fluxer](https://fluxer.app), buil We believe music features shouldn't be locked behind paywalls — **all commands on Remix are 100% free and always will be.** +### Fluxer.js 3.0 + +Remix runs on **`@fluxerjs/core` / `@fluxerjs/util` / `@fluxerjs/voice` 3.0.0** plus **`@fluxerjs/sharding` 3.0.0** (see the [changelog](https://fluxer.js.org/changelog/)). The v3 DX overhaul required only five code-level changes in this codebase — everything else (event names, gateway opcodes, permission flags, the voice/LiveKit API, `EmbedBuilder`, message `reply`/`edit`/`react`, the raw `VOICE_STATE_UPDATE` / `VoiceStatesSync` payloads this bot tracks) is unchanged between 2.2 and 3.0: + +1. `package.json` — the three `@fluxerjs/*` ranges moved from `^2.2.0` to `^3.0.0` (a `^2.2.0` range will not install 3.0). +2. `src/core/Bot.mjs` — the `Client` `presence` option now uses the normalized v3 shape (`customStatus`/`emojiName`/`emojiId`) instead of the 2.2 wire format (`custom_status`); the deprecated no-op `suppressIntentWarning` option was dropped. +3. `src/voice/gateway/GatewayHandler.mjs` — the presence-rotation sender wraps its `client.ws` access in a try/catch, because 3.0 exposes `client.ws` as a getter that throws when the gateway is not connected (2.2 exposed a plain optional). The rotation payload itself stays in wire format because it sends opcode 3 straight to the shard. +4. `src/ui/MessageHandler.mjs` — `joinChannel()` checks `channel.isGuild?.()` first (the new ChannelType-based guard) and keeps the legacy `"guildId" in channel` check as a fallback for stub objects. +5. `src/utils/ShardingUtils.mjs` (new) — 3.0 removed the WebSocketManager's `shards` Map property in favour of `getShards()`/`getShard()` methods, which had silently disabled the bot's raw-socket listeners (they no-op'd behind their existing guards). All five readers — Bot.mjs's WS error handlers, GatewayHandler's raw listener and presence sender, LavalinkManager's payload routing and raw listener — now go through version-agnostic helpers that also make them shard-aware (see below). + +Two 3.0 library-level notes that need no code change here: the WS manager no longer emits `shardCreate` (the bot's 5-second handler re-arm loop covers re-attachment), and `Guild.description` was removed from the core structures (the dashboard serializer already null-guards it, so server descriptions simply render empty). Passing `intents` or `suppressIntentWarning` inside `config["fluxer.js"]` is still accepted — both are documented deprecated no-ops in 3.0. + +### Sharding (optional) + +`@fluxerjs/sharding` 3.0.0 (beta) is wired in as an **opt-in** layer — the default single-process boot (`npm start` / `node index.mjs`) is byte-for-byte unchanged, and none of the sharding code paths activate unless the process was actually forked by the manager (it sets `FLUXER_SHARD_IDS` *and* provides an IPC channel; manually exporting the variables does nothing). + +- **Supervisor:** `node shard.mjs` (or `npm run shard`) forks one child per shard slice, each running the ordinary `index.mjs` boot. The manager owns the shared per-IP IDENTIFY budget so children can never collectively exceed the gateway limit, respawns dead children, and exposes `broadcastEval` / `fetchClientValues` / `respawnAll`. +- **Child side:** `src/core/Bot.mjs` attaches the library's `ShardClientUtil` before `login()` (it applies the shard slice to the client options) and calls `notifyReady()` after login so the supervisor's spawn promise resolves. A failed attach under a manager is fatal by design — without its slice the child would identify as shard 0 like every other child and thrash the gateway sessions. +- **Guild→shard routing:** opcode-4 voice payloads from LavalinkManager now target `shardIdForGuildId(guildId)` instead of hardcoded shard 0, presence updates fan out to every gateway shard in the process, and raw-socket listeners attach to *all* local shard sockets. Unsharded, every one of these degrades to exactly the previous shard-0 behavior. + +Configuration (config.json, all optional — defaults shown): + +```json +"sharding": { "totalShards": 1, "shardsPerProcess": 1, "respawn": true, + "spawnTimeout": 30000, "spawnDelay": 5000 } +``` + +`FLUXER_TOTAL_SHARDS` / `FLUXER_SHARDS_PER_PROCESS` env vars override the config (useful in Docker, where you switch the container command to `node shard.mjs`). Prefer an explicit `totalShards` — Fluxer's `/gateway/bot` always reports `shards: 1`, so there is no reliable `"auto"`. + +Beta caveats worth knowing: DMs and guild-less events only reach shard 0 (library limitation); each child opens its own MySQL/Redis/Lavalink connections and its own dashboard RPC subscription, so the dashboard is currently single-process-first — guilds on other shards won't be reachable from it, and concurrent `storage/stats.json` writes across children can race. The stock `node index.mjs` deployment has none of these issues. + --- ## How Audio Playback Works @@ -67,7 +99,7 @@ Understanding the pipeline helps when debugging or contributing: ├─ /v4/loadstream → magic-byte sniffing: │ • WebM (1A45DFA3) → passthrough to LiveKit │ • OggS → OggDemuxer → WebMOpusMuxer (remux, no re-encode) - │ • raw PCM → OpusEncoder (opusscript / @discordjs/opus) + │ • raw PCM → OpusEncoder (opusscript) │ → WebMOpusMuxer → LiveKit └─ conn.play() → @fluxerjs/voice LiveKit connection (bot publishes audio as a LiveKit participant) @@ -393,79 +425,175 @@ Key configuration options in `config.json`: ``` fluxer/ -├── index.mjs # Entry point — Remix class, boot sequence, alone-check, -│ # presence rotation, error handling, graceful shutdown +├── index.mjs # Entry point — creates the Remix instance, process-level +│ # error guards, and signal-based graceful shutdown +├── shard.mjs # OPTIONAL sharding supervisor (@fluxerjs/sharding) — forks +│ # one child process per shard slice, each running index.mjs ├── config_example.json # Configuration template ├── package.json -├── commands/ # 37 command modules (one file per command) -│ ├── play.mjs # Play a track or playlist (Last.fm categories, providers) -│ ├── player.mjs # Interactive emoji control panel with live progress -│ ├── settings.mjs # Per-guild settings management (+ prefix/247 shortcuts) -│ ├── lyrics.mjs # Synced lyrics from NodeLink -│ ├── filter.mjs # Audio filter controls -│ ├── radio.mjs # Radio station management -│ ├── debug.mjs # Voice connection debugger (owner only) -│ ├── lastfm.mjs # Last.fm linking, scrobbling, profiles, leaderboards -│ ├── trackopt.mjs # Per-track start/end time options (set/get/remove/list) -│ └── ... # All other commands -├── src/ -│ ├── CommandHandler.mjs # Command framework — builder, options, requirements, -│ │ # cooldowns, prefix manager, loader -│ ├── MessageHandler.mjs # Replies/embeds, reaction observers, pagination, help -│ ├── PlayerManager.mjs # Player lifecycle, VC resolution & permission checks, -│ │ # dashboard broadcasts, Last.fm scrobble wiring -│ ├── Player.mjs # Core per-channel player — queue, playback, filters, -│ │ # search sessions, autoplay, error circuit breaker -│ ├── FluxerAudioBridge.mjs # Audio engine — NodeLink REST streams → sniff/remux/ -│ │ # encode → LiveKit publishing -│ ├── LavalinkManager.mjs # lavalink-client wrapper (NodeLink mode) — search, -│ │ # voice payload caching, node readiness -│ ├── GatewayHandler.mjs # Raw WS events, voice-state routing, guild lifecycle, -│ │ # 24/7 rejoin & rejoin retries -│ ├── LastFmManager.mjs # Last.fm API client — auth, scrobbling, user data, -│ │ # MySQL persistence (lastfm_users / lastfm_stats) -│ ├── FluxerListManager.mjs # FluxerList voters API client (5-min TTL cache) -│ ├── TrackOptionsManager.mjs # Per-user per-track start/end times (MySQL + LRU cache) -│ ├── Settings.mjs # RemoteSettingsManager — MySQL-backed per-guild settings -│ │ # with debounced JSON_SET writes -│ ├── Utils.mjs # Shared utilities (IDs, durations, markdown, progress bar) -│ ├── probe.mjs # ffprobe wrapper for audio stream info (radio metadata) -│ ├── constants/ -│ │ ├── Logger.mjs # Structured logger with per-category control -│ │ ├── Locale.mjs # i18n translation engine -│ │ ├── Helpers247.mjs # 24/7 mode helpers -│ │ ├── UI.mjs # Emoji + UI constants -│ │ ├── providers.mjs # 45+ audio source provider definitions -│ │ ├── VoiceStateCache.mjs # Dual LRU voice-state caches (humans / bots) -│ │ ├── VoiceStateResolver.mjs # Voice-state normalization + humans-in-channel check -│ │ └── audio/ -│ │ └── WebMOpusMuxer.mjs # Streaming EBML/Matroska muxer (Opus → WebM for LiveKit) -│ └── dashboard/ -│ ├── Dashboard.mjs # Dashboard backend — Redis RPC, player/user serializers, -│ │ # remote-control actions with authorization checks -│ ├── DatabaseManager.mjs # mysql2 pool + parameterized queries + bcrypt helpers -│ └── RedisHandler.mjs # Redis pub/sub RPC transport with reconnect handling -├── settings/ -│ ├── Settings.mjs # Re-export of src/Settings.mjs classes -│ ├── migrate.mjs # One-shot settings table clone/repair tool -│ ├── runnables.mjs # Setting validators (prefix, pfp, stay_247) -│ └── README.md # Settings system documentation +├── commands/ # 37 command entry files (one per command); the three +│ │ # largest (lastfm, settings, debug) are split into action-family +│ │ # modules inside commands// subdirectories +│ ├── lastfm/ # lastfm action families (account, playback, listening, +│ │ # whoknows, info, tags, discovery, help, shared) +│ ├── settings/ # settings helpers (utils, channels247, setters) +│ └── debug/ # debug helpers (consts, gateway, rejoin, voiceDiagnostic) +├── settings/ # Settings system entry points (re-export, migrate, validators) +├── storage/ # Runtime data: defaults, modules.json, locales ├── docker/ # Docker self-hosting (Dockerfile, compose, entrypoint, │ # config templates, .env.example) -└── storage/ - ├── defaults.json # Default per-guild settings template - ├── modules.json # Plugin module registry (empty by default) - ├── stats.json # Static counters - └── locales/bot/ # Translation files - ├── en.json - ├── ar-SA.json - ├── de-DE.json - ├── ckb.json - └── pt-BR.json +└── src/ + ├── core/ # Bot composition + │ ├── Bot.mjs # Remix class — boot sequence, service wiring, alone-check, + │ │ # presence rotation, WebSocket error guards + │ ├── BotVoiceMixin.mjs # Voice-channel resolution, 24/7 player spawning with + │ │ # announcements, programmatic leave, shared servers + │ ├── Logger.mjs # Structured logger with per-category control + │ └── Locale.mjs # i18n translation engine + ├── commands/ # Command framework layer + │ ├── index.mjs # Public surface (re-exports) + │ ├── CommandBuilder.mjs # Fluent builder + permission requirements + │ ├── Option.mjs # Typed options + flags with validation + │ ├── CommandHandler.mjs # Dispatcher: parsing, cooldowns, permission checks + │ ├── CommandLoader.mjs # Dynamic command loading + run-handler binding + │ ├── HelpHandler.mjs # Text help generation (usage/aliases/options) + │ └── PrefixManager.mjs # Per-guild prefix resolution + ├── ui/ # Message/embed layer + │ ├── index.mjs # Public surface (re-exports) + │ ├── MessageHandler.mjs # Reply/send/edit embeds, reaction + message observers, + │ │ # permission checks, pagination entry + │ ├── Wrappers.mjs # Message & Channel wrappers + │ ├── Paginators.mjs # PageBuilder, RichPaginator (tabbed), QueuePaginator + │ ├── HelpCommand.mjs # Rich tabbed help command (Home/Music/Utilities/Support) + │ ├── Permissions.mjs # Required/critical/optional bot permission catalog + │ └── Embeds.mjs # Global embed color + message-shape helpers + ├── voice/ # Gateway & voice-state layer + │ ├── VoiceStateCache.mjs # Dual LRU voice-state caches (humans / bots) + │ ├── VoiceStateResolver.mjs # Voice-state normalization + humans-in-channel check + │ └── gateway/ + │ ├── index.mjs # Public surface + │ ├── GatewayHandler.mjs # Raw WS dispatch, presence rotation, boot recovery + │ ├── VoiceStateRouting.mjs # Voice-state update handling, inactivity triggers + │ ├── GuildSync.mjs # Guild seeding (cache + REST), guild delete + │ └── RejoinManager.mjs # 24/7 rejoin scheduling with retries + ├── music/ # Player + audio engine layer + │ ├── PlayerManager.mjs # Player lifecycle & registry, getPlayer/initPlayer + │ ├── PlayerEventsMixin.mjs # Per-player event wiring, scrobbles, broadcasts + │ ├── PlayerLifecycleMixin.mjs# Voice checks, prompts, joins, leaves + │ ├── LavalinkManager.mjs # lavalink-client wrapper (NodeLink mode) + │ ├── probe.mjs # ffprobe wrapper for radio stream metadata + │ ├── providers.mjs # 45+ audio source provider definitions + │ ├── player/ + │ │ ├── index.mjs # Public surface (default export: Player) + │ │ ├── Player.mjs # Core state machine: join/leave/destroy, controls, 24/7 + │ │ ├── Queue.mjs # Queue data structure with loop modes + events + │ │ ├── PlaybackMixin.mjs # playNext pipeline, track-end timers, lyrics + │ │ ├── SearchMixin.mjs # Lavalink search, fallbacks, radio/external builders + │ │ └── DisplayMixin.mjs # Now-playing, queue listing, announcements + │ └── audio/ + │ ├── index.mjs # Public surface + │ ├── FluxerAudioBridge.mjs # NodeLink streams → LiveKit publishing core + │ ├── StreamPipeline.mjs # Magic-byte sniffing, remux, Opus encode + │ ├── HttpStreams.mjs # Redirect-following HTTP JSON/stream helpers + │ └── WebMOpusMuxer.mjs # Streaming EBML/Matroska muxer (Opus → WebM) + ├── services/ # Integrations + │ ├── FluxerListManager.mjs # FluxerList voters API client (TTL cache) + │ ├── TrackOptionsManager.mjs # Per-user per-track start/end times (MySQL + LRU) + │ └── lastfm/ + │ ├── index.mjs # Public surface + │ ├── LastFmManager.mjs # Base: config, MySQL pool, shared helpers + │ ├── UserStoreMixin.mjs # Linking, sessions, scrobble opt-ins + │ ├── ScrobblingMixin.mjs # Scrobble + now-playing + │ ├── TrackQueriesMixin.mjs # Track/artist/album/tag/geo/chart queries + │ ├── UserQueriesMixin.mjs # User tops, charts, playlists, play categories + │ ├── ServerStatsMixin.mjs # Whoknows, crowns, leaderboards, affinity + │ ├── constants.mjs # Signed API-call plumbing + │ └── urlUtils.mjs # lastfm:// URL parsing + ├── db/ # Persistence + │ ├── Settings.mjs # SettingsManager / ServerSettings / RemoteSettingsManager + │ │ # (MySQL-backed, debounced JSON_SET writes) + │ └── DatabaseManager.mjs # mysql2 pool + parameterized queries + bcrypt helpers + ├── utils/ # Cross-layer primitives (leaf layer) + │ ├── mixins.mjs # applyMixins — god-class splitting helper + │ ├── ShardingUtils.mjs # Shard-aware gateway helpers (2.2/3.0 compatible, + │ │ # guild→shard routing, local shard enumeration) + │ ├── Utils.mjs # Formatting, validation, ID cleaning + │ ├── API.mjs # REST call helpers (status/error wrapping) + │ ├── UI.mjs # Shared UI constants (colors) + │ └── Helpers247.mjs # 24/7 channel-mode helpers + └── dashboard/ # Dashboard backend + ├── index.mjs # Public surface + ├── Dashboard.mjs # Redis RPC routing, player/user broadcasts + ├── RpcHandlersMixin.mjs# Request handlers + authorization checks + ├── Serializers.mjs # Channel/user/player/command serializers (statics) + └── RedisHandler.mjs # Redis pub/sub RPC transport with reconnect handling ``` --- +## The Layered Codebase + +The rewrite organises the codebase into strict layers with one-way dependencies +(no layer reaches *down* past another): + +``` +index.mjs + └── core/ ──────────────► composition root: wires every layer together + ├── commands/ ─────► command framework (parsing, cooldowns, help) + │ └── ui/ ─────► message/embed primitives used by the framework + ├── ui/ ──── message wrappers, paginators, permissions + ├── voice/ ──── gateway events, voice-state caches, 24/7 rejoin + ├── music/ ──── players, queue, audio engine, Lavalink client + ├── services/ ──── Last.fm, FluxerList, track options + ├── db/ ──── MySQL settings + dashboard database pool + └── dashboard/ ──── Redis-RPC backend +``` + +**God classes were eliminated.** The five largest modules (Player, PlayerManager, +GatewayHandler, FluxerAudioBridge, LastFmManager, Dashboard) are each split into a +small base class plus **concern mixins** — one file per responsibility, applied onto +the class at load time via `src/utils/mixins.mjs` (`applyMixins`). All methods keep +the same names, so callers (including your own command files and modules) are +unaffected. + +**Big commands are grouped the same way.** The three commands that outgrew a +single file (`lastfm` 2.5k lines, `settings` 705, `debug` 669) keep their entry +file at `commands/.mjs` (same path the loader, `%reload` and help system +reference) and move their implementation into `commands//` — one module per +action family, dispatched by the entry's `run()` via per-module action sets: + +```js +// commands/lastfm.mjs (entry) — dispatch +if (ACCOUNT_ACTIONS.has(action)) + return runAccountActions.call(this, msg, data, lastfm, prefix, userId, targetUserId, action); +``` + +The loader only reads top-level `*.mjs` files, so the subdirectories are invisible +to command discovery; case bodies and helpers were moved verbatim (verified by +per-command runtime parity harnesses under `scripts/`), and every entry file keeps +its original exports (`playLastFmCategory` is still importable from +`commands/lastfm.mjs`). `commands/player.mjs` intentionally stays single-file: it +is one cohesive interactive UI flow (a single 500-line `run()` closure) with no +seams that could be split without rewriting behavior. + +**Public surfaces are barrels.** Each layer folder has an `index.mjs` that +re-exports its public API, so imports stay short and implementation files can move +without touching consumers: + +```js +import { CommandBuilder } from "../src/commands/index.mjs"; +import { Message, getGlobalColor } from "../src/ui/index.mjs"; +import Player from "../src/music/player/index.mjs"; +import { LastFmManager } from "../src/services/lastfm/index.mjs"; +``` + +**Compatibility is drop-in:** `config.json` keys, the MySQL schema, the Redis RPC +protocol, command names/aliases, locale files, and the Docker entrypoint +(`node index.mjs` at the repository root) are all unchanged from the previous +single-layer layout. + +--- + ## Localization Remix supports multiple languages out of the box. The locale system loads JSON translation files from `storage/locales/bot/` and serves the appropriate language based on each guild's `locale` setting. @@ -479,6 +607,7 @@ Currently supported languages: | `de-DE` | German | | `ckb` | Kurdish (Sorani) | | `pt-BR` | Brazilian Portuguese | +| `tr` | Turkish | To add a new language, place a JSON file in `storage/locales/bot/` following the same key structure as `en.json`, then set the locale per guild with `%settings set locale `. @@ -488,7 +617,8 @@ To add a new language, place a JSON file in `storage/locales/bot/` following the | Script | Command | Description | | :--- | :--- | :--- | -| `npm start` | `node index.mjs` | Start the bot | +| `npm start` | `node index.mjs` | Start the bot (single process — default) | +| `npm run shard` | `node shard.mjs` | Start under the sharding supervisor (optional) | | `npm run dev` | `node --inspect index.mjs --trace-warnings` | Start with Node.js inspector | | `npm run migrate` | `node settings/migrate.mjs` | Clone/repair the remote settings table | @@ -512,4 +642,3 @@ To add a new language, place a JSON file in `storage/locales/bot/` following the © 2026 Remix. Code licensed under the MIT License.
The Remix name, logo, and branding are proprietary and may not be reused.

- diff --git a/commands/autoplay.mjs b/commands/autoplay.mjs index b2cd1e9..4f383c9 100644 --- a/commands/autoplay.mjs +++ b/commands/autoplay.mjs @@ -3,10 +3,10 @@ * @description Toggle autoplay mode — keeps the music going forever: */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; -import { logger } from "../src/constants/Logger.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; +import { logger } from "../src/core/Logger.mjs"; /** @type {CommandBuilder} @description Command definition for the autoplay command. */ export const command = new CommandBuilder() diff --git a/commands/clear.mjs b/commands/clear.mjs index a41870d..45a8766 100644 --- a/commands/clear.mjs +++ b/commands/clear.mjs @@ -3,9 +3,9 @@ * @description Remove all songs from the playback queue. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; /** * @type {CommandBuilder} diff --git a/commands/debug.mjs b/commands/debug.mjs index d53fa79..3897410 100644 --- a/commands/debug.mjs +++ b/commands/debug.mjs @@ -1,340 +1,16 @@ /** * @module commands/debug - * @description Owner-only debug command for voice diagnostics, ghost connection detection, and forced rejoin. + * @description Owner-only debug command for voice diagnostics, ghost connection + * detection, and forced rejoin. The implementations live in commands/debug/ + * (gateway, rejoin, voiceDiagnostic); the builder and run() dispatch stay here. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor, cleanId } from "../src/MessageHandler.mjs"; -import { logger } from "../src/constants/Logger.mjs"; -import { getVoiceManager } from "@fluxerjs/voice"; -import { ERROR_COLOR, WARN_COLOR, SUCCESS_COLOR, DANGER_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs"; - -const REJOIN_DELAY_MS = 2_000; -const INTENTIONAL_LEAVE_TTL = 30_000; -const MAX_DESC = 4096; - -/** - * Get a human-readable label for a voice room's connection state. - * @private - * @param {object|null} room - The voice room object. - * @returns {string} Connection state label. - */ -function roomStateLabel(room) { - if (!room) return "none"; - const cs = room.connectionState; - if (cs === 0 || cs === "CONN_DISCONNECTED") return "disconnected(0)"; - if (cs === 1 || cs === "CONN_CONNECTED") return "connected(1)"; - if (cs === 2) return room.isConnected ? "connected(2)" : "reconnecting(2)"; - if (cs === "CONN_RECONNECTING") return "reconnecting"; - if (cs === 3) return "reconnecting(3)"; - if (cs === 4) return "signal_reconnecting(4)"; - if (typeof cs === "string") return cs; - return String(cs); -} - -/** - * Check if a player has a ghost connection (appears in voice but WebSocket is dead). - * @private - * @param {object} player - The player instance. - * @returns {boolean} True if the player has a ghost connection. - */ -function isGhostConnection(player) { - const conn = player.connection; - if (!conn) return false; - if (player._destroyed || player.leaving || player._isJoining) return false; - - const room = conn.room; - if (!room) { - return !conn._destroyed; - } - - if (!room.isConnected) return true; - - const cs = room.connectionState; - if (cs === 0 || cs === "CONN_DISCONNECTED") return true; - if (cs === "CONN_RECONNECTING" || cs === 3 || cs === 4) return true; - - return false; -} - -/** - * Get the bot's voice channel state from the Discord gateway cache. - * @private - * @param {object} client - The Discord client instance. - * @param {string} guildId - The guild ID to check. - * @returns {{ userId: string, channelId: string }|null} Bot's voice state or null. - */ -function getBotGatewayVoiceState(client, guildId) { - const botId = client.user?.id; - if (!botId || !guildId) return null; - - try { - const vm = getVoiceManager(client); - if (vm?.voiceStates) { - const cleanGuild = cleanId(guildId); - const guildVoiceMap = vm.voiceStates.get(cleanGuild) ?? vm.voiceStates.get(guildId); - if (guildVoiceMap && typeof guildVoiceMap.get === "function") { - const channelId = guildVoiceMap.get(botId); - if (channelId) return { userId: botId, channelId: cleanId(channelId) }; - } - } - } catch (e) { logger.warn("[Debug] getBotGatewayVoiceState (VoiceManager):", e?.message); } - - try { - const cleanGuild = cleanId(guildId); - const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId); - const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null; - if (!voiceStates) return null; - - const entries = Array.isArray(voiceStates) - ? voiceStates - : typeof voiceStates.values === "function" - ? [...voiceStates.values()] - : Object.entries(voiceStates).map(([uid, val]) => { - if (typeof val === "string") return { user_id: uid, channel_id: val }; - const obj = typeof val === "object" && val !== null ? val : {}; - return { user_id: uid, channel_id: obj.channelId ?? obj.channel_id ?? null, ...obj }; - }); - - for (const state of entries) { - const uid = state?.user_id ?? state?.userId ?? state?.id; - if (uid === botId) { - const chId = state?.channel_id ?? state?.channelId ?? null; - if (chId) return { userId: botId, channelId: cleanId(chId) }; - } - } - } catch (e) { logger.warn("[Debug] getBotGatewayVoiceState (guild cache):", e?.message); } - - return null; -} - -/** - * Check if the gateway voice state is stale (mismatches the player's channel). - * @private - * @param {object} client - The Discord client instance. - * @param {object} player - The player instance. - * @returns {boolean} True if the gateway presence is stale. - */ -function isStaleGatewayPresence(client, player) { - const guildId = player._guildId ?? player._resolveGuildId?.(); - if (!guildId) return false; - - const gatewayState = getBotGatewayVoiceState(client, guildId); - if (!gatewayState) return false; - - const playerChannel = cleanId(player._channelId ?? player._home247Channel); - const gatewayChannel = gatewayState.channelId; - - return !playerChannel || playerChannel !== gatewayChannel; -} - -/** - * Build a human-readable label for a player (guild name / #channel name). - * @private - * @param {object} client - The Discord client instance. - * @param {string} channelId - The voice channel ID. - * @param {object} player - The player instance. - * @returns {string} Formatted label string. - */ -function buildPlayerLabel(client, channelId, player) { - const channel = client.channels.get(channelId); - const gId = player._guildId ?? channel?.guildId; - const guild = gId ? client.guilds.get(cleanId(gId)) : null; - return `${guild?.name ?? "unknown"} / #${channel?.name ?? channelId}`; -} - -/** - * Force a player to leave and rejoin, restoring queue and playback state. - * @private - * @async - * @param {object} ctx - The bot (Remix) instance context. - * @param {object} player - The player to rejoin. - * @returns {Promise} Result object with success status, room state, and details. - */ -async function forceRejoinPlayer(ctx, player) { - const channelId = player._channelId ?? player._home247Channel; - const guildId = player._guildId ?? player._resolveGuildId?.(); - if (!channelId || !guildId) return { success: false, reason: "no channel or guild id" }; - - const cleanChannelId = cleanId(channelId); - const cleanGuildId = cleanId(guildId); - - const currentTrack = player.queue?.getCurrent(); - const queueTracks = player.queue?.data ? [...player.queue.data] : []; - const wasPaused = player._paused; - const wasAutoplay = player._autoplay; - const wasLoop = player.queue?.loop ?? false; - const wasSongLoop = player.queue?.songLoop ?? false; - const savedVolume = player.preferredVolume ?? 1; - const savedFilter = player.activeFilter ?? null; - const savedFilterPayload = player.activeFilterPayload ?? null; - - try { - ctx.markIntentionalLeave?.(cleanChannelId, INTENTIONAL_LEAVE_TTL); - - ctx.players.playerMap.delete(cleanChannelId); - ctx.players._unindexPlayer?.(cleanGuildId, cleanChannelId); - - const altIds = [player._channelId, player._home247Channel] - .filter(Boolean) - .map(id => cleanId(id)) - .filter(id => id !== cleanChannelId); - for (const altId of altIds) { - ctx.players.playerMap.delete(altId); - ctx.players._unindexPlayer?.(cleanGuildId, altId); - } - - const pendingScrobble = ctx.players._pendingScrobbleTimers?.get(cleanChannelId); - if (pendingScrobble) { - clearTimeout(pendingScrobble.timer); - ctx.players._pendingScrobbleTimers.delete(cleanChannelId); - } - - ctx.players._pendingJoins?.delete?.(cleanChannelId); - - if (player.connection) { - try { player.connection.removeAllListeners(); } catch (e) { logger.warn("[Debug] connection listener removal:", e?.message); } - try { await player.connection.disconnect(); } catch (e) { logger.warn("[Debug] connection disconnect:", e?.message); } - } - - try { await player.leave(); } catch (e) { logger.warn("[Debug] player leave:", e?.message); } - try { player.destroy(); } catch (e) { logger.warn("[Debug] player destroy:", e?.message); } - - await new Promise(r => setTimeout(r, REJOIN_DELAY_MS)); - - const newPlayer = await ctx._spawnPlayer(cleanGuildId, cleanChannelId); - - if (!newPlayer) { - return { success: false, reason: "_spawnPlayer returned null", channelId: cleanChannelId }; - } - - if (newPlayer.preferredVolume !== savedVolume) { - newPlayer.setVolume(savedVolume); - } - - if (wasLoop) newPlayer.queue?.setLoop?.(true); - if (wasSongLoop) newPlayer.queue?.setSongLoop?.(true); - - if (savedFilter && savedFilterPayload) { - newPlayer.activeFilter = savedFilter; - newPlayer.activeFilterPayload = savedFilterPayload; - } - - if (currentTrack && newPlayer.queue) { - try { - newPlayer.queue.data = queueTracks; - newPlayer.queue.current = null; - await newPlayer.playNext(); - if (wasPaused) newPlayer.pause(); - } catch (e) { logger.warn("[Debug] queue restore:", e?.message); } - } - - if (wasAutoplay) { - newPlayer._autoplay = true; - newPlayer._autoplayHistory = player._autoplayHistory ?? []; - try { - const { attachAutoplay } = await import("./autoplay.mjs"); - attachAutoplay(newPlayer, ctx); - } catch (e) { - logger.warn("[Debug] autoplay re-attach failed:", e?.message); - } - } - - const newRoom = newPlayer.connection?.room; - return { - success: !!(newPlayer.connection && newRoom?.isConnected), - roomConnected: newRoom?.isConnected ?? false, - roomState: roomStateLabel(newRoom), - resumedPlayback: !!(currentTrack && newPlayer.queue?.getCurrent()), - channelId: cleanChannelId, - }; - } catch (err) { - logger.warn("[Debug] forceRejoinPlayer error:", err?.message); - return { success: false, reason: err.message, channelId: cleanChannelId }; - } -} - -/** - * Process a batch of players for force-rejoin, updating a status message with progress. - * @private - * @async - * @param {object} ctx - The bot (Remix) instance context. - * @param {Array} entries - Array of [channelId, player] tuples. - * @param {object} statusMsg - The message to update with progress. - * @param {string} title - The title for the progress display. - * @returns {Promise} Array of rejoin results. - */ -async function processRejoinBatch(ctx, entries, statusMsg, title) { - const results = []; - - for (let i = 0; i < entries.length; i++) { - const [cid, player] = entries[i]; - const label = buildPlayerLabel(ctx.client, cid, player); - - const progressLines = [ - `🔄 **${title}** — Processing ${i + 1}/${entries.length}`, - `Currently rejoining: \`${label}\``, - ``, - ]; - for (let j = 0; j < results.length; j++) { - const r = results[j]; - const icon = r.success ? "✅" : "❌"; - progressLines.push(`${icon} \`${r.label}\`${r.success ? ` — room:${r.roomState}` : ` — failed (${r.reason ?? "?"})`}`); - } - await statusMsg.edit({ embeds: [new EmbedBuilder().setColor(WARN_COLOR).setTitle(`Debug — ${title}`).setDescription(progressLines.join("\n").slice(0, MAX_DESC))] }).catch(() => {}); - - const result = await forceRejoinPlayer(ctx, player); - result.label = label; - results.push(result); - - if (i < entries.length - 1) { - await new Promise(r => setTimeout(r, REJOIN_DELAY_MS)); - } - } - - return results; -} - -/** - * Build the final embed summarizing rejoin results. - * @private - * @param {object[]} results - Array of rejoin result objects. - * @param {string} title - The title for the embed. - * @param {string} noun - The noun describing the rejoin targets. - * @returns {object} Message payload with embed. - */ -function buildRejoinResultEmbed(results, title, noun) { - const resultLines = [ - `🔄 **${title} Complete**`, - `${noun.charAt(0).toUpperCase() + noun.slice(1)} processed: **${results.length}**`, - ``, - ]; - - let rejoinedCount = 0; - let resumedCount = 0; - let failedCount = 0; - - for (const r of results) { - if (r.success) { - rejoinedCount++; - if (r.resumedPlayback) resumedCount++; - resultLines.push(`✅ \`${r.label}\` — rejoined (room:${r.roomState}, playback:${r.resumedPlayback ? "resumed" : "no track"})`); - } else { - failedCount++; - resultLines.push(`❌ \`${r.label}\` — failed${r.reason ? ` (${r.reason})` : ""}`); - } - } - - if (failedCount === 0) { - resultLines.push("", `All **${rejoinedCount}** ${noun} restored.${resumedCount > 0 ? ` ${resumedCount} had playback resumed.` : ""}`); - } else { - resultLines.push("", `⚠️ **${failedCount}** ${noun} could not be restored.`); - } - - const finalColor = failedCount === 0 ? SUCCESS_COLOR : DANGER_COLOR; - return { embeds: [new EmbedBuilder().setColor(finalColor).setTitle(`Debug — ${title}`).setDescription(resultLines.join("\n").slice(0, MAX_DESC))] }; -} +import { ERROR_COLOR } from "../src/utils/UI.mjs"; +import { isGhostConnection } from "./debug/gateway.mjs"; +import { runBatchRejoin } from "./debug/rejoin.mjs"; +import { runVoiceDiagnostic } from "./debug/voiceDiagnostic.mjs"; /** * @type {CommandBuilder} @@ -351,6 +27,7 @@ export const command = new CommandBuilder() .addChoices("voice", "voice-rejoin", "247-rejoin") .setRequired(true)); + /** * Run handler for the debug command. * Routes to the appropriate debug subcommand based on the target option. @@ -385,285 +62,3 @@ export async function run(msg, data) { } } } - -/** - * Run a batch rejoin operation on matching players. - * @private - * @async - * @param {object} msg - The command message wrapper. - * @param {string} key - Identifier key for the rejoin type. - * @param {string} title - Display title for the operation. - * @param {string} noun - Noun describing the targets. - * @param {Function} filter - Function to filter which players to rejoin. - * @param {boolean} [showHintIfEmpty=false] - Whether to show a hint if no matches found. - * @returns {Promise} - */ -async function runBatchRejoin(msg, key, title, noun, filter, showHintIfEmpty = false) { - const allPlayers = [...this.players.playerMap.entries()]; - const matching = allPlayers.filter(([, player]) => filter(player)); - - if (matching.length === 0) { - const has247 = allPlayers.some(([, player]) => player._home247Channel); - const hintLine = showHintIfEmpty && has247 - ? `\n\n💡 No ghosts auto-detected, but 24/7 channels with dead WebSockets may still report as "connected".\nUse \`%debug 247-rejoin\` to force-rejoin all 24/7 channels.` - : ""; - const embed = new EmbedBuilder() - .setColor(SUCCESS_COLOR) - .setTitle(`Debug — ${title}`) - .setDescription(`No ${noun} found. All voice connections appear healthy.${hintLine}`) - ; - return msg.reply({ embeds: [embed] }); - } - - const statusLines = [ - `🔄 **${title}** — Found **${matching.length}** ${noun}`, - `Destroying stale connections and respawning fresh players...`, - ``, - ]; - - for (let i = 0; i < matching.length; i++) { - const [cid, player] = matching[i]; - const label = buildPlayerLabel(this.client, cid, player); - const ghost = isGhostConnection(player) ? " 👻GHOST" : ""; - const roomLabel = player.connection?.room ? roomStateLabel(player.connection.room) : "none"; - const connectedLabel = player.connection?.room?.isConnected ? "yes" : "no"; - statusLines.push(`${i + 1}. \`${label}\` — room:${roomLabel} isConnected:${connectedLabel}${ghost}`); - } - - const statusEmbed = new EmbedBuilder() - .setColor(WARN_COLOR) - .setTitle(`Debug — ${title}`) - .setDescription(statusLines.join("\n").slice(0, MAX_DESC)) - ; - const statusMsg = await msg.reply({ embeds: [statusEmbed] }); - - const results = await processRejoinBatch(this, matching, statusMsg, title); - - const finalPayload = buildRejoinResultEmbed(results, title, noun); - await statusMsg.edit(finalPayload).catch(() => { - msg.reply(finalPayload); - }); -} - -/** - * Run a full voice diagnostic, displaying player states and ghost connections. - * @private - * @async - * @param {object} msg - The command message wrapper. - * @returns {Promise} - */ -async function runVoiceDiagnostic(msg) { - const servers = [...this.players.playerMap.entries()].map(([cid, s]) => { - const channel = this.client.channels.get(cid); - const guildId = s._guildId ?? channel?.guildId ?? channel?.guild_id; - const guild = guildId ? this.client.guilds.get(cleanId(guildId)) : null; - const conn = s.connection; - const room = conn?.room; - const ghost = isGhostConnection(s); - const staleGateway = ghost ? isStaleGatewayPresence(this.client, s) : false; - const gatewayVoiceState = getBotGatewayVoiceState(this.client, guildId); - return { - name: channel?.name ?? "unknown", - id: channel?.id ?? cid, - channelId: s._channelId ?? cid, - guildId: guildId ?? "unknown", - guildname: guild?.name ?? channel?.guild?.name ?? "unknown", - conn: conn ? "yes" : "null", - connDestroyed: conn?._destroyed ?? null, - roomConnected: room?.isConnected ?? null, - roomState: roomStateLabel(room), - mediaPlayer: !!s._mediaPlayer && !s._mediaPlayer?.destroyed ? "alive" : (s._mediaPlayer?.destroyed ? "destroyed" : "none"), - destroyed: s._destroyed ?? false, - leaving: s.leaving ?? false, - joining: s._isJoining ?? false, - recovering: s._isRecovering ?? false, - paused: s._paused ?? false, - hasQueue: !!(s.queue?.getCurrent() || !s.queue?.isEmpty()), - home247: s._home247Channel ?? null, - ghost, - staleGateway, - gatewayVoiceChannel: gatewayVoiceState?.channelId ?? null, - }; - }); - const pending = [...(this.players._pendingJoins ?? [])]; - - const ghostConnections = servers.filter(s => s.ghost); - const livePlayers = servers.filter(s => s.conn === "yes" && !s.destroyed && !s.leaving); - const actuallyConnected = livePlayers.filter(s => !s.ghost); - const channels247 = servers.filter(s => s.home247); - - const summary = { - playerMapSize: this.players.playerMap.size, - livePlayers: livePlayers.length, - actuallyConnected: actuallyConnected.length, - ghostConnections: ghostConnections.length, - channels247: channels247.length, - pendingJoins: pending.length, - pendingChannels: pending, - }; - - const pages = []; - - const summaryLines = [ - `📊 **Summary**`, - `Players in map: **${summary.playerMapSize}**`, - `Live players: **${summary.livePlayers}**`, - `Actually connected: **${summary.actuallyConnected}**`, - `Ghost connections: **${summary.ghostConnections}**`, - `24/7 channels: **${summary.channels247}**`, - `Pending joins: **${summary.pendingJoins}**${summary.pendingChannels.length ? ` (\`${summary.pendingChannels.join("`, `")}\`)` : ""}`, - ]; - - if (ghostConnections.length > 0) { - summaryLines.push("", `👻 **Ghost Connections (${ghostConnections.length}):**`, "These players *appear* in voice but their WebSocket/LiveKit room is dead:"); - summaryLines.push(`Use \`%debug voice-rejoin\` to rejoin detected ghosts, or \`%debug 247-rejoin\` to force-rejoin all 24/7 channels.`); - for (const g of ghostConnections) { - const gatewayInfo = g.staleGateway - ? `gateway:stale(ch:${g.gatewayVoiceChannel ?? "?"})` - : `gateway:present(ch:${g.gatewayVoiceChannel ?? "?"})`; - const detail = ` 👻 \`${g.guildname}\` / \`#${g.name}\` — room:${g.roomState} connected:${g.roomConnected} media:${g.mediaPlayer} ${gatewayInfo} 247:${g.home247 ?? "no"}`; - if (summaryLines.join("\n").length + detail.length + 1 > MAX_DESC - 60) { - summaryLines.push(` … and more ghosts (see JSON details)`); - break; - } - summaryLines.push(detail); - } - } - - if (channels247.length > 0 && ghostConnections.length === 0) { - summaryLines.push("", `ℹ️ **24/7 Channels (${channels247.length}):**`, `WebSocket deaths can leave 24/7 channels as invisible ghosts (room reports healthy but transport is dead).`); - summaryLines.push(`Use \`%debug 247-rejoin\` to force-rejoin all 24/7 channels if you suspect ghost connections.`); - } - - summaryLines.push("", "**Players:**"); - for (let i = 0; i < servers.length; i++) { - const s = servers[i]; - let status; - if (s.ghost) { - status = "👻"; - } else if (s.conn === "yes" && !s.destroyed && !s.leaving) { - status = "🟢"; - } else { - status = "🔴"; - } - const ghostTag = s.ghost ? " ⚠️GHOST" : ""; - const staleTag = s.staleGateway ? " ⚠️STALE_GW" : ""; - const tag247 = s.home247 ? " 🔄247" : ""; - const line = `${status} \`${s.guildname}\` / \`#${s.name}\` — conn:${s.conn} room:${s.roomState} connected:${s.roomConnected} media:${s.mediaPlayer}${ghostTag}${staleTag}${tag247}`; - if (summaryLines.join("\n").length + line.length + 1 > MAX_DESC - 30) { - summaryLines.push(`… and ${servers.length - i} more (see next pages)`); - break; - } - summaryLines.push(line); - } - pages.push(summaryLines.join("\n")); - - let groupJson = ""; - for (let i = 0; i < servers.length; i++) { - const singleJson = JSON.stringify(servers[i], null, 2); - const candidate = groupJson - ? groupJson.slice(0, -1) + ",\n" + singleJson.slice(1) - : singleJson; - - const candidateLen = ("```json\n" + candidate + "\n```").length; - - if (candidateLen > MAX_DESC && groupJson) { - pages.push(("```json\n" + groupJson + "\n```").slice(0, MAX_DESC)); - groupJson = singleJson; - } else if (candidateLen > MAX_DESC) { - const budget = MAX_DESC - 12; - pages.push(("```json\n" + singleJson.slice(0, budget) + "\n```").slice(0, MAX_DESC)); - groupJson = ""; - } else { - groupJson = candidate; - } - } - if (groupJson) { - pages.push(("```json\n" + groupJson + "\n```").slice(0, MAX_DESC)); - } - - if (pages.length === 1) { - const embedColor = ghostConnections.length > 0 ? DANGER_COLOR : getGlobalColor(); - const embed = new EmbedBuilder() - .setColor(embedColor) - .setTitle(this.t(msg, "responses.debug.voiceTitle") + (ghostConnections.length > 0 ? ` — ${ghostConnections.length} Ghost(s) Detected!` : "")) - .setDescription(pages[0].slice(0, MAX_DESC)) - ; - return msg.reply({ embeds: [embed] }); - } - - const totalPages = pages.length; - let currentPage = 0; - - const buildPage = (pageIdx, expired = false) => { - const isSummaryPage = pageIdx === 0; - const pageLabel = isSummaryPage - ? "Summary" - : `Player Detail${pages[pageIdx].split(`"name":`).length - 1 > 1 ? "s" : ""}`; - const footerText = expired - ? this.t(msg, "responses._common.controlsExpired") - : `${this.t(msg, "responses.debug.pageLabel", { page: pageIdx + 1, total: totalPages })} • ${this.t(msg, "responses.eval.navigateHint")}`; - - const embedColor = (isSummaryPage && ghostConnections.length > 0) ? DANGER_COLOR : getGlobalColor(); - const titleSuffix = (isSummaryPage && ghostConnections.length > 0) ? ` — ${ghostConnections.length} Ghost(s) Detected!` : ""; - - const embed = new EmbedBuilder() - .setColor(embedColor) - .setTitle(this.t(msg, "responses.debug.voiceTitle") + titleSuffix + ` — ${pageLabel}`) - .setDescription(pages[pageIdx].slice(0, MAX_DESC)) - .setFooter({ text: footerText }) - ; - return { embeds: [embed] }; - }; - - const replyMsg = await msg.reply(buildPage(0)); - if (!replyMsg?.message) return; - - const navEmojis = ["⬅️", "➡️", "❌"]; - for (const emoji of navEmojis) { - await replyMsg.message.react(emoji).catch(() => {}); - } - - const clearReactions = async () => { - try { - await replyMsg.message.removeAllReactions(); - } catch (e) { - for (const emoji of navEmojis) { - try { await replyMsg.message.removeReaction(emoji); } catch (err) { logger.warn("[Debug] removeReaction fallback:", err?.message); } - } - } - }; - - let emojiTimeout; - const resetTimer = () => { - clearTimeout(emojiTimeout); - emojiTimeout = setTimeout(async () => { - unobserve?.(); - await clearReactions(); - await replyMsg.edit(buildPage(currentPage, true)).catch(() => {}); - }, EMOJI_REMOVE_TIMEOUT); - }; - - const unobserve = replyMsg.onReaction(navEmojis, async (e) => { - const emoji = e?.emoji_id ?? e?.emoji?.id ?? e?.emoji; - - if (emoji === "❌") { - clearTimeout(emojiTimeout); - unobserve?.(); - await replyMsg.message.delete().catch(() => {}); - return; - } - - resetTimer(); - - if (emoji === "⬅️") { - currentPage = currentPage > 0 ? currentPage - 1 : totalPages - 1; - } else if (emoji === "➡️") { - currentPage = currentPage < totalPages - 1 ? currentPage + 1 : 0; - } - - await replyMsg.edit(buildPage(currentPage)).catch(() => {}); - }); - - resetTimer(); -} diff --git a/commands/debug/consts.mjs b/commands/debug/consts.mjs new file mode 100644 index 0000000..4dd05fb --- /dev/null +++ b/commands/debug/consts.mjs @@ -0,0 +1,10 @@ +/** + * @module commands/debug/consts + * @description Shared timing and embed-size constants for the debug command + * modules. Verbatim from the original single-file command; only `export ` + * prefixes added. + */ + +export const REJOIN_DELAY_MS = 2_000; +export const INTENTIONAL_LEAVE_TTL = 30_000; +export const MAX_DESC = 4096; diff --git a/commands/debug/gateway.mjs b/commands/debug/gateway.mjs new file mode 100644 index 0000000..02019c8 --- /dev/null +++ b/commands/debug/gateway.mjs @@ -0,0 +1,134 @@ +/** + * @module commands/debug/gateway + * @description Gateway/voice state inspection helpers (room labels, ghost detection, bot gateway voice state, stale presence, player labels). Verbatim from the original single-file command. + */ + +import { getVoiceManager } from "@fluxerjs/voice"; +import { logger } from "../../src/core/Logger.mjs"; +import { cleanId } from "../../src/ui/index.mjs"; + +/** + * Get a human-readable label for a voice room's connection state. + * @private + * @param {object|null} room - The voice room object. + * @returns {string} Connection state label. + */ +export function roomStateLabel(room) { + if (!room) return "none"; + const cs = room.connectionState; + if (cs === 0 || cs === "CONN_DISCONNECTED") return "disconnected(0)"; + if (cs === 1 || cs === "CONN_CONNECTED") return "connected(1)"; + if (cs === 2) return room.isConnected ? "connected(2)" : "reconnecting(2)"; + if (cs === "CONN_RECONNECTING") return "reconnecting"; + if (cs === 3) return "reconnecting(3)"; + if (cs === 4) return "signal_reconnecting(4)"; + if (typeof cs === "string") return cs; + return String(cs); +} +/** + * Check if a player has a ghost connection (appears in voice but WebSocket is dead). + * @private + * @param {object} player - The player instance. + * @returns {boolean} True if the player has a ghost connection. + */ +export function isGhostConnection(player) { + const conn = player.connection; + if (!conn) return false; + if (player._destroyed || player.leaving || player._isJoining) return false; + + const room = conn.room; + if (!room) { + return !conn._destroyed; + } + + if (!room.isConnected) return true; + + const cs = room.connectionState; + if (cs === 0 || cs === "CONN_DISCONNECTED") return true; + if (cs === "CONN_RECONNECTING" || cs === 3 || cs === 4) return true; + + return false; +} +/** + * Get the bot's voice channel state from the gateway cache. + * @private + * @param {object} client - The client instance. + * @param {string} guildId - The guild ID to check. + * @returns {{ userId: string, channelId: string }|null} Bot's voice state or null. + */ +export function getBotGatewayVoiceState(client, guildId) { + const botId = client.user?.id; + if (!botId || !guildId) return null; + + try { + const vm = getVoiceManager(client); + if (vm?.voiceStates) { + const cleanGuild = cleanId(guildId); + const guildVoiceMap = vm.voiceStates.get(cleanGuild) ?? vm.voiceStates.get(guildId); + if (guildVoiceMap && typeof guildVoiceMap.get === "function") { + const channelId = guildVoiceMap.get(botId); + if (channelId) return { userId: botId, channelId: cleanId(channelId) }; + } + } + } catch (e) { logger.warn("[Debug] getBotGatewayVoiceState (VoiceManager):", e?.message); } + + try { + const cleanGuild = cleanId(guildId); + const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId); + const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null; + if (!voiceStates) return null; + + const entries = Array.isArray(voiceStates) + ? voiceStates + : typeof voiceStates.values === "function" + ? [...voiceStates.values()] + : Object.entries(voiceStates).map(([uid, val]) => { + if (typeof val === "string") return { user_id: uid, channel_id: val }; + const obj = typeof val === "object" && val !== null ? val : {}; + return { user_id: uid, channel_id: obj.channelId ?? obj.channel_id ?? null, ...obj }; + }); + + for (const state of entries) { + const uid = state?.user_id ?? state?.userId ?? state?.id; + if (uid === botId) { + const chId = state?.channel_id ?? state?.channelId ?? null; + if (chId) return { userId: botId, channelId: cleanId(chId) }; + } + } + } catch (e) { logger.warn("[Debug] getBotGatewayVoiceState (guild cache):", e?.message); } + + return null; +} +/** + * Check if the gateway voice state is stale (mismatches the player's channel). + * @private + * @param {object} client - The client instance. + * @param {object} player - The player instance. + * @returns {boolean} True if the gateway presence is stale. + */ +export function isStaleGatewayPresence(client, player) { + const guildId = player._guildId ?? player._resolveGuildId?.(); + if (!guildId) return false; + + const gatewayState = getBotGatewayVoiceState(client, guildId); + if (!gatewayState) return false; + + const playerChannel = cleanId(player._channelId ?? player._home247Channel); + const gatewayChannel = gatewayState.channelId; + + return !playerChannel || playerChannel !== gatewayChannel; +} +/** + * Build a human-readable label for a player (guild name / #channel name). + * @private + * @param {object} client - The client instance. + * @param {string} channelId - The voice channel ID. + * @param {object} player - The player instance. + * @returns {string} Formatted label string. + */ +export function buildPlayerLabel(client, channelId, player) { + const channel = client.channels.get(channelId); + const gId = player._guildId ?? channel?.guildId; + const guild = gId ? client.guilds.get(cleanId(gId)) : null; + return `${guild?.name ?? "unknown"} / #${channel?.name ?? channelId}`; +} diff --git a/commands/debug/rejoin.mjs b/commands/debug/rejoin.mjs new file mode 100644 index 0000000..d75d4d8 --- /dev/null +++ b/commands/debug/rejoin.mjs @@ -0,0 +1,259 @@ +/** + * @module commands/debug/rejoin + * @description Force-rejoin machinery for the debug command (forceRejoinPlayer, batch processing, result embed, runBatchRejoin entry). Verbatim from the original single-file command; the relative dynamic import of autoplay.mjs was adjusted for the deeper directory. + */ + +import { EmbedBuilder } from "@fluxerjs/core"; +import { logger } from "../../src/core/Logger.mjs"; +import { cleanId } from "../../src/ui/index.mjs"; +import { WARN_COLOR, SUCCESS_COLOR, DANGER_COLOR } from "../../src/utils/UI.mjs"; +import { REJOIN_DELAY_MS, INTENTIONAL_LEAVE_TTL, MAX_DESC } from "./consts.mjs"; +import { roomStateLabel, isGhostConnection, buildPlayerLabel } from "./gateway.mjs"; + +/** + * Force a player to leave and rejoin, restoring queue and playback state. + * @private + * @async + * @param {object} ctx - The bot (Remix) instance context. + * @param {object} player - The player to rejoin. + * @returns {Promise} Result object with success status, room state, and details. + */ +async function forceRejoinPlayer(ctx, player) { + const channelId = player._channelId ?? player._home247Channel; + const guildId = player._guildId ?? player._resolveGuildId?.(); + if (!channelId || !guildId) return { success: false, reason: "no channel or guild id" }; + + const cleanChannelId = cleanId(channelId); + const cleanGuildId = cleanId(guildId); + + const currentTrack = player.queue?.getCurrent(); + const queueTracks = player.queue?.data ? [...player.queue.data] : []; + const wasPaused = player._paused; + const wasAutoplay = player._autoplay; + const wasLoop = player.queue?.loop ?? false; + const wasSongLoop = player.queue?.songLoop ?? false; + const savedVolume = player.preferredVolume ?? 1; + const savedFilter = player.activeFilter ?? null; + const savedFilterPayload = player.activeFilterPayload ?? null; + + try { + ctx.markIntentionalLeave?.(cleanChannelId, INTENTIONAL_LEAVE_TTL); + + ctx.players.playerMap.delete(cleanChannelId); + ctx.players._unindexPlayer?.(cleanGuildId, cleanChannelId); + + const altIds = [player._channelId, player._home247Channel] + .filter(Boolean) + .map(id => cleanId(id)) + .filter(id => id !== cleanChannelId); + for (const altId of altIds) { + ctx.players.playerMap.delete(altId); + ctx.players._unindexPlayer?.(cleanGuildId, altId); + } + + const pendingScrobble = ctx.players._pendingScrobbleTimers?.get(cleanChannelId); + if (pendingScrobble) { + clearTimeout(pendingScrobble.timer); + ctx.players._pendingScrobbleTimers.delete(cleanChannelId); + } + + ctx.players._pendingJoins?.delete?.(cleanChannelId); + + if (player.connection) { + try { player.connection.removeAllListeners(); } catch (e) { logger.warn("[Debug] connection listener removal:", e?.message); } + try { await player.connection.disconnect(); } catch (e) { logger.warn("[Debug] connection disconnect:", e?.message); } + } + + try { await player.leave(); } catch (e) { logger.warn("[Debug] player leave:", e?.message); } + try { player.destroy(); } catch (e) { logger.warn("[Debug] player destroy:", e?.message); } + + await new Promise(r => setTimeout(r, REJOIN_DELAY_MS)); + + const newPlayer = await ctx._spawnPlayer(cleanGuildId, cleanChannelId); + + if (!newPlayer) { + return { success: false, reason: "_spawnPlayer returned null", channelId: cleanChannelId }; + } + + if (newPlayer.preferredVolume !== savedVolume) { + newPlayer.setVolume(savedVolume); + } + + if (wasLoop) newPlayer.queue?.setLoop?.(true); + if (wasSongLoop) newPlayer.queue?.setSongLoop?.(true); + + if (savedFilter && savedFilterPayload) { + newPlayer.activeFilter = savedFilter; + newPlayer.activeFilterPayload = savedFilterPayload; + } + + if (currentTrack && newPlayer.queue) { + try { + newPlayer.queue.data = queueTracks; + newPlayer.queue.current = null; + await newPlayer.playNext(); + if (wasPaused) newPlayer.pause(); + } catch (e) { logger.warn("[Debug] queue restore:", e?.message); } + } + + if (wasAutoplay) { + newPlayer._autoplay = true; + newPlayer._autoplayHistory = player._autoplayHistory ?? []; + try { + const { attachAutoplay } = await import("../autoplay.mjs"); + attachAutoplay(newPlayer, ctx); + } catch (e) { + logger.warn("[Debug] autoplay re-attach failed:", e?.message); + } + } + + const newRoom = newPlayer.connection?.room; + return { + success: !!(newPlayer.connection && newRoom?.isConnected), + roomConnected: newRoom?.isConnected ?? false, + roomState: roomStateLabel(newRoom), + resumedPlayback: !!(currentTrack && newPlayer.queue?.getCurrent()), + channelId: cleanChannelId, + }; + } catch (err) { + logger.warn("[Debug] forceRejoinPlayer error:", err?.message); + return { success: false, reason: err.message, channelId: cleanChannelId }; + } +} +/** + * Process a batch of players for force-rejoin, updating a status message with progress. + * @private + * @async + * @param {object} ctx - The bot (Remix) instance context. + * @param {Array} entries - Array of [channelId, player] tuples. + * @param {object} statusMsg - The message to update with progress. + * @param {string} title - The title for the progress display. + * @returns {Promise} Array of rejoin results. + */ +async function processRejoinBatch(ctx, entries, statusMsg, title) { + const results = []; + + for (let i = 0; i < entries.length; i++) { + const [cid, player] = entries[i]; + const label = buildPlayerLabel(ctx.client, cid, player); + + const progressLines = [ + `🔄 **${title}** — Processing ${i + 1}/${entries.length}`, + `Currently rejoining: \`${label}\``, + ``, + ]; + for (let j = 0; j < results.length; j++) { + const r = results[j]; + const icon = r.success ? "✅" : "❌"; + progressLines.push(`${icon} \`${r.label}\`${r.success ? ` — room:${r.roomState}` : ` — failed (${r.reason ?? "?"})`}`); + } + await statusMsg.edit({ embeds: [new EmbedBuilder().setColor(WARN_COLOR).setTitle(`Debug — ${title}`).setDescription(progressLines.join("\n").slice(0, MAX_DESC))] }).catch(() => {}); + + const result = await forceRejoinPlayer(ctx, player); + result.label = label; + results.push(result); + + if (i < entries.length - 1) { + await new Promise(r => setTimeout(r, REJOIN_DELAY_MS)); + } + } + + return results; +} +/** + * Build the final embed summarizing rejoin results. + * @private + * @param {object[]} results - Array of rejoin result objects. + * @param {string} title - The title for the embed. + * @param {string} noun - The noun describing the rejoin targets. + * @returns {object} Message payload with embed. + */ +function buildRejoinResultEmbed(results, title, noun) { + const resultLines = [ + `🔄 **${title} Complete**`, + `${noun.charAt(0).toUpperCase() + noun.slice(1)} processed: **${results.length}**`, + ``, + ]; + + let rejoinedCount = 0; + let resumedCount = 0; + let failedCount = 0; + + for (const r of results) { + if (r.success) { + rejoinedCount++; + if (r.resumedPlayback) resumedCount++; + resultLines.push(`✅ \`${r.label}\` — rejoined (room:${r.roomState}, playback:${r.resumedPlayback ? "resumed" : "no track"})`); + } else { + failedCount++; + resultLines.push(`❌ \`${r.label}\` — failed${r.reason ? ` (${r.reason})` : ""}`); + } + } + + if (failedCount === 0) { + resultLines.push("", `All **${rejoinedCount}** ${noun} restored.${resumedCount > 0 ? ` ${resumedCount} had playback resumed.` : ""}`); + } else { + resultLines.push("", `⚠️ **${failedCount}** ${noun} could not be restored.`); + } + + const finalColor = failedCount === 0 ? SUCCESS_COLOR : DANGER_COLOR; + return { embeds: [new EmbedBuilder().setColor(finalColor).setTitle(`Debug — ${title}`).setDescription(resultLines.join("\n").slice(0, MAX_DESC))] }; +} +/** + * Run a batch rejoin operation on matching players. + * @private + * @async + * @param {object} msg - The command message wrapper. + * @param {string} key - Identifier key for the rejoin type. + * @param {string} title - Display title for the operation. + * @param {string} noun - Noun describing the targets. + * @param {Function} filter - Function to filter which players to rejoin. + * @param {boolean} [showHintIfEmpty=false] - Whether to show a hint if no matches found. + * @returns {Promise} + */ +export async function runBatchRejoin(msg, key, title, noun, filter, showHintIfEmpty = false) { + const allPlayers = [...this.players.playerMap.entries()]; + const matching = allPlayers.filter(([, player]) => filter(player)); + + if (matching.length === 0) { + const has247 = allPlayers.some(([, player]) => player._home247Channel); + const hintLine = showHintIfEmpty && has247 + ? `\n\n💡 No ghosts auto-detected, but 24/7 channels with dead WebSockets may still report as "connected".\nUse \`%debug 247-rejoin\` to force-rejoin all 24/7 channels.` + : ""; + const embed = new EmbedBuilder() + .setColor(SUCCESS_COLOR) + .setTitle(`Debug — ${title}`) + .setDescription(`No ${noun} found. All voice connections appear healthy.${hintLine}`) + ; + return msg.reply({ embeds: [embed] }); + } + + const statusLines = [ + `🔄 **${title}** — Found **${matching.length}** ${noun}`, + `Destroying stale connections and respawning fresh players...`, + ``, + ]; + + for (let i = 0; i < matching.length; i++) { + const [cid, player] = matching[i]; + const label = buildPlayerLabel(this.client, cid, player); + const ghost = isGhostConnection(player) ? " 👻GHOST" : ""; + const roomLabel = player.connection?.room ? roomStateLabel(player.connection.room) : "none"; + const connectedLabel = player.connection?.room?.isConnected ? "yes" : "no"; + statusLines.push(`${i + 1}. \`${label}\` — room:${roomLabel} isConnected:${connectedLabel}${ghost}`); + } + + const statusEmbed = new EmbedBuilder() + .setColor(WARN_COLOR) + .setTitle(`Debug — ${title}`) + .setDescription(statusLines.join("\n").slice(0, MAX_DESC)) + ; + const statusMsg = await msg.reply({ embeds: [statusEmbed] }); + + const results = await processRejoinBatch(this, matching, statusMsg, title); + + const finalPayload = buildRejoinResultEmbed(results, title, noun); + await statusMsg.edit(finalPayload).catch(() => { + msg.reply(finalPayload); + }); +} diff --git a/commands/debug/voiceDiagnostic.mjs b/commands/debug/voiceDiagnostic.mjs new file mode 100644 index 0000000..469f74b --- /dev/null +++ b/commands/debug/voiceDiagnostic.mjs @@ -0,0 +1,236 @@ +/** + * @module commands/debug/voiceDiagnostic + * @description Full voice diagnostic renderer for the debug command. Verbatim from the original single-file command. + */ + +import { EmbedBuilder } from "@fluxerjs/core"; +import { logger } from "../../src/core/Logger.mjs"; +import { getGlobalColor, cleanId } from "../../src/ui/index.mjs"; +import { DANGER_COLOR, EMOJI_REMOVE_TIMEOUT } from "../../src/utils/UI.mjs"; +import { MAX_DESC } from "./consts.mjs"; +import { + roomStateLabel, isGhostConnection, getBotGatewayVoiceState, isStaleGatewayPresence, +} from "./gateway.mjs"; + +/** + * Run a full voice diagnostic, displaying player states and ghost connections. + * @private + * @async + * @param {object} msg - The command message wrapper. + * @returns {Promise} + */ +export async function runVoiceDiagnostic(msg) { + const servers = [...this.players.playerMap.entries()].map(([cid, s]) => { + const channel = this.client.channels.get(cid); + const guildId = s._guildId ?? channel?.guildId ?? channel?.guild_id; + const guild = guildId ? this.client.guilds.get(cleanId(guildId)) : null; + const conn = s.connection; + const room = conn?.room; + const ghost = isGhostConnection(s); + const staleGateway = ghost ? isStaleGatewayPresence(this.client, s) : false; + const gatewayVoiceState = getBotGatewayVoiceState(this.client, guildId); + return { + name: channel?.name ?? "unknown", + id: channel?.id ?? cid, + channelId: s._channelId ?? cid, + guildId: guildId ?? "unknown", + guildname: guild?.name ?? channel?.guild?.name ?? "unknown", + conn: conn ? "yes" : "null", + connDestroyed: conn?._destroyed ?? null, + roomConnected: room?.isConnected ?? null, + roomState: roomStateLabel(room), + mediaPlayer: !!s._mediaPlayer && !s._mediaPlayer?.destroyed ? "alive" : (s._mediaPlayer?.destroyed ? "destroyed" : "none"), + destroyed: s._destroyed ?? false, + leaving: s.leaving ?? false, + joining: s._isJoining ?? false, + recovering: s._isRecovering ?? false, + paused: s._paused ?? false, + hasQueue: !!(s.queue?.getCurrent() || !s.queue?.isEmpty()), + home247: s._home247Channel ?? null, + ghost, + staleGateway, + gatewayVoiceChannel: gatewayVoiceState?.channelId ?? null, + }; + }); + const pending = [...(this.players._pendingJoins ?? [])]; + + const ghostConnections = servers.filter(s => s.ghost); + const livePlayers = servers.filter(s => s.conn === "yes" && !s.destroyed && !s.leaving); + const actuallyConnected = livePlayers.filter(s => !s.ghost); + const channels247 = servers.filter(s => s.home247); + + const summary = { + playerMapSize: this.players.playerMap.size, + livePlayers: livePlayers.length, + actuallyConnected: actuallyConnected.length, + ghostConnections: ghostConnections.length, + channels247: channels247.length, + pendingJoins: pending.length, + pendingChannels: pending, + }; + + const pages = []; + + const summaryLines = [ + `📊 **Summary**`, + `Players in map: **${summary.playerMapSize}**`, + `Live players: **${summary.livePlayers}**`, + `Actually connected: **${summary.actuallyConnected}**`, + `Ghost connections: **${summary.ghostConnections}**`, + `24/7 channels: **${summary.channels247}**`, + `Pending joins: **${summary.pendingJoins}**${summary.pendingChannels.length ? ` (\`${summary.pendingChannels.join("`, `")}\`)` : ""}`, + ]; + + if (ghostConnections.length > 0) { + summaryLines.push("", `👻 **Ghost Connections (${ghostConnections.length}):**`, "These players *appear* in voice but their WebSocket/LiveKit room is dead:"); + summaryLines.push(`Use \`%debug voice-rejoin\` to rejoin detected ghosts, or \`%debug 247-rejoin\` to force-rejoin all 24/7 channels.`); + for (const g of ghostConnections) { + const gatewayInfo = g.staleGateway + ? `gateway:stale(ch:${g.gatewayVoiceChannel ?? "?"})` + : `gateway:present(ch:${g.gatewayVoiceChannel ?? "?"})`; + const detail = ` 👻 \`${g.guildname}\` / \`#${g.name}\` — room:${g.roomState} connected:${g.roomConnected} media:${g.mediaPlayer} ${gatewayInfo} 247:${g.home247 ?? "no"}`; + if (summaryLines.join("\n").length + detail.length + 1 > MAX_DESC - 60) { + summaryLines.push(` … and more ghosts (see JSON details)`); + break; + } + summaryLines.push(detail); + } + } + + if (channels247.length > 0 && ghostConnections.length === 0) { + summaryLines.push("", `ℹ️ **24/7 Channels (${channels247.length}):**`, `WebSocket deaths can leave 24/7 channels as invisible ghosts (room reports healthy but transport is dead).`); + summaryLines.push(`Use \`%debug 247-rejoin\` to force-rejoin all 24/7 channels if you suspect ghost connections.`); + } + + summaryLines.push("", "**Players:**"); + for (let i = 0; i < servers.length; i++) { + const s = servers[i]; + let status; + if (s.ghost) { + status = "👻"; + } else if (s.conn === "yes" && !s.destroyed && !s.leaving) { + status = "🟢"; + } else { + status = "🔴"; + } + const ghostTag = s.ghost ? " ⚠️GHOST" : ""; + const staleTag = s.staleGateway ? " ⚠️STALE_GW" : ""; + const tag247 = s.home247 ? " 🔄247" : ""; + const line = `${status} \`${s.guildname}\` / \`#${s.name}\` — conn:${s.conn} room:${s.roomState} connected:${s.roomConnected} media:${s.mediaPlayer}${ghostTag}${staleTag}${tag247}`; + if (summaryLines.join("\n").length + line.length + 1 > MAX_DESC - 30) { + summaryLines.push(`… and ${servers.length - i} more (see next pages)`); + break; + } + summaryLines.push(line); + } + pages.push(summaryLines.join("\n")); + + let groupJson = ""; + for (let i = 0; i < servers.length; i++) { + const singleJson = JSON.stringify(servers[i], null, 2); + const candidate = groupJson + ? groupJson.slice(0, -1) + ",\n" + singleJson.slice(1) + : singleJson; + + const candidateLen = ("```json\n" + candidate + "\n```").length; + + if (candidateLen > MAX_DESC && groupJson) { + pages.push(("```json\n" + groupJson + "\n```").slice(0, MAX_DESC)); + groupJson = singleJson; + } else if (candidateLen > MAX_DESC) { + const budget = MAX_DESC - 12; + pages.push(("```json\n" + singleJson.slice(0, budget) + "\n```").slice(0, MAX_DESC)); + groupJson = ""; + } else { + groupJson = candidate; + } + } + if (groupJson) { + pages.push(("```json\n" + groupJson + "\n```").slice(0, MAX_DESC)); + } + + if (pages.length === 1) { + const embedColor = ghostConnections.length > 0 ? DANGER_COLOR : getGlobalColor(); + const embed = new EmbedBuilder() + .setColor(embedColor) + .setTitle(this.t(msg, "responses.debug.voiceTitle") + (ghostConnections.length > 0 ? ` — ${ghostConnections.length} Ghost(s) Detected!` : "")) + .setDescription(pages[0].slice(0, MAX_DESC)) + ; + return msg.reply({ embeds: [embed] }); + } + + const totalPages = pages.length; + let currentPage = 0; + + const buildPage = (pageIdx, expired = false) => { + const isSummaryPage = pageIdx === 0; + const pageLabel = isSummaryPage + ? "Summary" + : `Player Detail${pages[pageIdx].split(`"name":`).length - 1 > 1 ? "s" : ""}`; + const footerText = expired + ? this.t(msg, "responses._common.controlsExpired") + : `${this.t(msg, "responses.debug.pageLabel", { page: pageIdx + 1, total: totalPages })} • ${this.t(msg, "responses.eval.navigateHint")}`; + + const embedColor = (isSummaryPage && ghostConnections.length > 0) ? DANGER_COLOR : getGlobalColor(); + const titleSuffix = (isSummaryPage && ghostConnections.length > 0) ? ` — ${ghostConnections.length} Ghost(s) Detected!` : ""; + + const embed = new EmbedBuilder() + .setColor(embedColor) + .setTitle(this.t(msg, "responses.debug.voiceTitle") + titleSuffix + ` — ${pageLabel}`) + .setDescription(pages[pageIdx].slice(0, MAX_DESC)) + .setFooter({ text: footerText }) + ; + return { embeds: [embed] }; + }; + + const replyMsg = await msg.reply(buildPage(0)); + if (!replyMsg?.message) return; + + const navEmojis = ["⬅️", "➡️", "❌"]; + for (const emoji of navEmojis) { + await replyMsg.message.react(emoji).catch(() => {}); + } + + const clearReactions = async () => { + try { + await replyMsg.message.removeAllReactions(); + } catch (e) { + for (const emoji of navEmojis) { + try { await replyMsg.message.removeReaction(emoji); } catch (err) { logger.warn("[Debug] removeReaction fallback:", err?.message); } + } + } + }; + + let emojiTimeout; + const resetTimer = () => { + clearTimeout(emojiTimeout); + emojiTimeout = setTimeout(async () => { + unobserve?.(); + await clearReactions(); + await replyMsg.edit(buildPage(currentPage, true)).catch(() => {}); + }, EMOJI_REMOVE_TIMEOUT); + }; + + const unobserve = replyMsg.onReaction(navEmojis, async (e) => { + const emoji = e?.emoji_id ?? e?.emoji?.id ?? e?.emoji; + + if (emoji === "❌") { + clearTimeout(emojiTimeout); + unobserve?.(); + await replyMsg.message.delete().catch(() => {}); + return; + } + + resetTimer(); + + if (emoji === "⬅️") { + currentPage = currentPage > 0 ? currentPage - 1 : totalPages - 1; + } else if (emoji === "➡️") { + currentPage = currentPage < totalPages - 1 ? currentPage + 1 : 0; + } + + await replyMsg.edit(buildPage(currentPage)).catch(() => {}); + }); + + resetTimer(); +} diff --git a/commands/eval.mjs b/commands/eval.mjs index fb7be0d..c22f736 100644 --- a/commands/eval.mjs +++ b/commands/eval.mjs @@ -3,12 +3,12 @@ * @description Owner-only command to evaluate arbitrary JavaScript code and display the result. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; -import { logger } from "../src/constants/Logger.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; +import { logger } from "../src/core/Logger.mjs"; import { inspect } from "node:util"; -import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs"; +import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/utils/UI.mjs"; /** @private @type {string[]} Property name substrings that indicate sensitive/secret data. */ const RESTRICTED = [ @@ -88,7 +88,7 @@ function removeSensitive(obj, level = 0, visited = new WeakSet()) { * @private * @async * Sanitize a value for safe display: await promises, redact sensitive keys, - * inspect with node:util, and escape Discord markup characters. + * inspect with node:util, and escape markup characters. * @param {*} value - The raw eval result. * @returns {Promise} The sanitized output string. */ diff --git a/commands/filter.mjs b/commands/filter.mjs index 05ce88d..fa6e241 100644 --- a/commands/filter.mjs +++ b/commands/filter.mjs @@ -3,12 +3,12 @@ * @description Interactive audio filter picker with emoji-based selection and pagination. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; -import { Utils } from "../src/Utils.mjs"; -import { PREV_EMOJI, NEXT_EMOJI, CANCEL_EMOJI } from "../src/constants/UI.mjs"; -import { logger } from "../src/constants/Logger.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; +import { Utils } from "../src/utils/Utils.mjs"; +import { PREV_EMOJI, NEXT_EMOJI, CANCEL_EMOJI } from "../src/utils/UI.mjs"; +import { logger } from "../src/core/Logger.mjs"; const NAV_EMOJIS = [PREV_EMOJI, NEXT_EMOJI, CANCEL_EMOJI]; diff --git a/commands/forceleave.mjs b/commands/forceleave.mjs index cb90253..640ef91 100644 --- a/commands/forceleave.mjs +++ b/commands/forceleave.mjs @@ -3,8 +3,8 @@ * @description Force the bot to leave a voice channel (requires ManageChannels permission). */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; -import { cleanId } from "../src/MessageHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; +import { cleanId } from "../src/ui/index.mjs"; /** * @type {CommandBuilder} diff --git a/commands/invite.mjs b/commands/invite.mjs index 2c7b3cb..d1e5f68 100644 --- a/commands/invite.mjs +++ b/commands/invite.mjs @@ -3,9 +3,9 @@ * @description Display the bot invite link and support server information. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; /** * @type {CommandBuilder} diff --git a/commands/join.mjs b/commands/join.mjs index e6486a1..3e10cf5 100644 --- a/commands/join.mjs +++ b/commands/join.mjs @@ -6,9 +6,9 @@ * 24/7 handling, event binding, and permission checks. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor, cleanId, getMessageGuildId } from "../src/MessageHandler.mjs"; +import { getGlobalColor, cleanId, getMessageGuildId } from "../src/ui/index.mjs"; /** * @type {CommandBuilder} diff --git a/commands/lastfm.mjs b/commands/lastfm.mjs index 025dfc8..c212830 100644 --- a/commands/lastfm.mjs +++ b/commands/lastfm.mjs @@ -1,19 +1,26 @@ /** * @module commands/lastfm * @description Last.fm integration command supporting account linking, scrobbling, - * profile viewing, leaderboards, whoknows, and playlist playback. + * profile viewing, leaderboards, whoknows, and playlist playback. The action + * implementations live in commands/lastfm/ (one module per action family); + * run() below dispatches to them via their action sets. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; -import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; -import { Utils } from "../src/Utils.mjs"; -import { logger } from "../src/constants/Logger.mjs"; -import { PROVIDER_CHOICES } from "../src/constants/providers.mjs"; -import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; +import { + ACCOUNT_ACTIONS, runAccountActions, + PLAYBACK_ACTIONS, runPlaybackActions, + LISTENING_ACTIONS, runListeningActions, + WHOKNOWS_ACTIONS, runWhoknowsActions, + INFO_ACTIONS, runInfoActions, + TAG_ACTIONS, runTagActions, + DISCOVERY_ACTIONS, runDiscoveryActions, + runLastFmHelp, + notConfigured, +} from "./lastfm/index.mjs"; -const VALID_PERIODS = ["7day", "1month", "3month", "6month", "12month", "overall"]; +export { playLastFmCategory } from "./lastfm/playback.mjs"; /** * @type {CommandBuilder} @@ -54,327 +61,6 @@ export const command = new CommandBuilder() .setRequired(false) ); -/** - * Return an embed indicating Last.fm is not configured. - * @private - * @param {object} ctx - The bot (Remix) instance context. - * @param {object} msg - The command message wrapper. - * @returns {{ embeds: EmbedBuilder[] }} Error embed payload. - */ -function notConfigured(ctx, msg) { - return { - embeds: [new EmbedBuilder() - .setColor(ERROR_COLOR) - .setDescription(ctx.t(msg, "responses.lastfm.notConfigured"))] - }; -} - -/** - * Return an embed indicating the user has not linked their Last.fm account. - * @private - * @param {object} ctx - The bot (Remix) instance context. - * @param {object} msg - The command message wrapper. - * @param {string} prefix - The guild's command prefix. - * @returns {{ embeds: EmbedBuilder[] }} Error embed payload. - */ -function notLinked(ctx, msg, prefix) { - return { - embeds: [new EmbedBuilder() - .setColor(getGlobalColor()) - .setDescription(ctx.t(msg, "responses.lastfm.notLinked", { prefix }))] - }; -} - -const SIMPLE_CATEGORIES = ["loved", "top", "recent", "albums", "artists"]; - -/** - * Build a Last.fm track metadata object from a track. - * @private - * @param {object} track - The track object with artist, name, and url. - * @returns {{ source: string, artist: string, name: string, url: string }} Track metadata. - */ -function buildLastFmTrackMeta(track) { - return { - source: "lastfm", - artist: track.artist, - name: track.name, - url: track.url ?? "", - }; -} - -/** - * Resolve a Last.fm track to playable audio via a search provider. - * @private - * @async - * @param {object} player - The player instance. - * @param {object} track - The Last.fm track with query and metadata. - * @param {string} [resolveProvider="yt"] - The provider to resolve with. - * @returns {Promise} Array of resolved track data, or null on failure. - */ -async function resolveLastFmTrack(player, track, resolveProvider = "yt") { - const data = await player.generalQuery({ - query: track.query, - provider: resolveProvider, - trackMeta: buildLastFmTrackMeta(track), - }); - - if (!data || data.type === "error") return null; - if (data.type === "video") return [data.data]; - if (data.type === "list") return data.data ?? []; - return null; -} - -/** - * Extract Last.fm-relevant info from the player's current track. - * @private - * @param {object} player - The player instance. - * @returns {{ artist: string|null, name: string|null, album: string|null, track: object|null }} Extracted track info. - */ -function extractCurrentTrack(player) { - const track = player?.queue?.getCurrent(); - if (!track) return null; - const artist = track.lastfm?.artist ?? track.requestedArtist ?? track.artist ?? track.artists?.[0]?.name ?? track.author?.name ?? null; - const name = track.lastfm?.name ?? track.requestedTitle ?? track.title ?? track.name ?? null; - const album = track.album ?? track.lastfm?.album ?? null; - return { artist, name, album, track }; -} - -/** - * Get all non-bot user IDs in a guild. - * @private - * @async - * @param {object} guild - The Discord guild object. - * @returns {Promise} Array of user ID strings. - */ -async function getGuildLinkedUsers(guild) { - const memberIds = []; - try { - const members = guild?.members; - if (members) { - const iter = typeof members.values === "function" ? members.values() : Object.values(members); - for (const m of iter) { - const userId = m.user?.id ?? m.id; - if (userId && !m.user?.bot) memberIds.push(String(userId)); - } - } - } catch(e) { logger.warn("[LastFm] Error:", e?.message); } - return memberIds; -} - -/** - * Extract a valid time period from command data or message content. - * @private - * @param {object} data - Parsed command data. - * @param {object} msg - The command message wrapper. - * @returns {string} The period string, defaults to "overall". - */ -function extractPeriod(data, msg) { - let raw = data.get("token")?.value; - if (!raw) { - const content = msg.message?.content ?? ""; - const args = content.split(/\s+/); - const last = args[args.length - 1]; - if (last && VALID_PERIODS.includes(last.toLowerCase())) raw = last; - } - if (raw && VALID_PERIODS.includes(raw.toLowerCase().trim())) { - return raw.toLowerCase().trim(); - } - return "overall"; -} - -/** - * Fetch and play tracks from a Last.fm category (loved, top, recent, albums, artists, playlist). - * @async - * @param {object} ctx - The bot (Remix) instance context. - * @param {object} msg - The command message wrapper. - * @param {string} userId - The Discord user ID. - * @param {string} category - The Last.fm category to play. - * @param {object} [options={}] - Additional options. - * @param {string} [options.resolveProvider="yt"] - Provider to resolve tracks with. - * @param {string} [options.playlistId] - Playlist number for playlist category. - * @returns {Promise} - */ -export async function playLastFmCategory(ctx, msg, userId, category, options = {}) { - const lastfm = ctx.lastfm; - const prefix = ctx.handler.getPrefix(msg.message?.guildId); - const resolveProvider = options.resolveProvider || "yt"; - - if (!lastfm || !lastfm.enabled) return msg.reply(notConfigured(ctx, msg)); - - const validCategories = [...SIMPLE_CATEGORIES, "playlist"]; - if (!validCategories.includes(category)) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( - `❌ Unknown category \`${category}\`. Use \`loved\`, \`top\`, \`recent\`, \`albums\`, \`artists\`, or \`playlist\`.` - )] - }); - } - - if (category === "playlist" && !options.playlistId) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( - `❌ Specify a playlist number. Use \`${prefix}lastfm playlists\` to see your playlists, then \`${prefix}lastfm play playlist \`.` - )] - }); - } - - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(ctx, msg, prefix)); - - const p = await ctx.getPlayer(msg, true, true, true); - if (!p) return; - - const categoryEmoji = { loved: "❤️", top: "📊", recent: "🕐", playlist: "📋", albums: "💿", artists: "🎤" }[category]; - const categoryLabel = { loved: "Loved", top: "Top", recent: "Recent", playlist: "Playlist", albums: "Top Albums", artists: "Top Artists" }[category]; - - const resolveLabel = resolveProvider !== "yt" ? ` via ${resolveProvider.toUpperCase()}` : ""; - - let statusMsg; - try { - statusMsg = await msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription( - `${categoryEmoji} Fetching your ${categoryLabel} tracks from Last.fm${resolveLabel}...` - )] - }); - } catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; } - - let result; - try { - result = await lastfm.getTracksForPlay(userId, category, options); - } catch (err) { - const errMsg = err.message === "NOT_LINKED" - ? notLinked(ctx, msg, prefix) - : { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(ctx.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; - if (statusMsg) statusMsg.edit(errMsg).catch(() => msg.reply(errMsg)); - else msg.reply(errMsg); - return; - } - - if (!result.tracks.length) { - const noTracks = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription( - `${categoryEmoji} No ${categoryLabel.toLowerCase()} tracks found for **${result.username}**.` - )] }; - if (statusMsg) statusMsg.edit(noTracks).catch(() => msg.reply(noTracks)); - else msg.reply(noTracks); - return; - } - - let added = 0; - let failed = 0; - - if (statusMsg) { - statusMsg.edit({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription( - `${categoryEmoji} Loading **${result.tracks.length}** ${categoryLabel.toLowerCase()} tracks from **${result.username}**${resolveLabel}...` - )] - }).catch(() => {}); - } - - for (const track of result.tracks) { - try { - const resolvedTracks = await resolveLastFmTrack(p, track, resolveProvider); - if (!resolvedTracks?.length) { - failed++; - continue; - } - - p.addManyToQueue(resolvedTracks, false); - added += resolvedTracks.length; - - if (!p.queue.getCurrent()) { - p.playNext(); - } - } catch (e) { - logger.warn("[LastfmCmd] Track resolve failed:", e?.message); - failed++; - } - } - - const summary = []; - if (added > 0) summary.push(`✅ Added **${added}** track${added !== 1 ? "s" : ""} to the queue`); - if (failed > 0) summary.push(`⚠️ ${failed} track${failed !== 1 ? "s" : ""} couldn't be found`); - - const doneEmbed = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription( - `${categoryEmoji} **${categoryLabel} Tracks — ${result.username}**\n${summary.join(" · ")}` - )] }; - - if (statusMsg) statusMsg.edit(doneEmbed).catch(() => msg.reply(doneEmbed)); - else msg.reply(doneEmbed); -} - -/** - * Parse play subcommand arguments for category and provider. - * @private - * @param {object} msg - The command message wrapper. - * @param {object} data - Parsed command data. - * @returns {{ category: string, resolveProvider?: string, playlistId?: string, showAllCategories?: boolean, invalidCategory?: string }} Parsed args. - */ -function parsePlayArgs(msg, data) { - let raw = data.get("token")?.value; - if (!raw) { - const content = msg.message?.content ?? ""; - const args = content.split(/\s+/); - const playIdx = args.indexOf("play"); - if (playIdx >= 0 && args[playIdx + 1]) { - raw = args.slice(playIdx + 1).join(" "); - } - } - - if (!raw) return { category: "" }; - - const lower = raw.toLowerCase().trim(); - - const subMatch = lower.match(/^([a-z]+):\s*(.*)$/); - if (subMatch) { - const maybeProvider = subMatch[1]; - const rest = subMatch[2].trim(); - if (PROVIDER_CHOICES.includes(maybeProvider)) { - const isLastFmProvider = maybeProvider === "lf" || maybeProvider === "lastfm"; - - if (!rest) { - if (isLastFmProvider) { - return { category: "", resolveProvider: maybeProvider, showAllCategories: true }; - } - return { category: "top", resolveProvider: maybeProvider }; - } - - if (isLastFmProvider) { - const playlistMatch = rest.match(/^playlist\s+(\d+)$/); - if (playlistMatch) { - return { category: "playlist", playlistId: playlistMatch[1], resolveProvider: maybeProvider }; - } - if (SIMPLE_CATEGORIES.includes(rest)) { - return { category: rest, resolveProvider: maybeProvider }; - } - } else { - if (rest === "top") { - return { category: "top", resolveProvider: maybeProvider }; - } - return { category: "", resolveProvider: maybeProvider, invalidCategory: rest }; - } - } - } - - if (PROVIDER_CHOICES.includes(lower)) { - const isLastFmProvider = lower === "lf" || lower === "lastfm"; - if (isLastFmProvider) { - return { category: "", resolveProvider: lower, showAllCategories: true }; - } - return { category: "top", resolveProvider: lower }; - } - - const playlistMatch = lower.match(/^playlist\s+(\d+)$/); - if (playlistMatch) { - return { category: "playlist", playlistId: playlistMatch[1] }; - } - - if (SIMPLE_CATEGORIES.includes(lower)) { - return { category: lower }; - } - - return { category: "" }; -} - /** * Run handler for the lastfm command. * Routes to the appropriate subcommand based on the action option. @@ -383,6 +69,7 @@ function parsePlayArgs(msg, data) { * @param {object} data - Parsed command data containing action, user, and token options. * @returns {Promise} */ + export async function run(msg, data) { const lastfm = this.lastfm; if (!lastfm || !lastfm.enabled) return msg.reply(notConfigured(this, msg)); @@ -392,2184 +79,19 @@ export async function run(msg, data) { const userId = msg.message?.author?.id ?? msg.author?.id; const targetUserId = data.get("user")?.value ?? null; - switch (action) { - case "link": { - const existing = await lastfm.getUser(userId); - if (existing) { - return msg.reply({ - embeds: [new EmbedBuilder() - .setColor(getGlobalColor()) - .setDescription(this.t(msg, "responses.lastfm.alreadyLinked", { username: existing.username, prefix }))] - }); - } - - let token; - try { - token = await lastfm.getAuthToken(); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.tokenFailed", { error: err.message }))] - }); - } - - const authUrl = lastfm.getAuthUrl(token); - - let sent = false; - try { - const dm = await msg.author.createDM(); - await dm.send({ - embeds: [new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(this.t(msg, "responses.lastfm.authLinkTitle")) - .setDescription(this.t(msg, "responses.lastfm.authLinkBody", { url: authUrl, prefix, token })) - ] - }); - sent = true; - } catch(e) { logger.warn("[LastFm] Error:", e?.message); } - - const replyEmbed = new EmbedBuilder() - .setColor(getGlobalColor()) - .setDescription( - sent - ? this.t(msg, "responses.lastfm.authDM", { prefix }) - : this.t(msg, "responses.lastfm.authDMFailed", { url: authUrl, prefix }) - ); - - return msg.reply({ embeds: [replyEmbed] }); - } - - case "confirm": { - let tokenValue = data.get("token")?.value; - if (!tokenValue) { - const rawContent = msg.message?.content ?? ""; - const args = rawContent.split(/\s+/); - const confirmIdx = args.indexOf("confirm"); - tokenValue = confirmIdx >= 0 ? args[confirmIdx + 1] : null; - } - - if (!tokenValue) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.confirmUsage", { prefix }))] - }); - } - - let session; - try { - session = await lastfm.getSession(tokenValue); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.confirmFailed", { error: err.message }))] - }); - } - - await lastfm.saveUser(userId, session.key, session.name); - - return msg.reply({ - embeds: [new EmbedBuilder() - .setColor(getGlobalColor()) - .setDescription(this.t(msg, "responses.lastfm.linked", { username: session.name }))] - }); - } - - case "unlink": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - await lastfm.removeUser(userId); - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.unlinked", { username: user.username }))] - }); - } - - case "scrobble": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - const newState = !user.scrobbleEnabled; - await lastfm.setScrobble(userId, newState); - - return msg.reply({ - embeds: [new EmbedBuilder() - .setColor(getGlobalColor()) - .setDescription(newState - ? this.t(msg, "responses.lastfm.scrobbleEnabled", { username: user.username }) - : this.t(msg, "responses.lastfm.scrobbleDisabled") - )] - }); - } - - case "np": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - let recentData; - try { - recentData = await lastfm.getRecentTracks(userId, 1); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - if (!recentData.length) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noRecent", { username: user.username }))] - }); - } - - const track = recentData[0]; - const statusEmoji = track.now ? this.t(msg, "responses.lastfm.nowPlaying") : this.t(msg, "responses.lastfm.lastPlayed"); - const embed = new EmbedBuilder() - .setColor(getGlobalColor()) - .setAuthor({ name: statusEmoji, iconURL: track.image || undefined }) - .setDescription(this.t(msg, "responses.lastfm.npTrackInfo", { name: track.name, artist: track.artist, url: track.url })) - .setFooter({ text: this.t(msg, "responses.lastfm.npFooter", { username: user.username }) }); - - return msg.reply({ embeds: [embed] }); - } - - case "profile": { - const profileUserId = targetUserId || userId; - const user = await lastfm.getUser(profileUserId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - let info; - try { - info = await lastfm.getUserInfo(profileUserId); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - lastfm.syncUserScrobbleCount(profileUserId).catch(() => {}); - - const embed = new EmbedBuilder() - .setColor(getGlobalColor()) - .setAuthor({ name: this.t(msg, "responses.lastfm.profileTitle", { username: info.name }), iconURL: info.image?.[2]?.["#text"] || undefined, url: info.url }) - .setDescription([ - this.t(msg, "responses.lastfm.profileScrobbles", { playcount: Utils.formatNumber(info.playcount ?? 0) }), - this.t(msg, "responses.lastfm.profileRegistered", { date: info.registered?.unixtime ? new Date(+info.registered.unixtime * 1000).toLocaleDateString() : "unknown" }), - this.t(msg, "responses.lastfm.profileScrobbleStatus", { status: user.scrobbleEnabled ? this.t(msg, "responses.lastfm.profileScrobbleEnabled") : this.t(msg, "responses.lastfm.profileScrobbleDisabled") }), - ``, - this.t(msg, "responses.lastfm.profileLink", { url: info.url }), - ].join("\n")) - .setFooter({ text: this.t(msg, "responses.lastfm.profileScrobbleFooter", { prefix }) }); - - return msg.reply({ embeds: [embed] }); - } - - case "playlists": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - let playlists; - try { - playlists = await lastfm.getPlaylists(userId); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - if (!playlists.length) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noPlaylists", { username: user.username }))] - }); - } - - const lines = playlists.map((pl, i) => { - const num = String(i + 1).padStart(2, " "); - const link = pl.url ? `[${pl.title}](${pl.url})` : pl.title; - return `\`${num}.\` ${link} — **${pl.trackCount}** tracks`; - }); - - const desc = lines.join("\n").slice(0, 4096); - - return msg.reply({ - embeds: [new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(this.t(msg, "responses.lastfm.playlistsTitle", { username: user.username })) - .setDescription(desc) - .setFooter({ text: this.t(msg, "responses.lastfm.playlistsFooter", { prefix }) })] - }); - } - - case "play": { - const parsed = parsePlayArgs(msg, data); - - if (parsed.invalidCategory) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( - `❌ \`${parsed.resolveProvider}:${parsed.invalidCategory}\` is not valid. Non-Last.fm providers only support \`top\`.\nUse \`${prefix}lastfm play ${parsed.resolveProvider}\` or \`${prefix}lastfm play ${parsed.resolveProvider}:top\` instead.\nFor other categories, use Last.fm as the resolve provider: \`${prefix}lastfm play lf:${parsed.invalidCategory}\`` - )] - }); - } - - if (!parsed.category) { - const lfProviderNote = parsed.showAllCategories && parsed.resolveProvider - ? `\n\n💡 \`${prefix}lastfm play ${parsed.resolveProvider}:\` — Specify a category after the provider:` - : ""; - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription([ - `❌ Usage: \`${prefix}lastfm play \``, - ``, - `**Categories:**`, - `\`loved\` — Play your loved tracks`, - `\`top\` — Play your top tracks`, - `\`recent\` — Play your recent tracks`, - `\`albums\` — Play your top albums`, - `\`artists\` — Play your top artists' tracks`, - `\`playlist \` — Play a playlist (use \`${prefix}lastfm playlists\` to list)`, - ``, - `**With a search provider (defaults to \`top\`):**`, - `\`${prefix}lastfm play td\` or \`${prefix}lastfm play td:top\` — Play top tracks, search on Tidal`, - `\`${prefix}lastfm play sp\` or \`${prefix}lastfm play sp:top\` — Play top tracks, search on Spotify`, - `\`${prefix}lastfm play dz\` or \`${prefix}lastfm play dz:top\` — Play top tracks, search on Deezer`, - `\`${prefix}lastfm play yt\` or \`${prefix}lastfm play yt:top\` — Play top tracks, search on YouTube`, - ``, - `**Last.fm as resolve provider (all categories):**`, - `\`${prefix}lastfm play lf:loved\` — Play loved tracks, search on Last.fm`, - `\`${prefix}lastfm play lf:top\` — Play top tracks, search on Last.fm`, - `\`${prefix}lastfm play lf:recent\` — Play recent tracks, search on Last.fm`, - `\`${prefix}lastfm play lf:albums\` — Play top albums, search on Last.fm`, - `\`${prefix}lastfm play lf:artists\` — Play top artists, search on Last.fm`, - ``, - `**Examples:**`, - `\`${prefix}lastfm play loved\``, - `\`${prefix}lastfm play td\``, - `\`${prefix}lastfm play sp:top\``, - `\`${prefix}lastfm play lf:loved\``, - `\`${prefix}lastfm play playlist 1\``, - lfProviderNote, - ].join("\n"))] - }); - } - - return playLastFmCategory(this, msg, userId, parsed.category, { - playlistId: parsed.playlistId, - resolveProvider: parsed.resolveProvider, - }); - } - - case "loved": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - let tracks; - try { - tracks = await lastfm.getLovedTracks(userId, 15); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - if (!tracks.length) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noLoved", { username: user.username }))] - }); - } - - return msg.reply({ embeds: [buildTrackList(user.username, this.t(msg, "responses.lastfm.lovedTitle", { username: user.username }), tracks, false, prefix)] }); - } - - case "top": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - const period = extractPeriod(data, msg); - - let tracks; - try { - tracks = await lastfm.getTopTracks(userId, period, 15); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - if (!tracks.length) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noTop", { username: user.username }))] - }); - } - - const periodLabel = period !== "overall" ? ` (${period})` : ""; - return msg.reply({ embeds: [buildTrackList(user.username, this.t(msg, "responses.lastfm.topTitle", { username: user.username }) + periodLabel, tracks, true, prefix)] }); - } - - case "leaderboard": - case "lb": { - let lb; - try { - lb = await lastfm.getLeaderboard(0, 10); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - if (!lb.entries.length) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription( - this.t(msg, "responses.lastfm.leaderboardEmpty", { prefix }) - )] - }); - } - - if (lb.totalPages <= 1) { - const embed = buildLeaderboardEmbed(lb, 0, prefix); - return msg.reply({ embeds: [embed] }); - } - - let currentPage = 0; - - const buildPage = (pageIdx, expired = false) => { - const footerText = expired - ? this.t(msg, "responses.lastfm.leaderboardControlsExpired") - : this.t(msg, "responses.lastfm.leaderboardPageFooter", { current: pageIdx + 1, total: lb.totalPages }); - const embed = buildLeaderboardEmbed(lb, pageIdx, prefix); - embed.setFooter({ text: footerText }); - return { embeds: [embed] }; - }; - - const replyMsg = await msg.reply(buildPage(0)); - if (!replyMsg?.message) return; - - const navEmojis = ["◀️", "▶️", "❌"]; - for (const emoji of navEmojis) { - await replyMsg.message.react(emoji).catch(() => {}); - } - - const clearReactions = async () => { - try { - await replyMsg.message.removeAllReactions(); - } catch { - for (const emoji of navEmojis) { - try { await replyMsg.message.removeReaction(emoji); } catch(e) { logger.warn("[LastFm] Error:", e?.message); } - } - } - }; - - let emojiTimeout; - const resetTimer = () => { - clearTimeout(emojiTimeout); - emojiTimeout = setTimeout(async () => { - unobserve?.(); - await clearReactions(); - await replyMsg.edit(buildPage(currentPage, true)).catch(() => {}); - }, EMOJI_REMOVE_TIMEOUT); - }; - - const unobserve = replyMsg.onReaction(navEmojis, async (e) => { - if (e.emoji_id === "❌") { - clearTimeout(emojiTimeout); - unobserve?.(); - await replyMsg.message.delete().catch(() => {}); - return; - } - - resetTimer(); - - if (e.emoji_id === "◀️") { - currentPage = currentPage > 0 ? currentPage - 1 : lb.totalPages - 1; - } else if (e.emoji_id === "▶️") { - currentPage = currentPage < lb.totalPages - 1 ? currentPage + 1 : 0; - } - - try { - lb = await lastfm.getLeaderboard(currentPage, 10); - } catch(e) { logger.warn("[LastFm] Error:", e?.message); } - - await replyMsg.edit(buildPage(currentPage)).catch(() => {}); - }); - - resetTimer(); - break; - } - - case "recent": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - let tracks; - try { - tracks = await lastfm.getRecentTracks(userId, 15); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - if (!tracks.length) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noRecent", { username: user.username }))] - }); - } - - return msg.reply({ embeds: [buildTrackList(user.username, this.t(msg, "responses.lastfm.recentTitle", { username: user.username }), tracks, false, prefix)] }); - } - - case "artists": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - const period = extractPeriod(data, msg); - - let artists; - try { - artists = await lastfm.getTopArtists(userId, period, 15); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - if (!artists.length) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noArtists", { username: user.username }))] - }); - } - - const periodLabel = period !== "overall" ? ` (${period})` : ""; - const lines = artists.map((a, i) => { - const num = String(i + 1).padStart(2, " "); - let name = a.name; - if (name.length > 40) name = name.slice(0, 37) + "..."; - const link = a.url ? `[${name}](${a.url})` : name; - return `\`${num}.\` ${link} — **${a.playcount}** plays`; - }); - - const desc = lines.join("\n").slice(0, 4096); - - return msg.reply({ - embeds: [new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(this.t(msg, "responses.lastfm.artistsTitle", { username: user.username }) + periodLabel) - .setDescription(desc) - .setFooter({ text: this.t(msg, "responses.lastfm.artistsFooter", { prefix }) })] - }); - } - - case "love": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - const pLove = await this.getPlayer(msg, false, false, false); - if (!pLove) return; - const track = pLove.queue?.getCurrent(); - if (!track) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.nothingPlayingLove"))] - }); - } - - const artist = track.lastfm?.artist ?? track.requestedArtist ?? track.artist ?? track.artists?.[0]?.name ?? track.author?.name ?? "Unknown"; - const name = track.lastfm?.name ?? track.requestedTitle ?? track.title ?? track.name ?? "Unknown"; - - try { - await lastfm.loveTrack(userId, artist, name); - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.lovedTrack", { name, artist }))] - }); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.loveFailed", { error: err.message }))] - }); - } - } - - case "unlove": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - const pUnlove = await this.getPlayer(msg, false, false, false); - if (!pUnlove) return; - const track = pUnlove.queue?.getCurrent(); - if (!track) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.nothingPlayingUnlove"))] - }); - } - - const artist = track.lastfm?.artist ?? track.requestedArtist ?? track.artist ?? track.artists?.[0]?.name ?? track.author?.name ?? "Unknown"; - const name = track.lastfm?.name ?? track.requestedTitle ?? track.title ?? track.name ?? "Unknown"; - - try { - await lastfm.unloveTrack(userId, artist, name); - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.unlovedTrack", { name, artist }))] - }); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.unloveFailed", { error: err.message }))] - }); - } - } - - case "whoknows": - case "wk": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - let artistName = null; - const tokenTextWk = data.get("token")?.value; - if (tokenTextWk) { - artistName = tokenTextWk.trim(); - } else { - const pWk = await this.getPlayer(msg, false, false, false); - const current = extractCurrentTrack(pWk); - if (current?.artist) { - artistName = current.artist; - } - } - - if (!artistName) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.nothingPlayingNoArtist"))] - }); - } - - let statusMsg; - try { - statusMsg = await msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription( - this.t(msg, "responses.lastfm.whoknowsChecking", { artist: artistName }) - )] - }); - } catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; } - - const guild = msg.message?.guild ?? msg.message?.member?.guild; - const memberIds = await getGuildLinkedUsers(guild); - - let listeners; - try { - listeners = await lastfm.getWhoKnows(artistName, memberIds); - } catch (err) { - const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; - if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed)); - else msg.reply(errEmbed); - return; - } - - if (!listeners.length) { - const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription( - this.t(msg, "responses.lastfm.whoknowsNobody", { artist: artistName }) - )] }; - if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData)); - else msg.reply(noData); - return; - } - - const MEDALS = ["🥇", "🥈", "🥉"]; - const totalPlays = listeners.reduce((sum, l) => sum + l.playcount, 0); - - const lines = listeners.map((l, i) => { - const medal = i < 3 ? MEDALS[i] : ` `; - return `${medal} ${i + 1}. **${l.username}** — **${Utils.formatNumber(l.playcount)}** plays`; - }); - - const desc = lines.join("\n").slice(0, 4096); - - const embed = new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(this.t(msg, "responses.lastfm.whoknowsTitle", { artist: artistName })) - .setDescription(desc) - .setFooter({ text: this.t(msg, "responses.lastfm.whoknowsFooter", { count: listeners.length, plural: listeners.length !== 1 ? "s" : "", totalPlays: Utils.formatNumber(totalPlays) }) }); - - const replyPayload = { embeds: [embed] }; - if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload)); - else msg.reply(replyPayload); - return; - } - - case "artistinfo": - case "ai": { - const user = await lastfm.getUser(userId); - - let artistName = null; - - const pAi = await this.getPlayer(msg, false, false, false); - const current = extractCurrentTrack(pAi); - if (current?.artist) { - artistName = current.artist; - } - - const tokenText = data.get("token")?.value; - if (tokenText) { - artistName = tokenText.trim(); - } - - if (!artistName) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( - this.t(msg, "responses.lastfm.noArtistSpecified") - )] - }); - } - - let info; - try { - info = await lastfm.getArtistInfo(artistName, userId); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - if (!info) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.artistNotFound", { artist: artistName }))] - }); - } - - const embed = new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(`🎤 ${info.name}`) - .setURL(info.url || undefined) - .setThumbnail(info.image || undefined); - - const fields = []; - fields.push({ name: "Listeners", value: Utils.formatNumber(info.stats?.listeners ?? 0), inline: true }); - fields.push({ name: "Global Plays", value: Utils.formatNumber(info.stats?.playcount ?? 0), inline: true }); - - if (info.userplaycount != null && user) { - fields.push({ name: "Your Plays", value: Utils.formatNumber(info.userplaycount), inline: true }); - } - - if (info.tags?.length) { - const tagStr = info.tags.slice(0, 8).map(t => { - const tagLower = String(t).toLowerCase().replace(/\s+/g, "+"); - return `[${t}](https://www.last.fm/tag/${encodeURIComponent(tagLower)})`; - }).join(" · "); - fields.push({ name: "Tags", value: tagStr, inline: false }); - } - - if (info.similar?.length) { - const simStr = info.similar.slice(0, 5).map(s => { - return s.url ? `[${s.name}](${s.url})` : s.name; - }).join(" · "); - fields.push({ name: "Similar Artists", value: simStr, inline: false }); - } - - embed.addFields(...fields); - - if (info.bio) { - const cleanBio = info.bio.replace(/<[^>]*>/g, "").trim(); - if (cleanBio.length > 0) { - const truncated = cleanBio.length > 300 ? cleanBio.slice(0, 297) + "..." : cleanBio; - embed.setDescription(truncated); - } - } - - embed.setFooter({ text: user ? `Last.fm: ${user.username}` : "Last.fm" }); - - return msg.reply({ embeds: [embed] }); - } - - case "albuminfo": - case "ali": { - const user = await lastfm.getUser(userId); - - let artistName = null; - let albumName = null; - - const pAli = await this.getPlayer(msg, false, false, false); - const current = extractCurrentTrack(pAli); - if (current?.album && current?.artist) { - artistName = current.artist; - albumName = current.album; - } - - const tokenText = data.get("token")?.value; - if (tokenText) { - const dashMatch = tokenText.match(/^(.+?)\s*[-–—]\s*(.+)$/); - if (dashMatch) { - artistName = dashMatch[1].trim(); - albumName = dashMatch[2].trim(); - } else { - albumName = tokenText.trim(); - } - } - - if (!albumName) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( - this.t(msg, "responses.lastfm.noAlbumSpecified") - )] - }); - } - - let info; - try { - info = await lastfm.getAlbumInfo(artistName || "", albumName, userId); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - if (!info) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.albumNotFound", { album: albumName }))] - }); - } - - const embed = new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(`💿 ${info.name}`) - .setURL(info.url || undefined) - .setThumbnail(info.image || undefined); - - const fields = []; - - if (info.artist) { - fields.push({ name: "Artist", value: info.artist, inline: true }); - } - - if (info.userplaycount != null && user) { - fields.push({ name: "Your Plays", value: Utils.formatNumber(info.userplaycount), inline: true }); - } - - if (info.tags?.length) { - const tagStr = info.tags.slice(0, 8).map(t => { - const tagLower = String(t).toLowerCase().replace(/\s+/g, "+"); - return `[${t}](https://www.last.fm/tag/${encodeURIComponent(tagLower)})`; - }).join(" · "); - fields.push({ name: "Tags", value: tagStr, inline: false }); - } - - if (info.tracks?.length) { - const trackLines = info.tracks.slice(0, 15).map((t, i) => { - const num = String(i + 1).padStart(2, " "); - const dur = t.duration > 0 ? ` (${formatDuration(t.duration)})` : ""; - const link = t.url ? `[${t.name}](${t.url})` : t.name; - return `\`${num}.\` ${link}${dur}`; - }); - fields.push({ name: "Tracklist", value: trackLines.join("\n").slice(0, 1024), inline: false }); - } - - embed.addFields(...fields); - embed.setFooter({ text: user ? `Last.fm: ${user.username}` : "Last.fm" }); - - return msg.reply({ embeds: [embed] }); - } - - case "trackinfo": - case "ti": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - let artistName = null; - let trackName = null; - - const pTi = await this.getPlayer(msg, false, false, false); - const current = extractCurrentTrack(pTi); - if (current?.artist && current?.name) { - artistName = current.artist; - trackName = current.name; - } - - const tokenText = data.get("token")?.value; - if (tokenText) { - const dashMatch = tokenText.match(/^(.+?)\s*[-–—]\s*(.+)$/); - if (dashMatch) { - artistName = dashMatch[1].trim(); - trackName = dashMatch[2].trim(); - } else { - try { - const searchResult = await lastfm.searchTrack(tokenText.trim()); - if (searchResult) { - artistName = searchResult.artist; - trackName = searchResult.name; - } - } catch(e) { logger.warn("[LastFm] Error:", e?.message); } - } - } - - if (!artistName || !trackName) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( - this.t(msg, "responses.lastfm.noTrackSpecified") - )] - }); - } - - let info; - try { - info = await lastfm.getTrackInfo(artistName, trackName, userId); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - if (!info) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.trackNotFound", { track: trackName, artist: artistName }))] - }); - } - - const embed = new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(`🎵 ${info.name}`) - .setURL(info.url || undefined); - - if (info.album?.image?.[2]?.["#text"] || info.album?.image?.[1]?.["#text"]) { - embed.setThumbnail(info.album?.image?.[2]?.["#text"] || info.album?.image?.[1]?.["#text"]); - } - - const fields = []; - - if (info.artist?.name || info.artist?.["#text"]) { - fields.push({ name: "Artist", value: String(info.artist?.name ?? info.artist?.["#text"] ?? "Unknown"), inline: true }); - } - - if (info.album?.title) { - fields.push({ name: "Album", value: info.album.title, inline: true }); - } - - if (info.listeners) { - fields.push({ name: "Listeners", value: Utils.formatNumber(Number(info.listeners)), inline: true }); - } - - if (info.playcount) { - fields.push({ name: "Global Plays", value: Utils.formatNumber(Number(info.playcount)), inline: true }); - } - - if (info.userplaycount) { - fields.push({ name: "Your Plays", value: Utils.formatNumber(Number(info.userplaycount)), inline: true }); - } - - const userLoved = info.userloved === "1" || info.userloved === 1 || info.userloved === true; - fields.push({ name: "Loved", value: userLoved ? "❤️ Yes" : "🖤 No", inline: true }); - - if (info.toptags?.tag?.length) { - const tagStr = info.toptags.tag.slice(0, 8).map(t => { - const tagName = t.name ?? t; - const tagLower = String(tagName).toLowerCase().replace(/\s+/g, "+"); - return `[${tagName}](https://www.last.fm/tag/${encodeURIComponent(tagLower)})`; - }).join(" · "); - fields.push({ name: "Tags", value: tagStr, inline: false }); - } - - embed.addFields(...fields); - - if (info.wiki?.summary) { - const cleanSummary = info.wiki.summary.replace(/<[^>]*>/g, "").trim(); - if (cleanSummary.length > 0) { - const truncated = cleanSummary.length > 200 ? cleanSummary.slice(0, 197) + "..." : cleanSummary; - embed.setDescription(truncated); - } - } - - let similarTracks = []; - try { - similarTracks = await lastfm.getSimilarTracks(artistName, trackName, 5); - } catch(e) { logger.warn("[LastFm] Error:", e?.message); } - - if (similarTracks.length) { - const simStr = similarTracks.map(t => { - const matchPct = Math.round(t.match * 100); - const link = t.url ? `[${t.name}](${t.url})` : t.name; - return `${link} by **${t.artist}** (${matchPct}%)`; - }).join("\n"); - embed.addFields({ name: "Similar Tracks", value: simStr.slice(0, 1024), inline: false }); - } - - embed.setFooter({ text: `Last.fm: ${user.username}` }); - - return msg.reply({ embeds: [embed] }); - } - - case "topalbums": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - const period = extractPeriod(data, msg); - - let albums; - try { - albums = await lastfm.getTopAlbums(userId, period, 15); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - if (!albums.length) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noTopAlbums", { username: user.username }))] - }); - } - - const periodLabel = period !== "overall" ? ` (${period})` : ""; - - const lines = albums.map((a, i) => { - const num = String(i + 1).padStart(2, " "); - let albumTitle = a.name; - if (albumTitle.length > 30) albumTitle = albumTitle.slice(0, 27) + "..."; - const link = a.url ? `[${albumTitle}](${a.url})` : albumTitle; - return `\`${num}.\` ${link} — **${a.artist}** (**${a.playcount}** plays)`; - }); - - const desc = lines.join("\n").slice(0, 4096); - - const embed = new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(this.t(msg, "responses.lastfm.topAlbumsTitle", { period: periodLabel, username: user.username })) - .setDescription(desc); - - if (albums[0]?.image) { - embed.setThumbnail(albums[0].image); - } - - embed.setFooter({ text: this.t(msg, "responses.lastfm.topAlbumsFooter", { prefix }) }); - - return msg.reply({ embeds: [embed] }); - } - - case "toptags": - case "tags": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - let tags; - try { - tags = await lastfm.getUserTopTags(userId, 20); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - if (!tags.length) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noTopTags", { username: user.username }))] - }); - } - - const lines = tags.map((t, i) => { - const num = String(i + 1).padStart(2, " "); - const link = t.url ? `[${t.name}](${t.url})` : t.name; - return `\`${num}.\` ${link} — **${t.count}**`; - }); - - const desc = lines.join("\n").slice(0, 4096); - - return msg.reply({ - embeds: [new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(this.t(msg, "responses.lastfm.topTagsTitle", { username: user.username })) - .setDescription(desc) - .setFooter({ text: this.t(msg, "responses.lastfm.topTagsFooter", { prefix }) })] - }); - } - - case "tag": { - const tagName = data.get("token")?.value; - if (!tagName) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( - this.t(msg, "responses.lastfm.tagProvideName", { prefix }) - )] - }); - } - - let tagInfo; - let topTracks; - let topArtists; - - try { - [tagInfo, topTracks, topArtists] = await Promise.all([ - lastfm.getTagInfo(tagName), - lastfm.getTagTopTracks(tagName, 5), - lastfm.getTagTopArtists(tagName, 5), - ]); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - if (!tagInfo) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.tagNotFound", { tag: tagName }))] - }); - } - - const embed = new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(`🏷️ ${tagInfo.name}`) - .setURL(tagInfo.url || undefined); - - const fields = []; - fields.push({ name: "Reach", value: Utils.formatNumber(tagInfo.reach), inline: true }); - fields.push({ name: "Total Taggings", value: Utils.formatNumber(tagInfo.count), inline: true }); - - if (topArtists.length) { - const artistStr = topArtists.map((a, i) => { - const link = a.url ? `[${a.name}](${a.url})` : a.name; - return `${i + 1}. ${link} (**${Utils.formatNumber(a.playcount)}** plays)`; - }).join("\n"); - fields.push({ name: "Top Artists", value: artistStr.slice(0, 1024), inline: false }); - } - - if (topTracks.length) { - const trackStr = topTracks.map((t, i) => { - const link = t.url ? `[${t.name}](${t.url})` : t.name; - return `${i + 1}. ${link} by **${t.artist}**`; - }).join("\n"); - fields.push({ name: "Top Tracks", value: trackStr.slice(0, 1024), inline: false }); - } - - embed.addFields(...fields); - - if (tagInfo.summary) { - const cleanSummary = tagInfo.summary.replace(/<[^>]*>/g, "").trim(); - if (cleanSummary.length > 0) { - const truncated = cleanSummary.length > 300 ? cleanSummary.slice(0, 297) + "..." : cleanSummary; - embed.setDescription(truncated); - } - } - - return msg.reply({ embeds: [embed] }); - } - - case "compare": - case "fmc": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - if (!targetUserId) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( - this.t(msg, "responses.lastfm.compareSpecifyUser", { prefix }) - )] - }); - } - - const targetUser = await lastfm.getUser(targetUserId); - if (!targetUser) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( - this.t(msg, "responses.lastfm.compareUserNotLinked") - )] - }); - } - - let comparison; - try { - comparison = await lastfm.compareUsers(userId, targetUserId); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - if (!comparison) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.compareFailed"))] - }); - } - - const embed = new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(this.t(msg, "responses.lastfm.compareTitle")) - .setDescription([ - `**${comparison.user1.username}** vs **${comparison.user2.username}**`, - ``, - `📊 **${comparison.matchPercentage}%** match`, - ``, - `👤 ${comparison.user1.username}: ${comparison.user1.totalArtists} top artists`, - `👤 ${comparison.user2.username}: ${comparison.user2.totalArtists} top artists`, - ].join("\n")); - - if (comparison.commonArtists?.length) { - const commonStr = comparison.commonArtists.slice(0, 15).map((a, i) => { - const num = String(i + 1).padStart(2, " "); - const link = a.url ? `[${a.name}](${a.url})` : a.name; - return `\`${num}.\` ${link} (**${a.playcount}** plays)`; - }).join("\n"); - embed.addFields({ name: `Common Artists (${comparison.commonArtists.length})`, value: commonStr.slice(0, 1024), inline: false }); - } - - return msg.reply({ embeds: [embed] }); - } - - case "cover": - case "art": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - const pCover = await this.getPlayer(msg, false, false, false); - const current = extractCurrentTrack(pCover); - if (!current || !current.name) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.coverNothingPlaying"))] - }); - } - - const artistName = current.artist ?? "Unknown"; - const trackName = current.name; - const albumName = current.album; - - let coverUrl = null; - let albumTitle = albumName ?? "Unknown Album"; - - if (albumName) { - try { - const albumInfo = await lastfm.getAlbumInfo(artistName, albumName, userId); - if (albumInfo?.image) { - coverUrl = albumInfo.image; - albumTitle = `${albumInfo.name} by ${albumInfo.artist}`; - } - } catch(e) { logger.warn("[LastFm] Error:", e?.message); } - } - - if (!coverUrl) { - try { - const trackInfo = await lastfm.getTrackInfo(artistName, trackName, userId); - if (trackInfo?.album?.image) { - const images = trackInfo.album.image; - coverUrl = images?.[2]?.["#text"] || images?.[1]?.["#text"] || images?.[0]?.["#text"] || null; - if (trackInfo.album?.title) { - albumTitle = trackInfo.album.title; - } - } - } catch(e) { logger.warn("[LastFm] Error:", e?.message); } - } - - if (!coverUrl) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.coverNotFound", { track: trackName, artist: artistName }))] - }); - } - - const embed = new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(this.t(msg, "responses.lastfm.coverTitle", { album: albumTitle })) - .setImage(coverUrl) - .setFooter({ text: this.t(msg, "responses.lastfm.coverFooter", { track: trackName, artist: artistName }) }); - - return msg.reply({ embeds: [embed] }); - } - - case "refreshmembers": - case "rm": { - const guild = msg.message?.guild ?? msg.message?.member?.guild; - if (!guild) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.refreshFailed"))] - }); - } - let count = 0; - try { - if (guild.members && typeof guild.members.fetch === "function") { - const fetched = await guild.members.fetch(); - count = fetched.size; - } else { - const memberIds = await getGuildLinkedUsers(guild); - count = memberIds.length; - } - } catch { - const memberIds = await getGuildLinkedUsers(guild); - count = memberIds.length; - } - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.refreshSuccess", { count: Utils.formatNumber(count) }))] - }); - } - - case "affinity": - case "af": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - const guild = msg.message?.guild ?? msg.message?.member?.guild; - const memberIds = await getGuildLinkedUsers(guild); - - if (memberIds.length < 2) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.affinityNeedUsers"))] - }); - } - - let statusMsg; - try { - statusMsg = await msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.affinityChecking"))] - }); - } catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; } - - let affinityResults; - try { - affinityResults = await lastfm.getAffinity(memberIds, 10); - } catch (err) { - const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; - if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed)); - else msg.reply(errEmbed); - return; - } - - if (!affinityResults.length) { - const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.affinityNoCommon"))] }; - if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData)); - else msg.reply(noData); - return; - } - - const lines = affinityResults.map(r => { - const topCommon = r.commonArtists.slice(0, 3).map(a => a.name).join(", "); - return `**${r.users[0]}** & **${r.users[1]}** — ${r.matchCount} common artists (${topCommon}${r.commonArtists.length > 3 ? "..." : ""})`; - }); - - const desc = lines.join("\n").slice(0, 4096); - - const embed = new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(this.t(msg, "responses.lastfm.affinityTitle")) - .setDescription(desc) - .setFooter({ text: this.t(msg, "responses.lastfm.affinityFooter", { count: memberIds.length }) }); - - const replyPayload = { embeds: [embed] }; - if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload)); - else msg.reply(replyPayload); - return; - } - - case "crowns": - case "cr": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - const guild = msg.message?.guild ?? msg.message?.member?.guild; - const memberIds = await getGuildLinkedUsers(guild); - - let statusMsg; - try { - statusMsg = await msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.crownsChecking"))] - }); - } catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; } - - let crowns; - try { - crowns = await lastfm.getCrowns(userId, memberIds); - } catch (err) { - const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; - if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed)); - else msg.reply(errEmbed); - return; - } - - if (!crowns.length) { - const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.crownsNone"))] }; - if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData)); - else msg.reply(noData); - return; - } - - const tokenFilter = data.get("token")?.value?.toLowerCase().trim(); - - let filteredCrowns = crowns; - if (tokenFilter === "stolen") { - filteredCrowns = crowns.filter(c => c.nextBest && c.nextBest.playcount > 0); - } else if (tokenFilter === "recent") { - filteredCrowns = crowns.slice(0, 10); - } - - const lines = filteredCrowns.slice(0, 20).map(c => { - const link = c.artistUrl ? `[${c.artist}](${c.artistUrl})` : c.artist; - const nextStr = c.nextBest ? ` (next: **${c.nextBest.username}** with ${Utils.formatNumber(c.nextBest.playcount)})` : ""; - return `👑 ${link} — **${Utils.formatNumber(c.userPlaycount)}** plays${nextStr}`; - }); - - const desc = lines.join("\n").slice(0, 4096); - - const embed = new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(this.t(msg, "responses.lastfm.crownsTitle", { username: user.username })) - .setDescription(desc) - .setFooter({ text: this.t(msg, "responses.lastfm.crownsFooter", { count: filteredCrowns.length, plural: filteredCrowns.length !== 1 ? "s" : "" }) }); - - if (filteredCrowns[0]?.image) { - embed.setThumbnail(filteredCrowns[0].image); - } - - const replyPayload = { embeds: [embed] }; - if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload)); - else msg.reply(replyPayload); - return; - } - - case "whoknowstrack": - case "wkt": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - let artistName = null; - let trackName = null; - - const pWkt = await this.getPlayer(msg, false, false, false); - const current = extractCurrentTrack(pWkt); - if (current?.artist && current?.name) { - artistName = current.artist; - trackName = current.name; - } - - const tokenTextWkt = data.get("token")?.value; - if (tokenTextWkt) { - const dashMatch = tokenTextWkt.match(/^(.+?)\s*[-–—]\s*(.+)$/); - if (dashMatch) { - artistName = dashMatch[1].trim(); - trackName = dashMatch[2].trim(); - } else { - try { - const searchResult = await lastfm.searchTrack(tokenTextWkt.trim()); - if (searchResult) { - artistName = searchResult.artist; - trackName = searchResult.name; - } - } catch(e) { logger.warn("[LastFm] Error:", e?.message); } - } - } - - if (!artistName || !trackName) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noTrackSpecified"))] - }); - } - - let statusMsg; - try { - statusMsg = await msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.whoknowsTrackChecking", { track: trackName, artist: artistName }))] - }); - } catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; } - - const guild = msg.message?.guild ?? msg.message?.member?.guild; - const memberIds = await getGuildLinkedUsers(guild); - - let listeners; - try { - listeners = await lastfm.getWhoKnowsTrack(artistName, trackName, memberIds); - } catch (err) { - const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; - if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed)); - else msg.reply(errEmbed); - return; - } - - if (!listeners.length) { - const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.whoknowsTrackNobody", { track: trackName, artist: artistName }))] }; - if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData)); - else msg.reply(noData); - return; - } - - const MEDALS = ["🥇", "🥈", "🥉"]; - const totalPlays = listeners.reduce((sum, l) => sum + l.playcount, 0); - - const lines = listeners.map((l, i) => { - const medal = i < 3 ? MEDALS[i] : ` `; - return `${medal} ${i + 1}. **${l.username}** — **${Utils.formatNumber(l.playcount)}** plays`; - }); - - const desc = lines.join("\n").slice(0, 4096); - - const embed = new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(this.t(msg, "responses.lastfm.whoknowsTrackTitle", { track: trackName })) - .setDescription(desc) - .setFooter({ text: this.t(msg, "responses.lastfm.whoknowsTrackFooter", { count: listeners.length, plural: listeners.length !== 1 ? "s" : "", totalPlays: Utils.formatNumber(totalPlays), artist: artistName }) }); - - const replyPayload = { embeds: [embed] }; - if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload)); - else msg.reply(replyPayload); - return; - } - - case "whoknowsalbum": - case "wka": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - let artistName = null; - let albumName = null; - - const pWka = await this.getPlayer(msg, false, false, false); - const current = extractCurrentTrack(pWka); - if (current?.album && current?.artist) { - artistName = current.artist; - albumName = current.album; - } - - const tokenTextWka = data.get("token")?.value; - if (tokenTextWka) { - const dashMatch = tokenTextWka.match(/^(.+?)\s*[-–—]\s*(.+)$/); - if (dashMatch) { - artistName = dashMatch[1].trim(); - albumName = dashMatch[2].trim(); - } else { - albumName = tokenTextWka.trim(); - } - } - - if (!albumName) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noAlbumSpecified"))] - }); - } - - let statusMsg; - try { - statusMsg = await msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.whoknowsAlbumChecking", { album: albumName, artistClause: artistName ? ` by **${artistName}**` : "" }))] - }); - } catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; } - - const guild = msg.message?.guild ?? msg.message?.member?.guild; - const memberIds = await getGuildLinkedUsers(guild); - - let listeners; - try { - listeners = await lastfm.getWhoKnowsAlbum(artistName || "", albumName, memberIds); - } catch (err) { - const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; - if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed)); - else msg.reply(errEmbed); - return; - } - - if (!listeners.length) { - const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.whoknowsAlbumNobody", { album: albumName }))] }; - if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData)); - else msg.reply(noData); - return; - } - - const MEDALS = ["🥇", "🥈", "🥉"]; - const totalPlays = listeners.reduce((sum, l) => sum + l.playcount, 0); - - const lines = listeners.map((l, i) => { - const medal = i < 3 ? MEDALS[i] : ` `; - return `${medal} ${i + 1}. **${l.username}** — **${Utils.formatNumber(l.playcount)}** plays`; - }); - - const desc = lines.join("\n").slice(0, 4096); - - const embed = new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(this.t(msg, "responses.lastfm.whoknowsAlbumTitle", { album: albumName })) - .setDescription(desc) - .setFooter({ text: this.t(msg, "responses.lastfm.whoknowsFooter", { count: listeners.length, plural: listeners.length !== 1 ? "s" : "", totalPlays: Utils.formatNumber(totalPlays) }) }); - - const replyPayload = { embeds: [embed] }; - if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload)); - else msg.reply(replyPayload); - return; - } - - case "artisttags": - case "at": { - let artistName = null; - - const pAt = await this.getPlayer(msg, false, false, false); - const current = extractCurrentTrack(pAt); - if (current?.artist) { - artistName = current.artist; - } - - const tokenTextAt = data.get("token")?.value; - if (tokenTextAt) { - artistName = tokenTextAt.trim(); - } - - if (!artistName) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noArtistSpecified"))] - }); - } - - let tags; - try { - tags = await lastfm.getArtistTopTags(artistName, 15); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - if (!tags.length) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noArtistTags", { artist: artistName }))] - }); - } - - const lines = tags.map((t, i) => { - const num = String(i + 1).padStart(2, " "); - const link = t.url ? `[${t.name}](${t.url})` : t.name; - return `\`${num}.\` ${link}${t.count > 0 ? ` — **${Utils.formatNumber(t.count)}**` : ""}`; - }); - - const desc = lines.join("\n").slice(0, 4096); - - return msg.reply({ - embeds: [new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(this.t(msg, "responses.lastfm.artistTagsTitle", { artist: artistName })) - .setDescription(desc)] - }); - } - - case "albumtags": - case "alt": { - let artistName = null; - let albumName = null; - - const pAlt = await this.getPlayer(msg, false, false, false); - const current = extractCurrentTrack(pAlt); - if (current?.album && current?.artist) { - artistName = current.artist; - albumName = current.album; - } - - const tokenTextAlt = data.get("token")?.value; - if (tokenTextAlt) { - const dashMatch = tokenTextAlt.match(/^(.+?)\s*[-–—]\s*(.+)$/); - if (dashMatch) { - artistName = dashMatch[1].trim(); - albumName = dashMatch[2].trim(); - } else { - albumName = tokenTextAlt.trim(); - } - } - - if (!albumName) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noAlbumSpecified"))] - }); - } - - let tags; - try { - tags = await lastfm.getAlbumTopTags(artistName || "", albumName, 15); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - if (!tags.length) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🏷️ No tags found for album **${albumName}**.`)] - }); - } - - const lines = tags.map((t, i) => { - const num = String(i + 1).padStart(2, " "); - const link = t.url ? `[${t.name}](${t.url})` : t.name; - return `\`${num}.\` ${link}${t.count > 0 ? ` — **${Utils.formatNumber(t.count)}**` : ""}`; - }); - - const desc = lines.join("\n").slice(0, 4096); - - return msg.reply({ - embeds: [new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(this.t(msg, "responses.lastfm.artistTagsTitle", { artist: albumName })) - .setDescription(desc)] - }); - } - - case "tracktags": - case "tt": { - let artistName = null; - let trackName = null; - - const pTt = await this.getPlayer(msg, false, false, false); - const current = extractCurrentTrack(pTt); - if (current?.artist && current?.name) { - artistName = current.artist; - trackName = current.name; - } - - const tokenTextTt = data.get("token")?.value; - if (tokenTextTt) { - const dashMatch = tokenTextTt.match(/^(.+?)\s*[-–—]\s*(.+)$/); - if (dashMatch) { - artistName = dashMatch[1].trim(); - trackName = dashMatch[2].trim(); - } else { - try { - const searchResult = await lastfm.searchTrack(tokenTextTt.trim()); - if (searchResult) { - artistName = searchResult.artist; - trackName = searchResult.name; - } - } catch(e) { logger.warn("[LastFm] Error:", e?.message); } - } - } - - if (!artistName || !trackName) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noTrackSpecified"))] - }); - } - - let tags; - try { - tags = await lastfm.getTrackTopTags(artistName, trackName, 15); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - if (!tags.length) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🏷️ No tags found for **${trackName}** by **${artistName}**.`)] - }); - } - - const lines = tags.map((t, i) => { - const num = String(i + 1).padStart(2, " "); - const link = t.url ? `[${t.name}](${t.url})` : t.name; - return `\`${num}.\` ${link}${t.count > 0 ? ` — **${Utils.formatNumber(t.count)}**` : ""}`; - }); - - const desc = lines.join("\n").slice(0, 4096); - - return msg.reply({ - embeds: [new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(this.t(msg, "responses.lastfm.artistTagsTitle", { artist: trackName })) - .setDescription(desc)] - }); - } - - case "friends": - case "fr": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - let friends; - try { - friends = await lastfm.getUserFriends(userId, 20); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - if (!friends.length) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`👥 No friends found for **${user.username}**.`)] - }); - } - - const lines = friends.map((f, i) => { - const num = String(i + 1).padStart(2, " "); - const link = f.url ? `[${f.name}](${f.url})` : f.name; - const details = []; - if (f.realname) details.push(f.realname); - if (f.country) details.push(f.country); - const detailStr = details.length > 0 ? ` (${details.join(", ")})` : ""; - return `\`${num}.\` ${link}${detailStr}`; - }); - - const desc = lines.join("\n").slice(0, 4096); - - return msg.reply({ - embeds: [new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(`👥 Friends — ${user.username}`) - .setDescription(desc)] - }); - } - - case "weekly": - case "wc": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - const tokenTextWc = data.get("token")?.value?.toLowerCase().trim() ?? "artists"; - let chartData; - let chartTitle; - - try { - if (tokenTextWc === "tracks") { - chartData = await lastfm.getUserWeeklyTrackChart(userId); - chartTitle = `📅 Weekly Track Chart — ${user.username}`; - } else if (tokenTextWc === "albums") { - chartData = await lastfm.getUserWeeklyAlbumChart(userId); - chartTitle = `📅 Weekly Album Chart — ${user.username}`; - } else { - chartData = await lastfm.getUserWeeklyArtistChart(userId); - chartTitle = `📅 Weekly Artist Chart — ${user.username}`; - } - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - if (!chartData.length) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`📅 No weekly chart data found for **${user.username}**.`)] - }); - } - - const lines = chartData.slice(0, 15).map((item, i) => { - const num = String(i + 1).padStart(2, " "); - const link = item.url ? `[${item.name}](${item.url})` : item.name; - const artistStr = item.artist ? ` by **${item.artist}**` : ""; - return `\`${num}.\` ${link}${artistStr} — **${Utils.formatNumber(item.playcount)}** plays`; - }); - - const desc = lines.join("\n").slice(0, 4096); - - return msg.reply({ - embeds: [new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(chartTitle) - .setDescription(desc) - .setFooter({ text: `💡 Use token option: artists, tracks, or albums` })] - }); - } - - case "trending": - case "tr": { - const tokenTextTr = data.get("token")?.value?.toLowerCase().trim() ?? "tracks"; - let trendingData; - let trendingTitle; - - try { - if (tokenTextTr === "artists") { - trendingData = await lastfm.getChartTopArtists(15); - trendingTitle = "🔥 Trending Artists on Last.fm"; - } else { - trendingData = await lastfm.getChartTopTracks(15); - trendingTitle = "🔥 Trending Tracks on Last.fm"; - } - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - if (!trendingData.length) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🔥 No trending data found.`)] - }); - } - - const lines = trendingData.map((item, i) => { - const num = String(i + 1).padStart(2, " "); - const link = item.url ? `[${item.name}](${item.url})` : item.name; - const artistStr = item.artist ? ` by **${item.artist}**` : ""; - const extra = item.listeners ? ` — ${Utils.formatNumber(item.listeners)} listeners` : item.playcount ? ` — ${Utils.formatNumber(item.playcount)} plays` : ""; - return `\`${num}.\` ${link}${artistStr}${extra}`; - }); - - const desc = lines.join("\n").slice(0, 4096); - - return msg.reply({ - embeds: [new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(trendingTitle) - .setDescription(desc) - .setFooter({ text: `💡 Use token option: tracks or artists` })] - }); - } - - case "geo": - case "g": { - const tokenTextG = data.get("token")?.value?.trim() ?? ""; - if (!tokenTextG) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Provide a query like \`artists \` or \`tracks \`. Example: \`${prefix}lastfm geo artists united states\`.`)] - }); - } - - const lowerToken = tokenTextG.toLowerCase(); - let type = "artists"; - let country = tokenTextG; - - if (lowerToken.startsWith("artists ")) { - type = "artists"; - country = tokenTextG.slice(8).trim(); - } else if (lowerToken.startsWith("tracks ")) { - type = "tracks"; - country = tokenTextG.slice(7).trim(); - } - - if (!country) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Please specify a country name. Example: \`${prefix}lastfm geo artists united states\`.`)] - }); - } - - let geoData; - let geoTitle; - - try { - if (type === "tracks") { - geoData = await lastfm.getGeoTopTracks(country, 15); - geoTitle = `🌍 Top Tracks in ${country}`; - } else { - geoData = await lastfm.getGeoTopArtists(country, 15); - geoTitle = `🌍 Top Artists in ${country}`; - } - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - if (!geoData.length) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🌍 No data found for **${country}**.`)] - }); - } - - const lines = geoData.map((item, i) => { - const num = String(i + 1).padStart(2, " "); - const link = item.url ? `[${item.name}](${item.url})` : item.name; - const artistStr = item.artist ? ` by **${item.artist}**` : ""; - const extra = item.listeners ? ` — ${Utils.formatNumber(item.listeners)} listeners` : ""; - return `\`${num}.\` ${link}${artistStr}${extra}`; - }); - - const desc = lines.join("\n").slice(0, 4096); - - return msg.reply({ - embeds: [new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(geoTitle) - .setDescription(desc)] - }); - } - - case "tagalbums": - case "ta": { - const tagName = data.get("token")?.value; - if (!tagName) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Provide a tag name via the token option. Example: \`${prefix}lastfm tagalbums rock\``)] - }); - } - - let albums; - try { - albums = await lastfm.getTagTopAlbums(tagName.trim(), 15); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - if (!albums.length) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`💿 No top albums found for tag **${tagName}**.`)] - }); - } - - const lines = albums.map((a, i) => { - const num = String(i + 1).padStart(2, " "); - const link = a.url ? `[${a.name}](${a.url})` : a.name; - return `\`${num}.\` ${link} by **${a.artist}**${a.playcount > 0 ? ` (${Utils.formatNumber(a.playcount)} plays)` : ""}`; - }); - - const desc = lines.join("\n").slice(0, 4096); - - const embed = new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(`💿 Top Albums — ${tagName}`) - .setDescription(desc); - - if (albums[0]?.image) { - embed.setThumbnail(albums[0].image); - } - - return msg.reply({ embeds: [embed] }); - } - - case "artisttracks": - case "atr": { - const user = await lastfm.getUser(userId); - if (!user) return msg.reply(notLinked(this, msg, prefix)); - - let artistName = null; - - const pAtr = await this.getPlayer(msg, false, false, false); - const current = extractCurrentTrack(pAtr); - if (current?.artist) { - artistName = current.artist; - } - - const tokenTextAtr = data.get("token")?.value; - if (tokenTextAtr) { - artistName = tokenTextAtr.trim(); - } - - if (!artistName) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noArtistSpecified"))] - }); - } - - let recentTracks; - try { - recentTracks = await lastfm.getRecentTracks(userId, 200); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - const artistTracks = recentTracks.filter(t => - t.artist.toLowerCase() === artistName.toLowerCase() - ); - - if (!artistTracks.length) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🎵 No scrobbles found for **${artistName}** in your recent history.`)] - }); - } - - const lines = artistTracks.slice(0, 15).map((t, i) => { - const num = String(i + 1).padStart(2, " "); - const link = t.url ? `[${t.name}](${t.url})` : t.name; - const nowStr = t.now ? " 🎵" : ""; - return `\`${num}.\` ${link}${nowStr}`; - }); - - const desc = lines.join("\n").slice(0, 4096); - - return msg.reply({ - embeds: [new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(`🎵 ${artistName} Scrobbles — ${user.username}`) - .setDescription(desc) - .setFooter({ text: `${artistTracks.length} scrobble${artistTracks.length !== 1 ? "s" : ""} found` })] - }); - } - - case "search": - case "s": { - const query = data.get("token")?.value; - if (!query) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Provide a search query via the token option. Example: \`${prefix}lastfm search radiohead\``)] - }); - } - - let artistResults, albumResults, trackResult; - try { - [artistResults, albumResults, trackResult] = await Promise.all([ - lastfm.searchArtist(query, 5), - lastfm.searchAlbum(query, 5), - lastfm.searchTrack(query), - ]); - } catch (err) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] - }); - } - - const sections = []; - - if (artistResults.length) { - const artistLines = artistResults.map((a, i) => { - const link = a.url ? `[${a.name}](${a.url})` : a.name; - const listeners = a.listeners ? ` — ${Utils.formatNumber(a.listeners)} listeners` : ""; - return `${i + 1}. ${link}${listeners}`; - }); - sections.push(`**🎤 Artists:**\n${artistLines.join("\n")}`); - } - - if (albumResults.length) { - const albumLines = albumResults.map((a, i) => { - const link = a.url ? `[${a.name}](${a.url})` : a.name; - return `${i + 1}. ${link} by **${a.artist}**`; - }); - sections.push(`**💿 Albums:**\n${albumLines.join("\n")}`); - } - - if (trackResult) { - sections.push(`**🎵 Best Track Match:**\n[${trackResult.name}](${trackResult.url}) by **${trackResult.artist}**`); - } - - if (!sections.length) { - return msg.reply({ - embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🔍 No results found for **${query}**.`)] - }); - } - - const desc = sections.join("\n\n").slice(0, 4096); - - return msg.reply({ - embeds: [new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(`🔍 Search Results for "${query}"`) - .setDescription(desc)] - }); - } - - default: - return msg.reply({ - embeds: [new EmbedBuilder() - .setColor(getGlobalColor()) - .setDescription([ - `🎵 **Last.fm Commands:**`, - ``, - `\`${prefix}lastfm link\` — Link your Last.fm account`, - `\`${prefix}lastfm unlink\` — Disconnect your account`, - `\`${prefix}lastfm scrobble\` — Toggle auto-scrobbling`, - `\`${prefix}lastfm np\` — Show your Last.fm now playing`, - `\`${prefix}lastfm profile\` — View your Last.fm profile (or another user's with user option)`, - `\`${prefix}lastfm loved\` — View your loved tracks`, - `\`${prefix}lastfm top\` — View your top tracks (supports period)`, - `\`${prefix}lastfm artists\` — View your top artists (supports period)`, - `\`${prefix}lastfm recent\` — View your recent tracks`, - `\`${prefix}lastfm playlists\` — View your Last.fm playlists`, - `\`${prefix}lastfm leaderboard\` — Scrobble leaderboard`, - `\`${prefix}lastfm love\` — Love the current track`, - `\`${prefix}lastfm unlove\` — Unlove the current track`, - ``, - `🔍 **Info Commands:**`, - `\`${prefix}lastfm whoknows [artist]\` — Who in the server listens to an artist`, - `\`${prefix}lastfm whoknowstrack\` — Who knows a specific track`, - `\`${prefix}lastfm whoknowsalbum\` — Who knows a specific album`, - `\`${prefix}lastfm artistinfo\` — Detailed info about an artist`, - `\`${prefix}lastfm albuminfo\` — Detailed info about an album`, - `\`${prefix}lastfm trackinfo\` — Detailed info about a track`, - `\`${prefix}lastfm topalbums\` — View your top albums (supports period)`, - `\`${prefix}lastfm toptags\` — View your top tags/genres`, - `\`${prefix}lastfm tag \` — View info about a specific tag`, - `\`${prefix}lastfm compare @user\` — Compare your taste with another user`, - `\`${prefix}lastfm cover\` — Get album cover art for the current track`, - ``, - `🏷️ **Tag Commands:**`, - `\`${prefix}lastfm artisttags\` — Top tags for an artist`, - `\`${prefix}lastfm albumtags\` — Top tags for an album`, - `\`${prefix}lastfm tracktags\` — Top tags for a track`, - `\`${prefix}lastfm tagalbums \` — Top albums for a tag`, - ``, - `👥 **Social Commands:**`, - `\`${prefix}lastfm affinity\` — Find users with similar taste`, - `\`${prefix}lastfm crowns\` — View your artist crowns (#1 listener)`, - `\`${prefix}lastfm friends\` — View your Last.fm friends`, - `\`${prefix}lastfm refreshmembers\` — Refresh server member cache`, - ``, - `📊 **Charts & Discovery:**`, - `\`${prefix}lastfm weekly [artists|tracks|albums]\` — Weekly charts`, - `\`${prefix}lastfm trending [tracks|artists]\` — Global trending on Last.fm`, - `\`${prefix}lastfm geo [artists|tracks] \` — Top by country`, - `\`${prefix}lastfm artisttracks\` — Your scrobbles for an artist`, - `\`${prefix}lastfm search \` — Universal search`, - ``, - `🎶 **Play from Last.fm:**`, - `\`${prefix}lastfm play loved\` — Play your loved tracks`, - `\`${prefix}lastfm play top\` — Play your top tracks`, - `\`${prefix}lastfm play recent\` — Play your recent tracks`, - `\`${prefix}lastfm play albums\` — Play your top albums`, - `\`${prefix}lastfm play artists\` — Play your top artists' tracks`, - `\`${prefix}lastfm play playlist 1\` — Play a playlist`, - ``, - `🎧 **Play with a specific provider (defaults to \`top\`):**`, - `\`${prefix}lastfm play sp\` or \`${prefix}lastfm play sp:top\` — Play top tracks, search on Spotify`, - `\`${prefix}lastfm play td\` or \`${prefix}lastfm play td:top\` — Play top tracks, search on Tidal`, - `\`${prefix}lastfm play dz\` or \`${prefix}lastfm play dz:top\` — Play top tracks, search on Deezer`, - `\`${prefix}lastfm play yt\` or \`${prefix}lastfm play yt:top\` — Play top tracks, search on YouTube`, - ``, - `🎧 **Last.fm as resolve provider (all categories):**`, - `\`${prefix}lastfm play lf:loved\` — Play loved tracks, search on Last.fm`, - `\`${prefix}lastfm play lf:top\` — Play top tracks, search on Last.fm`, - `\`${prefix}lastfm play lf:recent\` — Play recent tracks, search on Last.fm`, - `\`${prefix}lastfm play lf:albums\` — Play top albums, search on Last.fm`, - `\`${prefix}lastfm play lf:artists\` — Play top artists, search on Last.fm`, - ``, - `💡 Or use inline: \`${prefix}play lastfm:loved\` or \`${prefix}play lastfm:sp\` or \`${prefix}play lastfm:td:top\``, - ].join("\n"))] - }); - } -} - -/** - * Build an embed listing tracks with optional playcount. - * @private - * @param {string} username - The Last.fm username. - * @param {string} title - The list title. - * @param {object[]} tracks - Array of track objects with name, artist, url, and optional playcount. - * @param {boolean} [showPlaycount=false] - Whether to show play counts. - * @param {string} [prefix="%"] - The command prefix for the footer hint. - * @returns {EmbedBuilder} The constructed embed. - */ -function buildTrackList(username, title, tracks, showPlaycount = false, prefix = "%") { - const lines = tracks.map((t, i) => { - const num = String(i + 1).padStart(2, " "); - let name = t.name; - if (name.length > 40) name = name.slice(0, 37) + "..."; - const link = t.url ? `[${name}](${t.url})` : name; - const extra = showPlaycount && t.playcount ? ` (${t.playcount} plays)` : ""; - return `\`${num}.\` ${link} — **${t.artist}**${extra}`; - }); - - const desc = lines.join("\n").slice(0, 4096); - - return new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(`${title} — ${username}`) - .setDescription(desc) - .setFooter({ text: `💡 Use ${prefix}lastfm play loved to play these!` }); -} - -/** - * Build a scrobble leaderboard embed for a given page. - * @private - * @param {object} lb - Leaderboard data with entries and perPage. - * @param {number} pageIdx - The page index (0-based). - * @param {string} prefix - The command prefix for the footer hint. - * @returns {EmbedBuilder} The constructed embed. - */ -function buildLeaderboardEmbed(lb, pageIdx, prefix) { - const MEDALS = ["🥇", "🥈", "🥉"]; - const startRank = pageIdx * lb.perPage; - - const lines = lb.entries.map((entry, i) => { - const rank = startRank + i + 1; - const medal = rank <= 3 ? MEDALS[rank - 1] : ` `; - const name = entry.username || entry.userId; - const count = Utils.formatNumber(entry.scrobbleCount); - return `${medal} ${rank}. **${name}** — ${count} scrobbles`; - }); - - const desc = lines.join("\n").slice(0, 4096); - - return new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle("🎵 Scrobble Leaderboard") - .setDescription(desc) - .setFooter({ text: `💡 View & sync your count: ${prefix}lastfm profile` }); -} - -/** - * Format seconds into a human-readable duration string (h:mm:ss or m:ss). - * @private - * @param {number} seconds - Duration in seconds. - * @returns {string} Formatted duration, or empty string if invalid. - */ -function formatDuration(seconds) { - if (!seconds || seconds <= 0) return ""; - const h = Math.floor(seconds / 3600); - const m = Math.floor((seconds % 3600) / 60); - const s = seconds % 60; - if (h > 0) { - return `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`; - } - return `${m}:${String(s).padStart(2, "0")}`; + if (ACCOUNT_ACTIONS.has(action)) + return runAccountActions.call(this, msg, data, lastfm, prefix, userId, targetUserId, action); + if (PLAYBACK_ACTIONS.has(action)) + return runPlaybackActions.call(this, msg, data, lastfm, prefix, userId, targetUserId, action); + if (LISTENING_ACTIONS.has(action)) + return runListeningActions.call(this, msg, data, lastfm, prefix, userId, targetUserId, action); + if (WHOKNOWS_ACTIONS.has(action)) + return runWhoknowsActions.call(this, msg, data, lastfm, prefix, userId, targetUserId, action); + if (INFO_ACTIONS.has(action)) + return runInfoActions.call(this, msg, data, lastfm, prefix, userId, targetUserId, action); + if (TAG_ACTIONS.has(action)) + return runTagActions.call(this, msg, data, lastfm, prefix, userId, targetUserId, action); + if (DISCOVERY_ACTIONS.has(action)) + return runDiscoveryActions.call(this, msg, data, lastfm, prefix, userId, targetUserId, action); + return runLastFmHelp.call(this, msg, data, lastfm, prefix, userId, targetUserId, action); } diff --git a/commands/lastfm/account.mjs b/commands/lastfm/account.mjs new file mode 100644 index 0000000..639d930 --- /dev/null +++ b/commands/lastfm/account.mjs @@ -0,0 +1,245 @@ +/** + * @module commands/lastfm/account + * @description Account linking, profile and playlist actions for the lastfm command (link, confirm, unlink, scrobble, np, profile, playlists). Extracted verbatim from the original single-file command; dispatched by commands/lastfm.mjs. + */ + + +import { EmbedBuilder } from "@fluxerjs/core"; +import { getGlobalColor } from "../../src/ui/index.mjs"; +import { Utils } from "../../src/utils/Utils.mjs"; +import { logger } from "../../src/core/Logger.mjs"; +import { ERROR_COLOR } from "../../src/utils/UI.mjs"; +import { notLinked } from "./shared.mjs"; + +/** + * Action names dispatched to this module. + * @type {Set} + */ +export const ACCOUNT_ACTIONS = new Set([ + "link",, + "confirm",, + "unlink",, + "scrobble",, + "np",, + "profile",, + "playlists" +]); + + +/** + * @async + * @param {object} msg - The command message wrapper. + * @param {object} data - Parsed command data. + * @param {object} lastfm - The Last.fm manager instance. + * @param {string} prefix - The guild command prefix. + * @param {string} userId - The invoking user's ID. + * @param {string|null} targetUserId - The targeted user's ID, if any. + * @param {string} action - The resolved action name. + * @returns {Promise<*>} Whatever the original switch returned for this action. + */ +export async function runAccountActions(msg, data, lastfm, prefix, userId, targetUserId, action) { + switch (action) { + case "link": { + const existing = await lastfm.getUser(userId); + if (existing) { + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setDescription(this.t(msg, "responses.lastfm.alreadyLinked", { username: existing.username, prefix }))] + }); + } + + let token; + try { + token = await lastfm.getAuthToken(); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.tokenFailed", { error: err.message }))] + }); + } + + const authUrl = lastfm.getAuthUrl(token); + + let sent = false; + try { + const dm = await msg.author.createDM(); + await dm.send({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(this.t(msg, "responses.lastfm.authLinkTitle")) + .setDescription(this.t(msg, "responses.lastfm.authLinkBody", { url: authUrl, prefix, token })) + ] + }); + sent = true; + } catch(e) { logger.warn("[LastFm] Error:", e?.message); } + + const replyEmbed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setDescription( + sent + ? this.t(msg, "responses.lastfm.authDM", { prefix }) + : this.t(msg, "responses.lastfm.authDMFailed", { url: authUrl, prefix }) + ); + + return msg.reply({ embeds: [replyEmbed] }); + } + + case "confirm": { + let tokenValue = data.get("token")?.value; + if (!tokenValue) { + const rawContent = msg.message?.content ?? ""; + const args = rawContent.split(/\s+/); + const confirmIdx = args.indexOf("confirm"); + tokenValue = confirmIdx >= 0 ? args[confirmIdx + 1] : null; + } + + if (!tokenValue) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.confirmUsage", { prefix }))] + }); + } + + let session; + try { + session = await lastfm.getSession(tokenValue); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.confirmFailed", { error: err.message }))] + }); + } + + await lastfm.saveUser(userId, session.key, session.name); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setDescription(this.t(msg, "responses.lastfm.linked", { username: session.name }))] + }); + } + + case "unlink": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + await lastfm.removeUser(userId); + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.unlinked", { username: user.username }))] + }); + } + + case "scrobble": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + const newState = !user.scrobbleEnabled; + await lastfm.setScrobble(userId, newState); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setDescription(newState + ? this.t(msg, "responses.lastfm.scrobbleEnabled", { username: user.username }) + : this.t(msg, "responses.lastfm.scrobbleDisabled") + )] + }); + } + + case "np": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + let recentData; + try { + recentData = await lastfm.getRecentTracks(userId, 1); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + if (!recentData.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noRecent", { username: user.username }))] + }); + } + + const track = recentData[0]; + const statusEmoji = track.now ? this.t(msg, "responses.lastfm.nowPlaying") : this.t(msg, "responses.lastfm.lastPlayed"); + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setAuthor({ name: statusEmoji, iconURL: track.image || undefined }) + .setDescription(this.t(msg, "responses.lastfm.npTrackInfo", { name: track.name, artist: track.artist, url: track.url })) + .setFooter({ text: this.t(msg, "responses.lastfm.npFooter", { username: user.username }) }); + + return msg.reply({ embeds: [embed] }); + } + + case "profile": { + const profileUserId = targetUserId || userId; + const user = await lastfm.getUser(profileUserId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + let info; + try { + info = await lastfm.getUserInfo(profileUserId); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + lastfm.syncUserScrobbleCount(profileUserId).catch(() => {}); + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setAuthor({ name: this.t(msg, "responses.lastfm.profileTitle", { username: info.name }), iconURL: info.image?.[2]?.["#text"] || undefined, url: info.url }) + .setDescription([ + this.t(msg, "responses.lastfm.profileScrobbles", { playcount: Utils.formatNumber(info.playcount ?? 0) }), + this.t(msg, "responses.lastfm.profileRegistered", { date: info.registered?.unixtime ? new Date(+info.registered.unixtime * 1000).toLocaleDateString() : "unknown" }), + this.t(msg, "responses.lastfm.profileScrobbleStatus", { status: user.scrobbleEnabled ? this.t(msg, "responses.lastfm.profileScrobbleEnabled") : this.t(msg, "responses.lastfm.profileScrobbleDisabled") }), + ``, + this.t(msg, "responses.lastfm.profileLink", { url: info.url }), + ].join("\n")) + .setFooter({ text: this.t(msg, "responses.lastfm.profileScrobbleFooter", { prefix }) }); + + return msg.reply({ embeds: [embed] }); + } + + case "playlists": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + let playlists; + try { + playlists = await lastfm.getPlaylists(userId); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + if (!playlists.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noPlaylists", { username: user.username }))] + }); + } + + const lines = playlists.map((pl, i) => { + const num = String(i + 1).padStart(2, " "); + const link = pl.url ? `[${pl.title}](${pl.url})` : pl.title; + return `\`${num}.\` ${link} — **${pl.trackCount}** tracks`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(this.t(msg, "responses.lastfm.playlistsTitle", { username: user.username })) + .setDescription(desc) + .setFooter({ text: this.t(msg, "responses.lastfm.playlistsFooter", { prefix }) })] + }); + } + + } +} diff --git a/commands/lastfm/discovery.mjs b/commands/lastfm/discovery.mjs new file mode 100644 index 0000000..8c19fbf --- /dev/null +++ b/commands/lastfm/discovery.mjs @@ -0,0 +1,372 @@ +/** + * @module commands/lastfm/discovery + * @description Charts and discovery actions for the lastfm command (friends, weekly, trending, geo, artisttracks, search). Extracted verbatim from the original single-file command; dispatched by commands/lastfm.mjs. + */ + + +import { EmbedBuilder } from "@fluxerjs/core"; +import { getGlobalColor } from "../../src/ui/index.mjs"; +import { Utils } from "../../src/utils/Utils.mjs"; +import { ERROR_COLOR } from "../../src/utils/UI.mjs"; +import { notLinked, extractCurrentTrack } from "./shared.mjs"; + +/** + * Action names dispatched to this module. + * @type {Set} + */ +export const DISCOVERY_ACTIONS = new Set([ + "friends",, + "fr",, + "weekly",, + "wc",, + "trending",, + "tr",, + "geo",, + "g",, + "artisttracks",, + "atr",, + "search",, + "s" +]); + + +/** + * @async + * @param {object} msg - The command message wrapper. + * @param {object} data - Parsed command data. + * @param {object} lastfm - The Last.fm manager instance. + * @param {string} prefix - The guild command prefix. + * @param {string} userId - The invoking user's ID. + * @param {string|null} targetUserId - The targeted user's ID, if any. + * @param {string} action - The resolved action name. + * @returns {Promise<*>} Whatever the original switch returned for this action. + */ +export async function runDiscoveryActions(msg, data, lastfm, prefix, userId, targetUserId, action) { + switch (action) { + case "friends": + case "fr": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + let friends; + try { + friends = await lastfm.getUserFriends(userId, 20); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + if (!friends.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`👥 No friends found for **${user.username}**.`)] + }); + } + + const lines = friends.map((f, i) => { + const num = String(i + 1).padStart(2, " "); + const link = f.url ? `[${f.name}](${f.url})` : f.name; + const details = []; + if (f.realname) details.push(f.realname); + if (f.country) details.push(f.country); + const detailStr = details.length > 0 ? ` (${details.join(", ")})` : ""; + return `\`${num}.\` ${link}${detailStr}`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`👥 Friends — ${user.username}`) + .setDescription(desc)] + }); + } + + case "weekly": + case "wc": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + const tokenTextWc = data.get("token")?.value?.toLowerCase().trim() ?? "artists"; + let chartData; + let chartTitle; + + try { + if (tokenTextWc === "tracks") { + chartData = await lastfm.getUserWeeklyTrackChart(userId); + chartTitle = `📅 Weekly Track Chart — ${user.username}`; + } else if (tokenTextWc === "albums") { + chartData = await lastfm.getUserWeeklyAlbumChart(userId); + chartTitle = `📅 Weekly Album Chart — ${user.username}`; + } else { + chartData = await lastfm.getUserWeeklyArtistChart(userId); + chartTitle = `📅 Weekly Artist Chart — ${user.username}`; + } + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + if (!chartData.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`📅 No weekly chart data found for **${user.username}**.`)] + }); + } + + const lines = chartData.slice(0, 15).map((item, i) => { + const num = String(i + 1).padStart(2, " "); + const link = item.url ? `[${item.name}](${item.url})` : item.name; + const artistStr = item.artist ? ` by **${item.artist}**` : ""; + return `\`${num}.\` ${link}${artistStr} — **${Utils.formatNumber(item.playcount)}** plays`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(chartTitle) + .setDescription(desc) + .setFooter({ text: `💡 Use token option: artists, tracks, or albums` })] + }); + } + + case "trending": + case "tr": { + const tokenTextTr = data.get("token")?.value?.toLowerCase().trim() ?? "tracks"; + let trendingData; + let trendingTitle; + + try { + if (tokenTextTr === "artists") { + trendingData = await lastfm.getChartTopArtists(15); + trendingTitle = "🔥 Trending Artists on Last.fm"; + } else { + trendingData = await lastfm.getChartTopTracks(15); + trendingTitle = "🔥 Trending Tracks on Last.fm"; + } + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + if (!trendingData.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🔥 No trending data found.`)] + }); + } + + const lines = trendingData.map((item, i) => { + const num = String(i + 1).padStart(2, " "); + const link = item.url ? `[${item.name}](${item.url})` : item.name; + const artistStr = item.artist ? ` by **${item.artist}**` : ""; + const extra = item.listeners ? ` — ${Utils.formatNumber(item.listeners)} listeners` : item.playcount ? ` — ${Utils.formatNumber(item.playcount)} plays` : ""; + return `\`${num}.\` ${link}${artistStr}${extra}`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(trendingTitle) + .setDescription(desc) + .setFooter({ text: `💡 Use token option: tracks or artists` })] + }); + } + + case "geo": + case "g": { + const tokenTextG = data.get("token")?.value?.trim() ?? ""; + if (!tokenTextG) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Provide a query like \`artists \` or \`tracks \`. Example: \`${prefix}lastfm geo artists united states\`.`)] + }); + } + + const lowerToken = tokenTextG.toLowerCase(); + let type = "artists"; + let country = tokenTextG; + + if (lowerToken.startsWith("artists ")) { + type = "artists"; + country = tokenTextG.slice(8).trim(); + } else if (lowerToken.startsWith("tracks ")) { + type = "tracks"; + country = tokenTextG.slice(7).trim(); + } + + if (!country) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Please specify a country name. Example: \`${prefix}lastfm geo artists united states\`.`)] + }); + } + + let geoData; + let geoTitle; + + try { + if (type === "tracks") { + geoData = await lastfm.getGeoTopTracks(country, 15); + geoTitle = `🌍 Top Tracks in ${country}`; + } else { + geoData = await lastfm.getGeoTopArtists(country, 15); + geoTitle = `🌍 Top Artists in ${country}`; + } + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + if (!geoData.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🌍 No data found for **${country}**.`)] + }); + } + + const lines = geoData.map((item, i) => { + const num = String(i + 1).padStart(2, " "); + const link = item.url ? `[${item.name}](${item.url})` : item.name; + const artistStr = item.artist ? ` by **${item.artist}**` : ""; + const extra = item.listeners ? ` — ${Utils.formatNumber(item.listeners)} listeners` : ""; + return `\`${num}.\` ${link}${artistStr}${extra}`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(geoTitle) + .setDescription(desc)] + }); + } + + case "artisttracks": + case "atr": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + let artistName = null; + + const pAtr = await this.getPlayer(msg, false, false, false); + const current = extractCurrentTrack(pAtr); + if (current?.artist) { + artistName = current.artist; + } + + const tokenTextAtr = data.get("token")?.value; + if (tokenTextAtr) { + artistName = tokenTextAtr.trim(); + } + + if (!artistName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noArtistSpecified"))] + }); + } + + let recentTracks; + try { + recentTracks = await lastfm.getRecentTracks(userId, 200); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + const artistTracks = recentTracks.filter(t => + t.artist.toLowerCase() === artistName.toLowerCase() + ); + + if (!artistTracks.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🎵 No scrobbles found for **${artistName}** in your recent history.`)] + }); + } + + const lines = artistTracks.slice(0, 15).map((t, i) => { + const num = String(i + 1).padStart(2, " "); + const link = t.url ? `[${t.name}](${t.url})` : t.name; + const nowStr = t.now ? " 🎵" : ""; + return `\`${num}.\` ${link}${nowStr}`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`🎵 ${artistName} Scrobbles — ${user.username}`) + .setDescription(desc) + .setFooter({ text: `${artistTracks.length} scrobble${artistTracks.length !== 1 ? "s" : ""} found` })] + }); + } + + case "search": + case "s": { + const query = data.get("token")?.value; + if (!query) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Provide a search query via the token option. Example: \`${prefix}lastfm search radiohead\``)] + }); + } + + let artistResults, albumResults, trackResult; + try { + [artistResults, albumResults, trackResult] = await Promise.all([ + lastfm.searchArtist(query, 5), + lastfm.searchAlbum(query, 5), + lastfm.searchTrack(query), + ]); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + const sections = []; + + if (artistResults.length) { + const artistLines = artistResults.map((a, i) => { + const link = a.url ? `[${a.name}](${a.url})` : a.name; + const listeners = a.listeners ? ` — ${Utils.formatNumber(a.listeners)} listeners` : ""; + return `${i + 1}. ${link}${listeners}`; + }); + sections.push(`**🎤 Artists:**\n${artistLines.join("\n")}`); + } + + if (albumResults.length) { + const albumLines = albumResults.map((a, i) => { + const link = a.url ? `[${a.name}](${a.url})` : a.name; + return `${i + 1}. ${link} by **${a.artist}**`; + }); + sections.push(`**💿 Albums:**\n${albumLines.join("\n")}`); + } + + if (trackResult) { + sections.push(`**🎵 Best Track Match:**\n[${trackResult.name}](${trackResult.url}) by **${trackResult.artist}**`); + } + + if (!sections.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🔍 No results found for **${query}**.`)] + }); + } + + const desc = sections.join("\n\n").slice(0, 4096); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`🔍 Search Results for "${query}"`) + .setDescription(desc)] + }); + } + + } +} diff --git a/commands/lastfm/help.mjs b/commands/lastfm/help.mjs new file mode 100644 index 0000000..5f85288 --- /dev/null +++ b/commands/lastfm/help.mjs @@ -0,0 +1,99 @@ +/** + * @module commands/lastfm/help + * @description Fallback help action for the lastfm command (the original + * switch's `default` branch). Extracted verbatim; reached when the action + * matches no known action name. + */ + +import { EmbedBuilder } from "@fluxerjs/core"; +import { getGlobalColor } from "../../src/ui/index.mjs"; + +/** + * @async + * @param {object} msg - The command message wrapper. + * @param {object} data - Parsed command data. + * @param {object} lastfm - The Last.fm manager instance. + * @param {string} prefix - The guild command prefix. + * @param {string} userId - The invoking user's ID. + * @param {string|null} targetUserId - The targeted user's ID, if any. + * @param {string} action - The resolved action name. + * @returns {Promise<*>} Whatever the original switch returned for this action. + */ +export async function runLastFmHelp(msg, data, lastfm, prefix, userId, targetUserId, action) { + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setDescription([ + `🎵 **Last.fm Commands:**`, + ``, + `\`${prefix}lastfm link\` — Link your Last.fm account`, + `\`${prefix}lastfm unlink\` — Disconnect your account`, + `\`${prefix}lastfm scrobble\` — Toggle auto-scrobbling`, + `\`${prefix}lastfm np\` — Show your Last.fm now playing`, + `\`${prefix}lastfm profile\` — View your Last.fm profile (or another user's with user option)`, + `\`${prefix}lastfm loved\` — View your loved tracks`, + `\`${prefix}lastfm top\` — View your top tracks (supports period)`, + `\`${prefix}lastfm artists\` — View your top artists (supports period)`, + `\`${prefix}lastfm recent\` — View your recent tracks`, + `\`${prefix}lastfm playlists\` — View your Last.fm playlists`, + `\`${prefix}lastfm leaderboard\` — Scrobble leaderboard`, + `\`${prefix}lastfm love\` — Love the current track`, + `\`${prefix}lastfm unlove\` — Unlove the current track`, + ``, + `🔍 **Info Commands:**`, + `\`${prefix}lastfm whoknows [artist]\` — Who in the server listens to an artist`, + `\`${prefix}lastfm whoknowstrack\` — Who knows a specific track`, + `\`${prefix}lastfm whoknowsalbum\` — Who knows a specific album`, + `\`${prefix}lastfm artistinfo\` — Detailed info about an artist`, + `\`${prefix}lastfm albuminfo\` — Detailed info about an album`, + `\`${prefix}lastfm trackinfo\` — Detailed info about a track`, + `\`${prefix}lastfm topalbums\` — View your top albums (supports period)`, + `\`${prefix}lastfm toptags\` — View your top tags/genres`, + `\`${prefix}lastfm tag \` — View info about a specific tag`, + `\`${prefix}lastfm compare @user\` — Compare your taste with another user`, + `\`${prefix}lastfm cover\` — Get album cover art for the current track`, + ``, + `🏷️ **Tag Commands:**`, + `\`${prefix}lastfm artisttags\` — Top tags for an artist`, + `\`${prefix}lastfm albumtags\` — Top tags for an album`, + `\`${prefix}lastfm tracktags\` — Top tags for a track`, + `\`${prefix}lastfm tagalbums \` — Top albums for a tag`, + ``, + `👥 **Social Commands:**`, + `\`${prefix}lastfm affinity\` — Find users with similar taste`, + `\`${prefix}lastfm crowns\` — View your artist crowns (#1 listener)`, + `\`${prefix}lastfm friends\` — View your Last.fm friends`, + `\`${prefix}lastfm refreshmembers\` — Refresh server member cache`, + ``, + `📊 **Charts & Discovery:**`, + `\`${prefix}lastfm weekly [artists|tracks|albums]\` — Weekly charts`, + `\`${prefix}lastfm trending [tracks|artists]\` — Global trending on Last.fm`, + `\`${prefix}lastfm geo [artists|tracks] \` — Top by country`, + `\`${prefix}lastfm artisttracks\` — Your scrobbles for an artist`, + `\`${prefix}lastfm search \` — Universal search`, + ``, + `🎶 **Play from Last.fm:**`, + `\`${prefix}lastfm play loved\` — Play your loved tracks`, + `\`${prefix}lastfm play top\` — Play your top tracks`, + `\`${prefix}lastfm play recent\` — Play your recent tracks`, + `\`${prefix}lastfm play albums\` — Play your top albums`, + `\`${prefix}lastfm play artists\` — Play your top artists' tracks`, + `\`${prefix}lastfm play playlist 1\` — Play a playlist`, + ``, + `🎧 **Play with a specific provider (defaults to \`top\`):**`, + `\`${prefix}lastfm play sp\` or \`${prefix}lastfm play sp:top\` — Play top tracks, search on Spotify`, + `\`${prefix}lastfm play td\` or \`${prefix}lastfm play td:top\` — Play top tracks, search on Tidal`, + `\`${prefix}lastfm play dz\` or \`${prefix}lastfm play dz:top\` — Play top tracks, search on Deezer`, + `\`${prefix}lastfm play yt\` or \`${prefix}lastfm play yt:top\` — Play top tracks, search on YouTube`, + ``, + `🎧 **Last.fm as resolve provider (all categories):**`, + `\`${prefix}lastfm play lf:loved\` — Play loved tracks, search on Last.fm`, + `\`${prefix}lastfm play lf:top\` — Play top tracks, search on Last.fm`, + `\`${prefix}lastfm play lf:recent\` — Play recent tracks, search on Last.fm`, + `\`${prefix}lastfm play lf:albums\` — Play top albums, search on Last.fm`, + `\`${prefix}lastfm play lf:artists\` — Play top artists, search on Last.fm`, + ``, + `💡 Or use inline: \`${prefix}play lastfm:loved\` or \`${prefix}play lastfm:sp\` or \`${prefix}play lastfm:td:top\``, + ].join("\n"))] + }); +} diff --git a/commands/lastfm/index.mjs b/commands/lastfm/index.mjs new file mode 100644 index 0000000..0b80bd7 --- /dev/null +++ b/commands/lastfm/index.mjs @@ -0,0 +1,16 @@ +/** + * @module commands/lastfm + * @description Barrel for the lastfm command group implementation modules. + * commands/lastfm.mjs (the command entry file) dispatches through this + * barrel; it stays the single import surface for the group. + */ + +export { notConfigured, notLinked, extractCurrentTrack, extractPeriod, VALID_PERIODS } from "./shared.mjs"; +export { runAccountActions, ACCOUNT_ACTIONS } from "./account.mjs"; +export { runPlaybackActions, PLAYBACK_ACTIONS, playLastFmCategory } from "./playback.mjs"; +export { runListeningActions, LISTENING_ACTIONS } from "./listening.mjs"; +export { runWhoknowsActions, WHOKNOWS_ACTIONS } from "./whoknows.mjs"; +export { runInfoActions, INFO_ACTIONS } from "./info.mjs"; +export { runTagActions, TAG_ACTIONS } from "./tags.mjs"; +export { runDiscoveryActions, DISCOVERY_ACTIONS } from "./discovery.mjs"; +export { runLastFmHelp } from "./help.mjs"; diff --git a/commands/lastfm/info.mjs b/commands/lastfm/info.mjs new file mode 100644 index 0000000..6ee80e6 --- /dev/null +++ b/commands/lastfm/info.mjs @@ -0,0 +1,505 @@ +/** + * @module commands/lastfm/info + * @description Metadata lookup actions for the lastfm command (artistinfo, albuminfo, trackinfo, topalbums, toptags, cover) with the duration formatter. Extracted verbatim from the original single-file command; dispatched by commands/lastfm.mjs. + */ + + +import { EmbedBuilder } from "@fluxerjs/core"; +import { getGlobalColor } from "../../src/ui/index.mjs"; +import { Utils } from "../../src/utils/Utils.mjs"; +import { logger } from "../../src/core/Logger.mjs"; +import { ERROR_COLOR } from "../../src/utils/UI.mjs"; +import { notLinked, extractCurrentTrack, extractPeriod } from "./shared.mjs"; + +/** + * Action names dispatched to this module. + * @type {Set} + */ +export const INFO_ACTIONS = new Set([ + "artistinfo",, + "ai",, + "albuminfo",, + "ali",, + "trackinfo",, + "ti",, + "topalbums",, + "toptags",, + "tags",, + "cover",, + "art" +]); + + +/** + * Format seconds into a human-readable duration string (h:mm:ss or m:ss). + * @private + * @param {number} seconds - Duration in seconds. + * @returns {string} Formatted duration, or empty string if invalid. + */ +function formatDuration(seconds) { + if (!seconds || seconds <= 0) return ""; + const h = Math.floor(seconds / 3600); + const m = Math.floor((seconds % 3600) / 60); + const s = seconds % 60; + if (h > 0) { + return `${h}:${String(m).padStart(2, "0")}:${String(s).padStart(2, "0")}`; + } + return `${m}:${String(s).padStart(2, "0")}`; +} + +/** + * @async + * @param {object} msg - The command message wrapper. + * @param {object} data - Parsed command data. + * @param {object} lastfm - The Last.fm manager instance. + * @param {string} prefix - The guild command prefix. + * @param {string} userId - The invoking user's ID. + * @param {string|null} targetUserId - The targeted user's ID, if any. + * @param {string} action - The resolved action name. + * @returns {Promise<*>} Whatever the original switch returned for this action. + */ +export async function runInfoActions(msg, data, lastfm, prefix, userId, targetUserId, action) { + switch (action) { + case "artistinfo": + case "ai": { + const user = await lastfm.getUser(userId); + + let artistName = null; + + const pAi = await this.getPlayer(msg, false, false, false); + const current = extractCurrentTrack(pAi); + if (current?.artist) { + artistName = current.artist; + } + + const tokenText = data.get("token")?.value; + if (tokenText) { + artistName = tokenText.trim(); + } + + if (!artistName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( + this.t(msg, "responses.lastfm.noArtistSpecified") + )] + }); + } + + let info; + try { + info = await lastfm.getArtistInfo(artistName, userId); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + if (!info) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.artistNotFound", { artist: artistName }))] + }); + } + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`🎤 ${info.name}`) + .setURL(info.url || undefined) + .setThumbnail(info.image || undefined); + + const fields = []; + fields.push({ name: "Listeners", value: Utils.formatNumber(info.stats?.listeners ?? 0), inline: true }); + fields.push({ name: "Global Plays", value: Utils.formatNumber(info.stats?.playcount ?? 0), inline: true }); + + if (info.userplaycount != null && user) { + fields.push({ name: "Your Plays", value: Utils.formatNumber(info.userplaycount), inline: true }); + } + + if (info.tags?.length) { + const tagStr = info.tags.slice(0, 8).map(t => { + const tagLower = String(t).toLowerCase().replace(/\s+/g, "+"); + return `[${t}](https://www.last.fm/tag/${encodeURIComponent(tagLower)})`; + }).join(" · "); + fields.push({ name: "Tags", value: tagStr, inline: false }); + } + + if (info.similar?.length) { + const simStr = info.similar.slice(0, 5).map(s => { + return s.url ? `[${s.name}](${s.url})` : s.name; + }).join(" · "); + fields.push({ name: "Similar Artists", value: simStr, inline: false }); + } + + embed.addFields(...fields); + + if (info.bio) { + const cleanBio = info.bio.replace(/<[^>]*>/g, "").trim(); + if (cleanBio.length > 0) { + const truncated = cleanBio.length > 300 ? cleanBio.slice(0, 297) + "..." : cleanBio; + embed.setDescription(truncated); + } + } + + embed.setFooter({ text: user ? `Last.fm: ${user.username}` : "Last.fm" }); + + return msg.reply({ embeds: [embed] }); + } + + case "albuminfo": + case "ali": { + const user = await lastfm.getUser(userId); + + let artistName = null; + let albumName = null; + + const pAli = await this.getPlayer(msg, false, false, false); + const current = extractCurrentTrack(pAli); + if (current?.album && current?.artist) { + artistName = current.artist; + albumName = current.album; + } + + const tokenText = data.get("token")?.value; + if (tokenText) { + const dashMatch = tokenText.match(/^(.+?)\s*[-–—]\s*(.+)$/); + if (dashMatch) { + artistName = dashMatch[1].trim(); + albumName = dashMatch[2].trim(); + } else { + albumName = tokenText.trim(); + } + } + + if (!albumName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( + this.t(msg, "responses.lastfm.noAlbumSpecified") + )] + }); + } + + let info; + try { + info = await lastfm.getAlbumInfo(artistName || "", albumName, userId); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + if (!info) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.albumNotFound", { album: albumName }))] + }); + } + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`💿 ${info.name}`) + .setURL(info.url || undefined) + .setThumbnail(info.image || undefined); + + const fields = []; + + if (info.artist) { + fields.push({ name: "Artist", value: info.artist, inline: true }); + } + + if (info.userplaycount != null && user) { + fields.push({ name: "Your Plays", value: Utils.formatNumber(info.userplaycount), inline: true }); + } + + if (info.tags?.length) { + const tagStr = info.tags.slice(0, 8).map(t => { + const tagLower = String(t).toLowerCase().replace(/\s+/g, "+"); + return `[${t}](https://www.last.fm/tag/${encodeURIComponent(tagLower)})`; + }).join(" · "); + fields.push({ name: "Tags", value: tagStr, inline: false }); + } + + if (info.tracks?.length) { + const trackLines = info.tracks.slice(0, 15).map((t, i) => { + const num = String(i + 1).padStart(2, " "); + const dur = t.duration > 0 ? ` (${formatDuration(t.duration)})` : ""; + const link = t.url ? `[${t.name}](${t.url})` : t.name; + return `\`${num}.\` ${link}${dur}`; + }); + fields.push({ name: "Tracklist", value: trackLines.join("\n").slice(0, 1024), inline: false }); + } + + embed.addFields(...fields); + embed.setFooter({ text: user ? `Last.fm: ${user.username}` : "Last.fm" }); + + return msg.reply({ embeds: [embed] }); + } + + case "trackinfo": + case "ti": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + let artistName = null; + let trackName = null; + + const pTi = await this.getPlayer(msg, false, false, false); + const current = extractCurrentTrack(pTi); + if (current?.artist && current?.name) { + artistName = current.artist; + trackName = current.name; + } + + const tokenText = data.get("token")?.value; + if (tokenText) { + const dashMatch = tokenText.match(/^(.+?)\s*[-–—]\s*(.+)$/); + if (dashMatch) { + artistName = dashMatch[1].trim(); + trackName = dashMatch[2].trim(); + } else { + try { + const searchResult = await lastfm.searchTrack(tokenText.trim()); + if (searchResult) { + artistName = searchResult.artist; + trackName = searchResult.name; + } + } catch(e) { logger.warn("[LastFm] Error:", e?.message); } + } + } + + if (!artistName || !trackName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( + this.t(msg, "responses.lastfm.noTrackSpecified") + )] + }); + } + + let info; + try { + info = await lastfm.getTrackInfo(artistName, trackName, userId); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + if (!info) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.trackNotFound", { track: trackName, artist: artistName }))] + }); + } + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`🎵 ${info.name}`) + .setURL(info.url || undefined); + + if (info.album?.image?.[2]?.["#text"] || info.album?.image?.[1]?.["#text"]) { + embed.setThumbnail(info.album?.image?.[2]?.["#text"] || info.album?.image?.[1]?.["#text"]); + } + + const fields = []; + + if (info.artist?.name || info.artist?.["#text"]) { + fields.push({ name: "Artist", value: String(info.artist?.name ?? info.artist?.["#text"] ?? "Unknown"), inline: true }); + } + + if (info.album?.title) { + fields.push({ name: "Album", value: info.album.title, inline: true }); + } + + if (info.listeners) { + fields.push({ name: "Listeners", value: Utils.formatNumber(Number(info.listeners)), inline: true }); + } + + if (info.playcount) { + fields.push({ name: "Global Plays", value: Utils.formatNumber(Number(info.playcount)), inline: true }); + } + + if (info.userplaycount) { + fields.push({ name: "Your Plays", value: Utils.formatNumber(Number(info.userplaycount)), inline: true }); + } + + const userLoved = info.userloved === "1" || info.userloved === 1 || info.userloved === true; + fields.push({ name: "Loved", value: userLoved ? "❤️ Yes" : "🖤 No", inline: true }); + + if (info.toptags?.tag?.length) { + const tagStr = info.toptags.tag.slice(0, 8).map(t => { + const tagName = t.name ?? t; + const tagLower = String(tagName).toLowerCase().replace(/\s+/g, "+"); + return `[${tagName}](https://www.last.fm/tag/${encodeURIComponent(tagLower)})`; + }).join(" · "); + fields.push({ name: "Tags", value: tagStr, inline: false }); + } + + embed.addFields(...fields); + + if (info.wiki?.summary) { + const cleanSummary = info.wiki.summary.replace(/<[^>]*>/g, "").trim(); + if (cleanSummary.length > 0) { + const truncated = cleanSummary.length > 200 ? cleanSummary.slice(0, 197) + "..." : cleanSummary; + embed.setDescription(truncated); + } + } + + let similarTracks = []; + try { + similarTracks = await lastfm.getSimilarTracks(artistName, trackName, 5); + } catch(e) { logger.warn("[LastFm] Error:", e?.message); } + + if (similarTracks.length) { + const simStr = similarTracks.map(t => { + const matchPct = Math.round(t.match * 100); + const link = t.url ? `[${t.name}](${t.url})` : t.name; + return `${link} by **${t.artist}** (${matchPct}%)`; + }).join("\n"); + embed.addFields({ name: "Similar Tracks", value: simStr.slice(0, 1024), inline: false }); + } + + embed.setFooter({ text: `Last.fm: ${user.username}` }); + + return msg.reply({ embeds: [embed] }); + } + + case "topalbums": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + const period = extractPeriod(data, msg); + + let albums; + try { + albums = await lastfm.getTopAlbums(userId, period, 15); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + if (!albums.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noTopAlbums", { username: user.username }))] + }); + } + + const periodLabel = period !== "overall" ? ` (${period})` : ""; + + const lines = albums.map((a, i) => { + const num = String(i + 1).padStart(2, " "); + let albumTitle = a.name; + if (albumTitle.length > 30) albumTitle = albumTitle.slice(0, 27) + "..."; + const link = a.url ? `[${albumTitle}](${a.url})` : albumTitle; + return `\`${num}.\` ${link} — **${a.artist}** (**${a.playcount}** plays)`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(this.t(msg, "responses.lastfm.topAlbumsTitle", { period: periodLabel, username: user.username })) + .setDescription(desc); + + if (albums[0]?.image) { + embed.setThumbnail(albums[0].image); + } + + embed.setFooter({ text: this.t(msg, "responses.lastfm.topAlbumsFooter", { prefix }) }); + + return msg.reply({ embeds: [embed] }); + } + + case "toptags": + case "tags": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + let tags; + try { + tags = await lastfm.getUserTopTags(userId, 20); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + if (!tags.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noTopTags", { username: user.username }))] + }); + } + + const lines = tags.map((t, i) => { + const num = String(i + 1).padStart(2, " "); + const link = t.url ? `[${t.name}](${t.url})` : t.name; + return `\`${num}.\` ${link} — **${t.count}**`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(this.t(msg, "responses.lastfm.topTagsTitle", { username: user.username })) + .setDescription(desc) + .setFooter({ text: this.t(msg, "responses.lastfm.topTagsFooter", { prefix }) })] + }); + } + + case "cover": + case "art": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + const pCover = await this.getPlayer(msg, false, false, false); + const current = extractCurrentTrack(pCover); + if (!current || !current.name) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.coverNothingPlaying"))] + }); + } + + const artistName = current.artist ?? "Unknown"; + const trackName = current.name; + const albumName = current.album; + + let coverUrl = null; + let albumTitle = albumName ?? "Unknown Album"; + + if (albumName) { + try { + const albumInfo = await lastfm.getAlbumInfo(artistName, albumName, userId); + if (albumInfo?.image) { + coverUrl = albumInfo.image; + albumTitle = `${albumInfo.name} by ${albumInfo.artist}`; + } + } catch(e) { logger.warn("[LastFm] Error:", e?.message); } + } + + if (!coverUrl) { + try { + const trackInfo = await lastfm.getTrackInfo(artistName, trackName, userId); + if (trackInfo?.album?.image) { + const images = trackInfo.album.image; + coverUrl = images?.[2]?.["#text"] || images?.[1]?.["#text"] || images?.[0]?.["#text"] || null; + if (trackInfo.album?.title) { + albumTitle = trackInfo.album.title; + } + } + } catch(e) { logger.warn("[LastFm] Error:", e?.message); } + } + + if (!coverUrl) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.coverNotFound", { track: trackName, artist: artistName }))] + }); + } + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(this.t(msg, "responses.lastfm.coverTitle", { album: albumTitle })) + .setImage(coverUrl) + .setFooter({ text: this.t(msg, "responses.lastfm.coverFooter", { track: trackName, artist: artistName }) }); + + return msg.reply({ embeds: [embed] }); + } + + } +} diff --git a/commands/lastfm/listening.mjs b/commands/lastfm/listening.mjs new file mode 100644 index 0000000..d4a2433 --- /dev/null +++ b/commands/lastfm/listening.mjs @@ -0,0 +1,358 @@ +/** + * @module commands/lastfm/listening + * @description Personal listening actions for the lastfm command (loved, top, leaderboard, recent, artists, love, unlove) with their list/leaderboard embed builders. Extracted verbatim from the original single-file command; dispatched by commands/lastfm.mjs. + */ + + +import { EmbedBuilder } from "@fluxerjs/core"; +import { getGlobalColor } from "../../src/ui/index.mjs"; +import { Utils } from "../../src/utils/Utils.mjs"; +import { logger } from "../../src/core/Logger.mjs"; +import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../../src/utils/UI.mjs"; +import { notLinked, extractPeriod } from "./shared.mjs"; + +/** + * Action names dispatched to this module. + * @type {Set} + */ +export const LISTENING_ACTIONS = new Set([ + "loved",, + "top",, + "leaderboard",, + "lb",, + "recent",, + "artists",, + "love",, + "unlove" +]); + + +/** + * Build an embed listing tracks with optional playcount. + * @private + * @param {string} username - The Last.fm username. + * @param {string} title - The list title. + * @param {object[]} tracks - Array of track objects with name, artist, url, and optional playcount. + * @param {boolean} [showPlaycount=false] - Whether to show play counts. + * @param {string} [prefix="%"] - The command prefix for the footer hint. + * @returns {EmbedBuilder} The constructed embed. + */ +function buildTrackList(username, title, tracks, showPlaycount = false, prefix = "%") { + const lines = tracks.map((t, i) => { + const num = String(i + 1).padStart(2, " "); + let name = t.name; + if (name.length > 40) name = name.slice(0, 37) + "..."; + const link = t.url ? `[${name}](${t.url})` : name; + const extra = showPlaycount && t.playcount ? ` (${t.playcount} plays)` : ""; + return `\`${num}.\` ${link} — **${t.artist}**${extra}`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + return new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`${title} — ${username}`) + .setDescription(desc) + .setFooter({ text: `💡 Use ${prefix}lastfm play loved to play these!` }); +} + +/** + * Build a scrobble leaderboard embed for a given page. + * @private + * @param {object} lb - Leaderboard data with entries and perPage. + * @param {number} pageIdx - The page index (0-based). + * @param {string} prefix - The command prefix for the footer hint. + * @returns {EmbedBuilder} The constructed embed. + */ +function buildLeaderboardEmbed(lb, pageIdx, prefix) { + const MEDALS = ["🥇", "🥈", "🥉"]; + const startRank = pageIdx * lb.perPage; + + const lines = lb.entries.map((entry, i) => { + const rank = startRank + i + 1; + const medal = rank <= 3 ? MEDALS[rank - 1] : ` `; + const name = entry.username || entry.userId; + const count = Utils.formatNumber(entry.scrobbleCount); + return `${medal} ${rank}. **${name}** — ${count} scrobbles`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + return new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle("🎵 Scrobble Leaderboard") + .setDescription(desc) + .setFooter({ text: `💡 View & sync your count: ${prefix}lastfm profile` }); +} + +/** + * @async + * @param {object} msg - The command message wrapper. + * @param {object} data - Parsed command data. + * @param {object} lastfm - The Last.fm manager instance. + * @param {string} prefix - The guild command prefix. + * @param {string} userId - The invoking user's ID. + * @param {string|null} targetUserId - The targeted user's ID, if any. + * @param {string} action - The resolved action name. + * @returns {Promise<*>} Whatever the original switch returned for this action. + */ +export async function runListeningActions(msg, data, lastfm, prefix, userId, targetUserId, action) { + switch (action) { + case "loved": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + let tracks; + try { + tracks = await lastfm.getLovedTracks(userId, 15); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + if (!tracks.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noLoved", { username: user.username }))] + }); + } + + return msg.reply({ embeds: [buildTrackList(user.username, this.t(msg, "responses.lastfm.lovedTitle", { username: user.username }), tracks, false, prefix)] }); + } + + case "top": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + const period = extractPeriod(data, msg); + + let tracks; + try { + tracks = await lastfm.getTopTracks(userId, period, 15); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + if (!tracks.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noTop", { username: user.username }))] + }); + } + + const periodLabel = period !== "overall" ? ` (${period})` : ""; + return msg.reply({ embeds: [buildTrackList(user.username, this.t(msg, "responses.lastfm.topTitle", { username: user.username }) + periodLabel, tracks, true, prefix)] }); + } + + case "leaderboard": + case "lb": { + let lb; + try { + lb = await lastfm.getLeaderboard(0, 10); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + if (!lb.entries.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription( + this.t(msg, "responses.lastfm.leaderboardEmpty", { prefix }) + )] + }); + } + + if (lb.totalPages <= 1) { + const embed = buildLeaderboardEmbed(lb, 0, prefix); + return msg.reply({ embeds: [embed] }); + } + + let currentPage = 0; + + const buildPage = (pageIdx, expired = false) => { + const footerText = expired + ? this.t(msg, "responses.lastfm.leaderboardControlsExpired") + : this.t(msg, "responses.lastfm.leaderboardPageFooter", { current: pageIdx + 1, total: lb.totalPages }); + const embed = buildLeaderboardEmbed(lb, pageIdx, prefix); + embed.setFooter({ text: footerText }); + return { embeds: [embed] }; + }; + + const replyMsg = await msg.reply(buildPage(0)); + if (!replyMsg?.message) return; + + const navEmojis = ["◀️", "▶️", "❌"]; + for (const emoji of navEmojis) { + await replyMsg.message.react(emoji).catch(() => {}); + } + + const clearReactions = async () => { + try { + await replyMsg.message.removeAllReactions(); + } catch { + for (const emoji of navEmojis) { + try { await replyMsg.message.removeReaction(emoji); } catch(e) { logger.warn("[LastFm] Error:", e?.message); } + } + } + }; + + let emojiTimeout; + const resetTimer = () => { + clearTimeout(emojiTimeout); + emojiTimeout = setTimeout(async () => { + unobserve?.(); + await clearReactions(); + await replyMsg.edit(buildPage(currentPage, true)).catch(() => {}); + }, EMOJI_REMOVE_TIMEOUT); + }; + + const unobserve = replyMsg.onReaction(navEmojis, async (e) => { + if (e.emoji_id === "❌") { + clearTimeout(emojiTimeout); + unobserve?.(); + await replyMsg.message.delete().catch(() => {}); + return; + } + + resetTimer(); + + if (e.emoji_id === "◀️") { + currentPage = currentPage > 0 ? currentPage - 1 : lb.totalPages - 1; + } else if (e.emoji_id === "▶️") { + currentPage = currentPage < lb.totalPages - 1 ? currentPage + 1 : 0; + } + + try { + lb = await lastfm.getLeaderboard(currentPage, 10); + } catch(e) { logger.warn("[LastFm] Error:", e?.message); } + + await replyMsg.edit(buildPage(currentPage)).catch(() => {}); + }); + + resetTimer(); + break; + } + + case "recent": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + let tracks; + try { + tracks = await lastfm.getRecentTracks(userId, 15); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + if (!tracks.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noRecent", { username: user.username }))] + }); + } + + return msg.reply({ embeds: [buildTrackList(user.username, this.t(msg, "responses.lastfm.recentTitle", { username: user.username }), tracks, false, prefix)] }); + } + + case "artists": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + const period = extractPeriod(data, msg); + + let artists; + try { + artists = await lastfm.getTopArtists(userId, period, 15); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + if (!artists.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noArtists", { username: user.username }))] + }); + } + + const periodLabel = period !== "overall" ? ` (${period})` : ""; + const lines = artists.map((a, i) => { + const num = String(i + 1).padStart(2, " "); + let name = a.name; + if (name.length > 40) name = name.slice(0, 37) + "..."; + const link = a.url ? `[${name}](${a.url})` : name; + return `\`${num}.\` ${link} — **${a.playcount}** plays`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(this.t(msg, "responses.lastfm.artistsTitle", { username: user.username }) + periodLabel) + .setDescription(desc) + .setFooter({ text: this.t(msg, "responses.lastfm.artistsFooter", { prefix }) })] + }); + } + + case "love": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + const pLove = await this.getPlayer(msg, false, false, false); + if (!pLove) return; + const track = pLove.queue?.getCurrent(); + if (!track) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.nothingPlayingLove"))] + }); + } + + const artist = track.lastfm?.artist ?? track.requestedArtist ?? track.artist ?? track.artists?.[0]?.name ?? track.author?.name ?? "Unknown"; + const name = track.lastfm?.name ?? track.requestedTitle ?? track.title ?? track.name ?? "Unknown"; + + try { + await lastfm.loveTrack(userId, artist, name); + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.lovedTrack", { name, artist }))] + }); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.loveFailed", { error: err.message }))] + }); + } + } + + case "unlove": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + const pUnlove = await this.getPlayer(msg, false, false, false); + if (!pUnlove) return; + const track = pUnlove.queue?.getCurrent(); + if (!track) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.nothingPlayingUnlove"))] + }); + } + + const artist = track.lastfm?.artist ?? track.requestedArtist ?? track.artist ?? track.artists?.[0]?.name ?? track.author?.name ?? "Unknown"; + const name = track.lastfm?.name ?? track.requestedTitle ?? track.title ?? track.name ?? "Unknown"; + + try { + await lastfm.unloveTrack(userId, artist, name); + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.unlovedTrack", { name, artist }))] + }); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.unloveFailed", { error: err.message }))] + }); + } + } + + } +} diff --git a/commands/lastfm/playback.mjs b/commands/lastfm/playback.mjs new file mode 100644 index 0000000..96165fc --- /dev/null +++ b/commands/lastfm/playback.mjs @@ -0,0 +1,326 @@ +/** + * @module commands/lastfm/playback + * @description The `play` action plus the shared Last.fm playback pipeline (playLastFmCategory, kept exported for commands/play.mjs, plus its private helpers). Extracted verbatim from the original single-file command; dispatched by commands/lastfm.mjs. + */ + + +import { EmbedBuilder } from "@fluxerjs/core"; +import { getGlobalColor } from "../../src/ui/index.mjs"; +import { logger } from "../../src/core/Logger.mjs"; +import { PROVIDER_CHOICES } from "../../src/music/providers.mjs"; +import { ERROR_COLOR } from "../../src/utils/UI.mjs"; +import { notConfigured, notLinked } from "./shared.mjs"; + +/** + * Action names dispatched to this module. + * @type {Set} + */ +export const PLAYBACK_ACTIONS = new Set([ + "play" +]); + + +const SIMPLE_CATEGORIES = ["loved", "top", "recent", "albums", "artists"]; + +/** + * Build a Last.fm track metadata object from a track. + * @private + * @param {object} track - The track object with artist, name, and url. + * @returns {{ source: string, artist: string, name: string, url: string }} Track metadata. + */ +function buildLastFmTrackMeta(track) { + return { + source: "lastfm", + artist: track.artist, + name: track.name, + url: track.url ?? "", + }; +} + +/** + * Resolve a Last.fm track to playable audio via a search provider. + * @private + * @async + * @param {object} player - The player instance. + * @param {object} track - The Last.fm track with query and metadata. + * @param {string} [resolveProvider="yt"] - The provider to resolve with. + * @returns {Promise} Array of resolved track data, or null on failure. + */ +async function resolveLastFmTrack(player, track, resolveProvider = "yt") { + const data = await player.generalQuery({ + query: track.query, + provider: resolveProvider, + trackMeta: buildLastFmTrackMeta(track), + }); + + if (!data || data.type === "error") return null; + if (data.type === "video") return [data.data]; + if (data.type === "list") return data.data ?? []; + return null; +} + +/** + * Fetch and play tracks from a Last.fm category (loved, top, recent, albums, artists, playlist). + * @async + * @param {object} ctx - The bot (Remix) instance context. + * @param {object} msg - The command message wrapper. + * @param {string} userId - The user ID. + * @param {string} category - The Last.fm category to play. + * @param {object} [options={}] - Additional options. + * @param {string} [options.resolveProvider="yt"] - Provider to resolve tracks with. + * @param {string} [options.playlistId] - Playlist number for playlist category. + * @returns {Promise} + */ +export async function playLastFmCategory(ctx, msg, userId, category, options = {}) { + const lastfm = ctx.lastfm; + const prefix = ctx.handler.getPrefix(msg.message?.guildId); + const resolveProvider = options.resolveProvider || "yt"; + + if (!lastfm || !lastfm.enabled) return msg.reply(notConfigured(ctx, msg)); + + const validCategories = [...SIMPLE_CATEGORIES, "playlist"]; + if (!validCategories.includes(category)) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( + `❌ Unknown category \`${category}\`. Use \`loved\`, \`top\`, \`recent\`, \`albums\`, \`artists\`, or \`playlist\`.` + )] + }); + } + + if (category === "playlist" && !options.playlistId) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( + `❌ Specify a playlist number. Use \`${prefix}lastfm playlists\` to see your playlists, then \`${prefix}lastfm play playlist \`.` + )] + }); + } + + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(ctx, msg, prefix)); + + const p = await ctx.getPlayer(msg, true, true, true); + if (!p) return; + + const categoryEmoji = { loved: "❤️", top: "📊", recent: "🕐", playlist: "📋", albums: "💿", artists: "🎤" }[category]; + const categoryLabel = { loved: "Loved", top: "Top", recent: "Recent", playlist: "Playlist", albums: "Top Albums", artists: "Top Artists" }[category]; + + const resolveLabel = resolveProvider !== "yt" ? ` via ${resolveProvider.toUpperCase()}` : ""; + + let statusMsg; + try { + statusMsg = await msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription( + `${categoryEmoji} Fetching your ${categoryLabel} tracks from Last.fm${resolveLabel}...` + )] + }); + } catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; } + + let result; + try { + result = await lastfm.getTracksForPlay(userId, category, options); + } catch (err) { + const errMsg = err.message === "NOT_LINKED" + ? notLinked(ctx, msg, prefix) + : { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(ctx.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; + if (statusMsg) statusMsg.edit(errMsg).catch(() => msg.reply(errMsg)); + else msg.reply(errMsg); + return; + } + + if (!result.tracks.length) { + const noTracks = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription( + `${categoryEmoji} No ${categoryLabel.toLowerCase()} tracks found for **${result.username}**.` + )] }; + if (statusMsg) statusMsg.edit(noTracks).catch(() => msg.reply(noTracks)); + else msg.reply(noTracks); + return; + } + + let added = 0; + let failed = 0; + + if (statusMsg) { + statusMsg.edit({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription( + `${categoryEmoji} Loading **${result.tracks.length}** ${categoryLabel.toLowerCase()} tracks from **${result.username}**${resolveLabel}...` + )] + }).catch(() => {}); + } + + for (const track of result.tracks) { + try { + const resolvedTracks = await resolveLastFmTrack(p, track, resolveProvider); + if (!resolvedTracks?.length) { + failed++; + continue; + } + + p.addManyToQueue(resolvedTracks, false); + added += resolvedTracks.length; + + if (!p.queue.getCurrent()) { + p.playNext(); + } + } catch (e) { + logger.warn("[LastfmCmd] Track resolve failed:", e?.message); + failed++; + } + } + + const summary = []; + if (added > 0) summary.push(`✅ Added **${added}** track${added !== 1 ? "s" : ""} to the queue`); + if (failed > 0) summary.push(`⚠️ ${failed} track${failed !== 1 ? "s" : ""} couldn't be found`); + + const doneEmbed = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription( + `${categoryEmoji} **${categoryLabel} Tracks — ${result.username}**\n${summary.join(" · ")}` + )] }; + + if (statusMsg) statusMsg.edit(doneEmbed).catch(() => msg.reply(doneEmbed)); + else msg.reply(doneEmbed); +} + +/** + * Parse play subcommand arguments for category and provider. + * @private + * @param {object} msg - The command message wrapper. + * @param {object} data - Parsed command data. + * @returns {{ category: string, resolveProvider?: string, playlistId?: string, showAllCategories?: boolean, invalidCategory?: string }} Parsed args. + */ +function parsePlayArgs(msg, data) { + let raw = data.get("token")?.value; + if (!raw) { + const content = msg.message?.content ?? ""; + const args = content.split(/\s+/); + const playIdx = args.indexOf("play"); + if (playIdx >= 0 && args[playIdx + 1]) { + raw = args.slice(playIdx + 1).join(" "); + } + } + + if (!raw) return { category: "" }; + + const lower = raw.toLowerCase().trim(); + + const subMatch = lower.match(/^([a-z]+):\s*(.*)$/); + if (subMatch) { + const maybeProvider = subMatch[1]; + const rest = subMatch[2].trim(); + if (PROVIDER_CHOICES.includes(maybeProvider)) { + const isLastFmProvider = maybeProvider === "lf" || maybeProvider === "lastfm"; + + if (!rest) { + if (isLastFmProvider) { + return { category: "", resolveProvider: maybeProvider, showAllCategories: true }; + } + return { category: "top", resolveProvider: maybeProvider }; + } + + if (isLastFmProvider) { + const playlistMatch = rest.match(/^playlist\s+(\d+)$/); + if (playlistMatch) { + return { category: "playlist", playlistId: playlistMatch[1], resolveProvider: maybeProvider }; + } + if (SIMPLE_CATEGORIES.includes(rest)) { + return { category: rest, resolveProvider: maybeProvider }; + } + } else { + if (rest === "top") { + return { category: "top", resolveProvider: maybeProvider }; + } + return { category: "", resolveProvider: maybeProvider, invalidCategory: rest }; + } + } + } + + if (PROVIDER_CHOICES.includes(lower)) { + const isLastFmProvider = lower === "lf" || lower === "lastfm"; + if (isLastFmProvider) { + return { category: "", resolveProvider: lower, showAllCategories: true }; + } + return { category: "top", resolveProvider: lower }; + } + + const playlistMatch = lower.match(/^playlist\s+(\d+)$/); + if (playlistMatch) { + return { category: "playlist", playlistId: playlistMatch[1] }; + } + + if (SIMPLE_CATEGORIES.includes(lower)) { + return { category: lower }; + } + + return { category: "" }; +} + +/** + * @async + * @param {object} msg - The command message wrapper. + * @param {object} data - Parsed command data. + * @param {object} lastfm - The Last.fm manager instance. + * @param {string} prefix - The guild command prefix. + * @param {string} userId - The invoking user's ID. + * @param {string|null} targetUserId - The targeted user's ID, if any. + * @param {string} action - The resolved action name. + * @returns {Promise<*>} Whatever the original switch returned for this action. + */ +export async function runPlaybackActions(msg, data, lastfm, prefix, userId, targetUserId, action) { + switch (action) { + case "play": { + const parsed = parsePlayArgs(msg, data); + + if (parsed.invalidCategory) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( + `❌ \`${parsed.resolveProvider}:${parsed.invalidCategory}\` is not valid. Non-Last.fm providers only support \`top\`.\nUse \`${prefix}lastfm play ${parsed.resolveProvider}\` or \`${prefix}lastfm play ${parsed.resolveProvider}:top\` instead.\nFor other categories, use Last.fm as the resolve provider: \`${prefix}lastfm play lf:${parsed.invalidCategory}\`` + )] + }); + } + + if (!parsed.category) { + const lfProviderNote = parsed.showAllCategories && parsed.resolveProvider + ? `\n\n💡 \`${prefix}lastfm play ${parsed.resolveProvider}:\` — Specify a category after the provider:` + : ""; + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription([ + `❌ Usage: \`${prefix}lastfm play \``, + ``, + `**Categories:**`, + `\`loved\` — Play your loved tracks`, + `\`top\` — Play your top tracks`, + `\`recent\` — Play your recent tracks`, + `\`albums\` — Play your top albums`, + `\`artists\` — Play your top artists' tracks`, + `\`playlist \` — Play a playlist (use \`${prefix}lastfm playlists\` to list)`, + ``, + `**With a search provider (defaults to \`top\`):**`, + `\`${prefix}lastfm play td\` or \`${prefix}lastfm play td:top\` — Play top tracks, search on Tidal`, + `\`${prefix}lastfm play sp\` or \`${prefix}lastfm play sp:top\` — Play top tracks, search on Spotify`, + `\`${prefix}lastfm play dz\` or \`${prefix}lastfm play dz:top\` — Play top tracks, search on Deezer`, + `\`${prefix}lastfm play yt\` or \`${prefix}lastfm play yt:top\` — Play top tracks, search on YouTube`, + ``, + `**Last.fm as resolve provider (all categories):**`, + `\`${prefix}lastfm play lf:loved\` — Play loved tracks, search on Last.fm`, + `\`${prefix}lastfm play lf:top\` — Play top tracks, search on Last.fm`, + `\`${prefix}lastfm play lf:recent\` — Play recent tracks, search on Last.fm`, + `\`${prefix}lastfm play lf:albums\` — Play top albums, search on Last.fm`, + `\`${prefix}lastfm play lf:artists\` — Play top artists, search on Last.fm`, + ``, + `**Examples:**`, + `\`${prefix}lastfm play loved\``, + `\`${prefix}lastfm play td\``, + `\`${prefix}lastfm play sp:top\``, + `\`${prefix}lastfm play lf:loved\``, + `\`${prefix}lastfm play playlist 1\``, + lfProviderNote, + ].join("\n"))] + }); + } + + return playLastFmCategory(this, msg, userId, parsed.category, { + playlistId: parsed.playlistId, + resolveProvider: parsed.resolveProvider, + }); + } + + } +} diff --git a/commands/lastfm/shared.mjs b/commands/lastfm/shared.mjs new file mode 100644 index 0000000..850391b --- /dev/null +++ b/commands/lastfm/shared.mjs @@ -0,0 +1,80 @@ +/** + * @module commands/lastfm/shared + * @description Helpers shared by several lastfm action modules. Bodies + * are verbatim from the original single-file command; the `export ` + * prefixes are the only addition. + */ + + +import { EmbedBuilder } from "@fluxerjs/core"; +import { getGlobalColor } from "../../src/ui/index.mjs"; +import { ERROR_COLOR } from "../../src/utils/UI.mjs"; + +export const VALID_PERIODS = ["7day", "1month", "3month", "6month", "12month", "overall"]; + +/** + * Return an embed indicating Last.fm is not configured. + * @private + * @param {object} ctx - The bot (Remix) instance context. + * @param {object} msg - The command message wrapper. + * @returns {{ embeds: EmbedBuilder[] }} Error embed payload. + */ +export function notConfigured(ctx, msg) { + return { + embeds: [new EmbedBuilder() + .setColor(ERROR_COLOR) + .setDescription(ctx.t(msg, "responses.lastfm.notConfigured"))] + }; +} + +/** + * Return an embed indicating the user has not linked their Last.fm account. + * @private + * @param {object} ctx - The bot (Remix) instance context. + * @param {object} msg - The command message wrapper. + * @param {string} prefix - The guild's command prefix. + * @returns {{ embeds: EmbedBuilder[] }} Error embed payload. + */ +export function notLinked(ctx, msg, prefix) { + return { + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setDescription(ctx.t(msg, "responses.lastfm.notLinked", { prefix }))] + }; +} + +/** + * Extract Last.fm-relevant info from the player's current track. + * @private + * @param {object} player - The player instance. + * @returns {{ artist: string|null, name: string|null, album: string|null, track: object|null }} Extracted track info. + */ +export function extractCurrentTrack(player) { + const track = player?.queue?.getCurrent(); + if (!track) return null; + const artist = track.lastfm?.artist ?? track.requestedArtist ?? track.artist ?? track.artists?.[0]?.name ?? track.author?.name ?? null; + const name = track.lastfm?.name ?? track.requestedTitle ?? track.title ?? track.name ?? null; + const album = track.album ?? track.lastfm?.album ?? null; + return { artist, name, album, track }; +} + +/** + * Extract a valid time period from command data or message content. + * @private + * @param {object} data - Parsed command data. + * @param {object} msg - The command message wrapper. + * @returns {string} The period string, defaults to "overall". + */ +export function extractPeriod(data, msg) { + let raw = data.get("token")?.value; + if (!raw) { + const content = msg.message?.content ?? ""; + const args = content.split(/\s+/); + const last = args[args.length - 1]; + if (last && VALID_PERIODS.includes(last.toLowerCase())) raw = last; + } + if (raw && VALID_PERIODS.includes(raw.toLowerCase().trim())) { + return raw.toLowerCase().trim(); + } + return "overall"; +} diff --git a/commands/lastfm/tags.mjs b/commands/lastfm/tags.mjs new file mode 100644 index 0000000..b5e3076 --- /dev/null +++ b/commands/lastfm/tags.mjs @@ -0,0 +1,337 @@ +/** + * @module commands/lastfm/tags + * @description Tag/genre actions for the lastfm command (tag, artisttags, albumtags, tracktags, tagalbums). Extracted verbatim from the original single-file command; dispatched by commands/lastfm.mjs. + */ + + +import { EmbedBuilder } from "@fluxerjs/core"; +import { getGlobalColor } from "../../src/ui/index.mjs"; +import { Utils } from "../../src/utils/Utils.mjs"; +import { logger } from "../../src/core/Logger.mjs"; +import { ERROR_COLOR } from "../../src/utils/UI.mjs"; +import { extractCurrentTrack } from "./shared.mjs"; + +/** + * Action names dispatched to this module. + * @type {Set} + */ +export const TAG_ACTIONS = new Set([ + "tag",, + "artisttags",, + "at",, + "albumtags",, + "alt",, + "tracktags",, + "tt",, + "tagalbums",, + "ta" +]); + + +/** + * @async + * @param {object} msg - The command message wrapper. + * @param {object} data - Parsed command data. + * @param {object} lastfm - The Last.fm manager instance. + * @param {string} prefix - The guild command prefix. + * @param {string} userId - The invoking user's ID. + * @param {string|null} targetUserId - The targeted user's ID, if any. + * @param {string} action - The resolved action name. + * @returns {Promise<*>} Whatever the original switch returned for this action. + */ +export async function runTagActions(msg, data, lastfm, prefix, userId, targetUserId, action) { + switch (action) { + case "tag": { + const tagName = data.get("token")?.value; + if (!tagName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( + this.t(msg, "responses.lastfm.tagProvideName", { prefix }) + )] + }); + } + + let tagInfo; + let topTracks; + let topArtists; + + try { + [tagInfo, topTracks, topArtists] = await Promise.all([ + lastfm.getTagInfo(tagName), + lastfm.getTagTopTracks(tagName, 5), + lastfm.getTagTopArtists(tagName, 5), + ]); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + if (!tagInfo) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.tagNotFound", { tag: tagName }))] + }); + } + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`🏷️ ${tagInfo.name}`) + .setURL(tagInfo.url || undefined); + + const fields = []; + fields.push({ name: "Reach", value: Utils.formatNumber(tagInfo.reach), inline: true }); + fields.push({ name: "Total Taggings", value: Utils.formatNumber(tagInfo.count), inline: true }); + + if (topArtists.length) { + const artistStr = topArtists.map((a, i) => { + const link = a.url ? `[${a.name}](${a.url})` : a.name; + return `${i + 1}. ${link} (**${Utils.formatNumber(a.playcount)}** plays)`; + }).join("\n"); + fields.push({ name: "Top Artists", value: artistStr.slice(0, 1024), inline: false }); + } + + if (topTracks.length) { + const trackStr = topTracks.map((t, i) => { + const link = t.url ? `[${t.name}](${t.url})` : t.name; + return `${i + 1}. ${link} by **${t.artist}**`; + }).join("\n"); + fields.push({ name: "Top Tracks", value: trackStr.slice(0, 1024), inline: false }); + } + + embed.addFields(...fields); + + if (tagInfo.summary) { + const cleanSummary = tagInfo.summary.replace(/<[^>]*>/g, "").trim(); + if (cleanSummary.length > 0) { + const truncated = cleanSummary.length > 300 ? cleanSummary.slice(0, 297) + "..." : cleanSummary; + embed.setDescription(truncated); + } + } + + return msg.reply({ embeds: [embed] }); + } + + case "artisttags": + case "at": { + let artistName = null; + + const pAt = await this.getPlayer(msg, false, false, false); + const current = extractCurrentTrack(pAt); + if (current?.artist) { + artistName = current.artist; + } + + const tokenTextAt = data.get("token")?.value; + if (tokenTextAt) { + artistName = tokenTextAt.trim(); + } + + if (!artistName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noArtistSpecified"))] + }); + } + + let tags; + try { + tags = await lastfm.getArtistTopTags(artistName, 15); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + if (!tags.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.noArtistTags", { artist: artistName }))] + }); + } + + const lines = tags.map((t, i) => { + const num = String(i + 1).padStart(2, " "); + const link = t.url ? `[${t.name}](${t.url})` : t.name; + return `\`${num}.\` ${link}${t.count > 0 ? ` — **${Utils.formatNumber(t.count)}**` : ""}`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(this.t(msg, "responses.lastfm.artistTagsTitle", { artist: artistName })) + .setDescription(desc)] + }); + } + + case "albumtags": + case "alt": { + let artistName = null; + let albumName = null; + + const pAlt = await this.getPlayer(msg, false, false, false); + const current = extractCurrentTrack(pAlt); + if (current?.album && current?.artist) { + artistName = current.artist; + albumName = current.album; + } + + const tokenTextAlt = data.get("token")?.value; + if (tokenTextAlt) { + const dashMatch = tokenTextAlt.match(/^(.+?)\s*[-–—]\s*(.+)$/); + if (dashMatch) { + artistName = dashMatch[1].trim(); + albumName = dashMatch[2].trim(); + } else { + albumName = tokenTextAlt.trim(); + } + } + + if (!albumName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noAlbumSpecified"))] + }); + } + + let tags; + try { + tags = await lastfm.getAlbumTopTags(artistName || "", albumName, 15); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + if (!tags.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🏷️ No tags found for album **${albumName}**.`)] + }); + } + + const lines = tags.map((t, i) => { + const num = String(i + 1).padStart(2, " "); + const link = t.url ? `[${t.name}](${t.url})` : t.name; + return `\`${num}.\` ${link}${t.count > 0 ? ` — **${Utils.formatNumber(t.count)}**` : ""}`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(this.t(msg, "responses.lastfm.artistTagsTitle", { artist: albumName })) + .setDescription(desc)] + }); + } + + case "tracktags": + case "tt": { + let artistName = null; + let trackName = null; + + const pTt = await this.getPlayer(msg, false, false, false); + const current = extractCurrentTrack(pTt); + if (current?.artist && current?.name) { + artistName = current.artist; + trackName = current.name; + } + + const tokenTextTt = data.get("token")?.value; + if (tokenTextTt) { + const dashMatch = tokenTextTt.match(/^(.+?)\s*[-–—]\s*(.+)$/); + if (dashMatch) { + artistName = dashMatch[1].trim(); + trackName = dashMatch[2].trim(); + } else { + try { + const searchResult = await lastfm.searchTrack(tokenTextTt.trim()); + if (searchResult) { + artistName = searchResult.artist; + trackName = searchResult.name; + } + } catch(e) { logger.warn("[LastFm] Error:", e?.message); } + } + } + + if (!artistName || !trackName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noTrackSpecified"))] + }); + } + + let tags; + try { + tags = await lastfm.getTrackTopTags(artistName, trackName, 15); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + if (!tags.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`🏷️ No tags found for **${trackName}** by **${artistName}**.`)] + }); + } + + const lines = tags.map((t, i) => { + const num = String(i + 1).padStart(2, " "); + const link = t.url ? `[${t.name}](${t.url})` : t.name; + return `\`${num}.\` ${link}${t.count > 0 ? ` — **${Utils.formatNumber(t.count)}**` : ""}`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + return msg.reply({ + embeds: [new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(this.t(msg, "responses.lastfm.artistTagsTitle", { artist: trackName })) + .setDescription(desc)] + }); + } + + case "tagalbums": + case "ta": { + const tagName = data.get("token")?.value; + if (!tagName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(`❌ Provide a tag name via the token option. Example: \`${prefix}lastfm tagalbums rock\``)] + }); + } + + let albums; + try { + albums = await lastfm.getTagTopAlbums(tagName.trim(), 15); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + if (!albums.length) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(`💿 No top albums found for tag **${tagName}**.`)] + }); + } + + const lines = albums.map((a, i) => { + const num = String(i + 1).padStart(2, " "); + const link = a.url ? `[${a.name}](${a.url})` : a.name; + return `\`${num}.\` ${link} by **${a.artist}**${a.playcount > 0 ? ` (${Utils.formatNumber(a.playcount)} plays)` : ""}`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(`💿 Top Albums — ${tagName}`) + .setDescription(desc); + + if (albums[0]?.image) { + embed.setThumbnail(albums[0].image); + } + + return msg.reply({ embeds: [embed] }); + } + + } +} diff --git a/commands/lastfm/whoknows.mjs b/commands/lastfm/whoknows.mjs new file mode 100644 index 0000000..4e86fde --- /dev/null +++ b/commands/lastfm/whoknows.mjs @@ -0,0 +1,525 @@ +/** + * @module commands/lastfm/whoknows + * @description Server-social actions for the lastfm command (whoknows, whoknowstrack, whoknowsalbum, affinity, crowns, compare, refreshmembers) with the guild-member helper. Extracted verbatim from the original single-file command; dispatched by commands/lastfm.mjs. + */ + + +import { EmbedBuilder } from "@fluxerjs/core"; +import { getGlobalColor } from "../../src/ui/index.mjs"; +import { Utils } from "../../src/utils/Utils.mjs"; +import { logger } from "../../src/core/Logger.mjs"; +import { ERROR_COLOR } from "../../src/utils/UI.mjs"; +import { notLinked, extractCurrentTrack } from "./shared.mjs"; + +/** + * Action names dispatched to this module. + * @type {Set} + */ +export const WHOKNOWS_ACTIONS = new Set([ + "whoknows",, + "wk",, + "compare",, + "fmc",, + "refreshmembers",, + "rm",, + "affinity",, + "af",, + "crowns",, + "cr",, + "whoknowstrack",, + "wkt",, + "whoknowsalbum",, + "wka" +]); + + +/** + * Get all non-bot user IDs in a guild. + * @private + * @async + * @param {object} guild - The guild object. + * @returns {Promise} Array of user ID strings. + */ +async function getGuildLinkedUsers(guild) { + const memberIds = []; + try { + const members = guild?.members; + if (members) { + const iter = typeof members.values === "function" ? members.values() : Object.values(members); + for (const m of iter) { + const userId = m.user?.id ?? m.id; + if (userId && !m.user?.bot) memberIds.push(String(userId)); + } + } + } catch(e) { logger.warn("[LastFm] Error:", e?.message); } + return memberIds; +} + +/** + * @async + * @param {object} msg - The command message wrapper. + * @param {object} data - Parsed command data. + * @param {object} lastfm - The Last.fm manager instance. + * @param {string} prefix - The guild command prefix. + * @param {string} userId - The invoking user's ID. + * @param {string|null} targetUserId - The targeted user's ID, if any. + * @param {string} action - The resolved action name. + * @returns {Promise<*>} Whatever the original switch returned for this action. + */ +export async function runWhoknowsActions(msg, data, lastfm, prefix, userId, targetUserId, action) { + switch (action) { + case "whoknows": + case "wk": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + let artistName = null; + const tokenTextWk = data.get("token")?.value; + if (tokenTextWk) { + artistName = tokenTextWk.trim(); + } else { + const pWk = await this.getPlayer(msg, false, false, false); + const current = extractCurrentTrack(pWk); + if (current?.artist) { + artistName = current.artist; + } + } + + if (!artistName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.nothingPlayingNoArtist"))] + }); + } + + let statusMsg; + try { + statusMsg = await msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription( + this.t(msg, "responses.lastfm.whoknowsChecking", { artist: artistName }) + )] + }); + } catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; } + + const guild = msg.message?.guild ?? msg.message?.member?.guild; + const memberIds = await getGuildLinkedUsers(guild); + + let listeners; + try { + listeners = await lastfm.getWhoKnows(artistName, memberIds); + } catch (err) { + const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; + if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed)); + else msg.reply(errEmbed); + return; + } + + if (!listeners.length) { + const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription( + this.t(msg, "responses.lastfm.whoknowsNobody", { artist: artistName }) + )] }; + if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData)); + else msg.reply(noData); + return; + } + + const MEDALS = ["🥇", "🥈", "🥉"]; + const totalPlays = listeners.reduce((sum, l) => sum + l.playcount, 0); + + const lines = listeners.map((l, i) => { + const medal = i < 3 ? MEDALS[i] : ` `; + return `${medal} ${i + 1}. **${l.username}** — **${Utils.formatNumber(l.playcount)}** plays`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(this.t(msg, "responses.lastfm.whoknowsTitle", { artist: artistName })) + .setDescription(desc) + .setFooter({ text: this.t(msg, "responses.lastfm.whoknowsFooter", { count: listeners.length, plural: listeners.length !== 1 ? "s" : "", totalPlays: Utils.formatNumber(totalPlays) }) }); + + const replyPayload = { embeds: [embed] }; + if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload)); + else msg.reply(replyPayload); + return; + } + + case "compare": + case "fmc": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + if (!targetUserId) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( + this.t(msg, "responses.lastfm.compareSpecifyUser", { prefix }) + )] + }); + } + + const targetUser = await lastfm.getUser(targetUserId); + if (!targetUser) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription( + this.t(msg, "responses.lastfm.compareUserNotLinked") + )] + }); + } + + let comparison; + try { + comparison = await lastfm.compareUsers(userId, targetUserId); + } catch (err) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] + }); + } + + if (!comparison) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.compareFailed"))] + }); + } + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(this.t(msg, "responses.lastfm.compareTitle")) + .setDescription([ + `**${comparison.user1.username}** vs **${comparison.user2.username}**`, + ``, + `📊 **${comparison.matchPercentage}%** match`, + ``, + `👤 ${comparison.user1.username}: ${comparison.user1.totalArtists} top artists`, + `👤 ${comparison.user2.username}: ${comparison.user2.totalArtists} top artists`, + ].join("\n")); + + if (comparison.commonArtists?.length) { + const commonStr = comparison.commonArtists.slice(0, 15).map((a, i) => { + const num = String(i + 1).padStart(2, " "); + const link = a.url ? `[${a.name}](${a.url})` : a.name; + return `\`${num}.\` ${link} (**${a.playcount}** plays)`; + }).join("\n"); + embed.addFields({ name: `Common Artists (${comparison.commonArtists.length})`, value: commonStr.slice(0, 1024), inline: false }); + } + + return msg.reply({ embeds: [embed] }); + } + + case "refreshmembers": + case "rm": { + const guild = msg.message?.guild ?? msg.message?.member?.guild; + if (!guild) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.refreshFailed"))] + }); + } + let count = 0; + try { + if (guild.members && typeof guild.members.fetch === "function") { + const fetched = await guild.members.fetch(); + count = fetched.size; + } else { + const memberIds = await getGuildLinkedUsers(guild); + count = memberIds.length; + } + } catch { + const memberIds = await getGuildLinkedUsers(guild); + count = memberIds.length; + } + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.refreshSuccess", { count: Utils.formatNumber(count) }))] + }); + } + + case "affinity": + case "af": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + const guild = msg.message?.guild ?? msg.message?.member?.guild; + const memberIds = await getGuildLinkedUsers(guild); + + if (memberIds.length < 2) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.affinityNeedUsers"))] + }); + } + + let statusMsg; + try { + statusMsg = await msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.affinityChecking"))] + }); + } catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; } + + let affinityResults; + try { + affinityResults = await lastfm.getAffinity(memberIds, 10); + } catch (err) { + const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; + if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed)); + else msg.reply(errEmbed); + return; + } + + if (!affinityResults.length) { + const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.affinityNoCommon"))] }; + if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData)); + else msg.reply(noData); + return; + } + + const lines = affinityResults.map(r => { + const topCommon = r.commonArtists.slice(0, 3).map(a => a.name).join(", "); + return `**${r.users[0]}** & **${r.users[1]}** — ${r.matchCount} common artists (${topCommon}${r.commonArtists.length > 3 ? "..." : ""})`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(this.t(msg, "responses.lastfm.affinityTitle")) + .setDescription(desc) + .setFooter({ text: this.t(msg, "responses.lastfm.affinityFooter", { count: memberIds.length }) }); + + const replyPayload = { embeds: [embed] }; + if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload)); + else msg.reply(replyPayload); + return; + } + + case "crowns": + case "cr": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + const guild = msg.message?.guild ?? msg.message?.member?.guild; + const memberIds = await getGuildLinkedUsers(guild); + + let statusMsg; + try { + statusMsg = await msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.crownsChecking"))] + }); + } catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; } + + let crowns; + try { + crowns = await lastfm.getCrowns(userId, memberIds); + } catch (err) { + const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; + if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed)); + else msg.reply(errEmbed); + return; + } + + if (!crowns.length) { + const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.crownsNone"))] }; + if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData)); + else msg.reply(noData); + return; + } + + const tokenFilter = data.get("token")?.value?.toLowerCase().trim(); + + let filteredCrowns = crowns; + if (tokenFilter === "stolen") { + filteredCrowns = crowns.filter(c => c.nextBest && c.nextBest.playcount > 0); + } else if (tokenFilter === "recent") { + filteredCrowns = crowns.slice(0, 10); + } + + const lines = filteredCrowns.slice(0, 20).map(c => { + const link = c.artistUrl ? `[${c.artist}](${c.artistUrl})` : c.artist; + const nextStr = c.nextBest ? ` (next: **${c.nextBest.username}** with ${Utils.formatNumber(c.nextBest.playcount)})` : ""; + return `👑 ${link} — **${Utils.formatNumber(c.userPlaycount)}** plays${nextStr}`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(this.t(msg, "responses.lastfm.crownsTitle", { username: user.username })) + .setDescription(desc) + .setFooter({ text: this.t(msg, "responses.lastfm.crownsFooter", { count: filteredCrowns.length, plural: filteredCrowns.length !== 1 ? "s" : "" }) }); + + if (filteredCrowns[0]?.image) { + embed.setThumbnail(filteredCrowns[0].image); + } + + const replyPayload = { embeds: [embed] }; + if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload)); + else msg.reply(replyPayload); + return; + } + + case "whoknowstrack": + case "wkt": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + let artistName = null; + let trackName = null; + + const pWkt = await this.getPlayer(msg, false, false, false); + const current = extractCurrentTrack(pWkt); + if (current?.artist && current?.name) { + artistName = current.artist; + trackName = current.name; + } + + const tokenTextWkt = data.get("token")?.value; + if (tokenTextWkt) { + const dashMatch = tokenTextWkt.match(/^(.+?)\s*[-–—]\s*(.+)$/); + if (dashMatch) { + artistName = dashMatch[1].trim(); + trackName = dashMatch[2].trim(); + } else { + try { + const searchResult = await lastfm.searchTrack(tokenTextWkt.trim()); + if (searchResult) { + artistName = searchResult.artist; + trackName = searchResult.name; + } + } catch(e) { logger.warn("[LastFm] Error:", e?.message); } + } + } + + if (!artistName || !trackName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noTrackSpecified"))] + }); + } + + let statusMsg; + try { + statusMsg = await msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.whoknowsTrackChecking", { track: trackName, artist: artistName }))] + }); + } catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; } + + const guild = msg.message?.guild ?? msg.message?.member?.guild; + const memberIds = await getGuildLinkedUsers(guild); + + let listeners; + try { + listeners = await lastfm.getWhoKnowsTrack(artistName, trackName, memberIds); + } catch (err) { + const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; + if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed)); + else msg.reply(errEmbed); + return; + } + + if (!listeners.length) { + const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.whoknowsTrackNobody", { track: trackName, artist: artistName }))] }; + if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData)); + else msg.reply(noData); + return; + } + + const MEDALS = ["🥇", "🥈", "🥉"]; + const totalPlays = listeners.reduce((sum, l) => sum + l.playcount, 0); + + const lines = listeners.map((l, i) => { + const medal = i < 3 ? MEDALS[i] : ` `; + return `${medal} ${i + 1}. **${l.username}** — **${Utils.formatNumber(l.playcount)}** plays`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(this.t(msg, "responses.lastfm.whoknowsTrackTitle", { track: trackName })) + .setDescription(desc) + .setFooter({ text: this.t(msg, "responses.lastfm.whoknowsTrackFooter", { count: listeners.length, plural: listeners.length !== 1 ? "s" : "", totalPlays: Utils.formatNumber(totalPlays), artist: artistName }) }); + + const replyPayload = { embeds: [embed] }; + if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload)); + else msg.reply(replyPayload); + return; + } + + case "whoknowsalbum": + case "wka": { + const user = await lastfm.getUser(userId); + if (!user) return msg.reply(notLinked(this, msg, prefix)); + + let artistName = null; + let albumName = null; + + const pWka = await this.getPlayer(msg, false, false, false); + const current = extractCurrentTrack(pWka); + if (current?.album && current?.artist) { + artistName = current.artist; + albumName = current.album; + } + + const tokenTextWka = data.get("token")?.value; + if (tokenTextWka) { + const dashMatch = tokenTextWka.match(/^(.+?)\s*[-–—]\s*(.+)$/); + if (dashMatch) { + artistName = dashMatch[1].trim(); + albumName = dashMatch[2].trim(); + } else { + albumName = tokenTextWka.trim(); + } + } + + if (!albumName) { + return msg.reply({ + embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.noAlbumSpecified"))] + }); + } + + let statusMsg; + try { + statusMsg = await msg.reply({ + embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.whoknowsAlbumChecking", { album: albumName, artistClause: artistName ? ` by **${artistName}**` : "" }))] + }); + } catch (e) { logger.warn("[LastfmCmd] Error:", e?.message); statusMsg = null; } + + const guild = msg.message?.guild ?? msg.message?.member?.guild; + const memberIds = await getGuildLinkedUsers(guild); + + let listeners; + try { + listeners = await lastfm.getWhoKnowsAlbum(artistName || "", albumName, memberIds); + } catch (err) { + const errEmbed = { embeds: [new EmbedBuilder().setColor(ERROR_COLOR).setDescription(this.t(msg, "responses.lastfm.fetchFailed", { error: err.message }))] }; + if (statusMsg) statusMsg.edit(errEmbed).catch(() => msg.reply(errEmbed)); + else msg.reply(errEmbed); + return; + } + + if (!listeners.length) { + const noData = { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this.t(msg, "responses.lastfm.whoknowsAlbumNobody", { album: albumName }))] }; + if (statusMsg) statusMsg.edit(noData).catch(() => msg.reply(noData)); + else msg.reply(noData); + return; + } + + const MEDALS = ["🥇", "🥈", "🥉"]; + const totalPlays = listeners.reduce((sum, l) => sum + l.playcount, 0); + + const lines = listeners.map((l, i) => { + const medal = i < 3 ? MEDALS[i] : ` `; + return `${medal} ${i + 1}. **${l.username}** — **${Utils.formatNumber(l.playcount)}** plays`; + }); + + const desc = lines.join("\n").slice(0, 4096); + + const embed = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(this.t(msg, "responses.lastfm.whoknowsAlbumTitle", { album: albumName })) + .setDescription(desc) + .setFooter({ text: this.t(msg, "responses.lastfm.whoknowsFooter", { count: listeners.length, plural: listeners.length !== 1 ? "s" : "", totalPlays: Utils.formatNumber(totalPlays) }) }); + + const replyPayload = { embeds: [embed] }; + if (statusMsg) statusMsg.edit(replyPayload).catch(() => msg.reply(replyPayload)); + else msg.reply(replyPayload); + return; + } + + } +} diff --git a/commands/leave.mjs b/commands/leave.mjs index ea31f62..2e5749a 100644 --- a/commands/leave.mjs +++ b/commands/leave.mjs @@ -3,10 +3,10 @@ * @description Make the bot leave a voice channel, with 24/7 cleanup and player destruction. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { logger } from "../src/constants/Logger.mjs"; -import { getGlobalColor, cleanId } from "../src/MessageHandler.mjs"; +import { logger } from "../src/core/Logger.mjs"; +import { getGlobalColor, cleanId } from "../src/ui/index.mjs"; /** @type {CommandBuilder} @description Command definition for the leave/stop command. */ export const command = new CommandBuilder() @@ -25,7 +25,7 @@ export const command = new CommandBuilder() * Resolve the guild ID from a player, its map key, or the channel object. * @param {Player} player - The player instance. * @param {string} mapKey - The key under which the player is stored in playerMap. - * @param {import('@fluxerjs/core').Client} client - The Discord/Fluxer client. + * @param {import('@fluxerjs/core').Client} client - The Fluxer client. * @returns {string} Cleaned guild ID, or empty string if unresolvable. */ function resolvePlayerGuildId(player, mapKey, client) { diff --git a/commands/list.mjs b/commands/list.mjs index 31434da..94a2ee3 100644 --- a/commands/list.mjs +++ b/commands/list.mjs @@ -3,8 +3,8 @@ * @description List the songs in the queue of the current voice channel with pagination. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; -import { QueuePaginator, getGlobalColor } from "../src/MessageHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; +import { QueuePaginator, getGlobalColor } from "../src/ui/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; const PAGE_SIZE = 10; diff --git a/commands/loop.mjs b/commands/loop.mjs index 96e612c..126599e 100644 --- a/commands/loop.mjs +++ b/commands/loop.mjs @@ -3,9 +3,9 @@ * @description Toggle looping of the current song or the entire queue. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; /** @type {CommandBuilder} @description Command definition for the loop command. */ export const command = new CommandBuilder() diff --git a/commands/lyrics.mjs b/commands/lyrics.mjs index 147e1d0..7d33a22 100644 --- a/commands/lyrics.mjs +++ b/commands/lyrics.mjs @@ -3,12 +3,12 @@ * @description Display synced or unsynced lyrics for the currently playing track from NodeLink. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; -import { logger } from "../src/constants/Logger.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; +import { logger } from "../src/core/Logger.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; -import { Utils } from "../src/Utils.mjs"; -import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; +import { Utils } from "../src/utils/Utils.mjs"; +import { EMOJI_REMOVE_TIMEOUT } from "../src/utils/UI.mjs"; /** @type {CommandBuilder} @description Command definition for the lyrics command. */ export const command = new CommandBuilder() diff --git a/commands/move.mjs b/commands/move.mjs index 6047923..b267d6b 100644 --- a/commands/move.mjs +++ b/commands/move.mjs @@ -3,7 +3,7 @@ * @description Move a track from one position to another in the queue. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; /** @type {CommandBuilder} @description Command definition for the move command. */ export const command = new CommandBuilder() diff --git a/commands/np.mjs b/commands/np.mjs index fadec04..3fe4fcd 100644 --- a/commands/np.mjs +++ b/commands/np.mjs @@ -3,9 +3,9 @@ * @description Display the currently playing track name and URL. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; /** @type {CommandBuilder} @description Command definition for the np (now playing) command. */ export const command = new CommandBuilder() diff --git a/commands/pause.mjs b/commands/pause.mjs index 92e95a5..9152902 100644 --- a/commands/pause.mjs +++ b/commands/pause.mjs @@ -3,9 +3,9 @@ * @description Pause the currently playing track. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; /** @type {CommandBuilder} @description Command definition for the pause command. */ export const command = new CommandBuilder() diff --git a/commands/play.mjs b/commands/play.mjs index f5a6b47..3661bb0 100644 --- a/commands/play.mjs +++ b/commands/play.mjs @@ -4,14 +4,14 @@ * Supports YouTube, Spotify, SoundCloud, Deezer, Apple Music, Tidal, and Last.fm integration. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; -import { logger } from "../src/constants/Logger.mjs"; -import { PROVIDER_CHOICES, parseInlineProvider } from "../src/constants/providers.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; +import { logger } from "../src/core/Logger.mjs"; +import { PROVIDER_CHOICES, parseInlineProvider } from "../src/music/providers.mjs"; import { playLastFmCategory } from "./lastfm.mjs"; -import { parseLastFmUrl, isLastFmUrl } from "../src/LastFmManager.mjs"; -import { ERROR_COLOR } from "../src/constants/UI.mjs"; +import { parseLastFmUrl, isLastFmUrl } from "../src/services/lastfm/LastFmManager.mjs"; +import { ERROR_COLOR } from "../src/utils/UI.mjs"; const LASTFM_PLAY_CATEGORIES = ["loved", "top", "recent", "albums"]; diff --git a/commands/player.mjs b/commands/player.mjs index 482fa29..9e1e74e 100644 --- a/commands/player.mjs +++ b/commands/player.mjs @@ -1,15 +1,17 @@ /** * @module commands/player * @description Create an interactive player control panel with live progress, reaction controls, - * and embedded lyrics viewer. + * and embedded lyrics viewer. The panel embed construction, display constants and the lyrics + * viewer live in commands/player/; run() below owns the session lifecycle (timers, player + * event wiring and the control-reaction dispatcher). */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; -import { Utils } from "../src/Utils.mjs"; -import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; -import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs"; -import { logger } from "../src/constants/Logger.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; +import { Utils } from "../src/utils/Utils.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; +import { EMOJI_REMOVE_TIMEOUT } from "../src/utils/UI.mjs"; +import { logger } from "../src/core/Logger.mjs"; +import { CONTROLS, buildPlayerEmbed, openLyricsViewer, clearLyricsReactions } from "./player/index.mjs"; /** @type {CommandBuilder} @description Command definition for the player command. */ export const command = new CommandBuilder() @@ -17,40 +19,6 @@ export const command = new CommandBuilder() .setDescription("Create an interactive player control panel with live progress", "commands.player") .setCategory("music"); -/** @private @type {Object.} Emoji indicators for player states. */ -const STATES = { - playing: "🎵", - paused: "⏸️", - stopped: "🔇", - loading: "⏳" -}; - -/** @private @type {Object.} Available control button definitions. */ -const CONTROLS = { - prev: { emoji: "⏮️", action: "previous", desc: "Previous" }, - play: { emoji: "▶️", action: "resume", desc: "Play" }, - pause: { emoji: "⏸️", action: "pause", desc: "Pause" }, - stop: { emoji: "⏹️", action: "stop", desc: "Stop" }, - next: { emoji: "⏭️", action: "skip", desc: "Skip" }, - loop: { emoji: "🔁", action: "loop", desc: "Loop" }, - shuffle: { emoji: "🔀", action: "shuffle", desc: "Shuffle" }, - volDown: { emoji: "🔉", action: "voldown", desc: "Volume Down" }, - volUp: { emoji: "🔊", action: "volup", desc: "Volume Up" }, - lyrics: { emoji: "📜", action: "lyrics", desc: "Lyrics" }, - filter: { emoji: "🎛️", action: "filter", desc: "Audio Filters" }, - close: { emoji: "❌", action: "close", desc: "Close" } -}; - -/** @private @type {Object.} Progress bar character set. */ -const PROGRESS = { - filled: "▰", - empty: "▱", - indicator: "●", - start: "▏", - end: "▕" -}; - - /** * @async * Run handler for the player command. @@ -73,89 +41,7 @@ export async function run(msg) { const allControls = controlsLayout.flat(); const controlEmojis = allControls.map(c => c.emoji); - /** - * @private - * Build the player panel embed with current state, progress, volume, and loop info. - * @param {object} [state={}] - Optional state override with a message field. - * @returns {EmbedBuilder} The constructed embed builder. - */ - const buildEmbed = (state = {}) => { - const current = player.queue.getCurrent(); - const isPlaying = !player.paused && current; - const statusEmoji = isPlaying ? STATES.playing : player.paused ? STATES.paused : STATES.stopped; - - let progressBar = ""; - let timeDisplay = "`0:00 / 0:00`"; - - if (current?.duration && player.startedPlaying) { - const elapsed = Date.now() - player.startedPlaying; - const totalMs = typeof current.duration === "object" - ? (current.duration.seconds ?? 0) * 1000 - : current.duration; - - const bar = Utils.progressBar(elapsed, totalMs, 20, PROGRESS.filled, PROGRESS.empty, isPlaying ? PROGRESS.indicator : PROGRESS.filled); - progressBar = PROGRESS.start + bar + PROGRESS.end; - - const elapsedStr = Utils.prettifyMS(elapsed); - const totalStr = Utils.prettifyMS(totalMs); - timeDisplay = `\`${elapsedStr} / ${totalStr}\``; - } else { - progressBar = PROGRESS.start + PROGRESS.empty.repeat(20) + PROGRESS.end; - } - - const volPercent = Math.round((player.preferredVolume ?? 1) * 100); - const volBars = Math.ceil(volPercent / 10); - const volumeBar = "█".repeat(volBars) + "░".repeat(10 - volBars); - - const queueSize = player.queue.size(); - const loopStatus = player.queue.songLoop ? this.t(msg, "responses.player.loopSong") : player.queue.loop ? this.t(msg, "responses.player.loopQueue") : this.t(msg, "responses.player.loopOff"); - - let filterStatus = this.t(msg, "responses.player.filterOff"); - if (player.activeFilter) { - if (player.activeFilter.label.includes("+")) { - filterStatus = `🔥 **${player.activeFilter.label}**`; - } else { - filterStatus = `${player.activeFilter.emoji ?? "🎛️"} **${player.activeFilter.label}**`; - } - } - - const nowPlaying = current - ? `[${Utils.truncate(current.title, 45)}](${current.spotifyUrl || current.url})` - : this.t(msg, "responses.filter.nothingPlayingInline"); - - const description = [ - `${statusEmoji} ${this.t(msg, "responses.player.nowPlayingLabel")}`, - `${nowPlaying}`, - ``, - `${progressBar}`, - `${timeDisplay}`, - ``, - this.t(msg, "responses.player.volumeLabel", { volume: volPercent }) + " " + volumeBar, - `${this.t(msg, "responses.player.queueLabel", { count: queueSize })} | Loop: ${loopStatus} | Filter: ${filterStatus}`, - ``, - state.message ? `💬 *${state.message}*` : `💡 *${this.t(msg, "responses.player.reactHint")}*`, - ``, - this.t(msg, "responses.player.sessionExpires", { minutes: Math.ceil(timeout / 60000) }) - ].join("\n"); - - const avatarUrl = typeof msg.author?.avatarURL === "function" - ? msg.author.avatarURL() - : msg.author?.avatarURL ?? null; - - const builder = new EmbedBuilder() - .setColor(getGlobalColor()) - .setTitle(this.t(msg, "responses.player.title")) - .setDescription(description) - .setFooter({ - text: this.t(msg, "responses.player.requestedBy", { username: msg.author?.username || "Unknown" }), - iconURL: avatarUrl - }); - if (typeof builder.setTimestamp === "function") builder.setTimestamp(); - if (current?.thumbnail) builder.setThumbnail(current.thumbnail); - return builder; - }; - - const message = await msg.reply({ embeds: [buildEmbed()] }); + const message = await msg.reply({ embeds: [buildPlayerEmbed(this, msg, player, timeout)] }); if (!message?.message) return; for (const row of controlsLayout) { @@ -172,9 +58,8 @@ export async function run(msg) { let emojiRemoveTimeout; let lastState = {}; - let activeLyricsMsg = null; - let lyricsUnobserve = null; - let lyricsEmojiTimeout = null; + /** @private @type {object} Shared lyrics-viewer session state (cleaned up by closeSession). */ + const lyrics = { activeLyricsMsg: null, unobserve: null, emojiTimeout: null }; /** * @private @@ -202,31 +87,12 @@ export async function run(msg) { clearTimeout(emojiRemoveTimeout); emojiRemoveTimeout = setTimeout(async () => { await clearReactions(); - const disabledEmbed = buildEmbed({ message: this.t(msg, "responses.player.controlsDisabled") }); + const disabledEmbed = buildPlayerEmbed(this, msg, player, timeout, { message: this.t(msg, "responses.player.controlsDisabled") }); disabledEmbed.footer = { text: this.t(msg, "responses._common.controlsExpired") }; await message.edit({ embeds: [disabledEmbed] }).catch(() => {}); }, EMOJI_REMOVE_TIMEOUT); }; - /** - * @private - * Remove navigation reactions from a lyrics message. - * @param {object} lyricsMsg - The wrapped lyrics message with a .message property. - * @returns {Promise} - */ - const clearLyricsReactions = async (lyricsMsg) => { - if (!lyricsMsg?.message) return; - try { - await lyricsMsg.message.removeAllReactions(); - } catch (e) { - for (const emoji of ["⬅️", "➡️", "❌"]) { - try { - await lyricsMsg.message.removeReaction(emoji); - } catch(e) { logger.warn("[Player] Error:", e?.message); } - } - } - }; - let editFailures = 0; /** @@ -236,7 +102,7 @@ export async function run(msg) { * @returns {void} */ const refresh = (extra = {}) => { - const embed = buildEmbed(extra); + const embed = buildPlayerEmbed(this, msg, player, timeout, extra); message.edit({ embeds: [embed] }) .then(() => { editFailures = 0; }) .catch(() => { @@ -275,17 +141,17 @@ export async function run(msg) { player.off("filter", onFilter); player.off("autoleave", onAutoLeave); - if (lyricsUnobserve) { - lyricsUnobserve(); - clearTimeout(lyricsEmojiTimeout); + if (lyrics.unobserve) { + lyrics.unobserve(); + clearTimeout(lyrics.emojiTimeout); } - if (activeLyricsMsg) { - await clearLyricsReactions(activeLyricsMsg); + if (lyrics.activeLyricsMsg) { + await clearLyricsReactions(lyrics.activeLyricsMsg); } await clearReactions(); - const closedEmbed = buildEmbed({ + const closedEmbed = buildPlayerEmbed(this, msg, player, timeout, { message: this.t(msg, "responses.player.sessionClosed", { reason: reason !== "timeout" ? ` • ${reason}` : "" }) }); closedEmbed.setColor(getGlobalColor()); @@ -431,122 +297,7 @@ export async function run(msg) { break; case "lyrics": - reply = this.t(msg, "responses.player.fetchingLyrics"); - refresh({ message: reply }); - - try { - if (lyricsUnobserve) { - lyricsUnobserve(); - clearTimeout(lyricsEmojiTimeout); - if (activeLyricsMsg) await clearLyricsReactions(activeLyricsMsg); - } - - const lyricsResult = await player.lyrics(); - if (!lyricsResult) { - reply = this.t(msg, "responses.player.noLyricsFound"); - shouldUpdate = true; - break; - } - - const syncBadge = lyricsResult.synced ? " ⏱️ Synced" : ""; - const lines = lyricsResult.text.split('\n'); - const totalLines = lines.length; - const LINES_PER_PAGE = 25; - const totalPages = Math.ceil(totalLines / LINES_PER_PAGE); - - const pages = []; - for (let i = 0; i < totalLines; i += LINES_PER_PAGE) { - pages.push(lines.slice(i, i + LINES_PER_PAGE).join('\n')); - } - - let currentPage = 0; - - const buildLyricsContent = (pageIdx, expired = false, closed = false) => { - const title = Utils.truncate( - player.queue.getCurrent()?.title?.replace(/\(Official.*?\)/gi, '').trim() ?? '', - 50 - ); - const footerText = closed - ? `👋 Lyrics closed • NodeLink • ${totalLines} lines` - : expired - ? `⌛ Controls expired • NodeLink • ${totalLines} lines` - : `NodeLink • ${totalLines} lines total${lyricsResult.synced ? ' • Synced' : ''}`; - const desc = [ - `**${title}**${syncBadge} • Page ${pageIdx + 1}/${totalPages}`, - ``, - '```', - pages[pageIdx], - totalPages > 1 && !expired && !closed ? `\n\n💡 ⬅️ ➡️ Navigate • ❌ Close` : '', - '```' - ].join('\n'); - return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).setFooter({ text: footerText })] }; - }; - - activeLyricsMsg = await msg.reply(buildLyricsContent(0)); - - if (activeLyricsMsg?.message && totalPages > 1) { - const navEmojis = ["⬅️", "➡️", "❌"]; - for (const emoji of navEmojis) { - await activeLyricsMsg.message.react(emoji).catch(() => {}); - } - - const resetLyricsTimer = () => { - clearTimeout(lyricsEmojiTimeout); - lyricsEmojiTimeout = setTimeout(async () => { - await clearLyricsReactions(activeLyricsMsg); - await activeLyricsMsg.edit(buildLyricsContent(currentPage, true, false)).catch(() => {}); - }, EMOJI_REMOVE_TIMEOUT); - }; - - lyricsUnobserve = activeLyricsMsg.onReaction(navEmojis, async (e) => { - if (e.emoji_id === "❌") { - lyricsUnobserve(); - clearTimeout(lyricsEmojiTimeout); - await clearLyricsReactions(activeLyricsMsg); - await activeLyricsMsg.edit(buildLyricsContent(currentPage, false, true)).catch(() => {}); - return; - } - - resetLyricsTimer(); - - if (e.emoji_id === "⬅️") { - currentPage = currentPage > 0 ? currentPage - 1 : totalPages - 1; - } else if (e.emoji_id === "➡️") { - currentPage = currentPage < totalPages - 1 ? currentPage + 1 : 0; - } - - await activeLyricsMsg.edit(buildLyricsContent(currentPage)); - }); - - resetLyricsTimer(); - } else if (activeLyricsMsg?.message) { - await activeLyricsMsg.message.react("❌").catch(() => {}); - - const resetLyricsTimer = () => { - clearTimeout(lyricsEmojiTimeout); - lyricsEmojiTimeout = setTimeout(async () => { - await clearLyricsReactions(activeLyricsMsg); - await activeLyricsMsg.edit(buildLyricsContent(0, true, false)).catch(() => {}); - }, EMOJI_REMOVE_TIMEOUT); - }; - - lyricsUnobserve = activeLyricsMsg.onReaction(["❌"], async (e) => { - if (e.emoji_id === "❌") { - lyricsUnobserve(); - clearTimeout(lyricsEmojiTimeout); - await clearLyricsReactions(activeLyricsMsg); - await activeLyricsMsg.edit(buildLyricsContent(0, false, true)).catch(() => {}); - } - }); - - resetLyricsTimer(); - } - - reply = this.t(msg, "responses.player.lyricsDisplayed", { lines: totalLines, pages: totalPages }); - - } catch (err) { - reply = this.t(msg, "responses.player.lyricsError", { error: Utils.truncate(err.message, 50) }); - } + reply = await openLyricsViewer(this, msg, player, refresh, lyrics); shouldUpdate = true; break; diff --git a/commands/player/consts.mjs b/commands/player/consts.mjs new file mode 100644 index 0000000..e48093f --- /dev/null +++ b/commands/player/consts.mjs @@ -0,0 +1,38 @@ +/** + * @module commands/player/consts + * @description Pure display constants for the player control panel: state + * emoji indicators, control button definitions and progress-bar characters. + */ + +/** @type {Object.} Emoji indicators for player states. */ +export const STATES = { + playing: "🎵", + paused: "⏸️", + stopped: "🔇", + loading: "⏳" +}; + +/** @type {Object.} Available control button definitions. */ +export const CONTROLS = { + prev: { emoji: "⏮️", action: "previous", desc: "Previous" }, + play: { emoji: "▶️", action: "resume", desc: "Play" }, + pause: { emoji: "⏸️", action: "pause", desc: "Pause" }, + stop: { emoji: "⏹️", action: "stop", desc: "Stop" }, + next: { emoji: "⏭️", action: "skip", desc: "Skip" }, + loop: { emoji: "🔁", action: "loop", desc: "Loop" }, + shuffle: { emoji: "🔀", action: "shuffle", desc: "Shuffle" }, + volDown: { emoji: "🔉", action: "voldown", desc: "Volume Down" }, + volUp: { emoji: "🔊", action: "volup", desc: "Volume Up" }, + lyrics: { emoji: "📜", action: "lyrics", desc: "Lyrics" }, + filter: { emoji: "🎛️", action: "filter", desc: "Audio Filters" }, + close: { emoji: "❌", action: "close", desc: "Close" } +}; + +/** @type {Object.} Progress bar character set. */ +export const PROGRESS = { + filled: "▰", + empty: "▱", + indicator: "●", + start: "▏", + end: "▕" +}; diff --git a/commands/player/embed.mjs b/commands/player/embed.mjs new file mode 100644 index 0000000..5920395 --- /dev/null +++ b/commands/player/embed.mjs @@ -0,0 +1,96 @@ +/** + * @module commands/player/embed + * @description Player panel embed construction: state emoji, progress bar, + * volume gauge, loop/filter status and footer (verbatim body of the original + * run() closure, with the bot instance passed explicitly instead of `this`). + */ + +import { Utils } from "../../src/utils/Utils.mjs"; +import { EmbedBuilder } from "@fluxerjs/core"; +import { getGlobalColor } from "../../src/ui/index.mjs"; +import { STATES, PROGRESS } from "./consts.mjs"; + +/** + * Build the player panel embed with current state, progress, volume, and loop info. + * @param {object} bot - The bot instance (used for locale translation). + * @param {object} msg - The command message wrapper. + * @param {object} player - The guild player. + * @param {number} timeout - Session timeout in ms (shown in the footer area). + * @param {object} [state={}] - Optional state override with a message field. + * @returns {EmbedBuilder} The constructed embed builder. + */ +export function buildPlayerEmbed(bot, msg, player, timeout, state = {}) { + const current = player.queue.getCurrent(); + const isPlaying = !player.paused && current; + const statusEmoji = isPlaying ? STATES.playing : player.paused ? STATES.paused : STATES.stopped; + + let progressBar = ""; + let timeDisplay = "`0:00 / 0:00`"; + + if (current?.duration && player.startedPlaying) { + const elapsed = Date.now() - player.startedPlaying; + const totalMs = typeof current.duration === "object" + ? (current.duration.seconds ?? 0) * 1000 + : current.duration; + + const bar = Utils.progressBar(elapsed, totalMs, 20, PROGRESS.filled, PROGRESS.empty, isPlaying ? PROGRESS.indicator : PROGRESS.filled); + progressBar = PROGRESS.start + bar + PROGRESS.end; + + const elapsedStr = Utils.prettifyMS(elapsed); + const totalStr = Utils.prettifyMS(totalMs); + timeDisplay = `\`${elapsedStr} / ${totalStr}\``; + } else { + progressBar = PROGRESS.start + PROGRESS.empty.repeat(20) + PROGRESS.end; + } + + const volPercent = Math.round((player.preferredVolume ?? 1) * 100); + const volBars = Math.ceil(volPercent / 10); + const volumeBar = "█".repeat(volBars) + "░".repeat(10 - volBars); + + const queueSize = player.queue.size(); + const loopStatus = player.queue.songLoop ? bot.t(msg, "responses.player.loopSong") : player.queue.loop ? bot.t(msg, "responses.player.loopQueue") : bot.t(msg, "responses.player.loopOff"); + + let filterStatus = bot.t(msg, "responses.player.filterOff"); + if (player.activeFilter) { + if (player.activeFilter.label.includes("+")) { + filterStatus = `🔥 **${player.activeFilter.label}**`; + } else { + filterStatus = `${player.activeFilter.emoji ?? "🎛️"} **${player.activeFilter.label}**`; + } + } + + const nowPlaying = current + ? `[${Utils.truncate(current.title, 45)}](${current.spotifyUrl || current.url})` + : bot.t(msg, "responses.filter.nothingPlayingInline"); + + const description = [ + `${statusEmoji} ${bot.t(msg, "responses.player.nowPlayingLabel")}`, + `${nowPlaying}`, + ``, + `${progressBar}`, + `${timeDisplay}`, + ``, + bot.t(msg, "responses.player.volumeLabel", { volume: volPercent }) + " " + volumeBar, + `${bot.t(msg, "responses.player.queueLabel", { count: queueSize })} | Loop: ${loopStatus} | Filter: ${filterStatus}`, + ``, + state.message ? `💬 *${state.message}*` : `💡 *${bot.t(msg, "responses.player.reactHint")}*`, + ``, + bot.t(msg, "responses.player.sessionExpires", { minutes: Math.ceil(timeout / 60000) }) + ].join("\n"); + + const avatarUrl = typeof msg.author?.avatarURL === "function" + ? msg.author.avatarURL() + : msg.author?.avatarURL ?? null; + + const builder = new EmbedBuilder() + .setColor(getGlobalColor()) + .setTitle(bot.t(msg, "responses.player.title")) + .setDescription(description) + .setFooter({ + text: bot.t(msg, "responses.player.requestedBy", { username: msg.author?.username || "Unknown" }), + iconURL: avatarUrl + }); + if (typeof builder.setTimestamp === "function") builder.setTimestamp(); + if (current?.thumbnail) builder.setThumbnail(current.thumbnail); + return builder; +} diff --git a/commands/player/index.mjs b/commands/player/index.mjs new file mode 100644 index 0000000..0127d7d --- /dev/null +++ b/commands/player/index.mjs @@ -0,0 +1,10 @@ +/** + * @module commands/player + * @description Barrel for the player control-panel implementation modules. + * commands/player.mjs (the command entry file) imports through this barrel; + * it stays the single import surface for the group. + */ + +export { STATES, CONTROLS, PROGRESS } from "./consts.mjs"; +export { buildPlayerEmbed } from "./embed.mjs"; +export { openLyricsViewer, clearLyricsReactions } from "./lyrics.mjs"; diff --git a/commands/player/lyrics.mjs b/commands/player/lyrics.mjs new file mode 100644 index 0000000..7f3d490 --- /dev/null +++ b/commands/player/lyrics.mjs @@ -0,0 +1,166 @@ +/** + * @module commands/player/lyrics + * @description Embedded lyrics viewer for the player panel (verbatim body of + * the original "lyrics" reaction case): paginated lyric pages with navigation + * reactions, control-expiry timer and close handling. Session-scoped mutable + * state lives in the shared `session` object ({activeLyricsMsg, unobserve, + * emojiTimeout}) so the panel's closeSession can clean it up. + */ + +import { Utils } from "../../src/utils/Utils.mjs"; +import { EmbedBuilder } from "@fluxerjs/core"; +import { getGlobalColor } from "../../src/ui/index.mjs"; +import { EMOJI_REMOVE_TIMEOUT } from "../../src/utils/UI.mjs"; +import { logger } from "../../src/core/Logger.mjs"; + +/** + * Remove navigation reactions from a lyrics message. + * @param {object} lyricsMsg - The wrapped lyrics message with a .message property. + * @returns {Promise} + */ +export async function clearLyricsReactions(lyricsMsg) { + if (!lyricsMsg?.message) return; + try { + await lyricsMsg.message.removeAllReactions(); + } catch (e) { + for (const emoji of ["⬅️", "➡️", "❌"]) { + try { + await lyricsMsg.message.removeReaction(emoji); + } catch(e) { logger.warn("[Player] Error:", e?.message); } + } + } +} + +/** + * Open (or reopen) the lyrics viewer for the player's current track. + * + * Mirrors the original `case "lyrics":` flow exactly: announces fetching, + * tears down a previous viewer, fetches lyrics from the player, renders + * paginated content, wires navigation/close reactions with the shared + * emoji-expiry timer, and returns the final reply string. Every exit path + * corresponds to `shouldUpdate = true` in the original switch, so the caller + * always refreshes the panel afterwards. + * + * @param {object} bot - The bot instance (locale translation via bot.t). + * @param {object} msg - The command message wrapper. + * @param {object} player - The guild player (player.lyrics(), queue). + * @param {function} refresh - Panel refresh callback ({ message }) => void. + * @param {object} session - Shared viewer state: { activeLyricsMsg, unobserve, emojiTimeout }. + * @returns {Promise} The reply message text to surface on the panel. + */ +export async function openLyricsViewer(bot, msg, player, refresh, session) { + let reply = bot.t(msg, "responses.player.fetchingLyrics"); + refresh({ message: reply }); + + try { + if (session.unobserve) { + session.unobserve(); + clearTimeout(session.emojiTimeout); + if (session.activeLyricsMsg) await clearLyricsReactions(session.activeLyricsMsg); + } + + const lyricsResult = await player.lyrics(); + if (!lyricsResult) { + return bot.t(msg, "responses.player.noLyricsFound"); + } + + const syncBadge = lyricsResult.synced ? " ⏱️ Synced" : ""; + const lines = lyricsResult.text.split('\n'); + const totalLines = lines.length; + const LINES_PER_PAGE = 25; + const totalPages = Math.ceil(totalLines / LINES_PER_PAGE); + + const pages = []; + for (let i = 0; i < totalLines; i += LINES_PER_PAGE) { + pages.push(lines.slice(i, i + LINES_PER_PAGE).join('\n')); + } + + let currentPage = 0; + + const buildLyricsContent = (pageIdx, expired = false, closed = false) => { + const title = Utils.truncate( + player.queue.getCurrent()?.title?.replace(/\(Official.*?\)/gi, '').trim() ?? '', + 50 + ); + const footerText = closed + ? `👋 Lyrics closed • NodeLink • ${totalLines} lines` + : expired + ? `⌛ Controls expired • NodeLink • ${totalLines} lines` + : `NodeLink • ${totalLines} lines total${lyricsResult.synced ? ' • Synced' : ''}`; + const desc = [ + `**${title}**${syncBadge} • Page ${pageIdx + 1}/${totalPages}`, + ``, + '```', + pages[pageIdx], + totalPages > 1 && !expired && !closed ? `\n\n💡 ⬅️ ➡️ Navigate • ❌ Close` : '', + '```' + ].join('\n'); + return { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc).setFooter({ text: footerText })] }; + }; + + session.activeLyricsMsg = await msg.reply(buildLyricsContent(0)); + + if (session.activeLyricsMsg?.message && totalPages > 1) { + const navEmojis = ["⬅️", "➡️", "❌"]; + for (const emoji of navEmojis) { + await session.activeLyricsMsg.message.react(emoji).catch(() => {}); + } + + const resetLyricsTimer = () => { + clearTimeout(session.emojiTimeout); + session.emojiTimeout = setTimeout(async () => { + await clearLyricsReactions(session.activeLyricsMsg); + await session.activeLyricsMsg.edit(buildLyricsContent(currentPage, true, false)).catch(() => {}); + }, EMOJI_REMOVE_TIMEOUT); + }; + + session.unobserve = session.activeLyricsMsg.onReaction(navEmojis, async (e) => { + if (e.emoji_id === "❌") { + session.unobserve(); + clearTimeout(session.emojiTimeout); + await clearLyricsReactions(session.activeLyricsMsg); + await session.activeLyricsMsg.edit(buildLyricsContent(currentPage, false, true)).catch(() => {}); + return; + } + + resetLyricsTimer(); + + if (e.emoji_id === "⬅️") { + currentPage = currentPage > 0 ? currentPage - 1 : totalPages - 1; + } else if (e.emoji_id === "➡️") { + currentPage = currentPage < totalPages - 1 ? currentPage + 1 : 0; + } + + await session.activeLyricsMsg.edit(buildLyricsContent(currentPage)); + }); + + resetLyricsTimer(); + } else if (session.activeLyricsMsg?.message) { + await session.activeLyricsMsg.message.react("❌").catch(() => {}); + + const resetLyricsTimer = () => { + clearTimeout(session.emojiTimeout); + session.emojiTimeout = setTimeout(async () => { + await clearLyricsReactions(session.activeLyricsMsg); + await session.activeLyricsMsg.edit(buildLyricsContent(0, true, false)).catch(() => {}); + }, EMOJI_REMOVE_TIMEOUT); + }; + + session.unobserve = session.activeLyricsMsg.onReaction(["❌"], async (e) => { + if (e.emoji_id === "❌") { + session.unobserve(); + clearTimeout(session.emojiTimeout); + await clearLyricsReactions(session.activeLyricsMsg); + await session.activeLyricsMsg.edit(buildLyricsContent(0, false, true)).catch(() => {}); + } + }); + + resetLyricsTimer(); + } + + return bot.t(msg, "responses.player.lyricsDisplayed", { lines: totalLines, pages: totalPages }); + + } catch (err) { + return bot.t(msg, "responses.player.lyricsError", { error: Utils.truncate(err.message, 50) }); + } +} diff --git a/commands/playnext.mjs b/commands/playnext.mjs index ac52f2d..f93784d 100644 --- a/commands/playnext.mjs +++ b/commands/playnext.mjs @@ -4,10 +4,10 @@ * Supports inline provider prefixes and flag-based provider selection. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; -import { PROVIDER_CHOICES, parseInlineProvider } from "../src/constants/providers.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; +import { PROVIDER_CHOICES, parseInlineProvider } from "../src/music/providers.mjs"; /** diff --git a/commands/radio.mjs b/commands/radio.mjs index 236f873..c032a9b 100644 --- a/commands/radio.mjs +++ b/commands/radio.mjs @@ -3,11 +3,11 @@ * @description Play internet radio stations with interactive station selection via reactions. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; -import { logger } from "../src/constants/Logger.mjs"; -import { NUMBER_EMOJIS, CANCEL_EMOJI, PREV_EMOJI, NEXT_EMOJI } from "../src/constants/UI.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; +import { logger } from "../src/core/Logger.mjs"; +import { NUMBER_EMOJIS, CANCEL_EMOJI, PREV_EMOJI, NEXT_EMOJI } from "../src/utils/UI.mjs"; /** diff --git a/commands/reload.mjs b/commands/reload.mjs index b5ee7ba..d1b87b8 100644 --- a/commands/reload.mjs +++ b/commands/reload.mjs @@ -3,9 +3,9 @@ * @description Owner-only command to hot-reload commands, source modules, or audio modules at runtime. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; import fs from "node:fs"; import path from "node:path"; import { pathToFileURL } from "node:url"; diff --git a/commands/remove.mjs b/commands/remove.mjs index 3769bd4..714183e 100644 --- a/commands/remove.mjs +++ b/commands/remove.mjs @@ -3,7 +3,7 @@ * @description Remove a specific track from the queue by its position. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; /** @type {CommandBuilder} @description Command definition for the remove command. */ export const command = new CommandBuilder() diff --git a/commands/resume.mjs b/commands/resume.mjs index a721785..8e184bd 100644 --- a/commands/resume.mjs +++ b/commands/resume.mjs @@ -3,9 +3,9 @@ * @description Resume paused playback in the current voice channel. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; /** * @type {CommandBuilder} diff --git a/commands/search.mjs b/commands/search.mjs index 385a2ed..1eb1e73 100644 --- a/commands/search.mjs +++ b/commands/search.mjs @@ -3,12 +3,12 @@ * @description Search for tracks across providers and pick one to play via reaction selection. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; -import { Message, getGlobalColor } from "../src/MessageHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; +import { Message, getGlobalColor } from "../src/ui/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { PROVIDER_CHOICES, PROVIDER_NAMES, parseInlineProvider } from "../src/constants/providers.mjs"; -import { NUMBER_EMOJIS, CANCEL_EMOJI } from "../src/constants/UI.mjs"; -import { logger } from "../src/constants/Logger.mjs"; +import { PROVIDER_CHOICES, PROVIDER_NAMES, parseInlineProvider } from "../src/music/providers.mjs"; +import { NUMBER_EMOJIS, CANCEL_EMOJI } from "../src/utils/UI.mjs"; +import { logger } from "../src/core/Logger.mjs"; /** @type {CommandBuilder} @description Command definition for the search command. */ export const command = new CommandBuilder() diff --git a/commands/seek.mjs b/commands/seek.mjs index 4315abc..3aa91f7 100644 --- a/commands/seek.mjs +++ b/commands/seek.mjs @@ -3,11 +3,11 @@ * @description Seek to a specific position in the currently playing track. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; -import { Utils } from "../src/Utils.mjs"; -import { ERROR_COLOR } from "../src/constants/UI.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; +import { Utils } from "../src/utils/Utils.mjs"; +import { ERROR_COLOR } from "../src/utils/UI.mjs"; /** @type {CommandBuilder} @description Command definition for the seek command. */ export const command = new CommandBuilder() diff --git a/commands/servers.mjs b/commands/servers.mjs index 53738cf..cc21dcf 100644 --- a/commands/servers.mjs +++ b/commands/servers.mjs @@ -3,11 +3,11 @@ * @description Owner-only command to list all servers the bot is in with pagination. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; -import { EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs"; -import { logger } from "../src/constants/Logger.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; +import { EMOJI_REMOVE_TIMEOUT } from "../src/utils/UI.mjs"; +import { logger } from "../src/core/Logger.mjs"; /** @type {CommandBuilder} @description Command definition for the servers command (owner-only). */ export const command = new CommandBuilder() diff --git a/commands/settings.mjs b/commands/settings.mjs index 7b59d56..f2e9ffb 100644 --- a/commands/settings.mjs +++ b/commands/settings.mjs @@ -1,455 +1,22 @@ /** * @module commands/settings - * @description Server settings management with subcommands (get/set/reset/help) and shortcut aliases (prefix, 247). + * @description Server settings management with subcommands (get/set/reset/help) and + * shortcut aliases (prefix, 247). The helpers live in commands/settings/ (utils, + * channels247, setters); the command factory and run() dispatch stay here. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; -import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor, cleanId, getMessageGuildId } from "../src/MessageHandler.mjs"; -import { logger } from "../src/constants/Logger.mjs"; -import runnables from "../settings/runnables.mjs"; -/** - * Command alias to setting key mapping. - * @type {Object.} - */ -const SHORTCUTS = { - prefix: "prefix", - pfx: "prefix", - "247": "stay_247", -}; - -/** @private @type {Set} Strings that evaluate to boolean true. */ -const BOOL_TRUE = new Set(["true", "1", "yes", "on", "enable", "enabled"]); -/** @private @type {Set} Strings that evaluate to boolean false. */ -const BOOL_FALSE = new Set(["false", "0", "no", "off", "disable", "disabled"]); -/** @private @type {Set} Setting keys that use boolean display formatting. */ -const BOOL_SETTINGS = new Set(["songAnnouncements"]); - -/** @private @type {Set} Available locale codes, populated at load time. */ -let VALID_LOCALES = new Set(["en"]); - -/** @private @type {number} Minimum allowed volume value. */ -const VOLUME_MIN = 1; -/** @private @type {number} Maximum allowed volume value. */ -const VOLUME_MAX = 200; -/** @private @type {number} Maximum prefix length in characters. */ -const PREFIX_MAX = 5; -/** @private @type {number} Maximum number of 24/7 channels per guild. */ -const MAX_247_CHANNELS = 1; - -/** - * Check whether a string looks like a valid Fluxer ID (Snowflake-like). - * @param {string} id - The ID to validate. - * @returns {boolean} True if the ID is 15-22 characters after cleaning. - */ -function isValidFluxerId(id) { - const cleaned = cleanId(id); - return cleaned.length >= 15 && cleaned.length <= 22; -} - -/** - * Parse a string into a boolean, or return null if unrecognised. - * @param {string} str - The string to parse. - * @returns {boolean|null} True, false, or null if not a boolean string. - */ -function parseBool(str) { - const s = String(str).toLowerCase().trim(); - if (BOOL_TRUE.has(s)) return true; - if (BOOL_FALSE.has(s)) return false; - return null; -} - -/** - * Format a setting value for display in embed messages. - * @param {string} key - The setting key. - * @param {*} value - The setting value. - * @returns {string} Formatted display string. - */ -function displayValue(key, value) { - if (BOOL_SETTINGS.has(key)) return value ? "\u2705 enabled" : "\u274c disabled"; - if (value === null || value === undefined || value === "none") return "none"; - return "`" + value + "`"; -} - -/** - * @private - * Get the display name of the guild from a message object. - * @param {object} message - The command message wrapper. - * @returns {string} The guild name, or a fallback string. - */ -function getGuildName(message) { - return message.message?.guild?.name ?? message.channel?.guild?.name ?? "this server"; -} - -/** - * @private - * Create a simple embed payload with global color, description, and optional title/footer. - * @param {string} desc - The embed description text. - * @param {object} [opts={}] - Optional overrides for title, iconURL, and footer. - * @returns {object} Embed payload for message.reply(). - */ -function embed(desc, opts = {}) { - const b = new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc); - if (opts.title) b.setTitle(opts.title); - if (opts.iconURL) b.setAuthor({ name: opts.title || "\u200b", iconURL: opts.iconURL }); - if (opts.footer) b.setFooter({ text: opts.footer }); - return { embeds: [b] }; -} - -/** - * Parse the stay_247 setting into a Set of validated channel IDs. - * @param {ServerSettings} set - The guild settings instance. - * @returns {Set} Set of cleaned, valid channel IDs. - */ -function get247Channels(set) { - const raw = set.get("stay_247"); - if (!raw || raw === "none") return new Set(); - if (typeof raw === "string") { - const id = cleanId(raw); - return (id && isValidFluxerId(id)) ? new Set([id]) : new Set(); - } - if (Array.isArray(raw)) { - return new Set(raw.map(id => cleanId(id)).filter(id => id && isValidFluxerId(id))); - } - return new Set(); -} - -/** - * Save a Set of channel IDs back to the stay_247 setting. - * Writes 'none' if the set is empty. - * @param {ServerSettings} set - The guild settings instance. - * @param {Set} channels - The channel IDs to save. - */ -function save247Channels(set, channels) { - const arr = [...channels].filter(id => id && isValidFluxerId(id)); - set.set("stay_247", arr.length > 0 ? arr : "none"); -} - -/** - * @private - * Resolve a channel ID to a human-readable channel name from the client cache. - * @param {import('@fluxerjs/core').Client} client - The Discord/Fluxer client. - * @param {string} channelId - The channel ID to look up. - * @returns {string|null} The channel name, or null if not found. - */ -function resolveChannelName(client, channelId) { - try { - const ch = client?.channels?.get?.(channelId); - if (ch?.name) return ch.name; - } catch (_) {} - return null; -} - -/** - * @private - * Create a translation function bound to the given context and guild. - * @param {object} ctx - The bot (Remix) context. - * @param {string} guildId - The guild ID for localization. - * @returns {Function} A translation function with signature (key, data?) => string. - */ -function tWrap(ctx, guildId) { - const tFn = ctx.locale?.translate?.bind(ctx.locale); - return (key, data = {}) => tFn ? tFn(guildId, key, data) : key; -} - -/** - * @private - * Get a human-readable label for a setting key, using locale translations when available. - * @param {string} key - The setting key. - * @param {Function|null} t - Translation function (guildId, key, data) => string. - * @param {string} guildId - The guild ID for localization. - * @returns {string} The pretty-printed setting label. - */ -function prettifySettingLabel(key, t, guildId) { - const localeMap = { - songAnnouncements: "responses.settings.labelSongAnnouncements", - prefix: "responses.settings.labelPrefix", - pfx: "responses.settings.labelPfp", - locale: "responses.settings.labelLocale", - stay_247: "responses.settings.label247", - volume: "responses.settings.labelVolume", - }; - if (localeMap[key] && t && guildId) return t(guildId, localeMap[key]); - const fallback = { - songAnnouncements: "Song announcements", - prefix: "Prefix", - pfp: "Bot avatar style", - locale: "Locale", - stay_247: "24/7 mode", - volume: "Default volume", - }; - return fallback[key] ?? key.replace(/_/g, " "); -} - -/** - * Build an embed payload showing the current 24/7 status for the guild. - * @param {ServerSettings} set - The guild settings instance. - * @param {object} ctx - The bot (Remix) context. - * @param {string} guildId - The guild ID. - * @param {string|null} channelId - The channel ID (for active indicator), or null. - * @returns {object} Embed payload object for message.reply(). - */ -function build247Panel(set, ctx, guildId, channelId) { - const channels = [...get247Channels(set)]; - const prefix = ctx.handler.getPrefix(guildId); - - if (channels.length > 0) { - const lines = channels.map(id => { - const name = resolveChannelName(ctx.client, id); - const isActive = id === channelId; - return (isActive ? "\u25b6 " : "\u2022 ") + (name ? "**" + name + "** " : "") + "<#" + id + ">"; - }); - return embed( - channels.length === 1 && channelId - ? "\u2705 24/7 is now **enabled** in <#" + channelId + ">\n\n" + - "The bot will stay connected and auto-rejoin if disconnected." - : "\u2705 24/7 active in " + channels.length + " channel(s):\n\n" + lines.join("\n"), - { title: "\u2705 24/7 Mode" } - ); - } - - return embed( - "\u274c 24/7 is **disabled**\n\n" + - "The bot will leave voice channels when idle.\n\n" + - "Join a voice channel and use `" + prefix + "247` to enable.", - { title: "\u274c 24/7 Mode" } - ); -} - -/** - * Disable 24/7 mode for a specific channel. - * Removes the channel from stay_247, marks intentional leave, and destroys the player. - * @param {object} ctx - The bot (Remix) context. - * @param {ServerSettings} set - The guild settings instance. - * @param {string} guildId - The guild ID. - * @param {string} channelId - The channel ID to disable. - * @returns {Promise} - */ -async function disable247(ctx, set, guildId, channelId) { - const id = cleanId(channelId); - const channels = get247Channels(set); - channels.delete(id); - save247Channels(set, channels); - ctx.markIntentionalLeave?.(id); - const player = ctx.players.playerMap.get(id) - ?? [...ctx.players.playerMap.values()].find(p => - cleanId(p?._channelId ?? "") === id && - cleanId(p?._guildId ?? "") === cleanId(guildId) - ); - if (player) { - const activeId = cleanId(player._channelId ?? id); - ctx.players.playerMap.delete(activeId); - if (activeId !== id) ctx.players.playerMap.delete(id); - await player.leave().catch(() => {}); - player.destroy(); - } -} - -/** - * Enable 24/7 mode for a specific channel. - * Enforces MAX_247_CHANNELS (1) by disabling any existing 24/7 channel first, - * then saves the new channel and spawns a player if none exists. - * @param {object} ctx - The bot (Remix) context. - * @param {ServerSettings} set - The guild settings instance. - * @param {string} guildId - The guild ID. - * @param {string} channelId - The channel ID to enable. - * @returns {Promise} - */ -async function enable247(ctx, set, guildId, channelId) { - const id = cleanId(channelId); - const channels = get247Channels(set); - if (channels.has(id)) return; - - // Platform only supports 1 voice channel per bot per guild. - // If another channel already has 24/7, disable it first. - if (channels.size >= MAX_247_CHANNELS) { - for (const oldId of channels) { - if (oldId !== id) { - ctx.markIntentionalLeave?.(oldId); - const oldPlayer = ctx.players.playerMap.get(oldId) - ?? [...ctx.players.playerMap.values()].find(p => - cleanId(p?._channelId ?? "") === oldId && - cleanId(p?._guildId ?? "") === cleanId(guildId) - ); - if (oldPlayer) { - const activeId = cleanId(oldPlayer._channelId ?? oldId); - ctx.players.playerMap.delete(activeId); - if (activeId !== oldId) ctx.players.playerMap.delete(oldId); - await oldPlayer.leave().catch(() => {}); - oldPlayer.destroy(); - } - channels.delete(oldId); - } - } - } - - channels.add(id); - save247Channels(set, channels); - const playerExists = ctx.players.playerMap.has(id) || - [...ctx.players.playerMap.values()].some(p => - cleanId(p?._channelId ?? "") === id && cleanId(p?._guildId ?? "") === cleanId(guildId) - ); - if (!playerExists) { - try { await ctx._spawnPlayer(guildId, id); } catch (_) {} - } -} - -/** - * Handle the !247 toggle command. If the user is in a 24/7 channel, disable it; - * otherwise, enable it for the user's current voice channel. - * @param {object} ctx - The bot (Remix) context. - * @param {object} message - The command message. - * @param {ServerSettings} set - The guild settings instance. - * @param {string} guildId - The guild ID. - * @returns {Promise} - */ -async function handle247Toggle(ctx, message, set, guildId) { - const loc = tWrap(ctx, guildId); - if (!guildId) return message.reply(embed(loc("responses.settings.noServer"))); - - const { channelId: userChannelId } = await ctx.players.checkVoiceChannels(message); - if (!userChannelId) { - return message.reply(build247Panel(set, ctx, guildId, null)); - } - - const id = cleanId(userChannelId); - const channels = get247Channels(set); - - if (channels.has(id)) { - await disable247(ctx, set, guildId, userChannelId); - return message.reply(build247Panel(set, ctx, guildId, id)); - } - - const result = await enable247(ctx, set, guildId, userChannelId); - if (result?.max) { - return message.reply(embed( - loc("responses.settings.max247Channels", { max: MAX_247_CHANNELS, prefix: ctx.handler.getPrefix(guildId) }) - )); - } - - return message.reply(build247Panel(set, ctx, guildId, id)); -} - -/** - * Apply a new value to a setting, with type-specific validation. - * @param {object} ctx - The bot (Remix) context. - * @param {object} message - The command message. - * @param {ServerSettings} set - The guild settings instance. - * @param {string} key - The setting key. - * @param {string} rawValue - The raw string value from the command. - * @returns {Promise} Error message string, or null on success. - */ -async function applySet(ctx, message, set, key, rawValue) { - if (BOOL_SETTINGS.has(key)) { - const bool = parseBool(rawValue); - if (bool === null) { - return ctx.t(message, "responses.settings.mustBeBool", { setting: key }); - } - set.set(key, bool); - return null; - } - - if (key === "volume") { - const num = parseInt(rawValue, 10); - if (isNaN(num) || num < VOLUME_MIN || num > VOLUME_MAX) { - return ctx.t(message, "responses.settings.volumeRange"); - } - set.set(key, num); - return null; - } - - if (key === "locale") { - if (!VALID_LOCALES.has(rawValue)) { - return ctx.t(message, "responses.settings.invalidLocale", { - locale: rawValue, - locales: [...VALID_LOCALES].map(l => "`" + l + "`").join(", ") - }); - } - set.set(key, rawValue); - const gid = getMessageGuildId(message); - if (gid) ctx.locale.invalidateCache(gid); - return null; - } - - if (key === "prefix") { - if (!rawValue || rawValue.length > PREFIX_MAX) { - return ctx.t(message, "responses.settings.prefixLength"); - } - if (/\s/.test(rawValue)) { - return ctx.t(message, "responses.settings.prefixSpaces"); - } - } - - if (runnables[key]) { - const err = runnables[key].call(ctx, rawValue, { msg: message }); - if (err) return "\u274c " + err; - } - - set.set(key, rawValue); - return null; -} - -/** - * @private - * @async - * Handle a settings shortcut command (e.g. `prefix`, `247`). - * Dispatches to 24/7 toggle, value display, or value set depending on arguments. - * @param {object} ctx - The bot (Remix) context. - * @param {object} message - The command message. - * @param {string} settingKey - The resolved setting key. - * @param {string[]} valueTokens - Remaining argument tokens after the shortcut alias. - * @returns {Promise} - */ -async function handleShortcut(ctx, message, settingKey, valueTokens) { - const set = ctx.getSettings(message); - const guildId = getMessageGuildId(message); - const t247 = ctx.locale?.translate?.bind(ctx.locale); - - if (valueTokens.length === 0) { - if (settingKey === "stay_247") { - return handle247Toggle(ctx, message, set, guildId); - } - const val = set.get(settingKey); - const label = prettifySettingLabel(settingKey, t247, guildId); - return message.reply(embed("**" + label + "**\nValue: " + displayValue(settingKey, val))); - } - - const rawValue = valueTokens.join(" "); - - if (settingKey === "stay_247") { - const mode = rawValue.toLowerCase().trim(); - if (mode === "off" || mode === "false" || mode === "disable" || mode === "0") { - const loc = tWrap(ctx, guildId); - if (!guildId) return message.reply(embed(loc("responses.settings.noServer"))); - const { channelId } = await ctx.players.checkVoiceChannels(message); - if (channelId) { - await disable247(ctx, set, guildId, channelId); - return message.reply(build247Panel(set, ctx, guildId, cleanId(channelId))); - } - for (const [chId, player] of [...ctx.players.playerMap.entries()]) { - if (cleanId(player?._guildId ?? "") === cleanId(guildId)) { - const activeId = cleanId(player._channelId ?? chId); - ctx.markIntentionalLeave?.(activeId); - ctx.players.playerMap.delete(activeId); - if (activeId !== chId) ctx.players.playerMap.delete(chId); - await player.leave().catch(() => {}); - player.destroy(); - } - } - save247Channels(set, new Set()); - return message.reply(build247Panel(set, ctx, guildId, null)); - } - return handle247Toggle(ctx, message, set, guildId); - } - - const err = await applySet(ctx, message, set, settingKey, rawValue); - if (err) return message.reply(embed(err)); - - const val = set.get(settingKey); - const label = prettifySettingLabel(settingKey, t247, guildId); - return message.reply(embed(ctx.t(message, "responses.settings.setSuccess", { label, value: displayValue(settingKey, val) }))); -} +import { CommandBuilder } from "../src/commands/index.mjs"; +import { getMessageGuildId } from "../src/ui/index.mjs"; +// kept verbatim from the original file (unused there as well): +import { logger } from "../src/core/Logger.mjs"; +import { + SHORTCUTS, BOOL_SETTINGS, VALID_LOCALES, setValidLocales, + VOLUME_MIN, VOLUME_MAX, + displayValue, getGuildName, embed, prettifySettingLabel, +} from "./settings/utils.mjs"; +import { get247Channels, build247Panel } from "./settings/channels247.mjs"; +import { applySet, handleShortcut } from "./settings/setters.mjs"; /** * @type {Function} @@ -459,7 +26,7 @@ async function handleShortcut(ctx, message, settingKey, valueTokens) { */ export const command = function() { if (this.locale) { - VALID_LOCALES = this.locale.availableLocales(); + setValidLocales(this.locale.availableLocales()); } if (this.loader) { diff --git a/commands/settings/channels247.mjs b/commands/settings/channels247.mjs new file mode 100644 index 0000000..a417b82 --- /dev/null +++ b/commands/settings/channels247.mjs @@ -0,0 +1,198 @@ +/** + * @module commands/settings/channels247 + * @description 24/7 channel storage, panel + * rendering and enable/disable/toggle handling for the settings command. + * Bodies are verbatim from the original single-file command. + */ + + +import { cleanId } from "../../src/ui/index.mjs"; +import { isValidFluxerId, MAX_247_CHANNELS, embed, tWrap } from "./utils.mjs"; + +/** + * Parse the stay_247 setting into a Set of validated channel IDs. + * @param {ServerSettings} set - The guild settings instance. + * @returns {Set} Set of cleaned, valid channel IDs. + */ +export function get247Channels(set) { + const raw = set.get("stay_247"); + if (!raw || raw === "none") return new Set(); + if (typeof raw === "string") { + const id = cleanId(raw); + return (id && isValidFluxerId(id)) ? new Set([id]) : new Set(); + } + if (Array.isArray(raw)) { + return new Set(raw.map(id => cleanId(id)).filter(id => id && isValidFluxerId(id))); + } + return new Set(); +} +/** + * Save a Set of channel IDs back to the stay_247 setting. + * Writes 'none' if the set is empty. + * @param {ServerSettings} set - The guild settings instance. + * @param {Set} channels - The channel IDs to save. + */ +export function save247Channels(set, channels) { + const arr = [...channels].filter(id => id && isValidFluxerId(id)); + set.set("stay_247", arr.length > 0 ? arr : "none"); +} +/** + * @private + * Resolve a channel ID to a human-readable channel name from the client cache. + * @param {import('@fluxerjs/core').Client} client - The Fluxer client. + * @param {string} channelId - The channel ID to look up. + * @returns {string|null} The channel name, or null if not found. + */ +function resolveChannelName(client, channelId) { + try { + const ch = client?.channels?.get?.(channelId); + if (ch?.name) return ch.name; + } catch (_) {} + return null; +} + +/** + * Build an embed payload showing the current 24/7 status for the guild. + * @param {ServerSettings} set - The guild settings instance. + * @param {object} ctx - The bot (Remix) context. + * @param {string} guildId - The guild ID. + * @param {string|null} channelId - The channel ID (for active indicator), or null. + * @returns {object} Embed payload object for message.reply(). + */ +export function build247Panel(set, ctx, guildId, channelId) { + const channels = [...get247Channels(set)]; + const prefix = ctx.handler.getPrefix(guildId); + + if (channels.length > 0) { + const lines = channels.map(id => { + const name = resolveChannelName(ctx.client, id); + const isActive = id === channelId; + return (isActive ? "\u25b6 " : "\u2022 ") + (name ? "**" + name + "** " : "") + "<#" + id + ">"; + }); + return embed( + channels.length === 1 && channelId + ? "\u2705 24/7 is now **enabled** in <#" + channelId + ">\n\n" + + "The bot will stay connected and auto-rejoin if disconnected." + : "\u2705 24/7 active in " + channels.length + " channel(s):\n\n" + lines.join("\n"), + { title: "\u2705 24/7 Mode" } + ); + } + + return embed( + "\u274c 24/7 is **disabled**\n\n" + + "The bot will leave voice channels when idle.\n\n" + + "Join a voice channel and use `" + prefix + "247` to enable.", + { title: "\u274c 24/7 Mode" } + ); +} +/** + * Disable 24/7 mode for a specific channel. + * Removes the channel from stay_247, marks intentional leave, and destroys the player. + * @param {object} ctx - The bot (Remix) context. + * @param {ServerSettings} set - The guild settings instance. + * @param {string} guildId - The guild ID. + * @param {string} channelId - The channel ID to disable. + * @returns {Promise} + */ +export async function disable247(ctx, set, guildId, channelId) { + const id = cleanId(channelId); + const channels = get247Channels(set); + channels.delete(id); + save247Channels(set, channels); + ctx.markIntentionalLeave?.(id); + const player = ctx.players.playerMap.get(id) + ?? [...ctx.players.playerMap.values()].find(p => + cleanId(p?._channelId ?? "") === id && + cleanId(p?._guildId ?? "") === cleanId(guildId) + ); + if (player) { + const activeId = cleanId(player._channelId ?? id); + ctx.players.playerMap.delete(activeId); + if (activeId !== id) ctx.players.playerMap.delete(id); + await player.leave().catch(() => {}); + player.destroy(); + } +} +/** + * Enable 24/7 mode for a specific channel. + * Enforces MAX_247_CHANNELS (1) by disabling any existing 24/7 channel first, + * then saves the new channel and spawns a player if none exists. + * @param {object} ctx - The bot (Remix) context. + * @param {ServerSettings} set - The guild settings instance. + * @param {string} guildId - The guild ID. + * @param {string} channelId - The channel ID to enable. + * @returns {Promise} + */ +async function enable247(ctx, set, guildId, channelId) { + const id = cleanId(channelId); + const channels = get247Channels(set); + if (channels.has(id)) return; + + // Platform only supports 1 voice channel per bot per guild. + // If another channel already has 24/7, disable it first. + if (channels.size >= MAX_247_CHANNELS) { + for (const oldId of channels) { + if (oldId !== id) { + ctx.markIntentionalLeave?.(oldId); + const oldPlayer = ctx.players.playerMap.get(oldId) + ?? [...ctx.players.playerMap.values()].find(p => + cleanId(p?._channelId ?? "") === oldId && + cleanId(p?._guildId ?? "") === cleanId(guildId) + ); + if (oldPlayer) { + const activeId = cleanId(oldPlayer._channelId ?? oldId); + ctx.players.playerMap.delete(activeId); + if (activeId !== oldId) ctx.players.playerMap.delete(oldId); + await oldPlayer.leave().catch(() => {}); + oldPlayer.destroy(); + } + channels.delete(oldId); + } + } + } + + channels.add(id); + save247Channels(set, channels); + const playerExists = ctx.players.playerMap.has(id) || + [...ctx.players.playerMap.values()].some(p => + cleanId(p?._channelId ?? "") === id && cleanId(p?._guildId ?? "") === cleanId(guildId) + ); + if (!playerExists) { + try { await ctx._spawnPlayer(guildId, id); } catch (_) {} + } +} +/** + * Handle the !247 toggle command. If the user is in a 24/7 channel, disable it; + * otherwise, enable it for the user's current voice channel. + * @param {object} ctx - The bot (Remix) context. + * @param {object} message - The command message. + * @param {ServerSettings} set - The guild settings instance. + * @param {string} guildId - The guild ID. + * @returns {Promise} + */ +export async function handle247Toggle(ctx, message, set, guildId) { + const loc = tWrap(ctx, guildId); + if (!guildId) return message.reply(embed(loc("responses.settings.noServer"))); + + const { channelId: userChannelId } = await ctx.players.checkVoiceChannels(message); + if (!userChannelId) { + return message.reply(build247Panel(set, ctx, guildId, null)); + } + + const id = cleanId(userChannelId); + const channels = get247Channels(set); + + if (channels.has(id)) { + await disable247(ctx, set, guildId, userChannelId); + return message.reply(build247Panel(set, ctx, guildId, id)); + } + + const result = await enable247(ctx, set, guildId, userChannelId); + if (result?.max) { + return message.reply(embed( + loc("responses.settings.max247Channels", { max: MAX_247_CHANNELS, prefix: ctx.handler.getPrefix(guildId) }) + )); + } + + return message.reply(build247Panel(set, ctx, guildId, id)); +} diff --git a/commands/settings/setters.mjs b/commands/settings/setters.mjs new file mode 100644 index 0000000..aff741e --- /dev/null +++ b/commands/settings/setters.mjs @@ -0,0 +1,136 @@ +/** + * @module commands/settings/setters + * @description Value application (applySet) and + * shortcut dispatch (handleShortcut) for the settings command. Bodies are + * verbatim from the original single-file command. + */ + + +import { cleanId, getMessageGuildId } from "../../src/ui/index.mjs"; +import runnables from "../../settings/runnables.mjs"; +import { + parseBool, displayValue, getGuildName, embed, tWrap, prettifySettingLabel, + BOOL_SETTINGS, VALID_LOCALES, VOLUME_MIN, VOLUME_MAX, PREFIX_MAX, SHORTCUTS, +} from "./utils.mjs"; +import { + get247Channels, save247Channels, build247Panel, disable247, handle247Toggle, +} from "./channels247.mjs"; + +/** + * Apply a new value to a setting, with type-specific validation. + * @param {object} ctx - The bot (Remix) context. + * @param {object} message - The command message. + * @param {ServerSettings} set - The guild settings instance. + * @param {string} key - The setting key. + * @param {string} rawValue - The raw string value from the command. + * @returns {Promise} Error message string, or null on success. + */ +export async function applySet(ctx, message, set, key, rawValue) { + if (BOOL_SETTINGS.has(key)) { + const bool = parseBool(rawValue); + if (bool === null) { + return ctx.t(message, "responses.settings.mustBeBool", { setting: key }); + } + set.set(key, bool); + return null; + } + + if (key === "volume") { + const num = parseInt(rawValue, 10); + if (isNaN(num) || num < VOLUME_MIN || num > VOLUME_MAX) { + return ctx.t(message, "responses.settings.volumeRange"); + } + set.set(key, num); + return null; + } + + if (key === "locale") { + if (!VALID_LOCALES.has(rawValue)) { + return ctx.t(message, "responses.settings.invalidLocale", { + locale: rawValue, + locales: [...VALID_LOCALES].map(l => "`" + l + "`").join(", ") + }); + } + set.set(key, rawValue); + const gid = getMessageGuildId(message); + if (gid) ctx.locale.invalidateCache(gid); + return null; + } + + if (key === "prefix") { + if (!rawValue || rawValue.length > PREFIX_MAX) { + return ctx.t(message, "responses.settings.prefixLength"); + } + if (/\s/.test(rawValue)) { + return ctx.t(message, "responses.settings.prefixSpaces"); + } + } + + if (runnables[key]) { + const err = runnables[key].call(ctx, rawValue, { msg: message }); + if (err) return "\u274c " + err; + } + + set.set(key, rawValue); + return null; +} +/** + * @private + * @async + * Handle a settings shortcut command (e.g. `prefix`, `247`). + * Dispatches to 24/7 toggle, value display, or value set depending on arguments. + * @param {object} ctx - The bot (Remix) context. + * @param {object} message - The command message. + * @param {string} settingKey - The resolved setting key. + * @param {string[]} valueTokens - Remaining argument tokens after the shortcut alias. + * @returns {Promise} + */ +export async function handleShortcut(ctx, message, settingKey, valueTokens) { + const set = ctx.getSettings(message); + const guildId = getMessageGuildId(message); + const t247 = ctx.locale?.translate?.bind(ctx.locale); + + if (valueTokens.length === 0) { + if (settingKey === "stay_247") { + return handle247Toggle(ctx, message, set, guildId); + } + const val = set.get(settingKey); + const label = prettifySettingLabel(settingKey, t247, guildId); + return message.reply(embed("**" + label + "**\nValue: " + displayValue(settingKey, val))); + } + + const rawValue = valueTokens.join(" "); + + if (settingKey === "stay_247") { + const mode = rawValue.toLowerCase().trim(); + if (mode === "off" || mode === "false" || mode === "disable" || mode === "0") { + const loc = tWrap(ctx, guildId); + if (!guildId) return message.reply(embed(loc("responses.settings.noServer"))); + const { channelId } = await ctx.players.checkVoiceChannels(message); + if (channelId) { + await disable247(ctx, set, guildId, channelId); + return message.reply(build247Panel(set, ctx, guildId, cleanId(channelId))); + } + for (const [chId, player] of [...ctx.players.playerMap.entries()]) { + if (cleanId(player?._guildId ?? "") === cleanId(guildId)) { + const activeId = cleanId(player._channelId ?? chId); + ctx.markIntentionalLeave?.(activeId); + ctx.players.playerMap.delete(activeId); + if (activeId !== chId) ctx.players.playerMap.delete(chId); + await player.leave().catch(() => {}); + player.destroy(); + } + } + save247Channels(set, new Set()); + return message.reply(build247Panel(set, ctx, guildId, null)); + } + return handle247Toggle(ctx, message, set, guildId); + } + + const err = await applySet(ctx, message, set, settingKey, rawValue); + if (err) return message.reply(embed(err)); + + const val = set.get(settingKey); + const label = prettifySettingLabel(settingKey, t247, guildId); + return message.reply(embed(ctx.t(message, "responses.settings.setSuccess", { label, value: displayValue(settingKey, val) }))); +} diff --git a/commands/settings/utils.mjs b/commands/settings/utils.mjs new file mode 100644 index 0000000..3966a65 --- /dev/null +++ b/commands/settings/utils.mjs @@ -0,0 +1,146 @@ +/** + * @module commands/settings/utils + * @description Constants and pure helpers + * shared by the settings command modules. Bodies are verbatim from the + * original single-file command; `export ` prefixes and setValidLocales() + * are the only additions. + */ + + +import { EmbedBuilder } from "@fluxerjs/core"; +import { getGlobalColor, cleanId } from "../../src/ui/index.mjs"; + +/** + * Command alias to setting key mapping. + * @type {Object.} + */ +export const SHORTCUTS = { + prefix: "prefix", + pfx: "prefix", + "247": "stay_247", +}; + +/** @private @type {Set} Strings that evaluate to boolean true. */ +const BOOL_TRUE = new Set(["true", "1", "yes", "on", "enable", "enabled"]); +/** @private @type {Set} Strings that evaluate to boolean false. */ +const BOOL_FALSE = new Set(["false", "0", "no", "off", "disable", "disabled"]); +/** @private @type {Set} Setting keys that use boolean display formatting. */ +export const BOOL_SETTINGS = new Set(["songAnnouncements"]); + +/** @private @type {Set} Available locale codes, populated at load time. */ +export let VALID_LOCALES = new Set(["en"]); + +/** @private @type {number} Minimum allowed volume value. */ +export const VOLUME_MIN = 1; +/** @private @type {number} Maximum allowed volume value. */ +export const VOLUME_MAX = 200; +/** @private @type {number} Maximum prefix length in characters. */ +export const PREFIX_MAX = 5; +/** @private @type {number} Maximum number of 24/7 channels per guild. */ +export const MAX_247_CHANNELS = 1; + +/** + * Replace the set of known locale codes (called by the settings command + * factory at load time). Importers read VALID_LOCALES as a live binding, + * so this stays behavior-identical to the original module-level assignment. + * @param {Iterable} locales + */ +export function setValidLocales(locales) { + VALID_LOCALES = locales; +} + + +/** + * Check whether a string looks like a valid Fluxer ID (Snowflake-like). + * @param {string} id - The ID to validate. + * @returns {boolean} True if the ID is 15-22 characters after cleaning. + */ +export function isValidFluxerId(id) { + const cleaned = cleanId(id); + return cleaned.length >= 15 && cleaned.length <= 22; +} +/** + * Parse a string into a boolean, or return null if unrecognised. + * @param {string} str - The string to parse. + * @returns {boolean|null} True, false, or null if not a boolean string. + */ +export function parseBool(str) { + const s = String(str).toLowerCase().trim(); + if (BOOL_TRUE.has(s)) return true; + if (BOOL_FALSE.has(s)) return false; + return null; +} +/** + * Format a setting value for display in embed messages. + * @param {string} key - The setting key. + * @param {*} value - The setting value. + * @returns {string} Formatted display string. + */ +export function displayValue(key, value) { + if (BOOL_SETTINGS.has(key)) return value ? "\u2705 enabled" : "\u274c disabled"; + if (value === null || value === undefined || value === "none") return "none"; + return "`" + value + "`"; +} +/** + * @private + * Get the display name of the guild from a message object. + * @param {object} message - The command message wrapper. + * @returns {string} The guild name, or a fallback string. + */ +export function getGuildName(message) { + return message.message?.guild?.name ?? message.channel?.guild?.name ?? "this server"; +} +/** + * @private + * Create a simple embed payload with global color, description, and optional title/footer. + * @param {string} desc - The embed description text. + * @param {object} [opts={}] - Optional overrides for title, iconURL, and footer. + * @returns {object} Embed payload for message.reply(). + */ +export function embed(desc, opts = {}) { + const b = new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc); + if (opts.title) b.setTitle(opts.title); + if (opts.iconURL) b.setAuthor({ name: opts.title || "\u200b", iconURL: opts.iconURL }); + if (opts.footer) b.setFooter({ text: opts.footer }); + return { embeds: [b] }; +} + +/** + * @private + * Create a translation function bound to the given context and guild. + * @param {object} ctx - The bot (Remix) context. + * @param {string} guildId - The guild ID for localization. + * @returns {Function} A translation function with signature (key, data?) => string. + */ +export function tWrap(ctx, guildId) { + const tFn = ctx.locale?.translate?.bind(ctx.locale); + return (key, data = {}) => tFn ? tFn(guildId, key, data) : key; +} +/** + * @private + * Get a human-readable label for a setting key, using locale translations when available. + * @param {string} key - The setting key. + * @param {Function|null} t - Translation function (guildId, key, data) => string. + * @param {string} guildId - The guild ID for localization. + * @returns {string} The pretty-printed setting label. + */ +export function prettifySettingLabel(key, t, guildId) { + const localeMap = { + songAnnouncements: "responses.settings.labelSongAnnouncements", + prefix: "responses.settings.labelPrefix", + pfx: "responses.settings.labelPfp", + locale: "responses.settings.labelLocale", + stay_247: "responses.settings.label247", + volume: "responses.settings.labelVolume", + }; + if (localeMap[key] && t && guildId) return t(guildId, localeMap[key]); + const fallback = { + songAnnouncements: "Song announcements", + prefix: "Prefix", + pfp: "Bot avatar style", + locale: "Locale", + stay_247: "24/7 mode", + volume: "Default volume", + }; + return fallback[key] ?? key.replace(/_/g, " "); +} diff --git a/commands/shuffle.mjs b/commands/shuffle.mjs index 38831b8..4926fe1 100644 --- a/commands/shuffle.mjs +++ b/commands/shuffle.mjs @@ -3,9 +3,9 @@ * @description Randomly re-order the tracks in the playback queue. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; /** * @type {CommandBuilder} diff --git a/commands/skip.mjs b/commands/skip.mjs index 209ae25..f7a5c5b 100644 --- a/commands/skip.mjs +++ b/commands/skip.mjs @@ -3,9 +3,9 @@ * @description Skip the currently playing track. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; /** @type {CommandBuilder} @description Command definition for the skip command. */ export const command = new CommandBuilder() diff --git a/commands/stats.mjs b/commands/stats.mjs index 9dd45f0..d1a3454 100644 --- a/commands/stats.mjs +++ b/commands/stats.mjs @@ -5,11 +5,11 @@ import * as fs from "node:fs"; import * as path from "node:path"; -import { CommandBuilder } from "../src/CommandHandler.mjs"; -import { Utils } from "../src/Utils.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; +import { Utils } from "../src/utils/Utils.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; -import { logger } from "../src/constants/Logger.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; +import { logger } from "../src/core/Logger.mjs"; /** * @type {CommandBuilder} @@ -33,6 +33,9 @@ const RATE_LIMIT_MAX_RETRIES = 2; const RATE_LIMIT_MAX_WAIT_MS = 15_000; /** Where the warm cache is persisted (cwd-relative, same convention as ./storage/defaults.json). */ const CACHE_FILE = path.join(process.cwd(), "storage", "stats-cache.json"); +/** Last-resort label for the gateway line when locale files lack the key + * (customized deployments keep their own locale files across updates). */ +const GATEWAY_FALLBACK_LABEL = "\u{1F310} **Gateway**"; let cache = { guilds: null, users: null, scrobbles: null, linkedUsers: null, updatedAt: 0 }; let lastPing = null; @@ -180,6 +183,23 @@ function withBudget(promise, ms, fallback) { }); } +/** + * Read the gateway heartbeat ACK latency from the WebSocket manager + * (`client.ws.ping`). Returns -1 when unavailable (not logged in yet, or + * no heartbeat ACK received yet). + * @private + * @param {object} client - The client instance. + * @returns {number} Gateway latency in ms, or -1. + */ +function readGatewayPing(client) { + try { + const ping = client?.ws?.ping; + return typeof ping === "number" && Number.isFinite(ping) ? ping : -1; + } catch (_) { + return -1; + } +} + /** * Run a message send/edit action, transparently retrying when the REST * library throws a 429 RateLimitError. Waits exactly as long as the API @@ -236,6 +256,22 @@ function getLivePlayerCount(playerMap) { return live; } +/** + * Translate with a hardcoded fallback. Locale lookups that miss (custom or + * outdated locale files make translate() return the raw dot-notation key) + * render the readable fallback instead of an ugly key path in the embed. + * @private + * @param {Function} t - Translation function. + * @param {object} msg - The command message wrapper. + * @param {string} key - Locale key. + * @param {string} fallback - Label used when the key is missing. + * @returns {string} + */ +function tOr(t, msg, key, fallback) { + const value = t(msg, key); + return value === key ? fallback : value; +} + /** * Build the stats embed with all bot information. * @private @@ -247,7 +283,8 @@ function getLivePlayerCount(playerMap) { * @param {number} s.playerCount - Number of active players. * @param {number} s.scrobbleCount - Total Last.fm scrobbles. * @param {number} s.linkedUsers - Number of Last.fm linked users. - * @param {number} s.ping - Bot response ping in ms. + * @param {number} s.ping - Bot response ping in ms (REST reply round trip). + * @param {number} s.gatewayPing - Gateway heartbeat ACK latency in ms (-1 if unknown). * @param {string} s.uptime - Formatted uptime string. * @param {string} s.comHash - Git commit hash. * @param {string} s.comLink - Git commit link URL. @@ -276,6 +313,7 @@ function buildEmbed(t, msg, s, pending = []) { description.push( `${t(msg, "responses.stats.ping")} — ${field("ping", `${num(s.ping)}ms`)}`, + s.gatewayPing >= 0 ? `${tOr(t, msg, "responses.stats.gateway", GATEWAY_FALLBACK_LABEL)} — \`${num(s.gatewayPing)}ms\`` : null, `${t(msg, "responses.stats.uptime")} — \`${s.uptime}\``, `${t(msg, "responses.stats.build")} — [\`${s.comHash}\`](${s.comLink})`, s.reason ? `${t(msg, "responses.stats.lastRestart")} — \`${s.reason}\`` : null, @@ -330,6 +368,7 @@ export async function run(message) { linkedUsers: lastfmEnabled ? (cache.linkedUsers ?? 0) : 0, lastfmEnabled, ping: lastPing ?? 0, + gatewayPing: readGatewayPing(this.client), uptime: Utils.prettifyMS(Math.round(process.uptime()) * 1000), comHash: this.comHash, comLink: this.comLink, @@ -374,6 +413,7 @@ export async function run(message) { scrobbleCount: lastfmEnabled ? (cache.scrobbles ?? 0) : 0, linkedUsers: lastfmEnabled ? (cache.linkedUsers ?? 0) : 0, ping: lastPing ?? 0, + gatewayPing: readGatewayPing(this.client), }; const stillPending = []; diff --git a/commands/support.mjs b/commands/support.mjs index 3f503e3..d501a23 100644 --- a/commands/support.mjs +++ b/commands/support.mjs @@ -3,9 +3,9 @@ * @description Displays a link and invitation to the bot's support server. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; /** @type {CommandBuilder} @description Command definition for the support command. */ export const command = new CommandBuilder() diff --git a/commands/test.mjs b/commands/test.mjs index 54de6e9..e065c28 100644 --- a/commands/test.mjs +++ b/commands/test.mjs @@ -3,10 +3,10 @@ * @description Owner-only diagnostic command to display voice channel user counts. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; -import { logger } from "../src/constants/Logger.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; +import { logger } from "../src/core/Logger.mjs"; /** @type {CommandBuilder} @description Command definition for the test command (owner-only). */ export const command = new CommandBuilder() diff --git a/commands/thumbnail.mjs b/commands/thumbnail.mjs index 12d31fe..8da5f52 100644 --- a/commands/thumbnail.mjs +++ b/commands/thumbnail.mjs @@ -3,9 +3,9 @@ * @description Display the thumbnail artwork of the currently playing track. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; /** @type {CommandBuilder} @description Command definition for the thumbnail command. */ export const command = new CommandBuilder() diff --git a/commands/trackopt.mjs b/commands/trackopt.mjs index 966bca5..7637fb0 100644 --- a/commands/trackopt.mjs +++ b/commands/trackopt.mjs @@ -3,12 +3,12 @@ * @description Set custom start/end times for tracks with named alias support. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; -import { Utils } from "../src/Utils.mjs"; -import { logger } from "../src/constants/Logger.mjs"; -import { ERROR_COLOR } from "../src/constants/UI.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; +import { Utils } from "../src/utils/Utils.mjs"; +import { logger } from "../src/core/Logger.mjs"; +import { ERROR_COLOR } from "../src/utils/UI.mjs"; /** @private @type {string} The default alias name for non-named track options. */ const DEFAULT_ALIAS = "default"; diff --git a/commands/volume.mjs b/commands/volume.mjs index 9d22c01..bfc6807 100644 --- a/commands/volume.mjs +++ b/commands/volume.mjs @@ -3,10 +3,10 @@ * @description Get or change the playback volume for the current voice channel. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; -import { MAX_VOLUME } from "../src/constants/UI.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; +import { MAX_VOLUME } from "../src/utils/UI.mjs"; /** diff --git a/commands/volumedefault.mjs b/commands/volumedefault.mjs index 62f5deb..5cbc550 100644 --- a/commands/volumedefault.mjs +++ b/commands/volumedefault.mjs @@ -3,11 +3,11 @@ * @description View or set the server default volume. Requires Manage Server permission to set. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; import { PermissionFlags } from "@fluxerjs/core"; -import { MAX_VOLUME } from "../src/constants/UI.mjs"; +import { MAX_VOLUME } from "../src/utils/UI.mjs"; /** @type {CommandBuilder} @description Command definition for the volumedefault command. */ export const command = new CommandBuilder() diff --git a/commands/vote.mjs b/commands/vote.mjs index 7bf081f..8d11320 100644 --- a/commands/vote.mjs +++ b/commands/vote.mjs @@ -3,13 +3,13 @@ * @description View voting info, check voters, or browse voter lists for a server/bot on FluxerList. */ -import { CommandBuilder } from "../src/CommandHandler.mjs"; +import { CommandBuilder } from "../src/commands/index.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "../src/MessageHandler.mjs"; -import { Utils } from "../src/Utils.mjs"; -import { FLUXERLIST, buildVoteLink } from "../src/constants/API.mjs"; -import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/constants/UI.mjs"; -import { logger } from "../src/constants/Logger.mjs"; +import { getGlobalColor } from "../src/ui/index.mjs"; +import { Utils } from "../src/utils/Utils.mjs"; +import { FLUXERLIST, buildVoteLink } from "../src/utils/API.mjs"; +import { ERROR_COLOR, EMOJI_REMOVE_TIMEOUT } from "../src/utils/UI.mjs"; +import { logger } from "../src/core/Logger.mjs"; /** @type {CommandBuilder} @description Command definition for the vote command. */ export const command = new CommandBuilder() diff --git a/config_example.json b/config_example.json index fa44e00..1c65095 100644 --- a/config_example.json +++ b/config_example.json @@ -62,7 +62,7 @@ "dashboard": { "enabled": false, "redis": { - "url": "redis://localhost:6379" + "url": "redis://127.0.0.1:6379" }, "Comment": "Optional dashboard backend. When enabled, the bot speaks Redis RPC (request/response/info channels) with an external web frontend. Login codes are verified (bcrypt) from the MySQL login_codes table. Keep Redis network-isolated — the RPC channel has no shared secret." }, @@ -116,5 +116,13 @@ "searchSessionTimeout": 30000, "playerSessionTimeout": 300000, "intentionalLeaveTTL": 8000 + }, + "sharding-Comment": "Optional process-level sharding (@fluxerjs/sharding 3.0, beta). Only read by 'node shard.mjs' / 'npm run shard' — plain 'npm start' ignores this block entirely. totalShards: total gateway shards (use an explicit number, never 'auto'); shardsPerProcess: how many shards each child process runs; respawn: restart dead children; spawnTimeout: ms to wait for a child's ready IPC; spawnDelay: ms between successive spawns. The FLUXER_TOTAL_SHARDS / FLUXER_SHARDS_PER_PROCESS env vars override the first two (handy for Docker). Sharding only matters at ~2500+ guilds; leave at defaults otherwise. Caveats: DMs only reach shard 0, and the dashboard is single-process-first.", + "sharding": { + "totalShards": 1, + "shardsPerProcess": 1, + "respawn": true, + "spawnTimeout": 30000, + "spawnDelay": 5000 } } diff --git a/docker/Dockerfile b/docker/Dockerfile index dafab17..a90ba88 100644 --- a/docker/Dockerfile +++ b/docker/Dockerfile @@ -36,7 +36,7 @@ USER remix EXPOSE 80 HEALTHCHECK --interval=30s --timeout=10s --start-period=60s --retries=3 \ - CMD pgrep -f "node index.mjs" >/dev/null 2>&1 || exit 1 + CMD pgrep -f "node .*index.mjs" >/dev/null 2>&1 || pgrep -f "node .*shard.mjs" >/dev/null 2>&1 || exit 1 ENTRYPOINT ["/usr/bin/tini", "--", "/app/docker/docker-entrypoint.sh"] diff --git a/docker/docker-entrypoint.sh b/docker/docker-entrypoint.sh index bfcac6b..b524942 100644 --- a/docker/docker-entrypoint.sh +++ b/docker/docker-entrypoint.sh @@ -21,4 +21,8 @@ if [ "$1" = "node" ] && [ "$2" = "index.mjs" ]; then echo "[Docker] Starting Remix bot..." fi +if [ "$1" = "node" ] && [ "$2" = "shard.mjs" ]; then + echo "[Docker] Starting Remix bot (sharded supervisor)..." +fi + exec "$@" diff --git a/index.mjs b/index.mjs index f0e65fe..c8ec63c 100644 --- a/index.mjs +++ b/index.mjs @@ -1,1035 +1,18 @@ /** * @module index - * @description Entry point for the Fluxer music bot. Creates the {@link Remix} instance, - * sets up process-level error handlers, and registers signal-based graceful shutdown. + * @description Entry point for the Remix music bot. Creates the {@link Remix} + * instance, sets up process-level error handlers, and registers signal-based + * graceful shutdown. All boot logic lives in src/core/Bot.mjs. */ -import * as fs from "fs"; -import path from "path"; -import { initLogger, logger, _wsErrorCooldown } from "./src/constants/Logger.mjs"; -import { Client, Events, EmbedBuilder } from "@fluxerjs/core"; -import { get247ChannelMode, remove247ChannelMode } from "./src/constants/Helpers247.mjs"; -import { CommandHandler, CommandLoader, PrefixManager } from "./src/CommandHandler.mjs"; -import { MessageHandler, PageBuilder, HelpCommand, setGlobalColor, getGlobalColor } from "./src/MessageHandler.mjs"; -import { cleanId } from "./src/Utils.mjs"; -import { RemoteSettingsManager } from "./src/Settings.mjs"; -import { PlayerManager } from "./src/PlayerManager.mjs"; -import childProcess from "node:child_process"; -import { getVoiceManager } from "@fluxerjs/voice"; -import { LavalinkManager } from "./src/LavalinkManager.mjs"; -import { Dashboard } from "./src/dashboard/Dashboard.mjs"; -import { Locale } from "./src/constants/Locale.mjs"; -import { VoiceStateCache } from "./src/constants/VoiceStateCache.mjs"; -import { GatewayHandler } from "./src/GatewayHandler.mjs"; -import { LastFmManager } from "./src/LastFmManager.mjs"; -import { FluxerListManager } from "./src/FluxerListManager.mjs"; -import { TrackOptionsManager } from "./src/TrackOptionsManager.mjs"; - -/** - * Create a Map-like view object that proxies bot voice-state lookups - * through the VoiceStateCache's bot-specific methods. - * @param {object} voiceCache - The {@link VoiceStateCache} instance. - * @returns {Map} A Map-like object with `size`, `get`, `set`, `has`, `delete`, - * `forEach`, and iterator methods backed by the voice cache. - */ -function createBotView(voiceCache) { - return { - get size() { return voiceCache.botLocations.size; }, - get(key) { return voiceCache.botLocations.get(key); }, - set(key, val) { voiceCache.setBotUser(key, val); }, - has(key) { return voiceCache.botLocations.has(key); }, - delete(key) { voiceCache.deleteBotUser(key); }, - forEach(fn) { for (const [k, v] of voiceCache.iterateBotUsers()) fn(v, k, this); }, - *[Symbol.iterator]() { yield* voiceCache.iterateBotUsers(); }, - *entries() { yield* voiceCache.iterateBotUsers(); }, - *keys() { for (const [k] of voiceCache.iterateBotUsers()) yield k; }, - *values() { for (const [, v] of voiceCache.iterateBotUsers()) yield v; }, - get observedVoiceBotsSize() { return voiceCache.botLocations.size; }, - }; -} - - -/** - * @class - * @description Main bot class. Orchestrates client, settings, players, lavalink, - * gateway events, commands, and 24/7 voice channel management. - */ -export class Remix { - /** - * Bootstrap the entire bot: load config, create Discord client, initialise - * settings/commands/players/dashboard, set up event handlers, load modules, - * and log in to Discord. - */ - constructor() { - let config; - try { - config = JSON.parse(fs.readFileSync("config.json", "utf8")); - } catch (e) { - const reason = e.code === "ENOENT" - ? "config.json not found. Copy config_example.json → config.json and fill in your values." - : `config.json is malformed JSON: ${e.message}`; - console.error(`[Startup] FATAL: ${reason}`); - process.exit(1); - } - const REQUIRED_KEYS = ["token", "mysql"]; - for (const key of REQUIRED_KEYS) { - if (config[key] == null) { - console.error(`[Startup] FATAL: config.json is missing required key "${key}".`); - process.exit(1); - } - } - this.config = config; - - setGlobalColor(config.embedColor); - - this.locale = new Locale(typeof config.prefix === "string" && config.prefix ? config.prefix : "%"); - this.locale.load(); - - this.dashboard = new Dashboard(this, { - enabled: config.dashboard?.enabled, - redis: config.dashboard?.redis, - mysql: config.mysql, - }); - - const presenceContents = config.presenceContents ?? []; - const presenceInterval = config.presenceInterval ?? 30_000; - - const buildRuntimePresence = (entry) => { - const isObj = typeof entry === "object" && entry !== null; - const customStatus = {}; - if (isObj) { - if (entry.text) customStatus.text = entry.text; - if (entry.emoji_name) customStatus.emojiName = entry.emoji_name; - if (entry.emoji_id) customStatus.emojiId = entry.emoji_id; - } else { - customStatus.text = String(entry); - } - - const update = { status: "online", afk: false, customStatus }; - - if (isObj && entry.activity) { - update.activities = [{ - name: entry.activity.name ?? "music", - type: entry.activity.type ?? 0, - url: entry.activity.url ?? undefined, - }]; - } - - return update; - }; - let presenceRotationIndex = presenceContents.length > 1 ? 1 : 0; - let presenceRotationStarted = false; - let wsHandlerRearmStarted = false; - - const timers = config.timers ?? {}; - this.T = { - aloneCheckInterval: timers.aloneCheckInterval ?? 60_000, - aloneCheckDebounce: timers.aloneCheckDebounce ?? 500, - rejoin247Delay: timers.rejoin247Delay ?? 3_000, - leave247RejoinDelay: timers.leave247RejoinDelay ?? 5_000, - intentionalLeaveTTL: timers.intentionalLeaveTTL ?? 10_000, - }; - - const client = new Client({ - suppressIntentWarning: true, - waitForGuilds: true, - cache: { guilds: false, channels: false, users: false, members: false }, - ...config["fluxer.js"], - presence: (() => { - if (presenceContents.length === 0) return undefined; - const entry = presenceContents[0]; - const isObj = typeof entry === "object" && entry !== null; - - const custom_status = {}; - if (isObj) { - if (entry.text) custom_status.text = entry.text; - if (entry.emoji_name) custom_status.emoji_name = entry.emoji_name; - if (entry.emoji_id) custom_status.emoji_id = entry.emoji_id; - } else { - custom_status.text = String(entry); - } - - const p = { - status: "online", - mobile: false, - afk: false, - custom_status, - }; - - if (isObj && entry.activity) { - p.activities = [{ - name: entry.activity.name ?? "music", - type: entry.activity.type ?? 0, - url: entry.activity.url ?? undefined, - }]; - } - - return p; - })(), - }); - - client.setMaxListeners(50); - this.client = client; - - try { - getVoiceManager(client); - logger.player("[Startup] VoiceManager initialized before login."); - } catch (e) { - logger.warn("[Startup] VoiceManager pre-login init failed:", e.message); - } - - const messages = new MessageHandler(this.client); - this.messages = messages; - - const settings = new RemoteSettingsManager(config.mysql, "./storage/defaults.json"); - this.settingsMgr = settings; - - const configPrefix = config.prefix ?? null; - if (configPrefix && settings.defaults) { - settings.defaults.prefix = configPrefix; - } - - this.locale.bind(this.settingsMgr); - - const commands = new CommandHandler(messages, configPrefix); - this.handler = commands; - - const prefixMgr = new PrefixManager(settings, configPrefix); - commands.setPrefixManager(prefixMgr); - commands.setLocale(this.locale); - messages.setLocale(this.locale); - this.locale.setPrefixResolver((guildId) => commands.getPrefix(guildId)); - - new HelpCommand(commands, messages, (msg) => this.getSettings(msg)).register(); - - commands.onPing = (msg) => { - msg.replyEmbed( - this.handler.format( - "My prefix in this server is `$prefix`\n\nRun `$prefix$helpCmd` to get started!", - msg.message.guildId - ), - false, - { - icon_url: msg.channel.channel.guild?.icon - ? `https://cdn.fluxer.app/icons/${msg.channel.channel.guild.id}/${msg.channel.channel.guild.icon}.webp` - : null, - title: msg.channel.channel.guild?.name ?? null, - } - ); - }; - commands.owners = config.owners ?? []; - - this.lavalink = null; - let lavalinkInitialised = false; - - this.voiceCache = new VoiceStateCache({ maxUsers: 50_000, maxBots: 10_000 }); - - this.observedVoiceUsers = this.voiceCache; - this.observedVoiceBots = createBotView(this.voiceCache); - - this._announcementChannelCache = new Map(); - this._announcementChannelTTL = 5 * 60 * 1000; - setInterval(() => { - const now = Date.now(); - for (const [k, v] of this._announcementChannelCache) { - if (v.timestamp && now - v.timestamp > this._announcementChannelTTL) this._announcementChannelCache.delete(k); - } - }, 60_000); - this.intentionalLeaves = new Map(); - - this.gatewayHandler = new GatewayHandler(this); - - this.gatewayHandler.setupEventHandlers(); - - this.lastfm = new LastFmManager(config.lastfm, config.mysql); - - this.fluxerlist = new FluxerListManager(config.fluxerlist); - - this.trackOptions = new TrackOptionsManager(config.mysql); - - settings.on("ready", () => { - initLogger(config); - logger.settings("[settings] Loaded from DB."); - for (const [guildId, serverSettings] of settings.guilds) { - const val = serverSettings.get("stay_247"); - if (!val || val === "none") continue; - const rawArr = Array.isArray(val) ? val : [val]; - const cleaned = rawArr - .map(id => cleanId(id)) - .filter(id => id.length >= 15 && id.length <= 22); - - if (cleaned.length > 1) { - // Only 1 channel per guild supported. Keep first, drop the rest. - serverSettings.set("stay_247", cleaned.slice(0, 1)); - logger.settings( - `[settings] Trimmed stay_247 for guild ${guildId}: had ${cleaned.length} channels, kept first 1.` - ); - continue; - } - - const needsSave = JSON.stringify(cleaned) !== JSON.stringify(val); - if (needsSave || !Array.isArray(val)) { - const newVal = cleaned.length > 0 ? cleaned : "none"; - serverSettings.set("stay_247", newVal); - logger.settings( - `[settings] Cleaned stay_247 for guild ${guildId}: ${JSON.stringify(val)} → ${JSON.stringify(newVal)}` - ); - } - } - - }); - - client.on(Events.Ready, async () => { - try { - logger.player("Logged in as " + (client.user?.username ?? "bot")); - - this._attachWsErrorHandlers(); - - if (!wsHandlerRearmStarted) { - wsHandlerRearmStarted = true; - setInterval(() => { - this._attachWsErrorHandlers(); - this.gatewayHandler.attachRawListener(); - }, 5_000).unref?.(); - } - - const botId = client.user?.id ?? "0"; - - await this.settingsMgr.setBotId(botId); - await this.lastfm.setBotId(botId); - this.dashboard.setBotId(botId); - this.trackOptions.setBotId(botId); - - if (!lavalinkInitialised) { - lavalinkInitialised = true; - this.lavalink = new LavalinkManager(config.nodelink ?? {}, client, { id: botId, username: client.user?.username ?? "bot" }); - this.lavalink.on("ready", () => { - logger.lavalink("[Lavalink] Session ready"); - }); - await this.lavalink.init(); - this.playerContext.lavalink = this.lavalink; - } - - this.gatewayHandler.onReady(); - - if (!presenceRotationStarted && presenceContents.length > 1) { - presenceRotationStarted = true; - setInterval(() => { - try { - const entry = presenceContents[presenceRotationIndex % presenceContents.length]; - client.user?.setPresence(buildRuntimePresence(entry)); - presenceRotationIndex = (presenceRotationIndex + 1) % presenceContents.length; - } catch (e) { - logger.warn("[Presence] Rotation update failed:", e?.message); - } - }, presenceInterval).unref?.(); - } - } catch (e) { - logger.error("[Ready] Fatal error in Ready handler:", e); - } - }); - - client._remix = this; - - this.playerContext = { - client: this.client, - config, - lavalink: null, - }; - this.players = new PlayerManager(settings, commands, { - config, - player: this.playerContext, - dashboard: this.dashboard, - locale: this.locale, - timers: this.T, - trackOptions: this.trackOptions, - }); - this.players.observedVoiceUsers = this.observedVoiceUsers; - this.players.voiceCache = this.voiceCache; - this.players._lastfm = this.lastfm; - - const ALONE_CHECK_INTERVAL = this.T.aloneCheckInterval; - setInterval(() => { - if (this.players.playerMap.size === 0) return; - - for (const [mapKey, player] of this.players.playerMap) { - let channelId; - try { - if (player._destroyed || player._isJoining) continue; - - const guildId = player._guildId; - if (!guildId) continue; - - channelId = player._channelId ?? mapKey; - const cleanChanId = cleanId(channelId); - if (!cleanChanId) continue; - - const cleanGuildId = cleanId(guildId); - - if (player._is247Enabled()) continue; - - if (!player.connection) continue; - - let hasHuman = this.voiceCache.hasHumansInChannel(cleanGuildId, cleanChanId); - - if (!hasHuman) { - try { - const guild = this.client?.guilds?.get?.(cleanGuildId); - const voiceStates = guild?.voice_states ?? guild?.voiceStates; - if (voiceStates) { - const entries = Array.isArray(voiceStates) - ? voiceStates - : typeof voiceStates.values === "function" - ? [...voiceStates.values()] - : Object.values(voiceStates); - for (const state of entries) { - const stateChannel = cleanId(state?.channelId ?? state?.channel_id); - if (stateChannel === cleanChanId) { - const stateUserId = state?.userId ?? state?.user_id ?? state?.id; - const member = guild?.members?.get?.(stateUserId); - const isBot = member?.user?.bot ?? state?.member?.user?.bot ?? false; - if (!isBot) { - hasHuman = true; - break; - } - } - } - } - } catch(e) { logger.warn("[AloneCheck] Voice state check error:", e?.message); } - } - - if (!hasHuman) { - try { - const room = player.connection?.room; - if (room?.isConnected && room.remoteParticipants && room.remoteParticipants.size > 0) { - hasHuman = true; - } - } catch(e) { logger.warn("[AloneCheck] LiveKit check error:", e?.message); } - } - - if (!hasHuman && !player._paused) { - if (player.queue?.getCurrent() || !player.queue?.isEmpty()) { - player._startInactivityTimer?.(); - } else { - player._stopInactivityTimer?.(); - player.emit("autoleave"); - } - } else if (hasHuman) { - player._stopInactivityTimer?.(); - } - } catch (e) { - logger.warn("[AloneCheck] Error checking channel", channelId, e.message); - } - } - }, ALONE_CHECK_INTERVAL); - - this.players.checkVoiceChannels = async (message) => { - const userId = message?.author?.id ?? message?.message?.author?.id; - const guildId = - message?.channel?.guildId ?? - message?.channel?.guild?.id ?? - message?.channel?.server_id ?? - message?.channel?.serverId ?? - message?.message?.guildId ?? - message?.message?.guild?.id ?? - message?.message?.channel?.guildId ?? - message?.message?.channel?.guild?.id ?? - message?.message?.channel?.server_id ?? - message?.message?.channel?.serverId; - - const _empty = { channelId: null, alreadyInVoice: false, hasHumans: false }; - - if (!userId || !guildId) { - logger.voice(`[checkVC] BAIL — missing userId or guildId`); - return _empty; - } - - const cleanGuild = cleanId(guildId); - - const makeResult = (channelId) => { - const cId = cleanId(channelId); - return { - channelId: cId, - alreadyInVoice: this.players.playerMap.has(cId), - hasHumans: this.voiceCache.hasHumansInChannel(cleanGuild, cId), - }; - }; - - const seedCache = (channelId) => { - if (!this.voiceCache.hasHumanUser(userId, cleanGuild)) { - this.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId, isBot: false }); - } - }; - - logger.voice(`[checkVC] userId=${userId} guildId=${guildId} cleanGuild=${cleanGuild}`); - - const observed = this.voiceCache.getUserLocation(cleanGuild, userId); - if (observed && observed.channelId) { - logger.voice(`[checkVC] HIT voiceCache → ${observed.channelId}`); - return makeResult(observed.channelId); - } - - try { - const vm = getVoiceManager(client); - const channelId = vm?.getVoiceChannelId?.(guildId, userId) ?? vm?.getVoiceChannelId?.(cleanGuild, userId); - logger.voice(`[checkVC] vm.getVoiceChannelId → ${channelId}`); - if (channelId) { - seedCache(channelId); - return makeResult(channelId); - } - } catch (e) { logger.voice(`[checkVC] vm error: ${e.message}`); } - - try { - const guild = client.guilds.get(guildId) ?? client.guilds.get(cleanGuild); - const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null; - if (voiceStates) { - const entries = Array.isArray(voiceStates) - ? voiceStates - : typeof voiceStates.values === "function" - ? [...voiceStates.values()] - : Object.values(voiceStates); - for (const state of entries) { - const sid = state?.userId ?? state?.user_id ?? state?.id; - const sch = state?.channelId ?? state?.channel_id; - if ((sid === userId || sid === cleanId(userId)) && sch) { - logger.voice(`[checkVC] HIT guild.voice_states → ${sch}`); - seedCache(sch); - return makeResult(sch); - } - } - } - } catch (e) { logger.voice(`[checkVC] guild error: ${e.message}`); } - - try { - const loc = this.voiceCache.getHumanUser(userId, cleanGuild); - if (loc && loc.channelId) { - logger.voice(`[checkVC] HIT voiceCache scan → ${loc.channelId}`); - return makeResult(loc.channelId); - } - } catch (e) { logger.voice(`[checkVC] scan error: ${e.message}`); } - - try { - const guild = client.guilds.get(guildId) ?? client.guilds.get(cleanGuild); - if (guild && typeof guild.fetchMember === "function") { - logger.voice(`[checkVC] Trying REST fetchMember fallback for user ${userId}`); - const member = await guild.fetchMember(userId); - const voiceState = member?.voice ?? member?.voiceState ?? null; - const restChannelId = voiceState?.channelId ?? voiceState?.channel_id ?? null; - if (restChannelId) { - logger.voice(`[checkVC] HIT REST member.voice → ${restChannelId}`); - seedCache(restChannelId); - return makeResult(restChannelId); - } - } - } catch (e) { logger.voice(`[checkVC] REST fallback error: ${e.message}`); } - - try { - const guild = client.guilds.get(guildId) ?? client.guilds.get(cleanGuild); - if (guild && typeof client.rest?.get === "function") { - logger.voice(`[checkVC] Trying raw REST /guilds/${cleanGuild}/members/${userId}`); - const memberData = await client.rest.get(`/guilds/${cleanGuild}/members/${userId}`); - const restChannelId = memberData?.voice_state?.channel_id ?? memberData?.channel_id ?? null; - if (restChannelId) { - logger.voice(`[checkVC] HIT raw REST → ${restChannelId}`); - seedCache(restChannelId); - return makeResult(restChannelId); - } - } - } catch (e) { logger.voice(`[checkVC] raw REST error: ${e.message}`); } - - logger.voice(`[checkVC] MISS — returning empty`); - return _empty; - }; - - const __dirname = import.meta.dirname; - try { - this.comHash = childProcess.execSync("git rev-parse --short HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim(); - this.comHashLong = childProcess.execSync("git rev-parse HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim(); - } catch (e) { - logger.warn("[Git] comhash error:", e?.message); - this.comHash = "Newest"; - this.comHashLong = null; - } - - this.comLink = "https://github.com/remix-bot/fluxer/commit/" + (this.comHashLong ?? ""); - - const loader = new CommandLoader(commands, this); - const dir = path.join(__dirname, "commands"); - logger.commands("Started loading commands."); - loader.loadFromDir(dir) - .then(() => logger.commands("Commands loaded.")) - .catch(e => logger.error("Failed to load commands:", e)); - - logger.commands("Loading Modules."); - this.loadedModules = new Map(); - try { - this.modules = JSON.parse(fs.readFileSync("./storage/modules.json")); - } catch (e) { - const reason = e.code === "ENOENT" - ? "storage/modules.json not found." - : `storage/modules.json is malformed JSON: ${e.message}`; - console.error(`[Startup] WARN: ${reason} — starting with no modules.`); - this.modules = []; - } - Promise.allSettled(this.modules.map(async m => { - if (!m.enabled) return; - try { - const exported = await import(m.index); - const ModClass = exported.default; - this.loadedModules.set(m.name, { instance: new ModClass(this), c: ModClass }); - } catch (e) { - logger.error(`[Module] Failed to load "${m.name}":`, e.message); - } - })) - .then(results => { - const succeeded = results.filter(r => r.status === "fulfilled").length; - const failed = results.length - succeeded; - logger.commands(`Modules loaded (${succeeded} succeeded, ${failed} failed).`); - }); - - client.login(config.token).catch(e => { - logger.error("[Startup] Login failed:", e.message); - process.exit(1); - }); - } - - /** - * Attach proactive error handlers to WebSocket sockets/shards to prevent - * unhandled crashes from WebSocket transport errors. Re-armed periodically. - * @private - */ - _attachWsErrorHandlers() { - try { - const wsManager = this.client?.ws; - if (!wsManager) return; - - let attachedNew = false; - - const logWsError = (label, err) => { - const now = Date.now(); - if (now - _wsErrorCooldown.lastLogged < _wsErrorCooldown.COOLDOWN_MS) return; - _wsErrorCooldown.lastLogged = now; - logger.warn(`[WS] ${label} transport error (auto-recovering): ${err?.message ?? err}`); - }; - - const attachToSocket = (wsObj, label) => { - if (!wsObj) return; - if (wsObj._fluxerErrorHandled) return; - wsObj._fluxerErrorHandled = true; - attachedNew = true; - - if (typeof wsObj.on === "function") { - wsObj.on("error", (err) => logWsError(label, err)); - } - if (typeof wsObj.addEventListener === "function") { - wsObj.addEventListener("error", (event) => { - if (typeof event.preventDefault === "function") event.preventDefault(); - const err = event?.error ?? event?.message ?? event; - logWsError(label, err); - }); - } - }; - - const attachToShard = (shard, id) => { - if (!shard) return; - if (shard._fluxerErrorHandled) return; - shard._fluxerErrorHandled = true; - attachedNew = true; - shard.on("error", (err) => logWsError(`Shard ${id}`, err)); - if (shard.ws) attachToSocket(shard.ws, `Shard ${id} socket`); - }; - - if (wsManager.shards && typeof wsManager.shards.forEach === "function") { - wsManager.shards.forEach((shard, id) => { - attachToShard(shard, id); - }); - } - - if (wsManager.ws) { - attachToSocket(wsManager.ws, "Gateway"); - } - - if (typeof wsManager.on === "function" && !wsManager._fluxerErrorHandled) { - wsManager._fluxerErrorHandled = true; - attachedNew = true; - wsManager.on("error", ({ shardId, error }) => { - logWsError(`WSManager (shard ${shardId})`, error); - }); - } - - if (typeof wsManager.on === "function" && !wsManager._shardCreateHandled) { - wsManager._shardCreateHandled = true; - attachedNew = true; - wsManager.on("shardCreate", (shard) => { - attachToShard(shard, shard.id ?? "?"); - }); - } - - if (attachedNew) { - logger.player("[WS] Proactive error handlers attached to gateway sockets."); - } - } catch (e) { - logger.warn("[WS] Failed to attach WS error handlers:", e.message); - } - } - - /** - * Mark a channel leave as intentional (user-initiated) to prevent - * the 24/7 auto-rejoin system from rejoining. - * @param {string} channelId - The channel ID. - * @param {number|null} [ttlMs=null] - Time-to-live in ms (default: config.timers.intentionalLeaveTTL or 10s). - */ - markIntentionalLeave(channelId, ttlMs = null) { - const cleanChId = cleanId(channelId); - if (!cleanChId) return; - if (ttlMs === null) ttlMs = this.config?.timers?.intentionalLeaveTTL ?? 10_000; - const existing = this.intentionalLeaves.get(cleanChId); - if (existing) clearTimeout(existing); - this.intentionalLeaves.set(cleanChId, setTimeout(() => { - this.intentionalLeaves.delete(cleanChId); - }, ttlMs)); - } - - /** - * Spawn a new Player for a channel. Used by 24/7 boot recovery and enable247. - * Guards against duplicate players, missing channels, and pending joins. - * @param {string} guildId - The guild ID. - * @param {string} channelId - The target voice channel ID. - * @returns {Promise} The spawned and connected player. - * @throws {Error} If channel not found, not a voice channel, or join fails. - */ - async _spawnPlayer(guildId, channelId) { - const cleanGuildId = cleanId(guildId); - const cleanChannelId = cleanId(channelId); - - if (!cleanChannelId) throw new Error("_spawnPlayer: invalid channelId"); - - const existing = this.players.playerMap.get(cleanChannelId) - ?? this.players.getPlayerByGuildAndChannel(cleanGuildId, cleanChannelId); - if (existing) return existing; - - if (!this.lavalink) throw new Error("Audio node not ready yet — try again in a moment"); - - const channel = this.client?.channels?.get?.(cleanChannelId); - if (!channel) throw new Error("Channel not found"); - if (channel.type !== 2) throw new Error("Not a voice channel"); - - if (this.players._pendingJoins?.has?.(cleanChannelId)) { - throw new Error("Join already in progress for this channel"); - } - - const Player = (await import("./src/Player.mjs")).default; - - const player = new Player(this.config.token, { - client: this.client, - config: this.config, - lavalink: this.lavalink ?? null, - settingsMgr: this.settingsMgr ?? this.settings ?? null, - getPrefix: (guildId) => this.handler.getPrefix(guildId), - observedVoiceUsers: this.observedVoiceUsers ?? null, - voiceCache: this.voiceCache ?? null, - locale: this.locale ?? null, - trackOptions: this.trackOptions ?? null, - }); - - player._home247Channel = cleanChannelId; - - this.players.setupEvents(player, { - channelId: cleanChannelId, - guildId: cleanGuildId, - }); - - player.on("autoleave", () => { - const mode = player._get247Mode(); - if (mode === "on") { - logger.inactivity(`[_spawnPlayer] autoleave suppressed for 24/7 channel ${cleanChannelId} (guild ${cleanGuildId})`); - return; - } - if (player._hasHumansInChannel()) { - logger.inactivity(`[_spawnPlayer] autoleave suppressed — humans in channel ${cleanChannelId}`); - return; - } - if (player.queue?.getCurrent() || !player.queue?.isEmpty()) { - logger.inactivity(`[_spawnPlayer] autoleave suppressed — queue has songs in channel ${cleanChannelId}`); - return; - } - - const activeChId = cleanId(player._channelId ?? cleanChannelId) || cleanChannelId; - const homeChId = cleanId(player._home247Channel ?? activeChId) || activeChId; - this.players.playerMap.delete(activeChId); - this.players._unindexPlayer?.(cleanGuildId, activeChId); - const pendingScrobble = this.players._pendingScrobbleTimers?.get(cleanChannelId); - if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this.players._pendingScrobbleTimers.delete(cleanChannelId); } - if (activeChId !== cleanChannelId) this.players.playerMap.delete(cleanChannelId); - if (homeChId !== activeChId) this.players.playerMap.delete(homeChId); - player.destroy(); - }); - - player.on("message", async (m) => { - try { - const serverSettings = this.settingsMgr?.getServer?.(cleanGuildId); - const raw = serverSettings?.get?.("songAnnouncements"); - const disabled = raw === false || raw === 0 || - ["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim()); - if (disabled) return; - - const chMgr = this.client?.channels ?? null; - const canPostById = (c) => !!c?.id && !!chMgr && typeof chMgr.send === "function"; - const asSendable = (c) => { - if (!c || typeof c === "string" || typeof c.send === "function") return c; - if (!canPostById(c)) return c; - const target = { id: c.id, type: c.type }; - target.isTextBased = () => true; - target.send = (options) => chMgr.send(c.id, options); - return target; - }; - const usable = (c) => !!c && typeof c === "object" && - (typeof c.send === "function" || canPostById(c)); - - const _tc = player.textChannel; - let ch = (_tc && typeof _tc === "object" && _tc.channel && typeof _tc.channel === "object") - ? _tc.channel - : _tc; - if (!usable(ch)) { - const savedAnnChId = serverSettings?.get?.("announcementChannelId"); - if (savedAnnChId) { - ch = this.client?.channels?.get?.(cleanId(savedAnnChId)) ?? null; - } - } - if (!usable(ch)) { - const guild = this.client?.guilds?.get?.(cleanGuildId); - if (guild?.systemChannelId) { - ch = guild.channels?.get?.(guild.systemChannelId) ?? null; - } - } - if (!usable(ch)) { - const guild = this.client?.guilds?.get?.(cleanGuildId); - if (guild?.channels) { - for (const c of (guild.channels.values?.() ?? [])) { - if (c.isTextBased?.() || c.type === 0 || c.type === "GUILD_TEXT") { - ch = c; - break; - } - } - } - } - if (!usable(ch)) return; - - ch = asSendable(ch); - if (!player.textChannel) player.textChannel = ch; - - const payload = typeof m === "object" && Array.isArray(m.embeds) - ? { ...m, allowedMentions: { parse: [] } } - : { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(m)], allowedMentions: { parse: [] } }; - ch.send(payload).catch(err => { - if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) { - logger.warn(`[_spawnPlayer] Cannot send announcement in channel ${ch.id} — missing permissions`); - } else { - logger.warn(`[_spawnPlayer] Failed to send announcement in channel ${ch.id}:`, err?.message ?? err); - } - }); - } catch(e) { - logger.warn("[Player] Song announcement error:", e?.message); - } - }); - - if (this.players._pendingJoins) { - this.players._pendingJoins.add(cleanChannelId); - } - - try { - await player.join(cleanChannelId); - - this.players.playerMap.set(cleanChannelId, player); - this.players._indexPlayer(cleanGuildId, cleanChannelId); - if (this.players._pendingJoins) { - this.players._pendingJoins.delete(cleanChannelId); - } - - const savedVol = this.settingsMgr?.getServer?.(cleanGuildId)?.get?.("volume"); - if (savedVol !== undefined && savedVol !== null) { - const vol = Number(savedVol); - if (!isNaN(vol)) player.setVolume(vol / 100); - } - - logger.player(`[_spawnPlayer] Spawned player for channel ${cleanChannelId} in guild ${cleanGuildId}`); - return player; - } catch (err) { - if (this.players._pendingJoins) { - this.players._pendingJoins.delete(cleanChannelId); - } - this.players.playerMap.delete(cleanChannelId); - try { player.destroy(); } catch(e) { logger.warn("[_spawnPlayer] Cleanup destroy error:", e?.message); } - logger.warn(`[_spawnPlayer] Failed to spawn player for channel ${cleanChannelId}:`, err.message); - throw err; - } - } - - /** - * Leave a voice channel programmatically. Removes 24/7 if active, - * destroys the player, and optionally sends a confirmation message. - * @param {string} channelId - The channel ID to leave. - * @param {string} guildId - The guild ID. - * @param {object} [message=null] - Optional message for reply confirmation. - * @param {boolean} [force=false] - Whether to force-leave regardless of 24/7 status. - * @returns {Promise} True on success. - */ - async leaveChannel(channelId, guildId, message, force = false) { - const cleanChId = cleanId(channelId); - const cleanGuildId = cleanId(guildId); - const set = this.settingsMgr.getServer(cleanGuildId); - const raw = set?.get("stay_247"); - - const channels = (!raw || raw === "none") - ? new Set() - : Array.isArray(raw) - ? new Set(raw.map(id => cleanId(id)).filter(Boolean)) - : new Set([cleanId(raw)]); - - if (channels.has(cleanChId)) { - channels.delete(cleanChId); - set.set("stay_247", channels.size > 0 ? [...channels] : "none"); - remove247ChannelMode(set, cleanChId, channels); - } - - this.markIntentionalLeave(cleanChId); - - const player = this.players.playerMap.get(cleanChId); - if (player) { - this.players.playerMap.delete(cleanChId); - this.players._unindexPlayer(player._guildId, cleanChId); - const pendingScrobble = this.players._pendingScrobbleTimers?.get(cleanChId); - if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this.players._pendingScrobbleTimers.delete(cleanChId); } - await player.leave().catch(() => {}); - player.destroy(); - } - - if (message) { - const guildIdForLocale = message?.channel?.channel?.guildId ?? message?.guildId ?? cleanGuildId; - message.replyEmbed(this.locale.translate(guildIdForLocale, "responses._common.successfullyLeft")); - } - - return true; - } - - /** - * Get the server settings for the guild associated with a message. - * @param {object} message - The incoming message wrapper. - * @returns {object} The {@link ServerSettings} for the guild, or a fallback. - */ - getSettings(message) { - const guildId = message?.channel?.channel?.guildId ?? message?.guildId ?? null; - return this.settingsMgr.getServer(guildId); - } - - /** - * Shorthand to translate a locale key for the guild of a given message. - * @param {object} message - The message wrapper (used to resolve guild ID). - * @param {string} key - The locale key. - * @param {object} [data={}] - Interpolation data. - * @returns {string} The localised string. - */ - t(message, key, data = {}) { - const guildId = message?.channel?.channel?.guildId - ?? message?.message?.guildId - ?? message?.guildId - ?? null; - return this.locale.translate(guildId, key, data); - } - - /** - * Get or create a player for the given message context. - * Delegates to {@link PlayerManager.getPlayer}. - * @param {object} message - The message wrapper. - * @param {boolean} promptJoin - Whether to prompt the user to join a voice channel. - * @param {boolean} verifyUser - Whether to verify the user is in a voice channel. - * @param {boolean} shouldJoin - Whether to auto-join the voice channel. - * @returns {Promise} The Player instance. - */ - getPlayer(message, promptJoin, verifyUser, shouldJoin) { - return this.players.getPlayer(message, promptJoin, verifyUser, shouldJoin); - } - - /** - * Get all servers the bot and the given user share (i.e. the user is a member). - * Used by the dashboard to determine which servers a user can manage. - * @async - * @param {object} user - The Discord user. - * @returns {Promise>} Array of server summary objects with channels. - */ - async getSharedServers(user) { - if (!user) return []; - - const shared = []; - - for (const guild of this.client.guilds?.values?.() ?? []) { - let isMember = false; - - if (guild.members?.has?.(user.id)) { - isMember = true; - } - - if (!isMember) { - const cleanGuildId = cleanId(guild.id); - const userLoc = this.voiceCache.getUserLocation(cleanGuildId, user.id); - if (userLoc) isMember = true; - } - - if (!isMember) { - try { - const member = await guild.members.fetch(user.id).catch(() => null); - if (member) isMember = true; - } catch (e) { logger.warn(`[getSharedServers] Member fetch error for ${user.id}:`, e?.message); } - } - - if (!isMember) continue; - - const guildChannels = guild.channels - ? [...guild.channels.values()] - : []; - const allChannels = guildChannels - .map(c => Dashboard.convertChannel(c)) - .filter(c => !c.isCategory); - const channelIds = guildChannels.map(c => c.id); - - shared.push({ - name: guild.name, - id: guild.id, - icon: guild.icon - ? `https://cdn.fluxer.app/icons/${guild.id}/${guild.icon}.webp` - : null, - description: guild.description ?? null, - ownerId: guild.ownerId ?? null, - channels: allChannels, - channelIds: channelIds, - voiceChannels: allChannels.filter(c => c.isVoice), - }); - } - - return shared; - } - - /** - * Create and attach a paginated message to the given message. - * @param {string} form - The form/locale key for the page title. - * @param {string} content - The full content to paginate. - * @param {object} msg - The message wrapper. - * @param {number} linesPerPage - Maximum lines per page. - */ - pagination(form, content, msg, linesPerPage) { - this.messages.initPagination( - new PageBuilder(content).setForm(form).setMaxLines(linesPerPage), - msg - ); - } - -} +import { logger } from "./src/core/Logger.mjs"; +import Remix from "./src/core/Bot.mjs"; const remix = new Remix(); /** - * Check whether an error is a known-ignorable WebSocket transport crash - * from the fluxer.js ws or undici internals. + * Check whether an error is a known-ignorable WebSocket transport crash from + * the fluxer.js ws or undici internals. * @param {Error} err - The error to check. * @returns {boolean} True if the error should be silently recovered. */ @@ -1071,6 +54,7 @@ process.on("unhandledRejection", (reason, p) => { logger.error("[Error_Handling] Unhandled Rejection/Catch"); logger.error("Reason:", reason, p); }); + process.on("uncaughtException", (err, origin) => { if (isIgnorableWsCrash(err)) { const now = Date.now(); @@ -1100,6 +84,7 @@ process.on("uncaughtException", (err, origin) => { logger.error("Error:", err, origin); process.exit(1); }); + process.on("uncaughtExceptionMonitor", (err, origin) => { if (isIgnorableWsCrash(err)) return; if (isBenignAudioStopRace(err)) return; @@ -1109,8 +94,8 @@ process.on("uncaughtExceptionMonitor", (err, origin) => { }); /** - * Graceful shutdown handler: destroys all active players, closes - * Lavalink, Redis, and Dashboard DB connections, then exits. + * Graceful shutdown handler: destroys all active players, closes Lavalink, + * Redis, and Dashboard DB connections, then exits. * @async * @returns {Promise} */ diff --git a/package-lock.json b/package-lock.json deleted file mode 100644 index 1a7494f..0000000 --- a/package-lock.json +++ /dev/null @@ -1,1741 +0,0 @@ -{ - "name": "fluxer-main", - "lockfileVersion": 3, - "requires": true, - "packages": { - "": { - "dependencies": { - "@fluxerjs/core": "^2.2.0", - "@fluxerjs/util": "^2.2.0", - "@fluxerjs/voice": "^2.2.0", - "bcryptjs": "^3.0.3", - "ffprobe-static": "^3.1.0", - "lavalink-client": "^2.10.3", - "mysql2": "^3.9.0", - "opusscript": "^0.0.8", - "prism-media": "^1.3.5", - "redis": "^5.12.1" - }, - "engines": { - "node": ">=22.13.0" - }, - "optionalDependencies": { - "@discordjs/opus": "^0.10.0" - } - }, - "node_modules/@bufbuild/protobuf": { - "version": "1.10.1", - "resolved": "https://registry.npmjs.org/@bufbuild/protobuf/-/protobuf-1.10.1.tgz", - "integrity": "sha512-wJ8ReQbHxsAfXhrf9ixl0aYbZorRuOWpBNzm8pL8ftmSxQx/wnJD5Eg861NwJU/czy2VXFIebCeZnZrI9rktIQ==", - "license": "(Apache-2.0 AND BSD-3-Clause)" - }, - "node_modules/@datastructures-js/deque": { - "version": "1.0.8", - "resolved": "https://registry.npmjs.org/@datastructures-js/deque/-/deque-1.0.8.tgz", - "integrity": "sha512-PSBhJ2/SmeRPRHuBv7i/fHWIdSC3JTyq56qb+Rq0wjOagi0/fdV5/B/3Md5zFZus/W6OkSPMaxMKKMNMrSmubg==", - "license": "MIT" - }, - "node_modules/@discordjs/node-pre-gyp": { - "version": "0.4.5", - "resolved": "https://registry.npmjs.org/@discordjs/node-pre-gyp/-/node-pre-gyp-0.4.5.tgz", - "integrity": "sha512-YJOVVZ545x24mHzANfYoy0BJX5PDyeZlpiJjDkUBM/V/Ao7TFX9lcUvCN4nr0tbr5ubeaXxtEBILUrHtTphVeQ==", - "license": "BSD-3-Clause", - "optional": true, - "dependencies": { - "detect-libc": "^2.0.0", - "https-proxy-agent": "^5.0.0", - "make-dir": "^3.1.0", - "node-fetch": "^2.6.7", - "nopt": "^5.0.0", - "npmlog": "^5.0.1", - "rimraf": "^3.0.2", - "semver": "^7.3.5", - "tar": "^6.1.11" - }, - "bin": { - "node-pre-gyp": "bin/node-pre-gyp" - } - }, - "node_modules/@discordjs/opus": { - "version": "0.10.0", - "resolved": "https://registry.npmjs.org/@discordjs/opus/-/opus-0.10.0.tgz", - "integrity": "sha512-HHEnSNrSPmFEyndRdQBJN2YE6egyXS9JUnJWyP6jficK0Y+qKMEZXyYTgmzpjrxXP1exM/hKaNP7BRBUEWkU5w==", - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "dependencies": { - "@discordjs/node-pre-gyp": "^0.4.5", - "node-addon-api": "^8.1.0" - }, - "engines": { - "node": ">=12.0.0" - } - }, - "node_modules/@discordjs/opus/node_modules/node-addon-api": { - "version": "8.9.2", - "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-8.9.2.tgz", - "integrity": "sha512-VijLXbi3UACN69I0JVXJsX4tjACjNoQDgv2gTF6sx2wWEi8tkSg2eX8p5gSIFi8z2+DL3oHmY6OyKce38SDolg==", - "license": "MIT", - "optional": true, - "engines": { - "node": "^18 || ^20 || >= 21" - } - }, - "node_modules/@eshaz/web-worker": { - "version": "1.2.2", - "resolved": "https://registry.npmjs.org/@eshaz/web-worker/-/web-worker-1.2.2.tgz", - "integrity": "sha512-WxXiHFmD9u/owrzempiDlBB1ZYqiLnm9s6aPc8AlFQalq2tKmqdmMr9GXOupDgzXtqnBipj8Un0gkIm7Sjf8mw==", - "license": "Apache-2.0" - }, - "node_modules/@fluxerjs/builders": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@fluxerjs/builders/-/builders-2.2.0.tgz", - "integrity": "sha512-ghRxVx0vHGY4PxS38C7suYQXfSPGb/d3jb8qzGqa2bdW6MyfoSfBXYHSbpxvEKeGypeccr2xYW0Q9bVC+5DVEA==", - "license": "Apache-2.0", - "dependencies": { - "@fluxerjs/types": "2.2.0", - "@fluxerjs/util": "2.2.0" - }, - "engines": { - "node": ">=22.13.0" - } - }, - "node_modules/@fluxerjs/collection": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@fluxerjs/collection/-/collection-2.2.0.tgz", - "integrity": "sha512-EwTFm8TOaRf4DhxXM1gV+FocsXcsjARGazsnAANy4U3G1IzzzaGA7vAmoDlYQLx6Aoi3IVyQb1ueJGK1w2FW0Q==", - "license": "Apache-2.0", - "engines": { - "node": ">=22.13.0" - } - }, - "node_modules/@fluxerjs/core": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@fluxerjs/core/-/core-2.2.0.tgz", - "integrity": "sha512-pgIqqu4mwa9AgFKDsWN0scddEcxG79+z91d8hlfOqf1rMCyrw6rFlmP53aPKoEw/udunRy+T0z3ckC4M9lVYdw==", - "license": "Apache-2.0", - "dependencies": { - "@fluxerjs/builders": "2.2.0", - "@fluxerjs/collection": "2.2.0", - "@fluxerjs/rest": "2.2.0", - "@fluxerjs/types": "2.2.0", - "@fluxerjs/util": "2.2.0", - "@fluxerjs/ws": "2.2.0" - }, - "engines": { - "node": ">=22.13.0" - } - }, - "node_modules/@fluxerjs/rest": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@fluxerjs/rest/-/rest-2.2.0.tgz", - "integrity": "sha512-41XQRLvrSjwYMnFJe/8usigLC4PtjB9aeGgmKN5x+GUgJzRswiNUfrHXpiq7uqvTdGSsI+tbghJatzPRTg4B9w==", - "license": "Apache-2.0", - "dependencies": { - "@fluxerjs/types": "2.2.0", - "undici": "^7.28.0" - }, - "engines": { - "node": ">=22.13.0" - } - }, - "node_modules/@fluxerjs/types": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@fluxerjs/types/-/types-2.2.0.tgz", - "integrity": "sha512-5ZhG/fQYphmngnHvS5FxJZUl5uBGPuK+JV+s9M/iPH+vYToHRJ1tkk55Sm8fbkqr9lvXEkmENvT5soQ2ooAFJQ==", - "license": "Apache-2.0", - "engines": { - "node": ">=22.13.0" - } - }, - "node_modules/@fluxerjs/util": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@fluxerjs/util/-/util-2.2.0.tgz", - "integrity": "sha512-apxwph0w7hBDcnnC7St3/qPCRlKvj2zdj+rNa96JG6BDCHiD3RfLzZrkSTLyVfVKpUjDtuO/6X4T/0cQAhLHcA==", - "license": "Apache-2.0", - "dependencies": { - "@fluxerjs/types": "2.2.0" - }, - "engines": { - "node": ">=22.13.0" - } - }, - "node_modules/@fluxerjs/voice": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@fluxerjs/voice/-/voice-2.2.0.tgz", - "integrity": "sha512-6XsJCEvutixQXu0aB0Wbs63+K4YRCdIGf541QswzA7JR1AYIPKzM1uSHV7SDiAggMURgYQTnhZBgKxp/9eZQ+A==", - "license": "Apache-2.0", - "dependencies": { - "@fluxerjs/collection": "2.2.0", - "@fluxerjs/core": "2.2.0", - "@fluxerjs/types": "2.2.0", - "@fluxerjs/util": "2.2.0", - "@livekit/rtc-node": "^0.13.24", - "mp4box": "^0.5.2", - "opus-decoder": "^0.7.0", - "prism-media": "^1.3.5", - "tweetnacl": "^1.0.3", - "ws": "^8.21.0" - }, - "engines": { - "node": ">=22.13.0" - }, - "optionalDependencies": { - "livekit-server-sdk": "^2.15.0", - "node-webcodecs": "^1.0.0" - } - }, - "node_modules/@fluxerjs/ws": { - "version": "2.2.0", - "resolved": "https://registry.npmjs.org/@fluxerjs/ws/-/ws-2.2.0.tgz", - "integrity": "sha512-WXy67dNALMV60jMaw1TJjziSz7gEK1EO82DtBHinL96tZ78QKz7Qst99wuy1RlR9LvDbN7X7CBlFsgx+Bo6PNw==", - "license": "Apache-2.0", - "dependencies": { - "@fluxerjs/types": "2.2.0", - "@fluxerjs/util": "2.2.0", - "ws": "^8.21.0" - }, - "engines": { - "node": ">=22.13.0" - } - }, - "node_modules/@livekit/mutex": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/@livekit/mutex/-/mutex-1.1.1.tgz", - "integrity": "sha512-EsshAucklmpuUAfkABPxJNhzj9v2sG7JuzFDL4ML1oJQSV14sqrpTYnsaOudMAw9yOaW53NU3QQTlUQoRs4czw==", - "license": "Apache-2.0" - }, - "node_modules/@livekit/protocol": { - "version": "1.48.0", - "resolved": "https://registry.npmjs.org/@livekit/protocol/-/protocol-1.48.0.tgz", - "integrity": "sha512-fYHYgltH6YavAsokl3qsHLkBdQeKCl4UORVTub5crS3t8JtKFZ0uinHDFQ+XXdNKS6Ub9gcOjV+UHcDiqnWXoQ==", - "license": "Apache-2.0", - "optional": true, - "dependencies": { - "@bufbuild/protobuf": "^1.10.0" - } - }, - "node_modules/@livekit/rtc-ffi-bindings": { - "version": "0.12.73", - "resolved": "https://registry.npmjs.org/@livekit/rtc-ffi-bindings/-/rtc-ffi-bindings-0.12.73.tgz", - "integrity": "sha512-ZxkCQlsfTG7Eqi6KBXulEWJBUxeRVRYqCc795CsmKsGfqmBX5gE5CnTiynN8fFdzSGwApaVogeGSB6JszCf/Xw==", - "license": "Apache-2.0", - "dependencies": { - "@bufbuild/protobuf": "^1.10.1" - }, - "engines": { - "node": ">= 18" - }, - "optionalDependencies": { - "@livekit/rtc-ffi-bindings-darwin-arm64": "0.12.73", - "@livekit/rtc-ffi-bindings-darwin-x64": "0.12.73", - "@livekit/rtc-ffi-bindings-linux-arm64-gnu": "0.12.73", - "@livekit/rtc-ffi-bindings-linux-x64-gnu": "0.12.73", - "@livekit/rtc-ffi-bindings-win32-x64-msvc": "0.12.73" - } - }, - "node_modules/@livekit/rtc-ffi-bindings-darwin-arm64": { - "version": "0.12.73", - "resolved": "https://registry.npmjs.org/@livekit/rtc-ffi-bindings-darwin-arm64/-/rtc-ffi-bindings-darwin-arm64-0.12.73.tgz", - "integrity": "sha512-gIGftVyO1Jl266AZPRzoL6dxck969dmIiaut3+D1aCZRkDb/gLz98BEGRfOSU3X0LS4QBkmiaYWsjN9ot/zmwg==", - "cpu": [ - "arm64" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 18" - } - }, - "node_modules/@livekit/rtc-ffi-bindings-darwin-x64": { - "version": "0.12.73", - "resolved": "https://registry.npmjs.org/@livekit/rtc-ffi-bindings-darwin-x64/-/rtc-ffi-bindings-darwin-x64-0.12.73.tgz", - "integrity": "sha512-esPwYCbUnDD/KxBo0YU8awTFglRG7SvOT/sfiP19KChS5SH8TgXc7JwfSvnjRx1PndUqHFzQAbQDcYaeL9PFTg==", - "cpu": [ - "x64" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">= 18" - } - }, - "node_modules/@livekit/rtc-ffi-bindings-linux-arm64-gnu": { - "version": "0.12.73", - "resolved": "https://registry.npmjs.org/@livekit/rtc-ffi-bindings-linux-arm64-gnu/-/rtc-ffi-bindings-linux-arm64-gnu-0.12.73.tgz", - "integrity": "sha512-2YBatXjuaumnaNVqRC63flX5XZTvHcQWRsABw6e2yp+Hlxl3ocjVVyk5PrAsRzCdeyxbHLduqV9ctqGbpTA27Q==", - "cpu": [ - "arm64" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 18" - } - }, - "node_modules/@livekit/rtc-ffi-bindings-linux-x64-gnu": { - "version": "0.12.73", - "resolved": "https://registry.npmjs.org/@livekit/rtc-ffi-bindings-linux-x64-gnu/-/rtc-ffi-bindings-linux-x64-gnu-0.12.73.tgz", - "integrity": "sha512-BrP3IyNkcjldeO+SbnF0hX2mipst8aHiBIiGJcQCd8HEjsaabfkYk4Y5uoNsTVMrUSyrNrJte2itAhuxP9FCSA==", - "cpu": [ - "x64" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">= 18" - } - }, - "node_modules/@livekit/rtc-ffi-bindings-win32-x64-msvc": { - "version": "0.12.73", - "resolved": "https://registry.npmjs.org/@livekit/rtc-ffi-bindings-win32-x64-msvc/-/rtc-ffi-bindings-win32-x64-msvc-0.12.73.tgz", - "integrity": "sha512-2RnKXMTnNfvjJ3kbuhE1jqFNAQNmqSrxy3GlEnByY61tbtY14QPFn8X/0lh+Mjst8pZdfxkXvtbRyPt5KYHvMA==", - "cpu": [ - "x64" - ], - "license": "Apache-2.0", - "optional": true, - "os": [ - "win32" - ], - "engines": { - "node": ">= 18" - } - }, - "node_modules/@livekit/rtc-node": { - "version": "0.13.34", - "resolved": "https://registry.npmjs.org/@livekit/rtc-node/-/rtc-node-0.13.34.tgz", - "integrity": "sha512-22EWklyNUGJ5EamOcC/eUnLy0Gu3SpzxzUkuXCixCequwNDmj8PGjKgtpWThlqTWkzvh9xsAKmQoDWhlXhkrzA==", - "license": "Apache-2.0", - "dependencies": { - "@datastructures-js/deque": "1.0.8", - "@livekit/mutex": "^1.0.0", - "@livekit/rtc-ffi-bindings": "0.12.73", - "@livekit/typed-emitter": "^3.0.0", - "pino": "^9.0.0", - "pino-pretty": "^13.0.0" - }, - "engines": { - "node": ">= 18" - } - }, - "node_modules/@livekit/typed-emitter": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/@livekit/typed-emitter/-/typed-emitter-3.0.0.tgz", - "integrity": "sha512-9bl0k4MgBPZu3Qu3R3xy12rmbW17e3bE9yf4YY85gJIQ3ezLEj/uzpKHWBsLaDoL5Mozz8QCgggwIBudYQWeQg==", - "license": "MIT" - }, - "node_modules/@node-webcodecs/static-darwin-arm64": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/@node-webcodecs/static-darwin-arm64/-/static-darwin-arm64-1.3.0.tgz", - "integrity": "sha512-ukzff4SooS4TyYDlZiOUIV8mi6vIzLjM93PlQgIAfHhj//pocegPvXK6FmUaRc174U5DE/vSkTgpAmuvwkft6Q==", - "cpu": [ - "arm64" - ], - "license": "MIT AND LGPL-2.1-or-later AND BSD-2-Clause AND BSD-3-Clause", - "optional": true, - "os": [ - "darwin" - ], - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@node-webcodecs/static-linux-arm64": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/@node-webcodecs/static-linux-arm64/-/static-linux-arm64-1.3.0.tgz", - "integrity": "sha512-iKFS3d+96Ex5mDcTCAvPaEdrOA6ktLXBfDa8eMkddvX0y19e3jzyYQa0UavM8ykARdftFQyaHjphiVExpG2QEQ==", - "cpu": [ - "arm64" - ], - "license": "MIT AND LGPL-2.1-or-later AND BSD-2-Clause AND BSD-3-Clause", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@node-webcodecs/static-linux-x64": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/@node-webcodecs/static-linux-x64/-/static-linux-x64-1.3.0.tgz", - "integrity": "sha512-aUqz7mL1aQKmcgU0ASFxsYVmOMdg+EydKcYUKwtFb77n5w1E0ojQh/7ggkJpMVQWAevdRGM8rpMy6b//etrWSw==", - "cpu": [ - "x64" - ], - "license": "MIT AND LGPL-2.1-or-later AND BSD-2-Clause AND BSD-3-Clause", - "optional": true, - "os": [ - "linux" - ], - "engines": { - "node": ">=18.0.0" - } - }, - "node_modules/@pinojs/redact": { - "version": "0.4.0", - "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz", - "integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==", - "license": "MIT" - }, - "node_modules/@redis/bloom": { - "version": "5.12.1", - "resolved": "https://registry.npmjs.org/@redis/bloom/-/bloom-5.12.1.tgz", - "integrity": "sha512-PUUfv+ms7jgPSBVoo/DN4AkPHj4D5TZSd6SbJX7egzBplkYUcKmHRE8RKia7UtZ8bSQbLguLvxVO+asKtQfZWA==", - "license": "MIT", - "engines": { - "node": ">= 18.19.0" - }, - "peerDependencies": { - "@redis/client": "^5.12.1" - } - }, - "node_modules/@redis/client": { - "version": "5.12.1", - "resolved": "https://registry.npmjs.org/@redis/client/-/client-5.12.1.tgz", - "integrity": "sha512-7aPGWeqA3uFm43o19umzdl16CEjK/JQGtSXVPevplTaOU3VJA/rseBC1QvYUz9lLDIMBimc4SW/zrW4S89BaCA==", - "license": "MIT", - "dependencies": { - "cluster-key-slot": "1.1.2" - }, - "engines": { - "node": ">= 18.19.0" - }, - "peerDependencies": { - "@node-rs/xxhash": "^1.1.0", - "@opentelemetry/api": ">=1 <2" - }, - "peerDependenciesMeta": { - "@node-rs/xxhash": { - "optional": true - }, - "@opentelemetry/api": { - "optional": true - } - } - }, - "node_modules/@redis/json": { - "version": "5.12.1", - "resolved": "https://registry.npmjs.org/@redis/json/-/json-5.12.1.tgz", - "integrity": "sha512-eOze75esLve4vfqDel7aMX08CNaiLLQS2fV8mpRN9NxPe1rVR4vQyYiW/OgtGUysF6QOr9ANhfxABKNOJfXdKg==", - "license": "MIT", - "engines": { - "node": ">= 18.19.0" - }, - "peerDependencies": { - "@redis/client": "^5.12.1" - } - }, - "node_modules/@redis/search": { - "version": "5.12.1", - "resolved": "https://registry.npmjs.org/@redis/search/-/search-5.12.1.tgz", - "integrity": "sha512-ItlxbxC9cKI6IU1TLWoczwJCRb6TdmkEpWv05UrPawqaAnWGRu3rcIqsc5vN483T2fSociuyV1UkWIL5I4//2w==", - "license": "MIT", - "engines": { - "node": ">= 18.19.0" - }, - "peerDependencies": { - "@redis/client": "^5.12.1" - } - }, - "node_modules/@redis/time-series": { - "version": "5.12.1", - "resolved": "https://registry.npmjs.org/@redis/time-series/-/time-series-5.12.1.tgz", - "integrity": "sha512-c6JL6E3EcZJuNqKFz+KM+l9l5mpcQiKvTwgA3blt5glWJ8hjDk0yeHN3beE/MpqYIQ8UEX44ItQzgkE/gCBELQ==", - "license": "MIT", - "engines": { - "node": ">= 18.19.0" - }, - "peerDependencies": { - "@redis/client": "^5.12.1" - } - }, - "node_modules/@types/node": { - "version": "26.4.0", - "resolved": "https://registry.npmjs.org/@types/node/-/node-26.4.0.tgz", - "integrity": "sha512-faiGnoIrLH/V8cibOMEAZ8pMw6oXqSukl29ra4mN8GdaB2ZewzeaLj+INpV5N+Z1eKWzY+IzaIZH2EIR6YZRNQ==", - "license": "MIT", - "peer": true, - "dependencies": { - "undici-types": "~8.3.0" - } - }, - "node_modules/@wasm-audio-decoders/common": { - "version": "9.0.7", - "resolved": "https://registry.npmjs.org/@wasm-audio-decoders/common/-/common-9.0.7.tgz", - "integrity": "sha512-WRaUuWSKV7pkttBygml/a6dIEpatq2nnZGFIoPTc5yPLkxL6Wk4YaslPM98OPQvWacvNZ+Py9xROGDtrFBDzag==", - "license": "MIT", - "dependencies": { - "@eshaz/web-worker": "1.2.2", - "simple-yenc": "^1.0.4" - } - }, - "node_modules/abbrev": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/abbrev/-/abbrev-1.1.1.tgz", - "integrity": "sha512-nne9/IiQ/hzIhY6pdDnbBtz7DjPTKrY00P/zvPSm5pOFkl6xuGrGnXn/VtTNNfNtAfZ9/1RtehkszU9qcTii0Q==", - "license": "ISC", - "optional": true - }, - "node_modules/agent-base": { - "version": "6.0.2", - "resolved": "https://registry.npmjs.org/agent-base/-/agent-base-6.0.2.tgz", - "integrity": "sha512-RZNwNclF7+MS/8bDg70amg32dyeZGZxiDuQmZxKLAlQjr3jGyLx+4Kkk58UO7D2QdgFIQCovuSuZESne6RG6XQ==", - "license": "MIT", - "optional": true, - "dependencies": { - "debug": "4" - }, - "engines": { - "node": ">= 6.0.0" - } - }, - "node_modules/ansi-regex": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", - "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/aproba": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/aproba/-/aproba-2.1.0.tgz", - "integrity": "sha512-tLIEcj5GuR2RSTnxNKdkK0dJ/GrC7P38sUkiDmDuHfsHmbagTFAxDVIBltoklXEVIQ/f14IL8IMJ5pn9Hez1Ew==", - "license": "ISC", - "optional": true - }, - "node_modules/are-we-there-yet": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/are-we-there-yet/-/are-we-there-yet-2.0.0.tgz", - "integrity": "sha512-Ci/qENmwHnsYo9xKIcUJN5LeDKdJ6R1Z1j9V/J5wyq8nh/mYPEpIKJbBZXtZjG04HiK7zV/p6Vs9952MrMeUIw==", - "deprecated": "This package is no longer supported.", - "license": "ISC", - "optional": true, - "dependencies": { - "delegates": "^1.0.0", - "readable-stream": "^3.6.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/atomic-sleep": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz", - "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==", - "license": "MIT", - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/aws-ssl-profiles": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz", - "integrity": "sha512-NZKeq9AfyQvEeNlN0zSYAaWrmBffJh3IELMZfRpJVWgrpEbtEpnjvzqBPf+mxoI287JohRDoa+/nsfqqiZmF6g==", - "license": "MIT", - "engines": { - "node": ">= 6.0.0" - } - }, - "node_modules/balanced-match": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", - "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==", - "license": "MIT", - "optional": true - }, - "node_modules/bcryptjs": { - "version": "3.0.3", - "resolved": "https://registry.npmjs.org/bcryptjs/-/bcryptjs-3.0.3.tgz", - "integrity": "sha512-GlF5wPWnSa/X5LKM1o0wz0suXIINz1iHRLvTS+sLyi7XPbe5ycmYI3DlZqVGZZtDgl4DmasFg7gOB3JYbphV5g==", - "license": "BSD-3-Clause", - "bin": { - "bcrypt": "bin/bcrypt" - } - }, - "node_modules/brace-expansion": { - "version": "1.1.18", - "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.18.tgz", - "integrity": "sha512-Edep/X9fGqVNmzKBVsDYIOtD+z1tuezV70LBjdCst9Tqu76lsnvRiZ6oTic1n+/BIwX6QDGAO94PN4N2SADvtw==", - "license": "MIT", - "optional": true, - "dependencies": { - "balanced-match": "^1.0.0", - "concat-map": "0.0.1" - } - }, - "node_modules/chownr": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/chownr/-/chownr-2.0.0.tgz", - "integrity": "sha512-bIomtDF5KGpdogkLd9VspvFzk9KfpyyGlS8YFVZl7TGPBHL5snIOnxeshwVgPteQ9b4Eydl+pVbIyE1DcvCWgQ==", - "license": "ISC", - "optional": true, - "engines": { - "node": ">=10" - } - }, - "node_modules/cluster-key-slot": { - "version": "1.1.2", - "resolved": "https://registry.npmjs.org/cluster-key-slot/-/cluster-key-slot-1.1.2.tgz", - "integrity": "sha512-RMr0FhtfXemyinomL4hrWcYJxmX6deFdCxpJzhDttxgO1+bcCnkk+9drydLVDmAMG7NE6aN/fl4F7ucU/90gAA==", - "license": "Apache-2.0", - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/color-support": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/color-support/-/color-support-1.1.3.tgz", - "integrity": "sha512-qiBjkpbMLO/HL68y+lh4q0/O1MZFj2RX6X/KmMa3+gJD3z+WwI1ZzDHysvqHGS3mP6mznPckpXmw1nI9cJjyRg==", - "license": "ISC", - "optional": true, - "bin": { - "color-support": "bin.js" - } - }, - "node_modules/colorette": { - "version": "2.0.20", - "resolved": "https://registry.npmjs.org/colorette/-/colorette-2.0.20.tgz", - "integrity": "sha512-IfEDxwoWIjkeXL1eXcDiow4UbKjhLdq6/EuSVR9GMN7KVH3r9gQ83e73hsz1Nd1T3ijd5xv1wcWRYO+D6kCI2w==", - "license": "MIT" - }, - "node_modules/concat-map": { - "version": "0.0.1", - "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", - "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==", - "license": "MIT", - "optional": true - }, - "node_modules/console-control-strings": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/console-control-strings/-/console-control-strings-1.1.0.tgz", - "integrity": "sha512-ty/fTekppD2fIwRvnZAVdeOiGd1c7YXEixbgJTNzqcxJWKQnjJ/V1bNEEE6hygpM3WjwHFUVK6HTjWSzV4a8sQ==", - "license": "ISC", - "optional": true - }, - "node_modules/dateformat": { - "version": "4.6.3", - "resolved": "https://registry.npmjs.org/dateformat/-/dateformat-4.6.3.tgz", - "integrity": "sha512-2P0p0pFGzHS5EMnhdxQi7aJN+iMheud0UhG4dlE1DLAlvL8JHjJJTX/CSm4JXwV0Ka5nGk3zC5mcb5bUQUxxMA==", - "license": "MIT", - "engines": { - "node": "*" - } - }, - "node_modules/debug": { - "version": "4.4.3", - "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", - "integrity": "sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==", - "license": "MIT", - "optional": true, - "dependencies": { - "ms": "^2.1.3" - }, - "engines": { - "node": ">=6.0" - }, - "peerDependenciesMeta": { - "supports-color": { - "optional": true - } - } - }, - "node_modules/delegates": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/delegates/-/delegates-1.0.0.tgz", - "integrity": "sha512-bd2L678uiWATM6m5Z1VzNCErI3jiGzt6HGY8OVICs40JQq/HALfbyNJmp0UDakEY4pMMaN0Ly5om/B1VI/+xfQ==", - "license": "MIT", - "optional": true - }, - "node_modules/detect-libc": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", - "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", - "license": "Apache-2.0", - "optional": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/emoji-regex": { - "version": "8.0.0", - "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", - "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==", - "license": "MIT", - "optional": true - }, - "node_modules/end-of-stream": { - "version": "1.4.5", - "resolved": "https://registry.npmjs.org/end-of-stream/-/end-of-stream-1.4.5.tgz", - "integrity": "sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg==", - "license": "MIT", - "dependencies": { - "once": "^1.4.0" - } - }, - "node_modules/fast-copy": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/fast-copy/-/fast-copy-4.0.4.tgz", - "integrity": "sha512-eVAiWVNPSEGIzDl5yPuLrx8fNMogScXvD9xp1Kzd41FjRIz2I3sSIcxsFeM5EzFfHAfobdvs8ZySffUopljvIA==", - "license": "MIT" - }, - "node_modules/fast-safe-stringify": { - "version": "2.1.1", - "resolved": "https://registry.npmjs.org/fast-safe-stringify/-/fast-safe-stringify-2.1.1.tgz", - "integrity": "sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==", - "license": "MIT" - }, - "node_modules/ffprobe-static": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/ffprobe-static/-/ffprobe-static-3.1.0.tgz", - "integrity": "sha512-Dvpa9uhVMOYivhHKWLGDoa512J751qN1WZAIO+Xw4L/mrUSPxS4DApzSUDbCFE/LUq2+xYnznEahTd63AqBSpA==", - "license": "MIT" - }, - "node_modules/fs-minipass": { - "version": "2.1.0", - "resolved": "https://registry.npmjs.org/fs-minipass/-/fs-minipass-2.1.0.tgz", - "integrity": "sha512-V/JgOLFCS+R6Vcq0slCuaeWEdNC3ouDlJMNIsacH2VtALiu9mV4LPrHc5cDl8k5aw6J8jwgWWpiTo5RYhmIzvg==", - "license": "ISC", - "optional": true, - "dependencies": { - "minipass": "^3.0.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/fs-minipass/node_modules/minipass": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", - "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", - "license": "ISC", - "optional": true, - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/fs.realpath": { - "version": "1.0.0", - "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", - "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==", - "license": "ISC", - "optional": true - }, - "node_modules/gauge": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/gauge/-/gauge-3.0.2.tgz", - "integrity": "sha512-+5J6MS/5XksCuXq++uFRsnUd7Ovu1XenbeuIuNRJxYWjgQbPuFhT14lAvsWfqfAmnwluf1OwMjz39HjfLPci0Q==", - "deprecated": "This package is no longer supported.", - "license": "ISC", - "optional": true, - "dependencies": { - "aproba": "^1.0.3 || ^2.0.0", - "color-support": "^1.1.2", - "console-control-strings": "^1.0.0", - "has-unicode": "^2.0.1", - "object-assign": "^4.1.1", - "signal-exit": "^3.0.0", - "string-width": "^4.2.3", - "strip-ansi": "^6.0.1", - "wide-align": "^1.1.2" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/generate-function": { - "version": "2.3.1", - "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", - "integrity": "sha512-eeB5GfMNeevm/GRYq20ShmsaGcmI81kIX2K9XQx5miC8KdHaC6Jm0qQ8ZNeGOi7wYB8OsdxKs+Y2oVuTFuVwKQ==", - "license": "MIT", - "dependencies": { - "is-property": "^1.0.2" - } - }, - "node_modules/glob": { - "version": "7.2.3", - "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.3.tgz", - "integrity": "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q==", - "deprecated": "Old versions of glob are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", - "license": "ISC", - "optional": true, - "dependencies": { - "fs.realpath": "^1.0.0", - "inflight": "^1.0.4", - "inherits": "2", - "minimatch": "^3.1.1", - "once": "^1.3.0", - "path-is-absolute": "^1.0.0" - }, - "engines": { - "node": "*" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/has-unicode": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/has-unicode/-/has-unicode-2.0.1.tgz", - "integrity": "sha512-8Rf9Y83NBReMnx0gFzA8JImQACstCYWUplepDa9xprwwtmgEZUF0h/i5xSA625zB/I37EtrswSST6OXxwaaIJQ==", - "license": "ISC", - "optional": true - }, - "node_modules/help-me": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/help-me/-/help-me-5.0.0.tgz", - "integrity": "sha512-7xgomUX6ADmcYzFik0HzAxh/73YlKR9bmFzf51CZwR+b6YtzU2m0u49hQCqV6SvlqIqsaxovfwdvbnsw3b/zpg==", - "license": "MIT" - }, - "node_modules/https-proxy-agent": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-5.0.1.tgz", - "integrity": "sha512-dFcAjpTQFgoLMzC2VwU+C/CbS7uRL0lWmxDITmqm7C+7F0Odmj6s9l6alZc6AELXhrnggM2CeWSXHGOdX2YtwA==", - "license": "MIT", - "optional": true, - "dependencies": { - "agent-base": "6", - "debug": "4" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/iconv-lite": { - "version": "0.7.3", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.3.tgz", - "integrity": "sha512-IKXpvIzjnC9XTAUbVBcMfGS0EPaIXtW6v+zr+RRp+hqULEpo0owZax6wyRwPOJbWbzjYspQwusTsfVr0ifh4uQ==", - "license": "MIT", - "dependencies": { - "safer-buffer": ">= 2.1.2 < 3.0.0" - }, - "engines": { - "node": ">=0.10.0" - }, - "funding": { - "type": "opencollective", - "url": "https://opencollective.com/express" - } - }, - "node_modules/inflight": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", - "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", - "deprecated": "This module is not supported, and leaks memory. Do not use it. Check out lru-cache if you want a good and tested way to coalesce async requests by a key value, which is much more comprehensive and powerful.", - "license": "ISC", - "optional": true, - "dependencies": { - "once": "^1.3.0", - "wrappy": "1" - } - }, - "node_modules/inherits": { - "version": "2.0.4", - "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", - "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==", - "license": "ISC", - "optional": true - }, - "node_modules/is-fullwidth-code-point": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", - "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/is-property": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", - "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==", - "license": "MIT" - }, - "node_modules/jose": { - "version": "5.10.0", - "resolved": "https://registry.npmjs.org/jose/-/jose-5.10.0.tgz", - "integrity": "sha512-s+3Al/p9g32Iq+oqXxkW//7jk2Vig6FF1CFqzVXoTUXt2qz89YWbL+OwS17NFYEvxC35n0FKeGO2LGYSxeM2Gg==", - "license": "MIT", - "optional": true, - "funding": { - "url": "https://github.com/sponsors/panva" - } - }, - "node_modules/joycon": { - "version": "3.1.1", - "resolved": "https://registry.npmjs.org/joycon/-/joycon-3.1.1.tgz", - "integrity": "sha512-34wB/Y7MW7bzjKRjUKTa46I2Z7eV62Rkhva+KkopW7Qvv/OSWBqvkSY7vusOPrNuZcUG3tApvdVgNB8POj3SPw==", - "license": "MIT", - "engines": { - "node": ">=10" - } - }, - "node_modules/lavalink-client": { - "version": "2.11.0", - "resolved": "https://registry.npmjs.org/lavalink-client/-/lavalink-client-2.11.0.tgz", - "integrity": "sha512-x4mobBpwSjJ+jC2XDevcMc8Mj454Bx3cTfmWgtLHisY+U/HlK7ubWkdHawZrEwBW5E6zIDjoiBvVBR8FDIUdkw==", - "license": "MIT", - "dependencies": { - "tslib": "^2.8.1", - "ws": "^8.21.3" - }, - "engines": { - "bun": ">=1.1.27", - "node": ">=18.0.0" - } - }, - "node_modules/livekit-server-sdk": { - "version": "2.18.0", - "resolved": "https://registry.npmjs.org/livekit-server-sdk/-/livekit-server-sdk-2.18.0.tgz", - "integrity": "sha512-iUGmkbyi0g4DHKQ0Z4VSVs/V+ddp3T75ccQIe6LX94AYlqgyh+SVSM1lQMjFQuI3Qh6Z9v06T4xxV+vWmp7VeQ==", - "license": "Apache-2.0", - "optional": true, - "dependencies": { - "@bufbuild/protobuf": "^1.10.1", - "@livekit/protocol": "1.48.0", - "jose": "^5.1.2" - }, - "engines": { - "node": ">=18" - } - }, - "node_modules/long": { - "version": "5.3.2", - "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", - "integrity": "sha512-mNAgZ1GmyNhD7AuqnTG3/VQ26o760+ZYBPKjPvugO8+nLbYfX6TVpJPseBvopbdY+qpZ/lKUnmEc1LeZYS3QAA==", - "license": "Apache-2.0" - }, - "node_modules/lru.min": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/lru.min/-/lru.min-1.1.4.tgz", - "integrity": "sha512-DqC6n3QQ77zdFpCMASA1a3Jlb64Hv2N2DciFGkO/4L9+q/IpIAuRlKOvCXabtRW6cQf8usbmM6BE/TOPysCdIA==", - "license": "MIT", - "engines": { - "bun": ">=1.0.0", - "deno": ">=1.30.0", - "node": ">=8.0.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/sponsors/wellwelwel" - } - }, - "node_modules/make-dir": { - "version": "3.1.0", - "resolved": "https://registry.npmjs.org/make-dir/-/make-dir-3.1.0.tgz", - "integrity": "sha512-g3FeP20LNwhALb/6Cz6Dd4F2ngze0jz7tbzrD2wAV+o9FeNHe4rL+yK2md0J/fiSf1sa1ADhXqi5+oVwOM/eGw==", - "license": "MIT", - "optional": true, - "dependencies": { - "semver": "^6.0.0" - }, - "engines": { - "node": ">=8" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/make-dir/node_modules/semver": { - "version": "6.3.1", - "resolved": "https://registry.npmjs.org/semver/-/semver-6.3.1.tgz", - "integrity": "sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA==", - "license": "ISC", - "optional": true, - "bin": { - "semver": "bin/semver.js" - } - }, - "node_modules/minimatch": { - "version": "3.1.5", - "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", - "integrity": "sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w==", - "license": "ISC", - "optional": true, - "dependencies": { - "brace-expansion": "^1.1.7" - }, - "engines": { - "node": "*" - } - }, - "node_modules/minimist": { - "version": "1.2.8", - "resolved": "https://registry.npmjs.org/minimist/-/minimist-1.2.8.tgz", - "integrity": "sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA==", - "license": "MIT", - "funding": { - "url": "https://github.com/sponsors/ljharb" - } - }, - "node_modules/minipass": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-5.0.0.tgz", - "integrity": "sha512-3FnjYuehv9k6ovOEbyOswadCDPX1piCfhV8ncmYtHOjuPwylVWsghTLo7rabjC3Rx5xD4HDx8Wm1xnMF7S5qFQ==", - "license": "ISC", - "optional": true, - "engines": { - "node": ">=8" - } - }, - "node_modules/minizlib": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/minizlib/-/minizlib-2.1.2.tgz", - "integrity": "sha512-bAxsR8BVfj60DWXHE3u30oHzfl4G7khkSuPW+qvpd7jFRHm7dLxOjUk1EHACJ/hxLY8phGJ0YhYHZo7jil7Qdg==", - "license": "MIT", - "optional": true, - "dependencies": { - "minipass": "^3.0.0", - "yallist": "^4.0.0" - }, - "engines": { - "node": ">= 8" - } - }, - "node_modules/minizlib/node_modules/minipass": { - "version": "3.3.6", - "resolved": "https://registry.npmjs.org/minipass/-/minipass-3.3.6.tgz", - "integrity": "sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw==", - "license": "ISC", - "optional": true, - "dependencies": { - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/mkdirp": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/mkdirp/-/mkdirp-1.0.4.tgz", - "integrity": "sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw==", - "license": "MIT", - "optional": true, - "bin": { - "mkdirp": "bin/cmd.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/mp4box": { - "version": "0.5.4", - "resolved": "https://registry.npmjs.org/mp4box/-/mp4box-0.5.4.tgz", - "integrity": "sha512-GcCH0fySxBurJtvr0dfhz0IxHZjc1RP+F+I8xw+LIwkU1a+7HJx8NCDiww1I5u4Hz6g4eR1JlGADEGJ9r4lSfA==", - "license": "BSD-3-Clause" - }, - "node_modules/ms": { - "version": "2.1.3", - "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", - "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==", - "license": "MIT", - "optional": true - }, - "node_modules/mysql2": { - "version": "3.24.2", - "resolved": "https://registry.npmjs.org/mysql2/-/mysql2-3.24.2.tgz", - "integrity": "sha512-l9kXeKGwd6VCbSjmpO/bLWb+YCYpbvE4whte8ec6InXebvCNyEEydyRCnRU+TSHNqRLJ8B+Tk1uWb+vMCJgJzA==", - "license": "MIT", - "dependencies": { - "aws-ssl-profiles": "^1.1.2", - "generate-function": "^2.3.1", - "iconv-lite": "^0.7.3", - "long": "^5.3.2", - "lru.min": "^1.1.4", - "named-placeholders": "^1.1.6", - "sql-escaper": "^1.5.1" - }, - "engines": { - "node": ">= 8.0" - }, - "peerDependencies": { - "@types/node": ">= 8" - } - }, - "node_modules/named-placeholders": { - "version": "1.1.6", - "resolved": "https://registry.npmjs.org/named-placeholders/-/named-placeholders-1.1.6.tgz", - "integrity": "sha512-Tz09sEL2EEuv5fFowm419c1+a/jSMiBjI9gHxVLrVdbUkkNUUfjsVYs9pVZu5oCon/kmRh9TfLEObFtkVxmY0w==", - "license": "MIT", - "dependencies": { - "lru.min": "^1.1.0" - }, - "engines": { - "node": ">=8.0.0" - } - }, - "node_modules/node-addon-api": { - "version": "7.1.1", - "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz", - "integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==", - "license": "MIT", - "optional": true - }, - "node_modules/node-fetch": { - "version": "2.7.0", - "resolved": "https://registry.npmjs.org/node-fetch/-/node-fetch-2.7.0.tgz", - "integrity": "sha512-c4FRfUm/dbcWZ7U+1Wq0AwCyFL+3nt2bEw05wfxSz+DWpWsitgmSgYmy2dQdWyKC1694ELPqMs/YzUSNozLt8A==", - "license": "MIT", - "optional": true, - "dependencies": { - "whatwg-url": "^5.0.0" - }, - "engines": { - "node": "4.x || >=6.0.0" - }, - "peerDependencies": { - "encoding": "^0.1.0" - }, - "peerDependenciesMeta": { - "encoding": { - "optional": true - } - } - }, - "node_modules/node-gyp-build": { - "version": "4.8.4", - "resolved": "https://registry.npmjs.org/node-gyp-build/-/node-gyp-build-4.8.4.tgz", - "integrity": "sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==", - "license": "MIT", - "optional": true, - "bin": { - "node-gyp-build": "bin.js", - "node-gyp-build-optional": "optional.js", - "node-gyp-build-test": "build-test.js" - } - }, - "node_modules/node-webcodecs": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/node-webcodecs/-/node-webcodecs-1.3.0.tgz", - "integrity": "sha512-iMx9mhiefQiw32FKlmr+4xc6o3Se+34qOFxAmuKDK4Lkoj0new1AsKTcHPeWxRgpT8MgwUbmPdSNLqtI9SObSg==", - "cpu": [ - "x64", - "arm64" - ], - "hasInstallScript": true, - "license": "MIT", - "optional": true, - "os": [ - "darwin", - "linux", - "win32" - ], - "dependencies": { - "node-addon-api": "^7.0.0", - "node-gyp-build": "^4.8.4" - }, - "engines": { - "node": ">=18.0.0" - }, - "optionalDependencies": { - "@node-webcodecs/static-darwin-arm64": "1.3.0", - "@node-webcodecs/static-linux-arm64": "1.3.0", - "@node-webcodecs/static-linux-x64": "1.3.0" - }, - "peerDependencies": { - "mediabunny": ">=1.0.0" - }, - "peerDependenciesMeta": { - "mediabunny": { - "optional": true - } - } - }, - "node_modules/nopt": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/nopt/-/nopt-5.0.0.tgz", - "integrity": "sha512-Tbj67rffqceeLpcRXrT7vKAN8CwfPeIBgM7E6iBkmKLV7bEMwpGgYLGv0jACUsECaa/vuxP0IjEont6umdMgtQ==", - "license": "ISC", - "optional": true, - "dependencies": { - "abbrev": "1" - }, - "bin": { - "nopt": "bin/nopt.js" - }, - "engines": { - "node": ">=6" - } - }, - "node_modules/npmlog": { - "version": "5.0.1", - "resolved": "https://registry.npmjs.org/npmlog/-/npmlog-5.0.1.tgz", - "integrity": "sha512-AqZtDUWOMKs1G/8lwylVjrdYgqA4d9nu8hc+0gzRxlDb1I10+FHBGMXs6aiQHFdCUUlqH99MUMuLfzWDNDtfxw==", - "deprecated": "This package is no longer supported.", - "license": "ISC", - "optional": true, - "dependencies": { - "are-we-there-yet": "^2.0.0", - "console-control-strings": "^1.1.0", - "gauge": "^3.0.0", - "set-blocking": "^2.0.0" - } - }, - "node_modules/object-assign": { - "version": "4.1.1", - "resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz", - "integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/on-exit-leak-free": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", - "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==", - "license": "MIT", - "engines": { - "node": ">=14.0.0" - } - }, - "node_modules/once": { - "version": "1.4.0", - "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", - "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", - "license": "ISC", - "dependencies": { - "wrappy": "1" - } - }, - "node_modules/opus-decoder": { - "version": "0.7.12", - "resolved": "https://registry.npmjs.org/opus-decoder/-/opus-decoder-0.7.12.tgz", - "integrity": "sha512-6zpHFDi/MhYvMwyYiuJPqJ2lcRkfm7wHblSvT3lUtx/kLvHkunoe/rhTn1dLKxqVGLeQj3gQi7CnR0N2p3RuOg==", - "license": "MIT", - "dependencies": { - "@wasm-audio-decoders/common": "9.0.7" - }, - "funding": { - "type": "individual", - "url": "https://github.com/sponsors/eshaz" - } - }, - "node_modules/opusscript": { - "version": "0.0.8", - "resolved": "https://registry.npmjs.org/opusscript/-/opusscript-0.0.8.tgz", - "integrity": "sha512-VSTi1aWFuCkRCVq+tx/BQ5q9fMnQ9pVZ3JU4UHKqTkf0ED3fKEPdr+gKAAl3IA2hj9rrP6iyq3hlcJq3HELtNQ==", - "license": "MIT" - }, - "node_modules/path-is-absolute": { - "version": "1.0.1", - "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", - "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", - "license": "MIT", - "optional": true, - "engines": { - "node": ">=0.10.0" - } - }, - "node_modules/pino": { - "version": "9.14.0", - "resolved": "https://registry.npmjs.org/pino/-/pino-9.14.0.tgz", - "integrity": "sha512-8OEwKp5juEvb/MjpIc4hjqfgCNysrS94RIOMXYvpYCdm/jglrKEiAYmiumbmGhCvs+IcInsphYDFwqrjr7398w==", - "license": "MIT", - "dependencies": { - "@pinojs/redact": "^0.4.0", - "atomic-sleep": "^1.0.0", - "on-exit-leak-free": "^2.1.0", - "pino-abstract-transport": "^2.0.0", - "pino-std-serializers": "^7.0.0", - "process-warning": "^5.0.0", - "quick-format-unescaped": "^4.0.3", - "real-require": "^0.2.0", - "safe-stable-stringify": "^2.3.1", - "sonic-boom": "^4.0.1", - "thread-stream": "^3.0.0" - }, - "bin": { - "pino": "bin.js" - } - }, - "node_modules/pino-abstract-transport": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-2.0.0.tgz", - "integrity": "sha512-F63x5tizV6WCh4R6RHyi2Ml+M70DNRXt/+HANowMflpgGFMAym/VKm6G7ZOQRjqN7XbGxK1Lg9t6ZrtzOaivMw==", - "license": "MIT", - "dependencies": { - "split2": "^4.0.0" - } - }, - "node_modules/pino-pretty": { - "version": "13.1.3", - "resolved": "https://registry.npmjs.org/pino-pretty/-/pino-pretty-13.1.3.tgz", - "integrity": "sha512-ttXRkkOz6WWC95KeY9+xxWL6AtImwbyMHrL1mSwqwW9u+vLp/WIElvHvCSDg0xO/Dzrggz1zv3rN5ovTRVowKg==", - "license": "MIT", - "dependencies": { - "colorette": "^2.0.7", - "dateformat": "^4.6.3", - "fast-copy": "^4.0.0", - "fast-safe-stringify": "^2.1.1", - "help-me": "^5.0.0", - "joycon": "^3.1.1", - "minimist": "^1.2.6", - "on-exit-leak-free": "^2.1.0", - "pino-abstract-transport": "^3.0.0", - "pump": "^3.0.0", - "secure-json-parse": "^4.0.0", - "sonic-boom": "^4.0.1", - "strip-json-comments": "^5.0.2" - }, - "bin": { - "pino-pretty": "bin.js" - } - }, - "node_modules/pino-pretty/node_modules/pino-abstract-transport": { - "version": "3.0.0", - "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-3.0.0.tgz", - "integrity": "sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==", - "license": "MIT", - "dependencies": { - "split2": "^4.0.0" - } - }, - "node_modules/pino-std-serializers": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.1.0.tgz", - "integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==", - "license": "MIT" - }, - "node_modules/prism-media": { - "version": "1.3.5", - "resolved": "https://registry.npmjs.org/prism-media/-/prism-media-1.3.5.tgz", - "integrity": "sha512-IQdl0Q01m4LrkN1EGIE9lphov5Hy7WWlH6ulf5QdGePLlPas9p2mhgddTEHrlaXYjjFToM1/rWuwF37VF4taaA==", - "license": "Apache-2.0", - "peerDependencies": { - "@discordjs/opus": ">=0.8.0 <1.0.0", - "ffmpeg-static": "^5.0.2 || ^4.2.7 || ^3.0.0 || ^2.4.0", - "node-opus": "^0.3.3", - "opusscript": "^0.0.8" - }, - "peerDependenciesMeta": { - "@discordjs/opus": { - "optional": true - }, - "ffmpeg-static": { - "optional": true - }, - "node-opus": { - "optional": true - }, - "opusscript": { - "optional": true - } - } - }, - "node_modules/process-warning": { - "version": "5.1.0", - "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.1.0.tgz", - "integrity": "sha512-jQSaVHsPgtyw60e1rQ/A+/ArPEj/S8pS/vFnyGa/gYFXrKk/6RuDkoqVDQ5NI5MmS01698ltlAk0NoDBNLujRw==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "MIT" - }, - "node_modules/pump": { - "version": "3.0.4", - "resolved": "https://registry.npmjs.org/pump/-/pump-3.0.4.tgz", - "integrity": "sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA==", - "license": "MIT", - "dependencies": { - "end-of-stream": "^1.1.0", - "once": "^1.3.1" - } - }, - "node_modules/quick-format-unescaped": { - "version": "4.0.4", - "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz", - "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==", - "license": "MIT" - }, - "node_modules/readable-stream": { - "version": "3.6.2", - "resolved": "https://registry.npmjs.org/readable-stream/-/readable-stream-3.6.2.tgz", - "integrity": "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA==", - "license": "MIT", - "optional": true, - "dependencies": { - "inherits": "^2.0.3", - "string_decoder": "^1.1.1", - "util-deprecate": "^1.0.1" - }, - "engines": { - "node": ">= 6" - } - }, - "node_modules/real-require": { - "version": "0.2.0", - "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz", - "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==", - "license": "MIT", - "engines": { - "node": ">= 12.13.0" - } - }, - "node_modules/redis": { - "version": "5.12.1", - "resolved": "https://registry.npmjs.org/redis/-/redis-5.12.1.tgz", - "integrity": "sha512-LDsoVvb/CpoV9EN3FXvgvSHNJWuCIzl9MiO3ppOevuGLpSGJhwfQjpEwfFJcQvNSddHADDdZaWx0HnmMxRXG7g==", - "license": "MIT", - "dependencies": { - "@redis/bloom": "5.12.1", - "@redis/client": "5.12.1", - "@redis/json": "5.12.1", - "@redis/search": "5.12.1", - "@redis/time-series": "5.12.1" - }, - "engines": { - "node": ">= 18.19.0" - } - }, - "node_modules/rimraf": { - "version": "3.0.2", - "resolved": "https://registry.npmjs.org/rimraf/-/rimraf-3.0.2.tgz", - "integrity": "sha512-JZkJMZkAGFFPP2YqXZXPbMlMBgsxzE8ILs4lMIX/2o0L9UBw9O/Y3o6wFw/i9YLapcUJWwqbi3kdxIPdC62TIA==", - "deprecated": "Rimraf versions prior to v4 are no longer supported", - "license": "ISC", - "optional": true, - "dependencies": { - "glob": "^7.1.3" - }, - "bin": { - "rimraf": "bin.js" - }, - "funding": { - "url": "https://github.com/sponsors/isaacs" - } - }, - "node_modules/safe-buffer": { - "version": "5.2.1", - "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", - "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/feross" - }, - { - "type": "patreon", - "url": "https://www.patreon.com/feross" - }, - { - "type": "consulting", - "url": "https://feross.org/support" - } - ], - "license": "MIT", - "optional": true - }, - "node_modules/safe-stable-stringify": { - "version": "2.5.0", - "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz", - "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==", - "license": "MIT", - "engines": { - "node": ">=10" - } - }, - "node_modules/safer-buffer": { - "version": "2.1.2", - "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", - "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", - "license": "MIT" - }, - "node_modules/secure-json-parse": { - "version": "4.1.0", - "resolved": "https://registry.npmjs.org/secure-json-parse/-/secure-json-parse-4.1.0.tgz", - "integrity": "sha512-l4KnYfEyqYJxDwlNVyRfO2E4NTHfMKAWdUuA8J0yve2Dz/E/PdBepY03RvyJpssIpRFwJoCD55wA+mEDs6ByWA==", - "funding": [ - { - "type": "github", - "url": "https://github.com/sponsors/fastify" - }, - { - "type": "opencollective", - "url": "https://opencollective.com/fastify" - } - ], - "license": "BSD-3-Clause" - }, - "node_modules/semver": { - "version": "7.8.5", - "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", - "integrity": "sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA==", - "license": "ISC", - "optional": true, - "bin": { - "semver": "bin/semver.js" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/set-blocking": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/set-blocking/-/set-blocking-2.0.0.tgz", - "integrity": "sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==", - "license": "ISC", - "optional": true - }, - "node_modules/signal-exit": { - "version": "3.0.7", - "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", - "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", - "license": "ISC", - "optional": true - }, - "node_modules/simple-yenc": { - "version": "1.0.4", - "resolved": "https://registry.npmjs.org/simple-yenc/-/simple-yenc-1.0.4.tgz", - "integrity": "sha512-5gvxpSd79e9a3V4QDYUqnqxeD4HGlhCakVpb6gMnDD7lexJggSBJRBO5h52y/iJrdXRilX9UCuDaIJhSWm5OWw==", - "license": "MIT", - "funding": { - "type": "individual", - "url": "https://github.com/sponsors/eshaz" - } - }, - "node_modules/sonic-boom": { - "version": "4.2.1", - "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz", - "integrity": "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==", - "license": "MIT", - "dependencies": { - "atomic-sleep": "^1.0.0" - } - }, - "node_modules/split2": { - "version": "4.2.0", - "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", - "integrity": "sha512-UcjcJOWknrNkF6PLX83qcHM6KHgVKNkV62Y8a5uYDVv9ydGQVwAHMKqHdJje1VTWpljG0WYpCDhrCdAOYH4TWg==", - "license": "ISC", - "engines": { - "node": ">= 10.x" - } - }, - "node_modules/sql-escaper": { - "version": "1.5.1", - "resolved": "https://registry.npmjs.org/sql-escaper/-/sql-escaper-1.5.1.tgz", - "integrity": "sha512-4toX5E1fQbBrpfXidaHnF0669nkAdETeIPTs2SUjxxD7RRIs9ICG4gtpmfc68JCEKehsdwLFqBu9VlQqZ1P1gg==", - "license": "MIT", - "engines": { - "bun": ">=1.0.0", - "deno": ">=2.0.0", - "node": ">=12.0.0" - }, - "funding": { - "type": "github", - "url": "https://github.com/mysqljs/sql-escaper?sponsor=1" - } - }, - "node_modules/string_decoder": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/string_decoder/-/string_decoder-1.3.0.tgz", - "integrity": "sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==", - "license": "MIT", - "optional": true, - "dependencies": { - "safe-buffer": "~5.2.0" - } - }, - "node_modules/string-width": { - "version": "4.2.3", - "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", - "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", - "license": "MIT", - "optional": true, - "dependencies": { - "emoji-regex": "^8.0.0", - "is-fullwidth-code-point": "^3.0.0", - "strip-ansi": "^6.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-ansi": { - "version": "6.0.1", - "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", - "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", - "license": "MIT", - "optional": true, - "dependencies": { - "ansi-regex": "^5.0.1" - }, - "engines": { - "node": ">=8" - } - }, - "node_modules/strip-json-comments": { - "version": "5.0.3", - "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-5.0.3.tgz", - "integrity": "sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw==", - "license": "MIT", - "engines": { - "node": ">=14.16" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, - "node_modules/tar": { - "version": "6.2.1", - "resolved": "https://registry.npmjs.org/tar/-/tar-6.2.1.tgz", - "integrity": "sha512-DZ4yORTwrbTj/7MZYq2w+/ZFdI6OZ/f9SFHR+71gIVUZhOQPHzVCLpvRnPgyaMpfWxxk/4ONva3GQSyNIKRv6A==", - "deprecated": "Old versions of tar are not supported, and contain widely publicized security vulnerabilities, which have been fixed in the current version. Please update. Support for old versions may be purchased (at exorbitant rates) by contacting i@izs.me", - "license": "ISC", - "optional": true, - "dependencies": { - "chownr": "^2.0.0", - "fs-minipass": "^2.0.0", - "minipass": "^5.0.0", - "minizlib": "^2.1.1", - "mkdirp": "^1.0.3", - "yallist": "^4.0.0" - }, - "engines": { - "node": ">=10" - } - }, - "node_modules/thread-stream": { - "version": "3.2.0", - "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-3.2.0.tgz", - "integrity": "sha512-zLBvqpwr4Esa0kRjcrzGU6zL25lePWaCLMx0RQFrmteozIfeNdaMLpG5U7PeHzvlFkAWaRKA9/KVW4F60iB+qw==", - "license": "MIT", - "dependencies": { - "real-require": "^0.2.0" - } - }, - "node_modules/tr46": { - "version": "0.0.3", - "resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz", - "integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==", - "license": "MIT", - "optional": true - }, - "node_modules/tslib": { - "version": "2.8.1", - "resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz", - "integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==", - "license": "0BSD" - }, - "node_modules/tweetnacl": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/tweetnacl/-/tweetnacl-1.0.3.tgz", - "integrity": "sha512-6rt+RN7aOi1nGMyC4Xa5DdYiukl2UWCbcJft7YhxReBGQD7OAM8Pbxw6YMo4r2diNEA8FEmu32YOn9rhaiE5yw==", - "license": "Unlicense" - }, - "node_modules/undici": { - "version": "7.29.0", - "resolved": "https://registry.npmjs.org/undici/-/undici-7.29.0.tgz", - "integrity": "sha512-IDxfleLmmbSskfWSUATiN1nfn2rDuvnMOqb5CWR92iIfojA0Ud+ulOAAEQ57LPr9rWmsreUyf5lwyao+7GNNVw==", - "license": "MIT", - "engines": { - "node": ">=20.18.1" - } - }, - "node_modules/undici-types": { - "version": "8.3.0", - "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.3.0.tgz", - "integrity": "sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ==", - "license": "MIT", - "peer": true - }, - "node_modules/util-deprecate": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/util-deprecate/-/util-deprecate-1.0.2.tgz", - "integrity": "sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw==", - "license": "MIT", - "optional": true - }, - "node_modules/webidl-conversions": { - "version": "3.0.1", - "resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz", - "integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==", - "license": "BSD-2-Clause", - "optional": true - }, - "node_modules/whatwg-url": { - "version": "5.0.0", - "resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz", - "integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==", - "license": "MIT", - "optional": true, - "dependencies": { - "tr46": "~0.0.3", - "webidl-conversions": "^3.0.0" - } - }, - "node_modules/wide-align": { - "version": "1.1.5", - "resolved": "https://registry.npmjs.org/wide-align/-/wide-align-1.1.5.tgz", - "integrity": "sha512-eDMORYaPNZ4sQIuuYPDHdQvf4gyCF9rEEV/yPxGfwPkRodwEgiMUUXTx/dex+Me0wxx53S+NgUHaP7y3MGlDmg==", - "license": "ISC", - "optional": true, - "dependencies": { - "string-width": "^1.0.2 || 2 || 3 || 4" - } - }, - "node_modules/wrappy": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", - "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==", - "license": "ISC" - }, - "node_modules/ws": { - "version": "8.21.3", - "resolved": "https://registry.npmjs.org/ws/-/ws-8.21.3.tgz", - "integrity": "sha512-201TZ/kPWxoPr/OKWjquZR1SWKXcvxdH+e1xrx89b3YbmzLMFCLfnaG1HFIgWzJOEWZ7MvpK++odZufgYR50Rw==", - "license": "MIT", - "engines": { - "node": ">=10.0.0" - }, - "peerDependencies": { - "bufferutil": "^4.0.1", - "utf-8-validate": ">=5.0.2" - }, - "peerDependenciesMeta": { - "bufferutil": { - "optional": true - }, - "utf-8-validate": { - "optional": true - } - } - }, - "node_modules/yallist": { - "version": "4.0.0", - "resolved": "https://registry.npmjs.org/yallist/-/yallist-4.0.0.tgz", - "integrity": "sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A==", - "license": "ISC", - "optional": true - } - } -} diff --git a/package.json b/package.json index f1460c3..601e279 100644 --- a/package.json +++ b/package.json @@ -4,10 +4,10 @@ "node": ">=22.13.0" }, "dependencies": { - "@discordjs/opus": "^0.10.0", - "@fluxerjs/core": "^2.2.0", - "@fluxerjs/util": "^2.2.0", - "@fluxerjs/voice": "^2.2.0", + "@fluxerjs/core": "^3.0.0", + "@fluxerjs/sharding": "^3.0.0", + "@fluxerjs/util": "^3.0.0", + "@fluxerjs/voice": "^3.0.0", "bcryptjs": "^3.0.3", "ffprobe-static": "^3.1.0", "lavalink-client": "^2.10.3", @@ -19,6 +19,7 @@ "scripts": { "dev": "node --inspect index.mjs --trace-warnings", "start": "node index.mjs", + "shard": "node shard.mjs", "migrate": "node settings/migrate.mjs" } } diff --git a/settings/README.md b/settings/README.md index aaa657e..c57c545 100644 --- a/settings/README.md +++ b/settings/README.md @@ -5,7 +5,7 @@ Per-guild settings for Remix, backed by MySQL. ## How it works - Defaults live in `storage/defaults.json`. Every guild starts from this template. -- `src/Settings.mjs` contains the implementation: +- `src/db/Settings.mjs` contains the implementation: - `SettingsManager` — defines the setting keys, their defaults and descriptions. - `ServerSettings` — per-guild view; `get`/`set`/`reset` operate in memory and persist with an 80 ms debounced write. - `RemoteSettingsManager` — loads every guild row from the MySQL `settings` table (`id` primary key + `data` JSON column) and writes individual keys back with `JSON_SET`. @@ -22,7 +22,7 @@ Per-guild settings for Remix, backed by MySQL. | File | Purpose | | :--- | :--- | -| `Settings.mjs` | Re-export of `src/Settings.mjs` classes | +| `Settings.mjs` | Re-export of `src/db/Settings.mjs` classes | | `migrate.mjs` | One-shot tool that clones every guild row from one settings table/bot ID to another (`npm run migrate`) | | `runnables.mjs` | Validators applied when a setting changes (e.g. `prefix` must be ≤ 5 chars with no whitespace, `pfp` only accepts `default`) | diff --git a/settings/Settings.mjs b/settings/Settings.mjs index 5fd9603..3812de2 100644 --- a/settings/Settings.mjs +++ b/settings/Settings.mjs @@ -2,4 +2,4 @@ * @module settings/Settings * @description Re-exports the core Settings classes from `src/Settings.mjs`. */ -export { SettingsManager, ServerSettings, RemoteSettingsManager } from "../src/Settings.mjs"; +export { SettingsManager, ServerSettings, RemoteSettingsManager } from "../src/db/Settings.mjs"; diff --git a/settings/migrate.mjs b/settings/migrate.mjs index 7a13ac7..feefc3e 100644 --- a/settings/migrate.mjs +++ b/settings/migrate.mjs @@ -5,9 +5,9 @@ * Reads `config.json` for MySQL credentials and runs once on the "ready" event. */ -import { RemoteSettingsManager } from "../src/Settings.mjs"; +import { RemoteSettingsManager } from "../src/db/Settings.mjs"; import fs from "node:fs"; -import { logger } from "../src/constants/Logger.mjs"; +import { logger } from "../src/core/Logger.mjs"; const config = JSON.parse(fs.readFileSync(new URL("../config.json", import.meta.url))); diff --git a/shard.mjs b/shard.mjs new file mode 100644 index 0000000..144bb3b --- /dev/null +++ b/shard.mjs @@ -0,0 +1,157 @@ +/** + * @module shard + * @description Opt-in process-level sharding supervisor for the Remix music + * bot, built on @fluxerjs/sharding 3.0 (beta). + * + * Forks one child process per shard slice; every child runs the standard + * `index.mjs` boot path, attaches the child-side ShardClientUtil before + * login (see src/core/Bot.mjs), and reports readiness over IPC. The manager + * owns the shared per-IP IDENTIFY budget so children never collectively + * exceed the gateway's identify limit. + * + * Usage: + * node shard.mjs (or `npm run shard`) + * + * Single-process operation (`npm start` / `node index.mjs`) is unchanged and + * remains the default — sharding is purely additive. + * + * Configuration (config.json, optional `sharding` object): + * { + * "sharding": { + * "totalShards": 4, // gateway shards across all children + * "shardsPerProcess": 2, // gateway shards per child process + * "respawn": true, // restart dead children + * "spawnTimeout": 30000, // ms to wait for a child's ready IPC + * "spawnDelay": 5000 // ms between successive spawns + * } + * } + * + * Environment overrides (win over config.json — handy for Docker): + * FLUXER_TOTAL_SHARDS, FLUXER_SHARDS_PER_PROCESS + * + * Notes: + * - DMs and guild-less events only reach shard 0 (Fluxer limitation). + * - Prefer an explicit totalShards number: Fluxer's /gateway/bot always + * reports `shards: 1`, so `'auto'` is not offered here. + * - The FLUXER_SHARD_* / FLUXER_TOKEN env vars are set by the manager on + * its children — never export them manually. + */ + +import * as fs from "node:fs"; +import { fileURLToPath } from "node:url"; +import { ShardingManager } from "@fluxerjs/sharding"; +import { logger } from "./src/core/Logger.mjs"; + +/** + * Load config.json with the same fatal-error semantics as src/core/Bot.mjs. + * @returns {{token: string, sharding?: object}} The parsed config. + */ +function loadConfig() { + let config; + try { + config = JSON.parse(fs.readFileSync("config.json", "utf8")); + } catch (e) { + const reason = e.code === "ENOENT" + ? "config.json not found. Copy config_example.json → config.json and fill in your values." + : `config.json is malformed JSON: ${e.message}`; + console.error(`[Sharding] FATAL: ${reason}`); + process.exit(1); + } + if (config.token == null) { + console.error('[Sharding] FATAL: config.json is missing required key "token".'); + process.exit(1); + } + return config; +} + +/** + * Read a positive integer from an env var (undefined when unset/invalid). + * @param {string} name - The env var name. + * @returns {number|undefined} + */ +function envPositiveInt(name) { + const raw = process.env[name]; + if (raw === undefined || raw === "") return undefined; + const n = Number(raw); + return Number.isFinite(n) && n > 0 ? Math.floor(n) : undefined; +} + +/** + * Read a positive integer from the sharding config with a default. + * @param {object} shardingCfg - The config's `sharding` object. + * @param {string} key - The key to read. + * @param {number} fallback - Default value. + * @returns {number} + */ +function cfgPositiveInt(shardingCfg, key, fallback) { + const n = Number(shardingCfg?.[key]); + return Number.isFinite(n) && n > 0 ? n : fallback; +} + +const config = loadConfig(); +const shardingCfg = config.sharding ?? {}; + +const totalShards = envPositiveInt("FLUXER_TOTAL_SHARDS") + ?? cfgPositiveInt(shardingCfg, "totalShards", 1); +const shardsPerProcess = envPositiveInt("FLUXER_SHARDS_PER_PROCESS") + ?? cfgPositiveInt(shardingCfg, "shardsPerProcess", 1); +const respawn = shardingCfg.respawn !== false; +const spawnTimeout = cfgPositiveInt(shardingCfg, "spawnTimeout", 30_000); +const spawnDelay = Math.max(0, Number(shardingCfg.spawnDelay) >= 0 ? Number(shardingCfg.spawnDelay) : 5_000); + +// Absolute path to the bot entry — robust regardless of cwd (fork resolves +// relative paths against cwd, but the manager may be started from anywhere). +const entryFile = fileURLToPath(new URL("./index.mjs", import.meta.url)); + +const manager = new ShardingManager(entryFile, { + token: config.token, + totalShards, + shardsPerProcess, + respawn, + spawnTimeout, + spawnDelay, +}); + +manager.on("shardCreate", (shard) => { + logger.player(`[Sharding] Spawning shard process ${shard.id} (gateway shards ${shard.shardIds.join(", ")})...`); +}); +manager.on("shardReady", (shard) => { + logger.player(`[Sharding] Shard process ${shard.id} ready (gateway shards ${shard.shardIds.join(", ")}).`); +}); +manager.on("shardDeath", (shard, info) => { + logger.warn( + `[Sharding] Shard process ${shard.id} died (code=${info?.code} signal=${info?.signal})` + + `${respawn ? " — respawning" : ""}.` + ); +}); +manager.on("error", (err) => { + logger.error("[Sharding] Manager error:", err?.message ?? err); +}); + +/** Graceful shutdown: destroy all children, then exit. + * @param {string} sig - The received signal name. */ +let shuttingDown = false; +const shutdown = async (sig) => { + if (shuttingDown) return; + shuttingDown = true; + logger.recovery(`\n[Sharding] ${sig} received — destroying shard processes...`); + try { + await manager.destroy(); + } catch (e) { + logger.warn("[Sharding] destroy error:", e?.message); + } + process.exit(0); +}; +process.once("SIGINT", () => shutdown("SIGINT")); +process.once("SIGTERM", () => shutdown("SIGTERM")); +process.on("SIGPIPE", () => {}); + +manager.spawn().then((shards) => { + logger.player( + `[Sharding] ${shards.size} shard process(es) online — ${totalShards} gateway shard(s), ` + + `${shardsPerProcess} per process (respawn ${respawn ? "on" : "off"}).` + ); +}).catch((e) => { + logger.error("[Sharding] Spawn failed:", e?.message ?? e); + process.exit(1); +}); diff --git a/src/CommandHandler.mjs b/src/CommandHandler.mjs deleted file mode 100644 index 7619a64..0000000 --- a/src/CommandHandler.mjs +++ /dev/null @@ -1,927 +0,0 @@ -/** @module src/CommandHandler @description Command registration, loading, parsing, and execution framework with builder pattern, subcommands, and flags. */ -import { pathToFileURL } from "node:url"; -import { logger } from "./constants/Logger.mjs"; -import { Utils } from "./Utils.mjs"; -import { EventEmitter } from "node:events"; -import { Message, MessageHandler, PageBuilder, REQUIRED_BOT_PERMISSIONS, CRITICAL_PERMISSIONS } from "./MessageHandler.mjs"; -import { Client, PermissionFlags } from "@fluxerjs/core"; -import { SettingsManager } from "./Settings.mjs"; -import path from "node:path"; -import * as fs from "node:fs"; - -/** @class CommandBuilder @description Fluent builder for constructing command definitions with name, description, options, subcommands, aliases, and requirements. */ -export class CommandBuilder { - /** Create a new CommandBuilder with default empty state. */ - constructor() { - this.name = null; - this.description = null; - this.id = null; - this.aliases = []; - this.subcommands = []; - this.options = []; - this.requirements = []; - this.category = "default"; - this.examples = []; - - this.uid = Utils.uid(); - - this.subcommandError = "Invalid subcommand. Try one of the following options: `$previousCmd <$cmdlist>`"; - this.parent = null; - } - /** Set the command name and add it as the primary alias. @param {string} n @returns {CommandBuilder} */ - setName(n) { this.name = n; this.aliases.push(n.toLowerCase()); return this; } - /** Set the command description. @param {string} d @returns {CommandBuilder} */ - setDescription(d) { this.description = d; return this; } - /** Set the command ID. @param {string} id @returns {CommandBuilder} */ - setId(id) { this.id = id; return this; } - /** @returns {string} Full command path including parent chain (e.g. "music play"). */ - get command() { return (this.parent) ? this.parent.command + " " + this.name : this.name; } - /** Add a permission/owner-only requirement. @param {Function} config @returns {CommandBuilder} */ - setRequirement(config) { let req = config(new CommandRequirement()); this.requirements.push(req); return this; } - /** Add a subcommand builder. @param {Function} config @returns {CommandBuilder} */ - addSubcommand(config) { let sub = config(new CommandBuilder()); sub.parent = this; this.subcommands.push(sub); return this; } - /** Add a string option. @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */ - addStringOption(config, flag = false) { this.options.push(config(Option.create("string", flag))); return this; } - /** Add a number option. @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */ - addNumberOption(config, flag = false) { this.options.push(config(Option.create("number", flag))); return this; } - /** Add a boolean option. @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */ - addBooleanOption(config, flag = false) { this.options.push(config(Option.create("boolean", flag))); return this; } - /** Add a channel option. @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */ - addChannelOption(config, flag = false) { this.options.push(config(Option.create("channel", flag))); return this; } - /** Add a user option. @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */ - addUserOption(config, flag = false) { this.options.push(config(Option.create("user", flag))); return this; } - /** Add a text (remaining-args) option. Only one is allowed per command. @param {Function} config @returns {CommandBuilder} @throws {Error} If a text option already exists. */ - addTextOption(config) { - if (this.options.findIndex(e => e.type === "text") !== -1) throw new Error("There can only be 1 text option."); - this.options.push(config(new Option("text"))); - return this; - } - /** Add a choice option (enum-like). @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} */ - addChoiceOption(config, flag = false) { this.options.push(config(Option.create("choice", flag))); return this; } - /** Add an alias. @param {string} alias @returns {CommandBuilder} */ - addAlias(alias) { if (this.aliases.findIndex(e => e === alias.toLowerCase()) !== -1) return this; this.aliases.push(alias.toLowerCase()); return this; } - /** Add multiple aliases. @param {...string} aliases @returns {CommandBuilder} */ - addAliases(...aliases) { aliases.forEach((a) => this.addAlias(a)); return this; } - /** Set the command category. @param {string} cat @returns {CommandBuilder} */ - setCategory(cat) { this.category = cat; return this; } - /** Add usage examples. @param {...string} examples @returns {CommandBuilder} */ - addExamples(...examples) { this.examples.push(...examples); return this; } -} - -/** @class CommandRequirement @description Defines permission and owner-only requirements for commands. */ -export class CommandRequirement { - /** @type {boolean} Whether the command is restricted to bot owners. */ - ownerOnly = false; - /** Create a new CommandRequirement. */ - constructor() { - this.permissions = []; - this.permissionError = "You don't have the needed permissions to run this command!"; - return this; - } - /** @param {boolean} bool @returns {CommandRequirement} */ - setOwnerOnly(bool) { this.ownerOnly = bool; return this; } - /** @param {string} p @returns {CommandRequirement} */ - addPermission(p) { this.permissions.push(p); return this; } - /** @param {...string} p @returns {CommandRequirement} */ - addPermissions(...p) { this.permissions.push(...p); return this; } - /** @returns {string[]} */ - getPermissions() { return (this.ownerOnly) ? [...this.permissions, "Owner-only command"] : this.permissions; } - /** @param {string} e @returns {CommandRequirement} */ - setPermissionError(e) { this.permissionError = e; return this; } -} - -/** @class Option @description Represents a command option (string, number, boolean, channel, choice, flag) with validation and formatting. */ -export class Option { - /** @type {number} @description Maximum choices before switching to compact format. */ - static THRESHOLD = 10; - /** @type {number} @description Number of choice columns per line in compact format. */ - static COLS_PER_LINE = 5; - - /** Format choice values in a compact multi-column layout. @param {string[]} choices @param {number} [perLine=Option.COLS_PER_LINE] @returns {string} */ - static formatChoicesCompact(choices, perLine = Option.COLS_PER_LINE) { - const lines = []; - for (let i = 0; i < choices.length; i += perLine) { - lines.push(choices.slice(i, i + perLine).map(c => '`' + c + '`').join(' · ')); - } - return lines.join('\n'); - } - - /** Format choice values inline, switching to compact layout above the threshold. @param {string[]} choices @returns {string} */ - static formatChoicesInline(choices) { - if (choices.length <= Option.THRESHOLD) { - return '`' + choices.join('`, `') + '`'; - } - return Option.formatChoicesCompact(choices, 6); - } - - /** Format choice values for a usage string, truncating with "…" if over max. @param {string[]} choices @param {number} [max=6] @returns {string} */ - static formatChoicesUsage(choices, max = 6) { - if (choices.length <= max) return choices.join(' | '); - return choices.slice(0, max).join(' | ') + ' | ...'; - } - channelRegex = /^<#(?\d+)>/; - userRegex = /^<@!?(?\d+)>/; - idRegex = /^(?\d+)/; - - /** @type {Function|null} Dynamic default value resolver. */ - dynamicDefault; - - /** Create a new Option. @param {string} [type="string"] */ - constructor(type = "string") { - this.name = null; - this.description = null; - this.required = false; - this.id = null; - this.uid = Utils.uid(); - this.type = type; - this.tError = null; - this.aliases = [null]; - this.choices = []; - this.translations = {}; - this.defaultValue = null; - this.dynamicDefault = null; - } - - /** Factory to create an Option or Flag instance. @param {string} type @param {boolean} [flag=false] @returns {Option|Flag} */ - static create(type, flag = false) { - return (!flag) ? new Option(type) : new Flag(type); - } - - /** Set the option name. @param {string} n @returns {Option} */ - setName(n) { this.name = n; this.aliases[0] = n; return this; } - /** Set the option description. @param {string} d @returns {Option} */ - setDescription(d) { this.description = d; return this; } - /** Set whether the option is required. @param {boolean} r @returns {Option} */ - setRequired(r) { this.required = r; return this; } - /** Set the option ID. @param {string} id @returns {Option} */ - setId(id) { this.id = id; return this; } - /** Set the option type. @param {string} t @returns {Option} */ - setType(t) { this.type = t; return this; } - /** Add flag aliases (e.g. "v" for "-v"). @param {...string} a @returns {Option} */ - addFlagAliases(...a) { this.aliases.push(...a); return this; } - /** Add a single valid choice value. @param {string} c @returns {Option} @throws {Error} If option type is not "choice". */ - addChoice(c) { if (this.type !== "choice") throw new Error(".addChoice is only available for choice options!"); this.choices.push(c); return this; } - /** Add multiple valid choice values. @param {...string} cs @returns {Option} @throws {Error} If option type is not "choice". */ - addChoices(...cs) { if (this.type !== "choice") throw new Error(".addChoices is only available for choice options!"); cs.forEach(c => this.addChoice(c)); return this; } - /** Set the default value when the option is omitted. @param {*} value @returns {Option} */ - setDefault(value) { this.defaultValue = value; return this; } - /** Set a dynamic default resolver function. @param {Function} callback @returns {Option} */ - setDynamicDefault(callback) { this.dynamicDefault = callback; return this; } - - /** Check whether a value is considered empty/omitted. @param {*} i @returns {boolean} */ - empty(i) { - if (i === undefined || i === null) return true; - return (!i && !(String(i).includes("0"))); - } - - /** Validate an input value for this option type. @param {*} i @param {object} client @param {object} msg @param {string} [type] @returns {boolean} */ - validateInput(i, client, msg, type) { - switch (type || this.type) { - case "text": - case "string": - return !!i; - case "number": - return !isNaN(i) && !isNaN(parseFloat(i)); - case "boolean": - return i === "0" || i === "1" || i?.toLowerCase() === "true" || i?.toLowerCase() === "false"; - case "choice": - return this.choices.includes(i); - case "user": - return this.userRegex.test(i) || this.idRegex.test(i); - case "channel": - if (i === undefined) return false; - return this.channelRegex.test(i) || this.idRegex.test(i) || client.channels.some(c => c.name === i); - case "voiceChannel": { - if (!i) return false; - const results = this.channelRegex.exec(i) ?? this.idRegex.exec(i); - const guildId = msg?.channel?.guildId ?? msg?.guildId; - - 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"]) - : (byName ?? null); - return cObj ? voiceTypes.includes(cObj.type) : false; - } - } - } - - /** Format/parse an input value for this option type. @param {*} i @param {object} client @param {object} msg @param {string} [type] @returns {*} */ - formatInput(i, client, msg, type) { - switch (type || this.type) { - case "text": - case "string": - return i; - case "number": - return parseFloat(i); - case "boolean": - return i?.toLowerCase() === "true" || i === "1"; - case "choice": - return i; - case "user": { - const rs = this.userRegex.exec(i) ?? this.idRegex.exec(i); - return rs?.groups["id"] ?? null; - } - case "channel": { - const results = this.channelRegex.exec(i) ?? this.idRegex.exec(i); - const channel = client.channels.find(c => c.name === i); - return results ? results.groups["id"] : (channel ? channel.id : null); - } - case "voiceChannel": { - const r = this.channelRegex.exec(i) ?? this.idRegex.exec(i); - const guildId = msg?.channel?.guildId ?? msg?.guildId; - if (guildId === "eval") return r ? r.groups["id"] : (i || null); - const voiceTypes = [2, 13]; - const c = msg?.guild?.channels?.find(c => c.name === i && voiceTypes.includes(c.type)); - return r ? r.groups["id"] : (c ? c.id : null); - } - } - } - - /** Generate a type-error message for this option. @returns {string} */ - get typeError() { - if (this.tError) return this.tError; - switch (this.type) { - case "choice": { - const choiceStr = this.choices.length > Option.THRESHOLD - ? Option.formatChoicesCompact(this.choices) - : this.choices.map(c => '- ' + c).join('\n'); - return "Invalid value '$currValue'. The option `" + this.name + "` has to be one of the following: \n" + choiceStr + "\nSchematic: `$previousCmd <" + this.type + ">`"; - } - case "voiceChannel": - case "channel": - return "Invalid value '$currValue'. The option `" + this.name + "` has to be a channel mention, id, or name.\nSchematic: `$previousCmd <" + this.type + ">`"; - default: - return "Invalid value '$currValue'. The option `" + this.name + "` has to be of type `" + this.type + "`.\nSchematic: `$previousCmd <" + this.type + ">`"; - } - } - /** Set a custom type-error message template. @param {string} e */ - set typeError(e) { this.tError = e; } -} - -/** @class Flag @description A flag-type option that cannot be text. Extends Option. */ -export class Flag extends Option { - /** Create a Flag (non-text option). @param {string} [type="string"] */ - constructor(type = "string") { - if (type === "text") throw new Error("Flags can't be of type 'text'!"); - super(type); - } -} - -/** @class PrefixManager @description Manages per-guild command prefixes (falling back to config or default). */ -export class PrefixManager { - /** @type {RemoteSettingsManager} */ - settings; - /** @type {string|null} */ - configPrefix; - /** @param {RemoteSettingsManager} settings @param {string|null} [configPrefix=null] */ - constructor(settings, configPrefix = null) { this.settings = settings; this.configPrefix = configPrefix; } - /** Get the command prefix for a guild. @param {string} guildId @returns {string} */ - getPrefix(guildId) { - const serverPrefix = this.settings.getServer(guildId).get("prefix"); - return serverPrefix ?? this.configPrefix ?? "%"; - } -} - -/** @class HelpHandler @description Generates paginated help text for commands. */ -export class HelpHandler { - /** @type {CommandHandler} */ - commands; - /** @type {number} Commands per help page. */ - commandsPerPage = 5; - - /** Default pagination handler that builds paginated help pages. @param {object} msg - Message wrapper with message data. @param {HelpHandler} helpHandler @param {Array} cmds @returns {string|null} */ - paginationHandler = (msg, helpHandler, cmds) => { - const guildId = msg.message.guildId; - let form = this.commands.t(guildId, "cmdHandler.help.pageStructure"); - - const contents = cmds.map((cmd, i) => { - return (i + 1) + ". **" + cmd.name + "**: " + (cmd.description || "").split("\n")[0]; - }); - - const pages = new PageBuilder(contents) - .setForm(helpHandler.commands.format(form, msg.message.guildId)) - .setMaxLines(helpHandler.commandsPerPage); - - helpHandler.commands.messages.initPagination(pages, msg); - return null; - } - - /** @type {Function|null} Custom help handler function override. */ - customHelpHandler = null; - - /** @param {CommandHandler} commands */ - constructor(commands) { this.commands = commands; } - - /** @param {string} string @returns {string} Capitalised first letter. */ - static capitalise(string) { - if (string.length < 1) return string; - if (string.length === 1) return string.toUpperCase(); - return string.charAt(0).toUpperCase() + string.slice(1); - } - - /** @param {Array} [cmds] @returns {Array} Non-owner-only commands. */ - userCommands(cmds) { - return (cmds || this.commands.commands).filter(c => - c.requirements.findIndex(r => r.ownerOnly) === -1 - ); - } - - /** @returns {number} Total number of help pages. */ - pageNumber() { - return Math.ceil(this.commands.commands.length / this.commandsPerPage); - } - - /** @param {object} message @returns {string|null} */ - help(message) { - if (this.customHelpHandler) return this.customHelpHandler(message); - if (this.paginationHandler) return this.genHelp(null, message, true); - return this.getHelpPage(0, message); - } - - /** @param {number} n @param {object} msg @param {Array} [cmds=null] @returns {string} */ - getHelpPage(n, msg, cmds = null) { - if (!cmds) cmds = this.commands.commands; - if (!(this.commandsPerPage < cmds.length)) return this.genHelp(null, msg, false, cmds); - let offset = this.commandsPerPage * n; - const commands = cmds.slice(offset, offset + this.commandsPerPage); - let max = Math.ceil(cmds.length / this.commandsPerPage); - return this.genHelp({ curr: n + 1, max, offset }, msg, false, commands); - } - - /** @param {object|null} page @param {object} msg @param {boolean} [paginate=false] @param {Array} [cmds=null] @returns {string} */ - genHelp(page, msg, paginate = false, cmds = null) { - cmds = this.userCommands(cmds); - if (this.paginationHandler && msg && paginate) return this.paginationHandler(msg, this, cmds); - - const guildId = msg.message.guildId; - let p = (page) ? ` (page ${page.curr}/${page.max})` : ""; - const indexOffset = (page) ? page.offset : 0; - let content = this.commands.t(guildId, "cmdHandler.help.availableCommands", { $page: p }) + "\n\n"; - if (page && page.curr !== 1) content += (indexOffset) + this.commands.t(guildId, "cmdHandler.help.ellipsis") + "\n"; - cmds.forEach((cmd, i) => { content += (i + 1 + indexOffset) + ". **" + cmd.name + "**: " + cmd.description + "\n"; }); - if (page && page.curr !== page.max) content += (cmds.length + indexOffset) + this.commands.t(guildId, "cmdHandler.help.ellipsis") + "\n"; - content += this.commands.format(this.commands.t(guildId, "cmdHandler.help.runHelp"), guildId); - if (page) content += this.commands.format(this.commands.t(guildId, "cmdHandler.help.pageTip"), guildId); - - return this.commands.format(content, guildId); - } - - /** Get the description of a command. @param {CommandBuilder} command @returns {string} */ - commandDescription(command) { return command.description; } - - /** Build a usage string for a command including options and flags. @param {CommandBuilder} cmd @param {object} msg @returns {string} */ - commandUsage(cmd, msg) { - if (cmd.subcommands.length > 0) { - return this.commands.format("$prefix" + cmd.command, msg.message.guildId) + " <" + cmd.subcommands.map(e => e.name).join(" | ") + "> [...]"; - } - let options = this.commands.format("$prefix" + cmd.command, msg.message.guildId); - cmd.options.forEach(o => { - if (o.type === "text") return; - if (o instanceof Flag) - return options += (o.type === "choice") ? "-" + o.aliases[0] + " <" + Option.formatChoicesUsage(o.choices) + ">" : " -" + o.aliases[0] + " '" + o.type + "'"; - options += (o.type === "choice") ? " <" + Option.formatChoicesUsage(o.choices) + ">" : " '" + o.name + ": " + o.type + "'"; - }); - let o = cmd.options.find(e => e.type === "text"); - if (o) options += "'" + o.name + ": " + o.type + "'"; - return options.trim(); - } - - /** Generate detailed help for a single command. @param {object} command @param {object} msg @returns {string} */ - getCommandHelp(command, msg) { - const guildId = msg.message.guildId; - let content = `${HelpHandler.capitalise(command.name)}\n`; - content += this.commandDescription(command, msg) + "\n\n"; - content += this.commands.t(guildId, "cmdHandler.help.usage") + "\n💻 `" + this.commandUsage(command, msg) + "`\n\n"; - if (command.examples.length > 0) - content += this.commands.t(guildId, "cmdHandler.help.examples") + "\n- `" + command.examples.map(e => this.commands.format(e, guildId)).join("`\n- `") + "`\n\n"; - if (command.aliases.length > 1) { - content += this.commands.t(guildId, "cmdHandler.help.aliases") + "\n"; - command.aliases.forEach(alias => { content += "- " + alias + "\n"; }); - content += "\n"; - } - if (command.subcommands.length > 0) { - content += this.commands.t(guildId, "cmdHandler.help.subcommands") + "\n"; - command.subcommands.forEach(s => { - const optCount = s.options.length > 0 ? "; (`" + this.commands.t(guildId, "cmdHandler.help.optionCount", { $count: s.options.length }) + "`)" : ""; - content += "- " + s.name + ": " + (this.commandDescription(s, msg) || "").split("\n")[0] + optCount + "\n"; - }); - content += "\n"; - } else if (command.options.length > 0) { - content += this.commands.t(guildId, "cmdHandler.help.arguments") + "\n"; - command.options.forEach(o => { - const optional = ((o.required) ? "" : "?"); - const flag = (o instanceof Flag) ? "-" : ""; - if (o.type === "choice") { - const choiceDisplay = Option.formatChoicesInline(o.choices); - const aliasDisplay = o.aliases.filter(a => a !== null).join('`, `'); - content += "- **" + flag + o.name + "**" + optional + ": " + (o.description || "").split("\n")[0] + ";\n - " + this.commands.t(guildId, "cmdHandler.help.allowedValues") + choiceDisplay + "\n - " + this.commands.t(guildId, "cmdHandler.help.aliasesLabel") + "`" + aliasDisplay + "`\n"; - } else { - content += "- **" + flag + o.name + "**" + optional + ": " + (o.description || "").split("\n")[0] + "\n - " + this.commands.t(guildId, "cmdHandler.help.aliasesLabel") + "`" + o.aliases.join("`, `") + "`\n"; - } - content += "\n"; - }); - content += "\n"; - } - if (command.requirements.length > 0) { - content += this.commands.t(guildId, "cmdHandler.help.requirements") + "\n"; - command.requirements.forEach(r => { - content += "- " + r.getPermissions().map(e => this.commands.t(guildId, "cmdHandler.help.permission", { $permission: e })).join("\n- "); - }); - } - return content.trim(); - } -} - -/** @class CommandHandler @description Main command dispatcher. Parses incoming messages, matches commands, validates arguments, checks permissions, and emits run events. @extends {EventEmitter} */ -export class CommandHandler extends EventEmitter { - /** @type {Function|null} Custom handler when the bot is pinged. */ - onPing = null; - /** @type {boolean} Whether the bot responds to pings as a prefix. */ - pingPrefix = true; - /** @type {string[]} Bot owner user IDs. */ - owners = []; - - messages; - client; - prefixes; - helpHandler; - - commandNames = []; - commands = []; - - locale = null; - 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."; - - /** @private @type {Map} Per-user last command timestamps for cooldown enforcement. */ - _cmdCooldowns = new Map(); - /** @private @type {number} Cooldown duration in milliseconds between commands per non-owner user. */ - _cmdCooldownMs = 1500; - - /** @param {MessageHandler} handler - The message handler instance. @param {string} [prefix="%"] - Default command prefix. */ - constructor(handler, prefix = "%") { - super(); - this.messages = handler; - this.client = handler.client; - this.prefix = prefix; - this.helpHandler = new HelpHandler(this); - this.helpCommand = "help"; - this.replyHandler = (message, msg) => { - msg.reply(this.format(message, msg.channel.channel.guildId)); - }; - this.messages.onMessage(this.messageHandler.bind(this)); - } - - /** Get the command prefix for a guild. @param {string} guildId @returns {string} */ - getPrefix(guildId) { return this.prefixes.getPrefix(guildId); } - /** Enable or disable ping-as-prefix. @param {boolean} bool */ - setPingPrefix(bool) { this.pingPrefix = bool; } - /** Set the prefix manager instance. @param {PrefixManager} manager */ - setPrefixManager(manager) { this.prefixes = manager; } - /** Set a custom help handler. @param {HelpHandler} handler */ - setHelpHandler(handler) { this.helpHandler = handler; } - /** Set the locale manager. @param {object} locale */ - setLocale(locale) { this.locale = locale; } - - /** Translate a locale key. @param {string} guildId @param {string} key @param {object} [replacements={}] @returns {string} */ - t(guildId, key, replacements = {}) { - if (!this.locale) return key; - return this.locale.translate(guildId, key, replacements); - } - - /** Replace $prefix and $helpCmd placeholders in text. @param {string} text @param {string} guildId @returns {string} */ - format(text, guildId) { - const prefix = (!guildId) ? this.prefix : this.getPrefix(guildId); - return text - .replace(/\$prefix/gi, prefix) - .replace(/\$helpCmd/gi, this.helpCommand); - } - - /** Remove a command from the registry. @param {CommandBuilder} command */ - removeCommand(command) { - command.aliases.forEach(a => { - const idx = this.commandNames.indexOf(a); - if (idx !== -1) this.commandNames.splice(idx, 1); - }); - const idx = this.commands.findIndex(c => c.uid === command.uid); - if (idx !== -1) this.commands.splice(idx, 1); - } - - /** @private Handle an incoming message and route to command processing. @param {Message} msg */ - messageHandler(msg) { - if (!msg || !msg.content) return; - const trimmed = msg.content.trim(); - if (/^<@!?\d+>$/.test(trimmed)) { - const botId = this.client.user?.id; - if (botId && (trimmed === `<@${botId}>` || trimmed === `<@!${botId}>`)) { - return this.onPing?.(msg); - } - return; - } - - const guildId = msg.channel?.channel?.guildId ?? msg.message?.guildId; - const prefix = this.getPrefix(guildId); - const ping = `<@${this.client.user?.id}>`; - const pingBang = `<@!${this.client.user?.id}>`; - if (!(msg.content.startsWith(prefix) || msg.content.startsWith(ping) || msg.content.startsWith(pingBang))) return; - - const 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); - if (this._cmdCooldowns.size > 500) { - const cutoff = now - this._cmdCooldownMs * 2; - for (const [uid, ts] of this._cmdCooldowns) { - if (ts < cutoff) this._cmdCooldowns.delete(uid); - } - } - } - - const len = msg.content.startsWith(prefix) ? prefix.length : (msg.content.startsWith(pingBang) ? pingBang.length : ping.length); - const args = msg.content.slice(len).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim()); - - if (!args[0]) return; - - if (args[0] === this.helpCommand) { - if (!args[1]) { - const res = this.helpHandler.help(msg); - return (typeof res === "string") ? this.replyHandler(res, msg) : undefined; - } - if (args.length > 1 && Utils.isNumber(args[1])) { - const pageNumber = parseInt(args[1]); - if (pageNumber < 1 || pageNumber > this.helpHandler.pageNumber()) { - return this.replyHandler(this.t(guildId, "cmdHandler.page.invalid", { number: pageNumber }), msg); - } - return this.replyHandler(this.helpHandler.getHelpPage(pageNumber - 1, msg), msg); - } - if (args.length <= 2) { - let idx = this.commands.findIndex(e => e.aliases.some(al => al.toLowerCase() === args[1].toLowerCase())); - if (idx === -1) return this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix" + args[1], guildId) }), msg); - return this.replyHandler(this.helpHandler.getCommandHelp(this.commands[idx], msg), msg); - } - let currCmd = null; - let prefix2 = ""; - for (let i = 0; i < args.slice(1).length; i++) { - let a = args.slice(1)[i]; - let curr = (currCmd) ? currCmd.subcommands : this.commands; - let idx = curr.findIndex(e => e.aliases.some(al => al.toLowerCase() === a.toLowerCase())); - if (idx === -1) return this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix" + prefix2 + a, guildId) }), msg); - currCmd = curr[idx]; - prefix2 += a + " "; - } - return this.replyHandler(this.helpHandler.getCommandHelp(currCmd, msg), msg); - } - - if (!this.commandNames.includes(args[0].toLowerCase())) { - this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix$helpCmd", guildId) }), msg); - return; - } - return this.processCommand(this.commands.find(e => e.aliases.includes(args[0].toLowerCase())), args, msg); - } - - /** Parse and execute a command with its options. @param {CommandBuilder} cmd @param {string[]} args @param {Message} msg @param {string|boolean} [previous=false] @param {boolean} [external=false] @returns {object|undefined} */ - processCommand(cmd, args, msg, previous = false, external = false) { - if (!cmd) return logger.warn("[CommandHandler.processCommand] Invalid case: `cmd` falsy."); - - if (!external) { - const channel = msg.channel?.channel ?? msg.channel; - if (channel?.guild) { - const botPermResult = this.messages.checkAllBotPermissions(channel); - if (botPermResult.criticalMissing.length > 0) { - const permEmbed = this.messages.buildPermissionEmbed(botPermResult.missing, channel.guildId); - try { - msg.message?.reply?.({ embeds: [permEmbed] }, { ping: false }); - } catch (_) { - 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 }); - } catch (__) { logger.warn("[CommandHandler] Fallback perm reply failed"); } - } - return; - } - } - } - - if (cmd.requirements.length > 0 && !external) { - if (!this.assertRequirements(cmd, msg)) return; - } - if (previous === false) previous = this.format("$prefix" + cmd.name, msg.channel?.channel?.guildId); - if (!external) this.emit("command", { command: cmd, message: msg }); - - if (cmd.subcommands.length !== 0) { - const idx = cmd.subcommands.findIndex(el => { - if (!args[1]) return false; - return el.name.toLowerCase() === args[1].toLowerCase(); - }); - if (idx === -1) { - const list = cmd.subcommands.map(s => s.name).join(" | "); - const subGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId; - const e = this.t(subGuildId, "cmdBuilder.subcommand.invalid").replace(/\$previousCmd/gi, previous).replace(/\$cmdList/gi, list); - return (!external) ? this.replyHandler(e, msg) : e; - } - return this.processCommand(cmd.subcommands[idx], args.slice(1), msg, previous + this.format(" " + cmd.subcommands[idx].name), external); - } - - const opts = []; - const texts = []; - - /** @private Collect quoted arguments spanning multiple tokens. @param {number} index @param {string} currVal @param {string[]} as @returns {{args: string[], index: number}|null} */ - const collectArguments = (index, currVal, as) => { - const lastChar = currVal.charAt(currVal.length - 1); - if (lastChar === '"') return { args: as, index }; - const a = args[++index]; - if (!a) return null; - as.push(a); - return collectArguments(index, a, as); - }; - - const options = cmd.options.slice().sort((a, b) => { - const aText = (a.type === "text") ? 1 : 2; - const bText = (b.type === "text") ? 1 : 2; - return aText - bText; - }); - - const STRING_TYPES = ["string", "text", "channel", "voiceChannel"]; - const usedOptions = []; - let usedArgumentCount = 0; - - for (let i = 0, argIndex = 1; i < options.length; i++) { - const o = options[i]; - if (o?.type === "text") { texts.push(o); continue; } - if ((args[argIndex] || "").startsWith("-")) { - const flagName = args[argIndex].slice(1); - const op = cmd.options.find(e => e.aliases.includes(flagName)); - if (!op) { - const flagGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId; - const error = this.t(flagGuildId, "cmdHandler.invalidFlag").replace(/\$previousCmd/gi, previous).replace(/\$invalidFlag/gi, "-" + flagName); - return (!external) ? this.replyHandler(error, msg) : error; - } - previous += " " + args[argIndex]; - let value = args[++argIndex]; - if ((value || "").startsWith('"') && (STRING_TYPES.includes(op.type))) { - const data = collectArguments(argIndex, value, [value]); - if (!data) { const twGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId; return this.replyHandler(this._textWrapErrorMsg(twGuildId, args.slice(argIndex).join(" "), args[argIndex].charAt(0)), msg); } - argIndex += data.index - argIndex; - const _joined = data.args.join(" "); - value = _joined.slice(1, _joined.length - 1); - } - argIndex++; - i--; - const valid = op.validateInput(value, this.client, msg.message); - if (!valid && (op.required || !op.empty(value))) { - const errGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId; - const e = this._optionTypeError(errGuildId, op, value, previous); - return (!external) ? this.replyHandler(e, msg) : e; - } - usedArgumentCount += 2; - previous += " " + value; - opts.push({ value: op.formatInput(value, this.client, msg.message), name: op.name, id: op.id, uid: op.uid }); - usedOptions.push(op.uid); - continue; - } - - if (!o) continue; - if (o instanceof Flag) continue; - if (opts.findIndex(op => op.uid === o.uid) !== -1) continue; - let value = args[argIndex]; - if ((args[argIndex] || "").startsWith('"') && (STRING_TYPES.includes(o.type))) { - const data = collectArguments(argIndex, args[argIndex], [args[argIndex]]); - if (!data) { const twGuildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId; return this.replyHandler(this._textWrapErrorMsg(twGuildId2, args.slice(argIndex).join(" "), args[argIndex].charAt(0)), msg); } - argIndex += data.index - argIndex; - value = data.args.join(" "); - value = value.slice(1, value.length - 1); - } - let valid = o.validateInput(value, this.client, msg.message); - if (!valid && o.dynamicDefault) { - value = o.dynamicDefault(this.client, msg); - valid = o.validateInput(value, this.client, msg.message); - } - if (!valid && (o.required || !o.empty(value))) { - const errGuildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId; - const e = this._optionTypeError(errGuildId2, o, value, previous); - return (!external) ? this.replyHandler(e, msg) : e; - } - if (o.empty(value)) value = o.defaultValue; - opts.push({ value: o.formatInput(value, this.client, msg.message), name: o.name, id: o.id, uid: o.uid }); - usedOptions.push(o.uid); - previous += " " + value; - argIndex++; - usedArgumentCount++; - } - - if (texts.length > 0) { - let o = texts[0]; - let text = args.slice(usedArgumentCount + 1).join(" "); - if (o.required && !o.validateInput(text, this.client, msg.message)) { - const textErrGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId; - let e = this._optionTypeError(textErrGuildId, o, text, previous); - return (!external) ? this.replyHandler(e, msg) : e; - } - const quote = (['"', "'"].includes(text.charAt(0))) ? text.charAt(0) : null; - if (quote && text.charAt(text.length - 1) === quote) text = text.slice(1, text.length - 1); - opts.push({ name: o.name, value: text, id: o.id, uid: o.uid }); - usedOptions.push(o.uid); - } - - options.filter(o => !usedOptions.includes(o.uid)).forEach(o => { - if (!o.defaultValue) return; - opts.push({ name: o.name, value: o.defaultValue, id: o.id, uid: o.uid }); - }); - - const commandRunData = { - command: cmd, - commandId: cmd.id, - options: opts, - message: msg, - get: function (oName) { return this.options.find(o => o.name === oName); }, - getById: function (id) { return this.options.find(o => o.id === id); } - }; - if (!external) this.emit("run", commandRunData); - return commandRunData; - } - - /** Check whether the message author meets all command requirements (owner, permissions). @param {CommandBuilder} cmd @param {Message} msg @returns {boolean} */ - assertRequirements(cmd, msg) { - const authorId = msg.message?.author?.id; - const isOwner = this.owners.includes(authorId); - const permGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId; - - for (let i = 0; i < cmd.requirements.length; i++) { - let req = cmd.requirements[i]; - if (req.ownerOnly && !isOwner) return false; - if (req.permissions.length > 0 && !isOwner) { - const guild = msg.message?.guild ?? null; - if (!guild) { - this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg); - return false; - } - - const member = guild.members.get(authorId) ?? null; - if (member?.permissions) { - 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 { - const fetchPromise = typeof guild.fetchMember === "function" - ? guild.fetchMember(authorId) - : typeof guild.members?.fetch === "function" - ? guild.members.fetch(authorId) - : Promise.reject(new Error("No member fetch API available")); - fetchPromise.then(member => { - 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); - } else { - 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()); - this.processCommand(cmd, args, msg, false, true); - } - }).catch(() => this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg)); - return false; - } - } - } - return true; - } - - /** Validate an input for a given option type. @param {string} type @param {*} i @param {object} m @returns {boolean} */ - validateInput(type, i, m) { return (new Option()).validateInput(i, this.client, m, type); } - /** Format an input for a given option type. @param {string} type @param {*} i @param {object} m @returns {*} */ - formatInput(type, i, m) { return (new Option()).formatInput(i, this.client, m, type); } - - /** @private Build a type-error message for an option. @param {string} guildId @param {Option} option @param {*} value @param {string} previous @returns {string} */ - _optionTypeError(guildId, option, value, previous) { - if (option.tError) { - return option.tError.replace(/\$previousCmd/gi, previous).replace(/\$currValue/gi, value); - } - const localeKey = option.type === 'choice' ? 'cmdBuilder.option.invalidChoice' - : (option.type === 'channel' || option.type === 'voiceChannel') ? 'cmdBuilder.option.invalidChannel' - : 'cmdBuilder.option.invalidType'; - const choiceStr = option.type === 'choice' - ? (option.choices.length > Option.THRESHOLD ? Option.formatChoicesCompact(option.choices) : option.choices.map(c => '- ' + c).join('\n')) - : ''; - return this.t(guildId, localeKey, { - $currValue: value, - $optionName: option.name, - $type: option.type, - $choices: choiceStr - }).replace(/\$previousCmd/gi, previous); - } - - /** @private Build a text-wrap error message. @param {string} guildId @param {string} value @param {string} quote @returns {string} */ - _textWrapErrorMsg(guildId, value, quote) { - return this.t(guildId, 'cmdHandler.textWrapError', { $value: value, $quote: quote }); - } - - /** Register a command builder and sort the command list alphabetically. @param {CommandBuilder} builder @returns {CommandBuilder[]} */ - addCommand(builder) { - this.commandNames.push(...builder.aliases); - this.commands.push(builder); - this.commands.sort((a, b) => { - let A = a.name.toUpperCase(); - let B = b.name.toUpperCase(); - return (A < B) ? -1 : (A > B) ? 1 : 0; - }); - return this.commands; - } -} - -/** @class CommandLoader @description Dynamically loads command files from a directory, registers builders, and binds run handlers. */ -export class CommandLoader { - /** @type {CommandHandler} Reference to the command handler. */ - commands; - /** @type {Map} Command UID → file path. */ - commandFiles = new Map(); - /** @type {Map} Command UID → run function. */ - runnables = new Map(); - /** @type {object} Shared context (the bot instance). */ - context; - - /** @param {CommandHandler} commands @param {object} context - Bot context object. */ - constructor(commands, context) { - this.commands = commands; - this.context = context; - this.context.loader ??= this; - this.context.commandFiles = this.commandFiles; - this.context.runnables = this.runnables; - - this.commands.on("run", (data) => { - if (!this.runnables.has(data.command.uid)) return; - const runFc = this.runnables.get(data.command.uid); - const sendErrorReply = (id) => { - Promise.resolve(data.message.reply("An error occurred. Error id: `#" + id + "`")) - .catch(err => logger.warn("[CommandHandler] Failed to send error-reply; error id #" + id + ":", err?.message)); - }; - try { - const result = runFc.call(this.context, data.message, data); - if (result && typeof result.catch === "function") { - result.catch(e => { - const id = Utils.uid(); - logger.error("Error running command; error id #" + id, e); - sendErrorReply(id); - }); - } - } catch (e) { - const id = Utils.uid(); - logger.error("Error running command; error id #" + id, e); - sendErrorReply(id); - } - }); - } - - /** Normalize a module export to { command, run, exportDef }. @param {object} cData @returns {object} */ - canonData(cData) { - if (cData.command !== undefined) { - return { - command: cData.command, - run: cData.run, - exportDef: cData.exportDef ?? cData.export ?? null - }; - } - const d = cData.default ?? cData; - return { - command: d.command, - run: d.run, - exportDef: d.exportDef ?? d.export ?? null - }; - } - - /** @async Load all command files from a directory. @param {string} dir @returns {Promise} */ - loadFromDir(dir) { - const files = fs.readdirSync(dir) - .filter(f => !f.startsWith(".") && (f.endsWith(".js") || f.endsWith(".mjs"))); - - return Promise.all(files.map(async commandFile => { - const file = path.join(dir, commandFile); - - const cData = this.canonData(await import(pathToFileURL(file).href)); - - const builder = (typeof cData.command === "function") - ? cData.command.call(this.context) - : cData.command; - - if (!builder) return logger.warn("No builder returned. Skipping '" + commandFile + "'"); - - if (cData.exportDef) - this.context[cData.exportDef.name] = cData.exportDef.object; - - this.commands.addCommand(builder); - this.commandFiles.set(builder.uid, file); - - if (!cData.run) return; - - this.runnables.set(builder.uid, cData.run); - builder.subcommands.forEach(sub => { - this.runnables.set(sub.uid, cData.run); - }); - })); - } -} diff --git a/src/FluxerAudioBridge.mjs b/src/FluxerAudioBridge.mjs deleted file mode 100644 index 479a19a..0000000 --- a/src/FluxerAudioBridge.mjs +++ /dev/null @@ -1,879 +0,0 @@ -/** @module src/FluxerAudioBridge @description Audio bridge for streaming Lavalink/NodeLink audio through Fluxer voice connections. 100% in-process — Opus encoding via prism-media (native/WASM), WebM muxing via WebMOpusMuxer. No FFmpeg processes. Supports MP3/AAC/radio streams via Lavalink resolve-through. */ - -import { logger } from "./constants/Logger.mjs"; -import { WebMOpusMuxer, OPUS_FRAME_MS } from "./constants/audio/WebMOpusMuxer.mjs"; -import { EventEmitter } from "node:events"; -import { Readable } from "node:stream"; -import http from "node:http"; -import https from "node:https"; -import prismMedia from "prism-media"; - -const { Encoder: PrismOpusEncoder, OggDemuxer: PrismOggDemuxer } = prismMedia.opus; - -/** @type {number} @description Maximum number of HTTP redirect hops to follow. */ -const MAX_REDIRECTS = 5; - -/** @type {number} @description Timeout (ms) for HTTP requests to Lavalink REST endpoints (trackstream, loadtracks JSON). */ -const REST_REQUEST_TIMEOUT_MS = 15_000; - -/** @type {number} @description Timeout (ms) to wait for the first byte from loadstream (Lavalink may need time to resolve HLS/external streams). */ -const LOADSTREAM_CONNECT_TIMEOUT_MS = 60_000; - -/** @type {number} @description Idle timeout (ms) once loadstream data is flowing — if no data arrives for this long, abort. */ -const LOADSTREAM_IDLE_TIMEOUT_MS = 30_000; - -/** @type {number} @description PCM sample rate expected from NodeLink loadstream (48kHz stereo s16le). */ -const PCM_RATE = 48000; -/** @type {number} @description PCM channel count expected from NodeLink loadstream. */ -const PCM_CHANNELS = 2; -/** @type {number} @description Opus frame size in samples per channel (20ms @ 48kHz). */ -const PCM_FRAME_SIZE = 960; -/** @type {number} @description Opus encoding bitrate. */ -const OPUS_BITRATE = 128000; - -/** @type {Buffer} @description WebM/Matroska EBML magic bytes. */ -const WEBM_MAGIC = Buffer.from([0x1a, 0x45, 0xdf, 0xa3]); -/** @type {Buffer} @description OGG container magic bytes ("OggS"). */ -const OGG_MAGIC = Buffer.from("OggS", "ascii"); - -/** @type {number} @description livekit TrackKind.KIND_AUDIO — publications with this kind are managed by the bridge. */ -const TRACK_KIND_AUDIO = 1; - -/** @extends {EventEmitter} */ -export class FluxerAudioBridge extends EventEmitter { - _conn = null; - _stream = null; - _encoder = null; - _sourceStream = null; - _sourceReq = null; - _playing = false; - _stopped = false; - _startedAt = 0; - _currentUri = null; - _lavalink = null; - _playGeneration = 0; - _durationTimer = null; - _endResolve = null; - _endReject = null; - _usedTrackstream = false; - - /** @type {boolean} @description Whether audio is currently playing. */ - get playing() { return this._playing; } - /** @type {number} @description Timestamp (ms) when playback started. */ - get startedAt() { return this._startedAt; } - /** @type {string|null} @description URI of the currently playing track. */ - get currentUri() { return this._currentUri; } - - /** @param {LavalinkManager|null} lavalinkManager - LavalinkManager for trackstream/loadstream. */ - constructor(lavalinkManager = null) { - super(); - this._lavalink = lavalinkManager; - } - - /** - * Play a track through a Fluxer voice connection, entirely in-process. - * Routing order: - * 1. trackstream passthrough (seek=0, no filters) — NodeLink hands back a WebM/Opus - * direct URL which the voice connection plays natively (zero re-encode). - * 2. loadstream — NodeLink returns raw PCM (48k stereo s16le) with server-side - * seek/filters; PCM is Opus-encoded in-process and muxed to WebM. - * 3. direct URL fallback — magic-byte sniff: WebM passthrough or Ogg/Opus remux. - * @param {object} conn - Fluxer voice connection - * @param {object} trackInfo - Track metadata (encoded, title, url, guildId) - * @param {object} [options] - * @param {number} [options.seekSeconds=0] - * @param {number} [options.durationMs=0] - * @param {object} [options.filterPayload] - * @returns {Promise<"finished"|"stopped">} - */ - async play(conn, trackInfo, options = {}) { - this.stop(); - if (!conn) throw new Error("[AudioBridge] No voice connection provided"); - - this._unpublishStaleAudioTracks(conn); - - const generation = ++this._playGeneration; - this._conn = conn; - this._playing = true; - this._stopped = false; - this._startedAt = Date.now(); - this._currentUri = trackInfo?.url ?? trackInfo?.title ?? "unknown"; - this._usedTrackstream = false; - - const seekMs = Math.floor((options.seekSeconds ?? 0) * 1000); - let durationMs = options.durationMs || 0; - - try { - if (seekMs === 0 && !options.filterPayload && trackInfo.encoded && this._lavalink) { - try { - const direct = await this._getTrackstreamUrl(trackInfo); - if (direct?.url && /webm|opus/i.test(direct.format || "")) { - this._usedTrackstream = true; - logger.player("[AudioBridge] Passthrough webm/opus via trackstream (zero-copy): " + (trackInfo.title || "unknown")); - - await conn.play(direct.url); - if (generation !== this._playGeneration) return "stopped"; - - if (durationMs > 0) await this._waitDuration(durationMs); - if (generation !== this._playGeneration) return "stopped"; - - if (this._playing && !this._stopped) { - this._playing = false; - logger.player("[AudioBridge] Track finished naturally (trackstream passthrough)"); - return "finished"; - } - return "stopped"; - } - if (direct?.url && this._lavalink && trackInfo.url && trackInfo.url.startsWith("http")) { - logger.player("[AudioBridge] trackstream format " + (direct.format || "?") + " — resolving original source URL via Lavalink for fresh encoded track..."); - const freshEncoded = await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId); - if (freshEncoded) { - trackInfo.encoded = freshEncoded; - logger.player("[AudioBridge] Fresh encoded track obtained — retrying trackstream for webm/opus..."); - try { - const freshDirect = await this._getTrackstreamUrl(trackInfo); - if (freshDirect?.url && /webm|opus/i.test(freshDirect.format || "")) { - this._usedTrackstream = true; - logger.player("[AudioBridge] Fresh trackstream is webm/opus — zero-copy passthrough: " + (trackInfo.title || "unknown")); - await conn.play(freshDirect.url); - if (generation !== this._playGeneration) return "stopped"; - if (durationMs > 0) await this._waitDuration(durationMs); - if (generation !== this._playGeneration) return "stopped"; - if (this._playing && !this._stopped) { - this._playing = false; - logger.player("[AudioBridge] Track finished naturally (fresh trackstream passthrough)"); - return "finished"; - } - return "stopped"; - } - logger.player("[AudioBridge] Fresh trackstream also " + (freshDirect?.format || "?") + ", falling through to loadstream"); - } catch (e2) { - logger.player("[AudioBridge] Fresh trackstream failed, falling through to loadstream: " + e2.message); - } - } else { - logger.player("[AudioBridge] Could not resolve source URL via Lavalink, using original encoded track for loadstream"); - } - } else { - logger.player("[AudioBridge] trackstream format not opus/webm (" + (direct?.format || "?") + "), falling through to loadstream"); - } - } catch (e) { - logger.warn("[AudioBridge] Trackstream failed, falling back to loadstream: " + e.message); - this._playing = true; - this._stopped = false; - this._startedAt = Date.now(); - } - } - - if (trackInfo.encoded && this._lavalink) { - const loaded = await this._streamFromLoadstream(trackInfo, seekMs, options.filterPayload); - if (generation !== this._playGeneration) { - loaded.stream.destroy(); - return "stopped"; - } - - const routed = await this._routeByMagic(loaded.stream); - this._sourceStream = loaded.stream; - this._sourceReq = loaded.req || null; - - if (routed.kind === "webm") { - logger.player("[AudioBridge] Playing loadstream webm/opus passthrough: " + (trackInfo.title || "unknown") + - (seekMs > 0 ? " [seek: " + seekMs + "ms]" : "")); - this._stream = routed.stream; - await conn.play(routed.stream); - } else if (routed.kind === "ogg") { - logger.player("[AudioBridge] Playing loadstream ogg/opus (remux to webm): " + (trackInfo.title || "unknown")); - const oggResult = await this._remuxOggToWebM(routed.stream); - this._stream = oggResult; - if (durationMs <= 0) durationMs = oggResult.getDurationMs(); - await conn.play(this._stream); - } else { - logger.player("[AudioBridge] Playing via loadstream PCM -> in-process Opus: " + (trackInfo.title || "unknown") + - (seekMs > 0 ? " [seek: " + seekMs + "ms]" : "") + - (options.filterPayload ? " [filters]" : "")); - this._stream = this._buildPcmPipeline(routed.stream); - await conn.play(this._stream); - } - if (generation !== this._playGeneration) return "stopped"; - - await this._awaitEnd(durationMs); - if (generation !== this._playGeneration) return "stopped"; - - if (this._playing && !this._stopped) { - this._playing = false; - logger.player("[AudioBridge] Track finished naturally (loadstream)"); - return "finished"; - } - return "stopped"; - } - - if (trackInfo.url && trackInfo.url.startsWith("http")) { - logger.player("[AudioBridge] Route 3: Fetching directly: " + trackInfo.url.substring(0, 80) + "..."); - const response = await fetch(trackInfo.url, { - headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)" }, - redirect: "follow", - }); - if (!response.ok) { - throw new Error("HTTP " + response.status + " for " + trackInfo.url); - } - const stream = Readable.fromWeb(response.body); - this._sourceStream = stream; - - const routed = await this._routeByMagic(stream); - if (routed.kind === "webm") { - logger.player("[AudioBridge] Route 3a: webm/opus passthrough: " + (trackInfo.title || "unknown")); - this._stream = routed.stream; - await conn.play(routed.stream); - } else if (routed.kind === "ogg") { - logger.player("[AudioBridge] Route 3b: ogg/opus remux to webm: " + (trackInfo.title || "unknown")); - const oggResult = await this._remuxOggToWebM(routed.stream); - this._stream = oggResult; - await conn.play(this._stream); - if (generation !== this._playGeneration) return "stopped"; - - await new Promise(r => { - if (this._stream.readableEnded) return r(); - const done = () => { this._stream.off("end", done); this._stream.off("close", done); r(); }; - this._stream.once("end", done); - this._stream.once("close", done); - }); - if (generation !== this._playGeneration) return "stopped"; - - const fullDurationMs = oggResult.getDurationMs(); - const elapsedMs = Date.now() - this._startedAt; - const remainingMs = Math.max(0, fullDurationMs - elapsedMs); - logger.player("[AudioBridge] Route 3b: OGG " + fullDurationMs + "ms total, " + elapsedMs + "ms elapsed, waiting " + remainingMs + "ms more"); - - if (remainingMs > 0) await this._awaitEnd(remainingMs); - if (generation !== this._playGeneration) return "stopped"; - - if (this._playing && !this._stopped) { - this._playing = false; - logger.player("[AudioBridge] Track finished naturally (direct URL, OGG remux)"); - return "finished"; - } - return "stopped"; - } else { - stream.destroy(); - this._sourceStream = null; - logger.player("[AudioBridge] Route 3c: Direct stream is " + routed.kind + " (MP3/AAC?) — resolving through Lavalink..."); - - if (this._lavalink) { - const encoded = await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId); - if (encoded) { - trackInfo.encoded = encoded; - logger.player("[AudioBridge] Route 3c: Got encoded track from Lavalink, retrying via loadstream..."); - const loaded = await this._streamFromLoadstream(trackInfo, 0, null); - if (generation !== this._playGeneration) { - loaded.stream.destroy(); - return "stopped"; - } - - const routed2 = await this._routeByMagic(loaded.stream); - this._sourceStream = loaded.stream; - this._sourceReq = loaded.req || null; - - if (routed2.kind === "webm") { - logger.player("[AudioBridge] Route 3c (Lavalink): webm/opus passthrough"); - this._stream = routed2.stream; - await conn.play(routed2.stream); - } else if (routed2.kind === "ogg") { - logger.player("[AudioBridge] Route 3c (Lavalink): ogg/opus remux to webm"); - const oggResult3c = await this._remuxOggToWebM(routed2.stream); - this._stream = oggResult3c; - if (durationMs <= 0) durationMs = oggResult3c.getDurationMs(); - await conn.play(this._stream); - } else { - logger.player("[AudioBridge] Route 3c (Lavalink): PCM -> Opus -> WebM"); - this._stream = this._buildPcmPipeline(routed2.stream); - await conn.play(this._stream); - } - if (generation !== this._playGeneration) return "stopped"; - - await this._awaitEnd(durationMs); - if (generation !== this._playGeneration) return "stopped"; - - if (this._playing && !this._stopped) { - this._playing = false; - logger.player("[AudioBridge] Track finished naturally (Route 3c Lavalink resolve)"); - return "finished"; - } - return "stopped"; - } - } - - throw new Error( - "[AudioBridge] Direct URL is not WebM/Opus or Ogg/Opus (" + routed.kind + "). " + - "Lavalink resolve also failed or is unavailable. " + - "Make sure your Lavalink/NodeLink node is running and can decode this stream format." - ); - } - if (generation !== this._playGeneration) return "stopped"; - - await this._awaitEnd(durationMs); - if (generation !== this._playGeneration) return "stopped"; - - if (this._playing && !this._stopped) { - this._playing = false; - logger.player("[AudioBridge] Track finished naturally (direct URL)"); - return "finished"; - } - return "stopped"; - } - - throw new Error("Could not get audio stream for: " + (trackInfo.title || trackInfo.url || "unknown")); - - } catch (e) { - if (generation !== this._playGeneration) return "stopped"; - if (this._stopped || !this._playing) return "stopped"; - this._playing = false; - logger.error("[AudioBridge] Playback error: " + e.message); - throw e; - } finally { - this._cleanup(); - } - } - - /** - * Wait for playback end: duration timer for fixed-length tracks, pipeline - * end event for live/radio streams (durationMs = 0). Rejects early on - * pipeline errors so the player can skip to the next track. - * @param {number} durationMs - * @returns {Promise} - * @private - */ - _awaitEnd(durationMs) { return new Promise((resolve, reject) => { - this._endResolve = resolve; - this._endReject = reject; - const failFast = (err) => { - if (this._playing && !this._stopped) { - this._playing = false; - reject(err); - } else { - resolve(); - } - }; - - if (durationMs > 0) { - this._durationTimer = setTimeout(resolve, durationMs); - } else { - const stream = this._stream; - if (!stream) return resolve(); - const onEnd = () => resolve(); - stream.once("end", onEnd); - stream.once("close", onEnd); - stream.once("error", failFast); - } - - if (this._sourceStream) { - this._sourceStream.once("error", failFast); - } - if (this._encoder) { - this._encoder.once("error", failFast); - } - }); - } - - /** - * Simple timed wait used by the trackstream passthrough route (no local - * pipeline to watch). Resolves early if stopped. - * @param {number} durationMs - * @returns {Promise} - * @private - */ - _waitDuration(durationMs) { - return new Promise((resolve) => { - const timer = setTimeout(() => { - this._durationTimer = null; - resolve(); - }, durationMs); - this._durationTimer = timer; - }); - } - - /** - * Peek at the first bytes of a stream and classify it, pushing the peeked - * bytes back so nothing is lost. - * @param {Readable} stream - * @returns {Promise<{stream: Readable, kind: "webm"|"ogg"|"pcm"}>} - * @private - */ - async _routeByMagic(stream) { - const head = await this._peek(stream, 4); - if (head.length >= 4 && head.subarray(0, 4).equals(WEBM_MAGIC)) return { stream, kind: "webm" }; - if (head.length >= 4 && head.subarray(0, 4).equals(OGG_MAGIC)) return { stream, kind: "ogg" }; - return { stream, kind: "pcm" }; - } - - /** - * Read up to `n` bytes from a paused-mode stream, then unshift them. - * @param {Readable} stream - * @param {number} n - * @returns {Promise} - * @private - */ - _peek(stream, n) { - return new Promise((resolve, reject) => { - const tryRead = () => { - const chunks = []; - let total = 0; - let chunk; - while (total < n && (chunk = stream.read()) !== null) { - chunks.push(chunk); - total += chunk.length; - } - if (total >= n || stream.readableEnded) { - const buf = Buffer.concat(chunks); - cleanup(); - if (buf.length > 0) stream.unshift(buf); - resolve(buf.subarray(0, n)); - return; - } - }; - const onReadable = () => { cleanup(); tryRead(); }; - const onEnd = () => { cleanup(); tryRead(); }; - const onError = (err) => { cleanup(); reject(err); }; - const cleanup = () => { - stream.off("readable", onReadable); - stream.off("end", onEnd); - stream.off("error", onError); - }; - stream.once("readable", onReadable); - stream.once("end", onEnd); - stream.once("error", onError); - tryRead(); - }); - } - - /** - * Build the in-process PCM -> Opus -> WebM pipeline. - * @param {Readable} pcmStream - s16le 48kHz stereo byte stream - * @returns {WebMOpusMuxer} - byte stream consumable by conn.play() - * @private - */ - _buildPcmPipeline(pcmStream) { - let encoder; - try { - encoder = new PrismOpusEncoder({ - rate: PCM_RATE, - channels: PCM_CHANNELS, - frameSize: PCM_FRAME_SIZE, - }); - } catch (e) { - pcmStream.destroy(); - throw new Error( - "No Opus encoder available (" + e.message + "). Install one: npm install @discordjs/opus (or opusscript)" - ); - } - try { encoder.setBitrate(OPUS_BITRATE); } catch (_) {} - - const muxer = new WebMOpusMuxer({ sampleRate: PCM_RATE, channels: PCM_CHANNELS }); - this._encoder = encoder; - - pcmStream.on("error", (err) => { - logger.warn("[AudioBridge] PCM source error: " + err.message); - encoder.destroy(err); - }); - encoder.on("error", (err) => { - muxer.destroy(err); - }); - - pcmStream.pipe(encoder).pipe(muxer); - return muxer; - } - - /** - * Remux an Ogg/Opus stream into WebM/Opus (packet-level, no re-encode). - * @param {Readable} oggStream - * @returns {Promise<{stream: WebMOpusMuxer, getDurationMs: function}>} - * @private - */ - async _remuxOggToWebM(oggStream) { - const demuxer = new PrismOggDemuxer(); - const muxer = new WebMOpusMuxer(); - oggStream.on("error", (err) => demuxer.destroy(err)); - demuxer.on("error", (err) => muxer.destroy(err)); - let frameCount = 0; - demuxer.on("data", () => { frameCount++; }); - const headPromise = new Promise((resolve, reject) => { - demuxer.once("head", () => resolve()); - demuxer.once("error", (err) => reject(new Error("OGG demux: " + err.message))); - oggStream.once("error", (err) => reject(new Error("OGG source: " + err.message))); - }); - oggStream.pipe(demuxer).pipe(muxer); - await headPromise; - const wrapper = Object.create(muxer); - wrapper.getDurationMs = () => frameCount * OPUS_FRAME_MS; - return wrapper; - } - - /** - * @param {object} trackInfo - * @returns {Promise<{url: string, format: string}>} - * @private - */ - async _getTrackstreamUrl(trackInfo) { - const nlInfo = this._lavalink.getNodeLinkInfo?.(); - if (!nlInfo) throw new Error("NodeLink info not available"); - - const protocol = nlInfo.secure ? "https" : "http"; - const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port; - - const headers = { "Authorization": nlInfo.password }; - if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId; - if (trackInfo.guildId) headers["Guild-Id"] = trackInfo.guildId; - - const params = "encodedTrack=" + encodeURIComponent(trackInfo.encoded); - const url = baseUrl + "/v4/trackstream?" + params; - - logger.player("[AudioBridge] Querying /v4/trackstream..."); - - const body = await this._httpGetJson(url, headers); - - const directUrl = body?.url; - if (!directUrl || typeof directUrl !== "string") { - throw new Error("trackstream returned no URL"); - } - - const format = body?.format || ""; - logger.player("[AudioBridge] trackstream: format=" + format + " url=" + directUrl.substring(0, 100) + "..."); - - return { url: directUrl, format }; - } - - /** - * @param {object} trackInfo - * @param {number} [seekMs=0] - * @param {object|null} [filterPayload] - * @returns {Promise<{stream: Readable, inputFormat: string|null}>} - * @private - */ - async _streamFromLoadstream(trackInfo, seekMs = 0, filterPayload = null) { - const nlInfo = this._lavalink.getNodeLinkInfo?.(); - if (!nlInfo) { - throw new Error("NodeLink info not available"); - } - - const protocol = nlInfo.secure ? "https" : "http"; - const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port; - - const headers = { "Authorization": nlInfo.password }; - if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId; - if (trackInfo.guildId) headers["Guild-Id"] = trackInfo.guildId; - - let baseParams = "encodedTrack=" + encodeURIComponent(trackInfo.encoded) + "&position=" + seekMs + "&volume=100"; - if (filterPayload) { - baseParams += "&filters=" + encodeURIComponent(JSON.stringify(filterPayload)); - } - - const url = baseUrl + "/v4/loadstream?" + baseParams; - logger.player("[AudioBridge] Querying /v4/loadstream (seek: " + seekMs + "ms)..."); - - return this._httpRequestStream(url, headers); - } - - /** - * Resolve a direct audio URL through Lavalink's /v4/loadtracks to get an encoded track. - * This allows MP3/AAC radio streams and direct audio URLs to be played through - * the loadstream pipeline without any FFmpeg dependency. - * @param {string} url - The HTTP(S) audio stream URL to resolve. - * @param {string} [guildId] - Optional guild ID for the request. - * @returns {Promise} The encoded track string, or null if resolution failed. - * @private - */ - async _resolveUrlViaLavalink(url, guildId) { - try { - const nlInfo = this._lavalink.getNodeLinkInfo?.(); - if (!nlInfo) { - logger.warn("[AudioBridge] _resolveUrlViaLavalink: no NodeLink info"); - return null; - } - - const protocol = nlInfo.secure ? "https" : "http"; - const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port; - - const headers = { "Authorization": nlInfo.password }; - if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId; - if (guildId) headers["Guild-Id"] = guildId; - - const params = "identifier=" + encodeURIComponent(url); - const loadtracksUrl = baseUrl + "/v4/loadtracks?" + params; - - logger.player("[AudioBridge] Resolving URL via Lavalink /v4/loadtracks: " + url.substring(0, 80) + "..."); - - const body = await this._httpGetJson(loadtracksUrl, headers, 0, 30_000); - - const track = body?.data?.tracks?.[0] ?? body?.tracks?.[0] ?? body?.data; - const encoded = track?.encoded ?? track?.data; - - if (encoded && typeof encoded === "string") { - logger.player("[AudioBridge] Lavalink resolved URL to encoded track successfully"); - return encoded; - } - - const loadType = body?.loadType ?? body?.data?.loadType; - logger.warn("[AudioBridge] Lavalink loadtracks returned no playable track (loadType=" + loadType + ")"); - return null; - } catch (e) { - logger.warn("[AudioBridge] _resolveUrlViaLavalink failed: " + e.message); - return null; - } - } - - /** - * @param {string} url - * @param {object} [headers] - * @returns {Promise} - * @private - */ - _httpGetJson(url, headers = {}, _redirectCount = 0, timeoutMs = REST_REQUEST_TIMEOUT_MS) { - return new Promise((resolve, reject) => { - if (_redirectCount >= MAX_REDIRECTS) { - return reject(new Error("Too many redirects (" + _redirectCount + ")")); - } - const urlObj = new URL(url); - const client = urlObj.protocol === "https:" ? https : http; - - const req = client.request({ - protocol: urlObj.protocol, - host: urlObj.hostname, - port: urlObj.port, - path: urlObj.pathname + urlObj.search, - method: "GET", - headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)", ...headers }, - }, (res) => { - if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { - res.resume(); - let loc = res.headers.location; - if (loc.startsWith("/")) loc = urlObj.protocol + "//" + urlObj.host + loc; - return this._httpGetJson(loc, headers, _redirectCount + 1, timeoutMs).then(resolve, reject); - } - if (res.statusCode !== 200) { - let body = ""; - res.on("data", (chunk) => { body += chunk; }); - res.on("end", () => { - reject(new Error("HTTP " + res.statusCode + " for " + url + ": " + body.substring(0, 300))); - }); - return; - } - - let data = ""; - res.on("data", (chunk) => { data += chunk; }); - res.on("end", () => { - try { - resolve(JSON.parse(data)); - } catch (e) { - reject(new Error("Invalid JSON from trackstream: " + data.substring(0, 200))); - } - }); - }); - - req.on("socket", (socket) => { - socket.on("error", () => {}); - }); - req.on("error", reject); - req.setTimeout(timeoutMs, () => { - req.destroy(); - reject(new Error("REST request timeout (" + timeoutMs / 1000 + "s)")); - }); - req.end(); - }); - } - - /** - * @param {string} url - * @param {object} [headers] - * @param {number} [_redirectCount=0] - * @returns {Promise<{stream: Readable, inputFormat: string|null, req: http.ClientRequest}>} - * @private - */ - _httpRequestStream(url, headers = {}, _redirectCount = 0) { - return new Promise((resolve, reject) => { - if (_redirectCount >= MAX_REDIRECTS) { - return reject(new Error("Too many redirects (" + _redirectCount + ")")); - } - - const urlObj = new URL(url); - const client = urlObj.protocol === "https:" ? https : http; - let firstByte = true; - let connectTimer = null; - let idleTimer = null; - - const resetIdleTimeout = () => { - if (idleTimer) clearTimeout(idleTimer); - idleTimer = setTimeout(() => { - req.destroy(); - reject(new Error("loadstream idle timeout (" + LOADSTREAM_IDLE_TIMEOUT_MS / 1000 + "s no data)")); - }, LOADSTREAM_IDLE_TIMEOUT_MS); - idleTimer.unref?.(); - }; - - const req = client.request({ - protocol: urlObj.protocol, - host: urlObj.hostname, - port: urlObj.port, - path: urlObj.pathname + urlObj.search, - method: "GET", - headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)", ...headers }, - }, (res) => { - if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { - if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; } - res.resume(); - let nextHeaders = headers; - let loc = res.headers.location; - if (loc.startsWith("/")) loc = urlObj.protocol + "//" + urlObj.host + loc; - try { - const redirectHost = new URL(loc).hostname; - if (redirectHost !== urlObj.hostname) { - const { Authorization, "Session-Id": _, ...safe } = headers; - nextHeaders = safe; - } - } catch (_) {} - return this._httpRequestStream(loc, nextHeaders, _redirectCount + 1).then(resolve, reject); - } - if (res.statusCode !== 200) { - if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; } - let body = ""; - res.on("data", (chunk) => { body += chunk; }); - res.on("end", () => { - reject(new Error("HTTP " + res.statusCode + " for " + url + ": " + body.substring(0, 300))); - }); - return; - } - - if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; } - resetIdleTimeout(); - res.once("data", () => resetIdleTimeout()); - - logger.player("[AudioBridge] loadstream response: " + res.statusCode + " content-type=" + (res.headers["content-type"] || "?")); - resolve({ stream: res, inputFormat: res.headers["content-type"] || null, req }); - }); - - req.on("socket", (socket) => { - socket.on("error", () => {}); - }); - - req.on("error", (err) => { - if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; } - if (idleTimer) { clearTimeout(idleTimer); idleTimer = null; } - reject(err); - }); - - connectTimer = setTimeout(() => { - req.destroy(); - reject(new Error("loadstream connect timeout (" + LOADSTREAM_CONNECT_TIMEOUT_MS / 1000 + "s — Lavalink took too long to start stream)")); - }, LOADSTREAM_CONNECT_TIMEOUT_MS); - connectTimer.unref?.(); - - req.end(); - }); - } - - /** Stop current playback and clean up resources. */ - stop() { - const wasPlaying = this._playing; - this._stopped = true; - this._playing = false; - this._playGeneration++; - - this._cleanup(); - - if (this._conn) { - try { this._conn.stop(); } catch (_) {} - this._unpublishStaleAudioTracks(this._conn); - } - - if (wasPlaying) { - this.emit("stopped"); - logger.player("[AudioBridge] Playback stopped"); - } - } - - /** - * @param {object} conn - Fluxer voice connection - * @param {string|null} [keepSid=null] - Track SID to keep (currently active publication) - * @private - */ - _unpublishStaleAudioTracks(conn, keepSid = null) { - try { - const room = conn?.room; - const participant = room?.localParticipant; - if (!room?.isConnected || typeof participant?.unpublishTrack !== "function") return; - - const publications = participant.trackPublications; - if (!publications || typeof publications.entries !== "function") return; - - for (const [sid, pub] of publications.entries()) { - if (keepSid && sid === keepSid) continue; - if (pub?.kind !== TRACK_KIND_AUDIO) continue; - try { - const p = participant.unpublishTrack(sid, true); - if (p?.catch) p.catch(() => {}); - logger.player("[AudioBridge] Unpublished stale audio track: " + sid); - } catch (_) {} - } - } catch (_) { - } - } - - /** - * Set the playback volume on the voice connection. - * @param {number} percent - Volume 0–100. - */ - setVolume(percent) { - if (this._conn) { - try { this._conn.setVolume(percent); } catch (e) { - logger.warn("[AudioBridge] setVolume error: " + e.message); - } - } - } - - /** @returns {number} Current volume percentage (0–100). */ - getVolume() { - if (this._conn) { - try { return this._conn.getVolume(); } catch (_) {} - } - return 100; - } - - /** @returns {boolean} Whether the voice connection is currently active. */ - isConnected() { - if (this._conn) { - try { return this._conn.isConnected(); } catch (_) {} - } - return false; - } - - /** - * Clear timers, settle pending waits, and tear down the pipeline. - * @private - */ - _cleanup() { - if (this._durationTimer) { clearTimeout(this._durationTimer); this._durationTimer = null; } - if (this._endResolve) { - const resolve = this._endResolve; - this._endResolve = null; - this._endReject = null; - resolve(); - } - for (const s of [this._stream, this._encoder, this._sourceStream]) { - if (s) { - try { s.destroy(); } catch (_) {} - } - } - if (this._sourceReq) { - try { this._sourceReq.destroy(); } catch (_) {} - } - this._stream = null; - this._encoder = null; - this._sourceStream = null; - this._sourceReq = null; - } - - /** Stop playback, release the voice connection, and remove all listeners. */ - destroy() { - this.stop(); - this._conn = null; - this._currentUri = null; - this.removeAllListeners(); - } -} diff --git a/src/GatewayHandler.mjs b/src/GatewayHandler.mjs deleted file mode 100644 index 375acc0..0000000 --- a/src/GatewayHandler.mjs +++ /dev/null @@ -1,1473 +0,0 @@ -/** @module src/GatewayHandler @description Handles all Discord gateway events relevant to voice state tracking, 24/7 mode, boot recovery, presence rotation, and permission checks. */ -import { Events, GatewayOpcodes } from "@fluxerjs/core"; -import { getVoiceManager } from "@fluxerjs/voice"; -import { logger, _wsErrorCooldown } from "./constants/Logger.mjs"; -import { ServerSettings } from "./Settings.mjs"; -import { get247ChannelMode, remove247ChannelMode } from "./constants/Helpers247.mjs"; -import { VoiceStateCache } from "./constants/VoiceStateCache.mjs"; -import { REQUIRED_BOT_PERMISSIONS } from "./MessageHandler.mjs"; -import { cleanId } from "./Utils.mjs"; -import { iterateVoiceStates, hasHumansInChannel, getChannelsWithHumans } from "./constants/VoiceStateResolver.mjs"; - -const RAW_GATEWAY_INTEREST = - /"(?:t|op)":\s*(?:"(?:VOICE_STATE_UPDATE|VOICE_SERVER_UPDATE|GUILD_CREATE|READY|RESUMED)"|(?:7|9|10|12)\b)/; - -/** @class GatewayHandler @description Handles all Discord gateway events relevant to voice state tracking, 24/7 mode, boot recovery, presence rotation, and permission checks. Key responsibilities include voice state cache seeding and updates, bot move-away detection with 24/7 rejoin scheduling, boot recovery with sequential rejoin of 24/7 channels, inactivity timer management on human join/leave, and guild create/delete handling with startup grace period. */ -export class GatewayHandler { - /** - * Create a new GatewayHandler. - * @param {import('../index.mjs').Remix} remix - The bot context. - */ - constructor(remix) { - this.remix = remix; - - const timers = remix.config.timers ?? {}; - this.T = { - aloneCheckDebounce: timers.aloneCheckDebounce ?? 500, - rejoin247Delay: timers.rejoin247Delay ?? 3_000, - }; - - this.presenceContents = remix.config.presenceContents ?? []; - this.presenceInterval = remix.config.presenceInterval ?? 30_000; - - this.wsListenerAttached = false; - this.presenceTimer = null; - this.presenceIndex = 0; - - this._prevVoiceState = new Map(); - - this._deferredGuildDeletes = new Map(); - this._startupDeleteGraceMs = 15_000; - this._inStartupGrace = true; - this._deferredDeleteCount = 0; - - this._lastReadyAt = 0; - this._wsReconnectGraceMs = 30_000; - this._moveEvidenceWindowMs = 10_000; - } - - /** - * Check whether a WebSocket reconnect happened recently (within 30s). - * Used to treat transient disconnects as non-24/7-requiring. - * @returns {boolean} - */ - isWsReconnectRecent() { - if (!this._lastReadyAt) return false; - return Date.now() - this._lastReadyAt < this._wsReconnectGraceMs; - } - - /** @private Build a composite bot key for voice state tracking. @param {string} userId @param {string} guildId @returns {string|null} */ - getObservedVoiceBotKey(userId, guildId) { - const cleanUserId = cleanId(userId ?? ""); - const cleanGuildId = cleanId(guildId ?? ""); - return cleanUserId && cleanGuildId ? `${cleanGuildId}:${cleanUserId}` : cleanUserId || null; - } - - /** @private Build a previous voice state lookup key. @param {string} userId @param {string} guildId @returns {string|null} */ - getPrevVoiceStateKey(userId, guildId) { - const cleanUserId = cleanId(userId ?? ""); - const cleanGuildId = cleanId(guildId ?? ""); - return cleanUserId && cleanGuildId ? `${cleanGuildId}:${cleanUserId}` : null; - } - - /** Find a previous voice state entry for a user. @param {string} userId @param {string|null} [guildId=null] @returns {{key: string|null, value: object|null}} */ - findPrevVoiceStateEntry(userId, guildId = null) { - const directKey = this.getPrevVoiceStateKey(userId, guildId); - if (directKey && this._prevVoiceState.has(directKey)) { - return { key: directKey, value: this._prevVoiceState.get(directKey) }; - } - - const cleanUserId = cleanId(userId ?? ""); - if (!cleanUserId) return { key: null, value: null }; - - for (const [key, value] of this._prevVoiceState) { - if (key.endsWith(`:${cleanUserId}`)) { - return { key, value }; - } - } - - return { key: null, value: null }; - } - - /** - * Check and warn about missing bot permissions in a guild. - * Sends an embed to the system channel if critical or optional perms are missing. - * @param {object} guild - The guild object. - * @param {string} guildId - The guild ID. - * @returns {Promise} - * @private - */ - async _checkGuildPermissions(guild, guildId) { - const { remix } = this; - - try { - if (guild.members && !guild.members.me) { - await guild.members.fetchMe(); - } - } catch (e) { logger.warn("[GatewayHandler] fetchMe failed:", e?.message); } - - const channels = guild.channels; - if (!channels) return; - - let targetChannel = null; - if (guild.systemChannelId) { - targetChannel = channels.get?.(guild.systemChannelId) ?? null; - } - if (!targetChannel) { - for (const ch of (channels.values?.() ?? [])) { - if (ch.isTextBased?.() || ch.type === 0 || ch.type === "GUILD_TEXT") { - targetChannel = ch; - break; - } - } - } - if (!targetChannel) return; - - const result = remix.messages.checkAllBotPermissions(targetChannel); - if (result.missing.length === 0) return; - - const missingNames = result.missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k); - if (result.criticalMissing.length > 0) { - logger.warn( - `[GuildCreate] Server ${guildId} is missing CRITICAL bot permissions: ${result.criticalMissing.join(", ")}\n` + - ` All missing: ${missingNames.join(", ")}` - ); - } else { - logger.guild( - `[GuildCreate] Server ${guildId} is missing optional permissions: ${result.optionalMissing.join(", ")}` - ); - } - - try { - const permEmbed = remix.messages.buildPermissionEmbed(result.missing, guildId); - await targetChannel.send({ embeds: [permEmbed], allowedMentions: { parse: [] } }); - } catch (e) { - logger.warn(`[GuildCreate] Cannot send permission warning to server ${guildId}: ${e.message}`); - try { - const t = this.remix.locale?.translate?.bind(this.remix.locale); - const guildIdStr = cleanId(guildId); - await targetChannel.send({ - content: t ? t(guildIdStr, "responses.gateway.missingPermsFallback", { perms: missingNames.join("**, **") }) : - "⚠️ I'm missing permissions I need to work properly! Missing: **" + missingNames.join("**, **") + "**. Please ask a server administrator to grant these permissions in Server Settings → Roles.", - allowedMentions: { parse: [] }, - }); - } catch (e) { - logger.warn(`[GuildCreate] Cannot send ANY notification to server ${guildId} — bot is missing SendMessages permission:`, e?.message); - } - } - } - - /** - * Seed the voice state cache from VoiceManager or guild cache on startup. - * @private - */ - seedVoiceStatesFromGuilds() { - const { remix } = this; - const client = remix.client; - - try { - const vm = getVoiceManager(client); - if (vm?.voiceStates && vm.voiceStates.size > 0) { - let totalHumans = 0; - let totalBots = 0; - for (const [guildId, userMap] of vm.voiceStates) { - if (!userMap || typeof userMap.forEach !== "function") continue; - const cleanGuildId = cleanId(guildId); - if (!cleanGuildId) continue; - userMap.forEach((channelId, userId) => { - if (!userId || !channelId) return; - const botId = client.user?.id; - if (userId === botId) { - remix.voiceCache.updateUser({ guildId: cleanGuildId, userId, channelId, isBot: true }); - totalBots++; - } else { - const guild = client.guilds.get(cleanGuildId) ?? client.guilds.get(guildId); - const member = guild?.members?.get?.(userId); - const isBot = member?.user?.bot ?? false; - remix.voiceCache.updateUser({ guildId: cleanGuildId, userId, channelId, isBot }); - if (isBot) totalBots++; - else totalHumans++; - } - }); - } - logger.voiceState( - `[Seed] Seeded from VoiceManager.voiceStates — ` + - `${totalHumans} humans, ${totalBots} bots across ${vm.voiceStates.size} guilds. ` + - `Cache now: ${remix.voiceCache.observedVoiceUsersSize} humans, ${remix.voiceCache.observedVoiceBotsSize} bots.` - ); - return; - } - logger.voiceState(`[Seed] VoiceManager.voiceStates is empty (${vm?.voiceStates?.size ?? "null"} guilds). ` + - `This is expected if no users were in voice when the bot started. ` + - `VoiceStatesSync handler will populate the cache as guilds become available.`); - } catch (e) { - logger.voiceState(`[Seed] VoiceManager seeding failed: ${e?.message} — falling back to guild cache.`); - } - - for (const [gId, guild] of client.guilds) { - for (const vs of iterateVoiceStates(guild)) { - remix.voiceCache.updateUser({ guildId: gId, userId: vs.userId, channelId: vs.channelId, isBot: vs.isBot }); - } - } - } - - /** - * Re-seed voice states for a specific channel from multiple sources. - * Checks VoiceManager, guild cache, VoiceStateCache, and LiveKit participants. - * @param {string} guildId - The guild ID. - * @param {string} channelId - The channel ID. - * @returns {number} Number of humans found in the channel. - */ - reseedVoiceStatesForChannel(guildId, channelId) { - const { remix } = this; - const client = remix.client; - - const cleanGuild = cleanId(guildId); - const cleanChannel = cleanId(channelId); - if (!cleanGuild || !cleanChannel) return 0; - - let humansFound = 0; - const botId = client.user?.id; - - try { - const vm = getVoiceManager(client); - if (vm?.voiceStates) { - const guildVoiceMap = vm.voiceStates.get(cleanGuild) ?? vm.voiceStates.get(guildId); - if (guildVoiceMap && typeof guildVoiceMap.forEach === "function") { - guildVoiceMap.forEach((userChannelId, userId) => { - if (!userId || !userChannelId) return; - const userChannel = cleanId(userChannelId); - if (userChannel !== cleanChannel) return; - if (userId === botId) { - remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: true }); - } else { - const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId); - const member = guild?.members?.get?.(userId); - const isBot = member?.user?.bot ?? false; - if (isBot) { - remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: true }); - } else { - remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: false }); - humansFound++; - logger.voiceState( - `[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild}) via VoiceManager` - ); - } - } - }); - - if (botId) { - remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true }); - } - - logger.voiceState( - `[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` + - `found ${humansFound} human(s) via VoiceManager, observedVoiceUsers size now ${remix.voiceCache.observedVoiceUsersSize}` - ); - - if (humansFound > 0) return humansFound; - } - } - } catch (e) { - logger.voiceState(`[Reseed] VoiceManager lookup failed: ${e?.message} — falling back.`); - } - - const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId); - if (!guild) { - logger.voiceState( - `[Reseed] Guild ${cleanGuild} not in cache — cannot reseed voice states.` - ); - } else { - for (const vs of iterateVoiceStates(guild)) { - if (vs.isBot) continue; - if (vs.channelId === cleanChannel) { - remix.voiceCache.updateUser({ guildId: cleanGuild, userId: vs.userId, channelId: vs.channelId, isBot: false }); - humansFound++; - logger.voiceState( - `[Reseed] Found human ${vs.userId} in channel ${cleanChannel} (guild ${cleanGuild})` - ); - } - } - - if (botId) { - remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true }); - } - - if (humansFound > 0) { - logger.voiceState( - `[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` + - `found ${humansFound} human(s), observedVoiceUsers size now ${remix.voiceCache.observedVoiceUsersSize}` - ); - return humansFound; - } - } - - if (humansFound === 0 && remix.voiceCache) { - const humans = remix.voiceCache.getHumansInChannel(cleanGuild, cleanChannel); - for (const uid of humans) { - humansFound++; - logger.voiceState( - `[Reseed] Found human ${uid} in channel ${cleanChannel} (guild ${cleanGuild}) via VoiceStateCache` - ); - } - - if (botId) { - remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true }); - } - } - - if (humansFound === 0) { - try { - const player = remix.players.playerMap.get(cleanChannel); - const room = player?.connection?.room; - if (room?.isConnected && room.remoteParticipants) { - for (const [, participant] of room.remoteParticipants) { - const userId = participant?.identity ?? participant?.sid; - if (userId) { - humansFound++; - remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: false }); - logger.voiceState( - `[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild}) via LiveKit participants` - ); - } - } - } - } catch (e) { - logger.voiceState(`[Reseed] LiveKit participant fallback error: ${e?.message}`); - } - } - - logger.voiceState( - `[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` + - `found ${humansFound} human(s), observedVoiceUsers size now ${remix.voiceCache.observedVoiceUsersSize}` - ); - - return humansFound; - } - - /** Attach a raw WebSocket listener to cache VOICE_SERVER_UPDATE events. @private */ - attachRawListener() { - const { remix } = this; - const client = remix.client; - - try { - const shard0 = client.ws?.shards?.get?.(0); - const wsObj = shard0?.ws ?? null; - - if (this.wsListenerAttached && remix._rawGatewayWsObj && remix._rawGatewayWsObj !== wsObj) { - try { - if (typeof remix._rawGatewayWsObj.removeEventListener === "function") { - remix._rawGatewayWsObj.removeEventListener("message", remix._rawGatewayMessageListener ?? remix._rawGatewayHandler); - remix._rawGatewayWsObj.removeEventListener("error", remix._rawGatewayErrorHandler); - } else if (typeof remix._rawGatewayWsObj.off === "function") { - remix._rawGatewayWsObj.off("message", remix._rawGatewayMessageListener ?? remix._rawGatewayHandler); - remix._rawGatewayWsObj.off("error", remix._rawGatewayErrorHandler); - } - } catch(e) { logger.warn("[Gateway] Failed to detach old WS listener:", e?.message); } - } - - if (wsObj && wsObj !== remix._rawGatewayWsObj) { - remix._rawGatewayHandler = (data) => { - try { - if (typeof data === "string" && !RAW_GATEWAY_INTEREST.test(data)) return; - const payload = typeof data === "string" ? JSON.parse(data) : data; - - if (payload?.op === GatewayOpcodes.GatewayError || payload?.op === 12) { - logger.warn("[Gateway] GatewayError (12) received from Fluxer:", payload.d); - } - - if (payload?.op === GatewayOpcodes.Hello || payload?.op === 10) { - logger.player(`[Gateway] HELLO received (heartbeat ${payload.d?.heartbeat_interval ?? "unknown"}ms)`); - } - if (payload?.op === GatewayOpcodes.Reconnect || payload?.op === 7) { - logger.warn("[Gateway] RECONNECT requested by gateway."); - } - if (payload?.op === GatewayOpcodes.InvalidSession || payload?.op === 9) { - logger.warn("[Gateway] INVALID_SESSION received from gateway."); - } - - if (payload?.op !== 0) return; - - if (payload.t === "READY") { - logger.player(`[Gateway] READY received (session ${payload.d?.session_id ?? "unknown"})`); - const readyGuilds = payload.d?.guilds; - if (Array.isArray(readyGuilds)) { - for (const g of readyGuilds) { - const gId = g?.id; - if (!gId || !Array.isArray(g.voice_states)) continue; - for (const state of g.voice_states) { - const userId = state.user_id; - const channelId = state.channel_id; - if (!userId || !channelId) continue; - const isBot = state.member?.user?.bot ?? false; - remix.voiceCache.updateUser({ guildId: gId, userId, channelId, isBot }); - } - } - } - } - - if (payload.t === "RESUMED") { - logger.player("[Gateway] RESUMED received from gateway."); - } - - if (payload.t === "GUILD_CREATE") { - const d = payload.d; - const gId = d?.id; - const voiceStates = d?.voice_states; - if (gId && Array.isArray(voiceStates) && voiceStates.length > 0) { - for (const state of voiceStates) { - const userId = state.user_id; - const channelId = state.channel_id; - if (!userId || !channelId) continue; - const isBot = state.member?.user?.bot ?? false; - remix.voiceCache.updateUser({ guildId: gId, userId, channelId, isBot }); - } - } - } - - if (payload.t === "VOICE_SERVER_UPDATE") { - logger.voiceState(`[Gateway] VOICE_SERVER_UPDATE guild=${payload.d?.guild_id ?? "dm"} endpoint=${payload.d?.endpoint ?? "unknown"}`); - } - - if (payload.t === "VOICE_STATE_UPDATE") { - const d = payload.d; - const userId = d?.user_id; - const channelId = d?.channel_id ?? null; - const guildId = d?.guild_id; - const isBot = d?.member?.user?.bot ?? false; - if (!userId) return; - if (channelId) { - remix.voiceCache.updateUser({ guildId, userId, channelId, isBot }); - } else { - remix.voiceCache.updateUser({ guildId, userId, channelId: null, isBot }); - } - } - } catch(e) { logger.warn("[Gateway] Raw gateway handler error:", e?.message); } - }; - - remix._rawGatewayErrorHandler = (errOrEvent) => { - if (typeof errOrEvent?.preventDefault === "function") errOrEvent.preventDefault(); - const err = errOrEvent?.error ?? errOrEvent?.message ?? errOrEvent; - const now = Date.now(); - if (now - _wsErrorCooldown.lastLogged < _wsErrorCooldown.COOLDOWN_MS) return; - _wsErrorCooldown.lastLogged = now; - logger.warn("[Gateway] Raw WS socket error (will reconnect):", err?.message ?? err); - }; - remix._rawGatewayMessageListener = (event) => remix._rawGatewayHandler(event?.data ?? event); - - if (typeof wsObj.addEventListener === "function") { - wsObj.addEventListener("message", remix._rawGatewayMessageListener); - wsObj.addEventListener("error", remix._rawGatewayErrorHandler); - } else if (typeof wsObj.on === "function") { - wsObj.on("message", remix._rawGatewayMessageListener); - wsObj.on("error", remix._rawGatewayErrorHandler); - } - - remix._rawGatewayWsObj = wsObj; - this.wsListenerAttached = true; - logger.player("[Gateway] Raw WS listener attached to new socket."); - } - } catch(e) { logger.warn("[Gateway] attachRawListener failed:", e?.message); } - } - - /** Rotate the bot's presence/status text at a configured interval. @private */ - setupPresenceRotation() { - if (this.presenceContents.length === 0) return; - - const { remix } = this; - const client = remix.client; - - const setPresence = () => { - const entry = this.presenceContents[this.presenceIndex]; - - const isObj = typeof entry === "object" && entry !== null; - - const custom_status = {}; - if (isObj) { - if (entry.text) custom_status.text = entry.text; - if (entry.emoji_name) custom_status.emoji_name = entry.emoji_name; - if (entry.emoji_id) custom_status.emoji_id = entry.emoji_id; - } else { - custom_status.text = String(entry); - } - - const presence = { - status: "online", - mobile: false, - afk: false, - custom_status, - }; - - if (isObj && entry.activity) { - presence.activities = [{ - name: entry.activity.name ?? "music", - type: entry.activity.type ?? 0, - url: entry.activity.url ?? undefined, - }]; - } - - if (client.ws?.send) { - client.ws.send(0, { op: GatewayOpcodes.PresenceUpdate, d: presence }); - } else { - const shard = client.ws?.shards?.get?.(0); - if (shard) shard.send({ op: GatewayOpcodes.PresenceUpdate, d: presence }); - } - this.presenceIndex = (this.presenceIndex + 1) % this.presenceContents.length; - }; - setPresence(); - if (this.presenceTimer) clearInterval(this.presenceTimer); - this.presenceTimer = setInterval(setPresence, this.presenceInterval); - } - - /** - * Register all gateway event handlers (GuildCreate, GuildDelete, VoiceStateUpdate, VoiceStatesSync). - * Called once during bot initialisation. - */ - setupEventHandlers() { - const { remix } = this; - const client = remix.client; - - client.on(Events.GuildCreate, async (guild) => { - const guildId = guild?.id ?? guild?._id; - if (!guildId) return; - - const deferred = this._deferredGuildDeletes.get(guildId); - if (deferred) { - clearTimeout(deferred.timer); - this._deferredGuildDeletes.delete(guildId); - logger.guild( - `[GuildDelete] Cancelled deferred cleanup for server ${guildId} — ` + - `guild came back (GuildCreate received during grace period).` - ); - } - - const voiceStatesRaw = - guild.voice_states ?? - guild.voiceStates ?? - null; - - if (voiceStatesRaw) { - const newUserIds = new Set(); - for (const vs of iterateVoiceStates(guild)) { - newUserIds.add(vs.userId); - } - remix.voiceCache.purgeUsersInGuild(guildId, newUserIds); - } - if (voiceStatesRaw) { - for (const vs of iterateVoiceStates(guild)) { - remix.voiceCache.updateUser({ guildId, userId: vs.userId, channelId: vs.channelId, isBot: vs.isBot }); - } - } - - if (!remix.settingsMgr.guilds.has(guildId)) { - logger.guild(`[GuildCreate] (Re-)joined server ${guildId} — initialising settings.`); - try { - const cleanGuildId = cleanId(guildId); - if (!cleanGuildId) throw new Error("Invalid guildId: " + guildId); - const res = await remix.settingsMgr.selectGuild(cleanGuildId); - if (res?.results?.length) { - const row = res.results[0]; - const server = new ServerSettings(guildId, remix.settingsMgr); - const parsed = (typeof row.data === "string") ? JSON.parse(row.data) : row.data; - server.deserialize(parsed); - server.checkDefaults(remix.settingsMgr.defaults); - remix.settingsMgr.guilds.set(guildId, server); - logger.guild(`[GuildCreate] Restored existing settings for server ${guildId}.`); - } else { - const server = new ServerSettings(guildId, remix.settingsMgr); - server.checkDefaults(remix.settingsMgr.defaults); - remix.settingsMgr.guilds.set(guildId, server); - await remix.settingsMgr.create(guildId, server); - logger.guild(`[GuildCreate] Fresh settings initialised for server ${guildId}.`); - } - } catch (err) { - logger.warn("[GuildCreate] Settings init failed for", guildId, err.message); - } - } - - this._checkGuildPermissions(guild, guildId).catch(e => logger.warn("[GuildCreate] Permission check error for", guildId, e.message)); - - }); - - client.on(Events.GuildDelete, (guild) => { - const guildId = guild?.id ?? guild?._id; - if (!guildId) return; - - if (this._inStartupGrace) { - this._deferredDeleteCount++; - if (this._deferredDeleteCount <= 3) { - logger.guild( - `[GuildDelete] Deferring cleanup for server ${guildId} ` + - `(startup grace — will confirm after ${this._startupDeleteGraceMs / 1000}s).` - ); - } - const existing = this._deferredGuildDeletes.get(guildId); - if (existing) clearTimeout(existing.timer); - - const timer = setTimeout(() => { - this._deferredGuildDeletes.delete(guildId); - this._processGuildDelete(guildId); - }, this._startupDeleteGraceMs); - - this._deferredGuildDeletes.set(guildId, { guild, timer }); - return; - } - - logger.guild(`[GuildDelete] Received GuildDelete for server ${guildId}.`); - this._processGuildDelete(guildId); - }); - - client.on(Events.VoiceStateUpdate, async (data) => { - this._handleVoiceStateUpdate(data); - }); - - client.on(Events.VoiceStatesSync, (data) => { - this._handleVoiceStatesSync(data); - }); - } - - /** - * Main handler for VOICE_STATE_UPDATE events. Routes to human or bot sub-handlers. - * @param {object} data - The voice state update payload from the gateway. - * @returns {Promise} - * @private - */ - async _handleVoiceStateUpdate(data) { - const { remix } = this; - const client = remix.client; - - const userId = data?.user_id; - if (!userId) return; - - const newChannelId = data?.channel_id ?? null; - const vsuGuildId = data?.guild_id; - const isBot = data?.member?.user?.bot ?? null; - - - const prevEntry = this.findPrevVoiceStateEntry(userId, vsuGuildId); - const prev = prevEntry.value; - const prevSameGuild = prev && - cleanId(prev.guildId ?? "") === cleanId(vsuGuildId ?? ""); - const oldChannelId = prevSameGuild ? (prev?.channelId ?? null) : null; - - - this._updatePreviousStates(userId, vsuGuildId, oldChannelId, newChannelId, isBot, prevEntry, prev); - this._updateVoiceStateCache(userId, vsuGuildId, oldChannelId, newChannelId, isBot, prev); - - - const { player, playerGuildId, homeChannelId } = this._findAffectedPlayer(vsuGuildId, oldChannelId, newChannelId); - - const isBotUser = isBot === true && userId === client.user?.id; - - if (!isBotUser) { - - this._handleInactivityOnVoiceChange(player, playerGuildId, homeChannelId, userId, oldChannelId, newChannelId, vsuGuildId, data); - return; - } - - - this._handleBotVoiceChange(player, playerGuildId, homeChannelId, oldChannelId, newChannelId, vsuGuildId, data); - } - - /** Handle VoiceStatesSync bulk event from the gateway. @param {object} data - Sync payload with voiceStates array. @private */ - _handleVoiceStatesSync(data) { - const { remix } = this; - const client = remix.client; - const guildId = data?.guildId; - if (!guildId || !Array.isArray(data?.voiceStates)) return; - - const botId = client.user?.id; - let humansAdded = 0; - let botsAdded = 0; - - for (const vs of data.voiceStates) { - const userId = vs.user_id; - const channelId = vs.channel_id; - if (!userId || !channelId) continue; - - const isBot = vs.member?.user?.bot ?? (userId === botId); - - remix.voiceCache.updateUser({ guildId, userId, channelId, isBot }); - if (isBot) { - botsAdded++; - } else { - humansAdded++; - } - } - - if (humansAdded > 0 || botsAdded > 0) { - logger.voiceState( - `[VoiceStatesSync] Guild ${guildId}: seeded ${humansAdded} humans, ${botsAdded} bots ` + - `(${data.voiceStates.length} total states).` - ); - } - } - - /** @private Update the voice state cache for a user joining/leaving. @param {string} userId @param {string} guildId @param {string|null} oldChannelId @param {string|null} newChannelId @param {boolean} isBot @param {object|null} prev */ - _updateVoiceStateCache(userId, guildId, oldChannelId, newChannelId, isBot, prev) { - const { remix } = this; - - if (newChannelId) { - remix.voiceCache.updateUser({ guildId: guildId ?? prev?.guildId, userId, channelId: newChannelId, isBot: isBot === true }); - } else { - const resolvedGuildId = guildId ?? prev?.guildId; - if (resolvedGuildId) { - remix.voiceCache.deleteHumanUser(userId, resolvedGuildId); - remix.voiceCache.deleteBotUser(VoiceStateCache.userKey(resolvedGuildId, userId)); - } - } - } - - /** @private Update the previous-voice-state map and evict stale entries. @param {string} userId @param {string} guildId @param {string|null} oldChannelId @param {string|null} newChannelId @param {boolean} isBot @param {object} prevEntry @param {object|null} prev */ - _updatePreviousStates(userId, guildId, oldChannelId, newChannelId, isBot, prevEntry, prev) { - const { remix } = this; - const prevKey = prevEntry.key; - const nextKey = this.getPrevVoiceStateKey(userId, guildId ?? prev?.guildId); - - if (newChannelId) { - if (prevKey && prevKey !== nextKey) { - const prevGuildPart = prevKey.split(":")[0]; - const nextGuildPart = nextKey.split(":")[0]; - if (prevGuildPart === nextGuildPart) { - this._prevVoiceState.delete(prevKey); - } - } - if (nextKey && this._prevVoiceState.size >= 10_000 && !this._prevVoiceState.has(nextKey)) { - const evictKey = this._prevVoiceState.keys().next().value; - const evictEntry = this._prevVoiceState.get(evictKey); - this._prevVoiceState.delete(evictKey); - if (evictEntry) { - const evictGuildId = evictEntry.guildId; - const evictUserId = evictKey.split(":")[1]; - if (evictGuildId && evictUserId) { - const currentLoc = remix.voiceCache.getUserLocation(evictGuildId, evictUserId); - if (currentLoc && currentLoc.channelId === evictEntry.channelId) { - remix.voiceCache.updateUser({ guildId: evictGuildId, userId: evictUserId, channelId: null, isBot: evictEntry.isBot ?? false }); - } - } - } - } - if (nextKey) this._prevVoiceState.set(nextKey, { channelId: newChannelId, guildId: guildId ?? prev?.guildId, isBot: isBot === true }); - } else { - if (prevKey) this._prevVoiceState.delete(prevKey); - } - } - - /** @private Find a player affected by a voice state change. @param {string} guildId @param {string|null} oldChannelId @param {string|null} newChannelId @returns {{player: Player|null, playerGuildId: string|null, homeChannelId: string|null}} */ - _findAffectedPlayer(guildId, oldChannelId, newChannelId) { - const { remix } = this; - - - if (oldChannelId) { - const cleanOld = cleanId(oldChannelId); - const player = remix.players.playerMap.get(cleanOld); - if (player) { - return { player, playerGuildId: player._guildId, homeChannelId: player._home247Channel }; - } - } - - - if (newChannelId) { - const cleanNew = cleanId(newChannelId); - const player = remix.players.playerMap.get(cleanNew); - if (player) { - return { player, playerGuildId: player._guildId, homeChannelId: player._home247Channel }; - } - } - - return { player: null, playerGuildId: null, homeChannelId: null }; - } - - /** @private Manage inactivity timers when a human joins or leaves a voice channel. @param {Player|null} player @param {string|null} playerGuildId @param {string|null} homeChannelId @param {string} userId @param {string|null} oldChannelId @param {string|null} newChannelId @param {string} vsuGuildId @param {object} vsu */ - async _handleInactivityOnVoiceChange(player, playerGuildId, homeChannelId, userId, oldChannelId, newChannelId, vsuGuildId, vsu) { - const { remix } = this; - const client = remix.client; - const resolvedGuildId = vsuGuildId ?? playerGuildId; - if (!resolvedGuildId) return; - - if (newChannelId) { - try { - const cleanId247 = cleanId(newChannelId); - const player247 = remix.players.playerMap.get(cleanId247); - if (player247 && typeof player247._stopInactivityTimer === "function") { - logger.voiceState(`[VoiceState] Human joined 247 channel ${cleanId247}, stopping inactivity timer`); - player247._stopInactivityTimer(); - } - } catch(e) { logger.warn("[VoiceState] 247 inactivity timer stop failed:", e?.message); } - } - - if (oldChannelId && oldChannelId !== newChannelId) { - try { - const cleanOld = cleanId(oldChannelId); - const oldPlayer = remix.players.playerMap.get(cleanOld); - if (oldPlayer && typeof oldPlayer._startInactivityTimer === "function") { - setTimeout(() => { - if (!oldPlayer._hasHumansInChannel()) { - logger.voiceState(`[VoiceState] Last human left ${cleanOld}, starting inactivity timer`); - oldPlayer._startInactivityTimer(); - } - }, this.T.aloneCheckDebounce); - } - } catch(e) { logger.warn("[VoiceState] Inactivity timer start failed:", e?.message); } - } - - if (newChannelId) { - try { - const cleanChId = cleanId(newChannelId); - const newPlayer = remix.players.playerMap.get(cleanChId); - if (newPlayer && typeof newPlayer._stopInactivityTimer === "function") { - logger.voiceState(`[VoiceState] Human joined ${cleanChId}, stopping inactivity timer`); - newPlayer._stopInactivityTimer(); - } - } catch(e) { logger.warn("[VoiceState] Inactivity timer stop failed:", e?.message); } - } - - if (remix.dashboard?.enabled) { - try { - let userObj = vsu?.member?.user; - if (!userObj) { - try { userObj = await client.users.fetch(userId).catch(() => null); } catch(e) { logger.warn("[VoiceState] Dashboard user fetch failed:", e?.message); } - } - if (userObj) { - const details = { - type: newChannelId ? "join" : "leave", - guildId: resolvedGuildId, - channelId: newChannelId ?? null, - oldChannelId: oldChannelId ?? null, - }; - remix.dashboard.updateUser(details, userObj); - } - - const refChannel = newChannelId ?? oldChannelId; - const cleanId_ref = refChannel ? cleanId(refChannel) : null; - - if (cleanId_ref) { - const dashPlayer = remix.players.playerMap.get(cleanId_ref); - if (dashPlayer) { - const eventType = newChannelId ? "join" : "leave"; - remix.dashboard.updatePlayer({ - type: eventType, - data: userId, - }, dashPlayer); - - remix.dashboard.playerUpdate({ - type: eventType, - }, dashPlayer); - } - } - } catch(e) { logger.warn("[VoiceState] Dashboard update failed:", e?.message); } - } - } - - /** - * Handle a voice state update for the bot itself. - * Detects move-away from 24/7 channels and unexpected disconnects. - * @param {Player|null} player - The affected player (if any). - * @param {string|null} playerGuildId - The guild ID from the player. - * @param {string|null} homeChannelId - The 24/7 home channel ID from the player. - * @param {string|null} oldChannelId - The channel the bot was in. - * @param {string|null} newChannelId - The channel the bot moved to (null if disconnected). - * @param {string} vsuGuildId - The guild ID from the VSU event. - * @param {object} vsu - The raw VSU payload. - * @private - */ - _handleBotVoiceChange(player, playerGuildId, homeChannelId, oldChannelId, newChannelId, vsuGuildId, vsu) { - const { remix } = this; - const client = remix.client; - const guildId = vsuGuildId; - - if (newChannelId && guildId && oldChannelId && oldChannelId !== newChannelId) { - // During boot recovery, ignore move events — the recovery loop handles rejoining. - if (this._bootRecoveryActive) { - logger.voice247( - `[247] Ignoring bot move ${cleanId(oldChannelId)} → ${cleanId(newChannelId)} during boot recovery.` - ); - return; - } - try { - const cleanNew = cleanId(newChannelId); - const cleanOld = cleanId(oldChannelId); - - // Check if old channel is a saved 24/7 channel - const oldIs247 = (() => { - try { - const set = remix.settingsMgr.getServer(guildId); - return get247ChannelMode(set, cleanOld) === "on"; - } catch (_) { return false; } - })(); - - // Check if new channel is a saved 24/7 channel or has a pending spawn - const newChannelSaved = (() => { - try { - const set = remix.settingsMgr.getServer(guildId); - return get247ChannelMode(set, cleanNew) === "on"; - } catch (_) { return false; } - })(); - const newChannelPendingSpawn = remix.players?._pendingJoins?.has?.(cleanNew) || false; - - const existingPlayer = remix.players.playerMap.get(cleanOld); - - if (oldIs247 && existingPlayer) { - // Old channel is 24/7 — bot physically moved away, so the voice - // connection to old channel is dead. Destroy the old player and - // schedule a fresh rejoin so it gets a new live connection. - logger.voice247( - `[247] Bot moved away from 24/7 channel ${cleanOld} → ${cleanNew}. ` + - `Destroying stale player, scheduling rejoin for ${cleanOld}.` - ); - remix.players.playerMap.delete(cleanOld); - const homeCh = cleanId(existingPlayer._home247Channel ?? ""); - if (homeCh && homeCh !== cleanOld) remix.players.playerMap.delete(homeCh); - try { existingPlayer.destroy(); } catch (_) {} - const rejoinDelay = this.T.rejoin247Delay ?? 3_000; - setTimeout(() => { - this._rejoinChannel(cleanId(guildId), cleanOld).catch(err => { - logger.warn(`[247] Failed to rejoin ${cleanOld} after move-away:`, err.message); - }); - }, rejoinDelay); - } else if (newChannelSaved || newChannelPendingSpawn) { - // New channel is already 24/7 or being spawned — keep both, don't rekey. - logger.voice247( - `[247] Keeping both channels ${cleanOld} and ${cleanNew} ` + - `(saved=${newChannelSaved} pending=${newChannelPendingSpawn})` - ); - } else if (existingPlayer && cleanNew !== cleanOld) { - // Neither channel is 24/7 — safe to rekey the player. - const targetChannel = client.channels.get(cleanNew) - ?? client.channels.get?.(cleanNew) - ?? null; - const targetGuildId = cleanId(targetChannel?.guildId ?? targetChannel?.guild?.id ?? guildId ?? ""); - - const playerAtNewKey = remix.players.playerMap.get(cleanNew); - if (!playerAtNewKey || playerAtNewKey === existingPlayer) { - remix.players.playerMap.delete(cleanOld); - remix.players.playerMap.set(cleanNew, existingPlayer); - existingPlayer._channelId = cleanNew; - existingPlayer._home247Channel = cleanNew; - if (targetGuildId) existingPlayer._guildId = targetGuildId; - logger.voice247(`[247] Re-keyed playerMap ${cleanOld} → ${cleanNew}`); - } else { - logger.voice247( - `[247] Skipped re-key ${cleanOld} → ${cleanNew} (new key occupied by another player)` - ); - } - } - - // Simplified 24/7: stay_247 list only changes via !247 command. - // Do NOT auto-add/remove channels on bot move. - } catch (e) { - logger.warn("[247] Bot move handler failed:", e.message); - } - } - - - if (!newChannelId && oldChannelId && guildId) { - try { - const cleanOld = cleanId(oldChannelId); - const cleanGuild = cleanId(guildId); - - if (this._inStartupGrace) { - const bootPlayer = remix.players.playerMap.get(cleanOld); - if (bootPlayer && !bootPlayer._destroyed) { - logger.voiceState( - `[VoiceState] Bot disconnected from ${cleanOld} during startup grace — ` + - `player still active, ignoring stale disconnect.` - ); - } else { - logger.voiceState( - `[VoiceState] Bot disconnected from ${cleanOld} during startup grace — ` + - `deferring until grace period ends.` - ); - } - return; - } - - if (remix.intentionalLeaves.has(cleanOld)) { - logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — intentional leave.`); - } else if (this._isGuildMoveInProgress(cleanGuild, cleanOld)) { - logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — guild move in progress, skipping.`); - } else if (this._bootRecoveryActive) { - logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — boot recovery active, skipping.`); - } else { - const set = remix.settingsMgr.getServer(guildId); - const mode = set ? get247ChannelMode(set, cleanOld) : "off"; - const wsInduced = this.isWsReconnectRecent(); - - if (mode === "on" || wsInduced) { - const reason = wsInduced && mode !== "on" - ? `WS reconnect detected (${Math.round((Date.now() - this._lastReadyAt) / 1000)}s ago) — treating as transient, scheduling rejoin` - : `24/7 mode — scheduling rejoin`; - logger.voice247( - `[VoiceState] Bot unexpectedly disconnected from ${cleanOld} — ${reason}.` - ); - const discPlayer = remix.players.playerMap.get(cleanOld); - if (discPlayer && !discPlayer._destroyed) { - remix.players.playerMap.delete(cleanOld); - const homeChannel = cleanId(discPlayer._home247Channel ?? ""); - if (homeChannel && homeChannel !== cleanOld) { - remix.players.playerMap.delete(homeChannel); - } - try { discPlayer.destroy(); } catch(e) { logger.warn("[VoiceState] Player destroy failed:", e?.message); } - const pendingScrobble = remix.players._pendingScrobbleTimers?.get(cleanOld); - if (pendingScrobble) { - clearTimeout(pendingScrobble.timer); - remix.players._pendingScrobbleTimers.delete(cleanOld); - } - } - const rejoinDelay = this.T.rejoin247Delay ?? 3_000; - setTimeout(() => { - this._rejoinChannel(cleanGuild, cleanOld).catch(err => { - logger.warn(`[VoiceState] Failed to rejoin ${cleanOld} after disconnect:`, err.message); - }); - }, rejoinDelay); - } else { - const leavePlayer = remix.players.playerMap.get(cleanOld); - if (leavePlayer && !leavePlayer.leaving && !leavePlayer._destroyed) { - logger.voiceState( - `[VoiceState] Bot disconnected from ${cleanOld} (24/7 mode: ${mode}) — emitting autoleave.` - ); - leavePlayer.emit("autoleave"); - } - } - } - } catch (e) { - logger.warn("[VoiceState] Bot disconnect handler failed:", e.message); - } - } - } - - /** @private @type {Set} @description Channel IDs currently being rejoined (duplicate guard). */ - _rejoinInProgress = new Set(); - - /** @private @type {Map} @description Channel ID → retry count for exponential backoff. */ - _rejoinAttempts = new Map(); - - /** @private @type {boolean} @description Whether boot recovery is actively rejoining 24/7 channels. */ - _bootRecoveryActive = false; - - /** @type {number} @description Maximum number of rejoin retry attempts per channel. */ - static MAX_REJOIN_RETRIES = 3; - - /** - * Attempt to spawn a player for a channel with exponential-backoff retries. - * @param {string} channelId - The target channel ID. - * @param {string} guildId - The guild ID. - * @param {number} [maxRetries=3] - Maximum retry attempts. - * @param {number} [baseDelay=5000] - Base delay in ms (doubled each retry). - * @param {string} [context='Rejoin'] - Label for log messages. - * @returns {Promise} The spawned player, or null if all retries failed. - * @private - */ - async _attemptRejoin(channelId, guildId, maxRetries = 3, baseDelay = 5_000, context = 'Rejoin') { - for (let attempt = 1; attempt <= maxRetries; attempt++) { - try { - const player = await this.remix._spawnPlayer(guildId, channelId); - this.reseedVoiceStatesForChannel(guildId, channelId); - logger.voice247( - `[${context}] Successfully rejoined channel ${channelId}` + - (attempt > 1 ? ` (after ${attempt - 1} retry/retries)` : '') - ); - return player; - } catch (err) { - const errMsg = err?.message ?? String(err); - const isTrackTimeout = errMsg.includes("track publication timed out") - || errMsg.includes("lavalink player create failed") - || errMsg.includes("Failed to create audio player") - || errMsg.includes("internal error"); - - if (isTrackTimeout && attempt < maxRetries) { - const backoffMs = baseDelay * Math.pow(2, attempt - 1); - logger.warn( - `[${context}] Track publication failed for channel ${channelId} (attempt ${attempt}/${maxRetries}) — ` + - `retrying in ${backoffMs / 1000}s: ${errMsg}` - ); - await new Promise(resolve => setTimeout(resolve, backoffMs)); - continue; - } - - logger.warn( - `[${context}] Failed to rejoin channel ${channelId} (attempt ${attempt}/${maxRetries}): ${errMsg}` + - (attempt > 1 ? ` (after ${attempt} attempts)` : '') - ); - return null; - } - } - return null; - } - - /** - * Safely rejoin a 24/7 channel. Guards against duplicate joins, - * intentional leaves, missing channels, and pending joins. - * @param {string} guildId - The guild ID. - * @param {string} channelId - The target channel ID. - * @returns {Promise} The spawned player, or null if skipped. - * @private - */ - async _rejoinChannel(guildId, channelId) { - const { remix } = this; - const cleanGuildId = cleanId(guildId); - const cleanChannelId = cleanId(channelId); - - if (this._rejoinInProgress.has(cleanChannelId)) { - logger.voice247(`[Rejoin] Channel ${cleanChannelId} rejoin already in progress — skipping.`); - return; - } - - const existing = remix.players.playerMap.get(cleanChannelId); - if (existing && !existing._destroyed) { - logger.voice247(`[Rejoin] Channel ${cleanChannelId} already has a player — skipping.`); - this._rejoinAttempts.delete(cleanChannelId); - return; - } - - if (remix.players._pendingJoins?.has?.(cleanChannelId)) { - logger.voice247(`[Rejoin] Channel ${cleanChannelId} already has a pending join — skipping.`); - return; - } - - if (remix.intentionalLeaves.has(cleanChannelId)) { - logger.voice247(`[Rejoin] Channel ${cleanChannelId} was intentionally left — skipping.`); - this._rejoinAttempts.delete(cleanChannelId); - return; - } - - const channel = remix.client?.channels?.get?.(cleanChannelId); - if (!channel) { - logger.voice247(`[Rejoin] Channel ${cleanChannelId} no longer exists — skipping.`); - this._rejoinAttempts.delete(cleanChannelId); - return; - } - - this._rejoinInProgress.add(cleanChannelId); - - const maxRetries = GatewayHandler.MAX_REJOIN_RETRIES; - logger.voice247( - `[Rejoin] Attempting to rejoin channel ${cleanChannelId} in guild ${cleanGuildId}...` - ); - - try { - const player = await this._attemptRejoin(cleanChannelId, cleanGuildId, maxRetries, 5_000, "Rejoin"); - if (player) { - this._rejoinAttempts.delete(cleanChannelId); - } else { - this._rejoinAttempts.delete(cleanChannelId); - } - return player; - } finally { - this._rejoinInProgress.delete(cleanChannelId); - } - } - - /** @private Check whether a guild currently has a move in progress (recently connected player or pending join). Used to suppress false positive disconnect-rejoin loops. @param {string} guildId - The guild ID. @param {string} oldChannelId - The channel the bot just left. @returns {boolean} True if a move is in progress within the evidence window. */ - _isGuildMoveInProgress(guildId, oldChannelId) { - const { remix } = this; - const cleanGuild = cleanId(guildId); - const cleanOld = cleanId(oldChannelId); - if (!cleanGuild || !cleanOld) return false; - - const now = Date.now(); - const activePlayers = [...remix.players.playerMap.values()].filter( - p => !p._destroyed && cleanId(p._guildId ?? "") === cleanGuild - ); - - for (const player of activePlayers) { - const playerChannel = cleanId(player._channelId ?? ""); - if (!playerChannel || playerChannel === cleanOld) continue; - const connectedAt = player._lastConnectedAt ?? 0; - if (now - connectedAt < this._moveEvidenceWindowMs) { - return true; - } - } - - if (remix.players._pendingJoins) { - for (const pendingId of remix.players._pendingJoins) { - const cleanPending = cleanId(pendingId); - if (cleanPending && cleanPending !== cleanOld) { - const pendingChannel = remix.client?.channels?.get?.(cleanPending); - if (pendingChannel && cleanId(pendingChannel.guildId ?? "") === cleanGuild) { - return true; - } - } - } - } - - return false; - } - - /** @async @private Fetch all guilds the bot is in via REST and create stub entries in the client cache for any missing guilds. This ensures settings and 24/7 lookups work even for guilds that haven't sent GUILD_CREATE yet. */ - async seedGuildsFromRest() { - const { remix } = this; - const client = remix.client; - - try { - let after = null; - let added = 0; - - while (true) { - const url = "/users/@me/guilds?limit=200" + (after ? "&after=" + after : ""); - const chunk = await client.rest.get(url); - - if (!Array.isArray(chunk) || chunk.length === 0) break; - - for (const g of chunk) { - const id = g?.id; - if (!id) continue; - if (!client.guilds.has(id)) { - try { - const Guild = this._getGuildClass(); - if (Guild) { - const stub = new Guild(client, { id, name: g.name ?? "unknown" }); - stub._stub = true; - client.guilds.set(id, stub); - } else { - client.guilds.set(id, { - id, - name: g.name ?? "unknown", - _stub: true, - members: { set: () => {}, get: () => undefined, has: () => false, me: null }, - channels: { set: () => {}, get: () => undefined, has: () => false }, - roles: { set: () => {}, get: () => undefined, has: () => false }, - emojis: { set: () => {}, get: () => undefined, has: () => false }, - stickers: { set: () => {}, get: () => undefined, has: () => false }, - }); - } - } catch (stubErr) { - logger.guild(`[GuildSeed] Guild constructor failed for ${id}, using safe stub: ${stubErr?.message}`); - client.guilds.set(id, { - id, - name: g.name ?? "unknown", - _stub: true, - members: { set: () => {}, get: () => undefined, has: () => false, me: null }, - channels: { set: () => {}, get: () => undefined, has: () => false }, - roles: { set: () => {}, get: () => undefined, has: () => false }, - emojis: { set: () => {}, get: () => undefined, has: () => false }, - stickers: { set: () => {}, get: () => undefined, has: () => false }, - }); - } - added++; - } - } - - if (chunk.length < 200) break; - after = chunk[chunk.length - 1].id; - } - - if (added > 0) { - logger.guild(`[GuildSeed] Added ${added} missing guild stub(s) from REST. Total: ${client.guilds.size}`); - } else { - logger.guild(`[GuildSeed] All guilds already cached. Total: ${client.guilds.size}`); - } - } catch (err) { - logger.warn("[GuildSeed] REST guild seeding failed:", err?.message ?? err); - } - } - - /** @private @returns {Function|null} The Guild constructor class. */ - _getGuildClass() { - if (this._GuildClass) return this._GuildClass; - try { - const { client } = this.remix; - for (const guild of client.guilds.values()) { - if (guild && !guild._stub && typeof guild.constructor === 'function' && guild.constructor.name === 'Guild') { - this._GuildClass = guild.constructor; - return this._GuildClass; - } - } - } catch(e) { logger.warn("[Gateway] _getGuildClass failed:", e?.message); } - this._GuildClass = null; - return null; - } - - /** - * Called when the bot receives the READY event. - * Seeds voice states, starts presence rotation, ends startup grace period, - * and begins 24/7 boot recovery. - */ - onReady() { - this._lastReadyAt = Date.now(); - this.seedVoiceStatesFromGuilds(); - this.seedGuildsFromRest().catch(e => logger.warn("[onReady] seedGuildsFromRest error:", e.message)); - this.attachRawListener(); - - this.setupPresenceRotation(); - - setTimeout(() => { - this._inStartupGrace = false; - const pending = this._deferredGuildDeletes.size; - if (pending > 0) { - logger.guild( - `[GuildDelete] Startup grace period ended. ` + - `${pending} deferred deletion(s) confirmed — cleaning up.` - ); - } else { - logger.guild(`[GuildDelete] Startup grace period ended. No deferred deletions.`); - } - if (this._deferredDeleteCount > 3) { - logger.guild( - `[GuildDelete] (Suppressed ${this._deferredDeleteCount - 3} deferral log lines for brevity)` - ); - } - }, this._startupDeleteGraceMs); - - this.rejoin247Channels(); - } - - /** - * Boot recovery: sequentially rejoin all saved 24/7 channels. - * Sets _bootRecoveryActive=true to suppress fake move events during the process. - * Cleans up missing channels from settings to prevent repeated failures. - * @returns {Promise} - */ - async rejoin247Channels() { - this._bootRecoveryActive = true; - try { - await this._rejoin247ChannelsInner(); - } catch (err) { - logger.warn("[BootRecovery] 24/7 boot recovery crashed:", err?.message ?? err); - } finally { - this._bootRecoveryActive = false; - } - } - - /** @private Inner boot-recovery loop. The flag reset is handled by the caller's finally block. */ - async _rejoin247ChannelsInner() { - const { remix } = this; - const channelsToRejoin = []; - - for (const [guildId, serverSettings] of remix.settingsMgr.guilds) { - const raw = serverSettings.get("stay_247"); - if (!raw || raw === "none") continue; - - const rawArr = Array.isArray(raw) ? raw : [raw]; - const channels = rawArr - .map(id => cleanId(id)) - .filter(id => id.length >= 15 && id.length <= 22); - - for (const channelId of channels) { - const mode = get247ChannelMode(serverSettings, channelId); - if (mode === "on") { - channelsToRejoin.push({ guildId, channelId, mode }); - } - } - } - - if (channelsToRejoin.length === 0) { - logger.voice247("[BootRecovery] No 24/7 channels to rejoin."); - return; - } - - logger.voice247( - `[BootRecovery] Found ${channelsToRejoin.length} 24/7 channel(s) to rejoin: ` + - channelsToRejoin.map(c => `${c.channelId}(${c.mode})`).join(", ") - ); - - const baseStagger = remix.config?.timers?.bootRejoinStagger ?? 5_000; - - for (let i = 0; i < channelsToRejoin.length; i++) { - const { guildId, channelId, mode } = channelsToRejoin[i]; - - if (i > 0) { - let staggerDelay = baseStagger; - if (i >= 8) staggerDelay = baseStagger * 2; - else if (i >= 4) staggerDelay = Math.round(baseStagger * 1.5); - logger.voice247(`[BootRecovery] Waiting ${staggerDelay / 1000}s before rejoining next channel...`); - await new Promise(resolve => setTimeout(resolve, staggerDelay)); - } - - const existing = remix.players.playerMap.get(channelId); - if (existing && !existing._destroyed) { - logger.voice247(`[BootRecovery] Channel ${channelId} already has a player — skipping.`); - continue; - } - if (remix.players._pendingJoins?.has?.(channelId)) { - logger.voice247(`[BootRecovery] Channel ${channelId} already has a pending join — skipping.`); - continue; - } - - const channelObj = remix.client?.channels?.get?.(channelId); - if (!channelObj) { - logger.warn( - `[BootRecovery] Channel ${channelId} in guild ${guildId} no longer exists — ` + - `removing from 24/7 settings to prevent repeated failures.` - ); - try { - const set = remix.settingsMgr.getServer(guildId); - if (set) { - const raw = set.get("stay_247"); - const arr = Array.isArray(raw) ? raw : raw ? [raw] : []; - const filtered = arr.filter(id => id && id !== "none" && cleanId(id) !== channelId); - const remainingSet = new Set(filtered.map(id => cleanId(id))); - remove247ChannelMode(set, channelId, remainingSet); - set.set("stay_247", filtered.length > 0 ? filtered : "none"); - } - } catch (cleanupErr) { - logger.warn(`[BootRecovery] Failed to auto-remove missing channel ${channelId} from 24/7:`, cleanupErr?.message); - } - continue; - } - if (channelObj.type !== 2) { - logger.warn( - `[BootRecovery] Channel ${channelId} in guild ${guildId} is not a voice channel (type: ${channelObj.type}) — skipping.` - ); - continue; - } - - const guildHasActivePlayer = [...remix.players.playerMap.values()] - .some(p => !p._destroyed && cleanId(p._guildId ?? "") === guildId); - if (guildHasActivePlayer && i > 0) { - const extraDelay = 3_000; - logger.voice247( - `[BootRecovery] Guild ${guildId} already has an active player — ` + - `waiting extra ${extraDelay / 1000}s to avoid move-disconnect.` - ); - await new Promise(resolve => setTimeout(resolve, extraDelay)); - } - - logger.voice247( - `[BootRecovery] Rejoining channel ${channelId} in guild ${guildId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]` - ); - - const player = await this._attemptRejoin(channelId, guildId, 3, 5_000, "BootRecovery"); - - if (player) { - logger.voice247( - `[BootRecovery] Successfully rejoined channel ${channelId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]` - ); - } else { - logger.warn( - `[BootRecovery] Failed to rejoin channel ${channelId} in guild ${guildId} after retries — ` + - `keeping 24/7 setting intact, will retry on next disconnect/restart.` - ); - } - } - - logger.voice247( - `[BootRecovery] Boot recovery complete. ${channelsToRejoin.length} channel(s) processed.` - ); - } - - /** - * Process a confirmed guild deletion. Cleans up voice cache and previous state. - * Does NOT delete 24/7 settings (preserved for re-invite). - * @param {string} guildId - The deleted guild ID. - * @private - */ - _processGuildDelete(guildId) { - const { remix } = this; - const cleanGuildId = cleanId(guildId); - - logger.guild( - `[GuildDelete] Received GuildDelete for server ${guildId} — ` + - `skipping removal (24/7 removal system disabled). ` + - `Settings and players are preserved. If the server truly removed the bot, ` + - `the GuildCreate handler will re-initialise on re-invite.` - ); - - remix.voiceCache.removeGuild(cleanGuildId); - for (const [stateKey, info] of [...this._prevVoiceState]) { - if (cleanId(info.guildId) === cleanGuildId) - this._prevVoiceState.delete(stateKey); - } - remix._announcementChannelCache?.delete(guildId); - } -} diff --git a/src/LastFmManager.mjs b/src/LastFmManager.mjs deleted file mode 100644 index ff321e9..0000000 --- a/src/LastFmManager.mjs +++ /dev/null @@ -1,2324 +0,0 @@ -/** @module src/LastFmManager @description Last.fm API integration for scrobbling, now-playing updates, loved tracks, and user session management with MySQL persistence. */ - -import crypto from "node:crypto"; -import { logger } from "./constants/Logger.mjs"; -import { Utils } from "./Utils.mjs"; - -const BASE_URL = "https://ws.audioscrobbler.com/2.0/"; - -/** @private @param {string} value @returns {string} */ -function normalizeTrackText(value) { - return Utils.normalizeText(value); -} - -/** @private Build an API signature per Last.fm auth spec. @param {object} params @param {string} apiSecret @returns {string} MD5 hex digest. */ -function buildSignature(params, apiSecret) { - const sorted = Object.keys(params).sort(); - const str = sorted.map(k => k + params[k]).join(""); - return crypto.createHash("md5").update(str + apiSecret).digest("hex"); -} - -/** @private Make an authenticated Last.fm API call. @async @param {object} params @param {string} apiSecret @param {boolean} [post=false] @returns {Promise} @throws {Error} On HTTP or Last.fm API error. */ -async function apiCall(params, apiSecret, post = false) { - const allParams = { ...params }; - allParams.api_sig = buildSignature(allParams, apiSecret); - allParams.format = "json"; - - const url = post ? BASE_URL : `${BASE_URL}?${new URLSearchParams(allParams)}`; - - const opts = post - ? { - method: "POST", - headers: { "Content-Type": "application/x-www-form-urlencoded" }, - body: new URLSearchParams(allParams).toString(), - } - : {}; - - const res = await fetch(url, opts); - if (!res.ok) { - const text = await res.text().catch(() => ""); - throw new Error(`Last.fm HTTP ${res.status}: ${text.slice(0, 200)}`); - } - - const data = await res.json(); - if (data.error) { - throw new Error(`Last.fm ${data.error}: ${data.message}`); - } - return data; -} - -/** @class LastFmManager @description Manages Last.fm user sessions, scrobbling, loved tracks, and top/recent track queries with MySQL persistence. */ -export class LastFmManager { - /** @param {object} config @param {string} config.apiKey @param {string} config.apiSecret @param {boolean} [config.enabled] @param {number} [config.scrobbleThreshold] @param {number} [config.scrobbleMinMs] @param {object} mysqlConfig */ - constructor(config, mysqlConfig) { - this.apiKey = config?.apiKey ?? ""; - this.apiSecret = config?.apiSecret ?? ""; - this.enabled = config?.enabled !== false && !!(this.apiKey && this.apiSecret); - this.scrobbleThreshold = config?.scrobbleThreshold ?? 0.5; - this.scrobbleMinMs = config?.scrobbleMinMs ?? 240_000; - - this._mysqlConfig = mysqlConfig; - this._pool = null; - - this.botId = null; - this._hasBotIdColumn = false; - - this._userCache = new Map(); - this._userCacheMax = 5000; - - this._totalScrobblesCache = null; - this._totalScrobblesCacheExpiry = 0; - this._totalScrobblesInflight = null; - - if (!this.enabled) { - if (config?.enabled === false) { - logger.settings("[LastFm] Disabled — \"enabled\" is set to false in config."); - } else { - logger.settings("[LastFm] Disabled — apiKey or apiSecret missing in config."); - } - } - } - - /** @async Set the bot ID for multi-bot isolation. @param {string} id */ - async setBotId(id) { - const changed = this.botId !== id; - this.botId = id; - if (changed) { - await this._ensureBotIdColumn(); - this._userCache.clear(); - } - } - - /** @private @async Ensure the bot_id column exists and is part of the primary key. */ - async _ensureBotIdColumn() { - if (this._hasBotIdColumn) return; - const pool = await this._getPool(); - - 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..."); - await pool.execute("ALTER TABLE `lastfm_users` ADD COLUMN `bot_id` VARCHAR(32) NOT NULL DEFAULT ''"); - 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 { - const colInfo = cols[0]; - const isNullable = colInfo.IS_NULLABLE === 'YES'; - const isPK = colInfo.COLUMN_KEY === 'PRI'; - if (!isPK) { - logger.settings("[LastFm] Fixing lastfm_users.bot_id: adding to primary key..."); - if (isNullable) { - await pool.execute("UPDATE `lastfm_users` SET `bot_id` = '' WHERE `bot_id` IS NULL"); - await pool.execute("ALTER TABLE `lastfm_users` MODIFY COLUMN `bot_id` VARCHAR(32) NOT NULL DEFAULT ''"); - } - 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] Fix complete: lastfm_users.bot_id added to primary key."); - } - } - - 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'` - ); - if (statsCols.length === 0) { - logger.settings("[LastFm] Auto-migrating: adding bot_id column to lastfm_stats..."); - await pool.execute("ALTER TABLE `lastfm_stats` ADD COLUMN `bot_id` VARCHAR(32) NOT NULL DEFAULT ''"); - if (this.botId) { - await pool.execute("UPDATE `lastfm_stats` SET `bot_id` = ? WHERE `bot_id` = ''", [String(this.botId)]); - } - await pool.execute("ALTER TABLE `lastfm_stats` DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)"); - logger.settings("[LastFm] Auto-migration complete: lastfm_stats.bot_id added."); - } else { - const colInfo = statsCols[0]; - const isNullable = colInfo.IS_NULLABLE === 'YES'; - const isPK = colInfo.COLUMN_KEY === 'PRI'; - if (!isPK) { - logger.settings("[LastFm] Fixing lastfm_stats.bot_id: adding to primary key..."); - if (isNullable) { - await pool.execute("UPDATE `lastfm_stats` SET `bot_id` = '' WHERE `bot_id` IS NULL"); - await pool.execute("ALTER TABLE `lastfm_stats` MODIFY COLUMN `bot_id` VARCHAR(32) NOT NULL DEFAULT ''"); - } - if (this.botId) { - await pool.execute("UPDATE `lastfm_stats` SET `bot_id` = ? WHERE `bot_id` = ''", [String(this.botId)]); - } - await pool.execute("ALTER TABLE `lastfm_stats` DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)"); - logger.settings("[LastFm] Fix complete: lastfm_stats.bot_id added to primary key."); - } - } - - this._hasBotIdColumn = true; - } - - /** @private @returns {{where: string, params: Array}} SQL filter fragment for bot_id. */ - _botIdFilter() { - if (!this.botId || !this._hasBotIdColumn) return { where: "", params: [] }; - return { where: " AND bot_id = ?", params: [String(this.botId)] }; - } - - /** @private @async Get or create the MySQL connection pool. @returns {Promise} */ - async _getPool() { - if (this._pool) return this._pool; - const mysql = await import("mysql2/promise"); - this._pool = mysql.createPool({ - host: this._mysqlConfig.host, - port: this._mysqlConfig.port ?? 3306, - user: this._mysqlConfig.user, - password: this._mysqlConfig.password, - database: this._mysqlConfig.database, - }); - await this._initTable(); - return this._pool; - } - - /** @private @async Create the lastfm_users and lastfm_stats tables if they don't exist. */ - async _initTable() { - const pool = this._pool; - await pool.execute(` - CREATE TABLE IF NOT EXISTS \`lastfm_users\` ( - \`user_id\` VARCHAR(30) NOT NULL PRIMARY KEY, - \`session_key\` VARCHAR(64) NOT NULL, - \`username\` VARCHAR(64) NOT NULL DEFAULT '', - \`scrobble\` TINYINT(1) NOT NULL DEFAULT 1, - \`scrobble_count\` BIGINT NOT NULL DEFAULT 0, - \`linked_at\` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - `); - - await pool.execute(` - CREATE TABLE IF NOT EXISTS \`lastfm_stats\` ( - \`id\` TINYINT(1) NOT NULL PRIMARY KEY DEFAULT 1, - \`stored_scrobbles\` BIGINT NOT NULL DEFAULT 0, - \`linked_users\` INT NOT NULL DEFAULT 0 - ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; - `); - await pool.execute(` - INSERT IGNORE INTO \`lastfm_stats\` (id, stored_scrobbles, linked_users) VALUES (1, 0, 0) - `); - } - - /** @async Get a user's Last.fm session from cache or DB. @param {string} userId @returns {Promise<{sessionKey: string, username: string, scrobbleEnabled: boolean}|null>} */ - async getUser(userId) { - const cached = this._userCache.get(userId); - if (cached) return cached; - - const pool = await this._getPool(); - const f = this._botIdFilter(); - const [rows] = await pool.execute( - `SELECT session_key, username, scrobble FROM lastfm_users WHERE user_id = ?${f.where}`, - [String(userId), ...f.params] - ); - - if (!rows.length) return null; - - const row = rows[0]; - const data = { - sessionKey: row.session_key, - username: row.username, - scrobbleEnabled: !!row.scrobble, - }; - this._userCache.set(userId, data); - while (this._userCache.size > this._userCacheMax) { - const oldestKey = this._userCache.keys().next().value; - this._userCache.delete(oldestKey); - } - return data; - } - - /** @async Save or update a user's Last.fm session. @param {string} userId @param {string} sessionKey @param {string} username @returns {Promise<{sessionKey: string, username: string, scrobbleEnabled: boolean}>} */ - async saveUser(userId, sessionKey, username) { - const pool = await this._getPool(); - const f = this._botIdFilter(); - await pool.execute( - `INSERT INTO lastfm_users (user_id, session_key, username, scrobble${f.where ? ', bot_id' : ''}) - VALUES (?, ?, ?, 1${f.where ? ', ?' : ''}) - ON DUPLICATE KEY UPDATE session_key = VALUES(session_key), username = VALUES(username)`, - [String(userId), sessionKey, username ?? "", ...f.params] - ); - const data = { sessionKey, username: username ?? "", scrobbleEnabled: true }; - this._userCache.set(userId, data); - while (this._userCache.size > this._userCacheMax) { - const oldestKey = this._userCache.keys().next().value; - this._userCache.delete(oldestKey); - } - - 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 (e) { - logger.warn("[LastFm] Stats update warning:", e?.message); - } - - return data; - } - - /** @async Remove a user's Last.fm session from cache and DB. @param {string} userId */ - async removeUser(userId) { - const pool = await this._getPool(); - const f = this._botIdFilter(); - await pool.execute(`DELETE FROM lastfm_users WHERE user_id = ?${f.where}`, [String(userId), ...f.params]); - this._userCache.delete(userId); - } - - /** @async Toggle scrobbling for a user. @param {string} userId @param {boolean} enabled */ - async setScrobble(userId, enabled) { - const pool = await this._getPool(); - const f = this._botIdFilter(); - await pool.execute( - `UPDATE lastfm_users SET scrobble = ? WHERE user_id = ?${f.where}`, - [enabled ? 1 : 0, String(userId), ...f.params] - ); - const cached = this._userCache.get(userId); - if (cached) cached.scrobbleEnabled = enabled; - } - - /** @async Request a Last.fm auth token. @returns {Promise} The auth token. @throws {Error} If Last.fm is not enabled. */ - async getAuthToken() { - this._assertEnabled(); - const data = await apiCall( - { method: "auth.gettoken", api_key: this.apiKey }, - this.apiSecret - ); - return data.token; - } - - /** Build the Last.fm auth URL for user authorization. @param {string} token @returns {string} */ - getAuthUrl(token) { - return `https://www.last.fm/api/auth/?api_key=${this.apiKey}&token=${token}`; - } - - /** @async Exchange an auth token for a session. @param {string} token @returns {Promise} The session object with key and name. @throws {Error} If Last.fm is not enabled. */ - async getSession(token) { - this._assertEnabled(); - const data = await apiCall( - { method: "auth.getsession", api_key: this.apiKey, token }, - this.apiSecret - ); - return data.session; - } - - /** @async Send a now-playing update to Last.fm for a user. @param {string} userId @param {object} track @param {string} track.title @param {string} [track.album] @param {number} [track.trackNumber] */ - async updateNowPlaying(userId, track) { - if (!this.enabled) return; - const user = await this.getUser(userId); - if (!user || !user.scrobbleEnabled) return; - - try { - await apiCall( - { - method: "track.updatenowplaying", - api_key: this.apiKey, - sk: user.sessionKey, - artist: this._extractArtist(track), - track: this._extractTitle(track), - album: track.album ?? "", - duration: this._extractDurationSec(track), - trackNumber: track.trackNumber ?? "", - }, - this.apiSecret, - true - ); - } catch (err) { - logger.warn(`[LastFm] updateNowPlaying failed for ${userId}: ${err.message}`); - } - } - - /** @async Scrobble a track for a user. @param {string} userId @param {object} track @param {number} startedAtMs @param {string} track.title @param {string} [track.album] @param {number} [track.trackNumber] */ - async scrobble(userId, track, startedAtMs) { - if (!this.enabled) return; - const user = await this.getUser(userId); - if (!user || !user.scrobbleEnabled) return; - - try { - await apiCall( - { - method: "track.scrobble", - api_key: this.apiKey, - sk: user.sessionKey, - "artist[0]": this._extractArtist(track), - "track[0]": this._extractTitle(track), - "album[0]": track.album ?? "", - "timestamp[0]": Math.floor(startedAtMs / 1000), - "duration[0]": this._extractDurationSec(track), - }, - this.apiSecret, - true - ); - logger.settings(`[LastFm] Scrobbled "${track.title}" for ${userId}`); - - this._incrementScrobbleCount(userId); - } catch (err) { - logger.warn(`[LastFm] Scrobble failed for ${userId}: ${err.message}`); - } - } - - /** @async Get a user's loved tracks. @param {string} userId @param {number} [limit=20] @returns {Promise>} @throws {Error} If user not linked. */ - async getLovedTracks(userId, limit = 20) { - const user = await this.getUser(userId); - if (!user) throw new Error("NOT_LINKED"); - - const data = await apiCall( - { - method: "user.getlovedtracks", - api_key: this.apiKey, - user: user.username, - limit, - }, - this.apiSecret - ); - - return (data.lovedtracks?.track ?? []).map(t => ({ - artist: t.artist?.name ?? t.artist?.["#text"] ?? "Unknown", - name: t.name, - url: t.url, - image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "", - })); - } - - /** @async Get a user's top tracks. @param {string} userId @param {string} [period="overall"] @param {number} [limit=20] @returns {Promise>} @throws {Error} If user not linked. */ - async getTopTracks(userId, period = "overall", limit = 20) { - const user = await this.getUser(userId); - if (!user) throw new Error("NOT_LINKED"); - - const data = await apiCall( - { - method: "user.gettoptracks", - api_key: this.apiKey, - user: user.username, - period, - limit, - }, - this.apiSecret - ); - - return (data.toptracks?.track ?? []).map(t => ({ - artist: t.artist?.name ?? "Unknown", - name: t.name, - url: t.url, - playcount: t.playcount ?? 0, - image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "", - })); - } - - /** @async Get a user's recent tracks. @param {string} userId @param {number} [limit=20] @returns {Promise>} @throws {Error} If user not linked. */ - async getRecentTracks(userId, limit = 20) { - const user = await this.getUser(userId); - if (!user) throw new Error("NOT_LINKED"); - - const data = await apiCall( - { - method: "user.getrecenttracks", - api_key: this.apiKey, - user: user.username, - limit, - }, - this.apiSecret - ); - - return (data.recenttracks?.track ?? []).map(t => ({ - artist: t.artist?.["#text"] ?? t.artist?.name ?? "Unknown", - name: t.name, - url: t.url, - now: t["@attr"]?.nowplaying === "true", - image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "", - })); - } - - /** @async Get track info from Last.fm. @param {string} artist @param {string} track @param {string} [userId] @returns {Promise} Track info object or null. */ - async getTrackInfo(artist, track, userId = null) { - if (!this.enabled) return null; - - const params = { - method: "track.getinfo", - api_key: this.apiKey, - artist, - track, - }; - - if (userId) { - const user = await this.getUser(userId); - if (user) params.username = user.username; - } - - try { - const data = await apiCall(params, this.apiSecret); - return data.track; - } catch (e) { - logger.warn("[LastFm] Error:", e?.message); - return null; - } - } - - /** @async Love a track on Last.fm. @param {string} userId @param {string} artist @param {string} track @throws {Error} If user not linked. */ - async loveTrack(userId, artist, track) { - if (!this.enabled) return; - const user = await this.getUser(userId); - if (!user) throw new Error("NOT_LINKED"); - - await apiCall( - { - method: "track.love", - api_key: this.apiKey, - sk: user.sessionKey, - artist, - track, - }, - this.apiSecret, - true - ); - } - - /** @async Unlove a track on Last.fm. @param {string} userId @param {string} artist @param {string} track @throws {Error} If user not linked. */ - async unloveTrack(userId, artist, track) { - if (!this.enabled) return; - const user = await this.getUser(userId); - if (!user) throw new Error("NOT_LINKED"); - - await apiCall( - { - method: "track.unlove", - api_key: this.apiKey, - sk: user.sessionKey, - artist, - track, - }, - this.apiSecret, - true - ); - } - - /** @async Search for tracks on Last.fm and score results by relevance. @param {string} query @param {number} [limit=10] @returns {Promise|null>} */ - async searchTrack(query, limit = 10) { - if (!this.enabled) return null; - - const data = await apiCall( - { - method: "track.search", - api_key: this.apiKey, - track: query, - limit, - }, - this.apiSecret - ); - - const matches = data?.results?.trackmatches?.track; - const tracks = Array.isArray(matches) - ? matches - : matches - ? [matches] - : []; - - if (!tracks.length) return null; - - const normalizedQuery = normalizeTrackText(query); - const queryTokens = normalizedQuery.split(" ").filter(Boolean); - - const scored = tracks.map((track, index) => { - const artist = String(track.artist ?? "").trim(); - const name = String(track.name ?? "").trim(); - const artistNorm = normalizeTrackText(artist); - const nameNorm = normalizeTrackText(name); - const combined = `${artistNorm} ${nameNorm}`.trim(); - - let score = 0; - - if (combined === normalizedQuery) score += 50; - if (combined.includes(normalizedQuery) && normalizedQuery) score += 25; - if (normalizedQuery.includes(nameNorm) && nameNorm) score += 15; - if (normalizedQuery.includes(artistNorm) && artistNorm) score += 12; - - const overlap = queryTokens.filter(token => combined.includes(token)).length; - score += overlap * 4; - - const nameLower = name.toLowerCase(); - const artistLower = artist.toLowerCase(); - const urlLower = String(track.url ?? "").toLowerCase(); - const fullText = `${nameLower} ${artistLower} ${urlLower}`; - - const negativePatterns = [ - /\bofficial (?:lyric|lyrics)\s*video\b/, - /\bofficial video\b/, - /\bofficial music video\b/, - /\blyric video\b/, - /\blyrics video\b/, - /\bmusic video\b/, - /\bofficial audio\b/, - /\bvisuali[sz]er\b/, - /\bkaraoke\b/, - /\bcover\b/, - /\bremix\b/, - /\bacoustic\b/, - /\blive\b/, - /\bsped up\b/, - /\bslowed\b/, - /\breverb\b/, - /\bnightcore\b/, - /\b8d\b/, - /\bclip officiel\b/, - /\bvideo oficial\b/, - /\bperformance\b/, - ]; - - for (const re of negativePatterns) { - if (re.test(fullText)) { - score -= 30; - break; - } - } - - const labelKeywords = [ - /\bpictures\b/i, - /\banimation\b/i, - /\brecords?\b/i, - /\bstudios?\b/i, - /\bentertainment\b/i, - /\bproductions?\b/i, - /\bmusic\s+(group|corp|inc|llc)\b/i, - /\brecordings?\b/i, - /\blabel\b/i, - ]; - for (const re of labelKeywords) { - if (re.test(artist)) { - score -= 20; - break; - } - } - - if (/^["""].*["""]$/.test(name) || /["""]/.test(name)) { - score -= 15; - } - - if (urlLower.includes("/_/")) { - score += 5; - } - - return { - index, - score, - track: { - artist, - name, - url: track.url ?? "", - }, - }; - }); - - scored.sort((a, b) => b.score - a.score || a.index - b.index); - return scored[0]?.track ?? null; - } - - /** - * Get similar tracks for a given artist and track from Last.fm. - * @async - * @param {string} artist - The artist name. - * @param {string} track - The track name. - * @param {number} [limit=5] - Maximum number of results. - * @returns {Promise>} Filtered similar tracks (match > 0.1). - */ - async getSimilarTracks(artist, track, limit = 5) { - if (!this.enabled) return []; - - try { - const data = await apiCall( - { - method: "track.getsimilar", - api_key: this.apiKey, - artist, - track, - limit, - }, - this.apiSecret - ); - - return (data.similartracks?.track ?? []).map(t => ({ - artist: t.artist?.name ?? "Unknown", - name: t.name, - url: t.url ?? "", - match: parseFloat(t.match ?? 0), - })).filter(t => t.match > 0.1); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** - * Get detailed artist info from Last.fm. - * @async - * @param {string} artist - The artist name. - * @param {string|null} [userId] - Optional user ID to include user playcount. - * @returns {Promise} Artist info object with name, url, image, tags, bio, stats, similar, and userplaycount, or null. - */ - async getArtistInfo(artist, userId = null) { - if (!this.enabled) return null; - - const params = { - method: "artist.getinfo", - api_key: this.apiKey, - artist, - }; - - if (userId) { - const user = await this.getUser(userId); - if (user) params.username = user.username; - } - - try { - const data = await apiCall(params, this.apiSecret); - const a = data.artist; - if (!a) return null; - - return { - name: a.name ?? "", - url: a.url ?? "", - image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", - tags: (a.tags?.tag ?? []).map(t => t.name ?? t), - bio: a.bio?.summary ?? a.bio?.content ?? "", - stats: { - listeners: Number(a.stats?.listeners ?? 0), - playcount: Number(a.stats?.playcount ?? 0), - }, - similar: (a.similar?.artist ?? []).map(s => ({ - name: s.name ?? "", - url: s.url ?? "", - image: s.image?.[2]?.["#text"] ?? s.image?.[1]?.["#text"] ?? "", - })), - userplaycount: a.stats?.userplaycount ? Number(a.stats.userplaycount) : null, - }; - } catch (e) { - logger.warn("[LastFm] Error:", e?.message); - return null; - } - } - - /** - * Get detailed album info from Last.fm. - * @async - * @param {string} artist - The artist name. - * @param {string} album - The album name. - * @param {string|null} [userId] - Optional user ID to include user playcount. - * @returns {Promise} Album info object with name, artist, url, image, tags, tracks, and userplaycount, or null. - */ - async getAlbumInfo(artist, album, userId = null) { - if (!this.enabled) return null; - - const params = { - method: "album.getinfo", - api_key: this.apiKey, - artist, - album, - }; - - if (userId) { - const user = await this.getUser(userId); - if (user) params.username = user.username; - } - - try { - const data = await apiCall(params, this.apiSecret); - const a = data.album; - if (!a) return null; - - return { - name: a.name ?? "", - artist: a.artist ?? "", - url: a.url ?? "", - image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", - tags: (a.tags?.tag ?? []).map(t => t.name ?? t), - tracks: (a.tracks?.track ?? []).map(t => ({ - name: t.name ?? "", - url: t.url ?? "", - duration: Number(t.duration ?? 0), - playcount: Number(t.playcount ?? 0), - })), - userplaycount: a.userplaycount ? Number(a.userplaycount) : null, - }; - } catch (e) { - logger.warn("[LastFm] Error:", e?.message); - return null; - } - } - - /** - * Get top tracks for an artist from Last.fm. - * @async - * @param {string} artist - The artist name. - * @param {number} [limit=10] - Maximum number of results. - * @returns {Promise>} Top tracks. - */ - async getArtistTopTracks(artist, limit = 10) { - if (!this.enabled) return []; - - try { - const data = await apiCall( - { - method: "artist.gettoptracks", - api_key: this.apiKey, - artist, - limit, - }, - this.apiSecret - ); - - return (data.toptracks?.track ?? []).map(t => ({ - artist: t.artist?.name ?? artist, - name: t.name ?? "", - url: t.url ?? "", - playcount: Number(t.playcount ?? 0), - image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "", - })); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** - * Get top albums for an artist from Last.fm. - * @async - * @param {string} artist - The artist name. - * @param {number} [limit=10] - Maximum number of results. - * @returns {Promise>} Top albums. - */ - async getArtistTopAlbums(artist, limit = 10) { - if (!this.enabled) return []; - - try { - const data = await apiCall( - { - method: "artist.gettopalbums", - api_key: this.apiKey, - artist, - limit, - }, - this.apiSecret - ); - - return (data.topalbums?.album ?? []).map(a => ({ - name: a.name ?? "", - artist: a.artist?.name ?? artist, - url: a.url ?? "", - playcount: Number(a.playcount ?? 0), - image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", - })); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** - * Get similar artists for a given artist from Last.fm. - * @async - * @param {string} artist - The artist name. - * @param {number} [limit=10] - Maximum number of results. - * @returns {Promise>} Similar artists. - */ - async getSimilarArtists(artist, limit = 10) { - if (!this.enabled) return []; - - try { - const data = await apiCall( - { - method: "artist.getsimilar", - api_key: this.apiKey, - artist, - limit, - }, - this.apiSecret - ); - - return (data.similarartists?.artist ?? []).map(a => ({ - name: a.name ?? "", - url: a.url ?? "", - image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", - match: parseFloat(a.match ?? 0), - })); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** - * Get a user's top tags from Last.fm. - * @async - * @param {string} userId - The Discord user ID. - * @param {number} [limit=20] - Maximum number of results. - * @returns {Promise>} Top tags. - */ - async getUserTopTags(userId, limit = 20) { - if (!this.enabled) return []; - - const user = await this.getUser(userId); - if (!user) return []; - - try { - const data = await apiCall( - { - method: "user.gettoptags", - api_key: this.apiKey, - user: user.username, - limit, - }, - this.apiSecret - ); - - return (data.toptags?.tag ?? []).map(t => ({ - name: t.name ?? "", - url: t.url ?? "", - count: Number(t.count ?? 0), - })); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** - * Get information about a specific tag from Last.fm. - * @async - * @param {string} tag - The tag name. - * @returns {Promise} Tag info with name, url, reach, count, and summary, or null. - */ - async getTagInfo(tag) { - if (!this.enabled) return null; - - try { - const data = await apiCall( - { - method: "tag.getinfo", - api_key: this.apiKey, - tag, - }, - this.apiSecret - ); - - const t = data.tag; - if (!t) return null; - - return { - name: t.name ?? "", - url: t.url ?? "", - reach: Number(t.reach ?? 0), - count: Number(t.taggings?.total ?? t.total ?? 0), - summary: t.wiki?.summary ?? "", - }; - } catch (e) { - logger.warn("[LastFm] Error:", e?.message); - return null; - } - } - - /** - * Get top tracks for a tag from Last.fm. - * @async - * @param {string} tag - The tag name. - * @param {number} [limit=10] - Maximum number of results. - * @returns {Promise>} Tag's top tracks. - */ - async getTagTopTracks(tag, limit = 10) { - if (!this.enabled) return []; - - try { - const data = await apiCall( - { - method: "tag.gettoptracks", - api_key: this.apiKey, - tag, - limit, - }, - this.apiSecret - ); - - return (data.tracks?.track ?? []).map(t => ({ - artist: t.artist?.name ?? "Unknown", - name: t.name ?? "", - url: t.url ?? "", - playcount: Number(t.playcount ?? 0), - image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "", - })); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** - * Get top artists for a tag from Last.fm. - * @async - * @param {string} tag - The tag name. - * @param {number} [limit=10] - Maximum number of results. - * @returns {Promise>} Tag's top artists. - */ - async getTagTopArtists(tag, limit = 10) { - if (!this.enabled) return []; - - try { - const data = await apiCall( - { - method: "tag.gettopartists", - api_key: this.apiKey, - tag, - limit, - }, - this.apiSecret - ); - - return (data.topartists?.artist ?? []).map(a => ({ - name: a.name ?? "", - url: a.url ?? "", - playcount: Number(a.playcount ?? 0), - image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", - })); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** - * Get who knows an artist among a list of users, ranked by playcount. - * @async - * @param {string} artist - The artist name. - * @param {Array} userIds - Array of Discord user IDs. - * @returns {Promise>} Users who know the artist, sorted by playcount descending. - */ - async getWhoKnows(artist, userIds) { - if (!this.enabled) return []; - if (!Array.isArray(userIds) || !userIds.length) return []; - - const concurrency = 5; - const results = []; - - for (let i = 0; i < userIds.length; i += concurrency) { - const batch = userIds.slice(i, i + concurrency); - - const batchResults = await Promise.allSettled( - batch.map(async (uid) => { - const user = await this.getUser(uid); - if (!user) return null; - - try { - const info = await this.getArtistInfo(artist, uid); - const playcount = info?.userplaycount ?? 0; - return { - userId: uid, - username: user.username, - playcount, - }; - } catch (e) { - logger.warn("[LastFm] Error:", e?.message); - return { - userId: uid, - username: user.username, - playcount: 0, - }; - } - }) - ); - - for (const r of batchResults) { - if (r.status === "fulfilled" && r.value && r.value.playcount > 0) { - results.push(r.value); - } - } - } - - results.sort((a, b) => b.playcount - a.playcount); - return results; - } - - /** - * Compare two users' top artists and compute a match percentage. - * @async - * @param {string} userId1 - First Discord user ID. - * @param {string} userId2 - Second Discord user ID. - * @returns {Promise} Comparison result with user1, user2, commonArtists, and matchPercentage, or null. - */ - async compareUsers(userId1, userId2) { - if (!this.enabled) return null; - - try { - const user1Data = await this.getUser(userId1); - const user2Data = await this.getUser(userId2); - if (!user1Data || !user2Data) return null; - - const [artists1, artists2] = await Promise.all([ - this.getTopArtists(userId1, "overall", 50), - this.getTopArtists(userId2, "overall", 50), - ]); - - const names1 = new Set(artists1.map(a => a.name.toLowerCase())); - const names2 = new Set(artists2.map(a => a.name.toLowerCase())); - - const commonNames = [...names1].filter(n => names2.has(n)); - const commonArtists = artists1 - .filter(a => names2.has(a.name.toLowerCase())) - .map(a => ({ - name: a.name, - url: a.url, - playcount: a.playcount, - })); - - const totalUnique = new Set([...names1, ...names2]).size; - const matchPercentage = totalUnique > 0 - ? Math.round((commonNames.length / totalUnique) * 100) - : 0; - - return { - user1: { - username: user1Data.username, - totalArtists: names1.size, - }, - user2: { - username: user2Data.username, - totalArtists: names2.size, - }, - commonArtists, - matchPercentage, - }; - } catch (e) { - logger.warn("[LastFm] Error:", e?.message); - return null; - } - } - - /** - * Get the list of weekly chart periods for a user. - * @async - * @param {string} userId - The Discord user ID. - * @returns {Promise>} Weekly chart periods with Unix timestamps. - */ - async getUserWeeklyChartList(userId) { - if (!this.enabled) return []; - - const user = await this.getUser(userId); - if (!user) return []; - - try { - const data = await apiCall( - { - method: "user.getweeklychartlist", - api_key: this.apiKey, - user: user.username, - }, - this.apiSecret - ); - - return (data.weeklychartlist?.chart ?? []).map(c => ({ - from: Number(c.from ?? 0), - to: Number(c.to ?? 0), - })); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** - * Search for artists on Last.fm. - * @async - * @param {string} query - The search query. - * @param {number} [limit=10] - Maximum number of results. - * @returns {Promise>} Matching artists. - */ - async searchArtist(query, limit = 10) { - if (!this.enabled) return []; - - try { - const data = await apiCall( - { - method: "artist.search", - api_key: this.apiKey, - artist: query, - limit, - }, - this.apiSecret - ); - - const matches = data?.results?.artistmatches?.artist; - const artists = Array.isArray(matches) - ? matches - : matches - ? [matches] - : []; - - return artists.map(a => ({ - name: a.name ?? "", - url: a.url ?? "", - image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", - listeners: Number(a.listeners ?? 0), - })); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** - * Search for albums on Last.fm. - * @async - * @param {string} query - The search query. - * @param {number} [limit=10] - Maximum number of results. - * @returns {Promise>} Matching albums. - */ - async searchAlbum(query, limit = 10) { - if (!this.enabled) return []; - - try { - const data = await apiCall( - { - method: "album.search", - api_key: this.apiKey, - album: query, - limit, - }, - this.apiSecret - ); - - const matches = data?.results?.albummatches?.album; - const albums = Array.isArray(matches) - ? matches - : matches - ? [matches] - : []; - - return albums.map(a => ({ - name: a.name ?? "", - artist: a.artist ?? "", - url: a.url ?? "", - image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", - })); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** - * Parse a Last.fm music URL into artist, track, and album components. - * @param {string} url - The Last.fm URL to parse. - * @returns {object|null} Parsed components { artist, track, album, url } or null if invalid. - */ - parseLastFmUrl(url) { - return parseLastFmUrl(url); - } - - /** - * Check whether a string is a valid Last.fm music URL. - * @param {string} str - String to check. - * @returns {boolean} True if the string is a Last.fm music URL. - */ - isLastFmUrl(str) { - return isLastFmUrl(str); - } - - /** - * Get a user's Last.fm profile info. - * @async - * @param {string} userId - The Discord user ID. - * @returns {Promise} The Last.fm user object. - * @throws {Error} If user is not linked. - */ - async getUserInfo(userId) { - const user = await this.getUser(userId); - if (!user) throw new Error("NOT_LINKED"); - - const data = await apiCall( - { - method: "user.getinfo", - api_key: this.apiKey, - user: user.username, - }, - this.apiSecret - ); - - return data.user; - } - - /** - * Get a user's Last.fm playlists by scraping their profile page. - * @async - * @param {string} userId - The Discord user ID. - * @returns {Promise>} User's playlists. - * @throws {Error} If user is not linked or fetch fails. - */ - async getPlaylists(userId) { - const user = await this.getUser(userId); - if (!user) throw new Error("NOT_LINKED"); - - const profileUrl = `https://www.last.fm/user/${encodeURIComponent(user.username)}/playlists`; - const res = await fetch(profileUrl, { - headers: { "User-Agent": "RemixBot/1.0 (Last.fm Integration)" }, - }); - - if (!res.ok) { - throw new Error(`Failed to fetch profile page (HTTP ${res.status})`); - } - - const html = await res.text(); - const playlists = []; - - const playlistRegex = /href="\/user\/[^/]+\/playlists\/(\d+)"[^>]*>([^<]+)<\/a>/gi; - let match; - while ((match = playlistRegex.exec(html)) !== null) { - const id = match[1]; - const title = match[2].trim(); - if (title && id) { - playlists.push({ - id, - title, - url: `https://www.last.fm/user/${user.username}/playlists/${id}`, - }); - } - } - - const countRegex = /(\d+)\s+track/gi; - const counts = []; - let cMatch; - while ((cMatch = countRegex.exec(html)) !== null) { - counts.push(+cMatch[1]); - } - playlists.forEach((pl, i) => { - pl.trackCount = counts[i] ?? 0; - }); - - return playlists; - } - - /** - * Get tracks from a user's Last.fm playlist by scraping the playlist page. - * @async - * @param {string} userId - The Discord user ID. - * @param {string|number} playlistId - Playlist number (1-based index) or URL. - * @param {number} [limit=50] - Maximum number of tracks. - * @returns {Promise>} Playlist tracks. - * @throws {Error} If user is not linked or playlist not found. - */ - async getPlaylistTracks(userId, playlistId, limit = 50) { - const user = await this.getUser(userId); - if (!user) throw new Error("NOT_LINKED"); - - let playlistUrl; - - if (/^\d+$/.test(String(playlistId))) { - const playlists = await this.getPlaylists(userId); - const idx = +playlistId - 1; - if (idx < 0 || idx >= playlists.length) { - throw new Error(`Playlist #${playlistId} not found. You have ${playlists.length} playlist(s). Use the lastfm playlists command to see them.`); - } - playlistUrl = playlists[idx].url; - } else if (String(playlistId).startsWith("http")) { - playlistUrl = String(playlistId); - } else { - playlistUrl = `https://www.last.fm/user/${user.username}/playlists/${playlistId}`; - } - - const res = await fetch(playlistUrl, { - headers: { "User-Agent": "RemixBot/1.0 (Last.fm Integration)" }, - }); - - if (!res.ok) { - throw new Error(`Failed to fetch playlist page (HTTP ${res.status})`); - } - - const html = await res.text(); - const tracks = []; - - 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(); - const parts = urlPath.split("/"); - let artist = "Unknown"; - if (parts.length >= 1) { - artist = parts[0].replace(/\+/g, " "); - } - - if (name && name !== "Unknown") { - tracks.push({ - artist, - name, - url: `https://www.last.fm/music/${urlPath}`, - image: "", - }); - } - } - - if (!tracks.length) { - const broadRegex = /href="\/music\/([^"]+)"[^>]*>([^<]{2,80})<\/a>/gi; - const seen = new Set(); - let bMatch; - while ((bMatch = broadRegex.exec(html)) !== null && tracks.length < limit) { - const urlPath = decodeURIComponent(bMatch[1]); - const name = bMatch[2].trim(); - const parts = urlPath.split("/"); - if (parts.length < 2) continue; - if (seen.has(urlPath)) continue; - seen.add(urlPath); - - const artist = parts[0].replace(/\+/g, " "); - const trackName = parts.length >= 3 && parts[1] === "_" - ? parts[2].replace(/\+/g, " ") - : parts[1].replace(/\+/g, " "); - - if (trackName && artist) { - tracks.push({ - artist, - name: trackName, - url: `https://www.last.fm/music/${urlPath}`, - image: "", - }); - } - } - } - - return tracks; - } - - /** - * Get a user's top albums from Last.fm. - * @async - * @param {string} userId - The Discord user ID. - * @param {string} [period="overall"] - Time period (7day, 1month, 3month, 6month, 12month, overall). - * @param {number} [limit=20] - Maximum number of results. - * @returns {Promise>} Top albums. - * @throws {Error} If user is not linked. - */ - async getTopAlbums(userId, period = "overall", limit = 20) { - const user = await this.getUser(userId); - if (!user) throw new Error("NOT_LINKED"); - - const data = await apiCall( - { - method: "user.gettopalbums", - api_key: this.apiKey, - user: user.username, - period, - limit, - }, - this.apiSecret - ); - - return (data.topalbums?.album ?? []).map(a => ({ - artist: a.artist?.name ?? "Unknown", - name: a.name, - url: a.url ?? "", - playcount: a.playcount ?? 0, - image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", - })); - } - - /** - * Get a user's top artists from Last.fm. - * @async - * @param {string} userId - The Discord user ID. - * @param {string} [period="overall"] - Time period (7day, 1month, 3month, 6month, 12month, overall). - * @param {number} [limit=15] - Maximum number of results. - * @returns {Promise>} Top artists. - * @throws {Error} If user is not linked. - */ - async getTopArtists(userId, period = "overall", limit = 15) { - const user = await this.getUser(userId); - if (!user) throw new Error("NOT_LINKED"); - - const data = await apiCall( - { - method: "user.gettopartists", - api_key: this.apiKey, - user: user.username, - period, - limit, - }, - this.apiSecret - ); - - return (data.topartists?.artist ?? []).map(a => ({ - name: a.name, - url: a.url ?? "", - playcount: a.playcount ?? 0, - image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", - })); - } - - /** - * Get tracks from a user's Last.fm data for playback based on category. - * @async - * @param {string} userId - The Discord user ID. - * @param {string} category - One of: loved, top, recent, playlist, albums, artists. - * @param {object} [options={}] - Additional options. - * @param {number} [options.limit] - Maximum number of tracks. - * @param {string} [options.period] - Time period for top/albums/artists categories. - * @param {string|number} [options.playlistId] - Playlist ID (required for playlist category). - * @returns {Promise<{username: string, tracks: Array<{query: string, artist: string, name: string, url: string, image?: string}>}>} Tracks ready for playback. - * @throws {Error} If user is not linked or category is unknown. - */ - async getTracksForPlay(userId, category, options = {}) { - const user = await this.getUser(userId); - if (!user) throw new Error("NOT_LINKED"); - - const limit = options.limit ?? 20; - let tracks; - - switch (category) { - case "loved": - tracks = await this.getLovedTracks(userId, limit); - break; - case "top": - tracks = await this.getTopTracks(userId, options.period ?? "overall", limit); - break; - case "recent": - tracks = await this.getRecentTracks(userId, limit); - tracks = tracks.filter(t => !t.now); - break; - case "playlist": - if (!options.playlistId) throw new Error("Playlist ID required. Use the lastfm playlists command to see your playlists, then use the lastfm play playlist command with a number."); - tracks = await this.getPlaylistTracks(userId, options.playlistId, limit); - break; - case "albums": - const albums = await this.getTopAlbums(userId, options.period ?? "overall", limit); - tracks = albums.map(a => ({ - artist: a.artist, - name: a.name, - url: a.url, - query: `${a.artist} ${a.name} album`, - image: a.image ?? "", - })); - return { - username: user.username, - tracks, - }; - case "artists": - const topArtistsList = await this.getTopArtists(userId, options.period ?? "overall", limit); - const artistTrackResults = []; - const artistConcurrency = 3; - for (let ai = 0; ai < topArtistsList.length; ai += artistConcurrency) { - const artistBatch = topArtistsList.slice(ai, ai + artistConcurrency); - const artistResults = await Promise.allSettled( - artistBatch.map(async (ar) => { - try { - const topTracks = await this.getArtistTopTracks(ar.name, 3); - return topTracks.map(t => ({ - artist: t.artist ?? ar.name, - name: t.name, - url: t.url, - query: `${t.name} ${t.artist ?? ar.name}`, - image: t.image ?? ar.image ?? "", - })); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - }) - ); - for (const r of artistResults) { - if (r.status === "fulfilled" && r.value) { - artistTrackResults.push(...r.value); - } - } - } - return { - username: user.username, - tracks: artistTrackResults.slice(0, limit * 3), - }; - default: - throw new Error(`Unknown Last.fm category: ${category}. Use loved, top, recent, playlist, albums, or artists.`); - } - - return { - username: user.username, - tracks: tracks.map(t => ({ - query: this._buildPlayQuery(t.artist, t.name), - artist: t.artist, - name: t.name, - url: t.url ?? "", - })), - }; - } - - /** - * Get total scrobble count across all linked users (cached for 10 minutes). - * @async - * @param {number} [concurrency=3] - Number of concurrent user syncs. - * @returns {Promise} Total scrobble count. - */ - async getTotalScrobbles(concurrency = 3) { - if (!this.enabled) return 0; - - if (this._totalScrobblesCache !== null && Date.now() < this._totalScrobblesCacheExpiry) { - return this._totalScrobblesCache; - } - - if (this._totalScrobblesInflight) return this._totalScrobblesInflight; - - this._totalScrobblesInflight = this._refreshTotalScrobbles(concurrency); - try { - return await this._totalScrobblesInflight; - } finally { - this._totalScrobblesInflight = null; - } - } - - /** @private @async Sync all users' scrobble counts from Last.fm and cache the total. @param {number} concurrency - Concurrent sync batch size. @returns {Promise} Fresh total scrobble count. */ - async _refreshTotalScrobbles(concurrency) { - try { - const pool = await this._getPool(); - - const f = this._botIdFilter(); - const [rows] = await pool.execute( - `SELECT user_id FROM lastfm_users WHERE 1=1${f.where}`, - [...f.params] - ); - - if (!rows.length) { - this._totalScrobblesCache = 0; - this._totalScrobblesCacheExpiry = Date.now() + 10 * 60 * 1000; - return 0; - } - - const userIds = rows.map(r => r.user_id); - - 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))); - } - - const [sumRows] = await pool.execute( - `SELECT COALESCE(SUM(scrobble_count), 0) AS total FROM lastfm_users WHERE 1=1${f.where}`, - [...f.params] - ); - - const total = Number(sumRows[0]?.total ?? 0); - this._totalScrobblesCache = total; - this._totalScrobblesCacheExpiry = Date.now() + 10 * 60 * 1000; - - logger.settings(`[LastFm] Total synced scrobbles across ${userIds.length} users: ${total}`); - return total; - } catch (err) { - logger.warn(`[LastFm] _refreshTotalScrobbles failed: ${err.message}`); - return this._totalScrobblesCache ?? 0; - } - } - - /** - * Get the number of linked Last.fm users from the stats table. - * @async - * @returns {Promise} Linked user count. - */ - async getLinkedUsersCount() { - if (!this.enabled) return 0; - try { - const pool = await this._getPool(); - const f = this._botIdFilter(); - const [rows] = await pool.execute( - `SELECT linked_users FROM lastfm_stats WHERE id = 1${f.where}`, - [...f.params] - ); - return Number(rows[0]?.linked_users ?? 0); - } catch (e) { - logger.warn("[LastFm] Error:", e?.message); - return 0; - } - } - - /** - * Get the scrobble leaderboard with pagination. - * @async - * @param {number} [page=0] - Zero-based page index. - * @param {number} [perPage=10] - Number of entries per page. - * @returns {Promise<{entries: Array<{userId: string, username: string, scrobbleCount: number}>, totalUsers: number, page: number, perPage: number, totalPages: number}>} Leaderboard data. - */ - async getLeaderboard(page = 0, perPage = 10) { - if (!this.enabled) return { entries: [], totalUsers: 0, page: 0, perPage: 10, totalPages: 0 }; - - const pool = await this._getPool(); - const f = this._botIdFilter(); - - const [countRows] = await pool.execute( - `SELECT COUNT(*) AS total FROM lastfm_users WHERE scrobble_count > 0${f.where}`, - [...f.params] - ); - const totalUsers = Number(countRows[0]?.total ?? 0); - const totalPages = Math.max(1, Math.ceil(totalUsers / perPage)); - - page = Math.max(0, Math.min(page, totalPages - 1)); - - const offset = page * perPage; - const [rows] = await pool.execute( - `SELECT user_id, username, scrobble_count FROM lastfm_users WHERE scrobble_count > 0${f.where} ORDER BY scrobble_count DESC LIMIT ? OFFSET ?`, - [...f.params, String(perPage), String(offset)] - ); - - const entries = rows.map(r => ({ - userId: r.user_id, - username: r.username || r.user_id, - scrobbleCount: Number(r.scrobble_count), - })); - - return { entries, totalUsers, page, perPage, totalPages }; - } - - /** - * Sync a user's scrobble count from Last.fm to the local database. - * @async - * @param {string} userId - The Discord user ID. - * @returns {Promise} The synced scrobble count. - */ - async syncUserScrobbleCount(userId) { - if (!this.enabled) return 0; - try { - const info = await this.getUserInfo(userId); - const playcount = Number(info.playcount ?? 0); - const pool = await this._getPool(); - const f = this._botIdFilter(); - await pool.execute( - `UPDATE lastfm_users SET scrobble_count = ? WHERE user_id = ?${f.where}`, - [String(playcount), String(userId), ...f.params] - ); - return playcount; - } catch (e) { - logger.warn("[LastFm] Error:", e?.message); - return 0; - } - } - - /** - * Get a user's Last.fm friends list. - * @async - * @param {string} userId - The Discord user ID. - * @param {number} [limit=20] - Maximum number of results. - * @returns {Promise>} Friends list. - */ - async getUserFriends(userId, limit = 20) { - if (!this.enabled) return []; - const user = await this.getUser(userId); - if (!user) return []; - try { - const data = await apiCall({ - method: "user.getfriends", - api_key: this.apiKey, - user: user.username, - limit, - }, this.apiSecret); - return (data.friends?.user ?? []).map(f => ({ - name: f.name ?? "", - url: f.url ?? "", - image: f.image?.[2]?.["#text"] ?? f.image?.[1]?.["#text"] ?? "", - realname: f.realname ?? "", - country: f.country ?? "", - })); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** - * Get a user's weekly artist chart for a specific time range. - * @async - * @param {string} userId - The Discord user ID. - * @param {number|null} [from] - Start Unix timestamp. - * @param {number|null} [to] - End Unix timestamp. - * @returns {Promise>} Weekly artist chart. - */ - async getUserWeeklyArtistChart(userId, from = null, to = null) { - if (!this.enabled) return []; - const user = await this.getUser(userId); - if (!user) return []; - try { - const params = { - method: "user.getweeklyartistchart", - api_key: this.apiKey, - user: user.username, - }; - if (from) params.from = from; - if (to) params.to = to; - const data = await apiCall(params, this.apiSecret); - return (data.weeklyartistchart?.artist ?? []).map(a => ({ - name: a.name ?? "", - url: a.url ?? "", - playcount: Number(a.playcount ?? 0), - image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", - })); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** - * Get a user's weekly track chart for a specific time range. - * @async - * @param {string} userId - The Discord user ID. - * @param {number|null} [from] - Start Unix timestamp. - * @param {number|null} [to] - End Unix timestamp. - * @returns {Promise>} Weekly track chart. - */ - async getUserWeeklyTrackChart(userId, from = null, to = null) { - if (!this.enabled) return []; - const user = await this.getUser(userId); - if (!user) return []; - try { - const params = { - method: "user.getweeklytrackchart", - api_key: this.apiKey, - user: user.username, - }; - if (from) params.from = from; - if (to) params.to = to; - const data = await apiCall(params, this.apiSecret); - return (data.weeklytrackchart?.track ?? []).map(t => ({ - name: t.name ?? "", - artist: t.artist?.["#text"] ?? t.artist ?? "", - url: t.url ?? "", - playcount: Number(t.playcount ?? 0), - image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "", - })); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** - * Get a user's weekly album chart for a specific time range. - * @async - * @param {string} userId - The Discord user ID. - * @param {number|null} [from] - Start Unix timestamp. - * @param {number|null} [to] - End Unix timestamp. - * @returns {Promise>} Weekly album chart. - */ - async getUserWeeklyAlbumChart(userId, from = null, to = null) { - if (!this.enabled) return []; - const user = await this.getUser(userId); - if (!user) return []; - try { - const params = { - method: "user.getweeklyalbumchart", - api_key: this.apiKey, - user: user.username, - }; - if (from) params.from = from; - if (to) params.to = to; - const data = await apiCall(params, this.apiSecret); - return (data.weeklyalbumchart?.album ?? []).map(a => ({ - name: a.name ?? "", - artist: a.artist?.["#text"] ?? a.artist ?? "", - url: a.url ?? "", - playcount: Number(a.playcount ?? 0), - image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", - })); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** - * Get top tags for an artist from Last.fm. - * @async - * @param {string} artist - The artist name. - * @param {number} [limit=10] - Maximum number of results. - * @returns {Promise>} Artist's top tags. - */ - async getArtistTopTags(artist, limit = 10) { - if (!this.enabled) return []; - try { - const data = await apiCall({ - method: "artist.gettoptags", - api_key: this.apiKey, - artist, - limit, - }, this.apiSecret); - return (data.toptags?.tag ?? []).map(t => ({ - name: t.name ?? "", - url: t.url ?? "", - count: Number(t.count ?? 0), - })); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** - * Get top tags for an album from Last.fm. - * @async - * @param {string} artist - The artist name. - * @param {string} album - The album name. - * @param {number} [limit=10] - Maximum number of results. - * @returns {Promise>} Album's top tags. - */ - async getAlbumTopTags(artist, album, limit = 10) { - if (!this.enabled) return []; - try { - const data = await apiCall({ - method: "album.gettoptags", - api_key: this.apiKey, - artist, - album, - limit, - }, this.apiSecret); - return (data.toptags?.tag ?? []).map(t => ({ - name: t.name ?? "", - url: t.url ?? "", - count: Number(t.count ?? 0), - })); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** - * Get top tags for a track from Last.fm. - * @async - * @param {string} artist - The artist name. - * @param {string} track - The track name. - * @param {number} [limit=10] - Maximum number of results. - * @returns {Promise>} Track's top tags. - */ - async getTrackTopTags(artist, track, limit = 10) { - if (!this.enabled) return []; - try { - const data = await apiCall({ - method: "track.gettoptags", - api_key: this.apiKey, - artist, - track, - limit, - }, this.apiSecret); - return (data.toptags?.tag ?? []).map(t => ({ - name: t.name ?? "", - url: t.url ?? "", - count: Number(t.count ?? 0), - })); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** - * Get top albums for a tag from Last.fm. - * @async - * @param {string} tag - The tag name. - * @param {number} [limit=10] - Maximum number of results. - * @returns {Promise>} Tag's top albums. - */ - async getTagTopAlbums(tag, limit = 10) { - if (!this.enabled) return []; - try { - const data = await apiCall({ - method: "tag.gettopalbums", - api_key: this.apiKey, - tag, - limit, - }, this.apiSecret); - return (data.albums?.album ?? []).map(a => ({ - name: a.name ?? "", - artist: a.artist?.name ?? "Unknown", - url: a.url ?? "", - playcount: Number(a.playcount ?? 0), - image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", - })); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** - * Get top artists for a country from Last.fm. - * @async - * @param {string} country - The country name. - * @param {number} [limit=10] - Maximum number of results. - * @returns {Promise>} Country's top artists. - */ - async getGeoTopArtists(country, limit = 10) { - if (!this.enabled) return []; - try { - const data = await apiCall({ - method: "geo.gettopartists", - api_key: this.apiKey, - country, - limit, - }, this.apiSecret); - return (data.topartists?.artist ?? []).map(a => ({ - name: a.name ?? "", - url: a.url ?? "", - listeners: Number(a.listeners ?? 0), - image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", - })); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** - * Get top tracks for a country from Last.fm. - * @async - * @param {string} country - The country name. - * @param {number} [limit=10] - Maximum number of results. - * @returns {Promise>} Country's top tracks. - */ - async getGeoTopTracks(country, limit = 10) { - if (!this.enabled) return []; - try { - const data = await apiCall({ - method: "geo.gettoptracks", - api_key: this.apiKey, - country, - limit, - }, this.apiSecret); - return (data.tracks?.track ?? []).map(t => ({ - name: t.name ?? "", - artist: t.artist?.name ?? "Unknown", - url: t.url ?? "", - listeners: Number(t.listeners ?? 0), - image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "", - })); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** - * Get the global top tracks chart from Last.fm. - * @async - * @param {number} [limit=10] - Maximum number of results. - * @returns {Promise>} Global top tracks. - */ - async getChartTopTracks(limit = 10) { - if (!this.enabled) return []; - try { - const data = await apiCall({ - method: "chart.gettoptracks", - api_key: this.apiKey, - limit, - }, this.apiSecret); - return (data.tracks?.track ?? []).map(t => ({ - name: t.name ?? "", - artist: t.artist?.name ?? "Unknown", - url: t.url ?? "", - listeners: Number(t.listeners ?? 0), - playcount: Number(t.playcount ?? 0), - image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "", - })); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** - * Get the global top artists chart from Last.fm. - * @async - * @param {number} [limit=10] - Maximum number of results. - * @returns {Promise>} Global top artists. - */ - async getChartTopArtists(limit = 10) { - if (!this.enabled) return []; - try { - const data = await apiCall({ - method: "chart.gettopartists", - api_key: this.apiKey, - limit, - }, this.apiSecret); - return (data.artists?.artist ?? []).map(a => ({ - name: a.name ?? "", - url: a.url ?? "", - listeners: Number(a.listeners ?? 0), - playcount: Number(a.playcount ?? 0), - image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", - })); - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** - * Get who knows a specific track among a list of users, ranked by playcount. - * @async - * @param {string} artist - The artist name. - * @param {string} track - The track name. - * @param {Array} userIds - Array of Discord user IDs. - * @returns {Promise>} Users who know the track, sorted by playcount descending. - */ - async getWhoKnowsTrack(artist, track, userIds) { - if (!this.enabled) return []; - if (!Array.isArray(userIds) || !userIds.length) return []; - - const concurrency = 5; - const results = []; - - for (let i = 0; i < userIds.length; i += concurrency) { - const batch = userIds.slice(i, i + concurrency); - - const batchResults = await Promise.allSettled( - batch.map(async (uid) => { - const user = await this.getUser(uid); - if (!user) return null; - - try { - const info = await this.getTrackInfo(artist, track, uid); - const playcount = Number(info?.userplaycount ?? 0); - return { - userId: uid, - username: user.username, - playcount, - }; - } catch (e) { - logger.warn("[LastFm] Error:", e?.message); - return { - userId: uid, - username: user.username, - playcount: 0, - }; - } - }) - ); - - for (const r of batchResults) { - if (r.status === "fulfilled" && r.value && r.value.playcount > 0) { - results.push(r.value); - } - } - } - - results.sort((a, b) => b.playcount - a.playcount); - return results; - } - - /** - * Get who knows a specific album among a list of users, ranked by playcount. - * @async - * @param {string} artist - The artist name. - * @param {string} album - The album name. - * @param {Array} userIds - Array of Discord user IDs. - * @returns {Promise>} Users who know the album, sorted by playcount descending. - */ - async getWhoKnowsAlbum(artist, album, userIds) { - if (!this.enabled) return []; - if (!Array.isArray(userIds) || !userIds.length) return []; - - const concurrency = 5; - const results = []; - - for (let i = 0; i < userIds.length; i += concurrency) { - const batch = userIds.slice(i, i + concurrency); - - const batchResults = await Promise.allSettled( - batch.map(async (uid) => { - const user = await this.getUser(uid); - if (!user) return null; - - try { - const info = await this.getAlbumInfo(artist, album, uid); - const playcount = Number(info?.userplaycount ?? 0); - return { - userId: uid, - username: user.username, - playcount, - }; - } catch (e) { - logger.warn("[LastFm] Error:", e?.message); - return { - userId: uid, - username: user.username, - playcount: 0, - }; - } - }) - ); - - for (const r of batchResults) { - if (r.status === "fulfilled" && r.value && r.value.playcount > 0) { - results.push(r.value); - } - } - } - - results.sort((a, b) => b.playcount - a.playcount); - return results; - } - - /** - * Compute affinity (common artists) between multiple users. - * @async - * @param {Array} userIds - Array of Discord user IDs (minimum 2). - * @param {number} [limit=10] - Maximum number of affinity pairs to return. - * @returns {Promise}>>} Affinity pairs sorted by match count descending. - */ - async getAffinity(userIds, limit = 10) { - if (!this.enabled) return []; - if (!Array.isArray(userIds) || userIds.length < 2) return []; - - const userArtistsMap = new Map(); - const concurrency = 5; - - for (let i = 0; i < userIds.length; i += concurrency) { - const batch = userIds.slice(i, i + concurrency); - const results = await Promise.allSettled( - batch.map(async (uid) => { - const user = await this.getUser(uid); - if (!user) return null; - try { - const artists = await this.getTopArtists(uid, "overall", 50); - return { uid, username: user.username, artists }; - } catch (e) { - logger.warn("[LastFm] Error:", e?.message); - return null; - } - }) - ); - for (const r of results) { - if (r.status === "fulfilled" && r.value) { - userArtistsMap.set(r.value.uid, r.value); - } - } - } - - const entries = [...userArtistsMap.values()]; - const affinityResults = []; - - for (let i = 0; i < entries.length; i++) { - for (let j = i + 1; j < entries.length; j++) { - const a = entries[i]; - const b = entries[j]; - const namesA = new Set(a.artists.map(ar => ar.name.toLowerCase())); - const namesB = new Set(b.artists.map(ar => ar.name.toLowerCase())); - const common = [...namesA].filter(n => namesB.has(n)); - if (common.length > 0) { - const commonArtists = a.artists - .filter(ar => namesB.has(ar.name.toLowerCase())) - .map(ar => ({ name: ar.name, url: ar.url, playcount: ar.playcount })); - affinityResults.push({ - users: [a.username, b.username], - userIds: [a.uid, b.uid], - matchCount: common.length, - commonArtists, - }); - } - } - } - - affinityResults.sort((a, b) => b.matchCount - a.matchCount); - return affinityResults.slice(0, limit); - } - - /** - * Get a user's "crowns" — artists where they have the highest playcount among the given users. - * @async - * @param {string} userId - The Discord user ID to check crowns for. - * @param {Array} userIds - Array of all Discord user IDs to compare against. - * @returns {Promise>} Crown entries sorted by user playcount descending. - */ - async getCrowns(userId, userIds) { - if (!this.enabled) return []; - const user = await this.getUser(userId); - if (!user) return []; - try { - const topArtists = await this.getTopArtists(userId, "overall", 50); - const crowns = []; - const concurrency = 3; - - for (let i = 0; i < topArtists.length; i += concurrency) { - const batch = topArtists.slice(i, i + concurrency); - const results = await Promise.allSettled( - batch.map(async (artist) => { - const listeners = await this.getWhoKnows(artist.name, userIds); - if (listeners.length > 0 && listeners[0].userId === String(userId)) { - return { - artist: artist.name, - artistUrl: artist.url, - userPlaycount: artist.playcount, - nextBest: listeners.length > 1 ? listeners[1] : null, - image: artist.image ?? "", - }; - } - return null; - }) - ); - for (const r of results) { - if (r.status === "fulfilled" && r.value) crowns.push(r.value); - } - } - - crowns.sort((a, b) => b.userPlaycount - a.userPlaycount); - return crowns; - } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } - } - - /** @private Throw if Last.fm integration is not enabled/configured. @throws {Error} If apiKey or apiSecret is missing. */ - _assertEnabled() { - if (!this.enabled) throw new Error("Last.fm integration is not configured (missing apiKey/apiSecret)."); - } - - /** @private Increment a user's scrobble_count in the database by 1 (fire-and-forget). @param {string} userId - The Discord user ID. */ - _incrementScrobbleCount(userId) { - if (!userId) return; - const f = this._botIdFilter(); - this._getPool().then(pool => { - pool.execute( - `UPDATE lastfm_users SET scrobble_count = scrobble_count + 1 WHERE user_id = ?${f.where}`, - [String(userId), ...f.params] - ).catch(e => { logger.warn("[LastFm] scrobble_count increment failed:", e?.message); }); - }).catch(e => { logger.warn("[LastFm] scrobble_count pool acquire failed:", e?.message); }); - } - - /** @private Build a search query string from artist and title for playback. @param {string} artist - The artist name. @param {string} title - The track title. @returns {string} Combined search query. */ - _buildPlayQuery(artist, title) { - const cleanArtist = String(artist ?? "").trim(); - const cleanTitle = String(title ?? "").trim(); - return [cleanTitle, cleanArtist].filter(Boolean).join(" "); - } - - /** @private Extract the best artist name from a track object, checking multiple possible fields. @param {object} track - Track object. @returns {string} The artist name. */ - _extractArtist(track) { - const preservedArtist = track?.lastfm?.artist - ?? track?.requestedArtist - ?? track?.artist; - if (preservedArtist) return preservedArtist; - - return track.artists?.[0]?.name - ?? track.author?.name - ?? "Unknown Artist"; - } - - /** @private Extract the best track title from a track object, checking multiple possible fields. @param {object} track - Track object. @returns {string} The track title. */ - _extractTitle(track) { - return track?.lastfm?.name - ?? track?.requestedTitle - ?? track.title - ?? track.name - ?? "Unknown Track"; - } - - /** @private Extract the duration in seconds from a track object, supporting number (ms), object with .seconds, ISO 8601, or plain seconds. @param {object} track - Track object. @returns {string|number} Duration in seconds, or empty string if unavailable. */ - _extractDurationSec(track) { - if (!track.duration) return ""; - 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") { - const m = track.duration.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/); - if (m) return ((+m[1] || 0) * 3600) + ((+m[2] || 0) * 60) + (+m[3] || 0); - } - return ""; - } - - /** - * Determine whether a track should be scrobbled based on playback time and duration. - * @param {object} track - Track object with duration and title/artist info. - * @param {number} playedMs - How many milliseconds the track has been playing. - * @returns {boolean} True if the track meets the scrobble threshold. - */ - shouldScrobble(track, playedMs) { - const durationMs = typeof track.duration === "object" && track.duration.seconds - ? track.duration.seconds * 1000 - : typeof track.duration === "number" - ? track.duration - : null; - - if (!durationMs || durationMs < 30_000) return false; - - const normalizedTitle = normalizeTrackText(this._extractTitle(track)); - const normalizedArtist = normalizeTrackText(this._extractArtist(track)); - if (!normalizedTitle || !normalizedArtist) return false; - - const thresholdMs = Math.min(durationMs * this.scrobbleThreshold, this.scrobbleMinMs); - return playedMs >= thresholdMs; - } -} - -/** - * Parse a Last.fm music URL into its components. - * @param {string} url - The Last.fm URL to parse. - * @returns {{artist: string, track: string|null, album: string|null, url: string}|null} Parsed components, or null if not a valid Last.fm music URL. - */ -export function parseLastFmUrl(url) { - try { - const u = new URL(url); - if (!/^(?:www\.)?last\.fm$/i.test(u.hostname)) return null; - - const match = u.pathname.match(/^\/music\/([^/]+)(?:\/([^/]+))?(?:\/([^/]+))?/); - if (!match) return null; - - const artist = decodeURIComponent(match[1].replace(/\+/g, " ")); - const segment2 = match[2] ? decodeURIComponent(match[2].replace(/\+/g, " ")) : null; - const segment3 = match[3] ? decodeURIComponent(match[3].replace(/\+/g, " ")) : null; - - let track = null; - let album = null; - - if (segment3) { - album = segment2 === "_" ? null : segment2; - track = segment3; - } else if (segment2 && segment2 !== "_") { - track = segment2; - } - - return { artist, track, album, url }; - } catch (e) { - logger.warn("[LastFm] parseLastFmUrl error:", e?.message); - return null; - } -} - -/** - * Check whether a string is a valid Last.fm music URL. - * @param {string} str - String to check. - * @returns {boolean} True if the string is a Last.fm URL with a /music/ path. - */ -export function isLastFmUrl(str) { - if (!str || typeof str !== "string") return false; - try { - const u = new URL(str); - return /^(?:www\.)?last\.fm$/i.test(u.hostname) && /^\/music\//i.test(u.pathname); - } catch (e) { - return false; - } -} diff --git a/src/MessageHandler.mjs b/src/MessageHandler.mjs deleted file mode 100644 index a808702..0000000 --- a/src/MessageHandler.mjs +++ /dev/null @@ -1,1164 +0,0 @@ -/** @module src/MessageHandler @description Message creation, reaction observation, permission checking, pagination, and command help display. */ - -import { Client, Events, EmbedBuilder, PermissionFlags } from "@fluxerjs/core"; -import { logger } from "./constants/Logger.mjs"; -import { Utils } from "./Utils.mjs"; - -/** @type {Map} @description Required bot permissions with human-readable names and descriptions. */ -export const REQUIRED_BOT_PERMISSIONS = Object.freeze(new Map([ - ["ViewChannel", { name: "View Channels", desc: "See channels and read their content" }], - ["SendMessages", { name: "Send Messages", desc: "Respond to commands and send messages" }], - ["EmbedLinks", { name: "Embed Links", desc: "Send rich embed messages (bot responses, now playing, etc.)" }], - ["AddReactions", { name: "Add Reactions", desc: "Add pagination reactions (help pages, queue, etc.)" }], - ["ReadMessageHistory", { name: "Read Message History", desc: "Read previous messages for context" }], - ["ManageMessages", { name: "Manage Messages", desc: "Pin messages, clean up bot responses" }], - ["AttachFiles", { name: "Attach Files", desc: "Send files and thumbnails" }], - ["Connect", { name: "Connect (Join Voice)", desc: "Join voice channels to play music" }], - ["Speak", { name: "Speak", desc: "Stream audio in voice channels" }], -])); - -/** @type {string[]} @description Permission keys that are strictly required for the bot to function. */ -export const CRITICAL_PERMISSIONS = ["ViewChannel", "SendMessages", "EmbedLinks", "Connect", "Speak"]; - -/** @type {string[]} @description Permission keys that are optional but improve the user experience. */ -export const OPTIONAL_PERMISSIONS = ["AddReactions", "ReadMessageHistory", "ManageMessages", "AttachFiles"]; - -/** Parse a color value (hex string, number) into an integer. @param {string|number} value @param {number} [fallback=0xe9196c] @returns {number} */ -export function parseColor(value, fallback = 0xe9196c) { - if (!value) return fallback; - if (typeof value === "number") return value; - const cleaned = String(value).replace(/^#/, "").replace(/^0x/i, ""); - const n = parseInt(cleaned, 16); - return isNaN(n) ? fallback : n; -} - -/** @private */ -let _globalColor = 0xe9196c; -/** Set the global embed color. @param {string|number} value */ -export function setGlobalColor(value) { _globalColor = parseColor(value); } -/** @returns {number} The current global embed color. */ -export function getGlobalColor() { return _globalColor; } - -/** Re-export of {@link cleanId} from Utils for convenience. @type {function} */ -export { cleanId } from "./Utils.mjs"; - -/** Extract the guild ID from various message wrapper shapes. @param {object} message @returns {string|null} */ -export function getMessageGuildId(message) { - return message?.channel?.guildId ?? - message?.channel?.guild?.id ?? - message?.message?.guildId ?? - message?.message?.guild?.id ?? - message?.channel?.server_id ?? - message?.channel?.serverId ?? - message?.message?.server_id ?? - message?.message?.serverId ?? - null; -} - -/** @class MessageHandler @description Handles message creation, reaction observation, permission checking, and pagination. */ -export class MessageHandler { - /** @type {Client} */ - client; - /** @type {Map} Message ID → reaction observer data. */ - observedReactions; - /** @type {Map} Channel ID → user message observer callbacks. */ - observedChannels; - /** @type {object|null} Locale manager instance. */ - locale; - - /** @param {Client} client - The Discord client. */ - constructor(client) { - this.client = client; - - this.observedReactions = new Map(); - this.observedChannels = new Map(); - - this.setupEvents(); - - this.client.on(Events.MessageCreate, (m) => { - if (!this.observedChannels.has(m.channelId)) return; - const data = this.observedChannels.get(m.channelId); - const d = data.filter(e => e.id === m.author.id); - if (d.length === 0) return; - d.forEach(e => e.cb(new Message(m, this))); - }); - } - - /** Set the locale manager. @param {object} locale */ - setLocale(locale) { this.locale = locale; } - - /** Translate a locale key. @param {string} guildId @param {string} key @param {object} [replacements={}] @returns {string} */ - t(guildId, key, replacements = {}) { - if (!this.locale) return key; - return this.locale.translate(guildId, key, replacements); - } - - /** @private Register reaction add/remove event listeners. */ - setupEvents() { - const reactionUpdate = (payload) => { - const { userId, messageId, emoji } = payload; - const emojiId = emoji?.name ?? emoji?.id ?? emoji; - const event = { user_id: userId, emoji_id: emojiId }; - - if (!this.observedReactions.has(messageId)) return; - if (event.user_id === this.client.user?.id) return; - const observer = this.observedReactions.get(messageId); - if (!observer.reactions.includes(event.emoji_id)) return; - if (observer.user && observer.user !== event.user_id) return; - - const wrappedMsg = observer.msg ? new Message(observer.msg, this) : null; - observer.cb(event, wrappedMsg); - }; - this.client.on(Events.MessageReactionAdd, (payload) => reactionUpdate(payload)); - this.client.on(Events.MessageReactionRemove, (payload) => reactionUpdate(payload)); - } - - /** Return the permission keys the bot is missing in a channel. @param {string[]} permissions @param {object} channel @returns {string[]} Missing permission keys. */ - checkPermissions(permissions, channel) { - 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 []; - } - const perms = channel.permissionsFor?.(me) ?? null; - if (!perms) { - logger.warn("[MessageHandler] Cannot check permissions — channel.permissionsFor() unavailable"); - return []; - } - return permissions.filter(p => !perms.has(PermissionFlags[p] ?? p)); - } - - /** Check all REQUIRED_BOT_PERMISSIONS and split into critical vs optional. @param {object} channel @returns {{missing: string[], criticalMissing: string[], optionalMissing: string[]}} */ - checkAllBotPermissions(channel) { - const allKeys = [...REQUIRED_BOT_PERMISSIONS.keys()]; - const missing = this.checkPermissions(allKeys, channel); - return { - missing, - criticalMissing: missing.filter(p => CRITICAL_PERMISSIONS.includes(p)), - optionalMissing: missing.filter(p => OPTIONAL_PERMISSIONS.includes(p)), - }; - } - - /** Build an EmbedBuilder showing missing permissions. @param {string[]} missingKeys @param {string} guildId @returns {EmbedBuilder} */ - buildPermissionEmbed(missingKeys, guildId) { - const criticalItems = []; - const optionalItems = []; - - for (const key of missingKeys) { - const info = REQUIRED_BOT_PERMISSIONS.get(key); - const isCritical = CRITICAL_PERMISSIONS.includes(key); - const line = info - ? `**${info.name}** — ${info.desc}` - : `**${key}**`; - if (isCritical) { - criticalItems.push("❌ " + line); - } else { - optionalItems.push("⚠️ " + line); - } - } - - const embed = new EmbedBuilder().setColor(0xFF4444); - - if (criticalItems.length > 0) { - embed.setTitle(this.t(guildId, "responses.messages.missingCriticalPermsTitle")); - embed.setDescription( - this.t(guildId, "responses.messages.missingCriticalPermsDesc") + "\n\n" + - criticalItems.join("\n") - ); - } else if (optionalItems.length > 0) { - embed.setTitle(this.t(guildId, "responses.messages.missingOptionalPermsTitle")); - embed.setDescription( - this.t(guildId, "responses.messages.missingOptionalPermsDesc") + "\n\n" + - optionalItems.join("\n") - ); - embed.setColor(0xFFA500); - } - - embed.setFooter({ - text: this.t(guildId, "responses.messages.permFooter") - }); - - return embed; - } - - /** Check permissions; send a DM or embed if missing. @async @param {string[]} permissions @param {object} message @returns {Promise} */ - async assertPermissions(permissions, message) { - const guild = message.guild ?? await message.client?.guilds?.resolve?.(message.guildId); - if (guild && !guild.members?.me) { - try { await guild.members.fetchMe(); } catch (e) { logger.warn("[MessageHandler] fetchMe failed:", e?.message); } - } - const missing = this.checkPermissions(permissions, message.channel ?? message.channel?.channel); - if (missing.length === 0) return true; - - if (missing.includes("SendMessages")) { - try { - const dm = await message.author.createDM(); - dm.send({ - embeds: [this.#embedify(this.t(message.guildId, "pagination.error.perms.messages", { channel: "<#" + message.channelId + ">" }))] - }); - } catch (e) { - logger.warn("[MessageHandler] Error sending message in DMs (" + message.author.id + "):", e.message); - } - return false; - } - - const permEmbed = this.buildPermissionEmbed(missing, message.guildId); - try { - await message.reply({ embeds: [permEmbed] }, { ping: false }); - } catch (e) { - logger.warn("[MessageHandler] Failed to send permission embed:", e.message); - try { - const names = missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k); - await message.reply(this.t(message.guildId, "responses.messages.needPermsFallback", { perms: names.join("** **") }), { ping: false }); - } catch (e) { logger.warn("[MessageHandler] Fallback permission reply failed:", e?.message); } - } - return false; - } - - /** Register a listener for all incoming messages. @param {Function} listener */ - onMessage(listener) { - this.client.on(Events.MessageCreate, (msg) => { - listener(new Message(msg, this)); - }); - } - - /** Get a wrapped Message from cache by ID. @param {string} id @returns {Message|null} */ - get(id) { - for (const channel of this.client.channels.values()) { - const msg = channel.messages?.get?.(id) ?? null; - if (msg) return new Message(msg, this); - } - return null; - } - - /** @async Get a message from cache or fetch it from the API. @param {string} id @param {string} channelId @returns {Promise} */ - async getOrFetch(id, channelId) { - const cached = this.get(id); - if (cached) return cached; - const channel = await this.client.channels.fetch(channelId).catch(() => null); - if (!channel) return null; - const raw = await channel.messages?.fetch?.(id); - return raw ? new Message(raw, this) : null; - } - - /** Get a wrapped Channel by ID. @param {string} id @returns {Channel} */ - getChannel(id) { - const c = this.client.channels.get(id); - return new Channel(c, this); - } - - /** @async Get a channel from cache or fetch from the API. @param {string} id @returns {Promise} */ - async getOrFetchChannel(id) { - const c = this.getChannel(id); - if (c?.channel) return c; - const raw = await this.client.channels.fetch(id).catch(() => undefined); - return new Channel(raw, this); - } - - /** Start observing reactions on a message. @param {object} msg @param {string[]} reactions @param {Function} cb @param {object} [user] @returns {string} Observation ID. */ - observeReactions(msg, reactions, cb, user) { - this.observedReactions.set(msg.id, { - reactions: reactions, - user: (user) ? user.id : null, - cb, - msg, - }); - return msg.id; - } - /** Stop observing reactions. @param {string} i - Observation ID. @returns {boolean} */ - unobserveReactions(i) { - return this.observedReactions.delete(i); - } - - /** Observe messages from a specific user in a channel. @param {string} userId @param {object} channel @param {Function} callback @returns {string} Observation ID. */ - observeUserMessagesChannel(userId, channel, callback) { - const current = (this.observedChannels.get(channel.id) || []); - const nonce = Utils.uid(); - current.push({ - id: userId, - nonce: nonce, - cb: callback - }); - this.observedChannels.set(channel.id, current); - return userId + ";" + channel.id + ";" + nonce; - } - /** @private Stop observing a user's messages in a channel. @param {string} oid */ - unobserveUserMessagesChannel(oid) { - const [userId, channelId, nonce] = oid.split(";"); - const current = (this.observedChannels.get(channelId) || []); - const idx = current.findIndex(e => e.id === userId && e.nonce === nonce); - if (idx === -1) return; - current.splice(idx, 1); - if (current.length === 0) return this.observedChannels.delete(channelId); - this.observedChannels.set(channelId, current); - } - - /** @private Build an EmbedBuilder from text with optional title, thumbnail, and icon. @param {string} [text=""] @param {object} [options={}] @param {string} [options.color] @param {string} [options.title] @param {string} [options.thumbnail] @param {string} [options.icon_url] @returns {EmbedBuilder} */ - #embedify(text = "", options = {}) { - const color = options.color ?? getGlobalColor(); - const builder = new EmbedBuilder() - .setDescription("" + text) - .setColor(color); - - if (options.title) builder.setTitle(options.title); - - if (options.thumbnail && Utils.isValidUrl(options.thumbnail)) { - builder.setThumbnail(options.thumbnail); - } - - if (options.icon_url) { - if (Utils.isValidUrl(options.icon_url)) { - builder.setAuthor({ name: options.title || "\u200b", iconURL: options.icon_url }); - } else { - builder.setAuthor({ name: options.title || "\u200b" }); - } - } - - return builder; - } - - /** @private Create a message payload object with an embed. @param {string} text @param {object} [options={}] @returns {{content: *, embeds: EmbedBuilder[]}} */ - #createEmbed(text, options = {}) { - return { - content: options.content ?? undefined, - embeds: [this.#embedify(text, options)], - }; - } - - /** @async Reply to a message with permission checks. @param {object} replyingTo @param {string|object} message @param {boolean} [mention=false] @returns {Promise} */ - async reply(replyingTo, message, mention = false) { - if (!(await this.assertPermissions(["SendMessages", "EmbedLinks"], replyingTo))) return null; - let opts; - if (typeof message === "string") { - opts = this.#createEmbed(message); - } else { - opts = { ...message }; - } - return new Message(await replyingTo.reply(opts, { ping: false }), this); - } - - /** @async Reply with an embed. @param {object} replyingTo @param {string|object} message @param {object} [options={}] @returns {Promise} */ - async replyEmbed(replyingTo, message, options = {}) { - if (!(await this.assertPermissions(["SendMessages", "EmbedLinks"], replyingTo))) return null; - - if (typeof message === "object" && Array.isArray(message.embeds)) { - return new Message(await replyingTo.reply(message, { ping: false }), this); - } - - options = { - mention: false, - embed: {}, - ...options - }; - const content = (typeof message === "object") ? message.embedText : message; - let payload = this.#createEmbed(content, options.embed); - if (typeof message === "object") { - const { embedText, ...rest } = message; - payload = { ...payload, ...rest }; - } - return new Message(await replyingTo.reply(payload, { ping: false }), this); - } - - /** @async Send a message to a channel. @param {object} channel @param {string|object} message @returns {Promise} */ - async sendMessage(channel, message) { - if (this.checkPermissions(["SendMessages", "EmbedLinks"], channel).length !== 0) { - logger.warn("[MessageHandler] Missing SendMessages/EmbedLinks permission in channel", channel.id); - return null; - } - let opts; - if (typeof message === "string") { - opts = this.#createEmbed(message); - } else { - opts = message; - } - return new Message(await channel.send(opts), this); - } - - /** @async Send an embed to a channel. @param {object} channel @param {string|object} content @param {object} [embedOptions={}] @returns {Promise} */ - async sendEmbed(channel, content, embedOptions = {}) { - if (this.checkPermissions(["SendMessages", "EmbedLinks"], channel).length !== 0) { - return this.sendMessage(channel, typeof content === "string" ? content : content?.embedText ?? ""); - } - if (typeof content === "object" && Array.isArray(content.embeds)) { - return new Message(await channel.send(content), this); - } - const text = (typeof content === "object") ? content.embedText : content; - const payload = this.#createEmbed(text, embedOptions); - if (typeof content === "object") { - const { embedText, ...rest } = content; - Object.assign(payload, rest); - } - return new Message(await channel.send(payload), this); - } - - /** @async Edit an existing message embed with retry on 502/503/504. @param {object} message @param {string|object} content @param {object} [embedOptions={}] @returns {Promise} */ - async editEmbed(message, content, embedOptions = {}) { - const RETRYABLE = new Set([502, 503, 504]); - const MAX_ATTEMPTS = 3; - const RETRY_DELAY_MS = 1500; - - let payload; - if (typeof content === "object" && Array.isArray(content.embeds)) { - payload = content; - } else { - const text = (typeof content === "object") ? content.embedText : content; - const embed = this.#embedify(text, embedOptions); - payload = { embeds: [embed] }; - if (typeof content === "object") { - const { embedText, ...rest } = content; - payload = { ...payload, ...rest }; - } - } - - for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) { - try { - return new Message(await message.edit(payload), this); - } catch (err) { - if (err.code === "UNKNOWN_MESSAGE" || err.code === 10008) { - logger.warn("[MessageHandler] editEmbed: Message no longer exists, skipping edit."); - return null; - } - - 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)); - continue; - } - - throw err; - } - } - } - - /** @async Create a paginated message with arrow reactions. @param {PageBuilder} builder @param {Message} msg @returns {Promise} */ - async initPagination(builder, msg) { - const pages = builder.createPages(); - if (pages.length === 0) return; - - const arrows = ["⬅️", "➡️"]; - const currPage = { n: 0 }; - const send = () => builder.getPage(currPage.n); - - const m = await msg.reply(send()); - if (!m) return; - - m.message.react(arrows[0]).catch(() => {}); - m.message.react(arrows[1]).catch(() => {}); - - const unobserve = m.onReaction(arrows, (e) => { - if (e.emoji_id === arrows[0]) { - currPage.n = Math.max(0, currPage.n - 1); - } else { - currPage.n = Math.min(pages.length - 1, currPage.n + 1); - } - m.edit(send()).catch(() => {}); - }); - - const guildId = msg.message?.guildId ?? null; - setTimeout(() => { - unobserve(); - m.edit(this.t(guildId, "pagination.embed.sclosedContent", { content: send() })).catch(() => {}); - }, 5 * 60 * 1000); - } - - /** @async Join a voice channel using VoiceManager. @param {string} channelId @returns {Promise} @throws {Error} If channel not found or not a guild channel. */ - async joinChannel(channelId) { - const { getVoiceManager } = await import("@fluxerjs/voice"); - const channel = await this.client.channels.fetch(channelId).catch(() => null); - if (!channel) throw new Error("Voice channel not found."); - if (!("guildId" in channel)) throw new Error("Cannot join a non-guild voice channel."); - const vm = getVoiceManager(this.client); - if (!vm) throw new Error("VoiceManager not available."); - return vm.join(channel); - } -} - -/** @class Channel @description Wrapper around a Discord channel object providing helpers for sending messages and observing users. */ -export class Channel { - /** @type {object} The raw channel object. */ - channel; - /** @type {MessageHandler} */ - handler; - - /** @param {object} channel @param {MessageHandler} handler */ - constructor(channel, handler) { - this.channel = channel; - this.handler = handler; - } - - /** @returns {object|null} The guild this channel belongs to. */ - get server() { - return this.channel?.guild ?? null; - } - /** @returns {object|null} Alias for server (guild). */ - get guild() { - return this.channel?.guild ?? null; - } - /** @returns {boolean} Whether this channel is a voice channel. */ - get isVoice() { - return this.channel?.isVoiceBased?.() ?? false; - } - /** @returns {string} The channel ID. */ - get id() { - return this.channel?.id; - } - /** @returns {string|null} The guild ID. */ - get guildId() { - return this.channel?.guildId ?? null; - } - /** @returns {string|null} Alias for guildId. */ - get serverId() { - return this.guildId; - } - - /** Observe messages from a specific user in this channel. @param {Function} callback @param {object} user @returns {Function} Unobserve function. */ - onMessageUser(callback, user) { - const resolvedUserId = user?.id - ?? user?._id - ?? user?.user?.id - ?? null; - const resolvedChannel = this.channel ?? null; - if (!resolvedUserId || !resolvedChannel?.id) { - return () => {}; - } - const oid = this.handler.observeUserMessagesChannel(resolvedUserId, resolvedChannel, callback); - return () => { - this.handler.unobserveUserMessagesChannel(oid); - }; - } - - /** Send a message to this channel. @param {string|object} content @returns {Promise} */ - sendMessage(content) { - return this.handler.sendMessage(this.channel, content); - } - - /** Alias for sendMessage. @param {string|object} content @returns {Promise} */ - send(content) { - return this.handler.sendMessage(this.channel, content); - } - - /** Send an embed to this channel. @param {string|object} content @param {object} [embedOptions={}] @returns {Promise} */ - sendEmbed(content, embedOptions = {}) { - return this.handler.sendEmbed(this.channel, content, embedOptions); - } - - /** Join this voice channel. @async @returns {Promise} @throws {Error} If not a voice channel. */ - join() { - if (!this.isVoice) throw new Error("Cannot join a text channel. Attempting to 'join' into channel `" + this.channel?.id + "`"); - return this.handler.joinChannel(this.channel.id); - } -} - -/** @class Message @description Wrapper around a Discord message providing helpers for replying, editing, and reaction observation. */ -export class Message { - /** @type {object} */ - message; - /** @type {MessageHandler} */ - handler; - - /** @param {object} message @param {MessageHandler} handler */ - constructor(message, handler) { - this.message = message; - this.handler = handler; - } - - /** @returns {string} The raw message content. */ - get content() { - return this.message.content; - } - /** @returns {string} The message ID. */ - get id() { - return this.message.id; - } - /** @returns {object} The author object. */ - get author() { - return this.message.author; - } - /** @returns {string} The author's user ID. */ - get authorId() { - return this.message.author?.id; - } - /** @returns {object|null} The guild member, if available. */ - get member() { - return this.message.member ?? null; - } - /** @returns {Channel} The wrapped channel this message was sent in. */ - get channel() { - return this.handler.getChannel(this.message.channelId); - } - - /** Observe reactions on this message. @param {string[]} reactions @param {Function} callback @param {object} [user=null] @returns {Function} Unobserve function. */ - onReaction(reactions, callback, user = null) { - const oid = this.handler.observeReactions(this.message, reactions, callback, user); - return () => { - this.handler.unobserveReactions(oid); - }; - } - - /** Reply to this message. @param {string|object} content @param {boolean} [mention=false] @returns {Promise} */ - reply(content, mention = false) { - return this.handler.reply(this.message, content, mention); - } - - /** Reply to this message with an embed. @param {string|object} content @param {boolean} [mention=false] @param {object} [embedOptions={}] @returns {Promise} */ - replyEmbed(content, mention = false, embedOptions = {}) { - return this.handler.replyEmbed(this.message, content, { - mention, - embed: embedOptions - }); - } - - /** Edit this message's embed. @param {string|object} content @param {object} [embedOptions={}] @returns {Promise} */ - editEmbed(content, embedOptions = {}) { - return this.handler.editEmbed(this.message, content, embedOptions); - } - - /** Alias for editEmbed. @param {string|object} content @param {object} [embedOptions={}] @returns {Promise} */ - edit(content, embedOptions = {}) { - return this.handler.editEmbed(this.message, content, embedOptions); - } -} - -/** @class PageBuilder @description Splits content into pages with template-based formatting. */ -export class PageBuilder { - /** @type {string} Template form string with $maxPage, $currentPage, $content placeholders. */ - form = ""; - /** @type {number} Maximum lines per page. */ - maxLinesPerPage = 2; - /** @type {Array|string[]} Content lines or array items. */ - content = []; - /** @type {boolean} Whether pages have been created. */ - initiated = false; - /** @type {Array} Created page arrays. */ - pages = []; - - /** @param {string|Array} content - String to split by newlines or an array of items. */ - constructor(content) { - if (!Array.isArray(content)) { - this.content = content.split("\n"); - return; - } - this.content = content; - } - - /** Set the template form string with $maxPage, $currentPage, $content placeholders. @param {string} form @returns {PageBuilder} */ - setForm(form) { - this.form = form; - this.initiated = false; - return this; - } - - /** Set the maximum lines per page. @param {number} [maxLinesPerPage=2] @returns {PageBuilder} */ - setMaxLines(maxLinesPerPage = 2) { - this.maxLinesPerPage = maxLinesPerPage; - this.initiated = false; - return this; - } - - /** Create page arrays from content. Lazily initialized; returns cached pages if already created. @returns {Array} */ - createPages() { - if (this.initiated) return this.pages; - - const lines = this.content; - const pages = []; - for (let i = 0; i < lines.length; i++) { - const n = Math.floor(i / this.maxLinesPerPage); - if (!pages[n]) pages[n] = []; - pages[n].push(lines[i]); - } - - this.pages = pages; - this.initiated = true; - return pages; - } - - /** Get a formatted page string by index (0-based). @param {number} n @returns {string|null} */ - getPage(n) { - const pages = this.createPages(); - if (!pages[n]) return null; - return this.form - .replace(/\$maxPage/gi, pages.length) - .replace(/\$currentPage/gi, n + 1) - .replace(/\$currPage/gi, n + 1) - .replace(/\$content/gi, pages[n].join("\n")); - } - - /** Get raw page content by index (0-based) without template formatting. @param {number} n @returns {string|null} */ - getContent(n) { - const pages = this.createPages(); - if (!pages[n]) return null; - return pages[n].join("\n"); - } - - /** Get the total number of pages. @returns {number} */ - size() { - return this.pages.length; - } -} - -/** @class RichPaginator @description Multi-tab paginated embed with tab and arrow navigation via reactions. */ -export class RichPaginator { - /** @param {Message} msg @param {MessageHandler} handler */ - constructor(msg, handler) { - this._msg = msg; - this._handler = handler; - this._tabs = []; - this._prev = "⬅️"; - this._next = "➡️"; - this._timeout = 5 * 60 * 1000; - this._color = getGlobalColor(); - this._state = { tab: 0, page: 0 }; - } - - /** Set the session timeout duration. @param {number} ms @returns {RichPaginator} */ - setTimeout(ms) { this._timeout = ms; return this; } - - /** Set the embed color. @param {number} color @returns {RichPaginator} */ - setColor(color) { this._color = color; return this; } - - /** Set the initially selected tab index. @param {number} idx @returns {RichPaginator} */ - setStartTab(idx) { this._state.tab = idx; return this; } - - /** Set the previous/next arrow emoji strings. @param {string} prev @param {string} next @returns {RichPaginator} */ - setPrevNext(prev, next) { this._prev = prev; this._next = next; return this; } - - /** Add a tab to the paginator. @param {object} tab @param {string} tab.emoji @param {string} tab.title @param {string} tab.header @param {string} [tab.content] @param {string[]} [tab.pages] @returns {RichPaginator} */ - addTab(tab) { - this._tabs.push({ - emoji: tab.emoji, - title: tab.title, - header: tab.header, - pages: tab.pages ?? (tab.content != null ? [tab.content] : []), - }); - return this; - } - - /** @private Build an embed for a given tab and sub-page. @param {number} tabIdx @param {number} pageIdx @returns {EmbedBuilder} */ - _buildEmbed(tabIdx, pageIdx) { - const tab = this._tabs[tabIdx]; - const totalTabs = this._tabs.length; - const totalPages = Math.max(1, tab.pages.length); - const safePage = Math.max(0, Math.min(pageIdx, totalPages - 1)); - const content = tab.pages[safePage] ?? ""; - - const footerParts = [`Page ${tabIdx + 1}/${totalTabs}`]; - if (totalPages > 1) footerParts.push(`• Subpage ${safePage + 1}/${totalPages}`); - - return new EmbedBuilder() - .setColor(this._color) - .setAuthor({ name: tab.header }) - .setTitle(tab.title) - .setDescription(content) - .setFooter({ text: footerParts.join(" ") }); - } - - /** @async Send the paginated embed and start observing reactions. @returns {Promise} The raw sent message. */ - async send() { - if (this._tabs.length === 0) return null; - - const tabEmojis = this._tabs.map(t => t.emoji); - const allReactions = [...tabEmojis, this._prev, this._next]; - - const nativeMsg = this._msg.message ?? this._msg; - if (!nativeMsg?.reply) return null; - - const rawMsg = await nativeMsg.reply( - { embeds: [this._buildEmbed(this._state.tab, this._state.page)] }, - { ping: false } - ).catch(() => null); - - if (!rawMsg) return null; - - const guildId = (this._msg.channel?.guildId) ?? (this._msg.guildId) ?? null; - - for (const emoji of allReactions) { - await rawMsg.react(emoji).catch(() => {}); - } - - const wrapped = new Message(rawMsg, this._handler); - const state = this._state; - const tabs = this._tabs; - const prev = this._prev; - const next = this._next; - const buildEmbed = this._buildEmbed.bind(this); - - const unobserve = wrapped.onReaction(allReactions, async (e) => { - const emoji = e.emoji_id; - - if (emoji === prev || emoji === next) { - const tab = tabs[state.tab]; - const totalPages = Math.max(1, tab.pages.length); - if (totalPages <= 1) return; - state.page = emoji === prev - ? (state.page - 1 + totalPages) % totalPages - : (state.page + 1) % totalPages; - } else { - const idx = tabEmojis.indexOf(emoji); - if (idx === -1 || idx === state.tab) return; - state.tab = idx; - state.page = 0; - } - - rawMsg.edit({ embeds: [buildEmbed(state.tab, state.page)] }).catch(() => {}); - }); - - /** @private Clear all reactions on the paginator message. */ - const clearReactions = async () => { - try { - await rawMsg.removeAllReactions(); - return; - } catch (e) { - if (String(e?.message ?? e).includes("Message wasn't found") || e?.code === 10008) return; - logger.warn("[RichPaginator] removeAllReactions failed:", e?.message ?? e); - } - for (const emoji of allReactions) { - try { - await rawMsg.removeReaction(emoji); - } catch(e) { - if (String(e?.message ?? e).includes("Message wasn't found") || e?.code === 10008) return; - logger.warn("[MessageHandler] Error:", e?.message); - } - } - }; - - /** @private Close the pagination session, update footer, and clear reactions. */ - const closeSession = async () => { - unobserve(); - const currentEmbed = buildEmbed(state.tab, state.page); - if (!currentEmbed.footer) currentEmbed.footer = { text: "" }; - currentEmbed.footer.text += " • " + this._handler.t(guildId, "pagination.embed.sclosedTitle"); - rawMsg.edit({ embeds: [currentEmbed] }).catch(() => {}); - await clearReactions(); - }; - - let timer = setTimeout(closeSession, this._timeout); - - /** @private Reset the inactivity timer. */ - const resetTimer = () => { - clearTimeout(timer); - timer = setTimeout(closeSession, this._timeout); - }; - - const origHandler = wrapped.handler.observedReactions.get(rawMsg.id); - if (origHandler) { - const origCb = origHandler.cb; - origHandler.cb = (e, m) => { resetTimer(); origCb(e, m); }; - } - - return rawMsg; - } -} - -/** @class QueuePaginator @description Simple two-arrow paginator for queue embeds with page count. */ -export class QueuePaginator { - /** @param {Message} msg @param {MessageHandler} handler @param {Client} client */ - constructor(msg, handler, client) { - this._msg = msg; - this._handler = handler; - this._client = client; - this._timeout = 30 * 1000; - this._prev = "⬅️"; - this._next = "➡️"; - } - - /** Set the session timeout duration. @param {number} ms @returns {QueuePaginator} */ - setTimeout(ms) { this._timeout = ms; return this; } - - /** Set the previous/next arrow emoji strings. @param {string} prev @param {string} next @returns {QueuePaginator} */ - setPrevNext(prev, next) { this._prev = prev; this._next = next; return this; } - - /** @async Send the paginated embed and observe arrow reactions. @param {Function} buildEmbed - Function that takes a page number and returns an EmbedBuilder. @param {number} totalPages @param {number} [startPage=1] @returns {Promise} The raw sent message. */ - async send(buildEmbed, totalPages, startPage = 1) { - const state = { page: Math.max(1, Math.min(startPage, totalPages)) }; - const nativeMsg = this._msg.message ?? this._msg; - if (!nativeMsg?.reply) return null; - const rawMsg = await nativeMsg.reply( - { embeds: [buildEmbed(state.page)] }, - { ping: false } - ).catch(() => null); - - if (!rawMsg) return null; - - const guildId = (this._msg.channel?.guildId) ?? (this._msg.guildId) ?? null; - - if (totalPages <= 1) return rawMsg; - - const prev = this._prev; - const next = this._next; - - await rawMsg.react(prev).catch(() => {}); - await rawMsg.react(next).catch(() => {}); - - const client = this._client; - const channelId = rawMsg.channelId ?? rawMsg.channel_id ?? rawMsg.channel?.id; - const msgId = rawMsg.id; - - /** @private Clear all reactions on the paginator message. */ - const clearReactions = async () => { - try { - await rawMsg.removeAllReactions(); - } catch (e) { - // Message deleted — nothing left to clean up. - if (String(e?.message ?? e).includes("Message wasn't found") || e?.code === 10008) return; - for (const emoji of [prev, next]) { - try { - await rawMsg.removeReaction(emoji); - } catch(e) { - if (String(e?.message ?? e).includes("Message wasn't found") || e?.code === 10008) return; - logger.warn("[MessageHandler] Error:", e?.message); - } - } - } - }; - - /** @private Close the pagination session, update footer, and clear reactions. */ - const closeSession = async () => { - unobserve(); - const embed = buildEmbed(state.page); - const closedLabel = this._handler.t(guildId, "pagination.embed.sclosedTitle"); - if (embed.footer && typeof embed.footer.text === "string") { - embed.footer.text += " • " + closedLabel; - } else { - embed.footer = { text: closedLabel }; - } - rawMsg.edit({ embeds: [embed] }).catch(() => {}); - await clearReactions(); - }; - - let timer = setTimeout(closeSession, this._timeout); - /** @private Reset the inactivity timer. */ - const resetTimer = () => { - clearTimeout(timer); - timer = setTimeout(closeSession, this._timeout); - }; - - const wrapped = new Message(rawMsg, this._handler); - const unobserve = wrapped.onReaction([prev, next], (e) => { - resetTimer(); - state.page = e.emoji_id === prev - ? (state.page <= 1 ? totalPages : state.page - 1) - : (state.page >= totalPages ? 1 : state.page + 1); - rawMsg.edit({ embeds: [buildEmbed(state.page)] }).catch(() => {}); - }); - - return rawMsg; - } -} - -/** @type {number} Maximum commands listed per page in the help paginator. */ -const HELP_CMDS_PER_PAGE = 10; -/** @type {number} Help paginator session timeout in milliseconds. */ -const HELP_SESSION_MS = 30 * 1000; - -const HELP_TABS = [ - { - emoji: "🏠", - title: "Home", - header: "Home Page", - static: true, - }, - { - emoji: "🎵", - title: "Music", - header: "Music Commands", - categories: ["music"], - }, - { - emoji: "🔧", - title: "Utilities", - header: "Utility Commands", - categories: ["util", "default"], - }, - { - emoji: "ℹ️", - title: "Support", - header: "Support Info", - static: true, - }, -]; - -/** @private @param {string} prefix @returns {string} */ -function _helpHomeContent(prefix) { - return ( - "**Welcome to the Remix help page.**\n\n" + - "Remix is an open-source music bot. It supports a variety of " + - "streaming services and has many features.\n\n" + - "We hope you enjoy using Remix!\n\n" + - "To get started, just click on the reactions below to find out " + - "more about the commands. In the case that reactions don't work " + - "for you, there's also the possibility to look through them by " + - `using \`${prefix}help \` :)\n\n` + - `**Tip:** Click the tab emojis to switch sections.` - ); -} - -/** @private @returns {string} */ -function _helpSupportContent() { - return ( - "If you need help with anything or encounter any issues, hop over to " + - "our support server **[Remix HQ](https://fluxer.gg/remix)**!\n" + - "Alternatively, you can write a dm to any of the following people:\n\n" + - "- **Fantic** (Community Manager)\n" + - "- **Shadow** (Lead Developer)\n" + - "- **NoLogicAlan** (Lead Developer)" - ); -} - -/** @private Build paginated content for a help category tab. @param {object} tab @param {Array} allCmds @param {string} prefix @returns {string[]} */ -function _helpBuildCategoryPages(tab, allCmds, prefix) { - const cmds = allCmds - .filter(cmd => { - if (cmd.requirements?.some(r => r.ownerOnly)) return false; - return tab.categories?.includes(cmd.category ?? "default"); - }) - .sort((a, b) => a.name.localeCompare(b.name)); - - if (cmds.length === 0) return ["_No commands available._"]; - - const pages = []; - for (let i = 0; i < cmds.length; i += HELP_CMDS_PER_PAGE) { - const slice = cmds.slice(i, i + HELP_CMDS_PER_PAGE); - let page = ""; - slice.forEach((cmd, j) => { - const d = (cmd.description || "No description.").split("\n")[0]; - page += `${i + j + 1}. **${cmd.name}**: ${d}\n`; - }); - page += `\nTo learn more about a command, run \`${prefix}help \`!`; - if (cmds.length > HELP_CMDS_PER_PAGE) - page += `\n\n**Tip:** Use ⬅️ ➡️ to scroll between pages.`; - pages.push(page); - } - return pages; -} - -/** @class HelpCommand @description Rich paginated help command with tabbed navigation (Home, Music, Utilities, Support). */ -export class HelpCommand { - /** @param {CommandHandler} commandHandler @param {MessageHandler} messageHandler @param {Function} getSettingsFn */ - constructor(commandHandler, messageHandler, getSettingsFn) { - this._commands = commandHandler; - this._messages = messageHandler; - this._getSettings = getSettingsFn; - } - - /** Register the help command, intercept invalid command replies, and intercept help aliases. */ - register() { - if (this._registered) return; - this._registered = true; - - const HELP_ALIASES = ["help", "h", "commands"]; - - this._commands.helpCommand = "\x00help"; - const _fmt = this._commands.format.bind(this._commands); - this._commands.format = (text, guildId) => - _fmt(text, guildId).replace(/\x00help/g, "help"); - - const _reply = this._commands.replyHandler.bind(this._commands); - this._commands.replyHandler = (message, msg) => { - if (typeof message === "string" && message.toLowerCase().includes("unknown command")) { - const content = msg?.content ?? msg?.message?.content ?? ""; - const guildId = msg?.channel?.channel?.guildId ?? msg?.message?.guildId; - const prefix = this._commands.getPrefix(guildId); - const botId = this._commands.client.user?.id; - const ping = `<@${botId}>`; - const pingBang = `<@!${botId}>`; - let body = null; - if (content.startsWith(prefix)) body = content.slice(prefix.length).trim(); - else if (content.startsWith(pingBang)) body = content.slice(pingBang.length).trim(); - 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; - } - } - return _reply(message, msg); - }; - - const evict = () => { - for (const alias of HELP_ALIASES) { - const i = this._commands.commandNames.indexOf(alias); - if (i !== -1) this._commands.commandNames.splice(i, 1); - } - const ci = this._commands.commands.findIndex(c => - c.aliases.some(a => HELP_ALIASES.includes(a.toLowerCase())) - ); - if (ci !== -1) this._commands.commands.splice(ci, 1); - }; - evict(); - const _add = this._commands.addCommand.bind(this._commands); - this._commands.addCommand = (builder) => { - const r = _add(builder); - if (builder.aliases.some(a => HELP_ALIASES.includes(a.toLowerCase()))) evict(); - return r; - }; - - this._messages.onMessage((msg) => { - if (!msg?.content) return; - const content = msg.content.trim(); - const guildId = msg.channel?.channel?.guildId ?? msg.message?.guildId; - const prefix = this._commands.getPrefix(guildId); - const botId = this._commands.client.user?.id; - const ping = `<@${botId}>`; - const pingBang = `<@!${botId}>`; - let body = null; - if (content.startsWith(prefix)) body = content.slice(prefix.length).trim(); - else if (content.startsWith(pingBang)) body = content.slice(pingBang.length).trim(); - else if (content.startsWith(ping)) body = content.slice(ping.length).trim(); - if (body === null) return; - - const args = body.split(/\s+/).map(s => s.trim()).filter(Boolean); - const cmdName = (args[0] ?? "").toLowerCase(); - if (!HELP_ALIASES.includes(cmdName)) return; - - this._handle(msg, args.slice(1), prefix); - }); - } - - /** @private Handle a help invocation: show command detail or paginated overview. @param {Message} msg @param {string[]} args @param {string} prefix */ - _handle(msg, args, prefix) { - const allCmds = this._commands.commands; - const query = (args[0] ?? "").trim(); - - if (query && isNaN(Number(query))) { - let currCmd = null; - for (const word of [query, ...args.slice(1)]) { - const pool = currCmd ? currCmd.subcommands : allCmds; - const found = pool.find(c => - c.aliases.some(a => a.toLowerCase() === word.toLowerCase()) - ); - if (!found) { - const guildId = msg.channel?.channel?.guildId ?? msg.message?.guildId; - msg.reply(this._commands.t(guildId, "cmdHandler.help.unknownCommand", { command: word, prefix })); - return; - } - currCmd = found; - } - if (currCmd) { - msg.reply(this._commands.helpHandler.getCommandHelp(currCmd, msg)); - } - return; - } - - const startTab = query - ? Math.max(0, Math.min(HELP_TABS.length - 1, parseInt(query) - 1)) - : 0; - - const paginator = new RichPaginator(msg, this._messages) - .setTimeout(HELP_SESSION_MS) - .setStartTab(startTab); - - for (const tab of HELP_TABS) { - if (tab.static) { - const content = tab.title === "Home" - ? _helpHomeContent(prefix) - : _helpSupportContent(); - paginator.addTab({ emoji: tab.emoji, title: tab.title, header: tab.header, content }); - } else { - const pages = _helpBuildCategoryPages(tab, allCmds, prefix); - paginator.addTab({ emoji: tab.emoji, title: tab.title, header: tab.header, pages }); - } - } - - paginator.send(); - } -} diff --git a/src/Player.mjs b/src/Player.mjs deleted file mode 100644 index 1eb778c..0000000 --- a/src/Player.mjs +++ /dev/null @@ -1,2105 +0,0 @@ -/** @module src/Player @description Core music player with queue management, voice connection handling, track streaming, and playback controls. */ - - -import { getVoiceManager } from "@fluxerjs/voice"; -import { Utils, cleanId } from "./Utils.mjs"; -import { EventEmitter } from "node:events"; -import meta from "./probe.mjs"; -import http from "node:http"; -import https from "node:https"; -import { EmbedBuilder } from "@fluxerjs/core"; -import { getGlobalColor } from "./MessageHandler.mjs"; -import { logger } from "./constants/Logger.mjs"; -import { get247ChannelMode } from "./constants/Helpers247.mjs"; -import { PROVIDERS, PROVIDER_NAMES } from "./constants/providers.mjs"; -import { hasHumansInChannel } from "./constants/VoiceStateResolver.mjs"; -import { FluxerAudioBridge } from "./FluxerAudioBridge.mjs"; - - -/** @class Queue @description Internal queue data structure that tracks tracks, loop state, and emits queue events. @extends {EventEmitter} */ -export class Queue extends EventEmitter { - /** @type {Array} @description The queued track objects. */ - data = []; - /** @type {object|null} @description The currently playing track. */ - current = null; - /** @type {boolean} @description Whether queue loop is enabled. */ - loop = false; - /** @type {boolean} @description Whether single-song loop is enabled. */ - songLoop = false; - - /** Initialize an empty queue with no loop enabled. */ - constructor() { - super(); - } - - /** @returns {boolean} Whether the queue has no tracks. */ - isEmpty() { return this.data.length === 0; } - /** @returns {number} Number of tracks in the queue (excluding current). */ - size() { return this.data.length; } - - /** Advance to the next track in the queue. If songLoop is active, returns the current track. Emits a queue update event. @returns {object|null} The next track, or null if the queue is empty. */ - next() { - const previous = this.current; - - if (this.songLoop && this.current) return this.current; - if (this.loop && this.current) this.data.push(this.current); - - if (this.isEmpty()) { - this.current = null; - return null; - } - - this.current = this.data.shift(); - this.emit("queue", { - type: "update", - data: { current: this.current, old: previous, loop: this.loop } - }); - return this.current; - } - -/** Remove a track from the queue by index. @param {number} idx - Zero-based index of the track to remove. @returns {string} Result message indicating success or out-of-bounds error. */ - remove(idx) { - if (idx < 0 || idx >= this.data.length) return "Index out of bounds"; - const title = this.data[idx].title; - const removed = this.data.splice(idx, 1); - this.emit("queue", { type: "remove", data: { index: idx, old: this.data.slice(), removed, new: this.data } }); - return `Successfully removed **${title}** from the queue.`; - } - -/** Move a track from one position to another (0-based indices). @param {number} from - Source index. @param {number} to - Destination index. @returns {string} Result message indicating success or error. */ - move(from, to) { - if (from < 0 || from >= this.data.length) return "Source index out of bounds"; - if (to < 0 || to >= this.data.length) return "Target index out of bounds"; - if (from === to) return "Track is already in that position"; - const [track] = this.data.splice(from, 1); - this.data.splice(to, 0, track); - this.emit("queue", { type: "move", data: { from, to, track } }); - return `Moved **${track.title}** from position ${from + 1} to ${to + 1}.`; - } - -/** Add a single track to the queue. @param {object} data - Track data object. @param {boolean} [top=false] - If true, insert at the front of the queue. @returns {number} The new length of the queue. */ - add(data, top = false) { - this.emit("queue", { type: "add", data: { append: !top, data } }); - return top ? this.data.unshift(data) : this.data.push(data); - } - -/** Add multiple tracks to the queue (up to 1000). @param {Array} tracks - Array of track data objects. @param {boolean} [top=false] - If true, insert at the front of the queue. @returns {number} Number of tracks actually added. */ - addMany(tracks, top = false) { - if (!tracks?.length) return 0; - if (!Array.isArray(tracks)) tracks = []; - const count = Math.min(tracks.length, 1000); - if (top) { - for (let i = count - 1; i >= 0; i--) this.data.unshift(tracks[i]); - } else { - for (let i = 0; i < count; i++) this.data.push(tracks[i]); - } - this.emit("queue", { type: "addMany", data: { append: !top, tracks: tracks.slice(0, count) } }); - return count; - } - - /** Remove all tracks from the queue. */ - clear() { this.data.length = 0; } - /** Clear the queue and reset all state (current, loops). */ - reset() { this.clear(); this.current = null; this.songLoop = false; this.loop = false; } - - /** @param {boolean} bool - Enable or disable song loop. */ - setSongLoop(bool) { this.songLoop = bool; } - /** @param {boolean} bool - Enable or disable queue loop. */ - setLoop(bool) { this.loop = bool; } - -/** Toggle a loop mode on or off. @param {"song"|"queue"} loop - The type of loop to toggle. @returns {boolean|null} The new loop state, or null if the loop type is invalid. */ - toggleLoop(loop) { - if (loop === "song") { this.setSongLoop(!this.songLoop); return this.songLoop; } - if (loop === "queue") { this.setLoop(!this.loop); return this.loop; } - return null; - } - - /** Shuffle the queue in place and emit a queue event. */ - shuffle() { - Utils.shuffleArr(this.data); - this.emit("queue", { type: "shuffle", data: this.data }); - } - - /** @returns {object|null} The currently playing track. */ - getCurrent() { return this.current; } - /** @returns {Array} A copy of the queue array. */ - getQueue() { return this.data; } - -/** Get a paginated slice of the queue. @param {number} [page=1] - 1-based page number (clamped to valid range). @param {number} [pageSize=10] - Number of tracks per page. @returns {object} Page result with items, page, totalPages, total, and start index. */ - getPage(page = 1, pageSize = 10) { - const total = this.data.length; - const totalPages = Math.max(1, Math.ceil(total / pageSize)); - const safePage = Utils.clamp(page, 1, totalPages); - const start = (safePage - 1) * pageSize; - return { items: this.data.slice(start, start + pageSize), page: safePage, totalPages, total, start }; - } -} - -/** @class Player @description Main music player class. Manages voice connections, playback, queue, filters, and search. Extends EventEmitter. */ -export default class Player extends EventEmitter { - /** @private */ - _voiceConn = null; - _audioBridge = null; - lavalinkPlayer = null; - connection = null; - _guildId = null; - _channelId = null; - _lastConnectedAt = null; - _home247Channel = null; - - queue = null; - client = null; - settings = null; - config = {}; - - _lavalink = null; - - leaving = false; - _paused = false; - _pausedAt = null; - _playingNext = false; - startedPlaying = null; - searches = new Map(); - _searchMaxSize = 50; - _maxQueueSize = 10_000; - resultLimit = 5; - preferredVolume = 1; - - _skipping = false; - _seeking = false; - _wasRadio = false; - _radioAnnounced = false; - _queueEndedSent = false; - _lastPlayedTrack = null; - - _autoplay = false; - _autoplayHandler = null; - - activeFilter = null; - activeFilterPayload = null; - - static INACTIVITY_DEFAULT_MS = 3 * 60 * 1000; - static TRACK_MOSTLY_FINISHED_RATIO = 0.85; - static TRACK_MOSTLY_FINISHED_FLOOR_MS = 15_000; - static RADIO_SAFETY_TIMEOUT_MS = 20 * 60 * 1000; - - _inactivityTimer = null; - _inactivityLimit = Player.INACTIVITY_DEFAULT_MS; - _pendingInactivityCheck = false; - - _isJoining = false; - - _destroyed = false; - _rejoinTimer = null; - -/** - * Create a new Player instance bound to a voice channel. - * - * @param {string} token - Bot authentication token (used internally, NOT guild ID). - * @param {object} [opts={}] - Player configuration options. - * @param {import('@fluxerjs/core').Client} [opts.client] - The Discord/Fluxer client instance. - * @param {object} [opts.config] - Full bot configuration object. - * @param {import('../src/LavalinkManager.mjs').LavalinkManager} [opts.lavalink] - Lavalink node manager for track search. - * @param {import('../src/Settings.mjs').RemoteSettingsManager} [opts.settingsMgr] - Remote settings manager. - * @param {Function} [opts.getPrefix] - Function returning command prefix for a guild: (guildId) => string. - * @param {import('../src/constants/VoiceStateCache.mjs').VoiceStateCache} [opts.observedVoiceUsers] - Voice state cache (legacy alias, same as voiceCache). - * @param {import('../src/constants/VoiceStateCache.mjs').VoiceStateCache} [opts.voiceCache] - Voice state cache for human/bot tracking. - * @param {import('../src/constants/Locale.mjs').Locale} [opts.locale] - Locale manager for i18n. - * @param {import('../src/TrackOptionsManager.mjs').TrackOptionsManager} [opts.trackOptions] - Per-user track option matcher. - */ - constructor(token, opts = {}) { - super(); - - this.queue = new Queue(); - this.queue.on("queue", (...args) => this.emit("queue", ...args)); - this.client = opts.client; - this.config = opts.config ?? {}; - this.settings = opts.settings ?? null; - this.settingsMgr = opts.settingsMgr ?? null; - this._getPrefix = opts.getPrefix ?? null; - this._observedVoiceUsers = opts.observedVoiceUsers ?? null; - this._voiceCache = opts.voiceCache ?? null; - this.locale = opts.locale ?? null; - this.trackOptions = opts.trackOptions ?? null; - this._activeTrackOpt = null; - - this._lavalink = opts.lavalink ?? null; - - this._audioBridge = new FluxerAudioBridge(opts.lavalink ?? null); - this._audioBridge.on("error", (err) => { - logger.error(`[Player] Audio bridge error (guild ${this._guildId}): ${err.message}`); - }); - - const inactivityMs = this.config?.timers?.inactivityTimeout ?? this.config?.inactivityTimeout; - if (inactivityMs !== undefined) { - const parsed = Number(inactivityMs); - if (!Number.isNaN(parsed) && parsed >= 0) { - this._inactivityLimit = parsed; - } - } - - if (this._lavalink) { - this._onLavalinkPlayerDisconnect = (lavaPlayer) => { - if (!lavaPlayer || String(lavaPlayer.guildId) !== String(this._guildId)) return; - logger.lavalink("[Player] lavalink-client player disconnect (guild: " + this._guildId + ") — ignored (voice via LiveKit)"); - }; - this._lavalink.on("playerDisconnected", this._onLavalinkPlayerDisconnect); - } - } - - /** - * Handle the end of a track. Advances to next song or starts 24/7 wait. - * For radio tracks, stops playback and starts inactivity (if not 24/7). - * @private - */ - _handleTrackEnd() { - const songData = this.queue.getCurrent(); - if (!songData) return; - - this._clearTrackEndTimer(); - - if (songData.type === "radio") { - logger.player(`[Player] Radio track ended: ${songData.title}`); - this._lastPlayedTrack = this.queue.getCurrent() ?? songData; - this.queue.current = null; - this.emit("stopplay"); - if (!this._is247Enabled()) { - this._startInactivityTimer(); - } - return; - } - - if (!this._paused) { - this._lastPlayedTrack = this.queue.getCurrent() ?? songData; - if (!this.queue.songLoop) this.queue.current = null; - this._playingNext = false; - this.playNext().catch(e => logger.error("[Player] auto-advance playNext error:", e.message)); - } - } - - /** - * Check whether 24/7 mode is active for this player's current channel. - * @returns {boolean} True if 24/7 is enabled. - */ - _is247Enabled() { - return this._get247Mode() !== "off"; - } - - /** - * Resolve the 24/7 mode for this player's current or home channel. - * Checks the guild's stay_247 setting to determine if the channel is registered. - * @returns {"on"|"off"} The 24/7 mode. Only "on" or "off" — no "auto". - * @private - */ - _get247Mode() { - if (!this._guildId) return "off"; - const serverSettings = this.settingsMgr?.getServer?.(this._guildId) - ?? this.settings - ?? this.client?.settings?.getServer?.(this._guildId); - if (!serverSettings?.get) return "off"; - - const channelId = cleanId(this._home247Channel ?? this._channelId ?? ""); - if (!channelId) return "off"; - - - const raw = serverSettings.get("stay_247"); - if (raw && raw !== "none") { - const channels = Array.isArray(raw) - ? raw.map(id => cleanId(id)).filter(Boolean) - : [cleanId(raw)].filter(Boolean); - if (!channels.includes(channelId)) return "off"; - } else { - return "off"; - } - - return get247ChannelMode(serverSettings, channelId); - } - - /** @private @returns {string|null} The cleaned guild ID, or null if unresolvable. */ - _resolveGuildId() { - const cleanGuild = cleanId(this._guildId ?? ""); - if (cleanGuild) return cleanGuild; - - try { - const channelId = this._channelId ?? this._home247Channel; - if (channelId) { - const ch = this.client?.channels?.get?.(channelId); - const fromChannel = ch?.guildId ?? ch?.guild?.id ?? null; - if (fromChannel) return cleanId(fromChannel); - } - } catch(e) { logger.warn("[Player] Guild resolution failed:", e?.message); } - - return null; - } - - /** @private Restore saved volume from guild settings. */ - _restoreVolume() { - if (!this._guildId) return; - let savedVol = null; - - if (this.settings?.get) { - savedVol = this.settings.get("volume"); - } else if (this.settingsMgr?.getServer) { - const set = this.settingsMgr.getServer(this._guildId); - savedVol = set?.get?.("volume"); - } else if (this.client?.settings?.getServer) { - savedVol = this.client.settings.getServer(this._guildId)?.get?.("volume"); - } else if (this.client?.settings?.get) { - const s = this.client.settings.get(this._guildId); - savedVol = s?.get?.("volume") ?? s?.volume; - } - - if (savedVol !== undefined && savedVol !== null) { - const parsed = Number(savedVol); - if (!Number.isNaN(parsed) && parsed > 0) { - this.preferredVolume = Utils.clamp(parsed / 100, 0, 2); - logger.player(`[Player] Restored volume ${savedVol}% for guild ${this._guildId}`); - if (this._voiceConn) { - try { this._voiceConn.setVolume(this.preferredVolume * 100); } catch (_) {} - } - } - } - } - - /** @private @returns {boolean} Whether there are non-bot users in the voice channel. */ - _hasHumansInChannel() { - return hasHumansInChannel({ - guildId: cleanId(this._guildId ?? ""), - channelId: cleanId(this._channelId ?? ""), - client: this.client, - voiceCache: this._voiceCache, - observedVoiceUsers: this._observedVoiceUsers, - botId: this.client?.user?.id, - }); - } - - /** - * Start the inactivity timer. Skipped if: - * - 24/7 mode is active (mode === "on") - * - Queue has songs - * - Humans are present in the channel - * The timer callback re-checks all conditions before emitting autoleave. - */ - _startInactivityTimer() { - this._stopInactivityTimer(); - if (this._inactivityLimit <= 0) return; - - const mode = this._get247Mode(); - logger.inactivity(`[Player] Checking 24/7 mode for guild ${this._guildId}: ${mode}`); - - if (mode === "on") { - logger.inactivity(`[Player] 24/7 mode active for guild ${this._guildId}, skipping inactivity timer`); - return; - } - - if (this.queue?.getCurrent() || !this.queue?.isEmpty()) { - logger.inactivity(`[Player] Queue has songs for guild ${this._guildId}, skipping inactivity timer`); - return; - } - - if (this._hasHumansInChannel()) { - logger.inactivity(`[Player] Humans present in channel ${this._channelId}, skipping inactivity timer`); - return; - } - - logger.inactivity(`[Player] Starting inactivity timer for guild ${this._guildId} (${this._inactivityLimit / 1000}s)`); - this._inactivityTimer = setTimeout(() => { - const currentMode = this._get247Mode(); - if (currentMode === "on") { - logger.inactivity(`[Player] 24/7 mode enabled during inactivity wait, aborting leave`); - return; - } - if (this.queue?.getCurrent() || !this.queue?.isEmpty()) { - logger.inactivity("[Player] Song in queue during inactivity wait, aborting leave"); - return; - } - if (this._hasHumansInChannel()) { - logger.inactivity("[Player] Human joined during inactivity wait, aborting leave"); - return; - } - logger.inactivity(`[Player] Guild ${this._guildId} inactive too long. Leaving.`); - this.emit("autoleave"); - }, this._inactivityLimit); - } - - /** - * Clear the inactivity timer if running. - */ - _stopInactivityTimer() { - this._pendingInactivityCheck = false; - if (this._inactivityTimer) { - logger.inactivity(`[Player] Stopping inactivity timer for guild ${this._guildId}`); - clearTimeout(this._inactivityTimer); - this._inactivityTimer = null; - } - } - - /** - * Schedule a 24/7 rejoin after a delay. Guards against: - * - Player already destroyed - * - Intentional leave registered - * - Pending or existing player in the target channel - * @param {string} channelId - The channel to rejoin. - * @param {string} guildId - The guild ID. - * @param {string} mode - The 24/7 mode ("on"). - * @private - */ - _schedule247Rejoin(channelId, guildId, mode) { - const ctx = this.client?._remix; - if (!ctx) { - logger.warn(`[Player] Cannot schedule 24/7 rejoin for ${channelId} — no bot context`); - return; - } - - if (ctx.players?._pendingJoins?.has?.(channelId)) { - logger.voice247(`[Player] 24/7 rejoin skipped for ${channelId} — join already pending`); - return; - } - - if (ctx.players?.playerMap?.has(channelId)) { - const existing = ctx.players.playerMap.get(channelId); - if (existing && !existing._destroyed && existing !== this) { - logger.voice247(`[Player] 24/7 rejoin skipped for ${channelId} — another player already exists`); - return; - } - } - - const rejoinDelay = ctx.config?.timers?.rejoin247Delay ?? 3_000; - logger.voice247(`[Player] Scheduling 24/7 ${mode} rejoin for channel ${channelId} (guild ${guildId}) in ${rejoinDelay / 1000}s`); - - this._rejoinTimer = setTimeout(() => { - this._rejoinTimer = null; - if (this._destroyed) { - logger.voice247(`[Player] 24/7 rejoin cancelled — player destroyed`); - return; - } - if (ctx.intentionalLeaves?.has(channelId)) { - logger.voice247(`[Player] 24/7 rejoin cancelled — intentional leave registered`); - return; - } - - ctx.gatewayHandler?._rejoinChannel?.(guildId, channelId).catch(err => { - logger.warn(`[Player] 24/7 rejoin failed for channel ${channelId}:`, err?.message); - }); - }, rejoinDelay); - } - - /** @private @async @param {string} url @param {object} [options={}] @param {boolean} [returnStream=false] @returns {Promise} */ - async _request(url, options = {}, returnStream = false) { - return new Promise((resolve, reject) => { - const fetchUrl = (target, _redirects = 0) => { - const urlObj = new URL(target); - const client = urlObj.protocol === "https:" ? https : http; - - const req = client.request({ - protocol: urlObj.protocol, - host: urlObj.hostname, - port: urlObj.port, - path: urlObj.pathname + urlObj.search, - method: options.method || "GET", - headers: { - "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)", - "Accept": "*/*", - ...options.headers, - }, - }, (res) => { - if (returnStream) req.setTimeout(0); - - if ([301, 302, 307, 308].includes(res.statusCode)) { - let loc = res.headers.location; - if (!loc) return reject(new Error("Redirect without location")); - if (loc.startsWith("/")) loc = `${urlObj.protocol}//${urlObj.host}${loc}`; - if (_redirects >= 5) return reject(new Error("Too many redirects")); - const redirectUrl = new URL(loc); - if (redirectUrl.host !== urlObj.host) { - if (options.headers) delete options.headers.Authorization; - } - return fetchUrl(loc, _redirects + 1); - } - if (![200, 204, 206].includes(res.statusCode)) { - res.resume(); - return reject(new Error(`HTTP ${res.statusCode}`)); - } - if (returnStream) return resolve(res); - - if (res.statusCode === 204) { res.resume(); return resolve(null); } - - const chunks = []; - res.on("data", d => chunks.push(d)); - res.on("end", () => { - const raw = Buffer.concat(chunks).toString().trim(); - if (!raw) return resolve(null); - try { resolve(JSON.parse(raw)); } - catch (e) { reject(new Error(`JSON parse error from ${target}`)); } - }); - }); - - req.on("error", reject); - req.setTimeout(options.timeout || 60_000, () => { - req.destroy(); - reject(new Error("Request timeout")); - }); - if (options.body) req.write(options.body); - req.end(); - }; - fetchUrl(url); - }); - } - - /** @private Extract track duration in milliseconds from various possible track data shapes. @param {object} track @returns {number} */ - _getTrackDurationMs(track) { - if (track?._durationMs != null && track._durationMs > 0) { - return track._durationMs; - } - if (track?.duration) { - if (typeof track.duration === "object" && track.duration?.seconds != null) { - return track.duration.seconds * 1000; - } - if (typeof track.duration === "string" && track.duration.startsWith("PT")) { - return Utils.parseISODuration(track.duration); - } - if (typeof track.duration === "number") return track.duration; - } - if (track?.info?.length) return track.info.length; - if (track?.info?.duration != null) { - if (typeof track.info.duration === "number") return track.info.duration; - if (typeof track.info.duration === "object" && track.info.duration.seconds != null) - return track.info.duration.seconds * 1000; - } - return 0; - } - - /** @private Check if a track has played past 85% or within 15s of the end. @param {object} track @returns {boolean} */ - _didTrackMostlyFinish(track) { - const totalMs = this._getTrackDurationMs(track); - if (!totalMs || !this.startedPlaying) return false; - - const elapsedMs = Math.max(0, Date.now() - this.startedPlaying); - const remainingMs = Math.max(0, totalMs - elapsedMs); - - return elapsedMs / totalMs >= Player.TRACK_MOSTLY_FINISHED_RATIO || remainingMs <= Player.TRACK_MOSTLY_FINISHED_FLOOR_MS; - } - - /** @private Stop the audio bridge if currently playing. */ - _bridgeStop() { - if (this._audioBridge?.playing) { - this._audioBridge.stop(); - } - } - -/** @async Join a voice channel via LiveKit. Sets up voice connection, event listeners, and resumes playback if queue has tracks. @param {string} channelId - The voice channel ID to join. @returns {Promise} @throws {Error} If the channel is not found, VoiceManager is unavailable, or connection fails. */ - async join(channelId) { - if (this._destroyed) return; - - if (this._isJoining) { - logger.player(`[Player] Busy joining. Ignoring: ${channelId}`); - return; - } - if (this._voiceConn && this._channelId === channelId) { - logger.player(`[Player] Already in channel: ${channelId}`); - return; - } - - if (this._voiceConn) { - logger.player("[Player] Cleaning up existing voice connection before join"); - this._bridgeStop(); - try { await this._voiceConn.disconnect(); } catch(e) { logger.warn("[Player] Existing voiceConn disconnect error:", e?.message); } - this._voiceConn = null; - this.connection = null; - await Utils.sleep(500); - } - - this._isJoining = true; - try { - const channel = this.client?.channels?.get?.(channelId); - if (!channel) throw new Error(`Channel not found: ${channelId}`); - - if (this._lavalink) { - logger.player(`[Player] Waiting for Lavalink node...`); - await this._lavalink.waitForNode({ timeoutMs: 15_000 }); - } - - this._channelId = channelId; - this._guildId = cleanId(channel.guildId); - this._lastConnectedAt = Date.now(); - this.leaving = false; - - logger.player(`[Player] Joining channel ${channelId} via vm.join() (LiveKit)...`); - const vm = getVoiceManager(this.client); - if (!vm) { - throw new Error("VoiceManager not available — call getVoiceManager(client) before login"); - } - - let voiceConn; - try { - voiceConn = await vm.join(channel); - } catch (e) { - throw new Error(`vm.join() failed for channel ${channelId}: ${e.message}`); - } - - if (!voiceConn) { - throw new Error(`vm.join() returned null for channel ${channelId}`); - } - - this._voiceConn = voiceConn; - this.connection = voiceConn; - - if (typeof voiceConn.isConnected === "function" && !voiceConn.isConnected()) { - logger.player("[Player] Waiting for LiveKit room to connect..."); - await new Promise((resolve, reject) => { - const timeout = setTimeout(() => reject(new Error("LiveKit connection timeout (15s)")), 15_000); - const check = () => { - try { - if (voiceConn.isConnected()) { clearTimeout(timeout); return resolve(); } - if (voiceConn.connectionState === 0) { clearTimeout(timeout); return resolve(); } - } catch (_) { clearTimeout(timeout); return resolve(); } - setTimeout(check, 200); - }; - check(); - }); - await Utils.sleep(500); - } - - logger.player(`[Player] LiveKit voice connected (guild: ${this._guildId}, channel: ${channelId})` + - ` isConnected=${voiceConn.isConnected ? voiceConn.isConnected() : 'unknown'}`); - - try { - vm.updateVoiceState(channelId, { self_deaf: true, self_mute: false }); - } catch (e) { - logger.warn("[Player] Self-deafen failed:", e.message); - } - - if (typeof voiceConn.on === "function") { - voiceConn.on("serverLeave", () => { - if (this.leaving || this._destroyed) return; - logger.player(`[Player] serverLeave received — Fluxer/LiveKit terminated session`); - this._voiceConn = null; - this.connection = null; - this._paused = true; - this._stopInactivityTimer(); - - const mode = this._get247Mode(); - const cId = cleanId(this._channelId ?? this._home247Channel ?? ""); - const gId = cleanId(this._guildId ?? ""); - - if (mode === "on") { - logger.player("[Player] serverLeave in 24/7 mode — scheduling rejoin"); - this.emit("autoleave"); - if (cId && gId) this._schedule247Rejoin(cId, gId, mode); - } else { - logger.player("[Player] Unexpected serverLeave"); - this.emit("autoleave"); - } - }); - - voiceConn.on("disconnect", () => { - if (this.leaving || this._destroyed) return; - logger.player(`[Player] Voice connection disconnected`); - }); - } - - this._restoreVolume(); - this.emit("roomfetched"); - logger.player(`[Player] Voice connected to ${channel.name || channelId}`); - - if (!this.queue.isEmpty() && !this.queue.getCurrent()) { - this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); - } else if (this.queue.isEmpty()) { - this._pendingInactivityCheck = true; - setTimeout(() => { - if (!this._pendingInactivityCheck) return; - this._pendingInactivityCheck = false; - if (this.queue.isEmpty() && !this.queue.getCurrent()) { - this._startInactivityTimer(); - } - }, 3000); - } - - } catch (e) { - const causeStr = e.cause ? ` (Cause: ${e.cause})` : ""; - logger.error("[Player] Join failed:", e.message, causeStr); - - if (this._voiceConn) { - try { await this._voiceConn.disconnect(); } catch(err) { logger.warn("[Player] voiceConn disconnect on join failure:", err?.message); } - this._voiceConn = null; - this.connection = null; - } - throw e; - } finally { - this._isJoining = false; - } - } - -/** @async Leave the current voice channel. Stops playback, resets state, and cleans up the voice connection. @returns {Promise} True if leave was successful, false otherwise. */ - async leave() { - if (!this._voiceConn && !this.connection) return false; - try { - this.leaving = true; - this._stopInactivityTimer(); - this._clearTrackEndTimer(); - this._activeTrackOpt = null; - - const channelId = this._channelId; - - this._bridgeStop(); - - try { - const vm = getVoiceManager(this.client); - if (channelId) { - vm.leaveChannel(channelId); - logger.player("[Player] Left channel " + channelId + " via vm.leaveChannel()"); - } - } catch(e) { logger.warn("[Player] Gateway leave error:", e?.message); } - - if (this._voiceConn) { - try { await this._voiceConn.disconnect(); } catch(e) { logger.warn("[Player] voiceConn disconnect error:", e?.message); } - } - - if (this._audioBridge) { - this._audioBridge.stop(); - } - - this.queue.reset(); - this._voiceConn = null; - this.lavalinkPlayer = null; - this.connection = null; - this._paused = false; - this._pausedAt = null; - this._playingNext = false; - this._autoplay = false; - if (this._autoplayHandler) { - this.removeListener("queueEnd", this._autoplayHandler); - this._autoplayHandler = null; - } - } catch (e) { - logger.error("[Player] leave error:", e.message); - this.leaving = false; - return false; - } - this.leaving = false; - this.emit("leave"); - return true; - } - - /** Fully destroy this player instance: clean up timers, listeners, connections, and resources. */ - destroy() { - if (this._destroyed) return; - this._destroyed = true; - - this._clearTrackEndTimer(); - this._activeTrackOpt = null; - - try { - if (this._lavalink) { - if (this._onLavalinkPlayerDisconnect) { - try { this._lavalink.off("playerDisconnected", this._onLavalinkPlayerDisconnect); } catch(e) { /* best effort */ } - this._onLavalinkPlayerDisconnect = null; - } - } - this.leaving = true; - this._stopInactivityTimer(); - if (this._rejoinTimer) { clearTimeout(this._rejoinTimer); this._rejoinTimer = null; } - this._autoplay = false; - if (this._autoplayHandler) { - this.removeListener("queueEnd", this._autoplayHandler); - this._autoplayHandler = null; - } - this.searches.clear(); - - this._bridgeStop(); - if (this._audioBridge) { - this._audioBridge.destroy(); - this._audioBridge = null; - } - if (this._voiceConn) { - try { this._voiceConn.disconnect(); } catch(e) { logger.warn("[Player] voiceConn disconnect in destroy:", e?.message); } - this._voiceConn = null; - } - this.lavalinkPlayer = null; - this.connection = null; - - if (this._channelId) { - try { - const vm = getVoiceManager(this.client); - vm.leaveChannel(this._channelId); - } catch(e) { /* best effort */ } - } - } catch (e) { - logger.error("[Player] destroy error:", e.message); - } - } - - /** @type {boolean} Whether the player is currently paused. */ - get paused() { return this._paused; } - - /** Pause current playback. @returns {string} Status message. */ - pause() { - if (!this._voiceConn || !this.queue.getCurrent()) - return ":negative_squared_cross_mark: There's nothing playing at the moment!"; - if (this._paused) - return ":negative_squared_cross_mark: Already paused!"; - - this._bridgeStop(); - this._paused = true; - this._pausedAt = Date.now(); - this._pauseTrackEndTimer(); - this.emit("playback", false); - this._stopInactivityTimer(); - return ":pause_button: Paused"; - } - - /** Resume paused playback. @returns {string} Status message. */ - resume() { - if (!this._voiceConn || !this.queue.getCurrent()) - return ":negative_squared_cross_mark: There's nothing playing at the moment!"; - if (!this._paused) - return ":negative_squared_cross_mark: Not paused!"; - - if (this._pausedAt) { - this.startedPlaying += (Date.now() - this._pausedAt); - } - - this._paused = false; - this._pausedAt = null; - this._resumeTrackEndTimer(); - this.emit("playback", true); - this._stopInactivityTimer(); - - const current = this.queue.getCurrent(); - if (current?.url) { - const elapsedMs = Date.now() - this.startedPlaying; - this._playTrackViaBridge(current, { seekSeconds: elapsedMs / 1000 }).catch(e => - logger.error("[Player] Resume playback error:", e.message) - ); - } - return ":arrow_forward: Resumed"; - } - - /** Skip the current track and advance to the next. Emits "trackSkip" with the skipped - * track so autoplay (when enabled) can replenish the queue with a new song. @returns {string} Status message. */ - skip() { - if (!this._voiceConn || !this.queue.getCurrent()) - return ":negative_squared_cross_mark: There's nothing playing at the moment!"; - this._lastPlayedTrack = this.queue.getCurrent(); - this._skipping = true; - this._radioAnnounced = false; - this._activeTrackOpt = null; - this._clearTrackEndTimer(); - this.queue.current = null; - - this._bridgeStop(); - - this.emit("trackSkip", this._lastPlayedTrack); - - if (this.queue.isEmpty() && !this._wasRadio && !this._queueEndedSent) { - this._queueEndedSent = true; - this.emit("queueEnd"); - if (!this._autoplay) { - const prefix = this._getPrefix?.(this._guildId) ?? "%"; - this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true }); - } - } - - this._playingNext = false; - if (!this.queue.isEmpty() && !this.leaving) { - this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); - } else { - this.emit("stopplay"); - if (!this._is247Enabled()) { - this._startInactivityTimer(); - } - } - - this._skipping = false; - return ":track_next: Skipped"; - } - - /** Skip to a specific position in the queue. @param {number} position - 1-based queue position. @returns {string} Status message. */ - skipTo(position) { - if (!this._voiceConn || !this.queue.getCurrent()) - return ":negative_squared_cross_mark: There's nothing playing at the moment!"; - const idx = position - 1; - if (idx < 0 || idx >= this.queue.size()) - return `:negative_squared_cross_mark: Position ${position} out of range (queue has ${this.queue.size()} tracks).`; - this._lastPlayedTrack = this.queue.getCurrent(); - this.queue.data.splice(0, idx); - this.queue.current = null; - this._skipping = true; - - this._bridgeStop(); - - this.emit("trackSkip", this._lastPlayedTrack); - - if (this.queue.isEmpty() && !this._wasRadio && !this._queueEndedSent) { - this._queueEndedSent = true; - this.emit("queueEnd"); - if (!this._autoplay) { - const prefix = this._getPrefix?.(this._guildId) ?? "%"; - this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true }); - } - } - - this._playingNext = false; - if (!this.queue.isEmpty() && !this.leaving) { - this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); - } else { - this.emit("stopplay"); - if (!this._is247Enabled()) { - this._startInactivityTimer(); - } - } - - this._skipping = false; - return `:track_next: Skipped to position ${position}`; - } - - /** Set the playback volume. @param {number} v - Volume as a decimal (0–2, where 1 = 100%). @returns {string} Status message. */ - setVolume(v) { - this.preferredVolume = Utils.clamp(v, 0, 2); - this.emit("volume", this.preferredVolume); - if (this._voiceConn) { - this._voiceConn.setVolume(this.preferredVolume * 100); - } - if (!this._voiceConn) - return `Volume set to \`${Math.round(this.preferredVolume * 100)}%\` — will apply when connected.`; - return `Volume changed to \`${Math.round(this.preferredVolume * 100)}%\`.`; - } - -/** @async Seek to a specific position in the currently playing track. @param {number} ms - Target position in milliseconds. @returns {Promise} True if seek succeeded, false otherwise. */ - async seekToPosition(ms) { - if (!this._voiceConn || !this.queue.getCurrent()) return false; - - this._seeking = true; - - try { - this._bridgeStop(); - const current = this.queue.getCurrent(); - if (current?.url) { - this.startedPlaying = Date.now() - ms; - await this._playTrackViaBridge(current, { seekSeconds: ms / 1000 }); - } - logger.player(`[Player] Seeked to ${ms}ms — adjusted startedPlaying`); - - this._recalcTrackEndTimer(); - - return true; - } catch (e) { - this._seeking = false; - logger.error("[Player] Seek failed:", e?.message); - return false; - } finally { - this._seeking = false; - } - } - -/** @async Apply an audio filter to the current playback. Stores filter metadata for dashboard tracking. @param {object} filterPayload - The filter configuration payload. @param {object|null} [filterMeta=null] - Human-readable filter metadata (name, etc.). @returns {Promise<{ok: boolean, reason?: string, pending?: boolean}>} Result indicating success or failure reason. */ - async applyFilter(filterPayload, filterMeta = null) { - if (!this._guildId) { - return { ok: false, reason: "Player not bound to a guild." }; - } - - const current = this.queue.getCurrent(); - - this.activeFilter = filterMeta ?? null; - this.activeFilterPayload = filterMeta ? filterPayload : null; - this.emit("filter", this.activeFilter); - - if (!current?.encoded || !this._voiceConn) { - return { ok: true, pending: true }; - } - - try { - return { ok: true }; - } catch (e) { - const errMsg = e.message ?? ""; - return { ok: false, reason: errMsg }; - } - } - - /** Clear any active audio filter. */ - clearFilter() { - this.activeFilter = null; - this.activeFilterPayload = null; - this.emit("filter", null); - logger.warn("[Player] clearFilter: filters not supported in LiveKit mode"); - } - - /** @returns {boolean} Whether the queue is empty. */ - isEmpty() { return this.queue.isEmpty(); } - - /** Add a track to the queue with optional top-insert. @param {object} d - Track data. @param {boolean} [t=false] - Insert at the top of the queue. */ - addToQueue(d, t) { - if (this.queue.data.length >= this._maxQueueSize) { - logger.warn(`[Player] Queue size cap reached (${this._maxQueueSize}) — dropping oldest track`); - this.queue.data.shift(); - } - this.queue.add(d, t); - this.emit("update", "queue"); - this._stopInactivityTimer(); - } - - /** Clear the queue and start inactivity timer if nothing is playing. */ - clear() { - this.queue.clear(); - this.emit("update", "queue"); - if (!this.queue.getCurrent()) { - this._startInactivityTimer(); - } - } - - /** Add multiple tracks to the queue. @param {Array} t - Track data array. @param {boolean} [top=false] - Insert at the top. @returns {number} Number of tracks added. */ - addManyToQueue(t, top = false) { - if (!Array.isArray(t)) return 0; - const overflow = (this.queue.data.length + t.length) - this._maxQueueSize; - if (overflow > 0) { - logger.warn(`[Player] Queue size cap (${this._maxQueueSize}) — dropping ${overflow} oldest tracks`); - this.queue.data.splice(0, overflow); - } - const added = this.queue.addMany(t, top); - this.emit("update", "queue"); - this._stopInactivityTimer(); - return added; - } - - /** Shuffle the queue. @returns {string} Status message. */ - shuffle() { - if (this.isEmpty()) return "There is nothing to shuffle in the queue."; - this.queue.shuffle(); - this.emit("update", "queue"); - return ":twisted_rightwards_arrows: Shuffled queue"; - } - - /** Move a track from one position to another (1-based indices). @param {number} from - Source position (1-based). @param {number} to - Destination position (1-based). @returns {string} Result message. */ - move(from, to) { - if (this.queue.size() === 0) return "The queue is empty."; - return this.queue.move(from - 1, to - 1); - } - - /** Toggle a loop mode. @param {"song"|"queue"} choice @returns {string} */ - loop(choice) { - if (!["song", "queue"].includes(choice)) - return `'${choice}' is not valid. Use \`song\` or \`queue\``; - const state = this.queue.toggleLoop(choice); - const name = choice.charAt(0).toUpperCase() + choice.slice(1); - return state - ? `:repeat: ${name} loop activated` - : `:arrow_right: ${name} loop disabled`; - } - - /** Remove a track from the queue by index. @param {number} index - 0-based. @returns {string} @throws {Error} If index is empty. */ - remove(index) { - if (index === undefined || index === null) throw new Error("Index can't be empty"); - const oldSize = this.queue.size(); - const msg = this.queue.remove(index); - if (oldSize !== this.queue.size()) this.emit("update", "queue"); - - if (this.isEmpty() && !this.queue.getCurrent()) { - this._startInactivityTimer(); - } - return msg; - } - - /** @private @param {number} [length=15] @returns {string} */ - _createProgressBar(length = 15) { - const current = this.queue.getCurrent(); - if (!current?.duration || !this.startedPlaying) { - const total = this._getTrackDurationMs(current); - if (total > 0) { - return `${Utils.progressBar(0, total, length)} \`0:00 / ${Utils.prettifyMS(total)}\``; - } - return Utils.progressBar(0, 1, length); - } - - const totalMs = this._getTrackDurationMs(current); - let elapsed = Date.now() - this.startedPlaying; - if (this._paused && this._pausedAt) { - elapsed = this._pausedAt - this.startedPlaying; - } - - if (totalMs > 0 && elapsed > totalMs) elapsed = totalMs; - elapsed = Math.max(0, elapsed); - - const bar = Utils.progressBar(elapsed, totalMs, length); - const timeNow = Utils.prettifyMS(elapsed); - const total = Utils.prettifyMS(totalMs); - return `${bar} \`${timeNow} / ${total}\``; - } - - /** @returns {string} Formatted name of the currently playing track. */ - getCurrent() { - const c = this.queue.getCurrent(); - if (!c) return "There's nothing playing at the moment."; - return this.getVideoName(c); - } - - /** Format a track object into a display name. @param {object} vid @param {boolean} [code=false] @returns {string} */ - getVideoName(vid, code = false) { - if (!vid) return "Unknown"; - if (vid.type === "radio") { - return code - ? `[Radio]: ${vid.title} - ${vid.author?.url || ""}` - : `[Radio] [${vid.title} by ${vid.author?.name || "Unknown"}](${vid.author?.url || ""})`; - } - if (vid.type === "external" || vid.type === "stream") { - return code - ? `${vid.title} - ${vid.url}` - : `[${vid.title}](${vid.url})`; - } - const elapsed = this.getCurrentElapsedDuration(); - const total = this.getDuration(vid.duration); - const link = vid.spotifyUrl || vid.url || ""; - return code - ? `${vid.title} (${elapsed}/${total})${link ? " - " + link : ""}` - : `[${vid.title} (${elapsed}/${total})]${link ? "(" + link + ")" : ""}`; - } - - /** @returns {string} Human-readable total remaining time for all queued tracks. */ - getQueueRemainingTime() { - let totalMs = 0; - const current = this.queue.getCurrent(); - if (current?.duration && this.startedPlaying) { - const totalMsCurrent = this._getTrackDurationMs(current); - let elapsed = Date.now() - this.startedPlaying; - if (this._paused && this._pausedAt) { - elapsed = this._pausedAt - this.startedPlaying; - } - totalMs += Math.max(0, totalMsCurrent - elapsed); - } - for (const track of this.queue.data) { - totalMs += this._getTrackDurationMs(track); - } - return Utils.prettifyMS(totalMs); - } - - /** @returns {string} Elapsed time of the current track. */ - getCurrentElapsedDuration() { - if (!this.startedPlaying) return "0:00"; - const current = this.queue.getCurrent(); - const totalMs = this._getTrackDurationMs(current); - - let elapsed = Date.now() - this.startedPlaying; - if (this._paused && this._pausedAt) { - elapsed = this._pausedAt - this.startedPlaying; - } - - if (totalMs > 0 && elapsed > totalMs) elapsed = totalMs; - return Utils.prettifyMS(Math.max(0, elapsed)); - } - - /** Generate a text-based queue listing. @param {number} [page=1] @param {number} [pageSize=10] @returns {string} */ - list(page = 1, pageSize = 10) { - const current = this.queue.getCurrent(); - const total = this.queue.size(); - let text = ""; - if (current) { - const remaining = this.getQueueRemainingTime(); - text += `🎧 **Queue**\n`; - text += `**${total} tracks** • ⏱️ ${remaining}\n`; - text += `${this._createProgressBar()}\n\n`; - text += `🎵 **Now Playing**\n`; - text += `${this.getVideoName(current)}\n\n`; - } - if (total === 0) { if (!current) text += "--- Empty ---"; return text; } - const { items, page: pg, totalPages, start } = this.queue.getPage(page, pageSize); - items.forEach((vid, i) => { - const index = String(start + i + 1).padStart(2, " "); - const name = this.getVideoName({ ...vid, title: Utils.truncate(vid.title, 60) }); - text += `\`${index}.\` ${name}\n`; - }); - text += `\nPage ${pg}/${totalPages} • Loop: ${this.queue.loop ? "🟢" : "🔴"}`; - return text; - } - -/** @async Build a now-playing info object for the current track, including progress bar, volume, and loop states. @returns {Promise} Object with msg (description string) and optional image URL. */ - async nowPlaying() { - const current = this.queue.getCurrent(); - if (!current) return { msg: "There's nothing playing at the moment." }; - - const loopqueue = this.queue.loop ? "🔄" : "⏹️"; - const songloop = this.queue.songLoop ? "🔂" : "⏹️"; - const vol = `${Math.round((this.preferredVolume || 1) * 100)}%`; - const autoplay = this._autoplay ? "🔁" : "⏹️"; - - const vcLine = this._channelId ? `🔊 <#${this._channelId}>\n` : ""; - - if (current.type === "radio") { - try { - const data = await meta(current.url); - return { - msg: `${vcLine}📻 **[${current.title}](${current.author?.url || current.url})**\n${current.description || ""}\n\n🎵 Now playing: ${data?.title || "Unknown"}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`, - image: current.thumbnail - }; - } catch (e) { - logger.warn("[Player] Error:", e?.message); - return { - msg: `${vcLine}📻 **[${current.title}](${current.author?.url || current.url})**\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`, - image: current.thumbnail - }; - } - } - - if (current.type === "external" || current.type === "stream") { - const totalMs = this._getTrackDurationMs(current); - let progressLine = ""; - - if (totalMs > 0) { - progressLine = `\n${this._createProgressBar(20)}`; - } - return { - msg: `${vcLine}🎵 **[${current.title}](${current.url})** by ${current.artist || "Unknown"}${progressLine}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`, - image: current.thumbnail - }; - } - - const progressBar = this._createProgressBar(20); - let trackOptLine = ""; - if (this._activeTrackOpt) { - const optStart = Utils.prettifyMS(this._activeTrackOpt.startMs); - const optEnd = this._activeTrackOpt.endMs > 0 ? Utils.prettifyMS(this._activeTrackOpt.endMs) : "end"; - trackOptLine = `\n✂️ Custom: ${optStart} → ${optEnd}`; - } - return { - msg: `${vcLine}🎵 **[${current.title}](${current.spotifyUrl || current.url})**\n${progressBar}${trackOptLine}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`, - image: current.thumbnail - }; - } - -/** @async Get the thumbnail of the currently playing track. @returns {Promise<{msg: string, image: string|null}>} Object with description message and image URL or null. */ - async getThumbnail() { - const current = this.queue.getCurrent(); - if (!current) return { msg: "There's nothing playing at the moment.", image: null }; - if (!current.thumbnail) return { msg: "No thumbnail available.", image: null }; - return { msg: `Thumbnail of [${current.title}](${current.url}):`, image: current.thumbnail }; - } - - /** Format a track duration from various shapes. @param {*} duration @returns {string} */ - getDuration(duration) { - if (typeof duration === "object" && duration?.timestamp) return duration.timestamp; - if (typeof duration === "object" && duration?.seconds != null) return Utils.formatSeconds(duration.seconds); - if (typeof duration === "string" && duration.startsWith("PT")) return Utils.prettifyMS(Utils.parseISODuration(duration)); - return Utils.prettifyMS(duration); - } - - /** @returns {string} Formatted duration of the currently playing track. */ - getCurrentDuration() { - const current = this.queue.getCurrent(); - if (!current?.duration) return "?:??"; - return this.getDuration(current.duration); - } - - /** @private Translate a locale key. @param {string} key @param {object} [replacements={}] @returns {string} */ - _t(key, replacements = {}) { - if (!this.locale) return key; - return this.locale.translate(this._guildId, key, replacements); - } - - /** Emit a now-playing announcement for the given track. @param {object} s */ - announceSong(s) { - if (!s) return; - - if (s.type === "radio") { - this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses.radio.nowPlaying", { - title: Utils.escapeMarkdown(s.title), - author: s.author?.name || "Unknown", - url: s.author?.url || "", - channel: this._channelId || "", - }))] }); - return; - } - const author = s.artists - ? s.artists.map(a => a.url ? `[${a.name}](${a.url})` : a.name).join(" & ") - : s.author?.url - ? `[${s.author.name}](${s.author.url})` - : s.author?.name || null; - - if (!author && (s.type === "external" || s.type === "stream")) { - const desc = "🎵 Now playing [" + Utils.escapeMarkdown(s.title) + "](" + (s.url || "") + ") in <#" + (this._channelId || "") + ">"; - this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] }); - return; - } - - this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses.play.nowPlaying", { - title: Utils.escapeMarkdown(s.title), - url: s.spotifyUrl || s.url, - author: author || "Unknown", - channel: this._channelId || "", - }))] }); - } - - - /** @async Resolve a free-text query or URL to track data via Lavalink, for internal consumers (autoplay, Last.fm). - * URL queries are loaded directly (like play()) instead of being prefixed with a search - * source, so playlist/mix URLs resolve to their full track lists. @param {{query: string, provider?: string, trackMeta?: object}} opts - Query, optional provider key, optional track metadata to attach. @returns {Promise<{type: "video"|"list"|"error", data?: object}|null>} Resolved track shape, or null on failure. */ - async generalQuery({ query, provider = "yt", trackMeta = null }) { - try { - if (!this._lavalink) return { type: "error", data: "Audio node not ready." }; - await this._lavalink.waitForNode({ timeoutMs: 15_000 }); - const isUrl = typeof query === "string" && Utils.isValidUrl(query); - const result = isUrl - ? await this._lavalink.search(query) - : await this._lavalink.search(query, { source: this._getSource(provider) }); - const tracks = (result?.tracks ?? []).map(t => this._lcTrackToVideo(t, trackMeta)).filter(Boolean); - if (!tracks.length) return null; - return tracks.length === 1 ? { type: "video", data: tracks[0] } : { type: "list", data: tracks }; - } catch (err) { - logger.warn("[Player] generalQuery failed:", err?.message); - return { type: "error", data: err?.message ?? String(err) }; - } - } - -/** @async Search for tracks via Lavalink and store results for interactive selection. @param {string} query - The search query string. @param {string} id - A unique key to identify this search session (e.g. message ID). @param {string} [provider="ytm"] - The search provider key. @returns {Promise<{m: string, count: number}>} Object with formatted result list message and track count. */ - async fetchResults(query, id, provider = "ytm") { - try { - if (!this._lavalink) return { m: "Audio node not ready.", count: 0 }; - - await this._lavalink.waitForNode({ timeoutMs: 15_000 }); - - const source = this._getSource(provider); - const result = await this._lavalink.search(query, { source }); - const lcTracks = result?.tracks ?? []; - - const results = lcTracks.slice(0, this.resultLimit).map(t => this._lcTrackToVideo(t)).filter(Boolean); - - let list = "Search results using **" + (PROVIDER_NAMES[provider] || "YouTube Music") + "**:\n\n"; - results.forEach((v, i) => { - const url = v.url || ""; - const title = v.title || Utils.formatTrackInfo(v, false); - const dur = v.duration ? this.getDuration(v.duration) : "?:??"; - list += (i + 1) + ". [" + title + "](" + url + ") - " + dur + "\n"; - }); - list += "\nSend the number of the result. Example: `2`\nSend 'x' to cancel."; - - if (this.searches.size >= this._searchMaxSize) { - const oldestKey = this.searches.keys().next().value; - if (oldestKey !== undefined) this.searches.delete(oldestKey); - } - this.searches.set(id, results); - - return { m: list, count: results.length }; - } catch (err) { - return { m: "Error searching: " + err.message, count: 0 }; - } - } - - /** Select a search result and add it to the queue. @param {string} id @param {number} [result=0] @param {boolean} [next=false] @returns {object|null} */ - playResult(id, result = 0, next = false) { - if (!this.searches.has(id)) return null; - const searchResults = this.searches.get(id); - if (!searchResults || !searchResults[result]) return null; - - const res = searchResults[result]; - this.addToQueue(res, next); - - this.searches.delete(id); - - if (!this.queue.getCurrent()) { - this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); - } - return res; - } - - /** Search and add a track to the top of the queue. @returns {EventEmitter} */ - playFirst(query, provider, trackMeta) { return this.play(query, true, provider, trackMeta); } - - /** @private Convert a Lavalink track to internal format. @param {object} track @param {object|null} [trackMeta=null] @returns {object|null} */ - _lcTrackToVideo(track, trackMeta = null) { - if (!track || typeof track !== "object") return null; - const info = track.info ?? track ?? {}; - - let ms = info.length ?? track.length ?? info.durationMs ?? 0; - if (ms === 0 && info.duration != null) { - if (typeof info.duration === "number") { - ms = info.duration; - } else if (typeof info.duration === "object" && info.duration.seconds != null) { - ms = info.duration.seconds * 1000; - } - } - - let trackUri = info.uri ?? ("https://www.youtube.com/watch?v=" + (info.identifier || "")); - if (typeof trackUri === 'string' && trackUri.includes('music.youtube.com')) { - trackUri = trackUri.replace('music.youtube.com', 'www.youtube.com'); - } - const video = { - videoId: info.identifier ?? "", - encoded: track.encoded ?? info.encoded ?? "", - sourceName: info.sourceName ?? "unknown", - title: Utils.cleanTitle(info.title ?? "Unknown"), - url: trackUri, - thumbnail: info.artworkUrl ?? null, - spotifyUrl: null, - _durationMs: ms, - duration: { - timestamp: Utils.prettifyMS(ms), - seconds: Math.floor(ms / 1000), - }, - author: { - name: info.author ?? "Unknown", - url: info.uri ?? null, - }, - artists: null, - }; - if (trackMeta) { - video.artist = trackMeta.artist ?? null; - video.requestedArtist = trackMeta.artist ?? null; - video.requestedTitle = trackMeta.name ?? trackMeta.title ?? null; - video.lastfm = { - source: trackMeta.source ?? "lastfm", - artist: trackMeta.artist ?? null, - name: trackMeta.name ?? trackMeta.title ?? null, - url: trackMeta.url ?? "", - }; - } - return video; - } - - /** @private Resolve a provider key to a Lavalink search prefix. @param {string} provider @returns {string} */ - _getSource(provider) { - return PROVIDERS[provider]?.prefix ?? (provider + "search"); - } - - /** Search for a track and add it to the queue. @param {string} query @param {boolean} [top=false] @param {string} [provider] @param {object} [trackMeta=null] @returns {EventEmitter} */ - play(query, top = false, provider, trackMeta = null) { - const events = new EventEmitter(); - const source = this._getSource(provider || "ytm"); - const isUrl = Utils.isValidUrl(query); - - (async () => { - try { - if (!this._lavalink) { - events.emit("message", "Audio node not ready yet."); - return; - } - - await this._lavalink.waitForNode({ timeoutMs: 15_000 }); - - events.emit("message", "Searching..."); - - const ytId = Utils.extractYouTubeId(query); - const canonicalYtUrl = ytId ? Utils.normalizeYouTubeUrl(query) : null; - const searchQuery = (isUrl && canonicalYtUrl) ? canonicalYtUrl : query; - - let result; - try { - if (isUrl) { - result = await this._lavalink.search(searchQuery); - } else { - result = await this._lavalink.search(searchQuery, { source }); - } - } catch (searchErr) { - logger.warn("[Player] URL/primary search failed:", searchErr?.message); - result = null; - if (!isUrl) throw searchErr; - } - let lcTracks = result?.tracks ?? []; - - if (isUrl && lcTracks.length === 0 && ytId) { - const directBlocked = "YouTube blocked direct loading for this video (`Sign in to confirm you're not a bot`) — trying search fallback..."; - - if (searchQuery !== query) { - events.emit("message", "Retrying with original URL..."); - try { - const retry = await this._lavalink.search(query); - lcTracks = retry?.tracks ?? []; - } catch (_) { lcTracks = []; } - } - - if (lcTracks.length === 0) { - events.emit("message", directBlocked); - const title = await Utils.fetchYouTubeOEmbedTitle(ytId); - if (title) { - logger.player(`[Player] oEmbed fallback: resolved title "${title}" for ${ytId}`); - for (const fallbackSource of ["ytsearch", "ytmsearch"]) { - try { - const fb = await this._lavalink.search(title, { source: fallbackSource }); - if (fb?.tracks?.length > 0) { - lcTracks = fb.tracks; - break; - } - } catch (_) { /* try next source */ } - } - } else { - logger.warn("[Player] oEmbed fallback: could not resolve title for " + ytId); - } - } - } - - if (lcTracks.length === 0) { - if (!isUrl && source !== "ytmsearch") { - events.emit("message", "No results from primary source, trying YouTube Music..."); - const fallback = await this._lavalink.search(searchQuery, { source: "ytmsearch" }); - if (fallback?.tracks?.length > 0) { - const video = this._lcTrackToVideo(fallback.tracks[0], trackMeta); - if (video) { - this.addToQueue(video, top); - events.emit("message", "Successfully added [" + video.title + "](" + video.url + ") to the queue."); - if (!this.queue.getCurrent()) { - this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); - } - return; - } - } - } - events.emit("message", "**No results found for '" + query + "'.**"); - return; - } - - const firstTrack = lcTracks[0]; - if (isUrl && lcTracks.length > 1) { - const videos = lcTracks.map(t => this._lcTrackToVideo(t, trackMeta)).filter(Boolean); - this.addManyToQueue(videos, top); - events.emit("message", "Successfully added **" + videos.length + "** songs to the queue."); - } else { - const video = this._lcTrackToVideo(firstTrack, trackMeta); - if (video) { - this.addToQueue(video, top); - events.emit("message", "Successfully added [" + video.title + "](" + video.url + ") to the queue."); - } else { - events.emit("message", "**Failed to parse track data.**"); - return; - } - } - - if (!this.queue.getCurrent()) { - this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); - } - } catch (err) { - logger.error("[Player] play() search error:", err?.message); - events.emit("message", err?.message || "An error occurred while loading the track."); - } - })(); - - return events; - } - -/** @async Search for tracks via Lavalink and return raw track results. @param {string} query - The search query string. @param {string} [provider="ytm"] - The search provider key. @returns {Promise>} Array of raw Lavalink track objects, or empty array on error. */ - async search(query, provider = 'ytm') { - if (!this._lavalink) return []; - try { - const source = this._getSource(provider); - const result = await this._lavalink.search(query, { source }); - return result.tracks || []; - } catch (e) { - logger.error(`[Player] lavalink search error:`, e?.message); - return []; - } - } - - /** @private Build a radio-type track object. @param {object} radio @returns {object} */ - _buildRadioTrack(radio) { - return { - type: "radio", - title: radio.detailedName || radio.title || "Unknown Radio", - description: Utils.truncate(radio.description || "", 200), - url: radio.url, - author: { - name: radio.author?.name || "Unknown", - url: radio.author?.url || radio.url, - }, - thumbnail: radio.thumbnail ?? null, - }; - } - - /** Add a radio stream to the queue. @param {object} radio @param {boolean} [top=false] */ - playRadio(radio, top = false) { - if (!radio?.url) { logger.error("[Player] Invalid radio data"); return; } - this.addToQueue(this._buildRadioTrack(radio), top); - if (!this.queue.getCurrent()) this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); - } - -/** @async Switch to a different radio stream, replacing any current radio tracks. @param {object} radio - Radio object with url, title, author, and thumbnail. @returns {Promise} */ - async switchRadio(radio) { - if (!radio?.url) { logger.error("[Player] switchRadio: invalid radio data"); return; } - - const newTrack = this._buildRadioTrack(radio); - this.queue.data = this.queue.data.filter(t => t.type !== "radio"); - - if (!this.queue.getCurrent()) { - this.queue.add(newTrack); - this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); - return; - } - - this.queue.data.unshift(newTrack); - this._skipping = true; - this._radioAnnounced = false; - this.queue.current = null; - this._bridgeStop(); - this._playingNext = false; - this._skipping = false; - if (!this.leaving) this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); - } - - /** @private Build a direct-URL track object. @param {string} url @param {string} [title] @param {string} [artist] @param {string} [trackType="external"] @returns {object} */ - _buildExternalTrack(url, title = null, artist = null, trackType = "external") { - const displayTitle = title || this._extractFilenameFromUrl(url); - return { - type: trackType, - title: displayTitle, - url: url, - artist: artist || null, - thumbnail: null, - }; - } - - /** @private Extract a display filename from a URL. @param {string} url @returns {string} */ - _extractFilenameFromUrl(url) { - try { - const pathname = new URL(url).pathname; - const filename = pathname.split("/").pop(); - if (filename && filename.includes(".")) { - return decodeURIComponent(filename.replace(/\.[^.]+$/, "")) || "Stream"; - } - } catch (_) {} - return "External Stream"; - } - - /** - * Play a direct audio URL (MP3, OGG, AAC, stream, etc.) without Lavalink search. - * The bridge handles decoding via Lavalink if needed. No FFmpeg required. - * @param {string} url - Direct HTTP(S) audio URL. - * @param {string} [title] - Optional display title. - * @param {string} [artist] - Optional artist name. - * @param {boolean} [top=false] - Insert at top of queue. - * @param {string} [trackType="external"] - Track type: "external" (no pre-resolve) or "stream" (Lavalink pre-resolve). - * @returns {EventEmitter} Emitter that emits "message" events with status strings. - */ - playExternal(url, title = null, artist = null, top = false, trackType = "external") { - const events = new EventEmitter(); - - (async () => { - try { - const track = this._buildExternalTrack(url, title, artist, trackType); - this.addToQueue(track, top); - events.emit("message", "Added **[" + track.title + "](" + url + ")** to the queue."); - - if (!this.queue.getCurrent()) { - this.playNext().catch(e => { - logger.error("[Player] playExternal playNext error:", e.message); - events.emit("message", "Error playing stream: " + e.message); - }); - } - } catch (err) { - logger.error("[Player] playExternal error:", err?.message); - events.emit("message", "Error: " + (err?.message || "Failed to add external stream.")); - } - })(); - - return events; - } - - /** @private @async Advance to the next track. Guarded against overlapping runs: a - * generation counter ensures an older run's cleanup never clears the in-flight - * flag of a newer run (which previously allowed double-advances). */ - async playNext() { - if (this._playingNext) return; - this._playingNext = true; - const generation = (this._playNextGeneration = (this._playNextGeneration ?? 0) + 1); - try { await this._doPlayNext(); } - finally { if (generation === this._playNextGeneration) this._playingNext = false; } - } - - /** @private @async Core logic for advancing to the next track. */ - async _doPlayNext() { - this._bridgeStop(); - - const currentBeforeNext = this.queue.getCurrent(); - if (currentBeforeNext) this._lastPlayedTrack = currentBeforeNext; - const songData = this.queue.next(); - if (!songData) { - this.emit("stopplay"); - this.emit("queueEnd"); - - if (!this._is247Enabled()) { - this._startInactivityTimer(); - } else { - logger.voice247("[Player] 24/7 enabled, staying in channel"); - } - - if (!this._wasRadio && !this._queueEndedSent && !this._autoplay) { - this._queueEndedSent = true; - const prefix = this._getPrefix?.(this._guildId) ?? "%"; - this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true }); - } - this._wasRadio = false; - return; - } - - this._stopInactivityTimer(); - this._wasRadio = songData.type === "radio"; - - if (!this._voiceConn || this.leaving) return; - - if (this.preferredVolume !== 1 && this._voiceConn) { - try { this._voiceConn.setVolume(this.preferredVolume * 100); } catch(_) {} - } - - if (!this._voiceConn || this.leaving) return; - - this._activeTrackOpt = null; - this._clearTrackEndTimer(); - - let trackOptMatch = null; - try { - trackOptMatch = await this._lookupTrackOptions(songData); - } catch (e) { - logger.warn("[Player] TrackOptions lookup error:", e.message); - } - - if (trackOptMatch) { - this._activeTrackOpt = trackOptMatch; - } - - logger.player(`[Player:${this._guildId}] Playing: ${songData.title}`); - - this.startedPlaying = Date.now(); - this._paused = false; - this._pausedAt = null; - this._queueEndedSent = false; - this._consecutiveErrors = 0; - - if (songData.type !== "radio" || !this._radioAnnounced) { - this.announceSong(songData); - if (songData.type === "radio") this._radioAnnounced = true; - } - this.emit("startplay", songData); - - try { - const playUri = songData.url; - const seekSec = trackOptMatch?.startMs > 0 ? trackOptMatch.startMs / 1000 : 0; - - if (!playUri || !Utils.isValidUrl(playUri)) { - logger.warn(`[Player] No valid URL for track: ${songData.title} (url=${songData.url}), trying search...`); - try { - if (this._lavalink) { - const result = await this._lavalink.search(songData.title, { source: "ytmsearch" }); - const track = result?.tracks?.[0]; - if (track?.info?.uri) { - songData.url = track.info.uri; - if (track.encoded) songData.encoded = track.encoded; - await this._playTrackViaBridge(songData, { seekSeconds: seekSec }); - } else { - throw new Error("No tracks found for title search"); - } - } else { - throw new Error("No Lavalink for fallback search"); - } - } catch (searchErr) { - logger.error("[Player] Could not resolve track:", searchErr?.message); - this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.couldNotGetStream", { title: songData.title }))] }); - this.emit("stopplay"); - if (!this._is247Enabled()) { - this._startInactivityTimer(); - } - return; - } - } else { - await this._playTrackViaBridge(songData, { seekSeconds: seekSec }); - } - - - if (trackOptMatch && trackOptMatch.endMs > 0) { - const elapsedMs = Date.now() - this.startedPlaying; - const remainingMs = trackOptMatch.endMs - elapsedMs; - if (remainingMs > 0) { - const match = trackOptMatch; - this._trackEndTimer = setTimeout(() => this._onTrackEndTimeReached(match), remainingMs); - } - } - } catch (err) { - logger.error("[Player] Play error:", err.message); - if (!this._skipping && !this.leaving && !this._paused && songData.type !== "radio") { - this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.errorStreaming", { title: songData.title }))] }); - } - if (!this._skipping && !this.leaving) { - this._consecutiveErrors = (this._consecutiveErrors || 0) + 1; - if (this._consecutiveErrors <= 3) { - this._handleTrackEnd(); - } else { - logger.error(`[Player] ${this._consecutiveErrors} consecutive play errors — stopping auto-advance`); - this._consecutiveErrors = 0; - this.emit("stopplay"); - if (!this._is247Enabled()) { - this._startInactivityTimer(); - } - } - } - } - } - - /** @private @async Play a track through the FluxerAudioBridge. For radio/external tracks - * without an encoded payload, attempts Lavalink URL resolution first so MP3/AAC - * streams can use the loadstream pipeline instead of the limited direct-URL path. - * @param {object} songData @param {object} [options={}] @returns {Promise} */ - async _playTrackViaBridge(songData, options = {}) { - if (!this._voiceConn || !this._audioBridge) { - throw new Error("No voice connection or audio bridge available"); - } - if (!songData?.encoded && !songData?.url) { - throw new Error("No encoded track or URL for: " + (songData?.title ?? "unknown")); - } - - if (!songData.encoded && songData.url && songData.url.startsWith("http") && this._lavalink && songData.type !== "external") { - try { - const nlInfo = this._lavalink.getNodeLinkInfo?.(); - if (nlInfo) { - const protocol = nlInfo.secure ? "https" : "http"; - const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port; - const headers = { "Authorization": nlInfo.password }; - if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId; - if (this._guildId) headers["Guild-Id"] = this._guildId; - - const loadtracksUrl = baseUrl + "/v4/loadtracks?identifier=" + encodeURIComponent(songData.url); - logger.player(`[Player] Pre-resolving ${songData.type || "external"} URL via Lavalink...`); - - const body = await this._request(loadtracksUrl, { headers }); - const track = body?.data?.tracks?.[0] ?? body?.tracks?.[0] ?? body?.data; - const encoded = track?.encoded ?? track?.data; - - if (encoded && typeof encoded === "string") { - songData.encoded = encoded; - logger.player("[Player] Lavalink pre-resolve succeeded — track now has encoded payload"); - } else { - logger.player("[Player] Lavalink pre-resolve: no encoded track returned, bridge will try direct URL"); - } - } - } catch (e) { - logger.warn("[Player] Lavalink pre-resolve failed (bridge will try direct URL): " + e.message); - } - } - - this._audioBridge._conn = this._voiceConn; - - const seekMs = Math.floor((options.seekSeconds ?? 0) * 1000); - - const totalMs = this._getTrackDurationMs(songData); - const durationMs = totalMs > 0 ? Math.max(0, totalMs - seekMs) : 0; - - const result = await this._audioBridge.play(this._voiceConn, { - encoded: songData.encoded, - url: songData.url, - title: songData.title, - guildId: this._guildId, - }, { - seekSeconds: options.seekSeconds ?? 0, - durationMs, - videoId: songData.videoId || null, - filterPayload: this.activeFilterPayload || null, - }); - - if (result === "finished" && !this._skipping && !this.leaving && !this._paused) { - this._handleTrackEnd(); - } else if (result === "stopped") { - } - } - - /** @private @type {Timeout|null} */ - _trackEndTimer = null; - /** @private @type {number|null} */ - _trackEndRemainingMs = null; - - /** @private Handle when a track option's end time is reached. @param {object} match */ - _onTrackEndTimeReached(match) { - if (this._destroyed || this.leaving || !this._activeTrackOpt) return; - logger.player(`[Player] TrackOptions: end time reached (${match.endMs}ms), skipping track`); - this._activeTrackOpt = null; - this._trackEndTimer = null; - this._trackEndRemainingMs = null; - this._skipping = true; - this._bridgeStop(); - this._playingNext = false; - this._lastPlayedTrack = this.queue.getCurrent() ?? this._lastPlayedTrack; - this.emit("trackSkip", this._lastPlayedTrack); - if (!this.queue.isEmpty() && !this.leaving) { - this.playNext().catch(e => logger.error("[Player] TrackEnd playNext error:", e.message)); - } else { - this.queue.current = null; - if (!this._wasRadio && !this._queueEndedSent) { - this._queueEndedSent = true; - this.emit("queueEnd"); - if (!this._autoplay) { - const prefix = this._getPrefix?.(this._guildId) ?? "%"; - this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true }); - } - } - this.emit("stopplay"); - if (!this._is247Enabled()) { - this._startInactivityTimer(); - } - } - this._skipping = false; - } - - /** @private Clear the track-end timer. */ - _clearTrackEndTimer() { - if (this._trackEndTimer) { - clearTimeout(this._trackEndTimer); - this._trackEndTimer = null; - } - this._trackEndRemainingMs = null; - } - - /** @private Pause the track-end timer, saving remaining time. */ - _pauseTrackEndTimer() { - if (!this._trackEndTimer || !this._activeTrackOpt || this._activeTrackOpt.endMs <= 0) return; - clearTimeout(this._trackEndTimer); - const elapsedMs = Date.now() - this.startedPlaying; - this._trackEndRemainingMs = Math.max(0, this._activeTrackOpt.endMs - elapsedMs); - this._trackEndTimer = null; - } - - /** @private Resume the track-end timer. */ - _resumeTrackEndTimer() { - if (this._trackEndRemainingMs == null || this._trackEndRemainingMs <= 0 || !this._activeTrackOpt || this._activeTrackOpt.endMs <= 0) { - this._trackEndRemainingMs = null; - return; - } - const remainingMs = this._trackEndRemainingMs; - const match = this._activeTrackOpt; - this._trackEndTimer = setTimeout(() => this._onTrackEndTimeReached(match), remainingMs); - this._trackEndRemainingMs = null; - } - - /** @private Recalculate and restart the track-end timer. */ - _recalcTrackEndTimer() { - if (!this._activeTrackOpt || this._activeTrackOpt.endMs <= 0) return; - this._clearTrackEndTimer(); - const elapsedMs = Date.now() - this.startedPlaying; - const remainingMs = this._activeTrackOpt.endMs - elapsedMs; - if (remainingMs <= 0) { - this._onTrackEndTimeReached(this._activeTrackOpt); - return; - } - const match = this._activeTrackOpt; - this._trackEndTimer = setTimeout(() => this._onTrackEndTimeReached(match), remainingMs); - } - - /** @private @async Look up per-user track options. @param {object} songData @returns {Promise} */ - async _lookupTrackOptions(songData) { - if (!this.trackOptions || !songData || songData.type === "radio") return null; - if (!this._guildId || !this._channelId) return null; - - const userIds = []; - if (this._voiceCache) { - const humans = this._voiceCache.getHumansInChannel( - cleanId(this._guildId), - cleanId(this._channelId) - ); - userIds.push(...humans); - } - - if (userIds.length === 0) { - try { - const guild = this.client?.guilds?.get?.(this._guildId); - const voiceStates = guild?.voice_states ?? guild?.voiceStates; - if (voiceStates) { - const entries = Array.isArray(voiceStates) ? voiceStates - : typeof voiceStates.values === "function" ? [...voiceStates.values()] - : Object.values(voiceStates); - for (const state of entries) { - const ch = cleanId(state?.channelId ?? state?.channel_id ?? ""); - if (ch === cleanId(this._channelId)) { - const uid = state?.userId ?? state?.user_id; - const member = guild?.members?.get?.(uid); - if (uid && !member?.user?.bot) userIds.push(uid); - } - } - } - } catch(e) { logger.warn("[Player] Voice state lookup error:", e?.message); } - } - - if (userIds.length === 0) return null; - - const match = await this.trackOptions.getBestMatchForChannel(userIds, songData); - return match || null; - } - - /** @private @async Auto-seek to a track options start position. @param {object} match */ - async _applyTrackOptionsSeek(match) { - if (!match || match.startMs <= 0) return; - const current = this.queue.getCurrent(); - if (!current?.url || !this._voiceConn || this.leaving) { - logger.warn(`[Player] TrackOptions: cannot seek (encoded=${!!current?.encoded} lavalinkPlayer=${!!this.lavalinkPlayer} leaving=${this.leaving})`); - return; - } - let seeked = false; - for (let attempt = 0; attempt < 10; attempt++) { - await Utils.sleep(500); - try { - const result = await this.seekToPosition(match.startMs); - if (result) { - seeked = true; - logger.player(`[Player] TrackOptions: auto-seeked to ${match.startMs}ms for user ${match.userId} (attempt ${attempt + 1})`); - break; - } - } catch (e) { - logger.warn(`[Player] TrackOptions auto-seek attempt ${attempt + 1} error:`, e.message); - } - } - if (!seeked) { - logger.warn(`[Player] TrackOptions: auto-seek to ${match.startMs}ms failed after all retries`); - } - } - -/** @async Apply a track options match (custom start/end times) to the currently playing track. Seeks to the start position and sets a timer for the end position. @param {object} match - Track options match with startMs and optional endMs. @returns {Promise} True if applied successfully, false otherwise. */ - async applyTrackOption(match) { - if (!match || !this._voiceConn || this._paused) return false; - - this._clearTrackEndTimer(); - this._activeTrackOpt = null; - - try { - await this.seekToPosition(match.startMs || 0); - } catch (e) { - logger.warn("[Player] TrackOptions apply-seek error:", e.message); - return false; - } - - if (match.endMs > 0) { - const elapsedMs = Date.now() - this.startedPlaying; - const remainingMs = match.endMs - elapsedMs; - if (remainingMs > 0) { - this._activeTrackOpt = match; - this._trackEndTimer = setTimeout(() => this._onTrackEndTimeReached(match), remainingMs); - } - } else { - this._activeTrackOpt = match; - } - - return true; - } - -/** @async Fetch lyrics for the currently playing track via Lavalink REST API. @returns {Promise<{text: string, source: string, synced: boolean, lines: Array}|null>} Lyrics object with text, source, synced flag, and lines array, or null if unavailable. */ - async lyrics() { - const current = this.queue.getCurrent(); - if (!current) return null; - - const node = this._lavalink?.getNode?.() ?? null; - - if (node) { - try { - const searchQuery = current.artists?.[0]?.name - ? `${current.title} ${current.artists[0].name}` - : current.title; - - const path = current.encoded - ? `/loadlyrics?encodedTrack=${encodeURIComponent(current.encoded)}` - : `/loadlyrics?identifier=${encodeURIComponent(searchQuery)}`; - - const results = await node.request(path); - - if (results?.data?.lines?.length) { - return { - text: results.data.lines.map(l => l.text).join("\n"), - source: "Lavalink", - synced: results.data.lines.some(l => l.startTimeMs != null), - lines: results.data.lines, - }; - } - } catch (e) { - logger.player(`[Lyrics] Lavalink REST lyrics failed: ${e.message}`); - } - } - - return null; - } -} diff --git a/src/commands/CommandBuilder.mjs b/src/commands/CommandBuilder.mjs new file mode 100644 index 0000000..4997625 --- /dev/null +++ b/src/commands/CommandBuilder.mjs @@ -0,0 +1,166 @@ +/** + * @module src/commands/CommandBuilder + * @description Fluent builder for command definitions (name, description, + * options, subcommands, aliases, requirements) plus the permission + * requirement model. + */ + +import { Utils } from "../utils/Utils.mjs"; +import { Option } from "./Option.mjs"; + +/** + * @class CommandRequirement + * @description Permission and owner-only gating for a command. + */ +export class CommandRequirement { + /** @type {boolean} Whether the command is restricted to bot owners. */ + ownerOnly = false; + + /** Create a new CommandRequirement with no permissions. */ + constructor() { + this.permissions = []; + this.permissionError = "You don't have the needed permissions to run this command!"; + return this; + } + + /** @param {boolean} bool @returns {CommandRequirement} */ + setOwnerOnly(bool) { this.ownerOnly = bool; return this; } + /** @param {string} p @returns {CommandRequirement} */ + addPermission(p) { this.permissions.push(p); return this; } + /** @param {...string} p @returns {CommandRequirement} */ + addPermissions(...p) { this.permissions.push(...p); return this; } + + /** + * @returns {string[]} The permission list (with an owner note appended when + * the requirement is owner-only). + */ + getPermissions() { return (this.ownerOnly) ? [...this.permissions, "Owner-only command"] : this.permissions; } + /** @param {string} e @returns {CommandRequirement} */ + setPermissionError(e) { this.permissionError = e; return this; } +} + +/** + * @class CommandBuilder + * @description Fluent builder for constructing command definitions with name, + * description, options, subcommands, aliases, requirements and examples. + */ +export class CommandBuilder { + /** Create a new CommandBuilder with default empty state. */ + constructor() { + this.name = null; + this.description = null; + this.id = null; + this.aliases = []; + this.subcommands = []; + this.options = []; + this.requirements = []; + this.category = "default"; + this.examples = []; + + this.uid = Utils.uid(); + + this.subcommandError = "Invalid subcommand. Try one of the following options: `$previousCmd <$cmdlist>`"; + this.parent = null; + } + + /** Set the command name and register it as the primary alias. @param {string} n @returns {CommandBuilder} */ + setName(n) { this.name = n; this.aliases.push(n.toLowerCase()); return this; } + /** Set the command description. @param {string} d @returns {CommandBuilder} */ + setDescription(d) { this.description = d; return this; } + /** Set the command ID. @param {string} id @returns {CommandBuilder} */ + setId(id) { this.id = id; return this; } + + /** @returns {string} Full command path including parent chain (e.g. "music play"). */ + get command() { return (this.parent) ? this.parent.command + " " + this.name : this.name; } + + /** + * Add a permission/owner-only requirement via a callback. + * @param {Function} config - Callback receiving a fresh {@link CommandRequirement}. + * @returns {CommandBuilder} + */ + setRequirement(config) { let req = config(new CommandRequirement()); this.requirements.push(req); return this; } + + /** + * Add a subcommand builder via a callback. + * @param {Function} config - Callback receiving a fresh {@link CommandBuilder}. + * @returns {CommandBuilder} + */ + addSubcommand(config) { let sub = config(new CommandBuilder()); sub.parent = this; this.subcommands.push(sub); return this; } + + /** + * Add a string option. + * @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} + */ + addStringOption(config, flag = false) { this.options.push(config(Option.create("string", flag))); return this; } + /** + * Add a number option. + * @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} + */ + addNumberOption(config, flag = false) { this.options.push(config(Option.create("number", flag))); return this; } + /** + * Add a boolean option. + * @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} + */ + addBooleanOption(config, flag = false) { this.options.push(config(Option.create("boolean", flag))); return this; } + /** + * Add a channel option. + * @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} + */ + addChannelOption(config, flag = false) { this.options.push(config(Option.create("channel", flag))); return this; } + /** + * Add a voice-channel option. + * @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} + */ + addVoiceChannelOption(config, flag = false) { this.options.push(config(Option.create("voiceChannel", flag))); return this; } + /** + * Add a user option. + * @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} + */ + addUserOption(config, flag = false) { this.options.push(config(Option.create("user", flag))); return this; } + + /** + * Add a text (remaining-args) option. Only one is allowed per command. + * @param {Function} config + * @returns {CommandBuilder} + * @throws {Error} If a text option already exists. + */ + addTextOption(config) { + if (this.options.findIndex(e => e.type === "text") !== -1) throw new Error("There can only be 1 text option."); + this.options.push(config(new Option("text"))); + return this; + } + + /** + * Add a choice (enum-like) option. + * @param {Function} config @param {boolean} [flag=false] @returns {CommandBuilder} + */ + addChoiceOption(config, flag = false) { this.options.push(config(Option.create("choice", flag))); return this; } + + /** + * Add an alias (case-insensitive, duplicates ignored). + * @param {string} alias + * @returns {CommandBuilder} + */ + addAlias(alias) { + if (this.aliases.findIndex(e => e === alias.toLowerCase()) !== -1) return this; + this.aliases.push(alias.toLowerCase()); + return this; + } + + /** + * Add multiple aliases. + * @param {...string} aliases + * @returns {CommandBuilder} + */ + addAliases(...aliases) { aliases.forEach((a) => this.addAlias(a)); return this; } + + /** Set the command category (used by help grouping). @param {string} cat @returns {CommandBuilder} */ + setCategory(cat) { this.category = cat; return this; } + + /** + * Add usage examples. + * @param {...string} examples + * @returns {CommandBuilder} + */ + addExamples(...examples) { this.examples.push(...examples); return this; } +} diff --git a/src/commands/CommandHandler.mjs b/src/commands/CommandHandler.mjs new file mode 100644 index 0000000..b22cb9e --- /dev/null +++ b/src/commands/CommandHandler.mjs @@ -0,0 +1,569 @@ +/** + * @module src/commands/CommandHandler + * @description The command dispatcher: parses incoming messages, matches + * commands and aliases, validates options/flags, enforces permissions and + * per-user cooldowns, and emits "run" events consumed by the CommandLoader. + */ + +import { EventEmitter } from "node:events"; +import { PermissionFlags } from "@fluxerjs/core"; +import { logger } from "../core/Logger.mjs"; +import { Utils } from "../utils/Utils.mjs"; +import { Message, REQUIRED_BOT_PERMISSIONS } from "../ui/index.mjs"; +import { Option, Flag } from "./Option.mjs"; +import { HelpHandler } from "./HelpHandler.mjs"; +import { PrefixManager } from "./PrefixManager.mjs"; + +/** @type {string[]} Option types whose quoted values may span multiple tokens. */ +const QUOTABLE_TYPES = ["string", "text", "channel", "voiceChannel"]; + +/** + * @class CommandHandler + * @description Main command dispatcher. + * @extends {EventEmitter} + * + * Events: + * - `"command"` — emitted with `{ command, message }` when a command starts. + * - `"run"` — emitted with the fully parsed run payload (see processCommand). + */ +export class CommandHandler extends EventEmitter { + /** @type {Function|null} Custom handler when the bot is pinged. */ + onPing = null; + /** @type {boolean} Whether the bot responds to pings as a prefix. */ + pingPrefix = true; + /** @type {string[]} Bot owner user IDs. */ + owners = []; + + /** @type {import('../ui/MessageHandler.mjs').MessageHandler} */ + messages; + client; + /** @type {PrefixManager} */ + prefixes; + /** @type {HelpHandler} */ + helpHandler; + + /** @type {string[]} All registered command aliases. */ + commandNames = []; + /** @type {import('./CommandBuilder.mjs').CommandBuilder[]} Registered commands. */ + commands = []; + + /** @type {object|null} Locale manager. */ + locale = null; + + 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."; + + /** @private @type {Map} Per-user last command timestamps for cooldown enforcement. */ + _cmdCooldowns = new Map(); + /** @private @type {number} Cooldown duration in ms between commands per non-owner user. */ + _cmdCooldownMs = 1500; + + /** + * @param {import('../ui/MessageHandler.mjs').MessageHandler} handler + * @param {string} [prefix="%"] + */ + constructor(handler, prefix = "%") { + super(); + this.messages = handler; + this.client = handler.client; + this.prefix = prefix; + this.helpHandler = new HelpHandler(this); + this.helpCommand = "help"; + this.replyHandler = (message, msg) => { + msg.reply(this.format(message, msg.channel.channel.guildId)); + }; + this.messages.onMessage(this.messageHandler.bind(this)); + } + + /** Get the command prefix for a guild. @param {string} guildId @returns {string} */ + getPrefix(guildId) { return this.prefixes.getPrefix(guildId); } + /** Enable or disable ping-as-prefix. @param {boolean} bool */ + setPingPrefix(bool) { this.pingPrefix = bool; } + /** @param {PrefixManager} manager */ + setPrefixManager(manager) { this.prefixes = manager; } + /** @param {HelpHandler} handler */ + setHelpHandler(handler) { this.helpHandler = handler; } + /** @param {object} locale */ + setLocale(locale) { this.locale = locale; } + + /** + * Translate a locale key. + * @param {string} guildId + * @param {string} key + * @param {object} [replacements={}] + * @returns {string} + */ + t(guildId, key, replacements = {}) { + if (!this.locale) return key; + return this.locale.translate(guildId, key, replacements); + } + + /** + * Replace $prefix and $helpCmd placeholders in text. + * @param {string} text + * @param {string} guildId + * @returns {string} + */ + format(text, guildId) { + const prefix = (!guildId) ? this.prefix : this.getPrefix(guildId); + return text + .replace(/\$prefix/gi, prefix) + .replace(/\$helpCmd/gi, this.helpCommand); + } + + /** + * Remove a command from the registry. + * @param {import('./CommandBuilder.mjs').CommandBuilder} command + */ + removeCommand(command) { + command.aliases.forEach(a => { + const idx = this.commandNames.indexOf(a); + if (idx !== -1) this.commandNames.splice(idx, 1); + }); + const idx = this.commands.findIndex(c => c.uid === command.uid); + if (idx !== -1) this.commands.splice(idx, 1); + } + + /** + * @private Handle an incoming message and route it to command processing. + * Handles bare pings, prefix detection, cooldowns and the built-in help. + * @param {Message} msg + */ + messageHandler(msg) { + if (!msg || !msg.content) return; + const trimmed = msg.content.trim(); + if (/^<@!?\d+>$/.test(trimmed)) { + const botId = this.client.user?.id; + if (botId && (trimmed === `<@${botId}>` || trimmed === `<@!${botId}>`)) { + return this.onPing?.(msg); + } + return; + } + + const guildId = msg.channel?.channel?.guildId ?? msg.message?.guildId; + const prefix = this.getPrefix(guildId); + const ping = `<@${this.client.user?.id}>`; + const pingBang = `<@!${this.client.user?.id}>`; + if (!(msg.content.startsWith(prefix) || msg.content.startsWith(ping) || msg.content.startsWith(pingBang))) return; + + if (this._isCoolingDown(msg)) return; + this._enforceCooldown(msg); + + const len = msg.content.startsWith(prefix) ? prefix.length : (msg.content.startsWith(pingBang) ? pingBang.length : ping.length); + const args = msg.content.slice(len).replace(/\u00A0/gi, " ").trim().split(" ").map(e => e.trim()); + + if (!args[0]) return; + + if (args[0] === this.helpCommand) { + return this._handleHelpInvocation(args, guildId, msg); + } + + if (!this.commandNames.includes(args[0].toLowerCase())) { + this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix$helpCmd", guildId) }), msg); + return; + } + return this.processCommand(this.commands.find(e => e.aliases.includes(args[0].toLowerCase())), args, msg); + } + + /** + * @private Apply the per-user cooldown gate: records the timestamp for the + * invoking user and prunes the cooldown map when it grows too large. + * Owners are exempt. + * @param {Message} msg + */ + _enforceCooldown(msg) { + const userId = msg.message?.author?.id ?? msg.author?.id; + if (!userId || this.owners.includes(userId)) return; + + const now = Date.now(); + this._cmdCooldowns.set(userId, now); + if (this._cmdCooldowns.size > 500) { + const cutoff = now - this._cmdCooldownMs * 2; + for (const [uid, ts] of this._cmdCooldowns) { + if (ts < cutoff) this._cmdCooldowns.delete(uid); + } + } + } + + /** + * @private Cooldown gate — returns true when the user invoked a command too + * recently and the message should be dropped (owners are exempt). + * @param {Message} msg + * @returns {boolean} + */ + _isCoolingDown(msg) { + const userId = msg.message?.author?.id ?? msg.author?.id; + if (!userId || this.owners.includes(userId)) return false; + const now = Date.now(); + const last = this._cmdCooldowns.get(userId) ?? 0; + return (now - last) < this._cmdCooldownMs; + } + + /** + * @private Built-in `%help` invocation handling (bare / page / command / subcommand path). + * @param {string[]} args + * @param {string} guildId + * @param {Message} msg + */ + _handleHelpInvocation(args, guildId, msg) { + if (!args[1]) { + const res = this.helpHandler.help(msg); + return (typeof res === "string") ? this.replyHandler(res, msg) : undefined; + } + if (args.length > 1 && Utils.isNumber(args[1])) { + const pageNumber = parseInt(args[1]); + if (pageNumber < 1 || pageNumber > this.helpHandler.pageNumber()) { + return this.replyHandler(this.t(guildId, "cmdHandler.page.invalid", { number: pageNumber }), msg); + } + return this.replyHandler(this.helpHandler.getHelpPage(pageNumber - 1, msg), msg); + } + if (args.length <= 2) { + let idx = this.commands.findIndex(e => e.aliases.some(al => al.toLowerCase() === args[1].toLowerCase())); + if (idx === -1) return this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix" + args[1], guildId) }), msg); + return this.replyHandler(this.helpHandler.getCommandHelp(this.commands[idx], msg), msg); + } + let currCmd = null; + let prefix2 = ""; + for (let i = 0; i < args.slice(1).length; i++) { + let a = args.slice(1)[i]; + let curr = (currCmd) ? currCmd.subcommands : this.commands; + let idx = curr.findIndex(e => e.aliases.some(al => al.toLowerCase() === a.toLowerCase())); + if (idx === -1) return this.replyHandler(this.t(guildId, "cmdHandler.command.invalid", { command: this.format("$prefix" + prefix2 + a, guildId) }), msg); + currCmd = curr[idx]; + prefix2 += a + " "; + } + return this.replyHandler(this.helpHandler.getCommandHelp(currCmd, msg), msg); + } + + /** + * Parse and execute a command with its options. + * @param {import('./CommandBuilder.mjs').CommandBuilder} cmd + * @param {string[]} args + * @param {Message} msg + * @param {string|boolean} [previous=false] - The command path so far (for error messages). + * @param {boolean} [external=false] - When true, errors are returned instead of replied. + * @returns {object|undefined} The command run payload. + */ + processCommand(cmd, args, msg, previous = false, external = false) { + if (!cmd) return logger.warn("[CommandHandler.processCommand] Invalid case: `cmd` falsy."); + + if (!external) { + const channel = msg.channel?.channel ?? msg.channel; + if (channel?.guild) { + const botPermResult = this.messages.checkAllBotPermissions(channel); + if (botPermResult.criticalMissing.length > 0) { + const permEmbed = this.messages.buildPermissionEmbed(botPermResult.missing, channel.guildId); + try { + msg.message?.reply?.({ embeds: [permEmbed] }, { ping: false }); + } catch (_) { + 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 }); + } catch (__) { logger.warn("[CommandHandler] Fallback perm reply failed"); } + } + return; + } + } + } + + if (cmd.requirements.length > 0 && !external) { + if (!this.assertRequirements(cmd, msg)) return; + } + if (previous === false) previous = this.format("$prefix" + cmd.name, msg.channel?.channel?.guildId); + if (!external) this.emit("command", { command: cmd, message: msg }); + + if (cmd.subcommands.length !== 0) { + const idx = cmd.subcommands.findIndex(el => { + if (!args[1]) return false; + return el.name.toLowerCase() === args[1].toLowerCase(); + }); + if (idx === -1) { + const list = cmd.subcommands.map(s => s.name).join(" | "); + const subGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId; + const e = this.t(subGuildId, "cmdBuilder.subcommand.invalid").replace(/\$previousCmd/gi, previous).replace(/\$cmdList/gi, list); + return (!external) ? this.replyHandler(e, msg) : e; + } + return this.processCommand(cmd.subcommands[idx], args.slice(1), msg, previous + this.format(" " + cmd.subcommands[idx].name), external); + } + + // `error === true` → internal invocation: the error reply was already + // sent by _parseOptions and, exactly like the original monolith, the + // command must NOT run (no "run" emission). A string is the external- + // mode error, returned to the caller as before. + const { opts, error } = this._parseOptions(cmd, args, msg, previous, external); + if (error) return (error === true) ? undefined : error; + + const commandRunData = { + command: cmd, + commandId: cmd.id, + options: opts, + message: msg, + get: function (oName) { return this.options.find(o => o.name === oName); }, + getById: function (id) { return this.options.find(o => o.id === id); } + }; + if (!external) this.emit("run", commandRunData); + return commandRunData; + } + + /** + * @private Parse positional options, flags, quoted values and text options. + * @param {import('./CommandBuilder.mjs').CommandBuilder} cmd + * @param {string[]} args + * @param {Message} msg + * @param {string} previous + * @param {boolean} external + * @returns {{opts: Array, error: *}} Parsed options or a handled error: + * `null` on success; `true` when an internal (non-external) invocation + * already sent its error reply and the caller must stop (the original + * monolith exited processCommand directly at these points); the error + * string for external invocations at the option/flag validation sites + * (textWrap sites always reply, matching the original's always-reply quirk). + */ + _parseOptions(cmd, args, msg, previous, external) { + const opts = []; + const texts = []; + + /** + * Collect quoted arguments spanning multiple tokens. + * @param {number} index + * @param {string} currVal + * @param {string[]} as + * @returns {{args: string[], index: number}|null} + */ + const collectArguments = (index, currVal, as) => { + const lastChar = currVal.charAt(currVal.length - 1); + if (lastChar === '"') return { args: as, index }; + const a = args[++index]; + if (!a) return null; + as.push(a); + return collectArguments(index, a, as); + }; + + const options = cmd.options.slice().sort((a, b) => { + const aText = (a.type === "text") ? 1 : 2; + const bText = (b.type === "text") ? 1 : 2; + return aText - bText; + }); + + const usedOptions = []; + let usedArgumentCount = 0; + + for (let i = 0, argIndex = 1; i < options.length; i++) { + const o = options[i]; + if (o?.type === "text") { texts.push(o); continue; } + if ((args[argIndex] || "").startsWith("-")) { + const flagName = args[argIndex].slice(1); + const op = cmd.options.find(e => e.aliases.includes(flagName)); + if (!op) { + const flagGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId; + const error = this.t(flagGuildId, "cmdHandler.invalidFlag").replace(/\$previousCmd/gi, previous).replace(/\$invalidFlag/gi, "-" + flagName); + return { opts, error: (!external) ? (this.replyHandler(error, msg) ?? true) : error }; + } + previous += " " + args[argIndex]; + let value = args[++argIndex]; + if ((value || "").startsWith('"') && (QUOTABLE_TYPES.includes(op.type))) { + const data = collectArguments(argIndex, value, [value]); + if (!data) { + const twGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId; + return { opts, error: (this.replyHandler(this._textWrapErrorMsg(twGuildId, args.slice(argIndex).join(" "), args[argIndex].charAt(0)), msg) ?? true) }; + } + argIndex += data.index - argIndex; + const _joined = data.args.join(" "); + value = _joined.slice(1, _joined.length - 1); + } + argIndex++; + i--; + const valid = op.validateInput(value, this.client, msg.message); + if (!valid && (op.required || !op.empty(value))) { + const errGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId; + const e = this._optionTypeError(errGuildId, op, value, previous); + return { opts, error: (!external) ? (this.replyHandler(e, msg) ?? true) : e }; + } + usedArgumentCount += 2; + previous += " " + value; + opts.push({ value: op.formatInput(value, this.client, msg.message), name: op.name, id: op.id, uid: op.uid }); + usedOptions.push(op.uid); + continue; + } + + if (!o) continue; + if (o instanceof Flag) continue; + if (opts.findIndex(op => op.uid === o.uid) !== -1) continue; + let value = args[argIndex]; + if ((args[argIndex] || "").startsWith('"') && (QUOTABLE_TYPES.includes(o.type))) { + const data = collectArguments(argIndex, args[argIndex], [args[argIndex]]); + if (!data) { + const twGuildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId; + return { opts, error: (this.replyHandler(this._textWrapErrorMsg(twGuildId2, args.slice(argIndex).join(" "), args[argIndex].charAt(0)), msg) ?? true) }; + } + argIndex += data.index - argIndex; + value = data.args.join(" "); + value = value.slice(1, value.length - 1); + } + let valid = o.validateInput(value, this.client, msg.message); + if (!valid && o.dynamicDefault) { + value = o.dynamicDefault(this.client, msg); + valid = o.validateInput(value, this.client, msg.message); + } + if (!valid && (o.required || !o.empty(value))) { + const errGuildId2 = msg.channel?.channel?.guildId ?? msg.message?.guildId; + const e = this._optionTypeError(errGuildId2, o, value, previous); + return { opts, error: (!external) ? (this.replyHandler(e, msg) ?? true) : e }; + } + if (o.empty(value)) value = o.defaultValue; + opts.push({ value: o.formatInput(value, this.client, msg.message), name: o.name, id: o.id, uid: o.uid }); + usedOptions.push(o.uid); + previous += " " + value; + argIndex++; + usedArgumentCount++; + } + + if (texts.length > 0) { + let o = texts[0]; + let text = args.slice(usedArgumentCount + 1).join(" "); + if (o.required && !o.validateInput(text, this.client, msg.message)) { + const textErrGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId; + let e = this._optionTypeError(textErrGuildId, o, text, previous); + return { opts, error: (!external) ? (this.replyHandler(e, msg) ?? true) : e }; + } + const quote = (['"', "'"].includes(text.charAt(0))) ? text.charAt(0) : null; + if (quote && text.charAt(text.length - 1) === quote) text = text.slice(1, text.length - 1); + opts.push({ name: o.name, value: text, id: o.id, uid: o.uid }); + usedOptions.push(o.uid); + } + + options.filter(o => !usedOptions.includes(o.uid)).forEach(o => { + if (!o.defaultValue) return; + opts.push({ name: o.name, value: o.defaultValue, id: o.id, uid: o.uid }); + }); + + return { opts, error: null }; + } + + /** + * Check whether the message author meets all command requirements + * (owner-only, guild permissions). When member data must be fetched over + * REST, re-invokes processCommand asynchronously once resolved. + * @param {import('./CommandBuilder.mjs').CommandBuilder} cmd + * @param {Message} msg + * @returns {boolean} + */ + assertRequirements(cmd, msg) { + const authorId = msg.message?.author?.id; + const isOwner = this.owners.includes(authorId); + const permGuildId = msg.channel?.channel?.guildId ?? msg.message?.guildId; + + for (let i = 0; i < cmd.requirements.length; i++) { + let req = cmd.requirements[i]; + if (req.ownerOnly && !isOwner) return false; + if (req.permissions.length > 0 && !isOwner) { + const guild = msg.message?.guild ?? null; + if (!guild) { + this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg); + return false; + } + + const member = guild.members.get(authorId) ?? null; + if (member?.permissions) { + 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 { + const fetchPromise = typeof guild.fetchMember === "function" + ? guild.fetchMember(authorId) + : typeof guild.members?.fetch === "function" + ? guild.members.fetch(authorId) + : Promise.reject(new Error("No member fetch API available")); + fetchPromise.then(member => { + 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); + } else { + 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()); + this.processCommand(cmd, args, msg, false, true); + } + }).catch(() => this.replyHandler(this.t(permGuildId, "cmdBuilder.requirement.permission"), msg)); + return false; + } + } + } + return true; + } + + /** + * Validate an input for a given option type. + * @param {string} type + * @param {*} i + * @param {object} m + * @returns {boolean} + */ + validateInput(type, i, m) { return (new Option()).validateInput(i, this.client, m, type); } + + /** + * Format an input for a given option type. + * @param {string} type + * @param {*} i + * @param {object} m + * @returns {*} + */ + formatInput(type, i, m) { return (new Option()).formatInput(i, this.client, m, type); } + + /** + * @private Build a type-error message for an option. + * @param {string} guildId + * @param {Option} option + * @param {*} value + * @param {string} previous + * @returns {string} + */ + _optionTypeError(guildId, option, value, previous) { + if (option.tError) { + return option.tError.replace(/\$previousCmd/gi, previous).replace(/\$currValue/gi, value); + } + const localeKey = option.type === 'choice' ? 'cmdBuilder.option.invalidChoice' + : (option.type === 'channel' || option.type === 'voiceChannel') ? 'cmdBuilder.option.invalidChannel' + : 'cmdBuilder.option.invalidType'; + const choiceStr = option.type === 'choice' + ? (option.choices.length > Option.THRESHOLD ? Option.formatChoicesCompact(option.choices) : option.choices.map(c => '- ' + c).join('\n')) + : ''; + return this.t(guildId, localeKey, { + $currValue: value, + $optionName: option.name, + $type: option.type, + $choices: choiceStr + }).replace(/\$previousCmd/gi, previous); + } + + /** + * @private Build a text-wrap error message. + * @param {string} guildId + * @param {string} value + * @param {string} quote + * @returns {string} + */ + _textWrapErrorMsg(guildId, value, quote) { + return this.t(guildId, 'cmdHandler.textWrapError', { $value: value, $quote: quote }); + } + + /** + * Register a command builder and sort the command list alphabetically. + * @param {import('./CommandBuilder.mjs').CommandBuilder} builder + * @returns {import('./CommandBuilder.mjs').CommandBuilder[]} + */ + addCommand(builder) { + this.commandNames.push(...builder.aliases); + this.commands.push(builder); + this.commands.sort((a, b) => { + let A = a.name.toUpperCase(); + let B = b.name.toUpperCase(); + return (A < B) ? -1 : (A > B) ? 1 : 0; + }); + return this.commands; + } +} diff --git a/src/commands/CommandLoader.mjs b/src/commands/CommandLoader.mjs new file mode 100644 index 0000000..19506aa --- /dev/null +++ b/src/commands/CommandLoader.mjs @@ -0,0 +1,123 @@ +/** + * @module src/commands/CommandLoader + * @description Dynamically loads command modules from a directory, registers + * their builders, and binds run handlers with error capture + error-id replies. + */ + +import { pathToFileURL } from "node:url"; +import path from "node:path"; +import * as fs from "node:fs"; +import { logger } from "../core/Logger.mjs"; +import { Utils } from "../utils/Utils.mjs"; + +/** + * @class CommandLoader + * @description Loads command files from a directory, registers builders with + * the CommandHandler, and dispatches "run" events to the matching run function. + * + * Command module shape (both shapes are accepted): + * - `export const command` (builder or builder-factory), `export const run` + * - default export object with the same keys + * - optional `exportDef: { name, object }` registers a global on the context + */ +export class CommandLoader { + /** @type {import('./CommandHandler.mjs').CommandHandler} */ + commands; + /** @type {Map} Command UID → file path. */ + commandFiles = new Map(); + /** @type {Map} Command UID → run function. */ + runnables = new Map(); + /** @type {object} Shared context (the bot instance). */ + context; + + /** + * @param {import('./CommandHandler.mjs').CommandHandler} commands + * @param {object} context - Bot context object (gets loader/runnables refs attached). + */ + constructor(commands, context) { + this.commands = commands; + this.context = context; + this.context.loader ??= this; + this.context.commandFiles = this.commandFiles; + this.context.runnables = this.runnables; + + this.commands.on("run", (data) => { + if (!this.runnables.has(data.command.uid)) return; + const runFc = this.runnables.get(data.command.uid); + const sendErrorReply = (id) => { + Promise.resolve(data.message.reply("An error occurred. Error id: `#" + id + "`")) + .catch(err => logger.warn("[CommandHandler] Failed to send error-reply; error id #" + id + ":", err?.message)); + }; + try { + const result = runFc.call(this.context, data.message, data); + if (result && typeof result.catch === "function") { + result.catch(e => { + const id = Utils.uid(); + logger.error("Error running command; error id #" + id, e); + sendErrorReply(id); + }); + } + } catch (e) { + const id = Utils.uid(); + logger.error("Error running command; error id #" + id, e); + sendErrorReply(id); + } + }); + } + + /** + * Normalize a module export to `{ command, run, exportDef }`. + * @param {object} cData + * @returns {object} + */ + canonData(cData) { + if (cData.command !== undefined) { + return { + command: cData.command, + run: cData.run, + exportDef: cData.exportDef ?? cData.export ?? null + }; + } + const d = cData.default ?? cData; + return { + command: d.command, + run: d.run, + exportDef: d.exportDef ?? d.export ?? null + }; + } + + /** + * @async Load all command files from a directory. + * @param {string} dir + * @returns {Promise} + */ + loadFromDir(dir) { + const files = fs.readdirSync(dir) + .filter(f => !f.startsWith(".") && (f.endsWith(".js") || f.endsWith(".mjs"))); + + return Promise.all(files.map(async commandFile => { + const file = path.join(dir, commandFile); + + const cData = this.canonData(await import(pathToFileURL(file).href)); + + const builder = (typeof cData.command === "function") + ? cData.command.call(this.context) + : cData.command; + + if (!builder) return logger.warn("No builder returned. Skipping '" + commandFile + "'"); + + if (cData.exportDef) + this.context[cData.exportDef.name] = cData.exportDef.object; + + this.commands.addCommand(builder); + this.commandFiles.set(builder.uid, file); + + if (!cData.run) return; + + this.runnables.set(builder.uid, cData.run); + builder.subcommands.forEach(sub => { + this.runnables.set(sub.uid, cData.run); + }); + })); + } +} diff --git a/src/commands/HelpHandler.mjs b/src/commands/HelpHandler.mjs new file mode 100644 index 0000000..3d8a6d0 --- /dev/null +++ b/src/commands/HelpHandler.mjs @@ -0,0 +1,203 @@ +/** + * @module src/commands/HelpHandler + * @description Text-based help generation: paginated command lists, per-command + * usage/aliases/options rendering. Used as the default help renderer behind + * `%help ` (the rich tabbed help lives in src/ui/HelpCommand.mjs). + */ + +import { PageBuilder } from "../ui/Paginators.mjs"; +import { Option, Flag } from "./Option.mjs"; + +/** + * @class HelpHandler + * @description Generates paginated help text for commands. + */ +export class HelpHandler { + /** @type {import('./CommandHandler.mjs').CommandHandler} */ + commands; + /** @type {number} Commands per help page. */ + commandsPerPage = 5; + + /** + * Default pagination handler that builds paginated help pages. + * @param {object} msg - Message wrapper with message data. + * @param {HelpHandler} helpHandler + * @param {Array} cmds + * @returns {string|null} + */ + paginationHandler = (msg, helpHandler, cmds) => { + const guildId = msg.message.guildId; + let form = this.commands.t(guildId, "cmdHandler.help.pageStructure"); + + const contents = cmds.map((cmd, i) => { + return (i + 1) + ". **" + cmd.name + "**: " + (cmd.description || "").split("\n")[0]; + }); + + const pages = new PageBuilder(contents) + .setForm(helpHandler.commands.format(form, msg.message.guildId)) + .setMaxLines(helpHandler.commandsPerPage); + + helpHandler.commands.messages.initPagination(pages, msg); + return null; + } + + /** @type {Function|null} Custom help handler function override. */ + customHelpHandler = null; + + /** @param {import('./CommandHandler.mjs').CommandHandler} commands */ + constructor(commands) { this.commands = commands; } + + /** + * @param {string} string + * @returns {string} Capitalised first letter. + */ + static capitalise(string) { + if (string.length < 1) return string; + if (string.length === 1) return string.toUpperCase(); + return string.charAt(0).toUpperCase() + string.slice(1); + } + + /** + * @param {Array} [cmds] + * @returns {Array} Non-owner-only commands. + */ + userCommands(cmds) { + return (cmds || this.commands.commands).filter(c => + c.requirements.findIndex(r => r.ownerOnly) === -1 + ); + } + + /** @returns {number} Total number of help pages. */ + pageNumber() { + return Math.ceil(this.commands.commands.length / this.commandsPerPage); + } + + /** + * Entry point for help rendering. + * @param {object} message + * @returns {string|null} + */ + help(message) { + if (this.customHelpHandler) return this.customHelpHandler(message); + if (this.paginationHandler) return this.genHelp(null, message, true); + return this.getHelpPage(0, message); + } + + /** + * @param {number} n - 0-based page index. + * @param {object} msg + * @param {Array} [cmds=null] + * @returns {string} + */ + getHelpPage(n, msg, cmds = null) { + if (!cmds) cmds = this.commands.commands; + if (!(this.commandsPerPage < cmds.length)) return this.genHelp(null, msg, false, cmds); + let offset = this.commandsPerPage * n; + const commands = cmds.slice(offset, offset + this.commandsPerPage); + let max = Math.ceil(cmds.length / this.commandsPerPage); + return this.genHelp({ curr: n + 1, max, offset }, msg, false, commands); + } + + /** + * @param {object|null} page + * @param {object} msg + * @param {boolean} [paginate=false] + * @param {Array} [cmds=null] + * @returns {string} + */ + genHelp(page, msg, paginate = false, cmds = null) { + cmds = this.userCommands(cmds); + if (this.paginationHandler && msg && paginate) return this.paginationHandler(msg, this, cmds); + + const guildId = msg.message.guildId; + let p = (page) ? ` (page ${page.curr}/${page.max})` : ""; + const indexOffset = (page) ? page.offset : 0; + let content = this.commands.t(guildId, "cmdHandler.help.availableCommands", { $page: p }) + "\n\n"; + if (page && page.curr !== 1) content += (indexOffset) + this.commands.t(guildId, "cmdHandler.help.ellipsis") + "\n"; + cmds.forEach((cmd, i) => { content += (i + 1 + indexOffset) + ". **" + cmd.name + "**: " + cmd.description + "\n"; }); + if (page && page.curr !== page.max) content += (cmds.length + indexOffset) + this.commands.t(guildId, "cmdHandler.help.ellipsis") + "\n"; + content += this.commands.format(this.commands.t(guildId, "cmdHandler.help.runHelp"), guildId); + if (page) content += this.commands.format(this.commands.t(guildId, "cmdHandler.help.pageTip"), guildId); + + return this.commands.format(content, guildId); + } + + /** + * Get the description of a command. + * @param {import('./CommandBuilder.mjs').CommandBuilder} command + * @returns {string} + */ + commandDescription(command) { return command.description; } + + /** + * Build a usage string for a command including options and flags. + * @param {import('./CommandBuilder.mjs').CommandBuilder} cmd + * @param {object} msg + * @returns {string} + */ + commandUsage(cmd, msg) { + if (cmd.subcommands.length > 0) { + return this.commands.format("$prefix" + cmd.command, msg.message.guildId) + " <" + cmd.subcommands.map(e => e.name).join(" | ") + "> [...]"; + } + let options = this.commands.format("$prefix" + cmd.command, msg.message.guildId); + cmd.options.forEach(o => { + if (o.type === "text") return; + if (o instanceof Flag) + return options += (o.type === "choice") ? "-" + o.aliases[0] + " <" + Option.formatChoicesUsage(o.choices) + ">" : " -" + o.aliases[0] + " '" + o.type + "'"; + options += (o.type === "choice") ? " <" + Option.formatChoicesUsage(o.choices) + ">" : " '" + o.name + ": " + o.type + "'"; + }); + let o = cmd.options.find(e => e.type === "text"); + if (o) options += "'" + o.name + ": " + o.type + "'"; + return options.trim(); + } + + /** + * Generate detailed help text for a single command. + * @param {import('./CommandBuilder.mjs').CommandBuilder} command + * @param {object} msg + * @returns {string} + */ + getCommandHelp(command, msg) { + const guildId = msg.message.guildId; + let content = `${HelpHandler.capitalise(command.name)}\n`; + content += this.commandDescription(command, msg) + "\n\n"; + content += this.commands.t(guildId, "cmdHandler.help.usage") + "\n💻 `" + this.commandUsage(command, msg) + "`\n\n"; + if (command.examples.length > 0) + content += this.commands.t(guildId, "cmdHandler.help.examples") + "\n- `" + command.examples.map(e => this.commands.format(e, guildId)).join("`\n- `") + "`\n\n"; + if (command.aliases.length > 1) { + content += this.commands.t(guildId, "cmdHandler.help.aliases") + "\n"; + command.aliases.forEach(alias => { content += "- " + alias + "\n"; }); + content += "\n"; + } + if (command.subcommands.length > 0) { + content += this.commands.t(guildId, "cmdHandler.help.subcommands") + "\n"; + command.subcommands.forEach(s => { + const optCount = s.options.length > 0 ? "; (`" + this.commands.t(guildId, "cmdHandler.help.optionCount", { $count: s.options.length }) + "`)" : ""; + content += "- " + s.name + ": " + (this.commandDescription(s, msg) || "").split("\n")[0] + optCount + "\n"; + }); + content += "\n"; + } else if (command.options.length > 0) { + content += this.commands.t(guildId, "cmdHandler.help.arguments") + "\n"; + command.options.forEach(o => { + const optional = ((o.required) ? "" : "?"); + const flag = (o instanceof Flag) ? "-" : ""; + if (o.type === "choice") { + const choiceDisplay = Option.formatChoicesInline(o.choices); + const aliasDisplay = o.aliases.filter(a => a !== null).join('`, `'); + content += "- **" + flag + o.name + "**" + optional + ": " + (o.description || "").split("\n")[0] + ";\n - " + this.commands.t(guildId, "cmdHandler.help.allowedValues") + choiceDisplay + "\n - " + this.commands.t(guildId, "cmdHandler.help.aliasesLabel") + "`" + aliasDisplay + "`\n"; + } else { + content += "- **" + flag + o.name + "**" + optional + ": " + (o.description || "").split("\n")[0] + "\n - " + this.commands.t(guildId, "cmdHandler.help.aliasesLabel") + "`" + o.aliases.join("`, `") + "`\n"; + } + content += "\n"; + }); + content += "\n"; + } + if (command.requirements.length > 0) { + content += this.commands.t(guildId, "cmdHandler.help.requirements") + "\n"; + command.requirements.forEach(r => { + content += "- " + r.getPermissions().map(e => this.commands.t(guildId, "cmdHandler.help.permission", { $permission: e })).join("\n- "); + }); + } + return content.trim(); + } +} diff --git a/src/commands/Option.mjs b/src/commands/Option.mjs new file mode 100644 index 0000000..fd32515 --- /dev/null +++ b/src/commands/Option.mjs @@ -0,0 +1,279 @@ +/** + * @module src/commands/Option + * @description Command option model — typed inputs (string, number, boolean, + * channel, user, choice, text) with validation, formatting and flag support. + */ + +import { Utils } from "../utils/Utils.mjs"; + +/** + * @class Option + * @description Represents a single command option with validation and + * user-friendly error formatting. Options are positional; Flags (dashed + * `-name` arguments) share the same base class. + */ +export class Option { + /** @type {number} Maximum choices before switching to compact format. */ + static THRESHOLD = 10; + /** @type {number} Number of choice columns per line in compact format. */ + static COLS_PER_LINE = 5; + + /** + * Format choice values in a compact multi-column layout. + * @param {string[]} choices + * @param {number} [perLine=Option.COLS_PER_LINE] + * @returns {string} + */ + static formatChoicesCompact(choices, perLine = Option.COLS_PER_LINE) { + const lines = []; + for (let i = 0; i < choices.length; i += perLine) { + lines.push(choices.slice(i, i + perLine).map(c => '`' + c + '`').join(' · ')); + } + return lines.join('\n'); + } + + /** + * Format choice values inline, switching to compact layout above the threshold. + * @param {string[]} choices + * @returns {string} + */ + static formatChoicesInline(choices) { + if (choices.length <= Option.THRESHOLD) { + return '`' + choices.join('`, `') + '`'; + } + return Option.formatChoicesCompact(choices, 6); + } + + /** + * Format choice values for a usage string, truncating with "…" if over max. + * @param {string[]} choices + * @param {number} [max=6] + * @returns {string} + */ + static formatChoicesUsage(choices, max = 6) { + if (choices.length <= max) return choices.join(' | '); + return choices.slice(0, max).join(' | ') + ' | ...'; + } + + /** @type {RegExp} Matches a channel mention like `<#123456>`. */ + channelRegex = /^<#(?\d+)>/; + /** @type {RegExp} Matches a user mention like `<@123>` or `<@!123>`. */ + userRegex = /^<@!?(?\d+)>/; + /** @type {RegExp} Matches a leading numeric ID. */ + idRegex = /^(?\d+)/; + + /** @type {Function|null} Dynamic default value resolver. */ + dynamicDefault; + + /** + * @param {string} [type="string"] One of: string, number, boolean, channel, + * voiceChannel, user, choice, text. + */ + constructor(type = "string") { + this.name = null; + this.description = null; + this.required = false; + this.id = null; + this.uid = Utils.uid(); + this.type = type; + this.tError = null; + this.aliases = [null]; + this.choices = []; + this.translations = {}; + this.defaultValue = null; + this.dynamicDefault = null; + } + + /** + * Factory to create an Option or Flag instance. + * @param {string} type + * @param {boolean} [flag=false] + * @returns {Option|Flag} + */ + static create(type, flag = false) { + return (!flag) ? new Option(type) : new Flag(type); + } + + /** @param {string} n @returns {Option} */ + setName(n) { this.name = n; this.aliases[0] = n; return this; } + /** @param {string} d @returns {Option} */ + setDescription(d) { this.description = d; return this; } + /** @param {boolean} r @returns {Option} */ + setRequired(r) { this.required = r; return this; } + /** @param {string} id @returns {Option} */ + setId(id) { this.id = id; return this; } + /** @param {string} t @returns {Option} */ + setType(t) { this.type = t; return this; } + + /** + * Add flag aliases (e.g. "v" for "-v"). + * @param {...string} a + * @returns {Option} + */ + addFlagAliases(...a) { this.aliases.push(...a); return this; } + + /** + * Add a single valid choice value (choice options only). + * @param {string} c + * @returns {Option} + * @throws {Error} If option type is not "choice". + */ + addChoice(c) { + if (this.type !== "choice") throw new Error(".addChoice is only available for choice options!"); + this.choices.push(c); + return this; + } + + /** + * Add multiple valid choice values (choice options only). + * @param {...string} cs + * @returns {Option} + * @throws {Error} If option type is not "choice". + */ + addChoices(...cs) { + if (this.type !== "choice") throw new Error(".addChoices is only available for choice options!"); + cs.forEach(c => this.addChoice(c)); + return this; + } + + /** + * Set the default value used when the option is omitted. + * @param {*} value + * @returns {Option} + */ + setDefault(value) { this.defaultValue = value; return this; } + + /** + * Set a dynamic default resolver function (called with (client, msg)). + * @param {Function} callback + * @returns {Option} + */ + setDynamicDefault(callback) { this.dynamicDefault = callback; return this; } + + /** + * Check whether a value is considered empty/omitted. + * @param {*} i + * @returns {boolean} + */ + empty(i) { + if (i === undefined || i === null) return true; + return (!i && !(String(i).includes("0"))); + } + + /** + * Validate an input value for this option type. + * @param {*} i + * @param {object} client + * @param {object} msg + * @param {string} [type] + * @returns {boolean} + */ + validateInput(i, client, msg, type) { + switch (type || this.type) { + case "text": + case "string": + return !!i; + case "number": + return !isNaN(i) && !isNaN(parseFloat(i)); + case "boolean": + return i === "0" || i === "1" || i?.toLowerCase() === "true" || i?.toLowerCase() === "false"; + case "choice": + return this.choices.includes(i); + case "user": + return this.userRegex.test(i) || this.idRegex.test(i); + case "channel": + if (i === undefined) return false; + return this.channelRegex.test(i) || this.idRegex.test(i) || client.channels.some(c => c.name === i); + case "voiceChannel": { + if (!i) return false; + const results = this.channelRegex.exec(i) ?? this.idRegex.exec(i); + 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"]) + : (byName ?? null); + return cObj ? voiceTypes.includes(cObj.type) : false; + } + } + } + + /** + * Format/parse an input value into its canonical form (IDs for mentions, + * numbers for numeric options, booleans for bools). + * @param {*} i + * @param {object} client + * @param {object} msg + * @param {string} [type] + * @returns {*} + */ + formatInput(i, client, msg, type) { + switch (type || this.type) { + case "text": + case "string": + return i; + case "number": + return parseFloat(i); + case "boolean": + return i?.toLowerCase() === "true" || i === "1"; + case "choice": + return i; + case "user": { + const rs = this.userRegex.exec(i) ?? this.idRegex.exec(i); + return rs?.groups["id"] ?? null; + } + case "channel": { + const results = this.channelRegex.exec(i) ?? this.idRegex.exec(i); + const channel = client.channels.find(c => c.name === i); + return results ? results.groups["id"] : (channel ? channel.id : null); + } + case "voiceChannel": { + const r = this.channelRegex.exec(i) ?? this.idRegex.exec(i); + const guildId = msg?.channel?.guildId ?? msg?.guildId; + if (guildId === "eval") return r ? r.groups["id"] : (i || null); + const voiceTypes = [2, 13]; + const c = msg?.guild?.channels?.find(c => c.name === i && voiceTypes.includes(c.type)); + return r ? r.groups["id"] : (c ? c.id : null); + } + } + } + + /** + * Generate a type-error message template for this option. + * @returns {string} + */ + get typeError() { + if (this.tError) return this.tError; + switch (this.type) { + case "choice": { + const choiceStr = this.choices.length > Option.THRESHOLD + ? Option.formatChoicesCompact(this.choices) + : this.choices.map(c => '- ' + c).join('\n'); + return "Invalid value '$currValue'. The option `" + this.name + "` has to be one of the following: \n" + choiceStr + "\nSchematic: `$previousCmd <" + this.type + ">`"; + } + case "voiceChannel": + case "channel": + return "Invalid value '$currValue'. The option `" + this.name + "` has to be a channel mention, id, or name.\nSchematic: `$previousCmd <" + this.type + ">`"; + default: + return "Invalid value '$currValue'. The option `" + this.name + "` has to be of type `" + this.type + "`.\nSchematic: `$previousCmd <" + this.type + ">`"; + } + } + + /** @param {string} e */ + set typeError(e) { this.tError = e; } +} + +/** + * @class Flag + * @description A dashed (`-name`) option. Flags cannot be of type "text". + * @extends Option + */ +export class Flag extends Option { + /** + * @param {string} [type="string"] + * @throws {Error} If type is "text". + */ + constructor(type = "string") { + if (type === "text") throw new Error("Flags can't be of type 'text'!"); + super(type); + } +} diff --git a/src/commands/PrefixManager.mjs b/src/commands/PrefixManager.mjs new file mode 100644 index 0000000..a4b6430 --- /dev/null +++ b/src/commands/PrefixManager.mjs @@ -0,0 +1,35 @@ +/** + * @module src/commands/PrefixManager + * @description Per-guild command prefix resolution (guild setting → config → "%"). + */ + +/** + * @class PrefixManager + * @description Manages per-guild command prefixes, falling back to the + * configured prefix and finally to "%". + */ +export class PrefixManager { + /** @type {import('../db/Settings.mjs').RemoteSettingsManager} */ + settings; + /** @type {string|null} */ + configPrefix; + + /** + * @param {import('../db/Settings.mjs').RemoteSettingsManager} settings + * @param {string|null} [configPrefix=null] + */ + constructor(settings, configPrefix = null) { + this.settings = settings; + this.configPrefix = configPrefix; + } + + /** + * Get the command prefix for a guild. + * @param {string} guildId + * @returns {string} + */ + getPrefix(guildId) { + const serverPrefix = this.settings.getServer(guildId).get("prefix"); + return serverPrefix ?? this.configPrefix ?? "%"; + } +} diff --git a/src/commands/index.mjs b/src/commands/index.mjs new file mode 100644 index 0000000..77ea983 --- /dev/null +++ b/src/commands/index.mjs @@ -0,0 +1,14 @@ +/** + * @module src/commands + * @description Public surface of the command framework layer. + * + * Import map from the old layout: + * - `src/CommandHandler.mjs` → this module + */ + +export { CommandBuilder, CommandRequirement } from "./CommandBuilder.mjs"; +export { Option, Flag } from "./Option.mjs"; +export { PrefixManager } from "./PrefixManager.mjs"; +export { HelpHandler } from "./HelpHandler.mjs"; +export { CommandHandler } from "./CommandHandler.mjs"; +export { CommandLoader } from "./CommandLoader.mjs"; diff --git a/src/constants/VoiceStateResolver.mjs b/src/constants/VoiceStateResolver.mjs index 6aba68c..87a1d2c 100644 --- a/src/constants/VoiceStateResolver.mjs +++ b/src/constants/VoiceStateResolver.mjs @@ -5,7 +5,7 @@ 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 - Discord guild object with a `voice_states` property. + * @param {object} guild - Fluxer guild object with a `voice_states` property. * @yields {{ userId: string, channelId: string, isBot: boolean }} */ export function* iterateVoiceStates(guild) { @@ -49,7 +49,7 @@ export function* iterateVoiceStates(guild) { * @param {object} opts * @param {string} opts.guildId * @param {string} opts.channelId - * @param {object} [opts.client] - Discord client with `guilds`. + * @param {object} [opts.client] - Fluxer client with `guilds`. * @param {VoiceStateCache} [opts.voiceCache] * @param {Map} [opts.observedVoiceUsers] * @param {object} [opts.room] - LiveKit room with `remoteParticipants`. @@ -112,7 +112,7 @@ export function hasHumansInChannel({ guildId, channelId, client, voiceCache, obs /** * Get the set of channel IDs that contain at least one human user. - * @param {object} guild - Discord guild object. + * @param {object} guild - Fluxer guild object. * @returns {Set} */ export function getChannelsWithHumans(guild) { @@ -125,7 +125,7 @@ export function getChannelsWithHumans(guild) { /** * Get the list of user IDs present in a specific voice channel. - * @param {object} guild - Discord guild object. + * @param {object} guild - Fluxer guild object. * @param {string} channelId * @returns {string[]} */ diff --git a/src/core/Bot.mjs b/src/core/Bot.mjs new file mode 100644 index 0000000..6a1e9c5 --- /dev/null +++ b/src/core/Bot.mjs @@ -0,0 +1,588 @@ +/** + * @module src/core/Bot + * @description The Remix bot class: config loading, client construction, + * service wiring (settings, commands, players, gateway, dashboard, Last.fm, + * FluxerList, track options), presence rotation, alone-check loop, and + * WebSocket error guards. Channel/voice operations live in BotVoiceMixin. + */ + +import * as fs from "node:fs"; +import path from "node:path"; +import childProcess from "node:child_process"; +import { Client, Events } from "@fluxerjs/core"; +import { getVoiceManager } from "@fluxerjs/voice"; +import { initLogger, logger, _wsErrorCooldown } from "./Logger.mjs"; +import { Locale } from "./Locale.mjs"; +import { CommandHandler, CommandLoader, PrefixManager } from "../commands/index.mjs"; +import { MessageHandler, HelpCommand, setGlobalColor } from "../ui/index.mjs"; +import { cleanId } from "../utils/Utils.mjs"; +import * as ShardingUtils from "../utils/ShardingUtils.mjs"; +import { RemoteSettingsManager } from "../db/Settings.mjs"; +import { PlayerManager } from "../music/PlayerManager.mjs"; +import { LavalinkManager } from "../music/LavalinkManager.mjs"; +import { Dashboard } from "../dashboard/Dashboard.mjs"; +import { VoiceStateCache } from "../voice/VoiceStateCache.mjs"; +import { GatewayHandler } from "../voice/gateway/GatewayHandler.mjs"; +import { LastFmManager } from "../services/lastfm/LastFmManager.mjs"; +import { FluxerListManager } from "../services/FluxerListManager.mjs"; +import { TrackOptionsManager } from "../services/TrackOptionsManager.mjs"; +import { applyMixins } from "../utils/mixins.mjs"; +import BotVoiceMixin from "./BotVoiceMixin.mjs"; + +/** + * Create a Map-like view object that proxies bot voice-state lookups through + * the VoiceStateCache's bot-specific methods. + * @param {VoiceStateCache} voiceCache + * @returns {Map} + */ +function createBotView(voiceCache) { + return { + get size() { return voiceCache.botLocations.size; }, + get(key) { return voiceCache.botLocations.get(key); }, + set(key, val) { return voiceCache.setBotUser(key, val); }, + has(key) { return voiceCache.botLocations.has(key); }, + delete(key) { return voiceCache.deleteBotUser(key); }, + forEach(fn) { for (const [k, v] of voiceCache.iterateBotUsers()) fn(v, k, this); }, + *[Symbol.iterator]() { yield* voiceCache.iterateBotUsers(); }, + *entries() { yield* voiceCache.iterateBotUsers(); }, + *keys() { for (const [k] of voiceCache.iterateBotUsers()) yield k; }, + *values() { for (const [, v] of voiceCache.iterateBotUsers()) yield v; }, + get observedVoiceBotsSize() { return voiceCache.botLocations.size; }, + }; +} + +/** + * Build a runtime presence update payload from a config entry (string or + * object with text/emoji/activity). + * @param {string|object} entry + * @returns {object} + */ +function buildRuntimePresence(entry) { + const isObj = typeof entry === "object" && entry !== null; + const customStatus = {}; + if (isObj) { + if (entry.text) customStatus.text = entry.text; + if (entry.emoji_name) customStatus.emojiName = entry.emoji_name; + if (entry.emoji_id) customStatus.emojiId = entry.emoji_id; + } else { + customStatus.text = String(entry); + } + + const update = { status: "online", afk: false, customStatus }; + + if (isObj && entry.activity) { + update.activities = [{ + name: entry.activity.name ?? "music", + type: entry.activity.type ?? 0, + url: entry.activity.url ?? undefined, + }]; + } + + return update; +} + +/** + * @class Remix + * @description Main bot class. Orchestrates client, settings, players, + * lavalink, gateway events, commands, and 24/7 voice channel management. + */ +class Remix { + /** + * Bootstrap the entire bot: load config, create the Fluxer client, + * initialise settings/commands/players/dashboard, set up event handlers, + * load modules, and log in. + */ + constructor() { + let config; + try { + config = JSON.parse(fs.readFileSync("config.json", "utf8")); + } catch (e) { + const reason = e.code === "ENOENT" + ? "config.json not found. Copy config_example.json → config.json and fill in your values." + : `config.json is malformed JSON: ${e.message}`; + console.error(`[Startup] FATAL: ${reason}`); + process.exit(1); + } + const REQUIRED_KEYS = ["token", "mysql"]; + for (const key of REQUIRED_KEYS) { + if (config[key] == null) { + console.error(`[Startup] FATAL: config.json is missing required key "${key}".`); + process.exit(1); + } + } + this.config = config; + + setGlobalColor(config.embedColor); + + this.locale = new Locale(typeof config.prefix === "string" && config.prefix ? config.prefix : "%"); + this.locale.load(); + + this.dashboard = new Dashboard(this, { + enabled: config.dashboard?.enabled, + redis: config.dashboard?.redis, + mysql: config.mysql, + }); + + const presenceContents = config.presenceContents ?? []; + const presenceInterval = config.presenceInterval ?? 30_000; + + let presenceRotationIndex = presenceContents.length > 1 ? 1 : 0; + let presenceRotationStarted = false; + let wsHandlerRearmStarted = false; + + const timers = config.timers ?? {}; + this.T = { + aloneCheckInterval: timers.aloneCheckInterval ?? 60_000, + aloneCheckDebounce: timers.aloneCheckDebounce ?? 500, + rejoin247Delay: timers.rejoin247Delay ?? 3_000, + leave247RejoinDelay: timers.leave247RejoinDelay ?? 5_000, + intentionalLeaveTTL: timers.intentionalLeaveTTL ?? 10_000, + }; + + // Fluxer 3.0: ClientOptions.presence is the normalized PresenceUpdateOptions + // shape (customStatus/emojiName/emojiId) — the 2.2 wire format + // (custom_status) is no longer read here. buildRuntimePresence() outputs + // exactly the normalized shape, so the initial presence reuses it. + const client = new Client({ + waitForGuilds: true, + cache: { guilds: false, channels: false, users: false, members: false }, + ...config["fluxer.js"], + presence: presenceContents.length === 0 ? undefined : buildRuntimePresence(presenceContents[0]), + }); + + client.setMaxListeners(50); + this.client = client; + + try { + getVoiceManager(client); + logger.player("[Startup] VoiceManager initialized before login."); + } catch (e) { + logger.warn("[Startup] VoiceManager pre-login init failed:", e.message); + } + + const messages = new MessageHandler(this.client); + this.messages = messages; + + const settings = new RemoteSettingsManager(config.mysql, "./storage/defaults.json"); + this.settingsMgr = settings; + + const configPrefix = config.prefix ?? null; + if (configPrefix && settings.defaults) { + settings.defaults.prefix = configPrefix; + } + + this.locale.bind(this.settingsMgr); + + const commands = new CommandHandler(messages, configPrefix); + this.handler = commands; + + const prefixMgr = new PrefixManager(settings, configPrefix); + commands.setPrefixManager(prefixMgr); + commands.setLocale(this.locale); + messages.setLocale(this.locale); + this.locale.setPrefixResolver((guildId) => commands.getPrefix(guildId)); + + new HelpCommand(commands, messages, (msg) => this.getSettings(msg)).register(); + + commands.onPing = (msg) => { + msg.replyEmbed( + this.handler.format( + "My prefix in this server is `$prefix`\n\nRun `$prefix$helpCmd` to get started!", + msg.message.guildId + ), + false, + { + icon_url: msg.channel.channel.guild?.icon + ? `https://cdn.fluxer.app/icons/${msg.channel.channel.guild.id}/${msg.channel.channel.guild.icon}.webp` + : null, + title: msg.channel.channel.guild?.name ?? null, + } + ); + }; + commands.owners = config.owners ?? []; + + this.lavalink = null; + let lavalinkInitialised = false; + + this.voiceCache = new VoiceStateCache({ maxUsers: 50_000, maxBots: 10_000 }); + + this.observedVoiceUsers = this.voiceCache; + this.observedVoiceBots = createBotView(this.voiceCache); + + this._announcementChannelCache = new Map(); + this._announcementChannelTTL = 5 * 60 * 1000; + setInterval(() => { + const now = Date.now(); + for (const [k, v] of this._announcementChannelCache) { + if (v.timestamp && now - v.timestamp > this._announcementChannelTTL) this._announcementChannelCache.delete(k); + } + }, 60_000); + this.intentionalLeaves = new Map(); + + this.gatewayHandler = new GatewayHandler(this); + this.gatewayHandler.setupEventHandlers(); + + this.lastfm = new LastFmManager(config.lastfm, config.mysql); + this.fluxerlist = new FluxerListManager(config.fluxerlist); + this.trackOptions = new TrackOptionsManager(config.mysql); + + settings.on("ready", () => this._onSettingsReady()); + + client.on(Events.Ready, async () => { + try { + logger.player("Logged in as " + (client.user?.username ?? "bot")); + + this._attachWsErrorHandlers(); + + if (!wsHandlerRearmStarted) { + wsHandlerRearmStarted = true; + setInterval(() => { + this._attachWsErrorHandlers(); + this.gatewayHandler.attachRawListener(); + }, 5_000).unref?.(); + } + + const botId = client.user?.id ?? "0"; + + await this.settingsMgr.setBotId(botId); + await this.lastfm.setBotId(botId); + this.dashboard.setBotId(botId); + this.trackOptions.setBotId(botId); + + if (!lavalinkInitialised) { + lavalinkInitialised = true; + this.lavalink = new LavalinkManager(config.nodelink ?? {}, client, { id: botId, username: client.user?.username ?? "bot" }); + this.lavalink.on("ready", () => { + logger.lavalink("[Lavalink] Session ready"); + }); + await this.lavalink.init(); + this.playerContext.lavalink = this.lavalink; + } + + this.gatewayHandler.onReady(); + + if (!presenceRotationStarted && presenceContents.length > 1) { + presenceRotationStarted = true; + setInterval(() => { + try { + const entry = presenceContents[presenceRotationIndex % presenceContents.length]; + client.user?.setPresence(buildRuntimePresence(entry)); + presenceRotationIndex = (presenceRotationIndex + 1) % presenceContents.length; + } catch (e) { + logger.warn("[Presence] Rotation update failed:", e?.message); + } + }, presenceInterval).unref?.(); + } + } catch (e) { + logger.error("[Ready] Fatal error in Ready handler:", e); + } + }); + + client._remix = this; + + this.playerContext = { + client: this.client, + config, + lavalink: null, + }; + this.players = new PlayerManager(settings, commands, { + config, + player: this.playerContext, + dashboard: this.dashboard, + locale: this.locale, + timers: this.T, + trackOptions: this.trackOptions, + }); + this.players.observedVoiceUsers = this.observedVoiceUsers; + this.players.voiceCache = this.voiceCache; + this.players._lastfm = this.lastfm; + + const ALONE_CHECK_INTERVAL = this.T.aloneCheckInterval; + setInterval(() => this._runAloneCheck(), ALONE_CHECK_INTERVAL); + + this.players.checkVoiceChannels = (message) => this._checkVoiceChannelsImpl(message); + + const __dirname = import.meta.dirname; + try { + this.comHash = childProcess.execSync("git rev-parse --short HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim(); + this.comHashLong = childProcess.execSync("git rev-parse HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim(); + } catch (e) { + logger.warn("[Git] comhash error:", e?.message); + this.comHash = "Newest"; + this.comHashLong = null; + } + + this.comLink = "https://github.com/remix-bot/fluxer/commit/" + (this.comHashLong ?? ""); + + const loader = new CommandLoader(commands, this); + const dir = path.join(__dirname, "..", "..", "commands"); + logger.commands("Started loading commands."); + loader.loadFromDir(dir) + .then(() => logger.commands("Commands loaded.")) + .catch(e => logger.error("Failed to load commands:", e)); + + logger.commands("Loading Modules."); + this.loadedModules = new Map(); + try { + this.modules = JSON.parse(fs.readFileSync("./storage/modules.json")); + } catch (e) { + const reason = e.code === "ENOENT" + ? "storage/modules.json not found." + : `storage/modules.json is malformed JSON: ${e.message}`; + console.error(`[Startup] WARN: ${reason} — starting with no modules.`); + this.modules = []; + } + Promise.allSettled(this.modules.map(async m => { + if (!m.enabled) return; + try { + const exported = await import(m.index); + const ModClass = exported.default; + this.loadedModules.set(m.name, { instance: new ModClass(this), c: ModClass }); + } catch (e) { + logger.error(`[Module] Failed to load "${m.name}":`, e.message); + } + })) + .then(results => { + const succeeded = results.filter(r => r.status === "fulfilled").length; + const failed = results.length - succeeded; + logger.commands(`Modules loaded (${succeeded} succeeded, ${failed} failed).`); + }); + + // Fluxer.js 3.0 sharding (opt-in, root `shard.mjs`): a child forked by a + // ShardingManager attaches the child-side ShardClientUtil BEFORE login — + // it applies FLUXER_SHARD_IDS/FLUXER_SHARD_COUNT to the client options + // and routes IDENTIFYs through the parent's shared per-IP budget — then + // reports readiness so the supervisor's spawn() promise resolves. + const startLogin = async () => { + if (ShardingUtils.isShardedProcess()) { + try { + const { attachShardClientUtil } = await import("@fluxerjs/sharding"); + this.shardUtil = attachShardClientUtil(client); + logger.player( + `[Startup] Sharding child attached — ${ShardingUtils.describeSharding(client)}.` + ); + } catch (e) { + // Fatal: without the shard slice this child would identify as shard 0 + // like every other child and thrash the gateway sessions. + logger.error( + "[Startup] FATAL: running under a ShardingManager but the sharding attach failed:", + e?.message + ); + process.exit(1); + } + } + await client.login(config.token); + if (this.shardUtil) { + try { this.shardUtil.notifyReady(); } + catch (e) { logger.warn("[Startup] Sharding ready report failed:", e?.message); } + } + }; + startLogin().catch(e => { + logger.error("[Startup] Login failed:", e?.message ?? e); + process.exit(1); + }); + } + + /** + * Settings-ready handler: initialise the logger and normalise stay_247 + * values (single channel per guild, cleaned IDs). + * @private + */ + _onSettingsReady() { + initLogger(this.config); + logger.settings("[settings] Loaded from DB."); + for (const [guildId, serverSettings] of this.settingsMgr.guilds) { + const val = serverSettings.get("stay_247"); + if (!val || val === "none") continue; + const rawArr = Array.isArray(val) ? val : [val]; + const cleaned = rawArr + .map(id => cleanId(id)) + .filter(id => id.length >= 15 && id.length <= 22); + + if (cleaned.length > 1) { + // Only 1 channel per guild supported. Keep first, drop the rest. + serverSettings.set("stay_247", cleaned.slice(0, 1)); + logger.settings( + `[settings] Trimmed stay_247 for guild ${guildId}: had ${cleaned.length} channels, kept first 1.` + ); + continue; + } + + const needsSave = JSON.stringify(cleaned) !== JSON.stringify(val); + if (needsSave || !Array.isArray(val)) { + const newVal = cleaned.length > 0 ? cleaned : "none"; + serverSettings.set("stay_247", newVal); + logger.settings( + `[settings] Cleaned stay_247 for guild ${guildId}: ${JSON.stringify(val)} → ${JSON.stringify(newVal)}` + ); + } + } + } + + /** + * Periodic alone-check: for every active player, when no humans remain in + * the channel, either arm the inactivity timer (music still queued) or + * emit autoleave. + * @private + */ + _runAloneCheck() { + if (this.players.playerMap.size === 0) return; + + for (const [mapKey, player] of this.players.playerMap) { + let channelId; + try { + if (player._destroyed || player._isJoining) continue; + + const guildId = player._guildId; + if (!guildId) continue; + + channelId = player._channelId ?? mapKey; + const cleanChanId = cleanId(channelId); + if (!cleanChanId) continue; + + const cleanGuildId = cleanId(guildId); + + if (player._is247Enabled()) continue; + + if (!player.connection) continue; + + let hasHuman = this.voiceCache.hasHumansInChannel(cleanGuildId, cleanChanId); + + if (!hasHuman) { + try { + const guild = this.client?.guilds?.get?.(cleanGuildId); + const voiceStates = guild?.voice_states ?? guild?.voiceStates; + if (voiceStates) { + const entries = Array.isArray(voiceStates) + ? voiceStates + : typeof voiceStates.values === "function" + ? [...voiceStates.values()] + : Object.values(voiceStates); + for (const state of entries) { + const stateChannel = cleanId(state?.channelId ?? state?.channel_id); + if (stateChannel === cleanChanId) { + const stateUserId = state?.userId ?? state?.user_id ?? state?.id; + const member = guild?.members?.get?.(stateUserId); + const isBot = member?.user?.bot ?? state?.member?.user?.bot ?? false; + if (!isBot) { + hasHuman = true; + break; + } + } + } + } + } catch(e) { logger.warn("[AloneCheck] Voice state check error:", e?.message); } + } + + if (!hasHuman) { + try { + const room = player.connection?.room; + if (room?.isConnected && room.remoteParticipants && room.remoteParticipants.size > 0) { + hasHuman = true; + } + } catch(e) { logger.warn("[AloneCheck] LiveKit check error:", e?.message); } + } + + if (!hasHuman && !player._paused) { + if (player.queue?.getCurrent() || !player.queue?.isEmpty()) { + player._startInactivityTimer?.(); + } else { + player._stopInactivityTimer?.(); + player.emit("autoleave"); + } + } else if (hasHuman) { + player._stopInactivityTimer?.(); + } + } catch (e) { + logger.warn("[AloneCheck] Error checking channel", channelId, e.message); + } + } + } + + /** + * Attach proactive error handlers to WebSocket sockets/shards to prevent + * unhandled crashes from WebSocket transport errors. Re-armed periodically. + * @private + */ + _attachWsErrorHandlers() { + try { + const wsManager = this.client?.ws; + if (!wsManager) return; + + let attachedNew = false; + + const logWsError = (label, err) => { + const now = Date.now(); + if (now - _wsErrorCooldown.lastLogged < _wsErrorCooldown.COOLDOWN_MS) return; + _wsErrorCooldown.lastLogged = now; + logger.warn(`[WS] ${label} transport error (auto-recovering): ${err?.message ?? err}`); + }; + + const attachToSocket = (wsObj, label) => { + if (!wsObj) return; + if (wsObj._fluxerErrorHandled) return; + wsObj._fluxerErrorHandled = true; + attachedNew = true; + + if (typeof wsObj.on === "function") { + wsObj.on("error", (err) => logWsError(label, err)); + } + if (typeof wsObj.addEventListener === "function") { + wsObj.addEventListener("error", (event) => { + if (typeof event.preventDefault === "function") event.preventDefault(); + const err = event?.error ?? event?.message ?? event; + logWsError(label, err); + }); + } + }; + + const attachToShard = (shard, id) => { + if (!shard) return; + if (shard._fluxerErrorHandled) return; + shard._fluxerErrorHandled = true; + attachedNew = true; + shard.on("error", (err) => logWsError(`Shard ${id}`, err)); + if (shard.ws) attachToSocket(shard.ws, `Shard ${id} socket`); + }; + + // Fluxer 3.0: the ws manager exposes shards via getShards() (2.2 used a + // `shards` Map property) and a sharded child owns several of them — + // attach to every shard connected in this process, not just shard 0. + for (const [id, shard] of ShardingUtils.getLocalShards(this.client)) { + attachToShard(shard, id); + } + + if (wsManager.ws) { + attachToSocket(wsManager.ws, "Gateway"); + } + + if (typeof wsManager.on === "function" && !wsManager._fluxerErrorHandled) { + wsManager._fluxerErrorHandled = true; + attachedNew = true; + wsManager.on("error", ({ shardId, error }) => { + logWsError(`WSManager (shard ${shardId})`, error); + }); + } + + if (typeof wsManager.on === "function" && !wsManager._shardCreateHandled) { + wsManager._shardCreateHandled = true; + attachedNew = true; + wsManager.on("shardCreate", (shard) => { + attachToShard(shard, shard.id ?? "?"); + }); + } + + if (attachedNew) { + logger.player("[WS] Proactive error handlers attached to gateway sockets."); + } + } catch (e) { + logger.warn("[WS] Failed to attach WS error handlers:", e.message); + } + } +} + +// Attach channel/voice operations (spawn, leave, shared servers, helpers). +applyMixins(Remix, BotVoiceMixin); + +export { Remix }; +export default Remix; diff --git a/src/core/BotVoiceMixin.mjs b/src/core/BotVoiceMixin.mjs new file mode 100644 index 0000000..07363d1 --- /dev/null +++ b/src/core/BotVoiceMixin.mjs @@ -0,0 +1,511 @@ +/** + * @module src/core/BotVoiceMixin + * @description Channel & voice operations for the {@link Remix} bot class: + * voice-channel resolution (checkVoiceChannels), 24/7 player spawning with + * announcements, programmatic channel leave, shared-server listing, and + * small translation/settings/pagination helpers. + * + * These methods are applied onto the Remix class prototype via + * {@link applyMixins} — `this` is a Remix instance. + */ + +import { EmbedBuilder } from "@fluxerjs/core"; +import { getVoiceManager } from "@fluxerjs/voice"; +import { getGlobalColor, PageBuilder } from "../ui/index.mjs"; +import { cleanId } from "../utils/Utils.mjs"; +import { remove247ChannelMode } from "../utils/Helpers247.mjs"; +import { logger } from "./Logger.mjs"; +import { Dashboard } from "../dashboard/Dashboard.mjs"; + +/** + * @type {object} + * @description Voice/channel mixin — applied to Remix. + */ +const BotVoiceMixin = { + /** + * Resolve the user's voice channel for a command invocation. Tries, in + * order: the voice-state cache, the VoiceManager, guild voice states, a + * cache scan, REST member fetch, and a raw REST member lookup. + * @this {import('./Bot.mjs').Remix} + * @param {object} message - Message wrapper. + * @returns {Promise<{channelId: string|null, alreadyInVoice: boolean, hasHumans: boolean}>} + */ + async _checkVoiceChannelsImpl(message) { + const userId = message?.author?.id ?? message?.message?.author?.id; + const guildId = + message?.channel?.guildId ?? + message?.channel?.guild?.id ?? + message?.channel?.server_id ?? + message?.channel?.serverId ?? + message?.message?.guildId ?? + message?.message?.guild?.id ?? + message?.message?.channel?.guildId ?? + message?.message?.channel?.guild?.id ?? + message?.message?.channel?.server_id ?? + message?.message?.channel?.serverId; + + const _empty = { channelId: null, alreadyInVoice: false, hasHumans: false }; + + if (!userId || !guildId) { + logger.voice(`[checkVC] BAIL — missing userId or guildId`); + return _empty; + } + + const cleanGuild = cleanId(guildId); + + const makeResult = (channelId) => { + const cId = cleanId(channelId); + return { + channelId: cId, + alreadyInVoice: this.players.playerMap.has(cId), + hasHumans: this.voiceCache.hasHumansInChannel(cleanGuild, cId), + }; + }; + + const seedCache = (channelId) => { + if (!this.voiceCache.hasHumanUser(userId, cleanGuild)) { + this.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId, isBot: false }); + } + }; + + logger.voice(`[checkVC] userId=${userId} guildId=${guildId} cleanGuild=${cleanGuild}`); + + const observed = this.voiceCache.getUserLocation(cleanGuild, userId); + if (observed && observed.channelId) { + logger.voice(`[checkVC] HIT voiceCache → ${observed.channelId}`); + return makeResult(observed.channelId); + } + + try { + const vm = getVoiceManager(this.client); + const channelId = vm?.getVoiceChannelId?.(guildId, userId) ?? vm?.getVoiceChannelId?.(cleanGuild, userId); + logger.voice(`[checkVC] vm.getVoiceChannelId → ${channelId}`); + if (channelId) { + seedCache(channelId); + return makeResult(channelId); + } + } catch (e) { logger.voice(`[checkVC] vm error: ${e.message}`); } + + try { + const guild = this.client.guilds.get(guildId) ?? this.client.guilds.get(cleanGuild); + const voiceStates = guild?.voice_states ?? guild?.voiceStates ?? null; + if (voiceStates) { + const entries = Array.isArray(voiceStates) + ? voiceStates + : typeof voiceStates.values === "function" + ? [...voiceStates.values()] + : Object.values(voiceStates); + for (const state of entries) { + const sid = state?.userId ?? state?.user_id ?? state?.id; + const sch = state?.channelId ?? state?.channel_id; + if ((sid === userId || sid === cleanId(userId)) && sch) { + logger.voice(`[checkVC] HIT guild.voice_states → ${sch}`); + seedCache(sch); + return makeResult(sch); + } + } + } + } catch (e) { logger.voice(`[checkVC] guild error: ${e.message}`); } + + try { + const loc = this.voiceCache.getHumanUser(userId, cleanGuild); + if (loc && loc.channelId) { + logger.voice(`[checkVC] HIT voiceCache scan → ${loc.channelId}`); + return makeResult(loc.channelId); + } + } catch (e) { logger.voice(`[checkVC] scan error: ${e.message}`); } + + try { + const guild = this.client.guilds.get(guildId) ?? this.client.guilds.get(cleanGuild); + if (guild && typeof guild.fetchMember === "function") { + logger.voice(`[checkVC] Trying REST fetchMember fallback for user ${userId}`); + const member = await guild.fetchMember(userId); + const voiceState = member?.voice ?? member?.voiceState ?? null; + const restChannelId = voiceState?.channelId ?? voiceState?.channel_id ?? null; + if (restChannelId) { + logger.voice(`[checkVC] HIT REST member.voice → ${restChannelId}`); + seedCache(restChannelId); + return makeResult(restChannelId); + } + } + } catch (e) { logger.voice(`[checkVC] REST fallback error: ${e.message}`); } + + try { + const guild = this.client.guilds.get(guildId) ?? this.client.guilds.get(cleanGuild); + if (guild && typeof this.client.rest?.get === "function") { + logger.voice(`[checkVC] Trying raw REST /guilds/${cleanGuild}/members/${userId}`); + const memberData = await this.client.rest.get(`/guilds/${cleanGuild}/members/${userId}`); + const restChannelId = memberData?.voice_state?.channel_id ?? memberData?.channel_id ?? null; + if (restChannelId) { + logger.voice(`[checkVC] HIT raw REST → ${restChannelId}`); + seedCache(restChannelId); + return makeResult(restChannelId); + } + } + } catch (e) { logger.voice(`[checkVC] raw REST error: ${e.message}`); } + + logger.voice(`[checkVC] MISS — returning empty`); + return _empty; + }, + + /** + * Mark a channel leave as intentional (user-initiated) to prevent the 24/7 + * auto-rejoin system from rejoining. + * @this {import('./Bot.mjs').Remix} + * @param {string} channelId - The channel ID. + * @param {number|null} [ttlMs=null] - TTL in ms (default: config.timers.intentionalLeaveTTL or 10s). + */ + markIntentionalLeave(channelId, ttlMs = null) { + const cleanChId = cleanId(channelId); + if (!cleanChId) return; + if (ttlMs === null) ttlMs = this.config?.timers?.intentionalLeaveTTL ?? 10_000; + const existing = this.intentionalLeaves.get(cleanChId); + if (existing) clearTimeout(existing); + this.intentionalLeaves.set(cleanChId, setTimeout(() => { + this.intentionalLeaves.delete(cleanChId); + }, ttlMs)); + }, + + /** + * Spawn a new Player for a channel. Used by 24/7 boot recovery and + * enable247. Guards against duplicate players, missing channels, and + * pending joins. + * @this {import('./Bot.mjs').Remix} + * @param {string} guildId - The guild ID. + * @param {string} channelId - The target voice channel ID. + * @returns {Promise} + * @throws {Error} If channel not found, not a voice channel, or join fails. + */ + async _spawnPlayer(guildId, channelId) { + const cleanGuildId = cleanId(guildId); + const cleanChannelId = cleanId(channelId); + + if (!cleanChannelId) throw new Error("_spawnPlayer: invalid channelId"); + + const existing = this.players.playerMap.get(cleanChannelId) + ?? this.players.getPlayerByGuildAndChannel(cleanGuildId, cleanChannelId); + if (existing) return existing; + + if (!this.lavalink) throw new Error("Audio node not ready yet — try again in a moment"); + + const channel = this.client?.channels?.get?.(cleanChannelId); + if (!channel) throw new Error("Channel not found"); + if (channel.type !== 2) throw new Error("Not a voice channel"); + + if (this.players._pendingJoins?.has?.(cleanChannelId)) { + throw new Error("Join already in progress for this channel"); + } + + const Player = (await import("../music/player/index.mjs")).default; + + const player = new Player(this.config.token, { + client: this.client, + config: this.config, + lavalink: this.lavalink ?? null, + settingsMgr: this.settingsMgr ?? this.settings ?? null, + getPrefix: (guildId) => this.handler.getPrefix(guildId), + observedVoiceUsers: this.observedVoiceUsers ?? null, + voiceCache: this.voiceCache ?? null, + locale: this.locale ?? null, + trackOptions: this.trackOptions ?? null, + }); + + player._home247Channel = cleanChannelId; + + this.players.setupEvents(player, { + channelId: cleanChannelId, + guildId: cleanGuildId, + }); + + player.on("autoleave", () => { + const mode = player._get247Mode(); + if (mode === "on") { + logger.inactivity(`[_spawnPlayer] autoleave suppressed for 24/7 channel ${cleanChannelId} (guild ${cleanGuildId})`); + return; + } + if (player._hasHumansInChannel()) { + logger.inactivity(`[_spawnPlayer] autoleave suppressed — humans in channel ${cleanChannelId}`); + return; + } + if (player.queue?.getCurrent() || !player.queue?.isEmpty()) { + logger.inactivity(`[_spawnPlayer] autoleave suppressed — queue has songs in channel ${cleanChannelId}`); + return; + } + + const activeChId = cleanId(player._channelId ?? cleanChannelId) || cleanChannelId; + const homeChId = cleanId(player._home247Channel ?? activeChId) || activeChId; + this.players.playerMap.delete(activeChId); + this.players._unindexPlayer?.(cleanGuildId, activeChId); + const pendingScrobble = this.players._pendingScrobbleTimers?.get(cleanChannelId); + if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this.players._pendingScrobbleTimers.delete(cleanChannelId); } + if (activeChId !== cleanChannelId) this.players.playerMap.delete(cleanChannelId); + if (homeChId !== activeChId) this.players.playerMap.delete(homeChId); + player.destroy(); + }); + + player.on("message", async (m) => { + try { + const serverSettings = this.settingsMgr?.getServer?.(cleanGuildId); + const raw = serverSettings?.get?.("songAnnouncements"); + const disabled = raw === false || raw === 0 || + ["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim()); + if (disabled) return; + + const chMgr = this.client?.channels ?? null; + const canPostById = (c) => !!c?.id && !!chMgr && typeof chMgr.send === "function"; + const asSendable = (c) => { + if (!c || typeof c === "string" || typeof c.send === "function") return c; + if (!canPostById(c)) return c; + const target = { id: c.id, type: c.type }; + target.isTextBased = () => true; + target.send = (options) => chMgr.send(c.id, options); + return target; + }; + const usable = (c) => !!c && typeof c === "object" && + (typeof c.send === "function" || canPostById(c)); + + const _tc = player.textChannel; + let ch = (_tc && typeof _tc === "object" && _tc.channel && typeof _tc.channel === "object") + ? _tc.channel + : _tc; + if (!usable(ch)) { + const savedAnnChId = serverSettings?.get?.("announcementChannelId"); + if (savedAnnChId) { + ch = this.client?.channels?.get?.(cleanId(savedAnnChId)) ?? null; + } + } + if (!usable(ch)) { + const guild = this.client?.guilds?.get?.(cleanGuildId); + if (guild?.systemChannelId) { + ch = guild.channels?.get?.(guild.systemChannelId) ?? null; + } + } + if (!usable(ch)) { + const guild = this.client?.guilds?.get?.(cleanGuildId); + if (guild?.channels) { + for (const c of (guild.channels.values?.() ?? [])) { + if (c.isTextBased?.() || c.type === 0 || c.type === "GUILD_TEXT") { + ch = c; + break; + } + } + } + } + if (!usable(ch)) return; + + ch = asSendable(ch); + if (!player.textChannel) player.textChannel = ch; + + const payload = typeof m === "object" && Array.isArray(m.embeds) + ? { ...m, allowedMentions: { parse: [] } } + : { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(m)], allowedMentions: { parse: [] } }; + ch.send(payload).catch(err => { + if (err.code === 'MISSING_PERMISSIONS' || err.statusCode === 403) { + logger.warn(`[_spawnPlayer] Cannot send announcement in channel ${ch.id} — missing permissions`); + } else { + logger.warn(`[_spawnPlayer] Failed to send announcement in channel ${ch.id}:`, err?.message ?? err); + } + }); + } catch(e) { + logger.warn("[Player] Song announcement error:", e?.message); + } + }); + + if (this.players._pendingJoins) { + this.players._pendingJoins.add(cleanChannelId); + } + + try { + await player.join(cleanChannelId); + + this.players.playerMap.set(cleanChannelId, player); + this.players._indexPlayer(cleanGuildId, cleanChannelId); + if (this.players._pendingJoins) { + this.players._pendingJoins.delete(cleanChannelId); + } + + const savedVol = this.settingsMgr?.getServer?.(cleanGuildId)?.get?.("volume"); + if (savedVol !== undefined && savedVol !== null) { + const vol = Number(savedVol); + if (!isNaN(vol)) player.setVolume(vol / 100); + } + + logger.player(`[_spawnPlayer] Spawned player for channel ${cleanChannelId} in guild ${cleanGuildId}`); + return player; + } catch (err) { + if (this.players._pendingJoins) { + this.players._pendingJoins.delete(cleanChannelId); + } + this.players.playerMap.delete(cleanChannelId); + try { player.destroy(); } catch(e) { logger.warn("[_spawnPlayer] Cleanup destroy error:", e?.message); } + logger.warn(`[_spawnPlayer] Failed to spawn player for channel ${cleanChannelId}:`, err.message); + throw err; + } + }, + + /** + * Leave a voice channel programmatically. Removes 24/7 if active, destroys + * the player, and optionally sends a confirmation message. + * @this {import('./Bot.mjs').Remix} + * @param {string} channelId - The channel ID to leave. + * @param {string} guildId - The guild ID. + * @param {object} [message=null] - Optional message for reply confirmation. + * @param {boolean} [force=false] - Whether to force-leave regardless of 24/7 status. + * @returns {Promise} True on success. + */ + async leaveChannel(channelId, guildId, message, force = false) { + const cleanChId = cleanId(channelId); + const cleanGuildId = cleanId(guildId); + const set = this.settingsMgr.getServer(cleanGuildId); + const raw = set?.get("stay_247"); + + const channels = (!raw || raw === "none") + ? new Set() + : Array.isArray(raw) + ? new Set(raw.map(id => cleanId(id)).filter(Boolean)) + : new Set([cleanId(raw)]); + + if (channels.has(cleanChId)) { + channels.delete(cleanChId); + set.set("stay_247", channels.size > 0 ? [...channels] : "none"); + remove247ChannelMode(set, cleanChId, channels); + } + + this.markIntentionalLeave(cleanChId); + + const player = this.players.playerMap.get(cleanChId); + if (player) { + this.players.playerMap.delete(cleanChId); + this.players._unindexPlayer(player._guildId, cleanChId); + const pendingScrobble = this.players._pendingScrobbleTimers?.get(cleanChId); + if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this.players._pendingScrobbleTimers.delete(cleanChId); } + await player.leave().catch(() => {}); + player.destroy(); + } + + if (message) { + const guildIdForLocale = message?.channel?.channel?.guildId ?? message?.guildId ?? cleanGuildId; + message.replyEmbed(this.locale.translate(guildIdForLocale, "responses._common.successfullyLeft")); + } + + return true; + }, + + /** + * Get the server settings for the guild associated with a message. + * @this {import('./Bot.mjs').Remix} + * @param {object} message - The incoming message wrapper. + * @returns {object} The ServerSettings for the guild, or a fallback. + */ + getSettings(message) { + const guildId = message?.channel?.channel?.guildId ?? message?.guildId ?? null; + return this.settingsMgr.getServer(guildId); + }, + + /** + * Shorthand to translate a locale key for the guild of a given message. + * @this {import('./Bot.mjs').Remix} + * @param {object} message - The message wrapper (used to resolve guild ID). + * @param {string} key - The locale key. + * @param {object} [data={}] - Interpolation data. + * @returns {string} The localised string. + */ + t(message, key, data = {}) { + const guildId = message?.channel?.channel?.guildId + ?? message?.message?.guildId + ?? message?.guildId + ?? null; + return this.locale.translate(guildId, key, data); + }, + + /** + * Get or create a player for the given message context. + * @this {import('./Bot.mjs').Remix} + * @param {object} message - The message wrapper. + * @param {boolean} promptJoin - Whether to prompt the user to join a voice channel. + * @param {boolean} verifyUser - Whether to verify the user is in a voice channel. + * @param {boolean} shouldJoin - Whether to auto-join the voice channel. + * @returns {Promise} The Player instance. + */ + getPlayer(message, promptJoin, verifyUser, shouldJoin) { + return this.players.getPlayer(message, promptJoin, verifyUser, shouldJoin); + }, + + /** + * Get all servers the bot and the given user share (i.e. the user is a + * member). Used by the dashboard to determine which servers a user can + * manage. + * @this {import('./Bot.mjs').Remix} + * @param {object} user - The Fluxer user. + * @returns {Promise>} Array of server summaries with channels. + */ + async getSharedServers(user) { + if (!user) return []; + + const shared = []; + + for (const guild of this.client.guilds?.values?.() ?? []) { + let isMember = false; + + if (guild.members?.has?.(user.id)) { + isMember = true; + } + + if (!isMember) { + const cleanGuildId = cleanId(guild.id); + const userLoc = this.voiceCache.getUserLocation(cleanGuildId, user.id); + if (userLoc) isMember = true; + } + + if (!isMember) { + try { + const member = await guild.members.fetch(user.id).catch(() => null); + if (member) isMember = true; + } catch (e) { logger.warn(`[getSharedServers] Member fetch error for ${user.id}:`, e?.message); } + } + + if (!isMember) continue; + + const guildChannels = guild.channels + ? [...guild.channels.values()] + : []; + const allChannels = guildChannels + .map(c => Dashboard.convertChannel(c)) + .filter(c => !c.isCategory); + const channelIds = guildChannels.map(c => c.id); + + shared.push({ + name: guild.name, + id: guild.id, + icon: guild.icon + ? `https://cdn.fluxer.app/icons/${guild.id}/${guild.icon}.webp` + : null, + description: guild.description ?? null, + ownerId: guild.ownerId ?? null, + channels: allChannels, + channelIds: channelIds, + voiceChannels: allChannels.filter(c => c.isVoice), + }); + } + + return shared; + }, + + /** + * Create and attach a paginated message to the given message. + * @this {import('./Bot.mjs').Remix} + * @param {string} form - The form/locale key for the page title. + * @param {string} content - The full content to paginate. + * @param {object} msg - The message wrapper. + * @param {number} linesPerPage - Maximum lines per page. + */ + pagination(form, content, msg, linesPerPage) { + this.messages.initPagination( + new PageBuilder(content).setForm(form).setMaxLines(linesPerPage), + msg + ); + }, +}; + +export default BotVoiceMixin; +export { BotVoiceMixin }; diff --git a/src/core/Locale.mjs b/src/core/Locale.mjs new file mode 100644 index 0000000..514270d --- /dev/null +++ b/src/core/Locale.mjs @@ -0,0 +1,210 @@ +/** @module src/core/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/core/Logger.mjs b/src/core/Logger.mjs new file mode 100644 index 0000000..b7b0536 --- /dev/null +++ b/src/core/Logger.mjs @@ -0,0 +1,199 @@ +/** @module src/core/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 }; + +/** + * Log-storm suppression for identical repeated `error`/`warn` lines. + * The first occurrence is always emitted; identical repeats within a 60s + * window are counted silently, and once per window a single pulse line with + * the repeat count is emitted instead. Bounds worst-case volume of any hot + * retry loop to one line per minute instead of millions. + * @private + * @type {Map} + */ +const _stormGuard = new Map(); +const STORM_WINDOW_MS = 60_000; +const STORM_MAX_KEYS = 128; + +/** + * Decide whether an error/warn line should be emitted, and with what suffix. + * @private + * @param {string} level - Log level ("error" | "warn"). + * @param {string} tag - Caller tag (e.g. "[Redis/Main]"). + * @param {Array<*>} args - Message arguments. + * @returns {{emit: boolean, suffix: string}} Whether to emit, and the pulse suffix. + */ +function _stormGate(level, tag, args) { + const key = level + "|" + tag + "|" + args.map(a => (typeof a === "string" ? a : String(a))).join(" "); + const now = Date.now(); + const st = _stormGuard.get(key); + if (st === undefined) { + if (_stormGuard.size >= STORM_MAX_KEYS) { + // Evict the oldest key to bound memory. + _stormGuard.delete(_stormGuard.keys().next().value); + } + _stormGuard.set(key, { n: 0, start: now }); + return { emit: true, suffix: "" }; + } + st.n++; + if (now - st.start >= STORM_WINDOW_MS) { + const n = st.n; + st.n = 0; + st.start = now; + return { emit: true, suffix: `── identical line suppressed ${n}x in the last 60s` }; + } + return { emit: false, suffix: "" }; +} + +/** + * Reset the log-storm suppression state (used by tests). + * @returns {void} + */ +export function _resetStormGuard() { + _stormGuard.clear(); +} + +/** + * 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) { + const g = _stormGate("error", tag, args); + if (!g.emit) return; + console.error(`[${ts()}] ${tag}`, ...args, ...(g.suffix ? [g.suffix] : [])); + }, + /** + * 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?.enabled === false && _config?.warn !== true) return; + const g = _stormGate("warn", tag, args); + if (!g.emit) return; + console.warn(`[${ts()}] ${tag}`, ...args, ...(g.suffix ? [g.suffix] : [])); + }, + /** + * 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/dashboard/Dashboard.mjs b/src/dashboard/Dashboard.mjs index 635bebf..be84d54 100644 --- a/src/dashboard/Dashboard.mjs +++ b/src/dashboard/Dashboard.mjs @@ -2,29 +2,41 @@ * @module dashboard/Dashboard * @description Web dashboard backend controller. Manages Redis pub/sub communication * with the dashboard frontend, handles remote function calls (join, play, pause, etc.), - * and provides static data-conversion helpers for Discord entities. + * and provides static data-conversion helpers for bot entities. + * + * Base class of the dashboard split: class fields, construction (including the + * Redis request-routing switch), the Redis/MySQL lifecycle, setBotId and the + * player/user update broadcasts. The remote RPC handler methods (runFunction, + * confirmLogin, authorization helpers) live in RpcHandlersMixin.mjs and the static + * conversion helpers in Serializers.mjs — both are attached at the bottom of this file. */ -import { CommandBuilder, CommandHandler, Option } from "../CommandHandler.mjs"; +import { CommandBuilder, CommandHandler, Option } from "../commands/index.mjs"; import { PermissionFlags } from "@fluxerjs/core"; -import Player from "../Player.mjs"; -import { Utils, cleanId } from "../Utils.mjs"; -import { DatabaseManager } from "./DatabaseManager.mjs"; +import Player from "../music/player/index.mjs"; +import { Utils, cleanId } from "../utils/Utils.mjs"; +import { DatabaseManager } from "../db/DatabaseManager.mjs"; import { RedisHandler } from "./RedisHandler.mjs"; -import { logger } from "../constants/Logger.mjs"; -import { iterateVoiceStates } from "../constants/VoiceStateResolver.mjs"; +import { logger } from "../core/Logger.mjs"; +import { iterateVoiceStates } from "../voice/VoiceStateResolver.mjs"; +import { applyMixins } from "../utils/mixins.mjs"; +import RpcHandlersMixin from "./RpcHandlersMixin.mjs"; +import Serializers from "./Serializers.mjs"; /** * @class * @description Orchestrates the web dashboard: wires up Redis request/response handling, - * converts Discord data for the frontend, and exposes remote control functions. + * converts bot data for the frontend, and exposes remote control functions. */ -export class Dashboard { +class Dashboard { /** @type {boolean} Whether the dashboard is enabled. */ enabled = false; /** @type {number} Login code expiry time in milliseconds (default 6 hours). */ expiryTime = 1000 * 60 * 60 * 6; + /** @private */ + _playerUpdateTimers = new Map(); + /** * Create a new Dashboard instance. * @param {object} remix - The main bot (Remix) instance. @@ -134,10 +146,9 @@ export class Dashboard { }); } - /** * Set the bot ID for the Redis platform prefix. - * @param {string} botId - The bot's Discord user ID. + * @param {string} botId - The bot's user ID. */ setBotId(botId) { if (!this.enabled || !this.redis) return; @@ -145,590 +156,6 @@ export class Dashboard { this.redis.readyMessage(); } - - /** - * Execute a remote dashboard function (e.g. join, pause, volume). - * @async - * @param {object} params - Function call parameters. - * @param {string} params.func - The function name to execute. - * @param {object} [params.data] - Additional data for the function. - * @param {string} [params.data.user] - The Discord user ID making the request. - * @returns {Promise} Result object with `message` or `error`. - */ - async runFunction(params) { - let user; - if (params.data?.user) { - try { - user = await this.remix.client.users.fetch(params.data.user); - } catch (e) { - logger.dashboard("[Dashboard] Error:", e); - return { error: "Invalid User" }; - } - } - switch (params.func) { - case "join": { - if (!user) return { error: "Invalid user" }; - let voiceChannel, textChannel; - try { - const chMgr = this.remix.client.channels; - if (typeof chMgr.fetch === "function") { - voiceChannel = await chMgr.fetch(params.data.channel).catch(() => null); - if (params.data.text) textChannel = await chMgr.fetch(params.data.text).catch(() => null); - } else { - voiceChannel = chMgr.get(params.data.channel); - if (params.data.text) textChannel = chMgr.get(params.data.text); - } - if (!voiceChannel) return { error: "Voice channel not found" }; - - const isText = (ch) => ch && (ch.type === 0 || ch.type === 5 || ch.type === 13 || - (typeof ch.isText === "function" && ch.isText())); - - if (!isText(textChannel)) { - 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); - const sysCh = guild.systemChannelId - ? channelValues.find(c => (c.id ?? c._id) === guild.systemChannelId && isText(c)) - : null; - textChannel = sysCh ?? channelValues.find(c => isText(c)) ?? null; - } - if (!textChannel) { - logger.dashboard("[Dashboard] No text channel found for guild", voiceChannel.guildId, "— voice channel will be used as fallback"); - textChannel = voiceChannel; - } - } - } catch (e) { - logger.dashboard("[Dashboard] Error:", e); - return { error: "Invalid Channel" }; - } - const authErr = await this._authorizeUserInGuild(user, voiceChannel.guildId); - if (authErr) return { error: authErr }; - if (this.remix.players.playerMap.has(voiceChannel.id)) { - 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)); - try { - const pubChannel = this.remix.redis?.publisher ?? this.remix.redis; - if (pubChannel && typeof pubChannel.publish === "function") { - pubChannel.publish("fluxer:player_" + voiceChannel.id, JSON.stringify({ - type: "join", - data: String(user.id) - })); - } - } catch (e) { logger.warn("[Dashboard] Error:", e?.message); } - } - return { message: "Already Connected" }; - } - const fakeMsg = { - channel: textChannel, - message: { guildId: voiceChannel.guildId }, - reply: async () => ({ edit: async () => {}, catch: () => {} }), - }; - this.remix.players.initPlayer(fakeMsg, voiceChannel.id); - const newPlayer = this.remix.players.playerMap.get(voiceChannel.id); - if (newPlayer && user) { - if (!newPlayer._dashboardUsers) newPlayer._dashboardUsers = []; - if (!newPlayer._dashboardUsers.includes(String(user.id))) { - newPlayer._dashboardUsers.push(String(user.id)); - } - } - return { message: "Joining" }; - } - - case "pausePlayback": { - const player = this._getPlayerById(params.data.player); - if (!player) return { error: "Player not found" }; - const authErr = this._authorizePlayerControl(user, player); - if (authErr) return { error: authErr }; - const msg = player.pause() || "Paused successfully"; - return { message: msg }; - } - - case "resumePlayback": { - const player = this._getPlayerById(params.data.player); - if (!player) return { error: "Player not found" }; - const authErr = this._authorizePlayerControl(user, player); - if (authErr) return { error: authErr }; - const msg = player.resume() || "Resumed successfully"; - return { message: msg }; - } - - case "skip": { - const player = this._getPlayerById(params.data.player); - if (!player) return { error: "Player not found" }; - const authErr = this._authorizePlayerControl(user, player); - if (authErr) return { error: authErr }; - const msg = player.skip() || "Skipped song"; - return { message: msg }; - } - - case "volume": { - const player = this._getPlayerById(params.data.player); - if (!player) return { error: "Player not found" }; - const authErr = this._authorizePlayerControl(user, player); - if (authErr) return { error: authErr }; - const vol = Number(params.data.volume); - if (isNaN(vol) || vol < 0 || vol > 2) return { - error: "Volume must be between 0 and 2" }; - const msg = player.setVolume(vol); - return { message: msg }; - } - - case "addToQueue": { - const player = this._getPlayerById(params.data.player); - if (!player) return { error: "Player not found" }; - if (!user) return { error: "Invalid user" }; - const authErr = this._authorizePlayerControl(user, player); - if (authErr) return { error: authErr }; - const type = params.data.type; - const query = params.data.query; - if (!query || typeof query !== "string") return { error: "Missing or invalid query" }; - if (query.length > 500) return { error: "Query too long (max 500 characters)" }; - if (type === "radio") { - const radio = this.remix.config.radio.find(e => e.name === query); - if (!radio) return { error: "Invalid radio station" }; - player.playRadio(radio); - return { message: "Adding radio station" }; - } - if (/^(javascript|data|vbscript):/i.test(query.trim())) { - return { error: "Invalid query protocol" }; - } - player.play(query); - return { message: "Adding to queue" }; - } - - case "testConnection": { - return { success: true }; - } - - case "voiceState": { - if (!user) return { channel: null }; - const userId = cleanId(user.id); - if (this.remix.voiceCache) { - for (const [mapUserId, info] of this.remix.voiceCache) { - if (cleanId(mapUserId) === userId && info.channelId) { - const ch = this.remix.client.channels.get(info.channelId); - return { - channelId: info.channelId, - channel: ch ? Dashboard.convertChannel(ch) : { id: info.channelId, name: "Unknown" }, - guildId: info.guildId ?? ch?.guildId ?? null, - }; - } - } - } - const guilds = this.remix.client.guilds; - const guildValues = guilds && typeof guilds.values === "function" - ? [...guilds.values()] : guilds ? Object.values(guilds) : []; - for (const guild of guildValues) { - for (const vs of iterateVoiceStates(guild)) { - const stateUserId = cleanId(vs.userId); - if (stateUserId === userId && vs.channelId) { - const ch = this.remix.client.channels.get(vs.channelId); - return { - channelId: vs.channelId, - channel: ch ? Dashboard.convertChannel(ch) : { id: vs.channelId, name: "Unknown" }, - guildId: guild.id, - }; - } - } - } - return { channel: null }; - } - - case "leave": { - if (!user) return { error: "Invalid user" }; - 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 }; - if (player._dashboardUsers && user) { - const idx = player._dashboardUsers.indexOf(String(user.id)); - if (idx !== -1) player._dashboardUsers.splice(idx, 1); - } - if (player._dashboardUsers && player._dashboardUsers.length > 0) { - try { - const pubChannel = this.remix.dashboard?.redis?.client ?? this.remix.redis?.client; - if (pubChannel && typeof pubChannel.publish === "function") { - pubChannel.publish("fluxer:player_" + playerId, JSON.stringify({ - type: "leave", - data: String(user.id) - })); - } - } catch (e) { logger.warn("[Dashboard] Error:", e?.message); } - return { message: "Left channel" }; - } - try { - await player.leave(); - return { message: "Left channel" }; - } catch (e) { - return { error: "Failed to leave: " + e.message }; - } - } - - default: - return { error: "Unknown function: " + (params.func ?? "(none)") }; - } - } - - - /** - * Verify that the given user is allowed to control the given player. - * Bot owners bypass the check; otherwise the user must be in the same voice channel. - * @private - * @param {object} user - The Discord user attempting to control the player. - * @param {object} player - The Player instance to control. - * @returns {string|null} An error message if unauthorized, or null if authorized. - */ - _authorizePlayerControl(user, player) { - if (user && this.remix.handler?.owners?.includes?.(user.id)) return null; - if (!user) return "User not provided"; - - const cleanUserId = cleanId(user.id); - const cleanChanId = cleanId(player._channelId); - if (!cleanChanId) return "Player has no active channel"; - - const observed = this.remix.voiceCache; - if (observed) { - const guildId = cleanId(player._guildId); - const userLoc = observed.get(cleanUserId, guildId || undefined); - if (userLoc) { - const infoChannelId = cleanId(userLoc.channelId); - if (infoChannelId === cleanChanId) return null; - } - for (const [mapUserId, info] of observed) { - if (cleanId(mapUserId) === cleanUserId) { - const infoChannelId = cleanId(info.channelId); - if (infoChannelId === cleanChanId) return null; - } - } - } - - return "You must be in the same voice channel as the bot to control playback"; - } - - /** - * Verify that the given user is a member of the specified guild. - * Bot owners bypass the check. - * @private - * @async - * @param {object} user - The Discord user to verify. - * @param {string} guildId - The guild ID to check membership in. - * @returns {Promise} An error message if not a member, or null if authorized. - */ - async _authorizeUserInGuild(user, guildId) { - if (this.remix.handler?.owners?.includes?.(user.id)) return null; - - try { - const guild = this.remix.client.guilds.get(guildId); - if (!guild) return "Server not found"; - const member = await guild.members.fetch(user.id).catch(() => null); - if (!member) return "You are not a member of this server"; - return null; - } catch (e) { - return "Failed to verify membership: " + e.message; - } - } - - /** - * Look up a player by channel ID, guild ID, or player ID. - * @private - * @param {string} id - Channel ID, guild ID, or player ID. - * @returns {object|null} The matching Player instance, or null. - */ - _getPlayerById(id) { - return this.remix.players.playerMap.get(id) - ?? [...this.remix.players.playerMap.values()].find( - p => p._channelId === id || p._guildId === id - ) - ?? null; - } - - - /** - * Convert a Discord user object to a dashboard-safe plain object. - * @static - * @param {object} user - The Discord user. - * @returns {{ id: string, username: string, displayName: string, avatar: { url: string } }} - */ - static convertUser(user) { - let avatarUrl = ""; - if (user.avatar) { - avatarUrl = `https://fluxerusercontent.com/avatars/${user.id}/${user.avatar}.webp`; - } else if (typeof user.displayAvatarURL === "function") { - try { avatarUrl = user.displayAvatarURL() ?? ""; } catch(e) { logger.warn("[Dashboard] displayAvatarURL:", e?.message); } - } else if (typeof user.avatarURL === "function") { - try { avatarUrl = user.avatarURL() ?? ""; } catch(e) { logger.warn("[Dashboard] avatarURL:", e?.message); } - } - if (!avatarUrl) { - avatarUrl = `https://fluxerusercontent.com/embed/avatars/${parseInt(user.id?.slice(-4) ?? "0") % 5}.png`; - } - return { - id: user.id, - username: user.username, - displayName: user.displayName ?? user.globalName ?? user.username, - avatar: { - url: avatarUrl, - }, - }; - } - - /** - * Convert a video/track object to a dashboard-safe plain object. - * @static - * @param {object} vid - The video/track object from the player queue. - * @returns {object|null} Sanitised video data, or null if input is falsy. - */ - static convertVideo(vid) { - if (!vid) return null; - const durationMs = - typeof vid.duration === "number" ? vid.duration : - typeof vid.duration === "object" && vid.duration?.seconds !== null ? vid.duration.seconds * 1000 : - 0; - return { - title: vid.title, - url: vid.type === "radio" ? vid.author?.url : vid.url, - videoId: vid.videoId, - type: vid.type, - duration: vid.type === "radio" ? "--:--" : Utils.prettifyMS(durationMs), - description: vid.description, - artist: { - name: vid.author?.name ?? vid.artist, - url: vid.author?.url, - }, - thumbnail: vid.thumbnail, - }; - } - - /** - * Convert a Discord channel to a dashboard-safe plain object, including - * voice participant info for voice channels. - * @static - * @param {object} channel - The Discord channel. - * @returns {object} Sanitised channel data. - */ - static convertChannel(channel) { - const type = channel.type ?? 0; - const isVoice = channel.isVoice?.() || type === 2; - const isCategory = type === 4; - const isText = !isVoice && !isCategory && ( - type === 0 || type === 5 || type === 13 || - (typeof channel.isText === "function" && channel.isText()) - ); - let voiceParticipants = []; - if (isVoice) { - const guild = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId); - for (const vs of iterateVoiceStates(guild)) { - const scId = cleanId(vs.channelId); - const chId = cleanId(channel?.id); - if (scId === chId) { - const user = guild?.members?.get?.(vs.userId)?.user; - if (user && !user.bot) voiceParticipants.push(Dashboard.convertUser(user)); - } - } - } - - return { - name: channel.name, - displayName: channel.name, - id: channel.id, - icon: null, - description: channel.topic ?? null, - type, - isVoice, - isCategory, - isText, - parentId: channel.parentId ?? channel.parent_id ?? null, - voiceParticipants, - mature: channel.nsfw ?? false, - serverId: channel.guildId, - }; - } - - /** - * Convert a Discord guild (server) to a dashboard-safe plain object with channels. - * @static - * @param {object} guild - The Discord guild. - * @returns {object} Sanitised server data including channels and voice channels. - */ - static convertServer(guild) { - const channelStore = guild.channels; - const channelIds = channelStore && typeof channelStore.keys === "function" - ? [...channelStore.keys()] - : []; - const channelValues = channelStore && typeof channelStore.values === "function" - ? [...channelStore.values()] - : []; - const allChannels = channelValues - .map(Dashboard.convertChannel) - .filter(c => !c.isCategory); - - let iconUrl = null; - if (guild.icon) { - iconUrl = `https://fluxerusercontent.com/icons/${guild.id}/${guild.icon}.webp`; - } else if (typeof guild.iconURL === "function") { - try { iconUrl = guild.iconURL() ?? null; } catch (e) { logger.warn("[Dashboard] iconURL error:", e?.message); iconUrl = null; } - } - - return { - name: guild.name, - id: guild.id, - icon: iconUrl, - channelIds, - description: guild.description ?? null, - ownerId: guild.ownerId, - channels: allChannels, - voiceChannels: allChannels.filter(c => c.isVoice), - }; - } - - /** - * Convert a Discord guild to a lightweight summary object (no channels). - * @static - * @param {object} guild - The Discord guild. - * @returns {{ name: string, id: string, icon: string|null, description: string|null, ownerId: string|null }} - */ - static convertServerSummary(guild) { - let iconUrl = null; - if (guild.icon) { - iconUrl = `https://fluxerusercontent.com/icons/${guild.id}/${guild.icon}.webp`; - } else if (typeof guild.iconURL === "function") { - try { iconUrl = guild.iconURL() ?? null; } catch (e) { logger.warn("[Dashboard] iconURL error:", e?.message); iconUrl = null; } - } - return { - name: guild.name, - id: guild.id, - icon: iconUrl, - description: guild.description ?? null, - ownerId: guild.ownerId, - }; - } - - /** - * Convert a Player instance to a dashboard-safe serialisable object. - * Includes queue, users, channel, and server info. - * @static - * @param {object} player - The Player instance. - * @returns {object} Sanitised player data. - */ - static convertPlayer(player) { - const channelId = player._channelId; - const channel = channelId ? player.client?.channels?.get(channelId) : null; - const guild = channel?.guild ?? (player._guildId ? player.client?.guilds?.get(player._guildId) : null); - const cleanChannelId = channelId ? cleanId(channelId) : ""; - const cleanGuildId = player._guildId ? cleanId(player._guildId) : ""; - - const queue = player.queue ?? { loop: false, songLoop: false, current: null, data: [] }; - - return { - loop: (queue.loop ? 1 : 0) + (queue.songLoop ? 2 : 0), - paused: !!player._paused, - volume: Number.isFinite(player.preferredVolume) ? player.preferredVolume * 100 : 100, - queue: { - current: Dashboard.convertVideo(queue.current), - data: Array.isArray(queue.data) ? queue.data.slice(0, 500).map(v => Dashboard.convertVideo(v)) : [], - }, - users: (() => { - if (!channel) return player._dashboardUsers ?? []; - const g = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId); - const ids = []; - const seen = new Set(); - for (const vs of iterateVoiceStates(g)) { - const scId = cleanId(vs.channelId); - const chId = cleanId(channel?.id); - if (scId === chId) { - const memberId = vs.userId; - if (memberId) { ids.push(memberId); seen.add(memberId); } - } - } - const vc = player._voiceCache ?? player._observedVoiceUsers; - if (vc && cleanChannelId && cleanGuildId) { - if (typeof vc.getHumansInChannel === "function") { - const channelHumans = vc.getHumansInChannel(cleanGuildId, cleanChannelId); - for (const hid of channelHumans) { - if (seen.has(hid)) continue; - const botId = player.client?.user?.id; - if (botId && String(hid) === String(botId)) continue; - ids.push(String(hid)); - seen.add(hid); - } - } else { - for (const [mapUserId, info] of vc) { - if (seen.has(mapUserId)) continue; - const infoCh = cleanId(info.channelId); - const infoG = cleanId(info.guildId); - if (infoCh === cleanChannelId && infoG === cleanGuildId) { - const botId = player.client?.user?.id; - if (botId && String(mapUserId) === String(botId)) continue; - ids.push(String(mapUserId)); - seen.add(mapUserId); - } - } - } - } - if (player._dashboardUsers) { - for (const du of player._dashboardUsers) { - if (!seen.has(du)) { ids.push(du); seen.add(du); } - } - } - return ids; - })(), - channel: channel ? Dashboard.convertChannel(channel) : null, - server: guild ? Dashboard.convertServerSummary(guild) : null, - }; - } - - /** - * Convert a command option to a dashboard-safe plain object. - * @static - * @param {object} opt - The command option. - * @returns {object} Sanitised option data. - */ - static convertOption(opt) { - return { - type: opt.type, - name: opt.name, - choices: opt.choices, - description: opt.description, - required: opt.required, - uid: opt.uid, - defaultValue: opt.defaultValue, - dynamicDefaultPresent: !!opt.dynamicDefault, - }; - } - - /** - * Convert a command (and its subcommands/options) to a dashboard-safe plain object. - * @static - * @param {object} com - The command object. - * @param {object} commands - The CommandHandler instance (for usage generation). - * @returns {object} Sanitised command data. - */ - static convertCommand(com, commands) { - return { - name: com.name, - description: com.description, - uid: com.uid, - aliases: com.aliases, - subcommands: com.subcommands.map(c => Dashboard.convertCommand(c, commands)), - category: com.category, - examples: com.examples, - usage: commands.helpHandler?.commandUsage?.(com, { - message: { guildId: null }, - }) ?? null, - options: com.options.map(o => Dashboard.convertOption(o)), - }; - } - - - /** @private */ - _playerUpdateTimers = new Map(); - /** * Broadcast a player state update to the dashboard via Redis. * Debounces non-init/close updates by 500ms. @@ -784,7 +211,7 @@ export class Dashboard { /** * Broadcast a user update to the global users Redis channel. * @param {object} details - The update payload. - * @param {object} user - The Discord user. + * @param {object} user - The user. */ userUpdate(details, user) { if (!this.enabled) return; @@ -798,48 +225,21 @@ export class Dashboard { /** * Send a lightweight update to the user-specific Redis channel. * @param {object} details - The update payload. - * @param {object} user - The Discord user. + * @param {object} user - The user. */ updateUser(details, user) { if (!this.enabled) return; const channel = this.redis.platform + ":user_" + user.id; this.redis.send(channel, JSON.stringify(details)); } - - - /** - * Verify a dashboard login code for a user. - * @async - * @param {string} user - The Discord user ID. - * @param {string} code - The login code to verify. - * @returns {Promise} An error message if verification fails, or null on success. - */ - async confirmLogin(user, code) { - if (!this.enabled) return "Dashboard not enabled."; - if (!this.db) return "Dashboard database not configured."; - - let res; - try { - res = await this.db.execute("SELECT * FROM login_codes WHERE user=? AND (verified IS NULL OR verified !== true)", [user]); - } catch (e) { - const id = Utils.uid(); - logger.dashboard("[Dashboard] MySQL error, id:", id, e); - return "An error occurred, please contact an administrator if this happens again. Error id: `" + id + "`"; - } - - 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; - 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; - } - } - - return "Invalid code."; - } } + +// Attach the split-out concerns: the remote RPC handler methods (runFunction, +// confirmLogin and the authorization helpers) from RpcHandlersMixin. +applyMixins(Dashboard, RpcHandlersMixin); + +// Re-attach the static conversion helpers (convertUser, convertChannel, +// convertPlayer, …) so external `Dashboard.convertX(...)` call sites keep working. +Object.assign(Dashboard, Serializers); + +export { Dashboard }; diff --git a/src/dashboard/RedisHandler.mjs b/src/dashboard/RedisHandler.mjs index b35444f..3403d7d 100644 --- a/src/dashboard/RedisHandler.mjs +++ b/src/dashboard/RedisHandler.mjs @@ -6,20 +6,23 @@ */ import { createClient } from "redis"; -import { logger } from "../constants/Logger.mjs"; +import { logger } from "../core/Logger.mjs"; /** * Default reconnection strategy for Redis sockets. - * @param {object} options - Reconnection options from the Redis client. - * @param {number} options.totalRetryTime - Cumulative retry time so far. - * @param {number} options.attempt - Current retry attempt number. - * @returns {number|Error} Delay in ms before next retry, or an Error to stop retrying. + * redis@5 calls the strategy as `strategy(retries, cause)` where `retries` is a + * plain NUMBER of reconnect attempts made so far — NOT an options object. + * The previous version read cumulative-time / attempt-count properties off + * that number, which produced NaN; NaN passes redis@5's `typeof !== "number"` + * gate and collapses `setTimeout(NaN)` to a ~1ms hot-retry loop (log storm). + * Strategy now: linear ramp 0.5s -> 5s, then a steady 15s retry pulse. It + * never exhausts, so the dashboard auto-recovers whenever Redis returns. + * @param {number} retries - Reconnect attempts made so far (redis@5 argument). + * @returns {number} Delay in ms before the next reconnect attempt. */ -const DEFAULT_RETRY_STRATEGY = (options) => { - if (options.totalRetryTime > 60_000) { - return new Error("Redis reconnection exhausted after 60s"); - } - return Math.min(options.attempt * 500, 5_000); +const DEFAULT_RETRY_STRATEGY = (retries) => { + if (!Number.isFinite(retries)) return 15_000; // defensive: wrong-shape argument + return retries < 10 ? Math.min(retries * 500, 5_000) : 15_000; }; /** @@ -46,12 +49,12 @@ export class RedisHandler { constructor(opts = {}) { this.platform = opts.platform ?? "fluxer"; - const clientOpts = { - ...opts, - socket: { - ...(opts.socket ?? {}), - reconnectStrategy: DEFAULT_RETRY_STRATEGY, - }, + // `url` (and any explicit socket options) come from config; the retry + // strategy is always pinned so misconfig can never cause a hot retry loop. + const { platform: _platform, ...clientOpts } = { ...opts }; + clientOpts.socket = { + ...(clientOpts.socket ?? {}), + reconnectStrategy: DEFAULT_RETRY_STRATEGY, }; this.client = createClient(clientOpts); @@ -74,51 +77,58 @@ export class RedisHandler { * @async */ async _connect() { - try { - await this.client.connect(); - logger.redis("[Redis/Main] Connected"); - this.readyMessage(); - } catch (e) { - logger.error("[Redis/Main] Initial connection failed:", e.message); - } - - try { - await this.subscriber.connect(); - logger.redis("[Redis/Subscriber] Connected"); - - this.subscriber.subscribe("request", async (m) => { + // Connect both clients CONCURRENTLY. The previous sequential awaits made + // the subscriber wait behind the main client's retry loop: while Redis was + // down, the subscriber never even attempted to connect. + this.client.connect() + .then(() => { if (this._destroyed) return; - try { - const payload = JSON.parse(m); - if (payload.platform !== this.platform) return; - if (typeof this.handleRequest !== "function") return; - const result = await this.handleRequest(payload.content); - this.send("response", JSON.stringify({ - id: payload.id, - content: result, - })); - } catch (e) { - logger.error("[Redis/Subscriber] Request handler error:", e.message); - } + logger.redis("[Redis/Main] Connected"); + this.readyMessage(); + }) + .catch((e) => { + logger.error("[Redis/Main] Initial connection failed:", e.message); }); - this.subscriber.subscribe("info", (m) => { + this.subscriber.connect() + .then(() => { if (this._destroyed) return; - try { - const data = JSON.parse(m); - if (data.platform !== "backend") return; - if (data.type !== "requestConnected") return; - this.readyMessage(); - } catch (e) { - logger.warn("[Redis/Subscriber] Info handler error:", e.message); - } + logger.redis("[Redis/Subscriber] Connected"); + + this.subscriber.subscribe("request", async (m) => { + if (this._destroyed) return; + try { + const payload = JSON.parse(m); + if (payload.platform !== this.platform) return; + if (typeof this.handleRequest !== "function") return; + const result = await this.handleRequest(payload.content); + this.send("response", JSON.stringify({ + id: payload.id, + content: result, + })); + } catch (e) { + logger.error("[Redis/Subscriber] Request handler error:", e.message); + } + }); + + this.subscriber.subscribe("info", (m) => { + if (this._destroyed) return; + try { + const data = JSON.parse(m); + if (data.platform !== "backend") return; + if (data.type !== "requestConnected") return; + this.readyMessage(); + } catch (e) { + logger.warn("[Redis/Subscriber] Info handler error:", e.message); + } + }); + this._pingInterval = setInterval(() => { + this.send(this.platform + ":ping", "" + Date.now()); + }, 10000); + }) + .catch((e) => { + logger.error("[Redis/Subscriber] Initial connection failed:", e.message); }); - this._pingInterval = setInterval(() => { - this.send(this.platform + ":ping", "" + Date.now()); - }, 10000); - } catch (e) { - logger.error("[Redis/Subscriber] Initial connection failed:", e.message); - } } /** @@ -173,8 +183,16 @@ export class RedisHandler { this._destroyed = true; if (this._pingInterval) { clearInterval(this._pingInterval); this._pingInterval = null; } if (this._readyTimer) { clearTimeout(this._readyTimer); this._readyTimer = null; } - try { await this.subscriber?.quit(); } catch(e) { logger.warn("[Redis/Subscriber] Quit error:", e?.message); } - try { await this.client?.quit(); } catch(e) { logger.warn("[Redis/Main] Quit error:", e?.message); } + // quit() waits for a live connection; on a still-connecting/down client it + // would pend forever (bot shutdown hang). Hard-disconnect instead. + try { + if (this.subscriber?.isReady) await this.subscriber.quit(); + else this.subscriber?.disconnect(); + } catch(e) { logger.warn("[Redis/Subscriber] Quit error:", e?.message); } + try { + if (this.client?.isReady) await this.client.quit(); + else this.client?.disconnect(); + } catch(e) { logger.warn("[Redis/Main] Quit error:", e?.message); } logger.redis("[Redis] Connections closed gracefully"); } } diff --git a/src/dashboard/RpcHandlersMixin.mjs b/src/dashboard/RpcHandlersMixin.mjs new file mode 100644 index 0000000..2abcab3 --- /dev/null +++ b/src/dashboard/RpcHandlersMixin.mjs @@ -0,0 +1,362 @@ +/** + * @module dashboard/RpcHandlersMixin + * @description Remote-control concern for {@link Dashboard}: the dashboard RPC + * "function" dispatch (runFunction — join / pausePlayback / resumePlayback / skip / + * volume / addToQueue / testConnection / voiceState / leave), the login-code + * verification (confirmLogin) and the authorization / player-lookup helpers. + * + * These methods are applied onto the Dashboard class prototype via + * {@link applyMixins} — `this` is a Dashboard instance. + */ + +import { Dashboard } from "./Dashboard.mjs"; +import { Utils, cleanId } from "../utils/Utils.mjs"; +import { logger } from "../core/Logger.mjs"; +import { iterateVoiceStates } from "../voice/VoiceStateResolver.mjs"; + +/** + * @type {object} + * @description RPC handlers mixin — applied to Dashboard. + */ +const RpcHandlersMixin = { + /** + * Execute a remote dashboard function (e.g. join, pause, volume). + * @async + * @param {object} params - Function call parameters. + * @param {string} params.func - The function name to execute. + * @param {object} [params.data] - Additional data for the function. + * @param {string} [params.data.user] - The user ID making the request. + * @returns {Promise} Result object with `message` or `error`. + */ + async runFunction(params) { + let user; + if (params.data?.user) { + try { + user = await this.remix.client.users.fetch(params.data.user); + } catch (e) { + logger.dashboard("[Dashboard] Error:", e); + return { error: "Invalid User" }; + } + } + switch (params.func) { + case "join": { + if (!user) return { error: "Invalid user" }; + let voiceChannel, textChannel; + try { + const chMgr = this.remix.client.channels; + if (typeof chMgr.fetch === "function") { + voiceChannel = await chMgr.fetch(params.data.channel).catch(() => null); + if (params.data.text) textChannel = await chMgr.fetch(params.data.text).catch(() => null); + } else { + voiceChannel = chMgr.get(params.data.channel); + if (params.data.text) textChannel = chMgr.get(params.data.text); + } + if (!voiceChannel) return { error: "Voice channel not found" }; + + const isText = (ch) => ch && (ch.type === 0 || ch.type === 5 || ch.type === 13 || + (typeof ch.isText === "function" && ch.isText())); + + if (!isText(textChannel)) { + 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); + const sysCh = guild.systemChannelId + ? channelValues.find(c => (c.id ?? c._id) === guild.systemChannelId && isText(c)) + : null; + textChannel = sysCh ?? channelValues.find(c => isText(c)) ?? null; + } + if (!textChannel) { + logger.dashboard("[Dashboard] No text channel found for guild", voiceChannel.guildId, "— voice channel will be used as fallback"); + textChannel = voiceChannel; + } + } + } catch (e) { + logger.dashboard("[Dashboard] Error:", e); + return { error: "Invalid Channel" }; + } + const authErr = await this._authorizeUserInGuild(user, voiceChannel.guildId); + if (authErr) return { error: authErr }; + if (this.remix.players.playerMap.has(voiceChannel.id)) { + 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)); + try { + const pubChannel = this.remix.redis?.publisher ?? this.remix.redis; + if (pubChannel && typeof pubChannel.publish === "function") { + pubChannel.publish("fluxer:player_" + voiceChannel.id, JSON.stringify({ + type: "join", + data: String(user.id) + })); + } + } catch (e) { logger.warn("[Dashboard] Error:", e?.message); } + } + return { message: "Already Connected" }; + } + const fakeMsg = { + channel: textChannel, + message: { guildId: voiceChannel.guildId }, + reply: async () => ({ edit: async () => {}, catch: () => {} }), + }; + this.remix.players.initPlayer(fakeMsg, voiceChannel.id); + const newPlayer = this.remix.players.playerMap.get(voiceChannel.id); + if (newPlayer && user) { + if (!newPlayer._dashboardUsers) newPlayer._dashboardUsers = []; + if (!newPlayer._dashboardUsers.includes(String(user.id))) { + newPlayer._dashboardUsers.push(String(user.id)); + } + } + return { message: "Joining" }; + } + + case "pausePlayback": { + const player = this._getPlayerById(params.data.player); + if (!player) return { error: "Player not found" }; + const authErr = this._authorizePlayerControl(user, player); + if (authErr) return { error: authErr }; + const msg = player.pause() || "Paused successfully"; + return { message: msg }; + } + + case "resumePlayback": { + const player = this._getPlayerById(params.data.player); + if (!player) return { error: "Player not found" }; + const authErr = this._authorizePlayerControl(user, player); + if (authErr) return { error: authErr }; + const msg = player.resume() || "Resumed successfully"; + return { message: msg }; + } + + case "skip": { + const player = this._getPlayerById(params.data.player); + if (!player) return { error: "Player not found" }; + const authErr = this._authorizePlayerControl(user, player); + if (authErr) return { error: authErr }; + const msg = player.skip() || "Skipped song"; + return { message: msg }; + } + + case "volume": { + const player = this._getPlayerById(params.data.player); + if (!player) return { error: "Player not found" }; + const authErr = this._authorizePlayerControl(user, player); + if (authErr) return { error: authErr }; + const vol = Number(params.data.volume); + if (isNaN(vol) || vol < 0 || vol > 2) return { + error: "Volume must be between 0 and 2" }; + const msg = player.setVolume(vol); + return { message: msg }; + } + + case "addToQueue": { + const player = this._getPlayerById(params.data.player); + if (!player) return { error: "Player not found" }; + if (!user) return { error: "Invalid user" }; + const authErr = this._authorizePlayerControl(user, player); + if (authErr) return { error: authErr }; + const type = params.data.type; + const query = params.data.query; + if (!query || typeof query !== "string") return { error: "Missing or invalid query" }; + if (query.length > 500) return { error: "Query too long (max 500 characters)" }; + if (type === "radio") { + const radio = this.remix.config.radio.find(e => e.name === query); + if (!radio) return { error: "Invalid radio station" }; + player.playRadio(radio); + return { message: "Adding radio station" }; + } + if (/^(javascript|data|vbscript):/i.test(query.trim())) { + return { error: "Invalid query protocol" }; + } + player.play(query); + return { message: "Adding to queue" }; + } + + case "testConnection": { + return { success: true }; + } + + case "voiceState": { + if (!user) return { channel: null }; + const userId = cleanId(user.id); + if (this.remix.voiceCache) { + for (const [mapUserId, info] of this.remix.voiceCache) { + if (cleanId(mapUserId) === userId && info.channelId) { + const ch = this.remix.client.channels.get(info.channelId); + return { + channelId: info.channelId, + channel: ch ? Dashboard.convertChannel(ch) : { id: info.channelId, name: "Unknown" }, + guildId: info.guildId ?? ch?.guildId ?? null, + }; + } + } + } + const guilds = this.remix.client.guilds; + const guildValues = guilds && typeof guilds.values === "function" + ? [...guilds.values()] : guilds ? Object.values(guilds) : []; + for (const guild of guildValues) { + for (const vs of iterateVoiceStates(guild)) { + const stateUserId = cleanId(vs.userId); + if (stateUserId === userId && vs.channelId) { + const ch = this.remix.client.channels.get(vs.channelId); + return { + channelId: vs.channelId, + channel: ch ? Dashboard.convertChannel(ch) : { id: vs.channelId, name: "Unknown" }, + guildId: guild.id, + }; + } + } + } + return { channel: null }; + } + + case "leave": { + if (!user) return { error: "Invalid user" }; + 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 }; + if (player._dashboardUsers && user) { + const idx = player._dashboardUsers.indexOf(String(user.id)); + if (idx !== -1) player._dashboardUsers.splice(idx, 1); + } + if (player._dashboardUsers && player._dashboardUsers.length > 0) { + try { + const pubChannel = this.remix.dashboard?.redis?.client ?? this.remix.redis?.client; + if (pubChannel && typeof pubChannel.publish === "function") { + pubChannel.publish("fluxer:player_" + playerId, JSON.stringify({ + type: "leave", + data: String(user.id) + })); + } + } catch (e) { logger.warn("[Dashboard] Error:", e?.message); } + return { message: "Left channel" }; + } + try { + await player.leave(); + return { message: "Left channel" }; + } catch (e) { + return { error: "Failed to leave: " + e.message }; + } + } + + default: + return { error: "Unknown function: " + (params.func ?? "(none)") }; + } + }, + + /** + * Verify that the given user is allowed to control the given player. + * Bot owners bypass the check; otherwise the user must be in the same voice channel. + * @private + * @param {object} user - The user attempting to control the player. + * @param {object} player - The Player instance to control. + * @returns {string|null} An error message if unauthorized, or null if authorized. + */ + _authorizePlayerControl(user, player) { + if (user && this.remix.handler?.owners?.includes?.(user.id)) return null; + if (!user) return "User not provided"; + + const cleanUserId = cleanId(user.id); + const cleanChanId = cleanId(player._channelId); + if (!cleanChanId) return "Player has no active channel"; + + const observed = this.remix.voiceCache; + if (observed) { + const guildId = cleanId(player._guildId); + const userLoc = observed.get(cleanUserId, guildId || undefined); + if (userLoc) { + const infoChannelId = cleanId(userLoc.channelId); + if (infoChannelId === cleanChanId) return null; + } + for (const [mapUserId, info] of observed) { + if (cleanId(mapUserId) === cleanUserId) { + const infoChannelId = cleanId(info.channelId); + if (infoChannelId === cleanChanId) return null; + } + } + } + + return "You must be in the same voice channel as the bot to control playback"; + }, + + /** + * Verify that the given user is a member of the specified guild. + * Bot owners bypass the check. + * @private + * @async + * @param {object} user - The user to verify. + * @param {string} guildId - The guild ID to check membership in. + * @returns {Promise} An error message if not a member, or null if authorized. + */ + async _authorizeUserInGuild(user, guildId) { + if (this.remix.handler?.owners?.includes?.(user.id)) return null; + + try { + const guild = this.remix.client.guilds.get(guildId); + if (!guild) return "Server not found"; + const member = await guild.members.fetch(user.id).catch(() => null); + if (!member) return "You are not a member of this server"; + return null; + } catch (e) { + return "Failed to verify membership: " + e.message; + } + }, + + /** + * Look up a player by channel ID, guild ID, or player ID. + * @private + * @param {string} id - Channel ID, guild ID, or player ID. + * @returns {object|null} The matching Player instance, or null. + */ + _getPlayerById(id) { + return this.remix.players.playerMap.get(id) + ?? [...this.remix.players.playerMap.values()].find( + p => p._channelId === id || p._guildId === id + ) + ?? null; + }, + + /** + * Verify a dashboard login code for a user. + * @async + * @param {string} user - The user ID. + * @param {string} code - The login code to verify. + * @returns {Promise} An error message if verification fails, or null on success. + */ + async confirmLogin(user, code) { + if (!this.enabled) return "Dashboard not enabled."; + if (!this.db) return "Dashboard database not configured."; + + let res; + try { + res = await this.db.execute("SELECT * FROM login_codes WHERE user=? AND (verified IS NULL OR verified !== true)", [user]); + } catch (e) { + const id = Utils.uid(); + logger.dashboard("[Dashboard] MySQL error, id:", id, e); + return "An error occurred, please contact an administrator if this happens again. Error id: `" + id + "`"; + } + + 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; + 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; + } + } + + return "Invalid code."; + }, +}; + +export default RpcHandlersMixin; +export { RpcHandlersMixin }; diff --git a/src/dashboard/Serializers.mjs b/src/dashboard/Serializers.mjs new file mode 100644 index 0000000..bc8a5cb --- /dev/null +++ b/src/dashboard/Serializers.mjs @@ -0,0 +1,300 @@ +/** + * @module dashboard/Serializers + * @description Static data-conversion helpers for {@link Dashboard}: turn + * users, videos/tracks, channels, guilds, players and commands into + * dashboard-safe plain objects. + * + * This plain object is attached to the Dashboard class as static methods via + * `Object.assign(Dashboard, Serializers)` at the bottom of Dashboard.mjs, so + * `Dashboard.convertChannel(...)`, `Dashboard.convertPlayer(...)`, etc. keep + * working for external callers. + */ + +import { Dashboard } from "./Dashboard.mjs"; +import { Utils, cleanId } from "../utils/Utils.mjs"; +import { logger } from "../core/Logger.mjs"; +import { iterateVoiceStates } from "../voice/VoiceStateResolver.mjs"; + +/** + * @type {object} + * @description Serializers — attached to Dashboard as static methods. + */ +const Serializers = { + /** + * Convert a user object to a dashboard-safe plain object. + * @static + * @param {object} user - The user. + * @returns {{ id: string, username: string, displayName: string, avatar: { url: string } }} + */ + convertUser(user) { + let avatarUrl = ""; + if (user.avatar) { + avatarUrl = `https://fluxerusercontent.com/avatars/${user.id}/${user.avatar}.webp`; + } else if (typeof user.displayAvatarURL === "function") { + try { avatarUrl = user.displayAvatarURL() ?? ""; } catch(e) { logger.warn("[Dashboard] displayAvatarURL:", e?.message); } + } else if (typeof user.avatarURL === "function") { + try { avatarUrl = user.avatarURL() ?? ""; } catch(e) { logger.warn("[Dashboard] avatarURL:", e?.message); } + } + if (!avatarUrl) { + avatarUrl = `https://fluxerusercontent.com/embed/avatars/${parseInt(user.id?.slice(-4) ?? "0") % 5}.png`; + } + return { + id: user.id, + username: user.username, + displayName: user.displayName ?? user.globalName ?? user.username, + avatar: { + url: avatarUrl, + }, + }; + }, + + /** + * Convert a video/track object to a dashboard-safe plain object. + * @static + * @param {object} vid - The video/track object from the player queue. + * @returns {object|null} Sanitised video data, or null if input is falsy. + */ + convertVideo(vid) { + if (!vid) return null; + const durationMs = + typeof vid.duration === "number" ? vid.duration : + typeof vid.duration === "object" && vid.duration?.seconds !== null ? vid.duration.seconds * 1000 : + 0; + return { + title: vid.title, + url: vid.type === "radio" ? vid.author?.url : vid.url, + videoId: vid.videoId, + type: vid.type, + duration: vid.type === "radio" ? "--:--" : Utils.prettifyMS(durationMs), + description: vid.description, + artist: { + name: vid.author?.name ?? vid.artist, + url: vid.author?.url, + }, + thumbnail: vid.thumbnail, + }; + }, + + /** + * Convert a channel to a dashboard-safe plain object, including + * voice participant info for voice channels. + * @static + * @param {object} channel - The channel. + * @returns {object} Sanitised channel data. + */ + convertChannel(channel) { + const type = channel.type ?? 0; + const isVoice = channel.isVoice?.() || type === 2; + const isCategory = type === 4; + const isText = !isVoice && !isCategory && ( + type === 0 || type === 5 || type === 13 || + (typeof channel.isText === "function" && channel.isText()) + ); + let voiceParticipants = []; + if (isVoice) { + const guild = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId); + for (const vs of iterateVoiceStates(guild)) { + const scId = cleanId(vs.channelId); + const chId = cleanId(channel?.id); + if (scId === chId) { + const user = guild?.members?.get?.(vs.userId)?.user; + if (user && !user.bot) voiceParticipants.push(Dashboard.convertUser(user)); + } + } + } + + return { + name: channel.name, + displayName: channel.name, + id: channel.id, + icon: null, + description: channel.topic ?? null, + type, + isVoice, + isCategory, + isText, + parentId: channel.parentId ?? channel.parent_id ?? null, + voiceParticipants, + mature: channel.nsfw ?? false, + serverId: channel.guildId, + }; + }, + + /** + * Convert a guild (server) to a dashboard-safe plain object with channels. + * @static + * @param {object} guild - The guild. + * @returns {object} Sanitised server data including channels and voice channels. + */ + convertServer(guild) { + const channelStore = guild.channels; + const channelIds = channelStore && typeof channelStore.keys === "function" + ? [...channelStore.keys()] + : []; + const channelValues = channelStore && typeof channelStore.values === "function" + ? [...channelStore.values()] + : []; + const allChannels = channelValues + .map(Dashboard.convertChannel) + .filter(c => !c.isCategory); + + let iconUrl = null; + if (guild.icon) { + iconUrl = `https://fluxerusercontent.com/icons/${guild.id}/${guild.icon}.webp`; + } else if (typeof guild.iconURL === "function") { + try { iconUrl = guild.iconURL() ?? null; } catch (e) { logger.warn("[Dashboard] iconURL error:", e?.message); iconUrl = null; } + } + + return { + name: guild.name, + id: guild.id, + icon: iconUrl, + channelIds, + description: guild.description ?? null, + ownerId: guild.ownerId, + channels: allChannels, + voiceChannels: allChannels.filter(c => c.isVoice), + }; + }, + + /** + * Convert a guild to a lightweight summary object (no channels). + * @static + * @param {object} guild - The guild. + * @returns {{ name: string, id: string, icon: string|null, description: string|null, ownerId: string|null }} + */ + convertServerSummary(guild) { + let iconUrl = null; + if (guild.icon) { + iconUrl = `https://fluxerusercontent.com/icons/${guild.id}/${guild.icon}.webp`; + } else if (typeof guild.iconURL === "function") { + try { iconUrl = guild.iconURL() ?? null; } catch (e) { logger.warn("[Dashboard] iconURL error:", e?.message); iconUrl = null; } + } + return { + name: guild.name, + id: guild.id, + icon: iconUrl, + description: guild.description ?? null, + ownerId: guild.ownerId, + }; + }, + + /** + * Convert a Player instance to a dashboard-safe serialisable object. + * Includes queue, users, channel, and server info. + * @static + * @param {object} player - The Player instance. + * @returns {object} Sanitised player data. + */ + convertPlayer(player) { + const channelId = player._channelId; + const channel = channelId ? player.client?.channels?.get(channelId) : null; + const guild = channel?.guild ?? (player._guildId ? player.client?.guilds?.get(player._guildId) : null); + const cleanChannelId = channelId ? cleanId(channelId) : ""; + const cleanGuildId = player._guildId ? cleanId(player._guildId) : ""; + + const queue = player.queue ?? { loop: false, songLoop: false, current: null, data: [] }; + + return { + loop: (queue.loop ? 1 : 0) + (queue.songLoop ? 2 : 0), + paused: !!player._paused, + volume: Number.isFinite(player.preferredVolume) ? player.preferredVolume * 100 : 100, + queue: { + current: Dashboard.convertVideo(queue.current), + data: Array.isArray(queue.data) ? queue.data.slice(0, 500).map(v => Dashboard.convertVideo(v)) : [], + }, + users: (() => { + if (!channel) return player._dashboardUsers ?? []; + const g = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId); + const ids = []; + const seen = new Set(); + for (const vs of iterateVoiceStates(g)) { + const scId = cleanId(vs.channelId); + const chId = cleanId(channel?.id); + if (scId === chId) { + const memberId = vs.userId; + if (memberId) { ids.push(memberId); seen.add(memberId); } + } + } + const vc = player._voiceCache ?? player._observedVoiceUsers; + if (vc && cleanChannelId && cleanGuildId) { + if (typeof vc.getHumansInChannel === "function") { + const channelHumans = vc.getHumansInChannel(cleanGuildId, cleanChannelId); + for (const hid of channelHumans) { + if (seen.has(hid)) continue; + const botId = player.client?.user?.id; + if (botId && String(hid) === String(botId)) continue; + ids.push(String(hid)); + seen.add(hid); + } + } else { + for (const [mapUserId, info] of vc) { + if (seen.has(mapUserId)) continue; + const infoCh = cleanId(info.channelId); + const infoG = cleanId(info.guildId); + if (infoCh === cleanChannelId && infoG === cleanGuildId) { + const botId = player.client?.user?.id; + if (botId && String(mapUserId) === String(botId)) continue; + ids.push(String(mapUserId)); + seen.add(mapUserId); + } + } + } + } + if (player._dashboardUsers) { + for (const du of player._dashboardUsers) { + if (!seen.has(du)) { ids.push(du); seen.add(du); } + } + } + return ids; + })(), + channel: channel ? Dashboard.convertChannel(channel) : null, + server: guild ? Dashboard.convertServerSummary(guild) : null, + }; + }, + + /** + * Convert a command option to a dashboard-safe plain object. + * @static + * @param {object} opt - The command option. + * @returns {object} Sanitised option data. + */ + convertOption(opt) { + return { + type: opt.type, + name: opt.name, + choices: opt.choices, + description: opt.description, + required: opt.required, + uid: opt.uid, + defaultValue: opt.defaultValue, + dynamicDefaultPresent: !!opt.dynamicDefault, + }; + }, + + /** + * Convert a command (and its subcommands/options) to a dashboard-safe plain object. + * @static + * @param {object} com - The command object. + * @param {object} commands - The CommandHandler instance (for usage generation). + * @returns {object} Sanitised command data. + */ + convertCommand(com, commands) { + return { + name: com.name, + description: com.description, + uid: com.uid, + aliases: com.aliases, + subcommands: com.subcommands.map(c => Dashboard.convertCommand(c, commands)), + category: com.category, + examples: com.examples, + usage: commands.helpHandler?.commandUsage?.(com, { + message: { guildId: null }, + }) ?? null, + options: com.options.map(o => Dashboard.convertOption(o)), + }; + }, +}; + +export default Serializers; +export { Serializers }; diff --git a/src/dashboard/index.mjs b/src/dashboard/index.mjs new file mode 100644 index 0000000..2738c83 --- /dev/null +++ b/src/dashboard/index.mjs @@ -0,0 +1,6 @@ +/** + * @module dashboard + * @description Barrel for the dashboard layer — re-exports the Dashboard class. + */ + +export { Dashboard } from "./Dashboard.mjs"; diff --git a/src/db/DatabaseManager.mjs b/src/db/DatabaseManager.mjs new file mode 100644 index 0000000..66e7f24 --- /dev/null +++ b/src/db/DatabaseManager.mjs @@ -0,0 +1,82 @@ +/** + * @module src/db/DatabaseManager + * @description MySQL connection pool wrapper for the dashboard. Provides parameterised + * query execution and bcrypt hashing utilities for login code management. + */ + +import { compare, genSalt, hash } from "bcryptjs"; +import { createPool } from "mysql2/promise"; +import { logger } from "../core/Logger.mjs"; + +/** + * @class + * @description Wraps a mysql2 connection pool with convenience methods for + * parameterised queries and bcrypt hash operations. + */ +export class DatabaseManager { + /** + * Create a new DatabaseManager. + * @param {object} config - mysql2 pool configuration (host, user, password, database, etc.). + */ + constructor(config) { + this.db = createPool({ + connectionLimit: 15, + ...config, + }); + this.db.on("error", (err) => { + logger.error("[DashboardDB] MySQL pool error:", err.code ?? err.message); + }); + } + + /** + * Execute a raw SQL query (no parameter binding). + * @async + * @param {string} query - The SQL query string. + * @returns {Promise} The query result rows and fields. + */ + async query(query) { + return this.db.query(query); + } + + /** + * Execute a parameterised SQL query. + * @async + * @param {string} query - The SQL query with `?` placeholders. + * @param {Array} data - The values to bind. + * @returns {Promise} The result rows. + */ + async execute(query, data) { + const [res, _fields] = await this.db.execute(query, data); + return res; + } + + /** + * Generate a bcrypt hash of the given plaintext. + * @async + * @param {string} plain - The plaintext string. + * @returns {Promise} The hashed string. + */ + async hash(plain) { + const salt = await genSalt(10); + return hash(plain, salt); + } + + /** + * Compare a plaintext string against a bcrypt hash. + * @async + * @param {string} plain - The plaintext string. + * @param {string} hashed - The bcrypt hash. + * @returns {Promise} True if the plaintext matches the hash. + */ + async compareHash(plain, hashed) { + return await compare(plain, hashed); + } + + /** + * Close the underlying MySQL connection pool. + * @returns {Promise} + */ + close() { + return this.db.end(); + } +} diff --git a/src/Settings.mjs b/src/db/Settings.mjs similarity index 99% rename from src/Settings.mjs rename to src/db/Settings.mjs index e25b7a3..854689a 100644 --- a/src/Settings.mjs +++ b/src/db/Settings.mjs @@ -1,5 +1,5 @@ /** - * @module src/Settings + * @module src/db/Settings * @description MySQL-backed settings system for per-guild bot configuration. * Supports debounced writes (80ms), multi-bot via bot_id column, and * automatic schema migration for legacy tables. @@ -8,7 +8,7 @@ import fs from "node:fs"; import mysql from "mysql2"; import { EventEmitter } from "node:events"; -import { logger } from "./constants/Logger.mjs"; +import { logger } from "../core/Logger.mjs"; /** * Base settings manager providing defaults, descriptions, and key utilities. diff --git a/src/LavalinkManager.mjs b/src/music/LavalinkManager.mjs similarity index 90% rename from src/LavalinkManager.mjs rename to src/music/LavalinkManager.mjs index 8f18e46..cb60ca1 100644 --- a/src/LavalinkManager.mjs +++ b/src/music/LavalinkManager.mjs @@ -1,10 +1,11 @@ -/** @module src/LavalinkManager @description Manages Lavalink/NodeLink connection, voice forwarding, and audio search functionality. */ +/** @module src/music/LavalinkManager @description Manages Lavalink/NodeLink connection, voice forwarding, and audio search functionality. */ import { LavalinkManager as LavalinkClientManager, NodeType } from "lavalink-client"; -import { logger, _wsErrorCooldown } from "./constants/Logger.mjs"; +import { logger, _wsErrorCooldown } from "../core/Logger.mjs"; import { EventEmitter } from "node:events"; import { Events } from "@fluxerjs/core"; import { getVoiceManager } from "@fluxerjs/voice"; +import * as ShardingUtils from "../utils/ShardingUtils.mjs"; /** @class LavalinkManager @description Manages Lavalink/NodeLink connection, voice forwarding, and audio search functionality. Wraps the lavalink-client library and provides node lifecycle management, search, player creation, and WebSocket payload interception. @extends {EventEmitter} */ export class LavalinkManager extends EventEmitter { @@ -23,7 +24,7 @@ export class LavalinkManager extends EventEmitter { /** @private @type {Map} @description Cached VOICE_SERVER_UPDATE payloads keyed by guild ID. */ _cachedVoiceServerUpdates = new Map(); -/** Create a new LavalinkManager and initialize the underlying lavalink-client connection. @param {object} nodeCfg - Node configuration (id, host, port, password, secure). @param {object} client - Discord bot client instance. @param {object} user - Bot user object with id and username. */ +/** Create a new LavalinkManager and initialize the underlying lavalink-client connection. @param {object} nodeCfg - Node configuration (id, host, port, password, secure). @param {object} client - bot client instance. @param {object} user - Bot user object with id and username. */ constructor(nodeCfg, client, user) { super(); this.setMaxListeners(50); @@ -178,12 +179,16 @@ export class LavalinkManager extends EventEmitter { } } + // Fluxer 3.0 sharding: gateway payloads are guild-scoped — route to the + // shard that owns this guild (single process: always shard 0, as before). + const targetShardId = ShardingUtils.shardIdForGuild(this._client, guildId); + if (typeof this._client?.ws?.send === "function") { - this._client.ws.send(0, payload); + this._client.ws.send(targetShardId, payload); return; } - const shard = this._client?.ws?.shards?.get?.(0); + const shard = ShardingUtils.getShard(this._client, targetShardId); if (!shard) { logger.warn("[LavalinkManager] No WebSocket shard available"); return; @@ -206,24 +211,31 @@ export class LavalinkManager extends EventEmitter { const attachRawWs = () => { try { - const shard0 = client.ws?.shards?.get?.(0); - const wsObj = shard0?.ws ?? null; - if (!wsObj) return; + // Fluxer 3.0 + sharding: getShards() replaces the 2.2 `shards` Map + // property, and a sharded child owns several shards — track the raw + // socket of EVERY local shard, not just shard 0. + const wsObjs = ShardingUtils.localShardSockets(client); + if (wsObjs.length === 0) return; - if (this._rawWsHandler && this._rawWsObj && this._rawWsObj !== wsObj) { + if (!this._rawWsObjs) this._rawWsObjs = new Set(); + const attached = this._rawWsObjs; + + // Detach listeners from sockets that went away (reconnects). + for (const old of attached) { + if (wsObjs.includes(old)) continue; try { - if (typeof this._rawWsObj.removeEventListener === "function") { - this._rawWsObj.removeEventListener( + if (typeof old.removeEventListener === "function") { + old.removeEventListener( "message", this._rawWsMessageListener ?? this._rawWsHandler ); - this._rawWsObj.removeEventListener("error", this._rawWsErrorHandler); - } else if (typeof this._rawWsObj.off === "function") { - this._rawWsObj.off( + old.removeEventListener("error", this._rawWsErrorHandler); + } else if (typeof old.off === "function") { + old.off( "message", this._rawWsMessageListener ?? this._rawWsHandler ); - this._rawWsObj.off("error", this._rawWsErrorHandler); + old.off("error", this._rawWsErrorHandler); } } catch (e) { logger.warn( @@ -231,10 +243,11 @@ export class LavalinkManager extends EventEmitter { e?.message ); } + attached.delete(old); } - if (wsObj === this._rawWsObj) return; - + // Create the shared handlers once (stateless parsers). + if (!this._rawWsHandler) { const botId = this._client?.user?.id; let _vsuLogCooldown = 0; let _vsuBotLogCooldown = 0; @@ -290,16 +303,24 @@ export class LavalinkManager extends EventEmitter { this._rawWsMessageListener = (event) => this._rawWsHandler(event?.data ?? event); - - if (typeof wsObj.addEventListener === "function") { - wsObj.addEventListener("message", this._rawWsMessageListener); - wsObj.addEventListener("error", this._rawWsErrorHandler); - } else if (typeof wsObj.on === "function") { - wsObj.on("message", this._rawWsMessageListener); - wsObj.on("error", this._rawWsErrorHandler); } - this._rawWsObj = wsObj; + for (const wsObj of wsObjs) { + if (attached.has(wsObj)) continue; + + if (typeof wsObj.addEventListener === "function") { + wsObj.addEventListener("message", this._rawWsMessageListener); + wsObj.addEventListener("error", this._rawWsErrorHandler); + } else if (typeof wsObj.on === "function") { + wsObj.on("message", this._rawWsMessageListener); + wsObj.on("error", this._rawWsErrorHandler); + } + + attached.add(wsObj); + } + + // Legacy singular field kept in sync (first socket). + this._rawWsObj = wsObjs[0] ?? null; } catch (e) { logger.warn("[LavalinkManager] Raw WS setup error:", e.message); } diff --git a/src/music/PlayerEventsMixin.mjs b/src/music/PlayerEventsMixin.mjs new file mode 100644 index 0000000..ba1e104 --- /dev/null +++ b/src/music/PlayerEventsMixin.mjs @@ -0,0 +1,298 @@ +/** + * @module src/music/PlayerEventsMixin + * @description Dashboard event wiring concern for {@link PlayerManager}: + * binds dashboard update/queue/message events onto spawned players, + * forwards now-playing updates to Last.fm with scrobble scheduling, and + * translates locale keys for message contexts. + * + * These methods are applied onto the PlayerManager class prototype via + * {@link applyMixins} (see src/music/PlayerManager.mjs) — `this` is a + * PlayerManager instance. + */ + +import { cleanId } from "../utils/Utils.mjs"; +import { getMessageGuildId } from "../ui/index.mjs"; +import { Dashboard } from "../dashboard/Dashboard.mjs"; + +// Module-level ID helpers from the original PlayerManager.mjs. They live in +// this module (not the base file) because it is the shared leaf of the three +// PlayerManager modules, which keeps the import graph acyclic: +// PlayerManager.mjs → PlayerEventsMixin.mjs ← PlayerLifecycleMixin.mjs. +/** @private @param {Player} player @param {object|null} [fallbackChannel=null] @returns {string} Cleaned guild ID. */ +function getPlayerGuildId(player, fallbackChannel = null) { + return cleanId( + player?._guildId ?? + fallbackChannel?.guildId ?? + fallbackChannel?.guild?.id ?? + fallbackChannel?.server_id ?? + fallbackChannel?.serverId + ); +} + +/** @private @param {Player} player @param {string|null} [fallbackChannelId=null] @returns {string} Cleaned channel ID. */ +function getPlayerChannelId(player, fallbackChannelId = null) { + return cleanId(player?._channelId ?? player?._home247Channel ?? fallbackChannelId); +} +export { getPlayerGuildId, getPlayerChannelId }; + +/** + * @type {object} + * @description Player events mixin — applied to PlayerManager. + */ +const PlayerEventsMixin = { + /** Bind dashboard update and message-sending events on a player. @this {import('./PlayerManager.mjs').PlayerManager} @param {Player} player @param {object} [context={}] @returns {Player} The same player, with events bound. */ + setupEvents(player, context = {}) { + if (!player || player._dashboardEventsBound) return player; + + Object.defineProperty(player, "_dashboardEventsBound", { + value: true, + configurable: true, + enumerable: false, + writable: true, + }); + + const emit = (type, data) => { + if (!this.dashboard?.enabled) return; + this.dashboard.updatePlayer({ type, data }, player); + }; + + const emitGlobal = (type) => { + if (!this.dashboard?.enabled) return; + this.dashboard.playerUpdate({ type }, player); + }; + + const sendUserUpdates = (eventType) => { + if (!this.dashboard?.enabled) return; + const channelId = getPlayerChannelId(player, context.channelId); + const channel = player.client?.channels?.get(channelId); + const guild = player.client?.guilds?.get(cleanId(player._guildId ?? context.guildId)); + if (!guild) return; + const voiceStates = guild.voice_states ?? guild.voiceStates ?? null; + if (!voiceStates) return; + const entries = Array.isArray(voiceStates) + ? voiceStates + : typeof voiceStates.values === "function" + ? [...voiceStates.values()] + : Object.values(voiceStates); + for (const state of entries) { + if (!state?.channelId && !state?.channel_id) continue; + const stateChannelId = cleanId(state.channelId ?? state.channel_id); + if (stateChannelId !== channelId) continue; + const member = guild.members?.get?.(state.userId ?? state.user_id); + if (!member?.user || member.user?.bot) continue; + emit(eventType, member.user.id); + this.dashboard.userUpdate({ + type: eventType, + guildId: cleanId(player._guildId ?? context.guildId), + channelId, + }, member.user); + } + }; + + player.on("roomfetched", () => { + emitGlobal("init"); + sendUserUpdates("join"); + }); + + player.on("startplay", (song) => { + emit("startplay", Dashboard.convertVideo(song ?? player.queue?.current)); + emit("streamStartPlay", Date.now()); + this.dashboard.playerUpdate({ type: "startplay" }, player); + + if (this._lastfm?.enabled && song) { + this._handleLastFmStartPlay(player, song); + } + }); + + player.on("stopplay", () => { + emit("stopplay", null); + this.dashboard.playerUpdate({ type: "stopplay" }, player); + }); + + player.on("playback", (playing) => { + const elapsedMs = player._pausedAt + ? (player._pausedAt.getTime?.() ?? Number(player._pausedAt)) - + (player.startedPlaying?.getTime?.() ?? Number(player.startedPlaying ?? 0)) + : Date.now() - (player.startedPlaying?.getTime?.() ?? Number(player.startedPlaying ?? 0)); + const type = playing ? "resume" : "pause"; + emit(type, { elapsedTime: Math.max(0, elapsedMs) }); + this.dashboard.playerUpdate({ type }, player); + }); + + player.on("volume", (volume) => { + emit("volume", volume); + this.dashboard.playerUpdate({ type: "volume" }, player); + }); + + player.on("filter", (filter) => { + emit("filter", filter); + }); + + player.on("update", (scope) => { + this.dashboard.playerUpdate({ type: "update" }, player); + }); + + player.on("autoleave", () => { + sendUserUpdates("leave"); + emitGlobal("close"); + emit("stopplay", null); + }); + + player.on("leave", () => { + sendUserUpdates("leave"); + emitGlobal("close"); + emit("stopplay", null); + }); + + player.queue?.on("queue", (queueEvent) => { + const serialised = { type: queueEvent.type }; + switch (queueEvent.type) { + case "add": + serialised.data = { + append: queueEvent.data?.append, + data: Dashboard.convertVideo(queueEvent.data?.data), + }; + break; + case "addMany": + serialised.data = { + append: queueEvent.data?.append, + tracks: (queueEvent.data?.tracks ?? []).map(v => Dashboard.convertVideo(v)), + }; + break; + case "remove": + serialised.data = { + index: queueEvent.data?.index, + removed: Dashboard.convertVideo(queueEvent.data?.removed), + old: (queueEvent.data?.old ?? []).map(v => Dashboard.convertVideo(v)), + new: (queueEvent.data?.new ?? []).map(v => Dashboard.convertVideo(v)), + }; + break; + case "move": + serialised.data = { + from: queueEvent.data?.from, + to: queueEvent.data?.to, + track: Dashboard.convertVideo(queueEvent.data?.track), + }; + break; + case "shuffle": + serialised.data = (queueEvent.data ?? []).map(v => Dashboard.convertVideo(v)); + break; + case "update": + serialised.data = { + current: Dashboard.convertVideo(queueEvent.data?.current), + old: Dashboard.convertVideo(queueEvent.data?.old), + loop: queueEvent.data?.loop, + }; + break; + default: + serialised.data = queueEvent.data; + break; + } + + emit("queue", serialised); + this.dashboard.playerUpdate({ type: "queue" }, player); + }); + + return player; + }, + + /** @private Translate a locale key for a message context. @this {import('./PlayerManager.mjs').PlayerManager} @param {object} message @param {string} key @param {object} [replacements={}] @returns {string} */ + _t(message, key, replacements = {}) { + if (!this.locale) return key; + const guildId = getMessageGuildId(message); + return this.locale.translate(guildId, key, replacements); + }, + + /** @private Handle Last.fm now-playing update and schedule scrobble timer. @this {import('./PlayerManager.mjs').PlayerManager} @param {Player} player @param {object} song */ + _handleLastFmStartPlay(player, song) { + const lastfm = this._lastfm; + if (!lastfm?.enabled) return; + + const guildId = cleanId(player._guildId); + if (!guildId) return; + + const channelId = getPlayerChannelId(player); + const humanUserIds = []; + + if (this.voiceCache) { + const users = this.voiceCache.getHumansInChannel(guildId, channelId); + humanUserIds.push(...users); + } else if (this.observedVoiceUsers) { + for (const [uid, info] of this.observedVoiceUsers) { + if (cleanId(info.guildId) === guildId && cleanId(info.channelId) === channelId) { + humanUserIds.push(uid); + } + } + } + + const guild = player.client?.guilds?.get(guildId); + if (guild) { + const voiceStates = guild.voice_states ?? guild.voiceStates ?? null; + if (voiceStates) { + const entries = Array.isArray(voiceStates) + ? voiceStates + : typeof voiceStates.values === "function" + ? [...voiceStates.values()] + : Object.values(voiceStates ?? {}); + for (const state of entries) { + const uid = state?.userId ?? state?.user_id; + const chId = cleanId(state?.channelId ?? state?.channel_id); + if (uid && chId === channelId) { + const member = guild.members?.get?.(uid); + if (member?.user?.bot) continue; + if (!humanUserIds.includes(uid)) humanUserIds.push(uid); + } + } + } + } + + const startedAtMs = player.startedPlaying; + + const pendingKey = channelId; + const existing = this._pendingScrobbleTimers.get(pendingKey); + if (existing) { + clearTimeout(existing.timer); + this._pendingScrobbleTimers.delete(pendingKey); + } + + for (const userId of humanUserIds) { + lastfm.updateNowPlaying(userId, song).catch(() => {}); + } + + const durationMs = (() => { + const d = song.duration; + if (!d) return null; + if (typeof d === "object" && d.seconds) return d.seconds * 1000; + if (typeof d === "number") return d; + return null; + })(); + + if (durationMs && durationMs >= 30_000) { + const thresholdMs = Math.min( + durationMs * lastfm.scrobbleThreshold, + lastfm.scrobbleMinMs + ); + if (thresholdMs <= 600_000) { + const timer = setTimeout(() => { + this._pendingScrobbleTimers.delete(pendingKey); + const current = player.queue?.getCurrent(); + if (!current || player._destroyed || player.leaving) return; + if (current.title !== song.title || current.url !== song.url) return; + if (player._paused) return; + + const playedMs = Date.now() - (player.startedPlaying ?? startedAtMs ?? Date.now()); + if (lastfm.shouldScrobble(song, playedMs)) { + for (const userId of humanUserIds) { + lastfm.scrobble(userId, song, startedAtMs).catch(() => {}); + } + } + }, thresholdMs); + + this._pendingScrobbleTimers.set(pendingKey, { timer, songUrl: song.url, startedAtMs }); + } + } + }, +}; + +export default PlayerEventsMixin; +export { PlayerEventsMixin }; diff --git a/src/PlayerManager.mjs b/src/music/PlayerLifecycleMixin.mjs similarity index 54% rename from src/PlayerManager.mjs rename to src/music/PlayerLifecycleMixin.mjs index 367b869..852c115 100644 --- a/src/PlayerManager.mjs +++ b/src/music/PlayerLifecycleMixin.mjs @@ -1,32 +1,28 @@ -/** @module src/PlayerManager @description Manages all Player instances. Handles player lifecycle (spawn, join, leave, destroy), voice channel resolution, dashboard events, and autoleave suppression for 24/7 channels. */ +/** + * @module src/music/PlayerLifecycleMixin + * @description Voice-channel resolution & player lifecycle concern for + * {@link PlayerManager}: author voice-channel detection, interactive + * voice-channel selection prompt, leave, saved-volume restore, and + * spawn/join of Player instances (including join retries and the autoleave + * / now-playing announcement handlers wired inside initPlayer). + * + * These methods are applied onto the PlayerManager class prototype via + * {@link applyMixins} (see src/music/PlayerManager.mjs) — `this` is a + * PlayerManager instance. + */ -import Player from "./Player.mjs"; -import { Utils, cleanId } from "./Utils.mjs"; -import { logger } from "./constants/Logger.mjs"; -import { get247ChannelMode } from "./constants/Helpers247.mjs"; +import Player from "./player/index.mjs"; +import { cleanId } from "../utils/Utils.mjs"; +import { logger } from "../core/Logger.mjs"; +import { get247ChannelMode } from "../utils/Helpers247.mjs"; import { EmbedBuilder, PermissionFlags } from "@fluxerjs/core"; import { getVoiceManager } from "@fluxerjs/voice"; -import { getGlobalColor, getMessageGuildId } from "./MessageHandler.mjs"; -import { Dashboard } from "./dashboard/Dashboard.mjs"; -import { hasHumansInChannel, iterateVoiceStates } from "./constants/VoiceStateResolver.mjs"; - - -/** @private @param {Player} player @param {object|null} [fallbackChannel=null] @returns {string} Cleaned guild ID. */ -function getPlayerGuildId(player, fallbackChannel = null) { - return cleanId( - player?._guildId ?? - fallbackChannel?.guildId ?? - fallbackChannel?.guild?.id ?? - fallbackChannel?.server_id ?? - fallbackChannel?.serverId - ); -} - -/** @private @param {Player} player @param {string|null} [fallbackChannelId=null] @returns {string} Cleaned channel ID. */ -function getPlayerChannelId(player, fallbackChannelId = null) { - return cleanId(player?._channelId ?? player?._home247Channel ?? fallbackChannelId); -} +import { getGlobalColor, getMessageGuildId } from "../ui/index.mjs"; +import { hasHumansInChannel, iterateVoiceStates } from "../voice/VoiceStateResolver.mjs"; +import { getPlayerChannelId } from "./PlayerEventsMixin.mjs"; +// Module-level join/permission helpers from the original PlayerManager.mjs +// (only initPlayer below uses them, so they stay private to this module). /** @private Check whether the bot has required voice permissions in a channel. @param {object} client @param {string} channelId @returns {boolean} True if the bot can connect, speak, and use VAD. */ function botHasVoicePermissions(client, channelId) { try { @@ -70,287 +66,12 @@ function sanitizeJoinError(err, client = null, channelId = null) { return null; } -/** @class PlayerManager @description Manages all Player instances. Handles player lifecycle (spawn, join, leave, destroy), voice channel resolution, dashboard events, and autoleave suppression for 24/7 channels. */ -export class PlayerManager { - /** @type {RemoteSettingsManager} */ - settings; - - /** @type {CommandHandler} */ - commands; - - /** @type {Map} Player instances keyed by channel ID. */ - playerMap = new Map(); - - /** @private @type {Map>} Guild ID → Set of channel IDs (for fast guild-player lookup). */ - _guildPlayerIndex = new Map(); - - /** @private @type {Set} Channel IDs currently being joined. */ - _pendingJoins = new Set(); - - /** @private @type {Map} */ - _pendingScrobbleTimers = new Map(); - - /** @type {object} Full bot config. */ - config; - - /** @type {object} Player-specific config (lavalink reference). */ - playerConfig; - - /** @type {Locale|null} */ - locale = null; - - /** @type {Dashboard|null} */ - dashboard = null; - - /** - * Create a new PlayerManager. - * @param {RemoteSettingsManager} settings - The settings manager. - * @param {CommandHandler} commands - The command handler. - * @param {object} config - Configuration object. - * @param {object} config.config - Full bot config. - * @param {object} config.player - Player-specific config (lavalink, etc.). - * @param {Dashboard} [config.dashboard] - Dashboard instance. - * @param {Locale} [config.locale] - Locale manager. - * @param {object} [config.timers] - Timer configuration. - * @param {TrackOptionsManager} [config.trackOptions] - Track options manager. - */ - constructor(settings, commands, config) { - this.commands = commands; - this.settings = settings; - this.config = config.config; - this.playerConfig = config.player; - this.dashboard = config.dashboard ?? null; - this.locale = config.locale ?? null; - this.timers = config.timers ?? {}; - this._lastfm = null; - this.trackOptions = config.trackOptions ?? null; - } - - /** @private Index a player by guild and channel ID for fast lookups. @param {string} guildId @param {string} channelId */ - _indexPlayer(guildId, channelId) { - const gId = cleanId(guildId); - const cId = cleanId(channelId); - if (!gId || !cId) return; - let set = this._guildPlayerIndex.get(gId); - if (!set) { set = new Set(); this._guildPlayerIndex.set(gId, set); } - set.add(cId); - } - - /** @private Remove a player from the guild-player index. @param {string} guildId @param {string} channelId */ - _unindexPlayer(guildId, channelId) { - const gId = cleanId(guildId); - const cId = cleanId(channelId); - if (!gId) return; - const set = this._guildPlayerIndex.get(gId); - if (set) { - set.delete(cId); - if (set.size === 0) this._guildPlayerIndex.delete(gId); - } - } - - /** Get all active (non-destroyed) players for a guild. @param {string} guildId @returns {Array<[string, Player]>} Array of [channelId, Player] pairs. */ - getGuildPlayers(guildId) { - const gId = cleanId(guildId); - const set = this._guildPlayerIndex.get(gId); - if (!set) return []; - const result = []; - for (const channelId of set) { - const player = this.playerMap.get(channelId); - if (!player || player._destroyed) { - set.delete(channelId); - continue; - } - result.push([channelId, player]); - } - return result; - } - - /** Find a player by both guild and channel. @param {string} guildId @param {string} channelId @returns {Player|null} */ - getPlayerByGuildAndChannel(guildId, channelId) { - const cId = cleanId(channelId); - const players = this.getGuildPlayers(guildId); - for (const [mapChannelId, player] of players) { - if (getPlayerChannelId(player, mapChannelId) === cId) return player; - } - return null; - } - - /** Find a player by its channel ID across all guilds. @param {string} channelId @returns {Player|null} */ - getPlayerByChannelId(channelId) { - const cId = cleanId(channelId); - for (const [, channelSet] of this._guildPlayerIndex) { - for (const mapChannelId of channelSet) { - const player = this.playerMap.get(mapChannelId); - if (player && getPlayerChannelId(player, mapChannelId) === cId) return player; - } - } - return null; - } - - /** Bind dashboard update and message-sending events on a player. @param {Player} player @param {object} [context={}] @returns {Player} The same player, with events bound. */ - setupEvents(player, context = {}) { - if (!player || player._dashboardEventsBound) return player; - - Object.defineProperty(player, "_dashboardEventsBound", { - value: true, - configurable: true, - enumerable: false, - writable: true, - }); - - const emit = (type, data) => { - if (!this.dashboard?.enabled) return; - this.dashboard.updatePlayer({ type, data }, player); - }; - - const emitGlobal = (type) => { - if (!this.dashboard?.enabled) return; - this.dashboard.playerUpdate({ type }, player); - }; - - const sendUserUpdates = (eventType) => { - if (!this.dashboard?.enabled) return; - const channelId = getPlayerChannelId(player, context.channelId); - const channel = player.client?.channels?.get(channelId); - const guild = player.client?.guilds?.get(cleanId(player._guildId ?? context.guildId)); - if (!guild) return; - const voiceStates = guild.voice_states ?? guild.voiceStates ?? null; - if (!voiceStates) return; - const entries = Array.isArray(voiceStates) - ? voiceStates - : typeof voiceStates.values === "function" - ? [...voiceStates.values()] - : Object.values(voiceStates); - for (const state of entries) { - if (!state?.channelId && !state?.channel_id) continue; - const stateChannelId = cleanId(state.channelId ?? state.channel_id); - if (stateChannelId !== channelId) continue; - const member = guild.members?.get?.(state.userId ?? state.user_id); - if (!member?.user || member.user?.bot) continue; - emit(eventType, member.user.id); - this.dashboard.userUpdate({ - type: eventType, - guildId: cleanId(player._guildId ?? context.guildId), - channelId, - }, member.user); - } - }; - - player.on("roomfetched", () => { - emitGlobal("init"); - sendUserUpdates("join"); - }); - - player.on("startplay", (song) => { - emit("startplay", Dashboard.convertVideo(song ?? player.queue?.current)); - emit("streamStartPlay", Date.now()); - this.dashboard.playerUpdate({ type: "startplay" }, player); - - if (this._lastfm?.enabled && song) { - this._handleLastFmStartPlay(player, song); - } - }); - - player.on("stopplay", () => { - emit("stopplay", null); - this.dashboard.playerUpdate({ type: "stopplay" }, player); - }); - - player.on("playback", (playing) => { - const elapsedMs = player._pausedAt - ? (player._pausedAt.getTime?.() ?? Number(player._pausedAt)) - - (player.startedPlaying?.getTime?.() ?? Number(player.startedPlaying ?? 0)) - : Date.now() - (player.startedPlaying?.getTime?.() ?? Number(player.startedPlaying ?? 0)); - const type = playing ? "resume" : "pause"; - emit(type, { elapsedTime: Math.max(0, elapsedMs) }); - this.dashboard.playerUpdate({ type }, player); - }); - - player.on("volume", (volume) => { - emit("volume", volume); - this.dashboard.playerUpdate({ type: "volume" }, player); - }); - - player.on("filter", (filter) => { - emit("filter", filter); - }); - - player.on("update", (scope) => { - this.dashboard.playerUpdate({ type: "update" }, player); - }); - - player.on("autoleave", () => { - sendUserUpdates("leave"); - emitGlobal("close"); - emit("stopplay", null); - }); - - player.on("leave", () => { - sendUserUpdates("leave"); - emitGlobal("close"); - emit("stopplay", null); - }); - - player.queue?.on("queue", (queueEvent) => { - const serialised = { type: queueEvent.type }; - switch (queueEvent.type) { - case "add": - serialised.data = { - append: queueEvent.data?.append, - data: Dashboard.convertVideo(queueEvent.data?.data), - }; - break; - case "addMany": - serialised.data = { - append: queueEvent.data?.append, - tracks: (queueEvent.data?.tracks ?? []).map(v => Dashboard.convertVideo(v)), - }; - break; - case "remove": - serialised.data = { - index: queueEvent.data?.index, - removed: Dashboard.convertVideo(queueEvent.data?.removed), - old: (queueEvent.data?.old ?? []).map(v => Dashboard.convertVideo(v)), - new: (queueEvent.data?.new ?? []).map(v => Dashboard.convertVideo(v)), - }; - break; - case "move": - serialised.data = { - from: queueEvent.data?.from, - to: queueEvent.data?.to, - track: Dashboard.convertVideo(queueEvent.data?.track), - }; - break; - case "shuffle": - serialised.data = (queueEvent.data ?? []).map(v => Dashboard.convertVideo(v)); - break; - case "update": - serialised.data = { - current: Dashboard.convertVideo(queueEvent.data?.current), - old: Dashboard.convertVideo(queueEvent.data?.old), - loop: queueEvent.data?.loop, - }; - break; - default: - serialised.data = queueEvent.data; - break; - } - - emit("queue", serialised); - this.dashboard.playerUpdate({ type: "queue" }, player); - }); - - return player; - } - - /** @private Translate a locale key for a message context. @param {object} message @param {string} key @param {object} [replacements={}] @returns {string} */ - _t(message, key, replacements = {}) { - if (!this.locale) return key; - const guildId = getMessageGuildId(message); - return this.locale.translate(guildId, key, replacements); - } - - /** Detect which voice channel the message author is in. @async @param {object} message @param {object} settings @returns {Promise<{channelId: string|null, alreadyInVoice: boolean, hasHumans: boolean}>} */ +/** + * @type {object} + * @description Player lifecycle mixin — applied to PlayerManager. + */ +const PlayerLifecycleMixin = { + /** Detect which voice channel the message author is in. @async @this {import('./PlayerManager.mjs').PlayerManager} @param {object} message @param {object} settings @returns {Promise<{channelId: string|null, alreadyInVoice: boolean, hasHumans: boolean}>} */ async checkVoiceChannels(message, settings) { const guildId = message?.guildId ?? message?.channel?.guildId ?? getMessageGuildId(message); const userId = message?.author?.id ?? message?.member?.user?.id; @@ -415,94 +136,9 @@ export class PlayerManager { }); return { channelId, alreadyInVoice, hasHumans: hasHumansResult }; - } + }, - /** Get or spawn a player for the message's voice channel. @async @param {object} message @param {boolean} [promptJoin=true] @param {boolean} [verifyUser=true] @param {boolean} [shouldJoin=false] @returns {Promise} */ - async getPlayer(message, promptJoin = true, verifyUser = true, shouldJoin = false) { - const guildId = getMessageGuildId(message); - const cleanGuildId = cleanId(guildId); - - const { channelId: userChannelId } = await this.checkVoiceChannels(message); - const cleanUserChannelId = cleanId(userChannelId); - - if (cleanUserChannelId) { - const player = this.playerMap.get(cleanUserChannelId) - ?? this.getPlayerByGuildAndChannel(cleanGuildId, cleanUserChannelId); - if (player) { - player.textChannel = message.channel?.channel ?? message.channel; - try { - const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null; - if (guildId && textChannelId) { - this.settings.getServer(guildId)?.set("announcementChannelId", textChannelId); - } - } catch(e) { - logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message); - } - return player; - } - if (this._pendingJoins.has(cleanUserChannelId)) { - return null; - } - } - - const serverPlayers = cleanGuildId - ? this.getGuildPlayers(cleanGuildId) - : []; - - if (serverPlayers.length > 0) { - const channelList = serverPlayers.map(([chId]) => `<#${chId}>`).join(" or "); - - if (!userChannelId) { - if (!verifyUser) { - const first = serverPlayers[0]; - first[1].textChannel = message.channel?.channel ?? message.channel; - return first[1]; - } - message.reply(this._t(message, "responses._common.noVoiceStrict")); - return null; - } - - const match = serverPlayers.find(([, player]) => - getPlayerChannelId(player) === cleanUserChannelId - ); - if (match) { - match[1].textChannel = message.channel?.channel ?? message.channel; - try { - const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null; - if (cleanGuildId && textChannelId) { - this.settings.getServer(cleanGuildId)?.set("announcementChannelId", textChannelId); - } - } catch(e) { - logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message); - } - return match[1]; - } - - if (shouldJoin) { - return this.initPlayer(message, userChannelId); - } - - const prefix = this.commands.getPrefix(guildId); - message.reply(this._t(message, "responses._common.alreadyInChannel", { channels: channelList, prefix })); - return null; - } - - if (!userChannelId) { - if (shouldJoin) { - return this.promptVC(message); - } - message.reply(this._t(message, "responses._common.noVoiceChannel")); - return null; - } - - if (shouldJoin) { - return this.initPlayer(message, userChannelId); - } - - return null; - } - - /** Prompt the user to select a voice channel via reactions or text input. @async @param {object} msg @returns {Promise} */ + /** Prompt the user to select a voice channel via reactions or text input. @async @this {import('./PlayerManager.mjs').PlayerManager} @param {object} msg @returns {Promise} */ async promptVC(msg) { const { channelId: autoDetected } = await this.checkVoiceChannels(msg); if (autoDetected) { @@ -585,9 +221,9 @@ export class PlayerManager { this.initPlayer(m, channel).then(p => resolve(p)); }, promptUser); }); - } + }, - /** Leave a voice channel, destroy the player, and send a confirmation. @async @param {object} msg @param {string} [cid] @returns {Promise} */ + /** Leave a voice channel, destroy the player, and send a confirmation. @async @this {import('./PlayerManager.mjs').PlayerManager} @param {object} msg @param {string} [cid] @returns {Promise} */ async leave(msg, cid) { if (!cid) { const guildId = getMessageGuildId(msg); @@ -620,18 +256,18 @@ export class PlayerManager { } player.destroy(); await msg.reply(this._t(msg, "responses._common.successfullyLeft")); - } + }, - /** @private Restore saved volume for a player from guild settings. @param {Player} player @param {string} guildId */ + /** @private Restore saved volume for a player from guild settings. @this {import('./PlayerManager.mjs').PlayerManager} @param {Player} player @param {string} guildId */ _restorePlayerVolume(player, guildId) { const savedVol = this.settings?.getServer?.(guildId)?.get?.("volume"); if (savedVol !== undefined && savedVol !== null) { const vol = Number(savedVol); if (!isNaN(vol)) player.setVolume(vol / 100); } - } + }, - /** Create a new Player, join the voice channel, and set up events. @async @param {object} message @param {string} cid @returns {Promise} The spawned player, or null on failure. */ + /** Create a new Player, join the voice channel, and set up events. @async @this {import('./PlayerManager.mjs').PlayerManager} @param {object} message @param {string} cid @returns {Promise} The spawned player, or null on failure. */ async initPlayer(message, cid) { const channel = this.commands.client?.channels?.get(cid); @@ -917,96 +553,8 @@ export class PlayerManager { player.destroy(); return null; } - } + }, +}; - /** @private Handle Last.fm now-playing update and schedule scrobble timer. @param {Player} player @param {object} song */ - _handleLastFmStartPlay(player, song) { - const lastfm = this._lastfm; - if (!lastfm?.enabled) return; - - const guildId = cleanId(player._guildId); - if (!guildId) return; - - const channelId = getPlayerChannelId(player); - const humanUserIds = []; - - if (this.voiceCache) { - const users = this.voiceCache.getHumansInChannel(guildId, channelId); - humanUserIds.push(...users); - } else if (this.observedVoiceUsers) { - for (const [uid, info] of this.observedVoiceUsers) { - if (cleanId(info.guildId) === guildId && cleanId(info.channelId) === channelId) { - humanUserIds.push(uid); - } - } - } - - const guild = player.client?.guilds?.get(guildId); - if (guild) { - const voiceStates = guild.voice_states ?? guild.voiceStates ?? null; - if (voiceStates) { - const entries = Array.isArray(voiceStates) - ? voiceStates - : typeof voiceStates.values === "function" - ? [...voiceStates.values()] - : Object.values(voiceStates ?? {}); - for (const state of entries) { - const uid = state?.userId ?? state?.user_id; - const chId = cleanId(state?.channelId ?? state?.channel_id); - if (uid && chId === channelId) { - const member = guild.members?.get?.(uid); - if (member?.user?.bot) continue; - if (!humanUserIds.includes(uid)) humanUserIds.push(uid); - } - } - } - } - - const startedAtMs = player.startedPlaying; - - const pendingKey = channelId; - const existing = this._pendingScrobbleTimers.get(pendingKey); - if (existing) { - clearTimeout(existing.timer); - this._pendingScrobbleTimers.delete(pendingKey); - } - - for (const userId of humanUserIds) { - lastfm.updateNowPlaying(userId, song).catch(() => {}); - } - - const durationMs = (() => { - const d = song.duration; - if (!d) return null; - if (typeof d === "object" && d.seconds) return d.seconds * 1000; - if (typeof d === "number") return d; - return null; - })(); - - if (durationMs && durationMs >= 30_000) { - const thresholdMs = Math.min( - durationMs * lastfm.scrobbleThreshold, - lastfm.scrobbleMinMs - ); - if (thresholdMs <= 600_000) { - const timer = setTimeout(() => { - this._pendingScrobbleTimers.delete(pendingKey); - const current = player.queue?.getCurrent(); - if (!current || player._destroyed || player.leaving) return; - if (current.title !== song.title || current.url !== song.url) return; - if (player._paused) return; - - const playedMs = Date.now() - (player.startedPlaying ?? startedAtMs ?? Date.now()); - if (lastfm.shouldScrobble(song, playedMs)) { - for (const userId of humanUserIds) { - lastfm.scrobble(userId, song, startedAtMs).catch(() => {}); - } - } - }, thresholdMs); - - this._pendingScrobbleTimers.set(pendingKey, { timer, songUrl: song.url, startedAtMs }); - } - } - } - -} +export default PlayerLifecycleMixin; +export { PlayerLifecycleMixin }; diff --git a/src/music/PlayerManager.mjs b/src/music/PlayerManager.mjs new file mode 100644 index 0000000..00b0898 --- /dev/null +++ b/src/music/PlayerManager.mjs @@ -0,0 +1,229 @@ +/** + * @module src/music/PlayerManager + * @description Manages all Player instances. Handles player lifecycle (spawn, + * join, leave, destroy), voice channel resolution, dashboard events, and + * autoleave suppression for 24/7 channels. + * + * Base class: class fields, constructor, the guild/channel player index, + * lookups and getPlayer. Dashboard event wiring and Last.fm scrobble + * scheduling live in PlayerEventsMixin.mjs; voice-channel detection, channel + * prompt, leave and player spawn/join live in PlayerLifecycleMixin.mjs. + * Both mixins are applied to the class at the bottom of this file. + */ + +import Player from "./player/index.mjs"; +import { Utils, cleanId } from "../utils/Utils.mjs"; +import { logger } from "../core/Logger.mjs"; +import { getMessageGuildId } from "../ui/index.mjs"; +import { applyMixins } from "../utils/mixins.mjs"; +import PlayerEventsMixin, { getPlayerChannelId } from "./PlayerEventsMixin.mjs"; +import PlayerLifecycleMixin from "./PlayerLifecycleMixin.mjs"; + + +/** @class PlayerManager @description Manages all Player instances. Handles player lifecycle (spawn, join, leave, destroy), voice channel resolution, dashboard events, and autoleave suppression for 24/7 channels. */ +export class PlayerManager { + /** @type {RemoteSettingsManager} */ + settings; + + /** @type {CommandHandler} */ + commands; + + /** @type {Map} Player instances keyed by channel ID. */ + playerMap = new Map(); + + /** @private @type {Map>} Guild ID → Set of channel IDs (for fast guild-player lookup). */ + _guildPlayerIndex = new Map(); + + /** @private @type {Set} Channel IDs currently being joined. */ + _pendingJoins = new Set(); + + /** @private @type {Map} */ + _pendingScrobbleTimers = new Map(); + + /** @type {object} Full bot config. */ + config; + + /** @type {object} Player-specific config (lavalink reference). */ + playerConfig; + + /** @type {Locale|null} */ + locale = null; + + /** @type {Dashboard|null} */ + dashboard = null; + + /** + * Create a new PlayerManager. + * @param {RemoteSettingsManager} settings - The settings manager. + * @param {CommandHandler} commands - The command handler. + * @param {object} config - Configuration object. + * @param {object} config.config - Full bot config. + * @param {object} config.player - Player-specific config (lavalink, etc.). + * @param {Dashboard} [config.dashboard] - Dashboard instance. + * @param {Locale} [config.locale] - Locale manager. + * @param {object} [config.timers] - Timer configuration. + * @param {TrackOptionsManager} [config.trackOptions] - Track options manager. + */ + constructor(settings, commands, config) { + this.commands = commands; + this.settings = settings; + this.config = config.config; + this.playerConfig = config.player; + this.dashboard = config.dashboard ?? null; + this.locale = config.locale ?? null; + this.timers = config.timers ?? {}; + this._lastfm = null; + this.trackOptions = config.trackOptions ?? null; + } + + /** @private Index a player by guild and channel ID for fast lookups. @param {string} guildId @param {string} channelId */ + _indexPlayer(guildId, channelId) { + const gId = cleanId(guildId); + const cId = cleanId(channelId); + if (!gId || !cId) return; + let set = this._guildPlayerIndex.get(gId); + if (!set) { set = new Set(); this._guildPlayerIndex.set(gId, set); } + set.add(cId); + } + + /** @private Remove a player from the guild-player index. @param {string} guildId @param {string} channelId */ + _unindexPlayer(guildId, channelId) { + const gId = cleanId(guildId); + const cId = cleanId(channelId); + if (!gId) return; + const set = this._guildPlayerIndex.get(gId); + if (set) { + set.delete(cId); + if (set.size === 0) this._guildPlayerIndex.delete(gId); + } + } + + /** Get all active (non-destroyed) players for a guild. @param {string} guildId @returns {Array<[string, Player]>} Array of [channelId, Player] pairs. */ + getGuildPlayers(guildId) { + const gId = cleanId(guildId); + const set = this._guildPlayerIndex.get(gId); + if (!set) return []; + const result = []; + for (const channelId of set) { + const player = this.playerMap.get(channelId); + if (!player || player._destroyed) { + set.delete(channelId); + continue; + } + result.push([channelId, player]); + } + return result; + } + + /** Find a player by both guild and channel. @param {string} guildId @param {string} channelId @returns {Player|null} */ + getPlayerByGuildAndChannel(guildId, channelId) { + const cId = cleanId(channelId); + const players = this.getGuildPlayers(guildId); + for (const [mapChannelId, player] of players) { + if (getPlayerChannelId(player, mapChannelId) === cId) return player; + } + return null; + } + + /** Find a player by its channel ID across all guilds. @param {string} channelId @returns {Player|null} */ + getPlayerByChannelId(channelId) { + const cId = cleanId(channelId); + for (const [, channelSet] of this._guildPlayerIndex) { + for (const mapChannelId of channelSet) { + const player = this.playerMap.get(mapChannelId); + if (player && getPlayerChannelId(player, mapChannelId) === cId) return player; + } + } + return null; + } + + /** Get or spawn a player for the message's voice channel. @async @param {object} message @param {boolean} [promptJoin=true] @param {boolean} [verifyUser=true] @param {boolean} [shouldJoin=false] @returns {Promise} */ + async getPlayer(message, promptJoin = true, verifyUser = true, shouldJoin = false) { + const guildId = getMessageGuildId(message); + const cleanGuildId = cleanId(guildId); + + const { channelId: userChannelId } = await this.checkVoiceChannels(message); + const cleanUserChannelId = cleanId(userChannelId); + + if (cleanUserChannelId) { + const player = this.playerMap.get(cleanUserChannelId) + ?? this.getPlayerByGuildAndChannel(cleanGuildId, cleanUserChannelId); + if (player) { + player.textChannel = message.channel?.channel ?? message.channel; + try { + const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null; + if (guildId && textChannelId) { + this.settings.getServer(guildId)?.set("announcementChannelId", textChannelId); + } + } catch(e) { + logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message); + } + return player; + } + if (this._pendingJoins.has(cleanUserChannelId)) { + return null; + } + } + + const serverPlayers = cleanGuildId + ? this.getGuildPlayers(cleanGuildId) + : []; + + if (serverPlayers.length > 0) { + const channelList = serverPlayers.map(([chId]) => `<#${chId}>`).join(" or "); + + if (!userChannelId) { + if (!verifyUser) { + const first = serverPlayers[0]; + first[1].textChannel = message.channel?.channel ?? message.channel; + return first[1]; + } + message.reply(this._t(message, "responses._common.noVoiceStrict")); + return null; + } + + const match = serverPlayers.find(([, player]) => + getPlayerChannelId(player) === cleanUserChannelId + ); + if (match) { + match[1].textChannel = message.channel?.channel ?? message.channel; + try { + const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null; + if (cleanGuildId && textChannelId) { + this.settings.getServer(cleanGuildId)?.set("announcementChannelId", textChannelId); + } + } catch(e) { + logger.warn("[PlayerManager] Failed to save announcement channel ID:", e?.message); + } + return match[1]; + } + + if (shouldJoin) { + return this.initPlayer(message, userChannelId); + } + + const prefix = this.commands.getPrefix(guildId); + message.reply(this._t(message, "responses._common.alreadyInChannel", { channels: channelList, prefix })); + return null; + } + + if (!userChannelId) { + if (shouldJoin) { + return this.promptVC(message); + } + message.reply(this._t(message, "responses._common.noVoiceChannel")); + return null; + } + + if (shouldJoin) { + return this.initPlayer(message, userChannelId); + } + + return null; + } + +} + +// Attach the split-out concerns: dashboard event wiring (PlayerEventsMixin) +// and voice-channel detection / player lifecycle (PlayerLifecycleMixin). +applyMixins(PlayerManager, PlayerEventsMixin, PlayerLifecycleMixin); diff --git a/src/music/audio/FluxerAudioBridge.mjs b/src/music/audio/FluxerAudioBridge.mjs new file mode 100644 index 0000000..fc31593 --- /dev/null +++ b/src/music/audio/FluxerAudioBridge.mjs @@ -0,0 +1,419 @@ +/** @module src/music/audio/FluxerAudioBridge @description Audio bridge for streaming Lavalink/NodeLink audio through Fluxer voice connections. 100% in-process — Opus encoding via prism-media (native/WASM), WebM muxing via WebMOpusMuxer. No FFmpeg processes. Supports MP3/AAC/radio streams via Lavalink resolve-through. Base class: lifecycle (play/stop/destroy), state getters, volume and cleanup. Stream pipeline building and Lavalink REST HTTP helpers live in the StreamPipeline/HttpStreams mixin modules applied at the bottom of this file. */ + +import { logger } from "../../core/Logger.mjs"; +import { EventEmitter } from "node:events"; +import { Readable } from "node:stream"; +import { applyMixins } from "../../utils/mixins.mjs"; +import StreamPipeline from "./StreamPipeline.mjs"; +import HttpStreams from "./HttpStreams.mjs"; + +/** @type {number} @description livekit TrackKind.KIND_AUDIO — publications with this kind are managed by the bridge. */ +const TRACK_KIND_AUDIO = 1; + +/** @extends {EventEmitter} */ +export class FluxerAudioBridge extends EventEmitter { + _conn = null; + _stream = null; + _encoder = null; + _sourceStream = null; + _sourceReq = null; + _playing = false; + _stopped = false; + _startedAt = 0; + _currentUri = null; + _lavalink = null; + _playGeneration = 0; + _durationTimer = null; + _endResolve = null; + _endReject = null; + _usedTrackstream = false; + + /** @type {boolean} @description Whether audio is currently playing. */ + get playing() { return this._playing; } + /** @type {number} @description Timestamp (ms) when playback started. */ + get startedAt() { return this._startedAt; } + /** @type {string|null} @description URI of the currently playing track. */ + get currentUri() { return this._currentUri; } + + /** @param {LavalinkManager|null} lavalinkManager - LavalinkManager for trackstream/loadstream. */ + constructor(lavalinkManager = null) { + super(); + this._lavalink = lavalinkManager; + } + + /** + * Play a track through a Fluxer voice connection, entirely in-process. + * Routing order: + * 1. trackstream passthrough (seek=0, no filters) — NodeLink hands back a WebM/Opus + * direct URL which the voice connection plays natively (zero re-encode). + * 2. loadstream — NodeLink returns raw PCM (48k stereo s16le) with server-side + * seek/filters; PCM is Opus-encoded in-process and muxed to WebM. + * 3. direct URL fallback — magic-byte sniff: WebM passthrough or Ogg/Opus remux. + * @param {object} conn - Fluxer voice connection + * @param {object} trackInfo - Track metadata (encoded, title, url, guildId) + * @param {object} [options] + * @param {number} [options.seekSeconds=0] + * @param {number} [options.durationMs=0] + * @param {object} [options.filterPayload] + * @returns {Promise<"finished"|"stopped">} + */ + async play(conn, trackInfo, options = {}) { + this.stop(); + if (!conn) throw new Error("[AudioBridge] No voice connection provided"); + + this._unpublishStaleAudioTracks(conn); + + const generation = ++this._playGeneration; + this._conn = conn; + this._playing = true; + this._stopped = false; + this._startedAt = Date.now(); + this._currentUri = trackInfo?.url ?? trackInfo?.title ?? "unknown"; + this._usedTrackstream = false; + + const seekMs = Math.floor((options.seekSeconds ?? 0) * 1000); + let durationMs = options.durationMs || 0; + + try { + if (seekMs === 0 && !options.filterPayload && trackInfo.encoded && this._lavalink) { + try { + const direct = await this._getTrackstreamUrl(trackInfo); + if (direct?.url && /webm|opus/i.test(direct.format || "")) { + this._usedTrackstream = true; + logger.player("[AudioBridge] Passthrough webm/opus via trackstream (zero-copy): " + (trackInfo.title || "unknown")); + + await conn.play(direct.url); + if (generation !== this._playGeneration) return "stopped"; + + if (durationMs > 0) await this._waitDuration(durationMs); + if (generation !== this._playGeneration) return "stopped"; + + if (this._playing && !this._stopped) { + this._playing = false; + logger.player("[AudioBridge] Track finished naturally (trackstream passthrough)"); + return "finished"; + } + return "stopped"; + } + if (direct?.url && this._lavalink && trackInfo.url && trackInfo.url.startsWith("http")) { + logger.player("[AudioBridge] trackstream format " + (direct.format || "?") + " — resolving original source URL via Lavalink for fresh encoded track..."); + const freshEncoded = await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId); + if (freshEncoded) { + trackInfo.encoded = freshEncoded; + logger.player("[AudioBridge] Fresh encoded track obtained — retrying trackstream for webm/opus..."); + try { + const freshDirect = await this._getTrackstreamUrl(trackInfo); + if (freshDirect?.url && /webm|opus/i.test(freshDirect.format || "")) { + this._usedTrackstream = true; + logger.player("[AudioBridge] Fresh trackstream is webm/opus — zero-copy passthrough: " + (trackInfo.title || "unknown")); + await conn.play(freshDirect.url); + if (generation !== this._playGeneration) return "stopped"; + if (durationMs > 0) await this._waitDuration(durationMs); + if (generation !== this._playGeneration) return "stopped"; + if (this._playing && !this._stopped) { + this._playing = false; + logger.player("[AudioBridge] Track finished naturally (fresh trackstream passthrough)"); + return "finished"; + } + return "stopped"; + } + logger.player("[AudioBridge] Fresh trackstream also " + (freshDirect?.format || "?") + ", falling through to loadstream"); + } catch (e2) { + logger.player("[AudioBridge] Fresh trackstream failed, falling through to loadstream: " + e2.message); + } + } else { + logger.player("[AudioBridge] Could not resolve source URL via Lavalink, using original encoded track for loadstream"); + } + } else { + logger.player("[AudioBridge] trackstream format not opus/webm (" + (direct?.format || "?") + "), falling through to loadstream"); + } + } catch (e) { + logger.warn("[AudioBridge] Trackstream failed, falling back to loadstream: " + e.message); + this._playing = true; + this._stopped = false; + this._startedAt = Date.now(); + } + } + + if (trackInfo.encoded && this._lavalink) { + const loaded = await this._streamFromLoadstream(trackInfo, seekMs, options.filterPayload); + if (generation !== this._playGeneration) { + loaded.stream.destroy(); + return "stopped"; + } + + const routed = await this._routeByMagic(loaded.stream); + this._sourceStream = loaded.stream; + this._sourceReq = loaded.req || null; + + if (routed.kind === "webm") { + logger.player("[AudioBridge] Playing loadstream webm/opus passthrough: " + (trackInfo.title || "unknown") + + (seekMs > 0 ? " [seek: " + seekMs + "ms]" : "")); + this._stream = routed.stream; + await conn.play(routed.stream); + } else if (routed.kind === "ogg") { + logger.player("[AudioBridge] Playing loadstream ogg/opus (remux to webm): " + (trackInfo.title || "unknown")); + const oggResult = await this._remuxOggToWebM(routed.stream); + this._stream = oggResult; + if (durationMs <= 0) durationMs = oggResult.getDurationMs(); + await conn.play(this._stream); + } else { + logger.player("[AudioBridge] Playing via loadstream PCM -> in-process Opus: " + (trackInfo.title || "unknown") + + (seekMs > 0 ? " [seek: " + seekMs + "ms]" : "") + + (options.filterPayload ? " [filters]" : "")); + this._stream = this._buildPcmPipeline(routed.stream); + await conn.play(this._stream); + } + if (generation !== this._playGeneration) return "stopped"; + + await this._awaitEnd(durationMs); + if (generation !== this._playGeneration) return "stopped"; + + if (this._playing && !this._stopped) { + this._playing = false; + logger.player("[AudioBridge] Track finished naturally (loadstream)"); + return "finished"; + } + return "stopped"; + } + + if (trackInfo.url && trackInfo.url.startsWith("http")) { + logger.player("[AudioBridge] Route 3: Fetching directly: " + trackInfo.url.substring(0, 80) + "..."); + const response = await fetch(trackInfo.url, { + headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)" }, + redirect: "follow", + }); + if (!response.ok) { + throw new Error("HTTP " + response.status + " for " + trackInfo.url); + } + const stream = Readable.fromWeb(response.body); + this._sourceStream = stream; + + const routed = await this._routeByMagic(stream); + if (routed.kind === "webm") { + logger.player("[AudioBridge] Route 3a: webm/opus passthrough: " + (trackInfo.title || "unknown")); + this._stream = routed.stream; + await conn.play(routed.stream); + } else if (routed.kind === "ogg") { + logger.player("[AudioBridge] Route 3b: ogg/opus remux to webm: " + (trackInfo.title || "unknown")); + const oggResult = await this._remuxOggToWebM(routed.stream); + this._stream = oggResult; + await conn.play(this._stream); + if (generation !== this._playGeneration) return "stopped"; + + await new Promise(r => { + if (this._stream.readableEnded) return r(); + const done = () => { this._stream.off("end", done); this._stream.off("close", done); r(); }; + this._stream.once("end", done); + this._stream.once("close", done); + }); + if (generation !== this._playGeneration) return "stopped"; + + const fullDurationMs = oggResult.getDurationMs(); + const elapsedMs = Date.now() - this._startedAt; + const remainingMs = Math.max(0, fullDurationMs - elapsedMs); + logger.player("[AudioBridge] Route 3b: OGG " + fullDurationMs + "ms total, " + elapsedMs + "ms elapsed, waiting " + remainingMs + "ms more"); + + if (remainingMs > 0) await this._awaitEnd(remainingMs); + if (generation !== this._playGeneration) return "stopped"; + + if (this._playing && !this._stopped) { + this._playing = false; + logger.player("[AudioBridge] Track finished naturally (direct URL, OGG remux)"); + return "finished"; + } + return "stopped"; + } else { + stream.destroy(); + this._sourceStream = null; + logger.player("[AudioBridge] Route 3c: Direct stream is " + routed.kind + " (MP3/AAC?) — resolving through Lavalink..."); + + if (this._lavalink) { + const encoded = await this._resolveUrlViaLavalink(trackInfo.url, trackInfo.guildId); + if (encoded) { + trackInfo.encoded = encoded; + logger.player("[AudioBridge] Route 3c: Got encoded track from Lavalink, retrying via loadstream..."); + const loaded = await this._streamFromLoadstream(trackInfo, 0, null); + if (generation !== this._playGeneration) { + loaded.stream.destroy(); + return "stopped"; + } + + const routed2 = await this._routeByMagic(loaded.stream); + this._sourceStream = loaded.stream; + this._sourceReq = loaded.req || null; + + if (routed2.kind === "webm") { + logger.player("[AudioBridge] Route 3c (Lavalink): webm/opus passthrough"); + this._stream = routed2.stream; + await conn.play(routed2.stream); + } else if (routed2.kind === "ogg") { + logger.player("[AudioBridge] Route 3c (Lavalink): ogg/opus remux to webm"); + const oggResult3c = await this._remuxOggToWebM(routed2.stream); + this._stream = oggResult3c; + if (durationMs <= 0) durationMs = oggResult3c.getDurationMs(); + await conn.play(this._stream); + } else { + logger.player("[AudioBridge] Route 3c (Lavalink): PCM -> Opus -> WebM"); + this._stream = this._buildPcmPipeline(routed2.stream); + await conn.play(this._stream); + } + if (generation !== this._playGeneration) return "stopped"; + + await this._awaitEnd(durationMs); + if (generation !== this._playGeneration) return "stopped"; + + if (this._playing && !this._stopped) { + this._playing = false; + logger.player("[AudioBridge] Track finished naturally (Route 3c Lavalink resolve)"); + return "finished"; + } + return "stopped"; + } + } + + throw new Error( + "[AudioBridge] Direct URL is not WebM/Opus or Ogg/Opus (" + routed.kind + "). " + + "Lavalink resolve also failed or is unavailable. " + + "Make sure your Lavalink/NodeLink node is running and can decode this stream format." + ); + } + if (generation !== this._playGeneration) return "stopped"; + + await this._awaitEnd(durationMs); + if (generation !== this._playGeneration) return "stopped"; + + if (this._playing && !this._stopped) { + this._playing = false; + logger.player("[AudioBridge] Track finished naturally (direct URL)"); + return "finished"; + } + return "stopped"; + } + + throw new Error("Could not get audio stream for: " + (trackInfo.title || trackInfo.url || "unknown")); + + } catch (e) { + if (generation !== this._playGeneration) return "stopped"; + if (this._stopped || !this._playing) return "stopped"; + this._playing = false; + logger.error("[AudioBridge] Playback error: " + e.message); + throw e; + } finally { + this._cleanup(); + } + } + + /** Stop current playback and clean up resources. */ + stop() { + const wasPlaying = this._playing; + this._stopped = true; + this._playing = false; + this._playGeneration++; + + this._cleanup(); + + if (this._conn) { + try { this._conn.stop(); } catch (_) {} + this._unpublishStaleAudioTracks(this._conn); + } + + if (wasPlaying) { + this.emit("stopped"); + logger.player("[AudioBridge] Playback stopped"); + } + } + + /** + * @param {object} conn - Fluxer voice connection + * @param {string|null} [keepSid=null] - Track SID to keep (currently active publication) + * @private + */ + _unpublishStaleAudioTracks(conn, keepSid = null) { + try { + const room = conn?.room; + const participant = room?.localParticipant; + if (!room?.isConnected || typeof participant?.unpublishTrack !== "function") return; + + const publications = participant.trackPublications; + if (!publications || typeof publications.entries !== "function") return; + + for (const [sid, pub] of publications.entries()) { + if (keepSid && sid === keepSid) continue; + if (pub?.kind !== TRACK_KIND_AUDIO) continue; + try { + const p = participant.unpublishTrack(sid, true); + if (p?.catch) p.catch(() => {}); + logger.player("[AudioBridge] Unpublished stale audio track: " + sid); + } catch (_) {} + } + } catch (_) { + } + } + + /** + * Set the playback volume on the voice connection. + * @param {number} percent - Volume 0–100. + */ + setVolume(percent) { + if (this._conn) { + try { this._conn.setVolume(percent); } catch (e) { + logger.warn("[AudioBridge] setVolume error: " + e.message); + } + } + } + + /** @returns {number} Current volume percentage (0–100). */ + getVolume() { + if (this._conn) { + try { return this._conn.getVolume(); } catch (_) {} + } + return 100; + } + + /** @returns {boolean} Whether the voice connection is currently active. */ + isConnected() { + if (this._conn) { + try { return this._conn.isConnected(); } catch (_) {} + } + return false; + } + + /** + * Clear timers, settle pending waits, and tear down the pipeline. + * @private + */ + _cleanup() { + if (this._durationTimer) { clearTimeout(this._durationTimer); this._durationTimer = null; } + if (this._endResolve) { + const resolve = this._endResolve; + this._endResolve = null; + this._endReject = null; + resolve(); + } + for (const s of [this._stream, this._encoder, this._sourceStream]) { + if (s) { + try { s.destroy(); } catch (_) {} + } + } + if (this._sourceReq) { + try { this._sourceReq.destroy(); } catch (_) {} + } + this._stream = null; + this._encoder = null; + this._sourceStream = null; + this._sourceReq = null; + } + + /** Stop playback, release the voice connection, and remove all listeners. */ + destroy() { + this.stop(); + this._conn = null; + this._currentUri = null; + this.removeAllListeners(); + } +} + +// Attach the split-out concerns: stream pipeline building/routing +// (StreamPipeline) and Lavalink REST HTTP helpers (HttpStreams). +applyMixins(FluxerAudioBridge, StreamPipeline, HttpStreams); diff --git a/src/music/audio/HttpStreams.mjs b/src/music/audio/HttpStreams.mjs new file mode 100644 index 0000000..4f0e31f --- /dev/null +++ b/src/music/audio/HttpStreams.mjs @@ -0,0 +1,185 @@ +/** + * @module src/music/audio/HttpStreams + * @description HTTP helper concern for {@link FluxerAudioBridge}: GET-JSON + * with redirect following and streaming GET with connect/idle timeouts, + * used for the Lavalink/NodeLink REST endpoints (trackstream, loadstream, + * loadtracks). + * + * These methods are applied onto the FluxerAudioBridge class prototype via + * {@link module:src/utils/mixins.applyMixins} — `this` is a + * FluxerAudioBridge instance. + */ + +import { logger } from "../../core/Logger.mjs"; +import http from "node:http"; +import https from "node:https"; + +/** @type {number} @description Maximum number of HTTP redirect hops to follow. */ +const MAX_REDIRECTS = 5; + +/** @type {number} @description Timeout (ms) for HTTP requests to Lavalink REST endpoints (trackstream, loadtracks JSON). */ +const REST_REQUEST_TIMEOUT_MS = 15_000; + +/** @type {number} @description Timeout (ms) to wait for the first byte from loadstream (Lavalink may need time to resolve HLS/external streams). */ +const LOADSTREAM_CONNECT_TIMEOUT_MS = 60_000; + +/** @type {number} @description Idle timeout (ms) once loadstream data is flowing — if no data arrives for this long, abort. */ +const LOADSTREAM_IDLE_TIMEOUT_MS = 30_000; + +/** + * @type {object} + * @description HTTP streams mixin — applied to FluxerAudioBridge. + */ +const HttpStreams = { + /** + * @param {string} url + * @param {object} [headers] + * @returns {Promise} + * @private + */ + _httpGetJson(url, headers = {}, _redirectCount = 0, timeoutMs = REST_REQUEST_TIMEOUT_MS) { + return new Promise((resolve, reject) => { + if (_redirectCount >= MAX_REDIRECTS) { + return reject(new Error("Too many redirects (" + _redirectCount + ")")); + } + const urlObj = new URL(url); + const client = urlObj.protocol === "https:" ? https : http; + + const req = client.request({ + protocol: urlObj.protocol, + host: urlObj.hostname, + port: urlObj.port, + path: urlObj.pathname + urlObj.search, + method: "GET", + headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)", ...headers }, + }, (res) => { + if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { + res.resume(); + let loc = res.headers.location; + if (loc.startsWith("/")) loc = urlObj.protocol + "//" + urlObj.host + loc; + return this._httpGetJson(loc, headers, _redirectCount + 1, timeoutMs).then(resolve, reject); + } + if (res.statusCode !== 200) { + let body = ""; + res.on("data", (chunk) => { body += chunk; }); + res.on("end", () => { + reject(new Error("HTTP " + res.statusCode + " for " + url + ": " + body.substring(0, 300))); + }); + return; + } + + let data = ""; + res.on("data", (chunk) => { data += chunk; }); + res.on("end", () => { + try { + resolve(JSON.parse(data)); + } catch (e) { + reject(new Error("Invalid JSON from trackstream: " + data.substring(0, 200))); + } + }); + }); + + req.on("socket", (socket) => { + socket.on("error", () => {}); + }); + req.on("error", reject); + req.setTimeout(timeoutMs, () => { + req.destroy(); + reject(new Error("REST request timeout (" + timeoutMs / 1000 + "s)")); + }); + req.end(); + }); + }, + + /** + * @param {string} url + * @param {object} [headers] + * @param {number} [_redirectCount=0] + * @returns {Promise<{stream: Readable, inputFormat: string|null, req: http.ClientRequest}>} + * @private + */ + _httpRequestStream(url, headers = {}, _redirectCount = 0) { + return new Promise((resolve, reject) => { + if (_redirectCount >= MAX_REDIRECTS) { + return reject(new Error("Too many redirects (" + _redirectCount + ")")); + } + + const urlObj = new URL(url); + const client = urlObj.protocol === "https:" ? https : http; + let firstByte = true; + let connectTimer = null; + let idleTimer = null; + + const resetIdleTimeout = () => { + if (idleTimer) clearTimeout(idleTimer); + idleTimer = setTimeout(() => { + req.destroy(); + reject(new Error("loadstream idle timeout (" + LOADSTREAM_IDLE_TIMEOUT_MS / 1000 + "s no data)")); + }, LOADSTREAM_IDLE_TIMEOUT_MS); + idleTimer.unref?.(); + }; + + const req = client.request({ + protocol: urlObj.protocol, + host: urlObj.hostname, + port: urlObj.port, + path: urlObj.pathname + urlObj.search, + method: "GET", + headers: { "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)", ...headers }, + }, (res) => { + if (res.statusCode >= 300 && res.statusCode < 400 && res.headers.location) { + if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; } + res.resume(); + let nextHeaders = headers; + let loc = res.headers.location; + if (loc.startsWith("/")) loc = urlObj.protocol + "//" + urlObj.host + loc; + try { + const redirectHost = new URL(loc).hostname; + if (redirectHost !== urlObj.hostname) { + const { Authorization, "Session-Id": _, ...safe } = headers; + nextHeaders = safe; + } + } catch (_) {} + return this._httpRequestStream(loc, nextHeaders, _redirectCount + 1).then(resolve, reject); + } + if (res.statusCode !== 200) { + if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; } + let body = ""; + res.on("data", (chunk) => { body += chunk; }); + res.on("end", () => { + reject(new Error("HTTP " + res.statusCode + " for " + url + ": " + body.substring(0, 300))); + }); + return; + } + + if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; } + resetIdleTimeout(); + res.once("data", () => resetIdleTimeout()); + + logger.player("[AudioBridge] loadstream response: " + res.statusCode + " content-type=" + (res.headers["content-type"] || "?")); + resolve({ stream: res, inputFormat: res.headers["content-type"] || null, req }); + }); + + req.on("socket", (socket) => { + socket.on("error", () => {}); + }); + + req.on("error", (err) => { + if (connectTimer) { clearTimeout(connectTimer); connectTimer = null; } + if (idleTimer) { clearTimeout(idleTimer); idleTimer = null; } + reject(err); + }); + + connectTimer = setTimeout(() => { + req.destroy(); + reject(new Error("loadstream connect timeout (" + LOADSTREAM_CONNECT_TIMEOUT_MS / 1000 + "s — Lavalink took too long to start stream)")); + }, LOADSTREAM_CONNECT_TIMEOUT_MS); + connectTimer.unref?.(); + + req.end(); + }); + }, +}; + +export default HttpStreams; +export { HttpStreams }; diff --git a/src/music/audio/StreamPipeline.mjs b/src/music/audio/StreamPipeline.mjs new file mode 100644 index 0000000..79557b1 --- /dev/null +++ b/src/music/audio/StreamPipeline.mjs @@ -0,0 +1,326 @@ +/** + * @module src/music/audio/StreamPipeline + * @description Stream pipeline concern for {@link FluxerAudioBridge}: + * end-of-playback waiting, magic-byte routing, the in-process PCM -> Opus -> + * WebM pipeline, Ogg/Opus remuxing, trackstream/loadstream URL handling and + * Lavalink URL resolution. + * + * These methods are applied onto the FluxerAudioBridge class prototype via + * {@link module:src/utils/mixins.applyMixins} — `this` is a + * FluxerAudioBridge instance. + */ + +import { logger } from "../../core/Logger.mjs"; +import { WebMOpusMuxer, OPUS_FRAME_MS } from "./WebMOpusMuxer.mjs"; +import prismMedia from "prism-media"; + +const { Encoder: PrismOpusEncoder, OggDemuxer: PrismOggDemuxer } = prismMedia.opus; + +/** @type {number} @description PCM sample rate expected from NodeLink loadstream (48kHz stereo s16le). */ +const PCM_RATE = 48000; +/** @type {number} @description PCM channel count expected from NodeLink loadstream. */ +const PCM_CHANNELS = 2; +/** @type {number} @description Opus frame size in samples per channel (20ms @ 48kHz). */ +const PCM_FRAME_SIZE = 960; +/** @type {number} @description Opus encoding bitrate. */ +const OPUS_BITRATE = 128000; + +/** @type {Buffer} @description WebM/Matroska EBML magic bytes. */ +const WEBM_MAGIC = Buffer.from([0x1a, 0x45, 0xdf, 0xa3]); +/** @type {Buffer} @description OGG container magic bytes ("OggS"). */ +const OGG_MAGIC = Buffer.from("OggS", "ascii"); + +/** + * @type {object} + * @description Stream pipeline mixin — applied to FluxerAudioBridge. + */ +const StreamPipeline = { + /** + * Wait for playback end: duration timer for fixed-length tracks, pipeline + * end event for live/radio streams (durationMs = 0). Rejects early on + * pipeline errors so the player can skip to the next track. + * @param {number} durationMs + * @returns {Promise} + * @private + */ + _awaitEnd(durationMs) { return new Promise((resolve, reject) => { + this._endResolve = resolve; + this._endReject = reject; + const failFast = (err) => { + if (this._playing && !this._stopped) { + this._playing = false; + reject(err); + } else { + resolve(); + } + }; + + if (durationMs > 0) { + this._durationTimer = setTimeout(resolve, durationMs); + } else { + const stream = this._stream; + if (!stream) return resolve(); + const onEnd = () => resolve(); + stream.once("end", onEnd); + stream.once("close", onEnd); + stream.once("error", failFast); + } + + if (this._sourceStream) { + this._sourceStream.once("error", failFast); + } + if (this._encoder) { + this._encoder.once("error", failFast); + } + }); + }, + + /** + * Simple timed wait used by the trackstream passthrough route (no local + * pipeline to watch). Resolves early if stopped. + * @param {number} durationMs + * @returns {Promise} + * @private + */ + _waitDuration(durationMs) { + return new Promise((resolve) => { + const timer = setTimeout(() => { + this._durationTimer = null; + resolve(); + }, durationMs); + this._durationTimer = timer; + }); + }, + + /** + * Peek at the first bytes of a stream and classify it, pushing the peeked + * bytes back so nothing is lost. + * @param {Readable} stream + * @returns {Promise<{stream: Readable, kind: "webm"|"ogg"|"pcm"}>} + * @private + */ + async _routeByMagic(stream) { + const head = await this._peek(stream, 4); + if (head.length >= 4 && head.subarray(0, 4).equals(WEBM_MAGIC)) return { stream, kind: "webm" }; + if (head.length >= 4 && head.subarray(0, 4).equals(OGG_MAGIC)) return { stream, kind: "ogg" }; + return { stream, kind: "pcm" }; + }, + + /** + * Read up to `n` bytes from a paused-mode stream, then unshift them. + * @param {Readable} stream + * @param {number} n + * @returns {Promise} + * @private + */ + _peek(stream, n) { + return new Promise((resolve, reject) => { + const tryRead = () => { + const chunks = []; + let total = 0; + let chunk; + while (total < n && (chunk = stream.read()) !== null) { + chunks.push(chunk); + total += chunk.length; + } + if (total >= n || stream.readableEnded) { + const buf = Buffer.concat(chunks); + cleanup(); + if (buf.length > 0) stream.unshift(buf); + resolve(buf.subarray(0, n)); + return; + } + }; + const onReadable = () => { cleanup(); tryRead(); }; + const onEnd = () => { cleanup(); tryRead(); }; + const onError = (err) => { cleanup(); reject(err); }; + const cleanup = () => { + stream.off("readable", onReadable); + stream.off("end", onEnd); + stream.off("error", onError); + }; + stream.once("readable", onReadable); + stream.once("end", onEnd); + stream.once("error", onError); + tryRead(); + }); + }, + + /** + * Build the in-process PCM -> Opus -> WebM pipeline. + * @param {Readable} pcmStream - s16le 48kHz stereo byte stream + * @returns {WebMOpusMuxer} - byte stream consumable by conn.play() + * @private + */ + _buildPcmPipeline(pcmStream) { + let encoder; + try { + encoder = new PrismOpusEncoder({ + rate: PCM_RATE, + channels: PCM_CHANNELS, + frameSize: PCM_FRAME_SIZE, + }); + } catch (e) { + pcmStream.destroy(); + throw new Error( + "No Opus encoder available (" + e.message + "). Install one: npm install opusscript" + ); + } + try { encoder.setBitrate(OPUS_BITRATE); } catch (_) {} + + const muxer = new WebMOpusMuxer({ sampleRate: PCM_RATE, channels: PCM_CHANNELS }); + this._encoder = encoder; + + pcmStream.on("error", (err) => { + logger.warn("[AudioBridge] PCM source error: " + err.message); + encoder.destroy(err); + }); + encoder.on("error", (err) => { + muxer.destroy(err); + }); + + pcmStream.pipe(encoder).pipe(muxer); + return muxer; + }, + + /** + * Remux an Ogg/Opus stream into WebM/Opus (packet-level, no re-encode). + * @param {Readable} oggStream + * @returns {Promise<{stream: WebMOpusMuxer, getDurationMs: function}>} + * @private + */ + async _remuxOggToWebM(oggStream) { + const demuxer = new PrismOggDemuxer(); + const muxer = new WebMOpusMuxer(); + oggStream.on("error", (err) => demuxer.destroy(err)); + demuxer.on("error", (err) => muxer.destroy(err)); + let frameCount = 0; + demuxer.on("data", () => { frameCount++; }); + const headPromise = new Promise((resolve, reject) => { + demuxer.once("head", () => resolve()); + demuxer.once("error", (err) => reject(new Error("OGG demux: " + err.message))); + oggStream.once("error", (err) => reject(new Error("OGG source: " + err.message))); + }); + oggStream.pipe(demuxer).pipe(muxer); + await headPromise; + const wrapper = Object.create(muxer); + wrapper.getDurationMs = () => frameCount * OPUS_FRAME_MS; + return wrapper; + }, + + /** + * @param {object} trackInfo + * @returns {Promise<{url: string, format: string}>} + * @private + */ + async _getTrackstreamUrl(trackInfo) { + const nlInfo = this._lavalink.getNodeLinkInfo?.(); + if (!nlInfo) throw new Error("NodeLink info not available"); + + const protocol = nlInfo.secure ? "https" : "http"; + const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port; + + const headers = { "Authorization": nlInfo.password }; + if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId; + if (trackInfo.guildId) headers["Guild-Id"] = trackInfo.guildId; + + const params = "encodedTrack=" + encodeURIComponent(trackInfo.encoded); + const url = baseUrl + "/v4/trackstream?" + params; + + logger.player("[AudioBridge] Querying /v4/trackstream..."); + + const body = await this._httpGetJson(url, headers); + + const directUrl = body?.url; + if (!directUrl || typeof directUrl !== "string") { + throw new Error("trackstream returned no URL"); + } + + const format = body?.format || ""; + logger.player("[AudioBridge] trackstream: format=" + format + " url=" + directUrl.substring(0, 100) + "..."); + + return { url: directUrl, format }; + }, + + /** + * @param {object} trackInfo + * @param {number} [seekMs=0] + * @param {object|null} [filterPayload] + * @returns {Promise<{stream: Readable, inputFormat: string|null}>} + * @private + */ + async _streamFromLoadstream(trackInfo, seekMs = 0, filterPayload = null) { + const nlInfo = this._lavalink.getNodeLinkInfo?.(); + if (!nlInfo) { + throw new Error("NodeLink info not available"); + } + + const protocol = nlInfo.secure ? "https" : "http"; + const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port; + + const headers = { "Authorization": nlInfo.password }; + if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId; + if (trackInfo.guildId) headers["Guild-Id"] = trackInfo.guildId; + + let baseParams = "encodedTrack=" + encodeURIComponent(trackInfo.encoded) + "&position=" + seekMs + "&volume=100"; + if (filterPayload) { + baseParams += "&filters=" + encodeURIComponent(JSON.stringify(filterPayload)); + } + + const url = baseUrl + "/v4/loadstream?" + baseParams; + logger.player("[AudioBridge] Querying /v4/loadstream (seek: " + seekMs + "ms)..."); + + return this._httpRequestStream(url, headers); + }, + + /** + * Resolve a direct audio URL through Lavalink's /v4/loadtracks to get an encoded track. + * This allows MP3/AAC radio streams and direct audio URLs to be played through + * the loadstream pipeline without any FFmpeg dependency. + * @param {string} url - The HTTP(S) audio stream URL to resolve. + * @param {string} [guildId] - Optional guild ID for the request. + * @returns {Promise} The encoded track string, or null if resolution failed. + * @private + */ + async _resolveUrlViaLavalink(url, guildId) { + try { + const nlInfo = this._lavalink.getNodeLinkInfo?.(); + if (!nlInfo) { + logger.warn("[AudioBridge] _resolveUrlViaLavalink: no NodeLink info"); + return null; + } + + const protocol = nlInfo.secure ? "https" : "http"; + const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port; + + const headers = { "Authorization": nlInfo.password }; + if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId; + if (guildId) headers["Guild-Id"] = guildId; + + const params = "identifier=" + encodeURIComponent(url); + const loadtracksUrl = baseUrl + "/v4/loadtracks?" + params; + + logger.player("[AudioBridge] Resolving URL via Lavalink /v4/loadtracks: " + url.substring(0, 80) + "..."); + + const body = await this._httpGetJson(loadtracksUrl, headers, 0, 30_000); + + const track = body?.data?.tracks?.[0] ?? body?.tracks?.[0] ?? body?.data; + const encoded = track?.encoded ?? track?.data; + + if (encoded && typeof encoded === "string") { + logger.player("[AudioBridge] Lavalink resolved URL to encoded track successfully"); + return encoded; + } + + const loadType = body?.loadType ?? body?.data?.loadType; + logger.warn("[AudioBridge] Lavalink loadtracks returned no playable track (loadType=" + loadType + ")"); + return null; + } catch (e) { + logger.warn("[AudioBridge] _resolveUrlViaLavalink failed: " + e.message); + return null; + } + }, +}; + +export default StreamPipeline; +export { StreamPipeline }; diff --git a/src/music/audio/Tuna.mjs b/src/music/audio/Tuna.mjs new file mode 100644 index 0000000..0702b39 --- /dev/null +++ b/src/music/audio/Tuna.mjs @@ -0,0 +1,107 @@ +/** @module constants/audio/Tuna */ + +import pkg from "follow-redirects"; +const { https } = pkg; + +/** + * Client for the Tuna (Voicemod) sound-effect API. + * @class + */ +class Tuna { + /** @private */ apiKey = null; + + /** + * @param {{ key: string }} auth - Object containing the API key. + */ + constructor(auth) { + this.apiKey = auth.key; + } + + /** + * Perform an authenticated GET request to the Tuna API. + * @private + * @async + * @param {string} path - API path (e.g. `"/v1/sounds/search"`). + * @param {Object} [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/music/audio/WebMOpusMuxer.mjs b/src/music/audio/WebMOpusMuxer.mjs new file mode 100644 index 0000000..8ba2b7d --- /dev/null +++ b/src/music/audio/WebMOpusMuxer.mjs @@ -0,0 +1,220 @@ +/** @module src/music/audio/WebMOpusMuxer @description Minimal streaming WebM/Matroska muxer for Opus packets. Produces streams consumable by prism-media's WebmDemuxer (what @fluxerjs/voice uses internally) — no FFmpeg required. */ + +import { Transform } from "node:stream"; + +/** @type {number} @description Opus frame duration in milliseconds (20ms = 960 samples @ 48kHz). */ +export const OPUS_FRAME_MS = 20; + +/** @type {number} @description Blocks per cluster before a new Cluster element is started. */ +const BLOCKS_PER_CLUSTER = 250; + +/** @type {number} @description Force a cluster flush when buffered blocks exceed this size. */ +const CLUSTER_FLUSH_BYTES = 64 * 1024; + +/** + * Encode a Matroska variable-length size integer (finite size). + * @param {number} value - Size to encode (must be >= 0). + * @returns {Buffer} + */ +function encodeSizeVint(value) { + let length = 1; + while (value > 2 ** (7 * length) - 1 && length < 8) length++; + const buf = Buffer.alloc(length); + for (let i = length - 1; i >= 0; i--) { + buf[i] = value & 0xff; + value = Math.floor(value / 256); + } + buf[0] |= 1 << (8 - length); + return buf; +} + +/** + * Build a single EBML element from an ID hex string and a payload Buffer. + * @param {string} idHex - EBML element ID as hex (e.g. "1a45dfa3"). + * @param {Buffer} payload + * @returns {Buffer} + */ +function element(idHex, payload) { + return Buffer.concat([Buffer.from(idHex, "hex"), encodeSizeVint(payload.length), payload]); +} + +/** + * Encode an unsigned integer EBML payload using minimal bytes. + * @param {number} value + * @returns {Buffer} + */ +function uintPayload(value) { + let bytes = 1; + while (value >= 2 ** (8 * bytes)) bytes++; + const buf = Buffer.alloc(bytes); + buf.writeUIntBE(value, 0, bytes); + return buf; +} + +/** + * Build the OpusHead codec private data (Matroska-embedded OpusHead). + * @param {number} sampleRate - Input sample rate (48000). + * @param {number} channels - Channel count (2). + * @returns {Buffer} + */ +export function buildOpusHead(sampleRate, channels) { + const buf = Buffer.alloc(19); + buf.write("OpusHead", 0, "ascii"); + buf.writeUInt8(1, 8); // version + buf.writeUInt8(channels, 9); + buf.writeUInt16LE(0, 10); // pre-skip (we encode ourselves; no trimming) + buf.writeUInt32LE(sampleRate, 12); + buf.writeInt16LE(0, 16); // output gain + buf.writeUInt8(0, 18); // mapping family (mono/stereo) + return buf; +} + +/** + * Build the WebM stream header: EBML + Segment start + Info + Tracks. + * The Segment element uses an unknown (streaming) size so clusters can be + * appended indefinitely. + * @param {number} sampleRate + * @param {number} channels + * @returns {Buffer} + */ +function buildHeader(sampleRate, channels) { + const ebml = element("1a45dfa3", Buffer.concat([ + element("4286", uintPayload(1)), // EBMLVersion + element("42f7", uintPayload(1)), // EBMLReadVersion + element("42f2", uintPayload(4)), // EBMLMaxIDLength + element("42f3", uintPayload(8)), // EBMLMaxSizeLength + element("4282", Buffer.from("webm", "ascii")), // DocType + element("4287", uintPayload(2)), // DocTypeVersion + element("4285", uintPayload(2)), // DocTypeReadVersion + ])); + + const info = element("1549a966", Buffer.concat([ + element("2ad7b1", uintPayload(1000000)), // TimecodeScale (1ms) + element("4d80", Buffer.from("fluxer-remix", "ascii")),// MuxingApp + element("5741", Buffer.from("fluxer-remix", "ascii")),// WritingApp + ])); + + const floatBuf = Buffer.alloc(4); + floatBuf.writeFloatBE(sampleRate, 0); + const audio = element("e1", Buffer.concat([ + element("b5", floatBuf), // SamplingFrequency + element("9f", uintPayload(channels)), // Channels + ])); + + const trackEntry = element("ae", Buffer.concat([ + element("d7", uintPayload(1)), // TrackNumber (must be 1 — demuxer masks data[0] & 0xF) + element("73c5", uintPayload(1)), // TrackUID + element("83", uintPayload(2)), // TrackType: audio + element("86", Buffer.from("A_OPUS", "ascii")), // CodecID + element("63a2", buildOpusHead(sampleRate, channels)), // CodecPrivate: OpusHead + audio, + ])); + const tracks = element("1654ae6b", trackEntry); + + // Streaming Segment size: a huge finite vint (0x01 + 7x0xFF = 2^56-1). The + // canonical all-0xFF unknown-size marker is misparsed by prism-media's + // vintLength (it reads 0xFF as a 1-byte vint), so we use this equivalent form. + const segmentStart = Buffer.concat([ + Buffer.from("18538067", "hex"), + Buffer.from([0x01, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff]), + ]); + + return Buffer.concat([ebml, segmentStart, info, tracks]); +} + +/** + * Build a SimpleBlock element for one Opus packet. + * @param {Buffer} packet - Raw Opus packet. + * @param {number} relTimeMs - Cluster-relative timestamp in ms. + * @returns {Buffer} + */ +function buildSimpleBlock(packet, relTimeMs) { + const clamped = Math.max(-32768, Math.min(32767, relTimeMs)); + const header = Buffer.from([0x81, (clamped >> 8) & 0xff, clamped & 0xff, 0x80]); + return element("a3", Buffer.concat([header, packet])); +} + +/** + * Streaming WebM muxer: consumes Opus packets (object mode) and emits a + * WebM/Opus byte stream compatible with prism-media's WebmDemuxer — the exact + * format @fluxerjs/voice's VoiceConnection.play() expects as input. + * @extends {Transform} + */ +export class WebMOpusMuxer extends Transform { + /** + * @param {object} [options] + * @param {number} [options.sampleRate=48000] + * @param {number} [options.channels=2] + */ + constructor(options = {}) { + super({ writableObjectMode: true }); + this._sampleRate = options.sampleRate ?? 48000; + this._channels = options.channels ?? 2; + this._header = buildHeader(this._sampleRate, this._channels); + this._blocks = []; + this._blocksBytes = 0; + this._blockIndex = 0; + this._clusterIndex = 0; + this._headerSent = false; + } + + /** + * Feed one Opus packet into the current cluster. + * @param {Buffer} packet + */ + _addBlock(packet) { + if (!this._headerSent) { + this.push(this._header); + this._headerSent = true; + } + const relTime = (this._blockIndex % BLOCKS_PER_CLUSTER) * OPUS_FRAME_MS; + const block = buildSimpleBlock(packet, relTime); + this._blocks.push(block); + this._blocksBytes += block.length; + this._blockIndex++; + if (this._blocks.length >= BLOCKS_PER_CLUSTER || this._blocksBytes >= CLUSTER_FLUSH_BYTES) { + this._flushCluster(); + } + } + + /** Emit the current cluster as a complete EBML element. */ + _flushCluster() { + if (this._blocks.length === 0) return; + const timecode = element("e7", uintPayload(this._clusterIndex * BLOCKS_PER_CLUSTER * OPUS_FRAME_MS)); + const cluster = element("1f43b675", Buffer.concat([timecode, ...this._blocks])); + this._blocks = []; + this._blocksBytes = 0; + this._clusterIndex++; + this.push(cluster); + } + + /** + * @param {Buffer} packet + * @param {string} _encoding + * @param {Function} callback + * @protected + */ + _transform(packet, _encoding, callback) { + try { + if (Buffer.isBuffer(packet) && packet.length > 0) { + this._addBlock(packet); + } + callback(); + } catch (err) { + callback(err); + } + } + + /** + * @param {Function} callback + * @protected + */ + _final(callback) { + try { + this._flushCluster(); + callback(); + } catch (err) { + callback(err); + } + } +} diff --git a/src/music/audio/index.mjs b/src/music/audio/index.mjs new file mode 100644 index 0000000..410bb43 --- /dev/null +++ b/src/music/audio/index.mjs @@ -0,0 +1,9 @@ +/** + * @module src/music/audio + * @description Public surface of the audio layer (Fluxer voice bridge). + * + * Import map from the old layout: + * - `src/FluxerAudioBridge.mjs` → this module (FluxerAudioBridge) + */ + +export { FluxerAudioBridge } from "./FluxerAudioBridge.mjs"; diff --git a/src/music/player/DisplayMixin.mjs b/src/music/player/DisplayMixin.mjs new file mode 100644 index 0000000..ad2b0c1 --- /dev/null +++ b/src/music/player/DisplayMixin.mjs @@ -0,0 +1,292 @@ +/** + * @module src/music/player/DisplayMixin + * @description User-facing rendering concern for {@link Player}: progress + * bars, now-playing announcements, queue listing, thumbnails and duration + * formatting. + * + * These methods are applied onto the Player class prototype via + * {@link applyMixins} — `this` is a Player instance. + */ + +import { EmbedBuilder } from "@fluxerjs/core"; +import { getGlobalColor } from "../../ui/index.mjs"; +import { Utils } from "../../utils/Utils.mjs"; +import { logger } from "../../core/Logger.mjs"; +import meta from "../probe.mjs"; + +/** + * @type {object} + * @description Display mixin — applied to Player. + */ +const DisplayMixin = { + /** + * @private Build a progress bar line for the current track. + * @this {import('./Player.mjs').Player} + * @param {number} [length=15] + * @returns {string} + */ + _createProgressBar(length = 15) { + const current = this.queue.getCurrent(); + if (!current?.duration || !this.startedPlaying) { + const total = this._getTrackDurationMs(current); + if (total > 0) { + return `${Utils.progressBar(0, total, length)} \`0:00 / ${Utils.prettifyMS(total)}\``; + } + return Utils.progressBar(0, 1, length); + } + + const totalMs = this._getTrackDurationMs(current); + let elapsed = Date.now() - this.startedPlaying; + if (this._paused && this._pausedAt) { + elapsed = this._pausedAt - this.startedPlaying; + } + + if (totalMs > 0 && elapsed > totalMs) elapsed = totalMs; + elapsed = Math.max(0, elapsed); + + const bar = Utils.progressBar(elapsed, totalMs, length); + const timeNow = Utils.prettifyMS(elapsed); + const total = Utils.prettifyMS(totalMs); + return `${bar} \`${timeNow} / ${total}\``; + }, + + /** + * @returns {string} Formatted name of the currently playing track. + * @this {import('./Player.mjs').Player} + */ + getCurrent() { + const c = this.queue.getCurrent(); + if (!c) return "There's nothing playing at the moment."; + return this.getVideoName(c); + }, + + /** + * Format a track object into a display name. + * @this {import('./Player.mjs').Player} + * @param {object} vid + * @param {boolean} [code=false] + * @returns {string} + */ + getVideoName(vid, code = false) { + if (!vid) return "Unknown"; + if (vid.type === "radio") { + return code + ? `[Radio]: ${vid.title} - ${vid.author?.url || ""}` + : `[Radio] [${vid.title} by ${vid.author?.name || "Unknown"}](${vid.author?.url || ""})`; + } + if (vid.type === "external" || vid.type === "stream") { + return code + ? `${vid.title} - ${vid.url}` + : `[${vid.title}](${vid.url})`; + } + const elapsed = this.getCurrentElapsedDuration(); + const total = this.getDuration(vid.duration); + const link = vid.spotifyUrl || vid.url || ""; + return code + ? `${vid.title} (${elapsed}/${total})${link ? " - " + link : ""}` + : `[${vid.title} (${elapsed}/${total})]${link ? "(" + link + ")" : ""}`; + }, + + /** + * @returns {string} Human-readable total remaining time for all queued tracks. + * @this {import('./Player.mjs').Player} + */ + getQueueRemainingTime() { + let totalMs = 0; + const current = this.queue.getCurrent(); + if (current?.duration && this.startedPlaying) { + const totalMsCurrent = this._getTrackDurationMs(current); + let elapsed = Date.now() - this.startedPlaying; + if (this._paused && this._pausedAt) { + elapsed = this._pausedAt - this.startedPlaying; + } + totalMs += Math.max(0, totalMsCurrent - elapsed); + } + for (const track of this.queue.data) { + totalMs += this._getTrackDurationMs(track); + } + return Utils.prettifyMS(totalMs); + }, + + /** + * @returns {string} Elapsed time of the current track. + * @this {import('./Player.mjs').Player} + */ + getCurrentElapsedDuration() { + if (!this.startedPlaying) return "0:00"; + const current = this.queue.getCurrent(); + const totalMs = this._getTrackDurationMs(current); + + let elapsed = Date.now() - this.startedPlaying; + if (this._paused && this._pausedAt) { + elapsed = this._pausedAt - this.startedPlaying; + } + + if (totalMs > 0 && elapsed > totalMs) elapsed = totalMs; + return Utils.prettifyMS(Math.max(0, elapsed)); + }, + + /** + * Generate a text-based queue listing. + * @this {import('./Player.mjs').Player} + * @param {number} [page=1] + * @param {number} [pageSize=10] + * @returns {string} + */ + list(page = 1, pageSize = 10) { + const current = this.queue.getCurrent(); + const total = this.queue.size(); + let text = ""; + if (current) { + const remaining = this.getQueueRemainingTime(); + text += `🎧 **Queue**\n`; + text += `**${total} tracks** • ⏱️ ${remaining}\n`; + text += `${this._createProgressBar()}\n\n`; + text += `🎵 **Now Playing**\n`; + text += `${this.getVideoName(current)}\n\n`; + } + if (total === 0) { if (!current) text += "--- Empty ---"; return text; } + const { items, page: pg, totalPages, start } = this.queue.getPage(page, pageSize); + items.forEach((vid, i) => { + const index = String(start + i + 1).padStart(2, " "); + const name = this.getVideoName({ ...vid, title: Utils.truncate(vid.title, 60) }); + text += `\`${index}.\` ${name}\n`; + }); + text += `\nPage ${pg}/${totalPages} • Loop: ${this.queue.loop ? "🟢" : "🔴"}`; + return text; + }, + + /** + * @async Build a now-playing info object for the current track, including + * progress bar, volume, and loop states. + * @this {import('./Player.mjs').Player} + * @returns {Promise<{msg: string, image?: string}>} + */ + async nowPlaying() { + const current = this.queue.getCurrent(); + if (!current) return { msg: "There's nothing playing at the moment." }; + + const loopqueue = this.queue.loop ? "🔄" : "⏹️"; + const songloop = this.queue.songLoop ? "🔂" : "⏹️"; + const vol = `${Math.round((this.preferredVolume || 1) * 100)}%`; + const autoplay = this._autoplay ? "🔁" : "⏹️"; + + const vcLine = this._channelId ? `🔊 <#${this._channelId}>\n` : ""; + + if (current.type === "radio") { + try { + const data = await meta(current.url); + return { + msg: `${vcLine}📻 **[${current.title}](${current.author?.url || current.url})**\n${current.description || ""}\n\n🎵 Now playing: ${data?.title || "Unknown"}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`, + image: current.thumbnail + }; + } catch (e) { + logger.warn("[Player] Error:", e?.message); + return { + msg: `${vcLine}📻 **[${current.title}](${current.author?.url || current.url})**\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`, + image: current.thumbnail + }; + } + } + + if (current.type === "external" || current.type === "stream") { + const totalMs = this._getTrackDurationMs(current); + let progressLine = ""; + + if (totalMs > 0) { + progressLine = `\n${this._createProgressBar(20)}`; + } + return { + msg: `${vcLine}🎵 **[${current.title}](${current.url})** by ${current.artist || "Unknown"}${progressLine}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`, + image: current.thumbnail + }; + } + + const progressBar = this._createProgressBar(20); + let trackOptLine = ""; + if (this._activeTrackOpt) { + const optStart = Utils.prettifyMS(this._activeTrackOpt.startMs); + const optEnd = this._activeTrackOpt.endMs > 0 ? Utils.prettifyMS(this._activeTrackOpt.endMs) : "end"; + trackOptLine = `\n✂️ Custom: ${optStart} → ${optEnd}`; + } + return { + msg: `${vcLine}🎵 **[${current.title}](${current.spotifyUrl || current.url})**\n${progressBar}${trackOptLine}\n\n🔉 ${vol} │ ${loopqueue} Queue │ ${songloop} Song │ ${autoplay} Autoplay`, + image: current.thumbnail + }; + }, + + /** + * @async Get the thumbnail of the currently playing track. + * @this {import('./Player.mjs').Player} + * @returns {Promise<{msg: string, image: string|null}>} + */ + async getThumbnail() { + const current = this.queue.getCurrent(); + if (!current) return { msg: "There's nothing playing at the moment.", image: null }; + if (!current.thumbnail) return { msg: "No thumbnail available.", image: null }; + return { msg: `Thumbnail of [${current.title}](${current.url}):`, image: current.thumbnail }; + }, + + /** + * Format a track duration from various shapes. + * @this {import('./Player.mjs').Player} + * @param {*} duration + * @returns {string} + */ + getDuration(duration) { + if (typeof duration === "object" && duration?.timestamp) return duration.timestamp; + if (typeof duration === "object" && duration?.seconds != null) return Utils.formatSeconds(duration.seconds); + if (typeof duration === "string" && duration.startsWith("PT")) return Utils.prettifyMS(Utils.parseISODuration(duration)); + return Utils.prettifyMS(duration); + }, + + /** + * @returns {string} Formatted duration of the currently playing track. + * @this {import('./Player.mjs').Player} + */ + getCurrentDuration() { + const current = this.queue.getCurrent(); + if (!current?.duration) return "?:??"; + return this.getDuration(current.duration); + }, + + /** + * Emit a now-playing announcement for the given track. + * @this {import('./Player.mjs').Player} + * @param {object} s + */ + announceSong(s) { + if (!s) return; + + if (s.type === "radio") { + this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses.radio.nowPlaying", { + title: Utils.escapeMarkdown(s.title), + author: s.author?.name || "Unknown", + url: s.author?.url || "", + channel: this._channelId || "", + }))] }); + return; + } + const author = s.artists + ? s.artists.map(a => a.url ? `[${a.name}](${a.url})` : a.name).join(" & ") + : s.author?.url + ? `[${s.author.name}](${s.author.url})` + : s.author?.name || null; + + if (!author && (s.type === "external" || s.type === "stream")) { + const desc = "🎵 Now playing [" + Utils.escapeMarkdown(s.title) + "](" + (s.url || "") + ") in <#" + (this._channelId || "") + ">"; + this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(desc)] }); + return; + } + + this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses.play.nowPlaying", { + title: Utils.escapeMarkdown(s.title), + url: s.spotifyUrl || s.url, + author: author || "Unknown", + channel: this._channelId || "", + }))] }); + }, +}; + +export default DisplayMixin; +export { DisplayMixin }; diff --git a/src/music/player/PlaybackMixin.mjs b/src/music/player/PlaybackMixin.mjs new file mode 100644 index 0000000..f89bf11 --- /dev/null +++ b/src/music/player/PlaybackMixin.mjs @@ -0,0 +1,631 @@ +/** + * @module src/music/player/PlaybackMixin + * @description Playback advancement concern for {@link Player}: track-end + * handling, playNext generation guarding, bridge playback with Lavalink + * pre-resolution, track-option timers, and lyrics. + * + * These methods are applied onto the Player class prototype via + * {@link applyMixins} — `this` is a Player instance. + */ + +import { EmbedBuilder } from "@fluxerjs/core"; +import { getGlobalColor } from "../../ui/index.mjs"; +import { Utils, cleanId } from "../../utils/Utils.mjs"; +import { logger } from "../../core/Logger.mjs"; +import meta from "../probe.mjs"; + +/** + * @type {object} + * @description Playback mixin — applied to Player. + */ +const PlaybackMixin = { + /** + * Handle the end of a track. Advances to the next song or starts the + * inactivity timer (if not 24/7). For radio tracks, stops playback. + * @this {import('./Player.mjs').Player} + * @private + */ + _handleTrackEnd() { + const songData = this.queue.getCurrent(); + if (!songData) return; + + this._clearTrackEndTimer(); + + if (songData.type === "radio") { + logger.player(`[Player] Radio track ended: ${songData.title}`); + this._lastPlayedTrack = this.queue.getCurrent() ?? songData; + this.queue.current = null; + this.emit("stopplay"); + if (!this._is247Enabled()) { + this._startInactivityTimer(); + } + return; + } + + if (!this._paused) { + this._lastPlayedTrack = this.queue.getCurrent() ?? songData; + if (!this.queue.songLoop) this.queue.current = null; + this._playingNext = false; + this.playNext().catch(e => logger.error("[Player] auto-advance playNext error:", e.message)); + } + }, + + /** + * @private Extract track duration in ms from various track data shapes. + * @this {import('./Player.mjs').Player} + * @param {object} track + * @returns {number} + */ + _getTrackDurationMs(track) { + if (track?._durationMs != null && track._durationMs > 0) { + return track._durationMs; + } + if (track?.duration) { + if (typeof track.duration === "object" && track.duration?.seconds != null) { + return track.duration.seconds * 1000; + } + if (typeof track.duration === "string" && track.duration.startsWith("PT")) { + return Utils.parseISODuration(track.duration); + } + if (typeof track.duration === "number") return track.duration; + } + if (track?.info?.length) return track.info.length; + if (track?.info?.duration != null) { + if (typeof track.info.duration === "number") return track.info.duration; + if (typeof track.info.duration === "object" && track.info.duration.seconds != null) + return track.info.duration.seconds * 1000; + } + return 0; + }, + + /** + * @private Check if a track has played past 85% or within 15s of the end. + * @this {import('./Player.mjs').Player} + * @param {object} track + * @returns {boolean} + */ + _didTrackMostlyFinish(track) { + const totalMs = this._getTrackDurationMs(track); + if (!totalMs || !this.startedPlaying) return false; + + const elapsedMs = Math.max(0, Date.now() - this.startedPlaying); + const remainingMs = Math.max(0, totalMs - elapsedMs); + + return elapsedMs / totalMs >= this.constructor.TRACK_MOSTLY_FINISHED_RATIO || remainingMs <= this.constructor.TRACK_MOSTLY_FINISHED_FLOOR_MS; + }, + + /** + * @async Advance to the next track. Guarded against overlapping runs: a + * generation counter ensures an older run's cleanup never clears the + * in-flight flag of a newer run (which previously allowed double-advances). + * @this {import('./Player.mjs').Player} + * @returns {Promise} + */ + async playNext() { + if (this._playingNext) return; + this._playingNext = true; + const generation = (this._playNextGeneration = (this._playNextGeneration ?? 0) + 1); + try { await this._doPlayNext(); } + finally { if (generation === this._playNextGeneration) this._playingNext = false; } + }, + + /** + * @private @async Core logic for advancing to the next track: resolves + * track options, announces, starts playback via the bridge, arms the + * track-end timer, and handles the queue-end path. + * @this {import('./Player.mjs').Player} + */ + async _doPlayNext() { + this._bridgeStop(); + + const currentBeforeNext = this.queue.getCurrent(); + if (currentBeforeNext) this._lastPlayedTrack = currentBeforeNext; + const songData = this.queue.next(); + if (!songData) { + this.emit("stopplay"); + this.emit("queueEnd"); + + if (!this._is247Enabled()) { + this._startInactivityTimer(); + } else { + logger.voice247("[Player] 24/7 enabled, staying in channel"); + } + + if (!this._wasRadio && !this._queueEndedSent && !this._autoplay) { + this._queueEndedSent = true; + const prefix = this._getPrefix?.(this._guildId) ?? "%"; + this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true }); + } + this._wasRadio = false; + return; + } + + this._stopInactivityTimer(); + this._wasRadio = songData.type === "radio"; + + if (!this._voiceConn || this.leaving) return; + + if (this.preferredVolume !== 1 && this._voiceConn) { + try { this._voiceConn.setVolume(this.preferredVolume * 100); } catch(_) {} + } + + if (!this._voiceConn || this.leaving) return; + + this._activeTrackOpt = null; + this._clearTrackEndTimer(); + + let trackOptMatch = null; + try { + trackOptMatch = await this._lookupTrackOptions(songData); + } catch (e) { + logger.warn("[Player] TrackOptions lookup error:", e.message); + } + + if (trackOptMatch) { + this._activeTrackOpt = trackOptMatch; + } + + logger.player(`[Player:${this._guildId}] Playing: ${songData.title}`); + + this.startedPlaying = Date.now(); + this._paused = false; + this._pausedAt = null; + this._queueEndedSent = false; + this._consecutiveErrors = 0; + + if (songData.type !== "radio" || !this._radioAnnounced) { + this.announceSong(songData); + if (songData.type === "radio") this._radioAnnounced = true; + } + this.emit("startplay", songData); + + try { + const playUri = songData.url; + const seekSec = trackOptMatch?.startMs > 0 ? trackOptMatch.startMs / 1000 : 0; + + if (!playUri || !Utils.isValidUrl(playUri)) { + logger.warn(`[Player] No valid URL for track: ${songData.title} (url=${songData.url}), trying search...`); + try { + if (this._lavalink) { + const result = await this._lavalink.search(songData.title, { source: "ytmsearch" }); + const track = result?.tracks?.[0]; + if (track?.info?.uri) { + songData.url = track.info.uri; + if (track.encoded) songData.encoded = track.encoded; + await this._playTrackViaBridge(songData, { seekSeconds: seekSec }); + } else { + throw new Error("No tracks found for title search"); + } + } else { + throw new Error("No Lavalink for fallback search"); + } + } catch (searchErr) { + logger.error("[Player] Could not resolve track:", searchErr?.message); + this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.couldNotGetStream", { title: songData.title }))] }); + this.emit("stopplay"); + if (!this._is247Enabled()) { + this._startInactivityTimer(); + } + return; + } + } else { + await this._playTrackViaBridge(songData, { seekSeconds: seekSec }); + } + + if (trackOptMatch && trackOptMatch.endMs > 0) { + const elapsedMs = Date.now() - this.startedPlaying; + const remainingMs = trackOptMatch.endMs - elapsedMs; + if (remainingMs > 0) { + const match = trackOptMatch; + this._trackEndTimer = setTimeout(() => this._onTrackEndTimeReached(match), remainingMs); + } + } + } catch (err) { + logger.error("[Player] Play error:", err.message); + if (!this._skipping && !this.leaving && !this._paused && songData.type !== "radio") { + this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.errorStreaming", { title: songData.title }))] }); + } + if (!this._skipping && !this.leaving) { + this._consecutiveErrors = (this._consecutiveErrors || 0) + 1; + if (this._consecutiveErrors <= 3) { + this._handleTrackEnd(); + } else { + logger.error(`[Player] ${this._consecutiveErrors} consecutive play errors — stopping auto-advance`); + this._consecutiveErrors = 0; + this.emit("stopplay"); + if (!this._is247Enabled()) { + this._startInactivityTimer(); + } + } + } + } + }, + + /** + * @private @async Play a track through the FluxerAudioBridge. For + * radio/external tracks without an encoded payload, attempts Lavalink URL + * resolution first so MP3/AAC streams can use the loadstream pipeline. + * @this {import('./Player.mjs').Player} + * @param {object} songData + * @param {object} [options={}] + * @returns {Promise} + */ + async _playTrackViaBridge(songData, options = {}) { + if (!this._voiceConn || !this._audioBridge) { + throw new Error("No voice connection or audio bridge available"); + } + if (!songData?.encoded && !songData?.url) { + throw new Error("No encoded track or URL for: " + (songData?.title ?? "unknown")); + } + + if (!songData.encoded && songData.url && songData.url.startsWith("http") && this._lavalink && songData.type !== "external") { + try { + const nlInfo = this._lavalink.getNodeLinkInfo?.(); + if (nlInfo) { + const protocol = nlInfo.secure ? "https" : "http"; + const baseUrl = protocol + "://" + nlInfo.host + ":" + nlInfo.port; + const headers = { "Authorization": nlInfo.password }; + if (nlInfo.sessionId) headers["Session-Id"] = nlInfo.sessionId; + if (this._guildId) headers["Guild-Id"] = this._guildId; + + const loadtracksUrl = baseUrl + "/v4/loadtracks?identifier=" + encodeURIComponent(songData.url); + logger.player(`[Player] Pre-resolving ${songData.type || "external"} URL via Lavalink...`); + + const body = await this._request(loadtracksUrl, { headers }); + const track = body?.data?.tracks?.[0] ?? body?.tracks?.[0] ?? body?.data; + const encoded = track?.encoded ?? track?.data; + + if (encoded && typeof encoded === "string") { + songData.encoded = encoded; + logger.player("[Player] Lavalink pre-resolve succeeded — track now has encoded payload"); + } else { + logger.player("[Player] Lavalink pre-resolve: no encoded track returned, bridge will try direct URL"); + } + } + } catch (e) { + logger.warn("[Player] Lavalink pre-resolve failed (bridge will try direct URL): " + e.message); + } + } + + this._audioBridge._conn = this._voiceConn; + + const seekMs = Math.floor((options.seekSeconds ?? 0) * 1000); + + const totalMs = this._getTrackDurationMs(songData); + const durationMs = totalMs > 0 ? Math.max(0, totalMs - seekMs) : 0; + + const result = await this._audioBridge.play(this._voiceConn, { + encoded: songData.encoded, + url: songData.url, + title: songData.title, + guildId: this._guildId, + }, { + seekSeconds: options.seekSeconds ?? 0, + durationMs, + videoId: songData.videoId || null, + filterPayload: this.activeFilterPayload || null, + }); + + if (result === "finished" && !this._skipping && !this.leaving && !this._paused) { + this._handleTrackEnd(); + } else if (result === "stopped") { + // Stopped intentionally (skip/seek/stop) — nothing to do. + } + }, + + /** + * @private Handle when a track option's end time is reached. + * @this {import('./Player.mjs').Player} + * @param {object} match + */ + _onTrackEndTimeReached(match) { + if (this._destroyed || this.leaving || !this._activeTrackOpt) return; + logger.player(`[Player] TrackOptions: end time reached (${match.endMs}ms), skipping track`); + this._activeTrackOpt = null; + this._trackEndTimer = null; + this._trackEndRemainingMs = null; + this._skipping = true; + this._bridgeStop(); + this._playingNext = false; + this._lastPlayedTrack = this.queue.getCurrent() ?? this._lastPlayedTrack; + this.emit("trackSkip", this._lastPlayedTrack); + if (!this.queue.isEmpty() && !this.leaving) { + this.playNext().catch(e => logger.error("[Player] TrackEnd playNext error:", e.message)); + } else { + this.queue.current = null; + if (!this._wasRadio && !this._queueEndedSent) { + this._queueEndedSent = true; + this.emit("queueEnd"); + if (!this._autoplay) { + const prefix = this._getPrefix?.(this._guildId) ?? "%"; + this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true }); + } + } + this.emit("stopplay"); + if (!this._is247Enabled()) { + this._startInactivityTimer(); + } + } + this._skipping = false; + }, + + /** + * @private Clear the track-end timer. + * @this {import('./Player.mjs').Player} + */ + _clearTrackEndTimer() { + if (this._trackEndTimer) { + clearTimeout(this._trackEndTimer); + this._trackEndTimer = null; + } + this._trackEndRemainingMs = null; + }, + + /** + * @private Pause the track-end timer, saving remaining time. + * @this {import('./Player.mjs').Player} + */ + _pauseTrackEndTimer() { + if (!this._trackEndTimer || !this._activeTrackOpt || this._activeTrackOpt.endMs <= 0) return; + clearTimeout(this._trackEndTimer); + const elapsedMs = Date.now() - this.startedPlaying; + this._trackEndRemainingMs = Math.max(0, this._activeTrackOpt.endMs - elapsedMs); + this._trackEndTimer = null; + }, + + /** + * @private Resume the track-end timer. + * @this {import('./Player.mjs').Player} + */ + _resumeTrackEndTimer() { + if (this._trackEndRemainingMs == null || this._trackEndRemainingMs <= 0 || !this._activeTrackOpt || this._activeTrackOpt.endMs <= 0) { + this._trackEndRemainingMs = null; + return; + } + const remainingMs = this._trackEndRemainingMs; + const match = this._activeTrackOpt; + this._trackEndTimer = setTimeout(() => this._onTrackEndTimeReached(match), remainingMs); + this._trackEndRemainingMs = null; + }, + + /** + * @private Recalculate and restart the track-end timer (after a seek). + * @this {import('./Player.mjs').Player} + */ + _recalcTrackEndTimer() { + if (!this._activeTrackOpt || this._activeTrackOpt.endMs <= 0) return; + this._clearTrackEndTimer(); + const elapsedMs = Date.now() - this.startedPlaying; + const remainingMs = this._activeTrackOpt.endMs - elapsedMs; + if (remainingMs <= 0) { + this._onTrackEndTimeReached(this._activeTrackOpt); + return; + } + const match = this._activeTrackOpt; + this._trackEndTimer = setTimeout(() => this._onTrackEndTimeReached(match), remainingMs); + }, + + /** + * @async Seek to a specific position in the currently playing track. + * @this {import('./Player.mjs').Player} + * @param {number} ms - Target position in milliseconds. + * @returns {Promise} True if seek succeeded, false otherwise. + */ + async seekToPosition(ms) { + if (!this._voiceConn || !this.queue.getCurrent()) return false; + + this._seeking = true; + + try { + this._bridgeStop(); + const current = this.queue.getCurrent(); + if (current?.url) { + this.startedPlaying = Date.now() - ms; + await this._playTrackViaBridge(current, { seekSeconds: ms / 1000 }); + } + logger.player(`[Player] Seeked to ${ms}ms — adjusted startedPlaying`); + + this._recalcTrackEndTimer(); + + return true; + } catch (e) { + this._seeking = false; + logger.error("[Player] Seek failed:", e?.message); + return false; + } finally { + this._seeking = false; + } + }, + + /** + * @async Apply an audio filter to playback. Stores filter metadata for + * dashboard tracking; filters are applied server-side by NodeLink on the + * next track. + * @this {import('./Player.mjs').Player} + * @param {object} filterPayload + * @param {object|null} [filterMeta=null] + * @returns {Promise<{ok: boolean, reason?: string, pending?: boolean}>} + */ + async applyFilter(filterPayload, filterMeta = null) { + if (!this._guildId) { + return { ok: false, reason: "Player not bound to a guild." }; + } + + const current = this.queue.getCurrent(); + + this.activeFilter = filterMeta ?? null; + this.activeFilterPayload = filterMeta ? filterPayload : null; + this.emit("filter", this.activeFilter); + + if (!current?.encoded || !this._voiceConn) { + return { ok: true, pending: true }; + } + + return { ok: true }; + }, + + /** + * Clear any active audio filter. + * @this {import('./Player.mjs').Player} + */ + clearFilter() { + this.activeFilter = null; + this.activeFilterPayload = null; + this.emit("filter", null); + logger.warn("[Player] clearFilter: filters not supported in LiveKit mode"); + }, + + /** + * @private @async Look up per-user track options for the humans currently + * in the player's channel. + * @this {import('./Player.mjs').Player} + * @param {object} songData + * @returns {Promise} + */ + async _lookupTrackOptions(songData) { + if (!this.trackOptions || !songData || songData.type === "radio") return null; + if (!this._guildId || !this._channelId) return null; + + const userIds = []; + if (this._voiceCache) { + const humans = this._voiceCache.getHumansInChannel( + cleanId(this._guildId), + cleanId(this._channelId) + ); + userIds.push(...humans); + } + + if (userIds.length === 0) { + try { + const guild = this.client?.guilds?.get?.(this._guildId); + const voiceStates = guild?.voice_states ?? guild?.voiceStates; + if (voiceStates) { + const entries = Array.isArray(voiceStates) ? voiceStates + : typeof voiceStates.values === "function" ? [...voiceStates.values()] + : Object.values(voiceStates); + for (const state of entries) { + const ch = cleanId(state?.channelId ?? state?.channel_id ?? ""); + if (ch === cleanId(this._channelId)) { + const uid = state?.userId ?? state?.user_id; + const member = guild?.members?.get?.(uid); + if (uid && !member?.user?.bot) userIds.push(uid); + } + } + } + } catch(e) { logger.warn("[Player] Voice state lookup error:", e?.message); } + } + + if (userIds.length === 0) return null; + + const match = await this.trackOptions.getBestMatchForChannel(userIds, songData); + return match || null; + }, + + /** + * @private @async Auto-seek to a track options start position. + * @this {import('./Player.mjs').Player} + * @param {object} match + */ + async _applyTrackOptionsSeek(match) { + if (!match || match.startMs <= 0) return; + const current = this.queue.getCurrent(); + if (!current?.url || !this._voiceConn || this.leaving) { + logger.warn(`[Player] TrackOptions: cannot seek (encoded=${!!current?.encoded} lavalinkPlayer=${!!this.lavalinkPlayer} leaving=${this.leaving})`); + return; + } + let seeked = false; + for (let attempt = 0; attempt < 10; attempt++) { + await Utils.sleep(500); + try { + const result = await this.seekToPosition(match.startMs); + if (result) { + seeked = true; + logger.player(`[Player] TrackOptions: auto-seeked to ${match.startMs}ms for user ${match.userId} (attempt ${attempt + 1})`); + break; + } + } catch (e) { + logger.warn(`[Player] TrackOptions auto-seek attempt ${attempt + 1} error:`, e.message); + } + } + if (!seeked) { + logger.warn(`[Player] TrackOptions: auto-seek to ${match.startMs}ms failed after all retries`); + } + }, + + /** + * @async Apply a track options match (custom start/end times) to the + * currently playing track. + * @this {import('./Player.mjs').Player} + * @param {object} match - Track options match with startMs and optional endMs. + * @returns {Promise} True if applied successfully, false otherwise. + */ + async applyTrackOption(match) { + if (!match || !this._voiceConn || this._paused) return false; + + this._clearTrackEndTimer(); + this._activeTrackOpt = null; + + try { + await this.seekToPosition(match.startMs || 0); + } catch (e) { + logger.warn("[Player] TrackOptions apply-seek error:", e.message); + return false; + } + + if (match.endMs > 0) { + const elapsedMs = Date.now() - this.startedPlaying; + const remainingMs = match.endMs - elapsedMs; + if (remainingMs > 0) { + this._activeTrackOpt = match; + this._trackEndTimer = setTimeout(() => this._onTrackEndTimeReached(match), remainingMs); + } + } else { + this._activeTrackOpt = match; + } + + return true; + }, + + /** + * @async Fetch lyrics for the currently playing track via the Lavalink + * REST API. + * @this {import('./Player.mjs').Player} + * @returns {Promise<{text: string, source: string, synced: boolean, lines: Array}|null>} + */ + async lyrics() { + const current = this.queue.getCurrent(); + if (!current) return null; + + const node = this._lavalink?.getNode?.() ?? null; + + if (node) { + try { + const searchQuery = current.artists?.[0]?.name + ? `${current.title} ${current.artists[0].name}` + : current.title; + + const path = current.encoded + ? `/loadlyrics?encodedTrack=${encodeURIComponent(current.encoded)}` + : `/loadlyrics?identifier=${encodeURIComponent(searchQuery)}`; + + const results = await node.request(path); + + if (results?.data?.lines?.length) { + return { + text: results.data.lines.map(l => l.text).join("\n"), + source: "Lavalink", + synced: results.data.lines.some(l => l.startTimeMs != null), + lines: results.data.lines, + }; + } + } catch (e) { + logger.player(`[Lyrics] Lavalink REST lyrics failed: ${e.message}`); + } + } + + return null; + }, +}; + +export default PlaybackMixin; +export { PlaybackMixin }; diff --git a/src/music/player/Player.mjs b/src/music/player/Player.mjs new file mode 100644 index 0000000..863f211 --- /dev/null +++ b/src/music/player/Player.mjs @@ -0,0 +1,993 @@ +/** + * @module src/music/player/Player + * @description Per-channel music player: voice connection lifecycle (join / + * leave / destroy / rejoin), playback controls (pause, resume, skip, seek, + * volume, filters), queue operations, 24/7 mode helpers and the inactivity + * timer. Playback advancement, search and display rendering live in the + * playback/search/display mixin modules applied at the bottom of this file. + */ + +import { getVoiceManager } from "@fluxerjs/voice"; +import { EventEmitter } from "node:events"; +import http from "node:http"; +import https from "node:https"; +import { EmbedBuilder } from "@fluxerjs/core"; +import { getGlobalColor } from "../../ui/index.mjs"; +import { Utils, cleanId } from "../../utils/Utils.mjs"; +import { logger } from "../../core/Logger.mjs"; +import { get247ChannelMode } from "../../utils/Helpers247.mjs"; +import { hasHumansInChannel } from "../../voice/VoiceStateResolver.mjs"; +import { FluxerAudioBridge } from "../audio/FluxerAudioBridge.mjs"; +import { applyMixins } from "../../utils/mixins.mjs"; +import { Queue } from "./Queue.mjs"; +import PlaybackMixin from "./PlaybackMixin.mjs"; +import SearchMixin from "./SearchMixin.mjs"; +import DisplayMixin from "./DisplayMixin.mjs"; + +/** + * @class Player + * @description Main music player class. Manages voice connections, playback, + * queue, filters, and search. + * @extends {EventEmitter} + * + * Events: + * - `"queue"` — queue mutation (proxied from the Queue) + * - `"message"` — announcements `{ embeds: [...] }` (or a plain string) + * - `"startplay"` / `"stopplay"` / `"queueEnd"` / `"trackSkip"` + * - `"playback"` (paused state boolean), `"volume"`, `"filter"` + * - `"autoleave"`, `"leave"`, `"roomfetched"` + */ +class Player extends EventEmitter { + /** @private @type {object|null} The LiveKit voice connection. */ + _voiceConn = null; + /** @private @type {FluxerAudioBridge|null} */ + _audioBridge = null; + lavalinkPlayer = null; + /** @type {object|null} Alias of _voiceConn (kept for dashboard/debug compat). */ + connection = null; + /** @private @type {string|null} */ + _guildId = null; + /** @private @type {string|null} */ + _channelId = null; + /** @private @type {number|null} */ + _lastConnectedAt = null; + /** @private @type {string|null} The home channel of a 24/7 spawn. */ + _home247Channel = null; + + /** @type {Queue} */ + queue = null; + client = null; + settings = null; + config = {}; + + /** @type {import('../LavalinkManager.mjs').LavalinkManager|null} */ + _lavalink = null; + + leaving = false; + _paused = false; + _pausedAt = null; + _playingNext = false; + startedPlaying = null; + /** @type {Map} Search sessions by key. */ + searches = new Map(); + _searchMaxSize = 50; + _maxQueueSize = 10_000; + resultLimit = 5; + preferredVolume = 1; + + _skipping = false; + _seeking = false; + _wasRadio = false; + _radioAnnounced = false; + _queueEndedSent = false; + _lastPlayedTrack = null; + + _autoplay = false; + _autoplayHandler = null; + + activeFilter = null; + activeFilterPayload = null; + + /** @type {number} Default inactivity timeout before auto-leave. */ + static INACTIVITY_DEFAULT_MS = 3 * 60 * 1000; + /** @type {number} Track is considered finished past this ratio. */ + static TRACK_MOSTLY_FINISHED_RATIO = 0.85; + /** @type {number} Or when less than this much time remains. */ + static TRACK_MOSTLY_FINISHED_FLOOR_MS = 15_000; + /** @type {number} Hard radio safety timeout. */ + static RADIO_SAFETY_TIMEOUT_MS = 20 * 60 * 1000; + + /** @private @type {Timeout|null} */ + _inactivityTimer = null; + /** @private @type {number} */ + _inactivityLimit = Player.INACTIVITY_DEFAULT_MS; + /** @private @type {boolean} */ + _pendingInactivityCheck = false; + + /** @private @type {boolean} */ + _isJoining = false; + /** @private @type {boolean} */ + _destroyed = false; + /** @private @type {Timeout|null} */ + _rejoinTimer = null; + + /** + * @param {string} token - Bot authentication token (used internally). + * @param {object} [opts={}] - Player configuration options. + * @param {import('@fluxerjs/core').Client} [opts.client] + * @param {object} [opts.config] + * @param {import('../LavalinkManager.mjs').LavalinkManager} [opts.lavalink] + * @param {import('../../db/Settings.mjs').RemoteSettingsManager} [opts.settingsMgr] + * @param {Function} [opts.getPrefix] + * @param {import('../../voice/VoiceStateCache.mjs').VoiceStateCache} [opts.observedVoiceUsers] + * @param {import('../../voice/VoiceStateCache.mjs').VoiceStateCache} [opts.voiceCache] + * @param {import('../../core/Locale.mjs').Locale} [opts.locale] + * @param {import('../../services/TrackOptionsManager.mjs').TrackOptionsManager} [opts.trackOptions] + */ + constructor(token, opts = {}) { + super(); + + this.queue = new Queue(); + this.queue.on("queue", (...args) => this.emit("queue", ...args)); + this.client = opts.client; + this.config = opts.config ?? {}; + this.settings = opts.settings ?? null; + this.settingsMgr = opts.settingsMgr ?? null; + this._getPrefix = opts.getPrefix ?? null; + this._observedVoiceUsers = opts.observedVoiceUsers ?? null; + this._voiceCache = opts.voiceCache ?? null; + this.locale = opts.locale ?? null; + this.trackOptions = opts.trackOptions ?? null; + this._activeTrackOpt = null; + + this._lavalink = opts.lavalink ?? null; + + this._audioBridge = new FluxerAudioBridge(opts.lavalink ?? null); + this._audioBridge.on("error", (err) => { + logger.error(`[Player] Audio bridge error (guild ${this._guildId}): ${err.message}`); + }); + + const inactivityMs = this.config?.timers?.inactivityTimeout ?? this.config?.inactivityTimeout; + if (inactivityMs !== undefined) { + const parsed = Number(inactivityMs); + if (!Number.isNaN(parsed) && parsed >= 0) { + this._inactivityLimit = parsed; + } + } + + if (this._lavalink) { + this._onLavalinkPlayerDisconnect = (lavaPlayer) => { + if (!lavaPlayer || String(lavaPlayer.guildId) !== String(this._guildId)) return; + logger.lavalink("[Player] lavalink-client player disconnect (guild: " + this._guildId + ") — ignored (voice via LiveKit)"); + }; + this._lavalink.on("playerDisconnected", this._onLavalinkPlayerDisconnect); + } + } + + /** + * Check whether 24/7 mode is active for this player's current channel. + * @returns {boolean} True if 24/7 is enabled. + */ + _is247Enabled() { + return this._get247Mode() !== "off"; + } + + /** + * Resolve the 24/7 mode for this player's current or home channel by + * consulting the guild's stay_247 setting. + * @returns {"on"|"off"} The 24/7 mode. Only "on" or "off" — no "auto". + * @private + */ + _get247Mode() { + if (!this._guildId) return "off"; + const serverSettings = this.settingsMgr?.getServer?.(this._guildId) + ?? this.settings + ?? this.client?.settings?.getServer?.(this._guildId); + if (!serverSettings?.get) return "off"; + + const channelId = cleanId(this._home247Channel ?? this._channelId ?? ""); + if (!channelId) return "off"; + + const raw = serverSettings.get("stay_247"); + if (raw && raw !== "none") { + const channels = Array.isArray(raw) + ? raw.map(id => cleanId(id)).filter(Boolean) + : [cleanId(raw)].filter(Boolean); + if (!channels.includes(channelId)) return "off"; + } else { + return "off"; + } + + return get247ChannelMode(serverSettings, channelId); + } + + /** @private @returns {string|null} The cleaned guild ID, or null if unresolvable. */ + _resolveGuildId() { + const cleanGuild = cleanId(this._guildId ?? ""); + if (cleanGuild) return cleanGuild; + + try { + const channelId = this._channelId ?? this._home247Channel; + if (channelId) { + const ch = this.client?.channels?.get?.(channelId); + const fromChannel = ch?.guildId ?? ch?.guild?.id ?? null; + if (fromChannel) return cleanId(fromChannel); + } + } catch(e) { logger.warn("[Player] Guild resolution failed:", e?.message); } + + return null; + } + + /** @private Restore saved volume from guild settings. */ + _restoreVolume() { + if (!this._guildId) return; + let savedVol = null; + + if (this.settings?.get) { + savedVol = this.settings.get("volume"); + } else if (this.settingsMgr?.getServer) { + const set = this.settingsMgr.getServer(this._guildId); + savedVol = set?.get?.("volume"); + } else if (this.client?.settings?.getServer) { + savedVol = this.client.settings.getServer(this._guildId)?.get?.("volume"); + } else if (this.client?.settings?.get) { + const s = this.client.settings.get(this._guildId); + savedVol = s?.get?.("volume") ?? s?.volume; + } + + if (savedVol !== undefined && savedVol !== null) { + const parsed = Number(savedVol); + if (!Number.isNaN(parsed) && parsed > 0) { + this.preferredVolume = Utils.clamp(parsed / 100, 0, 2); + logger.player(`[Player] Restored volume ${savedVol}% for guild ${this._guildId}`); + if (this._voiceConn) { + try { this._voiceConn.setVolume(this.preferredVolume * 100); } catch (_) {} + } + } + } + } + + /** @private @returns {boolean} Whether there are non-bot users in the channel. */ + _hasHumansInChannel() { + return hasHumansInChannel({ + guildId: cleanId(this._guildId ?? ""), + channelId: cleanId(this._channelId ?? ""), + client: this.client, + voiceCache: this._voiceCache, + observedVoiceUsers: this._observedVoiceUsers, + botId: this.client?.user?.id, + }); + } + + /** + * Start the inactivity timer. Skipped when 24/7 is active, the queue has + * songs, or humans are present. The timer callback re-checks all + * conditions before emitting autoleave. + */ + _startInactivityTimer() { + this._stopInactivityTimer(); + if (this._inactivityLimit <= 0) return; + + const mode = this._get247Mode(); + logger.inactivity(`[Player] Checking 24/7 mode for guild ${this._guildId}: ${mode}`); + + if (mode === "on") { + logger.inactivity(`[Player] 24/7 mode active for guild ${this._guildId}, skipping inactivity timer`); + return; + } + + if (this.queue?.getCurrent() || !this.queue?.isEmpty()) { + logger.inactivity(`[Player] Queue has songs for guild ${this._guildId}, skipping inactivity timer`); + return; + } + + if (this._hasHumansInChannel()) { + logger.inactivity(`[Player] Humans present in channel ${this._channelId}, skipping inactivity timer`); + return; + } + + logger.inactivity(`[Player] Starting inactivity timer for guild ${this._guildId} (${this._inactivityLimit / 1000}s)`); + this._inactivityTimer = setTimeout(() => { + const currentMode = this._get247Mode(); + if (currentMode === "on") { + logger.inactivity(`[Player] 24/7 mode enabled during inactivity wait, aborting leave`); + return; + } + if (this.queue?.getCurrent() || !this.queue?.isEmpty()) { + logger.inactivity("[Player] Song in queue during inactivity wait, aborting leave"); + return; + } + if (this._hasHumansInChannel()) { + logger.inactivity("[Player] Human joined during inactivity wait, aborting leave"); + return; + } + logger.inactivity(`[Player] Guild ${this._guildId} inactive too long. Leaving.`); + this.emit("autoleave"); + }, this._inactivityLimit); + } + + /** Clear the inactivity timer if running. */ + _stopInactivityTimer() { + this._pendingInactivityCheck = false; + if (this._inactivityTimer) { + logger.inactivity(`[Player] Stopping inactivity timer for guild ${this._guildId}`); + clearTimeout(this._inactivityTimer); + this._inactivityTimer = null; + } + } + + /** + * Schedule a 24/7 rejoin after a delay. Guards against destroyed players, + * registered intentional leaves, and pending/duplicate joins. + * @param {string} channelId - The channel to rejoin. + * @param {string} guildId - The guild ID. + * @param {string} mode - The 24/7 mode ("on"). + * @private + */ + _schedule247Rejoin(channelId, guildId, mode) { + const ctx = this.client?._remix; + if (!ctx) { + logger.warn(`[Player] Cannot schedule 24/7 rejoin for ${channelId} — no bot context`); + return; + } + + if (ctx.players?._pendingJoins?.has?.(channelId)) { + logger.voice247(`[Player] 24/7 rejoin skipped for ${channelId} — join already pending`); + return; + } + + if (ctx.players?.playerMap?.has(channelId)) { + const existing = ctx.players.playerMap.get(channelId); + if (existing && !existing._destroyed && existing !== this) { + logger.voice247(`[Player] 24/7 rejoin skipped for ${channelId} — another player already exists`); + return; + } + } + + const rejoinDelay = ctx.config?.timers?.rejoin247Delay ?? 3_000; + logger.voice247(`[Player] Scheduling 24/7 ${mode} rejoin for channel ${channelId} (guild ${guildId}) in ${rejoinDelay / 1000}s`); + + this._rejoinTimer = setTimeout(() => { + this._rejoinTimer = null; + if (this._destroyed) { + logger.voice247(`[Player] 24/7 rejoin cancelled — player destroyed`); + return; + } + if (ctx.intentionalLeaves?.has(channelId)) { + logger.voice247(`[Player] 24/7 rejoin cancelled — intentional leave registered`); + return; + } + + ctx.gatewayHandler?._rejoinChannel?.(guildId, channelId).catch(err => { + logger.warn(`[Player] 24/7 rejoin failed for channel ${channelId}:`, err?.message); + }); + }, rejoinDelay); + } + + /** + * @private Low-level HTTP(S) request helper with redirects and JSON parsing. + * Used for Lavalink REST calls (pre-resolve, loadtracks). + * @param {string} url + * @param {object} [options={}] + * @param {boolean} [returnStream=false] + * @returns {Promise} + */ + async _request(url, options = {}, returnStream = false) { + return new Promise((resolve, reject) => { + const fetchUrl = (target, _redirects = 0) => { + const urlObj = new URL(target); + const client = urlObj.protocol === "https:" ? https : http; + + const req = client.request({ + protocol: urlObj.protocol, + host: urlObj.hostname, + port: urlObj.port, + path: urlObj.pathname + urlObj.search, + method: options.method || "GET", + headers: { + "User-Agent": "Mozilla/5.0 (compatible; Bot/1.0)", + "Accept": "*/*", + ...options.headers, + }, + }, (res) => { + if (returnStream) req.setTimeout(0); + + if ([301, 302, 307, 308].includes(res.statusCode)) { + let loc = res.headers.location; + if (!loc) return reject(new Error("Redirect without location")); + if (loc.startsWith("/")) loc = `${urlObj.protocol}//${urlObj.host}${loc}`; + if (_redirects >= 5) return reject(new Error("Too many redirects")); + const redirectUrl = new URL(loc); + if (redirectUrl.host !== urlObj.host) { + if (options.headers) delete options.headers.Authorization; + } + return fetchUrl(loc, _redirects + 1); + } + if (![200, 204, 206].includes(res.statusCode)) { + res.resume(); + return reject(new Error(`HTTP ${res.statusCode}`)); + } + if (returnStream) return resolve(res); + + if (res.statusCode === 204) { res.resume(); return resolve(null); } + + const chunks = []; + res.on("data", d => chunks.push(d)); + res.on("end", () => { + const raw = Buffer.concat(chunks).toString().trim(); + if (!raw) return resolve(null); + try { resolve(JSON.parse(raw)); } + catch (e) { reject(new Error(`JSON parse error from ${target}`)); } + }); + }); + + req.on("error", reject); + req.setTimeout(options.timeout || 60_000, () => { + req.destroy(); + reject(new Error("Request timeout")); + }); + if (options.body) req.write(options.body); + req.end(); + }; + fetchUrl(url); + }); + } + + /** + * @async Join a voice channel via LiveKit. Sets up voice connection, event + * listeners, and resumes playback if the queue has tracks. + * @param {string} channelId - The voice channel ID to join. + * @returns {Promise} + * @throws {Error} If the channel is not found, VoiceManager is unavailable, or connection fails. + */ + async join(channelId) { + if (this._destroyed) return; + + if (this._isJoining) { + logger.player(`[Player] Busy joining. Ignoring: ${channelId}`); + return; + } + if (this._voiceConn && this._channelId === channelId) { + logger.player(`[Player] Already in channel: ${channelId}`); + return; + } + + if (this._voiceConn) { + logger.player("[Player] Cleaning up existing voice connection before join"); + this._bridgeStop(); + try { await this._voiceConn.disconnect(); } catch(e) { logger.warn("[Player] Existing voiceConn disconnect error:", e?.message); } + this._voiceConn = null; + this.connection = null; + await Utils.sleep(500); + } + + this._isJoining = true; + try { + const channel = this.client?.channels?.get?.(channelId); + if (!channel) throw new Error(`Channel not found: ${channelId}`); + + if (this._lavalink) { + logger.player(`[Player] Waiting for Lavalink node...`); + await this._lavalink.waitForNode({ timeoutMs: 15_000 }); + } + + this._channelId = channelId; + this._guildId = cleanId(channel.guildId); + this._lastConnectedAt = Date.now(); + this.leaving = false; + + logger.player(`[Player] Joining channel ${channelId} via vm.join() (LiveKit)...`); + const vm = getVoiceManager(this.client); + if (!vm) { + throw new Error("VoiceManager not available — call getVoiceManager(client) before login"); + } + + let voiceConn; + try { + voiceConn = await vm.join(channel); + } catch (e) { + throw new Error(`vm.join() failed for channel ${channelId}: ${e.message}`); + } + + if (!voiceConn) { + throw new Error(`vm.join() returned null for channel ${channelId}`); + } + + this._voiceConn = voiceConn; + this.connection = voiceConn; + + if (typeof voiceConn.isConnected === "function" && !voiceConn.isConnected()) { + logger.player("[Player] Waiting for LiveKit room to connect..."); + await new Promise((resolve, reject) => { + const timeout = setTimeout(() => reject(new Error("LiveKit connection timeout (15s)")), 15_000); + const check = () => { + try { + if (voiceConn.isConnected()) { clearTimeout(timeout); return resolve(); } + if (voiceConn.connectionState === 0) { clearTimeout(timeout); return resolve(); } + } catch (_) { clearTimeout(timeout); return resolve(); } + setTimeout(check, 200); + }; + check(); + }); + await Utils.sleep(500); + } + + logger.player(`[Player] LiveKit voice connected (guild: ${this._guildId}, channel: ${channelId})` + + ` isConnected=${voiceConn.isConnected ? voiceConn.isConnected() : 'unknown'}`); + + this._assertSelfDeaf(vm, channelId); + + if (typeof voiceConn.on === "function") { + // Self-deaf keeper: Fluxer's VoiceManager answers every + // requestVoiceStateSync event (emitted by conn.stop()/stopVideo(), + // which the audio bridge triggers on EVERY play() and stop()) with a + // gateway VoiceStateUpdate that resets self_deaf to false — silently + // un-deafening the bot the moment the first track starts and again on + // every skip/stop/track-end. The manager registers its own sync + // listener inside registerConnection() (before join() resolved), so + // this listener runs AFTER it and our re-deafen state update wins. + voiceConn.on("requestVoiceStateSync", () => { + if (this.leaving || this._destroyed) return; + this._assertSelfDeaf(vm, channelId); + }); + + voiceConn.on("serverLeave", () => { + if (this.leaving || this._destroyed) return; + logger.player(`[Player] serverLeave received — Fluxer/LiveKit terminated session`); + this._voiceConn = null; + this.connection = null; + this._paused = true; + this._stopInactivityTimer(); + + const mode = this._get247Mode(); + const cId = cleanId(this._channelId ?? this._home247Channel ?? ""); + const gId = cleanId(this._guildId ?? ""); + + if (mode === "on") { + logger.player("[Player] serverLeave in 24/7 mode — scheduling rejoin"); + this.emit("autoleave"); + if (cId && gId) this._schedule247Rejoin(cId, gId, mode); + } else { + logger.player("[Player] Unexpected serverLeave"); + this.emit("autoleave"); + } + }); + + voiceConn.on("disconnect", () => { + if (this.leaving || this._destroyed) return; + logger.player(`[Player] Voice connection disconnected`); + }); + } + + this._restoreVolume(); + this.emit("roomfetched"); + logger.player(`[Player] Voice connected to ${channel.name || channelId}`); + + if (!this.queue.isEmpty() && !this.queue.getCurrent()) { + this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); + } else if (this.queue.isEmpty()) { + this._pendingInactivityCheck = true; + setTimeout(() => { + if (!this._pendingInactivityCheck) return; + this._pendingInactivityCheck = false; + if (this.queue.isEmpty() && !this.queue.getCurrent()) { + this._startInactivityTimer(); + } + }, 3000); + } + + } catch (e) { + const causeStr = e.cause ? ` (Cause: ${e.cause})` : ""; + logger.error("[Player] Join failed:", e.message, causeStr); + + if (this._voiceConn) { + try { await this._voiceConn.disconnect(); } catch(err) { logger.warn("[Player] voiceConn disconnect on join failure:", err?.message); } + this._voiceConn = null; + this.connection = null; + } + throw e; + } finally { + this._isJoining = false; + } + } + + /** + * @async Leave the current voice channel. Stops playback, resets state, and + * cleans up the voice connection. + * @returns {Promise} True if leave was successful, false otherwise. + */ + async leave() { + if (!this._voiceConn && !this.connection) return false; + try { + this.leaving = true; + this._stopInactivityTimer(); + this._clearTrackEndTimer(); + this._activeTrackOpt = null; + + const channelId = this._channelId; + + this._bridgeStop(); + + try { + const vm = getVoiceManager(this.client); + if (channelId) { + vm.leaveChannel(channelId); + logger.player("[Player] Left channel " + channelId + " via vm.leaveChannel()"); + } + } catch(e) { logger.warn("[Player] Gateway leave error:", e?.message); } + + if (this._voiceConn) { + try { await this._voiceConn.disconnect(); } catch(e) { logger.warn("[Player] voiceConn disconnect error:", e?.message); } + } + + if (this._audioBridge) { + this._audioBridge.stop(); + } + + this.queue.reset(); + this._voiceConn = null; + this.lavalinkPlayer = null; + this.connection = null; + this._paused = false; + this._pausedAt = null; + this._playingNext = false; + this._autoplay = false; + if (this._autoplayHandler) { + this.removeListener("queueEnd", this._autoplayHandler); + this._autoplayHandler = null; + } + } catch (e) { + logger.error("[Player] leave error:", e.message); + this.leaving = false; + return false; + } + this.leaving = false; + this.emit("leave"); + return true; + } + + /** + * Fully destroy this player instance: clean up timers, listeners, + * connections, and resources. + */ + destroy() { + if (this._destroyed) return; + this._destroyed = true; + + this._clearTrackEndTimer(); + this._activeTrackOpt = null; + + try { + if (this._lavalink) { + if (this._onLavalinkPlayerDisconnect) { + try { this._lavalink.off("playerDisconnected", this._onLavalinkPlayerDisconnect); } catch(e) { /* best effort */ } + this._onLavalinkPlayerDisconnect = null; + } + } + this.leaving = true; + this._stopInactivityTimer(); + if (this._rejoinTimer) { clearTimeout(this._rejoinTimer); this._rejoinTimer = null; } + this._autoplay = false; + if (this._autoplayHandler) { + this.removeListener("queueEnd", this._autoplayHandler); + this._autoplayHandler = null; + } + this.searches.clear(); + + this._bridgeStop(); + if (this._audioBridge) { + this._audioBridge.destroy(); + this._audioBridge = null; + } + if (this._voiceConn) { + try { this._voiceConn.disconnect(); } catch(e) { logger.warn("[Player] voiceConn disconnect in destroy:", e?.message); } + this._voiceConn = null; + } + this.lavalinkPlayer = null; + this.connection = null; + + if (this._channelId) { + try { + const vm = getVoiceManager(this.client); + vm.leaveChannel(this._channelId); + } catch(e) { /* best effort */ } + } + } catch (e) { + logger.error("[Player] destroy error:", e.message); + } + } + + /** @type {boolean} Whether the player is currently paused. */ + get paused() { return this._paused; } + + /** + * Pause current playback. + * @returns {string} Status message. + */ + pause() { + if (!this._voiceConn || !this.queue.getCurrent()) + return ":negative_squared_cross_mark: There's nothing playing at the moment!"; + if (this._paused) + return ":negative_squared_cross_mark: Already paused!"; + + this._bridgeStop(); + this._paused = true; + this._pausedAt = Date.now(); + this._pauseTrackEndTimer(); + this.emit("playback", false); + this._stopInactivityTimer(); + return ":pause_button: Paused"; + } + + /** + * Resume paused playback. + * @returns {string} Status message. + */ + resume() { + if (!this._voiceConn || !this.queue.getCurrent()) + return ":negative_squared_cross_mark: There's nothing playing at the moment!"; + if (!this._paused) + return ":negative_squared_cross_mark: Not paused!"; + + if (this._pausedAt) { + this.startedPlaying += (Date.now() - this._pausedAt); + } + + this._paused = false; + this._pausedAt = null; + this._resumeTrackEndTimer(); + this.emit("playback", true); + this._stopInactivityTimer(); + + const current = this.queue.getCurrent(); + if (current?.url) { + const elapsedMs = Date.now() - this.startedPlaying; + this._playTrackViaBridge(current, { seekSeconds: elapsedMs / 1000 }).catch(e => + logger.error("[Player] Resume playback error:", e.message) + ); + } + return ":arrow_forward: Resumed"; + } + + /** + * Skip the current track and advance to the next. Emits "trackSkip" with + * the skipped track so autoplay (when enabled) can replenish the queue. + * @returns {string} Status message. + */ + skip() { + if (!this._voiceConn || !this.queue.getCurrent()) + return ":negative_squared_cross_mark: There's nothing playing at the moment!"; + this._lastPlayedTrack = this.queue.getCurrent(); + this._skipping = true; + this._radioAnnounced = false; + this._activeTrackOpt = null; + this._clearTrackEndTimer(); + this.queue.current = null; + + this._bridgeStop(); + + this.emit("trackSkip", this._lastPlayedTrack); + + if (this.queue.isEmpty() && !this._wasRadio && !this._queueEndedSent) { + this._queueEndedSent = true; + this.emit("queueEnd"); + if (!this._autoplay) { + const prefix = this._getPrefix?.(this._guildId) ?? "%"; + this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true }); + } + } + + this._playingNext = false; + if (!this.queue.isEmpty() && !this.leaving) { + this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); + } else { + this.emit("stopplay"); + if (!this._is247Enabled()) { + this._startInactivityTimer(); + } + } + + this._skipping = false; + return ":track_next: Skipped"; + } + + /** + * Skip to a specific position in the queue. + * @param {number} position - 1-based queue position. + * @returns {string} Status message. + */ + skipTo(position) { + if (!this._voiceConn || !this.queue.getCurrent()) + return ":negative_squared_cross_mark: There's nothing playing at the moment!"; + const idx = position - 1; + if (idx < 0 || idx >= this.queue.size()) + return `:negative_squared_cross_mark: Position ${position} out of range (queue has ${this.queue.size()} tracks).`; + this._lastPlayedTrack = this.queue.getCurrent(); + this.queue.data.splice(0, idx); + this.queue.current = null; + this._skipping = true; + + this._bridgeStop(); + + this.emit("trackSkip", this._lastPlayedTrack); + + if (this.queue.isEmpty() && !this._wasRadio && !this._queueEndedSent) { + this._queueEndedSent = true; + this.emit("queueEnd"); + if (!this._autoplay) { + const prefix = this._getPrefix?.(this._guildId) ?? "%"; + this.emit("message", { embeds: [new EmbedBuilder().setColor(getGlobalColor()).setDescription(this._t("responses._common.queueEnded", { prefix }))], system: true }); + } + } + + this._playingNext = false; + if (!this.queue.isEmpty() && !this.leaving) { + this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); + } else { + this.emit("stopplay"); + if (!this._is247Enabled()) { + this._startInactivityTimer(); + } + } + + this._skipping = false; + return `:track_next: Skipped to position ${position}`; + } + + /** + * Set the playback volume. + * @param {number} v - Volume as a decimal (0–2, where 1 = 100%). + * @returns {string} Status message. + */ + setVolume(v) { + this.preferredVolume = Utils.clamp(v, 0, 2); + this.emit("volume", this.preferredVolume); + if (this._voiceConn) { + this._voiceConn.setVolume(this.preferredVolume * 100); + } + if (!this._voiceConn) + return `Volume set to \`${Math.round(this.preferredVolume * 100)}%\` — will apply when connected.`; + return `Volume changed to \`${Math.round(this.preferredVolume * 100)}%\`.`; + } + + /** @returns {boolean} Whether the queue is empty. */ + isEmpty() { return this.queue.isEmpty(); } + + /** + * Add a track to the queue with optional top-insert. + * @param {object} d - Track data. + * @param {boolean} [t=false] - Insert at the top of the queue. + */ + addToQueue(d, t) { + if (this.queue.data.length >= this._maxQueueSize) { + logger.warn(`[Player] Queue size cap reached (${this._maxQueueSize}) — dropping oldest track`); + this.queue.data.shift(); + } + this.queue.add(d, t); + this.emit("update", "queue"); + this._stopInactivityTimer(); + } + + /** Clear the queue and start the inactivity timer if nothing is playing. */ + clear() { + this.queue.clear(); + this.emit("update", "queue"); + if (!this.queue.getCurrent()) { + this._startInactivityTimer(); + } + } + + /** + * Add multiple tracks to the queue. + * @param {Array} t - Track data array. + * @param {boolean} [top=false] - Insert at the top. + * @returns {number} Number of tracks added. + */ + addManyToQueue(t, top = false) { + if (!Array.isArray(t)) return 0; + const overflow = (this.queue.data.length + t.length) - this._maxQueueSize; + if (overflow > 0) { + logger.warn(`[Player] Queue size cap (${this._maxQueueSize}) — dropping ${overflow} oldest tracks`); + this.queue.data.splice(0, overflow); + } + const added = this.queue.addMany(t, top); + this.emit("update", "queue"); + this._stopInactivityTimer(); + return added; + } + + /** + * Shuffle the queue. + * @returns {string} Status message. + */ + shuffle() { + if (this.isEmpty()) return "There is nothing to shuffle in the queue."; + this.queue.shuffle(); + this.emit("update", "queue"); + return ":twisted_rightwards_arrows: Shuffled queue"; + } + + /** + * Move a track from one position to another (1-based indices). + * @param {number} from + * @param {number} to + * @returns {string} Result message. + */ + move(from, to) { + if (this.queue.size() === 0) return "The queue is empty."; + return this.queue.move(from - 1, to - 1); + } + + /** + * Toggle a loop mode. + * @param {"song"|"queue"} choice + * @returns {string} + */ + loop(choice) { + if (!["song", "queue"].includes(choice)) + return `'${choice}' is not valid. Use \`song\` or \`queue\``; + const state = this.queue.toggleLoop(choice); + const name = choice.charAt(0).toUpperCase() + choice.slice(1); + return state + ? `:repeat: ${name} loop activated` + : `:arrow_right: ${name} loop disabled`; + } + + /** + * Remove a track from the queue by index. + * @param {number} index - 0-based. + * @returns {string} + * @throws {Error} If index is empty. + */ + remove(index) { + if (index === undefined || index === null) throw new Error("Index can't be empty"); + const oldSize = this.queue.size(); + const msg = this.queue.remove(index); + if (oldSize !== this.queue.size()) this.emit("update", "queue"); + + if (this.isEmpty() && !this.queue.getCurrent()) { + this._startInactivityTimer(); + } + return msg; + } + + /** @private Stop the audio bridge if currently playing. */ + _bridgeStop() { + if (this._audioBridge?.playing) { + this._audioBridge.stop(); + } + } + + /** + * @private Send the self-deafen voice state update. Best effort: the + * VoiceManager silently no-ops when the connection has no connection_id + * yet (missing from VoiceServerUpdate) — re-sent after every + * requestVoiceStateSync so later attempts still land once it exists. + * @param {object} vm - VoiceManager instance. + * @param {string} channelId - Voice channel ID. + */ + _assertSelfDeaf(vm, channelId) { + try { + vm.updateVoiceState(channelId, { self_deaf: true, self_mute: false }); + } catch (e) { + logger.warn("[Player] Self-deafen failed:", e.message); + } + } + + /** + * @private Translate a locale key for this player's guild. + * @param {string} key + * @param {object} [replacements={}] + * @returns {string} + */ + _t(key, replacements = {}) { + if (!this.locale) return key; + return this.locale.translate(this._guildId, key, replacements); + } +} + +// Attach the split-out concerns: playback advancement (PlaybackMixin), search +// & queue-filling (SearchMixin), and user-facing rendering (DisplayMixin). +applyMixins(Player, PlaybackMixin, SearchMixin, DisplayMixin); + +export { Player as default, Player, Queue }; diff --git a/src/music/player/Queue.mjs b/src/music/player/Queue.mjs new file mode 100644 index 0000000..7076587 --- /dev/null +++ b/src/music/player/Queue.mjs @@ -0,0 +1,168 @@ +/** + * @module src/music/player/Queue + * @description Queue data structure: track list, loop modes (song/queue), + * add/remove/move/shuffle/pagination, and queue events. + */ + +import { EventEmitter } from "node:events"; +import { Utils } from "../../utils/Utils.mjs"; + +/** + * @class Queue + * @description Internal queue data structure that tracks tracks, loop state, + * and emits queue events. + * @extends {EventEmitter} + * + * Events (all emitted as `"queue"` with `{ type, data }`): + * - `update` — the current track advanced + * - `remove` / `move` / `add` / `addMany` / `shuffle` + */ +export class Queue extends EventEmitter { + /** @type {Array} The queued track objects. */ + data = []; + /** @type {object|null} The currently playing track. */ + current = null; + /** @type {boolean} Whether queue loop is enabled. */ + loop = false; + /** @type {boolean} Whether single-song loop is enabled. */ + songLoop = false; + + /** Initialize an empty queue with no loop enabled. */ + constructor() { + super(); + } + + /** @returns {boolean} Whether the queue has no tracks. */ + isEmpty() { return this.data.length === 0; } + /** @returns {number} Number of tracks in the queue (excluding current). */ + size() { return this.data.length; } + + /** + * Advance to the next track in the queue. If songLoop is active, returns + * the current track. If queue loop is active, re-appends the current track. + * @returns {object|null} The next track, or null if the queue is empty. + */ + next() { + const previous = this.current; + + if (this.songLoop && this.current) return this.current; + if (this.loop && this.current) this.data.push(this.current); + + if (this.isEmpty()) { + this.current = null; + return null; + } + + this.current = this.data.shift(); + this.emit("queue", { + type: "update", + data: { current: this.current, old: previous, loop: this.loop } + }); + return this.current; + } + + /** + * Remove a track from the queue by index. + * @param {number} idx - Zero-based index of the track to remove. + * @returns {string} Result message indicating success or out-of-bounds error. + */ + remove(idx) { + if (idx < 0 || idx >= this.data.length) return "Index out of bounds"; + const title = this.data[idx].title; + const removed = this.data.splice(idx, 1); + this.emit("queue", { type: "remove", data: { index: idx, old: this.data.slice(), removed, new: this.data } }); + return `Successfully removed **${title}** from the queue.`; + } + + /** + * Move a track from one position to another (0-based indices). + * @param {number} from - Source index. + * @param {number} to - Destination index. + * @returns {string} Result message indicating success or error. + */ + move(from, to) { + if (from < 0 || from >= this.data.length) return "Source index out of bounds"; + if (to < 0 || to >= this.data.length) return "Target index out of bounds"; + if (from === to) return "Track is already in that position"; + const [track] = this.data.splice(from, 1); + this.data.splice(to, 0, track); + this.emit("queue", { type: "move", data: { from, to, track } }); + return `Moved **${track.title}** from position ${from + 1} to ${to + 1}.`; + } + + /** + * Add a single track to the queue. + * @param {object} data - Track data object. + * @param {boolean} [top=false] - If true, insert at the front of the queue. + * @returns {number} The new length of the queue. + */ + add(data, top = false) { + this.emit("queue", { type: "add", data: { append: !top, data } }); + return top ? this.data.unshift(data) : this.data.push(data); + } + + /** + * Add multiple tracks to the queue (up to 1000). + * @param {Array} tracks - Array of track data objects. + * @param {boolean} [top=false] - If true, insert at the front of the queue. + * @returns {number} Number of tracks actually added. + */ + addMany(tracks, top = false) { + if (!tracks?.length) return 0; + if (!Array.isArray(tracks)) tracks = []; + const count = Math.min(tracks.length, 1000); + if (top) { + for (let i = count - 1; i >= 0; i--) this.data.unshift(tracks[i]); + } else { + for (let i = 0; i < count; i++) this.data.push(tracks[i]); + } + this.emit("queue", { type: "addMany", data: { append: !top, tracks: tracks.slice(0, count) } }); + return count; + } + + /** Remove all tracks from the queue. */ + clear() { this.data.length = 0; } + /** Clear the queue and reset all state (current, loops). */ + reset() { this.clear(); this.current = null; this.songLoop = false; this.loop = false; } + + /** @param {boolean} bool - Enable or disable song loop. */ + setSongLoop(bool) { this.songLoop = bool; } + /** @param {boolean} bool - Enable or disable queue loop. */ + setLoop(bool) { this.loop = bool; } + + /** + * Toggle a loop mode on or off. + * @param {"song"|"queue"} loop - The type of loop to toggle. + * @returns {boolean|null} The new loop state, or null if the loop type is invalid. + */ + toggleLoop(loop) { + if (loop === "song") { this.setSongLoop(!this.songLoop); return this.songLoop; } + if (loop === "queue") { this.setLoop(!this.loop); return this.loop; } + return null; + } + + /** Shuffle the queue in place and emit a queue event. */ + shuffle() { + Utils.shuffleArr(this.data); + this.emit("queue", { type: "shuffle", data: this.data }); + } + + /** @returns {object|null} The currently playing track. */ + getCurrent() { return this.current; } + /** @returns {Array} A copy of the queue array. */ + getQueue() { return this.data; } + + /** + * Get a paginated slice of the queue. + * @param {number} [page=1] - 1-based page number (clamped to valid range). + * @param {number} [pageSize=10] - Number of tracks per page. + * @returns {object} Page result with items, page, totalPages, total, start. + */ + getPage(page = 1, pageSize = 10) { + const total = this.data.length; + const totalPages = Math.max(1, Math.ceil(total / pageSize)); + const safePage = Utils.clamp(page, 1, totalPages); + const start = (safePage - 1) * pageSize; + return { items: this.data.slice(start, start + pageSize), page: safePage, totalPages, total, start }; + } +} diff --git a/src/music/player/SearchMixin.mjs b/src/music/player/SearchMixin.mjs new file mode 100644 index 0000000..bf9140d --- /dev/null +++ b/src/music/player/SearchMixin.mjs @@ -0,0 +1,484 @@ +/** + * @module src/music/player/SearchMixin + * @description Search & queue-filling concern for {@link Player}: Lavalink + * queries, search sessions with interactive selection, YouTube fallbacks, + * radio/external track builders. + * + * These methods are applied onto the Player class prototype via + * {@link applyMixins} — `this` is a Player instance. + */ + +import { EventEmitter } from "node:events"; +import { Utils } from "../../utils/Utils.mjs"; +import { logger } from "../../core/Logger.mjs"; +import { PROVIDERS, PROVIDER_NAMES } from "../providers.mjs"; + +/** + * @type {object} + * @description Search mixin — applied to Player. + */ +const SearchMixin = { + /** + * @async Resolve a free-text query or URL to track data via Lavalink for + * internal consumers (autoplay, Last.fm). URL queries are loaded directly + * (like play()) so playlist/mix URLs resolve to their full track lists. + * @this {import('./Player.mjs').Player} + * @param {{query: string, provider?: string, trackMeta?: object}} opts + * @returns {Promise<{type: "video"|"list"|"error", data?: object}|null>} + */ + async generalQuery({ query, provider = "yt", trackMeta = null }) { + try { + if (!this._lavalink) return { type: "error", data: "Audio node not ready." }; + await this._lavalink.waitForNode({ timeoutMs: 15_000 }); + const isUrl = typeof query === "string" && Utils.isValidUrl(query); + const result = isUrl + ? await this._lavalink.search(query) + : await this._lavalink.search(query, { source: this._getSource(provider) }); + const tracks = (result?.tracks ?? []).map(t => this._lcTrackToVideo(t, trackMeta)).filter(Boolean); + if (!tracks.length) return null; + return tracks.length === 1 ? { type: "video", data: tracks[0] } : { type: "list", data: tracks }; + } catch (err) { + logger.warn("[Player] generalQuery failed:", err?.message); + return { type: "error", data: err?.message ?? String(err) }; + } + }, + + /** + * @async Search for tracks via Lavalink and store results for interactive + * selection. + * @this {import('./Player.mjs').Player} + * @param {string} query - The search query string. + * @param {string} id - A unique key to identify this search session (e.g. message ID). + * @param {string} [provider="ytm"] - The search provider key. + * @returns {Promise<{m: string, count: number}>} Formatted result list message and track count. + */ + async fetchResults(query, id, provider = "ytm") { + try { + if (!this._lavalink) return { m: "Audio node not ready.", count: 0 }; + + await this._lavalink.waitForNode({ timeoutMs: 15_000 }); + + const source = this._getSource(provider); + const result = await this._lavalink.search(query, { source }); + const lcTracks = result?.tracks ?? []; + + const results = lcTracks.slice(0, this.resultLimit).map(t => this._lcTrackToVideo(t)).filter(Boolean); + + let list = "Search results using **" + (PROVIDER_NAMES[provider] || "YouTube Music") + "**:\n\n"; + results.forEach((v, i) => { + const url = v.url || ""; + const title = v.title || Utils.formatTrackInfo(v, false); + const dur = v.duration ? this.getDuration(v.duration) : "?:??"; + list += (i + 1) + ". [" + title + "](" + url + ") - " + dur + "\n"; + }); + list += "\nSend the number of the result. Example: `2`\nSend 'x' to cancel."; + + if (this.searches.size >= this._searchMaxSize) { + const oldestKey = this.searches.keys().next().value; + if (oldestKey !== undefined) this.searches.delete(oldestKey); + } + this.searches.set(id, results); + + return { m: list, count: results.length }; + } catch (err) { + return { m: "Error searching: " + err.message, count: 0 }; + } + }, + + /** + * Select a search result and add it to the queue. + * @this {import('./Player.mjs').Player} + * @param {string} id + * @param {number} [result=0] + * @param {boolean} [next=false] + * @returns {object|null} + */ + playResult(id, result = 0, next = false) { + if (!this.searches.has(id)) return null; + const searchResults = this.searches.get(id); + if (!searchResults || !searchResults[result]) return null; + + const res = searchResults[result]; + this.addToQueue(res, next); + + this.searches.delete(id); + + if (!this.queue.getCurrent()) { + this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); + } + return res; + }, + + /** + * Search and add a track to the top of the queue. + * @this {import('./Player.mjs').Player} + * @param {string} query + * @param {string} provider + * @param {object} trackMeta + * @returns {EventEmitter} + */ + playFirst(query, provider, trackMeta) { return this.play(query, true, provider, trackMeta); }, + + /** + * @private Convert a Lavalink track to the internal track format. + * @this {import('./Player.mjs').Player} + * @param {object} track + * @param {object|null} [trackMeta=null] + * @returns {object|null} + */ + _lcTrackToVideo(track, trackMeta = null) { + if (!track || typeof track !== "object") return null; + const info = track.info ?? track ?? {}; + + let ms = info.length ?? track.length ?? info.durationMs ?? 0; + if (ms === 0 && info.duration != null) { + if (typeof info.duration === "number") { + ms = info.duration; + } else if (typeof info.duration === "object" && info.duration.seconds != null) { + ms = info.duration.seconds * 1000; + } + } + + let trackUri = info.uri ?? ("https://www.youtube.com/watch?v=" + (info.identifier || "")); + if (typeof trackUri === 'string' && trackUri.includes('music.youtube.com')) { + trackUri = trackUri.replace('music.youtube.com', 'www.youtube.com'); + } + const video = { + videoId: info.identifier ?? "", + encoded: track.encoded ?? info.encoded ?? "", + sourceName: info.sourceName ?? "unknown", + title: Utils.cleanTitle(info.title ?? "Unknown"), + url: trackUri, + thumbnail: info.artworkUrl ?? null, + spotifyUrl: null, + _durationMs: ms, + duration: { + timestamp: Utils.prettifyMS(ms), + seconds: Math.floor(ms / 1000), + }, + author: { + name: info.author ?? "Unknown", + url: info.uri ?? null, + }, + artists: null, + }; + if (trackMeta) { + video.artist = trackMeta.artist ?? null; + video.requestedArtist = trackMeta.artist ?? null; + video.requestedTitle = trackMeta.name ?? trackMeta.title ?? null; + video.lastfm = { + source: trackMeta.source ?? "lastfm", + artist: trackMeta.artist ?? null, + name: trackMeta.name ?? trackMeta.title ?? null, + url: trackMeta.url ?? "", + }; + } + return video; + }, + + /** + * @private Resolve a provider key to a Lavalink search prefix. + * @this {import('./Player.mjs').Player} + * @param {string} provider + * @returns {string} + */ + _getSource(provider) { + return PROVIDERS[provider]?.prefix ?? (provider + "search"); + }, + + /** + * Search for a track and add it to the queue. Handles URL loading with + * YouTube normalization + oEmbed title fallback and playlist expansion. + * @this {import('./Player.mjs').Player} + * @param {string} query + * @param {boolean} [top=false] + * @param {string} [provider] + * @param {object} [trackMeta=null] + * @returns {EventEmitter} Emits "message" events with status strings. + */ + play(query, top = false, provider, trackMeta = null) { + const events = new EventEmitter(); + const source = this._getSource(provider || "ytm"); + const isUrl = Utils.isValidUrl(query); + + (async () => { + try { + if (!this._lavalink) { + events.emit("message", "Audio node not ready yet."); + return; + } + + await this._lavalink.waitForNode({ timeoutMs: 15_000 }); + + events.emit("message", "Searching..."); + + const ytId = Utils.extractYouTubeId(query); + const canonicalYtUrl = ytId ? Utils.normalizeYouTubeUrl(query) : null; + const searchQuery = (isUrl && canonicalYtUrl) ? canonicalYtUrl : query; + + let result; + try { + if (isUrl) { + result = await this._lavalink.search(searchQuery); + } else { + result = await this._lavalink.search(searchQuery, { source }); + } + } catch (searchErr) { + logger.warn("[Player] URL/primary search failed:", searchErr?.message); + result = null; + if (!isUrl) throw searchErr; + } + let lcTracks = result?.tracks ?? []; + // Set when the only results we have came from the oEmbed title-search + // fallback. That path resolves a SINGLE video (direct URL load was + // bot-blocked), so its result list is a search page — NOT a playlist. + // Bulk-queueing it would queue a bunch of "related" songs instead of + // the one requested video (original fluxer bug reported by users). + let fromTitleFallback = false; + + if (isUrl && lcTracks.length === 0 && ytId) { + const directBlocked = "YouTube blocked direct loading for this video (`Sign in to confirm you're not a bot`) — trying search fallback..."; + + if (searchQuery !== query) { + events.emit("message", "Retrying with original URL..."); + try { + const retry = await this._lavalink.search(query); + lcTracks = retry?.tracks ?? []; + } catch (_) { lcTracks = []; } + } + + if (lcTracks.length === 0) { + events.emit("message", directBlocked); + const title = await Utils.fetchYouTubeOEmbedTitle(ytId); + if (title) { + logger.player(`[Player] oEmbed fallback: resolved title "${title}" for ${ytId}`); + for (const fallbackSource of ["ytsearch", "ytmsearch"]) { + try { + const fb = await this._lavalink.search(title, { source: fallbackSource }); + if (fb?.tracks?.length > 0) { + lcTracks = fb.tracks; + fromTitleFallback = true; + break; + } + } catch (_) { /* try next source */ } + } + } else { + logger.warn("[Player] oEmbed fallback: could not resolve title for " + ytId); + } + } + } + + if (lcTracks.length === 0) { + if (!isUrl && source !== "ytmsearch") { + events.emit("message", "No results from primary source, trying YouTube Music..."); + const fallback = await this._lavalink.search(searchQuery, { source: "ytmsearch" }); + if (fallback?.tracks?.length > 0) { + const video = this._lcTrackToVideo(fallback.tracks[0], trackMeta); + if (video) { + this.addToQueue(video, top); + events.emit("message", "Successfully added [" + video.title + "](" + video.url + ") to the queue."); + if (!this.queue.getCurrent()) { + this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); + } + return; + } + } + } + events.emit("message", "**No results found for '" + query + "'.**"); + return; + } + + // Pick the track to queue. For a title-search fallback, prefer the + // result that is the exact video the user requested (search may rank + // covers/remixes first); otherwise take the first result. + let firstTrack = lcTracks[0]; + if (fromTitleFallback && ytId) { + firstTrack = lcTracks.find(t => (t?.info?.identifier ?? t?.identifier) === ytId) ?? lcTracks[0]; + if (firstTrack !== lcTracks[0]) { + logger.player(`[Player] Search fallback: exact video match found for ${ytId}`); + } + } + + // Only a genuine playlist/mix URL load may bulk-queue. A title-search + // fallback for a single video must queue exactly one track. + if (isUrl && !fromTitleFallback && lcTracks.length > 1) { + const videos = lcTracks.map(t => this._lcTrackToVideo(t, trackMeta)).filter(Boolean); + this.addManyToQueue(videos, top); + events.emit("message", "Successfully added **" + videos.length + "** songs to the queue."); + } else { + const video = this._lcTrackToVideo(firstTrack, trackMeta); + if (video) { + this.addToQueue(video, top); + events.emit("message", "Successfully added [" + video.title + "](" + video.url + ") to the queue."); + } else { + events.emit("message", "**Failed to parse track data.**"); + return; + } + } + + if (!this.queue.getCurrent()) { + this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); + } + } catch (err) { + logger.error("[Player] play() search error:", err?.message); + events.emit("message", err?.message || "An error occurred while loading the track."); + } + })(); + + return events; + }, + + /** + * @async Search for tracks via Lavalink and return raw track results. + * @this {import('./Player.mjs').Player} + * @param {string} query + * @param {string} [provider="ytm"] + * @returns {Promise>} + */ + async search(query, provider = 'ytm') { + if (!this._lavalink) return []; + try { + const source = this._getSource(provider); + const result = await this._lavalink.search(query, { source }); + return result.tracks || []; + } catch (e) { + logger.error(`[Player] lavalink search error:`, e?.message); + return []; + } + }, + + /** + * @private Build a radio-type track object. + * @this {import('./Player.mjs').Player} + * @param {object} radio + * @returns {object} + */ + _buildRadioTrack(radio) { + return { + type: "radio", + title: radio.detailedName || radio.title || "Unknown Radio", + description: Utils.truncate(radio.description || "", 200), + url: radio.url, + author: { + name: radio.author?.name || "Unknown", + url: radio.author?.url || radio.url, + }, + thumbnail: radio.thumbnail ?? null, + }; + }, + + /** + * Add a radio stream to the queue. + * @this {import('./Player.mjs').Player} + * @param {object} radio + * @param {boolean} [top=false] + */ + playRadio(radio, top = false) { + if (!radio?.url) { logger.error("[Player] Invalid radio data"); return; } + this.addToQueue(this._buildRadioTrack(radio), top); + if (!this.queue.getCurrent()) this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); + }, + + /** + * @async Switch to a different radio stream, replacing any current radio tracks. + * @this {import('./Player.mjs').Player} + * @param {object} radio - Radio object with url, title, author, thumbnail. + * @returns {Promise} + */ + async switchRadio(radio) { + if (!radio?.url) { logger.error("[Player] switchRadio: invalid radio data"); return; } + + const newTrack = this._buildRadioTrack(radio); + this.queue.data = this.queue.data.filter(t => t.type !== "radio"); + + if (!this.queue.getCurrent()) { + this.queue.add(newTrack); + this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); + return; + } + + this.queue.data.unshift(newTrack); + this._skipping = true; + this._radioAnnounced = false; + this.queue.current = null; + this._bridgeStop(); + this._playingNext = false; + this._skipping = false; + if (!this.leaving) this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); + }, + + /** + * @private Build a direct-URL track object. + * @this {import('./Player.mjs').Player} + * @param {string} url + * @param {string} [title] + * @param {string} [artist] + * @param {string} [trackType="external"] + * @returns {object} + */ + _buildExternalTrack(url, title = null, artist = null, trackType = "external") { + const displayTitle = title || this._extractFilenameFromUrl(url); + return { + type: trackType, + title: displayTitle, + url: url, + artist: artist || null, + thumbnail: null, + }; + }, + + /** + * @private Extract a display filename from a URL. + * @this {import('./Player.mjs').Player} + * @param {string} url + * @returns {string} + */ + _extractFilenameFromUrl(url) { + try { + const pathname = new URL(url).pathname; + const filename = pathname.split("/").pop(); + if (filename && filename.includes(".")) { + return decodeURIComponent(filename.replace(/\.[^.]+$/, "")) || "Stream"; + } + } catch (_) {} + return "External Stream"; + }, + + /** + * Play a direct audio URL (MP3, OGG, AAC, stream, etc.) without Lavalink + * search. The bridge handles decoding via Lavalink if needed. + * @this {import('./Player.mjs').Player} + * @param {string} url - Direct HTTP(S) audio URL. + * @param {string} [title] - Optional display title. + * @param {string} [artist] - Optional artist name. + * @param {boolean} [top=false] - Insert at top of queue. + * @param {string} [trackType="external"] - "external" or "stream". + * @returns {EventEmitter} Emits "message" events with status strings. + */ + playExternal(url, title = null, artist = null, top = false, trackType = "external") { + const events = new EventEmitter(); + + (async () => { + try { + const track = this._buildExternalTrack(url, title, artist, trackType); + this.addToQueue(track, top); + events.emit("message", "Added **[" + track.title + "](" + url + ")** to the queue."); + + if (!this.queue.getCurrent()) { + this.playNext().catch(e => { + logger.error("[Player] playExternal playNext error:", e.message); + events.emit("message", "Error playing stream: " + e.message); + }); + } + } catch (err) { + logger.error("[Player] playExternal error:", err?.message); + events.emit("message", "Error: " + (err?.message || "Failed to add external stream.")); + } + })(); + + return events; + }, +}; + +export default SearchMixin; +export { SearchMixin }; diff --git a/src/music/player/index.mjs b/src/music/player/index.mjs new file mode 100644 index 0000000..0479e14 --- /dev/null +++ b/src/music/player/index.mjs @@ -0,0 +1,9 @@ +/** + * @module src/music/player + * @description Public surface of the per-channel player. + * + * Import map from the old layout: + * - `src/Player.mjs` → this module (default export = Player) + */ + +export { default, Player, Queue } from "./Player.mjs"; diff --git a/src/probe.mjs b/src/music/probe.mjs similarity index 93% rename from src/probe.mjs rename to src/music/probe.mjs index 0693192..41ad76d 100644 --- a/src/probe.mjs +++ b/src/music/probe.mjs @@ -1,8 +1,8 @@ -/** @module src/probe @description Audio probing utilities using ffprobe to extract metadata from media files/streams. */ +/** @module src/music/probe @description Audio probing utilities using ffprobe to extract metadata from media files/streams. */ import ffprobe from "ffprobe-static"; import { spawn } from "node:child_process"; -import { logger } from "./constants/Logger.mjs"; +import { logger } from "../core/Logger.mjs"; /** @type {number} @description Maximum time in milliseconds to wait for ffprobe to complete. */ const PROBE_TIMEOUT_MS = 15_000; diff --git a/src/music/providers.mjs b/src/music/providers.mjs new file mode 100644 index 0000000..f5cf5fa --- /dev/null +++ b/src/music/providers.mjs @@ -0,0 +1,122 @@ +/** @module src/music/providers */ + +/** + * Map of provider shorthand keys to their Lavalink search prefix and display label. + * Both short aliases (e.g. `scld`) and full names (e.g. `soundcloud`) map to the same + * prefix/label pair. + * @type {Object} + */ +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/FluxerListManager.mjs b/src/services/FluxerListManager.mjs similarity index 96% rename from src/FluxerListManager.mjs rename to src/services/FluxerListManager.mjs index db17c41..888db11 100644 --- a/src/FluxerListManager.mjs +++ b/src/services/FluxerListManager.mjs @@ -1,12 +1,12 @@ -/** @module src/FluxerListManager @description FluxerList API integration for fetching server/bot voter lists with caching. */ +/** @module src/services/FluxerListManager @description FluxerList API integration for fetching server/bot voter lists with caching. */ -import { logger } from "./constants/Logger.mjs"; +import { logger } from "../core/Logger.mjs"; import { FLUXERLIST, FLUXERLIST_AUTH, FLUXERLIST_LIMITS, buildFluxerListUrl, -} from "./constants/API.mjs"; +} from "../utils/API.mjs"; /** @class FluxerListManager @description Fetches and caches voter lists from the FluxerList API for servers and bots. */ export class FluxerListManager { diff --git a/src/TrackOptionsManager.mjs b/src/services/TrackOptionsManager.mjs similarity index 98% rename from src/TrackOptionsManager.mjs rename to src/services/TrackOptionsManager.mjs index 8d6362e..d4a3c47 100644 --- a/src/TrackOptionsManager.mjs +++ b/src/services/TrackOptionsManager.mjs @@ -1,6 +1,6 @@ -/** @module src/TrackOptionsManager @description Per-user track options (start/end timestamps) stored in MySQL. Provides caching, matching, and CRUD for track segments. */ +/** @module src/services/TrackOptionsManager @description Per-user track options (start/end timestamps) stored in MySQL. Provides caching, matching, and CRUD for track segments. */ import mysql from "mysql2"; -import { logger } from "./constants/Logger.mjs"; +import { logger } from "../core/Logger.mjs"; const DEFAULT_ALIAS = "default"; const MAX_ALIAS_LEN = 32; diff --git a/src/services/lastfm/LastFmManager.mjs b/src/services/lastfm/LastFmManager.mjs new file mode 100644 index 0000000..2ff94c1 --- /dev/null +++ b/src/services/lastfm/LastFmManager.mjs @@ -0,0 +1,287 @@ +/** + * @module src/services/lastfm/LastFmManager + * @description Last.fm API integration for scrobbling, now-playing updates, + * loved tracks, and user session management with MySQL persistence. + * + * Base class of the split Last.fm manager: configuration, constructor, MySQL + * pool + schema setup, multi-bot isolation (bot_id) and the small helpers + * shared by every concern. User-session storage, scrobbling, track/artist/ + * album/tag queries, user chart queries and server statistics live in the + * mixin modules applied to this class at the bottom of the file. + */ + +import { logger } from "../../core/Logger.mjs"; +import { normalizeTrackText } from "./constants.mjs"; +import { applyMixins } from "../../utils/mixins.mjs"; +import { parseLastFmUrl, isLastFmUrl } from "./urlUtils.mjs"; +import UserStoreMixin from "./UserStoreMixin.mjs"; +import ScrobblingMixin from "./ScrobblingMixin.mjs"; +import TrackQueriesMixin from "./TrackQueriesMixin.mjs"; +import UserQueriesMixin from "./UserQueriesMixin.mjs"; +import ServerStatsMixin from "./ServerStatsMixin.mjs"; + +/** @class LastFmManager @description Manages Last.fm user sessions, scrobbling, loved tracks, and top/recent track queries with MySQL persistence. */ +export class LastFmManager { + + /** @param {object} config @param {string} config.apiKey @param {string} config.apiSecret @param {boolean} [config.enabled] @param {number} [config.scrobbleThreshold] @param {number} [config.scrobbleMinMs] @param {object} mysqlConfig */ + constructor(config, mysqlConfig) { + this.apiKey = config?.apiKey ?? ""; + this.apiSecret = config?.apiSecret ?? ""; + this.enabled = config?.enabled !== false && !!(this.apiKey && this.apiSecret); + this.scrobbleThreshold = config?.scrobbleThreshold ?? 0.5; + this.scrobbleMinMs = config?.scrobbleMinMs ?? 240_000; + + this._mysqlConfig = mysqlConfig; + this._pool = null; + + this.botId = null; + this._hasBotIdColumn = false; + + this._userCache = new Map(); + this._userCacheMax = 5000; + + this._totalScrobblesCache = null; + this._totalScrobblesCacheExpiry = 0; + this._totalScrobblesInflight = null; + + if (!this.enabled) { + if (config?.enabled === false) { + logger.settings("[LastFm] Disabled — \"enabled\" is set to false in config."); + } else { + logger.settings("[LastFm] Disabled — apiKey or apiSecret missing in config."); + } + } + } + + /** @async Set the bot ID for multi-bot isolation. @param {string} id */ + async setBotId(id) { + const changed = this.botId !== id; + this.botId = id; + if (changed) { + await this._ensureBotIdColumn(); + this._userCache.clear(); + } + } + + /** @private @async Ensure the bot_id column exists and is part of the primary key. */ + async _ensureBotIdColumn() { + if (this._hasBotIdColumn) return; + const pool = await this._getPool(); + + 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..."); + await pool.execute("ALTER TABLE `lastfm_users` ADD COLUMN `bot_id` VARCHAR(32) NOT NULL DEFAULT ''"); + 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 { + const colInfo = cols[0]; + const isNullable = colInfo.IS_NULLABLE === 'YES'; + const isPK = colInfo.COLUMN_KEY === 'PRI'; + if (!isPK) { + logger.settings("[LastFm] Fixing lastfm_users.bot_id: adding to primary key..."); + if (isNullable) { + await pool.execute("UPDATE `lastfm_users` SET `bot_id` = '' WHERE `bot_id` IS NULL"); + await pool.execute("ALTER TABLE `lastfm_users` MODIFY COLUMN `bot_id` VARCHAR(32) NOT NULL DEFAULT ''"); + } + 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] Fix complete: lastfm_users.bot_id added to primary key."); + } + } + + 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'` + ); + if (statsCols.length === 0) { + logger.settings("[LastFm] Auto-migrating: adding bot_id column to lastfm_stats..."); + await pool.execute("ALTER TABLE `lastfm_stats` ADD COLUMN `bot_id` VARCHAR(32) NOT NULL DEFAULT ''"); + if (this.botId) { + await pool.execute("UPDATE `lastfm_stats` SET `bot_id` = ? WHERE `bot_id` = ''", [String(this.botId)]); + } + await pool.execute("ALTER TABLE `lastfm_stats` DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)"); + logger.settings("[LastFm] Auto-migration complete: lastfm_stats.bot_id added."); + } else { + const colInfo = statsCols[0]; + const isNullable = colInfo.IS_NULLABLE === 'YES'; + const isPK = colInfo.COLUMN_KEY === 'PRI'; + if (!isPK) { + logger.settings("[LastFm] Fixing lastfm_stats.bot_id: adding to primary key..."); + if (isNullable) { + await pool.execute("UPDATE `lastfm_stats` SET `bot_id` = '' WHERE `bot_id` IS NULL"); + await pool.execute("ALTER TABLE `lastfm_stats` MODIFY COLUMN `bot_id` VARCHAR(32) NOT NULL DEFAULT ''"); + } + if (this.botId) { + await pool.execute("UPDATE `lastfm_stats` SET `bot_id` = ? WHERE `bot_id` = ''", [String(this.botId)]); + } + await pool.execute("ALTER TABLE `lastfm_stats` DROP PRIMARY KEY, ADD PRIMARY KEY (id, bot_id)"); + logger.settings("[LastFm] Fix complete: lastfm_stats.bot_id added to primary key."); + } + } + + this._hasBotIdColumn = true; + } + + /** @private @returns {{where: string, params: Array}} SQL filter fragment for bot_id. */ + _botIdFilter() { + if (!this.botId || !this._hasBotIdColumn) return { where: "", params: [] }; + return { where: " AND bot_id = ?", params: [String(this.botId)] }; + } + + /** @private @async Get or create the MySQL connection pool. @returns {Promise} */ + async _getPool() { + if (this._pool) return this._pool; + const mysql = await import("mysql2/promise"); + this._pool = mysql.createPool({ + host: this._mysqlConfig.host, + port: this._mysqlConfig.port ?? 3306, + user: this._mysqlConfig.user, + password: this._mysqlConfig.password, + database: this._mysqlConfig.database, + }); + await this._initTable(); + return this._pool; + } + + /** @private @async Create the lastfm_users and lastfm_stats tables if they don't exist. */ + async _initTable() { + const pool = this._pool; + await pool.execute(` + CREATE TABLE IF NOT EXISTS \`lastfm_users\` ( + \`user_id\` VARCHAR(30) NOT NULL PRIMARY KEY, + \`session_key\` VARCHAR(64) NOT NULL, + \`username\` VARCHAR(64) NOT NULL DEFAULT '', + \`scrobble\` TINYINT(1) NOT NULL DEFAULT 1, + \`scrobble_count\` BIGINT NOT NULL DEFAULT 0, + \`linked_at\` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + `); + + await pool.execute(` + CREATE TABLE IF NOT EXISTS \`lastfm_stats\` ( + \`id\` TINYINT(1) NOT NULL PRIMARY KEY DEFAULT 1, + \`stored_scrobbles\` BIGINT NOT NULL DEFAULT 0, + \`linked_users\` INT NOT NULL DEFAULT 0 + ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci; + `); + await pool.execute(` + INSERT IGNORE INTO \`lastfm_stats\` (id, stored_scrobbles, linked_users) VALUES (1, 0, 0) + `); + } + + /** + * Parse a Last.fm music URL into artist, track, and album components. + * @param {string} url - The Last.fm URL to parse. + * @returns {object|null} Parsed components { artist, track, album, url } or null if invalid. + */ + parseLastFmUrl(url) { + return parseLastFmUrl(url); + } + + /** + * Check whether a string is a valid Last.fm music URL. + * @param {string} str - String to check. + * @returns {boolean} True if the string is a Last.fm music URL. + */ + isLastFmUrl(str) { + return isLastFmUrl(str); + } + + /** @private Throw if Last.fm integration is not enabled/configured. @throws {Error} If apiKey or apiSecret is missing. */ + _assertEnabled() { + if (!this.enabled) throw new Error("Last.fm integration is not configured (missing apiKey/apiSecret)."); + } + + /** @private Increment a user's scrobble_count in the database by 1 (fire-and-forget). @param {string} userId - The user ID. */ + _incrementScrobbleCount(userId) { + if (!userId) return; + const f = this._botIdFilter(); + this._getPool().then(pool => { + pool.execute( + `UPDATE lastfm_users SET scrobble_count = scrobble_count + 1 WHERE user_id = ?${f.where}`, + [String(userId), ...f.params] + ).catch(e => { logger.warn("[LastFm] scrobble_count increment failed:", e?.message); }); + }).catch(e => { logger.warn("[LastFm] scrobble_count pool acquire failed:", e?.message); }); + } + + /** @private Build a search query string from artist and title for playback. @param {string} artist - The artist name. @param {string} title - The track title. @returns {string} Combined search query. */ + _buildPlayQuery(artist, title) { + const cleanArtist = String(artist ?? "").trim(); + const cleanTitle = String(title ?? "").trim(); + return [cleanTitle, cleanArtist].filter(Boolean).join(" "); + } + + /** @private Extract the best artist name from a track object, checking multiple possible fields. @param {object} track - Track object. @returns {string} The artist name. */ + _extractArtist(track) { + const preservedArtist = track?.lastfm?.artist + ?? track?.requestedArtist + ?? track?.artist; + if (preservedArtist) return preservedArtist; + + return track.artists?.[0]?.name + ?? track.author?.name + ?? "Unknown Artist"; + } + + /** @private Extract the best track title from a track object, checking multiple possible fields. @param {object} track - Track object. @returns {string} The track title. */ + _extractTitle(track) { + return track?.lastfm?.name + ?? track?.requestedTitle + ?? track.title + ?? track.name + ?? "Unknown Track"; + } + + /** @private Extract the duration in seconds from a track object, supporting number (ms), object with .seconds, ISO 8601, or plain seconds. @param {object} track - Track object. @returns {string|number} Duration in seconds, or empty string if unavailable. */ + _extractDurationSec(track) { + if (!track.duration) return ""; + 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") { + const m = track.duration.match(/PT(?:(\d+)H)?(?:(\d+)M)?(?:(\d+)S)?/); + if (m) return ((+m[1] || 0) * 3600) + ((+m[2] || 0) * 60) + (+m[3] || 0); + } + return ""; + } + + /** + * Determine whether a track should be scrobbled based on playback time and duration. + * @param {object} track - Track object with duration and title/artist info. + * @param {number} playedMs - How many milliseconds the track has been playing. + * @returns {boolean} True if the track meets the scrobble threshold. + */ + shouldScrobble(track, playedMs) { + const durationMs = typeof track.duration === "object" && track.duration.seconds + ? track.duration.seconds * 1000 + : typeof track.duration === "number" + ? track.duration + : null; + + if (!durationMs || durationMs < 30_000) return false; + + const normalizedTitle = normalizeTrackText(this._extractTitle(track)); + const normalizedArtist = normalizeTrackText(this._extractArtist(track)); + if (!normalizedTitle || !normalizedArtist) return false; + + const thresholdMs = Math.min(durationMs * this.scrobbleThreshold, this.scrobbleMinMs); + return playedMs >= thresholdMs; + } +} + +// Attach the split-out concerns: user-session storage (UserStoreMixin), +// scrobbling (ScrobblingMixin), track/artist/album/tag queries +// (TrackQueriesMixin), per-user chart queries (UserQueriesMixin) and +// server/guild statistics (ServerStatsMixin). +applyMixins(LastFmManager, UserStoreMixin, ScrobblingMixin, TrackQueriesMixin, UserQueriesMixin, ServerStatsMixin); + +// Keep the old import surface: commands used to import the URL helpers from +// this module when it was a single file. (The class itself is exported by its +// declaration above.) +export { parseLastFmUrl, isLastFmUrl } from "./urlUtils.mjs"; diff --git a/src/services/lastfm/ScrobblingMixin.mjs b/src/services/lastfm/ScrobblingMixin.mjs new file mode 100644 index 0000000..8d66de7 --- /dev/null +++ b/src/services/lastfm/ScrobblingMixin.mjs @@ -0,0 +1,98 @@ +/** + * @module src/services/lastfm/ScrobblingMixin + * @description Scrobbling concern for LastFmManager: now-playing updates, scrobble submissions and per-user scrobble-count syncing. + * + * These methods are applied onto the LastFmManager class prototype via + * {@link applyMixins} — `this` is a LastFmManager instance. + */ + +import { logger } from "../../core/Logger.mjs"; +import { apiCall } from "./constants.mjs"; + +/** + * @type {object} + * @description Scrobbling mixin — applied to LastFmManager. + */ +const ScrobblingMixin = { + /** @async Send a now-playing update to Last.fm for a user. @param {string} userId @param {object} track @param {string} track.title @param {string} [track.album] @param {number} [track.trackNumber] */ + async updateNowPlaying(userId, track) { + if (!this.enabled) return; + const user = await this.getUser(userId); + if (!user || !user.scrobbleEnabled) return; + + try { + await apiCall( + { + method: "track.updatenowplaying", + api_key: this.apiKey, + sk: user.sessionKey, + artist: this._extractArtist(track), + track: this._extractTitle(track), + album: track.album ?? "", + duration: this._extractDurationSec(track), + trackNumber: track.trackNumber ?? "", + }, + this.apiSecret, + true + ); + } catch (err) { + logger.warn(`[LastFm] updateNowPlaying failed for ${userId}: ${err.message}`); + } + }, + + /** @async Scrobble a track for a user. @param {string} userId @param {object} track @param {number} startedAtMs @param {string} track.title @param {string} [track.album] @param {number} [track.trackNumber] */ + async scrobble(userId, track, startedAtMs) { + if (!this.enabled) return; + const user = await this.getUser(userId); + if (!user || !user.scrobbleEnabled) return; + + try { + await apiCall( + { + method: "track.scrobble", + api_key: this.apiKey, + sk: user.sessionKey, + "artist[0]": this._extractArtist(track), + "track[0]": this._extractTitle(track), + "album[0]": track.album ?? "", + "timestamp[0]": Math.floor(startedAtMs / 1000), + "duration[0]": this._extractDurationSec(track), + }, + this.apiSecret, + true + ); + logger.settings(`[LastFm] Scrobbled "${track.title}" for ${userId}`); + + this._incrementScrobbleCount(userId); + } catch (err) { + logger.warn(`[LastFm] Scrobble failed for ${userId}: ${err.message}`); + } + }, + + /** + * Sync a user's scrobble count from Last.fm to the local database. + * @async + * @param {string} userId - The user ID. + * @returns {Promise} The synced scrobble count. + */ + async syncUserScrobbleCount(userId) { + if (!this.enabled) return 0; + try { + const info = await this.getUserInfo(userId); + const playcount = Number(info.playcount ?? 0); + const pool = await this._getPool(); + const f = this._botIdFilter(); + await pool.execute( + `UPDATE lastfm_users SET scrobble_count = ? WHERE user_id = ?${f.where}`, + [String(playcount), String(userId), ...f.params] + ); + return playcount; + } catch (e) { + logger.warn("[LastFm] Error:", e?.message); + return 0; + } + } +}; + +export default ScrobblingMixin; +export { ScrobblingMixin }; diff --git a/src/services/lastfm/ServerStatsMixin.mjs b/src/services/lastfm/ServerStatsMixin.mjs new file mode 100644 index 0000000..d6788f2 --- /dev/null +++ b/src/services/lastfm/ServerStatsMixin.mjs @@ -0,0 +1,460 @@ +/** + * @module src/services/lastfm/ServerStatsMixin + * @description Server/guild statistics concern for LastFmManager: who-knows lookups, user comparison, affinity and crowns, the scrobble leaderboard and global scrobble / linked-user totals. + * + * These methods are applied onto the LastFmManager class prototype via + * {@link applyMixins} — `this` is a LastFmManager instance. + */ + +import { logger } from "../../core/Logger.mjs"; + +/** + * @type {object} + * @description Server-stats mixin — applied to LastFmManager. + */ +const ServerStatsMixin = { + /** + * Get who knows an artist among a list of users, ranked by playcount. + * @async + * @param {string} artist - The artist name. + * @param {Array} userIds - Array of user IDs. + * @returns {Promise>} Users who know the artist, sorted by playcount descending. + */ + async getWhoKnows(artist, userIds) { + if (!this.enabled) return []; + if (!Array.isArray(userIds) || !userIds.length) return []; + + const concurrency = 5; + const results = []; + + for (let i = 0; i < userIds.length; i += concurrency) { + const batch = userIds.slice(i, i + concurrency); + + const batchResults = await Promise.allSettled( + batch.map(async (uid) => { + const user = await this.getUser(uid); + if (!user) return null; + + try { + const info = await this.getArtistInfo(artist, uid); + const playcount = info?.userplaycount ?? 0; + return { + userId: uid, + username: user.username, + playcount, + }; + } catch (e) { + logger.warn("[LastFm] Error:", e?.message); + return { + userId: uid, + username: user.username, + playcount: 0, + }; + } + }) + ); + + for (const r of batchResults) { + if (r.status === "fulfilled" && r.value && r.value.playcount > 0) { + results.push(r.value); + } + } + } + + results.sort((a, b) => b.playcount - a.playcount); + return results; + }, + + /** + * Get who knows a specific track among a list of users, ranked by playcount. + * @async + * @param {string} artist - The artist name. + * @param {string} track - The track name. + * @param {Array} userIds - Array of user IDs. + * @returns {Promise>} Users who know the track, sorted by playcount descending. + */ + async getWhoKnowsTrack(artist, track, userIds) { + if (!this.enabled) return []; + if (!Array.isArray(userIds) || !userIds.length) return []; + + const concurrency = 5; + const results = []; + + for (let i = 0; i < userIds.length; i += concurrency) { + const batch = userIds.slice(i, i + concurrency); + + const batchResults = await Promise.allSettled( + batch.map(async (uid) => { + const user = await this.getUser(uid); + if (!user) return null; + + try { + const info = await this.getTrackInfo(artist, track, uid); + const playcount = Number(info?.userplaycount ?? 0); + return { + userId: uid, + username: user.username, + playcount, + }; + } catch (e) { + logger.warn("[LastFm] Error:", e?.message); + return { + userId: uid, + username: user.username, + playcount: 0, + }; + } + }) + ); + + for (const r of batchResults) { + if (r.status === "fulfilled" && r.value && r.value.playcount > 0) { + results.push(r.value); + } + } + } + + results.sort((a, b) => b.playcount - a.playcount); + return results; + }, + + /** + * Get who knows a specific album among a list of users, ranked by playcount. + * @async + * @param {string} artist - The artist name. + * @param {string} album - The album name. + * @param {Array} userIds - Array of user IDs. + * @returns {Promise>} Users who know the album, sorted by playcount descending. + */ + async getWhoKnowsAlbum(artist, album, userIds) { + if (!this.enabled) return []; + if (!Array.isArray(userIds) || !userIds.length) return []; + + const concurrency = 5; + const results = []; + + for (let i = 0; i < userIds.length; i += concurrency) { + const batch = userIds.slice(i, i + concurrency); + + const batchResults = await Promise.allSettled( + batch.map(async (uid) => { + const user = await this.getUser(uid); + if (!user) return null; + + try { + const info = await this.getAlbumInfo(artist, album, uid); + const playcount = Number(info?.userplaycount ?? 0); + return { + userId: uid, + username: user.username, + playcount, + }; + } catch (e) { + logger.warn("[LastFm] Error:", e?.message); + return { + userId: uid, + username: user.username, + playcount: 0, + }; + } + }) + ); + + for (const r of batchResults) { + if (r.status === "fulfilled" && r.value && r.value.playcount > 0) { + results.push(r.value); + } + } + } + + results.sort((a, b) => b.playcount - a.playcount); + return results; + }, + + /** + * Compare two users' top artists and compute a match percentage. + * @async + * @param {string} userId1 - First user ID. + * @param {string} userId2 - Second user ID. + * @returns {Promise} Comparison result with user1, user2, commonArtists, and matchPercentage, or null. + */ + async compareUsers(userId1, userId2) { + if (!this.enabled) return null; + + try { + const user1Data = await this.getUser(userId1); + const user2Data = await this.getUser(userId2); + if (!user1Data || !user2Data) return null; + + const [artists1, artists2] = await Promise.all([ + this.getTopArtists(userId1, "overall", 50), + this.getTopArtists(userId2, "overall", 50), + ]); + + const names1 = new Set(artists1.map(a => a.name.toLowerCase())); + const names2 = new Set(artists2.map(a => a.name.toLowerCase())); + + const commonNames = [...names1].filter(n => names2.has(n)); + const commonArtists = artists1 + .filter(a => names2.has(a.name.toLowerCase())) + .map(a => ({ + name: a.name, + url: a.url, + playcount: a.playcount, + })); + + const totalUnique = new Set([...names1, ...names2]).size; + const matchPercentage = totalUnique > 0 + ? Math.round((commonNames.length / totalUnique) * 100) + : 0; + + return { + user1: { + username: user1Data.username, + totalArtists: names1.size, + }, + user2: { + username: user2Data.username, + totalArtists: names2.size, + }, + commonArtists, + matchPercentage, + }; + } catch (e) { + logger.warn("[LastFm] Error:", e?.message); + return null; + } + }, + + /** + * Get total scrobble count across all linked users (cached for 10 minutes). + * @async + * @param {number} [concurrency=3] - Number of concurrent user syncs. + * @returns {Promise} Total scrobble count. + */ + async getTotalScrobbles(concurrency = 3) { + if (!this.enabled) return 0; + + if (this._totalScrobblesCache !== null && Date.now() < this._totalScrobblesCacheExpiry) { + return this._totalScrobblesCache; + } + + if (this._totalScrobblesInflight) return this._totalScrobblesInflight; + + this._totalScrobblesInflight = this._refreshTotalScrobbles(concurrency); + try { + return await this._totalScrobblesInflight; + } finally { + this._totalScrobblesInflight = null; + } + }, + + /** @private @async Sync all users' scrobble counts from Last.fm and cache the total. @param {number} concurrency - Concurrent sync batch size. @returns {Promise} Fresh total scrobble count. */ + async _refreshTotalScrobbles(concurrency) { + try { + const pool = await this._getPool(); + + const f = this._botIdFilter(); + const [rows] = await pool.execute( + `SELECT user_id FROM lastfm_users WHERE 1=1${f.where}`, + [...f.params] + ); + + if (!rows.length) { + this._totalScrobblesCache = 0; + this._totalScrobblesCacheExpiry = Date.now() + 10 * 60 * 1000; + return 0; + } + + const userIds = rows.map(r => r.user_id); + + 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))); + } + + const [sumRows] = await pool.execute( + `SELECT COALESCE(SUM(scrobble_count), 0) AS total FROM lastfm_users WHERE 1=1${f.where}`, + [...f.params] + ); + + const total = Number(sumRows[0]?.total ?? 0); + this._totalScrobblesCache = total; + this._totalScrobblesCacheExpiry = Date.now() + 10 * 60 * 1000; + + logger.settings(`[LastFm] Total synced scrobbles across ${userIds.length} users: ${total}`); + return total; + } catch (err) { + logger.warn(`[LastFm] _refreshTotalScrobbles failed: ${err.message}`); + return this._totalScrobblesCache ?? 0; + } + }, + + /** + * Get the number of linked Last.fm users from the stats table. + * @async + * @returns {Promise} Linked user count. + */ + async getLinkedUsersCount() { + if (!this.enabled) return 0; + try { + const pool = await this._getPool(); + const f = this._botIdFilter(); + const [rows] = await pool.execute( + `SELECT linked_users FROM lastfm_stats WHERE id = 1${f.where}`, + [...f.params] + ); + return Number(rows[0]?.linked_users ?? 0); + } catch (e) { + logger.warn("[LastFm] Error:", e?.message); + return 0; + } + }, + + /** + * Get the scrobble leaderboard with pagination. + * @async + * @param {number} [page=0] - Zero-based page index. + * @param {number} [perPage=10] - Number of entries per page. + * @returns {Promise<{entries: Array<{userId: string, username: string, scrobbleCount: number}>, totalUsers: number, page: number, perPage: number, totalPages: number}>} Leaderboard data. + */ + async getLeaderboard(page = 0, perPage = 10) { + if (!this.enabled) return { entries: [], totalUsers: 0, page: 0, perPage: 10, totalPages: 0 }; + + const pool = await this._getPool(); + const f = this._botIdFilter(); + + const [countRows] = await pool.execute( + `SELECT COUNT(*) AS total FROM lastfm_users WHERE scrobble_count > 0${f.where}`, + [...f.params] + ); + const totalUsers = Number(countRows[0]?.total ?? 0); + const totalPages = Math.max(1, Math.ceil(totalUsers / perPage)); + + page = Math.max(0, Math.min(page, totalPages - 1)); + + const offset = page * perPage; + const [rows] = await pool.execute( + `SELECT user_id, username, scrobble_count FROM lastfm_users WHERE scrobble_count > 0${f.where} ORDER BY scrobble_count DESC LIMIT ? OFFSET ?`, + [...f.params, String(perPage), String(offset)] + ); + + const entries = rows.map(r => ({ + userId: r.user_id, + username: r.username || r.user_id, + scrobbleCount: Number(r.scrobble_count), + })); + + return { entries, totalUsers, page, perPage, totalPages }; + }, + + /** + * Compute affinity (common artists) between multiple users. + * @async + * @param {Array} userIds - Array of user IDs (minimum 2). + * @param {number} [limit=10] - Maximum number of affinity pairs to return. + * @returns {Promise}>>} Affinity pairs sorted by match count descending. + */ + async getAffinity(userIds, limit = 10) { + if (!this.enabled) return []; + if (!Array.isArray(userIds) || userIds.length < 2) return []; + + const userArtistsMap = new Map(); + const concurrency = 5; + + for (let i = 0; i < userIds.length; i += concurrency) { + const batch = userIds.slice(i, i + concurrency); + const results = await Promise.allSettled( + batch.map(async (uid) => { + const user = await this.getUser(uid); + if (!user) return null; + try { + const artists = await this.getTopArtists(uid, "overall", 50); + return { uid, username: user.username, artists }; + } catch (e) { + logger.warn("[LastFm] Error:", e?.message); + return null; + } + }) + ); + for (const r of results) { + if (r.status === "fulfilled" && r.value) { + userArtistsMap.set(r.value.uid, r.value); + } + } + } + + const entries = [...userArtistsMap.values()]; + const affinityResults = []; + + for (let i = 0; i < entries.length; i++) { + for (let j = i + 1; j < entries.length; j++) { + const a = entries[i]; + const b = entries[j]; + const namesA = new Set(a.artists.map(ar => ar.name.toLowerCase())); + const namesB = new Set(b.artists.map(ar => ar.name.toLowerCase())); + const common = [...namesA].filter(n => namesB.has(n)); + if (common.length > 0) { + const commonArtists = a.artists + .filter(ar => namesB.has(ar.name.toLowerCase())) + .map(ar => ({ name: ar.name, url: ar.url, playcount: ar.playcount })); + affinityResults.push({ + users: [a.username, b.username], + userIds: [a.uid, b.uid], + matchCount: common.length, + commonArtists, + }); + } + } + } + + affinityResults.sort((a, b) => b.matchCount - a.matchCount); + return affinityResults.slice(0, limit); + }, + + /** + * Get a user's "crowns" — artists where they have the highest playcount among the given users. + * @async + * @param {string} userId - The user ID to check crowns for. + * @param {Array} userIds - Array of all user IDs to compare against. + * @returns {Promise>} Crown entries sorted by user playcount descending. + */ + async getCrowns(userId, userIds) { + if (!this.enabled) return []; + const user = await this.getUser(userId); + if (!user) return []; + try { + const topArtists = await this.getTopArtists(userId, "overall", 50); + const crowns = []; + const concurrency = 3; + + for (let i = 0; i < topArtists.length; i += concurrency) { + const batch = topArtists.slice(i, i + concurrency); + const results = await Promise.allSettled( + batch.map(async (artist) => { + const listeners = await this.getWhoKnows(artist.name, userIds); + if (listeners.length > 0 && listeners[0].userId === String(userId)) { + return { + artist: artist.name, + artistUrl: artist.url, + userPlaycount: artist.playcount, + nextBest: listeners.length > 1 ? listeners[1] : null, + image: artist.image ?? "", + }; + } + return null; + }) + ); + for (const r of results) { + if (r.status === "fulfilled" && r.value) crowns.push(r.value); + } + } + + crowns.sort((a, b) => b.userPlaycount - a.userPlaycount); + return crowns; + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + } +}; + +export default ServerStatsMixin; +export { ServerStatsMixin }; diff --git a/src/services/lastfm/TrackQueriesMixin.mjs b/src/services/lastfm/TrackQueriesMixin.mjs new file mode 100644 index 0000000..4e565d7 --- /dev/null +++ b/src/services/lastfm/TrackQueriesMixin.mjs @@ -0,0 +1,795 @@ +/** + * @module src/services/lastfm/TrackQueriesMixin + * @description Read-only track / artist / album / tag / geo / chart Last.fm API queries (plus track search and love/unlove) for LastFmManager. + * + * These methods are applied onto the LastFmManager class prototype via + * {@link applyMixins} — `this` is a LastFmManager instance. + */ + +import { logger } from "../../core/Logger.mjs"; +import { apiCall, normalizeTrackText } from "./constants.mjs"; + +/** + * @type {object} + * @description Track-queries mixin — applied to LastFmManager. + */ +const TrackQueriesMixin = { + /** @async Get track info from Last.fm. @param {string} artist @param {string} track @param {string} [userId] @returns {Promise} Track info object or null. */ + async getTrackInfo(artist, track, userId = null) { + if (!this.enabled) return null; + + const params = { + method: "track.getinfo", + api_key: this.apiKey, + artist, + track, + }; + + if (userId) { + const user = await this.getUser(userId); + if (user) params.username = user.username; + } + + try { + const data = await apiCall(params, this.apiSecret); + return data.track; + } catch (e) { + logger.warn("[LastFm] Error:", e?.message); + return null; + } + }, + + /** @async Love a track on Last.fm. @param {string} userId @param {string} artist @param {string} track @throws {Error} If user not linked. */ + async loveTrack(userId, artist, track) { + if (!this.enabled) return; + const user = await this.getUser(userId); + if (!user) throw new Error("NOT_LINKED"); + + await apiCall( + { + method: "track.love", + api_key: this.apiKey, + sk: user.sessionKey, + artist, + track, + }, + this.apiSecret, + true + ); + }, + + /** @async Unlove a track on Last.fm. @param {string} userId @param {string} artist @param {string} track @throws {Error} If user not linked. */ + async unloveTrack(userId, artist, track) { + if (!this.enabled) return; + const user = await this.getUser(userId); + if (!user) throw new Error("NOT_LINKED"); + + await apiCall( + { + method: "track.unlove", + api_key: this.apiKey, + sk: user.sessionKey, + artist, + track, + }, + this.apiSecret, + true + ); + }, + + /** @async Search for tracks on Last.fm and score results by relevance. @param {string} query @param {number} [limit=10] @returns {Promise|null>} */ + async searchTrack(query, limit = 10) { + if (!this.enabled) return null; + + const data = await apiCall( + { + method: "track.search", + api_key: this.apiKey, + track: query, + limit, + }, + this.apiSecret + ); + + const matches = data?.results?.trackmatches?.track; + const tracks = Array.isArray(matches) + ? matches + : matches + ? [matches] + : []; + + if (!tracks.length) return null; + + const normalizedQuery = normalizeTrackText(query); + const queryTokens = normalizedQuery.split(" ").filter(Boolean); + + const scored = tracks.map((track, index) => { + const artist = String(track.artist ?? "").trim(); + const name = String(track.name ?? "").trim(); + const artistNorm = normalizeTrackText(artist); + const nameNorm = normalizeTrackText(name); + const combined = `${artistNorm} ${nameNorm}`.trim(); + + let score = 0; + + if (combined === normalizedQuery) score += 50; + if (combined.includes(normalizedQuery) && normalizedQuery) score += 25; + if (normalizedQuery.includes(nameNorm) && nameNorm) score += 15; + if (normalizedQuery.includes(artistNorm) && artistNorm) score += 12; + + const overlap = queryTokens.filter(token => combined.includes(token)).length; + score += overlap * 4; + + const nameLower = name.toLowerCase(); + const artistLower = artist.toLowerCase(); + const urlLower = String(track.url ?? "").toLowerCase(); + const fullText = `${nameLower} ${artistLower} ${urlLower}`; + + const negativePatterns = [ + /\bofficial (?:lyric|lyrics)\s*video\b/, + /\bofficial video\b/, + /\bofficial music video\b/, + /\blyric video\b/, + /\blyrics video\b/, + /\bmusic video\b/, + /\bofficial audio\b/, + /\bvisuali[sz]er\b/, + /\bkaraoke\b/, + /\bcover\b/, + /\bremix\b/, + /\bacoustic\b/, + /\blive\b/, + /\bsped up\b/, + /\bslowed\b/, + /\breverb\b/, + /\bnightcore\b/, + /\b8d\b/, + /\bclip officiel\b/, + /\bvideo oficial\b/, + /\bperformance\b/, + ]; + + for (const re of negativePatterns) { + if (re.test(fullText)) { + score -= 30; + break; + } + } + + const labelKeywords = [ + /\bpictures\b/i, + /\banimation\b/i, + /\brecords?\b/i, + /\bstudios?\b/i, + /\bentertainment\b/i, + /\bproductions?\b/i, + /\bmusic\s+(group|corp|inc|llc)\b/i, + /\brecordings?\b/i, + /\blabel\b/i, + ]; + for (const re of labelKeywords) { + if (re.test(artist)) { + score -= 20; + break; + } + } + + if (/^["""].*["""]$/.test(name) || /["""]/.test(name)) { + score -= 15; + } + + if (urlLower.includes("/_/")) { + score += 5; + } + + return { + index, + score, + track: { + artist, + name, + url: track.url ?? "", + }, + }; + }); + + scored.sort((a, b) => b.score - a.score || a.index - b.index); + return scored[0]?.track ?? null; + }, + + /** + * Get similar tracks for a given artist and track from Last.fm. + * @async + * @param {string} artist - The artist name. + * @param {string} track - The track name. + * @param {number} [limit=5] - Maximum number of results. + * @returns {Promise>} Filtered similar tracks (match > 0.1). + */ + async getSimilarTracks(artist, track, limit = 5) { + if (!this.enabled) return []; + + try { + const data = await apiCall( + { + method: "track.getsimilar", + api_key: this.apiKey, + artist, + track, + limit, + }, + this.apiSecret + ); + + return (data.similartracks?.track ?? []).map(t => ({ + artist: t.artist?.name ?? "Unknown", + name: t.name, + url: t.url ?? "", + match: parseFloat(t.match ?? 0), + })).filter(t => t.match > 0.1); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + }, + + /** + * Get detailed artist info from Last.fm. + * @async + * @param {string} artist - The artist name. + * @param {string|null} [userId] - Optional user ID to include user playcount. + * @returns {Promise} Artist info object with name, url, image, tags, bio, stats, similar, and userplaycount, or null. + */ + async getArtistInfo(artist, userId = null) { + if (!this.enabled) return null; + + const params = { + method: "artist.getinfo", + api_key: this.apiKey, + artist, + }; + + if (userId) { + const user = await this.getUser(userId); + if (user) params.username = user.username; + } + + try { + const data = await apiCall(params, this.apiSecret); + const a = data.artist; + if (!a) return null; + + return { + name: a.name ?? "", + url: a.url ?? "", + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + tags: (a.tags?.tag ?? []).map(t => t.name ?? t), + bio: a.bio?.summary ?? a.bio?.content ?? "", + stats: { + listeners: Number(a.stats?.listeners ?? 0), + playcount: Number(a.stats?.playcount ?? 0), + }, + similar: (a.similar?.artist ?? []).map(s => ({ + name: s.name ?? "", + url: s.url ?? "", + image: s.image?.[2]?.["#text"] ?? s.image?.[1]?.["#text"] ?? "", + })), + userplaycount: a.stats?.userplaycount ? Number(a.stats.userplaycount) : null, + }; + } catch (e) { + logger.warn("[LastFm] Error:", e?.message); + return null; + } + }, + + /** + * Get detailed album info from Last.fm. + * @async + * @param {string} artist - The artist name. + * @param {string} album - The album name. + * @param {string|null} [userId] - Optional user ID to include user playcount. + * @returns {Promise} Album info object with name, artist, url, image, tags, tracks, and userplaycount, or null. + */ + async getAlbumInfo(artist, album, userId = null) { + if (!this.enabled) return null; + + const params = { + method: "album.getinfo", + api_key: this.apiKey, + artist, + album, + }; + + if (userId) { + const user = await this.getUser(userId); + if (user) params.username = user.username; + } + + try { + const data = await apiCall(params, this.apiSecret); + const a = data.album; + if (!a) return null; + + return { + name: a.name ?? "", + artist: a.artist ?? "", + url: a.url ?? "", + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + tags: (a.tags?.tag ?? []).map(t => t.name ?? t), + tracks: (a.tracks?.track ?? []).map(t => ({ + name: t.name ?? "", + url: t.url ?? "", + duration: Number(t.duration ?? 0), + playcount: Number(t.playcount ?? 0), + })), + userplaycount: a.userplaycount ? Number(a.userplaycount) : null, + }; + } catch (e) { + logger.warn("[LastFm] Error:", e?.message); + return null; + } + }, + + /** + * Get top tracks for an artist from Last.fm. + * @async + * @param {string} artist - The artist name. + * @param {number} [limit=10] - Maximum number of results. + * @returns {Promise>} Top tracks. + */ + async getArtistTopTracks(artist, limit = 10) { + if (!this.enabled) return []; + + try { + const data = await apiCall( + { + method: "artist.gettoptracks", + api_key: this.apiKey, + artist, + limit, + }, + this.apiSecret + ); + + return (data.toptracks?.track ?? []).map(t => ({ + artist: t.artist?.name ?? artist, + name: t.name ?? "", + url: t.url ?? "", + playcount: Number(t.playcount ?? 0), + image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "", + })); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + }, + + /** + * Get top albums for an artist from Last.fm. + * @async + * @param {string} artist - The artist name. + * @param {number} [limit=10] - Maximum number of results. + * @returns {Promise>} Top albums. + */ + async getArtistTopAlbums(artist, limit = 10) { + if (!this.enabled) return []; + + try { + const data = await apiCall( + { + method: "artist.gettopalbums", + api_key: this.apiKey, + artist, + limit, + }, + this.apiSecret + ); + + return (data.topalbums?.album ?? []).map(a => ({ + name: a.name ?? "", + artist: a.artist?.name ?? artist, + url: a.url ?? "", + playcount: Number(a.playcount ?? 0), + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + })); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + }, + + /** + * Get similar artists for a given artist from Last.fm. + * @async + * @param {string} artist - The artist name. + * @param {number} [limit=10] - Maximum number of results. + * @returns {Promise>} Similar artists. + */ + async getSimilarArtists(artist, limit = 10) { + if (!this.enabled) return []; + + try { + const data = await apiCall( + { + method: "artist.getsimilar", + api_key: this.apiKey, + artist, + limit, + }, + this.apiSecret + ); + + return (data.similarartists?.artist ?? []).map(a => ({ + name: a.name ?? "", + url: a.url ?? "", + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + match: parseFloat(a.match ?? 0), + })); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + }, + + /** + * Get information about a specific tag from Last.fm. + * @async + * @param {string} tag - The tag name. + * @returns {Promise} Tag info with name, url, reach, count, and summary, or null. + */ + async getTagInfo(tag) { + if (!this.enabled) return null; + + try { + const data = await apiCall( + { + method: "tag.getinfo", + api_key: this.apiKey, + tag, + }, + this.apiSecret + ); + + const t = data.tag; + if (!t) return null; + + return { + name: t.name ?? "", + url: t.url ?? "", + reach: Number(t.reach ?? 0), + count: Number(t.taggings?.total ?? t.total ?? 0), + summary: t.wiki?.summary ?? "", + }; + } catch (e) { + logger.warn("[LastFm] Error:", e?.message); + return null; + } + }, + + /** + * Get top tracks for a tag from Last.fm. + * @async + * @param {string} tag - The tag name. + * @param {number} [limit=10] - Maximum number of results. + * @returns {Promise>} Tag's top tracks. + */ + async getTagTopTracks(tag, limit = 10) { + if (!this.enabled) return []; + + try { + const data = await apiCall( + { + method: "tag.gettoptracks", + api_key: this.apiKey, + tag, + limit, + }, + this.apiSecret + ); + + return (data.tracks?.track ?? []).map(t => ({ + artist: t.artist?.name ?? "Unknown", + name: t.name ?? "", + url: t.url ?? "", + playcount: Number(t.playcount ?? 0), + image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "", + })); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + }, + + /** + * Get top artists for a tag from Last.fm. + * @async + * @param {string} tag - The tag name. + * @param {number} [limit=10] - Maximum number of results. + * @returns {Promise>} Tag's top artists. + */ + async getTagTopArtists(tag, limit = 10) { + if (!this.enabled) return []; + + try { + const data = await apiCall( + { + method: "tag.gettopartists", + api_key: this.apiKey, + tag, + limit, + }, + this.apiSecret + ); + + return (data.topartists?.artist ?? []).map(a => ({ + name: a.name ?? "", + url: a.url ?? "", + playcount: Number(a.playcount ?? 0), + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + })); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + }, + + /** + * Search for artists on Last.fm. + * @async + * @param {string} query - The search query. + * @param {number} [limit=10] - Maximum number of results. + * @returns {Promise>} Matching artists. + */ + async searchArtist(query, limit = 10) { + if (!this.enabled) return []; + + try { + const data = await apiCall( + { + method: "artist.search", + api_key: this.apiKey, + artist: query, + limit, + }, + this.apiSecret + ); + + const matches = data?.results?.artistmatches?.artist; + const artists = Array.isArray(matches) + ? matches + : matches + ? [matches] + : []; + + return artists.map(a => ({ + name: a.name ?? "", + url: a.url ?? "", + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + listeners: Number(a.listeners ?? 0), + })); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + }, + + /** + * Search for albums on Last.fm. + * @async + * @param {string} query - The search query. + * @param {number} [limit=10] - Maximum number of results. + * @returns {Promise>} Matching albums. + */ + async searchAlbum(query, limit = 10) { + if (!this.enabled) return []; + + try { + const data = await apiCall( + { + method: "album.search", + api_key: this.apiKey, + album: query, + limit, + }, + this.apiSecret + ); + + const matches = data?.results?.albummatches?.album; + const albums = Array.isArray(matches) + ? matches + : matches + ? [matches] + : []; + + return albums.map(a => ({ + name: a.name ?? "", + artist: a.artist ?? "", + url: a.url ?? "", + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + })); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + }, + + /** + * Get top tags for an artist from Last.fm. + * @async + * @param {string} artist - The artist name. + * @param {number} [limit=10] - Maximum number of results. + * @returns {Promise>} Artist's top tags. + */ + async getArtistTopTags(artist, limit = 10) { + if (!this.enabled) return []; + try { + const data = await apiCall({ + method: "artist.gettoptags", + api_key: this.apiKey, + artist, + limit, + }, this.apiSecret); + return (data.toptags?.tag ?? []).map(t => ({ + name: t.name ?? "", + url: t.url ?? "", + count: Number(t.count ?? 0), + })); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + }, + + /** + * Get top tags for an album from Last.fm. + * @async + * @param {string} artist - The artist name. + * @param {string} album - The album name. + * @param {number} [limit=10] - Maximum number of results. + * @returns {Promise>} Album's top tags. + */ + async getAlbumTopTags(artist, album, limit = 10) { + if (!this.enabled) return []; + try { + const data = await apiCall({ + method: "album.gettoptags", + api_key: this.apiKey, + artist, + album, + limit, + }, this.apiSecret); + return (data.toptags?.tag ?? []).map(t => ({ + name: t.name ?? "", + url: t.url ?? "", + count: Number(t.count ?? 0), + })); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + }, + + /** + * Get top tags for a track from Last.fm. + * @async + * @param {string} artist - The artist name. + * @param {string} track - The track name. + * @param {number} [limit=10] - Maximum number of results. + * @returns {Promise>} Track's top tags. + */ + async getTrackTopTags(artist, track, limit = 10) { + if (!this.enabled) return []; + try { + const data = await apiCall({ + method: "track.gettoptags", + api_key: this.apiKey, + artist, + track, + limit, + }, this.apiSecret); + return (data.toptags?.tag ?? []).map(t => ({ + name: t.name ?? "", + url: t.url ?? "", + count: Number(t.count ?? 0), + })); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + }, + + /** + * Get top albums for a tag from Last.fm. + * @async + * @param {string} tag - The tag name. + * @param {number} [limit=10] - Maximum number of results. + * @returns {Promise>} Tag's top albums. + */ + async getTagTopAlbums(tag, limit = 10) { + if (!this.enabled) return []; + try { + const data = await apiCall({ + method: "tag.gettopalbums", + api_key: this.apiKey, + tag, + limit, + }, this.apiSecret); + return (data.albums?.album ?? []).map(a => ({ + name: a.name ?? "", + artist: a.artist?.name ?? "Unknown", + url: a.url ?? "", + playcount: Number(a.playcount ?? 0), + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + })); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + }, + + /** + * Get top artists for a country from Last.fm. + * @async + * @param {string} country - The country name. + * @param {number} [limit=10] - Maximum number of results. + * @returns {Promise>} Country's top artists. + */ + async getGeoTopArtists(country, limit = 10) { + if (!this.enabled) return []; + try { + const data = await apiCall({ + method: "geo.gettopartists", + api_key: this.apiKey, + country, + limit, + }, this.apiSecret); + return (data.topartists?.artist ?? []).map(a => ({ + name: a.name ?? "", + url: a.url ?? "", + listeners: Number(a.listeners ?? 0), + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + })); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + }, + + /** + * Get top tracks for a country from Last.fm. + * @async + * @param {string} country - The country name. + * @param {number} [limit=10] - Maximum number of results. + * @returns {Promise>} Country's top tracks. + */ + async getGeoTopTracks(country, limit = 10) { + if (!this.enabled) return []; + try { + const data = await apiCall({ + method: "geo.gettoptracks", + api_key: this.apiKey, + country, + limit, + }, this.apiSecret); + return (data.tracks?.track ?? []).map(t => ({ + name: t.name ?? "", + artist: t.artist?.name ?? "Unknown", + url: t.url ?? "", + listeners: Number(t.listeners ?? 0), + image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "", + })); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + }, + + /** + * Get the global top tracks chart from Last.fm. + * @async + * @param {number} [limit=10] - Maximum number of results. + * @returns {Promise>} Global top tracks. + */ + async getChartTopTracks(limit = 10) { + if (!this.enabled) return []; + try { + const data = await apiCall({ + method: "chart.gettoptracks", + api_key: this.apiKey, + limit, + }, this.apiSecret); + return (data.tracks?.track ?? []).map(t => ({ + name: t.name ?? "", + artist: t.artist?.name ?? "Unknown", + url: t.url ?? "", + listeners: Number(t.listeners ?? 0), + playcount: Number(t.playcount ?? 0), + image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "", + })); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + }, + + /** + * Get the global top artists chart from Last.fm. + * @async + * @param {number} [limit=10] - Maximum number of results. + * @returns {Promise>} Global top artists. + */ + async getChartTopArtists(limit = 10) { + if (!this.enabled) return []; + try { + const data = await apiCall({ + method: "chart.gettopartists", + api_key: this.apiKey, + limit, + }, this.apiSecret); + return (data.artists?.artist ?? []).map(a => ({ + name: a.name ?? "", + url: a.url ?? "", + listeners: Number(a.listeners ?? 0), + playcount: Number(a.playcount ?? 0), + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + })); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + } +}; + +export default TrackQueriesMixin; +export { TrackQueriesMixin }; diff --git a/src/services/lastfm/UserQueriesMixin.mjs b/src/services/lastfm/UserQueriesMixin.mjs new file mode 100644 index 0000000..53fefe4 --- /dev/null +++ b/src/services/lastfm/UserQueriesMixin.mjs @@ -0,0 +1,593 @@ +/** + * @module src/services/lastfm/UserQueriesMixin + * @description Per-user Last.fm queries: loved / top / recent tracks, profile info, playlists (scraped), top albums & artists, playback category resolution and weekly charts. + * + * These methods are applied onto the LastFmManager class prototype via + * {@link applyMixins} — `this` is a LastFmManager instance. + */ + +import { logger } from "../../core/Logger.mjs"; +import { apiCall } from "./constants.mjs"; + +/** + * @type {object} + * @description User-queries mixin — applied to LastFmManager. + */ +const UserQueriesMixin = { + /** @async Get a user's loved tracks. @param {string} userId @param {number} [limit=20] @returns {Promise>} @throws {Error} If user not linked. */ + async getLovedTracks(userId, limit = 20) { + const user = await this.getUser(userId); + if (!user) throw new Error("NOT_LINKED"); + + const data = await apiCall( + { + method: "user.getlovedtracks", + api_key: this.apiKey, + user: user.username, + limit, + }, + this.apiSecret + ); + + return (data.lovedtracks?.track ?? []).map(t => ({ + artist: t.artist?.name ?? t.artist?.["#text"] ?? "Unknown", + name: t.name, + url: t.url, + image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "", + })); + }, + + /** @async Get a user's top tracks. @param {string} userId @param {string} [period="overall"] @param {number} [limit=20] @returns {Promise>} @throws {Error} If user not linked. */ + async getTopTracks(userId, period = "overall", limit = 20) { + const user = await this.getUser(userId); + if (!user) throw new Error("NOT_LINKED"); + + const data = await apiCall( + { + method: "user.gettoptracks", + api_key: this.apiKey, + user: user.username, + period, + limit, + }, + this.apiSecret + ); + + return (data.toptracks?.track ?? []).map(t => ({ + artist: t.artist?.name ?? "Unknown", + name: t.name, + url: t.url, + playcount: t.playcount ?? 0, + image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "", + })); + }, + + /** @async Get a user's recent tracks. @param {string} userId @param {number} [limit=20] @returns {Promise>} @throws {Error} If user not linked. */ + async getRecentTracks(userId, limit = 20) { + const user = await this.getUser(userId); + if (!user) throw new Error("NOT_LINKED"); + + const data = await apiCall( + { + method: "user.getrecenttracks", + api_key: this.apiKey, + user: user.username, + limit, + }, + this.apiSecret + ); + + return (data.recenttracks?.track ?? []).map(t => ({ + artist: t.artist?.["#text"] ?? t.artist?.name ?? "Unknown", + name: t.name, + url: t.url, + now: t["@attr"]?.nowplaying === "true", + image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "", + })); + }, + + /** + * Get a user's top tags from Last.fm. + * @async + * @param {string} userId - The user ID. + * @param {number} [limit=20] - Maximum number of results. + * @returns {Promise>} Top tags. + */ + async getUserTopTags(userId, limit = 20) { + if (!this.enabled) return []; + + const user = await this.getUser(userId); + if (!user) return []; + + try { + const data = await apiCall( + { + method: "user.gettoptags", + api_key: this.apiKey, + user: user.username, + limit, + }, + this.apiSecret + ); + + return (data.toptags?.tag ?? []).map(t => ({ + name: t.name ?? "", + url: t.url ?? "", + count: Number(t.count ?? 0), + })); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + }, + + /** + * Get the list of weekly chart periods for a user. + * @async + * @param {string} userId - The user ID. + * @returns {Promise>} Weekly chart periods with Unix timestamps. + */ + async getUserWeeklyChartList(userId) { + if (!this.enabled) return []; + + const user = await this.getUser(userId); + if (!user) return []; + + try { + const data = await apiCall( + { + method: "user.getweeklychartlist", + api_key: this.apiKey, + user: user.username, + }, + this.apiSecret + ); + + return (data.weeklychartlist?.chart ?? []).map(c => ({ + from: Number(c.from ?? 0), + to: Number(c.to ?? 0), + })); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + }, + + /** + * Get a user's Last.fm profile info. + * @async + * @param {string} userId - The user ID. + * @returns {Promise} The Last.fm user object. + * @throws {Error} If user is not linked. + */ + async getUserInfo(userId) { + const user = await this.getUser(userId); + if (!user) throw new Error("NOT_LINKED"); + + const data = await apiCall( + { + method: "user.getinfo", + api_key: this.apiKey, + user: user.username, + }, + this.apiSecret + ); + + return data.user; + }, + + /** + * Get a user's Last.fm playlists by scraping their profile page. + * @async + * @param {string} userId - The user ID. + * @returns {Promise>} User's playlists. + * @throws {Error} If user is not linked or fetch fails. + */ + async getPlaylists(userId) { + const user = await this.getUser(userId); + if (!user) throw new Error("NOT_LINKED"); + + const profileUrl = `https://www.last.fm/user/${encodeURIComponent(user.username)}/playlists`; + const res = await fetch(profileUrl, { + headers: { "User-Agent": "RemixBot/1.0 (Last.fm Integration)" }, + }); + + if (!res.ok) { + throw new Error(`Failed to fetch profile page (HTTP ${res.status})`); + } + + const html = await res.text(); + const playlists = []; + + const playlistRegex = /href="\/user\/[^/]+\/playlists\/(\d+)"[^>]*>([^<]+)<\/a>/gi; + let match; + while ((match = playlistRegex.exec(html)) !== null) { + const id = match[1]; + const title = match[2].trim(); + if (title && id) { + playlists.push({ + id, + title, + url: `https://www.last.fm/user/${user.username}/playlists/${id}`, + }); + } + } + + const countRegex = /(\d+)\s+track/gi; + const counts = []; + let cMatch; + while ((cMatch = countRegex.exec(html)) !== null) { + counts.push(+cMatch[1]); + } + playlists.forEach((pl, i) => { + pl.trackCount = counts[i] ?? 0; + }); + + return playlists; + }, + + /** + * Get tracks from a user's Last.fm playlist by scraping the playlist page. + * @async + * @param {string} userId - The user ID. + * @param {string|number} playlistId - Playlist number (1-based index) or URL. + * @param {number} [limit=50] - Maximum number of tracks. + * @returns {Promise>} Playlist tracks. + * @throws {Error} If user is not linked or playlist not found. + */ + async getPlaylistTracks(userId, playlistId, limit = 50) { + const user = await this.getUser(userId); + if (!user) throw new Error("NOT_LINKED"); + + let playlistUrl; + + if (/^\d+$/.test(String(playlistId))) { + const playlists = await this.getPlaylists(userId); + const idx = +playlistId - 1; + if (idx < 0 || idx >= playlists.length) { + throw new Error(`Playlist #${playlistId} not found. You have ${playlists.length} playlist(s). Use the lastfm playlists command to see them.`); + } + playlistUrl = playlists[idx].url; + } else if (String(playlistId).startsWith("http")) { + playlistUrl = String(playlistId); + } else { + playlistUrl = `https://www.last.fm/user/${user.username}/playlists/${playlistId}`; + } + + const res = await fetch(playlistUrl, { + headers: { "User-Agent": "RemixBot/1.0 (Last.fm Integration)" }, + }); + + if (!res.ok) { + throw new Error(`Failed to fetch playlist page (HTTP ${res.status})`); + } + + const html = await res.text(); + const tracks = []; + + 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(); + const parts = urlPath.split("/"); + let artist = "Unknown"; + if (parts.length >= 1) { + artist = parts[0].replace(/\+/g, " "); + } + + if (name && name !== "Unknown") { + tracks.push({ + artist, + name, + url: `https://www.last.fm/music/${urlPath}`, + image: "", + }); + } + } + + if (!tracks.length) { + const broadRegex = /href="\/music\/([^"]+)"[^>]*>([^<]{2,80})<\/a>/gi; + const seen = new Set(); + let bMatch; + while ((bMatch = broadRegex.exec(html)) !== null && tracks.length < limit) { + const urlPath = decodeURIComponent(bMatch[1]); + const name = bMatch[2].trim(); + const parts = urlPath.split("/"); + if (parts.length < 2) continue; + if (seen.has(urlPath)) continue; + seen.add(urlPath); + + const artist = parts[0].replace(/\+/g, " "); + const trackName = parts.length >= 3 && parts[1] === "_" + ? parts[2].replace(/\+/g, " ") + : parts[1].replace(/\+/g, " "); + + if (trackName && artist) { + tracks.push({ + artist, + name: trackName, + url: `https://www.last.fm/music/${urlPath}`, + image: "", + }); + } + } + } + + return tracks; + }, + + /** + * Get a user's top albums from Last.fm. + * @async + * @param {string} userId - The user ID. + * @param {string} [period="overall"] - Time period (7day, 1month, 3month, 6month, 12month, overall). + * @param {number} [limit=20] - Maximum number of results. + * @returns {Promise>} Top albums. + * @throws {Error} If user is not linked. + */ + async getTopAlbums(userId, period = "overall", limit = 20) { + const user = await this.getUser(userId); + if (!user) throw new Error("NOT_LINKED"); + + const data = await apiCall( + { + method: "user.gettopalbums", + api_key: this.apiKey, + user: user.username, + period, + limit, + }, + this.apiSecret + ); + + return (data.topalbums?.album ?? []).map(a => ({ + artist: a.artist?.name ?? "Unknown", + name: a.name, + url: a.url ?? "", + playcount: a.playcount ?? 0, + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + })); + }, + + /** + * Get a user's top artists from Last.fm. + * @async + * @param {string} userId - The user ID. + * @param {string} [period="overall"] - Time period (7day, 1month, 3month, 6month, 12month, overall). + * @param {number} [limit=15] - Maximum number of results. + * @returns {Promise>} Top artists. + * @throws {Error} If user is not linked. + */ + async getTopArtists(userId, period = "overall", limit = 15) { + const user = await this.getUser(userId); + if (!user) throw new Error("NOT_LINKED"); + + const data = await apiCall( + { + method: "user.gettopartists", + api_key: this.apiKey, + user: user.username, + period, + limit, + }, + this.apiSecret + ); + + return (data.topartists?.artist ?? []).map(a => ({ + name: a.name, + url: a.url ?? "", + playcount: a.playcount ?? 0, + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + })); + }, + + /** + * Get tracks from a user's Last.fm data for playback based on category. + * @async + * @param {string} userId - The user ID. + * @param {string} category - One of: loved, top, recent, playlist, albums, artists. + * @param {object} [options={}] - Additional options. + * @param {number} [options.limit] - Maximum number of tracks. + * @param {string} [options.period] - Time period for top/albums/artists categories. + * @param {string|number} [options.playlistId] - Playlist ID (required for playlist category). + * @returns {Promise<{username: string, tracks: Array<{query: string, artist: string, name: string, url: string, image?: string}>}>} Tracks ready for playback. + * @throws {Error} If user is not linked or category is unknown. + */ + async getTracksForPlay(userId, category, options = {}) { + const user = await this.getUser(userId); + if (!user) throw new Error("NOT_LINKED"); + + const limit = options.limit ?? 20; + let tracks; + + switch (category) { + case "loved": + tracks = await this.getLovedTracks(userId, limit); + break; + case "top": + tracks = await this.getTopTracks(userId, options.period ?? "overall", limit); + break; + case "recent": + tracks = await this.getRecentTracks(userId, limit); + tracks = tracks.filter(t => !t.now); + break; + case "playlist": + if (!options.playlistId) throw new Error("Playlist ID required. Use the lastfm playlists command to see your playlists, then use the lastfm play playlist command with a number."); + tracks = await this.getPlaylistTracks(userId, options.playlistId, limit); + break; + case "albums": + const albums = await this.getTopAlbums(userId, options.period ?? "overall", limit); + tracks = albums.map(a => ({ + artist: a.artist, + name: a.name, + url: a.url, + query: `${a.artist} ${a.name} album`, + image: a.image ?? "", + })); + return { + username: user.username, + tracks, + }; + case "artists": + const topArtistsList = await this.getTopArtists(userId, options.period ?? "overall", limit); + const artistTrackResults = []; + const artistConcurrency = 3; + for (let ai = 0; ai < topArtistsList.length; ai += artistConcurrency) { + const artistBatch = topArtistsList.slice(ai, ai + artistConcurrency); + const artistResults = await Promise.allSettled( + artistBatch.map(async (ar) => { + try { + const topTracks = await this.getArtistTopTracks(ar.name, 3); + return topTracks.map(t => ({ + artist: t.artist ?? ar.name, + name: t.name, + url: t.url, + query: `${t.name} ${t.artist ?? ar.name}`, + image: t.image ?? ar.image ?? "", + })); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + }) + ); + for (const r of artistResults) { + if (r.status === "fulfilled" && r.value) { + artistTrackResults.push(...r.value); + } + } + } + return { + username: user.username, + tracks: artistTrackResults.slice(0, limit * 3), + }; + default: + throw new Error(`Unknown Last.fm category: ${category}. Use loved, top, recent, playlist, albums, or artists.`); + } + + return { + username: user.username, + tracks: tracks.map(t => ({ + query: this._buildPlayQuery(t.artist, t.name), + artist: t.artist, + name: t.name, + url: t.url ?? "", + })), + }; + }, + + /** + * Get a user's Last.fm friends list. + * @async + * @param {string} userId - The user ID. + * @param {number} [limit=20] - Maximum number of results. + * @returns {Promise>} Friends list. + */ + async getUserFriends(userId, limit = 20) { + if (!this.enabled) return []; + const user = await this.getUser(userId); + if (!user) return []; + try { + const data = await apiCall({ + method: "user.getfriends", + api_key: this.apiKey, + user: user.username, + limit, + }, this.apiSecret); + return (data.friends?.user ?? []).map(f => ({ + name: f.name ?? "", + url: f.url ?? "", + image: f.image?.[2]?.["#text"] ?? f.image?.[1]?.["#text"] ?? "", + realname: f.realname ?? "", + country: f.country ?? "", + })); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + }, + + /** + * Get a user's weekly artist chart for a specific time range. + * @async + * @param {string} userId - The user ID. + * @param {number|null} [from] - Start Unix timestamp. + * @param {number|null} [to] - End Unix timestamp. + * @returns {Promise>} Weekly artist chart. + */ + async getUserWeeklyArtistChart(userId, from = null, to = null) { + if (!this.enabled) return []; + const user = await this.getUser(userId); + if (!user) return []; + try { + const params = { + method: "user.getweeklyartistchart", + api_key: this.apiKey, + user: user.username, + }; + if (from) params.from = from; + if (to) params.to = to; + const data = await apiCall(params, this.apiSecret); + return (data.weeklyartistchart?.artist ?? []).map(a => ({ + name: a.name ?? "", + url: a.url ?? "", + playcount: Number(a.playcount ?? 0), + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + })); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + }, + + /** + * Get a user's weekly track chart for a specific time range. + * @async + * @param {string} userId - The user ID. + * @param {number|null} [from] - Start Unix timestamp. + * @param {number|null} [to] - End Unix timestamp. + * @returns {Promise>} Weekly track chart. + */ + async getUserWeeklyTrackChart(userId, from = null, to = null) { + if (!this.enabled) return []; + const user = await this.getUser(userId); + if (!user) return []; + try { + const params = { + method: "user.getweeklytrackchart", + api_key: this.apiKey, + user: user.username, + }; + if (from) params.from = from; + if (to) params.to = to; + const data = await apiCall(params, this.apiSecret); + return (data.weeklytrackchart?.track ?? []).map(t => ({ + name: t.name ?? "", + artist: t.artist?.["#text"] ?? t.artist ?? "", + url: t.url ?? "", + playcount: Number(t.playcount ?? 0), + image: t.image?.[2]?.["#text"] ?? t.image?.[1]?.["#text"] ?? "", + })); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + }, + + /** + * Get a user's weekly album chart for a specific time range. + * @async + * @param {string} userId - The user ID. + * @param {number|null} [from] - Start Unix timestamp. + * @param {number|null} [to] - End Unix timestamp. + * @returns {Promise>} Weekly album chart. + */ + async getUserWeeklyAlbumChart(userId, from = null, to = null) { + if (!this.enabled) return []; + const user = await this.getUser(userId); + if (!user) return []; + try { + const params = { + method: "user.getweeklyalbumchart", + api_key: this.apiKey, + user: user.username, + }; + if (from) params.from = from; + if (to) params.to = to; + const data = await apiCall(params, this.apiSecret); + return (data.weeklyalbumchart?.album ?? []).map(a => ({ + name: a.name ?? "", + artist: a.artist?.["#text"] ?? a.artist ?? "", + url: a.url ?? "", + playcount: Number(a.playcount ?? 0), + image: a.image?.[2]?.["#text"] ?? a.image?.[1]?.["#text"] ?? "", + })); + } catch (e) { logger.warn("[LastFm] Error:", e?.message); return []; } + } +}; + +export default UserQueriesMixin; +export { UserQueriesMixin }; diff --git a/src/services/lastfm/UserStoreMixin.mjs b/src/services/lastfm/UserStoreMixin.mjs new file mode 100644 index 0000000..c9ebb1f --- /dev/null +++ b/src/services/lastfm/UserStoreMixin.mjs @@ -0,0 +1,121 @@ +/** + * @module src/services/lastfm/UserStoreMixin + * @description User-session storage concern for LastFmManager: MySQL persistence of linked Last.fm accounts, the scrobble toggle and the auth token / URL / session exchange. + * + * These methods are applied onto the LastFmManager class prototype via + * {@link applyMixins} — `this` is a LastFmManager instance. + */ + +import { logger } from "../../core/Logger.mjs"; +import { apiCall } from "./constants.mjs"; + +/** + * @type {object} + * @description User-store mixin — applied to LastFmManager. + */ +const UserStoreMixin = { + /** @async Get a user's Last.fm session from cache or DB. @param {string} userId @returns {Promise<{sessionKey: string, username: string, scrobbleEnabled: boolean}|null>} */ + async getUser(userId) { + const cached = this._userCache.get(userId); + if (cached) return cached; + + const pool = await this._getPool(); + const f = this._botIdFilter(); + const [rows] = await pool.execute( + `SELECT session_key, username, scrobble FROM lastfm_users WHERE user_id = ?${f.where}`, + [String(userId), ...f.params] + ); + + if (!rows.length) return null; + + const row = rows[0]; + const data = { + sessionKey: row.session_key, + username: row.username, + scrobbleEnabled: !!row.scrobble, + }; + this._userCache.set(userId, data); + while (this._userCache.size > this._userCacheMax) { + const oldestKey = this._userCache.keys().next().value; + this._userCache.delete(oldestKey); + } + return data; + }, + + /** @async Save or update a user's Last.fm session. @param {string} userId @param {string} sessionKey @param {string} username @returns {Promise<{sessionKey: string, username: string, scrobbleEnabled: boolean}>} */ + async saveUser(userId, sessionKey, username) { + const pool = await this._getPool(); + const f = this._botIdFilter(); + await pool.execute( + `INSERT INTO lastfm_users (user_id, session_key, username, scrobble${f.where ? ', bot_id' : ''}) + VALUES (?, ?, ?, 1${f.where ? ', ?' : ''}) + ON DUPLICATE KEY UPDATE session_key = VALUES(session_key), username = VALUES(username)`, + [String(userId), sessionKey, username ?? "", ...f.params] + ); + const data = { sessionKey, username: username ?? "", scrobbleEnabled: true }; + this._userCache.set(userId, data); + while (this._userCache.size > this._userCacheMax) { + const oldestKey = this._userCache.keys().next().value; + this._userCache.delete(oldestKey); + } + + 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 (e) { + logger.warn("[LastFm] Stats update warning:", e?.message); + } + + return data; + }, + + /** @async Remove a user's Last.fm session from cache and DB. @param {string} userId */ + async removeUser(userId) { + const pool = await this._getPool(); + const f = this._botIdFilter(); + await pool.execute(`DELETE FROM lastfm_users WHERE user_id = ?${f.where}`, [String(userId), ...f.params]); + this._userCache.delete(userId); + }, + + /** @async Toggle scrobbling for a user. @param {string} userId @param {boolean} enabled */ + async setScrobble(userId, enabled) { + const pool = await this._getPool(); + const f = this._botIdFilter(); + await pool.execute( + `UPDATE lastfm_users SET scrobble = ? WHERE user_id = ?${f.where}`, + [enabled ? 1 : 0, String(userId), ...f.params] + ); + const cached = this._userCache.get(userId); + if (cached) cached.scrobbleEnabled = enabled; + }, + + /** @async Request a Last.fm auth token. @returns {Promise} The auth token. @throws {Error} If Last.fm is not enabled. */ + async getAuthToken() { + this._assertEnabled(); + const data = await apiCall( + { method: "auth.gettoken", api_key: this.apiKey }, + this.apiSecret + ); + return data.token; + }, + + /** Build the Last.fm auth URL for user authorization. @param {string} token @returns {string} */ + getAuthUrl(token) { + return `https://www.last.fm/api/auth/?api_key=${this.apiKey}&token=${token}`; + }, + + /** @async Exchange an auth token for a session. @param {string} token @returns {Promise} The session object with key and name. @throws {Error} If Last.fm is not enabled. */ + async getSession(token) { + this._assertEnabled(); + const data = await apiCall( + { method: "auth.getsession", api_key: this.apiKey, token }, + this.apiSecret + ); + return data.session; + } +}; + +export default UserStoreMixin; +export { UserStoreMixin }; diff --git a/src/services/lastfm/constants.mjs b/src/services/lastfm/constants.mjs new file mode 100644 index 0000000..5516492 --- /dev/null +++ b/src/services/lastfm/constants.mjs @@ -0,0 +1,55 @@ +/** + * @module src/services/lastfm/constants + * @description Constants and helpers shared by the Last.fm base class and all + * mixin modules: the API endpoint, shared text normalisation, request signing + * and the signed Last.fm API call wrapper. Kept in a dependency-free module so + * the mixins never import the class file (no circular imports). + */ + +import crypto from "node:crypto"; +import { Utils } from "../../utils/Utils.mjs"; + +const BASE_URL = "https://ws.audioscrobbler.com/2.0/"; + +/** @private @param {string} value @returns {string} */ +function normalizeTrackText(value) { + return Utils.normalizeText(value); +} + +/** @private Build an API signature per Last.fm auth spec. @param {object} params @param {string} apiSecret @returns {string} MD5 hex digest. */ +function buildSignature(params, apiSecret) { + const sorted = Object.keys(params).sort(); + const str = sorted.map(k => k + params[k]).join(""); + return crypto.createHash("md5").update(str + apiSecret).digest("hex"); +} + +/** @private Make an authenticated Last.fm API call. @async @param {object} params @param {string} apiSecret @param {boolean} [post=false] @returns {Promise} @throws {Error} On HTTP or Last.fm API error. */ +async function apiCall(params, apiSecret, post = false) { + const allParams = { ...params }; + allParams.api_sig = buildSignature(allParams, apiSecret); + allParams.format = "json"; + + const url = post ? BASE_URL : `${BASE_URL}?${new URLSearchParams(allParams)}`; + + const opts = post + ? { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams(allParams).toString(), + } + : {}; + + const res = await fetch(url, opts); + if (!res.ok) { + const text = await res.text().catch(() => ""); + throw new Error(`Last.fm HTTP ${res.status}: ${text.slice(0, 200)}`); + } + + const data = await res.json(); + if (data.error) { + throw new Error(`Last.fm ${data.error}: ${data.message}`); + } + return data; +} + +export { BASE_URL, normalizeTrackText, buildSignature, apiCall }; diff --git a/src/services/lastfm/index.mjs b/src/services/lastfm/index.mjs new file mode 100644 index 0000000..304ff03 --- /dev/null +++ b/src/services/lastfm/index.mjs @@ -0,0 +1,10 @@ +/** + * @module src/services/lastfm + * @description Public surface of the Last.fm service. + * + * Import map from the old layout: + * - `src/LastFmManager.mjs` → LastFmManager.mjs (class) + urlUtils.mjs (URL helpers) + */ + +export { LastFmManager } from "./LastFmManager.mjs"; +export { parseLastFmUrl, isLastFmUrl } from "./urlUtils.mjs"; diff --git a/src/services/lastfm/urlUtils.mjs b/src/services/lastfm/urlUtils.mjs new file mode 100644 index 0000000..522003d --- /dev/null +++ b/src/services/lastfm/urlUtils.mjs @@ -0,0 +1,56 @@ +/** + * @module src/services/lastfm/urlUtils + * @description Standalone Last.fm URL helpers: parsing music URLs into + * artist/track/album components and Last.fm URL validation. + */ + +import { logger } from "../../core/Logger.mjs"; + +/** + * Parse a Last.fm music URL into its components. + * @param {string} url - The Last.fm URL to parse. + * @returns {{artist: string, track: string|null, album: string|null, url: string}|null} Parsed components, or null if not a valid Last.fm music URL. + */ +export function parseLastFmUrl(url) { + try { + const u = new URL(url); + if (!/^(?:www\.)?last\.fm$/i.test(u.hostname)) return null; + + const match = u.pathname.match(/^\/music\/([^/]+)(?:\/([^/]+))?(?:\/([^/]+))?/); + if (!match) return null; + + const artist = decodeURIComponent(match[1].replace(/\+/g, " ")); + const segment2 = match[2] ? decodeURIComponent(match[2].replace(/\+/g, " ")) : null; + const segment3 = match[3] ? decodeURIComponent(match[3].replace(/\+/g, " ")) : null; + + let track = null; + let album = null; + + if (segment3) { + album = segment2 === "_" ? null : segment2; + track = segment3; + } else if (segment2 && segment2 !== "_") { + track = segment2; + } + + return { artist, track, album, url }; + } catch (e) { + logger.warn("[LastFm] parseLastFmUrl error:", e?.message); + return null; + } +} + +/** + * Check whether a string is a valid Last.fm music URL. + * @param {string} str - String to check. + * @returns {boolean} True if the string is a Last.fm URL with a /music/ path. + */ +export function isLastFmUrl(str) { + if (!str || typeof str !== "string") return false; + try { + const u = new URL(str); + return /^(?:www\.)?last\.fm$/i.test(u.hostname) && /^\/music\//i.test(u.pathname); + } catch (e) { + return false; + } +} diff --git a/src/ui/Embeds.mjs b/src/ui/Embeds.mjs new file mode 100644 index 0000000..5330365 --- /dev/null +++ b/src/ui/Embeds.mjs @@ -0,0 +1,50 @@ +/** + * @module src/ui/Embeds + * @description Global embed color management plus message-shape helpers used + * across the UI layer. + */ + +/** + * Parse a color value (hex string, 0x-prefixed string, or number) into an integer. + * @param {string|number} value + * @param {number} [fallback=0xe9196c] + * @returns {number} + */ +export function parseColor(value, fallback = 0xe9196c) { + if (!value) return fallback; + if (typeof value === "number") return value; + const cleaned = String(value).replace(/^#/, "").replace(/^0x/i, ""); + const n = parseInt(cleaned, 16); + return isNaN(n) ? fallback : n; +} + +/** @private @type {number} */ +let _globalColor = 0xe9196c; + +/** + * Set the global embed color (accepts hex strings or numbers). + * @param {string|number} value + */ +export function setGlobalColor(value) { _globalColor = parseColor(value); } + +/** + * @returns {number} The current global embed color. + */ +export function getGlobalColor() { return _globalColor; } + +/** + * Extract the guild ID from various message wrapper shapes. + * @param {object} message + * @returns {string|null} + */ +export function getMessageGuildId(message) { + return message?.channel?.guildId ?? + message?.channel?.guild?.id ?? + message?.message?.guildId ?? + message?.message?.guild?.id ?? + message?.channel?.server_id ?? + message?.channel?.serverId ?? + message?.message?.server_id ?? + message?.message?.serverId ?? + null; +} diff --git a/src/ui/HelpCommand.mjs b/src/ui/HelpCommand.mjs new file mode 100644 index 0000000..719a288 --- /dev/null +++ b/src/ui/HelpCommand.mjs @@ -0,0 +1,254 @@ +/** + * @module src/ui/HelpCommand + * @description The rich tabbed help command (Home / Music / Utilities / + * Support) rendered through RichPaginator, plus interception of plain-text + * help aliases so both styles coexist. + */ + +import { RichPaginator } from "./Paginators.mjs"; + +/** @type {number} Maximum commands listed per page in the help paginator. */ +const HELP_CMDS_PER_PAGE = 10; +/** @type {number} Help paginator session timeout in milliseconds. */ +const HELP_SESSION_MS = 30 * 1000; + +/** @type {object[]} Tab definitions for the rich help. */ +const HELP_TABS = [ + { + emoji: "🏠", + title: "Home", + header: "Home Page", + static: true, + }, + { + emoji: "🎵", + title: "Music", + header: "Music Commands", + categories: ["music"], + }, + { + emoji: "🔧", + title: "Utilities", + header: "Utility Commands", + categories: ["util", "default"], + }, + { + emoji: "ℹ️", + title: "Support", + header: "Support Info", + static: true, + }, +]; + +/** + * @private + * @param {string} prefix + * @returns {string} + */ +function _helpHomeContent(prefix) { + return ( + "**Welcome to the Remix help page.**\n\n" + + "Remix is an open-source music bot. It supports a variety of " + + "streaming services and has many features.\n\n" + + "We hope you enjoy using Remix!\n\n" + + "To get started, just click on the reactions below to find out " + + "more about the commands. In the case that reactions don't work " + + "for you, there's also the possibility to look through them by " + + `using \`${prefix}help \` :)\n\n` + + `**Tip:** Click the tab emojis to switch sections.` + ); +} + +/** + * @private + * @returns {string} + */ +function _helpSupportContent() { + return ( + "If you need help with anything or encounter any issues, hop over to " + + "our support server **[Remix HQ](https://fluxer.gg/remix)**!\n" + + "Alternatively, you can write a dm to any of the following people:\n\n" + + "- **Fantic** (Community Manager)\n" + + "- **Shadow** (Lead Developer)\n" + + "- **NoLogicAlan** (Lead Developer)" + ); +} + +/** + * @private Build paginated content for a help category tab. + * @param {object} tab + * @param {Array} allCmds + * @param {string} prefix + * @returns {string[]} + */ +function _helpBuildCategoryPages(tab, allCmds, prefix) { + const cmds = allCmds + .filter(cmd => { + if (cmd.requirements?.some(r => r.ownerOnly)) return false; + return tab.categories?.includes(cmd.category ?? "default"); + }) + .sort((a, b) => a.name.localeCompare(b.name)); + + if (cmds.length === 0) return ["_No commands available._"]; + + const pages = []; + for (let i = 0; i < cmds.length; i += HELP_CMDS_PER_PAGE) { + const slice = cmds.slice(i, i + HELP_CMDS_PER_PAGE); + let page = ""; + slice.forEach((cmd, j) => { + const d = (cmd.description || "No description.").split("\n")[0]; + page += `${i + j + 1}. **${cmd.name}**: ${d}\n`; + }); + page += `\nTo learn more about a command, run \`${prefix}help \`!`; + if (cmds.length > HELP_CMDS_PER_PAGE) + page += `\n\n**Tip:** Use ⬅️ ➡️ to scroll between pages.`; + pages.push(page); + } + return pages; +} + +/** + * @class HelpCommand + * @description Rich paginated help command with tabbed navigation. + */ +export class HelpCommand { + /** + * @param {import('../commands/CommandHandler.mjs').CommandHandler} commandHandler + * @param {import('./MessageHandler.mjs').MessageHandler} messageHandler + * @param {Function} getSettingsFn + */ + constructor(commandHandler, messageHandler, getSettingsFn) { + this._commands = commandHandler; + this._messages = messageHandler; + this._getSettings = getSettingsFn; + } + + /** + * Register the help command, intercept invalid command replies, and + * intercept help aliases so the rich help takes priority. + */ + register() { + if (this._registered) return; + this._registered = true; + + const HELP_ALIASES = ["help", "h", "commands"]; + + this._commands.helpCommand = "\x00help"; + const _fmt = this._commands.format.bind(this._commands); + this._commands.format = (text, guildId) => + _fmt(text, guildId).replace(/\x00help/g, "help"); + + const _reply = this._commands.replyHandler.bind(this._commands); + this._commands.replyHandler = (message, msg) => { + if (typeof message === "string" && message.toLowerCase().includes("unknown command")) { + const content = msg?.content ?? msg?.message?.content ?? ""; + const guildId = msg?.channel?.channel?.guildId ?? msg?.message?.guildId; + const prefix = this._commands.getPrefix(guildId); + const botId = this._commands.client.user?.id; + const ping = `<@${botId}>`; + const pingBang = `<@!${botId}>`; + let body = null; + if (content.startsWith(prefix)) body = content.slice(prefix.length).trim(); + else if (content.startsWith(pingBang)) body = content.slice(pingBang.length).trim(); + 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; + } + } + return _reply(message, msg); + }; + + const evict = () => { + for (const alias of HELP_ALIASES) { + const i = this._commands.commandNames.indexOf(alias); + if (i !== -1) this._commands.commandNames.splice(i, 1); + } + const ci = this._commands.commands.findIndex(c => + c.aliases.some(a => HELP_ALIASES.includes(a.toLowerCase())) + ); + if (ci !== -1) this._commands.commands.splice(ci, 1); + }; + evict(); + const _add = this._commands.addCommand.bind(this._commands); + this._commands.addCommand = (builder) => { + const r = _add(builder); + if (builder.aliases.some(a => HELP_ALIASES.includes(a.toLowerCase()))) evict(); + return r; + }; + + this._messages.onMessage((msg) => { + if (!msg?.content) return; + const content = msg.content.trim(); + const guildId = msg.channel?.channel?.guildId ?? msg.message?.guildId; + const prefix = this._commands.getPrefix(guildId); + const botId = this._commands.client.user?.id; + const ping = `<@${botId}>`; + const pingBang = `<@!${botId}>`; + let body = null; + if (content.startsWith(prefix)) body = content.slice(prefix.length).trim(); + else if (content.startsWith(pingBang)) body = content.slice(pingBang.length).trim(); + else if (content.startsWith(ping)) body = content.slice(ping.length).trim(); + if (body === null) return; + + const args = body.split(/\s+/).map(s => s.trim()).filter(Boolean); + const cmdName = (args[0] ?? "").toLowerCase(); + if (!HELP_ALIASES.includes(cmdName)) return; + + this._handle(msg, args.slice(1), prefix); + }); + } + + /** + * @private Handle a help invocation: show command detail or paginated overview. + * @param {import('./Wrappers.mjs').Message} msg + * @param {string[]} args + * @param {string} prefix + */ + _handle(msg, args, prefix) { + const allCmds = this._commands.commands; + const query = (args[0] ?? "").trim(); + + if (query && isNaN(Number(query))) { + let currCmd = null; + for (const word of [query, ...args.slice(1)]) { + const pool = currCmd ? currCmd.subcommands : allCmds; + const found = pool.find(c => + c.aliases.some(a => a.toLowerCase() === word.toLowerCase()) + ); + if (!found) { + const guildId = msg.channel?.channel?.guildId ?? msg.message?.guildId; + msg.reply(this._commands.t(guildId, "cmdHandler.help.unknownCommand", { command: word, prefix })); + return; + } + currCmd = found; + } + if (currCmd) { + msg.reply(this._commands.helpHandler.getCommandHelp(currCmd, msg)); + } + return; + } + + const startTab = query + ? Math.max(0, Math.min(HELP_TABS.length - 1, parseInt(query) - 1)) + : 0; + + const paginator = new RichPaginator(msg, this._messages) + .setTimeout(HELP_SESSION_MS) + .setStartTab(startTab); + + for (const tab of HELP_TABS) { + if (tab.static) { + const content = tab.title === "Home" + ? _helpHomeContent(prefix) + : _helpSupportContent(); + paginator.addTab({ emoji: tab.emoji, title: tab.title, header: tab.header, content }); + } else { + const pages = _helpBuildCategoryPages(tab, allCmds, prefix); + paginator.addTab({ emoji: tab.emoji, title: tab.title, header: tab.header, pages }); + } + } + + paginator.send(); + } +} diff --git a/src/ui/MessageHandler.mjs b/src/ui/MessageHandler.mjs new file mode 100644 index 0000000..0a83a80 --- /dev/null +++ b/src/ui/MessageHandler.mjs @@ -0,0 +1,583 @@ +/** + * @module src/ui/MessageHandler + * @description Central message/reaction plumbing: message-create events, + * reaction observers, permission checks, and the reply/send/edit embed API + * used by every command. + */ + +import { Client, Events, EmbedBuilder, PermissionFlags } from "@fluxerjs/core"; +import { logger } from "../core/Logger.mjs"; +import { Utils } from "../utils/Utils.mjs"; +import { Message, Channel } from "./Wrappers.mjs"; +import { getGlobalColor } from "./Embeds.mjs"; +import { + REQUIRED_BOT_PERMISSIONS, + CRITICAL_PERMISSIONS, + OPTIONAL_PERMISSIONS, +} from "./Permissions.mjs"; + +/** + * @class MessageHandler + * @description Handles message creation, reaction observation, permission + * checking, and the shared reply/send/embed API. + */ +export class MessageHandler { + /** @type {Client} */ + client; + /** @type {Map} Message ID → reaction observer data. */ + observedReactions; + /** @type {Map} Channel ID → user message observer callbacks. */ + observedChannels; + /** @type {object|null} Locale manager instance. */ + locale; + + /** + * @param {Client} client - The Fluxer client. + */ + constructor(client) { + this.client = client; + + this.observedReactions = new Map(); + this.observedChannels = new Map(); + + this.setupEvents(); + + this.client.on(Events.MessageCreate, (m) => { + if (!this.observedChannels.has(m.channelId)) return; + const data = this.observedChannels.get(m.channelId); + const d = data.filter(e => e.id === m.author.id); + if (d.length === 0) return; + d.forEach(e => e.cb(new Message(m, this))); + }); + } + + /** @param {object} locale */ + setLocale(locale) { this.locale = locale; } + + /** + * Translate a locale key. + * @param {string} guildId + * @param {string} key + * @param {object} [replacements={}] + * @returns {string} + */ + t(guildId, key, replacements = {}) { + if (!this.locale) return key; + return this.locale.translate(guildId, key, replacements); + } + + /** + * @private Register reaction add/remove event listeners. + */ + setupEvents() { + const reactionUpdate = (payload) => { + const { userId, messageId, emoji } = payload; + const emojiId = emoji?.name ?? emoji?.id ?? emoji; + const event = { user_id: userId, emoji_id: emojiId }; + + if (!this.observedReactions.has(messageId)) return; + if (event.user_id === this.client.user?.id) return; + const observer = this.observedReactions.get(messageId); + if (!observer.reactions.includes(event.emoji_id)) return; + if (observer.user && observer.user !== event.user_id) return; + + const wrappedMsg = observer.msg ? new Message(observer.msg, this) : null; + observer.cb(event, wrappedMsg); + }; + this.client.on(Events.MessageReactionAdd, (payload) => reactionUpdate(payload)); + this.client.on(Events.MessageReactionRemove, (payload) => reactionUpdate(payload)); + } + + /** + * Return the permission keys the bot is missing in a channel. + * @param {string[]} permissions + * @param {object} channel + * @returns {string[]} + */ + checkPermissions(permissions, channel) { + 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 []; + } + const perms = channel.permissionsFor?.(me) ?? null; + if (!perms) { + logger.warn("[MessageHandler] Cannot check permissions — channel.permissionsFor() unavailable"); + return []; + } + return permissions.filter(p => !perms.has(PermissionFlags[p] ?? p)); + } + + /** + * Check all REQUIRED_BOT_PERMISSIONS and split into critical vs optional. + * @param {object} channel + * @returns {{missing: string[], criticalMissing: string[], optionalMissing: string[]}} + */ + checkAllBotPermissions(channel) { + const allKeys = [...REQUIRED_BOT_PERMISSIONS.keys()]; + const missing = this.checkPermissions(allKeys, channel); + return { + missing, + criticalMissing: missing.filter(p => CRITICAL_PERMISSIONS.includes(p)), + optionalMissing: missing.filter(p => OPTIONAL_PERMISSIONS.includes(p)), + }; + } + + /** + * Build an EmbedBuilder showing missing permissions. + * @param {string[]} missingKeys + * @param {string} guildId + * @returns {EmbedBuilder} + */ + buildPermissionEmbed(missingKeys, guildId) { + const criticalItems = []; + const optionalItems = []; + + for (const key of missingKeys) { + const info = REQUIRED_BOT_PERMISSIONS.get(key); + const isCritical = CRITICAL_PERMISSIONS.includes(key); + const line = info + ? `**${info.name}** — ${info.desc}` + : `**${key}**`; + if (isCritical) { + criticalItems.push("❌ " + line); + } else { + optionalItems.push("⚠️ " + line); + } + } + + const embed = new EmbedBuilder().setColor(0xFF4444); + + if (criticalItems.length > 0) { + embed.setTitle(this.t(guildId, "responses.messages.missingCriticalPermsTitle")); + embed.setDescription( + this.t(guildId, "responses.messages.missingCriticalPermsDesc") + "\n\n" + + criticalItems.join("\n") + ); + } else if (optionalItems.length > 0) { + embed.setTitle(this.t(guildId, "responses.messages.missingOptionalPermsTitle")); + embed.setDescription( + this.t(guildId, "responses.messages.missingOptionalPermsDesc") + "\n\n" + + optionalItems.join("\n") + ); + embed.setColor(0xFFA500); + } + + embed.setFooter({ + text: this.t(guildId, "responses.messages.permFooter") + }); + + return embed; + } + + /** + * Check permissions; send a DM or embed if missing. + * @async + * @param {string[]} permissions + * @param {object} message + * @returns {Promise} + */ + async assertPermissions(permissions, message) { + const guild = message.guild ?? await message.client?.guilds?.resolve?.(message.guildId); + if (guild && !guild.members?.me) { + try { await guild.members.fetchMe(); } catch (e) { logger.warn("[MessageHandler] fetchMe failed:", e?.message); } + } + const missing = this.checkPermissions(permissions, message.channel ?? message.channel?.channel); + if (missing.length === 0) return true; + + if (missing.includes("SendMessages")) { + try { + const dm = await message.author.createDM(); + dm.send({ + embeds: [this.#embedify(this.t(message.guildId, "pagination.error.perms.messages", { channel: "<#" + message.channelId + ">" }))] + }); + } catch (e) { + logger.warn("[MessageHandler] Error sending message in DMs (" + message.author.id + "):", e.message); + } + return false; + } + + const permEmbed = this.buildPermissionEmbed(missing, message.guildId); + try { + await message.reply({ embeds: [permEmbed] }, { ping: false }); + } catch (e) { + logger.warn("[MessageHandler] Failed to send permission embed:", e.message); + try { + const names = missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k); + await message.reply(this.t(message.guildId, "responses.messages.needPermsFallback", { perms: names.join("** **") }), { ping: false }); + } catch (e) { logger.warn("[MessageHandler] Fallback permission reply failed:", e?.message); } + } + return false; + } + + /** + * Register a listener for all incoming messages. + * @param {Function} listener + */ + onMessage(listener) { + this.client.on(Events.MessageCreate, (msg) => { + listener(new Message(msg, this)); + }); + } + + /** + * Get a wrapped Message from cache by ID. + * @param {string} id + * @returns {Message|null} + */ + get(id) { + for (const channel of this.client.channels.values()) { + const msg = channel.messages?.get?.(id) ?? null; + if (msg) return new Message(msg, this); + } + return null; + } + + /** + * @async Get a message from cache or fetch it from the API. + * @param {string} id + * @param {string} channelId + * @returns {Promise} + */ + async getOrFetch(id, channelId) { + const cached = this.get(id); + if (cached) return cached; + const channel = await this.client.channels.fetch(channelId).catch(() => null); + if (!channel) return null; + const raw = await channel.messages?.fetch?.(id); + return raw ? new Message(raw, this) : null; + } + + /** + * Get a wrapped Channel by ID. + * @param {string} id + * @returns {Channel} + */ + getChannel(id) { + const c = this.client.channels.get(id); + return new Channel(c, this); + } + + /** + * @async Get a channel from cache or fetch from the API. + * @param {string} id + * @returns {Promise} + */ + async getOrFetchChannel(id) { + const c = this.getChannel(id); + if (c?.channel) return c; + const raw = await this.client.channels.fetch(id).catch(() => undefined); + return new Channel(raw, this); + } + + /** + * Start observing reactions on a message. + * @param {object} msg + * @param {string[]} reactions + * @param {Function} cb + * @param {object} [user] + * @returns {string} Observation ID. + */ + observeReactions(msg, reactions, cb, user) { + this.observedReactions.set(msg.id, { + reactions: reactions, + user: (user) ? user.id : null, + cb, + msg, + }); + return msg.id; + } + + /** + * Stop observing reactions. + * @param {string} i - Observation ID. + * @returns {boolean} + */ + unobserveReactions(i) { + return this.observedReactions.delete(i); + } + + /** + * Observe messages from a specific user in a channel. + * @param {string} userId + * @param {object} channel + * @param {Function} callback + * @returns {string} Observation ID. + */ + observeUserMessagesChannel(userId, channel, callback) { + const current = (this.observedChannels.get(channel.id) || []); + const nonce = Utils.uid(); + current.push({ + id: userId, + nonce: nonce, + cb: callback + }); + this.observedChannels.set(channel.id, current); + return userId + ";" + channel.id + ";" + nonce; + } + + /** + * @private Stop observing a user's messages in a channel. + * @param {string} oid + */ + unobserveUserMessagesChannel(oid) { + const [userId, channelId, nonce] = oid.split(";"); + const current = (this.observedChannels.get(channelId) || []); + const idx = current.findIndex(e => e.id === userId && e.nonce === nonce); + if (idx === -1) return; + current.splice(idx, 1); + if (current.length === 0) return this.observedChannels.delete(channelId); + this.observedChannels.set(channelId, current); + } + + /** + * @private Build an EmbedBuilder from text with optional title, thumbnail, + * and author icon. + * @param {string} [text=""] + * @param {object} [options={}] + * @param {string|number} [options.color] + * @param {string} [options.title] + * @param {string} [options.thumbnail] + * @param {string} [options.icon_url] + * @returns {EmbedBuilder} + */ + #embedify(text = "", options = {}) { + const color = options.color ?? getGlobalColor(); + const builder = new EmbedBuilder() + .setDescription("" + text) + .setColor(color); + + if (options.title) builder.setTitle(options.title); + + if (options.thumbnail && Utils.isValidUrl(options.thumbnail)) { + builder.setThumbnail(options.thumbnail); + } + + if (options.icon_url) { + if (Utils.isValidUrl(options.icon_url)) { + builder.setAuthor({ name: options.title || "\u200b", iconURL: options.icon_url }); + } else { + builder.setAuthor({ name: options.title || "\u200b" }); + } + } + + return builder; + } + + /** + * @private Create a message payload object with an embed. + * @param {string} text + * @param {object} [options={}] + * @returns {{content: *, embeds: EmbedBuilder[]}} + */ + #createEmbed(text, options = {}) { + return { + content: options.content ?? undefined, + embeds: [this.#embedify(text, options)], + }; + } + + /** + * @async Reply to a message with permission checks. + * @param {object} replyingTo + * @param {string|object} message + * @param {boolean} [mention=false] + * @returns {Promise} + */ + async reply(replyingTo, message, mention = false) { + if (!(await this.assertPermissions(["SendMessages", "EmbedLinks"], replyingTo))) return null; + let opts; + if (typeof message === "string") { + opts = this.#createEmbed(message); + } else { + opts = { ...message }; + } + return new Message(await replyingTo.reply(opts, { ping: false }), this); + } + + /** + * @async Reply with an embed. + * @param {object} replyingTo + * @param {string|object} message + * @param {object} [options={}] + * @returns {Promise} + */ + async replyEmbed(replyingTo, message, options = {}) { + if (!(await this.assertPermissions(["SendMessages", "EmbedLinks"], replyingTo))) return null; + + if (typeof message === "object" && Array.isArray(message.embeds)) { + return new Message(await replyingTo.reply(message, { ping: false }), this); + } + + options = { + mention: false, + embed: {}, + ...options + }; + const content = (typeof message === "object") ? message.embedText : message; + let payload = this.#createEmbed(content, options.embed); + if (typeof message === "object") { + const { embedText, ...rest } = message; + payload = { ...payload, ...rest }; + } + return new Message(await replyingTo.reply(payload, { ping: false }), this); + } + + /** + * @async Send a message to a channel. + * @param {object} channel + * @param {string|object} message + * @returns {Promise} + */ + async sendMessage(channel, message) { + if (this.checkPermissions(["SendMessages", "EmbedLinks"], channel).length !== 0) { + logger.warn("[MessageHandler] Missing SendMessages/EmbedLinks permission in channel", channel.id); + return null; + } + let opts; + if (typeof message === "string") { + opts = this.#createEmbed(message); + } else { + opts = message; + } + return new Message(await channel.send(opts), this); + } + + /** + * @async Send an embed to a channel. + * @param {object} channel + * @param {string|object} content + * @param {object} [embedOptions={}] + * @returns {Promise} + */ + async sendEmbed(channel, content, embedOptions = {}) { + if (this.checkPermissions(["SendMessages", "EmbedLinks"], channel).length !== 0) { + return this.sendMessage(channel, typeof content === "string" ? content : content?.embedText ?? ""); + } + if (typeof content === "object" && Array.isArray(content.embeds)) { + return new Message(await channel.send(content), this); + } + const text = (typeof content === "object") ? content.embedText : content; + const payload = this.#createEmbed(text, embedOptions); + if (typeof content === "object") { + const { embedText, ...rest } = content; + Object.assign(payload, rest); + } + return new Message(await channel.send(payload), this); + } + + /** + * @async Edit an existing message embed with retry on 502/503/504. + * @param {object} message + * @param {string|object} content + * @param {object} [embedOptions={}] + * @returns {Promise} + */ + async editEmbed(message, content, embedOptions = {}) { + const RETRYABLE = new Set([502, 503, 504]); + const MAX_ATTEMPTS = 3; + const RETRY_DELAY_MS = 1500; + + let payload; + if (typeof content === "object" && Array.isArray(content.embeds)) { + payload = content; + } else { + const text = (typeof content === "object") ? content.embedText : content; + const embed = this.#embedify(text, embedOptions); + payload = { embeds: [embed] }; + if (typeof content === "object") { + const { embedText, ...rest } = content; + payload = { ...payload, ...rest }; + } + } + + for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) { + try { + return new Message(await message.edit(payload), this); + } catch (err) { + if (err.code === "UNKNOWN_MESSAGE" || err.code === 10008) { + logger.warn("[MessageHandler] editEmbed: Message no longer exists, skipping edit."); + return null; + } + + 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)); + continue; + } + + throw err; + } + } + } + + /** + * @async Create a paginated message with arrow reactions. + * @param {import('./Paginators.mjs').PageBuilder} builder + * @param {Message} msg + * @returns {Promise} + */ + async initPagination(builder, msg) { + const pages = builder.createPages(); + if (pages.length === 0) return; + + const arrows = ["⬅️", "➡️"]; + const currPage = { n: 0 }; + const send = () => builder.getPage(currPage.n); + + const m = await msg.reply(send()); + if (!m) return; + + m.message.react(arrows[0]).catch(() => {}); + m.message.react(arrows[1]).catch(() => {}); + + const unobserve = m.onReaction(arrows, (e) => { + if (e.emoji_id === arrows[0]) { + currPage.n = Math.max(0, currPage.n - 1); + } else { + currPage.n = Math.min(pages.length - 1, currPage.n + 1); + } + m.edit(send()).catch(() => {}); + }); + + const guildId = msg.message?.guildId ?? null; + setTimeout(() => { + unobserve(); + m.edit(this.t(guildId, "pagination.embed.sclosedContent", { content: send() })).catch(() => {}); + }, 5 * 60 * 1000); + } + + /** + * @async Join a voice channel using VoiceManager. + * @param {string} channelId + * @returns {Promise} + * @throws {Error} If channel not found or not a guild channel. + */ + async joinChannel(channelId) { + const { getVoiceManager } = await import("@fluxerjs/voice"); + const channel = await this.client.channels.fetch(channelId).catch(() => null); + if (!channel) throw new Error("Voice channel not found."); + // Fluxer 3.0: isGuild() is ChannelType-based and replaces the 2.2 + // 'guildId' own-property duck check; the fallback keeps custom/stub + // channel objects working. + const isGuildChannel = channel.isGuild?.() ?? ("guildId" in channel); + if (!isGuildChannel) throw new Error("Cannot join a non-guild voice channel."); + const vm = getVoiceManager(this.client); + if (!vm) throw new Error("VoiceManager not available."); + const voiceConn = await vm.join(channel); + // Self-deafen raw joins too (Player.join does this for playback + // sessions): a music bot never listens, and Fluxer's VoiceManager resets + // self_deaf on every requestVoiceStateSync (fired by conn.stop()) — the + // re-assert listener keeps the deafened state for the connection's + // lifetime. Best effort: updateVoiceState no-ops without connection_id. + const deafen = () => { + try { + vm.updateVoiceState(channel.id, { self_deaf: true, self_mute: false }); + } catch (_) { /* best effort */ } + }; + deafen(); + if (typeof voiceConn?.on === "function") voiceConn.on("requestVoiceStateSync", deafen); + return voiceConn; + } +} diff --git a/src/ui/Paginators.mjs b/src/ui/Paginators.mjs new file mode 100644 index 0000000..2390573 --- /dev/null +++ b/src/ui/Paginators.mjs @@ -0,0 +1,394 @@ +/** + * @module src/ui/Paginators + * @description Pagination primitives: PageBuilder (line splitting with a + * template form), RichPaginator (multi-tab embeds) and QueuePaginator + * (two-arrow embed paging). + */ + +import { EmbedBuilder } from "@fluxerjs/core"; +import { logger } from "../core/Logger.mjs"; +import { Message } from "./Wrappers.mjs"; +import { getGlobalColor } from "./Embeds.mjs"; + +/** + * @class PageBuilder + * @description Splits content into pages with template-based formatting + * ($maxPage / $currentPage / $content placeholders). + */ +export class PageBuilder { + /** @type {string} Template form string. */ + form = ""; + /** @type {number} Maximum lines per page. */ + maxLinesPerPage = 2; + /** @type {Array|string[]} Content lines or array items. */ + content = []; + /** @type {boolean} Whether pages have been created. */ + initiated = false; + /** @type {Array} Created page arrays. */ + pages = []; + + /** + * @param {string|Array} content - String to split by newlines or an array of items. + */ + constructor(content) { + if (!Array.isArray(content)) { + this.content = content.split("\n"); + return; + } + this.content = content; + } + + /** + * Set the template form string. + * @param {string} form + * @returns {PageBuilder} + */ + setForm(form) { + this.form = form; + this.initiated = false; + return this; + } + + /** + * Set the maximum lines per page. + * @param {number} [maxLinesPerPage=2] + * @returns {PageBuilder} + */ + setMaxLines(maxLinesPerPage = 2) { + this.maxLinesPerPage = maxLinesPerPage; + this.initiated = false; + return this; + } + + /** + * Create page arrays from content. Lazily initialized. + * @returns {Array} + */ + createPages() { + if (this.initiated) return this.pages; + + const lines = this.content; + const pages = []; + for (let i = 0; i < lines.length; i++) { + const n = Math.floor(i / this.maxLinesPerPage); + if (!pages[n]) pages[n] = []; + pages[n].push(lines[i]); + } + + this.pages = pages; + this.initiated = true; + return pages; + } + + /** + * Get a formatted page string by index (0-based). + * @param {number} n + * @returns {string|null} + */ + getPage(n) { + const pages = this.createPages(); + if (!pages[n]) return null; + return this.form + .replace(/\$maxPage/gi, pages.length) + .replace(/\$currentPage/gi, n + 1) + .replace(/\$currPage/gi, n + 1) + .replace(/\$content/gi, pages[n].join("\n")); + } + + /** + * Get raw page content by index (0-based) without template formatting. + * @param {number} n + * @returns {string|null} + */ + getContent(n) { + const pages = this.createPages(); + if (!pages[n]) return null; + return pages[n].join("\n"); + } + + /** + * Get the total number of pages. + * @returns {number} + */ + size() { + return this.pages.length; + } +} + +/** + * @class RichPaginator + * @description Multi-tab paginated embed with tab and arrow navigation via + * reactions. Closes the session after an inactivity timeout. + */ +export class RichPaginator { + /** + * @param {Message} msg + * @param {import('./MessageHandler.mjs').MessageHandler} handler + */ + constructor(msg, handler) { + this._msg = msg; + this._handler = handler; + this._tabs = []; + this._prev = "⬅️"; + this._next = "➡️"; + this._timeout = 5 * 60 * 1000; + this._color = getGlobalColor(); + this._state = { tab: 0, page: 0 }; + } + + /** @param {number} ms @returns {RichPaginator} */ + setTimeout(ms) { this._timeout = ms; return this; } + /** @param {number} color @returns {RichPaginator} */ + setColor(color) { this._color = color; return this; } + /** @param {number} idx @returns {RichPaginator} */ + setStartTab(idx) { this._state.tab = idx; return this; } + /** @param {string} prev @param {string} next @returns {RichPaginator} */ + setPrevNext(prev, next) { this._prev = prev; this._next = next; return this; } + + /** + * Add a tab to the paginator. + * @param {object} tab + * @param {string} tab.emoji + * @param {string} tab.title + * @param {string} tab.header + * @param {string} [tab.content] + * @param {string[]} [tab.pages] + * @returns {RichPaginator} + */ + addTab(tab) { + this._tabs.push({ + emoji: tab.emoji, + title: tab.title, + header: tab.header, + pages: tab.pages ?? (tab.content != null ? [tab.content] : []), + }); + return this; + } + + /** + * @private Build an embed for a given tab and sub-page. + * @param {number} tabIdx + * @param {number} pageIdx + * @returns {EmbedBuilder} + */ + _buildEmbed(tabIdx, pageIdx) { + const tab = this._tabs[tabIdx]; + const totalTabs = this._tabs.length; + const totalPages = Math.max(1, tab.pages.length); + const safePage = Math.max(0, Math.min(pageIdx, totalPages - 1)); + const content = tab.pages[safePage] ?? ""; + + const footerParts = [`Page ${tabIdx + 1}/${totalTabs}`]; + if (totalPages > 1) footerParts.push(`• Subpage ${safePage + 1}/${totalPages}`); + + return new EmbedBuilder() + .setColor(this._color) + .setAuthor({ name: tab.header }) + .setTitle(tab.title) + .setDescription(content) + .setFooter({ text: footerParts.join(" ") }); + } + + /** + * @async Send the paginated embed and start observing reactions. + * @returns {Promise} The raw sent message. + */ + async send() { + if (this._tabs.length === 0) return null; + + const tabEmojis = this._tabs.map(t => t.emoji); + const allReactions = [...tabEmojis, this._prev, this._next]; + + const nativeMsg = this._msg.message ?? this._msg; + if (!nativeMsg?.reply) return null; + + const rawMsg = await nativeMsg.reply( + { embeds: [this._buildEmbed(this._state.tab, this._state.page)] }, + { ping: false } + ).catch(() => null); + + if (!rawMsg) return null; + + const guildId = (this._msg.channel?.guildId) ?? (this._msg.guildId) ?? null; + + for (const emoji of allReactions) { + await rawMsg.react(emoji).catch(() => {}); + } + + const wrapped = new Message(rawMsg, this._handler); + const state = this._state; + const tabs = this._tabs; + const prev = this._prev; + const next = this._next; + const buildEmbed = this._buildEmbed.bind(this); + + const unobserve = wrapped.onReaction(allReactions, async (e) => { + const emoji = e.emoji_id; + + if (emoji === prev || emoji === next) { + const tab = tabs[state.tab]; + const totalPages = Math.max(1, tab.pages.length); + if (totalPages <= 1) return; + state.page = emoji === prev + ? (state.page - 1 + totalPages) % totalPages + : (state.page + 1) % totalPages; + } else { + const idx = tabEmojis.indexOf(emoji); + if (idx === -1 || idx === state.tab) return; + state.tab = idx; + state.page = 0; + } + + rawMsg.edit({ embeds: [buildEmbed(state.tab, state.page)] }).catch(() => {}); + }); + + /** @private Clear all reactions on the paginator message. */ + const clearReactions = async () => { + try { + await rawMsg.removeAllReactions(); + return; + } catch (e) { + if (String(e?.message ?? e).includes("Message wasn't found") || e?.code === 10008) return; + logger.warn("[RichPaginator] removeAllReactions failed:", e?.message ?? e); + } + for (const emoji of allReactions) { + try { + await rawMsg.removeReaction(emoji); + } catch(e) { + if (String(e?.message ?? e).includes("Message wasn't found") || e?.code === 10008) return; + logger.warn("[MessageHandler] Error:", e?.message); + } + } + }; + + /** @private Close the pagination session, update footer, and clear reactions. */ + const closeSession = async () => { + unobserve(); + const currentEmbed = buildEmbed(state.tab, state.page); + if (!currentEmbed.footer) currentEmbed.footer = { text: "" }; + currentEmbed.footer.text += " • " + this._handler.t(guildId, "pagination.embed.sclosedTitle"); + rawMsg.edit({ embeds: [currentEmbed] }).catch(() => {}); + await clearReactions(); + }; + + let timer = setTimeout(closeSession, this._timeout); + + /** @private Reset the inactivity timer. */ + const resetTimer = () => { + clearTimeout(timer); + timer = setTimeout(closeSession, this._timeout); + }; + + const origHandler = wrapped.handler.observedReactions.get(rawMsg.id); + if (origHandler) { + const origCb = origHandler.cb; + origHandler.cb = (e, m) => { resetTimer(); origCb(e, m); }; + } + + return rawMsg; + } +} + +/** + * @class QueuePaginator + * @description Simple two-arrow paginator for queue embeds with page count. + */ +export class QueuePaginator { + /** + * @param {Message} msg + * @param {import('./MessageHandler.mjs').MessageHandler} handler + * @param {Client} client + */ + constructor(msg, handler, client) { + this._msg = msg; + this._handler = handler; + this._client = client; + this._timeout = 30 * 1000; + this._prev = "⬅️"; + this._next = "➡️"; + } + + /** @param {number} ms @returns {QueuePaginator} */ + setTimeout(ms) { this._timeout = ms; return this; } + /** @param {string} prev @param {string} next @returns {QueuePaginator} */ + setPrevNext(prev, next) { this._prev = prev; this._next = next; return this; } + + /** + * @async Send the paginated embed and observe arrow reactions. + * @param {Function} buildEmbed - Function that takes a 1-based page number and returns an EmbedBuilder. + * @param {number} totalPages + * @param {number} [startPage=1] + * @returns {Promise} The raw sent message. + */ + async send(buildEmbed, totalPages, startPage = 1) { + const state = { page: Math.max(1, Math.min(startPage, totalPages)) }; + const nativeMsg = this._msg.message ?? this._msg; + if (!nativeMsg?.reply) return null; + const rawMsg = await nativeMsg.reply( + { embeds: [buildEmbed(state.page)] }, + { ping: false } + ).catch(() => null); + + if (!rawMsg) return null; + + const guildId = (this._msg.channel?.guildId) ?? (this._msg.guildId) ?? null; + + if (totalPages <= 1) return rawMsg; + + const prev = this._prev; + const next = this._next; + + await rawMsg.react(prev).catch(() => {}); + await rawMsg.react(next).catch(() => {}); + + /** @private Clear all reactions on the paginator message. */ + const clearReactions = async () => { + try { + await rawMsg.removeAllReactions(); + } catch (e) { + // Message deleted — nothing left to clean up. + if (String(e?.message ?? e).includes("Message wasn't found") || e?.code === 10008) return; + for (const emoji of [prev, next]) { + try { + await rawMsg.removeReaction(emoji); + } catch(e) { + if (String(e?.message ?? e).includes("Message wasn't found") || e?.code === 10008) return; + logger.warn("[MessageHandler] Error:", e?.message); + } + } + } + }; + + /** @private Close the pagination session, update footer, and clear reactions. */ + const closeSession = async () => { + unobserve(); + const embed = buildEmbed(state.page); + const closedLabel = this._handler.t(guildId, "pagination.embed.sclosedTitle"); + if (embed.footer && typeof embed.footer.text === "string") { + embed.footer.text += " • " + closedLabel; + } else { + embed.footer = { text: closedLabel }; + } + rawMsg.edit({ embeds: [embed] }).catch(() => {}); + await clearReactions(); + }; + + let timer = setTimeout(closeSession, this._timeout); + /** @private Reset the inactivity timer. */ + const resetTimer = () => { + clearTimeout(timer); + timer = setTimeout(closeSession, this._timeout); + }; + + const wrapped = new Message(rawMsg, this._handler); + const unobserve = wrapped.onReaction([prev, next], (e) => { + resetTimer(); + state.page = e.emoji_id === prev + ? (state.page <= 1 ? totalPages : state.page - 1) + : (state.page >= totalPages ? 1 : state.page + 1); + rawMsg.edit({ embeds: [buildEmbed(state.page)] }).catch(() => {}); + }); + + return rawMsg; + } +} diff --git a/src/ui/Permissions.mjs b/src/ui/Permissions.mjs new file mode 100644 index 0000000..ca16a03 --- /dev/null +++ b/src/ui/Permissions.mjs @@ -0,0 +1,27 @@ +/** + * @module src/ui/Permissions + * @description Bot permission requirements for full functionality, split into + * critical (bot cannot operate without) and optional (UX improvements). + */ + +/** + * Required bot permissions with human-readable names and descriptions. + * @type {Map} + */ +export const REQUIRED_BOT_PERMISSIONS = Object.freeze(new Map([ + ["ViewChannel", { name: "View Channels", desc: "See channels and read their content" }], + ["SendMessages", { name: "Send Messages", desc: "Respond to commands and send messages" }], + ["EmbedLinks", { name: "Embed Links", desc: "Send rich embed messages (bot responses, now playing, etc.)" }], + ["AddReactions", { name: "Add Reactions", desc: "Add pagination reactions (help pages, queue, etc.)" }], + ["ReadMessageHistory", { name: "Read Message History", desc: "Read previous messages for context" }], + ["ManageMessages", { name: "Manage Messages", desc: "Pin messages, clean up bot responses" }], + ["AttachFiles", { name: "Attach Files", desc: "Send files and thumbnails" }], + ["Connect", { name: "Connect (Join Voice)", desc: "Join voice channels to play music" }], + ["Speak", { name: "Speak", desc: "Stream audio in voice channels" }], +])); + +/** @type {string[]} Permission keys that are strictly required for the bot to function. */ +export const CRITICAL_PERMISSIONS = ["ViewChannel", "SendMessages", "EmbedLinks", "Connect", "Speak"]; + +/** @type {string[]} Permission keys that are optional but improve the user experience. */ +export const OPTIONAL_PERMISSIONS = ["AddReactions", "ReadMessageHistory", "ManageMessages", "AttachFiles"]; diff --git a/src/ui/Wrappers.mjs b/src/ui/Wrappers.mjs new file mode 100644 index 0000000..ae7f05e --- /dev/null +++ b/src/ui/Wrappers.mjs @@ -0,0 +1,191 @@ +/** + * @module src/ui/Wrappers + * @description Message and Channel wrappers providing reply/edit/reaction + * observation helpers on top of the raw @fluxerjs/core objects. + */ + +/** + * @class Channel + * @description Wrapper around a raw channel object providing helpers for + * sending messages and observing per-user messages. + */ +export class Channel { + /** @type {object} The raw channel object. */ + channel; + /** @type {import('./MessageHandler.mjs').MessageHandler} */ + handler; + + /** + * @param {object} channel + * @param {import('./MessageHandler.mjs').MessageHandler} handler + */ + constructor(channel, handler) { + this.channel = channel; + this.handler = handler; + } + + /** @returns {object|null} The guild this channel belongs to. */ + get server() { return this.channel?.guild ?? null; } + /** @returns {object|null} Alias for server (guild). */ + get guild() { return this.channel?.guild ?? null; } + /** @returns {boolean} Whether this channel is a voice channel. */ + get isVoice() { return this.channel?.isVoiceBased?.() ?? false; } + /** @returns {string} The channel ID. */ + get id() { return this.channel?.id; } + /** @returns {string|null} The guild ID. */ + get guildId() { return this.channel?.guildId ?? null; } + /** @returns {string|null} Alias for guildId. */ + get serverId() { return this.guildId; } + + /** + * Observe messages from a specific user in this channel. + * @param {Function} callback + * @param {object} user + * @returns {Function} Unobserve function. + */ + onMessageUser(callback, user) { + const resolvedUserId = user?.id + ?? user?._id + ?? user?.user?.id + ?? null; + const resolvedChannel = this.channel ?? null; + if (!resolvedUserId || !resolvedChannel?.id) { + return () => {}; + } + const oid = this.handler.observeUserMessagesChannel(resolvedUserId, resolvedChannel, callback); + return () => { + this.handler.unobserveUserMessagesChannel(oid); + }; + } + + /** + * Send a message to this channel. + * @param {string|object} content + * @returns {Promise} + */ + sendMessage(content) { + return this.handler.sendMessage(this.channel, content); + } + + /** + * Alias for sendMessage. + * @param {string|object} content + * @returns {Promise} + */ + send(content) { + return this.handler.sendMessage(this.channel, content); + } + + /** + * Send an embed to this channel. + * @param {string|object} content + * @param {object} [embedOptions={}] + * @returns {Promise} + */ + sendEmbed(content, embedOptions = {}) { + return this.handler.sendEmbed(this.channel, content, embedOptions); + } + + /** + * Join this voice channel. + * @async + * @returns {Promise} + * @throws {Error} If not a voice channel. + */ + join() { + if (!this.isVoice) throw new Error("Cannot join a text channel. Attempting to 'join' into channel `" + this.channel?.id + "`"); + return this.handler.joinChannel(this.channel.id); + } +} + +/** + * @class Message + * @description Wrapper around a raw message object providing helpers for + * replying, editing, and reaction observation. + */ +export class Message { + /** @type {object} */ + message; + /** @type {import('./MessageHandler.mjs').MessageHandler} */ + handler; + + /** + * @param {object} message + * @param {import('./MessageHandler.mjs').MessageHandler} handler + */ + constructor(message, handler) { + this.message = message; + this.handler = handler; + } + + /** @returns {string} The raw message content. */ + get content() { return this.message.content; } + /** @returns {string} The message ID. */ + get id() { return this.message.id; } + /** @returns {object} The author object. */ + get author() { return this.message.author; } + /** @returns {string} The author's user ID. */ + get authorId() { return this.message.author?.id; } + /** @returns {object|null} The guild member, if available. */ + get member() { return this.message.member ?? null; } + /** @returns {Channel} The wrapped channel this message was sent in. */ + get channel() { return this.handler.getChannel(this.message.channelId); } + + /** + * Observe reactions on this message. + * @param {string[]} reactions + * @param {Function} callback + * @param {object} [user=null] - Restrict observation to one user. + * @returns {Function} Unobserve function. + */ + onReaction(reactions, callback, user = null) { + const oid = this.handler.observeReactions(this.message, reactions, callback, user); + return () => { + this.handler.unobserveReactions(oid); + }; + } + + /** + * Reply to this message. + * @param {string|object} content + * @param {boolean} [mention=false] + * @returns {Promise} + */ + reply(content, mention = false) { + return this.handler.reply(this.message, content, mention); + } + + /** + * Reply to this message with an embed. + * @param {string|object} content + * @param {boolean} [mention=false] + * @param {object} [embedOptions={}] + * @returns {Promise} + */ + replyEmbed(content, mention = false, embedOptions = {}) { + return this.handler.replyEmbed(this.message, content, { + mention, + embed: embedOptions + }); + } + + /** + * Edit this message's embed. + * @param {string|object} content + * @param {object} [embedOptions={}] + * @returns {Promise} + */ + editEmbed(content, embedOptions = {}) { + return this.handler.editEmbed(this.message, content, embedOptions); + } + + /** + * Alias for editEmbed. + * @param {string|object} content + * @param {object} [embedOptions={}] + * @returns {Promise} + */ + edit(content, embedOptions = {}) { + return this.handler.editEmbed(this.message, content, embedOptions); + } +} diff --git a/src/ui/index.mjs b/src/ui/index.mjs new file mode 100644 index 0000000..a3c7582 --- /dev/null +++ b/src/ui/index.mjs @@ -0,0 +1,15 @@ +/** + * @module src/ui + * @description Public surface of the message/embed UI layer. + * + * Import map from the old layout: + * - `src/MessageHandler.mjs` → this module + */ + +export { REQUIRED_BOT_PERMISSIONS, CRITICAL_PERMISSIONS, OPTIONAL_PERMISSIONS } from "./Permissions.mjs"; +export { parseColor, setGlobalColor, getGlobalColor, getMessageGuildId } from "./Embeds.mjs"; +export { Message, Channel } from "./Wrappers.mjs"; +export { MessageHandler } from "./MessageHandler.mjs"; +export { PageBuilder, RichPaginator, QueuePaginator } from "./Paginators.mjs"; +export { HelpCommand } from "./HelpCommand.mjs"; +export { cleanId } from "../utils/Utils.mjs"; diff --git a/src/utils/API.mjs b/src/utils/API.mjs new file mode 100644 index 0000000..89b0451 --- /dev/null +++ b/src/utils/API.mjs @@ -0,0 +1,100 @@ +/** @module src/utils/API */ + +/** + * FluxerList API configuration. + * @namespace FLUXERLIST + */ +export const FLUXERLIST = { + /** Base URL for the FluxerList REST API. @type {string} */ + BASE_URL: "https://fluxerlist.com/api/v1", + + /** Public FluxerList website URL. @type {string} */ + SITE_URL: "https://fluxerlist.com", + + /** API endpoint path templates. @type {{ SERVER_VOTERS: string, BOT_VOTERS: string }} */ + ENDPOINTS: { + SERVER_VOTERS: "/servers/:id/voters", + + BOT_VOTERS: "/bots/:id/voters", + }, + + /** Accepted resource type identifiers. @type {string[]} */ + RESOURCE_TYPES: ["server", "bot"], + + /** Thumbnail API base URL. @type {string} */ + THUMBNAIL: "https://fluxerlist.com/api/v1", +}; + +/** + * FluxerList authentication helpers. + * @namespace FLUXERLIST_AUTH + */ +export const FLUXERLIST_AUTH = { + /** HTTP header name for auth. @type {string} */ + HEADER: "Authorization", + + /** Required API key prefix. @type {string} */ + KEY_PREFIX: "fl_", + + /** + * Format an API key as a Bearer token, prepending the prefix if needed. + * @param {string} apiKey - Raw or prefixed API key. + * @returns {string} `Bearer fl_...` string. + */ + bearer(apiKey) { + const key = apiKey.startsWith(FLUXERLIST_AUTH.KEY_PREFIX) + ? apiKey + : FLUXERLIST_AUTH.KEY_PREFIX + apiKey; + return `Bearer ${key}`; + }, +}; + +/** + * FluxerList pagination and cache limits. + * @namespace FLUXERLIST_LIMITS + */ +export const FLUXERLIST_LIMITS = { + /** Default page number. @type {number} */ + DEFAULT_PAGE: 1, + + /** Default items-per-page. @type {number} */ + DEFAULT_LIMIT: 50, + + /** Maximum allowed items-per-page. @type {number} */ + MAX_LIMIT: 100, + + /** Cache time-to-live in milliseconds. @type {number} */ + CACHE_TTL_MS: 5 * 60 * 1000, +}; + +/** + * Build a full FluxerList API URL by substituting `:id` in the endpoint and appending query params. + * @param {string} endpoint - Endpoint template (e.g. `"/servers/:id/voters"`). + * @param {string} resourceId - Value to substitute for `:id`. + * @param {{ page?: number, limit?: number }} [queryParams={}] + * @returns {string} Fully qualified URL. + */ +export function buildFluxerListUrl(endpoint, resourceId, queryParams = {}) { + const path = endpoint.replace(":id", encodeURIComponent(resourceId)); + const params = new URLSearchParams(); + + if (queryParams.page) params.set("page", String(queryParams.page)); + if (queryParams.limit) { + const clamped = Math.min(Math.max(1, queryParams.limit), FLUXERLIST_LIMITS.MAX_LIMIT); + params.set("limit", String(clamped)); + } + + const qs = params.toString(); + return `${FLUXERLIST.BASE_URL}${path}${qs ? "?" + qs : ""}`; +} + +/** + * Build a FluxerList vote link for a server or bot. + * @param {"server"|"bot"} type - Resource type. + * @param {string} resourceId - The server/bot ID. + * @returns {string} Absolute URL to the vote page. + */ +export function buildVoteLink(type, resourceId) { + const path = type === "server" ? "servers" : "bots"; + return `${FLUXERLIST.SITE_URL}/${path}/${resourceId}`; +} diff --git a/src/utils/Helpers247.mjs b/src/utils/Helpers247.mjs new file mode 100644 index 0000000..4871c2e --- /dev/null +++ b/src/utils/Helpers247.mjs @@ -0,0 +1,39 @@ +/** @module src/utils/Helpers247 */ + +/** + * Simplified 24/7 helpers — single mode (on/off), no per-channel modes. + * get247ChannelMode is used by Player.mjs, PlayerManager.mjs, GatewayHandler.mjs, leave.mjs. + * remove247ChannelMode and set247ChannelMode are kept as no-ops for backward compat + * (original files in the zip still import them). + */ + +/** + * Check if a channel has 24/7 enabled. + * @param {object} set - ServerSettings instance + * @param {string} channelId + * @returns {"on"|"off"} + */ +export function get247ChannelMode(set, channelId) { + if (!set?.get) return "off"; + const raw = set.get("stay_247"); + if (!raw || raw === "none") return "off"; + const channels = Array.isArray(raw) + ? raw.map(id => String(id).trim()).filter(Boolean) + : [String(raw).trim()]; + return channels.includes(channelId) ? "on" : "off"; +} + +/** + * No-op: per-channel modes removed. Kept for backward compatibility. + * Original GatewayHandler.mjs and index.mjs still import this. + */ +export function remove247ChannelMode(set, channelId, currentChannels) { + // No-op: modes no longer exist, stay_247 array is managed directly. +} + +/** + * No-op: per-channel modes removed. Kept for backward compatibility. + */ +export function set247ChannelMode(set, channelId, mode) { + // No-op: modes no longer exist. +} \ No newline at end of file diff --git a/src/utils/ShardingUtils.mjs b/src/utils/ShardingUtils.mjs new file mode 100644 index 0000000..d6de39e --- /dev/null +++ b/src/utils/ShardingUtils.mjs @@ -0,0 +1,140 @@ +/** + * @module src/utils/ShardingUtils + * @description Shard-aware gateway helpers that work identically on Fluxer.js + * 2.2 (plain single process) and 3.0 (optionally sharded via + * `@fluxerjs/sharding`). + * + * When the bot boots through the root `shard.mjs` supervisor, every child + * process is forked by a {@link ShardingManager} with the + * `FLUXER_SHARD_IDS` / `FLUXER_SHARD_COUNT` / `FLUXER_SHARD_PROCESS_ID` env + * vars set, and `Bot.mjs` attaches the child-side `ShardClientUtil` as + * `client.shard` before login. These helpers read that state to: + * - route guild-scoped gateway payloads (opcode 4 voice joins/leaves) to + * the shard that owns the guild, + * - fan presence updates out to every gateway shard connected in this + * process, + * - enumerate the raw WebSocket socket of every local shard (2.2 exposed + * a `ws.shards` Map property; 3.0 exposes `getShards()`/`getShard()` + * methods and no property). + * + * In plain single-process mode (`npm start` / `node index.mjs`) every helper + * degrades to the exact pre-sharding behavior — shard 0 and a one-element + * shard list — so callers never need to know whether the bot is sharded. + */ + +/** + * True when this process was forked by an `@fluxerjs/sharding` + * ShardingManager (root `shard.mjs`). Detection requires both the manager + * env var and a live IPC channel (`process.send`); manually exporting + * FLUXER_* variables does not activate sharding. + * @returns {boolean} + */ +export function isShardedProcess() { + return process.env.FLUXER_SHARD_IDS !== undefined && + typeof process.send === "function"; +} + +/** + * Resolve the gateway shard that owns a guild. Under a ShardingManager the + * child-side `client.shard.shardIdForGuildId()` computes the assignment + * (`(guild_id >> 22) % shard_count`, matching the gateway); otherwise the + * bot runs a single gateway shard and the answer is always 0. + * @param {object} client - The Fluxer client instance. + * @param {string|number|null} guildId - The guild ID to route for. + * @returns {number} The owning shard id (0 when not sharded). + */ +export function shardIdForGuild(client, guildId) { + try { + const shardUtil = client?.shard; + if (shardUtil && typeof shardUtil.shardIdForGuildId === "function") { + const id = shardUtil.shardIdForGuildId(String(guildId ?? "")); + if (Number.isInteger(id) && id >= 0) return id; + } + } catch { + // fall through to the single-process default + } + return 0; +} + +/** + * Read the client's shard map in a 2.2- and 3.0-compatible way. + * Fluxer 3.0 exposes `getShards()` on the WebSocketManager (the 2.2 `shards` + * Map property is gone), and `client.ws` itself is a throwing getter before + * login on 3.0, so every access here is guarded. + * @param {object} client - The Fluxer client instance. + * @returns {Array>} [id, shard] entries; empty when the + * gateway is not connected yet or no shards are running in this process. + */ +export function getLocalShards(client) { + try { + const ws = client?.ws; + if (!ws) return []; + const map = typeof ws.getShards === "function" ? ws.getShards() : ws.shards; + if (map && typeof map.entries === "function") { + return [...map.entries()].filter(([id]) => Number.isInteger(id)); + } + } catch { + // Fluxer 3.0: client.ws throws before login — treat as "no shards yet". + } + return []; +} + +/** + * Ids of the gateway shards connected in this process. Defaults to `[0]` + * (single-process behavior) when no shard map is available yet. + * @param {object} client - The Fluxer client instance. + * @returns {number[]} + */ +export function localShardIds(client) { + const ids = getLocalShards(client).map(([id]) => id); + return ids.length > 0 ? ids : [0]; +} + +/** + * Raw WebSocket socket of every gateway shard connected in this process + * (used by the raw-socket listeners in GatewayHandler and LavalinkManager). + * 2.2-style code read `client.ws.shards.get(0).ws`; this generalises it to + * all local shards for sharded children. + * @param {object} client - The Fluxer client instance. + * @returns {Array} Raw socket objects (may be empty). + */ +export function localShardSockets(client) { + const out = []; + for (const [, shard] of getLocalShards(client)) { + const wsObj = shard?.ws ?? null; + if (wsObj) out.push(wsObj); + } + return out; +} + +/** + * Look up a single shard handle by id, 2.2- and 3.0-compatible. + * @param {object} client - The Fluxer client instance. + * @param {number} [shardId=0] - The shard id to fetch. + * @returns {object|null} The shard handle, or null when unavailable. + */ +export function getShard(client, shardId = 0) { + try { + const ws = client?.ws; + if (!ws) return null; + if (typeof ws.getShard === "function") return ws.getShard(shardId) ?? null; + return ws.shards?.get?.(shardId) ?? null; + } catch { + return null; + } +} + +/** + * One-line sharding description for startup logs. + * @param {object} [client] - The Fluxer client instance (optional). + * @returns {string} e.g. "process 2, gateway shards 4,5 of 8" or + * "single process (unsharded)". + */ +export function describeSharding(client) { + if (!isShardedProcess()) return "single process (unsharded)"; + const ids = String(process.env.FLUXER_SHARD_IDS ?? "0"); + const count = Number(process.env.FLUXER_SHARD_COUNT ?? "1") || 1; + const pid = process.env.FLUXER_SHARD_PROCESS_ID ?? ids.split(",")[0] ?? "0"; + const live = localShardIds(client); + return `process ${pid}, gateway shards ${ids} of ${count} (connected: ${live.join(", ")})`; +} diff --git a/src/utils/UI.mjs b/src/utils/UI.mjs new file mode 100644 index 0000000..9192255 --- /dev/null +++ b/src/utils/UI.mjs @@ -0,0 +1,37 @@ +/** @module src/utils/UI */ + +/** Hex color string for error embeds. @type {string} */ +export const ERROR_COLOR = "#ff0000"; + +/** Numeric hex color for warning embeds. @type {number} */ +export const WARN_COLOR = 0xFFAA00; + +/** Numeric hex color for success embeds. @type {number} */ +export const SUCCESS_COLOR = 0x00CC66; + +/** Numeric hex color for danger/critical embeds. @type {number} */ +export const DANGER_COLOR = 0xFF4444; + +/** Auto-remove reaction collectors after this many ms. @type {number} */ +export const EMOJI_REMOVE_TIMEOUT = 60_000; + +/** Session idle timeout in ms. @type {number} */ +export const SESSION_TIMEOUT = 30_000; + +/** Number emoji map for selection menus (indices 1-10). @type {string[]} */ +export const NUMBER_EMOJIS = [ + "1️⃣", "2️⃣", "3️⃣", "4️⃣", "5️⃣", + "6️⃣", "7️⃣", "8️⃣", "9️⃣", "🔟", +]; + +/** Emoji used to cancel a selection. @type {string} */ +export const CANCEL_EMOJI = "❌"; + +/** Emoji for previous-page navigation. @type {string} */ +export const PREV_EMOJI = "⬅️"; + +/** Emoji for next-page navigation. @type {string} */ +export const NEXT_EMOJI = "➡️"; + +/** Maximum allowed volume value. @type {number} */ +export const MAX_VOLUME = 200; diff --git a/src/Utils.mjs b/src/utils/Utils.mjs similarity index 98% rename from src/Utils.mjs rename to src/utils/Utils.mjs index c1c369b..62a0a06 100644 --- a/src/Utils.mjs +++ b/src/utils/Utils.mjs @@ -1,7 +1,7 @@ -/** @module src/Utils @description General-purpose utility functions for formatting, validation, string manipulation, and ID cleaning. */ +/** @module src/utils/Utils @description General-purpose utility functions for formatting, validation, string manipulation, and ID cleaning. */ import { escapeMarkdown as _escapeMarkdown, truncate as _truncate } from "@fluxerjs/util"; -import { logger } from "./constants/Logger.mjs"; +import { logger } from "../core/Logger.mjs"; /** * Strip all non-digit characters from a value to extract a Snowflake/numeric ID. @@ -138,7 +138,7 @@ export class Utils { } /** - * Escape Discord markdown special characters in text. + * Escape markdown special characters in text. * @param {string} text - The text to escape. * @returns {string} Escaped text, or empty string if falsy. */ diff --git a/src/utils/mixins.mjs b/src/utils/mixins.mjs new file mode 100644 index 0000000..175feb0 --- /dev/null +++ b/src/utils/mixins.mjs @@ -0,0 +1,33 @@ +/** + * @module src/utils/mixins + * @description Minimal mixin helper used to split large classes across + * multiple files while keeping a single runtime class and public API. + */ + +/** + * Copy the methods of each mixin onto the target class prototype. + * + * Use this when a class has grown across many concerns (playback, search, + * display, …): define each concern as a plain object of methods in its own + * module and apply them onto the class. All methods share the same `this`, + * so behaviour is identical to a single-file class. + * + * Rules: + * - Methods defined directly on the base class always win (never overridden). + * - Later mixins override earlier mixins for the same method name. + * + * @param {Function} target - The base class to extend. + * @param {...object} mixins - Objects of instance methods. + * @returns {Function} The target class (for chaining). + */ +export function applyMixins(target, ...mixins) { + const baseOwned = new Set(Object.getOwnPropertyNames(target.prototype)); + for (const mixin of mixins) { + for (const [name, value] of Object.entries(mixin)) { + if (typeof value !== "function") continue; + if (baseOwned.has(name)) continue; + target.prototype[name] = value; + } + } + return target; +} diff --git a/src/voice/VoiceStateCache.mjs b/src/voice/VoiceStateCache.mjs new file mode 100644 index 0000000..a5eacbe --- /dev/null +++ b/src/voice/VoiceStateCache.mjs @@ -0,0 +1,589 @@ +/** @module src/voice/VoiceStateCache */ + +import { logger } from "../core/Logger.mjs"; +import { cleanId } from "../utils/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/voice/VoiceStateResolver.mjs b/src/voice/VoiceStateResolver.mjs new file mode 100644 index 0000000..5490269 --- /dev/null +++ b/src/voice/VoiceStateResolver.mjs @@ -0,0 +1,138 @@ +/** @module src/voice/VoiceStateResolver */ + +import { logger } from "../core/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 - 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] - 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 - 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 - 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/voice/gateway/GatewayHandler.mjs b/src/voice/gateway/GatewayHandler.mjs new file mode 100644 index 0000000..9b2321f --- /dev/null +++ b/src/voice/gateway/GatewayHandler.mjs @@ -0,0 +1,602 @@ +/** + * @module src/voice/gateway/GatewayHandler + * @description Handles all gateway events relevant to voice state + * tracking, 24/7 mode, boot recovery, presence rotation, and permission + * checks. Base class file: constructor & state, raw WS listener, presence + * rotation, event registration, READY sequencing and 24/7 boot recovery. + * Voice-state routing, guild sync and rejoin management live in sibling + * mixin modules applied onto the prototype at the bottom of this file. + */ +import { Events, GatewayOpcodes } from "@fluxerjs/core"; +import { logger, _wsErrorCooldown } from "../../core/Logger.mjs"; +import { ServerSettings } from "../../db/Settings.mjs"; +import { get247ChannelMode, remove247ChannelMode } from "../../utils/Helpers247.mjs"; +import { cleanId } from "../../utils/Utils.mjs"; +import * as ShardingUtils from "../../utils/ShardingUtils.mjs"; +import { iterateVoiceStates, hasHumansInChannel, getChannelsWithHumans } from "../VoiceStateResolver.mjs"; +import { applyMixins } from "../../utils/mixins.mjs"; +import VoiceStateRouting from "./VoiceStateRouting.mjs"; +import GuildSync from "./GuildSync.mjs"; +import RejoinManager from "./RejoinManager.mjs"; + +const RAW_GATEWAY_INTEREST = + /"(?:t|op)":\s*(?:"(?:VOICE_STATE_UPDATE|VOICE_SERVER_UPDATE|GUILD_CREATE|READY|RESUMED)"|(?:7|9|10|12)\b)/; + +/** @class GatewayHandler @description Handles all gateway events relevant to voice state tracking, 24/7 mode, boot recovery, presence rotation, and permission checks. Key responsibilities include voice state cache seeding and updates, bot move-away detection with 24/7 rejoin scheduling, boot recovery with sequential rejoin of 24/7 channels, inactivity timer management on human join/leave, and guild create/delete handling with startup grace period. */ +class GatewayHandler { + /** + * Create a new GatewayHandler. + * @param {import('../../core/Bot.mjs').Remix} remix - The bot context. + */ + constructor(remix) { + this.remix = remix; + + const timers = remix.config.timers ?? {}; + this.T = { + aloneCheckDebounce: timers.aloneCheckDebounce ?? 500, + rejoin247Delay: timers.rejoin247Delay ?? 3_000, + }; + + this.presenceContents = remix.config.presenceContents ?? []; + this.presenceInterval = remix.config.presenceInterval ?? 30_000; + + this.wsListenerAttached = false; + this.presenceTimer = null; + this.presenceIndex = 0; + + this._prevVoiceState = new Map(); + + this._deferredGuildDeletes = new Map(); + this._startupDeleteGraceMs = 15_000; + this._inStartupGrace = true; + this._deferredDeleteCount = 0; + + this._lastReadyAt = 0; + this._wsReconnectGraceMs = 30_000; + this._moveEvidenceWindowMs = 10_000; + } + + /** @private @type {Set} @description Channel IDs currently being rejoined (duplicate guard). */ + _rejoinInProgress = new Set(); + + /** @private @type {Map} @description Channel ID → retry count for exponential backoff. */ + _rejoinAttempts = new Map(); + + /** @private @type {boolean} @description Whether boot recovery is actively rejoining 24/7 channels. */ + _bootRecoveryActive = false; + + /** @type {number} @description Maximum number of rejoin retry attempts per channel. */ + static MAX_REJOIN_RETRIES = 3; + + /** + * Check whether a WebSocket reconnect happened recently (within 30s). + * Used to treat transient disconnects as non-24/7-requiring. + * @returns {boolean} + */ + isWsReconnectRecent() { + if (!this._lastReadyAt) return false; + return Date.now() - this._lastReadyAt < this._wsReconnectGraceMs; + } + + /** @private Build a composite bot key for voice state tracking. @param {string} userId @param {string} guildId @returns {string|null} */ + getObservedVoiceBotKey(userId, guildId) { + const cleanUserId = cleanId(userId ?? ""); + const cleanGuildId = cleanId(guildId ?? ""); + return cleanUserId && cleanGuildId ? `${cleanGuildId}:${cleanUserId}` : cleanUserId || null; + } + + /** @private Build a previous voice state lookup key. @param {string} userId @param {string} guildId @returns {string|null} */ + getPrevVoiceStateKey(userId, guildId) { + const cleanUserId = cleanId(userId ?? ""); + const cleanGuildId = cleanId(guildId ?? ""); + return cleanUserId && cleanGuildId ? `${cleanGuildId}:${cleanUserId}` : null; + } + + /** Find a previous voice state entry for a user. @param {string} userId @param {string|null} [guildId=null] @returns {{key: string|null, value: object|null}} */ + findPrevVoiceStateEntry(userId, guildId = null) { + const directKey = this.getPrevVoiceStateKey(userId, guildId); + if (directKey && this._prevVoiceState.has(directKey)) { + return { key: directKey, value: this._prevVoiceState.get(directKey) }; + } + + const cleanUserId = cleanId(userId ?? ""); + if (!cleanUserId) return { key: null, value: null }; + + for (const [key, value] of this._prevVoiceState) { + if (key.endsWith(`:${cleanUserId}`)) { + return { key, value }; + } + } + + return { key: null, value: null }; + } + + /** Attach a raw WebSocket listener to cache VOICE_SERVER_UPDATE events. @private */ + attachRawListener() { + const { remix } = this; + const client = remix.client; + + try { + // Fluxer 3.0 + sharding: the ws manager exposes shards via getShards() + // (2.2 used a `shards` Map property) and a sharded child owns several + // shards — track the raw socket of EVERY local shard, not just shard 0. + const wsObjs = ShardingUtils.localShardSockets(client); + + if (!remix._rawGatewayWsObjs) remix._rawGatewayWsObjs = new Set(); + const attached = remix._rawGatewayWsObjs; + + // Detach listeners from sockets that went away (reconnects). + for (const old of attached) { + if (wsObjs.includes(old)) continue; + try { + if (typeof old.removeEventListener === "function") { + old.removeEventListener("message", remix._rawGatewayMessageListener ?? remix._rawGatewayHandler); + old.removeEventListener("error", remix._rawGatewayErrorHandler); + } else if (typeof old.off === "function") { + old.off("message", remix._rawGatewayMessageListener ?? remix._rawGatewayHandler); + old.off("error", remix._rawGatewayErrorHandler); + } + } catch(e) { logger.warn("[Gateway] Failed to detach old WS listener:", e?.message); } + attached.delete(old); + } + + let attachedNew = false; + + // Create the shared raw-socket handlers once (stateless parsers + // shared by every local shard socket). + if (!remix._rawGatewayHandler) { + remix._rawGatewayHandler = (data) => { + try { + if (typeof data === "string" && !RAW_GATEWAY_INTEREST.test(data)) return; + const payload = typeof data === "string" ? JSON.parse(data) : data; + + if (payload?.op === GatewayOpcodes.GatewayError || payload?.op === 12) { + logger.warn("[Gateway] GatewayError (12) received from Fluxer:", payload.d); + } + + if (payload?.op === GatewayOpcodes.Hello || payload?.op === 10) { + logger.player(`[Gateway] HELLO received (heartbeat ${payload.d?.heartbeat_interval ?? "unknown"}ms)`); + } + if (payload?.op === GatewayOpcodes.Reconnect || payload?.op === 7) { + logger.warn("[Gateway] RECONNECT requested by gateway."); + } + if (payload?.op === GatewayOpcodes.InvalidSession || payload?.op === 9) { + logger.warn("[Gateway] INVALID_SESSION received from gateway."); + } + + if (payload?.op !== 0) return; + + if (payload.t === "READY") { + logger.player(`[Gateway] READY received (session ${payload.d?.session_id ?? "unknown"})`); + const readyGuilds = payload.d?.guilds; + if (Array.isArray(readyGuilds)) { + for (const g of readyGuilds) { + const gId = g?.id; + if (!gId || !Array.isArray(g.voice_states)) continue; + for (const state of g.voice_states) { + const userId = state.user_id; + const channelId = state.channel_id; + if (!userId || !channelId) continue; + const isBot = state.member?.user?.bot ?? false; + remix.voiceCache.updateUser({ guildId: gId, userId, channelId, isBot }); + } + } + } + } + + if (payload.t === "RESUMED") { + logger.player("[Gateway] RESUMED received from gateway."); + } + + if (payload.t === "GUILD_CREATE") { + const d = payload.d; + const gId = d?.id; + const voiceStates = d?.voice_states; + if (gId && Array.isArray(voiceStates) && voiceStates.length > 0) { + for (const state of voiceStates) { + const userId = state.user_id; + const channelId = state.channel_id; + if (!userId || !channelId) continue; + const isBot = state.member?.user?.bot ?? false; + remix.voiceCache.updateUser({ guildId: gId, userId, channelId, isBot }); + } + } + } + + if (payload.t === "VOICE_SERVER_UPDATE") { + logger.voiceState(`[Gateway] VOICE_SERVER_UPDATE guild=${payload.d?.guild_id ?? "dm"} endpoint=${payload.d?.endpoint ?? "unknown"}`); + } + + if (payload.t === "VOICE_STATE_UPDATE") { + const d = payload.d; + const userId = d?.user_id; + const channelId = d?.channel_id ?? null; + const guildId = d?.guild_id; + const isBot = d?.member?.user?.bot ?? false; + if (!userId) return; + if (channelId) { + remix.voiceCache.updateUser({ guildId, userId, channelId, isBot }); + } else { + remix.voiceCache.updateUser({ guildId, userId, channelId: null, isBot }); + } + } + } catch(e) { logger.warn("[Gateway] Raw gateway handler error:", e?.message); } + }; + + remix._rawGatewayErrorHandler = (errOrEvent) => { + if (typeof errOrEvent?.preventDefault === "function") errOrEvent.preventDefault(); + const err = errOrEvent?.error ?? errOrEvent?.message ?? errOrEvent; + const now = Date.now(); + if (now - _wsErrorCooldown.lastLogged < _wsErrorCooldown.COOLDOWN_MS) return; + _wsErrorCooldown.lastLogged = now; + logger.warn("[Gateway] Raw WS socket error (will reconnect):", err?.message ?? err); + }; + remix._rawGatewayMessageListener = (event) => remix._rawGatewayHandler(event?.data ?? event); + } + + for (const wsObj of wsObjs) { + if (attached.has(wsObj)) continue; + + if (typeof wsObj.addEventListener === "function") { + wsObj.addEventListener("message", remix._rawGatewayMessageListener); + wsObj.addEventListener("error", remix._rawGatewayErrorHandler); + } else if (typeof wsObj.on === "function") { + wsObj.on("message", remix._rawGatewayMessageListener); + wsObj.on("error", remix._rawGatewayErrorHandler); + } + + attached.add(wsObj); + attachedNew = true; + } + + // Legacy singular field kept in sync (first socket) for compatibility. + remix._rawGatewayWsObj = wsObjs[0] ?? null; + this.wsListenerAttached = attached.size > 0; + if (attachedNew) { + logger.player("[Gateway] Raw WS listener attached to new socket."); + } + } catch(e) { logger.warn("[Gateway] attachRawListener failed:", e?.message); } + } + + /** Rotate the bot's presence/status text at a configured interval. @private */ + setupPresenceRotation() { + if (this.presenceContents.length === 0) return; + + const { remix } = this; + const client = remix.client; + + const setPresence = () => { + const entry = this.presenceContents[this.presenceIndex]; + + const isObj = typeof entry === "object" && entry !== null; + + const custom_status = {}; + if (isObj) { + if (entry.text) custom_status.text = entry.text; + if (entry.emoji_name) custom_status.emoji_name = entry.emoji_name; + if (entry.emoji_id) custom_status.emoji_id = entry.emoji_id; + } else { + custom_status.text = String(entry); + } + + const presence = { + status: "online", + mobile: false, + afk: false, + custom_status, + }; + + if (isObj && entry.activity) { + presence.activities = [{ + name: entry.activity.name ?? "music", + type: entry.activity.type ?? 0, + url: entry.activity.url ?? undefined, + }]; + } + + // Fluxer 3.0: client.ws is a throwing getter when the gateway is not + // connected (2.2 exposed a plain optional). The raw opcode-3 payload + // below stays in wire format (custom_status) because it bypasses + // ClientUser.setPresence() and hits the shard directly. + // Sharded children fan the update out to every gateway shard in this + // process (presence is per shard); single process = shard 0 as before. + try { + if (client.ws?.send) { + for (const id of ShardingUtils.localShardIds(client)) { + client.ws.send(id, { op: GatewayOpcodes.PresenceUpdate, d: presence }); + } + } else { + const shard = ShardingUtils.getShard(client, 0); + if (shard) shard.send({ op: GatewayOpcodes.PresenceUpdate, d: presence }); + } + } catch (e) { + logger.warn("[Presence] Gateway not ready, skipping rotation update:", e?.message); + } + this.presenceIndex = (this.presenceIndex + 1) % this.presenceContents.length; + }; + setPresence(); + if (this.presenceTimer) clearInterval(this.presenceTimer); + this.presenceTimer = setInterval(setPresence, this.presenceInterval); + } + + /** + * Register all gateway event handlers (GuildCreate, GuildDelete, VoiceStateUpdate, VoiceStatesSync). + * Called once during bot initialisation. + */ + setupEventHandlers() { + const { remix } = this; + const client = remix.client; + + client.on(Events.GuildCreate, async (guild) => { + const guildId = guild?.id ?? guild?._id; + if (!guildId) return; + + const deferred = this._deferredGuildDeletes.get(guildId); + if (deferred) { + clearTimeout(deferred.timer); + this._deferredGuildDeletes.delete(guildId); + logger.guild( + `[GuildDelete] Cancelled deferred cleanup for server ${guildId} — ` + + `guild came back (GuildCreate received during grace period).` + ); + } + + const voiceStatesRaw = + guild.voice_states ?? + guild.voiceStates ?? + null; + + if (voiceStatesRaw) { + const newUserIds = new Set(); + for (const vs of iterateVoiceStates(guild)) { + newUserIds.add(vs.userId); + } + remix.voiceCache.purgeUsersInGuild(guildId, newUserIds); + } + if (voiceStatesRaw) { + for (const vs of iterateVoiceStates(guild)) { + remix.voiceCache.updateUser({ guildId, userId: vs.userId, channelId: vs.channelId, isBot: vs.isBot }); + } + } + + if (!remix.settingsMgr.guilds.has(guildId)) { + logger.guild(`[GuildCreate] (Re-)joined server ${guildId} — initialising settings.`); + try { + const cleanGuildId = cleanId(guildId); + if (!cleanGuildId) throw new Error("Invalid guildId: " + guildId); + const res = await remix.settingsMgr.selectGuild(cleanGuildId); + if (res?.results?.length) { + const row = res.results[0]; + const server = new ServerSettings(guildId, remix.settingsMgr); + const parsed = (typeof row.data === "string") ? JSON.parse(row.data) : row.data; + server.deserialize(parsed); + server.checkDefaults(remix.settingsMgr.defaults); + remix.settingsMgr.guilds.set(guildId, server); + logger.guild(`[GuildCreate] Restored existing settings for server ${guildId}.`); + } else { + const server = new ServerSettings(guildId, remix.settingsMgr); + server.checkDefaults(remix.settingsMgr.defaults); + remix.settingsMgr.guilds.set(guildId, server); + await remix.settingsMgr.create(guildId, server); + logger.guild(`[GuildCreate] Fresh settings initialised for server ${guildId}.`); + } + } catch (err) { + logger.warn("[GuildCreate] Settings init failed for", guildId, err.message); + } + } + + this._checkGuildPermissions(guild, guildId).catch(e => logger.warn("[GuildCreate] Permission check error for", guildId, e.message)); + + }); + + client.on(Events.GuildDelete, (guild) => { + const guildId = guild?.id ?? guild?._id; + if (!guildId) return; + + if (this._inStartupGrace) { + this._deferredDeleteCount++; + if (this._deferredDeleteCount <= 3) { + logger.guild( + `[GuildDelete] Deferring cleanup for server ${guildId} ` + + `(startup grace — will confirm after ${this._startupDeleteGraceMs / 1000}s).` + ); + } + const existing = this._deferredGuildDeletes.get(guildId); + if (existing) clearTimeout(existing.timer); + + const timer = setTimeout(() => { + this._deferredGuildDeletes.delete(guildId); + this._processGuildDelete(guildId); + }, this._startupDeleteGraceMs); + + this._deferredGuildDeletes.set(guildId, { guild, timer }); + return; + } + + logger.guild(`[GuildDelete] Received GuildDelete for server ${guildId}.`); + this._processGuildDelete(guildId); + }); + + client.on(Events.VoiceStateUpdate, async (data) => { + this._handleVoiceStateUpdate(data); + }); + + client.on(Events.VoiceStatesSync, (data) => { + this._handleVoiceStatesSync(data); + }); + } + + /** + * Called when the bot receives the READY event. + * Seeds voice states, starts presence rotation, ends startup grace period, + * and begins 24/7 boot recovery. + */ + onReady() { + this._lastReadyAt = Date.now(); + this.seedVoiceStatesFromGuilds(); + this.seedGuildsFromRest().catch(e => logger.warn("[onReady] seedGuildsFromRest error:", e.message)); + this.attachRawListener(); + + this.setupPresenceRotation(); + + setTimeout(() => { + this._inStartupGrace = false; + const pending = this._deferredGuildDeletes.size; + if (pending > 0) { + logger.guild( + `[GuildDelete] Startup grace period ended. ` + + `${pending} deferred deletion(s) confirmed — cleaning up.` + ); + } else { + logger.guild(`[GuildDelete] Startup grace period ended. No deferred deletions.`); + } + if (this._deferredDeleteCount > 3) { + logger.guild( + `[GuildDelete] (Suppressed ${this._deferredDeleteCount - 3} deferral log lines for brevity)` + ); + } + }, this._startupDeleteGraceMs); + + this.rejoin247Channels(); + } + + /** + * Boot recovery: sequentially rejoin all saved 24/7 channels. + * Sets _bootRecoveryActive=true to suppress fake move events during the process. + * Cleans up missing channels from settings to prevent repeated failures. + * @returns {Promise} + */ + async rejoin247Channels() { + this._bootRecoveryActive = true; + try { + await this._rejoin247ChannelsInner(); + } catch (err) { + logger.warn("[BootRecovery] 24/7 boot recovery crashed:", err?.message ?? err); + } finally { + this._bootRecoveryActive = false; + } + } + + /** @private Inner boot-recovery loop. The flag reset is handled by the caller's finally block. */ + async _rejoin247ChannelsInner() { + const { remix } = this; + const channelsToRejoin = []; + + for (const [guildId, serverSettings] of remix.settingsMgr.guilds) { + const raw = serverSettings.get("stay_247"); + if (!raw || raw === "none") continue; + + const rawArr = Array.isArray(raw) ? raw : [raw]; + const channels = rawArr + .map(id => cleanId(id)) + .filter(id => id.length >= 15 && id.length <= 22); + + for (const channelId of channels) { + const mode = get247ChannelMode(serverSettings, channelId); + if (mode === "on") { + channelsToRejoin.push({ guildId, channelId, mode }); + } + } + } + + if (channelsToRejoin.length === 0) { + logger.voice247("[BootRecovery] No 24/7 channels to rejoin."); + return; + } + + logger.voice247( + `[BootRecovery] Found ${channelsToRejoin.length} 24/7 channel(s) to rejoin: ` + + channelsToRejoin.map(c => `${c.channelId}(${c.mode})`).join(", ") + ); + + const baseStagger = remix.config?.timers?.bootRejoinStagger ?? 5_000; + + for (let i = 0; i < channelsToRejoin.length; i++) { + const { guildId, channelId, mode } = channelsToRejoin[i]; + + if (i > 0) { + let staggerDelay = baseStagger; + if (i >= 8) staggerDelay = baseStagger * 2; + else if (i >= 4) staggerDelay = Math.round(baseStagger * 1.5); + logger.voice247(`[BootRecovery] Waiting ${staggerDelay / 1000}s before rejoining next channel...`); + await new Promise(resolve => setTimeout(resolve, staggerDelay)); + } + + const existing = remix.players.playerMap.get(channelId); + if (existing && !existing._destroyed) { + logger.voice247(`[BootRecovery] Channel ${channelId} already has a player — skipping.`); + continue; + } + if (remix.players._pendingJoins?.has?.(channelId)) { + logger.voice247(`[BootRecovery] Channel ${channelId} already has a pending join — skipping.`); + continue; + } + + const channelObj = remix.client?.channels?.get?.(channelId); + if (!channelObj) { + logger.warn( + `[BootRecovery] Channel ${channelId} in guild ${guildId} no longer exists — ` + + `removing from 24/7 settings to prevent repeated failures.` + ); + try { + const set = remix.settingsMgr.getServer(guildId); + if (set) { + const raw = set.get("stay_247"); + const arr = Array.isArray(raw) ? raw : raw ? [raw] : []; + const filtered = arr.filter(id => id && id !== "none" && cleanId(id) !== channelId); + const remainingSet = new Set(filtered.map(id => cleanId(id))); + remove247ChannelMode(set, channelId, remainingSet); + set.set("stay_247", filtered.length > 0 ? filtered : "none"); + } + } catch (cleanupErr) { + logger.warn(`[BootRecovery] Failed to auto-remove missing channel ${channelId} from 24/7:`, cleanupErr?.message); + } + continue; + } + if (channelObj.type !== 2) { + logger.warn( + `[BootRecovery] Channel ${channelId} in guild ${guildId} is not a voice channel (type: ${channelObj.type}) — skipping.` + ); + continue; + } + + const guildHasActivePlayer = [...remix.players.playerMap.values()] + .some(p => !p._destroyed && cleanId(p._guildId ?? "") === guildId); + if (guildHasActivePlayer && i > 0) { + const extraDelay = 3_000; + logger.voice247( + `[BootRecovery] Guild ${guildId} already has an active player — ` + + `waiting extra ${extraDelay / 1000}s to avoid move-disconnect.` + ); + await new Promise(resolve => setTimeout(resolve, extraDelay)); + } + + logger.voice247( + `[BootRecovery] Rejoining channel ${channelId} in guild ${guildId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]` + ); + + const player = await this._attemptRejoin(channelId, guildId, 3, 5_000, "BootRecovery"); + + if (player) { + logger.voice247( + `[BootRecovery] Successfully rejoined channel ${channelId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]` + ); + } else { + logger.warn( + `[BootRecovery] Failed to rejoin channel ${channelId} in guild ${guildId} after retries — ` + + `keeping 24/7 setting intact, will retry on next disconnect/restart.` + ); + } + } + + logger.voice247( + `[BootRecovery] Boot recovery complete. ${channelsToRejoin.length} channel(s) processed.` + ); + } +} + +// Attach the split-out concerns: voice-state routing (VoiceStateRouting), +// guild sync & seeding (GuildSync), and 24/7 rejoin management (RejoinManager). +applyMixins(GatewayHandler, VoiceStateRouting, GuildSync, RejoinManager); + +export { GatewayHandler }; diff --git a/src/voice/gateway/GuildSync.mjs b/src/voice/gateway/GuildSync.mjs new file mode 100644 index 0000000..6ae7fbf --- /dev/null +++ b/src/voice/gateway/GuildSync.mjs @@ -0,0 +1,391 @@ +/** + * @module src/voice/gateway/GuildSync + * @description Guild synchronisation concern for {@link GatewayHandler}: + * bot permission checks on guild create, voice-state cache seeding + * (VoiceManager, guild cache, VoiceStateCache, LiveKit participants), REST + * guild-cache stubbing for guilds without GUILD_CREATE, and confirmed + * guild-delete cleanup. + * + * These methods are applied onto the GatewayHandler class prototype via + * {@link applyMixins} — `this` is a GatewayHandler instance. + */ + +import { getVoiceManager } from "@fluxerjs/voice"; +import { logger } from "../../core/Logger.mjs"; +import { REQUIRED_BOT_PERMISSIONS } from "../../ui/index.mjs"; +import { cleanId } from "../../utils/Utils.mjs"; +import { iterateVoiceStates } from "../VoiceStateResolver.mjs"; + +/** + * @type {object} + * @description Guild sync mixin — applied to GatewayHandler. + */ +const GuildSync = { + /** + * Check and warn about missing bot permissions in a guild. + * Sends an embed to the system channel if critical or optional perms are missing. + * @param {object} guild - The guild object. + * @param {string} guildId - The guild ID. + * @returns {Promise} + * @private + */ + async _checkGuildPermissions(guild, guildId) { + const { remix } = this; + + try { + if (guild.members && !guild.members.me) { + await guild.members.fetchMe(); + } + } catch (e) { logger.warn("[GatewayHandler] fetchMe failed:", e?.message); } + + const channels = guild.channels; + if (!channels) return; + + let targetChannel = null; + if (guild.systemChannelId) { + targetChannel = channels.get?.(guild.systemChannelId) ?? null; + } + if (!targetChannel) { + for (const ch of (channels.values?.() ?? [])) { + if (ch.isTextBased?.() || ch.type === 0 || ch.type === "GUILD_TEXT") { + targetChannel = ch; + break; + } + } + } + if (!targetChannel) return; + + const result = remix.messages.checkAllBotPermissions(targetChannel); + if (result.missing.length === 0) return; + + const missingNames = result.missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k); + if (result.criticalMissing.length > 0) { + logger.warn( + `[GuildCreate] Server ${guildId} is missing CRITICAL bot permissions: ${result.criticalMissing.join(", ")}\n` + + ` All missing: ${missingNames.join(", ")}` + ); + } else { + logger.guild( + `[GuildCreate] Server ${guildId} is missing optional permissions: ${result.optionalMissing.join(", ")}` + ); + } + + try { + const permEmbed = remix.messages.buildPermissionEmbed(result.missing, guildId); + await targetChannel.send({ embeds: [permEmbed], allowedMentions: { parse: [] } }); + } catch (e) { + logger.warn(`[GuildCreate] Cannot send permission warning to server ${guildId}: ${e.message}`); + try { + const t = this.remix.locale?.translate?.bind(this.remix.locale); + const guildIdStr = cleanId(guildId); + await targetChannel.send({ + content: t ? t(guildIdStr, "responses.gateway.missingPermsFallback", { perms: missingNames.join("**, **") }) : + "⚠️ I'm missing permissions I need to work properly! Missing: **" + missingNames.join("**, **") + "**. Please ask a server administrator to grant these permissions in Server Settings → Roles.", + allowedMentions: { parse: [] }, + }); + } catch (e) { + logger.warn(`[GuildCreate] Cannot send ANY notification to server ${guildId} — bot is missing SendMessages permission:`, e?.message); + } + } + }, + + /** + * Seed the voice state cache from VoiceManager or guild cache on startup. + * @private + */ + seedVoiceStatesFromGuilds() { + const { remix } = this; + const client = remix.client; + + try { + const vm = getVoiceManager(client); + if (vm?.voiceStates && vm.voiceStates.size > 0) { + let totalHumans = 0; + let totalBots = 0; + for (const [guildId, userMap] of vm.voiceStates) { + if (!userMap || typeof userMap.forEach !== "function") continue; + const cleanGuildId = cleanId(guildId); + if (!cleanGuildId) continue; + userMap.forEach((channelId, userId) => { + if (!userId || !channelId) return; + const botId = client.user?.id; + if (userId === botId) { + remix.voiceCache.updateUser({ guildId: cleanGuildId, userId, channelId, isBot: true }); + totalBots++; + } else { + const guild = client.guilds.get(cleanGuildId) ?? client.guilds.get(guildId); + const member = guild?.members?.get?.(userId); + const isBot = member?.user?.bot ?? false; + remix.voiceCache.updateUser({ guildId: cleanGuildId, userId, channelId, isBot }); + if (isBot) totalBots++; + else totalHumans++; + } + }); + } + logger.voiceState( + `[Seed] Seeded from VoiceManager.voiceStates — ` + + `${totalHumans} humans, ${totalBots} bots across ${vm.voiceStates.size} guilds. ` + + `Cache now: ${remix.voiceCache.observedVoiceUsersSize} humans, ${remix.voiceCache.observedVoiceBotsSize} bots.` + ); + return; + } + logger.voiceState(`[Seed] VoiceManager.voiceStates is empty (${vm?.voiceStates?.size ?? "null"} guilds). ` + + `This is expected if no users were in voice when the bot started. ` + + `VoiceStatesSync handler will populate the cache as guilds become available.`); + } catch (e) { + logger.voiceState(`[Seed] VoiceManager seeding failed: ${e?.message} — falling back to guild cache.`); + } + + for (const [gId, guild] of client.guilds) { + for (const vs of iterateVoiceStates(guild)) { + remix.voiceCache.updateUser({ guildId: gId, userId: vs.userId, channelId: vs.channelId, isBot: vs.isBot }); + } + } + }, + + /** + * Re-seed voice states for a specific channel from multiple sources. + * Checks VoiceManager, guild cache, VoiceStateCache, and LiveKit participants. + * @param {string} guildId - The guild ID. + * @param {string} channelId - The channel ID. + * @returns {number} Number of humans found in the channel. + */ + reseedVoiceStatesForChannel(guildId, channelId) { + const { remix } = this; + const client = remix.client; + + const cleanGuild = cleanId(guildId); + const cleanChannel = cleanId(channelId); + if (!cleanGuild || !cleanChannel) return 0; + + let humansFound = 0; + const botId = client.user?.id; + + try { + const vm = getVoiceManager(client); + if (vm?.voiceStates) { + const guildVoiceMap = vm.voiceStates.get(cleanGuild) ?? vm.voiceStates.get(guildId); + if (guildVoiceMap && typeof guildVoiceMap.forEach === "function") { + guildVoiceMap.forEach((userChannelId, userId) => { + if (!userId || !userChannelId) return; + const userChannel = cleanId(userChannelId); + if (userChannel !== cleanChannel) return; + if (userId === botId) { + remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: true }); + } else { + const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId); + const member = guild?.members?.get?.(userId); + const isBot = member?.user?.bot ?? false; + if (isBot) { + remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: true }); + } else { + remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: false }); + humansFound++; + logger.voiceState( + `[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild}) via VoiceManager` + ); + } + } + }); + + if (botId) { + remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true }); + } + + logger.voiceState( + `[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` + + `found ${humansFound} human(s) via VoiceManager, observedVoiceUsers size now ${remix.voiceCache.observedVoiceUsersSize}` + ); + + if (humansFound > 0) return humansFound; + } + } + } catch (e) { + logger.voiceState(`[Reseed] VoiceManager lookup failed: ${e?.message} — falling back.`); + } + + const guild = client.guilds.get(cleanGuild) ?? client.guilds.get(guildId); + if (!guild) { + logger.voiceState( + `[Reseed] Guild ${cleanGuild} not in cache — cannot reseed voice states.` + ); + } else { + for (const vs of iterateVoiceStates(guild)) { + if (vs.isBot) continue; + if (vs.channelId === cleanChannel) { + remix.voiceCache.updateUser({ guildId: cleanGuild, userId: vs.userId, channelId: vs.channelId, isBot: false }); + humansFound++; + logger.voiceState( + `[Reseed] Found human ${vs.userId} in channel ${cleanChannel} (guild ${cleanGuild})` + ); + } + } + + if (botId) { + remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true }); + } + + if (humansFound > 0) { + logger.voiceState( + `[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` + + `found ${humansFound} human(s), observedVoiceUsers size now ${remix.voiceCache.observedVoiceUsersSize}` + ); + return humansFound; + } + } + + if (humansFound === 0 && remix.voiceCache) { + const humans = remix.voiceCache.getHumansInChannel(cleanGuild, cleanChannel); + for (const uid of humans) { + humansFound++; + logger.voiceState( + `[Reseed] Found human ${uid} in channel ${cleanChannel} (guild ${cleanGuild}) via VoiceStateCache` + ); + } + + if (botId) { + remix.voiceCache.updateUser({ guildId: cleanGuild, userId: botId, channelId: cleanChannel, isBot: true }); + } + } + + if (humansFound === 0) { + try { + const player = remix.players.playerMap.get(cleanChannel); + const room = player?.connection?.room; + if (room?.isConnected && room.remoteParticipants) { + for (const [, participant] of room.remoteParticipants) { + const userId = participant?.identity ?? participant?.sid; + if (userId) { + humansFound++; + remix.voiceCache.updateUser({ guildId: cleanGuild, userId, channelId: cleanChannel, isBot: false }); + logger.voiceState( + `[Reseed] Found human ${userId} in channel ${cleanChannel} (guild ${cleanGuild}) via LiveKit participants` + ); + } + } + } + } catch (e) { + logger.voiceState(`[Reseed] LiveKit participant fallback error: ${e?.message}`); + } + } + + logger.voiceState( + `[Reseed] Channel ${cleanChannel} (guild ${cleanGuild}): ` + + `found ${humansFound} human(s), observedVoiceUsers size now ${remix.voiceCache.observedVoiceUsersSize}` + ); + + return humansFound; + }, + + /** @async @private Fetch all guilds the bot is in via REST and create stub entries in the client cache for any missing guilds. This ensures settings and 24/7 lookups work even for guilds that haven't sent GUILD_CREATE yet. */ + async seedGuildsFromRest() { + const { remix } = this; + const client = remix.client; + + try { + let after = null; + let added = 0; + + while (true) { + const url = "/users/@me/guilds?limit=200" + (after ? "&after=" + after : ""); + const chunk = await client.rest.get(url); + + if (!Array.isArray(chunk) || chunk.length === 0) break; + + for (const g of chunk) { + const id = g?.id; + if (!id) continue; + if (!client.guilds.has(id)) { + try { + const Guild = this._getGuildClass(); + if (Guild) { + const stub = new Guild(client, { id, name: g.name ?? "unknown" }); + stub._stub = true; + client.guilds.set(id, stub); + } else { + client.guilds.set(id, { + id, + name: g.name ?? "unknown", + _stub: true, + members: { set: () => {}, get: () => undefined, has: () => false, me: null }, + channels: { set: () => {}, get: () => undefined, has: () => false }, + roles: { set: () => {}, get: () => undefined, has: () => false }, + emojis: { set: () => {}, get: () => undefined, has: () => false }, + stickers: { set: () => {}, get: () => undefined, has: () => false }, + }); + } + } catch (stubErr) { + logger.guild(`[GuildSeed] Guild constructor failed for ${id}, using safe stub: ${stubErr?.message}`); + client.guilds.set(id, { + id, + name: g.name ?? "unknown", + _stub: true, + members: { set: () => {}, get: () => undefined, has: () => false, me: null }, + channels: { set: () => {}, get: () => undefined, has: () => false }, + roles: { set: () => {}, get: () => undefined, has: () => false }, + emojis: { set: () => {}, get: () => undefined, has: () => false }, + stickers: { set: () => {}, get: () => undefined, has: () => false }, + }); + } + added++; + } + } + + if (chunk.length < 200) break; + after = chunk[chunk.length - 1].id; + } + + if (added > 0) { + logger.guild(`[GuildSeed] Added ${added} missing guild stub(s) from REST. Total: ${client.guilds.size}`); + } else { + logger.guild(`[GuildSeed] All guilds already cached. Total: ${client.guilds.size}`); + } + } catch (err) { + logger.warn("[GuildSeed] REST guild seeding failed:", err?.message ?? err); + } + }, + + /** @private @returns {Function|null} The Guild constructor class. */ + _getGuildClass() { + if (this._GuildClass) return this._GuildClass; + try { + const { client } = this.remix; + for (const guild of client.guilds.values()) { + if (guild && !guild._stub && typeof guild.constructor === 'function' && guild.constructor.name === 'Guild') { + this._GuildClass = guild.constructor; + return this._GuildClass; + } + } + } catch(e) { logger.warn("[Gateway] _getGuildClass failed:", e?.message); } + this._GuildClass = null; + return null; + }, + + /** + * Process a confirmed guild deletion. Cleans up voice cache and previous state. + * Does NOT delete 24/7 settings (preserved for re-invite). + * @param {string} guildId - The deleted guild ID. + * @private + */ + _processGuildDelete(guildId) { + const { remix } = this; + const cleanGuildId = cleanId(guildId); + + logger.guild( + `[GuildDelete] Received GuildDelete for server ${guildId} — ` + + `skipping removal (24/7 removal system disabled). ` + + `Settings and players are preserved. If the server truly removed the bot, ` + + `the GuildCreate handler will re-initialise on re-invite.` + ); + + remix.voiceCache.removeGuild(cleanGuildId); + for (const [stateKey, info] of [...this._prevVoiceState]) { + if (cleanId(info.guildId) === cleanGuildId) + this._prevVoiceState.delete(stateKey); + } + remix._announcementChannelCache?.delete(guildId); + }, +}; + +export default GuildSync; +export { GuildSync }; diff --git a/src/voice/gateway/RejoinManager.mjs b/src/voice/gateway/RejoinManager.mjs new file mode 100644 index 0000000..23ae75f --- /dev/null +++ b/src/voice/gateway/RejoinManager.mjs @@ -0,0 +1,169 @@ +/** + * @module src/voice/gateway/RejoinManager + * @description Rejoin concern for {@link GatewayHandler}: 24/7 channel + * rejoin with exponential-backoff retries, duplicate-join guarding, and + * guild move-in-progress detection. The MAX_REJOIN_RETRIES static lives on + * the base GatewayHandler class (imported below). + * + * These methods are applied onto the GatewayHandler class prototype via + * {@link applyMixins} — `this` is a GatewayHandler instance. + */ + +import { logger } from "../../core/Logger.mjs"; +import { cleanId } from "../../utils/Utils.mjs"; +import { GatewayHandler } from "./GatewayHandler.mjs"; + +/** + * @type {object} + * @description Rejoin manager mixin — applied to GatewayHandler. + */ +const RejoinManager = { + /** + * Attempt to spawn a player for a channel with exponential-backoff retries. + * @param {string} channelId - The target channel ID. + * @param {string} guildId - The guild ID. + * @param {number} [maxRetries=3] - Maximum retry attempts. + * @param {number} [baseDelay=5000] - Base delay in ms (doubled each retry). + * @param {string} [context='Rejoin'] - Label for log messages. + * @returns {Promise} The spawned player, or null if all retries failed. + * @private + */ + async _attemptRejoin(channelId, guildId, maxRetries = 3, baseDelay = 5_000, context = 'Rejoin') { + for (let attempt = 1; attempt <= maxRetries; attempt++) { + try { + const player = await this.remix._spawnPlayer(guildId, channelId); + this.reseedVoiceStatesForChannel(guildId, channelId); + logger.voice247( + `[${context}] Successfully rejoined channel ${channelId}` + + (attempt > 1 ? ` (after ${attempt - 1} retry/retries)` : '') + ); + return player; + } catch (err) { + const errMsg = err?.message ?? String(err); + const isTrackTimeout = errMsg.includes("track publication timed out") + || errMsg.includes("lavalink player create failed") + || errMsg.includes("Failed to create audio player") + || errMsg.includes("internal error"); + + if (isTrackTimeout && attempt < maxRetries) { + const backoffMs = baseDelay * Math.pow(2, attempt - 1); + logger.warn( + `[${context}] Track publication failed for channel ${channelId} (attempt ${attempt}/${maxRetries}) — ` + + `retrying in ${backoffMs / 1000}s: ${errMsg}` + ); + await new Promise(resolve => setTimeout(resolve, backoffMs)); + continue; + } + + logger.warn( + `[${context}] Failed to rejoin channel ${channelId} (attempt ${attempt}/${maxRetries}): ${errMsg}` + + (attempt > 1 ? ` (after ${attempt} attempts)` : '') + ); + return null; + } + } + return null; + }, + + /** + * Safely rejoin a 24/7 channel. Guards against duplicate joins, + * intentional leaves, missing channels, and pending joins. + * @param {string} guildId - The guild ID. + * @param {string} channelId - The target channel ID. + * @returns {Promise} The spawned player, or null if skipped. + * @private + */ + async _rejoinChannel(guildId, channelId) { + const { remix } = this; + const cleanGuildId = cleanId(guildId); + const cleanChannelId = cleanId(channelId); + + if (this._rejoinInProgress.has(cleanChannelId)) { + logger.voice247(`[Rejoin] Channel ${cleanChannelId} rejoin already in progress — skipping.`); + return; + } + + const existing = remix.players.playerMap.get(cleanChannelId); + if (existing && !existing._destroyed) { + logger.voice247(`[Rejoin] Channel ${cleanChannelId} already has a player — skipping.`); + this._rejoinAttempts.delete(cleanChannelId); + return; + } + + if (remix.players._pendingJoins?.has?.(cleanChannelId)) { + logger.voice247(`[Rejoin] Channel ${cleanChannelId} already has a pending join — skipping.`); + return; + } + + if (remix.intentionalLeaves.has(cleanChannelId)) { + logger.voice247(`[Rejoin] Channel ${cleanChannelId} was intentionally left — skipping.`); + this._rejoinAttempts.delete(cleanChannelId); + return; + } + + const channel = remix.client?.channels?.get?.(cleanChannelId); + if (!channel) { + logger.voice247(`[Rejoin] Channel ${cleanChannelId} no longer exists — skipping.`); + this._rejoinAttempts.delete(cleanChannelId); + return; + } + + this._rejoinInProgress.add(cleanChannelId); + + const maxRetries = GatewayHandler.MAX_REJOIN_RETRIES; + logger.voice247( + `[Rejoin] Attempting to rejoin channel ${cleanChannelId} in guild ${cleanGuildId}...` + ); + + try { + const player = await this._attemptRejoin(cleanChannelId, cleanGuildId, maxRetries, 5_000, "Rejoin"); + if (player) { + this._rejoinAttempts.delete(cleanChannelId); + } else { + this._rejoinAttempts.delete(cleanChannelId); + } + return player; + } finally { + this._rejoinInProgress.delete(cleanChannelId); + } + }, + + /** @private Check whether a guild currently has a move in progress (recently connected player or pending join). Used to suppress false positive disconnect-rejoin loops. @param {string} guildId - The guild ID. @param {string} oldChannelId - The channel the bot just left. @returns {boolean} True if a move is in progress within the evidence window. */ + _isGuildMoveInProgress(guildId, oldChannelId) { + const { remix } = this; + const cleanGuild = cleanId(guildId); + const cleanOld = cleanId(oldChannelId); + if (!cleanGuild || !cleanOld) return false; + + const now = Date.now(); + const activePlayers = [...remix.players.playerMap.values()].filter( + p => !p._destroyed && cleanId(p._guildId ?? "") === cleanGuild + ); + + for (const player of activePlayers) { + const playerChannel = cleanId(player._channelId ?? ""); + if (!playerChannel || playerChannel === cleanOld) continue; + const connectedAt = player._lastConnectedAt ?? 0; + if (now - connectedAt < this._moveEvidenceWindowMs) { + return true; + } + } + + if (remix.players._pendingJoins) { + for (const pendingId of remix.players._pendingJoins) { + const cleanPending = cleanId(pendingId); + if (cleanPending && cleanPending !== cleanOld) { + const pendingChannel = remix.client?.channels?.get?.(cleanPending); + if (pendingChannel && cleanId(pendingChannel.guildId ?? "") === cleanGuild) { + return true; + } + } + } + } + + return false; + }, +}; + +export default RejoinManager; +export { RejoinManager }; diff --git a/src/voice/gateway/VoiceStateRouting.mjs b/src/voice/gateway/VoiceStateRouting.mjs new file mode 100644 index 0000000..605b276 --- /dev/null +++ b/src/voice/gateway/VoiceStateRouting.mjs @@ -0,0 +1,435 @@ +/** + * @module src/voice/gateway/VoiceStateRouting + * @description Voice-state routing concern for {@link GatewayHandler}: + * VOICE_STATE_UPDATE dispatch (human vs. bot paths), VOICE_STATES_SYNC bulk + * seeding, previous-state map maintenance, voice cache updates, inactivity + * timers on human join/leave, dashboard updates, and 24/7 bot move-away / + * disconnect handling. + * + * These methods are applied onto the GatewayHandler class prototype via + * {@link applyMixins} — `this` is a GatewayHandler instance. + */ + +import { logger } from "../../core/Logger.mjs"; +import { get247ChannelMode } from "../../utils/Helpers247.mjs"; +import { VoiceStateCache } from "../VoiceStateCache.mjs"; +import { cleanId } from "../../utils/Utils.mjs"; + +/** + * @type {object} + * @description Voice-state routing mixin — applied to GatewayHandler. + */ +const VoiceStateRouting = { + /** + * Main handler for VOICE_STATE_UPDATE events. Routes to human or bot sub-handlers. + * @param {object} data - The voice state update payload from the gateway. + * @returns {Promise} + * @private + */ + async _handleVoiceStateUpdate(data) { + const { remix } = this; + const client = remix.client; + + const userId = data?.user_id; + if (!userId) return; + + const newChannelId = data?.channel_id ?? null; + const vsuGuildId = data?.guild_id; + const isBot = data?.member?.user?.bot ?? null; + + + const prevEntry = this.findPrevVoiceStateEntry(userId, vsuGuildId); + const prev = prevEntry.value; + const prevSameGuild = prev && + cleanId(prev.guildId ?? "") === cleanId(vsuGuildId ?? ""); + const oldChannelId = prevSameGuild ? (prev?.channelId ?? null) : null; + + + this._updatePreviousStates(userId, vsuGuildId, oldChannelId, newChannelId, isBot, prevEntry, prev); + this._updateVoiceStateCache(userId, vsuGuildId, oldChannelId, newChannelId, isBot, prev); + + + const { player, playerGuildId, homeChannelId } = this._findAffectedPlayer(vsuGuildId, oldChannelId, newChannelId); + + const isBotUser = isBot === true && userId === client.user?.id; + + if (!isBotUser) { + + this._handleInactivityOnVoiceChange(player, playerGuildId, homeChannelId, userId, oldChannelId, newChannelId, vsuGuildId, data); + return; + } + + + this._handleBotVoiceChange(player, playerGuildId, homeChannelId, oldChannelId, newChannelId, vsuGuildId, data); + }, + + /** Handle VoiceStatesSync bulk event from the gateway. @param {object} data - Sync payload with voiceStates array. @private */ + _handleVoiceStatesSync(data) { + const { remix } = this; + const client = remix.client; + const guildId = data?.guildId; + if (!guildId || !Array.isArray(data?.voiceStates)) return; + + const botId = client.user?.id; + let humansAdded = 0; + let botsAdded = 0; + + for (const vs of data.voiceStates) { + const userId = vs.user_id; + const channelId = vs.channel_id; + if (!userId || !channelId) continue; + + const isBot = vs.member?.user?.bot ?? (userId === botId); + + remix.voiceCache.updateUser({ guildId, userId, channelId, isBot }); + if (isBot) { + botsAdded++; + } else { + humansAdded++; + } + } + + if (humansAdded > 0 || botsAdded > 0) { + logger.voiceState( + `[VoiceStatesSync] Guild ${guildId}: seeded ${humansAdded} humans, ${botsAdded} bots ` + + `(${data.voiceStates.length} total states).` + ); + } + }, + + /** @private Update the voice state cache for a user joining/leaving. @param {string} userId @param {string} guildId @param {string|null} oldChannelId @param {string|null} newChannelId @param {boolean} isBot @param {object|null} prev */ + _updateVoiceStateCache(userId, guildId, oldChannelId, newChannelId, isBot, prev) { + const { remix } = this; + + if (newChannelId) { + remix.voiceCache.updateUser({ guildId: guildId ?? prev?.guildId, userId, channelId: newChannelId, isBot: isBot === true }); + } else { + const resolvedGuildId = guildId ?? prev?.guildId; + if (resolvedGuildId) { + remix.voiceCache.deleteHumanUser(userId, resolvedGuildId); + remix.voiceCache.deleteBotUser(VoiceStateCache.userKey(resolvedGuildId, userId)); + } + } + }, + + /** @private Update the previous-voice-state map and evict stale entries. @param {string} userId @param {string} guildId @param {string|null} oldChannelId @param {string|null} newChannelId @param {boolean} isBot @param {object} prevEntry @param {object|null} prev */ + _updatePreviousStates(userId, guildId, oldChannelId, newChannelId, isBot, prevEntry, prev) { + const { remix } = this; + const prevKey = prevEntry.key; + const nextKey = this.getPrevVoiceStateKey(userId, guildId ?? prev?.guildId); + + if (newChannelId) { + if (prevKey && prevKey !== nextKey) { + const prevGuildPart = prevKey.split(":")[0]; + const nextGuildPart = nextKey.split(":")[0]; + if (prevGuildPart === nextGuildPart) { + this._prevVoiceState.delete(prevKey); + } + } + if (nextKey && this._prevVoiceState.size >= 10_000 && !this._prevVoiceState.has(nextKey)) { + const evictKey = this._prevVoiceState.keys().next().value; + const evictEntry = this._prevVoiceState.get(evictKey); + this._prevVoiceState.delete(evictKey); + if (evictEntry) { + const evictGuildId = evictEntry.guildId; + const evictUserId = evictKey.split(":")[1]; + if (evictGuildId && evictUserId) { + const currentLoc = remix.voiceCache.getUserLocation(evictGuildId, evictUserId); + if (currentLoc && currentLoc.channelId === evictEntry.channelId) { + remix.voiceCache.updateUser({ guildId: evictGuildId, userId: evictUserId, channelId: null, isBot: evictEntry.isBot ?? false }); + } + } + } + } + if (nextKey) this._prevVoiceState.set(nextKey, { channelId: newChannelId, guildId: guildId ?? prev?.guildId, isBot: isBot === true }); + } else { + if (prevKey) this._prevVoiceState.delete(prevKey); + } + }, + + /** @private Find a player affected by a voice state change. @param {string} guildId @param {string|null} oldChannelId @param {string|null} newChannelId @returns {{player: Player|null, playerGuildId: string|null, homeChannelId: string|null}} */ + _findAffectedPlayer(guildId, oldChannelId, newChannelId) { + const { remix } = this; + + + if (oldChannelId) { + const cleanOld = cleanId(oldChannelId); + const player = remix.players.playerMap.get(cleanOld); + if (player) { + return { player, playerGuildId: player._guildId, homeChannelId: player._home247Channel }; + } + } + + + if (newChannelId) { + const cleanNew = cleanId(newChannelId); + const player = remix.players.playerMap.get(cleanNew); + if (player) { + return { player, playerGuildId: player._guildId, homeChannelId: player._home247Channel }; + } + } + + return { player: null, playerGuildId: null, homeChannelId: null }; + }, + + /** @private Manage inactivity timers when a human joins or leaves a voice channel. @param {Player|null} player @param {string|null} playerGuildId @param {string|null} homeChannelId @param {string} userId @param {string|null} oldChannelId @param {string|null} newChannelId @param {string} vsuGuildId @param {object} vsu */ + async _handleInactivityOnVoiceChange(player, playerGuildId, homeChannelId, userId, oldChannelId, newChannelId, vsuGuildId, vsu) { + const { remix } = this; + const client = remix.client; + const resolvedGuildId = vsuGuildId ?? playerGuildId; + if (!resolvedGuildId) return; + + if (newChannelId) { + try { + const cleanId247 = cleanId(newChannelId); + const player247 = remix.players.playerMap.get(cleanId247); + if (player247 && typeof player247._stopInactivityTimer === "function") { + logger.voiceState(`[VoiceState] Human joined 247 channel ${cleanId247}, stopping inactivity timer`); + player247._stopInactivityTimer(); + } + } catch(e) { logger.warn("[VoiceState] 247 inactivity timer stop failed:", e?.message); } + } + + if (oldChannelId && oldChannelId !== newChannelId) { + try { + const cleanOld = cleanId(oldChannelId); + const oldPlayer = remix.players.playerMap.get(cleanOld); + if (oldPlayer && typeof oldPlayer._startInactivityTimer === "function") { + setTimeout(() => { + if (!oldPlayer._hasHumansInChannel()) { + logger.voiceState(`[VoiceState] Last human left ${cleanOld}, starting inactivity timer`); + oldPlayer._startInactivityTimer(); + } + }, this.T.aloneCheckDebounce); + } + } catch(e) { logger.warn("[VoiceState] Inactivity timer start failed:", e?.message); } + } + + if (newChannelId) { + try { + const cleanChId = cleanId(newChannelId); + const newPlayer = remix.players.playerMap.get(cleanChId); + if (newPlayer && typeof newPlayer._stopInactivityTimer === "function") { + logger.voiceState(`[VoiceState] Human joined ${cleanChId}, stopping inactivity timer`); + newPlayer._stopInactivityTimer(); + } + } catch(e) { logger.warn("[VoiceState] Inactivity timer stop failed:", e?.message); } + } + + if (remix.dashboard?.enabled) { + try { + let userObj = vsu?.member?.user; + if (!userObj) { + try { userObj = await client.users.fetch(userId).catch(() => null); } catch(e) { logger.warn("[VoiceState] Dashboard user fetch failed:", e?.message); } + } + if (userObj) { + const details = { + type: newChannelId ? "join" : "leave", + guildId: resolvedGuildId, + channelId: newChannelId ?? null, + oldChannelId: oldChannelId ?? null, + }; + remix.dashboard.updateUser(details, userObj); + } + + const refChannel = newChannelId ?? oldChannelId; + const cleanId_ref = refChannel ? cleanId(refChannel) : null; + + if (cleanId_ref) { + const dashPlayer = remix.players.playerMap.get(cleanId_ref); + if (dashPlayer) { + const eventType = newChannelId ? "join" : "leave"; + remix.dashboard.updatePlayer({ + type: eventType, + data: userId, + }, dashPlayer); + + remix.dashboard.playerUpdate({ + type: eventType, + }, dashPlayer); + } + } + } catch(e) { logger.warn("[VoiceState] Dashboard update failed:", e?.message); } + } + }, + + /** + * Handle a voice state update for the bot itself. + * Detects move-away from 24/7 channels and unexpected disconnects. + * @param {Player|null} player - The affected player (if any). + * @param {string|null} playerGuildId - The guild ID from the player. + * @param {string|null} homeChannelId - The 24/7 home channel ID from the player. + * @param {string|null} oldChannelId - The channel the bot was in. + * @param {string|null} newChannelId - The channel the bot moved to (null if disconnected). + * @param {string} vsuGuildId - The guild ID from the VSU event. + * @param {object} vsu - The raw VSU payload. + * @private + */ + _handleBotVoiceChange(player, playerGuildId, homeChannelId, oldChannelId, newChannelId, vsuGuildId, vsu) { + const { remix } = this; + const client = remix.client; + const guildId = vsuGuildId; + + if (newChannelId && guildId && oldChannelId && oldChannelId !== newChannelId) { + // During boot recovery, ignore move events — the recovery loop handles rejoining. + if (this._bootRecoveryActive) { + logger.voice247( + `[247] Ignoring bot move ${cleanId(oldChannelId)} → ${cleanId(newChannelId)} during boot recovery.` + ); + return; + } + try { + const cleanNew = cleanId(newChannelId); + const cleanOld = cleanId(oldChannelId); + + // Check if old channel is a saved 24/7 channel + const oldIs247 = (() => { + try { + const set = remix.settingsMgr.getServer(guildId); + return get247ChannelMode(set, cleanOld) === "on"; + } catch (_) { return false; } + })(); + + // Check if new channel is a saved 24/7 channel or has a pending spawn + const newChannelSaved = (() => { + try { + const set = remix.settingsMgr.getServer(guildId); + return get247ChannelMode(set, cleanNew) === "on"; + } catch (_) { return false; } + })(); + const newChannelPendingSpawn = remix.players?._pendingJoins?.has?.(cleanNew) || false; + + const existingPlayer = remix.players.playerMap.get(cleanOld); + + if (oldIs247 && existingPlayer) { + // Old channel is 24/7 — bot physically moved away, so the voice + // connection to old channel is dead. Destroy the old player and + // schedule a fresh rejoin so it gets a new live connection. + logger.voice247( + `[247] Bot moved away from 24/7 channel ${cleanOld} → ${cleanNew}. ` + + `Destroying stale player, scheduling rejoin for ${cleanOld}.` + ); + remix.players.playerMap.delete(cleanOld); + const homeCh = cleanId(existingPlayer._home247Channel ?? ""); + if (homeCh && homeCh !== cleanOld) remix.players.playerMap.delete(homeCh); + try { existingPlayer.destroy(); } catch (_) {} + const rejoinDelay = this.T.rejoin247Delay ?? 3_000; + setTimeout(() => { + this._rejoinChannel(cleanId(guildId), cleanOld).catch(err => { + logger.warn(`[247] Failed to rejoin ${cleanOld} after move-away:`, err.message); + }); + }, rejoinDelay); + } else if (newChannelSaved || newChannelPendingSpawn) { + // New channel is already 24/7 or being spawned — keep both, don't rekey. + logger.voice247( + `[247] Keeping both channels ${cleanOld} and ${cleanNew} ` + + `(saved=${newChannelSaved} pending=${newChannelPendingSpawn})` + ); + } else if (existingPlayer && cleanNew !== cleanOld) { + // Neither channel is 24/7 — safe to rekey the player. + const targetChannel = client.channels.get(cleanNew) + ?? client.channels.get?.(cleanNew) + ?? null; + const targetGuildId = cleanId(targetChannel?.guildId ?? targetChannel?.guild?.id ?? guildId ?? ""); + + const playerAtNewKey = remix.players.playerMap.get(cleanNew); + if (!playerAtNewKey || playerAtNewKey === existingPlayer) { + remix.players.playerMap.delete(cleanOld); + remix.players.playerMap.set(cleanNew, existingPlayer); + existingPlayer._channelId = cleanNew; + existingPlayer._home247Channel = cleanNew; + if (targetGuildId) existingPlayer._guildId = targetGuildId; + logger.voice247(`[247] Re-keyed playerMap ${cleanOld} → ${cleanNew}`); + } else { + logger.voice247( + `[247] Skipped re-key ${cleanOld} → ${cleanNew} (new key occupied by another player)` + ); + } + } + + // Simplified 24/7: stay_247 list only changes via !247 command. + // Do NOT auto-add/remove channels on bot move. + } catch (e) { + logger.warn("[247] Bot move handler failed:", e.message); + } + } + + + if (!newChannelId && oldChannelId && guildId) { + try { + const cleanOld = cleanId(oldChannelId); + const cleanGuild = cleanId(guildId); + + if (this._inStartupGrace) { + const bootPlayer = remix.players.playerMap.get(cleanOld); + if (bootPlayer && !bootPlayer._destroyed) { + logger.voiceState( + `[VoiceState] Bot disconnected from ${cleanOld} during startup grace — ` + + `player still active, ignoring stale disconnect.` + ); + } else { + logger.voiceState( + `[VoiceState] Bot disconnected from ${cleanOld} during startup grace — ` + + `deferring until grace period ends.` + ); + } + return; + } + + if (remix.intentionalLeaves.has(cleanOld)) { + logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — intentional leave.`); + } else if (this._isGuildMoveInProgress(cleanGuild, cleanOld)) { + logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — guild move in progress, skipping.`); + } else if (this._bootRecoveryActive) { + logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — boot recovery active, skipping.`); + } else { + const set = remix.settingsMgr.getServer(guildId); + const mode = set ? get247ChannelMode(set, cleanOld) : "off"; + const wsInduced = this.isWsReconnectRecent(); + + if (mode === "on" || wsInduced) { + const reason = wsInduced && mode !== "on" + ? `WS reconnect detected (${Math.round((Date.now() - this._lastReadyAt) / 1000)}s ago) — treating as transient, scheduling rejoin` + : `24/7 mode — scheduling rejoin`; + logger.voice247( + `[VoiceState] Bot unexpectedly disconnected from ${cleanOld} — ${reason}.` + ); + const discPlayer = remix.players.playerMap.get(cleanOld); + if (discPlayer && !discPlayer._destroyed) { + remix.players.playerMap.delete(cleanOld); + const homeChannel = cleanId(discPlayer._home247Channel ?? ""); + if (homeChannel && homeChannel !== cleanOld) { + remix.players.playerMap.delete(homeChannel); + } + try { discPlayer.destroy(); } catch(e) { logger.warn("[VoiceState] Player destroy failed:", e?.message); } + const pendingScrobble = remix.players._pendingScrobbleTimers?.get(cleanOld); + if (pendingScrobble) { + clearTimeout(pendingScrobble.timer); + remix.players._pendingScrobbleTimers.delete(cleanOld); + } + } + const rejoinDelay = this.T.rejoin247Delay ?? 3_000; + setTimeout(() => { + this._rejoinChannel(cleanGuild, cleanOld).catch(err => { + logger.warn(`[VoiceState] Failed to rejoin ${cleanOld} after disconnect:`, err.message); + }); + }, rejoinDelay); + } else { + const leavePlayer = remix.players.playerMap.get(cleanOld); + if (leavePlayer && !leavePlayer.leaving && !leavePlayer._destroyed) { + logger.voiceState( + `[VoiceState] Bot disconnected from ${cleanOld} (24/7 mode: ${mode}) — emitting autoleave.` + ); + leavePlayer.emit("autoleave"); + } + } + } + } catch (e) { + logger.warn("[VoiceState] Bot disconnect handler failed:", e.message); + } + } + }, +}; + +export default VoiceStateRouting; +export { VoiceStateRouting }; diff --git a/src/voice/gateway/index.mjs b/src/voice/gateway/index.mjs new file mode 100644 index 0000000..605d145 --- /dev/null +++ b/src/voice/gateway/index.mjs @@ -0,0 +1,8 @@ +/** + * @module src/voice/gateway + * @description Barrel for the gateway layer: re-exports the GatewayHandler + * base class with its applied mixins (VoiceStateRouting, GuildSync, + * RejoinManager). + */ + +export { GatewayHandler } from "./GatewayHandler.mjs"; diff --git a/storage/locales/bot/ar-SA.json b/storage/locales/bot/ar-SA.json index 18b67c2..99a9f07 100644 --- a/storage/locales/bot/ar-SA.json +++ b/storage/locales/bot/ar-SA.json @@ -565,6 +565,7 @@ "scrobbles": "🎵 **اسكروبلات**", "linkedUsers": "🔗 **حسابات Last.fm**", "ping": "🏓 **البينغ**", + "gateway": "🌐 **البوابة**", "uptime": "⏱️ **وقت التشغيل**", "build": "🔧 **الإصدار**", "lastRestart": "🪛 **آخر إعادة تشغيل**", diff --git a/storage/locales/bot/ckb.json b/storage/locales/bot/ckb.json index 36264d0..8e7e19f 100644 --- a/storage/locales/bot/ckb.json +++ b/storage/locales/bot/ckb.json @@ -565,6 +565,7 @@ "scrobbles": "🎵 **سکرۆبلەکان**", "linkedUsers": "🔗 **هەژمارەکانی Last.fm**", "ping": "🏓 **پینگ**", + "gateway": "🌐 **گەیتوەی**", "uptime": "⏱️ **کاتی چالاک**", "build": "🔧 **بەرنامە**", "lastRestart": "🪛 **دوایین دەستپێکردنەوە**", diff --git a/storage/locales/bot/de-DE.json b/storage/locales/bot/de-DE.json index f742690..e0bc8e1 100644 --- a/storage/locales/bot/de-DE.json +++ b/storage/locales/bot/de-DE.json @@ -565,6 +565,7 @@ "scrobbles": "🎵 **Scrobbles**", "linkedUsers": "🔗 **Verknüpfte Last.fm**", "ping": "🏓 **Ping**", + "gateway": "🌐 **Gateway**", "uptime": "⏱️ **Uptime**", "build": "🔧 **Build**", "lastRestart": "🪛 **Letzter Neustart**", diff --git a/storage/locales/bot/en.json b/storage/locales/bot/en.json index 6ec82ab..1502846 100644 --- a/storage/locales/bot/en.json +++ b/storage/locales/bot/en.json @@ -673,6 +673,7 @@ "scrobbles": "🎵 **Scrobbles**", "linkedUsers": "🔗 **Linked Last.fm**", "ping": "🏓 **Ping**", + "gateway": "🌐 **Gateway**", "uptime": "⏱️ **Uptime**", "build": "🔧 **Build**", "lastRestart": "🪛 **Last restart**", diff --git a/storage/locales/bot/pt-BR.json b/storage/locales/bot/pt-BR.json index 80a9822..b9e261d 100644 --- a/storage/locales/bot/pt-BR.json +++ b/storage/locales/bot/pt-BR.json @@ -565,6 +565,7 @@ "scrobbles": "🎵 **Scrobbles**", "linkedUsers": "🔗 **Last.fm Vinculadas**", "ping": "🏓 **Ping**", + "gateway": "🌐 **Gateway**", "uptime": "⏱️ **Tempo de Atividade**", "build": "🔧 **Build**", "lastRestart": "🪛 **Último Reinício**", diff --git a/storage/locales/bot/tr.json b/storage/locales/bot/tr.json index 99fd3b9..921a8fb 100644 --- a/storage/locales/bot/tr.json +++ b/storage/locales/bot/tr.json @@ -662,6 +662,7 @@ "scrobbles": "🎵 **Scrobble'lar**", "linkedUsers": "🔗 **Bağlı Last.fm**", "ping": "🏓 **Ping**", + "gateway": "🌐 **Gateway**", "uptime": "⏱️ **Çalışma Süresi**", "build": "🔧 **Yapı**", "lastRestart": "🪛 **Son yeniden başlatma**",