diff --git a/commands/lyrics.mjs b/commands/lyrics.mjs index 7d33a22..8687cf0 100644 --- a/commands/lyrics.mjs +++ b/commands/lyrics.mjs @@ -124,7 +124,7 @@ export async function run(message) { .setColor(getGlobalColor()) .setTitle(`🎵 ${Utils.truncate(displayTitle, 50)}`) .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); return message.reply({ embeds: [singleEmbed] }); } @@ -150,7 +150,7 @@ export async function run(message) { .setDescription(desc.slice(0, MAX_DESC)) .setFooter({ text: expired ? 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); return { embeds: [b] }; }; diff --git a/commands/player/lyrics.mjs b/commands/player/lyrics.mjs index 7f3d490..ce7eb7d 100644 --- a/commands/player/lyrics.mjs +++ b/commands/player/lyrics.mjs @@ -82,11 +82,12 @@ export async function openLyricsViewer(bot, msg, player, refresh, session) { player.queue.getCurrent()?.title?.replace(/\(Official.*?\)/gi, '').trim() ?? '', 50 ); + const lyricsSource = lyricsResult.source || "Lyrics"; const footerText = closed - ? `👋 Lyrics closed • NodeLink • ${totalLines} lines` + ? `👋 Lyrics closed • ${lyricsSource} • ${totalLines} lines` : expired - ? `⌛ Controls expired • NodeLink • ${totalLines} lines` - : `NodeLink • ${totalLines} lines total${lyricsResult.synced ? ' • Synced' : ''}`; + ? `⌛ Controls expired • ${lyricsSource} • ${totalLines} lines` + : `${lyricsSource} • ${totalLines} lines total${lyricsResult.synced ? ' • Synced' : ''}`; const desc = [ `**${title}**${syncBadge} • Page ${pageIdx + 1}/${totalPages}`, ``, diff --git a/src/music/player/PlaybackMixin.mjs b/src/music/player/PlaybackMixin.mjs index 1901f05..a7ca116 100644 --- a/src/music/player/PlaybackMixin.mjs +++ b/src/music/player/PlaybackMixin.mjs @@ -624,8 +624,11 @@ const PlaybackMixin = { }, /** - * @async Fetch lyrics for the currently playing track via the Lavalink - * REST API. + * @async Fetch lyrics for the currently playing track. + * 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} * @returns {Promise<{text: string, source: string, synced: boolean, lines: Array}|null>} */ @@ -633,18 +636,21 @@ const PlaybackMixin = { const current = this.queue.getCurrent(); if (!current) return null; + const query = this._buildLyricsQuery(current); + if (!query.title) return null; + + try { + const result = await this._fetchVerifiedLyrics(query); + if (result) return result; + } catch (e) { + logger.player(`[Lyrics] LRCLIB lookup failed: ${e.message}`); + } + const node = this._lavalink?.getNode?.() ?? null; - - if (node) { + if (node && query.candidates.length > 0) { try { - const searchQuery = current.artists?.[0]?.name - ? `${current.title} ${current.artists[0].name}` - : current.title; - - const path = current.encoded - ? `/loadlyrics?encodedTrack=${encodeURIComponent(current.encoded)}` - : `/loadlyrics?identifier=${encodeURIComponent(searchQuery)}`; - + const searchQuery = query.candidates.join(" "); + const path = `/loadlyrics?identifier=${encodeURIComponent(searchQuery)}`; const results = await node.request(path); if (results?.data?.lines?.length) { @@ -662,6 +668,107 @@ const PlaybackMixin = { 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; diff --git a/src/utils/Utils.mjs b/src/utils/Utils.mjs index 62a0a06..63c2190 100644 --- a/src/utils/Utils.mjs +++ b/src/utils/Utils.mjs @@ -419,4 +419,96 @@ export class Utils { .trim() .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; + } } diff --git a/storage/locales/bot/ar-SA.json b/storage/locales/bot/ar-SA.json index 5c8787d..5e341be 100644 --- a/storage/locales/bot/ar-SA.json +++ b/storage/locales/bot/ar-SA.json @@ -335,6 +335,7 @@ "error": "❌ خطأ: {{error}}", "syncedBadge": " ⏱️ متزامن", "nodeLinkFooter": "NodeLink • {{lines}} سطر", + "sourceFooter": "{{source}} • {{lines}} سطر", "controlsExpired": "⌛ انتهت صلاحية عناصر التحكم • NodeLink • {{lines}} سطر", "sessionClosed": "تم إغلاق الجلسة • NodeLink • {{lines}} سطر" }, diff --git a/storage/locales/bot/ckb.json b/storage/locales/bot/ckb.json index a6c88b3..045c3b3 100644 --- a/storage/locales/bot/ckb.json +++ b/storage/locales/bot/ckb.json @@ -335,6 +335,7 @@ "error": "❌ هەڵە: {{error}}", "syncedBadge": " ⏱️ هاوئاهەنگ", "nodeLinkFooter": "NodeLink • {{lines}} هێڵ", + "sourceFooter": "{{source}} • {{lines}} هێڵ", "controlsExpired": "⌛ کۆنتڕۆڵەکان بەسەرچوون • NodeLink • {{lines}} هێڵ", "sessionClosed": "دانیشتن داخرا • NodeLink • {{lines}} هێڵ" }, diff --git a/storage/locales/bot/de-DE.json b/storage/locales/bot/de-DE.json index faf7b11..c9834a0 100644 --- a/storage/locales/bot/de-DE.json +++ b/storage/locales/bot/de-DE.json @@ -335,6 +335,7 @@ "error": "❌ Fehler: {{error}}", "syncedBadge": " ⏱️ Synchronisiert", "nodeLinkFooter": "NodeLink • {{lines}} Zeilen", + "sourceFooter": "{{source}} • {{lines}} Zeilen", "controlsExpired": "⌛ Steuerung abgelaufen • NodeLink • {{lines}} Zeilen", "sessionClosed": "Sitzung geschlossen • NodeLink • {{lines}} Zeilen" }, diff --git a/storage/locales/bot/en.json b/storage/locales/bot/en.json index a7879b6..d91ceeb 100644 --- a/storage/locales/bot/en.json +++ b/storage/locales/bot/en.json @@ -444,6 +444,7 @@ "error": "❌ Error: {{error}}", "syncedBadge": " ⏱️ Synced", "nodeLinkFooter": "NodeLink • {{lines}} lines", + "sourceFooter": "{{source}} • {{lines}} lines", "controlsExpired": "⌛ Controls expired • NodeLink • {{lines}} lines", "sessionClosed": "Session closed • NodeLink • {{lines}} lines" }, diff --git a/storage/locales/bot/pt-BR.json b/storage/locales/bot/pt-BR.json index 47a887a..a635525 100644 --- a/storage/locales/bot/pt-BR.json +++ b/storage/locales/bot/pt-BR.json @@ -335,6 +335,7 @@ "error": "❌ Erro: {{error}}", "syncedBadge": " ⏱️ Sincronizado", "nodeLinkFooter": "NodeLink • {{lines}} linhas", + "sourceFooter": "{{source}} • {{lines}} linhas", "controlsExpired": "⌛ Controles expirados • NodeLink • {{lines}} linhas", "sessionClosed": "Sessão encerrada • NodeLink • {{lines}} linhas" }, diff --git a/storage/locales/bot/tr.json b/storage/locales/bot/tr.json index ba539f0..5bf3750 100644 --- a/storage/locales/bot/tr.json +++ b/storage/locales/bot/tr.json @@ -441,6 +441,7 @@ "error": "❌ Hata: {{error}}", "syncedBadge": " ⏱️ Senkronize", "nodeLinkFooter": "NodeLink • {{lines}} satır", + "sourceFooter": "{{source}} • {{lines}} satır", "controlsExpired": "⌛ Kontrollerin süresi doldu • NodeLink • {{lines}} satır", "sessionClosed": "Oturum kapatıldı • NodeLink • {{lines}} satır" },