SPB Git

Repository Public

APIClient.swift 9.3 KB 162 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Networking/APIClient.swift3// Description: JSON client of the cluster's API: session cookie, CSRF token, error mapping, connectivity reporting.4import Foundation56public enum APIError: Error, Sendable, Equatable {7    /// The cluster cannot be reached (no network, gateway down) or the app is in forced offline mode.8    case offline9    /// No session, or the session ended (expired, revoked).10    case unauthenticated11    case http(status: Int, code: String, message: String)12    case invalidResponse1314    public var isConflict: Bool { if case .http(409, "conflict", _) = self { return true }; return false }15    public var isNotFound: Bool { if case .http(404, _, _) = self { return true }; return false }16}1718/// JSON client of the cluster's API. It holds the session in memory (loaded from the credential store), sends it as19/// the session cookie, adds the CSRF token to state-changing requests, and reports every outcome to `Connectivity`.20public final class APIClient: @unchecked Sendable {21    public let baseURL: URL22    public let connectivity: Connectivity23    private let session: URLSession24    private let store: CredentialStore25    private let lock = NSLock()26    private var credential: Credential?27    private var unauthenticatedHandler: (@Sendable () -> Void)?28    public static let cookieName = "spmusic_session"2930    public static let userAgent: String = {31        let v = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "1.0"32        let os = ProcessInfo.processInfo.operatingSystemVersion33        // Header values must be ASCII: the Mac's name loses its accents and typographic apostrophes here.34        let folded = (Host.current().localizedName ?? "Mac").folding(options: [.diacriticInsensitive, .widthInsensitive], locale: Locale(identifier: "en_US_POSIX"))35        let host = String(folded.map { c -> Character in c == "’" || c == "‘" ? "'" : (c.isASCII && c != ";" && c != ")" && c != "(" ? c : " ") }).trimmingCharacters(in: .whitespaces)36        return "SPMusic/\(v) (\(host); macOS \(os.majorVersion).\(os.minorVersion))"37    }()3839    public init(baseURL: URL, credentials: CredentialStore, connectivity: Connectivity) {40        self.baseURL = baseURL; self.store = credentials; self.connectivity = connectivity41        let c = URLSessionConfiguration.ephemeral42        c.httpCookieStorage = nil; c.httpShouldSetCookies = false; c.urlCache = nil43        c.timeoutIntervalForRequest = 30; c.waitsForConnectivity = false44        c.httpAdditionalHeaders = ["User-Agent": Self.userAgent, "Accept": "application/json"]45        session = URLSession(configuration: c)46        if let saved = credentials.load(), saved.serverURL == baseURL { credential = saved }47    }4849    public var currentCredential: Credential? { lock.withLock { credential } }50    public var account: Account? { currentCredential?.account }51    public func setUnauthenticatedHandler(_ h: (@Sendable () -> Void)?) { lock.withLock { unauthenticatedHandler = h } }52    public func adopt(_ c: Credential) throws { try store.save(c); lock.withLock { credential = c } }53    public func forgetCredential() { store.clear(); lock.withLock { credential = nil } }5455    // MARK: Dates5657    public static let decoder: JSONDecoder = {58        let d = JSONDecoder()59        d.dateDecodingStrategy = .custom { dec in60            let s = try dec.singleValueContainer().decode(String.self)61            if let date = parseISO(s) { return date }62            throw DecodingError.dataCorrupted(.init(codingPath: dec.codingPath, debugDescription: "bad date \(s)"))63        }64        return d65    }()66    public static func parseISO(_ s: String) -> Date? {67        let f = ISO8601DateFormatter(); f.formatOptions = [.withInternetDateTime, .withFractionalSeconds]68        if let d = f.date(from: s) { return d }69        f.formatOptions = [.withInternetDateTime]70        return f.date(from: s)71    }72    /// Canonical ISO-8601 with exactly three fractional digits, computed from whole milliseconds so that a date read73    /// from the cluster and written back is the same string (used to compare playlist versions).74    public static func iso(_ d: Date) -> String {75        let ms = Int64((d.timeIntervalSince1970 * 1000).rounded())76        let secs = ms >= 0 ? ms / 1000 : (ms - 999) / 100077        let f = ISO8601DateFormatter(); f.formatOptions = [.withInternetDateTime]78        let base = f.string(from: Date(timeIntervalSince1970: TimeInterval(secs)))79        return String(base.dropLast()) + String(format: ".%03dZ", ms - secs * 1000)80    }8182    // MARK: Requests8384    public func url(_ path: String, query: [String: String] = [:]) -> URL {85        var comps = URLComponents(url: baseURL.appendingPathComponent("api/v1/" + path), resolvingAgainstBaseURL: false)!86        if !query.isEmpty { comps.queryItems = query.sorted { $0.key < $1.key }.map { URLQueryItem(name: $0.key, value: $0.value) } }87        return comps.url!88    }8990    /// A request carrying the session, for the media endpoints (stream, art) and uploads. Throws when offline or signed out.91    public func authorizedRequest(_ path: String, query: [String: String] = [:], method: String = "GET") throws -> URLRequest {92        guard !connectivity.forcedOffline else { throw APIError.offline }93        guard let c = currentCredential else { throw APIError.unauthenticated }94        var r = URLRequest(url: url(path, query: query))95        r.httpMethod = method96        r.setValue("\(Self.cookieName)=\(c.sessionToken)", forHTTPHeaderField: "Cookie")97        r.setValue(Self.userAgent, forHTTPHeaderField: "User-Agent")98        if method != "GET" && method != "HEAD" { r.setValue(c.csrfToken, forHTTPHeaderField: "X-CSRF-Token") }99        return r100    }101102    public func noteUnauthenticated() {103        let h = lock.withLock { unauthenticatedHandler }104        h?()105    }106107    public static func isOffline(_ error: Error) -> Bool {108        if let e = error as? APIError { return e == .offline }109        guard let u = error as? URLError else { return false }110        switch u.code {111        case .notConnectedToInternet, .cannotFindHost, .cannotConnectToHost, .networkConnectionLost, .timedOut, .dnsLookupFailed, .internationalRoamingOff,112             .dataNotAllowed, .secureConnectionFailed, .resourceUnavailable: return true113        default: return false114        }115    }116117    /// Raw exchange. `authenticated: false` is for the sign-in endpoints.118    public func exchange(_ method: String, _ path: String, query: [String: String] = [:], body: Data? = nil, contentType: String = "application/json",119                         authenticated: Bool = true, timeout: TimeInterval = 30) async throws -> (Data, HTTPURLResponse) {120        guard !connectivity.forcedOffline else { throw APIError.offline }121        var r: URLRequest122        if authenticated { r = try authorizedRequest(path, query: query, method: method) } else { r = URLRequest(url: url(path, query: query)); r.httpMethod = method }123        r.timeoutInterval = timeout124        if let body { r.httpBody = body; r.setValue(contentType, forHTTPHeaderField: "Content-Type") }125        let data: Data, response: URLResponse126        do { (data, response) = try await session.data(for: r) }127        catch {128            if Self.isOffline(error) { connectivity.noteFailure(); throw APIError.offline }129            throw error130        }131        guard let http = response as? HTTPURLResponse else { throw APIError.invalidResponse }132        // The gateway answers these when the node behind it is down: for the app, the cluster is unreachable.133        if [502, 503, 504].contains(http.statusCode) { connectivity.noteFailure(); throw APIError.offline }134        connectivity.noteSuccess()135        if http.statusCode == 401 && authenticated { noteUnauthenticated(); throw APIError.unauthenticated }136        guard (200..<300).contains(http.statusCode) else {137            struct Envelope: Decodable { struct E: Decodable { var code: String?; var message: String? }; var error: E? }138            let e = (try? JSONDecoder().decode(Envelope.self, from: data))?.error139            throw APIError.http(status: http.statusCode, code: e?.code ?? "http_\(http.statusCode)", message: e?.message ?? "HTTP \(http.statusCode)")140        }141        return (data, http)142    }143144    public func get<T: Decodable>(_ path: String, query: [String: String] = [:]) async throws -> T {145        let (data, _) = try await exchange("GET", path, query: query)146        return try Self.decoder.decode(T.self, from: data)147    }148149    public func send<T: Decodable>(_ method: String, _ path: String, json: [String: Any]? = nil, query: [String: String] = [:], authenticated: Bool = true) async throws -> T {150        let body = try json.map { try JSONSerialization.data(withJSONObject: $0) }151        let (data, _) = try await exchange(method, path, query: query, body: body ?? (method == "GET" ? nil : Data("{}".utf8)), authenticated: authenticated)152        return try Self.decoder.decode(T.self, from: data.isEmpty ? Data("{}".utf8) : data)153    }154155    /// Liveness of the cluster, without a session. Used to notice that it is back.156    public func probe() async -> Bool {157        var r = URLRequest(url: baseURL.appendingPathComponent("api/health")); r.timeoutInterval = 6158        guard let (_, resp) = try? await session.data(for: r), let http = resp as? HTTPURLResponse else { return false }159        return http.statusCode == 200160    }161}162
Files main
Menu

Theme