diff --git a/commands/forceleave.mjs b/commands/forceleave.mjs index bbddc31..46d1d01 100644 --- a/commands/forceleave.mjs +++ b/commands/forceleave.mjs @@ -28,8 +28,7 @@ export async function run(msg, data) { if (!targetChannel) return msg.reply(embed(this.t(msg, "responses.forceleave.channelNotFound"))); if (cleanId(msg.message.guildId) !== cleanId(targetChannel.guildId)) return msg.reply(embed(this.t(msg, "responses.forceleave.wrongServer"))); - const p = this.players.playerMap.get(cid) - ?? [...this.players.playerMap.values()].find((player) => cleanId(player?._channelId) === cid); + const p = this.players.findPlayerEntryByChannelId(cid)?.player ?? null; if (!p) return msg.reply(embed(this.t(msg, "responses.forceleave.playerNotFound"))); if (!p.connection) return msg.reply(embed(this.t(msg, "responses.forceleave.playerNotInit"))); await this.players.leave(msg, cid); diff --git a/commands/leave.mjs b/commands/leave.mjs index 1d7f0ec..cb53c47 100644 --- a/commands/leave.mjs +++ b/commands/leave.mjs @@ -1,5 +1,4 @@ import { CommandBuilder } from "../src/CommandHandler.mjs"; -import { logger } from "../src/constants/Logger.mjs"; import { EmbedBuilder } from "@fluxerjs/core"; import { getGlobalColor } from "../src/MessageHandler.mjs"; import { get247ChannelMode } from "../src/constants/Helpers247.mjs"; @@ -23,22 +22,6 @@ function cleanId(value) { return String(value ?? "").replace(/\D/g, ""); } -/** - * Resolve the guild ID from a player entry. - * Uses _guildId if set (populated after join() completes), otherwise falls - * back to the client channel cache. This is necessary because in the - * multi-voice scenario _guildId can still be null for a freshly-joined player, - * which caused guildPlayers to be empty and leave to report "not in voice". - */ -function resolvePlayerGuildId(player, mapKey, client) { - const direct = cleanId(player?._guildId); - if (direct) return direct; - const cid = cleanId(player?._channelId ?? mapKey); - if (!cid) return ""; - const ch = client?.channels?.get?.(cid); - return cleanId(ch?.guildId ?? ch?.guild?.id ?? ch?.server_id ?? ch?.serverId); -} - export async function run(msg, data) { const guildId = msg.channel?.guild?.id ?? msg.channel?.guildId @@ -49,15 +32,7 @@ export async function run(msg, data) { ?? msg.message?.serverId; const cleanGuildId = cleanId(guildId); - // Gather all active players in this guild. - // resolvePlayerGuildId handles players whose _guildId is still null by - // checking the channel cache — critical for the multi-voice use case where - // a player may have been joined before _guildId was written. - const client = this.client; - const guildPlayers = [...this.players.playerMap.entries()].filter(([mapKey, p]) => { - if (p?._destroyed) return false; - return resolvePlayerGuildId(p, mapKey, client) === cleanGuildId; - }); + const guildPlayers = this.players.findGuildPlayers(cleanGuildId); // Resolve the target channel to leave: // 1. If a channel option was provided, use that @@ -94,11 +69,8 @@ export async function run(msg, data) { // Match against both the map key and _channelId because after a voice-move // these can differ (the map key stays as the original join channel ID while // _channelId updates to the new channel). - const player = this.players.playerMap.get(targetChannelId) - ?? guildPlayers.find(([mapKey, p]) => - cleanId(p._channelId) === targetChannelId || cleanId(mapKey) === targetChannelId - )?.[1] - ?? null; + const playerEntry = this.players.findPlayerEntryByChannelId(targetChannelId); + const player = playerEntry?.player ?? null; if (!player) { // No player in that channel — check if user picked a non-voice channel @@ -142,90 +114,36 @@ export async function run(msg, data) { return mode === "auto"; }); - if (ch247.has(activeChannelId) || ch247.has(homeChannelId)) { - const matchChannel = ch247.has(homeChannelId) ? homeChannelId - : ch247.has(activeChannelId) ? activeChannelId - : null; - const mode = matchChannel ? get247ChannelMode(set, matchChannel) : "off"; + const matchChannel = ch247.has(homeChannelId) ? homeChannelId + : ch247.has(activeChannelId) ? activeChannelId + : null; + const mode = matchChannel ? get247ChannelMode(set, matchChannel) : "off"; + + if (matchChannel) { this.markIntentionalLeave(activeChannelId); - this.players.playerMap.delete(activeChannelId); - if (activeChannelId !== targetChannelId) this.players.playerMap.delete(targetChannelId); - if (homeChannelId !== activeChannelId) this.players.playerMap.delete(homeChannelId); + if (homeChannelId !== activeChannelId) this.markIntentionalLeave(homeChannelId); + + this.players.detachPlayer(player, targetChannelId); await player.leave().catch(() => {}); player.destroy(); + const respawnBaseDelay = this.config?.timers?.leave247RejoinDelay ?? 5000; + const respawnStagger = this.config?.timers?.rejoin247Delay ?? 3000; + if (mode === "auto") { msg.reply(embed(this.t(msg, "responses.leave.leftRejoin247", { channel: targetChannelId, prefix: set?.get("prefix") ?? "%" }))); - const leave247Delay = this.config?.timers?.leave247RejoinDelay ?? 5000; - setTimeout(() => { - if (this._spawnPlayer) { - this._spawnPlayer(guildId, homeChannelId).catch(e => - logger.warn("[leave] 247 rejoin failed for", homeChannelId, e.message) - ); - } - }, leave247Delay); - - // ── Rejoin other 24/7 auto channels that may have been disconnected ── - // If the gateway sent a guild-level leave, all other 24/7 auto channels - // also lost their connections. Schedule a rejoin for each one with a - // staggered delay to avoid overloading the global join queue. - if (other247AutoChannels.length > 0) { - const rejoinBaseDelay = leave247Delay; - const rejoinStagger = this.config?.timers?.rejoin247Delay ?? 3000; - for (let i = 0; i < other247AutoChannels.length; i++) { - const otherChannelId = other247AutoChannels[i]; - const otherPlayer = this.players.playerMap.get(otherChannelId); - // Only rejoin if the player is gone (was collateral-disconnected) - if (!otherPlayer || otherPlayer._destroyed) { - // Clean up the dead player from the map - if (otherPlayer) { - this.players.playerMap.delete(otherChannelId); - try { otherPlayer.destroy(); } catch (_) {} - } - const delay = rejoinBaseDelay + (i + 1) * rejoinStagger; - logger.recovery( - `[leave] Scheduling 247 auto-rejoin for collateral-disconnected channel ${otherChannelId} in ${delay}ms` - ); - setTimeout(() => { - if (this._spawnPlayer) { - this._spawnPlayer(guildId, otherChannelId).catch(e => - logger.warn("[leave] 247 collateral rejoin failed for", otherChannelId, e.message) - ); - } - }, delay); - } - } - } + this.players.schedule247Respawns(guildId, [homeChannelId, ...other247AutoChannels], { + baseDelay: respawnBaseDelay, + stagger: respawnStagger, + source: "leave", + }); } else { - // Mode is "on" — bot left, won't rejoin automatically for this channel. - // But still check if other 24/7 auto channels need rejoining. msg.reply(embed(this.t(msg, "responses.leave.left247On", { prefix: set?.get("prefix") ?? "%" }))); - - if (other247AutoChannels.length > 0) { - const rejoinDelay = this.config?.timers?.leave247RejoinDelay ?? 5000; - const rejoinStagger = this.config?.timers?.rejoin247Delay ?? 3000; - for (let i = 0; i < other247AutoChannels.length; i++) { - const otherChannelId = other247AutoChannels[i]; - const otherPlayer = this.players.playerMap.get(otherChannelId); - if (!otherPlayer || otherPlayer._destroyed) { - if (otherPlayer) { - this.players.playerMap.delete(otherChannelId); - try { otherPlayer.destroy(); } catch (_) {} - } - const delay = rejoinDelay + (i + 1) * rejoinStagger; - logger.recovery( - `[leave] Scheduling 247 auto-rejoin for collateral-disconnected channel ${otherChannelId} in ${delay}ms` - ); - setTimeout(() => { - if (this._spawnPlayer) { - this._spawnPlayer(guildId, otherChannelId).catch(e => - logger.warn("[leave] 247 collateral rejoin failed for", otherChannelId, e.message) - ); - } - }, delay); - } - } - } + this.players.schedule247Respawns(guildId, other247AutoChannels, { + baseDelay: respawnBaseDelay, + stagger: respawnStagger, + source: "leave", + }); } } else { await this.leaveChannel(activeChannelId, guildId, msg); diff --git a/index.mjs b/index.mjs index c8409ac..f022696 100644 --- a/index.mjs +++ b/index.mjs @@ -721,10 +721,11 @@ export class Remix { } this.markIntentionalLeave(cleanId); + const playerEntry = this.players.findPlayerEntryByChannelId?.(cleanId) ?? null; + const player = playerEntry?.player ?? null; - const player = this.players.playerMap.get(cleanId); if (player) { - this.players.playerMap.delete(cleanId); + this.players.detachPlayer?.(player, cleanId); await player.leave().catch(() => {}); player.destroy(); } @@ -742,28 +743,22 @@ export class Remix { if (other247AutoChannels.length > 0) { const rejoinBaseDelay = this.T?.leave247RejoinDelay ?? 5000; const rejoinStagger = this.T?.rejoin247Delay ?? 3000; - for (let i = 0; i < other247AutoChannels.length; i++) { - const otherChannelId = other247AutoChannels[i]; - const otherPlayer = this.players.playerMap.get(otherChannelId); - // Only rejoin if the player is gone (was collateral-disconnected) + const channelsToRespawn = []; + for (const otherChannelId of other247AutoChannels) { + const otherPlayer = this.players.findPlayerEntryByChannelId?.(otherChannelId)?.player ?? null; if (!otherPlayer || otherPlayer._destroyed) { if (otherPlayer) { - this.players.playerMap.delete(otherChannelId); + this.players.detachPlayer?.(otherPlayer, otherChannelId); try { otherPlayer.destroy(); } catch (_) {} } - const delay = rejoinBaseDelay + (i + 1) * rejoinStagger; - logger.recovery( - `[leaveChannel] Scheduling 247 auto-rejoin for collateral-disconnected channel ${otherChannelId} in ${delay}ms` - ); - setTimeout(() => { - if (this._spawnPlayer) { - this._spawnPlayer(guildId, otherChannelId).catch(e => - logger.warn("[leaveChannel] 247 collateral rejoin failed for", otherChannelId, e.message) - ); - } - }, delay); + channelsToRespawn.push(otherChannelId); } } + this.players.schedule247Respawns?.(guildId, channelsToRespawn, { + baseDelay: rejoinBaseDelay, + stagger: rejoinStagger, + source: "leaveChannel", + }); } return true; diff --git a/src/Player.mjs b/src/Player.mjs index 54861e8..857b4c6 100644 --- a/src/Player.mjs +++ b/src/Player.mjs @@ -1364,6 +1364,7 @@ export default class Player extends EventEmitter { async leave() { if (!this.connection) return false; + let leftCleanly = false; try { this.leaving = true; this._stopInactivityTimer(); @@ -1393,19 +1394,22 @@ export default class Player extends EventEmitter { } await this.connection.leave(); - + leftCleanly = true; + } catch (e) { + logger.warn("[Player] leave warning:", e.message); + try { + await this.connection?.disconnect?.(); + } catch (_) {} + } finally { this.queue.reset(); this.connection = null; this._paused = false; this._pausedAt = null; this._playingNext = false; this.leaving = false; - } catch (e) { - logger.error("[Player] leave error:", e.message); - return false; } - this.emit("leave"); - return true; + if (leftCleanly) this.emit("leave"); + return leftCleanly; } destroy() { diff --git a/src/PlayerManager.mjs b/src/PlayerManager.mjs index 34e4121..5acbbe3 100644 --- a/src/PlayerManager.mjs +++ b/src/PlayerManager.mjs @@ -350,6 +350,78 @@ export class PlayerManager { return this.locale.translate(guildId, key, replacements); } + findPlayerEntryByChannelId(channelId) { + const cleanChannelId = cleanId(channelId); + if (!cleanChannelId) return null; + + const direct = this.playerMap.get(cleanChannelId); + if (direct) return { mapKey: cleanChannelId, player: direct }; + + for (const [mapKey, player] of this.playerMap.entries()) { + const activeChannelId = getPlayerChannelId(player, mapKey); + const homeChannelId = cleanId(player?._home247Channel); + if (activeChannelId === cleanChannelId || homeChannelId === cleanChannelId) { + return { mapKey: cleanId(mapKey), player }; + } + } + + return null; + } + + findGuildPlayers(guildId) { + const cleanGuildId = cleanId(guildId); + if (!cleanGuildId) return []; + + return [...this.playerMap.entries()].filter(([mapKey, player]) => { + if (!player || player._destroyed) return false; + const fallbackChannel = this.commands.client?.channels?.get?.(cleanId(mapKey)) ?? null; + return getPlayerGuildId(player, fallbackChannel) === cleanGuildId; + }); + } + + detachPlayer(player, fallbackChannelId = null) { + const activeChannelId = getPlayerChannelId(player, fallbackChannelId) || cleanId(fallbackChannelId); + const homeChannelId = cleanId(player?._home247Channel) || activeChannelId; + const keysToRemove = [...new Set([ + cleanId(fallbackChannelId), + activeChannelId, + homeChannelId, + ].filter(Boolean))]; + + for (const key of keysToRemove) { + this.playerMap.delete(key); + const pendingScrobble = this._pendingScrobbleTimers.get(key); + if (pendingScrobble) { + clearTimeout(pendingScrobble.timer); + this._pendingScrobbleTimers.delete(key); + } + } + + return { activeChannelId, homeChannelId, removedKeys: keysToRemove }; + } + + schedule247Respawns(guildId, channelIds, opts = {}) { + if (typeof this.spawnPlayer !== "function") return; + + const cleanGuildId = cleanId(guildId); + const uniqueChannels = [...new Set((channelIds ?? []).map(cleanId).filter(Boolean))]; + if (!cleanGuildId || uniqueChannels.length === 0) return; + + const baseDelay = Math.max(0, Number(opts.baseDelay ?? this.timers?.leave247RejoinDelay ?? 5_000)); + const stagger = Math.max(0, Number(opts.stagger ?? this.timers?.rejoin247Delay ?? 3_000)); + const source = opts.source ?? "247"; + + uniqueChannels.forEach((channelId, index) => { + const delay = baseDelay + (index * stagger); + logger.recovery(`[${source}] Scheduling 24/7 respawn for ${channelId} in ${delay}ms`); + setTimeout(() => { + this.spawnPlayer(cleanGuildId, channelId).catch((err) => { + logger.warn(`[${source}] 24/7 respawn failed for ${channelId}:`, err?.message ?? err); + }); + }, delay); + }); + } + // ═══════════════════════════════════════════════════════════════════════════ // Voice Channel Detection // ═══════════════════════════════════════════════════════════════════════════ @@ -724,28 +796,19 @@ export class PlayerManager { if (!cid) { const guildId = getMessageGuildId(msg); if (guildId) { - const matchedEntry = [...this.playerMap.entries()].find(([, player]) => - getPlayerGuildId(player) === cleanId(guildId) - ); + const matchedEntry = this.findGuildPlayers(guildId)[0] ?? null; cid = getPlayerChannelId(matchedEntry?.[1], matchedEntry?.[0]) || matchedEntry?.[0] || null; } } const cleanChannelId = cleanId(cid); - const player = cleanChannelId - ? this.playerMap.get(cleanChannelId) ?? - [...this.playerMap.values()].find((entry) => getPlayerChannelId(entry) === cleanChannelId) - : null; + const playerEntry = cleanChannelId ? this.findPlayerEntryByChannelId(cleanChannelId) : null; + const player = playerEntry?.player ?? null; if (!player) return msg.reply(mkEmbed(this._t(msg, "responses._common.notInVoice"))); - const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId; - this.playerMap.delete(activeChannelId); - // Clean up pending scrobble timer - const pendingScrobble = this._pendingScrobbleTimers.get(activeChannelId); - if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this._pendingScrobbleTimers.delete(activeChannelId); } - if (activeChannelId !== cleanChannelId) this.playerMap.delete(cleanChannelId); + this.detachPlayer(player, cleanChannelId); await msg.reply(mkEmbed(this._t(msg, "responses._common.successfullyLeft"))); - await player.leave(); + await player.leave().catch(() => {}); player.destroy(); } @@ -806,8 +869,7 @@ export class PlayerManager { }); player.on("autoleave", () => { - const activeChannelId = getPlayerChannelId(player, cleanChannelId) || cleanChannelId; - const homeChannelId = cleanId(player._home247Channel) || activeChannelId; + const { activeChannelId, homeChannelId } = this.detachPlayer(player, cleanChannelId); const ch = player.textChannel; const guildId = cleanId(player._guildId ?? ch?.guildId ?? ch?.guild?.id ?? getMessageGuildId({ channel: ch })); @@ -833,26 +895,15 @@ export class PlayerManager { ? get247ChannelMode(this.settings.getServer(guildId), matchChannel) : "off"; - // Remove player from map and destroy - this.playerMap.delete(activeChannelId); - // Clean up pending scrobble timer - const pendingScrobble = this._pendingScrobbleTimers.get(activeChannelId); - if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this._pendingScrobbleTimers.delete(activeChannelId); } - if (activeChannelId !== cleanChannelId) this.playerMap.delete(cleanChannelId); - if (homeChannelId !== activeChannelId) this.playerMap.delete(homeChannelId); player.destroy(); if (isIn247List && (mode247 === "on" || mode247 === "auto")) { - // 24/7 is active — rejoin after a short delay (same as RecoveryManager.spawnPlayer autoleave) const delay = this.timers?.rejoin247Delay ?? 3000; - if (this.spawnPlayer) { - logger.recovery(`[AutoLeave] 24/7 rejoin scheduled for ${homeChannelId} (mode ${mode247}) in ${delay}ms`); - setTimeout(() => { - this.spawnPlayer(guildId, homeChannelId).catch(e => - logger.warn("[AutoLeave] 24/7 rejoin failed for", homeChannelId, e.message) - ); - }, delay); - } + this.schedule247Respawns(guildId, [homeChannelId], { + baseDelay: delay, + stagger: 0, + source: "AutoLeave", + }); } else { // Not 24/7 — send inactivity message const prefix = (() => { diff --git a/src/RecoveryManager.mjs b/src/RecoveryManager.mjs index 7714b94..e284078 100644 --- a/src/RecoveryManager.mjs +++ b/src/RecoveryManager.mjs @@ -357,8 +357,11 @@ export class RecoveryManager { // ── Autoleave handler ─────────────────────────────────────────────────── p.on("autoleave", async () => { - const activeChannelId = String(p._channelId ?? cleanChannelId).replace(/\D/g, "") || cleanChannelId; - const homeChannelId = String(p._home247Channel ?? activeChannelId).replace(/\D/g, "") || activeChannelId; + const { activeChannelId, homeChannelId } = remix.players.detachPlayer?.(p, cleanChannelId) + ?? { + activeChannelId: String(p._channelId ?? cleanChannelId).replace(/\D/g, "") || cleanChannelId, + homeChannelId: String(p._home247Channel ?? cleanChannelId).replace(/\D/g, "") || cleanChannelId, + }; const raw2 = remix.settingsMgr.getServer(guildId).get("stay_247"); const channels2 = (!raw2 || raw2 === "none") @@ -375,13 +378,14 @@ export class RecoveryManager { ? get247ChannelMode(remix.settingsMgr.getServer(guildId), matchChannel) : "off"; - // Remove player from map and destroy it now that we've read the state. - remix.players.playerMap.delete(activeChannelId); - if (activeChannelId !== cleanChannelId) remix.players.playerMap.delete(cleanChannelId); p.destroy(); if (matchChannel && (mode2 === "on" || mode2 === "auto")) { - this.scheduleSpawn(guildId, homeChannelId, this.T.rejoin247Delay, "247-autoleave"); + remix.players.schedule247Respawns?.(guildId, [homeChannelId], { + baseDelay: this.T.rejoin247Delay, + stagger: 0, + source: "247-autoleave", + }); } else { try { const prefix = remix.handler?.getPrefix?.(guildId) ?? "%";