This commit is contained in:
NoLogicAlan committed 2026-09-16 03:15:16 +03:00
1 parent 8cd0384f75
commit 990cc68100
10 files changed
+222 -16

No files matched your search

+2 -2
View File
@@ -124,7 +124,7 @@ export async function run(message) {
.setColor(getGlobalColor()) .setColor(getGlobalColor())
.setTitle(`🎵 ${Utils.truncate(displayTitle, 50)}`) .setTitle(`🎵 ${Utils.truncate(displayTitle, 50)}`)
.setDescription(singleDesc.slice(0, MAX_DESC)) .setDescription(singleDesc.slice(0, MAX_DESC))
.setFooter({ text: this.t(message, "responses.lyrics.nodeLinkFooter", { lines: totalLines }) }); .setFooter({ text: this.t(message, "responses.lyrics.sourceFooter", { source: result.source, lines: totalLines }) });
if (current.thumbnail) singleEmbed.setThumbnail(current.thumbnail); if (current.thumbnail) singleEmbed.setThumbnail(current.thumbnail);
return message.reply({ embeds: [singleEmbed] }); return message.reply({ embeds: [singleEmbed] });
} }
@@ -150,7 +150,7 @@ export async function run(message) {
.setDescription(desc.slice(0, MAX_DESC)) .setDescription(desc.slice(0, MAX_DESC))
.setFooter({ text: expired .setFooter({ text: expired
? this.t(message, "responses.lyrics.controlsExpired", { lines: totalLines }) ? this.t(message, "responses.lyrics.controlsExpired", { lines: totalLines })
: this.t(message, "responses.lyrics.nodeLinkFooter", { lines: totalLines }) }); : this.t(message, "responses.lyrics.sourceFooter", { source: result.source, lines: totalLines }) });
if (current.thumbnail) b.setThumbnail(current.thumbnail); if (current.thumbnail) b.setThumbnail(current.thumbnail);
return { embeds: [b] }; return { embeds: [b] };
}; };
+4 -3
View File
@@ -82,11 +82,12 @@ export async function openLyricsViewer(bot, msg, player, refresh, session) {
player.queue.getCurrent()?.title?.replace(/\(Official.*?\)/gi, '').trim() ?? '', player.queue.getCurrent()?.title?.replace(/\(Official.*?\)/gi, '').trim() ?? '',
50 50
); );
const lyricsSource = lyricsResult.source || "Lyrics";
const footerText = closed const footerText = closed
? `👋 Lyrics closed • NodeLink • ${totalLines} lines` ? `👋 Lyrics closed • ${lyricsSource} • ${totalLines} lines`
: expired : expired
? `⌛ Controls expired • NodeLink • ${totalLines} lines` ? `⌛ Controls expired • ${lyricsSource} • ${totalLines} lines`
: `NodeLink • ${totalLines} lines total${lyricsResult.synced ? ' • Synced' : ''}`; : `${lyricsSource} • ${totalLines} lines total${lyricsResult.synced ? ' • Synced' : ''}`;
const desc = [ const desc = [
`**${title}**${syncBadge} • Page ${pageIdx + 1}/${totalPages}`, `**${title}**${syncBadge} • Page ${pageIdx + 1}/${totalPages}`,
``, ``,
+118 -11
View File
@@ -624,8 +624,11 @@ const PlaybackMixin = {
}, },
/** /**
* @async Fetch lyrics for the currently playing track via the Lavalink * @async Fetch lyrics for the currently playing track.
* REST API. * Primary: LRCLIB direct lookup with a cleaned artist/title query, scoring
* every candidate by title, artist and duration agreement so a fuzzy hit on
* the wrong song is never returned.
* Fallback: NodeLink loadlyrics with the cleaned identifier (free-text).
* @this {import('./Player.mjs').Player} * @this {import('./Player.mjs').Player}
* @returns {Promise<{text: string, source: string, synced: boolean, lines: Array}|null>} * @returns {Promise<{text: string, source: string, synced: boolean, lines: Array}|null>}
*/ */
@@ -633,18 +636,21 @@ const PlaybackMixin = {
const current = this.queue.getCurrent(); const current = this.queue.getCurrent();
if (!current) return null; if (!current) return null;
const node = this._lavalink?.getNode?.() ?? null; const query = this._buildLyricsQuery(current);
if (!query.title) return null;
if (node) {
try { try {
const searchQuery = current.artists?.[0]?.name const result = await this._fetchVerifiedLyrics(query);
? `${current.title} ${current.artists[0].name}` if (result) return result;
: current.title; } catch (e) {
logger.player(`[Lyrics] LRCLIB lookup failed: ${e.message}`);
const path = current.encoded }
? `/loadlyrics?encodedTrack=${encodeURIComponent(current.encoded)}`
: `/loadlyrics?identifier=${encodeURIComponent(searchQuery)}`;
const node = this._lavalink?.getNode?.() ?? null;
if (node && query.candidates.length > 0) {
try {
const searchQuery = query.candidates.join(" ");
const path = `/loadlyrics?identifier=${encodeURIComponent(searchQuery)}`;
const results = await node.request(path); const results = await node.request(path);
if (results?.data?.lines?.length) { if (results?.data?.lines?.length) {
@@ -662,6 +668,107 @@ const PlaybackMixin = {
return null; return null;
}, },
/**
* @private Build a cleaned artist/title pair for lyrics lookups, preferring
* real metadata (lastfm tags, provider artists) over the raw YouTube title,
* and splitting "Artist - Song" titles when no artist metadata exists.
* @this {import('./Player.mjs').Player}
* @param {object} current - Queue track.
* @returns {{artist: string, title: string, candidates: string[]}}
*/
_buildLyricsQuery(current) {
const rawTitle = Utils.cleanTitle(current.title ?? "");
let artist = Utils.cleanArtistName(
current.lastfm?.artist
|| current.artists?.[0]?.name
|| current.author?.name
|| ""
);
let title = rawTitle;
if (artist) {
const prefix = artist + " - ";
if (title.toLowerCase().startsWith(prefix.toLowerCase())) {
title = title.slice(prefix.length).trim();
}
} else {
const split = rawTitle.match(/^(.+?)\s+-\s+(.+)$/);
if (split) {
artist = Utils.cleanArtistName(split[1]);
title = split[2].trim();
}
}
const candidates = [];
if (artist && title) candidates.push(`${artist} ${title}`);
if (title && !candidates.length) candidates.push(title);
return { artist, title, candidates };
},
/**
* @private Query LRCLIB for lyrics and return only a verified match.
* @this {import('./Player.mjs').Player}
* @param {{artist: string, title: string}} query
* @returns {Promise<{text: string, source: string, synced: boolean, lines: Array}|null>}
*/
async _fetchVerifiedLyrics(query) {
const durationMs = this._getTrackDurationMs(this.queue.getCurrent());
const durationSec = Math.round(durationMs / 1000);
const headers = { "User-Agent": "FluxerBot/1.0 (music bot lyrics lookup)" };
const urls = [];
if (query.artist) {
const p1 = new URLSearchParams({ track_name: query.title, artist_name: query.artist });
urls.push("https://lrclib.net/api/search?" + p1.toString());
}
const p2 = new URLSearchParams({ q: query.candidates.join(" ") || query.title });
urls.push("https://lrclib.net/api/search?" + p2.toString());
let candidates = [];
for (const url of urls) {
const res = await fetch(url, { headers, signal: AbortSignal.timeout(10_000) });
if (!res.ok) continue;
const body = await res.json();
if (Array.isArray(body) && body.length) {
candidates = body;
break;
}
}
if (!candidates.length) return null;
const best = Utils.pickBestLyrics(candidates, {
title: query.title,
artist: query.artist,
durationSec,
});
if (!best) return null;
if (best.instrumental) {
return { text: "♪", source: "LRCLIB", synced: false, lines: [] };
}
const parsed = Utils.parseSyncedLyrics(best.syncedLyrics);
if (parsed) {
return {
text: parsed.map(l => l.text).join("\n"),
source: "LRCLIB",
synced: true,
lines: parsed,
};
}
if (best.plainLyrics) {
const text = String(best.plainLyrics).trim();
return {
text,
source: "LRCLIB",
synced: false,
lines: text.split("\n").map(l => ({ text: l })),
};
}
return null;
},
}; };
export default PlaybackMixin; export default PlaybackMixin;
+92
View File
@@ -419,4 +419,96 @@ export class Utils {
.trim() .trim()
.toLowerCase(); .toLowerCase();
} }
/**
* Clean a channel/artist name for lyrics lookups: YouTube auto-generated
* channels append " - Topic", labels upload as "ArtistVEVO" or
* "Artist - Official Audio" — none of which match a lyrics provider index.
* @param {string} name - Raw artist or channel name.
* @returns {string} Cleaned artist name ("" when nothing left).
*/
static cleanArtistName(name) {
if (!name || typeof name !== "string") return "";
return name
.replace(/\s*-\s*topic$/i, "")
.replace(/vevo$/i, "")
.replace(/\s*-\s*(?:official|topic|subject).*$/i, "")
.replace(/\s*\((?:official|topic).*\)$/i, "")
.replace(/\s{2,}/g, " ")
.trim();
}
/**
* Parse LRC-format synced lyrics ("[mm:ss.xx] line text") into structured
* lines. Returns null when the input holds no timestamped lines at all.
* @param {string} raw - Raw LRC text (one lyric line per source line).
* @returns {Array<{startTimeMs: number, text: string}>|null}
*/
static parseSyncedLyrics(raw) {
if (!raw || typeof raw !== "string") return null;
const lines = [];
for (const line of raw.split("\n")) {
const m = line.match(/^\s*\[(\d+):(\d+)(?:[.:](\d{1,3}))?\]\s*(.*)$/);
if (!m) continue;
const frac = m[3] ? parseInt(m[3].padEnd(3, "0"), 10) : 0;
const startTimeMs = parseInt(m[1], 10) * 60_000 + parseInt(m[2], 10) * 1000 + frac;
lines.push({ startTimeMs, text: (m[4] || "").trim() });
}
return lines.length ? lines : null;
}
/**
* Pick the correct lyrics candidate from a provider result list by scoring
* title, artist and duration agreement. Returns null when no candidate is a
* confident match — wrong lyrics are worse than no lyrics.
* @param {Array<{trackName: string, artistName: string, duration?: number|null}>} candidates
* @param {object} ref - Reference track: { title, artist, durationSec }.
* @returns {object|null} The best-scoring candidate, or null.
*/
static pickBestLyrics(candidates, ref) {
if (!Array.isArray(candidates) || candidates.length === 0) return null;
const refTitle = this.normalizeText(ref?.title);
const refArtist = this.normalizeText(ref?.artist);
const refDur = Number(ref?.durationSec) || 0;
if (!refTitle) return null;
let best = null;
let bestScore = 0;
for (const c of candidates) {
if (!c || typeof c !== "object") continue;
const cTitle = this.normalizeText(c.trackName);
const cArtist = this.normalizeText(c.artistName);
if (!cTitle) continue;
let score = 0;
if (cTitle === refTitle) {
score += 3;
} else if (cTitle.includes(refTitle) || refTitle.includes(cTitle)) {
score += 1.5;
} else {
continue;
}
if (refArtist) {
if (cArtist === refArtist) score += 2;
else if (cArtist.includes(refArtist) || refArtist.includes(cArtist)) score += 1;
}
const dur = Number(c.duration) || 0;
if (refDur > 0 && dur > 0) {
const diff = Math.abs(dur - refDur);
if (diff <= 3) score += 2;
else if (diff <= 8) score += 1;
}
if (score > bestScore) {
bestScore = score;
best = c;
}
}
return bestScore >= 4 ? best : null;
}
} }
+1
View File
@@ -335,6 +335,7 @@
"error": "❌ خطأ: {{error}}", "error": "❌ خطأ: {{error}}",
"syncedBadge": " ⏱️ متزامن", "syncedBadge": " ⏱️ متزامن",
"nodeLinkFooter": "NodeLink • {{lines}} سطر", "nodeLinkFooter": "NodeLink • {{lines}} سطر",
"sourceFooter": "{{source}} • {{lines}} سطر",
"controlsExpired": "⌛ انتهت صلاحية عناصر التحكم • NodeLink • {{lines}} سطر", "controlsExpired": "⌛ انتهت صلاحية عناصر التحكم • NodeLink • {{lines}} سطر",
"sessionClosed": "تم إغلاق الجلسة • NodeLink • {{lines}} سطر" "sessionClosed": "تم إغلاق الجلسة • NodeLink • {{lines}} سطر"
}, },
+1
View File
@@ -335,6 +335,7 @@
"error": "❌ هەڵە: {{error}}", "error": "❌ هەڵە: {{error}}",
"syncedBadge": " ⏱️ هاوئاهەنگ", "syncedBadge": " ⏱️ هاوئاهەنگ",
"nodeLinkFooter": "NodeLink • {{lines}} هێڵ", "nodeLinkFooter": "NodeLink • {{lines}} هێڵ",
"sourceFooter": "{{source}} • {{lines}} هێڵ",
"controlsExpired": "⌛ کۆنتڕۆڵەکان بەسەرچوون • NodeLink • {{lines}} هێڵ", "controlsExpired": "⌛ کۆنتڕۆڵەکان بەسەرچوون • NodeLink • {{lines}} هێڵ",
"sessionClosed": "دانیشتن داخرا • NodeLink • {{lines}} هێڵ" "sessionClosed": "دانیشتن داخرا • NodeLink • {{lines}} هێڵ"
}, },
+1
View File
@@ -335,6 +335,7 @@
"error": "❌ Fehler: {{error}}", "error": "❌ Fehler: {{error}}",
"syncedBadge": " ⏱️ Synchronisiert", "syncedBadge": " ⏱️ Synchronisiert",
"nodeLinkFooter": "NodeLink • {{lines}} Zeilen", "nodeLinkFooter": "NodeLink • {{lines}} Zeilen",
"sourceFooter": "{{source}} • {{lines}} Zeilen",
"controlsExpired": "⌛ Steuerung abgelaufen • NodeLink • {{lines}} Zeilen", "controlsExpired": "⌛ Steuerung abgelaufen • NodeLink • {{lines}} Zeilen",
"sessionClosed": "Sitzung geschlossen • NodeLink • {{lines}} Zeilen" "sessionClosed": "Sitzung geschlossen • NodeLink • {{lines}} Zeilen"
}, },
+1
View File
@@ -444,6 +444,7 @@
"error": "❌ Error: {{error}}", "error": "❌ Error: {{error}}",
"syncedBadge": " ⏱️ Synced", "syncedBadge": " ⏱️ Synced",
"nodeLinkFooter": "NodeLink • {{lines}} lines", "nodeLinkFooter": "NodeLink • {{lines}} lines",
"sourceFooter": "{{source}} • {{lines}} lines",
"controlsExpired": "⌛ Controls expired • NodeLink • {{lines}} lines", "controlsExpired": "⌛ Controls expired • NodeLink • {{lines}} lines",
"sessionClosed": "Session closed • NodeLink • {{lines}} lines" "sessionClosed": "Session closed • NodeLink • {{lines}} lines"
}, },
+1
View File
@@ -335,6 +335,7 @@
"error": "❌ Erro: {{error}}", "error": "❌ Erro: {{error}}",
"syncedBadge": " ⏱️ Sincronizado", "syncedBadge": " ⏱️ Sincronizado",
"nodeLinkFooter": "NodeLink • {{lines}} linhas", "nodeLinkFooter": "NodeLink • {{lines}} linhas",
"sourceFooter": "{{source}} • {{lines}} linhas",
"controlsExpired": "⌛ Controles expirados • NodeLink • {{lines}} linhas", "controlsExpired": "⌛ Controles expirados • NodeLink • {{lines}} linhas",
"sessionClosed": "Sessão encerrada • NodeLink • {{lines}} linhas" "sessionClosed": "Sessão encerrada • NodeLink • {{lines}} linhas"
}, },
+1
View File
@@ -441,6 +441,7 @@
"error": "❌ Hata: {{error}}", "error": "❌ Hata: {{error}}",
"syncedBadge": " ⏱️ Senkronize", "syncedBadge": " ⏱️ Senkronize",
"nodeLinkFooter": "NodeLink • {{lines}} satır", "nodeLinkFooter": "NodeLink • {{lines}} satır",
"sourceFooter": "{{source}} • {{lines}} satır",
"controlsExpired": "⌛ Kontrollerin süresi doldu • NodeLink • {{lines}} satır", "controlsExpired": "⌛ Kontrollerin süresi doldu • NodeLink • {{lines}} satır",
"sessionClosed": "Oturum kapatıldı • NodeLink • {{lines}} satır" "sessionClosed": "Oturum kapatıldı • NodeLink • {{lines}} satır"
}, },