mirror of
https://github.com/remix-bot/fluxer.git
synced 2026-11-24 06:01:44 -05:00
lots of changes
This commit is contained in:
1 parent
ba225c914a
commit
6fa8f3b540
20 files changed
+218
-66
No files matched your search
+4
-5
@@ -94,8 +94,7 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) {
|
|||||||
})();
|
})();
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor())
|
const embed = new EmbedBuilder().setColor(getGlobalColor())
|
||||||
.setDescription(this.t(message, "responses.join.autoLeaveInactive247", { channel: activeChannelId, prefix }));
|
.setDescription(this.t(message, "responses.join.autoLeaveInactive247", { channel: activeChannelId, prefix }));
|
||||||
message.channel.send({ embeds: [embed] });
|
message.channel.send({ embeds: [embed] }).catch(() => {});
|
||||||
|
|
||||||
setTimeout(async () => {
|
setTimeout(async () => {
|
||||||
try {
|
try {
|
||||||
if (typeof this._spawnPlayer === "function") {
|
if (typeof this._spawnPlayer === "function") {
|
||||||
@@ -110,9 +109,9 @@ export async function joinChannel(message, cid, cb = () => {}, ecb = () => {}) {
|
|||||||
const prefix = (() => {
|
const prefix = (() => {
|
||||||
try { return this._commands?.getPrefix?.(guildId) ?? "%"; } catch (_) { return "%"; }
|
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 }));
|
.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)
|
.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)
|
// Check if a channel argument was provided (mention like <#123456>, bare ID, or name)
|
||||||
const rawArg = data?.get?.("channel")?.value?.trim?.() ?? null;
|
const rawArg = data?.get?.("channel")?.value?.trim?.() ?? null;
|
||||||
|
|
||||||
|
|||||||
+4
-4
@@ -48,7 +48,7 @@ export async function run(msg) {
|
|||||||
const player = await this.getPlayer(msg, false, false, false);
|
const player = await this.getPlayer(msg, false, false, false);
|
||||||
if (!player) return;
|
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 = [
|
const controlsLayout = [
|
||||||
[CONTROLS.prev, CONTROLS.play, CONTROLS.pause, CONTROLS.stop, CONTROLS.next],
|
[CONTROLS.prev, CONTROLS.play, CONTROLS.pause, CONTROLS.stop, CONTROLS.next],
|
||||||
[CONTROLS.loop, CONTROLS.shuffle, CONTROLS.volDown, CONTROLS.volUp, CONTROLS.lyrics],
|
[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;
|
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 volBars = Math.ceil(volPercent / 10);
|
||||||
const volumeBar = "█".repeat(volBars) + "░".repeat(10 - volBars);
|
const volumeBar = "█".repeat(volBars) + "░".repeat(10 - volBars);
|
||||||
|
|
||||||
@@ -349,13 +349,13 @@ export async function run(msg) {
|
|||||||
break;
|
break;
|
||||||
|
|
||||||
case "voldown": {
|
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);
|
reply = player.setVolume(newVolDown);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
case "volup": {
|
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);
|
reply = player.setVolume(newVolUp);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
+3
-2
@@ -17,7 +17,7 @@ export const command = function() {
|
|||||||
if (!this.config.radio?.length) return null;
|
if (!this.config.radio?.length) return null;
|
||||||
return new CommandBuilder()
|
return new CommandBuilder()
|
||||||
.setName("radio")
|
.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")
|
.addAliases("r")
|
||||||
.setCategory("music")
|
.setCategory("music")
|
||||||
.addTextOption(o =>
|
.addTextOption(o =>
|
||||||
@@ -137,13 +137,14 @@ async function playStation(ctx, msg, radio, editTarget = null) {
|
|||||||
if (current?.type === "radio" || hasRadioQueued) await p.switchRadio(radio);
|
if (current?.type === "radio" || hasRadioQueued) await p.switchRadio(radio);
|
||||||
else p.playRadio(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()
|
const embed = new EmbedBuilder()
|
||||||
.setColor(getGlobalColor())
|
.setColor(getGlobalColor())
|
||||||
.setTitle(`📻 ${radio.detailedName}`)
|
.setTitle(`📻 ${radio.detailedName}`)
|
||||||
.setDescription(
|
.setDescription(
|
||||||
`**[${radio.detailedName}](${radio.author.url})**\n\n` +
|
`**[${radio.detailedName}](${radio.author.url})**\n\n` +
|
||||||
`${radio.description}\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
@@ -152,9 +152,10 @@ export async function run(msg, data) {
|
|||||||
|
|
||||||
// Batch keywords
|
// Batch keywords
|
||||||
if (target === "commands") {
|
if (target === "commands") {
|
||||||
const results = await Promise.all(
|
const results = [];
|
||||||
this.handler.commands.map(c => reloadCommand(this, msg, c.name))
|
for (const c of [...this.handler.commands]) {
|
||||||
);
|
results.push(await reloadCommand(this, msg, c.name));
|
||||||
|
}
|
||||||
return showResults(msg, results, "Commands");
|
return showResults(msg, results, "Commands");
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -173,11 +174,16 @@ export async function run(msg, data) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (target === "all") {
|
if (target === "all") {
|
||||||
const results = await Promise.all([
|
const results = [];
|
||||||
...this.handler.commands.map(c => reloadCommand(this, msg, c.name)),
|
for (const c of [...this.handler.commands]) {
|
||||||
...allModuleFiles("src").map(m => reloadModule(this, msg, m.file, m.label)),
|
results.push(await reloadCommand(this, msg, c.name));
|
||||||
...allModuleFiles("audio").map(m => reloadModule(this, msg, m.file, m.label)),
|
}
|
||||||
]);
|
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");
|
return showResults(msg, results, "Everything");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+1
-1
@@ -13,7 +13,7 @@ export async function run(message, data) {
|
|||||||
const p = await this.getPlayer(message, false, false, false);
|
const p = await this.getPlayer(message, false, false, false);
|
||||||
if (!p) return;
|
if (!p) return;
|
||||||
const index = data.get("index")?.value;
|
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);
|
const res = p.remove(index - 1);
|
||||||
message.replyEmbed(res);
|
message.replyEmbed(res);
|
||||||
}
|
}
|
||||||
+1
-1
@@ -17,7 +17,7 @@ export async function run(message) {
|
|||||||
const skippedLink = current ? (current.spotifyUrl || current.url || "") : "";
|
const skippedLink = current ? (current.spotifyUrl || current.url || "") : "";
|
||||||
|
|
||||||
const err = p.skip();
|
const err = p.skip();
|
||||||
if (err && err.includes("nothing playing")) {
|
if (err) {
|
||||||
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(err);
|
const embed = new EmbedBuilder().setColor(getGlobalColor()).setDescription(err);
|
||||||
return message.reply({ embeds: [embed] });
|
return message.reply({ embeds: [embed] });
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,6 +17,31 @@ import { VoiceStateCache } from "./src/constants/VoiceStateCache.mjs";
|
|||||||
import { GatewayHandler } from "./src/GatewayHandler.mjs";
|
import { GatewayHandler } from "./src/GatewayHandler.mjs";
|
||||||
import { LastFmManager } from "./src/LastFmManager.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 {
|
export class Remix {
|
||||||
constructor() {
|
constructor() {
|
||||||
// ── Config ───────────────────────────────────────────────────────────────
|
// ── Config ───────────────────────────────────────────────────────────────
|
||||||
@@ -166,10 +191,14 @@ export class Remix {
|
|||||||
this.voiceCache = new VoiceStateCache({ maxUsers: 50_000, maxBots: 10_000 });
|
this.voiceCache = new VoiceStateCache({ maxUsers: 50_000, maxBots: 10_000 });
|
||||||
|
|
||||||
// ── Backward-compat aliases (deprecated — use voiceCache directly) ───
|
// ── Backward-compat aliases (deprecated — use voiceCache directly) ───
|
||||||
// These expose the same .size / .get / .set / .has / .delete / iteration
|
// observedVoiceUsers iterates HUMAN users only (backward compat).
|
||||||
// interface so existing code (dashboard, commands) continues to work.
|
// observedVoiceBots iterates BOT users only (backward compat).
|
||||||
this.observedVoiceUsers = this.voiceCache;
|
// Previously both pointed to the same VoiceStateCache, which caused
|
||||||
this.observedVoiceBots = this.voiceCache;
|
// 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 ───────────────────────────────────────────────────────────────
|
// ── Caches ───────────────────────────────────────────────────────────────
|
||||||
// _announcementChannelCache: TTL-based (5 min), auto-evicts stale entries
|
// _announcementChannelCache: TTL-based (5 min), auto-evicts stale entries
|
||||||
@@ -324,13 +353,14 @@ export class Remix {
|
|||||||
const ALONE_CHECK_INTERVAL = this.T.aloneCheckInterval;
|
const ALONE_CHECK_INTERVAL = this.T.aloneCheckInterval;
|
||||||
setInterval(() => {
|
setInterval(() => {
|
||||||
for (const [mapKey, player] of this.players.playerMap) {
|
for (const [mapKey, player] of this.players.playerMap) {
|
||||||
|
let channelId;
|
||||||
try {
|
try {
|
||||||
const guildId = player._guildId;
|
const guildId = player._guildId;
|
||||||
if (!guildId) continue;
|
if (!guildId) continue;
|
||||||
|
|
||||||
if (player._isJoining) continue;
|
if (player._isJoining) continue;
|
||||||
|
|
||||||
const channelId = player._channelId ?? mapKey;
|
channelId = player._channelId ?? mapKey;
|
||||||
const cleanChanId = String(channelId).replace(/\D/g, "");
|
const cleanChanId = String(channelId).replace(/\D/g, "");
|
||||||
if (!cleanChanId) continue;
|
if (!cleanChanId) continue;
|
||||||
|
|
||||||
@@ -517,11 +547,22 @@ export class Remix {
|
|||||||
return null;
|
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 ?? "");
|
this.comLink = "https://github.com/remix-bot/fluxer/commit/" + (this.comHashLong ?? "");
|
||||||
|
|
||||||
// ── Commands ──────────────────────────────────────────────────────────────
|
// ── Commands ──────────────────────────────────────────────────────────────
|
||||||
const loader = new CommandLoader(commands, this);
|
const loader = new CommandLoader(commands, this);
|
||||||
const __dirname = import.meta.dirname;
|
|
||||||
const dir = path.join(__dirname, "commands");
|
const dir = path.join(__dirname, "commands");
|
||||||
logger.commands("Started loading commands.");
|
logger.commands("Started loading commands.");
|
||||||
loader.loadFromDir(dir)
|
loader.loadFromDir(dir)
|
||||||
@@ -556,16 +597,6 @@ export class Remix {
|
|||||||
logger.commands(`Modules loaded (${succeeded} succeeded, ${failed} failed).`);
|
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 ─────────────────────────────────────────────────────────────────
|
// ── Login ─────────────────────────────────────────────────────────────────
|
||||||
client.login(config.token);
|
client.login(config.token);
|
||||||
}
|
}
|
||||||
|
|||||||
+11
-1
@@ -56,7 +56,7 @@ export class MySqlSettingsManager extends SettingsManager {
|
|||||||
logger.error("[DB] MySQL pool error:", err.code ?? err.message);
|
logger.error("[DB] MySQL pool error:", err.code ?? err.message);
|
||||||
});
|
});
|
||||||
if (defaultsPath) this.loadDefaultsSync(defaultsPath);
|
if (defaultsPath) this.loadDefaultsSync(defaultsPath);
|
||||||
this.load();
|
this.load().catch(err => logger.error("[Settings] Initial load failed:", err?.message ?? err));
|
||||||
}
|
}
|
||||||
query(query) {
|
query(query) {
|
||||||
return new Promise(res => {
|
return new Promise(res => {
|
||||||
@@ -73,6 +73,7 @@ export class MySqlSettingsManager extends SettingsManager {
|
|||||||
}
|
}
|
||||||
this._loadAttempts = 0;
|
this._loadAttempts = 0;
|
||||||
res.results.forEach((r) => {
|
res.results.forEach((r) => {
|
||||||
|
try {
|
||||||
const server = new ServerSettings(r.id, this);
|
const server = new ServerSettings(r.id, this);
|
||||||
// mysql2 may return JSON columns as already-parsed objects;
|
// mysql2 may return JSON columns as already-parsed objects;
|
||||||
// only JSON.parse when the value is still a string.
|
// only JSON.parse when the value is still a string.
|
||||||
@@ -80,6 +81,9 @@ export class MySqlSettingsManager extends SettingsManager {
|
|||||||
server.deserialize(parsed);
|
server.deserialize(parsed);
|
||||||
server.checkDefaults(this.defaults);
|
server.checkDefaults(this.defaults);
|
||||||
this.guilds.set(server.id, server);
|
this.guilds.set(server.id, server);
|
||||||
|
} catch (e) {
|
||||||
|
logger.error("[Settings] Failed to parse settings for server", r.id, ":", e.message);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
this.emit("ready");
|
this.emit("ready");
|
||||||
}
|
}
|
||||||
@@ -112,10 +116,16 @@ export class MySqlSettingsManager extends SettingsManager {
|
|||||||
if (r.error) logger.error("[Settings] remoteSave error:", r.error);
|
if (r.error) logger.error("[Settings] remoteSave error:", r.error);
|
||||||
}
|
}
|
||||||
loadDefaultsSync(filePath) {
|
loadDefaultsSync(filePath) {
|
||||||
|
try {
|
||||||
const d = fs.readFileSync(filePath, "utf8");
|
const d = fs.readFileSync(filePath, "utf8");
|
||||||
const parsed = JSON.parse(d);
|
const parsed = JSON.parse(d);
|
||||||
this.descriptions = parsed.descriptions;
|
this.descriptions = parsed.descriptions;
|
||||||
this.defaults = parsed.values;
|
this.defaults = parsed.values;
|
||||||
|
} catch (e) {
|
||||||
|
logger.error("[Settings] Failed to load defaults from", filePath, ":", e.message);
|
||||||
|
this.descriptions = {};
|
||||||
|
this.defaults = {};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
async saveAsync() {
|
async saveAsync() {
|
||||||
await Promise.allSettled([...this.guilds.values()].map(v => this.remoteSave(v)));
|
await Promise.allSettled([...this.guilds.values()].map(v => this.remoteSave(v)));
|
||||||
|
|||||||
+15
-6
@@ -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 sm = new RemoteSettingsManager(config.mysql, "./storage/defaults.json");
|
||||||
const rsm = 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.
|
// Ensure source manager is fully loaded BEFORE starting migration.
|
||||||
let servers = [];
|
// Previously, rsm's "ready" could fire before sm finished loading,
|
||||||
sm.on("ready", () => {
|
// resulting in an empty servers array and a silent no-op migration.
|
||||||
servers = sm.guilds.entries();
|
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) {
|
for (const [id, s] of servers) {
|
||||||
logger.settings("[migrate] Processing server:", id);
|
logger.settings("[migrate] Processing server:", id);
|
||||||
if (rsm.hasServer(id)) {
|
if (rsm.hasServer(id)) {
|
||||||
|
|||||||
+19
-1
@@ -768,7 +768,25 @@ export class GatewayHandler {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (nextKey && this._prevVoiceState.size >= 10_000 && !this._prevVoiceState.has(nextKey)) {
|
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 });
|
if (nextKey) this._prevVoiceState.set(nextKey, { channelId, guildId: guildId ?? prev?.guildId });
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
+4
-1
@@ -709,7 +709,10 @@ export default class Player extends EventEmitter {
|
|||||||
for (let attempt = 1; attempt <= MAX_PUBLISH_RETRIES; attempt++) {
|
for (let attempt = 1; attempt <= MAX_PUBLISH_RETRIES; attempt++) {
|
||||||
try {
|
try {
|
||||||
this._mediaPlayer = new MediaPlayer();
|
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);
|
await this._mediaPlayer.publishToRoom(room);
|
||||||
logger.mediaplayer("[Player] MediaPlayer published successfully");
|
logger.mediaplayer("[Player] MediaPlayer published successfully");
|
||||||
return true;
|
return true;
|
||||||
|
|||||||
@@ -810,9 +810,16 @@ export class PlayerManager {
|
|||||||
const pendingScrobble = this._pendingScrobbleTimers.get(activeChannelId);
|
const pendingScrobble = this._pendingScrobbleTimers.get(activeChannelId);
|
||||||
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this._pendingScrobbleTimers.delete(activeChannelId); }
|
if (pendingScrobble) { clearTimeout(pendingScrobble.timer); this._pendingScrobbleTimers.delete(activeChannelId); }
|
||||||
if (activeChannelId !== cleanChannelId) this.playerMap.delete(cleanChannelId);
|
if (activeChannelId !== cleanChannelId) this.playerMap.delete(cleanChannelId);
|
||||||
await msg.reply(mkEmbed(this._t(msg, "responses._common.successfullyLeft")));
|
// 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();
|
await player.leave();
|
||||||
|
} catch (e) {
|
||||||
|
logger.warn("[PlayerManager] leave() error (non-fatal):", e.message);
|
||||||
|
}
|
||||||
player.destroy();
|
player.destroy();
|
||||||
|
await msg.reply(mkEmbed(this._t(msg, "responses._common.successfullyLeft")));
|
||||||
}
|
}
|
||||||
|
|
||||||
// ═══════════════════════════════════════════════════════════════════════════
|
// ═══════════════════════════════════════════════════════════════════════════
|
||||||
|
|||||||
+11
-1
@@ -55,7 +55,7 @@ export class RemoteSettingsManager extends EventEmitter {
|
|||||||
logger.error("[DB] MySQL pool error:", err.code ?? err.message);
|
logger.error("[DB] MySQL pool error:", err.code ?? err.message);
|
||||||
});
|
});
|
||||||
if (defaultsPath) this.loadDefaultsSync(defaultsPath);
|
if (defaultsPath) this.loadDefaultsSync(defaultsPath);
|
||||||
this.load();
|
this.load().catch(err => logger.error("[Settings] Initial load failed:", err?.message ?? err));
|
||||||
}
|
}
|
||||||
|
|
||||||
query(q) {
|
query(q) {
|
||||||
@@ -75,6 +75,7 @@ export class RemoteSettingsManager extends EventEmitter {
|
|||||||
}
|
}
|
||||||
this._loadAttempts = 0;
|
this._loadAttempts = 0;
|
||||||
res.results.forEach((r) => {
|
res.results.forEach((r) => {
|
||||||
|
try {
|
||||||
const server = new ServerSettings(r.id, this);
|
const server = new ServerSettings(r.id, this);
|
||||||
// mysql2 may return JSON columns as already-parsed objects;
|
// mysql2 may return JSON columns as already-parsed objects;
|
||||||
// only JSON.parse when the value is still a string.
|
// only JSON.parse when the value is still a string.
|
||||||
@@ -82,6 +83,9 @@ export class RemoteSettingsManager extends EventEmitter {
|
|||||||
server.deserialize(parsed);
|
server.deserialize(parsed);
|
||||||
server.checkDefaults(this.defaults);
|
server.checkDefaults(this.defaults);
|
||||||
this.guilds.set(server.id, server);
|
this.guilds.set(server.id, server);
|
||||||
|
} catch (e) {
|
||||||
|
logger.error("[Settings] Failed to parse settings for server", r.id, ":", e.message);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
this.emit("ready");
|
this.emit("ready");
|
||||||
}
|
}
|
||||||
@@ -113,10 +117,16 @@ export class RemoteSettingsManager extends EventEmitter {
|
|||||||
}
|
}
|
||||||
|
|
||||||
loadDefaultsSync(filePath) {
|
loadDefaultsSync(filePath) {
|
||||||
|
try {
|
||||||
const d = fs.readFileSync(filePath, "utf8");
|
const d = fs.readFileSync(filePath, "utf8");
|
||||||
const parsed = JSON.parse(d);
|
const parsed = JSON.parse(d);
|
||||||
this.descriptions = parsed.descriptions;
|
this.descriptions = parsed.descriptions;
|
||||||
this.defaults = parsed.values;
|
this.defaults = parsed.values;
|
||||||
|
} catch (e) {
|
||||||
|
logger.error("[Settings] Failed to load defaults from", filePath, ":", e.message);
|
||||||
|
this.descriptions = {};
|
||||||
|
this.defaults = {};
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async saveAsync() {
|
async saveAsync() {
|
||||||
|
|||||||
+3
-3
@@ -210,8 +210,8 @@ export class Utils {
|
|||||||
* @returns {string} Human readable size
|
* @returns {string} Human readable size
|
||||||
*/
|
*/
|
||||||
static formatBytes(bytes, decimals = 2) {
|
static formatBytes(bytes, decimals = 2) {
|
||||||
if (!bytes || bytes === 0) return "0 Bytes";
|
if (bytes === 0) return "0 Bytes";
|
||||||
if (bytes < 0) return "Unknown";
|
if (!bytes || bytes < 0 || !isFinite(bytes)) return "Unknown";
|
||||||
|
|
||||||
const k = 1024;
|
const k = 1024;
|
||||||
const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB"];
|
const sizes = ["Bytes", "KB", "MB", "GB", "TB", "PB"];
|
||||||
@@ -453,7 +453,7 @@ export class Utils {
|
|||||||
progress = this.clamp(current, 0, 1);
|
progress = this.clamp(current, 0, 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
const position = Math.floor(progress * length);
|
const position = Math.min(Math.floor(progress * length), length - 1);
|
||||||
let bar = "";
|
let bar = "";
|
||||||
|
|
||||||
for (let i = 0; i < length; i++) {
|
for (let i = 0; i < length; i++) {
|
||||||
|
|||||||
@@ -32,6 +32,16 @@ import { joinVoiceChannel, getVoiceManager } from "@fluxerjs/voice";
|
|||||||
import { logger } from "./Logger.mjs";
|
import { logger } from "./Logger.mjs";
|
||||||
|
|
||||||
{
|
{
|
||||||
|
// ── LiveKit SDK log suppression ──────────────────────────────────────────
|
||||||
|
// The LiveKit Node.js SDK (via pino) emits verbose JSON and human-readable
|
||||||
|
// log lines that flood the console. We monkey-patch console.log and
|
||||||
|
// process.stdout.write to silently drop lines from the "lk-rtc" logger.
|
||||||
|
//
|
||||||
|
// Guard: only patch once even if the module is imported multiple times
|
||||||
|
// (e.g. during hot-reload). The global symbol ensures idempotency.
|
||||||
|
if (!globalThis.__fluxerLiveKitLogPatchApplied) {
|
||||||
|
globalThis.__fluxerLiveKitLogPatchApplied = true;
|
||||||
|
|
||||||
const _originalConsoleLog = console.log;
|
const _originalConsoleLog = console.log;
|
||||||
console.log = function (...args) {
|
console.log = function (...args) {
|
||||||
// Fast path: if the first arg is a string that looks like a pino JSON log
|
// Fast path: if the first arg is a string that looks like a pino JSON log
|
||||||
@@ -83,6 +93,7 @@ import { logger } from "./Logger.mjs";
|
|||||||
return _originalStdoutWrite(chunk, encoding, callback);
|
return _originalStdoutWrite(chunk, encoding, callback);
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ConnectionState enum values for reference:
|
// ConnectionState enum values for reference:
|
||||||
// ConnectionState.CONN_DISCONNECTED = 0
|
// ConnectionState.CONN_DISCONNECTED = 0
|
||||||
|
|||||||
@@ -105,15 +105,29 @@ export class VoiceStateCache {
|
|||||||
// ── Update location map ────────────────────────────────────────────
|
// ── Update location map ────────────────────────────────────────────
|
||||||
locations.set(uKey, { channelId: cleanChannel, guildId: cleanGuild, userId: cleanUser });
|
locations.set(uKey, { channelId: cleanChannel, guildId: cleanGuild, userId: cleanUser });
|
||||||
|
|
||||||
// ── LRU: move to front ─────────────────────────────────────────────
|
// ── LRU: move to most-recently-used position ──────────────────────
|
||||||
const idx = lruKeys.indexOf(uKey);
|
// JavaScript Maps maintain insertion order, so delete + re-insert
|
||||||
if (idx !== -1) lruKeys.splice(idx, 1);
|
// is O(1) amortized instead of O(n) with indexOf + splice on an array.
|
||||||
lruKeys.unshift(uKey);
|
// 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 ──────────────────────────────────────────────
|
// ── Evict if over cap ──────────────────────────────────────────────
|
||||||
while (lruKeys.length > maxEntries) {
|
// Use the Map's insertion order to find the oldest entry (first key).
|
||||||
const evictKey = lruKeys.pop();
|
// This is O(1) per eviction instead of popping from an array.
|
||||||
if (evictKey === uKey) continue; // don't evict the entry we just added
|
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);
|
const evicted = locations.get(evictKey);
|
||||||
if (evicted) {
|
if (evicted) {
|
||||||
const evictCKey = VoiceStateCache.channelKey(evicted.guildId, evicted.channelId);
|
const evictCKey = VoiceStateCache.channelKey(evicted.guildId, evicted.channelId);
|
||||||
@@ -124,6 +138,9 @@ export class VoiceStateCache {
|
|||||||
}
|
}
|
||||||
locations.delete(evictKey);
|
locations.delete(evictKey);
|
||||||
}
|
}
|
||||||
|
// Also remove from LRU key list if present
|
||||||
|
const lruIdx = lruKeys.indexOf(evictKey);
|
||||||
|
if (lruIdx !== -1) lruKeys.splice(lruIdx, 1);
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// ── User left voice — remove from location map ─────────────────────
|
// ── User left voice — remove from location map ─────────────────────
|
||||||
|
|||||||
@@ -53,7 +53,10 @@ export class Dashboard {
|
|||||||
const member = await guild.members.fetch(data.accessor).catch(() => null);
|
const member = await guild.members.fetch(data.accessor).catch(() => null);
|
||||||
const channels = await guild.fetchChannels(); // execute before converting the guild, see caching
|
const channels = await guild.fetchChannels(); // execute before converting the guild, see caching
|
||||||
const server = Dashboard.convertServer(guild);
|
const server = Dashboard.convertServer(guild);
|
||||||
if (member) {
|
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 => {
|
server.channels = server.channels.filter(c => {
|
||||||
const ch = channels.find(cl => c.id === cl.id);
|
const ch = channels.find(cl => c.id === cl.id);
|
||||||
return ch ? ch.permissionsFor?.(member)?.has?.("ViewChannel") ?? true : true;
|
return ch ? ch.permissionsFor?.(member)?.has?.("ViewChannel") ?? true : true;
|
||||||
@@ -63,7 +66,6 @@ export class Dashboard {
|
|||||||
const ch = channels.find(cl => c.id === cl.id);
|
const ch = channels.find(cl => c.id === cl.id);
|
||||||
return ch ? ch.permissionsFor?.(member)?.has?.("ViewChannel") ?? true : true;
|
return ch ? ch.permissionsFor?.(member)?.has?.("ViewChannel") ?? true : true;
|
||||||
});
|
});
|
||||||
}
|
|
||||||
return server;
|
return server;
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
const id = Utils.uid();
|
const id = Utils.uid();
|
||||||
@@ -236,7 +238,7 @@ export class Dashboard {
|
|||||||
if (authErr) return { error: authErr };
|
if (authErr) return { error: authErr };
|
||||||
const vol = Number(params.data.volume);
|
const vol = Number(params.data.volume);
|
||||||
if (isNaN(vol) || vol < 0 || vol > 150) return { error: "Volume must be between 0 and 150" };
|
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 };
|
return { message: msg };
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -310,7 +312,10 @@ export class Dashboard {
|
|||||||
}
|
}
|
||||||
|
|
||||||
case "leave": {
|
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" };
|
if (!player) return { error: "Player not found" };
|
||||||
const authErr = await this._authorizeUserInGuild(user, player._guildId);
|
const authErr = await this._authorizeUserInGuild(user, player._guildId);
|
||||||
if (authErr) return { error: authErr };
|
if (authErr) return { error: authErr };
|
||||||
@@ -324,9 +329,9 @@ export class Dashboard {
|
|||||||
if (player._dashboardUsers && player._dashboardUsers.length > 0) {
|
if (player._dashboardUsers && player._dashboardUsers.length > 0) {
|
||||||
// Publish a leave event for this user on the player channel
|
// Publish a leave event for this user on the player channel
|
||||||
try {
|
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") {
|
if (pubChannel && typeof pubChannel.publish === "function") {
|
||||||
pubChannel.publish("fluxer:player_" + params.data.channel, JSON.stringify({
|
pubChannel.publish("fluxer:player_" + playerId, JSON.stringify({
|
||||||
type: "leave",
|
type: "leave",
|
||||||
data: String(user.id)
|
data: String(user.id)
|
||||||
}));
|
}));
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { compare, genSalt, hash } from "bcryptjs";
|
import { compare, genSalt, hash } from "bcryptjs";
|
||||||
import { createPool } from "mysql2/promise";
|
import { createPool } from "mysql2/promise";
|
||||||
|
import { logger } from "../constants/Logger.mjs";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* DatabaseManager — MySQL pool for dashboard login codes and API tokens.
|
* DatabaseManager — MySQL pool for dashboard login codes and API tokens.
|
||||||
@@ -14,6 +15,11 @@ export class DatabaseManager {
|
|||||||
connectionLimit: 15,
|
connectionLimit: 15,
|
||||||
...config,
|
...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);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
|
|||||||
@@ -1,6 +1,8 @@
|
|||||||
import ffprobe from "ffprobe-static";
|
import ffprobe from "ffprobe-static";
|
||||||
import { spawn } from "node:child_process";
|
import { spawn } from "node:child_process";
|
||||||
|
|
||||||
|
const PROBE_TIMEOUT_MS = 15_000; // 15 seconds
|
||||||
|
|
||||||
export default function probe(file) {
|
export default function probe(file) {
|
||||||
return new Promise((res, rej) => {
|
return new Promise((res, rej) => {
|
||||||
// Pass args as an array — splitting a string on " " breaks paths that contain spaces.
|
// 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 proc = spawn(ffprobe.path, args);
|
||||||
const chunks = [];
|
const chunks = [];
|
||||||
const errChunks = [];
|
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.stdout.on("data", (d) => { chunks.push(d); });
|
||||||
proc.stderr.on("data", (d) => { errChunks.push(d); });
|
proc.stderr.on("data", (d) => { errChunks.push(d); });
|
||||||
|
|
||||||
proc.on("error", (err) => {
|
proc.on("error", (err) => {
|
||||||
|
if (settled) return;
|
||||||
|
cleanup();
|
||||||
rej(new Error("[probe] Failed to spawn ffprobe: " + err.message));
|
rej(new Error("[probe] Failed to spawn ffprobe: " + err.message));
|
||||||
});
|
});
|
||||||
|
|
||||||
proc.on("close", (code) => {
|
proc.on("close", (code) => {
|
||||||
|
if (settled) return;
|
||||||
|
cleanup();
|
||||||
try {
|
try {
|
||||||
const raw = Buffer.concat(chunks).toString();
|
const raw = Buffer.concat(chunks).toString();
|
||||||
if (!raw.trim()) {
|
if (!raw.trim()) {
|
||||||
|
|||||||
+2
-2
@@ -562,7 +562,7 @@ if (workerData?.poolMode) {
|
|||||||
result = await jobUtils.getResults(jData.query, jData.resultCount, jData.provider, jData.trackMeta);
|
result = await jobUtils.getResults(jData.query, jData.resultCount, jData.provider, jData.trackMeta);
|
||||||
break;
|
break;
|
||||||
case "search":
|
case "search":
|
||||||
result = await jobUtils.getVideoData(String(jData), "ytm");
|
result = await jobUtils.getVideoData(jData.query ?? String(jData), "ytm");
|
||||||
result = result?.data ?? null;
|
result = result?.data ?? null;
|
||||||
break;
|
break;
|
||||||
default:
|
default:
|
||||||
@@ -628,7 +628,7 @@ utils.on("error", (m) => {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "search": {
|
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);
|
post("finished", result?.data ?? null);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user