Repository Public
1// SP Drive iOS2// File: Features/Settings/ProblemsScreen.swift3// Description: Everything that waits for a decision of the user: version conflicts (never resolved silently) and operations the server refused.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import SwiftUI89struct ProblemsScreen: View {10 @Environment(AppModel.self) private var model11 @State private var failedOps: [PendingOp]?12 @State private var busyConflicts: Set<Int64> = []13 @State private var busyOps: Set<Int64> = []14 @State private var discardCandidate: ConflictRecord?15 @State private var comparing: ConflictRecord?1617 var body: some View {18 let itemsVersion = model.itemsVersion19 let conflictsVersion = model.conflictsVersion20 let conflicts = model.store.conflicts()21 let conflictItems = Set(conflicts.map(\.itemID))22 // an upload stopped by a version conflict is shown once, as a conflict23 let ops = (failedOps ?? []).filter { !(isUpload($0) && conflictItems.contains($0.itemID)) }2425 Group {26 if conflicts.isEmpty && ops.isEmpty {27 if failedOps == nil {28 ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity)29 } else {30 EmptyState(symbol: "checkmark.icloud", title: "Tout est synchronisé",31 message: "Aucun conflit, aucune opération refusée. Si un fichier est modifié à deux endroits en même temps, tu choisiras ici quoi garder.")32 .accessibilityIdentifier("problems.empty")33 }34 } else {35 List {36 if !conflicts.isEmpty {37 Section {38 ForEach(conflicts) { conflictRow($0) }39 } header: {40 Text("Conflits (\(conflicts.count))")41 } footer: {42 Text("Tant que tu n’as pas choisi, les deux versions sont conservées : la tienne sur cet appareil, l’autre sur le Drive.")43 }44 }45 if !ops.isEmpty {46 Section {47 ForEach(ops) { opRow($0) }48 } header: {49 Text("Opérations refusées (\(ops.count))")50 } footer: {51 Text("Le Drive a refusé ces changements faits sur cet appareil. « Réessayer » les renvoie ; « Ignorer » y renonce et garde l’état du Drive.")52 }53 }54 }55 .listStyle(.insetGrouped)56 .accessibilityIdentifier("problems.list")57 }58 }59 .navigationTitle("Conflits et problèmes")60 .sheet(item: $comparing) { ConflictSheet(conflict: $0) }61 .task(id: [itemsVersion, conflictsVersion]) { failedOps = await model.engine.failedOps() }62 .confirmationDialog(discardTitle, isPresented: discardDialogShown, titleVisibility: .visible, presenting: discardCandidate) { c in63 Button(c.reason == .bothModified ? "Abandonner ma version" : "Abandonner mes modifications", role: .destructive) { resolve(c, .keepServer) }64 .accessibilityIdentifier("problems.confirmDiscard")65 Button("Annuler", role: .cancel) {}66 } message: { c in67 Text(c.reason == .bothModified68 ? "Les modifications faites sur cet appareil à « \(c.name) » seront effacées et remplacées par la version du Drive. Elles n’ont jamais été envoyées : elles ne pourront pas être récupérées."69 : "« \(c.name) » a été supprimé sur le Drive. Tes modifications faites sur cet appareil seront effacées et ne pourront pas être récupérées.")70 }71 }7273 private var discardTitle: String { "Abandonner tes modifications ?" }74 private var discardDialogShown: Binding<Bool> {75 Binding(get: { discardCandidate != nil }, set: { if !$0 { discardCandidate = nil } })76 }77 private func isUpload(_ op: PendingOp) -> Bool { op.kind == .uploadNew || op.kind == .uploadVersion }7879 // MARK: Conflicts8081 private func conflictRow(_ c: ConflictRecord) -> some View {82 let busy = busyConflicts.contains(c.id)83 return VStack(alignment: .leading, spacing: 10) {84 HStack(alignment: .top, spacing: 12) {85 KindIcon(kind: FileKind(extension: (c.name as NSString).pathExtension.lowercased()))86 VStack(alignment: .leading, spacing: 3) {87 Text(c.name).font(.body.weight(.semibold)).lineLimit(3)88 Text(c.reason == .bothModified89 ? "Modifié ici et sur un autre appareil ; rien n’a été écrasé."90 : "Modifié ici, supprimé sur le Drive. Tes modifications sont toujours sur cet appareil.")91 .font(.subheadline).foregroundStyle(.secondary)92 .fixedSize(horizontal: false, vertical: true)93 Text("Détecté \(c.detectedAt.shortRelative)").font(.caption).foregroundStyle(.tertiary)94 }95 if busy { Spacer(minLength: 4); ProgressView() }96 }97 .accessibilityElement(children: .combine)9899 VStack(alignment: .leading, spacing: 8) {100 Button { comparing = c } label: { Label("Comparer les deux versions…", systemImage: "rectangle.split.2x1").frame(maxWidth: .infinity, alignment: .leading) }101 .buttonStyle(.borderedProminent).tint(SPDTheme.Palette.brand)102 .accessibilityIdentifier("problems.compare")103 switch c.reason {104 case .bothModified:105 choice("Garder les deux", symbol: "doc.on.doc", note: "Ta version devient un fichier à part, à côté de l’original.", id: "problems.keepBoth") { resolve(c, .keepBoth) }106 choice("Garder ma version", symbol: "iphone", note: "Elle devient la version courante ; celle du serveur reste dans l’historique du fichier.", id: "problems.keepMine") { resolve(c, .keepMine) }107 choice("Garder la version du serveur", symbol: "icloud", note: "Tes modifications faites ici sont abandonnées.", destructive: true, id: "problems.keepServer") { discardCandidate = c }108 case .remoteDeleted:109 choice("Renvoyer comme nouveau fichier", symbol: "arrow.up.doc", note: "Ta version retourne sur le Drive comme un nouveau fichier.", id: "problems.resend") { resolve(c, .keepMine) }110 choice("Abandonner mes modifications", symbol: "trash", note: "Le fichier reste supprimé ; ta copie locale est effacée.", destructive: true, id: "problems.discard") { discardCandidate = c }111 }112 }113 .disabled(busy)114 }115 .padding(.vertical, 6)116 .accessibilityIdentifier("problems.conflict.\(c.id)")117 }118119 private func choice(_ title: String, symbol: String, note: String, prominent: Bool = false, destructive: Bool = false, id: String, action: @escaping () -> Void) -> some View {120 VStack(alignment: .leading, spacing: 2) {121 Group {122 if prominent {123 Button(action: action) { Label(title, systemImage: symbol).frame(maxWidth: .infinity, alignment: .leading) }.buttonStyle(.borderedProminent)124 } else {125 Button(role: destructive ? .destructive : nil, action: action) { Label(title, systemImage: symbol).frame(maxWidth: .infinity, alignment: .leading) }.buttonStyle(.bordered)126 }127 }128 .accessibilityIdentifier(id)129 .accessibilityHint(note)130 Text(note).font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)131 }132 }133134 private func resolve(_ c: ConflictRecord, _ choice: ConflictChoice) {135 guard !busyConflicts.contains(c.id) else { return }136 busyConflicts.insert(c.id)137 let success: String138 switch (c.reason, choice) {139 case (.bothModified, .keepBoth): success = "Les deux versions sont conservées"140 case (.bothModified, .keepMine): success = "Ta version sera envoyée comme version courante"141 case (.remoteDeleted, .keepBoth), (.remoteDeleted, .keepMine): success = "Renvoyé comme nouveau fichier"142 case (.bothModified, .keepServer): success = "Version du serveur conservée"143 case (.remoteDeleted, .keepServer): success = "Modifications abandonnées"144 }145 Task {146 await model.perform(success: success) {147 try await model.engine.resolve(c.id, choice: choice, deviceName: AppConfiguration.deviceName)148 }149 busyConflicts.remove(c.id)150 }151 }152153 // MARK: Refused operations154155 private func opRow(_ op: PendingOp) -> some View {156 let busy = busyOps.contains(op.id)157 return VStack(alignment: .leading, spacing: 8) {158 VStack(alignment: .leading, spacing: 3) {159 Label(describe(op), systemImage: symbol(op)).font(.body.weight(.medium))160 Text(reason(op)).font(.subheadline).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true)161 Text("Demandé \(op.createdAt.shortRelative)").font(.caption).foregroundStyle(.tertiary)162 }163 .accessibilityElement(children: .combine)164 HStack(spacing: 12) {165 Button { retry(op) } label: { Label("Réessayer", systemImage: "arrow.clockwise") }166 .buttonStyle(.borderedProminent)167 .accessibilityIdentifier("problems.retry.\(op.id)")168 Button(role: .destructive) { dismiss(op) } label: { Label(op.kind == .uploadVersion ? "Abandonner mes modifications" : op.kind == .uploadNew ? "Ne pas envoyer" : "Ignorer", systemImage: "xmark") }169 .buttonStyle(.bordered)170 .accessibilityIdentifier("problems.dismiss.\(op.id)")171 if busy { ProgressView() }172 }173 .disabled(busy)174 }175 .padding(.vertical, 6)176 }177178 /// The transfer that carries (or carried) the content of an upload operation, if it is still in the queue.179 private func transfer(of op: PendingOp) -> TransferRecord? {180 guard isUpload(op) else { return nil }181 return model.store.transfers(states: [.failed, .paused, .queued, .running]).first { $0.kind == .upload && $0.opID == op.id }182 }183184 private func retry(_ op: PendingOp) {185 busyOps.insert(op.id)186 let stuck = transfer(of: op)187 Task {188 // a refused upload restarts through its transfer (which re-arms the operation); other operations are simply replayed189 if let stuck, stuck.state == .failed || stuck.state == .paused { await model.engine.resume(stuck.id) }190 else { await model.engine.retryFailedOp(op.id) }191 failedOps = await model.engine.failedOps()192 busyOps.remove(op.id)193 }194 }195196 private func dismiss(_ op: PendingOp) {197 busyOps.insert(op.id)198 let stuck = transfer(of: op)199 Task {200 // giving up an upload also removes its transfer from the queue (and, for a file never sent, the file itself from SP Drive)201 if let stuck { await model.engine.cancel(stuck.id) }202 await model.engine.dismissFailedOp(op.id)203 failedOps = await model.engine.failedOps()204 busyOps.remove(op.id)205 }206 }207208 private func name(_ id: String?, fallback: String? = nil) -> String {209 if let id, let n = model.store.item(id)?.name { return "« \(n) »" }210 if let fallback, !fallback.isEmpty { return "« \(fallback) »" }211 return "un élément qui n’existe plus"212 }213214 private func describe(_ op: PendingOp) -> String {215 switch op.kind {216 case .createFolder: "Créer le dossier \(name(nil, fallback: op.name ?? model.store.item(op.itemID)?.name))"217 case .rename: "Renommer \(name(op.itemID)) en « \(op.name ?? "?") »"218 case .move: "Déplacer \(name(op.itemID)) vers \(name(op.targetID))"219 case .trash: "Mettre \(name(op.itemID)) à la corbeille"220 case .restore: "Restaurer \(name(op.itemID))"221 case .star: op.flag ? "Ajouter \(name(op.itemID)) aux favoris" : "Retirer \(name(op.itemID)) des favoris"222 case .purge: "Supprimer définitivement \(name(op.itemID))"223 case .uploadNew: "Envoyer \(name(op.itemID, fallback: op.name))"224 case .uploadVersion: "Envoyer la nouvelle version de \(name(op.itemID))"225 }226 }227228 private func symbol(_ op: PendingOp) -> String {229 switch op.kind {230 case .createFolder: "folder.badge.plus"; case .rename: "pencil"; case .move: "folder"; case .trash: "trash"; case .restore: "arrow.uturn.backward"231 case .star: "star"; case .purge: "trash.slash"; case .uploadNew, .uploadVersion: "arrow.up.circle"232 }233 }234235 private func reason(_ op: PendingOp) -> String {236 switch op.errorCode {237 case "cancelled": "Tu as annulé cet envoi. Tes modifications sont toujours sur cet appareil."238 case "name_conflict": "Un élément du même nom existe déjà à cet endroit sur le Drive."239 case "not_found": "L’élément (ou son dossier) n’existe plus sur le Drive."240 case "quota": "Ton Drive est plein : libère de l’espace sur le Drive, puis réessaie."241 case "missing_item": "L’élément visé n’a jamais pu être créé sur le Drive."242 case "missing_file": "Le fichier à envoyer est introuvable sur cet appareil."243 case "conflict": "Le fichier a changé sur le Drive entre-temps. Rien n’a été écrasé."244 case "too_large": "Ce fichier dépasse la taille maximale acceptée par le Drive."245 case "infected": "L’antivirus du Drive a signalé ce fichier."246 case "checksum": "Le contenu reçu par le Drive ne correspondait pas à l’original."247 case "disk": "Impossible de préparer l’envoi sur cet appareil. Vérifie l’espace libre."248 case "unauthenticated": "Ta session avait pris fin. Réessaie maintenant que tu es connecté."249 case "network": "Le réseau a lâché trop souvent pendant l’envoi."250 case "refused", "server", nil, "": "Le Drive a refusé cette opération."251 case .some(let code): "Le Drive a refusé cette opération (\(code))."252 }253 }254}255