Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Administration/AdminView.swift3// Description: Administration of the cluster's library, for accounts with the admin role.4import SwiftUI5import UniformTypeIdentifiers6import SPMusicCore78/// Administration of the cluster's library, for accounts with the admin role: importing music, editing albums,9/// watching the server. Everything goes through the same authenticated API as the web console.10struct AdminView: View {11 @Environment(AppModel.self) private var model12 @State private var tab = "import"13 var body: some View {14 VStack(spacing: 0) {15 Picker("", selection: $tab) { Text("Importer").tag("import"); Text("Albums").tag("albums"); Text("Serveur").tag("server") }16 .pickerStyle(.segmented).labelsHidden().frame(width: 320).padding(.vertical, 12)17 Divider()18 if !model.isOnline { EmptyState(symbol: "icloud.slash", title: "Administration indisponible hors ligne", message: "Ces opérations modifient la bibliothèque sur le cluster : elles demandent une connexion.") }19 else {20 switch tab {21 case "albums": AdminAlbumsView()22 case "server": AdminServerView()23 default: AdminImportView()24 }25 }26 }27 .navigationTitle("Administration")28 }29}3031struct AdminImportView: View {32 @Environment(AppModel.self) private var model33 struct Job: Identifiable { let id = UUID(); let url: URL; var sent: Int64 = 0; var total: Int64 = 0; var state = "En attente"; var detail = ""; var uploadID: String?; var done = false; var failed = false; var duplicate = false }34 @State private var jobs: [Job] = []35 @State private var running = false36 @State private var targeted = false3738 var body: some View {39 VStack(spacing: 16) {40 VStack(spacing: 8) {41 Image(systemName: "square.and.arrow.down.on.square").font(.system(size: 34, weight: .light)).foregroundStyle(targeted ? Color.accentColor : .secondary)42 Text("Glissez ici des fichiers audio, des dossiers d’albums ou des archives ZIP").font(.headline)43 Text("FLAC, ALAC, MP3, AAC, WAV, AIFF… Les fichiers sont envoyés au cluster, analysés (tags, pochette, doublons) puis ajoutés à la bibliothèque de tous vos appareils.").font(.callout).foregroundStyle(.secondary).multilineTextAlignment(.center).frame(maxWidth: 520)44 Button("Choisir des fichiers…") { choose() }45 }46 .padding(26).frame(maxWidth: .infinity)47 .background(RoundedRectangle(cornerRadius: 14).strokeBorder(targeted ? Color.accentColor : Color.secondary.opacity(0.4), style: StrokeStyle(lineWidth: 1.5, dash: [7, 5])).background(targeted ? Color.accentColor.opacity(0.08) : .clear, in: RoundedRectangle(cornerRadius: 14)))48 .onDrop(of: [.fileURL], isTargeted: $targeted) { providers in49 Task {50 var urls: [URL] = []51 for p in providers { if let d = try? await p.loadItem(forTypeIdentifier: UTType.fileURL.identifier) as? Data, let u = URL(dataRepresentation: d, relativeTo: nil) { urls.append(u) } }52 add(urls)53 }54 return true55 }56 if !jobs.isEmpty {57 HStack {58 Text("\(jobs.filter(\.done).count) sur \(jobs.count) traités").font(.callout).foregroundStyle(.secondary)59 Spacer()60 Button("Effacer la liste") { jobs.removeAll { $0.done } }.controlSize(.small).disabled(running)61 }62 List(jobs) { j in63 HStack(spacing: 10) {64 Image(systemName: j.failed ? "xmark.octagon.fill" : j.duplicate ? "doc.on.doc.fill" : j.done ? "checkmark.circle.fill" : "arrow.up.circle").foregroundStyle(j.failed ? .red : j.duplicate ? .orange : j.done ? .green : .secondary)65 VStack(alignment: .leading, spacing: 2) {66 Text(j.url.lastPathComponent).lineLimit(1)67 if !j.done, j.total > 0 { ProgressView(value: Double(j.sent), total: Double(max(j.total, 1))).controlSize(.small) }68 Text(j.detail.isEmpty ? j.state : "\(j.state) — \(j.detail)").font(.caption).foregroundStyle(.secondary).lineLimit(2)69 }70 Spacer()71 if j.duplicate, let id = j.uploadID {72 Button("Remplacer") { Task { try? await model.admin?.replaceDuplicate(id); update(j.id) { $0.state = "Remplacement demandé"; $0.duplicate = false }; await model.syncNow() } }.controlSize(.small)73 .help("Remplace le fichier existant par celui-ci (les listes et favoris sont conservés)")74 }75 }76 }77 .listStyle(.inset).frame(minHeight: 160)78 }79 Spacer(minLength: 0)80 }81 .padding(24)82 }8384 private func choose() {85 let panel = NSOpenPanel(); panel.allowsMultipleSelection = true; panel.canChooseDirectories = true86 panel.allowedContentTypes = [.audio, .zip, .folder]87 if panel.runModal() == .OK { add(panel.urls) }88 }8990 private func add(_ urls: [URL]) {91 var files: [URL] = []92 let allowed = AppModel.audioExtensions.union(["zip", "ogg", "opus", "dsf", "dff"])93 for u in urls {94 var isDir: ObjCBool = false95 guard FileManager.default.fileExists(atPath: u.path, isDirectory: &isDir) else { continue }96 if isDir.boolValue {97 let e = FileManager.default.enumerator(at: u, includingPropertiesForKeys: nil, options: [.skipsHiddenFiles])98 while let f = e?.nextObject() as? URL { if allowed.contains(f.pathExtension.lowercased()) { files.append(f) } }99 } else if allowed.contains(u.pathExtension.lowercased()) { files.append(u) }100 }101 files.sort { $0.path.localizedStandardCompare($1.path) == .orderedAscending }102 jobs += files.map { Job(url: $0) }103 if !running { Task { await run() } }104 }105106 private func update(_ id: UUID, _ change: (inout Job) -> Void) { if let i = jobs.firstIndex(where: { $0.id == id }) { change(&jobs[i]) } }107108 private func run() async {109 guard let admin = model.admin else { return }110 running = true111 defer { running = false }112 var imported = 0113 while let job = jobs.first(where: { !$0.done && $0.state == "En attente" }) {114 let id = job.id115 update(id) { $0.state = "Envoi" }116 do {117 let result = try await admin.importFile(job.url) { sent, total in Task { @MainActor in update(id) { $0.sent = sent; $0.total = total; if sent >= total { $0.state = "Analyse sur le cluster" } } } }118 update(id) { j in119 j.done = true; j.uploadID = result.id120 switch result.status {121 case "ready": j.state = "Ajouté"; j.detail = result.trackTitle ?? ""122 case "duplicate": j.state = "Déjà dans la bibliothèque"; j.detail = result.trackTitle ?? ""; j.duplicate = result.errorCode == "same_track"123 default: j.state = "Refusé"; j.failed = true; j.detail = Self.reason(result.errorCode, result.errorDetail)124 }125 }126 if result.status == "ready" { imported += 1 }127 } catch {128 update(id) { $0.done = true; $0.failed = true; $0.state = "Échec"; $0.detail = model.describe(error) }129 }130 }131 if imported > 0 { await model.syncNow(); model.toast("\(imported) fichier(s) ajouté(s) à la bibliothèque.") }132 }133134 static func reason(_ code: String?, _ detail: String?) -> String {135 switch code {136 case "not_audio", "unsupported_type": "ce n’est pas un fichier audio"137 case "undecodable", "no_audio_stream": "fichier audio illisible"138 case "file_too_large": "fichier trop volumineux"139 case "quota_exceeded": "quota de la bibliothèque atteint"140 case "disk_full": "espace insuffisant sur le cluster"141 default: detail ?? code ?? "erreur inconnue"142 }143 }144}145146struct AdminAlbumsView: View {147 @Environment(AppModel.self) private var model148 @State private var albums: [Album] = []149 @State private var filter = ""150 @State private var editing: Album?151152 var body: some View {153 VStack(spacing: 0) {154 TextField("Filtrer les albums", text: $filter).textFieldStyle(.roundedBorder).padding(12)155 List(albums.filter { filter.isEmpty || TextNorm.norm($0.title + " " + $0.artistName).contains(TextNorm.norm(filter)) }) { a in156 HStack(spacing: 10) {157 ArtworkView(artworkID: a.artworkID, size: 38, cornerRadius: 4, symbol: "square.stack")158 VStack(alignment: .leading, spacing: 1) {159 Text(a.title).lineLimit(1)160 Text("\(a.artistName) · \(a.year.map(String.init) ?? "année inconnue") · \(a.genre ?? "sans genre") · \(a.trackCount) titres").font(.caption).foregroundStyle(.secondary).lineLimit(1)161 }162 Spacer()163 if a.artworkID == nil { Label("Sans pochette", systemImage: "photo").font(.caption).foregroundStyle(.orange).labelStyle(.titleAndIcon) }164 Button("Modifier…") { editing = a }.controlSize(.small)165 }166 }167 .listStyle(.inset)168 }169 .libraryTask(model) { albums = await model.store?.albums(sort: .artist) ?? [] }170 .sheet(item: $editing) { AdminAlbumEditor(album: $0) }171 }172}173174struct AdminAlbumEditor: View {175 @Environment(AppModel.self) private var model176 @Environment(\.dismiss) private var dismiss177 let album: Album178 @State private var title = ""179 @State private var artist = ""180 @State private var year = ""181 @State private var genre = ""182 @State private var busy = false183 @State private var error: String?184 @State private var confirmDelete = false185 @State private var newCover: URL?186187 var body: some View {188 VStack(alignment: .leading, spacing: 14) {189 Text("Modifier l’album").font(.title3.weight(.semibold))190 HStack(alignment: .top, spacing: 16) {191 VStack(spacing: 8) {192 if let newCover, let img = NSImage(contentsOf: newCover) { Image(nsImage: img).resizable().aspectRatio(contentMode: .fill).frame(width: 130, height: 130).clipShape(RoundedRectangle(cornerRadius: 8)) }193 else { ArtworkView(artworkID: album.artworkID, size: 130, cornerRadius: 8, symbol: "square.stack") }194 Button("Changer la pochette…") {195 let p = NSOpenPanel(); p.allowedContentTypes = [.jpeg, .png, .webP]196 if p.runModal() == .OK { newCover = p.url }197 }198 .controlSize(.small)199 }200 Form {201 TextField("Titre", text: $title)202 TextField("Artiste de l’album", text: $artist)203 TextField("Année", text: $year)204 TextField("Genre", text: $genre)205 }206 }207 if let error { Text(error).font(.callout).foregroundStyle(.orange) }208 HStack {209 Button("Supprimer l’album…", role: .destructive) { confirmDelete = true }.disabled(busy)210 Spacer()211 if busy { ProgressView().controlSize(.small) }212 Button("Annuler") { dismiss() }.keyboardShortcut(.cancelAction)213 Button("Enregistrer") { Task { await save() } }.keyboardShortcut(.defaultAction).disabled(busy || title.trimmingCharacters(in: .whitespaces).isEmpty || artist.trimmingCharacters(in: .whitespaces).isEmpty)214 }215 }216 .padding(20).frame(width: 560)217 .onAppear { title = album.title; artist = album.artistName; year = album.year.map(String.init) ?? ""; genre = album.genre ?? "" }218 .confirmationDialog("Supprimer « \(album.title) » du cluster ?", isPresented: $confirmDelete) {219 Button("Supprimer \(album.trackCount) titres et leurs fichiers", role: .destructive) { Task { await delete() } }220 } message: { Text("Les fichiers originaux sont effacés du cluster pour tous les appareils. Les copies déjà téléchargées sur ce Mac sont conservées. Cette action est irréversible.") }221 }222223 private func save() async {224 guard let admin = model.admin else { return }225 busy = true; error = nil226 defer { busy = false }227 do {228 let y = Int(year.trimmingCharacters(in: .whitespaces))229 if !year.trimmingCharacters(in: .whitespaces).isEmpty, y == nil || y! < 1000 || y! > 2999 { error = "L’année doit être un nombre à quatre chiffres."; return }230 if title != album.title || artist != album.artistName || y != album.year || genre != (album.genre ?? "") {231 try await admin.updateAlbum(album.id, title: title.trimmingCharacters(in: .whitespaces), artist: artist.trimmingCharacters(in: .whitespaces), year: y, genre: genre.trimmingCharacters(in: .whitespaces))232 }233 if let newCover { try await admin.setAlbumArtwork(album.id, image: try Data(contentsOf: newCover)) }234 await model.syncNow()235 dismiss()236 } catch { self.error = "Le cluster a refusé la modification : \(model.describe(error))" }237 }238 private func delete() async {239 guard let admin = model.admin else { return }240 busy = true241 defer { busy = false }242 do { try await admin.deleteAlbum(album.id); await model.syncNow(); dismiss() } catch { self.error = "Suppression impossible : \(model.describe(error))" }243 }244}245246struct AdminServerView: View {247 @Environment(AppModel.self) private var model248 @State private var health: ServerHealth?249 @State private var uploads: [ServerUpload] = []250 @State private var error: String?251252 var body: some View {253 ScrollView {254 VStack(alignment: .leading, spacing: 18) {255 if let h = health {256 HStack(alignment: .top, spacing: 14) {257 card("Stockage", h.storage.available ? "Disponible" : "Indisponible", ok: h.storage.available) {258 if let total = h.storage.totalBytes, let free = h.storage.freeBytes, total > 0 {259 ProgressView(value: (total - free) / total)260 Text("\(Format.bytes(Int64(free))) libres sur \(Format.bytes(Int64(total)))").font(.caption).foregroundStyle(.secondary)261 }262 Text("Bibliothèque : \(Format.bytes(Int64(h.storage.usedBytes)))").font(.caption).foregroundStyle(.secondary)263 ForEach(h.storage.byKind) { k in Text("\(kindName(k.kind)) : \(k.files) fichiers, \(Format.bytes(Int64(k.bytes)))").font(.caption2).foregroundStyle(.tertiary) }264 }265 card("Bibliothèque", "\(h.library.tracks) titres", ok: true) {266 Text("\(h.library.albums) albums · \(h.library.artists) artistes").font(.caption).foregroundStyle(.secondary)267 Text("Durée totale : \(Format.longDuration(ms: Int(h.library.durationMs)))").font(.caption).foregroundStyle(.secondary)268 if h.library.renditionsPending > 0 { Text("\(h.library.renditionsPending) rendus en préparation").font(.caption).foregroundStyle(.secondary) }269 if h.library.renditionErrors > 0 { Text("\(h.library.renditionErrors) rendus en erreur").font(.caption).foregroundStyle(.orange) }270 }271 card("Traitement", h.worker.ok ? "Actif" : "Arrêté", ok: h.worker.ok) {272 Text(h.worker.ageSec.map { "Dernier signe de vie il y a \($0) s" } ?? "Aucun signe de vie").font(.caption).foregroundStyle(.secondary)273 Text("Paroles : \(h.lyrics.configured ? h.lyrics.mode : "désactivées")").font(.caption).foregroundStyle(.secondary)274 Text("Sauvegarde : \(h.backup.configured ? (h.backup.last.map { "dernière le \($0.at.prefix(10))" } ?? "jamais faite") : "non configurée")").font(.caption).foregroundStyle(h.backup.last == nil ? .orange : .secondary)275 }276 }277 } else if let error { Label(error, systemImage: "exclamationmark.triangle.fill").foregroundStyle(.orange) } else { ProgressView() }278 if !uploads.isEmpty {279 Text("Imports récents sur le cluster").font(.headline)280 ForEach(uploads.prefix(40)) { u in281 HStack {282 Image(systemName: u.status == "ready" ? "checkmark.circle.fill" : u.status == "error" ? "xmark.octagon.fill" : u.status == "duplicate" ? "doc.on.doc.fill" : "clock").foregroundStyle(u.status == "ready" ? .green : u.status == "error" ? .red : .orange)283 Text(u.filename).lineLimit(1)284 Spacer()285 Text(u.status == "error" ? AdminImportView.reason(u.errorCode, u.errorDetail) : u.status == "duplicate" ? "doublon" + (u.trackTitle.map { " de « \($0) »" } ?? "") : u.trackTitle ?? u.status).font(.caption).foregroundStyle(.secondary).lineLimit(1)286 Text(u.updatedAt.formatted(date: .abbreviated, time: .shortened)).font(.caption.monospacedDigit()).foregroundStyle(.tertiary)287 }288 }289 }290 }291 .padding(24).frame(maxWidth: .infinity, alignment: .leading)292 }293 .task {294 guard let admin = model.admin else { return }295 while !Task.isCancelled {296 do { health = try await admin.health(); uploads = try await admin.uploads(); error = nil } catch { self.error = "État du serveur indisponible : \(model.describe(error))" }297 try? await Task.sleep(nanoseconds: 10_000_000_000)298 }299 }300 }301302 private func kindName(_ k: String) -> String { ["original": "Originaux", "rendition": "Rendus AAC", "artwork": "Pochettes", "thumbnail": "Vignettes"][k] ?? k }303 private func card<C: View>(_ title: String, _ value: String, ok: Bool, @ViewBuilder _ content: () -> C) -> some View {304 VStack(alignment: .leading, spacing: 6) {305 HStack { Text(title).font(.caption.weight(.semibold)).foregroundStyle(.secondary); Spacer(); Circle().fill(ok ? .green : .red).frame(width: 8, height: 8) }306 Text(value).font(.title3.weight(.semibold))307 content()308 }309 .padding(14).frame(maxWidth: .infinity, minHeight: 130, alignment: .topLeading)310 .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 12))311 }312}313