From 3ea4ac660ee5d0de57ec7743930d8db0bcf350c2 Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Thu, 7 May 2026 22:52:16 +0300 Subject: [PATCH] test --- index.mjs | 8 ++ package.json | 3 +- src/GatewayHandler.mjs | 28 +++-- src/PlayerManager.mjs | 165 ++++++++++++++++++++++-------- src/dashboard/Dashboard.mjs | 151 +++++++++++++++++++++------ src/dashboard/DatabaseManager.mjs | 66 ++++++++++++ 6 files changed, 338 insertions(+), 83 deletions(-) create mode 100644 src/dashboard/DatabaseManager.mjs diff --git a/index.mjs b/index.mjs index ca10b83..3e5a5c8 100644 --- a/index.mjs +++ b/index.mjs @@ -46,6 +46,7 @@ export class Remix { this.dashboard = new Dashboard(this, { enabled: config.dashboard?.enabled, redis: config.dashboard?.redis, + mysql: config.mysql, }); const presenceContents = config.presenceContents ?? []; @@ -657,6 +658,13 @@ const saveAndExit = async () => { } catch (e) { logger.error("[Shutdown] Failed to close Redis:", e.message); } + try { + if (remix.dashboard?.db?.close) { + await remix.dashboard.db.close(); + } + } catch (e) { + logger.error("[Shutdown] Failed to close Dashboard DB:", e.message); + } process.exit(0); }; diff --git a/package.json b/package.json index 019d853..571c6c3 100644 --- a/package.json +++ b/package.json @@ -7,6 +7,7 @@ "@fluxerjs/core": "^1.3.1", "@fluxerjs/voice": "^1.3.1", "@livekit/rtc-node": "^0.13.27", + "bcryptjs": "^3.0.3", "express": "^5.2.1", "ffmpeg-static": "^5.3.0", "ffprobe-static": "^3.1.0", @@ -25,4 +26,4 @@ "defaultsSync": "node index.mjs sreload", "migrate": "node settings/migrate.mjs" } -} \ No newline at end of file +} diff --git a/src/GatewayHandler.mjs b/src/GatewayHandler.mjs index 0653cbc..0f691e2 100644 --- a/src/GatewayHandler.mjs +++ b/src/GatewayHandler.mjs @@ -507,9 +507,9 @@ export class GatewayHandler { try { await client.users.fetch(userId).catch(() => {}); } catch (_) {} } if (userObj) { + // Send user update on the global :users channel const details = { - event: "voiceStateUpdate", - userId, + type: channelId ? "join" : "leave", guildId: resolvedGuildId, channelId: channelId ?? null, oldChannelId: oldChannelId ?? null, @@ -517,19 +517,25 @@ export class GatewayHandler { remix.dashboard.updateUser(details, userObj); } + // Send per-player channel events for join/leave const refChannel = channelId ?? oldChannelId; - const cleanId = refChannel ? String(refChannel).replace(/\D/g, "") : null; + const cleanId_ref = refChannel ? String(refChannel).replace(/\D/g, "") : null; - if (cleanId) { - const player = remix.players.playerMap.get(cleanId); + if (cleanId_ref) { + const player = remix.players.playerMap.get(cleanId_ref); if (player) { + // Send "join" or "leave" on the per-player channel + // (matching Stoat format: { type, data } where data = userId) + const eventType = channelId ? "join" : "leave"; remix.dashboard.updatePlayer({ - guildId: player._guildId, - channelId: player._channelId, - playing: player.playing ?? false, - paused: player.paused ?? false, - queueLength: player.queue?.length ?? 0, - }); + type: eventType, + data: userId, + }, player); + + // Also update the global players channel with current player state + remix.dashboard.playerUpdate({ + type: eventType, + }, player); } } } catch (_) {} diff --git a/src/PlayerManager.mjs b/src/PlayerManager.mjs index 003a944..7cfc261 100644 --- a/src/PlayerManager.mjs +++ b/src/PlayerManager.mjs @@ -14,6 +14,7 @@ import { logger } from "./constants/Logger.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getVoiceManager } from "@fluxerjs/voice"; import { getGlobalColor } from "./MessageHandler.mjs"; +import { Dashboard } from "./dashboard/Dashboard.mjs"; /** Helper — build a plain embed payload from a description string */ function mkEmbed(desc) { @@ -114,8 +115,14 @@ export class PlayerManager { /** * Forward player lifecycle/state events to the dashboard pub/sub channels. - * This keeps the event bridge in one place so both regular joins and - * background-spawned players can reuse it. + * + * IMPORTANT: Events are sent in Stoat-compatible { type, data } format so + * the backend (backend-master) PlayerManager can parse them correctly. + * + * Two channels are used: + * {platform}:players — global, for init/close lifecycle events + * {platform}:player_{id} — per-player, for playback/queue/volume events + * * @param {Player} player * @param {Object} [context] * @param {string|null} [context.channelId] @@ -132,23 +139,35 @@ export class PlayerManager { writable: true, }); - const sendDashboardUpdate = (event, details = {}) => { + // ── Per-player channel: Stoat-compatible { type, data } format ──────── + // The backend PlayerManager.setupEvents() expects: + // { type: "startplay", data: serialisedVideo } + // { type: "stopplay", data: null } + // { type: "pause", data: { elapsedTime: ms } } + // { type: "resume", data: { elapsedTime: ms } } + // { type: "volume", data: number } + // { type: "queue", data: serialisedQueueEvent } + // { type: "join", data: userId } + // { type: "leave", data: userId } + + const emit = (type, data) => { if (!this.dashboard?.enabled) return; + this.dashboard.updatePlayer({ type, data }, player); + }; - const payload = { - event, - guildId: cleanId(player._guildId ?? context.guildId), - channelId: getPlayerChannelId(player, context.channelId), - ...details, - }; + // ── Global channel: lifecycle events ────────────────────────────────── + // The backend PlayerManager.initChannels() expects: + // { type: "init", player: serialisedPlayer } — when player connects + // { type: "close", player: serialisedPlayer } — when player disconnects - this.dashboard.playerUpdate(payload, player); - this.dashboard.updatePlayer(payload, player); + const emitGlobal = (type) => { + if (!this.dashboard?.enabled) return; + this.dashboard.playerUpdate({ type }, player); }; // Broadcast user list changes to the global :users channel when // someone joins or leaves the player's voice channel. - const sendUserUpdates = (event) => { + const sendUserUpdates = (eventType) => { if (!this.dashboard?.enabled) return; const channelId = getPlayerChannelId(player, context.channelId); const channel = player.client?.channels?.get(channelId); @@ -167,71 +186,135 @@ export class PlayerManager { if (stateChannelId !== channelId) continue; const member = guild.members?.get?.(state.userId ?? state.user_id); if (!member?.user || member.user?.bot) continue; - const details = { - event, + // Send per-player channel "join"/"leave" event with just the user ID + // (matching Stoat format where data = userId string) + emit(eventType, member.user.id); + // Also send global user update + this.dashboard.userUpdate({ + type: eventType, guildId: cleanId(player._guildId ?? context.guildId), channelId, - }; - this.dashboard.userUpdate(details, member.user); + }, member.user); } }; + // ── Player event handlers ───────────────────────────────────────────── + player.on("roomfetched", () => { - sendDashboardUpdate("roomfetched", { state: "connected" }); - sendUserUpdates("roomfetched"); + // Player connected — send "init" on the global channel + emitGlobal("init"); + sendUserUpdates("join"); }); - player.on("startplay", () => { - sendDashboardUpdate("startplay", { state: "playing" }); + player.on("startplay", (song) => { + // Send the serialised video to the per-player channel + emit("startplay", Dashboard.convertVideo(song ?? player.queue?.current)); + // Also broadcast on global channel for full state update + this.dashboard.playerUpdate({ type: "startplay" }, player); }); player.on("stopplay", () => { - sendDashboardUpdate("stopplay", { state: "idle" }); + emit("stopplay", null); + this.dashboard.playerUpdate({ type: "stopplay" }, player); }); player.on("playback", (playing) => { - sendDashboardUpdate("playback", { - state: playing ? "playing" : "paused", - playing: !!playing, - }); + // Stoat sends "pause" or "resume" with { elapsedTime } — match that + 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) => { - sendDashboardUpdate("volume", { volume }); + emit("volume", volume); + this.dashboard.playerUpdate({ type: "volume" }, player); }); player.on("filter", (filter) => { - sendDashboardUpdate("filter", { filter }); + // Filter events are Fluxer-specific — no Stoat equivalent. + // Send as a custom event type; the backend will ignore unknown types. + emit("filter", filter); }); player.on("update", (scope) => { - sendDashboardUpdate("update", { scope }); + // Generic update — send full player state on global channel + this.dashboard.playerUpdate({ type: "update" }, player); }); player.on("message", (message) => { - sendDashboardUpdate("message", { - message: typeof message === "string" ? message : null, - }); + // No Stoat equivalent — skip per-player, only global broadcast }); player.on("autoleave", () => { - sendUserUpdates("autoleave"); - sendDashboardUpdate("autoleave", { - state: "disconnected", - reason: "inactivity", - }); + sendUserUpdates("leave"); + // Send "close" on global channel so backend removes the player + emitGlobal("close"); + emit("stopplay", null); }); player.on("leave", () => { sendUserUpdates("leave"); - sendDashboardUpdate("leave", { - state: "disconnected", - reason: "manual", - }); + // Send "close" on global channel so backend removes the player + emitGlobal("close"); + emit("stopplay", null); }); + // ── Queue event handler ─────────────────────────────────────────────── + // Queue events must be serialised with Dashboard.convertVideo() to match + // the format the backend Queue.update() method expects. + player.queue?.on("queue", (queueEvent) => { - sendDashboardUpdate("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: + // Unknown queue event — pass through as-is + serialised.data = queueEvent.data; + break; + } + + emit("queue", serialised); + this.dashboard.playerUpdate({ type: "queue" }, player); }); return player; diff --git a/src/dashboard/Dashboard.mjs b/src/dashboard/Dashboard.mjs index 1a92b7e..a2ee77c 100644 --- a/src/dashboard/Dashboard.mjs +++ b/src/dashboard/Dashboard.mjs @@ -1,17 +1,20 @@ import { CommandBuilder, CommandHandler, Option } from "../CommandHandler.mjs"; import Player from "../Player.mjs"; import { Utils } from "../Utils.mjs"; +import { DatabaseManager } from "./DatabaseManager.mjs"; import { RedisHandler } from "./RedisHandler.mjs"; import { logger } from "../constants/Logger.mjs"; export class Dashboard { enabled = false; + expiryTime = 1000 * 60 * 60 * 6; // 6 hours — login code expiry /** * @param {Remix} remix * @param {Object} opts * @param {boolean} opts.enabled Whether the Dashboard is enabled and connections should be attempted * @param {Object} opts.redis Connection options passed directly to redis createClient + * @param {Object} [opts.mysql] MySQL connection config for login code verification */ constructor(remix, opts) { this.enabled = opts?.enabled; @@ -19,6 +22,12 @@ export class Dashboard { if (!this.enabled) return this; + // DatabaseManager for login code verification (optional — only needed if + // the backend uses the bot-based login flow instead of Fluxer OAuth2) + if (opts.mysql) { + this.db = new DatabaseManager(opts.mysql); + } + this.redis = new RedisHandler(opts.redis); this.redis.setRequestHandler(async (data) => { switch (data.type) { @@ -104,7 +113,6 @@ export class Dashboard { if (authErr) return { error: authErr }; if (this.remix.players.playerMap.has(voiceChannel.id)) return { message: "Already Connected" }; // Build a minimal fake message that satisfies PlayerManager.initPlayer(). - // initPlayer calls message.reply() for status updates (joining, errors). const fakeMsg = { channel: { channel: textChannel, guildId: voiceChannel.guildId }, message: { guildId: voiceChannel.guildId }, @@ -168,7 +176,7 @@ export class Dashboard { player.playRadio(radio); return { message: "Adding radio station" }; } - // Sanitize: reject obviously malicious patterns (JavaScript URLs, data URIs) + // Sanitize: reject obviously malicious patterns if (/^(javascript|data|vbscript):/i.test(query.trim())) { return { error: "Invalid query protocol" }; } @@ -189,31 +197,24 @@ export class Dashboard { /** * Check if a user is a bot owner, or is in the same voice channel as the player. - * Bot owners are always allowed. Otherwise the user must be physically in the - * player's voice channel to control it. - * * @param {import("@fluxerjs/core").User|null} user * @param {Player} player * @returns {string|null} Error message, or null if authorized */ _authorizePlayerControl(user, player) { - // Bot owners bypass all checks if (user && this.remix.handler?.owners?.includes?.(user.id)) return null; - if (!user) return "User not provided"; const cleanUserId = String(user.id).replace(/\D/g, ""); const cleanChanId = String(player._channelId ?? "").replace(/\D/g, ""); if (!cleanChanId) return "Player has no active channel"; - // Check observed voice users — the authoritative voice state map. - // Map key is userId, value is { channelId, guildId }. const observed = this.remix.observedVoiceUsers; if (observed) { for (const [mapUserId, info] of observed) { if (String(mapUserId).replace(/\D/g, "") === cleanUserId) { const infoChannelId = String(info.channelId ?? "").replace(/\D/g, ""); - if (infoChannelId === cleanChanId) return null; // authorized + if (infoChannelId === cleanChanId) return null; } } } @@ -223,8 +224,6 @@ export class Dashboard { /** * Verify the user has permission to perform an action in the target guild. - * Bot owners are always allowed. Otherwise the user must be a member of the guild. - * * @param {import("@fluxerjs/core").User} user * @param {string} guildId * @returns {Promise} Error message, or null if authorized @@ -258,17 +257,8 @@ export class Dashboard { // ── Static converters ───────────────────────────────────────────────────── - /** - * @typedef APIUser - * @property {string} id - * @property {string} username - * @property {string} displayName - * @property {Object} avatar - * @property {string} avatar.url - */ /** * @param {import("@fluxerjs/core").User} user - * @returns {APIUser} */ static convertUser(user) { return { @@ -310,7 +300,6 @@ export class Dashboard { */ static convertChannel(channel) { const isVoice = channel.isVoiceBased?.() ?? false; - // Collect voice members for voice channels let voiceParticipants = []; if (isVoice) { const guild = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId); @@ -366,8 +355,6 @@ export class Dashboard { /** * Lightweight server summary for player payloads. - * Unlike convertServer(), this omits the full channels array to keep - * per-player Redis messages small (especially for large guilds). * @param {import("@fluxerjs/core").Guild} guild */ static convertServerSummary(guild) { @@ -457,21 +444,68 @@ export class Dashboard { }; } - // ── Pub/Sub broadcast helpers ───────────────────────────────────────────── + // ═══════════════════════════════════════════════════════════════════════════ + // Pub/Sub broadcast helpers + // + // CRITICAL: The backend (backend-master) expects Stoat-compatible message + // formats on both the global :players channel and the per-player + // :player_{channelId} channel. The formats are: + // + // Global (:players): + // { type: "init", player: serialisedPlayer } — when bot joins a VC + // { type: "close", player: serialisedPlayer } — when bot leaves a VC + // + // Per-player (:player_{channelId}): + // { type: "startplay", data: serialisedVideo } + // { type: "streamStartPlay", data: timestamp } + // { type: "stopplay", data: null } + // { type: "pause", data: { elapsedTime: ms } } + // { type: "resume", data: { elapsedTime: ms } } + // { type: "volume", data: number } + // { type: "queue", data: serialisedQueueEvent } + // { type: "join", data: userId } + // { type: "leave", data: userId } + // ═══════════════════════════════════════════════════════════════════════════ // Debounce map for playerUpdate — prevents flooding Redis with rapid updates. _playerUpdateTimers = new Map(); /** - * Global player update (broadcast to all dashboard listeners) + * Global player update (broadcast to all dashboard listeners on {platform}:players). + * + * Used for two purposes: + * 1. Lifecycle events: { type: "init" } / { type: "close" } — the backend + * PlayerManager uses these to add/remove Player objects. + * 2. Full state broadcast: any other type — the full serialised player is + * included so dashboard frontends can update their UI. + * * Debounced: rapid successive calls for the same player are coalesced * into a single publish every 500ms. - * @param {Object} details + * + * @param {Object} details Must include a `type` field (e.g. "init", "close", + * "startplay", "stopplay", etc.) and may include a `data` field. * @param {Player} player */ playerUpdate(details, player) { if (!this.enabled) return; const key = player._channelId ?? player._guildId ?? "unknown"; + + // For "init" and "close" events, send immediately (no debounce) — the + // backend relies on these for player lifecycle management. + if (details.type === "init" || details.type === "close") { + try { + const serialised = Dashboard.convertPlayer(player); + this.redis.send(this.redis.platform + ":players", JSON.stringify({ + type: details.type, + player: serialised, + })); + } catch (e) { + logger.dashboard("[Dashboard] playerUpdate error:", e.message); + } + return; + } + + // All other events are debounced to avoid flooding Redis. if (this._playerUpdateTimers.has(key)) { clearTimeout(this._playerUpdateTimers.get(key)); } @@ -490,8 +524,19 @@ export class Dashboard { } /** - * Per-player channel update - * @param {Object} details + * Per-player channel update (sent to {platform}:player_{channelId}). + * + * The backend PlayerManager.setupEvents() expects messages in the format: + * { type: "", data: } + * + * This method accepts details in that Stoat-compatible format directly. + * + * @param {Object} details Must include `type` and optionally `data`. + * Examples: + * { type: "startplay", data: convertVideo(song) } + * { type: "pause", data: { elapsedTime: 12345 } } + * { type: "queue", data: serialisedQueueEvent } + * { type: "join", data: userId } * @param {Player} player */ updatePlayer(details, player) { @@ -501,7 +546,7 @@ export class Dashboard { } /** - * Global user update + * Global user update (sent to {platform}:users). * @param {Object} details * @param {import("@fluxerjs/core").User} user */ @@ -514,9 +559,55 @@ export class Dashboard { })); } + /** + * Per-user channel update (sent to {platform}:user_{userId}). + * @param {Object} details + * @param {import("@fluxerjs/core").User} user + */ updateUser(details, user) { if (!this.enabled) return; const channel = this.redis.platform + ":user_" + user.id; this.redis.send(channel, JSON.stringify(details)); } + + // ═══════════════════════════════════════════════════════════════════════════ + // Login Confirmation (for backend-based DM code verification flow) + // ═══════════════════════════════════════════════════════════════════════════ + + /** + * Verify a login code submitted by a user via DM. + * The backend stores the code in MySQL; this method compares the supplied + * code against the stored (bcrypt-hashed) value. + * + * @param {string} user User ID + * @param {string} code Plain-text code supplied by the user + * @returns {Promise} null on success, error message on failure + */ + 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=?", [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 (await this.db.compareHash(code, res[i].token)) { + if (Date.now() - this.expiryTime > (new Date(res[i].createdAt)).getTime()) { + return "Login token expired"; + } + await this.db.execute("UPDATE login_codes SET verified=true WHERE id=?", [res[i].id]); + return null; // success + } + } + + return "Invalid code."; + } } diff --git a/src/dashboard/DatabaseManager.mjs b/src/dashboard/DatabaseManager.mjs new file mode 100644 index 0000000..75d5d59 --- /dev/null +++ b/src/dashboard/DatabaseManager.mjs @@ -0,0 +1,66 @@ +import { compare, genSalt, hash } from "bcryptjs"; +import { createPool } from "mysql2/promise"; + +/** + * DatabaseManager — MySQL pool for dashboard login codes and API tokens. + * Adapted from the Stoat version for use with the Fluxer bot. + */ +export class DatabaseManager { + /** + * @param {import("mysql2/promise").PoolOptions} config + */ + constructor(config) { + this.db = createPool({ + connectionLimit: 15, + ...config, + }); + } + + /** + * Execute a raw SQL query. + * @param {string} query + * @returns {Promise<[import("mysql2/promise").QueryResult, import("mysql2/promise").FieldPacket[]]>} + */ + async query(query) { + return this.db.query(query); + } + + /** + * Execute a parameterized SQL query. + * @param {string} query + * @param {any[]} [data] + * @returns {Promise} + */ + async execute(query, data) { + const [res, _fields] = await this.db.execute(query, data); + return res; + } + + /** + * Hash a plaintext string using bcrypt. + * @param {string} plain + * @returns {Promise} + */ + async hash(plain) { + const salt = await genSalt(10); + return hash(plain, salt); + } + + /** + * Compare a plaintext string against a bcrypt hash. + * @param {string} plain + * @param {string} hashed + * @returns {Promise} + */ + async compareHash(plain, hashed) { + return await compare(plain, hashed); + } + + /** + * Gracefully close the connection pool. + * @returns {Promise} + */ + close() { + return this.db.end(); + } +}