Add API infrastructure
This commit is contained in:
1 parent
51fee9350f
commit
3d07a77cb9
3 files changed
+285
No files matched your search
@@ -0,0 +1,150 @@
|
|||||||
|
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)" } ?? "") } }
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
/// MongoDB references are populated on some API routes and bare ObjectIds on others.
|
||||||
|
nonisolated public enum APIReference<Value: Decodable & Sendable>: Decodable, Sendable {
|
||||||
|
case id(String)
|
||||||
|
case value(Value)
|
||||||
|
|
||||||
|
public init(from decoder: Decoder) throws {
|
||||||
|
let container = try decoder.singleValueContainer()
|
||||||
|
if let id = try? container.decode(String.self) {
|
||||||
|
self = .id(id)
|
||||||
|
} else {
|
||||||
|
self = .value(try container.decode(Value.self))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
nonisolated public struct Artist: Decodable, Identifiable, Sendable {
|
||||||
|
public let id: String
|
||||||
|
public let name: String
|
||||||
|
public let file: String?
|
||||||
|
enum CodingKeys: String, CodingKey { case id = "_id", name, file }
|
||||||
|
}
|
||||||
|
|
||||||
|
nonisolated public struct Genre: Decodable, Identifiable, Sendable {
|
||||||
|
public let id: String
|
||||||
|
public let name: String
|
||||||
|
enum CodingKeys: String, CodingKey { case id = "_id", name }
|
||||||
|
}
|
||||||
|
|
||||||
|
nonisolated public struct Album: Decodable, Identifiable, Sendable {
|
||||||
|
public let id: String
|
||||||
|
public let name: String
|
||||||
|
public let artists: [APIReference<Artist>]
|
||||||
|
public let file: String?
|
||||||
|
public let genre: APIReference<Genre>?
|
||||||
|
enum CodingKeys: String, CodingKey { case id = "_id", name, artists, file, genre }
|
||||||
|
}
|
||||||
|
|
||||||
|
nonisolated public struct Lyrics: Decodable, Sendable {
|
||||||
|
public let synced: Bool
|
||||||
|
public let text: String
|
||||||
|
}
|
||||||
|
|
||||||
|
nonisolated public struct Track: Decodable, Identifiable, Sendable {
|
||||||
|
public let id: String
|
||||||
|
public let name: String
|
||||||
|
public let album: APIReference<Album>
|
||||||
|
public let artists: [APIReference<Artist>]
|
||||||
|
public let fileDir: String
|
||||||
|
public let durationInSeconds: Double
|
||||||
|
public let lyrics: Lyrics?
|
||||||
|
enum CodingKeys: String, CodingKey {
|
||||||
|
case id = "_id", name, album, artists, fileDir, durationInSeconds, lyrics
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
nonisolated public struct User: Decodable, Identifiable, Sendable {
|
||||||
|
public let id: String
|
||||||
|
public let name: String
|
||||||
|
public let email: String
|
||||||
|
public let role: String
|
||||||
|
public let savedTracks: [String]?
|
||||||
|
enum CodingKeys: String, CodingKey { case id = "_id", name, email, role, savedTracks }
|
||||||
|
}
|
||||||
|
|
||||||
|
nonisolated public struct SessionStatus: Decodable, Sendable { public let authenticated: Bool }
|
||||||
|
nonisolated public struct Session: Decodable, Sendable {
|
||||||
|
public let expireAt: Date
|
||||||
|
/// Returned for administrative bearer auth; ordinary user auth uses the HttpOnly cookie.
|
||||||
|
public let sessionToken: String
|
||||||
|
}
|
||||||
|
nonisolated public struct SearchResults: Decodable, Sendable {
|
||||||
|
public let tracks: [Track]
|
||||||
|
public let albums: [Album]
|
||||||
|
public let artists: [Artist]
|
||||||
|
}
|
||||||
|
nonisolated public struct TrackMembership: Decodable, Sendable { public let contains: Bool }
|
||||||
|
|
||||||
|
nonisolated public enum SearchType: String, Sendable { case track, album, artist, `default` }
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import Foundation
|
||||||
|
|
||||||
|
public struct MusicAPI: Sendable {
|
||||||
|
public let client: APIClient
|
||||||
|
public init(client: APIClient = APIClient()) { self.client = client }
|
||||||
|
|
||||||
|
private func q(_ pairs: [(String, String?)]) -> [URLQueryItem] {
|
||||||
|
pairs.compactMap { key, value in value.map { URLQueryItem(name: key, value: $0) } }
|
||||||
|
}
|
||||||
|
private func page(_ limit: Int?, _ skip: Int?) -> [URLQueryItem] {
|
||||||
|
q([("limit", limit.map(String.init)), ("skip", skip.map(String.init))])
|
||||||
|
}
|
||||||
|
|
||||||
|
public func signIn(email: String, password: String) async throws {
|
||||||
|
let _: APIClient.EmptyResponse = try await client.request("POST", path: "auth/signin", body: Credentials(email: email, password: password))
|
||||||
|
guard try await sessionStatus().authenticated else {
|
||||||
|
throw APIError.http(status: 401, message: "The server did not establish an authenticated session.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public func sessionStatus() async throws -> SessionStatus { try await client.request("GET", path: "auth/session") }
|
||||||
|
public func renewSession() async throws -> Session { try await client.request("POST", path: "auth/session") }
|
||||||
|
public func signOut() async throws -> SignOutResponse { try await client.request("POST", path: "auth/signout") }
|
||||||
|
public func currentUser() async throws -> User { try await client.request("GET", path: "user") }
|
||||||
|
|
||||||
|
public func search(_ query: String, type: SearchType = .default, limit: Int? = nil) async throws -> SearchResults {
|
||||||
|
try await client.request("GET", path: "search", query: q([("q", query), ("type", type.rawValue), ("limit", limit.map(String.init))]))
|
||||||
|
}
|
||||||
|
public func randomGenres(limit: Int? = nil) async throws -> [Genre] { try await client.request("GET", path: "genres/random", query: q([("limit", limit.map(String.init))])) }
|
||||||
|
public func album(id: String) async throws -> Album? { try await client.request("GET", path: "albums/\(id)") }
|
||||||
|
public func artist(id: String) async throws -> Artist? { try await client.request("GET", path: "artists/\(id)") }
|
||||||
|
public func track(id: String) async throws -> Track? { try await client.request("GET", path: "tracks/\(id)") }
|
||||||
|
public func lyrics(trackID: String) async throws -> Lyrics? { try await client.request("GET", path: "tracks/\(trackID)/lyrics") }
|
||||||
|
public func albumTracks(id: String, limit: Int? = nil, skip: Int? = nil) async throws -> [Track] { try await client.request("GET", path: "albums/\(id)/tracks", query: page(limit, skip)) }
|
||||||
|
public func artistTracks(id: String, limit: Int? = nil, skip: Int? = nil) async throws -> [Track] { try await client.request("GET", path: "artists/\(id)/tracks", query: page(limit, skip)) }
|
||||||
|
public func artistAlbums(id: String, limit: Int? = nil, skip: Int? = nil) async throws -> [Album] { try await client.request("GET", path: "artists/\(id)/albums", query: page(limit, skip)) }
|
||||||
|
public func genreAlbums(id: String, limit: Int? = nil, skip: Int? = nil) async throws -> [Album] { try await client.request("GET", path: "genres/albums/\(id)", query: page(limit, skip)) }
|
||||||
|
public func genreTracks(id: String, limit: Int? = nil, skip: Int? = nil) async throws -> [Track] { try await client.request("GET", path: "genres/tracks/\(id)", query: page(limit, skip)) }
|
||||||
|
public func allAlbums() async throws -> [Album] { try await client.request("GET", path: "all/albums") }
|
||||||
|
public func allArtists() async throws -> [Artist] { try await client.request("GET", path: "all/artists") }
|
||||||
|
public func allGenres() async throws -> [Genre] { try await client.request("GET", path: "all/genres") }
|
||||||
|
public func allTracks() async throws -> [Track] { try await client.request("GET", path: "all/tracks") }
|
||||||
|
public func savedTracks() async throws -> [Track] { try await client.request("GET", path: "user/tracks") }
|
||||||
|
public func savedAlbums() async throws -> [Album] { try await client.request("GET", path: "user/albums") }
|
||||||
|
public func savedArtists() async throws -> [Artist] { try await client.request("GET", path: "user/artists") }
|
||||||
|
public func isTrackSaved(id: String) async throws -> Bool { try await client.request("GET", path: "user/tracks/contains", query: q([("id", id)])).contains }
|
||||||
|
public func saveTrack(id: String) async throws { let _: APIClient.EmptyResponse = try await client.request("PATCH", path: "user/tracks", query: q([("id", id)])) }
|
||||||
|
public func removeTrack(id: String) async throws { let _: APIClient.EmptyResponse = try await client.request("DELETE", path: "user/tracks", query: q([("id", id)])) }
|
||||||
|
public func removeTracks(ids: [String]) async throws { let _: APIClient.EmptyResponse = try await client.request("DELETE", path: "user/tracks", query: ids.map { URLQueryItem(name: "ids", value: $0) }) }
|
||||||
|
public func tracks(ids: [String]) async throws -> [Track] { try await client.request("GET", path: "tracks", query: ids.map { URLQueryItem(name: "ids", value: $0) }) }
|
||||||
|
public func albums(ids: [String]) async throws -> [Album] { try await client.request("GET", path: "albums", query: ids.map { URLQueryItem(name: "ids", value: $0) }) }
|
||||||
|
public func artists(ids: [String]) async throws -> [Artist] { try await client.request("GET", path: "artists", query: ids.map { URLQueryItem(name: "ids", value: $0) }) }
|
||||||
|
}
|
||||||
|
|
||||||
|
private struct Credentials: Encodable, Sendable { let email: String; let password: String }
|
||||||
|
public struct SignOutResponse: Decodable, Sendable { public let success: Bool? }
|
||||||
Reference in new issue
Block a user