Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Next/SharedWithMeView.swift3// Description: "Partagés avec moi": folders other accounts shared with this one, browsed through the grant routes of the server (they are not part of this account's tree, nor of its Finder location). The interface follows the role: a reader browses, previews and downloads; an editor also creates, renames, uploads and trashes; a depositor only sends files in. An action the role does not allow is absent, and a 403 from the server is said as such.4import AppKit5import SPDriveCore6import SPDriveNext7import SwiftUI89struct SharedWithMeView: View {10 @Environment(AppModel.self) private var model11 @Environment(Navigator.self) private var nav12 @State private var grant: SharedGrant?13 @State private var folderID: String?14 @State private var listing: Loadable<SharedListing> = .loading15 @State private var selection: Set<String> = []16 @State private var note: String?17 @State private var renaming: (id: String, name: String)?18 @State private var newFolder = false19 @State private var newName = ""20 @State private var uploads: [String: Double] = [:]21 @State private var dropTargeted = false2223 var body: some View {24 Group {25 if let g = grant { inside(g) } else { grantList }26 }27 .navigationTitle(grant?.displayName ?? "Partagés avec moi")28 .navigationSubtitle(grant.map { "Partagé par \($0.owner.displayName) · \(NextText.role($0.role))" } ?? "")29 .task { await model.refreshGrants() }30 .accessibilityIdentifier("shared-with-me")31 }32 private var grantList: some View {33 Group {34 if model.grants.isEmpty {35 SPDEmptyState(symbol: "person.2", title: "Rien n’est partagé avec vous", message: "Quand une autre personne de ce serveur vous donne accès à l’un de ses dossiers, il apparaît ici. Vous n’y voyez que ce dossier, jamais le reste de son Drive.")36 } else {37 List(model.grants) { g in38 Button { open(g) } label: {39 HStack(spacing: SPDTheme.Space.md) {40 Image(systemName: g.role == .uploader ? "tray.and.arrow.down.fill" : "folder.fill.badge.person.crop").font(.title2).foregroundStyle(SPDTheme.brand).frame(width: 34)41 VStack(alignment: .leading, spacing: 1) {42 Text(g.displayName).font(SPDTheme.Typo.bodyStrong)43 Text("Partagé par \(g.owner.displayName)\(g.createdAt.map { " le \(Fmt.day($0))" } ?? "")").font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary)44 }45 Spacer()46 SPDPill(text: NextText.role(g.role), symbol: g.role == .viewer ? "eye" : g.role == .editor ? "pencil" : "tray.and.arrow.down", tint: SPDTheme.brand)47 Image(systemName: "chevron.right").font(.caption).foregroundStyle(SPDTheme.textTertiary)48 }.contentShape(Rectangle()).padding(.vertical, 4)49 }.buttonStyle(.plain)50 }.listStyle(.inset)51 }52 }53 }54 private func open(_ g: SharedGrant) { grant = g; folderID = nil; selection = []; note = nil; listing = .loading; Task { await load() } }5556 private func crumbs(_ g: SharedGrant) -> some View {57 let list = listing.value?.breadcrumbs ?? [NextCrumb(id: g.folder.id, name: g.displayName)]58 let here = listing.value?.folder.id59 return HStack(spacing: 2) {60 Button { grant = nil } label: { Label("Partagés avec moi", systemImage: "person.2") }.buttonStyle(.plain).foregroundStyle(SPDTheme.textSecondary).font(SPDTheme.Typo.callout)61 ForEach(list) { c in62 Image(systemName: "chevron.compact.right").font(.system(size: 11)).foregroundStyle(SPDTheme.textTertiary)63 Button(c.id == g.folder.id ? g.displayName : c.name) { folderID = c.id == g.folder.id ? nil : c.id; Task { await load() } }64 .buttonStyle(.plain).font(c.id == here ? SPDTheme.Typo.bodyStrong : SPDTheme.Typo.callout)65 }66 Spacer()67 }68 .padding(.horizontal, SPDTheme.Space.md).frame(height: 30).background(.bar).overlay(alignment: .bottom) { Rectangle().fill(SPDTheme.hairline).frame(height: 1) }69 }70 @ViewBuilder private func body(of g: SharedGrant) -> some View {71 if g.role == .uploader { depositOnly(g) }72 else {73 switch listing {74 case .loading: ProgressView().frame(maxWidth: .infinity, maxHeight: .infinity)75 case .failed(let m): SPDEmptyState(symbol: "exclamationmark.triangle", title: "Dossier indisponible", message: m) { Button("Revenir à la liste") { grant = nil; Task { await model.refreshGrants() } } }76 case .ready(let l): browser(g, l)77 }78 }79 }80 private func dropped(_ providers: [NSItemProvider], _ g: SharedGrant) -> Bool {81 guard g.role.canUpload else { return false }82 let group = DispatchGroup(), box = LockedList<URL>()83 for p in providers { group.enter(); _ = p.loadObject(ofClass: URL.self) { u, _ in if let u { box.append(u) }; group.leave() } }84 group.notify(queue: .main) { MainActor.assumeIsolated { let urls = box.values; Task { await send(urls, g) } } }85 return true86 }87 private func progressList() -> some View {88 VStack(spacing: 4) {89 ForEach(uploads.sorted { $0.key < $1.key }, id: \.key) { name, f in HStack { Text(name).font(SPDTheme.Typo.caption).lineLimit(1); ProgressView(value: f).controlSize(.small) } }90 }.padding(SPDTheme.Space.sm)91 }92 private func inside(_ g: SharedGrant) -> some View {93 let dropLabel = g.role.canUpload ? "Déposer dans « \(listing.value?.folder.name ?? g.displayName) »" : ""94 let main = VStack(spacing: 0) {95 crumbs(g)96 if let note { Label(note, systemImage: "info.circle").font(SPDTheme.Typo.callout).foregroundStyle(SPDTheme.warning).padding(SPDTheme.Space.sm).frame(maxWidth: .infinity, alignment: .leading).background(SPDTheme.warning.opacity(0.08)) }97 if !uploads.isEmpty { progressList() }98 body(of: g)99 .frame(maxWidth: .infinity, maxHeight: .infinity).background(SPDTheme.canvas)100 .overlay { DropOverlay(active: dropTargeted, label: dropLabel) }101 .onDrop(of: [.fileURL], isTargeted: Binding(get: { dropTargeted }, set: { dropTargeted = $0 && g.role.canUpload })) { dropped($0, g) }102 }103 return main104 .toolbar {105 ToolbarItemGroup {106 if g.role.canUpload { Button { let urls = Pickers.chooseUploads().filter { !$0.hasDirectoryPath }; Task { await send(urls, g) } } label: { Label("Téléverser", systemImage: "arrow.up.doc") }.help("Envoyer des fichiers dans ce dossier (ils comptent dans l’espace de son propriétaire)") }107 if g.role.canWrite { Button { newName = "Nouveau dossier"; newFolder = true } label: { Label("Nouveau dossier", systemImage: "folder.badge.plus") }.help("Nouveau dossier") }108 if g.role.canList { Button { Task { await load() } } label: { Label("Actualiser", systemImage: "arrow.clockwise") }.help("Les dossiers partagés ne sont pas synchronisés en continu : actualisez pour voir les changements") }109 }110 }111 .alert("Nouveau dossier", isPresented: $newFolder) {112 TextField("Nom", text: $newName)113 Button("Créer") { Task { await act(g) { _ = try await $0.sharedCreateFolder(grant: g.grantId, parentID: folderID, name: newName) } } }114 Button("Annuler", role: .cancel) {}115 }116 .alert("Renommer", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {117 TextField("Nom", text: Binding(get: { renaming?.name ?? "" }, set: { renaming?.name = $0 }))118 Button("Renommer") { if let r = renaming { Task { await act(g) { _ = try await $0.sharedUpdateItem(grant: g.grantId, itemID: r.id, name: r.name) } } } }119 Button("Annuler", role: .cancel) {}120 }121 }122 private func depositOnly(_ g: SharedGrant) -> some View {123 SPDEmptyState(symbol: "tray.and.arrow.down", title: "Dépôt seulement", message: "\(g.owner.displayName) vous permet d’envoyer des fichiers dans « \(g.displayName) », sans en voir le contenu. Glissez des fichiers ici ou choisissez-les ; ils comptent dans l’espace de \(g.owner.displayName).") {124 Button("Choisir des fichiers…") { let urls = Pickers.chooseUploads().filter { !$0.hasDirectoryPath }; Task { await send(urls, g) } }.buttonStyle(.borderedProminent)125 }126 }127 @ViewBuilder private func browser(_ g: SharedGrant, _ l: SharedListing) -> some View {128 if l.folders.isEmpty && l.files.isEmpty {129 SPDEmptyState(symbol: "folder", title: "Dossier vide", message: g.role.canWrite ? "Glissez des fichiers ici pour les ajouter à ce dossier partagé." : "Ce dossier partagé ne contient rien pour l’instant.")130 } else {131 List(selection: $selection) {132 ForEach(l.folders) { f in133 Label(f.name, systemImage: "folder.fill").tag(f.id)134 .contextMenu {135 Button("Ouvrir", systemImage: "folder") { folderID = f.id; Task { await load() } }136 if g.role.canWrite { Button("Renommer…", systemImage: "pencil") { renaming = (f.id, f.name) }; Button("Mettre à la corbeille du propriétaire", systemImage: "trash", role: .destructive) { Task { await act(g) { try await $0.sharedTrash(grant: g.grantId, folderIDs: [f.id]) } } } }137 }138 }139 ForEach(l.files) { f in140 HStack(spacing: SPDTheme.Space.sm) {141 SharedThumbnail(model: model, grant: g.grantId, file: f)142 Text(f.name).lineLimit(1).truncationMode(.middle)143 Spacer()144 Text("\(Fmt.bytes(f.size)) · \(f.modified.map(Fmt.day) ?? "")").font(SPDTheme.Typo.caption).foregroundStyle(SPDTheme.textSecondary).monospacedDigit()145 }146 .tag(f.id)147 .contextMenu {148 Button("Coup d’œil", systemImage: "eye") { Task { await preview(f, g) } }149 Button("Télécharger", systemImage: "arrow.down.circle") { Task { await download(f, g) } }150 if g.role.canWrite { Divider(); Button("Renommer…", systemImage: "pencil") { renaming = (f.id, f.name) }; Button("Mettre à la corbeille du propriétaire", systemImage: "trash", role: .destructive) { Task { await act(g) { try await $0.sharedTrash(grant: g.grantId, fileIDs: [f.id]) } } } }151 }152 }153 }154 .listStyle(.inset)155 .contextMenu(forSelectionType: String.self) { _ in } primaryAction: { ids in156 guard let id = ids.first else { return }157 if l.folders.contains(where: { $0.id == id }) { folderID = id; Task { await load() } }158 else if let f = l.files.first(where: { $0.id == id }) { Task { await preview(f, g) } }159 }160 }161 }162 private func load() async {163 guard let g = grant, let next = model.next, g.role.canList else { return }164 do { listing = .ready(try await next.sharedChildren(grant: g.grantId, folderID: folderID)); selection = [] }165 catch { listing = .failed(NextError.wrap(error).isNotFound ? "Ce partage n’existe plus : l’accès a été retiré ou le dossier supprimé." : NextText.error(error)) }166 }167 /// Runs an action of the grant, then re-lists. A 403 means the role changed: say it, do not pretend the folder vanished.168 private func act(_ g: SharedGrant, _ body: (NextClient) async throws -> Void) async {169 guard let next = model.next else { return }170 do { try await body(next); note = nil } catch { note = NextText.error(error); if NextError.wrap(error).isForbidden { await model.refreshGrants(); if let fresh = model.grants.first(where: { $0.grantId == g.grantId }) { grant = fresh } } }171 await load()172 }173 private func localCopy(_ f: NextFile, _ g: SharedGrant) async throws -> URL {174 guard let next = model.next else { throw NextError.unauthenticated }175 let dest = model.cacheDirectory.appendingPathComponent("shared/\(g.grantId)/\(f.id)-\(f.sha256?.prefix(12) ?? "x")/\(NameRules.sanitize(f.name))")176 if FileManager.default.fileExists(atPath: dest.path) { return dest }177 let sha = try await next.downloadShared(grant: g.grantId, fileID: f.id, to: dest)178 if let want = f.sha256, !want.isEmpty, sha != want { try? FileManager.default.removeItem(at: dest); throw NextError.invalidResponse("contenu différent de son empreinte") }179 return dest180 }181 private func preview(_ f: NextFile, _ g: SharedGrant) async {182 do { let url = try await localCopy(f, g); QuickLookCoordinator.shared.onKey = nil; QuickLookCoordinator.shared.show(url: url, itemID: "shared-\(f.id)") } catch { note = NextText.error(error) }183 }184 private func download(_ f: NextFile, _ g: SharedGrant) async {185 do {186 let url = try await localCopy(f, g)187 let taken = Set(((try? FileManager.default.contentsOfDirectory(atPath: model.downloadsFolder.path)) ?? []).map { NameRules.key($0) })188 let dest = model.downloadsFolder.appendingPathComponent(NameRules.nextFree(NameRules.sanitize(f.name)) { taken.contains($0) })189 try FileManager.default.copyItem(at: url, to: dest)190 model.banner = Banner(text: "« \(f.name) » est dans Téléchargements (vérifié par son empreinte).", isError: false)191 } catch { note = NextText.error(error) }192 }193 private func send(_ urls: [URL], _ g: SharedGrant) async {194 guard let next = model.next, !urls.isEmpty else { return }195 for url in urls {196 let scoped = url.startAccessingSecurityScopedResource(); defer { if scoped { url.stopAccessingSecurityScopedResource() } }197 let name = url.lastPathComponent198 uploads[name] = 0199 do { _ = try await next.uploadShared(grant: g.grantId, file: url, folderID: folderID) { done, total in Task { @MainActor in uploads[name] = total > 0 ? Double(done) / Double(total) : 1 } }; note = nil }200 catch { note = "« \(name) » : \(NextText.error(error))" }201 uploads[name] = nil202 }203 if g.role == .uploader, note == nil { model.banner = Banner(text: "\(urls.count) fichier\(urls.count > 1 ? "s" : "") déposé\(urls.count > 1 ? "s" : "") chez \(g.owner.displayName).", isError: false) }204 await load()205 }206}207208/// Thumbnail of a shared file, fetched through the grant.209private struct SharedThumbnail: View {210 let model: AppModel211 let grant: String212 let file: NextFile213 @State private var image: NSImage?214 var body: some View {215 Group {216 if let image { Image(nsImage: image).resizable().aspectRatio(contentMode: .fit).clipShape(RoundedRectangle(cornerRadius: 3)) }217 else { Image(nsImage: NSWorkspace.shared.icon(for: .init(filenameExtension: file.fileExtension) ?? .data)).resizable() }218 }219 .frame(width: 24, height: 24)220 .task(id: file.id) {221 guard file.thumb, let next = model.next, let req = try? await next.sharedPreviewRequest(grant: grant, fileID: file.id), let (data, _) = try? await next.data(for: req) else { return }222 image = NSImage(data: data)223 }224 }225}226