hotfix - somechanges

This commit is contained in:
NoLogicAlan committed 2026-05-18 21:50:48 +03:00
1 parent f513da88ab
commit b5a94a4f60
4 files changed
+124 -75

No files matched your search

+33 -37
View File
@@ -224,6 +224,12 @@ export class Remix {
// _announcementChannelCache: TTL-based (5 min), auto-evicts stale entries // _announcementChannelCache: TTL-based (5 min), auto-evicts stale entries
this._announcementChannelCache = new Map(); this._announcementChannelCache = new Map();
this._announcementChannelTTL = 5 * 60 * 1000; // 5 min this._announcementChannelTTL = 5 * 60 * 1000; // 5 min
setInterval(() => {
const now = Date.now();
for (const [k, v] of this._announcementChannelCache) {
if (v.timestamp && now - v.timestamp > this._announcementChannelTTL) this._announcementChannelCache.delete(k);
}
}, 60_000);
this.intentionalLeaves = new Map(); this.intentionalLeaves = new Map();
// ── Gateway Handler ───────────────────────────────────────────────────── // ── Gateway Handler ─────────────────────────────────────────────────────
@@ -294,6 +300,7 @@ export class Remix {
// ── Bot ready ───────────────────────────────────────────────────────────── // ── Bot ready ─────────────────────────────────────────────────────────────
client.on(Events.Ready, async () => { client.on(Events.Ready, async () => {
try {
logger.player("Logged in as " + (client.user?.username ?? "bot")); logger.player("Logged in as " + (client.user?.username ?? "bot"));
// ── Attach proactive error handlers on WS shards ─────────────────── // ── Attach proactive error handlers on WS shards ───────────────────
@@ -348,6 +355,9 @@ export class Remix {
// Delegate remaining Ready work to the gateway handler (voice-state // Delegate remaining Ready work to the gateway handler (voice-state
// seeding, raw WS listener, presence rotation, tryAutoJoin). // seeding, raw WS listener, presence rotation, tryAutoJoin).
this.gatewayHandler.onReady(); this.gatewayHandler.onReady();
} catch (e) {
logger.error("[Ready] Fatal error in Ready handler:", e);
}
}); });
// ── FluxerRevoice Instance (shared across all players) ───────────────── // ── FluxerRevoice Instance (shared across all players) ─────────────────
@@ -629,7 +639,10 @@ export class Remix {
}); });
// ── Login ───────────────────────────────────────────────────────────────── // ── Login ─────────────────────────────────────────────────────────────────
client.login(config.token); client.login(config.token).catch(e => {
logger.error("[Startup] Login failed:", e.message);
process.exit(1);
});
} }
// ─── Helpers ────────────────────────────────────────────────────────────── // ─── Helpers ──────────────────────────────────────────────────────────────
@@ -795,6 +808,9 @@ export class Remix {
const homeChId = String(player._home247Channel ?? activeChId).replace(/\D/g, "") || activeChId; const homeChId = String(player._home247Channel ?? activeChId).replace(/\D/g, "") || activeChId;
this.players.playerMap.delete(activeChId); this.players.playerMap.delete(activeChId);
this.players._unindexPlayer?.(cleanGuildId, activeChId); this.players._unindexPlayer?.(cleanGuildId, activeChId);
// Clean up pending scrobble timer
const pendingScrobble = this.players._pendingScrobbleTimers?.get(cleanChannelId);
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this.players._pendingScrobbleTimers.delete(cleanChannelId); }
if (activeChId !== cleanChannelId) this.players.playerMap.delete(cleanChannelId); if (activeChId !== cleanChannelId) this.players.playerMap.delete(cleanChannelId);
if (homeChId !== activeChId) this.players.playerMap.delete(homeChId); if (homeChId !== activeChId) this.players.playerMap.delete(homeChId);
player.destroy(); player.destroy();
@@ -930,6 +946,10 @@ export class Remix {
const player = this.players.playerMap.get(cleanId); const player = this.players.playerMap.get(cleanId);
if (player) { if (player) {
this.players.playerMap.delete(cleanId); this.players.playerMap.delete(cleanId);
this.players._unindexPlayer(player._guildId, cleanId);
// Clean up pending scrobble timer
const pendingScrobble = this.players._pendingScrobbleTimers?.get(cleanId);
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this.players._pendingScrobbleTimers.delete(cleanId); }
await player.leave().catch(() => {}); await player.leave().catch(() => {});
player.destroy(); player.destroy();
} }
@@ -992,11 +1012,8 @@ export class Remix {
// 2. Fallback — check voiceCache for this guild (O(1) per guild) // 2. Fallback — check voiceCache for this guild (O(1) per guild)
if (!isMember) { if (!isMember) {
const cleanGuildId = String(guild.id).replace(/\D/g, ""); const cleanGuildId = String(guild.id).replace(/\D/g, "");
// Check if any human users are tracked in this guild const userLoc = this.voiceCache.getUserLocation(cleanGuildId, user.id);
const hasVoiceUsers = [...this.voiceCache.userLocations.values()].some( if (userLoc) isMember = true;
loc => loc.guildId === cleanGuildId
);
if (hasVoiceUsers) isMember = true;
} }
// 3. Slow path — REST fetch for large guilds with incomplete caches // 3. Slow path — REST fetch for large guilds with incomplete caches
@@ -1009,6 +1026,13 @@ export class Remix {
if (!isMember) continue; if (!isMember) continue;
const allChannels = guild.channels?.cache
? [...guild.channels.cache.values()].map(c => Dashboard.convertChannel(c)).filter(c => !c.isCategory)
: [];
const channelIds = guild.channels?.cache
? [...guild.channels.cache.keys()]
: [];
shared.push({ shared.push({
name: guild.name, name: guild.name,
id: guild.id, id: guild.id,
@@ -1017,37 +1041,9 @@ export class Remix {
: null, : null,
description: guild.description ?? null, description: guild.description ?? null,
ownerId: guild.ownerId ?? null, ownerId: guild.ownerId ?? null,
voiceChannels: guild.channels channels: allChannels,
.filter(c => c.isVoiceBased?.() ?? false) channelIds: channelIds,
.map(c => { voiceChannels: allChannels.filter(c => c.isVoice),
// Build voice participants list for this channel
const voiceParticipants = [];
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));
}
}
}
}
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,
};
}),
}); });
} }
+40 -22
View File
@@ -154,13 +154,15 @@ class PlayerWorkerPool {
} }
entry.busy = false; entry.busy = false;
// Replace dead worker // Replace dead worker
this._workers.splice(this._workers.indexOf(entry), 1); const errIdx = this._workers.indexOf(entry);
if (errIdx !== -1) this._workers.splice(errIdx, 1);
this._spawn(); this._spawn();
this._drain(); this._drain();
}); });
worker.on("exit", (code) => { worker.on("exit", (code) => {
this._workers.splice(this._workers.indexOf(entry), 1); const exitIdx = this._workers.indexOf(entry);
if (exitIdx !== -1) this._workers.splice(exitIdx, 1);
if (this._workers.length < this._size) this._spawn(); if (this._workers.length < this._size) this._spawn();
}); });
@@ -266,13 +268,15 @@ export class Queue extends EventEmitter {
addMany(tracks, top = false) { addMany(tracks, top = false) {
if (!tracks?.length) return 0; if (!tracks?.length) return 0;
if (!Array.isArray(tracks)) tracks = [];
const count = Math.min(tracks.length, 1000);
if (top) { if (top) {
for (let i = tracks.length - 1; i >= 0; i--) this.data.unshift(tracks[i]); for (let i = count - 1; i >= 0; i--) this.data.unshift(tracks[i]);
} else { } else {
this.data.push(...tracks); for (let i = 0; i < count; i++) this.data.push(tracks[i]);
} }
this.emit("queue", { type: "addMany", data: { append: !top, tracks } }); this.emit("queue", { type: "addMany", data: { append: !top, tracks: tracks.slice(0, count) } });
return tracks.length; return count;
} }
clear() { this.data.length = 0; } clear() { this.data.length = 0; }
@@ -401,7 +405,10 @@ export default class Player extends EventEmitter {
// Set inactivity limit // Set inactivity limit
const inactivityMs = this.config?.timers?.inactivityTimeout ?? this.config?.inactivityTimeout; const inactivityMs = this.config?.timers?.inactivityTimeout ?? this.config?.inactivityTimeout;
if (inactivityMs !== undefined) { if (inactivityMs !== undefined) {
this._inactivityLimit = inactivityMs; const parsed = Number(inactivityMs);
if (!Number.isNaN(parsed) && parsed >= 0) {
this._inactivityLimit = parsed;
}
} }
// moonlink.js manager reference — injected by PlayerManager // moonlink.js manager reference — injected by PlayerManager
@@ -530,10 +537,13 @@ export default class Player extends EventEmitter {
} }
if (savedVol !== undefined && savedVol !== null) { if (savedVol !== undefined && savedVol !== null) {
this.preferredVolume = Utils.clamp(savedVol / 100, 0, 2); const parsed = Number(savedVol);
if (!Number.isNaN(parsed) && parsed > 0) {
this.preferredVolume = Utils.clamp(parsed / 100, 0, 2);
logger.player(`[Player] Restored volume ${savedVol}% for guild ${this._guildId}`); logger.player(`[Player] Restored volume ${savedVol}% for guild ${this._guildId}`);
} }
} }
}
// ═══════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════
// Inactivity Timer // Inactivity Timer
@@ -791,7 +801,7 @@ export default class Player extends EventEmitter {
async _request(url, options = {}, returnStream = false) { async _request(url, options = {}, returnStream = false) {
return new Promise((resolve, reject) => { return new Promise((resolve, reject) => {
const fetchUrl = (target) => { const fetchUrl = (target, _redirects = 0) => {
const urlObj = new URL(target); const urlObj = new URL(target);
const client = urlObj.protocol === "https:" ? https : http; const client = urlObj.protocol === "https:" ? https : http;
@@ -814,7 +824,13 @@ export default class Player extends EventEmitter {
let loc = res.headers.location; let loc = res.headers.location;
if (!loc) return reject(new Error("Redirect without location")); if (!loc) return reject(new Error("Redirect without location"));
if (loc.startsWith("/")) loc = `${urlObj.protocol}//${urlObj.host}${loc}`; if (loc.startsWith("/")) loc = `${urlObj.protocol}//${urlObj.host}${loc}`;
return fetchUrl(loc); if (_redirects >= 5) return reject(new Error("Too many redirects"));
// Strip auth header on cross-origin redirects
const redirectUrl = new URL(loc);
if (redirectUrl.host !== urlObj.host) {
delete options.headers?.Authorization;
}
return fetchUrl(loc, _redirects + 1);
} }
if (![200, 204, 206].includes(res.statusCode)) { if (![200, 204, 206].includes(res.statusCode)) {
res.resume(); res.resume();
@@ -976,7 +992,7 @@ export default class Player extends EventEmitter {
// Dynamic safety timeout based on track duration. // Dynamic safety timeout based on track duration.
const trackDuration = this._getTrackDurationMs(currentTrack); const trackDuration = this._getTrackDurationMs(currentTrack);
const safetyMs = (trackDuration > 0 && currentTrack.type !== "radio") const safetyMs = (trackDuration > 0 && currentTrack?.type !== "radio")
? trackDuration + 15_000 ? trackDuration + 15_000
: 20 * 60 * 1000; // default 20 min for radio/unknown : 20 * 60 * 1000; // default 20 min for radio/unknown
@@ -1316,7 +1332,7 @@ export default class Player extends EventEmitter {
logger.player(`[Player] Voice connected to ${channel.name || channelId} via FluxerRevoice`); logger.player(`[Player] Voice connected to ${channel.name || channelId} via FluxerRevoice`);
if (!this.queue.isEmpty() && !this.queue.getCurrent()) { if (!this.queue.isEmpty() && !this.queue.getCurrent()) {
this.playNext(); this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
} else if (this.queue.isEmpty()) { } else if (this.queue.isEmpty()) {
this._pendingInactivityCheck = true; this._pendingInactivityCheck = true;
setTimeout(() => { setTimeout(() => {
@@ -1492,7 +1508,7 @@ export default class Player extends EventEmitter {
this._stopMediaPlayer().then(() => { this._stopMediaPlayer().then(() => {
this._playingNext = false; this._playingNext = false;
if (!this.queue.isEmpty() && !this.leaving) { if (!this.queue.isEmpty() && !this.leaving) {
this.playNext(); this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
} else { } else {
this.emit("stopplay"); this.emit("stopplay");
if (!this._is247Enabled()) { if (!this._is247Enabled()) {
@@ -1532,7 +1548,7 @@ export default class Player extends EventEmitter {
this._stopMediaPlayer().then(() => { this._stopMediaPlayer().then(() => {
this._playingNext = false; this._playingNext = false;
if (!this.queue.isEmpty() && !this.leaving) { if (!this.queue.isEmpty() && !this.leaving) {
this.playNext(); this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
} else { } else {
this.emit("stopplay"); this.emit("stopplay");
if (!this._is247Enabled()) { if (!this._is247Enabled()) {
@@ -1696,6 +1712,7 @@ export default class Player extends EventEmitter {
} }
addManyToQueue(t, top = false) { addManyToQueue(t, top = false) {
if (!Array.isArray(t)) return 0;
// Enforce queue size cap // Enforce queue size cap
const overflow = (this.queue.data.length + t.length) - this._maxQueueSize; const overflow = (this.queue.data.length + t.length) - this._maxQueueSize;
if (overflow > 0) { if (overflow > 0) {
@@ -1975,8 +1992,9 @@ export default class Player extends EventEmitter {
async fetchResults(query, id, provider = "ytm") { async fetchResults(query, id, provider = "ytm") {
try { try {
const data = await this.workerJob("searchResults", { query, provider, resultCount: this.resultLimit }); const data = await this.workerJob("searchResults", { query, provider, resultCount: this.resultLimit });
const results = Array.isArray(data?.data) ? data.data : [];
let list = `Search results using **${PROVIDER_NAMES[provider] || "YouTube Music"}**:\n\n`; let list = `Search results using **${PROVIDER_NAMES[provider] || "YouTube Music"}**:\n\n`;
data.data.forEach((v, i) => { results.forEach((v, i) => {
const url = v.url || ""; const url = v.url || "";
const title = v.title || Utils.formatTrackInfo(v, false); const title = v.title || Utils.formatTrackInfo(v, false);
const dur = v.duration ? this.getDuration(v.duration) : "?:??"; const dur = v.duration ? this.getDuration(v.duration) : "?:??";
@@ -1988,9 +2006,9 @@ export default class Player extends EventEmitter {
const oldestKey = this.searches.keys().next().value; const oldestKey = this.searches.keys().next().value;
if (oldestKey !== undefined) this.searches.delete(oldestKey); if (oldestKey !== undefined) this.searches.delete(oldestKey);
} }
this.searches.set(id, data.data); this.searches.set(id, results);
return { m: list, count: data.data.length }; return { m: list, count: results.length };
} catch (err) { } catch (err) {
return { m: `Error searching: ${err.message}`, count: 0 }; return { m: `Error searching: ${err.message}`, count: 0 };
} }
@@ -2007,7 +2025,7 @@ export default class Player extends EventEmitter {
this.searches.delete(id); this.searches.delete(id);
if (!this.queue.getCurrent()) { if (!this.queue.getCurrent()) {
this.playNext(); this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
} }
return res; return res;
} }
@@ -2044,7 +2062,7 @@ export default class Player extends EventEmitter {
} }
if (!this.queue.getCurrent()) { if (!this.queue.getCurrent()) {
this.playNext(); this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
} }
events.removeAllListeners(); events.removeAllListeners();
}) })
@@ -2077,7 +2095,7 @@ export default class Player extends EventEmitter {
playRadio(radio, top = false) { playRadio(radio, top = false) {
if (!radio?.url) { logger.error("[Player] Invalid radio data"); return; } if (!radio?.url) { logger.error("[Player] Invalid radio data"); return; }
this.addToQueue(this._buildRadioTrack(radio), top); this.addToQueue(this._buildRadioTrack(radio), top);
if (!this.queue.getCurrent()) this.playNext(); if (!this.queue.getCurrent()) this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
} }
async switchRadio(radio) { async switchRadio(radio) {
@@ -2088,7 +2106,7 @@ export default class Player extends EventEmitter {
if (!this.queue.getCurrent()) { if (!this.queue.getCurrent()) {
this.queue.add(newTrack); this.queue.add(newTrack);
this.playNext(); this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
return; return;
} }
@@ -2099,7 +2117,7 @@ export default class Player extends EventEmitter {
await this._stopMediaPlayer(); await this._stopMediaPlayer();
this._playingNext = false; this._playingNext = false;
this._skipping = false; this._skipping = false;
if (!this.leaving) this.playNext(); if (!this.leaving) this.playNext().catch(e => logger.error("[Player] playNext error:", e.message));
} }
// ═══════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════
+7 -7
View File
@@ -173,9 +173,11 @@ export class PlayerManager {
const result = []; const result = [];
for (const channelId of set) { for (const channelId of set) {
const player = this.playerMap.get(channelId); const player = this.playerMap.get(channelId);
if (player && !player._destroyed) { if (!player || player._destroyed) {
result.push([channelId, player]); set.delete(channelId); // prune stale entry
continue;
} }
result.push([channelId, player]);
} }
return result; return result;
} }
@@ -601,7 +603,6 @@ export class PlayerManager {
if (player) { if (player) {
player.textChannel = message.channel; player.textChannel = message.channel;
try { try {
const guildId = getMessageGuildId(message);
const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null; const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null;
if (guildId && textChannelId) { if (guildId && textChannelId) {
this.settings.getServer(guildId)?.set("announcementChannelId", textChannelId); this.settings.getServer(guildId)?.set("announcementChannelId", textChannelId);
@@ -859,6 +860,7 @@ export class PlayerManager {
if (this._pendingJoins.has(cleanChannelId)) { if (this._pendingJoins.has(cleanChannelId)) {
return message.reply(mkEmbed(this._t(message, "responses.join.joining"))); return message.reply(mkEmbed(this._t(message, "responses.join.joining")));
} }
this._pendingJoins.add(cleanChannelId);
const player = new Player(this.config.token, { const player = new Player(this.config.token, {
...this.playerConfig, ...this.playerConfig,
@@ -1020,10 +1022,7 @@ export class PlayerManager {
}); });
}); });
// Mark as "pending join" so concurrent getPlayer() / checkVoiceChannels() // _pendingJoins was already added earlier (right after duplicate check)
// calls can see a player is being created for this channel, but stats
// won't count it until the join actually succeeds.
this._pendingJoins.add(cleanChannelId);
(async () => { (async () => {
const statusMsg = await message.reply(mkEmbed(this._t(message, "responses.join.joining"))); const statusMsg = await message.reply(mkEmbed(this._t(message, "responses.join.joining")));
@@ -1066,6 +1065,7 @@ export class PlayerManager {
this.playerMap.delete(cleanChannelId); this.playerMap.delete(cleanChannelId);
this._unindexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId); this._unindexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId);
player.destroy(); player.destroy();
cb(null);
} }
})(); })();
} }
+44 -9
View File
@@ -33,7 +33,10 @@ export class Dashboard {
this.redis.setRequestHandler(async (data) => { this.redis.setRequestHandler(async (data) => {
switch (data.type) { switch (data.type) {
case "fetchPlayers": case "fetchPlayers":
return [...this.remix.players.playerMap.values()].map(p => Dashboard.convertPlayer(p)); return [...this.remix.players.playerMap.values()]
.filter(p => !p._destroyed)
.map(p => { try { return Dashboard.convertPlayer(p); } catch(_) { return null; } })
.filter(Boolean);
case "user": { case "user": {
const user = await this.remix.client.users.fetch(data.key).catch(() => null); const user = await this.remix.client.users.fetch(data.key).catch(() => null);
@@ -76,17 +79,43 @@ export class Dashboard {
} }
case "allServers": { case "allServers": {
// Auth check: owners see all servers, non-owners see only shared servers
//if (data.accessor && this.remix.handler?.owners?.includes?.(data.accessor)) {
try {
const guilds = await this.remix.client.user.fetchGuilds(); const guilds = await this.remix.client.user.fetchGuilds();
return guilds.map(g => Dashboard.convertServer(g)); return guilds.map(g => Dashboard.convertServer(g));
} catch (e) {
const id = Utils.uid();
logger.dashboard("[Dashboard] allServers error:", id, e);
return [];
}
//}
if (data.accessor) {
try {
const accessorUser = await this.remix.client.users.fetch(data.accessor).catch(() => null);
if (accessorUser) return await this.remix.getSharedServers(accessorUser);
} catch (_) {}
}
// Always return an array — backend does .findIndex() on result
return [];
} }
case "commands": case "commands": {
try {
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)
); );
} catch (e) {
logger.dashboard("[Dashboard] commands error:", e.message);
return [];
}
}
case "function": case "function":
return await this.runFunction(data.params); return await this.runFunction(data.params);
default:
return { error: "Unknown request type: " + (data.type ?? "(none)") };
} }
}); });
} }
@@ -327,6 +356,7 @@ export class Dashboard {
} }
case "leave": { case "leave": {
if (!user) return { error: "Invalid user" };
// Support both params.data.channel and params.data.player for // Support both params.data.channel and params.data.player for
// backward compatibility with different backend versions. // backward compatibility with different backend versions.
const playerId = params.data.channel ?? params.data.player; const playerId = params.data.channel ?? params.data.player;
@@ -606,13 +636,16 @@ export class Dashboard {
const cleanChannelId = channelId ? String(channelId).replace(/\D/g, "") : ""; const cleanChannelId = channelId ? String(channelId).replace(/\D/g, "") : "";
const cleanGuildId = player._guildId ? String(player._guildId).replace(/\D/g, "") : ""; const cleanGuildId = player._guildId ? String(player._guildId).replace(/\D/g, "") : "";
// Null-guard: player.queue can be null during teardown
const queue = player.queue ?? { loop: false, songLoop: false, current: null, data: [] };
return { return {
loop: (player.queue.loop ? 1 : 0) + (player.queue.songLoop ? 2 : 0), loop: (queue.loop ? 1 : 0) + (queue.songLoop ? 2 : 0),
paused: player._paused, paused: !!player._paused,
volume: (player.preferredVolume ?? 1) * 100, volume: Number.isFinite(player.preferredVolume) ? player.preferredVolume * 100 : 100,
queue: { queue: {
current: Dashboard.convertVideo(player.queue.current), current: Dashboard.convertVideo(queue.current),
data: (player.queue.data ?? []).map(v => Dashboard.convertVideo(v)), data: Array.isArray(queue.data) ? queue.data.slice(0, 500).map(v => Dashboard.convertVideo(v)) : [],
}, },
users: (() => { users: (() => {
if (!channel) return player._dashboardUsers ?? []; if (!channel) return player._dashboardUsers ?? [];
@@ -667,7 +700,7 @@ export class Dashboard {
// Merge dashboard users (connected via web UI but not necessarily in Discord voice) // Merge dashboard users (connected via web UI but not necessarily in Discord voice)
if (player._dashboardUsers) { if (player._dashboardUsers) {
for (const du of player._dashboardUsers) { for (const du of player._dashboardUsers) {
if (!ids.includes(du)) ids.push(du); if (!seen.has(du)) { ids.push(du); seen.add(du); }
} }
} }
return ids; return ids;
@@ -783,6 +816,7 @@ export class Dashboard {
} }
this._playerUpdateTimers.set(key, setTimeout(() => { this._playerUpdateTimers.set(key, setTimeout(() => {
this._playerUpdateTimers.delete(key); this._playerUpdateTimers.delete(key);
if (player._destroyed) return; // skip destroyed players
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({
@@ -861,7 +895,7 @@ export class Dashboard {
let res; let res;
try { try {
res = await this.db.execute("SELECT * FROM login_codes WHERE user=?", [user]); res = await this.db.execute("SELECT * FROM login_codes WHERE user=? AND (verified IS NULL OR verified != true)", [user]);
} catch (e) { } catch (e) {
const id = Utils.uid(); const id = Utils.uid();
logger.dashboard("[Dashboard] MySQL error, id:", id, e); logger.dashboard("[Dashboard] MySQL error, id:", id, e);
@@ -871,6 +905,7 @@ export class Dashboard {
if (res.length === 0) return "If this is a valid code, it was not created for your account."; 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++) { for (let i = 0; i < res.length; i++) {
if (res[i].verified) continue; // skip already-verified codes (double guard)
if (await this.db.compareHash(code, res[i].token)) { if (await this.db.compareHash(code, res[i].token)) {
if (Date.now() - this.expiryTime > (new Date(res[i].createdAt)).getTime()) { if (Date.now() - this.expiryTime > (new Date(res[i].createdAt)).getTime()) {
return "Login token expired"; return "Login token expired";