mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
test
This commit is contained in:
1 parent
87f099cc6e
commit
3ea4ac660e
6 files changed
+337
-82
No files matched your search
@@ -46,6 +46,7 @@ export class Remix {
|
|||||||
this.dashboard = new Dashboard(this, {
|
this.dashboard = new Dashboard(this, {
|
||||||
enabled: config.dashboard?.enabled,
|
enabled: config.dashboard?.enabled,
|
||||||
redis: config.dashboard?.redis,
|
redis: config.dashboard?.redis,
|
||||||
|
mysql: config.mysql,
|
||||||
});
|
});
|
||||||
|
|
||||||
const presenceContents = config.presenceContents ?? [];
|
const presenceContents = config.presenceContents ?? [];
|
||||||
@@ -657,6 +658,13 @@ const saveAndExit = async () => {
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.error("[Shutdown] Failed to close Redis:", e.message);
|
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);
|
process.exit(0);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -7,6 +7,7 @@
|
|||||||
"@fluxerjs/core": "^1.3.1",
|
"@fluxerjs/core": "^1.3.1",
|
||||||
"@fluxerjs/voice": "^1.3.1",
|
"@fluxerjs/voice": "^1.3.1",
|
||||||
"@livekit/rtc-node": "^0.13.27",
|
"@livekit/rtc-node": "^0.13.27",
|
||||||
|
"bcryptjs": "^3.0.3",
|
||||||
"express": "^5.2.1",
|
"express": "^5.2.1",
|
||||||
"ffmpeg-static": "^5.3.0",
|
"ffmpeg-static": "^5.3.0",
|
||||||
"ffprobe-static": "^3.1.0",
|
"ffprobe-static": "^3.1.0",
|
||||||
|
|||||||
+17
-11
@@ -507,9 +507,9 @@ export class GatewayHandler {
|
|||||||
try { await client.users.fetch(userId).catch(() => {}); } catch (_) {}
|
try { await client.users.fetch(userId).catch(() => {}); } catch (_) {}
|
||||||
}
|
}
|
||||||
if (userObj) {
|
if (userObj) {
|
||||||
|
// Send user update on the global :users channel
|
||||||
const details = {
|
const details = {
|
||||||
event: "voiceStateUpdate",
|
type: channelId ? "join" : "leave",
|
||||||
userId,
|
|
||||||
guildId: resolvedGuildId,
|
guildId: resolvedGuildId,
|
||||||
channelId: channelId ?? null,
|
channelId: channelId ?? null,
|
||||||
oldChannelId: oldChannelId ?? null,
|
oldChannelId: oldChannelId ?? null,
|
||||||
@@ -517,19 +517,25 @@ export class GatewayHandler {
|
|||||||
remix.dashboard.updateUser(details, userObj);
|
remix.dashboard.updateUser(details, userObj);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Send per-player channel events for join/leave
|
||||||
const refChannel = channelId ?? oldChannelId;
|
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) {
|
if (cleanId_ref) {
|
||||||
const player = remix.players.playerMap.get(cleanId);
|
const player = remix.players.playerMap.get(cleanId_ref);
|
||||||
if (player) {
|
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({
|
remix.dashboard.updatePlayer({
|
||||||
guildId: player._guildId,
|
type: eventType,
|
||||||
channelId: player._channelId,
|
data: userId,
|
||||||
playing: player.playing ?? false,
|
}, player);
|
||||||
paused: player.paused ?? false,
|
|
||||||
queueLength: player.queue?.length ?? 0,
|
// Also update the global players channel with current player state
|
||||||
});
|
remix.dashboard.playerUpdate({
|
||||||
|
type: eventType,
|
||||||
|
}, player);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
|
|||||||
+124
-41
@@ -14,6 +14,7 @@ import { logger } from "./constants/Logger.mjs";
|
|||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
import { getVoiceManager } from "@fluxerjs/voice";
|
import { getVoiceManager } from "@fluxerjs/voice";
|
||||||
import { getGlobalColor } from "./MessageHandler.mjs";
|
import { getGlobalColor } from "./MessageHandler.mjs";
|
||||||
|
import { Dashboard } from "./dashboard/Dashboard.mjs";
|
||||||
|
|
||||||
/** Helper — build a plain embed payload from a description string */
|
/** Helper — build a plain embed payload from a description string */
|
||||||
function mkEmbed(desc) {
|
function mkEmbed(desc) {
|
||||||
@@ -114,8 +115,14 @@ export class PlayerManager {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Forward player lifecycle/state events to the dashboard pub/sub channels.
|
* 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 {Player} player
|
||||||
* @param {Object} [context]
|
* @param {Object} [context]
|
||||||
* @param {string|null} [context.channelId]
|
* @param {string|null} [context.channelId]
|
||||||
@@ -132,23 +139,35 @@ export class PlayerManager {
|
|||||||
writable: true,
|
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;
|
if (!this.dashboard?.enabled) return;
|
||||||
|
this.dashboard.updatePlayer({ type, data }, player);
|
||||||
|
};
|
||||||
|
|
||||||
const payload = {
|
// ── Global channel: lifecycle events ──────────────────────────────────
|
||||||
event,
|
// The backend PlayerManager.initChannels() expects:
|
||||||
guildId: cleanId(player._guildId ?? context.guildId),
|
// { type: "init", player: serialisedPlayer } — when player connects
|
||||||
channelId: getPlayerChannelId(player, context.channelId),
|
// { type: "close", player: serialisedPlayer } — when player disconnects
|
||||||
...details,
|
|
||||||
};
|
|
||||||
|
|
||||||
this.dashboard.playerUpdate(payload, player);
|
const emitGlobal = (type) => {
|
||||||
this.dashboard.updatePlayer(payload, player);
|
if (!this.dashboard?.enabled) return;
|
||||||
|
this.dashboard.playerUpdate({ type }, player);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Broadcast user list changes to the global :users channel when
|
// Broadcast user list changes to the global :users channel when
|
||||||
// someone joins or leaves the player's voice channel.
|
// someone joins or leaves the player's voice channel.
|
||||||
const sendUserUpdates = (event) => {
|
const sendUserUpdates = (eventType) => {
|
||||||
if (!this.dashboard?.enabled) return;
|
if (!this.dashboard?.enabled) return;
|
||||||
const channelId = getPlayerChannelId(player, context.channelId);
|
const channelId = getPlayerChannelId(player, context.channelId);
|
||||||
const channel = player.client?.channels?.get(channelId);
|
const channel = player.client?.channels?.get(channelId);
|
||||||
@@ -167,71 +186,135 @@ export class PlayerManager {
|
|||||||
if (stateChannelId !== channelId) continue;
|
if (stateChannelId !== channelId) continue;
|
||||||
const member = guild.members?.get?.(state.userId ?? state.user_id);
|
const member = guild.members?.get?.(state.userId ?? state.user_id);
|
||||||
if (!member?.user || member.user?.bot) continue;
|
if (!member?.user || member.user?.bot) continue;
|
||||||
const details = {
|
// Send per-player channel "join"/"leave" event with just the user ID
|
||||||
event,
|
// (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),
|
guildId: cleanId(player._guildId ?? context.guildId),
|
||||||
channelId,
|
channelId,
|
||||||
};
|
}, member.user);
|
||||||
this.dashboard.userUpdate(details, member.user);
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// ── Player event handlers ─────────────────────────────────────────────
|
||||||
|
|
||||||
player.on("roomfetched", () => {
|
player.on("roomfetched", () => {
|
||||||
sendDashboardUpdate("roomfetched", { state: "connected" });
|
// Player connected — send "init" on the global channel
|
||||||
sendUserUpdates("roomfetched");
|
emitGlobal("init");
|
||||||
|
sendUserUpdates("join");
|
||||||
});
|
});
|
||||||
|
|
||||||
player.on("startplay", () => {
|
player.on("startplay", (song) => {
|
||||||
sendDashboardUpdate("startplay", { state: "playing" });
|
// 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", () => {
|
player.on("stopplay", () => {
|
||||||
sendDashboardUpdate("stopplay", { state: "idle" });
|
emit("stopplay", null);
|
||||||
|
this.dashboard.playerUpdate({ type: "stopplay" }, player);
|
||||||
});
|
});
|
||||||
|
|
||||||
player.on("playback", (playing) => {
|
player.on("playback", (playing) => {
|
||||||
sendDashboardUpdate("playback", {
|
// Stoat sends "pause" or "resume" with { elapsedTime } — match that
|
||||||
state: playing ? "playing" : "paused",
|
const elapsedMs = player._pausedAt
|
||||||
playing: !!playing,
|
? (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) => {
|
player.on("volume", (volume) => {
|
||||||
sendDashboardUpdate("volume", { volume });
|
emit("volume", volume);
|
||||||
|
this.dashboard.playerUpdate({ type: "volume" }, player);
|
||||||
});
|
});
|
||||||
|
|
||||||
player.on("filter", (filter) => {
|
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) => {
|
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) => {
|
player.on("message", (message) => {
|
||||||
sendDashboardUpdate("message", {
|
// No Stoat equivalent — skip per-player, only global broadcast
|
||||||
message: typeof message === "string" ? message : null,
|
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
player.on("autoleave", () => {
|
player.on("autoleave", () => {
|
||||||
sendUserUpdates("autoleave");
|
sendUserUpdates("leave");
|
||||||
sendDashboardUpdate("autoleave", {
|
// Send "close" on global channel so backend removes the player
|
||||||
state: "disconnected",
|
emitGlobal("close");
|
||||||
reason: "inactivity",
|
emit("stopplay", null);
|
||||||
});
|
|
||||||
});
|
});
|
||||||
|
|
||||||
player.on("leave", () => {
|
player.on("leave", () => {
|
||||||
sendUserUpdates("leave");
|
sendUserUpdates("leave");
|
||||||
sendDashboardUpdate("leave", {
|
// Send "close" on global channel so backend removes the player
|
||||||
state: "disconnected",
|
emitGlobal("close");
|
||||||
reason: "manual",
|
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) => {
|
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;
|
return player;
|
||||||
|
|||||||
+121
-30
@@ -1,17 +1,20 @@
|
|||||||
import { CommandBuilder, CommandHandler, Option } from "../CommandHandler.mjs";
|
import { CommandBuilder, CommandHandler, Option } from "../CommandHandler.mjs";
|
||||||
import Player from "../Player.mjs";
|
import Player from "../Player.mjs";
|
||||||
import { Utils } from "../Utils.mjs";
|
import { Utils } from "../Utils.mjs";
|
||||||
|
import { DatabaseManager } from "./DatabaseManager.mjs";
|
||||||
import { RedisHandler } from "./RedisHandler.mjs";
|
import { RedisHandler } from "./RedisHandler.mjs";
|
||||||
import { logger } from "../constants/Logger.mjs";
|
import { logger } from "../constants/Logger.mjs";
|
||||||
|
|
||||||
export class Dashboard {
|
export class Dashboard {
|
||||||
enabled = false;
|
enabled = false;
|
||||||
|
expiryTime = 1000 * 60 * 60 * 6; // 6 hours — login code expiry
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* @param {Remix} remix
|
* @param {Remix} remix
|
||||||
* @param {Object} opts
|
* @param {Object} opts
|
||||||
* @param {boolean} opts.enabled Whether the Dashboard is enabled and connections should be attempted
|
* @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.redis Connection options passed directly to redis createClient
|
||||||
|
* @param {Object} [opts.mysql] MySQL connection config for login code verification
|
||||||
*/
|
*/
|
||||||
constructor(remix, opts) {
|
constructor(remix, opts) {
|
||||||
this.enabled = opts?.enabled;
|
this.enabled = opts?.enabled;
|
||||||
@@ -19,6 +22,12 @@ export class Dashboard {
|
|||||||
|
|
||||||
if (!this.enabled) return this;
|
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 = new RedisHandler(opts.redis);
|
||||||
this.redis.setRequestHandler(async (data) => {
|
this.redis.setRequestHandler(async (data) => {
|
||||||
switch (data.type) {
|
switch (data.type) {
|
||||||
@@ -104,7 +113,6 @@ export class Dashboard {
|
|||||||
if (authErr) return { error: authErr };
|
if (authErr) return { error: authErr };
|
||||||
if (this.remix.players.playerMap.has(voiceChannel.id)) return { message: "Already Connected" };
|
if (this.remix.players.playerMap.has(voiceChannel.id)) return { message: "Already Connected" };
|
||||||
// Build a minimal fake message that satisfies PlayerManager.initPlayer().
|
// Build a minimal fake message that satisfies PlayerManager.initPlayer().
|
||||||
// initPlayer calls message.reply() for status updates (joining, errors).
|
|
||||||
const fakeMsg = {
|
const fakeMsg = {
|
||||||
channel: { channel: textChannel, guildId: voiceChannel.guildId },
|
channel: { channel: textChannel, guildId: voiceChannel.guildId },
|
||||||
message: { guildId: voiceChannel.guildId },
|
message: { guildId: voiceChannel.guildId },
|
||||||
@@ -168,7 +176,7 @@ export class Dashboard {
|
|||||||
player.playRadio(radio);
|
player.playRadio(radio);
|
||||||
return { message: "Adding radio station" };
|
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())) {
|
if (/^(javascript|data|vbscript):/i.test(query.trim())) {
|
||||||
return { error: "Invalid query protocol" };
|
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.
|
* 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 {import("@fluxerjs/core").User|null} user
|
||||||
* @param {Player} player
|
* @param {Player} player
|
||||||
* @returns {string|null} Error message, or null if authorized
|
* @returns {string|null} Error message, or null if authorized
|
||||||
*/
|
*/
|
||||||
_authorizePlayerControl(user, player) {
|
_authorizePlayerControl(user, player) {
|
||||||
// Bot owners bypass all checks
|
|
||||||
if (user && this.remix.handler?.owners?.includes?.(user.id)) return null;
|
if (user && this.remix.handler?.owners?.includes?.(user.id)) return null;
|
||||||
|
|
||||||
if (!user) return "User not provided";
|
if (!user) return "User not provided";
|
||||||
|
|
||||||
const cleanUserId = String(user.id).replace(/\D/g, "");
|
const cleanUserId = String(user.id).replace(/\D/g, "");
|
||||||
const cleanChanId = String(player._channelId ?? "").replace(/\D/g, "");
|
const cleanChanId = String(player._channelId ?? "").replace(/\D/g, "");
|
||||||
if (!cleanChanId) return "Player has no active channel";
|
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;
|
const observed = this.remix.observedVoiceUsers;
|
||||||
if (observed) {
|
if (observed) {
|
||||||
for (const [mapUserId, info] of observed) {
|
for (const [mapUserId, info] of observed) {
|
||||||
if (String(mapUserId).replace(/\D/g, "") === cleanUserId) {
|
if (String(mapUserId).replace(/\D/g, "") === cleanUserId) {
|
||||||
const infoChannelId = String(info.channelId ?? "").replace(/\D/g, "");
|
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.
|
* 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 {import("@fluxerjs/core").User} user
|
||||||
* @param {string} guildId
|
* @param {string} guildId
|
||||||
* @returns {Promise<string|null>} Error message, or null if authorized
|
* @returns {Promise<string|null>} Error message, or null if authorized
|
||||||
@@ -258,17 +257,8 @@ export class Dashboard {
|
|||||||
|
|
||||||
// ── Static converters ─────────────────────────────────────────────────────
|
// ── 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
|
* @param {import("@fluxerjs/core").User} user
|
||||||
* @returns {APIUser}
|
|
||||||
*/
|
*/
|
||||||
static convertUser(user) {
|
static convertUser(user) {
|
||||||
return {
|
return {
|
||||||
@@ -310,7 +300,6 @@ export class Dashboard {
|
|||||||
*/
|
*/
|
||||||
static convertChannel(channel) {
|
static convertChannel(channel) {
|
||||||
const isVoice = channel.isVoiceBased?.() ?? false;
|
const isVoice = channel.isVoiceBased?.() ?? false;
|
||||||
// Collect voice members for voice channels
|
|
||||||
let voiceParticipants = [];
|
let voiceParticipants = [];
|
||||||
if (isVoice) {
|
if (isVoice) {
|
||||||
const guild = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId);
|
const guild = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId);
|
||||||
@@ -366,8 +355,6 @@ export class Dashboard {
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Lightweight server summary for player payloads.
|
* 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
|
* @param {import("@fluxerjs/core").Guild} guild
|
||||||
*/
|
*/
|
||||||
static convertServerSummary(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.
|
// Debounce map for playerUpdate — prevents flooding Redis with rapid updates.
|
||||||
_playerUpdateTimers = new Map();
|
_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
|
* Debounced: rapid successive calls for the same player are coalesced
|
||||||
* into a single publish every 500ms.
|
* 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
|
* @param {Player} player
|
||||||
*/
|
*/
|
||||||
playerUpdate(details, player) {
|
playerUpdate(details, player) {
|
||||||
if (!this.enabled) return;
|
if (!this.enabled) return;
|
||||||
const key = player._channelId ?? player._guildId ?? "unknown";
|
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)) {
|
if (this._playerUpdateTimers.has(key)) {
|
||||||
clearTimeout(this._playerUpdateTimers.get(key));
|
clearTimeout(this._playerUpdateTimers.get(key));
|
||||||
}
|
}
|
||||||
@@ -490,8 +524,19 @@ export class Dashboard {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Per-player channel update
|
* Per-player channel update (sent to {platform}:player_{channelId}).
|
||||||
* @param {Object} details
|
*
|
||||||
|
* The backend PlayerManager.setupEvents() expects messages in the format:
|
||||||
|
* { type: "<eventType>", data: <payload> }
|
||||||
|
*
|
||||||
|
* 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
|
* @param {Player} player
|
||||||
*/
|
*/
|
||||||
updatePlayer(details, 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 {Object} details
|
||||||
* @param {import("@fluxerjs/core").User} user
|
* @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) {
|
updateUser(details, user) {
|
||||||
if (!this.enabled) return;
|
if (!this.enabled) return;
|
||||||
const channel = this.redis.platform + ":user_" + user.id;
|
const channel = this.redis.platform + ":user_" + user.id;
|
||||||
this.redis.send(channel, JSON.stringify(details));
|
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<string|null>} 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.";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
@@ -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<import("mysql2/promise").QueryResult>}
|
||||||
|
*/
|
||||||
|
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<string>}
|
||||||
|
*/
|
||||||
|
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<boolean>}
|
||||||
|
*/
|
||||||
|
async compareHash(plain, hashed) {
|
||||||
|
return await compare(plain, hashed);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gracefully close the connection pool.
|
||||||
|
* @returns {Promise<void>}
|
||||||
|
*/
|
||||||
|
close() {
|
||||||
|
return this.db.end();
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in new issue
Block a user