SPB Git

Repository Public

SharingNext.swift 18.2 KB 311 lines swift

1// SP Drive iOS2// File: Features/Next/SharingNext.swift3// Description: Private sharing between accounts (SP Drive 2.0): the members of a folder with their roles and its workspace name, on the4//              owner's side; « Partagés avec moi » on the member's side, browsed through the grant routes with an interface that matches5//              the role — a viewer reads, an editor also writes, an uploader only sees a place to drop files. Also the QR code of a link,6//              generated on the device.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import CoreImage.CIFilterBuiltins11import QuickLook12import SPDriveNext13import SwiftUI14import UniformTypeIdentifiers1516extension GrantRole {17    var label: String { switch self { case .viewer: String(localized: "Lecture"); case .editor: String(localized: "Modification"); case .uploader: String(localized: "Dépôt seulement") } }18    var explanation: String {19        switch self {20        case .viewer: String(localized: "Voit et télécharge le contenu du dossier.")21        case .editor: String(localized: "Voit, ajoute, renomme, déplace et met à la corbeille dans ce dossier.")22        case .uploader: String(localized: "Peut déposer des fichiers ; ne voit pas ce que le dossier contient.")23        }24    }25    var symbol: String { switch self { case .viewer: "eye"; case .editor: "pencil"; case .uploader: "tray.and.arrow.up" } }26}2728// MARK: Owner side2930struct MembersScreen: View {31    @Environment(AppModel.self) private var model32    let folder: DriveItem33    @State private var state: Loadable<FolderMembers> = .loading34    @State private var email = ""35    @State private var role = GrantRole.viewer36    @State private var workspace = ""37    @State private var adding = false38    @State private var notFound = false3940    var body: some View {41        LoadingView(state: state, retry: load) { m in42            Form {43                Section {44                    TextField("Nom de l’espace (facultatif)", text: $workspace).accessibilityIdentifier("members.workspace")45                        .onSubmit { saveWorkspace() }46                    if workspace != (m.folder.workspaceName ?? "") { Button("Enregistrer le nom") { saveWorkspace() } }47                } header: { Text("Espace de travail") } footer: { Text("Le nom sous lequel ce dossier apparaît chez ses membres. Sans nom, c’est celui du dossier : « \(folder.name) ».") }4849                Section {50                    if m.members.isEmpty { Text("Ce dossier n’est partagé avec personne.").foregroundStyle(.secondary) }51                    ForEach(m.members) { member in52                        VStack(alignment: .leading, spacing: 6) {53                            Text(member.displayName).font(.body.weight(.medium)).accessibilityIdentifier("member.\(member.displayName)")54                            if let e = member.email { Text(e).font(.caption).foregroundStyle(.secondary) }55                            Picker("Rôle", selection: Binding(get: { member.role }, set: { new in Task { await model.performNext { _ = try await model.next.client.updateMember(of: folder.id, userID: member.userId, role: new) }; await load() } })) {56                                ForEach(GrantRole.allCases) { Label($0.label, systemImage: $0.symbol).tag($0) }57                            }58                            Text(member.role.explanation).font(.caption).foregroundStyle(.secondary)59                        }60                        .swipeActions { Button(role: .destructive) { Task { await model.performNext(success: String(localized: "Accès retiré")) { try await model.next.client.removeMember(of: folder.id, userID: member.userId) }; await load() } } label: { Label("Retirer", systemImage: "person.badge.minus") } }61                    }62                } header: { Text("Membres (\(m.members.count))") } footer: { Text("Retirer un membre lui ferme l’accès tout de suite. Ce qu’il a déposé reste dans ton dossier ; l’espace utilisé compte dans ton quota.") }6364                Section {65                    TextField("Adresse courriel exacte", text: $email).textInputAutocapitalization(.never).autocorrectionDisabled().keyboardType(.emailAddress).accessibilityIdentifier("members.email")66                    Picker("Rôle", selection: $role) { ForEach(GrantRole.allCases) { Label($0.label, systemImage: $0.symbol).tag($0) } }67                    Text(role.explanation).font(.caption).foregroundStyle(.secondary)68                    Button { add() } label: { HStack { Label("Ajouter ce membre", systemImage: "person.badge.plus"); if adding { Spacer(); ProgressView() } } }69                        .disabled(adding || !email.contains("@")).accessibilityIdentifier("members.add")70                    if notFound { Label("Aucun compte SP Drive n’a exactement cette adresse.", systemImage: "person.fill.questionmark").font(.footnote).foregroundStyle(SPDTheme.Palette.warning).accessibilityIdentifier("members.notFound") }71                } header: { Text("Ajouter") } footer: { Text("Seule une adresse exacte est acceptée : il n’existe pas d’annuaire à parcourir.") }7273                if model.next.has(.activity) {74                    Section { NavigationLink { ActivityScreen(source: .folder(folder.id), title: String(localized: "Activité du dossier")) } label: { Label("Activité du dossier", systemImage: "clock") } }75                }76            }77        }78        .navigationTitle("Membres")79        .navigationBarTitleDisplayMode(.inline)80        .task { await load() }81    }8283    private func load() async {84        do { let m = try await model.next.client.members(of: folder.id); workspace = m.folder.workspaceName ?? ""; state = .loaded(m) }85        catch { if state.value == nil { state = .failed(NextCenter.describe(error)) } }86    }87    private func saveWorkspace() {88        let name = workspace.trimmingCharacters(in: .whitespaces)89        Task { await model.performNext(success: String(localized: "Nom de l’espace enregistré")) { _ = try await model.next.client.setWorkspaceName(of: folder.id, name.isEmpty ? nil : name) }; await load() }90    }91    private func add() {92        adding = true; notFound = false93        let address = email.trimmingCharacters(in: .whitespaces)94        Task {95            do {96                _ = try await model.next.client.addMember(to: folder.id, email: address, as: role) // members are added by exact e-mail only (API-NEXT D18)97                email = ""; Haptics.success()98                await load()99            } catch let e as NextError where e.isNotFound { notFound = true } catch { model.toast = Toast(text: NextCenter.describe(error), style: .error) }100            adding = false101        }102    }103}104105// MARK: Member side106107struct SharedWithMeScreen: View {108    @Environment(AppModel.self) private var model109    @State private var state: Loadable<[SharedGrant]> = .loading110111    var body: some View {112        LoadingView(state: state, retry: load) { grants in113            if grants.isEmpty {114                EmptyState(symbol: "person.2", title: String(localized: "Rien n’est partagé avec toi"), message: String(localized: "Quand quelqu’un t’ajoute comme membre d’un de ses dossiers, il apparaît ici."))115            } else {116                List(grants) { g in117                    NavigationLink { SharedBrowser(grant: g, folderID: nil) } label: {118                        HStack(spacing: SPDTheme.Space.md) {119                            Image(systemName: g.role == .uploader ? "tray.and.arrow.up.fill" : "folder.fill.badge.person.crop").font(.title3).foregroundStyle(Theme.gradient).frame(width: 36)120                            VStack(alignment: .leading, spacing: 2) {121                                Text(g.displayName).font(.body)122                                Text("De \(g.owner.displayName) · \(g.role.label)").font(.caption).foregroundStyle(.secondary)123                            }124                        }125                    }126                    .accessibilityIdentifier("grant.\(g.displayName)")127                }128            }129        }130        .navigationTitle("Partagés avec moi")131        .refreshable { await load() }132        .task { await load() }133    }134    private func load() async { do { state = .loaded(try await model.next.client.sharedWithMe()) } catch { if state.value == nil { state = .failed(NextCenter.describe(error)) } } }135}136137/// A folder someone else shared, through the grant routes. It is not part of this device's mirror: it is listed live, and needs the network.138struct SharedBrowser: View {139    @Environment(AppModel.self) private var model140    let grant: SharedGrant141    let folderID: String?142    @State private var state: Loadable<SharedListing> = .loading143    @State private var importing = false144    @State private var sent: [String] = []145    @State private var uploading: String?146    @State private var previewURL: URL?147    @State private var opening: String?148    @State private var newFolder = false149    @State private var newFolderName = ""150    @State private var renaming: NextFile?151    @State private var renameText = ""152153    var body: some View {154        Group {155            if grant.role == .uploader { dropSurface } else { listing }156        }157        .navigationTitle(folderID == nil ? grant.displayName : (state.value?.folder.name ?? ""))158        .navigationBarTitleDisplayMode(.inline)159        .toolbar {160            if grant.role == .editor {161                ToolbarItem(placement: .topBarTrailing) {162                    Menu {163                        Button { importing = true } label: { Label("Ajouter des fichiers", systemImage: "doc.badge.plus") }164                        Button { newFolderName = ""; newFolder = true } label: { Label("Nouveau dossier", systemImage: "folder.badge.plus") }165                    } label: { Label("Ajouter", systemImage: "plus.circle.fill") }.accessibilityIdentifier("shared.add")166                }167            }168        }169        .fileImporter(isPresented: $importing, allowedContentTypes: [.item], allowsMultipleSelection: true) { if case .success(let urls) = $0 { upload(urls) } }170        .quickLookPreview($previewURL)171        .alert("Nouveau dossier", isPresented: $newFolder) {172            TextField("Nom du dossier", text: $newFolderName)173            Button("Annuler", role: .cancel) {}174            Button("Créer") { let n = newFolderName; Task { await model.performNext { _ = try await model.next.client.sharedCreateFolder(grant: grant.grantId, parentID: folderID, name: n) }; await load() } }175        }176        .alert("Renommer", isPresented: Binding(get: { renaming != nil }, set: { if !$0 { renaming = nil } })) {177            TextField("Nom", text: $renameText).textInputAutocapitalization(.never)178            Button("Annuler", role: .cancel) {}179            Button("Renommer") { if let f = renaming { let n = renameText; Task { await model.performNext { _ = try await model.next.client.sharedUpdateItem(grant: grant.grantId, itemID: f.id, name: n) }; await load() } } }180        }181        .task { if grant.role != .uploader { await load() } }182        .refreshable { if grant.role != .uploader { await load() } }183    }184185    /// An uploader sees no listing at all: only a place to hand files over, and what was sent during this visit.186    private var dropSurface: some View {187        VStack(spacing: SPDTheme.Space.lg) {188            Spacer()189            Image(systemName: "tray.and.arrow.up.fill").font(.system(size: 54)).foregroundStyle(Theme.gradient).accessibilityHidden(true)190            Text("Déposer dans « \(grant.displayName) »").font(SPDTheme.Typo.title).multilineTextAlignment(.center)191            Text("Tu peux déposer des fichiers dans ce dossier de \(grant.owner.displayName). Tu ne vois pas son contenu, et tes dépôts ne t’appartiennent plus une fois envoyés.")192                .font(SPDTheme.Typo.body).foregroundStyle(.secondary).multilineTextAlignment(.center).fixedSize(horizontal: false, vertical: true)193            Button { importing = true } label: { Label("Choisir des fichiers", systemImage: "doc.badge.plus") }.buttonStyle(GradientButtonStyle()).frame(maxWidth: 340).disabled(uploading != nil).accessibilityIdentifier("shared.drop")194            if let uploading { ProgressView(String(localized: "Envoi de « \(uploading) »…")) }195            if !sent.isEmpty {196                VStack(alignment: .leading, spacing: 4) {197                    Text("Déposés pendant cette visite").font(.caption.weight(.semibold)).foregroundStyle(.secondary)198                    ForEach(sent, id: \.self) { Label($0, systemImage: "checkmark.circle.fill").font(.footnote).foregroundStyle(SPDTheme.Palette.positive) }199                }200                .padding().frame(maxWidth: 340, alignment: .leading).spdCard().accessibilityIdentifier("shared.sent")201            }202            Spacer()203        }204        .padding(SPDTheme.Space.xl)205        .dropDestination(for: URL.self) { urls, _ in upload(urls); return !urls.isEmpty }206    }207208    private var listing: some View {209        LoadingView(state: state, retry: load) { l in210            List {211                Section {212                    if l.folders.isEmpty && l.files.isEmpty { Text("Ce dossier est vide.").foregroundStyle(.secondary) }213                    ForEach(l.folders) { f in214                        NavigationLink { SharedBrowser(grant: grant, folderID: f.id) } label: { Label { Text(f.name) } icon: { KindIcon(kind: .folder, size: 36) } }215                            .swipeActions { if grant.role.canWrite { Button(role: .destructive) { trash(folders: [f.id]) } label: { Label("Corbeille", systemImage: "trash") } } }216                    }217                    ForEach(l.files) { f in218                        Button { open(f) } label: {219                            HStack(spacing: SPDTheme.Space.md) {220                                KindIcon(kind: f.fileKind, size: 36)221                                VStack(alignment: .leading, spacing: 2) { Text(f.name).lineLimit(2); Text("\(f.size.byteString) · \((f.modified ?? .now).shortRelative)").font(.caption).foregroundStyle(.secondary) }222                                Spacer(minLength: 4)223                                if opening == f.id { ProgressView() }224                            }225                        }226                        .buttonStyle(.plain)227                        .accessibilityIdentifier("shared.file.\(f.name)")228                        .swipeActions {229                            if grant.role.canWrite {230                                Button(role: .destructive) { trash(files: [f.id]) } label: { Label("Corbeille", systemImage: "trash") }231                                Button { renameText = f.name; renaming = f } label: { Label("Renommer", systemImage: "pencil") }.tint(.indigo)232                            }233                        }234                    }235                } header: {236                    Label("\(grant.role.label) · dossier de \(grant.owner.displayName)", systemImage: grant.role.symbol).accessibilityIdentifier("shared.role")237                } footer: {238                    Text(grant.role == .viewer ? String(localized: "Tu peux consulter et télécharger. Ce dossier n’est pas gardé hors ligne et n’apparaît pas dans l’app Fichiers.")239                                               : String(localized: "Ce que tu ajoutes ici appartient au propriétaire du dossier et compte dans son espace. Ce dossier n’est pas gardé hors ligne."))240                }241                if let uploading { Section { ProgressView(String(localized: "Envoi de « \(uploading) »…")) } }242            }243        }244    }245246    private func load() async {247        do { state = .loaded(try await model.next.client.sharedChildren(grant: grant.grantId, folderID: folderID)) } catch { if state.value == nil { state = .failed(NextCenter.describe(error)) } }248    }249250    private func open(_ f: NextFile) {251        opening = f.id252        Task {253            await model.performNext {254                let dir = FileManager.default.temporaryDirectory.appendingPathComponent("SPDrive-shared-\(f.id)", isDirectory: true)255                try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)256                let url = dir.appendingPathComponent(LocalFiles.safeName(f.name))257                if let sha = f.sha256, IntegrityVerifier.verify(url, sha256: sha) {} else {258                    try? FileManager.default.removeItem(at: url)259                    try await model.next.client.downloadShared(grant: grant.grantId, fileID: f.id, to: url)260                }261                previewURL = url262            }263            opening = nil264        }265    }266267    private func upload(_ urls: [URL]) {268        Task {269            for url in urls {270                let scoped = url.startAccessingSecurityScopedResource()271                defer { if scoped { url.stopAccessingSecurityScopedResource() } }272                uploading = url.lastPathComponent273                await model.performNext {274                    _ = try await model.next.client.uploadShared(grant: grant.grantId, file: url, folderID: folderID)275                    sent.append(url.lastPathComponent)276                    Haptics.success()277                }278            }279            uploading = nil280            if grant.role != .uploader { await load() }281        }282    }283284    private func trash(files: [String] = [], folders: [String] = []) {285        Task { await model.performNext(success: String(localized: "Déplacé dans la corbeille du propriétaire")) { try await model.next.client.sharedTrash(grant: grant.grantId, fileIDs: files, folderIDs: folders) }; await load() }286    }287}288289// MARK: QR code of a link290291/// A link as a QR code, drawn on the device (nothing is sent anywhere to produce it).292struct QRCodeView: View {293    let url: URL294    var body: some View {295        if let image = Self.image(for: url.absoluteString) {296            Image(uiImage: image).interpolation(.none).resizable().scaledToFit()297                .padding(10).background(Color.white, in: RoundedRectangle(cornerRadius: SPDTheme.Radius.md, style: .continuous))298                .frame(maxWidth: 220)299                .accessibilityLabel(Text("Code QR du lien"))300                .accessibilityIdentifier("share.qr")301        }302    }303    static func image(for text: String) -> UIImage? {304        let filter = CIFilter.qrCodeGenerator()305        filter.message = Data(text.utf8)306        filter.correctionLevel = "M"307        guard let output = filter.outputImage?.transformed(by: CGAffineTransform(scaleX: 10, y: 10)), let cg = CIContext().createCGImage(output, from: output.extent) else { return nil }308        return UIImage(cgImage: cg)309    }310}311
Files main
Menu

Theme