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
@@ -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 ?? [];
|
||||||
@@ -76,6 +77,19 @@ export class Remix {
|
|||||||
client.setMaxListeners(50);
|
client.setMaxListeners(50);
|
||||||
this.client = client;
|
this.client = client;
|
||||||
|
|
||||||
|
// ── VoiceManager — MUST be created BEFORE login ──────────────────────────
|
||||||
|
// Per Fluxer.js docs: "Create a VoiceManager before login so it receives
|
||||||
|
// VoiceStatesSync from READY/GUILD_CREATE. This lets the manager see users
|
||||||
|
// already in voice when the bot starts."
|
||||||
|
// If created after login, the VoiceStatesSync events are already fired and
|
||||||
|
// missed — the bot won't know who's in voice channels after a restart.
|
||||||
|
try {
|
||||||
|
getVoiceManager(client);
|
||||||
|
// VoiceManager will auto-register for VoiceStatesSync / VoiceStateUpdate
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[VoiceManager] Pre-login init failed:", e.message);
|
||||||
|
}
|
||||||
|
|
||||||
// ── Message & Settings handlers ──────────────────────────────────────────
|
// ── Message & Settings handlers ──────────────────────────────────────────
|
||||||
const messages = new MessageHandler(this.client);
|
const messages = new MessageHandler(this.client);
|
||||||
this.messages = messages;
|
this.messages = messages;
|
||||||
@@ -105,7 +119,7 @@ export class Remix {
|
|||||||
false,
|
false,
|
||||||
{
|
{
|
||||||
icon_url: msg.channel.channel.guild?.icon
|
icon_url: msg.channel.channel.guild?.icon
|
||||||
? `https://cdn.fluxer.app/icons/${msg.channel.channel.guild.id}/${msg.channel.channel.guild.icon}.webp`
|
? `https://fluxerusercontent.com/icons/${msg.channel.channel.guild.id}/${msg.channel.channel.guild.icon}.webp`
|
||||||
: null,
|
: null,
|
||||||
title: msg.channel.channel.guild?.name ?? null,
|
title: msg.channel.channel.guild?.name ?? null,
|
||||||
}
|
}
|
||||||
@@ -175,10 +189,13 @@ export class Remix {
|
|||||||
logger.player("Logged in as " + (client.user?.username ?? "bot"));
|
logger.player("Logged in as " + (client.user?.username ?? "bot"));
|
||||||
|
|
||||||
try {
|
try {
|
||||||
getVoiceManager(client);
|
// VoiceManager was created before login to catch VoiceStatesSync.
|
||||||
logger.player("VoiceManager initialized.");
|
// Ensure it's accessible and log its state.
|
||||||
|
const vm = getVoiceManager(client);
|
||||||
|
const guildCount = vm.voiceStates?.size ?? 0;
|
||||||
|
logger.player(`VoiceManager ready (${guildCount} guild voice-state maps).`);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.warn("[VoiceManager] Init failed:", e.message);
|
logger.warn("[VoiceManager] Ready check failed:", e.message);
|
||||||
}
|
}
|
||||||
|
|
||||||
const botId = client.user?.id ?? "0";
|
const botId = client.user?.id ?? "0";
|
||||||
@@ -233,6 +250,7 @@ export class Remix {
|
|||||||
timers: this.T,
|
timers: this.T,
|
||||||
});
|
});
|
||||||
this.players.observedVoiceUsers = this.observedVoiceUsers;
|
this.players.observedVoiceUsers = this.observedVoiceUsers;
|
||||||
|
this.players.observedVoiceBots = this.observedVoiceBots;
|
||||||
|
|
||||||
// ── Periodic alone-check ───────────────────────────────────────────────────
|
// ── Periodic alone-check ───────────────────────────────────────────────────
|
||||||
const ALONE_CHECK_INTERVAL = this.T.aloneCheckInterval;
|
const ALONE_CHECK_INTERVAL = this.T.aloneCheckInterval;
|
||||||
@@ -262,6 +280,8 @@ export class Remix {
|
|||||||
if (player._is247Enabled()) continue;
|
if (player._is247Enabled()) continue;
|
||||||
|
|
||||||
let hasHuman = false;
|
let hasHuman = false;
|
||||||
|
|
||||||
|
// Source 1: observedVoiceUsers map (seeded from READY/GUILD_CREATE + VOICE_STATE_UPDATE)
|
||||||
for (const [, info] of this.observedVoiceUsers) {
|
for (const [, info] of this.observedVoiceUsers) {
|
||||||
const infoChannel = String(info.channelId ?? "").replace(/\D/g, "");
|
const infoChannel = String(info.channelId ?? "").replace(/\D/g, "");
|
||||||
const infoGuild = String(info.guildId ?? "").replace(/\D/g, "");
|
const infoGuild = String(info.guildId ?? "").replace(/\D/g, "");
|
||||||
@@ -271,6 +291,28 @@ export class Remix {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Source 2: VoiceManager.voiceStates (populated from VoiceStatesSync events)
|
||||||
|
// This is the authoritative source per Fluxer.js docs. It catches users
|
||||||
|
// who were already in voice when the bot started, even if
|
||||||
|
// observedVoiceUsers hasn't been fully seeded yet.
|
||||||
|
if (!hasHuman) {
|
||||||
|
try {
|
||||||
|
const vm = getVoiceManager(this.client);
|
||||||
|
const participants = vm.listParticipantsInChannel?.(guildId, channelId);
|
||||||
|
if (participants && participants.length > 0) {
|
||||||
|
// Filter out bots — listParticipantsInChannel returns ALL users
|
||||||
|
const guild = this.client.guilds.get(guildId);
|
||||||
|
for (const uid of participants) {
|
||||||
|
const member = guild?.members?.get?.(uid);
|
||||||
|
if (!member?.user?.bot) {
|
||||||
|
hasHuman = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
logger.aloneCheck(`[AloneCheck] channel=${channelId} guild=${guildId} hasHuman=${hasHuman} paused=${player._paused}`);
|
logger.aloneCheck(`[AloneCheck] channel=${channelId} guild=${guildId} hasHuman=${hasHuman} paused=${player._paused}`);
|
||||||
|
|
||||||
if (!hasHuman && !player._paused) {
|
if (!hasHuman && !player._paused) {
|
||||||
@@ -574,23 +616,44 @@ export class Remix {
|
|||||||
name: guild.name,
|
name: guild.name,
|
||||||
id: guild.id,
|
id: guild.id,
|
||||||
icon: guild.icon
|
icon: guild.icon
|
||||||
? `https://cdn.fluxer.app/icons/${guild.id}/${guild.icon}.webp`
|
? `https://fluxerusercontent.com/icons/${guild.id}/${guild.icon}.webp`
|
||||||
: null,
|
: null,
|
||||||
|
description: guild.description ?? null,
|
||||||
|
ownerId: guild.ownerId ?? null,
|
||||||
|
channelIds: guild.channels && typeof guild.channels.keys === "function"
|
||||||
|
? [...guild.channels.keys()]
|
||||||
|
: [],
|
||||||
voiceChannels: guild.channels
|
voiceChannels: guild.channels
|
||||||
.filter(c => c.isVoiceBased?.() ?? false)
|
.filter(c => c.isVoice?.() ?? (c.type === 2) ?? false)
|
||||||
.map(c => ({
|
.map(c => {
|
||||||
name: c.name,
|
// Build voice participants list for this channel
|
||||||
displayName: c.name,
|
const voiceParticipants = [];
|
||||||
id: c.id,
|
if (guild.voice_states) {
|
||||||
icon: null,
|
const vs = Array.isArray(guild.voice_states) ? guild.voice_states :
|
||||||
isVoice: true,
|
typeof guild.voice_states.values === "function" ? [...guild.voice_states.values()] : Object.values(guild.voice_states);
|
||||||
type: c.type,
|
for (const state of vs) {
|
||||||
isCategory: false,
|
const scId = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, "");
|
||||||
isText: false,
|
const chId = String(c.id ?? "").replace(/\D/g, "");
|
||||||
parentId: c.parentId ?? null,
|
if (scId === chId) {
|
||||||
serverId: guild.id,
|
const member = guild.members?.get?.(state?.userId ?? state?.user_id);
|
||||||
voiceParticipants: [],
|
if (member?.user && !member.user.bot) {
|
||||||
})),
|
voiceParticipants.push(Dashboard.convertUser(member.user));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
name: c.name,
|
||||||
|
displayName: c.name,
|
||||||
|
id: c.id,
|
||||||
|
icon: null,
|
||||||
|
description: c.topic ?? null,
|
||||||
|
isVoice: true,
|
||||||
|
mature: c.nsfw ?? false,
|
||||||
|
serverId: guild.id,
|
||||||
|
voiceParticipants,
|
||||||
|
};
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -669,6 +732,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);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
+90
-11
@@ -1,4 +1,5 @@
|
|||||||
import { Events, GatewayOpcodes } from "@fluxerjs/core";
|
import { Events, GatewayOpcodes } from "@fluxerjs/core";
|
||||||
|
import { getVoiceManager } from "@fluxerjs/voice";
|
||||||
import { logger } from "./constants/Logger.mjs";
|
import { logger } from "./constants/Logger.mjs";
|
||||||
import { ServerSettings } from "./Settings.mjs";
|
import { ServerSettings } from "./Settings.mjs";
|
||||||
import mysql from "mysql2";
|
import mysql from "mysql2";
|
||||||
@@ -79,13 +80,53 @@ export class GatewayHandler {
|
|||||||
// ── Voice-state seeding from guild cache ─────────────────────────────────────
|
// ── Voice-state seeding from guild cache ─────────────────────────────────────
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Seed observedVoiceUsers / observedVoiceBots from all cached guild voice
|
* Seed observedVoiceUsers / observedVoiceBots from VoiceManager.voiceStates
|
||||||
* states. Called once on Ready after the guild cache is populated.
|
* (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() {
|
seedVoiceStatesFromGuilds() {
|
||||||
const { remix } = this;
|
const { remix } = this;
|
||||||
const client = remix.client;
|
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) {
|
for (const [gId, guild] of client.guilds) {
|
||||||
const voiceStatesRaw =
|
const voiceStatesRaw =
|
||||||
guild.voice_states ??
|
guild.voice_states ??
|
||||||
@@ -99,9 +140,12 @@ export class GatewayHandler {
|
|||||||
const channelId = typeof val === "string" ? val
|
const channelId = typeof val === "string" ? val
|
||||||
: val?.channelId ?? val?.channel_id ?? null;
|
: val?.channelId ?? val?.channel_id ?? null;
|
||||||
if (!uid || !channelId) continue;
|
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 isBot = val?.member?.user?.bot ?? false;
|
||||||
const target = isBot ? remix.observedVoiceBots : remix.observedVoiceUsers;
|
const target = isBot ? remix.observedVoiceBots : remix.observedVoiceUsers;
|
||||||
target.set(uid, { channelId, guildId: gId });
|
target.set(uid, { channelId, guildId: gId });
|
||||||
|
if (!isBot) seededFromGuild++;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const entries = Array.isArray(voiceStatesRaw)
|
const entries = Array.isArray(voiceStatesRaw)
|
||||||
@@ -111,12 +155,20 @@ export class GatewayHandler {
|
|||||||
const userId = state?.userId ?? state?.user_id ?? state?.id;
|
const userId = state?.userId ?? state?.user_id ?? state?.id;
|
||||||
const channelId = state?.channelId ?? state?.channel_id;
|
const channelId = state?.channelId ?? state?.channel_id;
|
||||||
if (!userId || !channelId) continue;
|
if (!userId || !channelId) continue;
|
||||||
|
if (remix.observedVoiceUsers.has(userId)) continue;
|
||||||
const isBot = state?.member?.user?.bot ?? false;
|
const isBot = state?.member?.user?.bot ?? false;
|
||||||
const target = isBot ? remix.observedVoiceBots : remix.observedVoiceUsers;
|
const target = isBot ? remix.observedVoiceBots : remix.observedVoiceUsers;
|
||||||
target.set(userId, { channelId, guildId: gId });
|
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 ───────────────────────────────────────────
|
// ── Raw WebSocket gateway listener ───────────────────────────────────────────
|
||||||
@@ -294,16 +346,43 @@ export class GatewayHandler {
|
|||||||
if (!guildId) return;
|
if (!guildId) return;
|
||||||
|
|
||||||
// Part 1: Voice state population
|
// Part 1: Voice state population
|
||||||
// Purge stale entries for this guild first.
|
// ── DO NOT PURGE observedVoiceUsers/observedVoiceBots for this guild. ──
|
||||||
for (const [uid, info] of [...remix.observedVoiceUsers]) {
|
// Previously, this handler purged all entries for the guild and then
|
||||||
if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, ""))
|
// re-seeded from guild.voice_states. However:
|
||||||
remix.observedVoiceUsers.delete(uid);
|
// 1) Fluxer.js Guild has NO voice_states property — the re-seed silently
|
||||||
}
|
// failed, leaving the maps empty after every GUILD_CREATE.
|
||||||
for (const [uid, info] of [...remix.observedVoiceBots]) {
|
// 2) The raw WS GUILD_CREATE handler (in attachRawListener) correctly
|
||||||
if (String(info.guildId).replace(/\D/g, "") === String(guildId).replace(/\D/g, ""))
|
// seeds from the raw gateway payload BEFORE this high-level event
|
||||||
remix.observedVoiceBots.delete(uid);
|
// 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 =
|
const voiceStatesRaw =
|
||||||
guild.voice_states ??
|
guild.voice_states ??
|
||||||
guild.voiceStates ??
|
guild.voiceStates ??
|
||||||
|
|||||||
+32
-16
@@ -604,6 +604,8 @@ export default class Player extends EventEmitter {
|
|||||||
if (!this._channelId || !this._guildId) return false;
|
if (!this._channelId || !this._guildId) return false;
|
||||||
const cleanChan = String(this._channelId).replace(/\D/g, "");
|
const cleanChan = String(this._channelId).replace(/\D/g, "");
|
||||||
const cleanGuild = String(this._guildId).replace(/\D/g, "");
|
const cleanGuild = String(this._guildId).replace(/\D/g, "");
|
||||||
|
|
||||||
|
// ── Source 1: observedVoiceUsers map (fast path) ────────────────────────
|
||||||
try {
|
try {
|
||||||
const voiceUsers = this._observedVoiceUsers;
|
const voiceUsers = this._observedVoiceUsers;
|
||||||
if (voiceUsers) {
|
if (voiceUsers) {
|
||||||
@@ -613,25 +615,32 @@ export default class Player extends EventEmitter {
|
|||||||
String(info.channelId ?? "").replace(/\D/g, "") === cleanChan
|
String(info.channelId ?? "").replace(/\D/g, "") === cleanChan
|
||||||
) return true;
|
) 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 (_) {}
|
} catch (_) {}
|
||||||
|
|
||||||
|
// ── Source 2: VoiceManager.voiceStates (authoritative per Fluxer.js docs) ──
|
||||||
try {
|
try {
|
||||||
// @fluxerjs channels do NOT have a .members property.
|
const vm = getVoiceManager(this.client);
|
||||||
// Use the guild's member manager and filter by voice state instead.
|
const participants = vm?.listParticipantsInChannel?.(cleanGuild, cleanChan);
|
||||||
const guild = this.client?.guilds?.get?.(this._guildId);
|
if (participants && participants.length > 0) {
|
||||||
if (guild?.members) {
|
const guild = this.client?.guilds?.get?.(this._guildId);
|
||||||
for (const member of guild.members.values()) {
|
for (const uid of participants) {
|
||||||
// GuildMember doesn't expose voice channelId directly in @fluxerjs,
|
const member = guild?.members?.get?.(uid);
|
||||||
// so fall through to the voice_states raw data check below.
|
if (!member?.user?.bot) return true;
|
||||||
if (!member?.user?.bot) {
|
|
||||||
// We can't determine channel from member alone — skip here
|
|
||||||
// and rely on _observedVoiceUsers or voice_states instead.
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Fallback: iterate raw voice_states on the guild object.
|
} catch (_) {}
|
||||||
const voiceStates = guild?.voice_states;
|
|
||||||
|
// ── 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) {
|
if (voiceStates) {
|
||||||
const entries = Array.isArray(voiceStates)
|
const entries = Array.isArray(voiceStates)
|
||||||
? voiceStates
|
? voiceStates
|
||||||
@@ -642,7 +651,6 @@ export default class Player extends EventEmitter {
|
|||||||
const stateChannelId = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, "");
|
const stateChannelId = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, "");
|
||||||
if (stateChannelId === cleanChan) {
|
if (stateChannelId === cleanChan) {
|
||||||
const userId = String(state?.userId ?? state?.user_id ?? "");
|
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 member = guild?.members?.get?.(userId);
|
||||||
const isBot = member?.user?.bot ?? false;
|
const isBot = member?.user?.bot ?? false;
|
||||||
if (!isBot) return true;
|
if (!isBot) return true;
|
||||||
@@ -650,6 +658,7 @@ export default class Player extends EventEmitter {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch (_) {}
|
} catch (_) {}
|
||||||
|
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1306,9 +1315,16 @@ export default class Player extends EventEmitter {
|
|||||||
if (!this.queue.isEmpty() && !this.queue.getCurrent()) {
|
if (!this.queue.isEmpty() && !this.queue.getCurrent()) {
|
||||||
this.playNext();
|
this.playNext();
|
||||||
} else if (this.queue.isEmpty()) {
|
} 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(() => {
|
setTimeout(() => {
|
||||||
if (this.queue.isEmpty() && !this.queue.getCurrent()) {
|
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);
|
}, 3000);
|
||||||
}
|
}
|
||||||
|
|||||||
+78
-24
@@ -167,34 +167,88 @@ export class PlayerManager {
|
|||||||
|
|
||||||
// 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.
|
||||||
|
//
|
||||||
|
// 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) => {
|
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 guildId = cleanId(player._guildId ?? context.guildId);
|
||||||
const channel = player.client?.channels?.get(channelId);
|
const channel = player.client?.channels?.get(channelId);
|
||||||
const guild = player.client?.guilds?.get(cleanId(player._guildId ?? context.guildId));
|
const guild = player.client?.guilds?.get(guildId);
|
||||||
if (!guild) return;
|
const sentUserIds = new Set(); // Deduplicate across both sources
|
||||||
const voiceStates = guild.voice_states ?? guild.voiceStates ?? null;
|
|
||||||
if (!voiceStates) return;
|
// ── Source 1: guild.voice_states (real-time Discord data) ──────────
|
||||||
const entries = Array.isArray(voiceStates)
|
if (guild) {
|
||||||
? voiceStates
|
const voiceStates = guild.voice_states ?? guild.voiceStates ?? null;
|
||||||
: typeof voiceStates.values === "function"
|
if (voiceStates) {
|
||||||
? [...voiceStates.values()]
|
const entries = Array.isArray(voiceStates)
|
||||||
: Object.values(voiceStates);
|
? voiceStates
|
||||||
for (const state of entries) {
|
: typeof voiceStates.values === "function"
|
||||||
if (!state?.channelId && !state?.channel_id) continue;
|
? [...voiceStates.values()]
|
||||||
const stateChannelId = cleanId(state.channelId ?? state.channel_id);
|
: Object.values(voiceStates);
|
||||||
if (stateChannelId !== channelId) continue;
|
for (const state of entries) {
|
||||||
const member = guild.members?.get?.(state.userId ?? state.user_id);
|
if (!state?.channelId && !state?.channel_id) continue;
|
||||||
if (!member?.user || member.user?.bot) continue;
|
const stateChannelId = cleanId(state.channelId ?? state.channel_id);
|
||||||
// Send per-player channel "join"/"leave" event with just the user ID
|
if (stateChannelId !== channelId) continue;
|
||||||
// (matching Stoat format where data = userId string)
|
const userId = String(state.userId ?? state.user_id ?? "");
|
||||||
emit(eventType, member.user.id);
|
if (!userId) continue;
|
||||||
// Also send global user update
|
const member = guild.members?.get?.(userId);
|
||||||
this.dashboard.userUpdate({
|
if (!member?.user || member.user?.bot) continue;
|
||||||
type: eventType,
|
sentUserIds.add(userId);
|
||||||
guildId: cleanId(player._guildId ?? context.guildId),
|
emit(eventType, member.user.id);
|
||||||
channelId,
|
this.dashboard.userUpdate({
|
||||||
}, member.user);
|
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 * as fs from "fs";
|
||||||
import { logger } from "./constants/Logger.mjs";
|
import { logger } from "./constants/Logger.mjs";
|
||||||
import { EmbedBuilder } from "@fluxerjs/core";
|
import { EmbedBuilder } from "@fluxerjs/core";
|
||||||
|
import { getVoiceManager } from "@fluxerjs/voice";
|
||||||
import { getGlobalColor } from "./MessageHandler.mjs";
|
import { getGlobalColor } from "./MessageHandler.mjs";
|
||||||
import Player from "./Player.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)).`);
|
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) {
|
} catch (e) {
|
||||||
remix.players.playerMap.delete(cleanChannelId);
|
remix.players.playerMap.delete(cleanChannelId);
|
||||||
try { p.destroy(); } catch (_) {}
|
try { p.destroy(); } catch (_) {}
|
||||||
@@ -660,6 +707,34 @@ export class RecoveryManager {
|
|||||||
`(${ok} ok, ${errors.length} failed).`
|
`(${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).
|
// 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 the process crashes mid-recovery, the file still exists for next boot.
|
||||||
if (recoveryFileExisted) {
|
if (recoveryFileExisted) {
|
||||||
|
|||||||
+363
-118
@@ -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) {
|
||||||
@@ -46,7 +55,11 @@ export class Dashboard {
|
|||||||
if (member) {
|
if (member) {
|
||||||
server.channels = server.channels.filter(c => {
|
server.channels = server.channels.filter(c => {
|
||||||
const ch = guild.channels.get(c.id);
|
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;
|
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":
|
case "commands":
|
||||||
return this.remix.handler.commands.map(c =>
|
return this.remix.handler.commands.map(c =>
|
||||||
Dashboard.convertCommand(c, this.remix.handler)
|
Dashboard.convertCommand(c, this.remix.handler)
|
||||||
@@ -93,8 +116,42 @@ export class Dashboard {
|
|||||||
if (!user) return { error: "Invalid user" };
|
if (!user) return { error: "Invalid user" };
|
||||||
let voiceChannel, textChannel;
|
let voiceChannel, textChannel;
|
||||||
try {
|
try {
|
||||||
voiceChannel = await this.remix.client.channels.fetch(params.data.channel);
|
// Fluxer.js uses channels.get() for cached lookup and channels.fetch()
|
||||||
textChannel = await this.remix.client.channels.fetch(params.data.text);
|
// 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) {
|
} catch (e) {
|
||||||
logger.dashboard("[Dashboard] Error:", e);
|
logger.dashboard("[Dashboard] Error:", e);
|
||||||
return { error: "Invalid Channel" };
|
return { error: "Invalid Channel" };
|
||||||
@@ -102,15 +159,49 @@ export class Dashboard {
|
|||||||
// Verify the user has permission to join the voice channel
|
// Verify the user has permission to join the voice channel
|
||||||
const authErr = await this._authorizeUserInGuild(user, voiceChannel.guildId);
|
const authErr = await this._authorizeUserInGuild(user, voiceChannel.guildId);
|
||||||
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)) {
|
||||||
|
// 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().
|
// 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 = {
|
const fakeMsg = {
|
||||||
channel: { channel: textChannel, guildId: voiceChannel.guildId },
|
channel: textChannel,
|
||||||
message: { guildId: voiceChannel.guildId },
|
message: { guildId: voiceChannel.guildId },
|
||||||
reply: async () => ({ edit: async () => {}, catch: () => {} }),
|
reply: async () => ({ edit: async () => {}, catch: () => {} }),
|
||||||
};
|
};
|
||||||
this.remix.players.initPlayer(fakeMsg, voiceChannel.id);
|
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" };
|
return { message: "Joining" };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -148,8 +239,7 @@ export class Dashboard {
|
|||||||
if (authErr) return { error: authErr };
|
if (authErr) return { error: authErr };
|
||||||
const vol = Number(params.data.volume);
|
const vol = Number(params.data.volume);
|
||||||
if (isNaN(vol) || vol < 0 || vol > 150) return { error: "Volume must be between 0 and 150" };
|
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);
|
||||||
const msg = player.setVolume(vol / 100);
|
|
||||||
return { message: msg };
|
return { message: msg };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -169,7 +259,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" };
|
||||||
}
|
}
|
||||||
@@ -177,26 +267,83 @@ export class Dashboard {
|
|||||||
return { message: "Adding to queue" };
|
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": {
|
case "testConnection": {
|
||||||
return { success: true };
|
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:
|
default:
|
||||||
return { error: "Unknown function: " + (params.func ?? "(none)") };
|
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.
|
* 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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -240,8 +380,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
|
||||||
@@ -275,32 +413,24 @@ 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) {
|
||||||
// Construct avatar CDN URL from the raw hash — mirrors how getSharedServers
|
// Build avatar URL using fluxerusercontent.com CDN pattern
|
||||||
// builds icon URLs. @fluxerjs/core does NOT expose displayAvatarURL() or
|
// user.avatar is the avatar hash string; user.id is the user ID
|
||||||
// iconURL() methods (unlike Discord.js), so we build the URLs manually.
|
|
||||||
let avatarUrl = "";
|
let avatarUrl = "";
|
||||||
if (user.avatar && typeof user.avatar === "string") {
|
if (user.avatar) {
|
||||||
avatarUrl = `https://cdn.fluxer.app/avatars/${user.id}/${user.avatar}.webp`;
|
avatarUrl = `https://fluxerusercontent.com/avatars/${user.id}/${user.avatar}.webp`;
|
||||||
} else if (typeof user.displayAvatarURL === "function") {
|
} else if (typeof user.displayAvatarURL === "function") {
|
||||||
// Fallback: if the method exists, use it (future-proofing)
|
try { avatarUrl = user.displayAvatarURL() ?? ""; } catch (_) {}
|
||||||
avatarUrl = user.displayAvatarURL() ?? user.defaultAvatarURL ?? "";
|
} else if (typeof user.avatarURL === "function") {
|
||||||
} else if (user.defaultAvatarURL) {
|
try { avatarUrl = user.avatarURL() ?? ""; } catch (_) {}
|
||||||
avatarUrl = user.defaultAvatarURL;
|
}
|
||||||
|
// 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 {
|
return {
|
||||||
id: user.id,
|
id: user.id,
|
||||||
username: user.username,
|
username: user.username,
|
||||||
@@ -339,8 +469,15 @@ export class Dashboard {
|
|||||||
* @param {import("@fluxerjs/core").GuildChannel} channel
|
* @param {import("@fluxerjs/core").GuildChannel} channel
|
||||||
*/
|
*/
|
||||||
static convertChannel(channel) {
|
static convertChannel(channel) {
|
||||||
const isVoice = channel.isVoiceBased?.() ?? false;
|
const type = channel.type ?? 0;
|
||||||
// Collect voice members for voice channels
|
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 = [];
|
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);
|
||||||
@@ -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 {
|
return {
|
||||||
name: channel.name,
|
name: channel.name,
|
||||||
displayName: channel.name,
|
displayName: channel.name,
|
||||||
id: channel.id,
|
id: channel.id,
|
||||||
icon: null,
|
icon: null,
|
||||||
description: channel.topic ?? null,
|
description: channel.topic ?? null,
|
||||||
type: channel.type,
|
type,
|
||||||
isVoice,
|
isVoice,
|
||||||
isCategory,
|
isCategory,
|
||||||
isText,
|
isText,
|
||||||
parentId: channel.parentId ?? null,
|
parentId: channel.parentId ?? channel.parent_id ?? null,
|
||||||
voiceParticipants,
|
voiceParticipants,
|
||||||
mature: channel.nsfw ?? false,
|
mature: channel.nsfw ?? false,
|
||||||
serverId: channel.guildId,
|
serverId: channel.guildId,
|
||||||
@@ -389,33 +523,48 @@ export class Dashboard {
|
|||||||
const channelValues = channelStore && typeof channelStore.values === "function"
|
const channelValues = channelStore && typeof channelStore.values === "function"
|
||||||
? [...channelStore.values()]
|
? [...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 {
|
return {
|
||||||
name: guild.name,
|
name: guild.name,
|
||||||
id: guild.id,
|
id: guild.id,
|
||||||
icon: guild.icon
|
icon: iconUrl,
|
||||||
? `https://cdn.fluxer.app/icons/${guild.id}/${guild.icon}.webp`
|
|
||||||
: null,
|
|
||||||
channelIds,
|
channelIds,
|
||||||
description: guild.description ?? null,
|
description: guild.description ?? null,
|
||||||
ownerId: guild.ownerId,
|
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.
|
* 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) {
|
||||||
|
// 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 {
|
return {
|
||||||
name: guild.name,
|
name: guild.name,
|
||||||
id: guild.id,
|
id: guild.id,
|
||||||
icon: guild.icon
|
icon: iconUrl,
|
||||||
? `https://cdn.fluxer.app/icons/${guild.id}/${guild.icon}.webp`
|
|
||||||
: null,
|
|
||||||
description: guild.description ?? null,
|
description: guild.description ?? null,
|
||||||
ownerId: guild.ownerId,
|
ownerId: guild.ownerId,
|
||||||
};
|
};
|
||||||
@@ -428,41 +577,57 @@ export class Dashboard {
|
|||||||
const channelId = player._channelId;
|
const channelId = player._channelId;
|
||||||
const channel = channelId ? player.client?.channels?.get(channelId) : null;
|
const channel = channelId ? player.client?.channels?.get(channelId) : null;
|
||||||
const guild = channel?.guild ?? (player._guildId ? player.client?.guilds?.get(player._guildId) : 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 {
|
return {
|
||||||
loop: (player.queue.loop ? 1 : 0) + (player.queue.songLoop ? 2 : 0),
|
loop: (player.queue.loop ? 1 : 0) + (player.queue.songLoop ? 2 : 0),
|
||||||
paused: player._paused,
|
paused: player._paused,
|
||||||
playing: !player._paused && !!player.queue.current,
|
|
||||||
volume: (player.preferredVolume ?? 1) * 100,
|
volume: (player.preferredVolume ?? 1) * 100,
|
||||||
queue: {
|
queue: {
|
||||||
current: Dashboard.convertVideo(player.queue.current),
|
current: Dashboard.convertVideo(player.queue.current),
|
||||||
data: (player.queue.data ?? []).map(v => Dashboard.convertVideo(v)),
|
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: (() => {
|
users: (() => {
|
||||||
if (!channel) return [];
|
if (!channel) return player._dashboardUsers ?? [];
|
||||||
const g = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId);
|
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 = [];
|
const ids = [];
|
||||||
for (const state of vs) {
|
const seen = new Set();
|
||||||
const scId = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, "");
|
if (g?.voice_states) {
|
||||||
const chId = String(channel?.id ?? "").replace(/\D/g, "");
|
const vs = Array.isArray(g.voice_states) ? g.voice_states :
|
||||||
if (scId === chId) {
|
typeof g.voice_states.values === "function" ? [...g.voice_states.values()] : Object.values(g.voice_states);
|
||||||
const memberId = String(state?.userId ?? state?.user_id ?? "");
|
for (const state of vs) {
|
||||||
if (memberId) ids.push(memberId);
|
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;
|
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.
|
// Debounce map for playerUpdate — prevents flooding Redis with rapid updates.
|
||||||
_playerUpdateTimers = new Map();
|
_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
|
* Used for two purposes:
|
||||||
* can create or destroy Player objects without delay. All other events
|
* 1. Lifecycle events: { type: "init" } / { type: "close" } — the backend
|
||||||
* ("update") are debounced to 500ms per player to avoid flooding Redis.
|
* 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:
|
* Debounced: rapid successive calls for the same player are coalesced
|
||||||
* { type: "init"|"close"|"update", player: SerialisedPlayer }
|
* 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
|
* @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";
|
||||||
|
|
||||||
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 {
|
try {
|
||||||
const serialised = Dashboard.convertPlayer(player);
|
const serialised = Dashboard.convertPlayer(player);
|
||||||
this.redis.send(this.redis.platform + ":players", JSON.stringify({
|
this.redis.send(this.redis.platform + ":players", JSON.stringify({
|
||||||
@@ -543,33 +734,41 @@ export class Dashboard {
|
|||||||
} catch (e) {
|
} catch (e) {
|
||||||
logger.dashboard("[Dashboard] playerUpdate error:", e.message);
|
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;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Other updates are debounced to avoid flooding Redis
|
// 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));
|
||||||
}
|
}
|
||||||
this._playerUpdateTimers.set(key, setTimeout(() => {
|
this._playerUpdateTimers.set(key, setTimeout(() => {
|
||||||
this._playerUpdateTimers.delete(key);
|
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));
|
}, 500));
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 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) {
|
||||||
@@ -579,7 +778,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
|
||||||
*/
|
*/
|
||||||
@@ -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) {
|
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.";
|
||||||
|
}
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user