lots of changes

This commit is contained in:
NoLogicAlan committed 2026-05-16 20:30:56 +03:00
1 parent ba225c914a
commit 6fa8f3b540
20 files changed
+296 -144

No files matched your search

+19 -1
View File
@@ -768,7 +768,25 @@ export class GatewayHandler {
}
}
if (nextKey && this._prevVoiceState.size >= 10_000 && !this._prevVoiceState.has(nextKey)) {
this._prevVoiceState.delete(this._prevVoiceState.keys().next().value);
const evictKey = this._prevVoiceState.keys().next().value;
const evictEntry = this._prevVoiceState.get(evictKey);
this._prevVoiceState.delete(evictKey);
// When evicting a stale prevVoiceState entry, also clean up the
// corresponding VoiceStateCache entry so it doesn't hold a stale
// channel mapping that could cause incorrect "channel move" detection
// on the next voice state update for that user.
if (evictEntry) {
const evictGuildId = evictEntry.guildId;
const evictUserId = evictKey.split(":")[1];
if (evictGuildId && evictUserId) {
const currentLoc = remix.voiceCache.getUserLocation(evictGuildId, evictUserId);
// Only remove from voiceCache if the user is still in the evicted
// channel — if they've moved since, the cache is already correct.
if (currentLoc && currentLoc.channelId === evictEntry.channelId) {
remix.voiceCache.updateUser({ guildId: evictGuildId, userId: evictUserId, channelId: null, isBot: false });
}
}
}
}
if (nextKey) this._prevVoiceState.set(nextKey, { channelId, guildId: guildId ?? prev?.guildId });
} else {
+4 -1
View File
@@ -709,7 +709,10 @@ export default class Player extends EventEmitter {
for (let attempt = 1; attempt <= MAX_PUBLISH_RETRIES; attempt++) {
try {
this._mediaPlayer = new MediaPlayer();
this._mediaPlayer.setMaxListeners(0);
// Set a reasonable max listeners cap instead of 0 (unlimited).
// Unlimited masks real event emitter leaks; 20 is enough for
// the finish/error/playStream listeners plus dashboard forwarding.
this._mediaPlayer.setMaxListeners(20);
await this._mediaPlayer.publishToRoom(room);
logger.mediaplayer("[Player] MediaPlayer published successfully");
return true;
+9 -2
View File
@@ -810,9 +810,16 @@ export class PlayerManager {
const pendingScrobble = this._pendingScrobbleTimers.get(activeChannelId);
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this._pendingScrobbleTimers.delete(activeChannelId); }
if (activeChannelId !== cleanChannelId) this.playerMap.delete(cleanChannelId);
await msg.reply(mkEmbed(this._t(msg, "responses._common.successfullyLeft")));
await player.leave();
// Leave the voice channel BEFORE confirming to the user.
// Previously, the reply was sent first, which meant the user saw "successfully left"
// even if player.leave() subsequently threw an error.
try {
await player.leave();
} catch (e) {
logger.warn("[PlayerManager] leave() error (non-fatal):", e.message);
}
player.destroy();
await msg.reply(mkEmbed(this._t(msg, "responses._common.successfullyLeft")));
}
// ═══════════════════════════════════════════════════════════════════════════
+22 -12
View File
@@ -55,7 +55,7 @@ export class RemoteSettingsManager extends EventEmitter {
logger.error("[DB] MySQL pool error:", err.code ?? err.message);
});
if (defaultsPath) this.loadDefaultsSync(defaultsPath);
this.load();
this.load().catch(err => logger.error("[Settings] Initial load failed:", err?.message ?? err));
}
query(q) {
@@ -75,13 +75,17 @@ export class RemoteSettingsManager extends EventEmitter {
}
this._loadAttempts = 0;
res.results.forEach((r) => {
const server = new ServerSettings(r.id, this);
// mysql2 may return JSON columns as already-parsed objects;
// only JSON.parse when the value is still a string.
const parsed = (typeof r.data === "string") ? JSON.parse(r.data) : r.data;
server.deserialize(parsed);
server.checkDefaults(this.defaults);
this.guilds.set(server.id, server);
try {
const server = new ServerSettings(r.id, this);
// mysql2 may return JSON columns as already-parsed objects;
// only JSON.parse when the value is still a string.
const parsed = (typeof r.data === "string") ? JSON.parse(r.data) : r.data;
server.deserialize(parsed);
server.checkDefaults(this.defaults);
this.guilds.set(server.id, server);
} catch (e) {
logger.error("[Settings] Failed to parse settings for server", r.id, ":", e.message);
}
});
this.emit("ready");
}
@@ -113,10 +117,16 @@ export class RemoteSettingsManager extends EventEmitter {
}
loadDefaultsSync(filePath) {
const d = fs.readFileSync(filePath, "utf8");
const parsed = JSON.parse(d);
this.descriptions = parsed.descriptions;
this.defaults = parsed.values;
try {
const d = fs.readFileSync(filePath, "utf8");
const parsed = JSON.parse(d);
this.descriptions = parsed.descriptions;
this.defaults = parsed.values;
} catch (e) {
logger.error("[Settings] Failed to load defaults from", filePath, ":", e.message);
this.descriptions = {};
this.defaults = {};
}
}
async saveAsync() {
+3 -3
View File
@@ -210,8 +210,8 @@ export class Utils {
* @returns {string} Human readable size
*/
static formatBytes(bytes, decimals = 2) {
if (!bytes || bytes === 0) return "0 Bytes";
if (bytes < 0) return "Unknown";
if (bytes === 0) return "0 Bytes";
if (!bytes || bytes < 0 || !isFinite(bytes)) return "Unknown";
const k = 1024;
const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB"];
@@ -453,7 +453,7 @@ export class Utils {
progress = this.clamp(current, 0, 1);
}
const position = Math.floor(progress * length);
const position = Math.min(Math.floor(progress * length), length - 1);
let bar = "";
for (let i = 0; i < length; i++) {
+58 -47
View File
@@ -32,56 +32,67 @@ import { joinVoiceChannel, getVoiceManager } from "@fluxerjs/voice";
import { logger } from "./Logger.mjs";
{
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
}
_originalConsoleLog.apply(console, args);
};
// ── 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;
// ── 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;
}
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
}
} catch (_) {
// Not valid JSON — pass through
}
}
return _originalStdoutWrite(chunk, encoding, callback);
};
// 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
}
_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);
};
}
}
// ConnectionState enum values for reference:
+24 -7
View File
@@ -105,15 +105,29 @@ export class VoiceStateCache {
// ── Update location map ────────────────────────────────────────────
locations.set(uKey, { channelId: cleanChannel, guildId: cleanGuild, userId: cleanUser });
// ── LRU: move to front ─────────────────────────────────────────────
const idx = lruKeys.indexOf(uKey);
if (idx !== -1) lruKeys.splice(idx, 1);
lruKeys.unshift(uKey);
// ── LRU: move to most-recently-used position ──────────────────────
// JavaScript Maps maintain insertion order, so delete + re-insert
// is O(1) amortized instead of O(n) with indexOf + splice on an array.
// We keep the _lruUserKeys / _lruBotKeys arrays as fast eviction queues
// but use the Map's own key order for O(1) move-to-front.
if (locations.has(uKey)) {
// Re-insert to move to end (most recently used) — O(1)
locations.delete(uKey);
locations.set(uKey, { channelId: cleanChannel, guildId: cleanGuild, userId: cleanUser });
}
// ── Evict if over cap ──────────────────────────────────────────────
while (lruKeys.length > maxEntries) {
const evictKey = lruKeys.pop();
if (evictKey === uKey) continue; // don't evict the entry we just added
// Use the Map's insertion order to find the oldest entry (first key).
// This is O(1) per eviction instead of popping from an array.
while (locations.size > maxEntries) {
const evictKey = locations.keys().next().value;
if (evictKey === uKey) {
// Don't evict the entry we just added — re-insert at end and move to next
const evictVal = locations.get(evictKey);
locations.delete(evictKey);
locations.set(evictKey, evictVal);
continue;
}
const evicted = locations.get(evictKey);
if (evicted) {
const evictCKey = VoiceStateCache.channelKey(evicted.guildId, evicted.channelId);
@@ -124,6 +138,9 @@ export class VoiceStateCache {
}
locations.delete(evictKey);
}
// Also remove from LRU key list if present
const lruIdx = lruKeys.indexOf(evictKey);
if (lruIdx !== -1) lruKeys.splice(lruIdx, 1);
}
} else {
// ── User left voice — remove from location map ─────────────────────
+19 -14
View File
@@ -53,17 +53,19 @@ export class Dashboard {
const member = await guild.members.fetch(data.accessor).catch(() => null);
const channels = await guild.fetchChannels(); // execute before converting the guild, see caching
const server = Dashboard.convertServer(guild);
if (member) {
server.channels = server.channels.filter(c => {
const ch = channels.find(cl => c.id === cl.id);
return ch ? ch.permissionsFor?.(member)?.has?.("ViewChannel") ?? true : true;
});
server.voiceChannels = server.voiceChannels.filter(c => {
if (c.type !== 2) return false;
const ch = channels.find(cl => c.id === cl.id);
return ch ? ch.permissionsFor?.(member)?.has?.("ViewChannel") ?? true : true;
});
if (!member) {
// Non-member should not see any channels — return error instead of leaking all
return { error: "You are not a member of this server" };
}
server.channels = server.channels.filter(c => {
const ch = channels.find(cl => c.id === cl.id);
return ch ? ch.permissionsFor?.(member)?.has?.("ViewChannel") ?? true : true;
});
server.voiceChannels = server.voiceChannels.filter(c => {
if (c.type !== 2) return false;
const ch = channels.find(cl => c.id === cl.id);
return ch ? ch.permissionsFor?.(member)?.has?.("ViewChannel") ?? true : true;
});
return server;
} catch (e) {
const id = Utils.uid();
@@ -236,7 +238,7 @@ export class Dashboard {
if (authErr) return { error: authErr };
const vol = Number(params.data.volume);
if (isNaN(vol) || vol < 0 || vol > 150) return { error: "Volume must be between 0 and 150" };
const msg = player.setVolume(vol);
const msg = player.setVolume(vol / 100);
return { message: msg };
}
@@ -310,7 +312,10 @@ export class Dashboard {
}
case "leave": {
const player = this._getPlayerById(params.data.channel);
// Support both params.data.channel and params.data.player for
// backward compatibility with different backend versions.
const playerId = params.data.channel ?? params.data.player;
const player = this._getPlayerById(playerId);
if (!player) return { error: "Player not found" };
const authErr = await this._authorizeUserInGuild(user, player._guildId);
if (authErr) return { error: authErr };
@@ -324,9 +329,9 @@ export class Dashboard {
if (player._dashboardUsers && player._dashboardUsers.length > 0) {
// Publish a leave event for this user on the player channel
try {
const pubChannel = this.remix.redis?.publisher ?? this.remix.redis;
const pubChannel = this.remix.dashboard?.redis?.client ?? this.remix.redis?.client;
if (pubChannel && typeof pubChannel.publish === "function") {
pubChannel.publish("fluxer:player_" + params.data.channel, JSON.stringify({
pubChannel.publish("fluxer:player_" + playerId, JSON.stringify({
type: "leave",
data: String(user.id)
}));
+6
View File
@@ -1,5 +1,6 @@
import { compare, genSalt, hash } from "bcryptjs";
import { createPool } from "mysql2/promise";
import { logger } from "../constants/Logger.mjs";
/**
* DatabaseManager — MySQL pool for dashboard login codes and API tokens.
@@ -14,6 +15,11 @@ export class DatabaseManager {
connectionLimit: 15,
...config,
});
// Without this listener, unhandled pool-level errors (connection drops,
// timeouts) fire an unhandled 'error' event which crashes the process.
this.db.on("error", (err) => {
logger.error("[DashboardDB] MySQL pool error:", err.code ?? err.message);
});
}
/**
+19
View File
@@ -1,6 +1,8 @@
import ffprobe from "ffprobe-static";
import { spawn } from "node:child_process";
const PROBE_TIMEOUT_MS = 15_000; // 15 seconds
export default function probe(file) {
return new Promise((res, rej) => {
// Pass args as an array — splitting a string on " " breaks paths that contain spaces.
@@ -13,15 +15,32 @@ export default function probe(file) {
const proc = spawn(ffprobe.path, args);
const chunks = [];
const errChunks = [];
let settled = false;
const cleanup = () => {
settled = true;
clearTimeout(timeoutHandle);
try { proc.kill(); } catch (_) {}
};
const timeoutHandle = setTimeout(() => {
if (settled) return;
cleanup();
rej(new Error("[probe] ffprobe timed out after " + (PROBE_TIMEOUT_MS / 1000) + "s"));
}, PROBE_TIMEOUT_MS);
proc.stdout.on("data", (d) => { chunks.push(d); });
proc.stderr.on("data", (d) => { errChunks.push(d); });
proc.on("error", (err) => {
if (settled) return;
cleanup();
rej(new Error("[probe] Failed to spawn ffprobe: " + err.message));
});
proc.on("close", (code) => {
if (settled) return;
cleanup();
try {
const raw = Buffer.concat(chunks).toString();
if (!raw.trim()) {
+2 -2
View File
@@ -562,7 +562,7 @@ if (workerData?.poolMode) {
result = await jobUtils.getResults(jData.query, jData.resultCount, jData.provider, jData.trackMeta);
break;
case "search":
result = await jobUtils.getVideoData(String(jData), "ytm");
result = await jobUtils.getVideoData(jData.query ?? String(jData), "ytm");
result = result?.data ?? null;
break;
default:
@@ -628,7 +628,7 @@ utils.on("error", (m) => {
break;
}
case "search": {
const result = await utils.getVideoData(String(data), "ytm");
const result = await utils.getVideoData(data.query ?? String(data), "ytm");
post("finished", result?.data ?? null);
break;
}