Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SP Drive pour iPhone et iPad9// File : Features/MyDrive/ItemDetailsView.swift10// Description : Details sheet of a file or folder: information, offline11// availability, version history (download, restore, delete,12// comparison with the current version) and sharing.13// Module : Features14// Repository : https://git.spboucher.ai/sp-drive-ios15// Created : 2026-11-1916// Last Modified : 2026-11-1917//18// =============================================================================19// AUTHOR & PROFESSIONAL AFFILIATION20// =============================================================================21//22// Author : Simon-Pierre Boucher23// Position : Professor of Finance24// Institution : Université du Québec en Outaouais (UQO)25// Department : Département des sciences administratives26// Organization : SP Boucher27//28// Website : https://spboucher.ai29// Git : https://git.spboucher.ai30//31// =============================================================================32// OFFICIAL CONTACT DIRECTORY33// =============================================================================34//35// General : info@spboucher.ai36// Professional : contact@spboucher.ai37// Direct : simon@spboucher.ai38// Research : research@spboucher.ai39// Development : dev@spboucher.ai40// Support : support@spboucher.ai41// Security/Admin : admin@spboucher.ai42// Notifications : notifications@spboucher.ai43//44// Preferred Contact: support@spboucher.ai45//46// =============================================================================47// COPYRIGHT & INTELLECTUAL PROPERTY48// =============================================================================49//50// Copyright (c) 202651// Simon-Pierre Boucher52//53// All rights reserved where applicable.54//55// This file is governed by the applicable project license,56// copyright notices, institutional agreements and relevant law.57//58// Unless expressly authorized by the applicable license or59// rights holder, copying, redistribution, sublicensing,60// publication and commercial exploitation are not permitted.61//62// Existing third-party rights and notices remain unaffected.63//64// =============================================================================65// CONFIDENTIALITY & SECURITY66// =============================================================================67//68// Classification : Public69// Distribution : Public repository; use is governed by the project license70// Security Contact : admin@spboucher.ai71//72// Access to this source does not independently grant permission73// to redistribute or disclose confidential materials.74//75// Do not embed credentials, private keys, access tokens,76// certificates or confidential personal information.77//78// =============================================================================79// LICENSE & MAINTENANCE80// =============================================================================81//82// License : None specified (no license file in this repository)83// Maintainer : Simon-Pierre Boucher84// Technical Contact: dev@spboucher.ai85//86// =============================================================================87// END OF SP BOUCHER SOURCE HEADER88// =============================================================================8990import QuickLook91import SwiftUI92import UIKit9394struct ItemDetailsView: View {95 @Environment(AppModel.self) private var model96 @Environment(\.dismiss) private var dismiss97 private let initial: DriveItem9899 @State private var versions: [FileVersion] = []100 @State private var versionsPhase: LinkLoadPhase = .loading101 @State private var shareCount: Int?102 @State private var sharesOffline = false103 @State private var busyVersionID: String?104 @State private var versionToRestore: FileVersion?105 @State private var versionToDelete: FileVersion?106 @State private var previewURL: URL?107 @State private var showingShareEditor = false108 @State private var showingDepositEditor = false109 @State private var hashCopied = false110111 init(item: DriveItem) { initial = item }112113 /// Scratch space of the previous versions downloaded for a preview; emptied when the preview closes.114 private static var scratch: URL { FileManager.default.temporaryDirectory.appendingPathComponent("SPDrive-versions", isDirectory: true) }115116 var body: some View {117 let _ = model.itemsVersion118 // the local record follows renames, moves and new versions made while the sheet is open119 let item = model.store.item(initial.id) ?? initial120 NavigationStack {121 Form {122 header(item)123 informationSection(item)124 if !item.isFolder { versionsSection(item) }125 sharingSection(item)126 if model.next.meta.api >= 2, !item.isLocalOnly, model.network.online {127 // SP Drive 2.0: the timeline of the file, and its versions compared128 Section("Historique") {129 if !item.isFolder { NavigationLink { VersionsScreen(item: item) } label: { Label("Versions : comparer, restaurer", systemImage: "clock.arrow.circlepath") }.accessibilityIdentifier("details.versions") }130 if model.next.has(.activity) { NavigationLink { ActivityScreen(source: item.isFolder ? .folder(item.id) : .file(item.id), title: String(localized: "Activité")) } label: { Label("Activité", systemImage: "clock") }.accessibilityIdentifier("details.activity") }131 }132 }133 }134 .navigationTitle("Détails")135 .navigationBarTitleDisplayMode(.inline)136 .toolbar { ToolbarItem(placement: .cancellationAction) { Button("Fermer") { dismiss() }.accessibilityIdentifier("details.close") } }137 .refreshable { await loadRemote(item) }138 .task(id: item.versionID) { await loadRemote(item) }139 .task(id: hashCopied) {140 guard hashCopied else { return }141 try? await Task.sleep(for: .seconds(2))142 hashCopied = false143 }144 .confirmationDialog("Restaurer cette version ?", isPresented: Binding(get: { versionToRestore != nil }, set: { if !$0 { versionToRestore = nil } }), titleVisibility: .visible, presenting: versionToRestore) { v in145 Button("Restaurer la version \(v.seq)") { Task { await restore(v, of: item) } }146 Button("Annuler", role: .cancel) {}147 } message: { _ in148 Text("Une nouvelle version sera créée avec ce contenu. La version actuelle reste dans l’historique : rien n’est perdu.")149 }150 .confirmationDialog("Supprimer cette version ?", isPresented: Binding(get: { versionToDelete != nil }, set: { if !$0 { versionToDelete = nil } }), titleVisibility: .visible, presenting: versionToDelete) { v in151 Button("Supprimer la version \(v.seq)", role: .destructive) { Task { await delete(v, of: item) } }152 Button("Annuler", role: .cancel) {}153 } message: { _ in154 Text("Le contenu de cette version sera effacé définitivement. Les autres versions ne sont pas touchées.")155 }156 .sheet(isPresented: $showingShareEditor, onDismiss: { Task { await loadShareCount(item) } }) { ShareLinkEditor(item: item) }157 .sheet(isPresented: $showingDepositEditor) { DepositLinkEditor(folder: item) }158 .quickLookPreview($previewURL)159 .onChange(of: previewURL) { _, url in160 if url == nil { try? FileManager.default.removeItem(at: Self.scratch) }161 }162 }163 .sheetToast()164 .presentationDetents([.medium, .large])165 .presentationDragIndicator(.visible)166 }167168 // MARK: Sections169170 private func header(_ item: DriveItem) -> some View {171 Section {172 HStack(spacing: 14) {173 KindIcon(kind: item.kind, size: 56)174 VStack(alignment: .leading, spacing: 4) {175 Text(item.parentID == nil ? "Mon Drive" : item.name).font(.headline).lineLimit(3)176 Text(item.isFolder ? folderSummary(item) : "\(item.kind.label) · \(item.size.byteString)")177 .font(.subheadline)178 .foregroundStyle(.secondary)179 }180 }181 .padding(.vertical, 4)182 .accessibilityElement(children: .combine)183 .accessibilityIdentifier("details.header")184 }185 }186187 private func folderSummary(_ item: DriveItem) -> String {188 let n = model.store.childCount(of: item.id)189 return n == 0 ? "Dossier vide" : n == 1 ? "Dossier · 1 élément" : "Dossier · \(n) éléments"190 }191192 @ViewBuilder private func informationSection(_ item: DriveItem) -> some View {193 let badge = model.badge(item)194 let ownPin = model.store.localState(item.id)?.pinned == true195 let inheritedPin = !ownPin && model.engine.isEffectivelyPinned(item.id)196 Section {197 LabeledContent("Emplacement", value: location(of: item))198 LabeledContent("Créé", value: item.createdAt.linkDateTime)199 LabeledContent("Modifié", value: item.updatedAt.linkDateTime)200 if !item.isFolder {201 LabeledContent("Taille", value: "\(item.size.byteString) (\(item.size.formatted()) octets)")202 if !item.sha256.isEmpty {203 Button {204 UIPasteboard.general.string = item.sha256205 Haptics.success()206 hashCopied = true207 } label: {208 LabeledContent("SHA-256") {209 HStack(spacing: 6) {210 Text(hashCopied ? "Copié" : "\(item.sha256.prefix(12))…").font(.callout.monospaced())211 Image(systemName: hashCopied ? "checkmark" : "doc.on.doc").font(.footnote)212 }213 }214 }215 .tint(.primary)216 .accessibilityLabel("Empreinte SHA-256")217 .accessibilityHint("Copie l’empreinte complète")218 .accessibilityIdentifier("details.sha")219 }220 if item.isInfected { Label("Signalé par l’antivirus", systemImage: "exclamationmark.shield.fill").foregroundStyle(.red) }221 }222 LabeledContent("Synchronisation") {223 HStack(spacing: 6) {224 SyncBadgeView(badge: badge)225 Text(Self.syncText(badge, isFolder: item.isFolder))226 }227 }228 .accessibilityElement(children: .combine)229 Toggle("Disponible hors ligne", isOn: Binding(get: { ownPin || inheritedPin }, set: { setPinned($0, item: item) }))230 .disabled(inheritedPin || item.parentID == nil)231 .accessibilityIdentifier("details.offline")232 } header: {233 Text("Informations")234 } footer: {235 if inheritedPin { Text("Gardé hors ligne par un dossier parent.") }236 else if item.isFolder { Text("Hors ligne : tout le contenu du dossier, présent et à venir, est gardé sur cet appareil.") }237 }238 }239240 @ViewBuilder private func versionsSection(_ item: DriveItem) -> some View {241 let current = versions.first(where: \.current)242 Section {243 if item.isLocalOnly {244 Text("L’historique apparaîtra quand le fichier sera sur le Drive.").foregroundStyle(.secondary)245 } else {246 switch versionsPhase {247 case .loading:248 HStack { ProgressView(); Text("Chargement des versions…").foregroundStyle(.secondary) }249 case .offline:250 Label("Connexion requise pour voir l’historique des versions.", systemImage: "wifi.slash").foregroundStyle(.secondary)251 case .failed(let message):252 Label(message, systemImage: "exclamationmark.triangle").foregroundStyle(.secondary)253 Button("Réessayer") { Task { await loadRemote(item) } }254 case .ready:255 ForEach(versions) { v in versionRow(v, current: current, item: item) }256 }257 }258 } header: {259 Text(versions.count > 1 ? "Versions (\(versions.count))" : "Versions")260 } footer: {261 if versionsPhase == .ready, versions.count > 1 { Text("Restaurer une version en crée une nouvelle avec l’ancien contenu : rien n’est perdu.") }262 }263 .accessibilityIdentifier("details.versions")264 }265266 private func versionRow(_ v: FileVersion, current: FileVersion?, item: DriveItem) -> some View {267 HStack(spacing: 12) {268 VStack(alignment: .leading, spacing: 3) {269 HStack(spacing: 8) {270 Text("Version \(v.seq)").font(.body.weight(.medium))271 if v.current { LinkStatusChip(label: "actuelle", color: .green) }272 }273 Text("\(v.createdAt.linkDateTime) · \(v.size.byteString)").font(.caption).foregroundStyle(.secondary)274 if !v.note.isEmpty { Text(v.note).font(.caption).foregroundStyle(.secondary).lineLimit(2) }275 if !v.current, let current { Text(Self.comparison(v, with: current)).font(.caption).foregroundStyle(.secondary) }276 }277 Spacer(minLength: 8)278 if busyVersionID == v.id {279 ProgressView().accessibilityLabel("Opération en cours")280 } else {281 Menu {282 Button { Task { await download(v, of: item) } } label: { Label("Télécharger cette version", systemImage: "arrow.down.circle") }283 if !v.current {284 Button { versionToRestore = v } label: { Label("Restaurer", systemImage: "clock.arrow.circlepath") }285 Button(role: .destructive) { versionToDelete = v } label: { Label("Supprimer", systemImage: "trash") }286 }287 } label: {288 Image(systemName: "ellipsis.circle").font(.title3).frame(minWidth: 44, minHeight: 44).contentShape(Rectangle())289 }290 .disabled(busyVersionID != nil)291 .accessibilityLabel("Actions de la version \(v.seq)")292 .accessibilityIdentifier("details.version.\(v.seq).menu")293 }294 }295 }296297 @ViewBuilder private func sharingSection(_ item: DriveItem) -> some View {298 Section {299 if item.parentID == nil {300 Text("La racine du Drive ne peut pas être partagée.").foregroundStyle(.secondary)301 } else if item.isLocalOnly {302 Text("Le partage sera possible quand l’élément sera sur le Drive.").foregroundStyle(.secondary)303 } else {304 LabeledContent("Liens de partage") {305 if let shareCount { Text(shareCount == 0 ? "Aucun" : "\(shareCount)") }306 else if sharesOffline { Text("Connexion requise") }307 else { ProgressView() }308 }309 Button { showingShareEditor = true } label: { Label((shareCount ?? 0) > 0 ? "Gérer les liens de partage" : "Créer un lien de partage", systemImage: "link") }310 .accessibilityIdentifier("details.share")311 }312 if item.isFolder, !item.isLocalOnly {313 Button { showingDepositEditor = true } label: { Label("Créer un lien de dépôt", systemImage: "tray.and.arrow.down") }314 .accessibilityIdentifier("details.deposit")315 }316 } header: {317 Text("Partage")318 } footer: {319 if item.isFolder, !item.isLocalOnly { Text("Un lien de dépôt permet à quelqu’un d’envoyer des fichiers dans ce dossier sans en voir le contenu.") }320 }321 }322323 // MARK: Texts324325 private func location(of item: DriveItem) -> String {326 let ancestors = model.store.path(to: item.id).dropLast()327 if ancestors.isEmpty { return item.parentID == nil ? "Racine" : "Mon Drive" }328 return ancestors.map { $0.parentID == nil ? "Mon Drive" : $0.name }.joined(separator: " › ")329 }330331 private static func syncText(_ badge: SyncBadge, isFolder: Bool) -> String {332 switch badge {333 case .none: isFolder ? "À jour" : "En ligne seulement"334 case .available: "Copie sur cet appareil"335 case .pinned: "Disponible hors ligne"336 case .downloading(let f): "Téléchargement \(Int(f * 100)) %"337 case .uploading(let f): "Envoi \(Int(f * 100)) %"338 case .waiting: "En attente de synchronisation"339 case .conflict: "Conflit de versions"340 case .error: "Erreur de transfert"341 case .waitingDownload, .unavailableOffline: badge.spokenLabel342 }343 }344345 /// Metadata comparison of a previous version with the current one: size difference and whether the content differs.346 private static func comparison(_ v: FileVersion, with current: FileVersion) -> String {347 let delta = v.size - current.size348 let size = delta == 0 ? "même taille que l’actuelle" : "\(abs(delta).byteString) de \(delta > 0 ? "plus" : "moins") que l’actuelle"349 let content = v.sha256 == current.sha256 ? "contenu identique" : "contenu différent"350 return "\(size) · \(content)"351 }352353 // MARK: Actions354355 private func setPinned(_ on: Bool, item: DriveItem) {356 Task {357 if on {358 await model.perform { try await model.engine.pin(item.id) }359 } else {360 await model.engine.unpin(item.id)361 }362 }363 }364365 private func loadRemote(_ item: DriveItem) async {366 guard !item.isLocalOnly, item.parentID != nil else { return }367 if !item.isFolder {368 do {369 versions = try await model.api.fileDetail(id: item.id).versions.sorted { $0.seq > $1.seq }370 versionsPhase = .ready371 } catch {372 if let p = LinkLoadPhase.failure(error), versions.isEmpty || p == .offline { versionsPhase = p }373 }374 }375 await loadShareCount(item)376 }377378 private func loadShareCount(_ item: DriveItem) async {379 guard !item.isLocalOnly, item.parentID != nil else { return }380 do {381 shareCount = try await model.api.shares(fileID: item.isFolder ? nil : item.id, folderID: item.isFolder ? item.id : nil).count382 sharesOffline = false383 } catch {384 if !(error is CancellationError), shareCount == nil { sharesOffline = true }385 }386 }387388 private func download(_ v: FileVersion, of item: DriveItem) async {389 busyVersionID = v.id390 defer { busyVersionID = nil }391 await model.perform {392 let dir = Self.scratch.appendingPathComponent(v.id, isDirectory: true)393 try? FileManager.default.removeItem(at: dir)394 try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)395 let stem = (item.name as NSString).deletingPathExtension396 let ext = (item.name as NSString).pathExtension397 let destination = dir.appendingPathComponent(ext.isEmpty ? "\(stem) (version \(v.seq))" : "\(stem) (version \(v.seq)).\(ext)")398 let request = try await model.api.contentRequest(fileID: item.id, versionID: v.id, offset: 0, etag: nil)399 _ = try await model.api.download(request, to: destination, append: false)400 previewURL = destination401 }402 }403404 private func restore(_ v: FileVersion, of item: DriveItem) async {405 busyVersionID = v.id406 defer { busyVersionID = nil }407 await model.perform(success: "Version \(v.seq) restaurée") {408 _ = try await model.api.restoreVersion(fileID: item.id, versionID: v.id)409 await model.refresh()410 }411 await loadRemote(item)412 }413414 private func delete(_ v: FileVersion, of item: DriveItem) async {415 busyVersionID = v.id416 defer { busyVersionID = nil }417 await model.perform(success: "Version \(v.seq) supprimée") {418 try await model.api.deleteVersion(fileID: item.id, versionID: v.id)419 }420 await loadRemote(item)421 }422}423