Files
music-app/Music/API/APIClient.swift
T
2026-10-07 00:21:05 +02:00

151 lines
6.6 KiB
Swift

import Foundation
public struct APIConfiguration: Sendable {
public let apiBaseURL: URL
/// Object storage may use a different host from the JSON API. Defaults to the API origin.
public let mediaBaseURL: URL
public init(
apiBaseURL: URL = URL(string: "https://music.lucasskt.dk/api")!,
mediaBaseURL: URL? = nil
) {
self.apiBaseURL = apiBaseURL
self.mediaBaseURL = mediaBaseURL ?? URL(string: "/", relativeTo: apiBaseURL)!.absoluteURL
}
public func mediaURL(for path: String) -> URL? {
if let url = URL(string: path), url.scheme != nil { return url }
return URL(string: path.trimmingCharacters(in: CharacterSet(charactersIn: "/")), relativeTo: mediaBaseURL)?.absoluteURL
}
public func audioURL(for track: Track) -> URL? {
mediaURL(for: "\(track.fileDir.trimmingCharacters(in: CharacterSet(charactersIn: "/")))/high.m4a")
}
}
public enum APIError: Error, LocalizedError, Sendable {
case invalidURL
case nonHTTPResponse
case http(status: Int, message: String?)
case decoding(String)
case transport(String)
public var errorDescription: String? {
switch self {
case .invalidURL: "The API URL is invalid."
case .nonHTTPResponse: "The server returned an invalid response."
case let .http(status, message): message ?? "The server returned HTTP \(status)."
case let .decoding(message): "Could not read the server response: \(message)"
case let .transport(message): message
}
}
}
public final class APIClient: @unchecked Sendable {
public let configuration: APIConfiguration
private let session: URLSession
private let decoder: JSONDecoder
public init(configuration: APIConfiguration = APIConfiguration(), session: URLSession? = nil) {
self.configuration = configuration
if let session {
self.session = session
} else {
let config = URLSessionConfiguration.default
config.httpCookieStorage = .shared
config.httpCookieAcceptPolicy = .always
config.httpShouldSetCookies = true
self.session = URLSession(configuration: config)
}
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
self.decoder = decoder
}
@discardableResult
public func request<Response: Decodable & Sendable, Body: Encodable & Sendable>(
_ method: String,
path: String,
query: [URLQueryItem] = [],
body: Body? = nil,
response: Response.Type = Response.self
) async throws -> Response {
try await perform(method, path: path, query: query, body: body, response: response, refreshAfterUnauthorized: true)
}
private func perform<Response: Decodable & Sendable, Body: Encodable & Sendable>(
_ method: String,
path: String,
query: [URLQueryItem],
body: Body?,
response: Response.Type,
refreshAfterUnauthorized: Bool
) async throws -> Response {
guard var components = URLComponents(url: configuration.apiBaseURL.appending(path: path), resolvingAgainstBaseURL: false) else {
throw APIError.invalidURL
}
if !query.isEmpty { components.queryItems = query }
guard let url = components.url else { throw APIError.invalidURL }
var request = URLRequest(url: url)
request.httpMethod = method
request.setValue("application/json", forHTTPHeaderField: "Accept")
if let origin = URLComponents(url: configuration.apiBaseURL, resolvingAgainstBaseURL: false)?.url?.origin {
request.setValue(origin, forHTTPHeaderField: "Origin")
}
if let body {
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try JSONEncoder().encode(body)
}
do {
let (data, rawResponse) = try await session.data(for: request)
guard let http = rawResponse as? HTTPURLResponse else { throw APIError.nonHTTPResponse }
guard (200..<300).contains(http.statusCode) else {
let message = (try? JSONSerialization.jsonObject(with: data) as? [String: Any])?["message"] as? String
if http.statusCode == 401, refreshAfterUnauthorized, !path.hasPrefix("auth/") {
let status: SessionStatus = try await perform(
"GET",
path: "auth/session",
query: [],
body: Optional<EmptyBody>.none,
response: SessionStatus.self,
refreshAfterUnauthorized: false
)
if status.authenticated {
return try await perform(
method,
path: path,
query: query,
body: body,
response: response,
refreshAfterUnauthorized: false
)
}
}
throw APIError.http(status: http.statusCode, message: message)
}
if Response.self == EmptyResponse.self, let empty = EmptyResponse() as? Response { return empty }
do {
// The lyrics handler intentionally sends no body when lyrics are absent.
let isOptionalResponse = String(reflecting: Response.self).hasPrefix("Swift.Optional<")
if isOptionalResponse, data.isEmpty || (try? JSONSerialization.jsonObject(with: data) as? [String: Any])?.isEmpty == true {
return try decoder.decode(Response.self, from: Data("null".utf8))
}
return try decoder.decode(Response.self, from: data)
}
catch { throw APIError.decoding(error.localizedDescription) }
} catch let error as APIError { throw error }
catch { throw APIError.transport(error.localizedDescription) }
}
public func request<Response: Decodable & Sendable>(
_ method: String, path: String, query: [URLQueryItem] = [], response: Response.Type = Response.self
) async throws -> Response {
try await request(method, path: path, query: query, body: Optional<EmptyBody>.none, response: response)
}
private struct EmptyBody: Encodable, Sendable {}
public struct EmptyResponse: Decodable, Sendable { public init() {} }
}
private extension URL { var origin: String? { guard let scheme, let host else { return nil }; return "\(scheme)://\(host)" + (port.map { ":\($0)" } ?? "") } }