geesawra.industries/hydraulophone
An unofficial YouTube Music app for iPhone, iPad, and Mac.
0
0
import CommonCrypto
import Foundation
struct LastFMConfiguration: Sendable {
let apiKey: String
let sharedSecret: String
static func fromMainBundle() -> LastFMConfiguration? {
guard
let apiKey = LastFMBuildConfiguration.apiKey?.trimmingCharacters(in: .whitespacesAndNewlines),
let sharedSecret = LastFMBuildConfiguration.sharedSecret?.trimmingCharacters(
in: .whitespacesAndNewlines
),
!apiKey.isEmpty,
!sharedSecret.isEmpty
else {
return nil
}
return LastFMConfiguration(apiKey: apiKey, sharedSecret: sharedSecret)
}
}
struct LastFMAccount: Equatable, Sendable {
let username: String
}
enum LastFMAuthorizationState: Equatable {
case notConfigured
case signedOut
case connected(username: String)
}
struct LastFMTrack: Equatable, Sendable {
let artist: String
let title: String
let album: String?
let albumArtist: String?
let durationSeconds: Int?
let trackNumber: Int?
init(
artist: String,
title: String,
album: String? = nil,
albumArtist: String? = nil,
durationSeconds: Int? = nil,
trackNumber: Int? = nil
) {
self.artist = artist
self.title = title
self.album = album
self.albumArtist = albumArtist
self.durationSeconds = durationSeconds
self.trackNumber = trackNumber
}
}
struct LastFMScrobble: Sendable {
let track: LastFMTrack
let startedAt: Date
let chosenByUser: Bool?
init(track: LastFMTrack, startedAt: Date, chosenByUser: Bool? = nil) {
self.track = track
self.startedAt = startedAt
self.chosenByUser = chosenByUser
}
}
struct LastFMScrobbleResult: Equatable, Sendable {
let accepted: Int
let ignored: Int
let ignoredCode: Int?
var wasAccepted: Bool { accepted > 0 }
}
enum LastFMError: Error, Equatable {
case notConfigured
case noPendingAuthorization
case pendingAuthorizationNotApproved
case authorizationExpired
case invalidSession
case invalidTrack
case keychainFailure
case invalidResponse
case rejected(code: Int?)
case transport(statusCode: Int?)
}
extension LastFMError: LocalizedError {
var errorDescription: String? {
switch self {
case .notConfigured:
return "Last.fm is not configured in this build."
case .noPendingAuthorization:
return "Start Last.fm sign-in before finishing it."
case .pendingAuthorizationNotApproved:
return "Approve access in the browser, then try finishing sign-in again."
case .authorizationExpired:
return "Last.fm authorization expired. Start sign-in again."
case .invalidSession:
return "The Last.fm session is no longer valid. Sign in again."
case .invalidTrack:
return "This track is missing the artist or title Last.fm needs."
case .keychainFailure:
return "Last.fm sign-in could not be saved securely."
case .invalidResponse:
return "Last.fm returned an unreadable response."
case .rejected(let code):
return code.map { "Last.fm rejected the request (error \($0))." }
?? "Last.fm rejected the request."
case .transport(let statusCode):
return statusCode.map { "Last.fm could not complete the request (HTTP \($0))." }
?? "Last.fm could not complete the request."
}
}
}
struct LastFMStoredSession: Codable, Sendable {
let username: String
let key: String
}
protocol LastFMKeychainStoring: Sendable {
func load() throws -> LastFMStoredSession?
func save(_ session: LastFMStoredSession) throws
func delete() throws
}
protocol LastFMTransport: Sendable {
func perform(_ request: URLRequest) async throws -> (Data, HTTPURLResponse)
}
struct URLSessionLastFMTransport: LastFMTransport {
func perform(_ request: URLRequest) async throws -> (Data, HTTPURLResponse) {
let (data, response) = try await URLSession.shared.data(for: request)
guard let httpResponse = response as? HTTPURLResponse else {
throw LastFMError.invalidResponse
}
return (data, httpResponse)
}
}
actor LastFMClient {
private static let endpoint = "https://ws.audioscrobbler.com/2.0/"
private let configuration: LastFMConfiguration?
private let keychainStore: any LastFMKeychainStoring
private let transport: any LastFMTransport
private var pendingToken: String?
init(
configuration: LastFMConfiguration? = LastFMConfiguration.fromMainBundle(),
keychainStore: any LastFMKeychainStoring = LastFMKeychainStore(),
transport: any LastFMTransport = URLSessionLastFMTransport()
) {
self.configuration = configuration
self.keychainStore = keychainStore
self.transport = transport
}
func account() throws -> LastFMAccount? {
_ = try requireConfiguration()
do {
return try keychainStore.load().map { LastFMAccount(username: $0.username) }
} catch {
throw LastFMError.keychainFailure
}
}
func authorizationURL() async throws -> URL {
let configuration = try requireConfiguration()
var parameters = ["method": "auth.getToken", "api_key": configuration.apiKey]
parameters["api_sig"] = Self.signature(for: parameters, secret: configuration.sharedSecret)
let response = try await request(parameters)
guard let token = response.value("token"), !token.isEmpty else {
throw LastFMError.invalidResponse
}
var components = URLComponents(string: "https://www.last.fm/api/auth/")
components?.queryItems = [
URLQueryItem(name: "api_key", value: configuration.apiKey),
URLQueryItem(name: "token", value: token),
]
guard let url = components?.url else { throw LastFMError.invalidResponse }
pendingToken = token
return url
}
func completeAuthorization() async throws -> LastFMAccount {
let configuration = try requireConfiguration()
guard let token = pendingToken else { throw LastFMError.noPendingAuthorization }
var parameters = [
"method": "auth.getSession",
"api_key": configuration.apiKey,
"token": token,
]
parameters["api_sig"] = Self.signature(for: parameters, secret: configuration.sharedSecret)
do {
let response = try await request(parameters)
guard
let username = response.value("name"), !username.isEmpty,
let key = response.value("key"), !key.isEmpty
else {
throw LastFMError.invalidResponse
}
do {
try keychainStore.save(LastFMStoredSession(username: username, key: key))
} catch {
throw LastFMError.keychainFailure
}
pendingToken = nil
return LastFMAccount(username: username)
} catch LastFMError.rejected(code: 14) {
throw LastFMError.pendingAuthorizationNotApproved
} catch LastFMError.rejected(code: 15) {
pendingToken = nil
throw LastFMError.authorizationExpired
} catch LastFMError.rejected(code: 4) {
pendingToken = nil
throw LastFMError.authorizationExpired
}
}
func disconnect() throws {
pendingToken = nil
do {
try keychainStore.delete()
} catch {
throw LastFMError.keychainFailure
}
}
func updateNowPlaying(_ track: LastFMTrack) async throws {
let configuration = try requireConfiguration()
guard !track.artist.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
!track.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
else {
throw LastFMError.invalidTrack
}
let session = try requireSession()
var parameters = Self.trackParameters(track)
parameters["method"] = "track.updateNowPlaying"
parameters["api_key"] = configuration.apiKey
parameters["sk"] = session.key
parameters["api_sig"] = Self.signature(for: parameters, secret: configuration.sharedSecret)
do {
_ = try await request(parameters)
} catch LastFMError.rejected(code: 9) {
try clearInvalidSession()
throw LastFMError.invalidSession
}
}
func scrobble(_ scrobble: LastFMScrobble) async throws -> LastFMScrobbleResult {
let configuration = try requireConfiguration()
guard !scrobble.track.artist.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
!scrobble.track.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
else {
throw LastFMError.invalidTrack
}
let session = try requireSession()
var parameters = Self.trackParameters(scrobble.track)
parameters["method"] = "track.scrobble"
parameters["api_key"] = configuration.apiKey
parameters["sk"] = session.key
parameters["timestamp"] = String(Int(scrobble.startedAt.timeIntervalSince1970))
if let chosenByUser = scrobble.chosenByUser {
parameters["chosenByUser"] = chosenByUser ? "1" : "0"
}
parameters["api_sig"] = Self.signature(for: parameters, secret: configuration.sharedSecret)
do {
let response = try await requestScrobble(parameters)
guard let accepted = response.integerAttribute("scrobbles", "accepted"),
let ignored = response.integerAttribute("scrobbles", "ignored")
else {
throw LastFMError.invalidResponse
}
return LastFMScrobbleResult(
accepted: accepted,
ignored: ignored,
ignoredCode: response.integerAttribute("ignoredmessage", "code")
)
} catch LastFMError.rejected(code: 9) {
try clearInvalidSession()
throw LastFMError.invalidSession
}
}
private func requireSession() throws -> LastFMStoredSession {
do {
guard let session = try keychainStore.load() else { throw LastFMError.invalidSession }
return session
} catch let error as LastFMError {
throw error
} catch {
throw LastFMError.keychainFailure
}
}
private func requireConfiguration() throws -> LastFMConfiguration {
guard let configuration else { throw LastFMError.notConfigured }
return configuration
}
private func clearInvalidSession() throws {
do {
try keychainStore.delete()
} catch {
throw LastFMError.keychainFailure
}
}
private func requestScrobble(_ parameters: [String: String]) async throws -> LastFMXMLResponse {
do {
return try await request(parameters)
} catch LastFMError.rejected(code: 11) {
try await Task.sleep(nanoseconds: 500_000_000)
return try await request(parameters)
} catch LastFMError.rejected(code: 16) {
try await Task.sleep(nanoseconds: 500_000_000)
return try await request(parameters)
}
}
private func request(_ parameters: [String: String]) async throws -> LastFMXMLResponse {
guard let endpoint = URL(string: Self.endpoint) else { throw LastFMError.invalidResponse }
var request = URLRequest(url: endpoint)
request.httpMethod = "POST"
request.timeoutInterval = 20
request.setValue(
"application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
request.setValue("Hydraulophone/1.0 (iOS)", forHTTPHeaderField: "User-Agent")
request.httpBody = Self.formBody(parameters)
let data: Data
let response: HTTPURLResponse
do {
(data, response) = try await transport.perform(request)
} catch is CancellationError {
throw CancellationError()
} catch {
throw LastFMError.transport(statusCode: nil)
}
let parsed = try LastFMXMLResponse(data: data)
if let errorCode = parsed.errorCode {
throw LastFMError.rejected(code: errorCode)
}
guard (200..<300).contains(response.statusCode), parsed.status == "ok" else {
throw LastFMError.transport(statusCode: response.statusCode)
}
return parsed
}
private static func trackParameters(_ track: LastFMTrack) -> [String: String] {
var parameters = ["artist": track.artist, "track": track.title]
if let album = track.album, !album.isEmpty { parameters["album"] = album }
if let albumArtist = track.albumArtist, !albumArtist.isEmpty {
parameters["albumArtist"] = albumArtist
}
if let duration = track.durationSeconds, duration > 0 {
parameters["duration"] = String(duration)
}
if let trackNumber = track.trackNumber, trackNumber > 0 {
parameters["trackNumber"] = String(trackNumber)
}
return parameters
}
private static func signature(for parameters: [String: String], secret: String) -> String {
let canonical =
parameters.keys.sorted().map { "\($0)\(parameters[$0] ?? "")" }.joined() + secret
let bytes = Array(canonical.utf8)
var digest = [UInt8](repeating: 0, count: Int(CC_MD5_DIGEST_LENGTH))
_ = CC_MD5(bytes, CC_LONG(bytes.count), &digest)
return digest.map { String(format: "%02x", $0) }.joined()
}
private static func formBody(_ parameters: [String: String]) -> Data {
let allowed = CharacterSet(
charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._*")
let body = parameters.keys.sorted().map { key in
let encodedKey = key.addingPercentEncoding(withAllowedCharacters: allowed) ?? ""
let encodedValue =
(parameters[key] ?? "")
.addingPercentEncoding(withAllowedCharacters: allowed)?
.replacingOccurrences(of: "%20", with: "+") ?? ""
return "\(encodedKey)=\(encodedValue)"
}.joined(separator: "&")
return Data(body.utf8)
}
}
private final class LastFMXMLResponse: NSObject, XMLParserDelegate {
private(set) var status: String?
private(set) var errorCode: Int?
private(set) var values: [String: String] = [:]
private(set) var attributes: [String: [String: String]] = [:]
private var currentText = ""
init(data: Data) throws {
super.init()
let parser = XMLParser(data: data)
parser.delegate = self
guard parser.parse() else { throw LastFMError.invalidResponse }
}
func value(_ element: String) -> String? {
values[element.lowercased()]?.trimmingCharacters(in: .whitespacesAndNewlines)
}
func integerValue(_ element: String) -> Int? { Int(value(element) ?? "") }
func integerAttribute(_ element: String, _ attribute: String) -> Int? {
Int(attributes[element.lowercased()]?[attribute.lowercased()] ?? "")
}
func parser(
_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?,
qualifiedName qName: String?, attributes attributeDict: [String: String] = [:]
) {
let normalizedElement = elementName.lowercased()
currentText = ""
if normalizedElement == "lfm" { status = attributeDict["status"] }
if normalizedElement == "error" { errorCode = Int(attributeDict["code"] ?? "") }
attributes[normalizedElement] = Dictionary(
uniqueKeysWithValues: attributeDict.map { ($0.key.lowercased(), $0.value) }
)
}
func parser(_ parser: XMLParser, foundCharacters string: String) {
currentText += string
}
func parser(
_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?,
qualifiedName qName: String?
) {
let normalizedElement = elementName.lowercased()
values[normalizedElement] = (values[normalizedElement] ?? "") + currentText
currentText = ""
}
}