import Foundation extension InnerTubeMusicService: LyricsProviding { public func lyrics(for song: Song) async throws -> SongLyrics? { try Task.checkCancellation() guard await client.hasCompleteLogin(), await client.credentialTransportAllowed() else { throw InnerTubeError.authenticationRequired } var firstPlain: SongLyrics? var firstFailure: (any Error)? for provider in [primaryLyrics, lyricsFallback] { do { let result = try await provider.lyrics(for: song) try Task.checkCancellation() guard await client.hasCompleteLogin(), await client.credentialTransportAllowed() else { throw InnerTubeError.authenticationRequired } if result?.isSynchronized == true { return result } if firstPlain == nil { firstPlain = result } } catch { if Self.isCancellation(error) { throw CancellationError() } try Task.checkCancellation() guard await client.hasCompleteLogin(), await client.credentialTransportAllowed() else { throw InnerTubeError.authenticationRequired } if firstFailure == nil { firstFailure = error } } } do { let native = try await webLyrics(for: song) try Task.checkCancellation() if native?.isSynchronized == true { return native } if let native { return native } if let firstPlain { return firstPlain } } catch { if Self.isCancellation(error) { throw CancellationError() } try Task.checkCancellation() if let innerTubeError = error as? InnerTubeError { switch innerTubeError { case .authenticationRequired, .httpStatus(401), .httpStatus(403): throw innerTubeError default: break } } if let firstPlain { return firstPlain } throw firstFailure ?? error } if let firstFailure { throw firstFailure } return nil } private func webLyrics(for song: Song) async throws -> SongLyrics? { let nextRequest = try await makeBodyAndSession(["videoId": song.id], authenticated: true) guard nextRequest.session != nil else { throw InnerTubeError.authenticationRequired } let nextData = try await client.post( endpoint: "next", body: nextRequest.body, authenticated: true, sessionOverride: nextRequest.session ) try Task.checkCancellation() guard let endpoint = try LyricsResponseParser.lyricsEndpoint(from: nextData) else { return nil } var browseValues: [String: Any] = ["browseId": endpoint.browseID] if let params = endpoint.params { browseValues["params"] = params } let webRequest = try await makeBodyAndSession(browseValues, authenticated: true) guard webRequest.session != nil else { throw InnerTubeError.authenticationRequired } let webData = try await client.post( endpoint: "browse", body: webRequest.body, authenticated: true, sessionOverride: webRequest.session ) try Task.checkCancellation() return try LyricsResponseParser.lyrics(from: webData) } private static func isCancellation(_ error: any Error) -> Bool { error is CancellationError || (error as? URLError)?.code == .cancelled } }