Mulberry/App/Services/Lyrics.swift
2026-10-27 19:30:49 -05:00

240 lines
12 KiB
Swift

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import Foundation
/// Synced/plain lyrics from LRCLIB, NetEase, .lrc files and embedded tags (Android Lyrics.java).
enum Lyrics {
struct Line: Hashable {
let t: Double // seconds, -1 when unsynced
let text: String
}
struct Result {
var lines: [Line] = []
var synced = false
var source = ""
var message = ""
var raw = ""
}
private static let ts = try! NSRegularExpression(pattern: #"\[(\d+):(\d+(?:[.:]\d+)?)\]"#)
private static let credit = try! NSRegularExpression(
pattern: #"^\s*\[[^\]]*\]\s*(作词|作曲|编曲|制作人|监制|混音|母带|词|曲|Lyricist|Lyrics by|Composer|Composed by|Arranger|Producer|Written by)\s*[::].*"#,
options: .caseInsensitive)
private static let neHeaders = [
"Referer": "https://music.163.com/",
"User-Agent": "Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X) AppleWebKit/605.1.15 Mobile/15E148",
]
static func isSynced(_ s: String) -> Bool {
ts.firstMatch(in: s, range: NSRange(s.startIndex..., in: s)) != nil
}
static func parse(_ text: String, plain: Bool) -> Result {
var r = Result()
r.raw = text
var offset = 0.0
if let m = try? NSRegularExpression(pattern: #"\[offset:\s*([-+]?\d+)\]"#, options: .caseInsensitive)
.firstMatch(in: text, range: NSRange(text.startIndex..., in: text)),
let g = Range(m.range(at: 1), in: text) {
offset = (Double(text[g]) ?? 0) / 1000
}
var lines: [Line] = []
var synced = false
let word = try! NSRegularExpression(pattern: #"<\d+:\d+(?:\.\d+)?>"#)
let tag = try! NSRegularExpression(pattern: #"^\[[a-zA-Z]+:.*\]$"#)
for raw in text.components(separatedBy: .newlines) {
let ns = NSRange(raw.startIndex..., in: raw)
var times: [Double] = []
for m in ts.matches(in: raw, range: ns) {
guard let a = Range(m.range(at: 1), in: raw), let b = Range(m.range(at: 2), in: raw) else { continue }
let sec = Double(raw[b].replacingOccurrences(of: ":", with: ".")) ?? 0
times.append((Double(raw[a]) ?? 0) * 60 + sec - offset)
}
var clean = ts.stringByReplacingMatches(in: raw, range: ns, withTemplate: "")
clean = word.stringByReplacingMatches(in: clean, range: NSRange(clean.startIndex..., in: clean), withTemplate: "")
clean = clean.trimmingCharacters(in: .whitespaces)
if !times.isEmpty {
synced = true
for t in times { lines.append(Line(t: max(0, t), text: clean)) }
} else {
let tr = raw.trimmingCharacters(in: .whitespaces)
if tag.firstMatch(in: tr, range: NSRange(tr.startIndex..., in: tr)) == nil {
lines.append(Line(t: -1, text: tr))
}
}
}
if synced { lines = lines.filter { $0.t >= 0 }.sorted { $0.t < $1.t } }
if plain && synced {
lines = lines.map { Line(t: -1, text: $0.text) }
synced = false
}
while let f = lines.first, f.text.isEmpty, !synced { lines.removeFirst() }
r.lines = lines
r.synced = synced
return r
}
static func lineAt(_ lines: [Line], _ t: Double) -> Int {
var lo = 0, hi = lines.count - 1, ans = -1
while lo <= hi {
let mid = (lo + hi) / 2
if lines[mid].t <= t + 0.15 { ans = mid; lo = mid + 1 } else { hi = mid - 1 }
}
return ans
}
static func clean(_ s: String) -> String {
s.replacingOccurrences(of: #"\s*[\(\[](feat|ft|with|remaster|live|explicit|bonus)[^\)\]]*[\)\]]"#,
with: "", options: [.regularExpression, .caseInsensitive])
.trimmingCharacters(in: .whitespaces)
}
static func norm(_ s: String) -> String {
Library.norm(s).components(separatedBy: CharacterSet.alphanumerics.inverted).joined()
}
// MARK: Providers
static func lrclib(_ s: Song) throws -> String {
var q: [(String, String)] = [("artist_name", s.displayArtist), ("track_name", clean(s.displayTitle))]
var full = q
if !s.album.isEmpty { full.append(("album_name", s.album)) }
if s.duration > 0 { full.append(("duration", String(Int(s.duration.rounded())))) }
if let o = try? Net.json("https://lrclib.net/api/get?" + Net.query(full)) as? [String: Any], !o.isEmpty {
if (o["instrumental"] as? Bool) == true { return "[instrumental]" }
var l = o.str("syncedLyrics")
if l.isEmpty { l = o.str("plainLyrics") }
if !l.isEmpty { return l }
}
q = [("artist_name", s.displayArtist), ("track_name", clean(s.displayTitle))]
guard let arr = try Net.json("https://lrclib.net/api/search?" + Net.query(q)) as? [[String: Any]] else { return "" }
var fallback: [String: Any]?
for o in arr {
let d = o.num("duration")
guard s.duration <= 0 || d <= 0 || abs(d - s.duration) <= 6 else { continue }
if !o.str("syncedLyrics").isEmpty { return o.str("syncedLyrics") }
if fallback == nil { fallback = o }
}
return fallback?.str("plainLyrics") ?? ""
}
static func netease(_ s: String, artist: String, duration: Double) throws -> String {
let term = (clean(s) + " " + artist).trimmingCharacters(in: .whitespaces)
guard let res = (try Net.json("https://music.163.com/api/cloudsearch/pc?type=1&offset=0&limit=10&s=" + Net.enc(term),
headers: neHeaders) as? [String: Any])?.obj("result") else { return "" }
var best: [String: Any]?
var bestScore = -1e9
for o in res.arr("songs") {
var score = 0.0
let ar = norm(o.arr("ar").map { $0.str("name") }.joined(separator: " "))
let want = norm(artist)
if !want.isEmpty && (ar.contains(want) || want.contains(ar)) { score += 50 }
if norm(clean(s)) == norm(clean(o.str("name"))) { score += 30 }
let dt = o.num("dt") / 1000
if duration > 0 && dt > 0 { score -= min(40, abs(dt - duration) * 4) }
if score > bestScore { bestScore = score; best = o }
}
guard let b = best, bestScore >= 0 else { return "" }
let id = Int(b.num("id"))
let lj = try Net.json("https://music.163.com/api/song/lyric?lv=1&kv=1&tv=-1&id=\(id)", headers: neHeaders) as? [String: Any]
let lrc = lj?.obj("lrc")?.str("lyric") ?? ""
return lrc.components(separatedBy: "\n").filter { line in
credit.firstMatch(in: line, range: NSRange(line.startIndex..., in: line)) == nil
}.joined(separator: "\n").trimmingCharacters(in: .whitespacesAndNewlines)
}
static func local(_ s: Song) -> String {
guard !s.isStream else { return "" }
let base = s.url.deletingPathExtension()
let candidates = [base.appendingPathExtension("lrc"), base.appendingPathExtension("LRC"),
base.appendingPathExtension("txt"),
Library.root.appendingPathComponent("Lyrics").appendingPathComponent(base.lastPathComponent + ".lrc"),
Library.root.appendingPathComponent("Lyrics")
.appendingPathComponent("\(s.displayArtist) - \(s.displayTitle).lrc")]
for c in candidates {
if let d = try? Data(contentsOf: c) {
return String(data: d, encoding: .utf8) ?? String(data: d, encoding: .isoLatin1) ?? ""
}
}
return TagReader.read(s.url).lyrics
}
// MARK: Cache
static func cacheFile(_ s: Song, _ src: String) -> URL {
let dir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("lyrics")
try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)
let key = "\(src)|\(s.displayArtist)|\(s.displayTitle)|\(s.album)".data(using: .utf8)!.base64EncodedString()
.replacingOccurrences(of: "/", with: "_").prefix(120)
return dir.appendingPathComponent(String(key) + ".txt")
}
static func readCache(_ s: Song, _ src: String) -> String? { try? String(contentsOf: cacheFile(s, src), encoding: .utf8) }
static func writeCache(_ s: Song, _ src: String, _ text: String) { try? text.write(to: cacheFile(s, src), atomically: true, encoding: .utf8) }
static func clearCache(_ s: Song) {
for src in ["auto", "lrclib", "netease"] { try? FileManager.default.removeItem(at: cacheFile(s, src)) }
}
static func clearAllCache() {
let dir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("lyrics")
try? FileManager.default.removeItem(at: dir)
}
// MARK: Loading (Auto — synced first, local last)
static func load(_ s: Song, forceOnline: Bool = false) -> Result {
let p = Prefs.shared
let source = p.lyricsSource
let plain = p.lyricsPlain
let online = p.onlineLyrics || forceOnline
if source == "off" { return Result(message: "Lyrics are turned off in Settings.") }
var text = ""
var label = ""
var message = ""
switch source {
case "local":
text = local(s); label = "Local .lrc"
if text.isEmpty { message = "No .lrc file or embedded lyrics for this song." }
case "lrclib", "netease":
label = source == "lrclib" ? "LRCLIB" : "NetEase"
if let c = forceOnline ? nil : readCache(s, source) {
text = c
} else if online {
do {
text = source == "lrclib" ? try lrclib(s) : try netease(s.displayTitle, artist: s.displayArtist, duration: s.duration)
writeCache(s, source, text)
} catch { message = "Couldn't reach the lyrics service" }
}
if text.isEmpty && message.isEmpty { message = "\(label) has no lyrics for this song." }
default:
if let c = forceOnline ? nil : readCache(s, "auto") {
if let nl = c.firstIndex(of: "\n") {
label = String(c[..<nl]); text = String(c[c.index(after: nl)...])
}
} else {
let loc = local(s)
if isSynced(loc) {
text = loc; label = "Local .lrc"
} else if online && !s.isStream {
var reached = false
if let l = try? lrclib(s) { reached = true; if isSynced(l) || l == "[instrumental]" { text = l; label = "LRCLIB" } else if !l.isEmpty { text = l; label = "LRCLIB" } }
if !isSynced(text), let n = try? netease(s.displayTitle, artist: s.displayArtist, duration: s.duration) {
reached = true
if isSynced(n) || text.isEmpty { if !n.isEmpty { text = n; label = "NetEase" } }
}
if !isSynced(text) && !loc.isEmpty { text = loc; label = "Embedded" }
if reached { writeCache(s, "auto", label + "\n" + text) }
else if text.isEmpty { message = "Couldn't reach the lyrics services" }
} else if !loc.isEmpty {
text = loc; label = "Embedded"
}
}
if text.isEmpty && message.isEmpty { message = "No lyrics found for this song." }
}
if text == "[instrumental]" { return Result(lines: [Line(t: -1, text: "♪ Instrumental")], source: label) }
var r = parse(text, plain: plain)
r.source = label
r.message = message
return r
}
}