SPB Git

Repository Public

PortalViews.swift 18.9 KB 265 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Shared/PortalViews.swift3// Description: Deposit links: let someone else send files into one folder without seeing anything in it. Create (expiry, password, size limits, allowed types), copy, pause, renew, revoke, and read what was received.4import SPDriveCore5import SwiftUI67struct PortalSheet: View {8    @Environment(AppModel.self) private var model9    @Environment(\.dismiss) private var dismiss10    let folder: DriveItem11    @State private var title = ""12    @State private var description = ""13    @State private var usePassword = false14    @State private var password = ""15    @State private var useExpiry = true16    @State private var expiry = Calendar.current.date(byAdding: .day, value: 14, to: Date()) ?? Date()17    @State private var maxFileMB = 20018    @State private var maxTotalGB = 519    @State private var maxFiles = 2020    @State private var extensions = ""21    @State private var subfolder = true22    @State private var notify = true23    // the remaining fields of a deposit request (parity with the web builder)24    @State private var instructions = ""25    @State private var confirmation = ""26    @State private var brandName = ""27    @State private var limitSubmissions = false28    @State private var maxSubmissions = 5029    @State private var perHour = 2030    @State private var askName = "optional"31    @State private var askEmail = "optional"32    @State private var askReference = "off"33    @State private var requireConsent = false34    @State private var consentText = ""35    @State private var retentionNote = ""36    @State private var busy = false37    @State private var error: String?38    @State private var created: URL?3940    var body: some View {41        VStack(alignment: .leading, spacing: 0) {42            HStack {43                VStack(alignment: .leading) { Text("Lien de dépôt vers « \(folder.name.isEmpty ? "Mon Drive" : folder.name) »").font(.headline); Text("Les déposants envoient des fichiers ; ils ne voient ni le dossier ni les dépôts des autres.").font(.caption).foregroundStyle(.secondary) }44                Spacer()45                Button(created == nil ? "Annuler" : "Terminé") { dismiss() }.keyboardShortcut(.cancelAction)46            }.padding(16)47            Divider()48            if let created {49                VStack(spacing: 14) {50                    Image(systemName: "checkmark.circle.fill").font(.system(size: 40)).foregroundStyle(.green)51                    Text("Lien de dépôt créé et copié").font(.title3.weight(.semibold))52                    Text(created.absoluteString).font(.callout.monospaced()).textSelection(.enabled).multilineTextAlignment(.center)53                    Button("Copier de nouveau") { Pickers.copy(created.absoluteString) }54                    Text("Cette adresse n’est affichée qu’une fois. Vous pourrez la renouveler depuis « Liens de dépôt ».").font(.caption).foregroundStyle(.secondary)55                }.frame(maxWidth: .infinity, maxHeight: .infinity).padding(24)56            } else {57                Form {58                    Section("Présentation") {59                        TextField("Titre affiché au déposant", text: $title)60                        TextField("Consigne (facultatif)", text: $description, axis: .vertical).lineLimit(2...4)61                        TextField("Instructions détaillées (facultatif)", text: $instructions, axis: .vertical).lineLimit(2...5)62                        TextField("Message affiché après le dépôt (facultatif)", text: $confirmation, axis: .vertical).lineLimit(1...3)63                        TextField("Nom affiché en en-tête (facultatif)", text: $brandName)64                    }65                    Section("Ce que le déposant indique") {66                        Picker("Nom", selection: $askName) { fieldChoices }67                        Picker("Courriel", selection: $askEmail) { fieldChoices }68                        Picker("Référence de dossier", selection: $askReference) { fieldChoices }69                        Toggle("Exiger un consentement", isOn: $requireConsent)70                        if requireConsent { TextField("Texte du consentement", text: $consentText, axis: .vertical).lineLimit(2...4) }71                        TextField("Note sur la conservation des fichiers (facultatif)", text: $retentionNote)72                    }73                    Section("Protection") {74                        Toggle("Mot de passe", isOn: $usePassword)75                        if usePassword { SecureField("Mot de passe (4 caractères ou plus)", text: $password) }76                        Toggle("Expiration", isOn: $useExpiry)77                        if useExpiry { DatePicker("Expire le", selection: $expiry, in: Date().addingTimeInterval(300)...) }78                    }79                    Section("Limites") {80                        Stepper("Taille maximale par fichier : \(maxFileMB) Mo", value: $maxFileMB, in: 1...2048, step: 50)81                        Stepper("Total accepté : \(maxTotalGB) Go", value: $maxTotalGB, in: 1...500)82                        Stepper("Fichiers par dépôt : \(maxFiles)", value: $maxFiles, in: 1...200)83                        Toggle("Limiter le nombre de dépôts", isOn: $limitSubmissions)84                        if limitSubmissions { Stepper("Au plus \(maxSubmissions) dépôts", value: $maxSubmissions, in: 1...10000) }85                        Stepper("Dépôts par heure : \(perHour)", value: $perHour, in: 1...1000)86                        TextField("Types acceptés (ex. pdf, docx — vide = tous sauf exécutables)", text: $extensions)87                    }88                    Section("Réception") {89                        Toggle("Un sous-dossier par dépôt", isOn: $subfolder)90                        Toggle("Me notifier à chaque dépôt", isOn: $notify)91                    }92                    if let error { Section { Label(error, systemImage: "exclamationmark.triangle.fill").foregroundStyle(.orange) } }93                    HStack { Spacer(); Button { Task { await create() } } label: { Label(busy ? "Création…" : "Créer et copier le lien", systemImage: "tray.and.arrow.down") }.buttonStyle(.borderedProminent)94                        .disabled(busy || title.trimmingCharacters(in: .whitespaces).isEmpty || (usePassword && password.count < 4) || (requireConsent && consentText.trimmingCharacters(in: .whitespaces).isEmpty)).accessibilityIdentifier("create-portal") }95                }.formStyle(.grouped)96            }97        }98        .frame(width: 580, height: 700)99        .onAppear { if title.isEmpty { title = "Dépôt de fichiers" + (folder.name.isEmpty ? "" : " — \(folder.name)") } }100    }101    @ViewBuilder private var fieldChoices: some View { Text("Non demandé").tag("off"); Text("Facultatif").tag("optional"); Text("Obligatoire").tag("required") }102    private func create() async {103        guard let api = model.api else { return }104        busy = true; defer { busy = false }105        var s = PortalSettings()106        s.folderId = folder.isRoot ? "root" : folder.id; s.title = title; s.description = description107        s.password = usePassword ? .some(password) : nil; s.expiresAt = useExpiry ? .some(expiry) : nil108        s.maxFileBytes = Int64(maxFileMB) * 1024 * 1024; s.maxTotalBytes = Int64(maxTotalGB) * 1024 * 1024 * 1024; s.maxFilesPerSubmission = maxFiles109        s.allowedExtensions = extensions.lowercased().split(whereSeparator: { !$0.isLetter && !$0.isNumber }).map(String.init)110        s.subfolderPerSubmission = subfolder; s.notifyOwner = notify111        do {112            // the engine's settings plus the fields only the 2.0 builder knows, in one request body113            var body = (try JSONSerialization.jsonObject(with: APIClient.encoder.encode(s)) as? [String: Any]) ?? [:]114            body["instructions"] = instructions; body["confirmationMessage"] = confirmation; body["brandName"] = brandName; body["retentionNote"] = retentionNote115            body["submissionsPerHour"] = perHour; body["maxSubmissions"] = limitSubmissions ? maxSubmissions : NSNull()116            body["fields"] = ["name": askName, "email": askEmail, "reference": askReference, "custom": [Any]()] as [String: Any]117            body["requireConsent"] = requireConsent; body["consentText"] = requireConsent ? consentText : ""118            let request = try api.request("POST", "/requests", body: try JSONSerialization.data(withJSONObject: body))119            let made = try APIClient.decoder.decode(APIClient.CreatedPortal.self, from: try await api.data(for: request).0)120            created = made.url; Pickers.copy(made.url.absoluteString); error = nil121        } catch { self.error = DriveError.wrap(error).errorDescription }122    }123}124125struct PortalsView: View {126    @Environment(AppModel.self) private var model127    @Environment(Navigator.self) private var nav128    @State private var portals: [DepositPortal] = []129    @State private var loading = true130    @State private var error: String?131    @State private var submissions: [String: [PortalSubmission]] = [:]132    @State private var fresh: [String: URL] = [:]133134    static func state(_ s: String) -> (String, Color) {135        switch s { case "open": ("Ouvert", .green); case "paused": ("En pause", .secondary); case "revoked": ("Révoqué", .secondary); case "expired": ("Expiré", .orange); case "full": ("Plein", .orange); default: ("Dossier supprimé", .secondary) }136    }137    var body: some View {138        Group {139            if portals.isEmpty {140                if loading { ProgressView() }141                else { ContentUnavailableView { Label("Aucun lien de dépôt", systemImage: "tray.and.arrow.down") } description: { Text(error ?? "Créez un lien de dépôt depuis le menu contextuel d’un dossier : d’autres personnes pourront y envoyer des fichiers sans rien voir de son contenu.") } actions: {142                    Button("Créer un lien vers Mon Drive") { if let id = model.rootID, let root = model.item(id) { nav.sheet = .portal(folder: root) } }143                } }144            } else {145                List {146                    ForEach(portals) { p in147                        VStack(alignment: .leading, spacing: 6) {148                            HStack {149                                Image(systemName: "tray.and.arrow.down").foregroundStyle(.secondary)150                                VStack(alignment: .leading, spacing: 2) {151                                    Text(p.title).fontWeight(.medium)152                                    Text(["dans « \(p.folderName?.isEmpty == false ? p.folderName! : "Mon Drive") »", "\(p.submissions) dépôt(s)", "\(Fmt.bytes(p.bytesReceived)) reçus sur \(Fmt.bytes(p.maxTotalBytes))", p.expiresAt.map { "expire le \(Fmt.date($0))" }, p.hasPassword ? "mot de passe" : nil].compactMap { $0 }.joined(separator: " · "))153                                        .font(.caption).foregroundStyle(.secondary)154                                }155                                Spacer()156                                let (text, color) = PortalsView.state(p.state)157                                Text(text).font(.caption).padding(.horizontal, 6).padding(.vertical, 2).background(color.opacity(0.15), in: Capsule()).foregroundStyle(color)158                                Menu {159                                    Button("Voir le dossier de réception", systemImage: "folder") { nav.open(folder: p.folderId == model.rootID ? nil : p.folderId) }160                                    Button(submissions[p.id] == nil ? "Afficher les dépôts reçus" : "Masquer les dépôts", systemImage: "list.bullet") { Task { await toggleSubmissions(p) } }161                                    if p.revokedAt == nil {162                                        Button(p.active ? "Mettre en pause" : "Rouvrir", systemImage: p.active ? "pause.circle" : "play.circle") { Task { await setActive(p, !p.active) } }163                                        Button("Renouveler l’adresse et copier", systemImage: "arrow.triangle.2.circlepath") { Task { await rotate(p) } }164                                        Button("Révoquer", systemImage: "xmark.circle", role: .destructive) { Task { await revoke(p, delete: false) } }165                                    } else { Button("Retirer de la liste", systemImage: "trash", role: .destructive) { Task { await revoke(p, delete: true) } } }166                                } label: { Image(systemName: "ellipsis.circle") }.menuStyle(.borderlessButton).fixedSize().accessibilityLabel("Actions du lien de dépôt")167                            }168                            if let u = fresh[p.id] { HStack { Text(u.absoluteString).font(.caption.monospaced()).lineLimit(1).truncationMode(.middle).textSelection(.enabled); Button("Copier") { Pickers.copy(u.absoluteString) }.controlSize(.small) } }169                            if let subs = submissions[p.id] {170                                if subs.isEmpty { Text("Aucun dépôt reçu.").font(.caption).foregroundStyle(.secondary) }171                                ForEach(subs) { s in172                                    HStack {173                                        Image(systemName: s.status == "completed" ? "checkmark.circle" : s.status == "rejected" ? "xmark.circle" : "clock").foregroundStyle(s.status == "completed" ? .green : .secondary)174                                        Text("\(Fmt.date(s.createdAt)) · \(s.name.isEmpty ? "Anonyme" : s.name) · \(s.placed) fichier(s) accepté(s)\(s.rejected > 0 ? ", \(s.rejected) refusé(s)" : "") · \(Fmt.bytes(s.bytes))").font(.caption)175                                        Spacer()176                                        if let f = s.folderId { Button("Ouvrir") { nav.open(folder: f == model.rootID ? nil : f) }.controlSize(.small) }177                                    }178                                }179                            }180                        }.padding(.vertical, 3)181                    }182                }183            }184        }185        .navigationTitle("Liens de dépôt")186        .toolbar { ToolbarItem { Button { Task { await reload() } } label: { Label("Actualiser", systemImage: "arrow.clockwise") } } }187        .task(id: nav.sheet == nil) { await reload() }188    }189    private func reload() async {190        guard let api = model.api else { return }191        do { portals = try await api.portals(); error = nil } catch { self.error = DriveError.wrap(error).errorDescription }192        loading = false193    }194    private func fail(_ e: Error) { model.banner = Banner(text: DriveError.wrap(e).errorDescription ?? "échec", isError: true) }195    private func toggleSubmissions(_ p: DepositPortal) async {196        if submissions[p.id] != nil { submissions[p.id] = nil; return }197        do { submissions[p.id] = try await model.api?.portalSubmissions(p.id) ?? [] } catch { fail(error) }198    }199    private func setActive(_ p: DepositPortal, _ on: Bool) async {200        var s = PortalSettings(); s.active = on201        do { _ = try await model.api?.updatePortal(p.id, s); await reload() } catch { fail(error) }202    }203    private func rotate(_ p: DepositPortal) async {204        do { if let u = try await model.api?.rotatePortal(p.id) { fresh[p.id] = u; Pickers.copy(u.absoluteString); model.banner = Banner(text: "Nouvelle adresse copiée. L’ancienne ne fonctionne plus.", isError: false) } } catch { fail(error) }205    }206    private func revoke(_ p: DepositPortal, delete: Bool) async {207        do { try await model.api?.revokePortal(p.id, delete: delete); fresh[p.id] = nil; await reload() } catch { fail(error) }208    }209}210211/// Version history of a file: read, download an old version, restore one (which adds a version: history only grows), delete one.212struct VersionsSheet: View {213    @Environment(AppModel.self) private var model214    @Environment(\.dismiss) private var dismiss215    let item: DriveItem216    @State private var details: FileDetails?217    @State private var error: String?218    @State private var busy = false219220    var body: some View {221        VStack(alignment: .leading, spacing: 0) {222            HStack { ItemIcon(item: item, size: 28); VStack(alignment: .leading) { Text("Versions de « \(item.name) »").font(.headline).lineLimit(1); Text("Restaurer une version en crée une nouvelle : rien n’est remplacé.").font(.caption).foregroundStyle(.secondary) }; Spacer(); Button("Terminé") { dismiss() }.keyboardShortcut(.cancelAction) }.padding(16)223            Divider()224            if let d = details {225                List(d.versions) { v in226                    HStack {227                        VStack(alignment: .leading, spacing: 2) {228                            HStack { Text("Version \(v.seq)").fontWeight(.medium); if v.current { Text("Actuelle").font(.caption).padding(.horizontal, 6).padding(.vertical, 2).background(Color.accentColor.opacity(0.15), in: Capsule()) } }229                            Text("\(Fmt.date(v.createdAt)) · \(Fmt.bytes(v.size))\(v.note.isEmpty ? "" : " · \(v.note)")\(sizeDelta(v, in: d.versions))").font(.caption).foregroundStyle(.secondary)230                            Text(v.sha256.prefix(16) + "…").font(.caption2.monospaced()).foregroundStyle(.tertiary)231                        }232                        Spacer()233                        Button("Télécharger") { Task { await model.download([item], version: v) } }.controlSize(.small)234                        if !v.current {235                            Button("Restaurer") { Task { await restore(v) } }.controlSize(.small).disabled(busy)236                            Button(role: .destructive) { Task { await delete(v) } } label: { Image(systemName: "trash") }.controlSize(.small).disabled(busy).help("Supprimer cette version").accessibilityLabel("Supprimer la version \(v.seq)")237                        }238                    }.padding(.vertical, 2)239                }240            } else if let error { ContentUnavailableView("Historique indisponible", systemImage: "wifi.slash", description: Text(error)) }241            else { ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity) }242        }243        .frame(width: 560, height: 480)244        .task { await reload() }245    }246    /// Size difference with the version just before, as a comparison of metadata.247    private func sizeDelta(_ v: FileVersion, in all: [FileVersion]) -> String {248        guard let prev = all.first(where: { $0.seq == v.seq - 1 }) else { return "" }249        let d = v.size - prev.size250        return d == 0 ? (v.sha256 == prev.sha256 ? " · identique à la précédente" : " · même taille") : " · \(d > 0 ? "+" : "−")\(Fmt.bytes(abs(d)))"251    }252    private func reload() async {253        do { details = try await model.api?.fileDetails(item.id); error = nil } catch { self.error = DriveError.wrap(error).errorDescription }254    }255    private func restore(_ v: FileVersion) async {256        busy = true; defer { busy = false }257        do { if let updated = try await model.api?.restoreVersion(fileID: item.id, versionID: v.id) { try? model.store?.upsert([updated]) }; await model.syncNow(); await reload() }258        catch { self.error = DriveError.wrap(error).errorDescription }259    }260    private func delete(_ v: FileVersion) async {261        busy = true; defer { busy = false }262        do { try await model.api?.deleteVersion(fileID: item.id, versionID: v.id); await reload() } catch { self.error = DriveError.wrap(error).errorDescription }263    }264}265
Files main
Menu

Theme