Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Shared/ShareSheet.swift3// Description: Share links of one file or folder: create (permission, password, expiry, limits, single use), copy, renew the address, revoke, and read the access history. A link's address exists only when it is created or renewed: the server keeps a hash.4import SPDriveCore5import SwiftUI67struct ShareSheet: View {8 @Environment(AppModel.self) private var model9 @Environment(\.dismiss) private var dismiss10 let item: DriveItem11 @State private var links: [DriveShare] = []12 @State private var loading = true13 @State private var error: String?14 @State private var freshURL: [String: URL] = [:] // addresses shown once, by link15 @State private var events: [String: [ShareAccessEvent]] = [:]16 // new link17 @State private var label = ""18 @State private var canDownload = true19 @State private var usePassword = false20 @State private var password = ""21 @State private var useExpiry = false22 @State private var expiry = Calendar.current.date(byAdding: .day, value: 7, to: Date()) ?? Date()23 @State private var limitDownloads = false24 @State private var maxDownloads = 1025 @State private var singleUse = false26 @State private var busy = false2728 var body: some View {29 VStack(alignment: .leading, spacing: 0) {30 HStack(spacing: 10) {31 ItemIcon(item: item, size: 28)32 VStack(alignment: .leading) { Text("Partager « \(item.name) »").font(.headline).lineLimit(1); Text(item.isFolder ? "Lien vers ce dossier et son contenu, rien d’autre." : "Lien vers ce fichier, rien d’autre.").font(.caption).foregroundStyle(.secondary) }33 Spacer()34 Button("Terminé") { dismiss() }.keyboardShortcut(.cancelAction)35 }36 .padding(16)37 Divider()38 Form {39 Section("Nouveau lien") {40 TextField("Libellé (pour vous y retrouver)", text: $label)41 Picker("Permission", selection: $canDownload) { Text("Consultation et téléchargement").tag(true); Text("Consultation seulement").tag(false) }42 Toggle("Protéger par un mot de passe", isOn: $usePassword)43 if usePassword { SecureField("Mot de passe (4 caractères ou plus)", text: $password) }44 Toggle("Expiration", isOn: $useExpiry)45 if useExpiry { DatePicker("Expire le", selection: $expiry, in: Date().addingTimeInterval(300)...) }46 Toggle("Limiter le nombre de téléchargements", isOn: $limitDownloads)47 if limitDownloads { Stepper("Au plus \(maxDownloads) téléchargement\(maxDownloads > 1 ? "s" : "")", value: $maxDownloads, in: 1...1000) }48 Toggle("Usage unique (une seule ouverture)", isOn: $singleUse)49 HStack { Spacer(); Button { Task { await create() } } label: { Label(busy ? "Création…" : "Créer et copier le lien", systemImage: "link.badge.plus") }.buttonStyle(.borderedProminent).disabled(busy || (usePassword && password.count < 4)).accessibilityIdentifier("create-share") }50 }51 if let error { Section { Label(error, systemImage: "exclamationmark.triangle.fill").foregroundStyle(.orange) } }52 Section("Liens existants") {53 if loading { ProgressView() }54 else if links.isEmpty { Text("Aucun lien pour cet élément.").foregroundStyle(.secondary) }55 ForEach(links) { l in ShareRow(link: l, url: freshURL[l.id], events: events[l.id], copy: { copy(l) }, rotate: { Task { await rotate(l) } }, revoke: { Task { await revoke(l) } }, history: { Task { await history(l) } }) }56 }57 }58 .formStyle(.grouped)59 }60 .frame(width: 560, height: 640)61 .task { await reload() }62 }63 private func reload() async {64 guard let api = model.api else { return }65 do { links = try await api.shares(of: item); error = nil } catch { self.error = DriveError.wrap(error).errorDescription }66 loading = false67 await model.refreshShares()68 }69 private func create() async {70 guard let api = model.api else { return }71 busy = true; defer { busy = false }72 do {73 let s = ShareSettings(label: label, canDownload: canDownload, password: usePassword ? .some(password) : nil, expiresAt: useExpiry ? .some(expiry) : nil,74 maxDownloads: limitDownloads ? .some(maxDownloads) : nil, singleUse: singleUse)75 let made = try await api.createShare(for: item, settings: s)76 freshURL[made.share.id] = made.url77 Pickers.copy(made.url.absoluteString)78 model.banner = Banner(text: "Lien copié dans le presse-papiers.", isError: false)79 label = ""; password = ""; usePassword = false80 await reload()81 } catch { self.error = DriveError.wrap(error).errorDescription }82 }83 private func copy(_ l: DriveShare) { if let u = freshURL[l.id] { Pickers.copy(u.absoluteString); model.banner = Banner(text: "Lien copié.", isError: false) } }84 private func rotate(_ l: DriveShare) async {85 guard let api = model.api else { return }86 do { let u = try await api.rotateShare(l.id); freshURL[l.id] = u; Pickers.copy(u.absoluteString); model.banner = Banner(text: "Nouvelle adresse copiée. L’ancienne ne fonctionne plus.", isError: false) }87 catch { self.error = DriveError.wrap(error).errorDescription }88 }89 private func revoke(_ l: DriveShare) async {90 guard let api = model.api else { return }91 do { try await api.revokeShare(l.id, delete: !l.isActive); freshURL[l.id] = nil; await reload() } catch { self.error = DriveError.wrap(error).errorDescription }92 }93 private func history(_ l: DriveShare) async {94 guard let api = model.api else { return }95 if events[l.id] != nil { events[l.id] = nil; return }96 events[l.id] = (try? await api.shareEvents(l.id)) ?? []97 }98}99100struct ShareRow: View {101 let link: DriveShare102 let url: URL?103 let events: [ShareAccessEvent]?104 let copy: () -> Void, rotate: () -> Void, revoke: () -> Void, history: () -> Void105 static func status(_ s: String) -> (String, Color) {106 switch s { case "active": ("Actif", .green); case "revoked": ("Révoqué", .secondary); case "expired": ("Expiré", .orange); case "exhausted": ("Limite atteinte", .orange); default: ("Cible supprimée", .secondary) }107 }108 var body: some View {109 let (text, color) = ShareRow.status(link.status)110 VStack(alignment: .leading, spacing: 6) {111 HStack {112 Text(link.label.isEmpty ? "Lien du \(Fmt.date(link.createdAt))" : link.label).fontWeight(.medium).lineLimit(1)113 Text(text).font(.caption).padding(.horizontal, 6).padding(.vertical, 2).background(color.opacity(0.15), in: Capsule()).foregroundStyle(color)114 Spacer()115 Menu {116 if link.isActive {117 Button("Renouveler l’adresse et copier", systemImage: "arrow.triangle.2.circlepath", action: rotate)118 Button("Révoquer", systemImage: "xmark.circle", role: .destructive, action: revoke)119 } else { Button("Retirer de la liste", systemImage: "trash", role: .destructive, action: revoke) }120 Button(events == nil ? "Afficher l’historique d’accès" : "Masquer l’historique", systemImage: "list.bullet.rectangle", action: history)121 } label: { Image(systemName: "ellipsis.circle") }.menuStyle(.borderlessButton).fixedSize().accessibilityLabel("Actions du lien")122 }123 Text([link.canDownload ? "Téléchargement permis" : "Consultation seule", link.hasPassword ? "mot de passe" : nil, link.expiresAt.map { "expire le \(Fmt.date($0))" },124 link.maxDownloads.map { "\(link.downloadCount)/\($0) téléchargements" } ?? "\(link.downloadCount) téléchargement(s)", "\(link.viewCount) ouverture(s)", link.singleUse ? "usage unique" : nil].compactMap { $0 }.joined(separator: " · "))125 .font(.caption).foregroundStyle(.secondary)126 if let url {127 HStack { Text(url.absoluteString).font(.caption.monospaced()).lineLimit(1).truncationMode(.middle).textSelection(.enabled); Button("Copier", action: copy).controlSize(.small) }128 HStack(alignment: .top, spacing: 12) {129 QRCodeView(text: url.absoluteString, side: 110)130 Text("Code QR de cette adresse, dessiné sur ce Mac. Comme l’adresse, il n’est disponible que maintenant : renouvelez le lien pour en obtenir un autre.").font(.caption).foregroundStyle(.secondary)131 }132 } else if link.isActive {133 Text("L’adresse n’est affichée qu’à la création : renouvelez-la pour en obtenir une nouvelle.").font(.caption).foregroundStyle(.tertiary)134 }135 if let events {136 if events.isEmpty { Text("Aucun accès enregistré.").font(.caption).foregroundStyle(.secondary) }137 ForEach(events.prefix(20)) { e in138 HStack { Image(systemName: e.ok ? "checkmark.circle" : "xmark.circle").foregroundStyle(e.ok ? .green : .orange); Text("\(Fmt.date(e.at)) · \(e.kind) · \(e.ip)").font(.caption).foregroundStyle(.secondary) }139 }140 }141 }142 .padding(.vertical, 2)143 }144}145146/// "Partagés par moi": every share link of the account.147struct SharesView: View {148 @Environment(AppModel.self) private var model149 @Environment(Navigator.self) private var nav150 @State private var loading = true151 var body: some View {152 Group {153 if model.shares.isEmpty {154 if loading { ProgressView() }155 else { ContentUnavailableView("Aucun lien de partage", systemImage: "link", description: Text("Créez un lien depuis le menu contextuel d’un fichier ou d’un dossier.")) }156 } else {157 List(model.shares) { l in158 HStack {159 Image(systemName: l.type == .folder ? "folder" : "doc").foregroundStyle(.secondary)160 VStack(alignment: .leading, spacing: 2) {161 Text(l.targetName.isEmpty ? "(élément supprimé)" : l.targetName).fontWeight(.medium)162 Text([l.label.isEmpty ? nil : l.label, "créé le \(Fmt.date(l.createdAt))", l.expiresAt.map { "expire le \(Fmt.date($0))" }, l.hasPassword ? "mot de passe" : nil, "\(l.viewCount) ouverture(s)"].compactMap { $0 }.joined(separator: " · ")).font(.caption).foregroundStyle(.secondary)163 }164 Spacer()165 let (text, color) = ShareRow.status(l.status)166 Text(text).font(.caption).padding(.horizontal, 6).padding(.vertical, 2).background(color.opacity(0.15), in: Capsule()).foregroundStyle(color)167 Button("Gérer") { if let id = l.targetId, let item = model.item(id) { nav.sheet = .share(item) } }.disabled(l.targetId.flatMap { model.item($0) } == nil)168 }169 .padding(.vertical, 3)170 .contextMenu {171 if let id = l.targetId, let item = model.item(id) { Button("Afficher l’élément") { nav.open(folder: item.isFolder ? item.id : (item.parentID == model.rootID ? nil : item.parentID)); nav.selection = [item.id] } }172 if l.isActive { Button("Révoquer", role: .destructive) { Task { try? await model.api?.revokeShare(l.id); await model.refreshShares() } } }173 }174 }175 }176 }177 .navigationTitle("Partagés par moi")178 .toolbar { ToolbarItem { Button { Task { await model.refreshShares() } } label: { Label("Actualiser", systemImage: "arrow.clockwise") } } }179 .task { await model.refreshShares(); loading = false }180 }181}182