From b5a94a4f60837ae876219f7141755b1cc63c0e57 Mon Sep 17 00:00:00 2001 From: NoLogicAlan Date: Mon, 18 May 2026 21:50:48 +0300 Subject: [PATCH] hotfix - somechanges --- index.mjs | 70 +++++++++++++++++------------------ src/Player.mjs | 64 ++++++++++++++++++++------------ src/PlayerManager.mjs | 14 +++---- src/dashboard/Dashboard.mjs | 73 +++++++++++++++++++++++++++---------- 4 files changed, 135 insertions(+), 86 deletions(-) diff --git a/index.mjs b/index.mjs index 85341a0..e0bba49 100644 --- a/index.mjs +++ b/index.mjs @@ -224,6 +224,12 @@ export class Remix { // _announcementChannelCache: TTL-based (5 min), auto-evicts stale entries this._announcementChannelCache = new Map(); 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(); // ── Gateway Handler ───────────────────────────────────────────────────── @@ -294,6 +300,7 @@ export class Remix { // ── Bot ready ───────────────────────────────────────────────────────────── client.on(Events.Ready, async () => { + try { logger.player("Logged in as " + (client.user?.username ?? "bot")); // ── Attach proactive error handlers on WS shards ─────────────────── @@ -348,6 +355,9 @@ export class Remix { // Delegate remaining Ready work to the gateway handler (voice-state // seeding, raw WS listener, presence rotation, tryAutoJoin). this.gatewayHandler.onReady(); + } catch (e) { + logger.error("[Ready] Fatal error in Ready handler:", e); + } }); // ── FluxerRevoice Instance (shared across all players) ───────────────── @@ -629,7 +639,10 @@ export class Remix { }); // ── Login ───────────────────────────────────────────────────────────────── - client.login(config.token); + client.login(config.token).catch(e => { + logger.error("[Startup] Login failed:", e.message); + process.exit(1); + }); } // ─── Helpers ────────────────────────────────────────────────────────────── @@ -795,6 +808,9 @@ export class Remix { const homeChId = String(player._home247Channel ?? activeChId).replace(/\D/g, "") || activeChId; this.players.playerMap.delete(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 (homeChId !== activeChId) this.players.playerMap.delete(homeChId); player.destroy(); @@ -930,6 +946,10 @@ export class Remix { const player = this.players.playerMap.get(cleanId); if (player) { 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(() => {}); player.destroy(); } @@ -992,11 +1012,8 @@ export class Remix { // 2. Fallback — check voiceCache for this guild (O(1) per guild) if (!isMember) { const cleanGuildId = String(guild.id).replace(/\D/g, ""); - // Check if any human users are tracked in this guild - const hasVoiceUsers = [...this.voiceCache.userLocations.values()].some( - loc => loc.guildId === cleanGuildId - ); - if (hasVoiceUsers) isMember = true; + const userLoc = this.voiceCache.getUserLocation(cleanGuildId, user.id); + if (userLoc) isMember = true; } // 3. Slow path — REST fetch for large guilds with incomplete caches @@ -1009,6 +1026,13 @@ export class Remix { 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({ name: guild.name, id: guild.id, @@ -1017,37 +1041,9 @@ export class Remix { : null, description: guild.description ?? null, ownerId: guild.ownerId ?? null, - voiceChannels: guild.channels - .filter(c => c.isVoiceBased?.() ?? false) - .map(c => { - // 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, - }; - }), + channels: allChannels, + channelIds: channelIds, + voiceChannels: allChannels.filter(c => c.isVoice), }); } diff --git a/src/Player.mjs b/src/Player.mjs index e1e8d87..b98d52f 100644 --- a/src/Player.mjs +++ b/src/Player.mjs @@ -154,13 +154,15 @@ class PlayerWorkerPool { } entry.busy = false; // 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._drain(); }); 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(); }); @@ -266,13 +268,15 @@ export class Queue extends EventEmitter { addMany(tracks, top = false) { if (!tracks?.length) return 0; + if (!Array.isArray(tracks)) tracks = []; + const count = Math.min(tracks.length, 1000); 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 { - 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 } }); - return tracks.length; + this.emit("queue", { type: "addMany", data: { append: !top, tracks: tracks.slice(0, count) } }); + return count; } clear() { this.data.length = 0; } @@ -401,7 +405,10 @@ export default class Player extends EventEmitter { // Set inactivity limit const inactivityMs = this.config?.timers?.inactivityTimeout ?? this.config?.inactivityTimeout; 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 @@ -530,8 +537,11 @@ export default class Player extends EventEmitter { } if (savedVol !== undefined && savedVol !== null) { - this.preferredVolume = Utils.clamp(savedVol / 100, 0, 2); - logger.player(`[Player] Restored volume ${savedVol}% for guild ${this._guildId}`); + 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}`); + } } } @@ -791,7 +801,7 @@ export default class Player extends EventEmitter { async _request(url, options = {}, returnStream = false) { return new Promise((resolve, reject) => { - const fetchUrl = (target) => { + const fetchUrl = (target, _redirects = 0) => { const urlObj = new URL(target); const client = urlObj.protocol === "https:" ? https : http; @@ -814,7 +824,13 @@ export default class Player extends EventEmitter { let loc = res.headers.location; if (!loc) return reject(new Error("Redirect without location")); 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)) { res.resume(); @@ -976,7 +992,7 @@ export default class Player extends EventEmitter { // Dynamic safety timeout based on track duration. const trackDuration = this._getTrackDurationMs(currentTrack); - const safetyMs = (trackDuration > 0 && currentTrack.type !== "radio") + const safetyMs = (trackDuration > 0 && currentTrack?.type !== "radio") ? trackDuration + 15_000 : 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`); 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()) { this._pendingInactivityCheck = true; setTimeout(() => { @@ -1492,7 +1508,7 @@ export default class Player extends EventEmitter { this._stopMediaPlayer().then(() => { this._playingNext = false; if (!this.queue.isEmpty() && !this.leaving) { - this.playNext(); + this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); } else { this.emit("stopplay"); if (!this._is247Enabled()) { @@ -1532,7 +1548,7 @@ export default class Player extends EventEmitter { this._stopMediaPlayer().then(() => { this._playingNext = false; if (!this.queue.isEmpty() && !this.leaving) { - this.playNext(); + this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); } else { this.emit("stopplay"); if (!this._is247Enabled()) { @@ -1696,6 +1712,7 @@ export default class Player extends EventEmitter { } addManyToQueue(t, top = false) { + if (!Array.isArray(t)) return 0; // Enforce queue size cap const overflow = (this.queue.data.length + t.length) - this._maxQueueSize; if (overflow > 0) { @@ -1975,8 +1992,9 @@ export default class Player extends EventEmitter { async fetchResults(query, id, provider = "ytm") { try { 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`; - data.data.forEach((v, i) => { + results.forEach((v, i) => { const url = v.url || ""; const title = v.title || Utils.formatTrackInfo(v, false); 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; 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) { return { m: `Error searching: ${err.message}`, count: 0 }; } @@ -2007,7 +2025,7 @@ export default class Player extends EventEmitter { this.searches.delete(id); if (!this.queue.getCurrent()) { - this.playNext(); + this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); } return res; } @@ -2044,7 +2062,7 @@ export default class Player extends EventEmitter { } if (!this.queue.getCurrent()) { - this.playNext(); + this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); } events.removeAllListeners(); }) @@ -2077,7 +2095,7 @@ export default class Player extends EventEmitter { playRadio(radio, top = false) { if (!radio?.url) { logger.error("[Player] Invalid radio data"); return; } 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) { @@ -2088,7 +2106,7 @@ export default class Player extends EventEmitter { if (!this.queue.getCurrent()) { this.queue.add(newTrack); - this.playNext(); + this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); return; } @@ -2099,7 +2117,7 @@ export default class Player extends EventEmitter { await this._stopMediaPlayer(); this._playingNext = false; this._skipping = false; - if (!this.leaving) this.playNext(); + if (!this.leaving) this.playNext().catch(e => logger.error("[Player] playNext error:", e.message)); } // ═══════════════════════════════════════════════════════════════════════════ diff --git a/src/PlayerManager.mjs b/src/PlayerManager.mjs index 79a8074..f43e877 100644 --- a/src/PlayerManager.mjs +++ b/src/PlayerManager.mjs @@ -173,9 +173,11 @@ export class PlayerManager { const result = []; for (const channelId of set) { const player = this.playerMap.get(channelId); - if (player && !player._destroyed) { - result.push([channelId, player]); + if (!player || player._destroyed) { + set.delete(channelId); // prune stale entry + continue; } + result.push([channelId, player]); } return result; } @@ -601,7 +603,6 @@ export class PlayerManager { if (player) { player.textChannel = message.channel; try { - const guildId = getMessageGuildId(message); const textChannelId = message?.channel?.id ?? message?.channel?.channel?.id ?? null; if (guildId && textChannelId) { this.settings.getServer(guildId)?.set("announcementChannelId", textChannelId); @@ -859,6 +860,7 @@ export class PlayerManager { if (this._pendingJoins.has(cleanChannelId)) { return message.reply(mkEmbed(this._t(message, "responses.join.joining"))); } + this._pendingJoins.add(cleanChannelId); const player = new Player(this.config.token, { ...this.playerConfig, @@ -1020,10 +1022,7 @@ export class PlayerManager { }); }); - // Mark as "pending join" so concurrent getPlayer() / checkVoiceChannels() - // 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); + // _pendingJoins was already added earlier (right after duplicate check) (async () => { const statusMsg = await message.reply(mkEmbed(this._t(message, "responses.join.joining"))); @@ -1066,6 +1065,7 @@ export class PlayerManager { this.playerMap.delete(cleanChannelId); this._unindexPlayer(channel.guildId ?? getMessageGuildId(message), cleanChannelId); player.destroy(); + cb(null); } })(); } diff --git a/src/dashboard/Dashboard.mjs b/src/dashboard/Dashboard.mjs index 67af196..c246793 100644 --- a/src/dashboard/Dashboard.mjs +++ b/src/dashboard/Dashboard.mjs @@ -33,7 +33,10 @@ export class Dashboard { this.redis.setRequestHandler(async (data) => { switch (data.type) { 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": { const user = await this.remix.client.users.fetch(data.key).catch(() => null); @@ -76,17 +79,43 @@ export class Dashboard { } case "allServers": { - const guilds = await this.remix.client.user.fetchGuilds(); - return guilds.map(g => Dashboard.convertServer(g)); + // 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(); + 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": - return this.remix.handler.commands.map(c => - Dashboard.convertCommand(c, this.remix.handler) - ); + case "commands": { + try { + return this.remix.handler.commands.map(c => + Dashboard.convertCommand(c, this.remix.handler) + ); + } catch (e) { + logger.dashboard("[Dashboard] commands error:", e.message); + return []; + } + } case "function": return await this.runFunction(data.params); + + default: + return { error: "Unknown request type: " + (data.type ?? "(none)") }; } }); } @@ -146,7 +175,7 @@ export class Dashboard { // 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())); + (typeof ch.isText === "function" && ch.isText())); if (!isText(textChannel)) { // Auto-pick a text channel from the guild @@ -327,6 +356,7 @@ export class Dashboard { } case "leave": { + if (!user) return { error: "Invalid user" }; // Support both params.data.channel and params.data.player for // backward compatibility with different backend versions. const playerId = params.data.channel ?? params.data.player; @@ -501,8 +531,8 @@ export class Dashboard { // 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()) + type === 0 || type === 5 || type === 13 || + (typeof channel.isText === "function" && channel.isText()) ); let voiceParticipants = []; if (isVoice) { @@ -550,8 +580,8 @@ export class Dashboard { ? [...channelStore.values()] : []; const allChannels = channelValues - .map(Dashboard.convertChannel) - .filter(c => !c.isCategory); // exclude categories — they are not joinable + .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 @@ -606,13 +636,16 @@ export class Dashboard { const cleanChannelId = channelId ? String(channelId).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 { - loop: (player.queue.loop ? 1 : 0) + (player.queue.songLoop ? 2 : 0), - paused: player._paused, - volume: (player.preferredVolume ?? 1) * 100, + loop: (queue.loop ? 1 : 0) + (queue.songLoop ? 2 : 0), + paused: !!player._paused, + volume: Number.isFinite(player.preferredVolume) ? player.preferredVolume * 100 : 100, queue: { - current: Dashboard.convertVideo(player.queue.current), - data: (player.queue.data ?? []).map(v => Dashboard.convertVideo(v)), + current: Dashboard.convertVideo(queue.current), + data: Array.isArray(queue.data) ? queue.data.slice(0, 500).map(v => Dashboard.convertVideo(v)) : [], }, users: (() => { 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) if (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; @@ -783,6 +816,7 @@ export class Dashboard { } this._playerUpdateTimers.set(key, setTimeout(() => { this._playerUpdateTimers.delete(key); + if (player._destroyed) return; // skip destroyed players try { const serialised = Dashboard.convertPlayer(player); this.redis.send(this.redis.platform + ":players", JSON.stringify({ @@ -861,7 +895,7 @@ export class Dashboard { let res; 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) { const id = Utils.uid(); 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."; 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 (Date.now() - this.expiryTime > (new Date(res[i].createdAt)).getTime()) { return "Login token expired";