lots of stuff noo need to say it lol

This commit is contained in:
NoLogicAlan committed 2026-05-08 21:29:32 +03:00
1 parent 009ec31dd8
commit 57912539a9
7 files changed
+260 -482

No files matched your search

+1 -1
View File
@@ -519,7 +519,7 @@ export async function run(message, data) {
// guild.iconURL() is a method that does not exist on @fluxerjs/core Guild objects. // guild.iconURL() is a method that does not exist on @fluxerjs/core Guild objects.
const rawGuild = message.message?.guild; const rawGuild = message.message?.guild;
const iconUrl = rawGuild?.icon const iconUrl = rawGuild?.icon
? `https://cdn.fluxer.app/icons/${rawGuild.id}/${rawGuild.icon}.webp` ? `https://fluxerusercontent.com/icons/${rawGuild.id}/${rawGuild.icon}.webp`
: null; : null;
const lines = Object.entries(d) const lines = Object.entries(d)
+33 -63
View File
@@ -46,7 +46,6 @@ 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 ?? [];
@@ -239,14 +238,13 @@ export class Remix {
const ALONE_CHECK_INTERVAL = this.T.aloneCheckInterval; const ALONE_CHECK_INTERVAL = this.T.aloneCheckInterval;
setInterval(() => { setInterval(() => {
for (const [mapKey, player] of this.players.playerMap) { for (const [mapKey, player] of this.players.playerMap) {
let channelId = mapKey;
try { try {
const guildId = player._guildId; const guildId = player._guildId;
if (!guildId) continue; if (!guildId) continue;
if (player._isJoining || player._isRecovering) continue; if (player._isJoining || player._isRecovering) continue;
channelId = player._channelId ?? mapKey; const channelId = player._channelId ?? mapKey;
const cleanChanId = String(channelId).replace(/\D/g, ""); const cleanChanId = String(channelId).replace(/\D/g, "");
if (!cleanChanId) continue; if (!cleanChanId) continue;
@@ -541,82 +539,61 @@ export class Remix {
async getSharedServers(user) { async getSharedServers(user) {
if (!user) return []; if (!user) return [];
const userId = String(user.id);
const shared = []; const shared = [];
const guilds = [...this.client.guilds.values()];
logger.dashboard(`[getSharedServers] Checking ${guilds.length} guilds for user ${userId}`); for (const guild of this.client.guilds.values()) {
for (const guild of guilds) {
let isMember = false; let isMember = false;
const guildId = guild.id;
// 1. Fast path — check cached members // 1. Fast path — check cached members
if (guild.members?.has?.(userId)) { if (guild.members?.has?.(user.id)) {
isMember = true; isMember = true;
logger.dashboard(`[getSharedServers] guild ${guild.name} (${guildId}): cache HIT`);
} }
// 2. Fallback — observed voice users (no REST needed) // 2. Fallback — observed voice users (REST-less)
if (!isMember) { if (!isMember) {
const cleanGuildId = String(guildId).replace(/\D/g, ""); const cleanGuildId = String(guild.id).replace(/\D/g, "");
for (const [obsUid, info] of (this.observedVoiceUsers ?? [])) { for (const [, info] of (this.observedVoiceUsers ?? [])) {
if (String(obsUid).replace(/\D/g, "") === userId.replace(/\D/g, "") && if (String(info.guildId ?? "").replace(/\D/g, "") === cleanGuildId) {
String(info.guildId ?? "").replace(/\D/g, "") === cleanGuildId) {
isMember = true; isMember = true;
logger.dashboard(`[getSharedServers] guild ${guild.name} (${guildId}): observedVoiceUsers HIT`);
break; break;
} }
} }
} }
// 3. REST lookup — use guild.members.resolve() which checks cache then API. // 3. Slow path — REST fetch for large guilds with incomplete caches
// This is the Fluxer.js (discord.js compatible) way to look up a single member.
// Falls back to GET /guilds/{id}/members/{userId} if not cached.
// Also try guild.members.fetch(userId) as an alternative (pagination-style fetch).
if (!isMember) { if (!isMember) {
try { try {
// guild.members.resolve(userId) — cache + REST fallback (Fluxer v1.2+) const member = await guild.members.fetch(user.id).catch(() => null);
if (typeof guild.members?.resolve === "function") { if (member) isMember = true;
const member = await guild.members.resolve(userId); } catch (_) { /* not a member or fetch failed */ }
if (member) {
isMember = true;
logger.dashboard(`[getSharedServers] guild ${guild.name} (${guildId}): members.resolve() HIT`);
}
}
} catch (e) {
const msg = e?.message ?? String(e);
// "Unknown Member" / 10007 means user is genuinely not in this guild
if (!msg.includes("Unknown Member") && !msg.includes("10007") && !msg.includes("not found")) {
logger.dashboard(`[getSharedServers] guild ${guild.name} (${guildId}): resolve error: ${msg}`);
}
}
}
// 4. Fallback — guild.members.fetch(userId) (pagination-style single member fetch)
if (!isMember) {
try {
if (typeof guild.members?.fetch === "function") {
const member = await guild.members.fetch(userId);
if (member) {
isMember = true;
logger.dashboard(`[getSharedServers] guild ${guild.name} (${guildId}): members.fetch() HIT`);
}
}
} catch (e) {
const msg = e?.message ?? String(e);
if (!msg.includes("Unknown Member") && !msg.includes("10007") && !msg.includes("not found")) {
logger.dashboard(`[getSharedServers] guild ${guild.name} (${guildId}): fetch error: ${msg}`);
}
}
} }
if (!isMember) continue; if (!isMember) continue;
shared.push(Dashboard.convertServerForList(guild)); shared.push({
name: guild.name,
id: guild.id,
icon: guild.icon
? `https://cdn.fluxer.app/icons/${guild.id}/${guild.icon}.webp`
: null,
voiceChannels: guild.channels
.filter(c => c.isVoiceBased?.() ?? false)
.map(c => ({
name: c.name,
displayName: c.name,
id: c.id,
icon: null,
isVoice: true,
type: c.type,
isCategory: false,
isText: false,
parentId: c.parentId ?? null,
serverId: guild.id,
voiceParticipants: [],
})),
});
} }
logger.dashboard(`[getSharedServers] Found ${shared.length} mutual servers for user ${userId}`);
return shared; return shared;
} }
@@ -692,13 +669,6 @@ 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);
}; };
-6
View File
@@ -64,12 +64,6 @@ export class GatewayHandler {
return { key: directKey, value: this._prevVoiceState.get(directKey) }; return { key: directKey, value: this._prevVoiceState.get(directKey) };
} }
// Only do fuzzy search if guildId is null (e.g. from a gateway event
// that doesn't include guild context). When guildId IS provided, we
// must NOT match entries from other guilds — that causes false
// "cross-guild re-key" warnings during multi-guild recovery.
if (guildId) return { key: null, value: null };
const cleanUserId = String(userId ?? "").replace(/\D/g, ""); const cleanUserId = String(userId ?? "").replace(/\D/g, "");
if (!cleanUserId) return { key: null, value: null }; if (!cleanUserId) return { key: null, value: null };
+97 -22
View File
@@ -189,12 +189,6 @@ export class PlayerManager {
// Send per-player channel "join"/"leave" event with just the user ID // Send per-player channel "join"/"leave" event with just the user ID
// (matching Stoat format where data = userId string) // (matching Stoat format where data = userId string)
emit(eventType, member.user.id); emit(eventType, member.user.id);
// Send per-user channel update so the backend UserManager can track
// connectedTo for each dashboard user independently (not just globally)
this.dashboard.updateUser({
type: eventType,
channelId,
}, member.user);
// Also send global user update // Also send global user update
this.dashboard.userUpdate({ this.dashboard.userUpdate({
type: eventType, type: eventType,
@@ -329,6 +323,84 @@ export class PlayerManager {
return player; return player;
} }
/**
* Safely send a message to a text channel.
*
* In Fluxer.js, VoiceChannel does NOT have a .send() method — only
* TextChannel and DMChannel do. If player.textChannel is a voice
* channel (or any object without .send()), we fall back to
* client.channels.send(channelId, payload) which works on any
* channel type.
*
* @param {Object} ch - Channel object (player.textChannel)
* @param {Object} payload - Message payload (embed, content, etc.)
* @returns {Promise<any>}
*/
async _sendToTextChannel(ch, payload) {
// ── Check if the channel is actually a text channel ────────────────
// Fluxer.js voice channels have a .send() method that throws
// CANNOT_SEND_MESSAGES_IN_NON_TEXT_CHANNEL when called. We need to
// detect this BEFORE calling .send() and fall back to a real text
// channel from the same guild.
const isTextChannel = (c) => {
if (!c) return false;
// type 0 = text channel in Fluxer/Discord; type 2 = voice; type 13 = stage
if (c.type != null) return c.type === 0 || c.type === 5 || c.type === 13;
// isText() method if available
if (typeof c.isText === "function") return c.isText();
// If the channel has isVoice() and it returns true, it's NOT a text channel
if (typeof c.isVoice === "function" && c.isVoice()) return false;
return false;
};
// Method 1: channel.send() — only if it's a real text channel
if (ch && isTextChannel(ch) && typeof ch.send === "function") {
try {
return await ch.send(payload);
} catch (e) {
// Send failed even though we thought it was a text channel —
// fall through to the guild text channel search below
logger.warn("[PlayerManager] _sendToTextChannel: send() failed on type-0 channel:", e.message);
}
}
// Method 2: Find a suitable text channel from the same guild
const channelId = ch?.id ?? ch?._id;
const guildId = ch?.guildId ?? ch?.guild?.id ?? ch?.server_id ?? ch?.serverId;
if (guildId && this.commands?.client) {
const guild = this.commands.client.guilds.get(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 > first text channel the bot can send to
const sysCh = guild.systemChannelId
? channelValues.find(c => (c.id ?? c._id) === guild.systemChannelId)
: null;
if (sysCh && isTextChannel(sysCh) && typeof sysCh.send === "function") {
try { return await sysCh.send(payload); } catch (_) {}
}
// Fall back to the first text channel
const textCh = channelValues.find(c => isTextChannel(c));
if (textCh && typeof textCh.send === "function") {
try { return await textCh.send(payload); } catch (_) {}
}
}
}
// Method 3: client.channels.send(id, payload) — last resort
if (channelId && this.commands?.client?.channels?.send) {
try {
return await this.commands.client.channels.send(channelId, payload);
} catch (_) {}
}
logger.warn("[PlayerManager] _sendToTextChannel: no valid text channel found for guild", guildId ?? channelId ?? "(unknown)");
}
/** /**
* Translate a locale key using the message's guild locale. * Translate a locale key using the message's guild locale.
* @param {Object} message * @param {Object} message
@@ -707,7 +779,7 @@ export class PlayerManager {
guildId: cleanId(channel.guildId ?? getMessageGuildId(message)), guildId: cleanId(channel.guildId ?? getMessageGuildId(message)),
}); });
player.on("autoleave", () => { player.on("autoleave", async () => {
const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId; const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId;
const homeChannelId = cleanId(player._home247Channel) || activeChannelId; const homeChannelId = cleanId(player._home247Channel) || activeChannelId;
const ch = player.textChannel; const ch = player.textChannel;
@@ -752,37 +824,43 @@ export class PlayerManager {
})(); })();
const desc = this.locale?.translate(guildId, "responses.join.autoLeaveInactive247", { channel: `<#${activeChannelId}>`, prefix }) const desc = this.locale?.translate(guildId, "responses.join.autoLeaveInactive247", { channel: `<#${activeChannelId}>`, prefix })
?? `Left channel <#${activeChannelId}> because of inactivity.\nIf you want me to stay in voice, use \`${prefix}247 on/auto\``; ?? `Left channel <#${activeChannelId}> because of inactivity.\nIf you want me to stay in voice, use \`${prefix}247 on/auto\``;
ch?.send(mkEmbed(desc)); try {
await this._sendToTextChannel(ch, mkEmbed(desc));
} catch (e) {
logger.warn("[PlayerManager] autoleave send failed:", e.message);
}
} }
}); });
player.on("leave", () => {}); player.on("leave", () => {});
player.on("message", (m) => { player.on("message", async (m) => {
const ch = player.textChannel; const ch = player.textChannel;
const guildId = cleanId(player._guildId ?? ch?.guildId ?? ch?.guild?.id ?? getMessageGuildId({ channel: ch })); const guildId = cleanId(player._guildId ?? ch?.guildId ?? ch?.guild?.id ?? getMessageGuildId({ channel: ch }));
const raw = this.settings.getServer(guildId)?.get("songAnnouncements"); const raw = this.settings.getServer(guildId)?.get("songAnnouncements");
const disabled = raw === false || raw === 0 || const disabled = raw === false || raw === 0 ||
["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim()); ["false","0","no","off","disable"].includes(String(raw).toLowerCase().trim());
if (disabled) return; if (disabled) return;
ch?.send(typeof m === "object" && Array.isArray(m.embeds) ? m : mkEmbed(m)); try {
await this._sendToTextChannel(ch, typeof m === "object" && Array.isArray(m.embeds) ? m : mkEmbed(m));
} catch (e) {
logger.warn("[PlayerManager] message send failed:", e.message);
}
}); });
this.playerMap.set(cleanChannelId, player); this.playerMap.set(cleanChannelId, player);
(async () => { (async () => {
let statusMsg = null; let statusMsg;
try { try {
statusMsg = await message.reply(mkEmbed(this._t(message, "responses.join.joining"))); statusMsg = await message.reply(mkEmbed(this._t(message, "responses.join.joining")));
} catch (_) { } catch (e) {
// reply() may fail or return a non-standard object (e.g. dashboard fakeMsg) logger.warn("[PlayerManager] statusMsg reply failed:", e.message);
} }
const canEdit = typeof statusMsg?.edit === "function";
try { try {
await player.join(cid); await player.join(cid);
if (canEdit) { if (statusMsg?.edit) {
await statusMsg.edit(mkEmbed(this._t(message, "responses.join.joined", { channel: cid }))).catch(() => {}); try { await statusMsg.edit(mkEmbed(this._t(message, "responses.join.joined", { channel: cid }))); } catch (_) {}
} }
const guildId = cleanId(channel.guildId ?? getMessageGuildId(message)); const guildId = cleanId(channel.guildId ?? getMessageGuildId(message));
@@ -807,11 +885,8 @@ export class PlayerManager {
} else { } else {
errorMsg = this._t(message, "responses.join.joinFailed", { error: err.message }); errorMsg = this._t(message, "responses.join.joinFailed", { error: err.message });
} }
if (canEdit) { if (statusMsg?.edit) {
await statusMsg.edit(mkEmbed(errorMsg)).catch(() => {}); try { await statusMsg.edit(mkEmbed(errorMsg)); } catch (_) {}
} else {
// Can't edit the status message — send a new reply instead
try { await message.reply(mkEmbed(errorMsg)); } catch (_) {}
} }
this.playerMap.delete(cleanChannelId); this.playerMap.delete(cleanChannelId);
player.destroy(); player.destroy();
-10
View File
@@ -660,16 +660,6 @@ export class RecoveryManager {
`(${ok} ok, ${errors.length} failed).` `(${ok} ok, ${errors.length} failed).`
); );
// Re-announce readiness to the backend so it can re-initialize
// PlayerManager with the recovered players. Without this, the backend
// may have missed the "init" events published during recovery if its
// subscriber wasn't ready yet, or it may have initialized with empty
// data because the bot hadn't recovered sessions at the time.
if (ok > 0 && remix.dashboard?.announceReady) {
logger.recovery("[Recovery] Re-announcing bot readiness to backend...");
remix.dashboard.announceReady();
}
// 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) {
+113 -357
View File
@@ -1,20 +1,17 @@
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;
@@ -22,12 +19,6 @@ 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) {
@@ -41,38 +32,9 @@ export class Dashboard {
} }
case "sharedServers": { case "sharedServers": {
try {
const sharedUser = await this.remix.client.users.fetch(data.key).catch(() => null); const sharedUser = await this.remix.client.users.fetch(data.key).catch(() => null);
if (!sharedUser) { if (!sharedUser) return { error: "User not found" };
logger.dashboard("[Dashboard] sharedServers: user not found for key:", data.key); return await this.remix.getSharedServers(sharedUser);
return { error: "User not found" };
}
logger.dashboard("[Dashboard] sharedServers: fetching for user", sharedUser.id, sharedUser.username);
const result = await this.remix.getSharedServers(sharedUser);
logger.dashboard("[Dashboard] sharedServers: returning", Array.isArray(result) ? result.length + " servers" : JSON.stringify(result));
return result;
} catch (e) {
const id = Utils.uid();
logger.dashboard("[Dashboard] sharedServers error:", id, e);
return { error: "Failed to fetch shared servers. Id: " + id };
}
}
case "allServers": {
// Returns ALL guilds the bot is in, without checking if a specific
// user is a member. Used by the backend's OAuth2 fast path — the
// backend fetches the user's guild IDs from the Fluxer API and
// filters on its side, avoiding expensive per-guild member checks
// on the bot.
try {
const guilds = [...this.remix.client.guilds.values()];
logger.dashboard("[Dashboard] allServers: returning", guilds.length, "bot guilds");
return guilds.map(guild => Dashboard.convertServerForList(guild));
} catch (e) {
const id = Utils.uid();
logger.dashboard("[Dashboard] allServers error:", id, e);
return { error: "Failed to fetch all servers. Id: " + id };
}
} }
case "server": { case "server": {
@@ -84,20 +46,7 @@ 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);
if (!ch) return false; return ch ? ch.permissionsFor(member)?.has("ViewChannel") : false;
// @fluxerjs/core GuildChannel objects do NOT expose a
// permissionsFor() method like discord.js does. If the method
// exists, use it; otherwise the user is already verified as a
// guild member so showing all channels is safe.
if (typeof ch.permissionsFor === "function") {
try {
const perms = ch.permissionsFor(member);
return perms ? perms.has("ViewChannel") : false;
} catch (_) {
return true; // permission check failed — show channel anyway
}
}
return true;
}); });
} }
return server; return server;
@@ -115,10 +64,6 @@ export class Dashboard {
case "function": case "function":
return await this.runFunction(data.params); return await this.runFunction(data.params);
default:
logger.dashboard("[Dashboard] Unknown request type:", data.type);
return { error: "Unknown request type: " + (data.type ?? "(none)") };
} }
}); });
} }
@@ -148,31 +93,18 @@ export class Dashboard {
if (!user) return { error: "Invalid user" }; if (!user) return { error: "Invalid user" };
let voiceChannel, textChannel; let voiceChannel, textChannel;
try { try {
// Try fetch first (REST), fall back to cache voiceChannel = await this.remix.client.channels.fetch(params.data.channel);
voiceChannel = await this.remix.client.channels.fetch(params.data.channel).catch(() => textChannel = await this.remix.client.channels.fetch(params.data.text);
this.remix.client.channels.get(params.data.channel)
);
textChannel = await this.remix.client.channels.fetch(params.data.text).catch(() =>
this.remix.client.channels.get(params.data.text)
);
} catch (e) { } catch (e) {
logger.dashboard("[Dashboard] join: channel lookup error:", e); logger.dashboard("[Dashboard] Error:", e);
return { error: "Invalid Channel" }; return { error: "Invalid Channel" };
} }
if (!voiceChannel) return { error: "Voice channel not found" };
if (!textChannel) {
// If text channel is missing, create a minimal stub so initPlayer can still work.
// The text channel is only used for song announcements — missing it is non-fatal.
logger.dashboard("[Dashboard] join: text channel not found, using stub");
textChannel = { id: params.data.text, guildId: voiceChannel.guildId };
}
// 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)) return { message: "Already Connected" };
// Build a minimal fake message that satisfies PlayerManager.initPlayer(). // Build a minimal fake message that satisfies PlayerManager.initPlayer().
// The reply() returns a mock with edit() so initPlayer's statusMsg.edit // initPlayer calls message.reply() for status updates (joining, errors).
// calls don't crash (Fluxer doesn't expose message edit from dashboards).
const fakeMsg = { const fakeMsg = {
channel: { channel: textChannel, guildId: voiceChannel.guildId }, channel: { channel: textChannel, guildId: voiceChannel.guildId },
message: { guildId: voiceChannel.guildId }, message: { guildId: voiceChannel.guildId },
@@ -216,7 +148,8 @@ 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" };
const msg = player.setVolume(vol); // Dashboard slider sends 0–150; setVolume expects 0–1
const msg = player.setVolume(vol / 100);
return { message: msg }; return { message: msg };
} }
@@ -236,7 +169,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 // Sanitize: reject obviously malicious patterns (JavaScript URLs, data URIs)
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" };
} }
@@ -244,21 +177,24 @@ export class Dashboard {
return { message: "Adding to queue" }; return { message: "Adding to queue" };
} }
case "testConnection": { case "leave": {
return { success: true }; 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 "leave": { case "testConnection": {
const player = this._getPlayerById(params.data.channel); return { success: true };
if (!player) return { error: "Player not found" };
const authErr = await this._authorizeUserInGuild(user, player._guildId);
if (authErr) return { error: authErr };
try {
await player.leave();
return { message: "Left channel" };
} catch (e) {
return { error: "Failed to leave: " + e.message };
}
} }
default: default:
@@ -269,57 +205,43 @@ export class Dashboard {
// ── Authorization helpers ────────────────────────────────────────────── // ── Authorization helpers ──────────────────────────────────────────────
/** /**
* Check if a user is authorized to control the player. * Check if a user is a bot owner, or is in the same voice channel as the player.
* Authorization is granted if: * Bot owners are always allowed. Otherwise the user must be physically in the
* 1. User is a bot owner, OR * player's voice channel to control it.
* 2. User is in the same voice channel as the bot, OR
* 3. User is a member of the same guild as the player (dashboard control)
*
* The third case is important for dashboard users who control the bot
* remotely — they may not be in the voice channel themselves but still
* need to control playback from the web interface.
* *
* @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 if user is in the same voice channel as the bot // 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; if (infoChannelId === cleanChanId) return null; // authorized
} }
} }
} }
// Dashboard control: if the user is a member of the same guild as
// the player, allow control. This enables web dashboard users who
// aren't in the voice channel to still control playback.
const guildId = player._guildId;
if (guildId) {
const cleanGuildId = String(guildId).replace(/\D/g, "");
const guild = this.remix.client?.guilds?.get?.(guildId) ??
this.remix.client?.guilds?.get?.(cleanGuildId);
if (guild?.members?.has?.(cleanUserId)) {
return null;
}
}
return "You must be in the same voice channel as the bot to control playback"; return "You must be in the same voice channel as the bot to control playback";
} }
/** /**
* 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
@@ -354,42 +276,38 @@ export class Dashboard {
// ── Static converters ───────────────────────────────────────────────────── // ── Static converters ─────────────────────────────────────────────────────
/** /**
* Re-publish "connected" to the info channel so the backend can * @typedef APIUser
* re-initialize its PlayerManager with fresh data. Called after * @property {string} id
* session recovery completes so the backend sees up-to-date players. * @property {string} username
* @property {string} displayName
* @property {Object} avatar
* @property {string} avatar.url
*/ */
announceReady() {
if (!this.enabled) return;
this.redis.readyMessage();
}
/** /**
* @param {import("@fluxerjs/core").User} user * @param {import("@fluxerjs/core").User} user
* @returns {APIUser}
*/ */
static convertUser(user) { static convertUser(user) {
// Build avatar URL — @fluxerjs/core may expose displayAvatarURL() or // Construct avatar CDN URL from the raw hash — mirrors how getSharedServers
// may just have a raw hash in user.avatar. Handle both cases. // builds icon URLs. @fluxerjs/core does NOT expose displayAvatarURL() or
let avatarUrl = null; // iconURL() methods (unlike Discord.js), so we build the URLs manually.
try { let avatarUrl = "";
if (typeof user.displayAvatarURL === "function") { if (user.avatar && typeof user.avatar === "string") {
avatarUrl = user.displayAvatarURL(); avatarUrl = `https://cdn.fluxer.app/avatars/${user.id}/${user.avatar}.webp`;
} } else if (typeof user.displayAvatarURL === "function") {
} catch (_) { /* not available */ } // Fallback: if the method exists, use it (future-proofing)
if (!avatarUrl && user.avatar) { avatarUrl = user.displayAvatarURL() ?? user.defaultAvatarURL ?? "";
const hash = String(typeof user.avatar === "object" ? (user.avatar.hash ?? user.avatar) : user.avatar); } else if (user.defaultAvatarURL) {
if (hash && hash !== "[object Object]") {
const ext = hash.startsWith("a_") ? ".gif" : ".webp";
avatarUrl = `https://cdn.fluxer.app/avatars/${user.id}/${hash}${ext}?size=128`;
}
}
if (!avatarUrl && typeof user.defaultAvatarURL === "string") {
avatarUrl = user.defaultAvatarURL; avatarUrl = user.defaultAvatarURL;
} }
return { return {
id: user.id, id: user.id,
username: user.username, username: user.username,
displayName: user.displayName ?? user.globalName ?? user.username, displayName: user.displayName ?? user.globalName ?? user.username,
avatar: { url: avatarUrl }, avatar: {
url: avatarUrl,
},
}; };
} }
@@ -421,19 +339,8 @@ export class Dashboard {
* @param {import("@fluxerjs/core").GuildChannel} channel * @param {import("@fluxerjs/core").GuildChannel} channel
*/ */
static convertChannel(channel) { static convertChannel(channel) {
// @fluxerjs/core exposes isVoice() on channels, not isVoiceBased(). const isVoice = channel.isVoiceBased?.() ?? false;
// Fall back to checking the type field if the method is unavailable. // Collect voice members for voice channels
let isVoice = false;
if (typeof channel.isVoice === "function") {
isVoice = channel.isVoice();
} else if (typeof channel.isVoiceBased === "function") {
isVoice = channel.isVoiceBased();
} else if (channel.isVoiceBased === true) {
isVoice = true;
} else {
const t = channel.type;
isVoice = t === 2 || t === 13 || t === "GUILD_VOICE" || t === "GUILD_STAGE_VOICE";
}
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);
@@ -451,116 +358,26 @@ 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,
isVoice, isVoice,
isCategory,
isText,
parentId: channel.parentId ?? null,
voiceParticipants, voiceParticipants,
mature: channel.nsfw ?? false, mature: channel.nsfw ?? false,
serverId: channel.guildId, serverId: channel.guildId,
}; };
} }
/**
* Build the CDN URL for a guild icon from the icon hash.
* @fluxerjs/core Guild objects expose `icon` as a hash string (e.g. "a_b1234")
* but do NOT expose an `iconURL()` method. Construct the URL manually.
* @param {import("@fluxerjs/core").Guild} guild
* @returns {string|null}
*/
static guildIconURL(guild, size = 128) {
if (!guild?.icon) return null;
// guild.icon may be "hash" or "a_hash" (animated prefix)
const hash = String(guild.icon);
const ext = hash.startsWith("a_") ? ".gif" : ".webp";
return `https://cdn.fluxer.app/icons/${guild.id}/${hash}${ext}?size=${size}`;
}
/**
* Convert a guild into a server-list item with voice channels.
* Used by both `allServers` and `getSharedServers` — keeps the
* response format consistent and avoids duplicating the channel
* extraction logic.
*
* @param {import("@fluxerjs/core").Guild} guild
* @returns {{name: string, id: string, icon: string|null, description: string|null, ownerId: string|null, voiceChannels: Object[]}}
*/
static convertServerForList(guild) {
// ── Extract voice channels safely ────────────────────────────────────
// guild.channels may be a Collection (Map) or an array depending on
// the @fluxerjs/core version. Normalise to an array first.
let channelArray = [];
try {
const ch = guild.channels;
if (Array.isArray(ch)) {
channelArray = ch;
} else if (ch && typeof ch.values === "function") {
channelArray = [...ch.values()];
} else if (ch && typeof ch.forEach === "function") {
ch.forEach(c => channelArray.push(c));
}
} catch (e) {
logger.dashboard("[Dashboard] convertServerForList: channel extraction error:", e.message);
}
const voiceChannels = channelArray
.filter(c => {
// @fluxerjs/core exposes isVoice() on channels.
// Fall back to isVoiceBased() or type field check.
if (typeof c.isVoice === "function") return c.isVoice();
if (typeof c.isVoiceBased === "function") return c.isVoiceBased();
if (c.isVoiceBased === true) return true;
// Fluxer API voice channel types: 2 = voice, 13 = stage
const t = c.type;
return t === 2 || t === 13 || t === "GUILD_VOICE" || t === "GUILD_STAGE_VOICE";
})
.map(c => {
// Build voice participants list for this channel
const voiceParticipants = [];
try {
if (guild.voice_states) {
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 scId = String(state?.channelId ?? state?.channel_id ?? "").replace(/\D/g, "");
const chId = String(c.id ?? "").replace(/\D/g, "");
if (scId === chId) {
const member = guild.members?.get?.(state?.userId ?? state?.user_id);
if (member?.user && !member.user.bot) {
voiceParticipants.push(Dashboard.convertUser(member.user));
}
}
}
}
} catch (e) {
// Voice participants are optional — don't fail the whole response
}
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,
};
});
return {
name: guild.name,
id: guild.id,
icon: Dashboard.guildIconURL(guild),
description: guild.description ?? null,
ownerId: guild.ownerId ?? null,
voiceChannels,
};
}
/** /**
* @param {import("@fluxerjs/core").Guild} guild * @param {import("@fluxerjs/core").Guild} guild
*/ */
@@ -576,23 +393,29 @@ export class Dashboard {
return { return {
name: guild.name, name: guild.name,
id: guild.id, id: guild.id,
icon: Dashboard.guildIconURL(guild), icon: guild.icon
? `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), channels: channelValues.map(Dashboard.convertChannel).filter(c => !c.isCategory),
}; };
} }
/** /**
* 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) {
return { return {
name: guild.name, name: guild.name,
id: guild.id, id: guild.id,
icon: Dashboard.guildIconURL(guild), icon: guild.icon
? `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,
}; };
@@ -609,11 +432,24 @@ export class Dashboard {
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 [];
const g = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId); const g = channel?.guild ?? channel?.client?.guilds?.get(channel?.guildId);
@@ -675,55 +511,29 @@ 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 on {platform}:players). * Global player update (broadcast to all dashboard listeners via fluxer:players).
* *
* Used for two purposes: * Lifecycle events ("init" / "close") are sent IMMEDIATELY so the backend
* 1. Lifecycle events: { type: "init" } / { type: "close" } — the backend * can create or destroy Player objects without delay. All other events
* PlayerManager uses these to add/remove Player objects. * ("update") are debounced to 500ms per player to avoid flooding Redis.
* 2. Full state broadcast: any other type — the full serialised player is
* included so dashboard frontends can update their UI.
* *
* Debounced: rapid successive calls for the same player are coalesced * Expected message format on fluxer:players:
* into a single publish every 500ms. * { type: "init"|"close"|"update", player: SerialisedPlayer }
* *
* @param {Object} details Must include a `type` field (e.g. "init", "close", * @param {Object} details Must include { type: "init"|"close"|"update" }
* "startplay", "stopplay", etc.) and may include a `data` field.
* @param {Player} player * @param {Player} player
*/ */
playerUpdate(details, player) { playerUpdate(details, player) {
if (!this.enabled) return; if (!this.enabled) return;
const key = player._channelId ?? player._guildId ?? "unknown"; const key = player._channelId ?? player._guildId ?? "unknown";
// For "init" and "close" events, send immediately (no debounce) — the const publish = () => {
// 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({
@@ -733,41 +543,33 @@ 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;
} }
// All other events are debounced to avoid flooding Redis. // Other updates 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);
try { publish();
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 (sent to {platform}:player_{channelId}). * Per-player channel update
* * @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) {
@@ -777,7 +579,7 @@ export class Dashboard {
} }
/** /**
* Global user update (sent to {platform}:users). * Global user update
* @param {Object} details * @param {Object} details
* @param {import("@fluxerjs/core").User} user * @param {import("@fluxerjs/core").User} user
*/ */
@@ -790,55 +592,9 @@ 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.";
}
} }
+16 -23
View File
@@ -61,9 +61,7 @@ export class RedisHandler {
try { try {
await this.client.connect(); await this.client.connect();
logger.redis("[Redis/Main] Connected"); logger.redis("[Redis/Main] Connected");
// Do NOT call readyMessage() here — the subscriber is not yet listening this.readyMessage();
// on the "request" channel. If we announce before subscribing, the
// backend will send requests that we miss, causing a timeout.
} catch (e) { } catch (e) {
logger.error("[Redis/Main] Initial connection failed:", e.message); logger.error("[Redis/Main] Initial connection failed:", e.message);
} }
@@ -72,10 +70,7 @@ export class RedisHandler {
await this.subscriber.connect(); await this.subscriber.connect();
logger.redis("[Redis/Subscriber] Connected"); logger.redis("[Redis/Subscriber] Connected");
// CRITICAL: Await both subscriptions so they are guaranteed to be active this.subscriber.subscribe("request", async (m) => {
// before we announce readiness. Without awaiting, there is a window
// where the backend sends requests that this bot cannot yet receive.
await this.subscriber.subscribe("request", async (m) => {
if (this._destroyed) return; if (this._destroyed) return;
try { try {
const payload = JSON.parse(m); const payload = JSON.parse(m);
@@ -88,20 +83,10 @@ export class RedisHandler {
})); }));
} catch (e) { } catch (e) {
logger.error("[Redis/Subscriber] Request handler error:", e.message); logger.error("[Redis/Subscriber] Request handler error:", e.message);
// Always send a response so the backend doesn't time out.
// Parse the id from the raw message so we can reply even when
// the handler threw before producing a result.
try {
const payload = JSON.parse(m);
this.send("response", JSON.stringify({
id: payload.id,
content: { error: "Internal bot error: " + e.message },
}));
} catch (_) { /* payload was unparseable — nothing we can do */ }
} }
}); });
await this.subscriber.subscribe("info", (m) => { this.subscriber.subscribe("info", (m) => {
if (this._destroyed) return; if (this._destroyed) return;
try { try {
const data = JSON.parse(m); const data = JSON.parse(m);
@@ -112,22 +97,30 @@ export class RedisHandler {
logger.warn("[Redis/Subscriber] Info handler error:", e.message); logger.warn("[Redis/Subscriber] Info handler error:", e.message);
} }
}); });
// NOW announce readiness — the subscriber is guaranteed to be listening
// on both "request" and "info", so the backend's requests will be
// received and handled.
this.readyMessage();
} catch (e) { } catch (e) {
logger.error("[Redis/Subscriber] Initial connection failed:", e.message); logger.error("[Redis/Subscriber] Initial connection failed:", e.message);
} }
} }
/**
* Send the "connected" announcement to the backend.
* Delayed by 5 seconds so the bot has time to initialise players,
* recovery manager, and Moonlink before the backend starts sending
* requests like fetchPlayers. Without this delay the backend's
* initChannels() fires before the bot's playerMap is populated,
* causing "Redis request timed out" errors and a retry loop.
*/
readyMessage() { readyMessage() {
if (this._destroyed) return;
if (this._readyTimer) clearTimeout(this._readyTimer);
this._readyTimer = setTimeout(() => {
this._readyTimer = null;
if (this._destroyed) return; if (this._destroyed) return;
this.send("info", JSON.stringify({ this.send("info", JSON.stringify({
platform: this.platform, platform: this.platform,
type: "connected", type: "connected",
})); }));
}, 5000);
} }
/** /**