mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
feat: voice joins with FluxerRevoice adapter
This commit is contained in:
1 parent
40b1519de3
commit
5183f41862
9 files changed
+612
-120
No files matched your search
@@ -47,6 +47,7 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) {
|
|||||||
config: this.config,
|
config: this.config,
|
||||||
nodelink: this.config.nodelink,
|
nodelink: this.config.nodelink,
|
||||||
moonlink: this.moonlink ?? null,
|
moonlink: this.moonlink ?? null,
|
||||||
|
revoice: this.revoice ?? null,
|
||||||
messageChannel: message.channel,
|
messageChannel: message.channel,
|
||||||
settingsMgr: this.settingsMgr ?? this.settings ?? null,
|
settingsMgr: this.settingsMgr ?? this.settings ?? null,
|
||||||
observedVoiceUsers: this.observedVoiceUsers ?? null,
|
observedVoiceUsers: this.observedVoiceUsers ?? null,
|
||||||
|
|||||||
@@ -9,6 +9,7 @@ import { RemoteSettingsManager } from "./src/Settings.mjs";
|
|||||||
import { PlayerManager } from "./src/PlayerManager.mjs";
|
import { PlayerManager } from "./src/PlayerManager.mjs";
|
||||||
import childProcess from "node:child_process";
|
import childProcess from "node:child_process";
|
||||||
import { getVoiceManager } from "@fluxerjs/voice";
|
import { getVoiceManager } from "@fluxerjs/voice";
|
||||||
|
import { FluxerRevoice } from "./src/constants/FluxerRevoice.mjs";
|
||||||
import { MoonlinkManager } from "./src/MoonlinkManager.mjs";
|
import { MoonlinkManager } from "./src/MoonlinkManager.mjs";
|
||||||
import { Dashboard } from "./src/dashboard/Dashboard.mjs";
|
import { Dashboard } from "./src/dashboard/Dashboard.mjs";
|
||||||
import { Locale } from "./src/constants/Locale.mjs";
|
import { Locale } from "./src/constants/Locale.mjs";
|
||||||
@@ -229,6 +230,14 @@ export class Remix {
|
|||||||
client.on(Events.Ready, async () => {
|
client.on(Events.Ready, async () => {
|
||||||
logger.player("Logged in as " + (client.user?.username ?? "bot"));
|
logger.player("Logged in as " + (client.user?.username ?? "bot"));
|
||||||
|
|
||||||
|
// ── Attach proactive error handlers on WS shards ───────────────────
|
||||||
|
// @fluxerjs/ws throws "WebSocket error" on socket close/reconnect.
|
||||||
|
// Without an error handler on the WS object, this escalates to
|
||||||
|
// uncaughtException and produces noisy stack traces. By attaching
|
||||||
|
// .on("error") handlers on every shard's WebSocket, we catch the
|
||||||
|
// error at the source and log it cleanly instead.
|
||||||
|
this._attachWsErrorHandlers();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
getVoiceManager(client);
|
getVoiceManager(client);
|
||||||
logger.player("VoiceManager initialized.");
|
logger.player("VoiceManager initialized.");
|
||||||
@@ -272,12 +281,23 @@ export class Remix {
|
|||||||
this.gatewayHandler.onReady();
|
this.gatewayHandler.onReady();
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ── FluxerRevoice Instance (shared across all players) ─────────────────
|
||||||
|
// Uses the Fluxer gateway (via @fluxerjs/voice) to join voice channels
|
||||||
|
// instead of a third-party REST API. This avoids the 401 error that occurs
|
||||||
|
// when a Fluxer bot token is sent to an incompatible API endpoint.
|
||||||
|
// The FluxerRevoice class provides the same .join() interface as
|
||||||
|
// revoice.js's Revoice class, returning FluxerVoiceConnection objects
|
||||||
|
// that wrap LiveKit Rooms compatible with revoice.js's MediaPlayer.
|
||||||
|
this.revoice = new FluxerRevoice(client);
|
||||||
|
logger.player("[FluxerRevoice] Instance created with Fluxer client.");
|
||||||
|
|
||||||
// ── Player Manager ───────────────────────────────────────────────────────
|
// ── Player Manager ───────────────────────────────────────────────────────
|
||||||
this.playerContext = {
|
this.playerContext = {
|
||||||
client: this.client,
|
client: this.client,
|
||||||
config,
|
config,
|
||||||
nodelink: config.nodelink,
|
nodelink: config.nodelink,
|
||||||
moonlink: null,
|
moonlink: null,
|
||||||
|
revoice: this.revoice,
|
||||||
};
|
};
|
||||||
this.players = new PlayerManager(settings, commands, {
|
this.players = new PlayerManager(settings, commands, {
|
||||||
config,
|
config,
|
||||||
@@ -544,6 +564,79 @@ export class Remix {
|
|||||||
|
|
||||||
// ─── Helpers ──────────────────────────────────────────────────────────────
|
// ─── Helpers ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Attach error handlers on all @fluxerjs/ws shard WebSockets.
|
||||||
|
*
|
||||||
|
* When the Fluxer gateway's underlying WebSocket closes (e.g. network
|
||||||
|
* blip, server restart), @fluxerjs/ws throws a "WebSocket error" from
|
||||||
|
* its internal error handler. Without an .on("error") listener on the
|
||||||
|
* WS object itself, this escalates to Node's uncaughtException handler,
|
||||||
|
* producing a noisy stack trace even though the bot recovers
|
||||||
|
* automatically via gateway reconnection.
|
||||||
|
*
|
||||||
|
* By attaching .on("error") handlers here, we catch the error at the
|
||||||
|
* source, log a single clean line, and prevent it from reaching
|
||||||
|
* uncaughtException.
|
||||||
|
*/
|
||||||
|
_attachWsErrorHandlers() {
|
||||||
|
try {
|
||||||
|
const wsManager = this.client?.ws;
|
||||||
|
if (!wsManager) return;
|
||||||
|
|
||||||
|
// @fluxerjs/ws may use a single connection or a ShardManager.
|
||||||
|
// Handle both patterns:
|
||||||
|
const attachToSocket = (wsObj, label) => {
|
||||||
|
if (!wsObj) return;
|
||||||
|
// Avoid attaching duplicate handlers on reconnect
|
||||||
|
if (wsObj._fluxerErrorHandled) return;
|
||||||
|
wsObj._fluxerErrorHandled = true;
|
||||||
|
|
||||||
|
if (typeof wsObj.on === "function") {
|
||||||
|
wsObj.on("error", (err) => {
|
||||||
|
logger.warn(`[WS] ${label} transport error (auto-recovering): ${err?.message ?? err}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (typeof wsObj.addEventListener === "function") {
|
||||||
|
wsObj.addEventListener("error", (event) => {
|
||||||
|
const err = event?.error ?? event?.message ?? event;
|
||||||
|
logger.warn(`[WS] ${label} transport error (auto-recovering): ${err?.message ?? err}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
// Pattern 1: ws.shards is a Map (multi-shard)
|
||||||
|
if (wsManager.shards && typeof wsManager.shards.forEach === "function") {
|
||||||
|
wsManager.shards.forEach((shard, id) => {
|
||||||
|
attachToSocket(shard?.ws, `Shard ${id}`);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pattern 2: ws itself has a .ws property (single-shard)
|
||||||
|
if (wsManager.ws) {
|
||||||
|
attachToSocket(wsManager.ws, "Gateway");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Pattern 3: ws is itself a WebSocket-like object
|
||||||
|
if (typeof wsManager.on === "function" && !wsManager._fluxerErrorHandled) {
|
||||||
|
attachToSocket(wsManager, "WSManager");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Also listen for new shards being created (future-proofing)
|
||||||
|
if (typeof wsManager.on === "function" && !wsManager._shardCreateHandled) {
|
||||||
|
wsManager._shardCreateHandled = true;
|
||||||
|
wsManager.on("shardCreate", (shard) => {
|
||||||
|
if (shard?.ws) {
|
||||||
|
attachToSocket(shard.ws, `Shard ${shard.id ?? "?"}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.player("[WS] Proactive error handlers attached to gateway sockets.");
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[WS] Failed to attach WS error handlers:", e.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
markIntentionalLeave(channelId, ttlMs = null) {
|
markIntentionalLeave(channelId, ttlMs = null) {
|
||||||
const clean = String(channelId).replace(/\D/g, "");
|
const clean = String(channelId).replace(/\D/g, "");
|
||||||
if (!clean) return;
|
if (!clean) return;
|
||||||
@@ -739,6 +832,11 @@ const remix = new Remix();
|
|||||||
const isIgnorableWsCrash = (err) => {
|
const isIgnorableWsCrash = (err) => {
|
||||||
const message = String(err?.message ?? err ?? "");
|
const message = String(err?.message ?? err ?? "");
|
||||||
const stack = String(err?.stack ?? "");
|
const stack = String(err?.stack ?? "");
|
||||||
|
// WebSocket transport errors from @fluxerjs/ws — these are recoverable
|
||||||
|
// because the gateway client automatically reconnects. They should be
|
||||||
|
// caught by the proactive .on("error") handlers in _attachWsErrorHandlers(),
|
||||||
|
// but this acts as a safety net in case a new shard is created after the
|
||||||
|
// initial handler attachment or the error slips through via a different path.
|
||||||
return message === "WebSocket error" &&
|
return message === "WebSocket error" &&
|
||||||
(
|
(
|
||||||
stack.includes("@fluxerjs/ws/dist/index.mjs") ||
|
stack.includes("@fluxerjs/ws/dist/index.mjs") ||
|
||||||
|
|||||||
@@ -703,7 +703,7 @@ export class GatewayHandler {
|
|||||||
const player = remix.players.playerMap.get(cleanId_ref);
|
const player = remix.players.playerMap.get(cleanId_ref);
|
||||||
if (player) {
|
if (player) {
|
||||||
// Send "join" or "leave" on the per-player channel
|
// Send "join" or "leave" on the per-player channel
|
||||||
// (matching Stoat format: { type, data } where data = userId)
|
// (standard format: { type, data } where data = userId)
|
||||||
const eventType = channelId ? "join" : "leave";
|
const eventType = channelId ? "join" : "leave";
|
||||||
remix.dashboard.updatePlayer({
|
remix.dashboard.updatePlayer({
|
||||||
type: eventType,
|
type: eventType,
|
||||||
|
|||||||
+135
-109
@@ -1,15 +1,21 @@
|
|||||||
/**
|
/**
|
||||||
* Player.mjs — moonlink.js + revoice.js edition
|
* Player.mjs — FluxerRevoice edition
|
||||||
*
|
*
|
||||||
* Track resolution → moonlink.js Manager (search / load via NodeLink REST)
|
* Track resolution → moonlink.js Manager (search / load via NodeLink REST)
|
||||||
* Session handling → moonlink.js (WebSocket to NodeLink, session ID, player state)
|
* Session handling → moonlink.js (WebSocket to NodeLink, session ID, player state)
|
||||||
* Audio playback → revoice.js (LiveKit voice connection → Fluxer VC)
|
* Voice connection → FluxerRevoice (Fluxer gateway → LiveKit voice)
|
||||||
|
* Audio playback → revoice.js MediaPlayer (FFmpeg → LiveKit audio track)
|
||||||
*
|
*
|
||||||
|
* FluxerRevoice uses the Fluxer API/gateway (via @fluxerjs/voice) to obtain
|
||||||
|
* LiveKit credentials instead of a third-party REST API that the default
|
||||||
|
* revoice.js Revoice class uses. This avoids the 401 Unauthorized error
|
||||||
|
* that occurs when a Fluxer bot token is sent to an incompatible API.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import Revoicejs from "revoice.js";
|
import Revoicejs from "revoice.js";
|
||||||
const { MediaPlayer } = Revoicejs;
|
const { MediaPlayer } = Revoicejs;
|
||||||
import { joinVoiceChannel, getVoiceManager } from "@fluxerjs/voice";
|
import { ConnectionState, RoomEvent as LKRoomEvent } from "@livekit/rtc-node";
|
||||||
|
import { getVoiceManager } from "@fluxerjs/voice";
|
||||||
import { Utils } from "./Utils.mjs";
|
import { Utils } from "./Utils.mjs";
|
||||||
import { EventEmitter } from "node:events";
|
import { EventEmitter } from "node:events";
|
||||||
import meta from "./probe.mjs";
|
import meta from "./probe.mjs";
|
||||||
@@ -310,6 +316,8 @@ export default class Player extends EventEmitter {
|
|||||||
// revoice.js instances
|
// revoice.js instances
|
||||||
/** @type {import("revoice.js").MediaPlayer|null} */
|
/** @type {import("revoice.js").MediaPlayer|null} */
|
||||||
_mediaPlayer = null;
|
_mediaPlayer = null;
|
||||||
|
/** @type {import("./constants/FluxerRevoice.mjs").FluxerRevoice|null} Shared FluxerRevoice instance (injected from Remix) */
|
||||||
|
_revoice = null;
|
||||||
|
|
||||||
// moonlink.js manager reference (set by PlayerManager)
|
// moonlink.js manager reference (set by PlayerManager)
|
||||||
/** @type {import("./MoonlinkManager.mjs").MoonlinkManager|null} */
|
/** @type {import("./MoonlinkManager.mjs").MoonlinkManager|null} */
|
||||||
@@ -387,6 +395,9 @@ export default class Player extends EventEmitter {
|
|||||||
// moonlink.js manager reference — injected by PlayerManager
|
// moonlink.js manager reference — injected by PlayerManager
|
||||||
this._moonlink = opts.moonlink ?? null;
|
this._moonlink = opts.moonlink ?? null;
|
||||||
|
|
||||||
|
// 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 reconnection and stale sessions
|
||||||
if (this._moonlink) {
|
if (this._moonlink) {
|
||||||
this._onMoonlinkReady = (sessionId) => {
|
this._onMoonlinkReady = (sessionId) => {
|
||||||
@@ -556,12 +567,12 @@ export default class Player extends EventEmitter {
|
|||||||
logger.mediaplayer(`[Player] Rejoining channel ${targetChannelId}`);
|
logger.mediaplayer(`[Player] Rejoining channel ${targetChannelId}`);
|
||||||
await this.join(targetChannelId);
|
await this.join(targetChannelId);
|
||||||
|
|
||||||
// Do NOT re-read room.state here — on this LiveKit build room.state
|
// Do NOT re-read room.isConnected/room.connectionState here —
|
||||||
// returns undefined even on a healthy connection (not persistently stored).
|
// join() already awaited ConnectionStateChanged and only resolved when
|
||||||
// join() already awaited connectionStateChanged and only resolved when
|
|
||||||
// the room was truly connected, so reaching this line means success.
|
// the room was truly connected, so reaching this line means success.
|
||||||
// The old room.state check here always threw "unexpected state: undefined"
|
// The old check using room.state (which doesn't exist in @livekit/rtc-node)
|
||||||
// and emitted autoleave, causing the infinite reconnect storm in the logs.
|
// always threw "unexpected state: undefined" and emitted autoleave,
|
||||||
|
// causing the infinite reconnect storm in the logs.
|
||||||
this._isRecovering = false;
|
this._isRecovering = false;
|
||||||
this._recoveryPending = false;
|
this._recoveryPending = false;
|
||||||
this._recoveryAttempts = 0;
|
this._recoveryAttempts = 0;
|
||||||
@@ -726,16 +737,14 @@ export default class Player extends EventEmitter {
|
|||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
// only block on explicit dead states — do NOT treat undefined as dead.
|
// Use the correct @livekit/rtc-node Node.js SDK API:
|
||||||
// On some LiveKit builds room.state is not a persistent property and returns
|
// room.isConnected — boolean getter (true when connected)
|
||||||
// undefined even while the room is healthy. Blocking on undefined here causes
|
// room.connectionState — ConnectionState enum (CONN_DISCONNECTED=0, CONN_CONNECTED=1, CONN_RECONNECTING=2)
|
||||||
// publishToRoom to be skipped on a perfectly live connection.
|
// room.state — does NOT exist (that's the browser SDK API)
|
||||||
const roomState = room.state;
|
const roomAlive = room.isConnected;
|
||||||
const roomAlive = roomState !== "disconnected" &&
|
const cs = room.connectionState;
|
||||||
roomState !== "failed" &&
|
|
||||||
roomState !== 0;
|
|
||||||
|
|
||||||
logger.mediaplayer(`[Player] _ensureMediaPlayer: attempting to create MediaPlayer (room.state: ${roomState})`);
|
logger.mediaplayer(`[Player] _ensureMediaPlayer: attempting to create MediaPlayer (isConnected: ${roomAlive}, connectionState: ${cs})`);
|
||||||
|
|
||||||
if (this._mediaPlayer) {
|
if (this._mediaPlayer) {
|
||||||
const mpAlive = !this._mediaPlayer.destroyed && typeof this._mediaPlayer.playStream === "function";
|
const mpAlive = !this._mediaPlayer.destroyed && typeof this._mediaPlayer.playStream === "function";
|
||||||
@@ -752,7 +761,7 @@ export default class Player extends EventEmitter {
|
|||||||
|
|
||||||
// Room is dead — don't even attempt publishToRoom
|
// Room is dead — don't even attempt publishToRoom
|
||||||
if (!roomAlive) {
|
if (!roomAlive) {
|
||||||
logger.mediaplayer(`[Player] Room is in dead state (${roomState}), skipping MediaPlayer creation`);
|
logger.mediaplayer(`[Player] Room is in dead state (isConnected: ${room.isConnected}, connectionState: ${cs}), skipping MediaPlayer creation`);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -1115,12 +1124,12 @@ export default class Player extends EventEmitter {
|
|||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (this.connection && this._channelId === channelId) {
|
if (this.connection && this._channelId === channelId) {
|
||||||
const state = this.connection.room?.state;
|
const isConnected = this.connection.connected ?? false;
|
||||||
if (state === 1 || state === "connected") {
|
if (isConnected) {
|
||||||
logger.player(`[Player] Already in channel: ${channelId}`);
|
logger.player(`[Player] Already in channel: ${channelId}`);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
logger.mediaplayer(`[Player] Connection in bad state (${state}), reconnecting...`);
|
logger.mediaplayer(`[Player] Connection not connected, reconnecting...`);
|
||||||
try { this.connection.removeAllListeners(); } catch (_) {}
|
try { this.connection.removeAllListeners(); } catch (_) {}
|
||||||
try { await this.connection.disconnect(); } catch (_) {}
|
try { await this.connection.disconnect(); } catch (_) {}
|
||||||
this.connection = null;
|
this.connection = null;
|
||||||
@@ -1143,116 +1152,129 @@ export default class Player extends EventEmitter {
|
|||||||
this._mediaPlayer = null;
|
this._mediaPlayer = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
const connection = await joinVoiceChannel(this.client, channel);
|
// ── FluxerRevoice join ─────────────────────────────────────────────
|
||||||
|
// Use the FluxerRevoice instance to join the voice channel via the
|
||||||
|
// Fluxer gateway. FluxerRevoice sends a VOICE_STATE_UPDATE through
|
||||||
|
// the gateway, receives VOICE_SERVER_UPDATE with LiveKit credentials,
|
||||||
|
// then creates a FluxerVoiceConnection wrapping a LiveKit Room.
|
||||||
|
// The FluxerVoiceConnection is API-compatible with revoice.js's
|
||||||
|
// VoiceConnection (has .room, .disconnect(), .leave(), events).
|
||||||
|
if (!this._revoice) {
|
||||||
|
throw new Error("FluxerRevoice instance not available — cannot join voice channel");
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.mediaplayer(`[Player] Joining channel ${channelId} via FluxerRevoice (Fluxer API)...`);
|
||||||
|
|
||||||
|
const connection = await this._revoice.join(channelId, false);
|
||||||
this.connection = connection;
|
this.connection = connection;
|
||||||
this._channelId = channelId;
|
this._channelId = channelId;
|
||||||
this._guildId = channel.guildId;
|
this._guildId = channel.guildId;
|
||||||
this.leaving = false;
|
this.leaving = false;
|
||||||
|
|
||||||
const room = connection.room;
|
const room = connection.room;
|
||||||
if (room) {
|
if (!room) {
|
||||||
logger.mediaplayer(`[Player] Room obtained (state: ${room.state}), settling...`);
|
throw new Error("No room available after revoice.js join");
|
||||||
|
}
|
||||||
|
|
||||||
// ── connectionStateChanged is unreliable on this LiveKit build ───────
|
logger.mediaplayer(`[Player] FluxerVoiceConnection obtained (isConnected: ${room.isConnected}, connectionState: ${room.connectionState})`);
|
||||||
// The native lk-rtc layer connects and logs "connected to room", but
|
|
||||||
// the JS wrapper often NEVER fires "connectionStateChanged" with
|
|
||||||
// "connected" and room.state does not reflect the live state.
|
|
||||||
// Waiting for that event causes a guaranteed 15 s timeout.
|
|
||||||
//
|
|
||||||
// Strategy: listen for the event as a best-effort fast path (resolves
|
|
||||||
// instantly if it works), but also poll room.state every 500 ms.
|
|
||||||
// If NEITHER detects "connected" within a short window, check whether
|
|
||||||
// the room is in an obviously-dead state. If not, assume connected
|
|
||||||
// and let _ensureMediaPlayer (publishToRoom) be the real gate — it
|
|
||||||
// will throw if the room is genuinely unusable.
|
|
||||||
let connected = false;
|
|
||||||
let settled = false;
|
|
||||||
|
|
||||||
try {
|
// ── Wait for the room to be connected ──────────────────────────────
|
||||||
|
// FluxerRevoice already waits for the LiveKit room to be ready before
|
||||||
|
// resolving the join() promise, but we add a safety net for slow
|
||||||
|
// LiveKit servers.
|
||||||
|
// Uses the correct @livekit/rtc-node API:
|
||||||
|
// room.isConnected — boolean getter
|
||||||
|
// room.connectionState — ConnectionState enum
|
||||||
|
// RoomEvent.ConnectionStateChanged — fires with ConnectionState value
|
||||||
|
let connected = false;
|
||||||
|
let settled = false;
|
||||||
|
|
||||||
|
try {
|
||||||
|
// If already connected (FluxerRevoice.wait usually resolves this), skip
|
||||||
|
if (room.isConnected) {
|
||||||
|
connected = true;
|
||||||
|
settled = true;
|
||||||
|
logger.mediaplayer("[Player] Room already connected (immediate check via isConnected)");
|
||||||
|
} else {
|
||||||
await new Promise((resolve, reject) => {
|
await new Promise((resolve, reject) => {
|
||||||
const cleanup = () => {
|
const cleanup = () => {
|
||||||
clearTimeout(timeout);
|
clearTimeout(timeout);
|
||||||
clearInterval(poll);
|
clearInterval(poll);
|
||||||
try { room.off("connectionStateChanged", onStateChange); } catch (_) {}
|
try { room.off(LKRoomEvent.ConnectionStateChanged, onStateChange); } catch (_) {}
|
||||||
};
|
};
|
||||||
|
|
||||||
const timeout = setTimeout(() => {
|
const timeout = setTimeout(() => {
|
||||||
// Timeout — not necessarily a failure. The room may be connected
|
if (settled) return;
|
||||||
// at the native level with no JS event/state propagation.
|
|
||||||
logger.mediaplayer("[Player] connectionStateChanged not detected, checking state...");
|
|
||||||
cleanup();
|
cleanup();
|
||||||
const s = room.state;
|
// Use room.isConnected as the source of truth
|
||||||
if (s === "disconnected" || s === 0 || s === "failed") {
|
if (room.isConnected) {
|
||||||
reject(new Error(`LiveKit failed: ${s}`));
|
connected = true;
|
||||||
|
settled = true;
|
||||||
|
resolve();
|
||||||
|
} else if (!room.isConnected && (room.connectionState === ConnectionState.CONN_DISCONNECTED || room.connectionState === 0)) {
|
||||||
|
reject(new Error(`LiveKit disconnected (connectionState: ${room.connectionState})`));
|
||||||
} else {
|
} else {
|
||||||
// Indeterminate state (undefined, "connecting", etc.)
|
// Still connecting or indeterminate — optimistically proceed
|
||||||
// — optimistically proceed; MediaPlayer will validate.
|
|
||||||
connected = true;
|
connected = true;
|
||||||
settled = true;
|
settled = true;
|
||||||
resolve();
|
resolve();
|
||||||
}
|
}
|
||||||
}, 3_000); // 3 s instead of 15 s — avoid blocking recovery
|
}, 3_000);
|
||||||
|
|
||||||
const onStateChange = (state) => {
|
const onStateChange = (cs) => {
|
||||||
if (settled) return;
|
if (settled) return;
|
||||||
logger.mediaplayer(`[Player] LiveKit state changed: ${state}`);
|
logger.mediaplayer(`[Player] LiveKit connectionStateChanged: ${cs}`);
|
||||||
if (state === "connected" || state === 1) {
|
if (cs === ConnectionState.CONN_CONNECTED || cs === 1) {
|
||||||
connected = true;
|
connected = true;
|
||||||
|
settled = true;
|
||||||
cleanup();
|
cleanup();
|
||||||
resolve();
|
resolve();
|
||||||
} else if (state === "disconnected" || state === 0 || state === "failed") {
|
} else if (cs === ConnectionState.CONN_DISCONNECTED || cs === 0) {
|
||||||
cleanup();
|
cleanup();
|
||||||
reject(new Error(`LiveKit failed: ${state}`));
|
reject(new Error(`LiveKit disconnected (connectionState: ${cs})`));
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
room.on("connectionStateChanged", onStateChange);
|
room.on(LKRoomEvent.ConnectionStateChanged, onStateChange);
|
||||||
|
|
||||||
// Poll room.state every 500 ms as a fallback for builds where
|
|
||||||
// the event never fires but the getter eventually updates.
|
|
||||||
const poll = setInterval(() => {
|
const poll = setInterval(() => {
|
||||||
if (settled) return;
|
if (settled) return;
|
||||||
const s = room.state;
|
if (room.isConnected) {
|
||||||
if (s === "connected" || s === 1) {
|
|
||||||
connected = true;
|
connected = true;
|
||||||
|
settled = true;
|
||||||
cleanup();
|
cleanup();
|
||||||
resolve();
|
resolve();
|
||||||
} else if (s === "disconnected" || s === 0 || s === "failed") {
|
} else if (room.connectionState === ConnectionState.CONN_DISCONNECTED || room.connectionState === 0) {
|
||||||
cleanup();
|
cleanup();
|
||||||
reject(new Error(`LiveKit failed: ${s}`));
|
reject(new Error(`LiveKit disconnected (connectionState: ${room.connectionState})`));
|
||||||
}
|
}
|
||||||
}, 500);
|
}, 500);
|
||||||
|
|
||||||
// Immediate check after listener is registered.
|
// Immediate check using correct API
|
||||||
const currentState = room.state;
|
if (room.isConnected) {
|
||||||
if (currentState === "connected" || currentState === 1) {
|
|
||||||
connected = true;
|
connected = true;
|
||||||
|
settled = true;
|
||||||
cleanup();
|
cleanup();
|
||||||
logger.mediaplayer("[Player] Room already connected (immediate check)");
|
logger.mediaplayer("[Player] Room already connected (immediate check)");
|
||||||
resolve();
|
resolve();
|
||||||
} else if (currentState === "disconnected" || currentState === 0 || currentState === "failed") {
|
} else if (room.connectionState === ConnectionState.CONN_DISCONNECTED || room.connectionState === 0) {
|
||||||
cleanup();
|
cleanup();
|
||||||
reject(new Error(`LiveKit failed: ${currentState}`));
|
reject(new Error(`LiveKit disconnected (connectionState: ${room.connectionState})`));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
} catch (err) {
|
|
||||||
logger.error("[Player] LiveKit connection failed:", err.message);
|
|
||||||
throw err;
|
|
||||||
}
|
}
|
||||||
|
} catch (err) {
|
||||||
if (connected) {
|
logger.error("[Player] LiveKit connection failed:", err.message);
|
||||||
logger.mediaplayer("[Player] Room ready, proceeding to MediaPlayer");
|
throw err;
|
||||||
} else {
|
|
||||||
throw new Error("LiveKit room did not reach connected state");
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
// connection.room is null — this happens when joinVoiceChannel returns
|
|
||||||
// a stale/recycled connection object before the LiveKit room is assigned,
|
|
||||||
// usually due to a concurrent join race or a channel that no longer has
|
|
||||||
// an active room. Treat it as transient so the retry loop handles it.
|
|
||||||
throw new Error("No room available after joinVoiceChannel");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (connected) {
|
||||||
|
logger.mediaplayer("[Player] Room ready via FluxerRevoice, proceeding to MediaPlayer");
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── VoiceConnection event handlers ──────────────────────────────────
|
||||||
|
// FluxerVoiceConnection emits "disconnect" on unexpected
|
||||||
|
// disconnection and "autoleave" when the room empties.
|
||||||
connection.on("error", (err) => {
|
connection.on("error", (err) => {
|
||||||
if (this.connection !== connection) {
|
if (this.connection !== connection) {
|
||||||
try { connection.removeAllListeners(); } catch (_) {}
|
try { connection.removeAllListeners(); } catch (_) {}
|
||||||
@@ -1267,13 +1289,9 @@ export default class Player extends EventEmitter {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
// @fluxerjs VoiceConnection / LiveKitRtcConnection emits "disconnect",
|
|
||||||
// NOT "disconnected" (Discord.js naming). Using the wrong event name meant
|
|
||||||
// this handler was silently never registered — voice disconnect recovery
|
|
||||||
// was completely broken.
|
|
||||||
connection.on("disconnect", () => {
|
connection.on("disconnect", () => {
|
||||||
if (this.connection !== connection) {
|
if (this.connection !== connection) {
|
||||||
try { connection.removeAllListeners(); connection.destroy(); } catch (_) {}
|
try { connection.removeAllListeners(); } catch (_) {}
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (!this.leaving && !this._destroyed) {
|
if (!this.leaving && !this._destroyed) {
|
||||||
@@ -1282,10 +1300,19 @@ export default class Player extends EventEmitter {
|
|||||||
.catch(() => {})
|
.catch(() => {})
|
||||||
.finally(() => this._recoverConnection());
|
.finally(() => this._recoverConnection());
|
||||||
} else {
|
} else {
|
||||||
try { connection.removeAllListeners(); connection.destroy(); } catch (_) {}
|
try { connection.removeAllListeners(); } catch (_) {}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
connection.on("autoleave", () => {
|
||||||
|
if (this.connection !== connection) return;
|
||||||
|
logger.mediaplayer("[Player] Auto-leave triggered by FluxerVoiceConnection (room empty)");
|
||||||
|
if (!this.leaving && !this._destroyed) {
|
||||||
|
this.emit("autoleave");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// Send self-deaf voice state update via @fluxerjs/voice if available
|
||||||
try {
|
try {
|
||||||
const vm = getVoiceManager(this.client);
|
const vm = getVoiceManager(this.client);
|
||||||
vm.updateVoiceState(channelId, { self_deaf: true, self_mute: false });
|
vm.updateVoiceState(channelId, { self_deaf: true, self_mute: false });
|
||||||
@@ -1296,17 +1323,10 @@ export default class Player extends EventEmitter {
|
|||||||
const playerReady = await this._ensureMediaPlayer();
|
const playerReady = await this._ensureMediaPlayer();
|
||||||
if (!playerReady) {
|
if (!playerReady) {
|
||||||
logger.mediaplayer("[Player] First MediaPlayer attempt failed, retrying after delay...");
|
logger.mediaplayer("[Player] First MediaPlayer attempt failed, retrying after delay...");
|
||||||
// 1s wasn't enough — LiveKit can take 2-3s to fully tear down after
|
|
||||||
// a room_disconnected event fires. If we retry too soon we hit the
|
|
||||||
// same "engine is closed" error. 3s gives the engine time to settle.
|
|
||||||
await Utils.sleep(3000);
|
await Utils.sleep(3000);
|
||||||
if (this._destroyed || this.leaving) throw new Error("Player destroyed during MediaPlayer retry");
|
if (this._destroyed || this.leaving) throw new Error("Player destroyed during MediaPlayer retry");
|
||||||
// If the room disconnected while we were waiting, fail fast so the
|
const roomAlive = this.connection?.room?.isConnected ?? false;
|
||||||
// caller's retry logic (spawnPlayer) can respawn with a fresh connection.
|
if (!roomAlive) {
|
||||||
const roomAlive = this.connection?.room?.state !== "disconnected" &&
|
|
||||||
this.connection?.room?.state !== "failed" &&
|
|
||||||
this.connection?.room?.state !== 0;
|
|
||||||
if (!roomAlive && this.connection?.room?.state !== undefined) {
|
|
||||||
throw new Error("Room disconnected during MediaPlayer retry");
|
throw new Error("Room disconnected during MediaPlayer retry");
|
||||||
}
|
}
|
||||||
const retryReady = await this._ensureMediaPlayer();
|
const retryReady = await this._ensureMediaPlayer();
|
||||||
@@ -1315,21 +1335,13 @@ export default class Player extends EventEmitter {
|
|||||||
|
|
||||||
this._restoreVolume();
|
this._restoreVolume();
|
||||||
this.emit("roomfetched");
|
this.emit("roomfetched");
|
||||||
logger.player(`[Player] Voice connected to ${channel.name}`);
|
logger.player(`[Player] Voice connected to ${channel.name || channelId} via FluxerRevoice`);
|
||||||
|
|
||||||
if (!this.queue.isEmpty() && !this.queue.getCurrent()) {
|
if (!this.queue.isEmpty() && !this.queue.getCurrent()) {
|
||||||
this.playNext();
|
this.playNext();
|
||||||
} else if (this.queue.isEmpty()) {
|
} else if (this.queue.isEmpty()) {
|
||||||
// Delay the inactivity timer start to give the caller (e.g. RecoveryManager.spawnPlayer)
|
|
||||||
// time to re-seed voice states and check for humans already in the channel.
|
|
||||||
// The reseed will call _stopInactivityTimer() if humans are found, which
|
|
||||||
// sets this._inactivityTimer = null. When this callback fires, it checks
|
|
||||||
// whether the timer was cancelled (by checking if _inactivityTimer is null)
|
|
||||||
// before starting a new one.
|
|
||||||
this._pendingInactivityCheck = true;
|
this._pendingInactivityCheck = true;
|
||||||
setTimeout(() => {
|
setTimeout(() => {
|
||||||
// If the inactivity timer was stopped between scheduling and now (e.g.
|
|
||||||
// by reseedVoiceStatesForChannel finding humans), don't restart it.
|
|
||||||
if (!this._pendingInactivityCheck) return;
|
if (!this._pendingInactivityCheck) return;
|
||||||
this._pendingInactivityCheck = false;
|
this._pendingInactivityCheck = false;
|
||||||
if (this.queue.isEmpty() && !this.queue.getCurrent()) {
|
if (this.queue.isEmpty() && !this.queue.getCurrent()) {
|
||||||
@@ -1343,7 +1355,7 @@ export default class Player extends EventEmitter {
|
|||||||
logger.error("[Player] Join failed:", e.message, causeStr);
|
logger.error("[Player] Join failed:", e.message, causeStr);
|
||||||
|
|
||||||
if (this.connection) {
|
if (this.connection) {
|
||||||
try { this.connection.destroy(); } catch (_) {}
|
try { this.connection.disconnect(); } catch (_) {}
|
||||||
this.connection = null;
|
this.connection = null;
|
||||||
}
|
}
|
||||||
throw e;
|
throw e;
|
||||||
@@ -1369,7 +1381,20 @@ export default class Player extends EventEmitter {
|
|||||||
this._mediaPlayer.destroy();
|
this._mediaPlayer.destroy();
|
||||||
this._mediaPlayer = null;
|
this._mediaPlayer = null;
|
||||||
}
|
}
|
||||||
await this.connection.disconnect();
|
|
||||||
|
// Clean up from FluxerRevoice connections map before disconnecting
|
||||||
|
const channelId = this._channelId;
|
||||||
|
if (this._revoice && channelId) {
|
||||||
|
try {
|
||||||
|
if (typeof this._revoice.deleteConnection === "function") {
|
||||||
|
this._revoice.deleteConnection(channelId);
|
||||||
|
} else if (this._revoice.connections) {
|
||||||
|
this._revoice.connections.delete(channelId);
|
||||||
|
}
|
||||||
|
} catch (_) {}
|
||||||
|
}
|
||||||
|
|
||||||
|
await this.connection.leave();
|
||||||
|
|
||||||
this.queue.reset();
|
this.queue.reset();
|
||||||
this.connection = null;
|
this.connection = null;
|
||||||
@@ -2149,8 +2174,9 @@ export default class Player extends EventEmitter {
|
|||||||
if (!this.connection || this.leaving) return;
|
if (!this.connection || this.leaving) return;
|
||||||
|
|
||||||
const room = this.connection.room;
|
const room = this.connection.room;
|
||||||
if (!room || room.state === "disconnected" || room.state === "failed" || room.state === 0) {
|
if (!room || !room.isConnected) {
|
||||||
logger.mediaplayer("[Player] Room disconnected/failed, recovering connection before playing.");
|
const cs = room?.connectionState;
|
||||||
|
logger.mediaplayer(`[Player] Room not connected (isConnected: ${room?.isConnected}, connectionState: ${cs}), recovering connection before playing.`);
|
||||||
if (songData) {
|
if (songData) {
|
||||||
this.queue.data.unshift(songData);
|
this.queue.data.unshift(songData);
|
||||||
this.queue.current = null;
|
this.queue.current = null;
|
||||||
|
|||||||
@@ -121,7 +121,7 @@ export class PlayerManager {
|
|||||||
/**
|
/**
|
||||||
* Forward player lifecycle/state events to the dashboard pub/sub channels.
|
* Forward player lifecycle/state events to the dashboard pub/sub channels.
|
||||||
*
|
*
|
||||||
* IMPORTANT: Events are sent in Stoat-compatible { type, data } format so
|
* IMPORTANT: Events are sent in standard { type, data } format so
|
||||||
* the backend (backend-master) PlayerManager can parse them correctly.
|
* the backend (backend-master) PlayerManager can parse them correctly.
|
||||||
*
|
*
|
||||||
* Two channels are used:
|
* Two channels are used:
|
||||||
@@ -144,7 +144,7 @@ export class PlayerManager {
|
|||||||
writable: true,
|
writable: true,
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── Per-player channel: Stoat-compatible { type, data } format ────────
|
// ── Per-player channel: standard { type, data } format ────────
|
||||||
// The backend PlayerManager.setupEvents() expects:
|
// The backend PlayerManager.setupEvents() expects:
|
||||||
// { type: "startplay", data: serialisedVideo }
|
// { type: "startplay", data: serialisedVideo }
|
||||||
// { type: "stopplay", data: null }
|
// { type: "stopplay", data: null }
|
||||||
@@ -192,7 +192,7 @@ export class PlayerManager {
|
|||||||
const member = guild.members?.get?.(state.userId ?? state.user_id);
|
const member = guild.members?.get?.(state.userId ?? state.user_id);
|
||||||
if (!member?.user || member.user?.bot) continue;
|
if (!member?.user || member.user?.bot) continue;
|
||||||
// Send per-player channel "join"/"leave" event with just the user ID
|
// Send per-player channel "join"/"leave" event with just the user ID
|
||||||
// (matching Stoat format where data = userId string)
|
// (matching standard format where data = userId string)
|
||||||
emit(eventType, member.user.id);
|
emit(eventType, member.user.id);
|
||||||
// Also send global user update
|
// Also send global user update
|
||||||
this.dashboard.userUpdate({
|
this.dashboard.userUpdate({
|
||||||
@@ -215,7 +215,7 @@ export class PlayerManager {
|
|||||||
// Send the serialised video to the per-player channel
|
// Send the serialised video to the per-player channel
|
||||||
emit("startplay", Dashboard.convertVideo(song ?? player.queue?.current));
|
emit("startplay", Dashboard.convertVideo(song ?? player.queue?.current));
|
||||||
// Emit streamStartPlay with current timestamp so the backend can
|
// Emit streamStartPlay with current timestamp so the backend can
|
||||||
// calculate elapsed time accurately (matches Stoat behaviour)
|
// calculate elapsed time accurately (standard behaviour)
|
||||||
emit("streamStartPlay", Date.now());
|
emit("streamStartPlay", Date.now());
|
||||||
// Also broadcast on global channel for full state update
|
// Also broadcast on global channel for full state update
|
||||||
this.dashboard.playerUpdate({ type: "startplay" }, player);
|
this.dashboard.playerUpdate({ type: "startplay" }, player);
|
||||||
@@ -232,7 +232,7 @@ export class PlayerManager {
|
|||||||
});
|
});
|
||||||
|
|
||||||
player.on("playback", (playing) => {
|
player.on("playback", (playing) => {
|
||||||
// Stoat sends "pause" or "resume" with { elapsedTime } — match that
|
// Sends "pause" or "resume" with { elapsedTime } — match that format
|
||||||
const elapsedMs = player._pausedAt
|
const elapsedMs = player._pausedAt
|
||||||
? (player._pausedAt.getTime?.() ?? Number(player._pausedAt)) -
|
? (player._pausedAt.getTime?.() ?? Number(player._pausedAt)) -
|
||||||
(player.startedPlaying?.getTime?.() ?? Number(player.startedPlaying ?? 0))
|
(player.startedPlaying?.getTime?.() ?? Number(player.startedPlaying ?? 0))
|
||||||
@@ -248,7 +248,7 @@ export class PlayerManager {
|
|||||||
});
|
});
|
||||||
|
|
||||||
player.on("filter", (filter) => {
|
player.on("filter", (filter) => {
|
||||||
// Filter events are Fluxer-specific — no Stoat equivalent.
|
// Filter events are Fluxer-specific.
|
||||||
// Send as a custom event type; the backend will ignore unknown types.
|
// Send as a custom event type; the backend will ignore unknown types.
|
||||||
emit("filter", filter);
|
emit("filter", filter);
|
||||||
});
|
});
|
||||||
@@ -259,7 +259,7 @@ export class PlayerManager {
|
|||||||
});
|
});
|
||||||
|
|
||||||
player.on("message", (message) => {
|
player.on("message", (message) => {
|
||||||
// No Stoat equivalent — skip per-player, only global broadcast
|
// No per-player equivalent — skip, only global broadcast
|
||||||
});
|
});
|
||||||
|
|
||||||
player.on("autoleave", () => {
|
player.on("autoleave", () => {
|
||||||
@@ -708,6 +708,7 @@ export class PlayerManager {
|
|||||||
config: this.config,
|
config: this.config,
|
||||||
nodelink: this.config.nodelink,
|
nodelink: this.config.nodelink,
|
||||||
moonlink: this.playerConfig?.moonlink ?? null,
|
moonlink: this.playerConfig?.moonlink ?? null,
|
||||||
|
revoice: this.playerConfig?.revoice ?? null,
|
||||||
settingsMgr: this.settings,
|
settingsMgr: this.settings,
|
||||||
observedVoiceUsers: this.observedVoiceUsers ?? null,
|
observedVoiceUsers: this.observedVoiceUsers ?? null,
|
||||||
locale: this.locale ?? null,
|
locale: this.locale ?? null,
|
||||||
|
|||||||
@@ -350,6 +350,7 @@ export class RecoveryManager {
|
|||||||
config: remix.config,
|
config: remix.config,
|
||||||
nodelink: remix.config.nodelink,
|
nodelink: remix.config.nodelink,
|
||||||
moonlink: remix.moonlink,
|
moonlink: remix.moonlink,
|
||||||
|
revoice: remix.revoice,
|
||||||
settingsMgr: remix.settingsMgr,
|
settingsMgr: remix.settingsMgr,
|
||||||
observedVoiceUsers: remix.observedVoiceUsers,
|
observedVoiceUsers: remix.observedVoiceUsers,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,365 @@
|
|||||||
|
/**
|
||||||
|
* FluxerRevoice.mjs — Revoice-compatible adapter that uses the Fluxer API
|
||||||
|
*
|
||||||
|
* This module provides the same interface as revoice.js's `Revoice` class
|
||||||
|
* but uses the Fluxer gateway (via @fluxerjs/voice) to obtain LiveKit
|
||||||
|
* credentials instead of POSTing to a third-party REST API.
|
||||||
|
*
|
||||||
|
* Why this exists:
|
||||||
|
* revoice.js internally calls `POST /channels/{id}/join_call` on
|
||||||
|
* a third-party API with an `X-Bot-Token` header. A Fluxer
|
||||||
|
* bot token is NOT valid on that API, resulting in a 401.
|
||||||
|
* Fluxer's voice join flow instead uses the gateway WebSocket:
|
||||||
|
* 1. Bot sends VOICE_STATE_UPDATE opcode
|
||||||
|
* 2. Gateway responds with VOICE_STATE_UPDATE (ack)
|
||||||
|
* 3. Gateway sends VOICE_SERVER_UPDATE with { endpoint, token }
|
||||||
|
* 4. The endpoint/token are LiveKit credentials
|
||||||
|
*
|
||||||
|
* This adapter wraps @fluxerjs/voice's `joinVoiceChannel()` and returns
|
||||||
|
* a `FluxerVoiceConnection` that is API-compatible with revoice.js's
|
||||||
|
* `VoiceConnection`, so Player.mjs and MediaPlayer work unchanged.
|
||||||
|
*
|
||||||
|
* IMPORTANT: @livekit/rtc-node (Node.js SDK) does NOT have `room.state`.
|
||||||
|
* ✅ room.isConnected — boolean getter (true when connected)
|
||||||
|
* ✅ room.connectionState — ConnectionState enum getter
|
||||||
|
* (CONN_DISCONNECTED = 0, CONN_CONNECTED = 1, CONN_RECONNECTING = 2)
|
||||||
|
* ❌ room.state — does NOT exist (that's the browser SDK API)
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { EventEmitter } from "node:events";
|
||||||
|
import { Room, RoomEvent, ConnectionState } from "@livekit/rtc-node";
|
||||||
|
import { joinVoiceChannel, getVoiceManager } from "@fluxerjs/voice";
|
||||||
|
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
|
||||||
|
* gateway. Exposes the same interface as revoice.js's VoiceConnection:
|
||||||
|
*
|
||||||
|
* .room — LiveKit Room
|
||||||
|
* .channelId — the voice channel ID
|
||||||
|
* .connected — boolean (getter, reads from room.isConnected)
|
||||||
|
* .users — array (minimal; real tracking is via observedVoiceUsers)
|
||||||
|
* .disconnect() — tear down the LiveKit connection
|
||||||
|
* .leave() — alias for disconnect()
|
||||||
|
* Events: "disconnect", "error", "autoleave"
|
||||||
|
*/
|
||||||
|
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 = [];
|
||||||
|
_destroyed = false;
|
||||||
|
|
||||||
|
// @fluxerjs/voice native connection reference (for proper disconnect)
|
||||||
|
_nativeConn = null;
|
||||||
|
|
||||||
|
constructor(channelId, voice, opts = {}) {
|
||||||
|
super();
|
||||||
|
this.channelId = channelId;
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether this connection is currently alive.
|
||||||
|
* Reads from the LiveKit Room's `isConnected` boolean getter,
|
||||||
|
* which is the correct API in @livekit/rtc-node (Node.js SDK).
|
||||||
|
*/
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
set connected(val) {
|
||||||
|
this._connected = !!val;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Disconnect from the voice channel.
|
||||||
|
* Tries the @fluxerjs/voice native disconnect first, then falls back
|
||||||
|
* to closing the LiveKit Room directly.
|
||||||
|
*/
|
||||||
|
async disconnect() {
|
||||||
|
if (this._destroyed) return;
|
||||||
|
this._destroyed = true;
|
||||||
|
this._connected = false;
|
||||||
|
|
||||||
|
// Method 1: Use @fluxerjs/voice native connection disconnect
|
||||||
|
if (this._nativeConn && typeof this._nativeConn.disconnect === "function") {
|
||||||
|
try {
|
||||||
|
await this._nativeConn.disconnect();
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[FluxerVoiceConnection] Native disconnect error:", e?.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Method 2: Close LiveKit Room directly as fallback
|
||||||
|
if (this.room) {
|
||||||
|
try {
|
||||||
|
await this.room.disconnect();
|
||||||
|
} catch (e) {
|
||||||
|
// Room may already be closed
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.emit("disconnect");
|
||||||
|
this.removeAllListeners();
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Leave — alias for disconnect (matches revoice.js VoiceConnection API).
|
||||||
|
*/
|
||||||
|
async leave() {
|
||||||
|
return this.disconnect();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
// 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();
|
||||||
|
users = new Map();
|
||||||
|
|
||||||
|
constructor(client) {
|
||||||
|
super();
|
||||||
|
if (!client) throw new Error("FluxerRevoice requires a Fluxer client instance");
|
||||||
|
this.client = client;
|
||||||
|
logger.player("[FluxerRevoice] Instance created with Fluxer client.");
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Join a voice channel using the Fluxer gateway.
|
||||||
|
*
|
||||||
|
* This sends a VOICE_STATE_UPDATE through the Fluxer gateway, receives
|
||||||
|
* VOICE_SERVER_UPDATE with LiveKit credentials, then connects to the
|
||||||
|
* LiveKit room — the same flow @fluxerjs/voice uses internally.
|
||||||
|
*
|
||||||
|
* @param {string} channelId — The voice channel ID to join
|
||||||
|
* @param {boolean} [_leaveIfEmpty=false] — Not used (compatibility param)
|
||||||
|
* @returns {Promise<FluxerVoiceConnection>}
|
||||||
|
*/
|
||||||
|
async join(channelId, _leaveIfEmpty = false) {
|
||||||
|
if (this.connections.has(channelId)) {
|
||||||
|
logger.player(`[FluxerRevoice] Already connected to ${channelId}, returning existing connection`);
|
||||||
|
return this.connections.get(channelId);
|
||||||
|
}
|
||||||
|
|
||||||
|
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 {
|
||||||
|
channel = await this.client.channels.fetch(channelId);
|
||||||
|
} catch (e) {
|
||||||
|
throw new Error(`Could not fetch channel ${channelId}: ${e.message}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!channel) {
|
||||||
|
throw new Error(`Channel not found: ${channelId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// 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.
|
||||||
|
let nativeConnection;
|
||||||
|
try {
|
||||||
|
nativeConnection = await joinVoiceChannel(this.client, channel);
|
||||||
|
} catch (e) {
|
||||||
|
throw new Error(`Fluxer voice join failed for ${channelId}: ${e.message}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!nativeConnection) {
|
||||||
|
throw new Error(`Fluxer voice join returned null for ${channelId}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
logger.player(`[FluxerRevoice] Gateway join successful, extracting LiveKit room...`);
|
||||||
|
|
||||||
|
// 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)})`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// If we couldn't get a room, the connection might be Discord-style
|
||||||
|
// (non-LiveKit) which we don't support for music playback.
|
||||||
|
if (!room) {
|
||||||
|
try { await nativeConnection.disconnect(); } catch (_) {}
|
||||||
|
throw new Error(
|
||||||
|
`Fluxer voice connection for ${channelId} does not expose a LiveKit Room. ` +
|
||||||
|
`Music playback requires a LiveKit-based voice server.`
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── 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) => {
|
||||||
|
if (eventResolved) return;
|
||||||
|
if (cs === ConnectionState?.CONN_CONNECTED || cs === 1) {
|
||||||
|
eventResolved = true;
|
||||||
|
room.off(RoomEvent.ConnectionStateChanged, handler);
|
||||||
|
resolve();
|
||||||
|
} else if (cs === ConnectionState?.CONN_DISCONNECTED || cs === 0) {
|
||||||
|
eventResolved = true;
|
||||||
|
room.off(RoomEvent.ConnectionStateChanged, handler);
|
||||||
|
resolve(); // resolve so we can check isConnected below
|
||||||
|
}
|
||||||
|
};
|
||||||
|
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;
|
||||||
|
|
||||||
|
if (!finalConnected && (finalCS === ConnectionState?.CONN_DISCONNECTED || finalCS === 0)) {
|
||||||
|
try { await nativeConnection.disconnect(); } catch (_) {}
|
||||||
|
throw new Error(`LiveKit room in disconnected state: ${stateLabel(finalCS)}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
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) => {
|
||||||
|
logger.player(`[FluxerRevoice] Room disconnected: ${reason ?? "unknown"}`);
|
||||||
|
connection._connected = false;
|
||||||
|
connection.emit("disconnect");
|
||||||
|
});
|
||||||
|
|
||||||
|
room.on(RoomEvent.Reconnecting, () => {
|
||||||
|
logger.player("[FluxerRevoice] Room reconnecting...");
|
||||||
|
});
|
||||||
|
|
||||||
|
room.on(RoomEvent.Reconnected, () => {
|
||||||
|
logger.player("[FluxerRevoice] Room reconnected");
|
||||||
|
connection._connected = true;
|
||||||
|
});
|
||||||
|
|
||||||
|
room.on(RoomEvent.ParticipantConnected, (participant) => {
|
||||||
|
const userId = participant?.identity ?? participant?.sid;
|
||||||
|
if (userId) {
|
||||||
|
connection.users.push({ id: userId, connectedTo: channelId });
|
||||||
|
this.users.set(userId, { id: userId, connectedTo: channelId });
|
||||||
|
connection.emit("userjoin", userId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
room.on(RoomEvent.ParticipantDisconnected, (participant) => {
|
||||||
|
const userId = participant?.identity ?? participant?.sid;
|
||||||
|
if (userId) {
|
||||||
|
connection.users = connection.users.filter(u => u.id !== userId);
|
||||||
|
this.users.delete(userId);
|
||||||
|
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}`);
|
||||||
|
connection.emit("autoleave");
|
||||||
|
this.connections.delete(channelId);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return connection;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Delete a connection from the map (called during player leave/cleanup).
|
||||||
|
* @param {string} channelId
|
||||||
|
*/
|
||||||
|
deleteConnection(channelId) {
|
||||||
|
this.connections.delete(channelId);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -679,7 +679,7 @@ export class Dashboard {
|
|||||||
// ═══════════════════════════════════════════════════════════════════════════
|
// ═══════════════════════════════════════════════════════════════════════════
|
||||||
// Pub/Sub broadcast helpers
|
// Pub/Sub broadcast helpers
|
||||||
//
|
//
|
||||||
// CRITICAL: The backend (backend-master) expects Stoat-compatible message
|
// CRITICAL: The backend (backend-master) expects standard message
|
||||||
// formats on both the global :players channel and the per-player
|
// formats on both the global :players channel and the per-player
|
||||||
// :player_{channelId} channel. The formats are:
|
// :player_{channelId} channel. The formats are:
|
||||||
//
|
//
|
||||||
@@ -761,7 +761,7 @@ export class Dashboard {
|
|||||||
* The backend PlayerManager.setupEvents() expects messages in the format:
|
* The backend PlayerManager.setupEvents() expects messages in the format:
|
||||||
* { type: "<eventType>", data: <payload> }
|
* { type: "<eventType>", data: <payload> }
|
||||||
*
|
*
|
||||||
* This method accepts details in that Stoat-compatible format directly.
|
* This method accepts details in that standard format directly.
|
||||||
*
|
*
|
||||||
* @param {Object} details Must include `type` and optionally `data`.
|
* @param {Object} details Must include `type` and optionally `data`.
|
||||||
* Examples:
|
* Examples:
|
||||||
|
|||||||
@@ -3,7 +3,7 @@ import { createPool } from "mysql2/promise";
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* DatabaseManager — MySQL pool for dashboard login codes and API tokens.
|
* DatabaseManager — MySQL pool for dashboard login codes and API tokens.
|
||||||
* Adapted from the Stoat version for use with the Fluxer bot.
|
* Adapted for use with the Fluxer bot.
|
||||||
*/
|
*/
|
||||||
export class DatabaseManager {
|
export class DatabaseManager {
|
||||||
/**
|
/**
|
||||||
|
|||||||
Reference in new issue
Block a user