geesawra.industries/hydraulophone
An unofficial YouTube Music app for iPhone, iPad, and Mac.
0
0
import Foundation
public enum LRCLibLyricsError: Error, LocalizedError, Equatable, Sendable {
case invalidResponse
case httpStatus(Int)
case rateLimited
public var errorDescription: String? {
switch self {
case .invalidResponse:
return "The lyrics service returned an unexpected response."
case .httpStatus:
return "The lyrics service is unavailable right now."
case .rateLimited:
return "The lyrics service is busy. Try again later."
}
}
}
/// A bounded exact-then-search LRCLIB lookup. The default session is ephemeral and
/// carries no YouTube cookies or authorization values. Callers must gate this
/// provider behind the app's authenticated browsing boundary.
public struct LRCLibLyricsProvider: LyricsProviding {
private static let sharedThrottle = LRCLibRequestThrottle()
private let session: URLSession
private let throttle: LRCLibRequestThrottle
public init(session: URLSession? = nil) {
self.session = session ?? Self.ephemeralSession()
throttle = Self.sharedThrottle
}
// Isolated request pacing lets URLProtocol tests avoid cross-test timing.
init(session: URLSession, throttle: LRCLibRequestThrottle) {
self.session = session
self.throttle = throttle
}
public func lyrics(for song: Song) async throws -> SongLyrics? {
try Task.checkCancellation()
guard let exactRequest = Self.request(for: song, search: false) else { return nil }
let exact: SongLyrics?
if let data = try await fetch(exactRequest) {
guard let record = try? JSONDecoder().decode(LRCLibRecord.self, from: data) else {
throw LRCLibLyricsError.invalidResponse
}
exact = Self.matches(record, song: song) ? Self.lyrics(from: record) : nil
} else {
exact = nil
}
if exact?.isSynchronized == true { return exact }
try Task.checkCancellation()
guard let searchRequest = Self.request(for: song, search: true) else { return exact }
let data: Data
do {
guard let fetched = try await fetch(searchRequest) else { return exact }
data = fetched
} catch {
if error is CancellationError || (error as? URLError)?.code == .cancelled {
throw CancellationError()
}
try Task.checkCancellation()
if let exact { return exact }
throw error
}
let records: [LRCLibRecord]
do {
records = try JSONDecoder().decode([LRCLibRecord].self, from: data)
} catch {
if let exact { return exact }
throw LRCLibLyricsError.invalidResponse
}
let candidates = records.prefix(50).filter { Self.matchesSearch($0, song: song) }
let ordered = candidates.sorted { left, right in
let leftAlbum = Self.albumMatches(left, song: song)
let rightAlbum = Self.albumMatches(right, song: song)
if leftAlbum != rightAlbum { return leftAlbum }
if let duration = Self.durationSeconds(song.durationText) {
let leftGap = abs((left.duration ?? .infinity) - Double(duration))
let rightGap = abs((right.duration ?? .infinity) - Double(duration))
return leftGap < rightGap
}
return false
}
var firstPlain: SongLyrics?
for record in ordered {
guard let lyrics = Self.lyrics(from: record) else { continue }
if lyrics.isSynchronized { return lyrics }
if firstPlain == nil { firstPlain = lyrics }
}
return exact ?? firstPlain
}
private func fetch(_ request: URLRequest) async throws -> Data? {
try await throttle.beforeRequest()
let (data, response) = try await session.data(
for: request, delegate: LRCLibNoRedirectDelegate())
try Task.checkCancellation()
guard let response = response as? HTTPURLResponse else {
throw LRCLibLyricsError.invalidResponse
}
switch response.statusCode {
case 200:
guard data.count <= 512 * 1_024 else { throw LRCLibLyricsError.invalidResponse }
return data
case 404:
return nil
case 429:
await throttle.noteRateLimit(response)
throw LRCLibLyricsError.rateLimited
default:
throw LRCLibLyricsError.httpStatus(response.statusCode)
}
}
private static func request(for song: Song, search: Bool) -> URLRequest? {
let title = song.title.trimmingCharacters(in: .whitespacesAndNewlines)
let artist = song.artist.trimmingCharacters(in: .whitespacesAndNewlines)
guard !title.isEmpty, !artist.isEmpty else { return nil }
var components = URLComponents()
components.scheme = "https"
components.host = "lrclib.net"
components.path = search ? "/api/search" : "/api/get"
var query = [
URLQueryItem(name: "track_name", value: title),
URLQueryItem(name: "artist_name", value: artist),
]
if !search {
if let album = song.album?.trimmingCharacters(in: .whitespacesAndNewlines),
!album.isEmpty
{
query.append(URLQueryItem(name: "album_name", value: album))
}
if let duration = durationSeconds(song.durationText) {
query.append(URLQueryItem(name: "duration", value: String(duration)))
}
}
components.queryItems = query
guard let url = components.url, url.scheme == "https", url.host == "lrclib.net" else {
return nil
}
var request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData)
request.httpMethod = "GET"
request.timeoutInterval = 8
request.httpShouldHandleCookies = false
request.setValue("application/json", forHTTPHeaderField: "Accept")
request.setValue("Hydraulophone/0.1", forHTTPHeaderField: "User-Agent")
return request
}
private static func matches(_ record: LRCLibRecord, song: Song) -> Bool {
guard normalized(record.trackName) == normalized(song.title),
normalized(record.artistName) == normalized(song.artist)
else { return false }
if let album = song.album, !album.trimmingCharacters(in: .whitespaces).isEmpty {
guard let returnedAlbum = record.albumName,
normalized(returnedAlbum) == normalized(album)
else { return false }
}
if let duration = durationSeconds(song.durationText) {
guard let returnedDuration = record.duration, returnedDuration.isFinite,
abs(returnedDuration - Double(duration)) <= 2
else { return false }
}
return true
}
private static func matchesSearch(_ record: LRCLibRecord, song: Song) -> Bool {
guard record.instrumental != true,
normalized(record.trackName) == normalized(song.title),
normalized(record.artistName) == normalized(song.artist)
else { return false }
if let duration = durationSeconds(song.durationText) {
guard let returnedDuration = record.duration, returnedDuration.isFinite,
abs(returnedDuration - Double(duration)) <= 2
else { return false }
} else if !albumMatches(record, song: song) {
// Without duration, a different album can represent a different recording.
return false
}
return true
}
private static func albumMatches(_ record: LRCLibRecord, song: Song) -> Bool {
guard let album = song.album, !album.trimmingCharacters(in: .whitespaces).isEmpty else {
return true
}
guard let returnedAlbum = record.albumName else { return false }
return normalized(returnedAlbum) == normalized(album)
}
private static func lyrics(from record: LRCLibRecord) -> SongLyrics? {
guard record.instrumental != true else { return nil }
if let synced = record.syncedLyrics, !synced.isEmpty {
let lines = LRCParser.timedLines(from: synced)
if !lines.isEmpty { return SongLyrics(lines: lines, source: "LRCLIB") }
}
if let plain = record.plainLyrics, !plain.isEmpty {
let lines = LRCParser.plainLines(from: plain)
if !lines.isEmpty { return SongLyrics(lines: lines, source: "LRCLIB") }
}
return nil
}
private static func normalized(_ text: String) -> String {
text.folding(
options: [.caseInsensitive, .diacriticInsensitive], locale: Locale(identifier: "en_US_POSIX")
)
.split(whereSeparator: \.isWhitespace)
.joined(separator: " ")
}
private static func durationSeconds(_ durationText: String?) -> Int? {
guard let durationText else { return nil }
let parts = durationText.split(separator: ":", omittingEmptySubsequences: false)
let values = parts.compactMap { Int($0) }
guard (2...3).contains(parts.count),
parts.allSatisfy({ !$0.isEmpty && $0.allSatisfy(\.isNumber) }),
values.count == parts.count,
values.allSatisfy({ (0...3_600).contains($0) }),
values.dropFirst().allSatisfy({ $0 < 60 })
else { return nil }
var seconds = 0
for value in values {
let product = seconds.multipliedReportingOverflow(by: 60)
guard !product.overflow else { return nil }
let sum = product.partialValue.addingReportingOverflow(value)
guard !sum.overflow else { return nil }
seconds = sum.partialValue
}
return (1...3_600).contains(seconds) ? seconds : nil
}
private static func ephemeralSession() -> URLSession {
let configuration = URLSessionConfiguration.ephemeral
configuration.httpShouldSetCookies = false
configuration.httpCookieStorage = nil
configuration.urlCache = nil
configuration.requestCachePolicy = .reloadIgnoringLocalCacheData
configuration.timeoutIntervalForRequest = 8
configuration.timeoutIntervalForResource = 12
configuration.waitsForConnectivity = false
return URLSession(configuration: configuration)
}
}
private struct LRCLibRecord: Decodable {
let trackName: String
let artistName: String
let albumName: String?
let duration: Double?
let instrumental: Bool?
let plainLyrics: String?
let syncedLyrics: String?
}
/// Never follow a redirect from the fixed LRCLIB endpoint, including when a
/// caller supplies a custom URLSession for tests.
private final class LRCLibNoRedirectDelegate: NSObject, URLSessionTaskDelegate, @unchecked Sendable
{
func urlSession(
_ session: URLSession, task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void
) {
completionHandler(nil)
}
}
actor LRCLibRequestThrottle {
private var nextRequestAt = Date.distantPast
private var pausedUntil = Date.distantPast
func beforeRequest() async throws {
let now = Date()
guard now >= pausedUntil else { throw LRCLibLyricsError.rateLimited }
let reservedAt = max(now, nextRequestAt)
nextRequestAt = reservedAt.addingTimeInterval(0.25)
let delay = reservedAt.timeIntervalSince(now)
if delay > 0 {
try await Task.sleep(for: .seconds(delay))
}
try Task.checkCancellation()
guard Date() >= pausedUntil else { throw LRCLibLyricsError.rateLimited }
}
func noteRateLimit(_ response: HTTPURLResponse) {
let parsed = response.value(forHTTPHeaderField: "Retry-After").flatMap(TimeInterval.init)
let seconds = parsed.flatMap { $0.isFinite ? $0 : nil } ?? 30
pausedUntil = max(pausedUntil, Date().addingTimeInterval(min(max(seconds, 0), 3_600)))
}
}