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

No files matched your search

+119 -12
View File
@@ -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;
+92
View File
@@ -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;
}
}