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

+1
View File
@@ -91,6 +91,7 @@ export async function run(msg, data) {
} }
} }
} catch (err) { } catch (err) {
logger.warn("[Autoplay] Handler error:", err?.message);
if (!p.queue?.getCurrent() && p.queue?.isEmpty() && !p._is247Enabled()) { if (!p.queue?.getCurrent() && p.queue?.isEmpty() && !p._is247Enabled()) {
p._startInactivityTimer(); p._startInactivityTimer();
} }
+2 -1
View File
@@ -248,7 +248,8 @@ export async function playLastFmCategory(ctx, msg, userId, category, options = {
if (!p.queue.getCurrent()) { if (!p.queue.getCurrent()) {
p.playNext(); p.playNext();
} }
} catch { } catch (e) {
logger.warn("[LastfmCmd] Track resolve failed:", e?.message);
failed++; failed++;
} }
} }
+1 -56
View File
@@ -9,64 +9,9 @@ import { getGlobalColor } from "../src/MessageHandler.mjs";
import { logger } from "../src/constants/Logger.mjs"; import { logger } from "../src/constants/Logger.mjs";
import { PROVIDER_CHOICES, parseInlineProvider } from "../src/constants/providers.mjs"; import { PROVIDER_CHOICES, parseInlineProvider } from "../src/constants/providers.mjs";
import { playLastFmCategory } from "./lastfm.mjs"; import { playLastFmCategory } from "./lastfm.mjs";
import { parseLastFmUrl, isLastFmUrl } from "../src/LastFmManager.mjs";
import { ERROR_COLOR } from "../src/constants/UI.mjs"; import { ERROR_COLOR } from "../src/constants/UI.mjs";
/**
* 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}
*/
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("[Play] Error:", e?.message);
return null;
}
}
/**
* Check if a string is a Last.fm music URL.
* @param {string} str
* @returns {boolean}
*/
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) {
logger.warn("[Play] Error:", e?.message);
return false;
}
}
const LASTFM_PLAY_CATEGORIES = ["loved", "top", "recent", "albums"]; const LASTFM_PLAY_CATEGORIES = ["loved", "top", "recent", "albums"];
/** /**
+2 -1
View File
@@ -126,7 +126,8 @@ async function getGuildCount(client) {
cachedGuildCount = total; cachedGuildCount = total;
guildCacheExpiresAt = Date.now() + CACHE_TTL_MS; guildCacheExpiresAt = Date.now() + CACHE_TTL_MS;
return total; return total;
} catch { } catch (e) {
logger.warn("[Stats] REST guild count fetch failed:", e?.message);
if (typeof client.guilds?.size === "number") return client.guilds.size; if (typeof client.guilds?.size === "number") return client.guilds.size;
return Object.keys(client.guilds ?? {}).length; return Object.keys(client.guilds ?? {}).length;
} }
+2 -2
View File
@@ -40,7 +40,7 @@ export const command = new CommandBuilder()
.setRequired(false) .setRequired(false)
); );
function notConfigured(prefix, t, guildId) { function notConfigured(t, guildId) {
return { return {
embeds: [new EmbedBuilder() embeds: [new EmbedBuilder()
.setColor(ERROR_COLOR) .setColor(ERROR_COLOR)
@@ -156,7 +156,7 @@ export async function run(msg, data) {
case "check": case "check":
case "voters": { case "voters": {
if (!fluxerlist || !fluxerlist.enabled) return msg.reply(notConfigured(prefix, t, guildId)); if (!fluxerlist || !fluxerlist.enabled) return msg.reply(notConfigured(t, guildId));
const resolvedType = type || "bot"; const resolvedType = type || "bot";
const id = resourceId || (resolvedType === "server" ? fluxerlist.serverId : fluxerlist.botId); const id = resourceId || (resolvedType === "server" ? fluxerlist.serverId : fluxerlist.botId);
+9 -8
View File
@@ -531,8 +531,8 @@ export class Remix {
try { try {
this.comHash = childProcess.execSync("git rev-parse --short HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim(); 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(); this.comHashLong = childProcess.execSync("git rev-parse HEAD", { cwd: __dirname, timeout: 3000 }).toString().trim();
} catch { } catch (e) {
logger.warn("[Git] comhash error"); logger.warn("[Git] comhash error:", e?.message);
this.comHash = "Newest"; this.comHash = "Newest";
this.comHashLong = null; this.comHashLong = null;
} }
@@ -938,17 +938,18 @@ export class Remix {
try { try {
const member = await guild.members.fetch(user.id).catch(() => null); const member = await guild.members.fetch(user.id).catch(() => null);
if (member) isMember = true; if (member) isMember = true;
} catch (_) { logger.warn("[AloneCheck] Member fetch error for", user.id); } } catch (e) { logger.warn(`[getSharedServers] Member fetch error for ${user.id}:`, e?.message); }
} }
if (!isMember) continue; if (!isMember) continue;
const allChannels = guild.channels?.cache const guildChannels = guild.channels
? [...guild.channels.cache.values()].map(c => Dashboard.convertChannel(c)).filter(c => !c.isCategory) ? [...guild.channels.values()]
: [];
const channelIds = guild.channels?.cache
? [...guild.channels.cache.keys()]
: []; : [];
const allChannels = guildChannels
.map(c => Dashboard.convertChannel(c))
.filter(c => !c.isCategory);
const channelIds = guildChannels.map(c => c.id);
shared.push({ shared.push({
name: guild.name, name: guild.name,
+4 -6
View File
@@ -102,16 +102,14 @@ export class GatewayHandler {
if (guild.members && !guild.members.me) { if (guild.members && !guild.members.me) {
await guild.members.fetchMe(); await guild.members.fetchMe();
} }
} catch (_) { logger.warn("[GatewayHandler] fetchMe failed"); } } catch (e) { logger.warn("[GatewayHandler] fetchMe failed:", e?.message); }
const channels = guild.channels; const channels = guild.channels;
if (!channels) return; if (!channels) return;
let targetChannel = null; let targetChannel = null;
if (guild.systemChannelId) { if (guild.systemChannelId) {
targetChannel = channels.get?.(guild.systemChannelId) targetChannel = channels.get?.(guild.systemChannelId) ?? null;
?? channels.cache?.get?.(guild.systemChannelId)
?? null;
} }
if (!targetChannel) { if (!targetChannel) {
for (const ch of (channels.values?.() ?? [])) { for (const ch of (channels.values?.() ?? [])) {
@@ -150,8 +148,8 @@ export class GatewayHandler {
t ? t(guildIdStr, "responses.gateway.missingPermsFallback", { perms: missingNames.join("**, **") }) : 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." "⚠️ 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 (_) { } catch (e) {
logger.warn(`[GuildCreate] Cannot send ANY notification to server ${guildId} — bot is missing SendMessages permission.`); 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/Album/Track
* https://www.last.fm/music/Artist/_/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 * @param {string} url
* @returns {{ artist: string, track: string|null, album: string|null, url: string } | null} * @returns {{ artist: string, track: string|null, album: string|null, url: string } | null}
*/ */
parseLastFmUrl(url) { parseLastFmUrl(url) {
try { return parseLastFmUrl(url);
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;
}
} }
/** /**
@@ -1290,14 +1268,7 @@ export class LastFmManager {
* @returns {boolean} * @returns {boolean}
*/ */
isLastFmUrl(str) { isLastFmUrl(str) {
if (!str || typeof str !== "string") return false; return isLastFmUrl(str);
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;
}
} }
/** /**
@@ -1418,9 +1389,6 @@ export class LastFmManager {
if (parts.length >= 1) { if (parts.length >= 1) {
artist = parts[0].replace(/\+/g, " "); artist = parts[0].replace(/\+/g, " ");
} }
if (parts.length >= 3 && parts[1] === "_") {
} else if (parts.length >= 2) {
}
if (name && name !== "Unknown") { if (name && name !== "Unknown") {
tracks.push({ tracks.push({
@@ -2300,8 +2268,8 @@ export class LastFmManager {
pool.execute( pool.execute(
`UPDATE lastfm_users SET scrobble_count = scrobble_count + 1 WHERE user_id = ?${f.where}`, `UPDATE lastfm_users SET scrobble_count = scrobble_count + 1 WHERE user_id = ?${f.where}`,
[String(userId), ...f.params] [String(userId), ...f.params]
).catch(() => {}); ).catch(e => { logger.warn("[LastFm] scrobble_count increment failed:", e?.message); });
}).catch(() => {}); }).catch(e => { logger.warn("[LastFm] scrobble_count pool acquire failed:", e?.message); });
} }
_buildPlayQuery(artist, title) { _buildPlayQuery(artist, title) {
@@ -2362,3 +2330,58 @@ export class LastFmManager {
return playedMs >= thresholdMs; 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) { async assertPermissions(permissions, message) {
const guild = message.guild ?? await message.client?.guilds?.resolve?.(message.guildId); const guild = message.guild ?? await message.client?.guilds?.resolve?.(message.guildId);
if (guild && !guild.members?.me) { 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); const missing = this.checkPermissions(permissions, message.channel ?? message.channel?.channel);
if (missing.length === 0) return true; if (missing.length === 0) return true;
@@ -270,7 +270,7 @@ export class MessageHandler {
try { try {
const names = missing.map(k => REQUIRED_BOT_PERMISSIONS.get(k)?.name ?? k); 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 }); 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; return false;
} }
@@ -400,7 +400,7 @@ export class MessageHandler {
return builder; return builder;
} }
#createEmbed(text, message, options = {}) { #createEmbed(text, options = {}) {
return { return {
content: options.content ?? undefined, content: options.content ?? undefined,
embeds: [this.#embedify(text, options)], embeds: [this.#embedify(text, options)],
@@ -417,7 +417,7 @@ export class MessageHandler {
if (!(await this.assertPermissions(["SendMessages", "EmbedLinks"], replyingTo))) return null; if (!(await this.assertPermissions(["SendMessages", "EmbedLinks"], replyingTo))) return null;
let opts; let opts;
if (typeof message === "string") { if (typeof message === "string") {
opts = this.#createEmbed(message, replyingTo); opts = this.#createEmbed(message);
} else { } else {
opts = { ...message }; opts = { ...message };
} }
@@ -443,7 +443,7 @@ export class MessageHandler {
...options ...options
}; };
const content = (typeof message === "object") ? message.embedText : message; 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") { if (typeof message === "object") {
const { embedText, ...rest } = message; const { embedText, ...rest } = message;
payload = { ...payload, ...rest }; payload = { ...payload, ...rest };
@@ -463,7 +463,7 @@ export class MessageHandler {
} }
let opts; let opts;
if (typeof message === "string") { if (typeof message === "string") {
opts = this.#createEmbed(message, channel); opts = this.#createEmbed(message);
} else { } else {
opts = message; opts = message;
} }
@@ -484,7 +484,7 @@ export class MessageHandler {
return new Message(await channel.send(content), this); return new Message(await channel.send(content), this);
} }
const text = (typeof content === "object") ? content.embedText : content; 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") { if (typeof content === "object") {
const { embedText, ...rest } = content; const { embedText, ...rest } = content;
Object.assign(payload, rest); Object.assign(payload, rest);
@@ -1091,7 +1091,7 @@ export class QueuePaginator {
const clearReactions = async () => { const clearReactions = async () => {
try { try {
await rawMsg.removeAllReactions(); await rawMsg.removeAllReactions();
} catch (_) { } catch (e) {
for (const emoji of [prev, next]) { for (const emoji of [prev, next]) {
try { try {
await rawMsg.removeReaction(emoji); 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") { if (mp.source && typeof mp.source.captureFrame === "function") {
const _orig = mp.source.captureFrame.bind(mp.source); const _orig = mp.source.captureFrame.bind(mp.source);
mp.source.captureFrame = async (frame) => { 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; return;
} }
try { try {
@@ -989,7 +989,7 @@ export default class Player extends EventEmitter {
const connection = await this._revoice.join(channelId, false); const connection = await this._revoice.join(channelId, false);
this.connection = connection; this.connection = connection;
this._channelId = channelId; this._channelId = channelId;
this._guildId = channel.guildId; this._guildId = cleanId(channel.guildId);
this.leaving = false; this.leaving = false;
const room = connection.room; const room = connection.room;
@@ -1190,7 +1190,9 @@ export default class Player extends EventEmitter {
this._activeTrackOpt = null; this._activeTrackOpt = null;
if (this._mediaPlayer) { 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; this._mediaPlayer = null;
} }
@@ -1221,10 +1223,12 @@ export default class Player extends EventEmitter {
this.removeListener("queueEnd", this._autoplayHandler); this.removeListener("queueEnd", this._autoplayHandler);
this._autoplayHandler = null; this._autoplayHandler = null;
} }
this.leaving = false;
} catch (e) { } catch (e) {
logger.error("[Player] leave error:", e.message); logger.error("[Player] leave error:", e.message);
return false; return false;
} finally {
this.leaving = false;
this._replayingSeek = false;
} }
this.emit("leave"); this.emit("leave");
return true; return true;
@@ -1451,11 +1455,10 @@ export default class Player extends EventEmitter {
this._replayWithFilters(ms).catch((e) => { this._replayWithFilters(ms).catch((e) => {
logger.warn("[Player] Seek replay failed (non-fatal):", e.message); logger.warn("[Player] Seek replay failed (non-fatal):", e.message);
}); });
} else {
this._seeking = false;
} }
await Utils.sleep(500);
this._seeking = false;
return true; return true;
} catch (e) { } catch (e) {
this._seeking = false; this._seeking = false;
@@ -1517,7 +1520,6 @@ export default class Player extends EventEmitter {
this._replayWithFilters(positionMs).catch((e) => { this._replayWithFilters(positionMs).catch((e) => {
logger.warn("[Player] Filter replay failed (non-fatal):", e.message); logger.warn("[Player] Filter replay failed (non-fatal):", e.message);
}); });
setTimeout(() => { this._seeking = false; }, 500);
} }
return { ok: true }; return { ok: true };
@@ -1536,56 +1538,59 @@ export default class Player extends EventEmitter {
if (!current?.encoded || !this.connection || this.leaving) return; if (!current?.encoded || !this.connection || this.leaving) return;
this._replayingSeek = true; 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 { try {
await this._streamUrl(streamUrl); this._streamingStopped = true;
} catch (e) { await this._stopMediaPlayer().catch(() => {});
logger.warn("[Player] _replayWithFilters stream error:", e.message); 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) { if (this.preferredVolume !== 1) {
const current = this.queue.getCurrent(); this._mediaPlayer.setVolume(this.preferredVolume);
if (current?.type === "radio") { }
logger.player("[Player] Radio stream ended after replay");
this._lastPlayedTrack = current; const nlBase = `http://${this._nl.host}:${this._nl.port}`;
this.queue.current = null; let streamUrl = `${nlBase}/v4/loadstream?encodedTrack=${encodeURIComponent(current.encoded)}&position=${positionMs}&volume=100`;
this._streamingStopped = true;
this.emit("stopplay"); if (this.activeFilterPayload) {
if (!this._is247Enabled()) { streamUrl += `&filters=${encodeURIComponent(JSON.stringify(this.activeFilterPayload))}`;
this._startInactivityTimer(); }
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 { } else {
this._lastPlayedTrack = current;
if (!this.queue.songLoop) this.queue.current = null;
this._streamingStopped = false; this._streamingStopped = false;
this._clearTrackEndTimer();
this._activeTrackOpt = null;
this.playNext().catch(e => logger.error("[Player] post-replay playNext error:", e.message));
} }
} else { } finally {
this._streamingStopped = false; this._replayingSeek = false;
this._seeking = false;
} }
} }
@@ -2246,7 +2251,7 @@ export default class Player extends EventEmitter {
} }
} }
this._skipping = false; this._skipping = false;
if (this._seeking) this._seeking = false; this._seeking = false;
} }
_trackEndTimer = null; _trackEndTimer = null;
+5 -3
View File
@@ -14,7 +14,7 @@ import Player from "./Player.mjs";
import { Utils, cleanId } from "./Utils.mjs"; import { Utils, cleanId } from "./Utils.mjs";
import { logger } from "./constants/Logger.mjs"; import { logger } from "./constants/Logger.mjs";
import { get247ChannelMode } from "./constants/Helpers247.mjs"; import { get247ChannelMode } from "./constants/Helpers247.mjs";
import { EmbedBuilder } from "@fluxerjs/core"; import { EmbedBuilder, PermissionFlags } from "@fluxerjs/core";
import { getVoiceManager } from "@fluxerjs/voice"; import { getVoiceManager } from "@fluxerjs/voice";
import { getGlobalColor, getMessageGuildId } from "./MessageHandler.mjs"; import { getGlobalColor, getMessageGuildId } from "./MessageHandler.mjs";
import { Dashboard } from "./dashboard/Dashboard.mjs"; import { Dashboard } from "./dashboard/Dashboard.mjs";
@@ -53,8 +53,10 @@ function botHasVoicePermissions(client, channelId) {
if (!me) return true; if (!me) return true;
const perms = me.permissionsIn?.(channel); const perms = me.permissionsIn?.(channel);
if (!perms) return true; if (!perms) return true;
if (perms.has(0x8)) return true; if (perms.has(PermissionFlags.Administrator)) return true;
return perms.has(0x400) && perms.has(0x100000) && perms.has(0x200000); return perms.has(PermissionFlags.Connect)
&& perms.has(PermissionFlags.Speak)
&& perms.has(PermissionFlags.UseVAD);
} catch (e) { } catch (e) {
logger.warn("[PlayerManager] botHasVoicePermissions check failed:", e?.message); logger.warn("[PlayerManager] botHasVoicePermissions check failed:", e?.message);
return true; return true;
+4 -3
View File
@@ -35,6 +35,7 @@
import { EventEmitter } from "node:events"; import { EventEmitter } from "node:events";
import { getVoiceManager } from "@fluxerjs/voice"; import { getVoiceManager } from "@fluxerjs/voice";
import { cleanId } from "../Utils.mjs";
export const ConnectionState = Object.freeze({ export const ConnectionState = Object.freeze({
CONN_DISCONNECTED: 0, CONN_DISCONNECTED: 0,
@@ -64,7 +65,7 @@ function isLiveKitLogMessage(...args) {
try { try {
const parsed = JSON.parse(args[0]); const parsed = JSON.parse(args[0]);
if (parsed.name === "lk-rtc") return true; 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; 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._intentionalDisconnects.delete(key);
this._intentionalDisconnectTokens.delete(key); this._intentionalDisconnectTokens.delete(key);
}, 10_000)); }, 10_000));
const cleanChannelId = key.replace(/\D/g, ""); const cleanChannelId = cleanId(key);
if (this.client?._remix?.intentionalLeaves && !this.client._remix.intentionalLeaves.has(cleanChannelId)) { if (this.client?._remix?.intentionalLeaves && !this.client._remix.intentionalLeaves.has(cleanChannelId)) {
this.client._remix.intentionalLeaves.set(cleanChannelId, setTimeout(() => { this.client._remix.intentionalLeaves.set(cleanChannelId, setTimeout(() => {
this.client._remix.intentionalLeaves.delete(cleanChannelId); this.client._remix.intentionalLeaves.delete(cleanChannelId);
@@ -481,7 +482,7 @@ export class FluxerRevoice extends EventEmitter {
warn: (...args) => { if (!isLiveKitLogMessage(...args)) logger.warn("[LiveKit]", ...args); }, warn: (...args) => { if (!isLiveKitLogMessage(...args)) logger.warn("[LiveKit]", ...args); },
error: (...args) => logger.error("[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) { if (!room) {
+2 -2
View File
@@ -209,7 +209,7 @@ export class Dashboard {
data: String(user.id) data: String(user.id)
})); }));
} }
} catch (_) { logger.warn("[Dashboard] Error:", _.message); } } catch (e) { logger.warn("[Dashboard] Error:", e?.message); }
} }
return { message: "Already Connected" }; return { message: "Already Connected" };
} }
@@ -349,7 +349,7 @@ export class Dashboard {
data: String(user.id) data: String(user.id)
})); }));
} }
} catch (_) { logger.warn("[Dashboard] Error:", _.message); } } catch (e) { logger.warn("[Dashboard] Error:", e?.message); }
return { message: "Left channel" }; return { message: "Left channel" };
} }
try { try {
+4 -1
View File
@@ -5,6 +5,7 @@
import ffprobe from "ffprobe-static"; import ffprobe from "ffprobe-static";
import { spawn } from "node:child_process"; import { spawn } from "node:child_process";
import { logger } from "./constants/Logger.mjs";
const PROBE_TIMEOUT_MS = 15_000; const PROBE_TIMEOUT_MS = 15_000;
@@ -24,7 +25,9 @@ export default function probe(file) {
const cleanup = () => { const cleanup = () => {
settled = true; settled = true;
clearTimeout(timeoutHandle); 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(() => { const timeoutHandle = setTimeout(() => {
+3 -2
View File
@@ -11,7 +11,7 @@ import { workerData, parentPort } from "worker_threads";
import { EventEmitter } from "events"; import { EventEmitter } from "events";
import http from "http"; import http from "http";
import https from "https"; import https from "https";
import { Utils, cleanId } from "./Utils.mjs"; import { Utils } from "./Utils.mjs";
import { PROVIDERS } from "./constants/providers.mjs"; import { PROVIDERS } from "./constants/providers.mjs";
import { logger } from "./constants/Logger.mjs"; import { logger } from "./constants/Logger.mjs";
@@ -471,7 +471,8 @@ class YTUtils extends EventEmitter {
let data; let data;
try { try {
data = await loadTracks(id, this._nlGet ?? nlGet); data = await loadTracks(id, this._nlGet ?? nlGet);
} catch (_) { } catch (e) {
logger.worker("[Worker] getResults loadTracks failed:", e?.message);
continue; continue;
} }
tracks = extractTracks(data); tracks = extractTracks(data);