Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Core/Networking/AdminAPI.swift3// Description: Client of the cluster's administration surface: imports, album edits, server health.4import Foundation56public struct ServerHealth: Decodable, Sendable {7 public struct Storage: Decodable, Sendable {8 public struct Kind: Decodable, Sendable, Identifiable { public var kind: String; public var files: Int; public var bytes: Double; public var id: String { kind } }9 public var available: Bool; public var freeBytes: Double?; public var totalBytes: Double?; public var usedBytes: Double; public var quotaBytes: Double; public var byKind: [Kind]10 }11 public struct Library: Decodable, Sendable { public var tracks: Int; public var albums: Int; public var artists: Int; public var durationMs: Double; public var renditionsPending: Int; public var renditionErrors: Int }12 public struct Worker: Decodable, Sendable { public var ok: Bool; public var ageSec: Int? }13 public struct Backup: Decodable, Sendable { public struct Last: Decodable, Sendable { public var at: String }; public var configured: Bool; public var last: Last? }14 public struct Lyrics: Decodable, Sendable { public var mode: String; public var configured: Bool }15 public var storage: Storage; public var library: Library; public var worker: Worker; public var backup: Backup; public var lyrics: Lyrics16}1718public struct ServerUpload: Decodable, Sendable, Identifiable, Equatable {19 public var id: String; public var filename: String; public var sizeBytes: Double; public var receivedBytes: Double; public var status: String20 public var errorCode: String?; public var errorDetail: String?; public var trackId: String?; public var duplicateOf: String?; public var trackTitle: String?; public var updatedAt: Date21 public var isTerminal: Bool { ["ready", "error", "duplicate", "cancelled"].contains(status) }22}2324public struct TrackPatch: Sendable {25 public var title: String?, artist: String?, album: String?, albumArtist: String?, genre: String?26 public var trackNo: Int?, discNo: Int?, year: Int?27 public init() {}28 var json: [String: Any] {29 var j: [String: Any] = [:]30 if let title { j["title"] = title }; if let artist { j["artist"] = artist }; if let album { j["album"] = album }; if let albumArtist { j["albumArtist"] = albumArtist }31 if let genre { j["genre"] = genre }; if let trackNo { j["trackNo"] = trackNo }; if let discNo { j["discNo"] = discNo }; if let year { j["year"] = year }32 return j33 }34 public var isEmpty: Bool { json.isEmpty }35}3637/// The cluster's administration surface, for accounts with the admin role. Every call goes through the same38/// authenticated API as the web console; the server checks the role on each request.39public struct AdminAPI: Sendable {40 public let api: APIClient41 public init(api: APIClient) { self.api = api }4243 public func health() async throws -> ServerHealth { try await api.get("admin/health") }44 public func uploads(filter: String = "all") async throws -> [ServerUpload] {45 struct Page: Decodable { var items: [ServerUpload] }46 let p: Page = try await api.get("admin/uploads", query: ["filter": filter, "limit": "200"])47 return p.items48 }49 public func upload(_ id: String) async throws -> ServerUpload { try await api.get("admin/uploads/\(id)") }5051 /// Sends one file through the cluster's import pipeline (chunked, resumable from the offset the server reports),52 /// then waits for the worker's verdict. `progress` receives (bytes sent, total).53 public func importFile(_ url: URL, progress: @Sendable (Int64, Int64) -> Void = { _, _ in }) async throws -> ServerUpload {54 let size = Int64((try FileManager.default.attributesOfItem(atPath: url.path)[.size] as? NSNumber)?.int64Value ?? 0)55 struct Created: Decodable { var id: String; var chunkBytes: Int }56 let created: Created = try await api.send("POST", "admin/uploads", json: ["filename": url.lastPathComponent, "size": size])57 let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() }58 var offset: Int64 = 059 var retries = 060 while offset < size {61 try Task.checkCancellation()62 try handle.seek(toOffset: UInt64(offset))63 let chunk = try handle.read(upToCount: max(64 * 1024, min(created.chunkBytes, 8 * 1024 * 1024))) ?? Data()64 if chunk.isEmpty { break }65 do {66 _ = try await api.exchange("PATCH", "admin/uploads/\(created.id)", query: ["offset": String(offset)], body: chunk, contentType: "application/octet-stream", timeout: 300)67 offset += Int64(chunk.count); retries = 068 progress(offset, size)69 } catch {70 // The answer was lost or the offset is off: ask the server where it is and continue from there.71 retries += 172 guard retries <= 5, !(error is CancellationError) else { throw error }73 if APIClient.isOffline(error) { try await Task.sleep(nanoseconds: UInt64(retries) * 1_000_000_000) }74 let state = try await upload(created.id)75 guard state.status == "uploading" else { if state.receivedBytes >= Double(size) { offset = size; break }; throw error }76 offset = Int64(state.receivedBytes)77 }78 }79 while true {80 let u = try await upload(created.id)81 if u.isTerminal { return u }82 try await Task.sleep(nanoseconds: 400_000_000)83 }84 }8586 public func replaceDuplicate(_ uploadID: String) async throws { let _: WireOK = try await api.send("POST", "admin/uploads/\(uploadID)/replace") }87 public func cancelUpload(_ uploadID: String) async throws { let _: WireOK = try await api.send("DELETE", "admin/uploads/\(uploadID)") }88 public func clearFinishedUploads() async throws { let _: WireOK = try await api.send("POST", "admin/uploads/clear") }8990 public func updateTracks(_ ids: [String], _ patch: TrackPatch) async throws { let _: WireOK = try await api.send("PATCH", "admin/tracks", json: ["ids": ids, "patch": patch.json]) }91 public func updateAlbum(_ id: String, title: String? = nil, artist: String? = nil, year: Int? = nil, genre: String? = nil) async throws {92 var j: [String: Any] = [:]93 if let title { j["title"] = title }; if let artist { j["artist"] = artist }; if let year { j["year"] = year }; if let genre { j["genre"] = genre }94 let _: WireOK = try await api.send("PATCH", "admin/albums/\(id)", json: j)95 }96 public func setAlbumArtwork(_ id: String, image: Data) async throws { _ = try await api.exchange("PUT", "admin/albums/\(id)/artwork", body: image, contentType: "application/octet-stream", timeout: 120) }97 public func deleteTracks(_ ids: [String]) async throws { let _: WireOK = try await api.send("POST", "admin/tracks/delete", json: ["ids": ids, "confirm": true]) }98 public func deleteAlbum(_ id: String) async throws { let _: WireOK = try await api.send("POST", "admin/albums/\(id)/delete", json: ["confirm": true]) }99 public func generateLyrics(_ ids: [String], language: String?) async throws {100 var j: [String: Any] = ["ids": ids]; if let language { j["language"] = language }101 let _: WireOK = try await api.send("POST", "admin/lyrics/generate", json: j)102 }103}104