mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-23 21:52:45 -05:00
dashboard works
This commit is contained in:
1 parent
777c610b55
commit
009ec31dd8
5 files changed
+129
-35
No files matched your search
@@ -46,6 +46,7 @@ export class Remix {
|
||||
this.dashboard = new Dashboard(this, {
|
||||
enabled: config.dashboard?.enabled,
|
||||
redis: config.dashboard?.redis,
|
||||
mysql: config.mysql,
|
||||
});
|
||||
|
||||
const presenceContents = config.presenceContents ?? [];
|
||||
@@ -238,13 +239,14 @@ export class Remix {
|
||||
const ALONE_CHECK_INTERVAL = this.T.aloneCheckInterval;
|
||||
setInterval(() => {
|
||||
for (const [mapKey, player] of this.players.playerMap) {
|
||||
let channelId = mapKey;
|
||||
try {
|
||||
const guildId = player._guildId;
|
||||
if (!guildId) continue;
|
||||
|
||||
if (player._isJoining || player._isRecovering) continue;
|
||||
|
||||
const channelId = player._channelId ?? mapKey;
|
||||
channelId = player._channelId ?? mapKey;
|
||||
const cleanChanId = String(channelId).replace(/\D/g, "");
|
||||
if (!cleanChanId) continue;
|
||||
|
||||
@@ -539,49 +541,82 @@ export class Remix {
|
||||
async getSharedServers(user) {
|
||||
if (!user) return [];
|
||||
|
||||
const userId = String(user.id);
|
||||
const shared = [];
|
||||
const guilds = [...this.client.guilds.values()];
|
||||
|
||||
for (const guild of this.client.guilds.values()) {
|
||||
logger.dashboard(`[getSharedServers] Checking ${guilds.length} guilds for user ${userId}`);
|
||||
|
||||
for (const guild of guilds) {
|
||||
let isMember = false;
|
||||
const guildId = guild.id;
|
||||
|
||||
// 1. Fast path — check cached members
|
||||
if (guild.members?.has?.(user.id)) {
|
||||
if (guild.members?.has?.(userId)) {
|
||||
isMember = true;
|
||||
logger.dashboard(`[getSharedServers] guild ${guild.name} (${guildId}): cache HIT`);
|
||||
}
|
||||
|
||||
// 2. Fallback — observed voice users (REST-less)
|
||||
// 2. Fallback — observed voice users (no REST needed)
|
||||
if (!isMember) {
|
||||
const cleanGuildId = String(guild.id).replace(/\D/g, "");
|
||||
for (const [, info] of (this.observedVoiceUsers ?? [])) {
|
||||
if (String(info.guildId ?? "").replace(/\D/g, "") === cleanGuildId) {
|
||||
const cleanGuildId = String(guildId).replace(/\D/g, "");
|
||||
for (const [obsUid, info] of (this.observedVoiceUsers ?? [])) {
|
||||
if (String(obsUid).replace(/\D/g, "") === userId.replace(/\D/g, "") &&
|
||||
String(info.guildId ?? "").replace(/\D/g, "") === cleanGuildId) {
|
||||
isMember = true;
|
||||
logger.dashboard(`[getSharedServers] guild ${guild.name} (${guildId}): observedVoiceUsers HIT`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Slow path — REST fetch for large guilds with incomplete caches
|
||||
// 3. REST lookup — use guild.members.resolve() which checks cache then API.
|
||||
// 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) {
|
||||
try {
|
||||
const member = await guild.members.fetch(user.id).catch(() => null);
|
||||
if (member) isMember = true;
|
||||
} catch (_) { /* not a member or fetch failed */ }
|
||||
// guild.members.resolve(userId) — cache + REST fallback (Fluxer v1.2+)
|
||||
if (typeof guild.members?.resolve === "function") {
|
||||
const member = await guild.members.resolve(userId);
|
||||
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;
|
||||
|
||||
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, id: c.id, icon: null })),
|
||||
});
|
||||
shared.push(Dashboard.convertServerForList(guild));
|
||||
}
|
||||
|
||||
logger.dashboard(`[getSharedServers] Found ${shared.length} mutual servers for user ${userId}`);
|
||||
return shared;
|
||||
}
|
||||
|
||||
@@ -657,6 +692,13 @@ const saveAndExit = async () => {
|
||||
} catch (e) {
|
||||
logger.error("[Shutdown] Failed to close Redis:", e.message);
|
||||
}
|
||||
try {
|
||||
if (remix.dashboard?.db?.close) {
|
||||
await remix.dashboard.db.close();
|
||||
}
|
||||
} catch (e) {
|
||||
logger.error("[Shutdown] Failed to close Dashboard DB:", e.message);
|
||||
}
|
||||
process.exit(0);
|
||||
};
|
||||
|
||||
|
||||
+23
-11
@@ -64,6 +64,12 @@ export class GatewayHandler {
|
||||
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, "");
|
||||
if (!cleanUserId) return { key: null, value: null };
|
||||
|
||||
@@ -507,9 +513,9 @@ export class GatewayHandler {
|
||||
try { await client.users.fetch(userId).catch(() => {}); } catch (_) {}
|
||||
}
|
||||
if (userObj) {
|
||||
// Send user update on the global :users channel
|
||||
const details = {
|
||||
event: "voiceStateUpdate",
|
||||
userId,
|
||||
type: channelId ? "join" : "leave",
|
||||
guildId: resolvedGuildId,
|
||||
channelId: channelId ?? null,
|
||||
oldChannelId: oldChannelId ?? null,
|
||||
@@ -517,19 +523,25 @@ export class GatewayHandler {
|
||||
remix.dashboard.updateUser(details, userObj);
|
||||
}
|
||||
|
||||
// Send per-player channel events for join/leave
|
||||
const refChannel = channelId ?? oldChannelId;
|
||||
const cleanId = refChannel ? String(refChannel).replace(/\D/g, "") : null;
|
||||
const cleanId_ref = refChannel ? String(refChannel).replace(/\D/g, "") : null;
|
||||
|
||||
if (cleanId) {
|
||||
const player = remix.players.playerMap.get(cleanId);
|
||||
if (cleanId_ref) {
|
||||
const player = remix.players.playerMap.get(cleanId_ref);
|
||||
if (player) {
|
||||
// Send "join" or "leave" on the per-player channel
|
||||
// (matching Stoat format: { type, data } where data = userId)
|
||||
const eventType = channelId ? "join" : "leave";
|
||||
remix.dashboard.updatePlayer({
|
||||
guildId: player._guildId,
|
||||
channelId: player._channelId,
|
||||
playing: player.playing ?? false,
|
||||
paused: player.paused ?? false,
|
||||
queueLength: player.queue?.length ?? 0,
|
||||
});
|
||||
type: eventType,
|
||||
data: userId,
|
||||
}, player);
|
||||
|
||||
// Also update the global players channel with current player state
|
||||
remix.dashboard.playerUpdate({
|
||||
type: eventType,
|
||||
}, player);
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
@@ -660,6 +660,16 @@ export class RecoveryManager {
|
||||
`(${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).
|
||||
// If the process crashes mid-recovery, the file still exists for next boot.
|
||||
if (recoveryFileExisted) {
|
||||
|
||||
@@ -353,6 +353,16 @@ export class Dashboard {
|
||||
|
||||
// ── Static converters ─────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Re-publish "connected" to the info channel so the backend can
|
||||
* re-initialize its PlayerManager with fresh data. Called after
|
||||
* session recovery completes so the backend sees up-to-date players.
|
||||
*/
|
||||
announceReady() {
|
||||
if (!this.enabled) return;
|
||||
this.redis.readyMessage();
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {import("@fluxerjs/core").User} user
|
||||
*/
|
||||
|
||||
@@ -61,7 +61,9 @@ export class RedisHandler {
|
||||
try {
|
||||
await this.client.connect();
|
||||
logger.redis("[Redis/Main] Connected");
|
||||
this.readyMessage();
|
||||
// Do NOT call readyMessage() here — the subscriber is not yet listening
|
||||
// on the "request" channel. If we announce before subscribing, the
|
||||
// backend will send requests that we miss, causing a timeout.
|
||||
} catch (e) {
|
||||
logger.error("[Redis/Main] Initial connection failed:", e.message);
|
||||
}
|
||||
@@ -70,7 +72,10 @@ export class RedisHandler {
|
||||
await this.subscriber.connect();
|
||||
logger.redis("[Redis/Subscriber] Connected");
|
||||
|
||||
this.subscriber.subscribe("request", async (m) => {
|
||||
// CRITICAL: Await both subscriptions so they are guaranteed to be active
|
||||
// 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;
|
||||
try {
|
||||
const payload = JSON.parse(m);
|
||||
@@ -83,10 +88,20 @@ export class RedisHandler {
|
||||
}));
|
||||
} catch (e) {
|
||||
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 */ }
|
||||
}
|
||||
});
|
||||
|
||||
this.subscriber.subscribe("info", (m) => {
|
||||
await this.subscriber.subscribe("info", (m) => {
|
||||
if (this._destroyed) return;
|
||||
try {
|
||||
const data = JSON.parse(m);
|
||||
@@ -97,6 +112,11 @@ export class RedisHandler {
|
||||
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) {
|
||||
logger.error("[Redis/Subscriber] Initial connection failed:", e.message);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user