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

+4 -5
View File
@@ -94,8 +94,7 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) {
})();
const embed = new EmbedBuilder().setColor(getGlobalColor())
.setDescription(this.t(message, "responses.join.autoLeaveInactive247", { channel: activeChannelId, prefix }));
message.channel.send({ embeds: [embed] });
message.channel.send({ embeds: [embed] }).catch(() => {});
setTimeout(async () => {
try {
if (typeof this._spawnPlayer === "function") {
@@ -110,9 +109,9 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) {
const prefix = (() => {
try { return this._commands?.getPrefix?.(guildId) ?? "%"; } catch (_) { return "%"; }
})();
const embed = new EmbedBuilder().setColor(getGlobalColor())
const embed2 = new EmbedBuilder().setColor(getGlobalColor())
.setDescription(this.t(message, "responses.join.autoLeaveInactive", { channel: activeChannelId }));
message.channel.send({ embeds: [embed] });
message.channel.send({ embeds: [embed2] }).catch(() => {});
}
});
@@ -162,7 +161,7 @@ export const command = new CommandBuilder()
.setRequired(false)
);
export function run(message, data) {
export async function run(message, data) {
// Check if a channel argument was provided (mention like <#123456>, bare ID, or name)
const rawArg = data?.get?.("channel")?.value?.trim?.() ?? null;
+4 -4
View File
@@ -48,7 +48,7 @@ export async function run(msg) {
const player = await this.getPlayer(msg, false, false, false);
if (!player) return;
const timeout = this.config?.timers?.playerSessionTimeout ?? this.config.playerAFKTimeout ?? 300000;
const timeout = Math.max(60_000, this.config?.timers?.playerSessionTimeout ?? this.config.playerAFKTimeout ?? 300000);
const controlsLayout = [
[CONTROLS.prev, CONTROLS.play, CONTROLS.pause, CONTROLS.stop, CONTROLS.next],
[CONTROLS.loop, CONTROLS.shuffle, CONTROLS.volDown, CONTROLS.volUp, CONTROLS.lyrics],
@@ -91,7 +91,7 @@ export async function run(msg) {
progressBar = PROGRESS.start + PROGRESS.empty.repeat(20) + PROGRESS.end;
}
const volPercent = Math.round((player.preferredVolume || 1) * 100);
const volPercent = Math.round((player.preferredVolume ?? 1) * 100);
const volBars = Math.ceil(volPercent / 10);
const volumeBar = "█".repeat(volBars) + "░".repeat(10 - volBars);
@@ -349,13 +349,13 @@ export async function run(msg) {
break;
case "voldown": {
const newVolDown = Utils.clamp((player.preferredVolume || 1) - 0.1, 0, 1);
const newVolDown = Utils.clamp((player.preferredVolume ?? 1) - 0.1, 0, 1);
reply = player.setVolume(newVolDown);
break;
}
case "volup": {
const newVolUp = Utils.clamp((player.preferredVolume || 1) + 0.1, 0, 1);
const newVolUp = Utils.clamp((player.preferredVolume ?? 1) + 0.1, 0, 1);
reply = player.setVolume(newVolUp);
break;
}
+3 -2
View File
@@ -17,7 +17,7 @@ export const command = function() {
if (!this.config.radio?.length) return null;
return new CommandBuilder()
.setName("radio")
.setDescription("Play a radio station. Use `%radio list` to browse all stations.", "commands.radio")
.setDescription("Play a radio station. Use `${prefix}radio list` to browse all stations.", "commands.radio")
.addAliases("r")
.setCategory("music")
.addTextOption(o =>
@@ -137,13 +137,14 @@ async function playStation(ctx, msg, radio, editTarget = null) {
if (current?.type === "radio" || hasRadioQueued) await p.switchRadio(radio);
else p.playRadio(radio);
const prefix = (() => { try { return ctx.handler?.getPrefix?.(msg?.channel?.channel?.guildId ?? msg?.message?.guildId) ?? "%"; } catch (_) { return "%"; } })();
const embed = new EmbedBuilder()
.setColor(getGlobalColor())
.setTitle(`📻 ${radio.detailedName}`)
.setDescription(
`**[${radio.detailedName}](${radio.author.url})**\n\n` +
`${radio.description}\n\n` +
`_Use \`%skip\` to stop the radio, or \`%radio list\` to switch stations._`
`_Use \`${prefix}skip\` to stop the radio, or \`${prefix}radio list\` to switch stations._`
)
;
+14 -8
View File
@@ -152,9 +152,10 @@ export async function run(msg, data) {
// Batch keywords
if (target === "commands") {
const results = await Promise.all(
this.handler.commands.map(c => reloadCommand(this, msg, c.name))
);
const results = [];
for (const c of [...this.handler.commands]) {
results.push(await reloadCommand(this, msg, c.name));
}
return showResults(msg, results, "Commands");
}
@@ -173,11 +174,16 @@ export async function run(msg, data) {
}
if (target === "all") {
const results = await Promise.all([
...this.handler.commands.map(c => reloadCommand(this, msg, c.name)),
...allModuleFiles("src").map(m => reloadModule(this, msg, m.file, m.label)),
...allModuleFiles("audio").map(m => reloadModule(this, msg, m.file, m.label)),
]);
const results = [];
for (const c of [...this.handler.commands]) {
results.push(await reloadCommand(this, msg, c.name));
}
for (const m of allModuleFiles("src")) {
results.push(await reloadModule(this, msg, m.file, m.label));
}
for (const m of allModuleFiles("audio")) {
results.push(await reloadModule(this, msg, m.file, m.label));
}
return showResults(msg, results, "Everything");
}
+1 -1
View File
@@ -13,7 +13,7 @@ export async function run(message, data) {
const p = await this.getPlayer(message, false, false, false);
if (!p) return;
const index = data.get("index")?.value;
if (index == null) return message.reply("Please provide a valid queue position.");
if (index == null || index < 1) return message.replyEmbed("Queue position must be 1 or greater.");
const res = p.remove(index - 1);
message.replyEmbed(res);
}
+1 -1
View File
@@ -17,7 +17,7 @@ export async function run(message) {
const skippedLink = current ? (current.spotifyUrl || current.url || "") : "";
const err = p.skip();
if (err && err.includes("nothing playing")) {
if (err) {
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(err);
return message.reply({ embeds: [embed] });
}
+47 -16
View File
@@ -17,6 +17,31 @@ import { VoiceStateCache } from "./src/constants/VoiceStateCache.mjs";
import { GatewayHandler } from "./src/GatewayHandler.mjs";
import { LastFmManager } from "./src/LastFmManager.mjs";
/**
* Create a backward-compatible "bot view" wrapper around VoiceStateCache.
*
* The old code used separate Maps for observedVoiceUsers and observedVoiceBots.
* VoiceStateCache merged both into one object, but the default iterator/size
* only exposes human users. This wrapper provides the Map-like interface that
* iterates BOT entries instead, so code that does `for (const [k, v] of observedVoiceBots)`
* still gets bot data, not human data.
*/
function createBotView(voiceCache) {
return {
get size() { return voiceCache.botLocations.size; },
get(key) { return voiceCache.botLocations.get(key); },
set(key, val) { voiceCache.setBotUser(key, val); },
has(key) { return voiceCache.botLocations.has(key); },
delete(key) { voiceCache.deleteBotUser(key); },
forEach(fn) { for (const [k, v] of voiceCache.iterateBotUsers()) fn(v, k, this); },
*[Symbol.iterator]() { yield* voiceCache.iterateBotUsers(); },
*entries() { yield* voiceCache.iterateBotUsers(); },
*keys() { for (const [k] of voiceCache.iterateBotUsers()) yield k; },
*values() { for (const [, v] of voiceCache.iterateBotUsers()) yield v; },
get observedVoiceBotsSize() { return voiceCache.botLocations.size; },
};
}
export class Remix {
constructor() {
// ── Config ───────────────────────────────────────────────────────────────
@@ -166,10 +191,14 @@ export class Remix {
this.voiceCache = new VoiceStateCache({ maxUsers: 50_000, maxBots: 10_000 });
// ── Backward-compat aliases (deprecated — use voiceCache directly) ───
// These expose the same .size / .get / .set / .has / .delete / iteration
// interface so existing code (dashboard, commands) continues to work.
this.observedVoiceUsers = this.voiceCache;
this.observedVoiceBots = this.voiceCache;
// observedVoiceUsers iterates HUMAN users only (backward compat).
// observedVoiceBots iterates BOT users only (backward compat).
// Previously both pointed to the same VoiceStateCache, which caused
// observedVoiceBots to return human users instead of bots.
// We create thin wrapper objects that delegate to the correct
// internal indexes while preserving the Map-like interface.
this.observedVoiceUsers = this.voiceCache; // default iterator = human users
this.observedVoiceBots = createBotView(this.voiceCache);
// ── Caches ───────────────────────────────────────────────────────────────
// _announcementChannelCache: TTL-based (5 min), auto-evicts stale entries
@@ -324,13 +353,14 @@ export class Remix {
const ALONE_CHECK_INTERVAL = this.T.aloneCheckInterval;
setInterval(() => {
for (const [mapKey, player] of this.players.playerMap) {
let channelId;
try {
const guildId = player._guildId;
if (!guildId) continue;
if (player._isJoining) continue;
const channelId = player._channelId ?? mapKey;
channelId = player._channelId ?? mapKey;
const cleanChanId = String(channelId).replace(/\D/g, "");
if (!cleanChanId) continue;
@@ -517,11 +547,22 @@ export class Remix {
return null;
};
// ── Git commit hash ───────────────────────────────────────────────────────
// Must be computed BEFORE comLink is built so the hash is available.
const __dirname = import.meta.dirname;
try {
this.comHash = childProcess.execSync("git rev-parse --short HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim();
this.comHashLong = childProcess.execSync("git rev-parse HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim();
} catch {
logger.warn("[Git] comhash error");
this.comHash = "Newest";
this.comHashLong = null;
}
this.comLink = "https://github.com/remix-bot/fluxer/commit/" + (this.comHashLong ?? "");
// ── Commands ──────────────────────────────────────────────────────────────
const loader = new CommandLoader(commands, this);
const __dirname = import.meta.dirname;
const dir = path.join(__dirname, "commands");
logger.commands("Started loading commands.");
loader.loadFromDir(dir)
@@ -556,16 +597,6 @@ export class Remix {
logger.commands(`Modules loaded (${succeeded} succeeded, ${failed} failed).`);
});
// ── Git commit hash ───────────────────────────────────────────────────────
try {
this.comHash = childProcess.execSync("git rev-parse --short HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim();
this.comHashLong = childProcess.execSync("git rev-parse HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim();
} catch {
logger.warn("[Git] comhash error");
this.comHash = "Newest";
this.comHashLong = null;
}
// ── Login ─────────────────────────────────────────────────────────────────
client.login(config.token);
}
+22 -12
View File
@@ -56,7 +56,7 @@ export class MySqlSettingsManager extends SettingsManager {
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(query) {
return new Promise(res => {
@@ -73,13 +73,17 @@ export class MySqlSettingsManager extends SettingsManager {
}
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");
}
@@ -112,10 +116,16 @@ export class MySqlSettingsManager extends SettingsManager {
if (r.error) logger.error("[Settings] remoteSave error:", r.error);
}
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() {
await Promise.allSettled([...this.guilds.values()].map(v => this.remoteSave(v)));
+15 -6
View File
@@ -10,13 +10,22 @@ const config = JSON.parse(fs.readFileSync(new URL("../config.json", import.meta.
const sm = new RemoteSettingsManager(config.mysql, "./storage/defaults.json");
const rsm = new RemoteSettingsManager(config.mysql, "./storage/defaults.json");
// Capture entries after the source manager has loaded from DB.
let servers = [];
sm.on("ready", () => {
servers = sm.guilds.entries();
});
// Ensure source manager is fully loaded BEFORE starting migration.
// Previously, rsm's "ready" could fire before sm finished loading,
// resulting in an empty servers array and a silent no-op migration.
let migrationStarted = false;
sm.on("ready", async () => {
if (migrationStarted) return;
migrationStarted = true;
const servers = [...sm.guilds.entries()];
// Wait for the destination manager to be ready too
if (!rsm.guilds.size) {
await new Promise(resolve => rsm.on("ready", resolve));
}
rsm.on("ready", async () => {
for (const [id, s] of servers) {
logger.settings("[migrate] Processing server:", id);
if (rsm.hasServer(id)) {
+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;
}