Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Music9// File : Features/Downloads/DownloadsView.swift10// Description : Download manager and storage management screens.11// Module : Features12// Repository : https://git.spboucher.ai/sp-music-ios13// Created : 2026-11-1714// Last Modified : 2026-11-1715//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author : Simon-Pierre Boucher21// Position : Professor of Finance22// Institution : Université du Québec en Outaouais (UQO)23// Department : Département des sciences administratives24// Organization : SP Boucher25//26// Website : https://spboucher.ai27// Git : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General : info@spboucher.ai34// Professional : contact@spboucher.ai35// Direct : simon@spboucher.ai36// Research : research@spboucher.ai37// Development : dev@spboucher.ai38// Support : support@spboucher.ai39// Security/Admin : admin@spboucher.ai40// Notifications : notifications@spboucher.ai41//42// Preferred Contact: support@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification : Public67// Distribution : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License : None specified (no license file in this repository)81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import SPMusicCore89import SwiftUI9091/// The download manager: what is being fetched, what failed, what is kept on the device, and how much room it takes.92struct DownloadsView: View {93 @Environment(AppEnvironment.self) private var env94 @State private var active: [(DownloadRecord, Track?)] = []95 @State private var failed: [(DownloadRecord, Track?)] = []96 @State private var pinnedAlbums: [Album] = []97 @State private var pinnedPlaylists: [Playlist] = []98 @State private var libraryPinned = false99 @State private var pending = 0100 @State private var report = StorageReport()101 @State private var loaded = false102103 var body: some View {104 List {105 Section {106 NavigationLink(value: Route.storage) {107 HStack {108 Label("Stockage", systemImage: "internaldrive")109 Spacer()110 Text("\(Format.bytes(report.audioBytes + report.artworkBytes)) · \(report.tracks) titre\(report.tracks > 1 ? "s" : "")").foregroundStyle(Color.spMuted)111 }112 }113 NavigationLink(value: Route.downloaded) { Label("Tous les titres téléchargés", systemImage: "music.note") }114 if let blocked = NetworkPolicy.download(env.settings.transfer, env.network.status), !active.isEmpty {115 Label(blocked == .offline ? "Hors ligne : les téléchargements reprendront au retour de la connexion."116 : blocked == .lowDataMode ? "Mode Données réduites actif : les téléchargements attendent."117 : "En attente du Wi-Fi. Les téléchargements cellulaires sont désactivés dans les réglages.", systemImage: "wifi.exclamationmark")118 .font(.footnote).foregroundStyle(.yellow)119 }120 }121 if pending > 0 {122 Section {123 Button { Task { await env.downloads.enqueueWanted(); await env.downloadsModel.load(from: env.db) } } label: {124 Label("Télécharger \(pending) nouveau\(pending > 1 ? "x" : "") titre\(pending > 1 ? "s" : "")", systemImage: "arrow.down.circle")125 }126 } footer: { Text("Des albums ou des listes téléchargés ont reçu de nouveaux titres.") }127 }128 if !active.isEmpty {129 Section {130 ForEach(active, id: \.0.trackId) { d, t in activeRow(d, t) }131 } header: {132 HStack {133 Text("En cours (\(active.count))")134 Spacer()135 let allPaused = active.allSatisfy { $0.0.state == .paused }136 Button(allPaused ? "Tout reprendre" : "Tout mettre en pause") { Task { if allPaused { await env.downloads.resumeAll() } else { await env.downloads.pauseAll() } } }137 .font(.footnote).textCase(nil)138 }139 }140 }141 if !failed.isEmpty {142 Section {143 ForEach(failed, id: \.0.trackId) { d, t in144 HStack(spacing: 12) {145 ArtworkView(id: t?.artworkId, side: 40, corner: 5)146 VStack(alignment: .leading, spacing: 2) {147 Text(t?.title ?? "Titre").lineLimit(1)148 Text(Self.reason(d.error)).font(.footnote).foregroundStyle(.yellow)149 }150 Spacer()151 Button { Task { await env.downloads.resume(d.trackId) } } label: { Image(systemName: "arrow.clockwise") }.buttonStyle(.borderless).accessibilityLabel("Réessayer")152 }153 .swipeActions { Button(role: .destructive) { Task { await env.removeDownload(.track, d.trackId) } } label: { Label("Retirer", systemImage: "trash") } }154 }155 } header: {156 HStack { Text("Échecs (\(failed.count))"); Spacer(); Button("Tout réessayer") { Task { await env.downloads.retryFailed() } }.font(.footnote).textCase(nil) }157 }158 }159 if libraryPinned {160 Section("Bibliothèque") {161 HStack { Label("Toute la bibliothèque", systemImage: "books.vertical"); Spacer(); DownloadButton(kind: .library, id: "all", compact: true).buttonStyle(.borderless) }162 }163 }164 if !pinnedAlbums.isEmpty {165 Section("Albums téléchargés") {166 ForEach(pinnedAlbums) { a in167 NavigationLink(value: Route.album(a.id)) {168 HStack(spacing: 12) {169 ArtworkView(id: a.artworkId, side: 46, corner: 6)170 VStack(alignment: .leading, spacing: 2) { Text(a.title).lineLimit(1); Text(a.artistName).font(.footnote).foregroundStyle(Color.spMuted).lineLimit(1) }171 Spacer()172 DownloadButton(kind: .album, id: a.id, compact: true).buttonStyle(.borderless).foregroundStyle(Color.spEmber)173 }174 }175 .swipeActions { Button(role: .destructive) { Task { await env.removeDownload(.album, a.id) } } label: { Label("Supprimer", systemImage: "trash") } }176 }177 }178 }179 if !pinnedPlaylists.isEmpty {180 Section("Listes téléchargées") {181 ForEach(pinnedPlaylists) { p in182 NavigationLink(value: Route.playlist(p.id)) {183 HStack(spacing: 12) {184 MosaicArtwork(ids: p.artworkIds, side: 46, corner: 6)185 Text(p.name).lineLimit(1)186 Spacer()187 DownloadButton(kind: .playlist, id: p.id, compact: true).buttonStyle(.borderless).foregroundStyle(Color.spEmber)188 }189 }190 .swipeActions { Button(role: .destructive) { Task { await env.removeDownload(.playlist, p.id) } } label: { Label("Supprimer", systemImage: "trash") } }191 }192 }193 }194 }195 .scrollContentBackground(.hidden).background(Color.spBackground)196 .overlay {197 if loaded && active.isEmpty && failed.isEmpty && pinnedAlbums.isEmpty && pinnedPlaylists.isEmpty && !libraryPinned && report.tracks == 0 {198 ContentUnavailableView("Aucun téléchargement", systemImage: "arrow.down.circle", description: Text("Ouvrez un album ou une liste de lecture et touchez « Télécharger » pour l'écouter sans connexion."))199 .padding(.top, 150)200 }201 }202 .navigationTitle("Téléchargements")203 .task(id: "\(env.downloadsModel.version)|\(env.libraryVersion)") { await reload() }204 }205206 private func activeRow(_ d: DownloadRecord, _ t: Track?) -> some View {207 let live = env.downloadsModel.items[d.trackId]208 let state = live?.state ?? d.state209 return HStack(spacing: 12) {210 ArtworkView(id: t?.artworkId, side: 40, corner: 5)211 VStack(alignment: .leading, spacing: 4) {212 Text(t?.title ?? "Titre").lineLimit(1)213 if state == .running {214 ProgressView(value: live?.fraction ?? d.fraction).tint(Color.spEmber)215 Text("\(Format.bytes(live?.bytesDone ?? d.bytesDone)) sur \(Format.bytes(max(live?.bytesTotal ?? 0, d.bytesTotal)))").font(.caption).foregroundStyle(Color.spMuted).monospacedDigit()216 } else {217 Text(state == .paused ? "En pause" : state == .preparing ? "Préparation du rendu AAC sur MacLustr…" : "En attente").font(.footnote).foregroundStyle(Color.spMuted)218 }219 }220 Spacer()221 Button { Task { if state == .paused { await env.downloads.resume(d.trackId) } else { await env.downloads.pause(d.trackId) } } } label: {222 Image(systemName: state == .paused ? "play.circle" : "pause.circle").font(.title3)223 }224 .buttonStyle(.borderless).accessibilityLabel(state == .paused ? "Reprendre" : "Mettre en pause")225 }226 .swipeActions { Button(role: .destructive) { Task { await env.removeDownload(.track, d.trackId) } } label: { Label("Annuler", systemImage: "xmark") } }227 .accessibilityIdentifier("active-download")228 }229230 static func reason(_ code: String?) -> String {231 switch code {232 case "checksum", "size": "Fichier reçu incomplet ou altéré — non conservé"233 case "auth": "Session expirée : reconnectez-vous"234 case "missing": "Fichier absent du serveur"235 case "network": "Connexion interrompue"236 case "storage": "Espace insuffisant ou écriture impossible"237 case "rendition": "Rendu AAC indisponible sur le serveur"238 default: "Échec du transfert"239 }240 }241242 private func reload() async {243 let all = await env.db.downloads()244 let tracks = Dictionary((await env.db.tracks(ids: all.map(\.trackId))).map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })245 active = all.filter { [.running, .queued, .preparing, .paused].contains($0.state) }.sorted { ($0.state == .running ? 0 : 1, $0.addedAt) < ($1.state == .running ? 0 : 1, $1.addedAt) }.map { ($0, tracks[$0.trackId]) }246 failed = all.filter { $0.state == .failed }.map { ($0, tracks[$0.trackId]) }247 let pins = await env.db.pins()248 libraryPinned = pins.contains { $0.kind == .library }249 var albums: [Album] = []250 for p in pins where p.kind == .album { if let a = await env.db.album(id: p.id) { albums.append(a) } }251 pinnedAlbums = albums252 let lists = await env.db.playlists()253 pinnedPlaylists = pins.filter { $0.kind == .playlist }.compactMap { p in lists.first { $0.id == p.id } }254 pending = env.settings.transfer.autoDownloadPinned ? 0 : await env.downloads.pendingWanted().count255 report = await env.downloads.storageReport()256 loaded = true257 }258}259260struct StorageView: View {261 @Environment(AppEnvironment.self) private var env262 @State private var report = StorageReport()263 @State private var libraryBytes: Int64 = 0264 @State private var libraryTracks = 0265 @State private var confirmAll = false266 @State private var confirmLibrary = false267268 var body: some View {269 List {270 Section("Sur cet appareil") {271 row("Titres téléchargés", "\(report.tracks)")272 row("Albums", "\(report.albums)")273 row("Fichiers audio", Format.bytes(report.audioBytes))274 row("Pochettes", Format.bytes(report.artworkBytes))275 row("Cache", Format.bytes(report.cacheBytes))276 row("Espace disponible", Format.bytes(report.freeBytes))277 }278 Section {279 Button("Vider le cache") { env.files.clearCache(); env.artwork.clearMemory(); Task { report = await env.downloads.storageReport() } }280 } footer: { Text("Le cache contient les pochettes vues en naviguant. La musique téléchargée n'est pas touchée.") }281 Section {282 Button { confirmLibrary = true } label: { Label("Télécharger toute la bibliothèque", systemImage: "arrow.down.circle") }283 .disabled(libraryTracks == 0)284 } footer: {285 Text(libraryBytes > report.freeBytes286 ? "Il faudrait environ \(Format.bytes(libraryBytes)) ; l'appareil n'a que \(Format.bytes(report.freeBytes)) de libre."287 : "\(libraryTracks) titres restent à télécharger, environ \(Format.bytes(libraryBytes)) en qualité « \(env.settings.transfer.downloadQuality == .original ? "originale" : "AAC 256 kbit/s")».")288 }289 Section {290 Button("Supprimer tous les téléchargements", role: .destructive) { confirmAll = true }.disabled(report.tracks == 0)291 } footer: { Text("Les fichiers originaux restent sur MacLustr et peuvent être téléchargés de nouveau. Un titre téléchargé s'exporte depuis son menu « … » → « Exporter le fichier ».") }292 }293 .scrollContentBackground(.hidden).background(Color.spBackground)294 .navigationTitle("Stockage")295 .confirmationDialog("Supprimer toute la musique téléchargée ?", isPresented: $confirmAll, titleVisibility: .visible) {296 Button("Tout supprimer de cet appareil", role: .destructive) { Task { await env.removeAllDownloads(); await reload() } }297 } message: { Text("\(report.tracks) titres (\(Format.bytes(report.audioBytes))) seront retirés de cet appareil.") }298 .confirmationDialog("Télécharger toute la bibliothèque ?", isPresented: $confirmLibrary, titleVisibility: .visible) {299 if libraryBytes <= report.freeBytes { Button("Télécharger \(Format.bytes(libraryBytes))") { Task { _ = await env.download(.library, "all", confirmed: true); await reload() } } }300 } message: {301 Text(libraryBytes > report.freeBytes ? "Espace insuffisant : \(Format.bytes(libraryBytes)) nécessaires, \(Format.bytes(report.freeBytes)) disponibles. Choisissez la qualité AAC ou libérez de l'espace."302 : "\(libraryTracks) titres, environ \(Format.bytes(libraryBytes)). Espace disponible : \(Format.bytes(report.freeBytes)).")303 }304 .task(id: "\(env.downloadsModel.version)") { await reload() }305 }306 private func row(_ k: String, _ v: String) -> some View { HStack { Text(k); Spacer(); Text(v).foregroundStyle(Color.spMuted).monospacedDigit() } }307 private func reload() async {308 report = await env.downloads.storageReport()309 let ids = await env.db.allTrackIds()310 libraryBytes = await env.downloads.estimate(trackIds: ids)311 libraryTracks = max(0, ids.count - report.tracks)312 }313}314