Organize views and utilities

This commit is contained in:
lucast committed 2026-10-07 03:32:00 +02:00
1 parent 9e82949c1d
commit 7ce0827c9a
15 files changed
+5

No files matched your search

+207
View File
@@ -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)" } ?? "")
}
}
@@ -0,0 +1,96 @@
import Foundation
import Security
/// Keeps the backend's HttpOnly session and refresh cookies available when Xcode
/// replaces a SwiftUI preview process. Cookie values stay in the Keychain.
enum AuthCookiePersistence {
private static let service = "dk.lucasskt.MusicApp.auth-cookies"
private static let account = "music.lucasskt.dk"
static func restore(into storage: HTTPCookieStorage, for url: URL) {
guard let data = read() else {
debug("restore: no Keychain record for host=\(url.host ?? "?")")
return
}
guard let properties = try? PropertyListSerialization.propertyList(
from: data, options: [], format: nil) as? [[HTTPCookiePropertyKey: Any]] else {
debug("restore: Keychain data could not be decoded (\(data.count) bytes)")
return
}
let cookies = properties.compactMap(HTTPCookie.init(properties:))
.filter { $0.domain.hasSuffix("music.lucasskt.dk") && $0.expiresDate.map { $0 > Date() } ?? true }
storage.setCookies(cookies, for: url, mainDocumentURL: nil)
debug("restore: loaded \(cookies.count) cookies [\(cookieNames(cookies))] for host=\(url.host ?? "?")")
}
static func save(from storage: HTTPCookieStorage, for url: URL) {
let properties = storage.cookies(for: url)?
.filter { $0.domain.hasSuffix("music.lucasskt.dk") }
.compactMap(\.properties) ?? []
guard let data = try? PropertyListSerialization.data(
fromPropertyList: properties, format: .binary, options: 0)
else {
debug("save: cookie properties could not be encoded [\(cookieNames(storage.cookies(for: url) ?? []))]")
return
}
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account,
]
let update: [String: Any] = [kSecValueData as String: data]
let status = SecItemUpdate(query as CFDictionary, update as CFDictionary)
if status == errSecItemNotFound {
var insert = query
insert[kSecValueData as String] = data
insert[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly
let addStatus = SecItemAdd(insert as CFDictionary, nil)
debug("save: insert status=\(addStatus), cookies=\(properties.count) [\(cookieNames(storage.cookies(for: url) ?? []))]")
} else {
debug("save: update status=\(status), cookies=\(properties.count) [\(cookieNames(storage.cookies(for: url) ?? []))]")
}
}
static func logRequestCookies(from storage: HTTPCookieStorage, for url: URL, phase: String) {
debug("\(phase): request cookie names [\(cookieNames(storage.cookies(for: url) ?? []))] host=\(url.host ?? "?")")
}
static func clear() {
SecItemDelete([
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account,
] as CFDictionary)
}
private static func read() -> Data? {
var query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrService as String: service,
kSecAttrAccount as String: account,
kSecReturnData as String: true,
kSecMatchLimit as String: kSecMatchLimitOne,
]
query[kSecUseAuthenticationUI as String] = kSecUseAuthenticationUIFail
var result: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &result)
guard status == errSecSuccess else {
debug("read: Keychain status=\(status)")
return nil
}
debug("read: Keychain success")
return result as? Data
}
private static func cookieNames(_ cookies: [HTTPCookie]) -> String {
cookies.map(\.name).sorted().joined(separator: ",")
}
private static func debug(_ message: String) {
#if DEBUG
print("[AuthCookiePersistence] pid=\(ProcessInfo.processInfo.processIdentifier) bundle=\(Bundle.main.bundleIdentifier ?? "?") \(message)")
#endif
}
}
+103
View File
@@ -0,0 +1,103 @@
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"
case name, file
}
}
nonisolated public struct Genre: Decodable, Identifiable, Sendable {
public let id: String
public let name: String
enum CodingKeys: String, CodingKey {
case id = "_id"
case 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"
case name, artists, file, genre
}
}
nonisolated public struct TrackAlbum: Decodable, Identifiable, Sendable {
public let id: String
public let name: String
public let file: String
enum CodingKeys: String, CodingKey {
case id = "_id"
case name, file
}
}
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<TrackAlbum>
public let artists: [APIReference<Artist>]
public let fileDir: String
public let durationInSeconds: Double
public let lyrics: Lyrics?
enum CodingKeys: String, CodingKey {
case id = "_id"
case 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"
case 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` }
+131
View File
@@ -0,0 +1,131 @@
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, remember: Bool = true) async throws {
let _: APIClient.EmptyResponse = try await client.request(
"POST", path: "auth/signin",
body: Credentials(email: email, password: password, remember: remember))
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 {
let response: SignOutResponse = try await client.request("POST", path: "auth/signout")
AuthCookiePersistence.clear()
return response
}
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 {
let membership: TrackMembership = try await client.request(
"GET",
path: "user/tracks/contains",
query: q([("id", id)])
)
return membership.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) })
}
}
nonisolated private struct Credentials: Encodable, Sendable {
let email: String
let password: String
let remember: Bool
}
nonisolated public struct SignOutResponse: Decodable, Sendable { public let success: Bool? }