mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
hotfix :P
This commit is contained in:
1 parent
ee460d03ff
commit
7fadc67ee4
4 files changed
+390
-514
No files matched your search
+254
-78
@@ -1102,7 +1102,10 @@ export class GatewayHandler {
|
||||
}
|
||||
}
|
||||
|
||||
// Bot disconnected unexpectedly — check 24/7 before destroying player
|
||||
// Bot disconnected unexpectedly — handle based on 24/7 mode:
|
||||
// %247 auto → clean up old player and schedule rejoin (always stays in voice)
|
||||
// %247 on → emit autoleave (only rejoins on reboot, not on disconnect)
|
||||
// off → emit autoleave
|
||||
if (!channelId && oldChannelId && guildId) {
|
||||
try {
|
||||
const cleanOld = String(oldChannelId).replace(/\D/g, "");
|
||||
@@ -1110,35 +1113,48 @@ export class GatewayHandler {
|
||||
if (remix.intentionalLeaves.has(cleanOld)) {
|
||||
logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — intentional leave.`);
|
||||
} else {
|
||||
const player = remix.players.playerMap.get(cleanOld);
|
||||
if (player && !player.leaving && !player._destroyed) {
|
||||
// ── 24/7 channel protection ────────────────────────────────────
|
||||
// If this channel has 24/7 enabled (mode "on" or "auto"), the
|
||||
// gateway may have sent a spurious VOICE_STATE_UPDATE with
|
||||
// channel_id=null when the bot joined a channel in another guild.
|
||||
// Instead of destroying the player, schedule a rejoin so the bot
|
||||
// stays in the 24/7 channel.
|
||||
const is247 = player._is247Enabled?.();
|
||||
if (is247) {
|
||||
// Check 24/7 mode for this channel
|
||||
const set = remix.settingsMgr.getServer(guildId);
|
||||
const mode = set ? get247ChannelMode(set, cleanOld) : "off";
|
||||
|
||||
if (mode === "auto") {
|
||||
logger.voice247(
|
||||
`[VoiceState] Bot unexpectedly disconnected from 24/7 channel ${cleanOld} ` +
|
||||
`(guild ${cleanGuild}) — scheduling rejoin instead of autoleave.`
|
||||
`[VoiceState] Bot unexpectedly disconnected from ${cleanOld} (24/7 auto) — cleaning up and scheduling rejoin.`
|
||||
);
|
||||
// Clean up the dead player/connection first
|
||||
const player = remix.players.playerMap.get(cleanOld);
|
||||
if (player && !player._destroyed) {
|
||||
// Remove from player map first to prevent stale lookups
|
||||
remix.players.playerMap.delete(cleanOld);
|
||||
// Also clean up any alternate keys
|
||||
const homeChannel = String(player._home247Channel ?? "").replace(/\D/g, "");
|
||||
if (homeChannel && homeChannel !== cleanOld) {
|
||||
remix.players.playerMap.delete(homeChannel);
|
||||
}
|
||||
// Destroy the player (stops media, disconnects room)
|
||||
try { player.destroy(); } catch (_) {}
|
||||
// Schedule a rejoin after a short delay
|
||||
// Clean up pending scrobble timer if any
|
||||
const pendingScrobble = remix.players._pendingScrobbleTimers?.get(cleanOld);
|
||||
if (pendingScrobble) {
|
||||
clearTimeout(pendingScrobble.timer);
|
||||
remix.players._pendingScrobbleTimers.delete(cleanOld);
|
||||
}
|
||||
}
|
||||
// Schedule rejoin with delay to avoid overwhelming LiveKit.
|
||||
// The delay also gives the Fluxer gateway time to process the
|
||||
// leave signal before we attempt a new VOICE_STATE_UPDATE.
|
||||
const rejoinDelay = this.T.rejoin247Delay ?? 3_000;
|
||||
setTimeout(() => {
|
||||
if (remix._spawnPlayer) {
|
||||
logger.voice247(`[VoiceState] Rejoining 24/7 channel ${cleanOld} after unexpected disconnect`);
|
||||
remix._spawnPlayer(cleanGuild, cleanOld).catch(e =>
|
||||
logger.warn(`[VoiceState] 24/7 rejoin failed for ${cleanOld}:`, e.message)
|
||||
);
|
||||
}
|
||||
this._rejoinChannel(cleanGuild, cleanOld).catch(err => {
|
||||
logger.warn(`[VoiceState] Failed to rejoin ${cleanOld} after disconnect:`, err.message);
|
||||
});
|
||||
}, rejoinDelay);
|
||||
} else {
|
||||
logger.voiceState(`[VoiceState] Bot disconnected from ${cleanOld} — emitting autoleave.`);
|
||||
// %247 on or off: just emit autoleave (no reconnect on disconnect)
|
||||
const player = remix.players.playerMap.get(cleanOld);
|
||||
if (player && !player.leaving && !player._destroyed) {
|
||||
logger.voiceState(
|
||||
`[VoiceState] Bot disconnected from ${cleanOld} (24/7 mode: ${mode}) — emitting autoleave.`
|
||||
);
|
||||
player.emit("autoleave");
|
||||
}
|
||||
}
|
||||
@@ -1149,11 +1165,126 @@ export class GatewayHandler {
|
||||
}
|
||||
}
|
||||
|
||||
// ── Rejoin a single channel after disconnect (for %247 auto) ──────────────
|
||||
|
||||
/** @type {Set<string>} Channel IDs currently being rejoined (dedup guard) */
|
||||
_rejoinInProgress = new Set();
|
||||
|
||||
/** @type {Map<string, number>} Channel IDs with retry attempt counts */
|
||||
_rejoinAttempts = new Map();
|
||||
|
||||
/** @type {number} Maximum number of rejoin retry attempts */
|
||||
static MAX_REJOIN_RETRIES = 3;
|
||||
|
||||
/**
|
||||
* Rejoin a voice channel after an unexpected disconnect.
|
||||
* Used by the %247 auto mode to automatically reconnect.
|
||||
*
|
||||
* Includes deduplication (prevents concurrent rejoin for the same channel)
|
||||
* and retry with exponential backoff for transient failures like track
|
||||
* publication timeouts.
|
||||
*
|
||||
* @param {string} guildId
|
||||
* @param {string} channelId
|
||||
* @param {number} [attempt=1] Current attempt number (for retry logic)
|
||||
*/
|
||||
async _rejoinChannel(guildId, channelId, attempt = 1) {
|
||||
const { remix } = this;
|
||||
const cleanGuildId = String(guildId).replace(/\D/g, "");
|
||||
const cleanChannelId = String(channelId).replace(/\D/g, "");
|
||||
|
||||
// ── Deduplication: prevent concurrent rejoin for the same channel ──────
|
||||
if (this._rejoinInProgress.has(cleanChannelId)) {
|
||||
logger.voice247(`[Rejoin] Channel ${cleanChannelId} rejoin already in progress — skipping.`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't rejoin if there's already a player for this channel
|
||||
const existing = remix.players.playerMap.get(cleanChannelId);
|
||||
if (existing && !existing._destroyed) {
|
||||
logger.voice247(`[Rejoin] Channel ${cleanChannelId} already has a player — skipping.`);
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't rejoin if a join is already pending
|
||||
if (remix.players._pendingJoins?.has?.(cleanChannelId)) {
|
||||
logger.voice247(`[Rejoin] Channel ${cleanChannelId} already has a pending join — skipping.`);
|
||||
return;
|
||||
}
|
||||
|
||||
// Don't rejoin if the bot was intentionally disconnected
|
||||
if (remix.intentionalLeaves.has(cleanChannelId)) {
|
||||
logger.voice247(`[Rejoin] Channel ${cleanChannelId} was intentionally left — skipping.`);
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Verify the channel still exists
|
||||
const channel = remix.client?.channels?.get?.(cleanChannelId);
|
||||
if (!channel) {
|
||||
logger.voice247(`[Rejoin] Channel ${cleanChannelId} no longer exists — skipping.`);
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
return;
|
||||
}
|
||||
|
||||
// Mark as in-progress to prevent concurrent attempts
|
||||
this._rejoinInProgress.add(cleanChannelId);
|
||||
|
||||
const maxRetries = GatewayHandler.MAX_REJOIN_RETRIES;
|
||||
logger.voice247(
|
||||
`[Rejoin] Attempting to rejoin channel ${cleanChannelId} in guild ${cleanGuildId} (attempt ${attempt}/${maxRetries})...`
|
||||
);
|
||||
|
||||
try {
|
||||
const player = await remix._spawnPlayer(cleanGuildId, cleanChannelId);
|
||||
logger.voice247(`[Rejoin] Successfully rejoined channel ${cleanChannelId}`);
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
|
||||
// Reseed voice states so we know about humans in the channel
|
||||
this.reseedVoiceStatesForChannel(cleanGuildId, cleanChannelId);
|
||||
|
||||
return player;
|
||||
} catch (err) {
|
||||
const errMsg = err?.message ?? String(err);
|
||||
const isTrackTimeout = errMsg.includes("track publication timed out")
|
||||
|| errMsg.includes("publishToRoom failed")
|
||||
|| errMsg.includes("Failed to create MediaPlayer");
|
||||
|
||||
if (isTrackTimeout && attempt < maxRetries) {
|
||||
// Track publication timeout — likely transient (LiveKit overloaded).
|
||||
// Retry with exponential backoff: 5s, 10s, 20s
|
||||
const backoffMs = 5_000 * Math.pow(2, attempt - 1);
|
||||
logger.voice247(
|
||||
`[Rejoin] Track publication failed for channel ${cleanChannelId} (attempt ${attempt}/${maxRetries}) — ` +
|
||||
`retrying in ${backoffMs / 1000}s: ${errMsg}`
|
||||
);
|
||||
this._rejoinInProgress.delete(cleanChannelId);
|
||||
|
||||
await new Promise(resolve => setTimeout(resolve, backoffMs));
|
||||
|
||||
return this._rejoinChannel(cleanGuildId, cleanChannelId, attempt + 1);
|
||||
}
|
||||
|
||||
logger.warn(
|
||||
`[Rejoin] Failed to rejoin channel ${cleanChannelId} (attempt ${attempt}/${maxRetries}): ${errMsg}`
|
||||
);
|
||||
this._rejoinAttempts.delete(cleanChannelId);
|
||||
|
||||
// If all retries exhausted, the channel will be picked up on next
|
||||
// bot reboot via BootRecovery (for both %247 auto and %247 on).
|
||||
} finally {
|
||||
this._rejoinInProgress.delete(cleanChannelId);
|
||||
}
|
||||
}
|
||||
|
||||
// ── Called from Events.Ready ─────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Invoke after the bot has connected and Moonlink has been initialised.
|
||||
* Seeds voice states, attaches raw WS listener, and kicks off presence rotation.
|
||||
* Seeds voice states, attaches raw WS listener, kicks off presence rotation,
|
||||
* and rejoins 24/7 channels with staggered delays to avoid overwhelming
|
||||
* the LiveKit server.
|
||||
*/
|
||||
onReady() {
|
||||
this.seedVoiceStatesFromGuilds();
|
||||
@@ -1183,82 +1314,127 @@ export class GatewayHandler {
|
||||
}
|
||||
}, this._startupDeleteGraceMs);
|
||||
|
||||
// ── Boot 24/7 auto-rejoin ────────────────────────────────────────────────
|
||||
// After a reboot/crash, automatically rejoin all voice channels that have
|
||||
// 24/7 mode enabled (stay_247 setting with mode "on" or "auto").
|
||||
// Delayed slightly to let the gateway settle and Moonlink initialise.
|
||||
setTimeout(() => this.rejoin247Channels(), 5_000);
|
||||
// ── Boot 24/7 auto-rejoin ──────────────────────────────────────────────
|
||||
this.rejoin247Channels();
|
||||
}
|
||||
|
||||
/**
|
||||
* Rejoin all 24/7 voice channels after a bot reboot/crash.
|
||||
* Reads stay_247 settings from all guilds and spawns players for channels
|
||||
* that aren't already active.
|
||||
* Rejoin all 24/7 channels after boot with staggered delays.
|
||||
*
|
||||
* Both %247 auto and %247 on channels are rejoined because:
|
||||
* %247 auto: always stays in voice (disconnect + reboot)
|
||||
* %247 on: only on reboot, not on disconnect
|
||||
*
|
||||
* Channels are rejoined one at a time with a delay between each to
|
||||
* avoid overwhelming the LiveKit server with concurrent track publications.
|
||||
*/
|
||||
async rejoin247Channels() {
|
||||
const { remix } = this;
|
||||
const settings = remix.settingsMgr;
|
||||
if (!settings?.guilds) return;
|
||||
const channelsToRejoin = [];
|
||||
|
||||
const rejoinDelay = this.T.rejoin247Delay ?? 3_000;
|
||||
const channels = [];
|
||||
|
||||
// Collect all 24/7 channels with mode "on" or "auto"
|
||||
for (const [guildId, serverSettings] of settings.guilds) {
|
||||
// Collect all 24/7 channels from settings (both "auto" and "on" modes)
|
||||
for (const [guildId, serverSettings] of remix.settingsMgr.guilds) {
|
||||
const raw = serverSettings.get("stay_247");
|
||||
if (!raw || raw === "none") continue;
|
||||
|
||||
const rawArr = Array.isArray(raw) ? raw : [raw];
|
||||
const cleaned = rawArr
|
||||
const channels = rawArr
|
||||
.map(id => String(id).replace(/\D/g, ""))
|
||||
.filter(id => id.length >= 15);
|
||||
.filter(id => id.length >= 15 && id.length <= 22);
|
||||
|
||||
const modes = serverSettings.get("stay_247_modes");
|
||||
|
||||
for (const channelId of cleaned) {
|
||||
const mode = (modes && typeof modes === "object" && !Array.isArray(modes))
|
||||
? modes[channelId] ?? "off"
|
||||
: serverSettings.get("stay_247_mode") ?? "off";
|
||||
|
||||
if (mode !== "on" && mode !== "auto") continue;
|
||||
|
||||
// Skip if we already have an active player for this channel
|
||||
const existing = remix.players.playerMap.get(channelId)
|
||||
?? [...remix.players.playerMap.values()].find(p =>
|
||||
String(p?._channelId ?? "").replace(/\D/g, "") === channelId
|
||||
);
|
||||
if (existing && !existing._destroyed) continue;
|
||||
|
||||
channels.push({ guildId, channelId, mode });
|
||||
for (const channelId of channels) {
|
||||
const mode = get247ChannelMode(serverSettings, channelId);
|
||||
// Rejoin both "auto" and "on" channels on boot
|
||||
if (mode === "auto" || mode === "on") {
|
||||
channelsToRejoin.push({ guildId, channelId, mode });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (channels.length === 0) return;
|
||||
|
||||
logger.voice247(`[BootRecovery] Found ${channels.length} 24/7 channel(s) to rejoin`);
|
||||
|
||||
// Stagger the joins to avoid overloading the gateway
|
||||
for (let i = 0; i < channels.length; i++) {
|
||||
const { guildId, channelId, mode } = channels[i];
|
||||
const delay = i * rejoinDelay;
|
||||
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
// Verify the channel still exists
|
||||
const ch = remix.client?.channels?.get?.(channelId);
|
||||
if (!ch) {
|
||||
logger.voice247(`[BootRecovery] Channel ${channelId} no longer exists — skipping`);
|
||||
if (channelsToRejoin.length === 0) {
|
||||
logger.voice247("[BootRecovery] No 24/7 channels to rejoin.");
|
||||
return;
|
||||
}
|
||||
|
||||
logger.voice247(`[BootRecovery] Rejoining 24/7 channel ${channelId} (guild ${guildId}, mode ${mode})`);
|
||||
await remix._spawnPlayer(guildId, channelId);
|
||||
logger.voice247(`[BootRecovery] Successfully rejoined 24/7 channel ${channelId}`);
|
||||
} catch (e) {
|
||||
logger.warn(`[BootRecovery] Failed to rejoin 24/7 channel ${channelId}: ${e.message}`);
|
||||
logger.voice247(
|
||||
`[BootRecovery] Found ${channelsToRejoin.length} 24/7 channel(s) to rejoin: ` +
|
||||
channelsToRejoin.map(c => `${c.channelId}(${c.mode})`).join(", ")
|
||||
);
|
||||
|
||||
const baseStagger = remix.config?.timers?.bootRejoinStagger ?? 5_000;
|
||||
|
||||
for (let i = 0; i < channelsToRejoin.length; i++) {
|
||||
const { guildId, channelId, mode } = channelsToRejoin[i];
|
||||
|
||||
if (i > 0) {
|
||||
let staggerDelay = baseStagger;
|
||||
if (i >= 8) staggerDelay = baseStagger * 2;
|
||||
else if (i >= 4) staggerDelay = Math.round(baseStagger * 1.5);
|
||||
logger.voice247(`[BootRecovery] Waiting ${staggerDelay / 1000}s before rejoining next channel...`);
|
||||
await new Promise(resolve => setTimeout(resolve, staggerDelay));
|
||||
}
|
||||
}, delay);
|
||||
|
||||
// Don't rejoin if already has a player or pending join
|
||||
const existing = remix.players.playerMap.get(channelId);
|
||||
if (existing && !existing._destroyed) {
|
||||
logger.voice247(`[BootRecovery] Channel ${channelId} already has a player — skipping.`);
|
||||
continue;
|
||||
}
|
||||
if (remix.players._pendingJoins?.has?.(channelId)) {
|
||||
logger.voice247(`[BootRecovery] Channel ${channelId} already has a pending join — skipping.`);
|
||||
continue;
|
||||
}
|
||||
|
||||
logger.voice247(
|
||||
`[BootRecovery] Rejoining channel ${channelId} in guild ${guildId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]`
|
||||
);
|
||||
|
||||
const BOOT_MAX_RETRIES = 3;
|
||||
const BOOT_BASE_RETRY_MS = 5_000;
|
||||
let bootRetries = 0;
|
||||
|
||||
while (bootRetries < BOOT_MAX_RETRIES) {
|
||||
try {
|
||||
const player = await remix._spawnPlayer(guildId, channelId);
|
||||
|
||||
// Reseed voice states so we know about humans in the channel
|
||||
this.reseedVoiceStatesForChannel(guildId, channelId);
|
||||
|
||||
logger.voice247(
|
||||
`[BootRecovery] Successfully rejoined channel ${channelId} (mode: ${mode}) [${i + 1}/${channelsToRejoin.length}]` +
|
||||
(bootRetries > 0 ? ` (after ${bootRetries} retry/retries)` : '')
|
||||
);
|
||||
break; // success — move to next channel
|
||||
} catch (err) {
|
||||
bootRetries++;
|
||||
const errMsg = err?.message ?? String(err);
|
||||
const isTrackTimeout = errMsg.includes("track publication timed out")
|
||||
|| errMsg.includes("publishToRoom failed")
|
||||
|| errMsg.includes("Failed to create MediaPlayer")
|
||||
|| errMsg.includes("internal error");
|
||||
|
||||
if (isTrackTimeout && bootRetries < BOOT_MAX_RETRIES) {
|
||||
const backoffMs = BOOT_BASE_RETRY_MS * Math.pow(2, bootRetries - 1);
|
||||
logger.warn(
|
||||
`[BootRecovery] Track publication failed for channel ${channelId} (attempt ${bootRetries}/${BOOT_MAX_RETRIES}) — ` +
|
||||
`retrying in ${backoffMs / 1000}s: ${errMsg}`
|
||||
);
|
||||
await new Promise(resolve => setTimeout(resolve, backoffMs));
|
||||
continue;
|
||||
}
|
||||
|
||||
logger.warn(
|
||||
`[BootRecovery] Failed to rejoin channel ${channelId} (mode: ${mode}): ${errMsg}` +
|
||||
(bootRetries > 1 ? ` (after ${bootRetries} attempts)` : '')
|
||||
);
|
||||
break; // non-retryable error or max retries exhausted
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
logger.voice247(
|
||||
`[BootRecovery] Boot recovery complete. ${channelsToRejoin.length} channel(s) processed.`
|
||||
);
|
||||
}
|
||||
|
||||
// ── GuildDelete cleanup (extracted for deferred processing) ────────────────
|
||||
|
||||
+110
-234
@@ -349,13 +349,9 @@ export default class Player extends EventEmitter {
|
||||
// Join mutex — prevents concurrent join() calls from racing each other
|
||||
_isJoining = false;
|
||||
|
||||
// destroyed flag — prevents recovery/playback/worker spawn after destroy()
|
||||
// destroyed flag — prevents playback/worker spawn after destroy()
|
||||
_destroyed = false;
|
||||
|
||||
// publishToRoom self-healing — scheduled retry timer and consecutive fail count
|
||||
_publishRetryTimer = null;
|
||||
_publishFailCount = 0;
|
||||
|
||||
// NodeLink config (kept for direct stream URL building; session managed by moonlink)
|
||||
_nl = {
|
||||
host: "localhost",
|
||||
@@ -395,7 +391,7 @@ export default class Player extends EventEmitter {
|
||||
// revoice.js shared instance — injected by PlayerManager
|
||||
this._revoice = opts.revoice ?? null;
|
||||
|
||||
// Robust session sync that handles reconnection and stale sessions
|
||||
// Robust session sync that handles stale sessions
|
||||
if (this._moonlink) {
|
||||
this._onMoonlinkReady = (sessionId) => {
|
||||
const oldId = this._nl.sessionId;
|
||||
@@ -417,13 +413,29 @@ export default class Player extends EventEmitter {
|
||||
// 24/7 Mode Check
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
/**
|
||||
* Check if 24/7 mode is enabled for this player's channel.
|
||||
* Returns true for both "on" and "auto" modes.
|
||||
*/
|
||||
_is247Enabled() {
|
||||
if (!this._guildId) return false;
|
||||
return this._get247Mode() !== "off";
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the 24/7 mode for this player's channel.
|
||||
* Returns "auto", "on", or "off".
|
||||
*
|
||||
* %247 auto: bot stays in voice always (disconnect + reboot rejoin)
|
||||
* %247 on: bot stays in voice only on reboot (not on disconnect)
|
||||
* %247 off: bot leaves when inactive
|
||||
*/
|
||||
_get247Mode() {
|
||||
if (!this._guildId) return "off";
|
||||
|
||||
const checkSettings = (set) => {
|
||||
if (!set?.get) return false;
|
||||
if (!set?.get) return "off";
|
||||
const raw = set.get("stay_247");
|
||||
if (!raw || raw === "none") return false;
|
||||
if (!raw || raw === "none") return "off";
|
||||
|
||||
const channels = Array.isArray(raw)
|
||||
? raw.map(id => String(id).replace(/\D/g, "")).filter(Boolean)
|
||||
@@ -442,17 +454,16 @@ export default class Player extends EventEmitter {
|
||||
const matchChannel = channels.includes(homeChannel) ? homeChannel
|
||||
: channels.includes(currentChannel) ? currentChannel
|
||||
: null;
|
||||
if (!matchChannel) return false;
|
||||
if (!matchChannel) return "off";
|
||||
|
||||
// Per-channel mode lookup: each channel can have its own on/auto/off
|
||||
const mode = get247ChannelMode(set, matchChannel);
|
||||
return mode === "on" || mode === "auto";
|
||||
return get247ChannelMode(set, matchChannel);
|
||||
};
|
||||
|
||||
if (this.settingsMgr?.getServer) return checkSettings(this.settingsMgr.getServer(this._guildId));
|
||||
if (this.settings?.get) return checkSettings(this.settings);
|
||||
if (this.client?.settings?.getServer) return checkSettings(this.client.settings.getServer(this._guildId));
|
||||
return false;
|
||||
return "off";
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -478,6 +489,7 @@ export default class Player extends EventEmitter {
|
||||
return null;
|
||||
}
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
// Volume Restore
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
@@ -578,11 +590,14 @@ export default class Player extends EventEmitter {
|
||||
this._stopInactivityTimer();
|
||||
if (this._inactivityLimit <= 0) return;
|
||||
|
||||
const is247 = this._is247Enabled();
|
||||
logger.inactivity(`[Player] Checking 24/7 mode for guild ${this._guildId}: ${is247}`);
|
||||
const mode = this._get247Mode();
|
||||
logger.inactivity(`[Player] Checking 24/7 mode for guild ${this._guildId}: ${mode}`);
|
||||
|
||||
if (is247) {
|
||||
logger.inactivity(`[Player] 24/7 mode active for guild ${this._guildId}, skipping inactivity timer`);
|
||||
// %247 auto: bot always stays in voice, never start inactivity timer
|
||||
// %247 on: bot leaves when alone, but rejoins on reboot — timer is allowed
|
||||
// %247 off: bot leaves when alone — timer is allowed
|
||||
if (mode === "auto") {
|
||||
logger.inactivity(`[Player] 24/7 auto mode active for guild ${this._guildId}, skipping inactivity timer`);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -593,8 +608,8 @@ export default class Player extends EventEmitter {
|
||||
|
||||
logger.inactivity(`[Player] Starting inactivity timer for guild ${this._guildId} (${this._inactivityLimit / 1000}s)`);
|
||||
this._inactivityTimer = setTimeout(() => {
|
||||
if (this._is247Enabled()) {
|
||||
logger.inactivity("[Player] 24/7 mode enabled during inactivity wait, aborting leave");
|
||||
if (this._get247Mode() === "auto") {
|
||||
logger.inactivity("[Player] 24/7 auto mode enabled during inactivity wait, aborting leave");
|
||||
return;
|
||||
}
|
||||
if (this._hasHumansInChannel()) {
|
||||
@@ -608,9 +623,6 @@ export default class Player extends EventEmitter {
|
||||
|
||||
_stopInactivityTimer() {
|
||||
// Also cancel any pending inactivity check that Player.join() scheduled.
|
||||
// This is important after recovery: reseedVoiceStatesForChannel() calls
|
||||
// _stopInactivityTimer() when it finds humans in the channel, but
|
||||
// Player.join() may have already scheduled a 3-second delayed check.
|
||||
// Clearing the flag prevents that delayed check from restarting the timer.
|
||||
this._pendingInactivityCheck = false;
|
||||
if (this._inactivityTimer) {
|
||||
@@ -670,123 +682,47 @@ export default class Player extends EventEmitter {
|
||||
// re-check after async stop — player may have been destroyed
|
||||
if (this._destroyed) return false;
|
||||
|
||||
// publishToRoom with timeout and retry ──
|
||||
// publishToRoom has no internal timeout and can hang indefinitely if the
|
||||
// LiveKit server is slow or the network is congested. We wrap it in a
|
||||
// Promise.race with a timeout, and retry up to 3 times with exponential
|
||||
// backoff. On final failure, we DON'T leave the channel — the player
|
||||
// stays connected and can retry later (critical for 24/7 channels).
|
||||
const PUBLISH_TIMEOUT_MS = 8_000; // 8s timeout per attempt (was 15s)
|
||||
const MAX_RETRIES = 3;
|
||||
const BASE_BACKOFF_MS = 2_000;
|
||||
|
||||
for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
|
||||
// Re-check room state before each attempt
|
||||
if (!room.isConnected || this._destroyed) {
|
||||
logger.mediaplayer(`[Player] Room disconnected or player destroyed before attempt ${attempt} — aborting`);
|
||||
return false;
|
||||
}
|
||||
// Retry logic for transient failures like track publication timeouts.
|
||||
// LiveKit can timeout when the server is overloaded (e.g. during boot
|
||||
// recovery with many channels). Retry with exponential backoff.
|
||||
const MAX_PUBLISH_RETRIES = 3;
|
||||
const BASE_RETRY_DELAY_MS = 3_000;
|
||||
|
||||
for (let attempt = 1; attempt <= MAX_PUBLISH_RETRIES; attempt++) {
|
||||
try {
|
||||
this._mediaPlayer = new MediaPlayer();
|
||||
this._mediaPlayer.setMaxListeners(0);
|
||||
|
||||
// Race publishToRoom against a timeout
|
||||
await Promise.race([
|
||||
this._mediaPlayer.publishToRoom(room),
|
||||
new Promise((_, reject) =>
|
||||
setTimeout(() => reject(new Error(`publishToRoom timed out after ${PUBLISH_TIMEOUT_MS}ms`)), PUBLISH_TIMEOUT_MS)
|
||||
),
|
||||
]);
|
||||
|
||||
logger.mediaplayer(`[Player] MediaPlayer published successfully on attempt ${attempt}`);
|
||||
this._publishFailCount = 0;
|
||||
if (this._publishRetryTimer) {
|
||||
clearTimeout(this._publishRetryTimer);
|
||||
this._publishRetryTimer = null;
|
||||
}
|
||||
await this._mediaPlayer.publishToRoom(room);
|
||||
logger.mediaplayer("[Player] MediaPlayer published successfully");
|
||||
return true;
|
||||
} catch (e) {
|
||||
const msg = e?.message ?? String(e);
|
||||
const isTransient = msg.includes("engine is closed") ||
|
||||
msg.includes("engine: connection error");
|
||||
const isTimeout = msg.includes("timed out");
|
||||
const isTransient = msg.includes("track publication timed out")
|
||||
|| msg.includes("publishToRoom failed")
|
||||
|| msg.includes("internal error");
|
||||
|
||||
if (isTransient) {
|
||||
logger.mediaplayer(`[Player] publishToRoom transient fail on attempt ${attempt} (room mid-teardown): ${msg}`);
|
||||
} else if (isTimeout) {
|
||||
logger.warn(`[Player] publishToRoom timed out on attempt ${attempt}/${MAX_RETRIES}: ${msg}`);
|
||||
} else {
|
||||
logger.error(`[Player] publishToRoom failed on attempt ${attempt}/${MAX_RETRIES}: ${msg}`);
|
||||
}
|
||||
|
||||
// Clean up the failed MediaPlayer
|
||||
try { this._mediaPlayer?.stop?.(); } catch (_) {}
|
||||
this._mediaPlayer = null;
|
||||
|
||||
// If the room disconnected mid-attempt, don't retry
|
||||
if (!room.isConnected || this._destroyed) {
|
||||
logger.mediaplayer(`[Player] Room disconnected during publish attempt — aborting retries`);
|
||||
return false;
|
||||
}
|
||||
|
||||
// If we have more retries left, wait with backoff before retrying
|
||||
if (attempt < MAX_RETRIES) {
|
||||
const backoff = Math.min(BASE_BACKOFF_MS * Math.pow(2, attempt - 1), 10_000);
|
||||
logger.mediaplayer(`[Player] Retrying publishToRoom in ${backoff}ms...`);
|
||||
await new Promise(r => setTimeout(r, backoff));
|
||||
} else {
|
||||
// On final failure, DON'T leave the channel. The voice
|
||||
// connection is still alive — just the audio publishing failed.
|
||||
// Schedule a self-healing retry so 24/7 channels recover automatically
|
||||
// instead of staying silent forever.
|
||||
this._publishFailCount = (this._publishFailCount ?? 0) + 1;
|
||||
const SELF_HEAL_DELAY_MS = Math.min(30_000 * this._publishFailCount, 120_000);
|
||||
|
||||
logger.error(
|
||||
`[Player] All ${MAX_RETRIES} publishToRoom attempts failed (fail #${this._publishFailCount}) — ` +
|
||||
`scheduling self-heal retry in ${SELF_HEAL_DELAY_MS / 1000}s.`
|
||||
if (isTransient && attempt < MAX_PUBLISH_RETRIES) {
|
||||
const backoffMs = BASE_RETRY_DELAY_MS * Math.pow(2, attempt - 1);
|
||||
logger.warn(
|
||||
`[Player] publishToRoom failed (attempt ${attempt}/${MAX_PUBLISH_RETRIES}): ${msg} — retrying in ${backoffMs / 1000}s`
|
||||
);
|
||||
await new Promise(resolve => setTimeout(resolve, backoffMs));
|
||||
|
||||
// Clear any existing retry timer before scheduling a new one
|
||||
if (this._publishRetryTimer) {
|
||||
clearTimeout(this._publishRetryTimer);
|
||||
this._publishRetryTimer = null;
|
||||
// Re-check room state before retrying
|
||||
if (this._destroyed || !room.isConnected) {
|
||||
logger.mediaplayer("[Player] Room disconnected during publish retry — aborting");
|
||||
return false;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
|
||||
this._publishRetryTimer = setTimeout(async () => {
|
||||
this._publishRetryTimer = null;
|
||||
if (this._destroyed || this.leaving) return;
|
||||
const roomStillAlive = this.connection?.room?.isConnected ?? false;
|
||||
if (!roomStillAlive) {
|
||||
// Room died — emit autoleave so the 24/7 handler can respawn
|
||||
logger.warn("[Player] Self-heal: room no longer connected — emitting autoleave.");
|
||||
this.emit("autoleave");
|
||||
return;
|
||||
}
|
||||
logger.player(`[Player] Self-heal: retrying publishToRoom for channel ${this._channelId ?? "?"}`);
|
||||
const ok = await this._ensureMediaPlayer().catch(() => false);
|
||||
if (ok) {
|
||||
this._publishFailCount = 0;
|
||||
logger.player("[Player] Self-heal: publishToRoom succeeded — resuming playback.");
|
||||
if (!this.queue.isEmpty() && !this.queue.getCurrent()) {
|
||||
this.playNext();
|
||||
}
|
||||
} else {
|
||||
logger.warn("[Player] Self-heal: publishToRoom still failing — will try full reconnect.");
|
||||
// Final resort: destroy this player and let GatewayHandler's
|
||||
// 24/7 protection respawn it via _spawnPlayer.
|
||||
if (!this._destroyed && !this.leaving) {
|
||||
this.emit("autoleave");
|
||||
}
|
||||
}
|
||||
}, SELF_HEAL_DELAY_MS);
|
||||
|
||||
logger.error(`[Player] publishToRoom failed: ${msg}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
@@ -1063,21 +999,7 @@ export default class Player extends EventEmitter {
|
||||
logger.player(`[Player] NodeLink loadStream PCM active`);
|
||||
// Raw PCM from NodeLink — tell FFmpeg the input format
|
||||
const pcmInputOpts = ["-f", "s16le", "-ar", "48000", "-ac", "2"];
|
||||
try {
|
||||
return await this._streamViaRevoice(url, pcmInputOpts);
|
||||
} catch (err) {
|
||||
const msg = err?.message ?? String(err ?? "");
|
||||
if (msg.includes("HTTP ")) {
|
||||
logger.warn(`[Player] NodeLink loadStream failed (${msg}), falling back to trackstream URL mode`);
|
||||
const parsed = new URL(url);
|
||||
const encodedTrack = parsed.searchParams.get("encodedTrack");
|
||||
if (!encodedTrack) throw err;
|
||||
const nlBase = `http://${this._nl.host}:${this._nl.port}`;
|
||||
const fallbackUrl = `${nlBase}/v4/trackstream?encodedTrack=${encodeURIComponent(encodedTrack)}`;
|
||||
return this._streamUrl(fallbackUrl);
|
||||
}
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -1113,33 +1035,20 @@ export default class Player extends EventEmitter {
|
||||
logger.player(`[Player] Already in channel: ${channelId}`);
|
||||
return;
|
||||
}
|
||||
logger.mediaplayer(`[Player] Connection not connected, reconnecting...`);
|
||||
// Connection is dead — clean up. No auto-reconnect; the caller
|
||||
// must explicitly re-join if they want to reconnect.
|
||||
logger.player(`[Player] Dead connection detected for ${channelId}, cleaning up`);
|
||||
try { this.connection.removeAllListeners(); } catch (_) {}
|
||||
try { await this.connection.disconnect(); } catch (_) {}
|
||||
|
||||
// Send guild-scoped gateway leave signal so the gateway knows we left.
|
||||
// Without this, joinVoiceChannel() may not get VOICE_SERVER_UPDATE.
|
||||
// IMPORTANT: Never use unscoped updateVoiceState(null, opts) — it
|
||||
// disconnects ALL guilds' voice connections.
|
||||
try {
|
||||
const vm = getVoiceManager(this.client);
|
||||
if (vm && typeof vm.updateVoiceState === "function") {
|
||||
const guildIdForLeave = this._guildId ?? this._resolveGuildId();
|
||||
if (guildIdForLeave) {
|
||||
try {
|
||||
vm.updateVoiceState(guildIdForLeave, null, { self_deaf: false, self_mute: false });
|
||||
} catch (_) {
|
||||
try { vm.updateVoiceState(guildIdForLeave, null); } catch (_2) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
// Remove stale connection from FluxerRevoice's map
|
||||
// Use FluxerRevoice's channel-specific leave instead of raw
|
||||
// vm.updateVoiceState(guildId, null) which nukes ALL guild channels.
|
||||
if (this._revoice && this._channelId) {
|
||||
try { this._revoice.markIntentionalDisconnect(this._channelId); } catch (_) {}
|
||||
try { this._revoice._leaveGateway(this._channelId, this._guildId ?? this._resolveGuildId()); } catch (_) {}
|
||||
try { this._revoice.deleteConnection(this._channelId); } catch (_) {}
|
||||
}
|
||||
|
||||
try { await this.connection.disconnect(); } catch (_) {}
|
||||
this.connection = null;
|
||||
this._mediaPlayer = null;
|
||||
}
|
||||
@@ -1152,36 +1061,21 @@ export default class Player extends EventEmitter {
|
||||
if (this.connection) {
|
||||
logger.mediaplayer("[Player] Cleaning up existing connection before join");
|
||||
try { this.connection.removeAllListeners(); } catch (_) {}
|
||||
|
||||
// Use FluxerRevoice's channel-specific leave instead of raw
|
||||
// vm.updateVoiceState(guildId, null) which nukes ALL guild channels.
|
||||
if (this._revoice && this._channelId) {
|
||||
try { this._revoice.markIntentionalDisconnect(this._channelId); } catch (_) {}
|
||||
try { this._revoice._leaveGateway(this._channelId, this._guildId ?? this._resolveGuildId()); } catch (_) {}
|
||||
try { this._revoice.deleteConnection(this._channelId); } catch (_) {}
|
||||
}
|
||||
|
||||
try {
|
||||
await this.connection.disconnect();
|
||||
} catch (_) {}
|
||||
|
||||
// Send guild-scoped gateway leave signal for the old channel so the
|
||||
// gateway processes the leave before we join a new/different channel.
|
||||
// IMPORTANT: Never use unscoped updateVoiceState(null, opts) — it
|
||||
// disconnects ALL guilds' voice connections.
|
||||
try {
|
||||
const vm = getVoiceManager(this.client);
|
||||
if (vm && typeof vm.updateVoiceState === "function") {
|
||||
const guildIdForLeave = this._guildId ?? this._resolveGuildId();
|
||||
if (guildIdForLeave) {
|
||||
try {
|
||||
vm.updateVoiceState(guildIdForLeave, null, { self_deaf: false, self_mute: false });
|
||||
} catch (_) {
|
||||
try { vm.updateVoiceState(guildIdForLeave, null); } catch (_2) {}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (_) {}
|
||||
|
||||
// Remove from FluxerRevoice's map if the channel differs
|
||||
if (this._revoice && this._channelId) {
|
||||
try { this._revoice.deleteConnection(this._channelId); } catch (_) {}
|
||||
}
|
||||
|
||||
// Wait to give the Fluxer gateway time to process the voice state
|
||||
// leave before we join a new channel. FluxerRevoice adds its own
|
||||
// _globalJoinDelay before the actual join, so 500ms here is enough.
|
||||
// Brief wait so the gateway processes the leave before we join a
|
||||
// new channel. FluxerRevoice adds its own _globalJoinDelay too.
|
||||
await Utils.sleep(500);
|
||||
this.connection = null;
|
||||
this._mediaPlayer = null;
|
||||
@@ -1329,10 +1223,24 @@ export default class Player extends EventEmitter {
|
||||
return;
|
||||
}
|
||||
if (!this.leaving && !this._destroyed) {
|
||||
const mode = this._get247Mode();
|
||||
if (mode === "auto") {
|
||||
// %247 auto: Do NOT emit autoleave on unexpected disconnect.
|
||||
// The GatewayHandler will detect the bot's voice state change
|
||||
// and schedule a rejoin. Emitting autoleave here would cause
|
||||
// the player to be destroyed before the rejoin can be scheduled,
|
||||
// and creates a race condition where both Player.mjs AND
|
||||
// GatewayHandler try to handle the disconnect simultaneously.
|
||||
logger.mediaplayer("[Player] Unexpected disconnect detected (24/7 auto) — stopping media player, GatewayHandler will schedule rejoin");
|
||||
this._stopMediaPlayer().catch(() => {});
|
||||
} else {
|
||||
// %247 on or off: emit autoleave as normal.
|
||||
// %247 on does NOT rejoin on disconnect (only on reboot).
|
||||
logger.mediaplayer("[Player] Unexpected disconnect detected");
|
||||
this._stopMediaPlayer()
|
||||
.catch(() => {})
|
||||
.finally(() => this.emit("autoleave"));
|
||||
}
|
||||
} else {
|
||||
try { connection.removeAllListeners(); } catch (_) {}
|
||||
}
|
||||
@@ -1354,28 +1262,8 @@ export default class Player extends EventEmitter {
|
||||
logger.warn("[Player] Self-deafen failed:", e.message);
|
||||
}
|
||||
|
||||
// ── MediaPlayer creation with progressive retries ───────────────────
|
||||
// LiveKit's publishToRoom can time out on slow servers ("track publication
|
||||
// timed out, no response received from the server"). The room itself is
|
||||
// connected fine — only the audio track publishing fails. Progressive
|
||||
// retries with increasing delays give the LiveKit server time to recover.
|
||||
const MP_RETRIES = [
|
||||
{ delay: 2000, label: "1st retry (2s)" },
|
||||
{ delay: 4000, label: "2nd retry (4s)" },
|
||||
{ delay: 8000, label: "3rd retry (8s)" },
|
||||
];
|
||||
let playerReady = await this._ensureMediaPlayer();
|
||||
for (const { delay, label } of MP_RETRIES) {
|
||||
if (playerReady) break;
|
||||
if (this._destroyed || this.leaving) throw new Error("Player destroyed during MediaPlayer retry");
|
||||
const roomAlive = this.connection?.room?.isConnected ?? false;
|
||||
if (!roomAlive) throw new Error("Room disconnected during MediaPlayer retry");
|
||||
logger.mediaplayer(`[Player] MediaPlayer attempt failed — ${label}...`);
|
||||
await Utils.sleep(delay);
|
||||
if (this._destroyed || this.leaving) throw new Error("Player destroyed during MediaPlayer retry");
|
||||
playerReady = await this._ensureMediaPlayer();
|
||||
}
|
||||
if (!playerReady) throw new Error("Failed to create MediaPlayer after all retries");
|
||||
const playerReady = await this._ensureMediaPlayer();
|
||||
if (!playerReady) throw new Error("Failed to create MediaPlayer");
|
||||
|
||||
this._restoreVolume();
|
||||
this.emit("roomfetched");
|
||||
@@ -1465,19 +1353,6 @@ export default class Player extends EventEmitter {
|
||||
this.leaving = true;
|
||||
this._streamingStopped = true;
|
||||
this._stopInactivityTimer();
|
||||
if (this._recoveryTimer) {
|
||||
clearTimeout(this._recoveryTimer);
|
||||
this._recoveryTimer = null;
|
||||
}
|
||||
if (this._publishRetryTimer) {
|
||||
clearTimeout(this._publishRetryTimer);
|
||||
this._publishRetryTimer = null;
|
||||
}
|
||||
this._publishFailCount = 0;
|
||||
this._recoveryPending = false;
|
||||
this._isRecovering = false;
|
||||
this._recoveryAttempts = 0;
|
||||
this._lastDisconnectReason = null;
|
||||
this.searches.clear();
|
||||
|
||||
if (this._workerPool) {
|
||||
@@ -1602,7 +1477,7 @@ export default class Player extends EventEmitter {
|
||||
// Audio Filter Control
|
||||
// ═══════════════════════════════════════════════════════════════════════════
|
||||
|
||||
async applyFilter(filterPayload, meta = null, _retryCount = 0) {
|
||||
async applyFilter(filterPayload, meta = null) {
|
||||
const guildId = this._guildId;
|
||||
if (!guildId) {
|
||||
return { ok: false, reason: "Player not bound to a guild." };
|
||||
@@ -1663,14 +1538,6 @@ export default class Player extends EventEmitter {
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
const errMsg = e.message ?? "";
|
||||
if (_retryCount === 0 && (errMsg.includes("404") || errMsg.includes("not found") || errMsg.includes("Session-ID") || errMsg.includes("does not exist"))) {
|
||||
logger.warn("[Player] Filter apply failed with stale session, forcing re-sync...");
|
||||
const freshSession = this._moonlink?.getLiveSessionId?.() ?? this._moonlink?.sessionId;
|
||||
if (freshSession && freshSession !== liveSessionId) {
|
||||
this._nl.sessionId = freshSession;
|
||||
return this.applyFilter(filterPayload, meta, 1);
|
||||
}
|
||||
}
|
||||
return { ok: false, reason: sanitizeError(errMsg, this._nl) };
|
||||
}
|
||||
}
|
||||
@@ -2197,12 +2064,12 @@ export default class Player extends EventEmitter {
|
||||
const room = this.connection.room;
|
||||
if (!room || !room.isConnected) {
|
||||
const cs = room?.connectionState;
|
||||
logger.mediaplayer(`[Player] Room not connected (isConnected: ${room?.isConnected}, connectionState: ${cs}), recovering connection before playing.`);
|
||||
logger.mediaplayer(`[Player] Room not connected (isConnected: ${room?.isConnected}, connectionState: ${cs}) — emitting autoleave.`);
|
||||
if (songData) {
|
||||
this.queue.data.unshift(songData);
|
||||
this.queue.current = null;
|
||||
}
|
||||
this._recoverConnection();
|
||||
this.emit("autoleave");
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -2268,8 +2135,12 @@ export default class Player extends EventEmitter {
|
||||
if (!streamUrl || !Utils.isValidUrl(streamUrl)) {
|
||||
logger.error("[Player] No valid stream URL for:", songData.title);
|
||||
this.emit("message", mkEmbed(this._t("responses._common.couldNotGetStream", { title: songData.title })));
|
||||
this._streamingStopped = false;
|
||||
return this._doPlayNext();
|
||||
this._streamingStopped = true;
|
||||
this.emit("stopplay");
|
||||
if (!this._is247Enabled()) {
|
||||
this._startInactivityTimer();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
logger.player(`[Player:${this._guildId}] Streaming: ${songData.title}`);
|
||||
@@ -2299,11 +2170,16 @@ export default class Player extends EventEmitter {
|
||||
|
||||
if (!this.leaving && !this._skipping) {
|
||||
if (songData.type === "radio") {
|
||||
this.queue.data.unshift(songData);
|
||||
// Radio track ended — do NOT auto-retry/re-queue.
|
||||
// The user must manually restart if they want to continue.
|
||||
logger.player(`[Player] Radio stream ended: ${songData.title}`);
|
||||
this.queue.current = null;
|
||||
this._streamingStopped = false;
|
||||
await Utils.sleep(500);
|
||||
if (!this.leaving && !this._skipping) return this._doPlayNext();
|
||||
this._streamingStopped = true;
|
||||
this.emit("stopplay");
|
||||
if (!this._is247Enabled()) {
|
||||
this._startInactivityTimer();
|
||||
}
|
||||
return;
|
||||
} else {
|
||||
if (!this._paused) {
|
||||
if (!this.queue.songLoop) this.queue.current = null;
|
||||
|
||||
+15
-20
@@ -815,31 +815,26 @@ export class PlayerManager {
|
||||
if (homeChannelId !== activeChannelId) this.playerMap.delete(homeChannelId);
|
||||
player.destroy();
|
||||
|
||||
if (isIn247List && (mode247 === "on" || mode247 === "auto")) {
|
||||
// 24/7 mode active — auto-rejoin the channel after a delay
|
||||
const rejoinDelay = this.timers?.rejoin247Delay ?? 3_000;
|
||||
logger.voice247(`[AutoLeave] 24/7 channel ${homeChannelId} (mode ${mode247}) auto-left — scheduling rejoin in ${rejoinDelay}ms`);
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
if (typeof this.commands?.context?._spawnPlayer === "function") {
|
||||
await this.commands.context._spawnPlayer(guildId, homeChannelId);
|
||||
logger.voice247(`[AutoLeave] 24/7 auto-rejoin succeeded for channel ${homeChannelId}`);
|
||||
} else {
|
||||
logger.warn(`[AutoLeave] 24/7 auto-rejoin failed: _spawnPlayer not available`);
|
||||
}
|
||||
} catch (e) {
|
||||
logger.warn(`[AutoLeave] 24/7 auto-rejoin failed for channel ${homeChannelId}: ${e.message}`);
|
||||
}
|
||||
}, rejoinDelay);
|
||||
} else {
|
||||
// Not 24/7 — send inactivity message
|
||||
// Notify the channel that the bot left.
|
||||
// For %247 on: bot will rejoin on reboot (but not on disconnect)
|
||||
// For %247 auto: bot will rejoin automatically after disconnect
|
||||
// For non-247: user must manually re-invoke the join command
|
||||
const prefix = (() => {
|
||||
try { return this.settings.getServer(guildId)?.get("prefix") ?? "%"; } catch (_) { return "%"; }
|
||||
})();
|
||||
const desc = this.locale?.translate(guildId, "responses.join.autoLeaveInactive247", { channel: `<#${activeChannelId}>`, prefix })
|
||||
|
||||
let desc;
|
||||
if (mode247 === "on") {
|
||||
desc = this.locale?.translate(guildId, "responses.join.autoLeave247On", { channel: `<#${activeChannelId}>` })
|
||||
?? `Left channel <#${activeChannelId}> because of inactivity.\nI'll rejoin automatically when the bot restarts (%247 on mode).`;
|
||||
} else if (mode247 === "auto") {
|
||||
desc = this.locale?.translate(guildId, "responses.join.autoLeave247Auto", { channel: `<#${activeChannelId}>` })
|
||||
?? `Left channel <#${activeChannelId}> — reconnecting automatically (%247 auto mode)...`;
|
||||
} else {
|
||||
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\``;
|
||||
if (typeof ch?.send === "function") ch.send(mkEmbed(desc));
|
||||
}
|
||||
if (typeof ch?.send === "function") ch.send(mkEmbed(desc));
|
||||
});
|
||||
|
||||
player.on("leave", () => {});
|
||||
|
||||
+11
-182
@@ -163,7 +163,7 @@ export class FluxerVoiceConnection extends EventEmitter {
|
||||
async disconnect() {
|
||||
if (this._destroyed) return;
|
||||
// Mark this as an intentional disconnect so the RoomEvent.Disconnected
|
||||
// handler knows not to trigger recovery
|
||||
// handler can log it correctly
|
||||
if (this._voice && this.channelId) {
|
||||
this._voice.markIntentionalDisconnect(this.channelId);
|
||||
// Prefer a channel-scoped gateway leave before tearing down the room.
|
||||
@@ -225,52 +225,21 @@ export class FluxerRevoice extends EventEmitter {
|
||||
connections = new Map();
|
||||
users = new Map();
|
||||
|
||||
// Guild-level join mutex: kept for per-guild cooldown tracking (401 cooldowns
|
||||
// and minimum join intervals), but actual join serialization is handled by
|
||||
// the global queue above. The per-guild queue was insufficient because the
|
||||
// Fluxer gateway can't handle concurrent joins from DIFFERENT guilds either.
|
||||
/** @type {Map<string, Promise>} */
|
||||
_guildJoinQueue = new Map();
|
||||
|
||||
// ── Global join queue ──────────────────────────────────────────────────────
|
||||
// The per-guild queue serializes joins within the same guild, but the Fluxer
|
||||
// gateway also struggles when many DIFFERENT guilds are joined simultaneously.
|
||||
// During boot recovery, 10+ channels can be spawned within seconds, each
|
||||
// triggering VOICE_STATE_UPDATE + VOICE_SERVER_UPDATE + LiveKit connect.
|
||||
// The gateway's Erlang backend can't process this flood fast enough, causing
|
||||
// 401 Unauthorized errors on guilds that were scheduled later.
|
||||
//
|
||||
// The global queue ensures that only ONE join is in-flight at a time across
|
||||
// ALL guilds, with a delay between each to let the gateway catch up.
|
||||
/** @type {Promise} Global join serializer — only one join at a time across all guilds */
|
||||
_globalJoinQueue = Promise.resolve();
|
||||
/** @type {number} Minimum delay between ANY two joins (ms), even across guilds.
|
||||
* This delay runs AFTER the previous join completes and BEFORE the next
|
||||
* one starts, giving the Fluxer gateway time to clean up the previous
|
||||
* voice session. 500ms is sufficient; the per-guild _guildMinJoinInterval
|
||||
* provides additional safety for rapid same-guild rejoins. */
|
||||
* voice session. */
|
||||
_globalJoinDelay = 500;
|
||||
|
||||
/** @type {Set<string>} Channel IDs where disconnect is expected (bot-initiated) */
|
||||
_intentionalDisconnects = new Set();
|
||||
|
||||
/** @type {Map<string, number>} Guild ID → timestamp of last successful join.
|
||||
* Used to add an extra safety delay when the previous join in this guild
|
||||
* was very recent (< 5 seconds), which is the window where 401 errors
|
||||
* are most likely due to the gateway not having fully processed the
|
||||
* previous session's voice state. */
|
||||
_guildLastJoinTime = new Map();
|
||||
|
||||
/** @type {number} Minimum time between guild joins (ms) — enforced on top of
|
||||
* the per-join delay. If a new join is requested within this window, we
|
||||
* wait the remaining time before proceeding. 2s is enough with the global
|
||||
* join queue providing additional serialization. */
|
||||
_guildMinJoinInterval = 2000;
|
||||
|
||||
/** @type {Map<string, number>} Guild IDs that recently had a 401 error.
|
||||
* Used to add an even longer backoff before retrying joins in that guild. */
|
||||
_guild401Cooldown = new Map(); // guildId → timestamp when cooldown expires
|
||||
|
||||
/** @type {FluxerRevoice|null} Singleton instance */
|
||||
static _instance = null;
|
||||
|
||||
@@ -304,7 +273,7 @@ export class FluxerRevoice extends EventEmitter {
|
||||
|
||||
/**
|
||||
* Mark a channel as expecting an intentional disconnect so the
|
||||
* RoomEvent.Disconnected handler does not trigger recovery.
|
||||
* RoomEvent.Disconnected handler can log it correctly.
|
||||
* @param {string} channelId
|
||||
*/
|
||||
markIntentionalDisconnect(channelId) {
|
||||
@@ -414,7 +383,7 @@ export class FluxerRevoice extends EventEmitter {
|
||||
async _destroyStaleConnection(channelId, existing) {
|
||||
// 1. Remove from map immediately so no other code can get this dead ref
|
||||
this.connections.delete(channelId);
|
||||
// Mark as intentional so the LiveKit disconnect handler doesn't trigger recovery
|
||||
// Mark as intentional so the LiveKit disconnect handler logs correctly
|
||||
this.markIntentionalDisconnect(channelId);
|
||||
const staleGuildId = this._resolveGuildForChannel(channelId);
|
||||
this._leaveGateway(channelId, staleGuildId);
|
||||
@@ -438,10 +407,6 @@ export class FluxerRevoice extends EventEmitter {
|
||||
existing._destroyed = true;
|
||||
existing._connected = false;
|
||||
try { existing.removeAllListeners(); } catch (_) {}
|
||||
|
||||
// 4. Brief delay to let the gateway process the leave before we rejoin.
|
||||
// 250ms is enough since the join() operation itself adds _globalJoinDelay.
|
||||
await new Promise(r => setTimeout(r, 250));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -456,29 +421,6 @@ export class FluxerRevoice extends EventEmitter {
|
||||
* @returns {Promise<FluxerVoiceConnection>}
|
||||
*/
|
||||
async join(channelId, _leaveIfEmpty = false) {
|
||||
// ── Global join queue (TRUE serialization) ───────────────────────────
|
||||
// Serialize ALL joins so that only ONE join is in-flight at a time across
|
||||
// the entire bot. The Fluxer gateway's Erlang backend cannot handle
|
||||
// concurrent VOICE_STATE_UPDATE + VOICE_SERVER_UPDATE flows — it returns
|
||||
// 401 Unauthorized when LiveKit tokens haven't propagated for the previous
|
||||
// join yet.
|
||||
//
|
||||
// PREVIOUS APPROACH (broken): Add a 2s delay between starts, but don't
|
||||
// wait for the previous join to complete. Multiple joins were in-flight
|
||||
// simultaneously, causing 401 errors.
|
||||
//
|
||||
// NEW APPROACH: The global queue wraps the ENTIRE join() call. Each join
|
||||
// must FULLY COMPLETE (including LiveKit room connection) before the next
|
||||
// one starts, plus a 3-second gap between joins to give the gateway time
|
||||
// to clean up the previous voice session.
|
||||
//
|
||||
// The promise chain works like this:
|
||||
// _globalJoinQueue = Promise.resolve() // initial
|
||||
// _globalJoinQueue = prev.then(() => joinA()) // joinA runs after prev
|
||||
// _globalJoinQueue = prev.then(() => joinB()) // joinB runs after joinA completes
|
||||
//
|
||||
// Each caller awaits its own turn, which only resolves after the full
|
||||
// join operation completes (or throws).
|
||||
const joinOperation = async () => {
|
||||
// Small gap between joins to let the gateway process the previous
|
||||
// session's cleanup. This runs BEFORE the actual join logic.
|
||||
@@ -503,61 +445,13 @@ export class FluxerRevoice extends EventEmitter {
|
||||
* @returns {Promise<FluxerVoiceConnection>}
|
||||
*/
|
||||
async _joinInternal(channelId, _leaveIfEmpty = false) {
|
||||
// Resolve the guild ID for this channel so we can serialize joins per guild.
|
||||
// This prevents the 401 Unauthorized race condition that occurs when
|
||||
// multiple channels in the same guild are joined simultaneously.
|
||||
// Resolve the guild ID for this channel
|
||||
let guildId = null;
|
||||
try {
|
||||
const ch = this.client.channels?.get?.(channelId);
|
||||
guildId = ch?.guildId ?? ch?.guild?.id ?? null;
|
||||
} catch (_) {}
|
||||
|
||||
// Per-guild cooldown checks (still useful for same-guild rapid rejoins
|
||||
// from recovery or user commands, even though the global queue prevents
|
||||
// concurrent joins)
|
||||
if (guildId) {
|
||||
// Additional safety: if this guild was joined very recently, wait
|
||||
// until the minimum interval has elapsed. This prevents the rapid
|
||||
// rejoin that causes 401 Unauthorized errors.
|
||||
const lastJoin = this._guildLastJoinTime.get(guildId) ?? 0;
|
||||
const elapsed = Date.now() - lastJoin;
|
||||
if (elapsed < this._guildMinJoinInterval) {
|
||||
const extraWait = this._guildMinJoinInterval - elapsed;
|
||||
logger.player(
|
||||
`[FluxerRevoice] Guild ${guildId} was joined ${elapsed}ms ago — ` +
|
||||
`waiting additional ${extraWait}ms to avoid 401 race`
|
||||
);
|
||||
await new Promise(r => setTimeout(r, extraWait));
|
||||
}
|
||||
|
||||
// If this guild recently had a 401 error, wait for the cooldown.
|
||||
const cooldownExpiry = this._guild401Cooldown.get(guildId) ?? 0;
|
||||
const cooldownRemaining = cooldownExpiry - Date.now();
|
||||
if (cooldownRemaining > 0) {
|
||||
if (cooldownRemaining > 30_000) {
|
||||
throw new Error(
|
||||
`Guild ${guildId} has active 401 cooldown (${Math.round(cooldownRemaining / 1000)}s remaining) — ` +
|
||||
`aborting join for channel ${channelId} to avoid guaranteed failure. `
|
||||
);
|
||||
}
|
||||
logger.player(
|
||||
`[FluxerRevoice] Guild ${guildId} has 401 cooldown — ` +
|
||||
`waiting ${Math.round(cooldownRemaining / 1000)}s before attempting join`
|
||||
);
|
||||
await new Promise(r => setTimeout(r, cooldownRemaining));
|
||||
}
|
||||
|
||||
// Re-check cooldown after waiting
|
||||
const recheckExpiry = this._guild401Cooldown.get(guildId) ?? 0;
|
||||
const recheckRemaining = recheckExpiry - Date.now();
|
||||
if (recheckRemaining > 30_000) {
|
||||
throw new Error(
|
||||
`Guild ${guildId} 401 cooldown re-activated during wait — ` +
|
||||
`aborting join for channel ${channelId}.`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
if (this.connections.has(channelId)) {
|
||||
const existing = this.connections.get(channelId);
|
||||
// If the existing connection is still alive, reuse it.
|
||||
@@ -601,22 +495,12 @@ export class FluxerRevoice extends EventEmitter {
|
||||
try {
|
||||
nativeConnection = await joinVoiceChannel(this.client, channel);
|
||||
} catch (e) {
|
||||
// If the error is 401 Unauthorized, set a cooldown for this guild
|
||||
// so subsequent join attempts wait longer before retrying.
|
||||
if (e.message?.includes("401") || e.message?.includes("Unauthorized")) {
|
||||
const gId = channelGuildId ?? this._resolveGuildForChannel(channelId);
|
||||
if (gId) {
|
||||
// Reduced cooldown from 15s to 5s. 15s was too aggressive —
|
||||
// it blocked all join attempts for the guild for too long, causing
|
||||
// BootRecovery to fail entirely. 5s is enough for the gateway to
|
||||
// clean up the stale voice session.
|
||||
this._guild401Cooldown.set(gId, Date.now() + 5_000);
|
||||
logger.warn(
|
||||
`[FluxerRevoice] 401 error for channel ${channelId} — ` +
|
||||
`setting 5s cooldown for guild ${gId}`
|
||||
`[FluxerRevoice] 401 error for channel ${channelId} in guild ${gId ?? "unknown"}`
|
||||
);
|
||||
}
|
||||
}
|
||||
throw new Error(`Fluxer voice join failed for ${channelId}: ${e.message}`);
|
||||
}
|
||||
|
||||
@@ -624,7 +508,7 @@ export class FluxerRevoice extends EventEmitter {
|
||||
throw new Error(`Fluxer voice join returned null for ${channelId}`);
|
||||
}
|
||||
|
||||
logger.player(`[FluxerRevoice] Gateway join successful, extracting LiveKit room...`);
|
||||
logger.player(`[FluxerRevoice] Gateway join successful for ${channelId}`);
|
||||
|
||||
// The @fluxerjs/voice connection wraps a LiveKit Room.
|
||||
// Extract it so we can use it with revoice.js's MediaPlayer.
|
||||
@@ -700,18 +584,6 @@ export class FluxerRevoice extends EventEmitter {
|
||||
|
||||
logger.player(`[FluxerRevoice] LiveKit room ready (isConnected: ${finalConnected}, connectionState: ${stateLabel(finalCS)})`);
|
||||
|
||||
// Record the successful join time for this guild so future joins
|
||||
// can enforce the minimum interval and avoid 401 races.
|
||||
// Clear any 401 cooldown for this guild since the join succeeded.
|
||||
// Try both the resolved channelGuildId and the pre-resolved guildId
|
||||
// to ensure the cooldown is properly cleared even if channelGuildId
|
||||
// couldn't be resolved from the channel object.
|
||||
const clearIds = new Set([channelGuildId, guildId].filter(Boolean));
|
||||
for (const gId of clearIds) {
|
||||
this._guildLastJoinTime.set(gId, Date.now());
|
||||
this._guild401Cooldown.delete(gId);
|
||||
}
|
||||
|
||||
// Create our FluxerVoiceConnection wrapper
|
||||
const connection = new FluxerVoiceConnection(channelId, this, {
|
||||
room,
|
||||
@@ -725,7 +597,7 @@ export class FluxerRevoice extends EventEmitter {
|
||||
room.on(RoomEvent.Disconnected, (reason) => {
|
||||
const isIntentional = this._intentionalDisconnects.has(String(channelId));
|
||||
const reasonLabel = isIntentional ? "intentional" : (reason ?? "unexpected");
|
||||
logger.player(`[FluxerRevoice] Room disconnected: ${reasonLabel}${isIntentional ? " (bot-initiated, recovery suppressed)" : ""}`);
|
||||
logger.player(`[FluxerRevoice] Room disconnected: ${reasonLabel}`);
|
||||
this._intentionalDisconnects.delete(String(channelId));
|
||||
connection._connected = false;
|
||||
connection._destroyed = true;
|
||||
@@ -744,57 +616,14 @@ export class FluxerRevoice extends EventEmitter {
|
||||
if (nativeConnection && typeof nativeConnection.disconnect === "function") {
|
||||
try { nativeConnection.disconnect(); } catch (_) {}
|
||||
}
|
||||
|
||||
// Auto-rejoin on unexpected disconnect (serverLeave) ──
|
||||
// Per the Fluxer.js Voice guide: "If using LiveKit, the server may
|
||||
// emit serverLeave. Listen and reconnect if needed." When the LiveKit
|
||||
// room disconnects unexpectedly (token expiry, server restart, network
|
||||
// blip), we attempt to rejoin the same channel after a short delay.
|
||||
// The rejoin triggers a fresh VOICE_STATE_UPDATE → VOICE_SERVER_UPDATE
|
||||
// flow, giving us a new LiveKit token. The global join queue ensures
|
||||
// we don't collide with other in-flight joins.
|
||||
if (channelGuildId) {
|
||||
const rejoinDelay = 3_000; // 3s delay to let the gateway settle
|
||||
logger.player(
|
||||
`[FluxerRevoice] Scheduling auto-rejoin for channel ${channelId} ` +
|
||||
`in ${rejoinDelay}ms after unexpected disconnect`
|
||||
);
|
||||
setTimeout(async () => {
|
||||
try {
|
||||
// Check if the bot was intentionally disconnected in the meantime
|
||||
if (this._intentionalDisconnects.has(String(channelId))) {
|
||||
logger.player(`[FluxerRevoice] Skipping auto-rejoin — intentional disconnect detected for ${channelId}`);
|
||||
return;
|
||||
}
|
||||
// Check if another connection already exists (e.g. user ran !join)
|
||||
if (this.connections.has(channelId)) {
|
||||
logger.player(`[FluxerRevoice] Skipping auto-rejoin — connection already exists for ${channelId}`);
|
||||
return;
|
||||
}
|
||||
logger.player(`[FluxerRevoice] Auto-rejoining channel ${channelId}...`);
|
||||
await this.join(channelId);
|
||||
logger.player(`[FluxerRevoice] Auto-rejoin succeeded for channel ${channelId}`);
|
||||
} catch (e) {
|
||||
logger.warn(
|
||||
`[FluxerRevoice] Auto-rejoin failed for channel ${channelId}: ${e?.message ?? e}. ` +
|
||||
`BootRecovery will retry on next restart.`
|
||||
);
|
||||
}
|
||||
}, rejoinDelay);
|
||||
}
|
||||
}
|
||||
|
||||
connection.emit("disconnect");
|
||||
});
|
||||
|
||||
room.on(RoomEvent.Reconnecting, () => {
|
||||
logger.player("[FluxerRevoice] Room reconnecting...");
|
||||
});
|
||||
|
||||
room.on(RoomEvent.Reconnected, () => {
|
||||
logger.player("[FluxerRevoice] Room reconnected");
|
||||
connection._connected = true;
|
||||
});
|
||||
// No automatic reconnection handling — if the LiveKit room disconnects
|
||||
// unexpectedly, the connection is considered dead. The caller (Player.mjs)
|
||||
// will emit "autoleave" and the user must manually rejoin if desired.
|
||||
|
||||
room.on(RoomEvent.ParticipantConnected, (participant) => {
|
||||
const userId = participant?.identity ?? participant?.sid;
|
||||
|
||||
Reference in new issue
Block a user