refactor: codebase cleanup + critical player state bug fixes

This commit is contained in:
NoLogicAlan committed 2026-06-20 17:36:29 +03:00
1 parent 82aa296fbc
commit fbf725d29f
15 files changed
+166 -184

No files matched your search

+4 -6
View File
@@ -102,16 +102,14 @@ export class GatewayHandler {
if (guild.members && !guild.members.me) {
await guild.members.fetchMe();
}
} catch (_) { logger.warn("[GatewayHandler] fetchMe failed"); }
} catch (e) { logger.warn("[GatewayHandler] fetchMe failed:", e?.message); }
const channels = guild.channels;
if (!channels) return;
let targetChannel = null;
if (guild.systemChannelId) {
targetChannel = channels.get?.(guild.systemChannelId)
?? channels.cache?.get?.(guild.systemChannelId)
?? null;
targetChannel = channels.get?.(guild.systemChannelId) ?? null;
}
if (!targetChannel) {
for (const ch of (channels.values?.() ?? [])) {
@@ -150,8 +148,8 @@ export class GatewayHandler {
t ? t(guildIdStr, "responses.gateway.missingPermsFallback", { perms: missingNames.join("**, **") }) :
"⚠️ I'm missing permissions I need to work properly! Missing: **" + missingNames.join("**, **") + "**. Please ask a server administrator to grant these permissions in Server Settings → Roles."
);
} catch (_) {
logger.warn(`[GuildCreate] Cannot send ANY notification to server ${guildId} — bot is missing SendMessages permission.`);
} catch (e) {
logger.warn(`[GuildCreate] Cannot send ANY notification to server ${guildId} — bot is missing SendMessages permission:`, e?.message);
}
}
}
+62 -39
View File
@@ -1252,36 +1252,14 @@ export class LastFmManager {
* https://www.last.fm/music/Artist/Album/Track
* https://www.last.fm/music/Artist/_/Track
*
* Delegates to the module-level {@link parseLastFmUrl} so the same logic
* is reused by `commands/play.mjs` and the instance API.
*
* @param {string} url
* @returns {{ artist: string, track: string|null, album: string|null, url: string } | null}
*/
parseLastFmUrl(url) {
try {
const u = new URL(url);
if (!/^(?:www\.)?last\.fm$/i.test(u.hostname)) return null;
const match = u.pathname.match(/^\/music\/([^/]+)(?:\/([^/]+))?(?:\/([^/]+))?/);
if (!match) return null;
const artist = decodeURIComponent(match[1].replace(/\+/g, " "));
const segment2 = match[2] ? decodeURIComponent(match[2].replace(/\+/g, " ")) : null;
const segment3 = match[3] ? decodeURIComponent(match[3].replace(/\+/g, " ")) : null;
let track = null;
let album = null;
if (segment3) {
album = segment2 === "_" ? null : segment2;
track = segment3;
} else if (segment2 && segment2 !== "_") {
track = segment2;
}
return { artist, track, album, url };
} catch (e) {
logger.warn("[LastFm] Error:", e?.message);
return null;
}
return parseLastFmUrl(url);
}
/**
@@ -1290,14 +1268,7 @@ export class LastFmManager {
* @returns {boolean}
*/
isLastFmUrl(str) {
if (!str || typeof str !== "string") return false;
try {
const u = new URL(str);
return /^(?:www\.)?last\.fm$/i.test(u.hostname) && /^\/music\//.test(u.pathname);
} catch (e) {
logger.warn("[LastFm] Error:", e?.message);
return false;
}
return isLastFmUrl(str);
}
/**
@@ -1418,9 +1389,6 @@ export class LastFmManager {
if (parts.length >= 1) {
artist = parts[0].replace(/\+/g, " ");
}
if (parts.length >= 3 && parts[1] === "_") {
} else if (parts.length >= 2) {
}
if (name && name !== "Unknown") {
tracks.push({
@@ -2300,8 +2268,8 @@ export class LastFmManager {
pool.execute(
`UPDATE lastfm_users SET scrobble_count = scrobble_count + 1 WHERE user_id = ?${f.where}`,
[String(userId), ...f.params]
).catch(() => {});
}).catch(() => {});
).catch(e => { logger.warn("[LastFm] scrobble_count increment failed:", e?.message); });
}).catch(e => { logger.warn("[LastFm] scrobble_count pool acquire failed:", e?.message); });
}
_buildPlayQuery(artist, title) {
@@ -2362,3 +2330,58 @@ export class LastFmManager {
return playedMs >= thresholdMs;
}
}
/**
* Parse a Last.fm music URL and extract artist and track info.
* Supports:
* https://www.last.fm/music/Artist
* https://www.last.fm/music/Artist/Track
* https://www.last.fm/music/Artist/Album/Track
* https://www.last.fm/music/Artist/_/Track
*
* @param {string} url
* @returns {{ artist: string, track: string|null, album: string|null, url: string } | null}
*/
export function parseLastFmUrl(url) {
try {
const u = new URL(url);
if (!/^(?:www\.)?last\.fm$/i.test(u.hostname)) return null;
const match = u.pathname.match(/^\/music\/([^/]+)(?:\/([^/]+))?(?:\/([^/]+))?/);
if (!match) return null;
const artist = decodeURIComponent(match[1].replace(/\+/g, " "));
const segment2 = match[2] ? decodeURIComponent(match[2].replace(/\+/g, " ")) : null;
const segment3 = match[3] ? decodeURIComponent(match[3].replace(/\+/g, " ")) : null;
let track = null;
let album = null;
if (segment3) {
album = segment2 === "_" ? null : segment2;
track = segment3;
} else if (segment2 && segment2 !== "_") {
track = segment2;
}
return { artist, track, album, url };
} catch (e) {
logger.warn("[LastFm] parseLastFmUrl error:", e?.message);
return null;
}
}
/**
* Check if a string is a Last.fm music URL.
* @param {string} str
* @returns {boolean}
*/
export function isLastFmUrl(str) {
if (!str || typeof str !== "string") return false;
try {
const u = new URL(str);
return /^(?:www\.)?last\.fm$/i.test(u.hostname) && /^\/music\//.test(u.pathname);
} catch (e) {
return false;
}
}
+8 -8
View File
@@ -245,7 +245,7 @@ export class MessageHandler {
async assertPermissions(permissions, message) {
const guild = message.guild ?? await message.client?.guilds?.resolve?.(message.guildId);
if (guild && !guild.members?.me) {
try { await guild.members.fetchMe(); } catch (_) { logger.warn("[MessageHandler] fetchMe failed"); }
try { await guild.members.fetchMe(); } catch (e) { logger.warn("[MessageHandler] fetchMe failed:", e?.message); }
}
const missing = this.checkPermissions(permissions, message.channel ?? message.channel?.channel);
if (missing.length === 0) return true;
@@ -270,7 +270,7 @@ export class MessageHandler {
try {
const names = missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k);
await message.reply(this.t(message.guildId, "responses.messages.needPermsFallback", { perms: names.join("** **") }), { ping: false });
} catch (_) { logger.warn("[MessageHandler] Fallback permission reply failed"); }
} catch (e) { logger.warn("[MessageHandler] Fallback permission reply failed:", e?.message); }
}
return false;
}
@@ -400,7 +400,7 @@ export class MessageHandler {
return builder;
}
#createEmbed(text, message, options = {}) {
#createEmbed(text, options = {}) {
return {
content: options.content ?? undefined,
embeds: [this.#embedify(text, options)],
@@ -417,7 +417,7 @@ export class MessageHandler {
if (!(await this.assertPermissions(["SendMessages", "EmbedLinks"], replyingTo))) return null;
let opts;
if (typeof message === "string") {
opts = this.#createEmbed(message, replyingTo);
opts = this.#createEmbed(message);
} else {
opts = { ...message };
}
@@ -443,7 +443,7 @@ export class MessageHandler {
...options
};
const content = (typeof message === "object") ? message.embedText : message;
let payload = this.#createEmbed(content, replyingTo, options.embed);
let payload = this.#createEmbed(content, options.embed);
if (typeof message === "object") {
const { embedText, ...rest } = message;
payload = { ...payload, ...rest };
@@ -463,7 +463,7 @@ export class MessageHandler {
}
let opts;
if (typeof message === "string") {
opts = this.#createEmbed(message, channel);
opts = this.#createEmbed(message);
} else {
opts = message;
}
@@ -484,7 +484,7 @@ export class MessageHandler {
return new Message(await channel.send(content), this);
}
const text = (typeof content === "object") ? content.embedText : content;
const payload = this.#createEmbed(text, channel, embedOptions);
const payload = this.#createEmbed(text, embedOptions);
if (typeof content === "object") {
const { embedText, ...rest } = content;
Object.assign(payload, rest);
@@ -1091,7 +1091,7 @@ export class QueuePaginator {
const clearReactions = async () => {
try {
await rawMsg.removeAllReactions();
} catch (_) {
} catch (e) {
for (const emoji of [prev, next]) {
try {
await rawMsg.removeReaction(emoji);
+57 -52
View File
@@ -613,7 +613,7 @@ export default class Player extends EventEmitter {
if (mp.source && typeof mp.source.captureFrame === "function") {
const _orig = mp.source.captureFrame.bind(mp.source);
mp.source.captureFrame = async (frame) => {
if (this._streamingStopped || this._skipping || this._seeking || this.leaving || this._destroyed) {
if (this._streamingStopped || this._skipping || this._seeking || this._replayingSeek || this.leaving || this._destroyed) {
return;
}
try {
@@ -989,7 +989,7 @@ export default class Player extends EventEmitter {
const connection = await this._revoice.join(channelId, false);
this.connection = connection;
this._channelId = channelId;
this._guildId = channel.guildId;
this._guildId = cleanId(channel.guildId);
this.leaving = false;
const room = connection.room;
@@ -1190,7 +1190,9 @@ export default class Player extends EventEmitter {
this._activeTrackOpt = null;
if (this._mediaPlayer) {
try { this._mediaPlayer.destroy(); } catch(e) { /* MediaPlayer may not have destroy() */ }
if (typeof this._mediaPlayer.destroy === "function") {
try { this._mediaPlayer.destroy(); } catch(e) { logger.warn("[Player] MediaPlayer destroy error on leave:", e?.message); }
}
this._mediaPlayer = null;
}
@@ -1221,10 +1223,12 @@ export default class Player extends EventEmitter {
this.removeListener("queueEnd", this._autoplayHandler);
this._autoplayHandler = null;
}
this.leaving = false;
} catch (e) {
logger.error("[Player] leave error:", e.message);
return false;
} finally {
this.leaving = false;
this._replayingSeek = false;
}
this.emit("leave");
return true;
@@ -1451,11 +1455,10 @@ export default class Player extends EventEmitter {
this._replayWithFilters(ms).catch((e) => {
logger.warn("[Player] Seek replay failed (non-fatal):", e.message);
});
} else {
this._seeking = false;
}
await Utils.sleep(500);
this._seeking = false;
return true;
} catch (e) {
this._seeking = false;
@@ -1517,7 +1520,6 @@ export default class Player extends EventEmitter {
this._replayWithFilters(positionMs).catch((e) => {
logger.warn("[Player] Filter replay failed (non-fatal):", e.message);
});
setTimeout(() => { this._seeking = false; }, 500);
}
return { ok: true };
@@ -1536,56 +1538,59 @@ export default class Player extends EventEmitter {
if (!current?.encoded || !this.connection || this.leaving) return;
this._replayingSeek = true;
this._streamingStopped = true;
await this._stopMediaPlayer().catch(() => {});
this._streamingStopped = false;
const hasPlayer = await this._ensureMediaPlayer();
if (!hasPlayer) {
logger.warn("[Player] _replayWithFilters: could not recreate MediaPlayer");
return;
}
if (this.preferredVolume !== 1) {
this._mediaPlayer.setVolume(this.preferredVolume);
}
const nlBase = `http://${this._nl.host}:${this._nl.port}`;
let streamUrl = `${nlBase}/v4/loadstream?encodedTrack=${encodeURIComponent(current.encoded)}&position=${positionMs}&volume=100`;
if (this.activeFilterPayload) {
streamUrl += `&filters=${encodeURIComponent(JSON.stringify(this.activeFilterPayload))}`;
}
try {
await this._streamUrl(streamUrl);
} catch (e) {
logger.warn("[Player] _replayWithFilters stream error:", e.message);
}
this._streamingStopped = true;
await this._stopMediaPlayer().catch(() => {});
this._streamingStopped = false;
this._replayingSeek = false;
const hasPlayer = await this._ensureMediaPlayer();
if (!hasPlayer) {
logger.warn("[Player] _replayWithFilters: could not recreate MediaPlayer");
return;
}
if (!this.leaving && !this._skipping && !this._seeking && !this._paused) {
const current = this.queue.getCurrent();
if (current?.type === "radio") {
logger.player("[Player] Radio stream ended after replay");
this._lastPlayedTrack = current;
this.queue.current = null;
this._streamingStopped = true;
this.emit("stopplay");
if (!this._is247Enabled()) {
this._startInactivityTimer();
if (this.preferredVolume !== 1) {
this._mediaPlayer.setVolume(this.preferredVolume);
}
const nlBase = `http://${this._nl.host}:${this._nl.port}`;
let streamUrl = `${nlBase}/v4/loadstream?encodedTrack=${encodeURIComponent(current.encoded)}&position=${positionMs}&volume=100`;
if (this.activeFilterPayload) {
streamUrl += `&filters=${encodeURIComponent(JSON.stringify(this.activeFilterPayload))}`;
}
try {
await this._streamUrl(streamUrl);
} catch (e) {
logger.warn("[Player] _replayWithFilters stream error:", e.message);
}
if (!this.leaving && !this._skipping && !this._paused) {
const replayCurrent = this.queue.getCurrent();
if (replayCurrent?.type === "radio") {
logger.player("[Player] Radio stream ended after replay");
this._lastPlayedTrack = replayCurrent;
this.queue.current = null;
this._streamingStopped = true;
this.emit("stopplay");
if (!this._is247Enabled()) {
this._startInactivityTimer();
}
} else {
this._lastPlayedTrack = replayCurrent;
if (!this.queue.songLoop) this.queue.current = null;
this._streamingStopped = false;
this._clearTrackEndTimer();
this._activeTrackOpt = null;
this.playNext().catch(e => logger.error("[Player] post-replay playNext error:", e.message));
}
} else {
this._lastPlayedTrack = current;
if (!this.queue.songLoop) this.queue.current = null;
this._streamingStopped = false;
this._clearTrackEndTimer();
this._activeTrackOpt = null;
this.playNext().catch(e => logger.error("[Player] post-replay playNext error:", e.message));
}
} else {
this._streamingStopped = false;
} finally {
this._replayingSeek = false;
this._seeking = false;
}
}
@@ -2246,7 +2251,7 @@ export default class Player extends EventEmitter {
}
}
this._skipping = false;
if (this._seeking) this._seeking = false;
this._seeking = false;
}
_trackEndTimer = null;
+5 -3
View File
@@ -14,7 +14,7 @@ import Player from "./Player.mjs";
import { Utils, cleanId } from "./Utils.mjs";
import { logger } from "./constants/Logger.mjs";
import { get247ChannelMode } from "./constants/Helpers247.mjs";
import { EmbedBuilder } from "@fluxerjs/core";
import { EmbedBuilder, PermissionFlags } from "@fluxerjs/core";
import { getVoiceManager } from "@fluxerjs/voice";
import { getGlobalColor, getMessageGuildId } from "./MessageHandler.mjs";
import { Dashboard } from "./dashboard/Dashboard.mjs";
@@ -53,8 +53,10 @@ function botHasVoicePermissions(client, channelId) {
if (!me) return true;
const perms = me.permissionsIn?.(channel);
if (!perms) return true;
if (perms.has(0x8)) return true;
return perms.has(0x400) && perms.has(0x100000) && perms.has(0x200000);
if (perms.has(PermissionFlags.Administrator)) return true;
return perms.has(PermissionFlags.Connect)
&& perms.has(PermissionFlags.Speak)
&& perms.has(PermissionFlags.UseVAD);
} catch (e) {
logger.warn("[PlayerManager] botHasVoicePermissions check failed:", e?.message);
return true;
+4 -3
View File
@@ -35,6 +35,7 @@
import { EventEmitter } from "node:events";
import { getVoiceManager } from "@fluxerjs/voice";
import { cleanId } from "../Utils.mjs";
export const ConnectionState = Object.freeze({
CONN_DISCONNECTED: 0,
@@ -64,7 +65,7 @@ function isLiveKitLogMessage(...args) {
try {
const parsed = JSON.parse(args[0]);
if (parsed.name === "lk-rtc") return true;
} catch (_e) { logger.warn("[FluxerRevoice] Error parsing livekit args"); }
} catch (e) { logger.warn("[FluxerRevoice] Error parsing livekit args:", e?.message); }
}
if (LIVEKIT_LOG_PREFIXES.some(p => args[0].includes(p))) return true;
}
@@ -278,7 +279,7 @@ export class FluxerRevoice extends EventEmitter {
this._intentionalDisconnects.delete(key);
this._intentionalDisconnectTokens.delete(key);
}, 10_000));
const cleanChannelId = key.replace(/\D/g, "");
const cleanChannelId = cleanId(key);
if (this.client?._remix?.intentionalLeaves && !this.client._remix.intentionalLeaves.has(cleanChannelId)) {
this.client._remix.intentionalLeaves.set(cleanChannelId, setTimeout(() => {
this.client._remix.intentionalLeaves.delete(cleanChannelId);
@@ -481,7 +482,7 @@ export class FluxerRevoice extends EventEmitter {
warn: (...args) => { if (!isLiveKitLogMessage(...args)) logger.warn("[LiveKit]", ...args); },
error: (...args) => logger.error("[LiveKit]", ...args),
});
} catch (_e) { logger.warn("[FluxerRevoice] Error creating LiveKit logger adapter"); }
} catch (e) { logger.warn("[FluxerRevoice] Error creating LiveKit logger adapter:", e?.message); }
}
if (!room) {
+2 -2
View File
@@ -209,7 +209,7 @@ export class Dashboard {
data: String(user.id)
}));
}
} catch (_) { logger.warn("[Dashboard] Error:", _.message); }
} catch (e) { logger.warn("[Dashboard] Error:", e?.message); }
}
return { message: "Already Connected" };
}
@@ -349,7 +349,7 @@ export class Dashboard {
data: String(user.id)
}));
}
} catch (_) { logger.warn("[Dashboard] Error:", _.message); }
} catch (e) { logger.warn("[Dashboard] Error:", e?.message); }
return { message: "Left channel" };
}
try {
+4 -1
View File
@@ -5,6 +5,7 @@
import ffprobe from "ffprobe-static";
import { spawn } from "node:child_process";
import { logger } from "./constants/Logger.mjs";
const PROBE_TIMEOUT_MS = 15_000;
@@ -24,7 +25,9 @@ export default function probe(file) {
const cleanup = () => {
settled = true;
clearTimeout(timeoutHandle);
try { proc.kill(); } catch(e) { /* process already exited */ }
if (proc.exitCode === null && !proc.killed) {
try { proc.kill(); } catch(e) { logger.warn("[probe] kill error:", e?.message); }
}
};
const timeoutHandle = setTimeout(() => {
+3 -2
View File
@@ -11,7 +11,7 @@ import { workerData, parentPort } from "worker_threads";
import { EventEmitter } from "events";
import http from "http";
import https from "https";
import { Utils, cleanId } from "./Utils.mjs";
import { Utils } from "./Utils.mjs";
import { PROVIDERS } from "./constants/providers.mjs";
import { logger } from "./constants/Logger.mjs";
@@ -471,7 +471,8 @@ class YTUtils extends EventEmitter {
let data;
try {
data = await loadTracks(id, this._nlGet ?? nlGet);
} catch (_) {
} catch (e) {
logger.worker("[Worker] getResults loadTracks failed:", e?.message);
continue;
}
tracks = extractTracks(data);