mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
lots of stuff noo need to say it lol
This commit is contained in:
1 parent
57912539a9
commit
7662cbb944
6 files changed
+727
-188
No files matched your search
+90
-11
@@ -1,4 +1,5 @@
|
||||
import { Events, GatewayOpcodes } from "@fluxerjs/core";
|
||||
import { getVoiceManager } from "@fluxerjs/voice";
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
import { ServerSettings } from "./Settings.mjs";
|
||||
import mysql from "mysql2";
|
||||
@@ -79,13 +80,53 @@ export class GatewayHandler {
|
||||
// ── Voice-state seeding from guild cache ─────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Seed observedVoiceUsers / observedVoiceBots from all cached guild voice
|
||||
* states. Called once on Ready after the guild cache is populated.
|
||||
* Seed observedVoiceUsers / observedVoiceBots from VoiceManager.voiceStates
|
||||
* (populated by VoiceStatesSync events from READY/GUILD_CREATE) and from
|
||||
* cached guild voice states as a fallback.
|
||||
*
|
||||
* Called once on Ready after the guild cache is populated.
|
||||
*/
|
||||
seedVoiceStatesFromGuilds() {
|
||||
const { remix } = this;
|
||||
const client = remix.client;
|
||||
let seededFromVM = 0;
|
||||
let seededFromGuild = 0;
|
||||
|
||||
// ── Source 1: VoiceManager.voiceStates ──────────────────────────────────
|
||||
// This is the authoritative source per Fluxer.js docs. The VoiceManager
|
||||
// receives VoiceStatesSync events from READY/GUILD_CREATE and stores them
|
||||
// as Map<guildId, Map<userId, channelId>>.
|
||||
try {
|
||||
const vm = getVoiceManager(client);
|
||||
if (vm?.voiceStates) {
|
||||
for (const [guildId, userMap] of vm.voiceStates) {
|
||||
if (!userMap) continue;
|
||||
const cleanGuildId = String(guildId).replace(/\D/g, "");
|
||||
for (const [userId, channelId] of userMap) {
|
||||
if (!userId || !channelId) continue;
|
||||
// Determine if this user is a bot — check member cache
|
||||
const guild = client.guilds.get(guildId);
|
||||
const member = guild?.members?.get?.(userId);
|
||||
const isBot = member?.user?.bot ?? false;
|
||||
if (isBot) {
|
||||
remix.observedVoiceBots.set(
|
||||
this.getObservedVoiceBotKey(userId, guildId),
|
||||
{ channelId, guildId: cleanGuildId }
|
||||
);
|
||||
} else {
|
||||
remix.observedVoiceUsers.set(userId, { channelId, guildId: cleanGuildId });
|
||||
seededFromVM++;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn("[Gateway] VoiceManager seed failed:", e.message);
|
||||
}
|
||||
|
||||
// ── Source 2: guild.voice_states (legacy fallback) ──────────────────────
|
||||
// Fluxer.js Guild does NOT have a voice_states property in the standard API,
|
||||
// but check anyway in case a future version adds it.
|
||||
for (const [gId, guild] of client.guilds) {
|
||||
const voiceStatesRaw =
|
||||
guild.voice_states ??
|
||||
@@ -99,9 +140,12 @@ export class GatewayHandler {
|
||||
const channelId = typeof val === "string" ? val
|
||||
: val?.channelId ?? val?.channel_id ?? null;
|
||||
if (!uid || !channelId) continue;
|
||||
// Only add if not already in observedVoiceUsers (VM takes priority)
|
||||
if (remix.observedVoiceUsers.has(uid)) continue;
|
||||
const isBot = val?.member?.user?.bot ?? false;
|
||||
const target = isBot ? remix.observedVoiceBots : remix.observedVoiceUsers;
|
||||
target.set(uid, { channelId, guildId: gId });
|
||||
if (!isBot) seededFromGuild++;
|
||||
}
|
||||
} else {
|
||||
const entries = Array.isArray(voiceStatesRaw)
|
||||
@@ -111,12 +155,20 @@ export class GatewayHandler {
|
||||
const userId = state?.userId ?? state?.user_id ?? state?.id;
|
||||
const channelId = state?.channelId ?? state?.channel_id;
|
||||
if (!userId || !channelId) continue;
|
||||
if (remix.observedVoiceUsers.has(userId)) continue;
|
||||
const isBot = state?.member?.user?.bot ?? false;
|
||||
const target = isBot ? remix.observedVoiceBots : remix.observedVoiceUsers;
|
||||
target.set(userId, { channelId, guildId: gId });
|
||||
if (!isBot) seededFromGuild++;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.voiceState(
|
||||
`[seedVoiceStates] Seeded ${seededFromVM} users from VoiceManager, ` +
|
||||
`${seededFromGuild} from guild cache. ` +
|
||||
`observedVoiceUsers=${remix.observedVoiceUsers.size} observedVoiceBots=${remix.observedVoiceBots.size}`
|
||||
);
|
||||
}
|
||||
|
||||
// ── Raw WebSocket gateway listener ───────────────────────────────────────────
|
||||
@@ -294,16 +346,43 @@ export class GatewayHandler {
|
||||
if (!guildId) return;
|
||||
|
||||
// Part 1: Voice state population
|
||||
// Purge stale entries for this guild first.
|
||||
for (const [uid, info] of [...remix.observedVoiceUsers]) {
|
||||
if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, ""))
|
||||
remix.observedVoiceUsers.delete(uid);
|
||||
}
|
||||
for (const [uid, info] of [...remix.observedVoiceBots]) {
|
||||
if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, ""))
|
||||
remix.observedVoiceBots.delete(uid);
|
||||
}
|
||||
// ── DO NOT PURGE observedVoiceUsers/observedVoiceBots for this guild. ──
|
||||
// Previously, this handler purged all entries for the guild and then
|
||||
// re-seeded from guild.voice_states. However:
|
||||
// 1) Fluxer.js Guild has NO voice_states property — the re-seed silently
|
||||
// failed, leaving the maps empty after every GUILD_CREATE.
|
||||
// 2) The raw WS GUILD_CREATE handler (in attachRawListener) correctly
|
||||
// seeds from the raw gateway payload BEFORE this high-level event
|
||||
// fires, so the data is already correct.
|
||||
// 3) The VoiceManager also receives VoiceStatesSync from GUILD_CREATE
|
||||
// and populates its own voiceStates map.
|
||||
// Purging destroyed correctly-seeded data and was the root cause of the
|
||||
// "bot leaves voice after restart" bug.
|
||||
|
||||
// Reconcile from VoiceManager.voiceStates for this guild (additive only)
|
||||
try {
|
||||
const vm = getVoiceManager(client);
|
||||
const guildVoiceMap = vm?.voiceStates?.get?.(guildId);
|
||||
if (guildVoiceMap) {
|
||||
const cleanGuildId = String(guildId).replace(/\D/g, "");
|
||||
for (const [userId, channelId] of guildVoiceMap) {
|
||||
if (!userId || !channelId) continue;
|
||||
const member = guild?.members?.get?.(userId);
|
||||
const isBot = member?.user?.bot ?? false;
|
||||
if (isBot) {
|
||||
remix.observedVoiceBots.set(
|
||||
this.getObservedVoiceBotKey(userId, guildId),
|
||||
{ channelId, guildId: cleanGuildId }
|
||||
);
|
||||
} else {
|
||||
remix.observedVoiceUsers.set(userId, { channelId, guildId: cleanGuildId });
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
// Legacy: try guild.voice_states (won't exist in standard Fluxer.js,
|
||||
// but kept for forward compatibility)
|
||||
const voiceStatesRaw =
|
||||
guild.voice_states ??
|
||||
guild.voiceStates ??
|
||||
|
||||
+32
-16
@@ -604,6 +604,8 @@ export default class Player extends EventEmitter {
|
||||
if (!this._channelId || !this._guildId) return false;
|
||||
const cleanChan = String(this._channelId).replace(/\D/g, "");
|
||||
const cleanGuild = String(this._guildId).replace(/\D/g, "");
|
||||
|
||||
// ── Source 1: observedVoiceUsers map (fast path) ────────────────────────
|
||||
try {
|
||||
const voiceUsers = this._observedVoiceUsers;
|
||||
if (voiceUsers) {
|
||||
@@ -613,25 +615,32 @@ export default class Player extends EventEmitter {
|
||||
String(info.channelId ?? "").replace(/\D/g, "") === cleanChan
|
||||
) return true;
|
||||
}
|
||||
return false;
|
||||
// Don't return false here — fall through to VoiceManager check.
|
||||
// After a bot restart, observedVoiceUsers may be empty if the
|
||||
// GUILD_CREATE purge bug hasn't been fully resolved, but VoiceManager
|
||||
// receives VoiceStatesSync events and has the correct data.
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
// ── Source 2: VoiceManager.voiceStates (authoritative per Fluxer.js docs) ──
|
||||
try {
|
||||
// @fluxerjs channels do NOT have a .members property.
|
||||
// Use the guild's member manager and filter by voice state instead.
|
||||
const guild = this.client?.guilds?.get?.(this._guildId);
|
||||
if (guild?.members) {
|
||||
for (const member of guild.members.values()) {
|
||||
// GuildMember doesn't expose voice channelId directly in @fluxerjs,
|
||||
// so fall through to the voice_states raw data check below.
|
||||
if (!member?.user?.bot) {
|
||||
// We can't determine channel from member alone — skip here
|
||||
// and rely on _observedVoiceUsers or voice_states instead.
|
||||
}
|
||||
const vm = getVoiceManager(this.client);
|
||||
const participants = vm?.listParticipantsInChannel?.(cleanGuild, cleanChan);
|
||||
if (participants && participants.length > 0) {
|
||||
const guild = this.client?.guilds?.get?.(this._guildId);
|
||||
for (const uid of participants) {
|
||||
const member = guild?.members?.get?.(uid);
|
||||
if (!member?.user?.bot) return true;
|
||||
}
|
||||
}
|
||||
// Fallback: iterate raw voice_states on the guild object.
|
||||
const voiceStates = guild?.voice_states;
|
||||
} catch (_) {}
|
||||
|
||||
// ── Source 3: guild.voice_states (legacy fallback) ──────────────────────
|
||||
// Fluxer.js Guild does NOT normally have a voice_states property, but
|
||||
// check anyway for forward compatibility.
|
||||
try {
|
||||
const guild = this.client?.guilds?.get?.(this._guildId);
|
||||
const voiceStates = guild?.voice_states ?? guild?.voiceStates;
|
||||
if (voiceStates) {
|
||||
const entries = Array.isArray(voiceStates)
|
||||
? voiceStates
|
||||
@@ -642,7 +651,6 @@ export default class Player extends EventEmitter {
|
||||
const stateChannelId = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, "");
|
||||
if (stateChannelId === cleanChan) {
|
||||
const userId = String(state?.userId ?? state?.user_id ?? "");
|
||||
// Check if user is a bot — look up via members or observedVoiceUsers
|
||||
const member = guild?.members?.get?.(userId);
|
||||
const isBot = member?.user?.bot ?? false;
|
||||
if (!isBot) return true;
|
||||
@@ -650,6 +658,7 @@ export default class Player extends EventEmitter {
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1306,9 +1315,16 @@ export default class Player extends EventEmitter {
|
||||
if (!this.queue.isEmpty() && !this.queue.getCurrent()) {
|
||||
this.playNext();
|
||||
} else if (this.queue.isEmpty()) {
|
||||
// Only start inactivity timer if no humans are in the channel.
|
||||
// After a bot restart, humans may already be in the channel — don't
|
||||
// start a timer that would cause the bot to leave immediately.
|
||||
setTimeout(() => {
|
||||
if (this.queue.isEmpty() && !this.queue.getCurrent()) {
|
||||
this._startInactivityTimer();
|
||||
if (this._hasHumansInChannel()) {
|
||||
logger.inactivity(`[Player] Humans present after join — skipping inactivity timer.`);
|
||||
} else {
|
||||
this._startInactivityTimer();
|
||||
}
|
||||
}
|
||||
}, 3000);
|
||||
}
|
||||
|
||||
+78
-24
@@ -167,34 +167,88 @@ export class PlayerManager {
|
||||
|
||||
// Broadcast user list changes to the global :users channel when
|
||||
// someone joins or leaves the player's voice channel.
|
||||
//
|
||||
// CRITICAL: After a bot reload, guild.voice_states may not yet contain all
|
||||
// users who are in the channel (only the bot's own state may be present).
|
||||
// The observedVoiceUsers map is seeded from READY/GUILD_CREATE and IS
|
||||
// reliable — so we use it as a fallback to ensure all users are announced.
|
||||
const sendUserUpdates = (eventType) => {
|
||||
if (!this.dashboard?.enabled) return;
|
||||
const channelId = getPlayerChannelId(player, context.channelId);
|
||||
const guildId = cleanId(player._guildId ?? context.guildId);
|
||||
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;
|
||||
// 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,
|
||||
}, member.user);
|
||||
const guild = player.client?.guilds?.get(guildId);
|
||||
const sentUserIds = new Set(); // Deduplicate across both sources
|
||||
|
||||
// ── Source 1: guild.voice_states (real-time Discord data) ──────────
|
||||
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) {
|
||||
if (!state?.channelId && !state?.channel_id) continue;
|
||||
const stateChannelId = cleanId(state.channelId ?? state.channel_id);
|
||||
if (stateChannelId !== channelId) continue;
|
||||
const userId = String(state.userId ?? state.user_id ?? "");
|
||||
if (!userId) continue;
|
||||
const member = guild.members?.get?.(userId);
|
||||
if (!member?.user || member.user?.bot) continue;
|
||||
sentUserIds.add(userId);
|
||||
emit(eventType, member.user.id);
|
||||
this.dashboard.userUpdate({
|
||||
type: eventType,
|
||||
guildId,
|
||||
channelId,
|
||||
}, member.user);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ── Source 2: observedVoiceUsers (seeded from READY/GUILD_CREATE) ──
|
||||
// This catches users who were already in the channel when the bot
|
||||
// reloaded but whose voice states aren't in guild.voice_states yet.
|
||||
// After a bot restart, guild.voice_states may only contain the bot's
|
||||
// own voice state, while observedVoiceUsers was populated from the
|
||||
// READY payload and contains ALL humans who were already in voice.
|
||||
if (eventType === "join" && this.observedVoiceUsers) {
|
||||
const botUserId = player.client?.user?.id;
|
||||
for (const [mapUserId, info] of this.observedVoiceUsers) {
|
||||
if (sentUserIds.has(mapUserId)) continue; // Already sent from voice_states
|
||||
const infoChannelId = cleanId(info.channelId ?? "");
|
||||
const infoGuildId = cleanId(info.guildId ?? "");
|
||||
if (infoChannelId !== channelId || infoGuildId !== guildId) continue;
|
||||
// Skip the bot itself — it's not a "user" to announce
|
||||
if (botUserId && String(mapUserId) === String(botUserId)) continue;
|
||||
// Skip bots (check observedVoiceBots if available)
|
||||
const botKey = `${infoGuildId}:${mapUserId}`;
|
||||
if (this.observedVoiceBots?.has?.(botKey)) continue;
|
||||
sentUserIds.add(mapUserId);
|
||||
// Try to get user object from cache first, then fetch asynchronously
|
||||
const cachedUser = player.client?.users?.get?.(mapUserId);
|
||||
emit(eventType, String(mapUserId));
|
||||
if (cachedUser) {
|
||||
this.dashboard.userUpdate({
|
||||
type: eventType,
|
||||
guildId,
|
||||
channelId,
|
||||
}, cachedUser);
|
||||
} else {
|
||||
// User not in cache — fetch async and send update when available
|
||||
player.client?.users?.fetch?.(mapUserId)?.then?.((userObj) => {
|
||||
if (userObj) {
|
||||
this.dashboard.userUpdate({
|
||||
type: eventType,
|
||||
guildId,
|
||||
channelId,
|
||||
}, userObj);
|
||||
}
|
||||
})?.catch?.(() => {});
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import * as fs from "fs";
|
||||
import { logger } from "./constants/Logger.mjs";
|
||||
import { EmbedBuilder } from "@fluxerjs/core";
|
||||
import { getVoiceManager } from "@fluxerjs/voice";
|
||||
import { getGlobalColor } from "./MessageHandler.mjs";
|
||||
import Player from "./Player.mjs";
|
||||
|
||||
@@ -432,6 +433,52 @@ export class RecoveryManager {
|
||||
}
|
||||
logger.recovery(`[Recovery] Restored session in ${cleanChannelId} (${recoveryData.queue?.length ?? 0} track(s)).`);
|
||||
}
|
||||
|
||||
// ── Post-recovery voice state verification ─────────────────────────
|
||||
// After a bot restart, voice state data may not be fully settled when
|
||||
// the player first joins. Schedule a delayed check to:
|
||||
// 1. Re-seed observedVoiceUsers from VoiceManager (which receives
|
||||
// VoiceStatesSync events from READY/GUILD_CREATE)
|
||||
// 2. Stop any incorrectly-started inactivity timers if humans are
|
||||
// present in the channel
|
||||
setTimeout(() => {
|
||||
if (p._destroyed) return;
|
||||
|
||||
// Re-seed observedVoiceUsers from VoiceManager for this guild
|
||||
try {
|
||||
const vm = getVoiceManager(remix.client);
|
||||
const guildVoiceMap = vm?.voiceStates?.get?.(guildId);
|
||||
if (guildVoiceMap) {
|
||||
const cleanGuildId = String(guildId).replace(/\D/g, "");
|
||||
for (const [userId, channelId] of guildVoiceMap) {
|
||||
if (!userId || !channelId) continue;
|
||||
const guild = remix.client.guilds.get(guildId);
|
||||
const member = guild?.members?.get?.(userId);
|
||||
const isBot = member?.user?.bot ?? false;
|
||||
if (!isBot) {
|
||||
remix.observedVoiceUsers.set(userId, { channelId, guildId: cleanGuildId });
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
// Check if humans are now detected in the channel
|
||||
if (p._hasHumansInChannel()) {
|
||||
logger.recovery(
|
||||
`[Recovery] Post-join check: humans detected in ${cleanChannelId}, ` +
|
||||
`stopping any inactivity timer.`
|
||||
);
|
||||
p._stopInactivityTimer();
|
||||
} else if (!p._is247Enabled()) {
|
||||
// No humans and not 24/7 — start inactivity timer if not already running
|
||||
// (the bot may have been alone when it restarted)
|
||||
logger.recovery(
|
||||
`[Recovery] Post-join check: no humans in ${cleanChannelId}, ` +
|
||||
`starting inactivity timer.`
|
||||
);
|
||||
p._startInactivityTimer();
|
||||
}
|
||||
}, 8_000); // 8s grace period for voice states to settle after join
|
||||
} catch (e) {
|
||||
remix.players.playerMap.delete(cleanChannelId);
|
||||
try { p.destroy(); } catch (_) {}
|
||||
@@ -660,6 +707,34 @@ export class RecoveryManager {
|
||||
`(${ok} ok, ${errors.length} failed).`
|
||||
);
|
||||
|
||||
// ── Final voice state reconciliation ────────────────────────────────────
|
||||
// After all recovery spawns complete, do one final pass to re-seed
|
||||
// observedVoiceUsers from VoiceManager. This ensures that even if some
|
||||
// guilds' VoiceStatesSync events arrived late, the data is captured.
|
||||
try {
|
||||
const vm = getVoiceManager(remix.client);
|
||||
if (vm?.voiceStates) {
|
||||
let reconciled = 0;
|
||||
for (const [guildId, userMap] of vm.voiceStates) {
|
||||
if (!userMap) continue;
|
||||
const cleanGuildId = String(guildId).replace(/\D/g, "");
|
||||
for (const [userId, channelId] of userMap) {
|
||||
if (!userId || !channelId) continue;
|
||||
const guild = remix.client.guilds.get(guildId);
|
||||
const member = guild?.members?.get?.(userId);
|
||||
const isBot = member?.user?.bot ?? false;
|
||||
if (!isBot && !remix.observedVoiceUsers.has(userId)) {
|
||||
remix.observedVoiceUsers.set(userId, { channelId, guildId: cleanGuildId });
|
||||
reconciled++;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (reconciled > 0) {
|
||||
logger.recovery(`[Recovery] Final reconciliation: added ${reconciled} user(s) to observedVoiceUsers.`);
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
// Delete recovery file AFTER all spawns have been attempted (success or fail).
|
||||
// If the process crashes mid-recovery, the file still exists for next boot.
|
||||
if (recoveryFileExisted) {
|
||||
|
||||
+363
-118
@@ -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) {
|
||||
@@ -46,7 +55,11 @@ export class Dashboard {
|
||||
if (member) {
|
||||
server.channels = server.channels.filter(c => {
|
||||
const ch = guild.channels.get(c.id);
|
||||
return ch ? ch.permissionsFor(member)?.has("ViewChannel") : false;
|
||||
return ch ? ch.permissionsFor?.(member)?.has?.("ViewChannel") ?? true : true;
|
||||
});
|
||||
server.voiceChannels = server.voiceChannels.filter(c => {
|
||||
const ch = guild.channels.get(c.id);
|
||||
return ch ? ch.permissionsFor?.(member)?.has?.("ViewChannel") ?? true : true;
|
||||
});
|
||||
}
|
||||
return server;
|
||||
@@ -57,6 +70,16 @@ export class Dashboard {
|
||||
}
|
||||
}
|
||||
|
||||
case "allServers": {
|
||||
// Return ALL guilds the bot is in (no member check). The backend
|
||||
// filters by the user's own guild list to produce the mutual set.
|
||||
const guilds = this.remix.client.guilds;
|
||||
const guildValues = guilds && typeof guilds.values === "function"
|
||||
? [...guilds.values()]
|
||||
: guilds ? Object.values(guilds) : [];
|
||||
return guildValues.map(g => Dashboard.convertServer(g));
|
||||
}
|
||||
|
||||
case "commands":
|
||||
return this.remix.handler.commands.map(c =>
|
||||
Dashboard.convertCommand(c, this.remix.handler)
|
||||
@@ -93,8 +116,42 @@ export class Dashboard {
|
||||
if (!user) return { error: "Invalid user" };
|
||||
let voiceChannel, textChannel;
|
||||
try {
|
||||
voiceChannel = await this.remix.client.channels.fetch(params.data.channel);
|
||||
textChannel = await this.remix.client.channels.fetch(params.data.text);
|
||||
// Fluxer.js uses channels.get() for cached lookup and channels.fetch()
|
||||
// for REST fetch. Try fetch first (more reliable for uncached channels),
|
||||
// fall back to get (cache-only).
|
||||
const chMgr = this.remix.client.channels;
|
||||
if (typeof chMgr.fetch === "function") {
|
||||
voiceChannel = await chMgr.fetch(params.data.channel);
|
||||
if (params.data.text) textChannel = await chMgr.fetch(params.data.text);
|
||||
} 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" };
|
||||
|
||||
// Validate textChannel: if it's a voice channel (type === 2) or missing,
|
||||
// find a suitable text channel from the guild instead
|
||||
const isText = (ch) => ch && (ch.type === 0 || ch.type === 5 || ch.type === 13 ||
|
||||
(typeof ch.isText === "function" && ch.isText()));
|
||||
|
||||
if (!isText(textChannel)) {
|
||||
// Auto-pick a text channel from the guild
|
||||
const guild = this.remix.client.guilds.get(voiceChannel.guildId);
|
||||
if (guild?.channels) {
|
||||
const channelValues = typeof guild.channels.values === "function"
|
||||
? [...guild.channels.values()]
|
||||
: Array.isArray(guild.channels) ? guild.channels : Object.values(guild.channels);
|
||||
// Prefer system channel, then first text channel
|
||||
const sysCh = guild.systemChannelId
|
||||
? channelValues.find(c => (c.id ?? c._id) === guild.systemChannelId && isText(c))
|
||||
: null;
|
||||
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; // last resort — _sendToTextChannel will handle it
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
logger.dashboard("[Dashboard] Error:", e);
|
||||
return { error: "Invalid Channel" };
|
||||
@@ -102,15 +159,49 @@ export class Dashboard {
|
||||
// Verify the user has permission to join the voice channel
|
||||
const authErr = await this._authorizeUserInGuild(user, voiceChannel.guildId);
|
||||
if (authErr) return { error: authErr };
|
||||
if (this.remix.players.playerMap.has(voiceChannel.id)) return { message: "Already Connected" };
|
||||
if (this.remix.players.playerMap.has(voiceChannel.id)) {
|
||||
// Bot is already in this channel — just add the user to the player's
|
||||
// user list so the backend PlayerManager and SocketHandler can track
|
||||
// them for real-time updates and multi-user dashboard support.
|
||||
const existingPlayer = this.remix.players.playerMap.get(voiceChannel.id);
|
||||
if (existingPlayer && user && !existingPlayer._dashboardUsers) {
|
||||
existingPlayer._dashboardUsers = [];
|
||||
}
|
||||
if (existingPlayer && user && !existingPlayer._dashboardUsers.includes(String(user.id))) {
|
||||
existingPlayer._dashboardUsers.push(String(user.id));
|
||||
// Publish a "join" event on the player's per-channel Redis topic
|
||||
// so the backend PlayerManager adds this user to the player's users
|
||||
// list and the SocketHandler subscribes them.
|
||||
try {
|
||||
const pubChannel = this.remix.redis?.publisher ?? this.remix.redis;
|
||||
if (pubChannel && typeof pubChannel.publish === "function") {
|
||||
pubChannel.publish("fluxer:player_" + voiceChannel.id, JSON.stringify({
|
||||
type: "join",
|
||||
data: String(user.id)
|
||||
}));
|
||||
}
|
||||
} catch (_) { /* non-critical */ }
|
||||
}
|
||||
return { message: "Already Connected" };
|
||||
}
|
||||
// Build a minimal fake message that satisfies PlayerManager.initPlayer().
|
||||
// initPlayer calls message.reply() for status updates (joining, errors).
|
||||
// player.textChannel is set to message.channel, so it MUST be the real
|
||||
// textChannel object (which has .send()) — not a wrapper. Without this,
|
||||
// ch?.send throws "not a function" when announceSong fires.
|
||||
const fakeMsg = {
|
||||
channel: { channel: textChannel, guildId: voiceChannel.guildId },
|
||||
channel: textChannel,
|
||||
message: { guildId: voiceChannel.guildId },
|
||||
reply: async () => ({ edit: async () => {}, catch: () => {} }),
|
||||
};
|
||||
this.remix.players.initPlayer(fakeMsg, voiceChannel.id);
|
||||
// Track this dashboard user on the player for multi-user support
|
||||
const newPlayer = this.remix.players.playerMap.get(voiceChannel.id);
|
||||
if (newPlayer && user) {
|
||||
if (!newPlayer._dashboardUsers) newPlayer._dashboardUsers = [];
|
||||
if (!newPlayer._dashboardUsers.includes(String(user.id))) {
|
||||
newPlayer._dashboardUsers.push(String(user.id));
|
||||
}
|
||||
}
|
||||
return { message: "Joining" };
|
||||
}
|
||||
|
||||
@@ -148,8 +239,7 @@ export class Dashboard {
|
||||
if (authErr) return { error: authErr };
|
||||
const vol = Number(params.data.volume);
|
||||
if (isNaN(vol) || vol < 0 || vol > 150) return { error: "Volume must be between 0 and 150" };
|
||||
// Dashboard slider sends 0–150; setVolume expects 0–1
|
||||
const msg = player.setVolume(vol / 100);
|
||||
const msg = player.setVolume(vol);
|
||||
return { message: msg };
|
||||
}
|
||||
|
||||
@@ -169,7 +259,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" };
|
||||
}
|
||||
@@ -177,26 +267,83 @@ export class Dashboard {
|
||||
return { message: "Adding to queue" };
|
||||
}
|
||||
|
||||
case "leave": {
|
||||
if (!user) return { error: "Invalid user" };
|
||||
const channelId = params.data.channel;
|
||||
if (!channelId) return { error: "Missing channel ID" };
|
||||
const leavePlayer = this._getPlayerById(channelId);
|
||||
if (!leavePlayer) return { error: "Not in a voice channel" };
|
||||
const authErr2 = this._authorizePlayerControl(user, leavePlayer);
|
||||
if (authErr2) return { error: authErr2 };
|
||||
const activeChannelId = leavePlayer._channelId || channelId;
|
||||
this.remix.players.playerMap.delete(activeChannelId);
|
||||
if (activeChannelId !== channelId) this.remix.players.playerMap.delete(channelId);
|
||||
await leavePlayer.leave();
|
||||
leavePlayer.destroy();
|
||||
return { message: "Left channel" };
|
||||
}
|
||||
|
||||
case "testConnection": {
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
case "voiceState": {
|
||||
// Return the user's current voice channel (if any)
|
||||
if (!user) return { channel: null };
|
||||
const userId = String(user.id).replace(/\D/g, "");
|
||||
// Check observedVoiceUsers first (most reliable for Fluxer)
|
||||
if (this.remix.observedVoiceUsers) {
|
||||
for (const [mapUserId, info] of this.remix.observedVoiceUsers) {
|
||||
if (String(mapUserId).replace(/\D/g, "") === 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,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
// Fallback: check all guilds for the user's voice state
|
||||
const guilds = this.remix.client.guilds;
|
||||
const guildValues = guilds && typeof guilds.values === "function"
|
||||
? [...guilds.values()] : guilds ? Object.values(guilds) : [];
|
||||
for (const guild of guildValues) {
|
||||
if (!guild?.voice_states) continue;
|
||||
const vs = Array.isArray(guild.voice_states) ? guild.voice_states :
|
||||
typeof guild.voice_states.values === "function" ? [...guild.voice_states.values()] : Object.values(guild.voice_states);
|
||||
for (const state of vs) {
|
||||
const stateUserId = String(state?.userId ?? state?.user_id ?? "").replace(/\D/g, "");
|
||||
if (stateUserId === userId && state.channelId) {
|
||||
const ch = this.remix.client.channels.get(state.channelId);
|
||||
return {
|
||||
channelId: state.channelId,
|
||||
channel: ch ? Dashboard.convertChannel(ch) : { id: state.channelId, name: "Unknown" },
|
||||
guildId: guild.id,
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
return { channel: null };
|
||||
}
|
||||
|
||||
case "leave": {
|
||||
const player = this._getPlayerById(params.data.channel);
|
||||
if (!player) return { error: "Player not found" };
|
||||
const authErr = await this._authorizeUserInGuild(user, player._guildId);
|
||||
if (authErr) return { error: authErr };
|
||||
// Remove this user from the dashboard users list
|
||||
if (player._dashboardUsers && user) {
|
||||
const idx = player._dashboardUsers.indexOf(String(user.id));
|
||||
if (idx !== -1) player._dashboardUsers.splice(idx, 1);
|
||||
}
|
||||
// If there are still dashboard users connected, don't destroy the player
|
||||
// — just remove this user. The player stays active for other users.
|
||||
if (player._dashboardUsers && player._dashboardUsers.length > 0) {
|
||||
// Publish a leave event for this user on the player channel
|
||||
try {
|
||||
const pubChannel = this.remix.redis?.publisher ?? this.remix.redis;
|
||||
if (pubChannel && typeof pubChannel.publish === "function") {
|
||||
pubChannel.publish("fluxer:player_" + params.data.channel, JSON.stringify({
|
||||
type: "leave",
|
||||
data: String(user.id)
|
||||
}));
|
||||
}
|
||||
} catch (_) { /* non-critical */ }
|
||||
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)") };
|
||||
}
|
||||
@@ -206,31 +353,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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -240,8 +380,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<string|null>} Error message, or null if authorized
|
||||
@@ -275,32 +413,24 @@ 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) {
|
||||
// Construct avatar CDN URL from the raw hash — mirrors how getSharedServers
|
||||
// builds icon URLs. @fluxerjs/core does NOT expose displayAvatarURL() or
|
||||
// iconURL() methods (unlike Discord.js), so we build the URLs manually.
|
||||
// Build avatar URL using fluxerusercontent.com CDN pattern
|
||||
// user.avatar is the avatar hash string; user.id is the user ID
|
||||
let avatarUrl = "";
|
||||
if (user.avatar && typeof user.avatar === "string") {
|
||||
avatarUrl = `https://cdn.fluxer.app/avatars/${user.id}/${user.avatar}.webp`;
|
||||
if (user.avatar) {
|
||||
avatarUrl = `https://fluxerusercontent.com/avatars/${user.id}/${user.avatar}.webp`;
|
||||
} else if (typeof user.displayAvatarURL === "function") {
|
||||
// Fallback: if the method exists, use it (future-proofing)
|
||||
avatarUrl = user.displayAvatarURL() ?? user.defaultAvatarURL ?? "";
|
||||
} else if (user.defaultAvatarURL) {
|
||||
avatarUrl = user.defaultAvatarURL;
|
||||
try { avatarUrl = user.displayAvatarURL() ?? ""; } catch (_) {}
|
||||
} else if (typeof user.avatarURL === "function") {
|
||||
try { avatarUrl = user.avatarURL() ?? ""; } catch (_) {}
|
||||
}
|
||||
// Fallback to default avatar if no custom avatar
|
||||
if (!avatarUrl && user.discriminator) {
|
||||
avatarUrl = `https://fluxerusercontent.com/embed/avatars/${parseInt(user.discriminator || "0") % 5}.png`;
|
||||
}
|
||||
|
||||
return {
|
||||
id: user.id,
|
||||
username: user.username,
|
||||
@@ -339,8 +469,15 @@ export class Dashboard {
|
||||
* @param {import("@fluxerjs/core").GuildChannel} channel
|
||||
*/
|
||||
static convertChannel(channel) {
|
||||
const isVoice = channel.isVoiceBased?.() ?? false;
|
||||
// Collect voice members for voice channels
|
||||
const type = channel.type ?? 0;
|
||||
const isVoice = channel.isVoice?.() ?? (type === 2) ?? false;
|
||||
// Discord channel types: 0=text, 1=DM, 2=voice, 3=group DM, 4=category,
|
||||
// 5=announcement, 13=stage, 15=form, 16=forum, 17=media
|
||||
const isCategory = type === 4;
|
||||
const isText = !isVoice && !isCategory && (
|
||||
type === 0 || type === 5 || type === 13 ||
|
||||
(typeof channel.isText === "function" && channel.isText())
|
||||
);
|
||||
let voiceParticipants = [];
|
||||
if (isVoice) {
|
||||
const guild = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId);
|
||||
@@ -358,20 +495,17 @@ export class Dashboard {
|
||||
}
|
||||
}
|
||||
|
||||
const isCategory = channel.type === 4;
|
||||
const isText = !isVoice && !isCategory && (channel.type === 0 || channel.type === 5 || channel.type === 13 || channel.isText?.());
|
||||
|
||||
return {
|
||||
name: channel.name,
|
||||
displayName: channel.name,
|
||||
id: channel.id,
|
||||
icon: null,
|
||||
description: channel.topic ?? null,
|
||||
type: channel.type,
|
||||
type,
|
||||
isVoice,
|
||||
isCategory,
|
||||
isText,
|
||||
parentId: channel.parentId ?? null,
|
||||
parentId: channel.parentId ?? channel.parent_id ?? null,
|
||||
voiceParticipants,
|
||||
mature: channel.nsfw ?? false,
|
||||
serverId: channel.guildId,
|
||||
@@ -389,33 +523,48 @@ export class Dashboard {
|
||||
const channelValues = channelStore && typeof channelStore.values === "function"
|
||||
? [...channelStore.values()]
|
||||
: [];
|
||||
const allChannels = channelValues
|
||||
.map(Dashboard.convertChannel)
|
||||
.filter(c => !c.isCategory); // exclude categories — they are not joinable
|
||||
|
||||
// Build icon URL using fluxerusercontent.com CDN pattern
|
||||
// guild.icon is the icon hash string; guild.id is the server ID
|
||||
let iconUrl = null;
|
||||
if (guild.icon) {
|
||||
iconUrl = `https://fluxerusercontent.com/icons/${guild.id}/${guild.icon}.webp`;
|
||||
} else if (typeof guild.iconURL === "function") {
|
||||
try { iconUrl = guild.iconURL() ?? null; } catch (_) { iconUrl = null; }
|
||||
}
|
||||
|
||||
return {
|
||||
name: guild.name,
|
||||
id: guild.id,
|
||||
icon: guild.icon
|
||||
? `https://cdn.fluxer.app/icons/${guild.id}/${guild.icon}.webp`
|
||||
: null,
|
||||
icon: iconUrl,
|
||||
channelIds,
|
||||
description: guild.description ?? null,
|
||||
ownerId: guild.ownerId,
|
||||
channels: channelValues.map(Dashboard.convertChannel).filter(c => !c.isCategory),
|
||||
channels: allChannels,
|
||||
// Frontend expects voiceChannels array for server list display
|
||||
voiceChannels: allChannels.filter(c => c.isVoice),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) {
|
||||
// Build icon URL using fluxerusercontent.com CDN pattern
|
||||
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 (_) { iconUrl = null; }
|
||||
}
|
||||
return {
|
||||
name: guild.name,
|
||||
id: guild.id,
|
||||
icon: guild.icon
|
||||
? `https://cdn.fluxer.app/icons/${guild.id}/${guild.icon}.webp`
|
||||
: null,
|
||||
icon: iconUrl,
|
||||
description: guild.description ?? null,
|
||||
ownerId: guild.ownerId,
|
||||
};
|
||||
@@ -428,41 +577,57 @@ export class Dashboard {
|
||||
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 ? String(channelId).replace(/\D/g, "") : "";
|
||||
const cleanGuildId = player._guildId ? String(player._guildId).replace(/\D/g, "") : "";
|
||||
|
||||
return {
|
||||
loop: (player.queue.loop ? 1 : 0) + (player.queue.songLoop ? 2 : 0),
|
||||
paused: player._paused,
|
||||
playing: !player._paused && !!player.queue.current,
|
||||
volume: (player.preferredVolume ?? 1) * 100,
|
||||
queue: {
|
||||
current: Dashboard.convertVideo(player.queue.current),
|
||||
data: (player.queue.data ?? []).map(v => Dashboard.convertVideo(v)),
|
||||
},
|
||||
// Timing fields for the dashboard progress bar.
|
||||
// startedPlaying is the timestamp when the current track began (ms).
|
||||
// When paused, _pausedAt is the freeze moment; timeDiff is the elapsed
|
||||
// time (in ms) before the last resume. When playing, timeDiff is 0 and
|
||||
// the frontend calculates elapsed = Date.now() - started.
|
||||
started: player.startedPlaying ?? 0,
|
||||
timeDiff: (() => {
|
||||
if (player._paused && player._pausedAt && player.startedPlaying) {
|
||||
return player._pausedAt - player.startedPlaying;
|
||||
}
|
||||
return 0;
|
||||
})(),
|
||||
users: (() => {
|
||||
if (!channel) return [];
|
||||
if (!channel) return player._dashboardUsers ?? [];
|
||||
const g = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId);
|
||||
if (!g?.voice_states) return [];
|
||||
const vs = Array.isArray(g.voice_states) ? g.voice_states :
|
||||
typeof g.voice_states.values === "function" ? [...g.voice_states.values()] : Object.values(g.voice_states);
|
||||
const ids = [];
|
||||
for (const state of vs) {
|
||||
const scId = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, "");
|
||||
const chId = String(channel?.id ?? "").replace(/\D/g, "");
|
||||
if (scId === chId) {
|
||||
const memberId = String(state?.userId ?? state?.user_id ?? "");
|
||||
if (memberId) ids.push(memberId);
|
||||
const seen = new Set();
|
||||
if (g?.voice_states) {
|
||||
const vs = Array.isArray(g.voice_states) ? g.voice_states :
|
||||
typeof g.voice_states.values === "function" ? [...g.voice_states.values()] : Object.values(g.voice_states);
|
||||
for (const state of vs) {
|
||||
const scId = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, "");
|
||||
const chId = String(channel?.id ?? "").replace(/\D/g, "");
|
||||
if (scId === chId) {
|
||||
const memberId = String(state?.userId ?? state?.user_id ?? "");
|
||||
if (memberId) { ids.push(memberId); seen.add(memberId); }
|
||||
}
|
||||
}
|
||||
}
|
||||
// Fallback: observedVoiceUsers (seeded from READY/GUILD_CREATE).
|
||||
// After a bot reload, guild.voice_states may only contain the bot's
|
||||
// own voice state, while observedVoiceUsers has ALL humans who were
|
||||
// already in voice when the bot reconnected.
|
||||
const ovu = player._observedVoiceUsers;
|
||||
if (ovu && cleanChannelId && cleanGuildId) {
|
||||
for (const [mapUserId, info] of ovu) {
|
||||
if (seen.has(mapUserId)) continue;
|
||||
const infoCh = String(info.channelId ?? "").replace(/\D/g, "");
|
||||
const infoG = String(info.guildId ?? "").replace(/\D/g, "");
|
||||
if (infoCh === cleanChannelId && infoG === cleanGuildId) {
|
||||
// Skip the bot itself
|
||||
const botId = player.client?.user?.id;
|
||||
if (botId && String(mapUserId) === String(botId)) continue;
|
||||
ids.push(String(mapUserId));
|
||||
seen.add(mapUserId);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Merge dashboard users (connected via web UI but not necessarily in Discord voice)
|
||||
if (player._dashboardUsers) {
|
||||
for (const du of player._dashboardUsers) {
|
||||
if (!ids.includes(du)) ids.push(du);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
@@ -511,29 +676,55 @@ 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 via fluxer:players).
|
||||
* Global player update (broadcast to all dashboard listeners on {platform}:players).
|
||||
*
|
||||
* Lifecycle events ("init" / "close") are sent IMMEDIATELY so the backend
|
||||
* can create or destroy Player objects without delay. All other events
|
||||
* ("update") are debounced to 500ms per player to avoid flooding Redis.
|
||||
* 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.
|
||||
*
|
||||
* Expected message format on fluxer:players:
|
||||
* { type: "init"|"close"|"update", player: SerialisedPlayer }
|
||||
* Debounced: rapid successive calls for the same player are coalesced
|
||||
* into a single publish every 500ms.
|
||||
*
|
||||
* @param {Object} details Must include { type: "init"|"close"|"update" }
|
||||
* @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";
|
||||
|
||||
const publish = () => {
|
||||
// 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({
|
||||
@@ -543,33 +734,41 @@ export class Dashboard {
|
||||
} catch (e) {
|
||||
logger.dashboard("[Dashboard] playerUpdate error:", e.message);
|
||||
}
|
||||
};
|
||||
|
||||
// Lifecycle events must be sent immediately — the backend needs to
|
||||
// create/destroy Player objects in real-time for WebSocket subscriptions.
|
||||
if (details.type === "init" || details.type === "close") {
|
||||
// Clear any pending debounced update for this player
|
||||
if (this._playerUpdateTimers.has(key)) {
|
||||
clearTimeout(this._playerUpdateTimers.get(key));
|
||||
this._playerUpdateTimers.delete(key);
|
||||
}
|
||||
publish();
|
||||
return;
|
||||
}
|
||||
|
||||
// Other updates are debounced to avoid flooding Redis
|
||||
// All other events are debounced to avoid flooding Redis.
|
||||
if (this._playerUpdateTimers.has(key)) {
|
||||
clearTimeout(this._playerUpdateTimers.get(key));
|
||||
}
|
||||
this._playerUpdateTimers.set(key, setTimeout(() => {
|
||||
this._playerUpdateTimers.delete(key);
|
||||
publish();
|
||||
try {
|
||||
const serialised = Dashboard.convertPlayer(player);
|
||||
this.redis.send(this.redis.platform + ":players", JSON.stringify({
|
||||
...details,
|
||||
player: serialised,
|
||||
}));
|
||||
} catch (e) {
|
||||
logger.dashboard("[Dashboard] playerUpdate error:", e.message);
|
||||
}
|
||||
}, 500));
|
||||
}
|
||||
|
||||
/**
|
||||
* 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: "<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
|
||||
*/
|
||||
updatePlayer(details, player) {
|
||||
@@ -579,7 +778,7 @@ export class Dashboard {
|
||||
}
|
||||
|
||||
/**
|
||||
* Global user update
|
||||
* Global user update (sent to {platform}:users).
|
||||
* @param {Object} details
|
||||
* @param {import("@fluxerjs/core").User} user
|
||||
*/
|
||||
@@ -592,9 +791,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<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.";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user