This commit is contained in:
NoLogicAlan committed 2026-05-20 22:32:39 +03:00
1 parent 05fb38aabd
commit bc1fe82919
43 files changed
+122 -1784

No files matched your search

+8 -130
View File
@@ -32,62 +32,37 @@ import { joinVoiceChannel, getVoiceManager } from "@fluxerjs/voice";
import { logger } from "./Logger.mjs";
{
// ── LiveKit SDK log suppression ──────────────────────────────────────────
// The LiveKit Node.js SDK (via pino) emits verbose JSON and human-readable
// log lines that flood the console. We monkey-patch console.log and
// process.stdout.write to silently drop lines from the "lk-rtc" logger.
//
// Guard: only patch once even if the module is imported multiple times
// (e.g. during hot-reload). The global symbol ensures idempotency.
if (!globalThis.__fluxerLiveKitLogPatchApplied) {
globalThis.__fluxerLiveKitLogPatchApplied = true;
const _originalConsoleLog = console.log;
console.log = function (...args) {
// Fast path: if the first arg is a string that looks like a pino JSON log
if (args.length === 1 && typeof args[0] === "string" && args[0].startsWith("{")) {
try {
const parsed = JSON.parse(args[0]);
// Drop pino logs from LiveKit SDK ("lk-rtc" name)
if (parsed.name === "lk-rtc") return;
} catch (_) {
// Not valid JSON — pass through
}
}
// Suppress LiveKit SDK's human-readable log lines:
// [voice LiveKitRtc] connected to room
// [voice LiveKitRtc] Room disconnected
// [voice LiveKitRtc] emitting disconnect
// [voice LiveKitRtc] Room reconnecting...
// [voice LiveKitRtc] Room reconnected
if (args.length >= 1 && typeof args[0] === "string" && args[0].includes("[voice LiveKitRtc]")) {
return; // silently drop
return;
}
_originalConsoleLog.apply(console, args);
};
// ── Also monkey-patch process.stdout.write ──────────────────────────────
// Pino writes directly to process.stdout.write, bypassing console.log
// entirely. This is the primary path for the JSON log lines like:
// {"level":20,"time":1778784504183,"pid":961949,"name":"lk-rtc",...}
// We intercept these and silently drop them.
const _originalStdoutWrite = process.stdout.write.bind(process.stdout);
process.stdout.write = function (chunk, encoding, callback) {
// Only intercept string chunks that look like pino JSON logs
if (typeof chunk === "string" && chunk.startsWith("{")) {
try {
// Fast check: does it contain lk-rtc before full parse?
if (chunk.includes('"lk-rtc"')) {
const parsed = JSON.parse(chunk);
if (parsed.name === "lk-rtc") {
// Silently drop — call callback to signal "written" so pino doesn't stall
if (typeof encoding === "function") { encoding(); }
else if (typeof callback === "function") { callback(); }
return true;
}
}
} catch (_) {
// Not valid JSON — pass through
}
}
return _originalStdoutWrite(chunk, encoding, callback);
@@ -95,26 +70,18 @@ import { logger } from "./Logger.mjs";
}
}
// ConnectionState enum values for reference:
// ConnectionState.CONN_DISCONNECTED = 0
// ConnectionState.CONN_CONNECTED = 1
// ConnectionState.CONN_RECONNECTING = 2
/** Helper: returns a human-readable label for a ConnectionState value */
function stateLabel(cs) {
if (cs === ConnectionState?.CONN_CONNECTED) return "CONN_CONNECTED";
if (cs === ConnectionState?.CONN_DISCONNECTED) return "CONN_DISCONNECTED";
if (cs === ConnectionState?.CONN_RECONNECTING) return "CONN_RECONNECTING";
// Fallback for numeric values if enum import fails
if (cs === 1) return "CONN_CONNECTED(1)";
if (cs === 0) return "CONN_DISCONNECTED(0)";
if (cs === 2) return "CONN_RECONNECTING(2)";
return String(cs);
}
// ═══════════════════════════════════════════════════════════════════════════════
// FluxerVoiceConnection — compatible with revoice.js VoiceConnection
// ═══════════════════════════════════════════════════════════════════════════════
/**
* A voice connection that wraps a LiveKit Room obtained via the Fluxer
@@ -132,12 +99,11 @@ export class FluxerVoiceConnection extends EventEmitter {
/** @type {Room|null} */
room = null;
channelId = null;
_voice = null; // parent FluxerRevoice instance
_connected = false; // internal flag, set by events
_users = []; // internal, derived from parent FluxerRevoice.users
_voice = null;
_connected = false;
_users = [];
_destroyed = false;
// @fluxerjs/voice native connection reference (for proper disconnect)
_nativeConn = null;
/**
@@ -159,7 +125,6 @@ export class FluxerVoiceConnection extends EventEmitter {
this._voice = voice;
this.room = opts.room ?? null;
this._nativeConn = opts.nativeConnection ?? null;
// Use room.isConnected (boolean getter) — the correct Node.js SDK API
this._connected = !!(this.room && this.room.isConnected);
}
@@ -170,7 +135,6 @@ export class FluxerVoiceConnection extends EventEmitter {
*/
get connected() {
if (this._destroyed) return false;
// Prefer the LiveKit Room's own isConnected getter (source of truth)
if (this.room) return this.room.isConnected;
return this._connected;
}
@@ -186,29 +150,20 @@ export class FluxerVoiceConnection extends EventEmitter {
*/
async disconnect() {
if (this._destroyed) return;
// Mark this as an intentional disconnect so the RoomEvent.Disconnected
// 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.
// The native disconnect path can be guild-scoped in some environments,
// which drops every voice connection in the guild.
const guildId = this._voice._resolveGuildForChannel?.(this.channelId) ?? null;
this._voice._leaveGateway?.(this.channelId, guildId);
}
this._destroyed = true;
this._connected = false;
// Close the LiveKit room directly after sending the leave signal.
// This keeps the disconnect scoped to the target channel.
if (this.room) {
try {
await this.room.disconnect();
} catch (e) {
// Room may already be closed
}
} else if (this._nativeConn && typeof this._nativeConn.disconnect === "function") {
// Fallback only when no room object is available.
try {
await this._nativeConn.disconnect();
} catch (e) {
@@ -228,33 +183,27 @@ export class FluxerVoiceConnection extends EventEmitter {
}
}
// ═══════════════════════════════════════════════════════════════════════════════
// FluxerRevoice — drop-in replacement for revoice.js Revoice
// ═══════════════════════════════════════════════════════════════════════════════
/**
* Revoice-compatible class that uses the Fluxer gateway for voice joins.
*
* Usage (drop-in for `new Revoice(token)`):
*
* // Before (third-party API — 401 on Fluxer):
*
* this.revoice = new Revoice(config.token);
*
* // After (Fluxer API — works on Fluxer):
*
* this.revoice = new FluxerRevoice(client);
*/
export class FluxerRevoice extends EventEmitter {
/** @type {import("@fluxerjs/core").Client} */
client = null;
connections = new Map();
// Unified users map: keyed by "channelId:userId", value is { id, connectedTo }
// This is the single source of truth; connection.users is derived from it.
users = new Map();
/** @type {Map<string, Promise>} */
_guildJoinQueue = new Map();
// ── Global join queue ──────────────────────────────────────────────────────
/** @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.
@@ -304,7 +253,6 @@ export class FluxerRevoice extends EventEmitter {
*/
markIntentionalDisconnect(channelId) {
this._intentionalDisconnects.add(String(channelId));
// Auto-clear after 10 seconds as safety net
setTimeout(() => this._intentionalDisconnects.delete(String(channelId)), 10_000);
}
@@ -331,11 +279,6 @@ export class FluxerRevoice extends EventEmitter {
const guildForLeave = guildId ?? this._resolveGuildForChannel(channelId);
// ── Method 1 (PREFERRED): Use vm.leaveChannel(channelId) ──────────
// This sends a channel-specific VOICE_STATE_UPDATE that only leaves
// the specified channel, preserving all other voice connections in
// the same guild. This is critical for multi-voice / 24/7 setups
// where the bot may be in several channels simultaneously.
if (typeof vm.leaveChannel === "function") {
try {
vm.leaveChannel(channelId);
@@ -346,10 +289,6 @@ export class FluxerRevoice extends EventEmitter {
}
}
// ── Method 2: Use vm.leave(guildId) — guild-level fallback ─────────
// WARNING: This disconnects ALL voice channels in the guild, not just
// the target channel. Only used when leaveChannel() is unavailable.
// The caller must handle rejoining other 24/7 channels if needed.
if (guildForLeave && typeof vm.leave === "function") {
try {
vm.leave(guildForLeave);
@@ -360,12 +299,8 @@ export class FluxerRevoice extends EventEmitter {
}
}
// ── Method 3: Use vm.updateVoiceState() as last resort ─────────────
if (typeof vm.updateVoiceState === "function") {
if (guildForLeave) {
// NEVER send an unscoped updateVoiceState(null, opts) because it
// tells the gateway to leave ALL guilds' voice channels, causing
// cascading disconnections across all active voice connections.
try {
vm.updateVoiceState(guildForLeave, null, { self_deaf: false, self_mute: false });
logger.player(`[FluxerRevoice] Sent gateway leave via updateVoiceState() for guild ${guildForLeave}`);
@@ -407,19 +342,15 @@ export class FluxerRevoice extends EventEmitter {
* @param {FluxerVoiceConnection} existing
*/
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 logs correctly
this.markIntentionalDisconnect(channelId);
const staleGuildId = this._resolveGuildForChannel(channelId);
this._leaveGateway(channelId, staleGuildId);
// 2. Close the LiveKit Room directly
if (existing.room) {
try {
await existing.room.disconnect();
} catch (_) {
// Room may already be closed
}
} else if (existing._nativeConn && typeof existing._nativeConn.disconnect === "function") {
try {
@@ -429,7 +360,6 @@ export class FluxerRevoice extends EventEmitter {
}
}
// 3. Mark as destroyed and clean up listeners
existing._destroyed = true;
existing._connected = false;
try { existing.removeAllListeners(); } catch (_) {}
@@ -448,17 +378,13 @@ export class FluxerRevoice extends EventEmitter {
*/
async join(channelId, _leaveIfEmpty = false) {
const joinOperation = async () => {
// Small gap between joins to let the gateway process the previous
// session's cleanup. This runs BEFORE the actual join logic.
await new Promise(r => setTimeout(r, this._globalJoinDelay));
return await this._joinInternal(channelId, _leaveIfEmpty);
};
// Chain onto the global queue: our join only starts after the previous
// one has fully completed (or failed). We store the new tail of the chain.
const prevQueue = this._globalJoinQueue;
const ourResult = prevQueue.then(() => joinOperation());
this._globalJoinQueue = ourResult.catch(() => {}); // don't break chain on error
this._globalJoinQueue = ourResult.catch(() => {});
return await ourResult;
}
@@ -471,7 +397,6 @@ export class FluxerRevoice extends EventEmitter {
* @returns {Promise<FluxerVoiceConnection>}
*/
async _joinInternal(channelId, _leaveIfEmpty = false) {
// Resolve the guild ID for this channel
let guildId = null;
try {
const ch = this.client.channels?.get?.(channelId);
@@ -480,10 +405,6 @@ export class FluxerRevoice extends EventEmitter {
if (this.connections.has(channelId)) {
const existing = this.connections.get(channelId);
// If the existing connection is still alive, reuse it.
// If the LiveKit room disconnected, the connection is stale — clean it
// up fully and rejoin instead of returning a dead connection that will
// fail with "LiveKit disconnected (connectionState: 0)".
if (existing && !existing._destroyed && existing.room && existing.room.isConnected) {
logger.player(`[FluxerRevoice] Already connected to ${channelId}, returning existing connection`);
return existing;
@@ -498,7 +419,6 @@ export class FluxerRevoice extends EventEmitter {
logger.player(`[FluxerRevoice] Joining channel ${channelId} via Fluxer gateway...`);
// Fetch the channel object from the client cache (or REST)
let channel = this.client.channels?.get?.(channelId);
if (!channel) {
try {
@@ -511,17 +431,8 @@ export class FluxerRevoice extends EventEmitter {
throw new Error(`Channel not found: ${channelId}`);
}
// Resolve the guild ID for this channel (used for guild-scoped leave signals)
const channelGuildId = guildId ?? channel?.guildId ?? channel?.guild?.id ?? null;
// Use @fluxerjs/voice to join the channel via the Fluxer gateway.
// This handles the VOICE_STATE_UPDATE → VOICE_SERVER_UPDATE flow
// and creates a LiveKit connection with the returned credentials.
//
// Permission validation is handled upstream in PlayerManager via
// botHasVoicePermissions() — real permission errors are caught before
// we even reach this point. If we get a 401 here, it's a stale session,
// and PlayerManager's sanitizeJoinError will handle the retry.
let nativeConnection;
try {
nativeConnection = await joinVoiceChannel(this.client, channel);
@@ -535,17 +446,13 @@ export class FluxerRevoice extends EventEmitter {
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.
let room = null;
// Try to get the LiveKit Room from the native connection
if (nativeConnection.room) {
room = nativeConnection.room;
logger.player(`[FluxerRevoice] Got LiveKit room from native connection (isConnected: ${room.isConnected}, connectionState: ${stateLabel(room.connectionState)})`);
}
// (non-LiveKit) which we don't support for music playback.
if (!room) {
try { await nativeConnection.disconnect(); } catch (_) {}
throw new Error(
@@ -554,16 +461,10 @@ export class FluxerRevoice extends EventEmitter {
);
}
// ── Wait for the room to be connected ────────────────────────────────
// Use room.isConnected (boolean) and room.connectionState (enum) which
// are the correct APIs in @livekit/rtc-node Node.js SDK.
// Also listen for the ConnectionStateChanged event for immediate feedback.
const maxWait = 10_000;
const startTime = Date.now();
// If already connected, skip the wait loop
if (!room.isConnected) {
// Listen for the ConnectionStateChanged event to resolve faster
let eventResolved = false;
const statePromise = new Promise((resolve) => {
const handler = (cs) => {
@@ -575,30 +476,25 @@ export class FluxerRevoice extends EventEmitter {
} else if (cs === ConnectionState?.CONN_DISCONNECTED || cs === 0) {
eventResolved = true;
room.off(RoomEvent.ConnectionStateChanged, handler);
resolve(); // resolve so we can check isConnected below
resolve();
}
};
room.on(RoomEvent.ConnectionStateChanged, handler);
});
// Poll + event race
while (!room.isConnected && (Date.now() - startTime) < maxWait) {
// Wait for either the event to fire or a 200ms poll interval
await Promise.race([
statePromise,
new Promise(r => setTimeout(r, 200)),
]);
// Check if connected
if (room.isConnected) break;
// Check if disconnected (dead state)
const cs = room.connectionState;
if (cs === ConnectionState?.CONN_DISCONNECTED || cs === 0) break;
}
}
// Final state check using the correct API
const finalConnected = room.isConnected;
const finalCS = room.connectionState;
@@ -609,15 +505,11 @@ export class FluxerRevoice extends EventEmitter {
logger.player(`[FluxerRevoice] LiveKit room ready (isConnected: ${finalConnected}, connectionState: ${stateLabel(finalCS)})`);
// Create our FluxerVoiceConnection wrapper
const connection = new FluxerVoiceConnection(channelId, this, {
room,
nativeConnection,
});
// ── LiveKit room event forwarding ──────────────────────────────────
// Forward LiveKit events to FluxerVoiceConnection events so
// Player.mjs's connection.on("disconnect") etc. still work.
room.on(RoomEvent.Disconnected, (reason) => {
const isIntentional = this._intentionalDisconnects.has(String(channelId));
@@ -627,17 +519,11 @@ export class FluxerRevoice extends EventEmitter {
connection._connected = false;
connection._destroyed = true;
// Remove from connections map so the next join() creates a fresh
// connection instead of returning this dead one.
this.connections.delete(channelId);
if (!isIntentional) {
// Unexpected disconnects still need a gateway leave signal so the
// next join gets a fresh voice session.
this._leaveGateway(channelId, channelGuildId);
// Best-effort cleanup for the native wrapper. Skip this on intentional
// leaves because it can collapse multi-voice into a guild-wide leave.
if (nativeConnection && typeof nativeConnection.disconnect === "function") {
try { nativeConnection.disconnect(); } catch (_) {}
}
@@ -646,16 +532,12 @@ export class FluxerRevoice extends EventEmitter {
connection.emit("disconnect");
});
// 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;
if (userId) {
const uKey = `${channelId}:${userId}`;
this.users.set(uKey, { id: userId, connectedTo: channelId });
// Derive connection.users from the unified map (single source of truth)
connection._users = [...this.users.values()].filter(u => u.connectedTo === channelId);
connection.emit("userjoin", userId);
}
@@ -666,19 +548,15 @@ export class FluxerRevoice extends EventEmitter {
if (userId) {
const uKey = `${channelId}:${userId}`;
this.users.delete(uKey);
// Derive connection.users from the unified map
connection._users = [...this.users.values()].filter(u => u.connectedTo === channelId);
connection.emit("userleave", userId);
}
});
// Track the connection
this.connections.set(channelId, connection);
// Auto-leave when room empties (if requested)
if (_leaveIfEmpty) {
connection.on("userleave", () => {
// Only trigger autoleave if no remote participants remain
const remoteCount = room.remoteParticipants?.size ?? 0;
if (remoteCount === 0) {
logger.player(`[FluxerRevoice] Room empty, triggering autoleave for ${channelId}`);