Organize views and utilities
This commit is contained in:
1 parent
9e82949c1d
commit
7ce0827c9a
15 files changed
+5
No files matched your search
@@ -0,0 +1,207 @@
|
||||
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: "https://s3-seaweedfs.lucasskt.dk/music/")!
|
||||
}
|
||||
|
||||
public func mediaURL(for path: String) -> URL? {
|
||||
if let url = URL(string: path), url.scheme != nil { return url }
|
||||
let directoryURL =
|
||||
mediaBaseURL.absoluteString.hasSuffix("/")
|
||||
? mediaBaseURL
|
||||
: URL(string: mediaBaseURL.absoluteString + "/")!
|
||||
return URL(
|
||||
string: path.trimmingCharacters(in: CharacterSet(charactersIn: "/")),
|
||||
relativeTo: directoryURL
|
||||
)?.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 .http(let status, let message): message ?? "The server returned HTTP \(status)."
|
||||
case .decoding(let message): "Could not read the server response: \(message)"
|
||||
case .transport(let 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)
|
||||
}
|
||||
if let cookieStorage = self.session.configuration.httpCookieStorage {
|
||||
AuthCookiePersistence.restore(into: cookieStorage, for: configuration.apiBaseURL)
|
||||
}
|
||||
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 {
|
||||
do {
|
||||
return try await perform(
|
||||
method, path: path, query: query, body: body, response: response,
|
||||
refreshAfterUnauthorized: true)
|
||||
} catch {
|
||||
print("[APIClient] \(method) \(path) failed: \(error.localizedDescription)")
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
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 }
|
||||
if let cookieStorage = session.configuration.httpCookieStorage {
|
||||
AuthCookiePersistence.restore(into: cookieStorage, for: url)
|
||||
if path.hasPrefix("auth/") {
|
||||
AuthCookiePersistence.logRequestCookies(from: cookieStorage, for: url, phase: "before \(path)")
|
||||
}
|
||||
}
|
||||
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)
|
||||
if let cookieStorage = session.configuration.httpCookieStorage {
|
||||
AuthCookiePersistence.save(from: cookieStorage, for: url)
|
||||
if path.hasPrefix("auth/") {
|
||||
AuthCookiePersistence.logRequestCookies(from: cookieStorage, for: url, phase: "after \(path)")
|
||||
}
|
||||
}
|
||||
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(String(describing: error)) }
|
||||
} catch let error as APIError { throw error } catch {
|
||||
if Task.isCancelled || error is CancellationError
|
||||
|| (error as? URLError)?.code == .cancelled
|
||||
{
|
||||
throw CancellationError()
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
nonisolated private struct EmptyBody: Encodable, Sendable {}
|
||||
nonisolated public struct EmptyResponse: Decodable, Sendable { public init() {} }
|
||||
}
|
||||
|
||||
extension URL {
|
||||
fileprivate var origin: String? {
|
||||
guard let scheme, let host else { return nil }
|
||||
return "\(scheme)://\(host)" + (port.map { ":\($0)" } ?? "")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user