Repository Public
1// SP Music iOS2// File: Core/Sources/SPMusicCore/API/APIClient.swift3// Description: HTTP client of the Music SP API (session cookie, CSRF, error mapping).4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai78import Foundation9import Synchronization1011public struct APIError: Error, Equatable, Sendable, LocalizedError {12 public var status: Int13 public var code: String14 public var message: String15 public init(status: Int, code: String, message: String) { self.status = status; self.code = code; self.message = message }1617 /// The request never reached the server (no connection, DNS, TLS, timeout).18 public static let network = APIError(status: 0, code: "network", message: "Connexion impossible")19 public var isNetwork: Bool { status == 0 }20 public var isUnauthenticated: Bool { status == 401 }21 public var errorDescription: String? {22 switch code {23 case "network": "Connexion au serveur impossible."24 case "unauthenticated": "La session a expiré. Connectez-vous de nouveau."25 case "login_failed": "Connexion refusée."26 case "rate_limited": "Trop de tentatives. Réessayez dans quelques minutes."27 case "invalid_setup_token": "Ce lien d'inscription est invalide ou a expiré."28 case "conflict": "Cette liste a été modifiée sur un autre appareil."29 default: message30 }31 }32}3334/// JSON client of the Music SP API. Same surfaces as the web player:35/// • the session is the `spmusic_session` cookie, kept in the Keychain and sent by hand (no shared cookie jar);36/// • every state-changing request carries the session's CSRF token; no `Origin` header is sent.37public final class APIClient: Sendable {38 public static let cookieName = "spmusic_session"39 public let baseURL: URL40 public let tokens: SessionTokenStore41 public let userAgent: String42 private let session: URLSession43 private let csrf = Mutex<String?>(nil)44 private let unauthenticatedHandler = Mutex<(@Sendable () -> Void)?>(nil)4546 public init(baseURL: URL, tokens: SessionTokenStore, userAgent: String = "SPMusic-iOS", protocolClasses: [AnyClass]? = nil) {47 self.baseURL = baseURL; self.tokens = tokens; self.userAgent = userAgent48 let c = URLSessionConfiguration.ephemeral49 c.httpCookieStorage = nil; c.httpShouldSetCookies = false; c.httpCookieAcceptPolicy = .never50 c.urlCache = nil; c.requestCachePolicy = .reloadIgnoringLocalCacheData51 c.timeoutIntervalForRequest = 20; c.timeoutIntervalForResource = 12052 c.waitsForConnectivity = false53 if let protocolClasses { c.protocolClasses = protocolClasses }54 session = URLSession(configuration: c)55 }5657 /// Called (once per failing request) when the server no longer knows the session.58 public func onUnauthenticated(_ handler: (@Sendable () -> Void)?) { unauthenticatedHandler.withLock { $0 = handler } }59 public var hasSession: Bool { tokens.read() != nil }60 public func forgetSession() { tokens.write(nil); csrf.withLock { $0 = nil } }61 public func adoptSession(token: String, csrf csrfToken: String?) { tokens.write(token); csrf.withLock { $0 = csrfToken } }6263 // MARK: Requests6465 public func url(_ path: String, query: [String: String] = [:]) -> URL {66 var c = URLComponents(url: baseURL.appendingPathComponent(path), resolvingAgainstBaseURL: false)!67 if !query.isEmpty { c.queryItems = query.sorted { $0.key < $1.key }.map { URLQueryItem(name: $0.key, value: $0.value) } }68 return c.url!69 }7071 /// A request for a media URL (audio, cover) carrying the session cookie.72 public func authorized(_ url: URL) -> URLRequest {73 var r = URLRequest(url: url)74 r.setValue(userAgent, forHTTPHeaderField: "User-Agent")75 if let t = tokens.read() { r.setValue("\(Self.cookieName)=\(t)", forHTTPHeaderField: "Cookie") }76 return r77 }7879 /// The session as a cookie object, for AVURLAsset (which takes cookies, not headers).80 public func sessionCookie() -> HTTPCookie? {81 guard let t = tokens.read(), let host = baseURL.host else { return nil }82 var p: [HTTPCookiePropertyKey: Any] = [.name: Self.cookieName, .value: t, .domain: host, .path: "/"]83 if baseURL.scheme == "https" { p[.secure] = "TRUE" }84 return HTTPCookie(properties: p)85 }8687 public func streamURL(trackId: String, variant: AudioVariant) -> URL {88 url("api/v1/stream/\(trackId)", query: variant == .compat ? ["v": "compat"] : [:])89 }90 public func artURL(artworkId: String, size: Int) -> URL { url("api/v1/art/\(artworkId)", query: ["s": String(size)]) }9192 public struct Empty: Decodable, Sendable { public init() {} }9394 @discardableResult95 public func send<T: Decodable & Sendable>(_ method: String = "GET", _ path: String, query: [String: String] = [:], body: (any Encodable & Sendable)? = nil, as: T.Type = T.self) async throws -> T {96 let mutating = method != "GET" && method != "HEAD"97 let isAuth = path.hasPrefix("api/v1/auth/")98 for attempt in 0..<2 {99 var req = authorized(url(path, query: query))100 req.httpMethod = method101 req.setValue("application/json", forHTTPHeaderField: "Accept")102 if let body { req.httpBody = try Self.encoder.encode(body); req.setValue("application/json", forHTTPHeaderField: "Content-Type") }103 if mutating, hasSession, let token = try await csrfToken(allowFetch: !isAuth || path.hasSuffix("/logout") || path.contains("/register/")) {104 req.setValue(token, forHTTPHeaderField: "X-CSRF-Token")105 }106 let (data, http) = try await perform(req)107 if isAuth { captureSession(from: http) }108 if (200..<300).contains(http.statusCode) {109 if T.self == Empty.self { return Empty() as! T }110 do { return try Self.decoder.decode(T.self, from: data) }111 catch { Log.net.error("undecodable answer for \(path, privacy: .public): \(String(describing: error), privacy: .public)"); throw APIError(status: http.statusCode, code: "bad_answer", message: "Réponse du serveur illisible") }112 }113 let err = Self.error(from: data, status: http.statusCode)114 if err.code == "csrf", attempt == 0 { csrf.withLock { $0 = nil }; continue } // token rotated: fetch it again once115 if err.status == 401, !isAuth { unauthenticatedHandler.withLock { $0 }?() }116 throw err117 }118 throw APIError(status: 403, code: "csrf", message: "Jeton CSRF refusé")119 }120121 public func perform(_ req: URLRequest) async throws -> (Data, HTTPURLResponse) {122 do {123 let (data, resp) = try await session.data(for: req)124 guard let http = resp as? HTTPURLResponse else { throw APIError.network }125 return (data, http)126 } catch let e as APIError { throw e }127 catch is CancellationError { throw CancellationError() }128 catch let e as URLError where e.code == .cancelled { throw CancellationError() }129 catch { throw APIError.network }130 }131132 private func csrfToken(allowFetch: Bool) async throws -> String? {133 if let t = csrf.withLock({ $0 }) { return t }134 guard allowFetch else { return nil }135 let s: SessionInfo = try await send("GET", "api/v1/auth/session")136 csrf.withLock { $0 = s.csrfToken }137 return s.csrfToken138 }139140 /// `GET auth/session`: who is signed in. Also refreshes the CSRF token.141 public func sessionInfo() async throws -> SessionInfo {142 let s: SessionInfo = try await send("GET", "api/v1/auth/session")143 csrf.withLock { $0 = s.csrfToken }144 return s145 }146147 private func captureSession(from http: HTTPURLResponse) {148 guard let raw = http.value(forHTTPHeaderField: "Set-Cookie") else { return }149 // "spmusic_session=<token>; Path=/; Expires=…; HttpOnly; Secure; SameSite=lax" — an empty value signs out.150 guard let r = raw.range(of: "\(Self.cookieName)=") else { return }151 let value = raw[r.upperBound...].prefix { $0 != ";" && $0 != "," }152 csrf.withLock { $0 = nil }153 tokens.write(value.isEmpty ? nil : (String(value).removingPercentEncoding ?? String(value)))154 }155156 static func error(from data: Data, status: Int) -> APIError {157 struct Wrapper: Decodable { struct E: Decodable { var code: String?; var message: String? }; var error: E? }158 let e = (try? JSONDecoder().decode(Wrapper.self, from: data))?.error159 return APIError(status: status, code: e?.code ?? "http_\(status)", message: e?.message ?? "Erreur \(status)")160 }161162 // MARK: Coding163164 public static let encoder: JSONEncoder = {165 let e = JSONEncoder()166 e.dateEncodingStrategy = .custom { date, enc in var c = enc.singleValueContainer(); try c.encode(ISO8601.string(date)) }167 return e168 }()169 public static let decoder: JSONDecoder = {170 let d = JSONDecoder()171 d.dateDecodingStrategy = .custom { dec in172 let s = try dec.singleValueContainer().decode(String.self)173 guard let date = ISO8601.date(s) else { throw DecodingError.dataCorrupted(.init(codingPath: dec.codingPath, debugDescription: "date")) }174 return date175 }176 return d177 }()178}179180public enum ISO8601 {181 public static func string(_ d: Date) -> String { d.formatted(Date.ISO8601FormatStyle(includingFractionalSeconds: true)) }182 public static func date(_ s: String) -> Date? {183 (try? Date.ISO8601FormatStyle(includingFractionalSeconds: true).parse(s)) ?? (try? Date.ISO8601FormatStyle().parse(s))184 }185}186187public struct SessionInfo: Decodable, Sendable {188 public var authenticated: Bool189 public var csrfToken: String?190 public var user: Me?191}192