Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Music pour macOS9// File : Features/Downloads/DownloadsView.swift10// Description : Downloads manager: active, waiting, failed and finished11// downloads; whole-library download.12// Module : Features13// Repository : https://git.spboucher.ai/sp-music-macos14// Created : 2026-11-1815// Last Modified : 2026-11-1816//17// =============================================================================18// AUTHOR & PROFESSIONAL AFFILIATION19// =============================================================================20//21// Author : Simon-Pierre Boucher22// Position : Professor of Finance23// Institution : Université du Québec en Outaouais (UQO)24// Department : Département des sciences administratives25// Organization : SP Boucher26//27// Website : https://spboucher.ai28// Git : https://git.spboucher.ai29//30// =============================================================================31// OFFICIAL CONTACT DIRECTORY32// =============================================================================33//34// General : info@spboucher.ai35// Professional : contact@spboucher.ai36// Direct : simon@spboucher.ai37// Research : research@spboucher.ai38// Development : dev@spboucher.ai39// Support : support@spboucher.ai40// Security/Admin : admin@spboucher.ai41// Notifications : notifications@spboucher.ai42//43// Preferred Contact: support@spboucher.ai44//45// =============================================================================46// COPYRIGHT & INTELLECTUAL PROPERTY47// =============================================================================48//49// Copyright (c) 202650// Simon-Pierre Boucher51//52// All rights reserved where applicable.53//54// This file is governed by the applicable project license,55// copyright notices, institutional agreements and relevant law.56//57// Unless expressly authorized by the applicable license or58// rights holder, copying, redistribution, sublicensing,59// publication and commercial exploitation are not permitted.60//61// Existing third-party rights and notices remain unaffected.62//63// =============================================================================64// CONFIDENTIALITY & SECURITY65// =============================================================================66//67// Classification : Public68// Distribution : Public repository; use is governed by the project license69// Security Contact : admin@spboucher.ai70//71// Access to this source does not independently grant permission72// to redistribute or disclose confidential materials.73//74// Do not embed credentials, private keys, access tokens,75// certificates or confidential personal information.76//77// =============================================================================78// LICENSE & MAINTENANCE79// =============================================================================80//81// License : None specified (no license file in this repository)82// Maintainer : Simon-Pierre Boucher83// Technical Contact: dev@spboucher.ai84//85// =============================================================================86// END OF SP BOUCHER SOURCE HEADER87// =============================================================================8889import SwiftUI90import SPMusicCore9192struct DownloadsView: View {93 @Environment(AppModel.self) private var model94 @State private var items: [DownloadItem] = []95 @State private var stats = LibraryStats()96 @State private var usage: StorageUsage?97 @State private var estimate: (needed: Int64, free: Int64, tracks: Int)?98 @State private var confirmLibrary = false99 @State private var confirmClear = false100 @State private var keepingLibrary = false101 @State private var loaded = false102103 private func group(_ states: [DownloadState]) -> [DownloadItem] { items.filter { states.contains($0.state) } }104105 var body: some View {106 let active = group([.downloading]), waiting = group([.queued, .paused]), failed = group([.failed]), done = group([.done])107 ScrollView {108 VStack(alignment: .leading, spacing: 20) {109 summary110 if !active.isEmpty { section("En cours", active) }111 if !waiting.isEmpty { section("En attente", waiting) }112 if !failed.isEmpty {113 section("Échecs", failed, trailing: AnyView(Button("Tout réessayer") { Task { await model.session?.downloads.retryFailed() } }.controlSize(.small)))114 }115 if !done.isEmpty {116 section("Terminés (\(done.count))", Array(done.prefix(400)), trailing: AnyView(Button("Tout supprimer…", role: .destructive) { confirmClear = true }.controlSize(.small)))117 }118 if loaded && items.isEmpty {119 EmptyState(symbol: "arrow.down.circle", title: "Rien de téléchargé", message: "Ouvrez un album ou une liste et choisissez « Télécharger » : la musique sera copiée sur ce Mac, lisible sans aucune connexion.").frame(minHeight: 260)120 }121 }122 .padding(24).frame(maxWidth: 980, alignment: .leading).frame(maxWidth: .infinity, alignment: .leading)123 }124 .navigationTitle("Téléchargements")125 .toolbar {126 ToolbarItemGroup {127 if !active.isEmpty || !waiting.isEmpty {128 Button { model.setDownloadsPaused(!model.downloadsPaused) } label: { Label(model.downloadsPaused ? "Reprendre" : "Tout mettre en pause", systemImage: model.downloadsPaused ? "play.fill" : "pause.fill") }129 }130 }131 }132 .task(id: "\(model.libraryRevision)-\(model.liveProgress.count)") {133 guard let s = model.session else { return }134 items = await s.store.downloads()135 stats = await s.store.stats()136 usage = s.storage.usage(downloadedBytes: stats.downloadedBytes)137 keepingLibrary = await s.store.isPinned(.library, id: "all")138 loaded = true139 }140 .confirmationDialog("Télécharger toute la bibliothèque ?", isPresented: $confirmLibrary, presenting: estimate) { e in141 Button("Télécharger \(e.tracks) titres (\(Format.bytes(e.needed)))") { model.downloadLibrary() }.disabled(e.needed + 500_000_000 > e.free)142 } message: { e in143 Text(e.needed + 500_000_000 > e.free144 ? "Il faut \(Format.bytes(e.needed)) et il n’y a que \(Format.bytes(e.free)) libres à l’emplacement de la bibliothèque. Libérez de l’espace ou choisissez un autre dossier dans Réglages › Stockage."145 : "\(e.tracks) titres restent à copier sur ce Mac : \(Format.bytes(e.needed)) (espace libre : \(Format.bytes(e.free))). Les nouveautés ajoutées au cluster seront ensuite téléchargées automatiquement.")146 }147 .confirmationDialog("Supprimer tous les téléchargements de ce Mac ?", isPresented: $confirmClear) {148 Button("Supprimer \(done.count) fichiers", role: .destructive) { model.stopKeepingLibraryOffline(); Task { await model.session?.downloads.remove(done.map(\.trackID)) } }149 } message: { Text("Les fichiers audio copiés sur ce Mac seront effacés. Rien n’est supprimé sur le cluster.") }150 }151152 private var summary: some View {153 VStack(alignment: .leading, spacing: 12) {154 HStack(alignment: .top, spacing: 26) {155 stat("\(stats.downloadedTracks)", "titres sur ce Mac")156 stat("\(stats.downloadedAlbums)", "albums")157 stat(Format.bytes(stats.downloadedBytes), "utilisés")158 if let u = usage { stat(Format.bytes(u.freeBytes), "libres" + (u.volumeName.isEmpty ? "" : " sur \(u.volumeName)")) }159 if model.downloadSpeed > 1000 { stat(Format.bytes(Int64(model.downloadSpeed)) + "/s", "débit actuel") }160 Spacer()161 }162 HStack(spacing: 10) {163 if keepingLibrary {164 Label("Toute la bibliothèque est gardée hors ligne", systemImage: "checkmark.circle.fill").foregroundStyle(.secondary)165 Button("Arrêter") { model.stopKeepingLibraryOffline(); keepingLibrary = false }.controlSize(.small)166 } else {167 Button { Task { estimate = await model.libraryDownloadEstimate(); confirmLibrary = true } } label: { Label("Télécharger toute la bibliothèque…", systemImage: "square.and.arrow.down.on.square") }168 .disabled(!model.isOnline || stats.tracks == 0 || stats.downloadedTracks >= stats.tracks)169 }170 if let u = usage { Button("Afficher dans le Finder") { NSWorkspace.shared.open(u.libraryRoot) }.disabled(!u.rootAvailable) }171 if model.downloadsPaused { Label("Téléchargements en pause", systemImage: "pause.circle").foregroundStyle(.orange) }172 else if !model.isOnline && !group([.queued]).isEmpty { Label("Reprise automatique au retour du cluster", systemImage: "icloud.slash").foregroundStyle(.secondary) }173 }174 .font(.callout)175 }176 .padding(16).frame(maxWidth: .infinity, alignment: .leading)177 .background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 12))178 }179180 private func stat(_ value: String, _ label: String) -> some View {181 VStack(alignment: .leading, spacing: 1) { Text(value).font(.title2.weight(.semibold).monospacedDigit()); Text(label).font(.caption).foregroundStyle(.secondary) }182 }183184 private func section(_ title: String, _ list: [DownloadItem], trailing: AnyView? = nil) -> some View {185 VStack(alignment: .leading, spacing: 4) {186 HStack { Text(title).font(.headline); Spacer(); if let trailing { trailing } }187 ForEach(list) { DownloadRow(item: $0) }188 }189 }190}191192struct DownloadRow: View {193 @Environment(AppModel.self) private var model194 let item: DownloadItem195196 var body: some View {197 let live = model.liveProgress[item.trackID]198 HStack(spacing: 10) {199 ArtworkView(artworkID: item.artworkID, size: 36, cornerRadius: 4)200 VStack(alignment: .leading, spacing: 2) {201 Text(item.title.isEmpty ? "Titre retiré du cluster" : item.title).lineLimit(1)202 Text([item.artistName, item.albumTitle].filter { !$0.isEmpty }.joined(separator: " — ")).font(.caption).foregroundStyle(.secondary).lineLimit(1)203 if item.state == .downloading || live != nil {204 ProgressView(value: live?.fraction ?? (item.bytesTotal > 0 ? Double(item.bytesReceived) / Double(item.bytesTotal) : 0)).controlSize(.small)205 } else if let e = item.error, item.state != .done { Text(e).font(.caption).foregroundStyle(.orange).lineLimit(2) }206 }207 Spacer(minLength: 8)208 VStack(alignment: .trailing, spacing: 2) {209 if let live {210 Text("\(Format.bytes(live.received)) / \(Format.bytes(live.total))").font(.caption.monospacedDigit())211 Text(live.bytesPerSecond > 0 ? Format.bytes(Int64(live.bytesPerSecond)) + "/s" : "…").font(.caption2.monospacedDigit()).foregroundStyle(.secondary)212 } else {213 Text(item.state == .done || item.bytesReceived == 0 ? Format.bytes(item.bytesTotal) : "\(Format.bytes(item.bytesReceived)) / \(Format.bytes(item.bytesTotal))").font(.caption.monospacedDigit())214 Text(stateText).font(.caption2).foregroundStyle(.secondary)215 }216 }217 .frame(minWidth: 120, alignment: .trailing)218 HStack(spacing: 6) {219 switch item.state {220 case .downloading, .queued: button("pause.fill", "Mettre en pause") { Task { await model.session?.downloads.pause(item.trackID) } }221 case .paused: button("play.fill", "Reprendre") { Task { await model.session?.downloads.resume(item.trackID) } }222 case .failed: button("arrow.clockwise", "Réessayer") { Task { await model.session?.downloads.resume(item.trackID) } }223 case .done: button("magnifyingglass", "Afficher dans le Finder") { if let rel = item.relativePath, let s = model.session { NSWorkspace.shared.activateFileViewerSelecting([s.storage.fileURL(relativePath: rel)]) } }224 }225 button(item.state == .done ? "trash" : "xmark", item.state == .done ? "Supprimer le fichier" : "Annuler") { Task { await model.session?.downloads.remove(item.trackID) } }226 }227 }228 .padding(.vertical, 5).padding(.horizontal, 8)229 .background(.quaternary.opacity(0.25), in: RoundedRectangle(cornerRadius: 8))230 }231232 private var stateText: String {233 switch item.state {234 case .queued: "En attente"235 case .downloading: "Démarrage…"236 case .paused: item.error == nil ? "En pause" : "Nouvel essai bientôt"237 case .failed: "Échec"238 case .done: item.completedAt?.formatted(date: .abbreviated, time: .shortened) ?? "Terminé"239 }240 }241 private func button(_ symbol: String, _ help: String, _ action: @escaping () -> Void) -> some View {242 Button(action: action) { Image(systemName: symbol).frame(width: 22, height: 22) }.buttonStyle(.borderless).help(help).accessibilityLabel(help)243 }244}245