geesawra.industries/hydraulophone
An unofficial YouTube Music app for iPhone, iPad, and Mac.
0
0
import Foundation
public enum BetterLyricsError: Error, LocalizedError, Equatable, Sendable {
case invalidResponse
case httpStatus(Int)
case rateLimited
public var errorDescription: String? {
switch self {
case .invalidResponse:
return "The synchronized lyrics response could not be read."
case .httpStatus:
return "The synchronized lyrics service is unavailable right now."
case .rateLimited:
return "The synchronized lyrics service is busy. Try again later."
}
}
}
/// Fetches TTML with a single exact song/artist lookup. This provider carries
/// no YouTube credential and must be called behind the app's auth boundary.
public struct BetterLyricsProvider: LyricsProviding {
private static let sharedThrottle = BetterLyricsRequestThrottle()
private let session: URLSession
private let throttle: BetterLyricsRequestThrottle
public init(session: URLSession? = nil) {
self.session = session ?? Self.ephemeralSession()
throttle = Self.sharedThrottle
}
init(session: URLSession, throttle: BetterLyricsRequestThrottle) {
self.session = session
self.throttle = throttle
}
public func lyrics(for song: Song) async throws -> SongLyrics? {
try Task.checkCancellation()
guard let request = Self.request(for: song) else { return nil }
try await throttle.beforeRequest()
let (data, response) = try await session.data(
for: request, delegate: BetterLyricsNoRedirectDelegate())
try Task.checkCancellation()
guard let response = response as? HTTPURLResponse else {
throw BetterLyricsError.invalidResponse
}
switch response.statusCode {
case 200: break
// This client sends no API key; the documented 401 is an uncached lookup.
case 401, 404: return nil
case 429:
await throttle.noteRateLimit(response)
throw BetterLyricsError.rateLimited
default: throw BetterLyricsError.httpStatus(response.statusCode)
}
guard data.count <= 512 * 1_024,
let ttml = try? JSONDecoder().decode(BetterLyricsResponse.self, from: data).ttml,
!ttml.isEmpty,
let lines = TTMLLyricsParser.parse(ttml)
else { throw BetterLyricsError.invalidResponse }
return SongLyrics(lines: lines, source: "BetterLyrics")
}
private static func request(for song: Song) -> 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 = "api.betterlyrics.org"
components.path = "/getLyrics"
var query = [
URLQueryItem(name: "s", value: title),
URLQueryItem(name: "a", value: artist),
]
if let duration = durationSeconds(song.durationText) {
query.append(URLQueryItem(name: "d", value: String(duration)))
}
if let album = song.album?.trimmingCharacters(in: .whitespacesAndNewlines),
!album.isEmpty
{
query.append(URLQueryItem(name: "al", value: album))
}
components.queryItems = query
guard let url = components.url, url.scheme == "https",
url.host == "api.betterlyrics.org"
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 durationSeconds(_ text: String?) -> Int? {
guard let text else { return nil }
let parts = text.split(separator: ":", omittingEmptySubsequences: false)
let values = parts.compactMap { Int($0) }
guard (2...3).contains(parts.count), values.count == parts.count,
parts.allSatisfy({ !$0.isEmpty && $0.allSatisfy(\.isNumber) }),
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 BetterLyricsResponse: Decodable {
let ttml: String?
}
private final class BetterLyricsNoRedirectDelegate: NSObject, URLSessionTaskDelegate,
@unchecked Sendable
{
func urlSession(
_ session: URLSession, task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Void
) {
completionHandler(nil)
}
}
actor BetterLyricsRequestThrottle {
private var nextRequestAt = Date.distantPast
private var pausedUntil = Date.distantPast
func beforeRequest() async throws {
let now = Date()
guard now >= pausedUntil else { throw BetterLyricsError.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 BetterLyricsError.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)))
}
}