SPB Git

Repository Public

AttachmentGallery.swift 22.6 KB 386 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Next/AttachmentGallery.swift3// Description: The attachment gallery — a grid of tiles across mailboxes (Quick Look thumbnails for small images and PDFs), filters (kind,4// size, sender, date, mailbox) and search by file name, Quick Look preview, multi-selection (save to a folder, share, download as one ZIP),5// the source message, and tiles dragged out to other apps. Files come from the engine's sealed attachment cache; decrypted copies only6// ever live in the engine-managed temporary folder.7import QuickLook8import SPMailCore9import SwiftUI10import UniformTypeIdentifiers1112enum GallerySize: Int, CaseIterable, Identifiable, Sendable {13    case any = 0, over1MB = 1_048_576, over10MB = 10_485_760, over25MB = 26_214_40014    var id: Int { rawValue }15    var title: String { switch self { case .any: L("Toutes les tailles"); case .over1MB: L("Plus de 1 Mo"); case .over10MB: L("Plus de 10 Mo"); case .over25MB: L("Plus de 25 Mo") } }16}17enum GalleryPeriod: String, CaseIterable, Identifiable, Sendable {18    case any, week, month, year19    var id: String { rawValue }20    var title: String { switch self { case .any: L("Toutes les dates"); case .week: L("7 derniers jours"); case .month: L("30 derniers jours"); case .year: L("12 derniers mois") } }21    var after: Date? { switch self { case .any: nil; case .week: Date().addingTimeInterval(-7 * 86_400); case .month: Date().addingTimeInterval(-30 * 86_400); case .year: Date().addingTimeInterval(-365 * 86_400) } }22}2324extension AttachmentKind {25    var title: String {26        switch self {27        case .image: L("Images"); case .pdf: L("PDF"); case .document: L("Documents"); case .spreadsheet: L("Tableurs"); case .archive: L("Archives compressées")28        case .audio: L("Audio"); case .video: L("Vidéo"); case .other, .unknown: L("Autres")29        }30    }31    static var filters: [AttachmentKind] { [.image, .pdf, .document, .spreadsheet, .archive, .audio, .video, .other] }32}3334@MainActor @Observable35final class GalleryState {36    var items: [AttachmentItem] = []37    var cursor: String?38    var kind: AttachmentKind?39    var size = GallerySize.any40    var period = GalleryPeriod.any41    /// nil: every mailbox.42    var mailbox: String?43    var sender = ""44    var query = ""45    var isLoading = false46    var isLoadingMore = false47    var error: String?48    var selection: Set<String> = []49    /// Touch: taps select instead of previewing.50    var selecting = false51    var working: String?52    @ObservationIgnored var generation = 05354    var hasFilters: Bool { kind != nil || size != .any || period != .any || mailbox != nil || !sender.trimmingCharacters(in: .whitespaces).isEmpty }55    var filterKey: String { "\(kind?.rawValue ?? "")|\(size.rawValue)|\(period.rawValue)|\(mailbox ?? "")|\(sender)|\(query)" }56    func clearFilters() { kind = nil; size = .any; period = .any; mailbox = nil; sender = "" }57    func reset() { generation += 1; items = []; cursor = nil; clearFilters(); query = ""; isLoading = false; error = nil; selection = []; selecting = false; working = nil }58    var query_: AttachmentQuery {59        AttachmentQuery(scope: mailbox.map { .only([$0]) } ?? .all, kind: kind, minSize: size == .any ? nil : size.rawValue, q: query.trimmingCharacters(in: .whitespaces),60                        from: sender.trimmingCharacters(in: .whitespaces), after: period.after, limit: 60)61    }62}6364extension AttachmentItem {65    var part: BodyPart { BodyPart(partId: partId, blobId: blobId, size: size, name: name.isEmpty ? nil : name, type: type, disposition: "attachment") }66    var info: AttachmentInfo { AttachmentInfo(id: id, name: name.isEmpty ? CoreStrings.untitledAttachment : name, type: type, size: size, isRisky: isDangerous, thumbnailsDocuments: true) }67}6869/// A tile dragged out of the gallery: the file itself, fetched on demand into the engine's temporary folder.70struct AttachmentTransfer: Transferable {71    let name: String72    let file: @Sendable () async throws -> URL73    static var transferRepresentation: some TransferRepresentation {74        FileRepresentation(exportedContentType: .data) { item in SentTransferredFile(try await item.file()) }75            .suggestedFileName { $0.name }76    }77}7879/// A file already on disk (the ZIP of several attachments) offered to the save panel.80struct FileURLDocument: FileDocument {81    static let readableContentTypes: [UTType] = [.zip, .data]82    let url: URL?83    init(url: URL) { self.url = url }84    init(configuration: ReadConfiguration) throws { url = nil }85    func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {86        guard let url else { throw CocoaError(.fileNoSuchFile) }87        return try FileWrapper(url: url, options: .immediate)88    }89}9091extension MailScene {92    func reloadGallery() async {93        let g = next.gallery94        g.generation += 195        let generation = g.generation96        if g.items.isEmpty { g.isLoading = true }97        defer { if generation == g.generation { g.isLoading = false } }98        do {99            let page = try await app.next.api.attachments(g.query_)100            guard generation == g.generation else { return }101            g.items = page.items; g.cursor = page.nextCursor; g.error = nil102            g.selection.formIntersection(Set(page.items.map(\.id)))103        } catch {104            guard generation == g.generation, !(error is CancellationError) else { return }105            g.error = NextError.isOffline(error) ? L("La galerie des pièces jointes n’est visible qu’en ligne.") : app.next.describe(error)106        }107    }108    func loadMoreGallery(after item: AttachmentItem) async {109        let g = next.gallery110        guard item.id == g.items.last?.id, let cursor = g.cursor, !g.isLoadingMore else { return }111        g.isLoadingMore = true112        defer { g.isLoadingMore = false }113        var q = g.query_114        q.cursor = cursor115        guard let page = try? await app.next.api.attachments(q), cursor == g.cursor else { return }116        let known = Set(g.items.map(\.id))117        g.items += page.items.filter { !known.contains($0.id) }118        g.cursor = page.nextCursor119    }120121    /// A decrypted copy in the engine-managed temporary folder (from the sealed attachment cache when it is there).122    func galleryFile(_ item: AttachmentItem) async throws -> URL {123        guard let engine = app.engines[item.mailboxId] else { throw StoreError(message: "no account") }124        return try await engine.attachmentFile(for: item.part)125    }126    func galleryData(_ item: AttachmentItem) async throws -> Data {127        guard let engine = app.engines[item.mailboxId] else { throw StoreError(message: "no account") }128        return try await engine.fetchAttachment(item.part)129    }130131    /// Downloads the given attachments as one ZIP into the engine-managed temporary folder and returns its location.132    func galleryZip(_ items: [AttachmentItem]) async throws -> URL {133        guard let store = app.store else { throw StoreError(message: "no store") }134        let url = store.temporaryFilesDirectory.appendingPathComponent(UUID().uuidString, isDirectory: true).appendingPathComponent(L("Pièces jointes") + ".zip")135        try await app.next.api.downloadAttachmentsZip(items.map(AttachmentZipItem.init), to: url)136        return url137    }138}139140struct AttachmentGalleryView: View {141    @Bindable var scene: MailScene142    @State private var preview: URL?143    @State private var exportDoc: DataDocument?144    @State private var exportName = ""145    @State private var zipDoc: FileURLDocument?146    @State private var pickingFolder = false147    @State private var risky: AttachmentItem?148    @State private var shareURLs: [URL] = []149    @State private var showShare = false150151    private var app: AppModel { scene.app }152    private var g: GalleryState { scene.next.gallery }153    private var selected: [AttachmentItem] { g.items.filter { g.selection.contains($0.id) } }154155    var body: some View {156        @Bindable var g = scene.next.gallery157        ScrollView {158            LazyVStack(alignment: .leading, spacing: SPSpacing.l) {159                filterBar160                if let e = g.error { Label(e, systemImage: "wifi.slash").font(.footnote).foregroundStyle(SPColor.warn) }161                LazyVGrid(columns: [GridItem(.adaptive(minimum: 132, maximum: 168), spacing: SPSpacing.l, alignment: .top)], alignment: .leading, spacing: SPSpacing.l) {162                    ForEach(g.items) { item in tile(item).task { await scene.loadMoreGallery(after: item) } }163                }164                if g.isLoadingMore { ProgressView().controlSize(.small).frame(maxWidth: .infinity) }165            }166            .padding(SPSpacing.xl)167        }168        .background(SPColor.bg.ignoresSafeArea())169        .overlay {170            if g.items.isEmpty {171                if g.isLoading { ProgressView() } else if g.error == nil {172                    SPEmptyState(icon: "paperclip", title: g.hasFilters || !g.query.isEmpty ? L("Aucune pièce jointe ne correspond") : L("Aucune pièce jointe"),173                                 actionTitle: g.hasFilters ? L("Effacer les filtres") : nil, action: { g.clearFilters() }).padding(.top, 60)174                }175            }176        }177        .overlay(alignment: .top) { if let w = g.working { Label(w, systemImage: "arrow.down.circle").font(SPFont.callout).padding(.horizontal, SPSpacing.l).padding(.vertical, SPSpacing.m).spGlass(Capsule()).padding(.top, 8) } }178        .safeAreaInset(edge: .bottom, spacing: 0) { if !g.selection.isEmpty { selectionBar } }179        .navigationTitle("Pièces jointes")180        #if os(macOS)181        .navigationSubtitle(g.selection.isEmpty ? "" : L("\(g.selection.count) sélectionnées"))182        #endif183        .searchable(text: $g.query, prompt: Text("Nom du fichier"))184        .task(id: g.filterKey) {185            try? await Task.sleep(for: .milliseconds(g.query.isEmpty && g.sender.isEmpty ? 0 : 300))186            if !Task.isCancelled { await scene.reloadGallery() }187        }188        .refreshable { await scene.reloadGallery() }189        .toolbar {190            #if os(iOS)191            ToolbarItem(placement: .topBarTrailing) { Button(g.selecting ? L("OK") : L("Sélectionner")) { g.selecting.toggle(); if !g.selecting { g.selection = [] } }.disabled(g.items.isEmpty) }192            #else193            ToolbarItem { Button { g.selection = Set(g.items.map(\.id)) } label: { Label("Tout sélectionner", systemImage: "checkmark.circle") }.keyboardShortcut("a", modifiers: .command).disabled(g.items.isEmpty).help("Tout sélectionner (⌘A)") }194            #endif195        }196        .quickLookPreview($preview)197        .fileExporter(isPresented: Binding(get: { exportDoc != nil }, set: { if !$0 { exportDoc = nil } }), document: exportDoc, contentType: .data, defaultFilename: exportName) { _ in exportDoc = nil }198        .fileExporter(isPresented: Binding(get: { zipDoc != nil }, set: { if !$0 { zipDoc = nil } }), document: zipDoc, contentType: .zip, defaultFilename: L("Pièces jointes")) { _ in zipDoc = nil }199        .fileImporter(isPresented: $pickingFolder, allowedContentTypes: [.folder]) { result in if case .success(let folder) = result { saveSelection(into: folder) } }200        .confirmationDialog("Ce type de fichier peut exécuter du code à l’ouverture.", isPresented: Binding(get: { risky != nil }, set: { if !$0 { risky = nil } }), titleVisibility: .visible, presenting: risky) { item in201            Button("Enregistrer quand même…", role: .destructive) { save(item, confirmed: true) }202            Button("Annuler", role: .cancel) {}203        } message: { item in Text("« \(item.name) » ne sera pas ouvert par SP Mail. Ne l’enregistrez que si vous faites confiance à l’expéditeur.") }204        #if os(iOS)205        .sheet(isPresented: $showShare) { ActivitySheet(urls: shareURLs) }206        #endif207        #if os(macOS)208        .onExitCommand { g.selection = [] }209        #endif210    }211212    // MARK: filters213214    private func chip<V: View>(_ title: String, active: Bool, @ViewBuilder _ content: () -> V) -> some View {215        Menu { content() } label: {216            HStack(spacing: 4) { Text(title).lineLimit(1); Image(systemName: "chevron.down").font(.system(size: 8, weight: .bold)) }217                .font(SPFont.caption).padding(.horizontal, 10).padding(.vertical, 5)218                .background(active ? AnyShapeStyle(SPColor.accentSoft) : AnyShapeStyle(SPColor.surface3), in: Capsule()).foregroundStyle(active ? SPColor.accent : SPColor.text2)219                #if os(iOS)220                .frame(minHeight: 34)221                #endif222                .contentShape(Capsule())223        }224        .menuStyle(.button).buttonStyle(.plain).menuIndicator(.hidden).fixedSize()225    }226227    private var filterBar: some View {228        @Bindable var g = scene.next.gallery229        return ScrollView(.horizontal, showsIndicators: false) {230            HStack(spacing: SPSpacing.m) {231                chip(g.kind?.title ?? L("Tous les types"), active: g.kind != nil) {232                    Picker("Type", selection: $g.kind) { Text("Tous les types").tag(AttachmentKind?.none); ForEach(AttachmentKind.filters, id: \.self) { Text($0.title).tag(AttachmentKind?.some($0)) } }.pickerStyle(.inline)233                }234                chip(g.size.title, active: g.size != .any) { Picker("Taille", selection: $g.size) { ForEach(GallerySize.allCases) { Text($0.title).tag($0) } }.pickerStyle(.inline) }235                chip(g.period.title, active: g.period != .any) { Picker("Date", selection: $g.period) { ForEach(GalleryPeriod.allCases) { Text($0.title).tag($0) } }.pickerStyle(.inline) }236                if app.accounts.count > 1 {237                    chip(g.mailbox.flatMap { app.box($0)?.address } ?? L("Toutes les boîtes"), active: g.mailbox != nil) {238                        Picker("Boîte", selection: $g.mailbox) { Text("Toutes les boîtes").tag(String?.none); ForEach(app.accounts) { Text($0.address).tag(String?.some($0.id)) } }.pickerStyle(.inline)239                    }240                }241                HStack(spacing: 4) {242                    Image(systemName: "person").imageScale(.small).foregroundStyle(SPColor.text3)243                    TextField("Expéditeur", text: $g.sender).textFieldStyle(.plain).font(SPFont.caption).frame(width: 130).autocorrectionDisabled()244                        #if os(iOS)245                        .textInputAutocapitalization(.never)246                        #endif247                }248                .padding(.horizontal, 10).padding(.vertical, 5)249                .background(g.sender.isEmpty ? AnyShapeStyle(SPColor.surface3) : AnyShapeStyle(SPColor.accentSoft), in: Capsule())250                if g.hasFilters { Button("Effacer") { g.clearFilters() }.buttonStyle(.borderless).font(SPFont.caption).foregroundStyle(SPColor.accent) }251            }252        }253        .accessibilityElement(children: .contain).accessibilityLabel(Text("Filtres"))254    }255256    // MARK: tiles257258    @ViewBuilder private func tile(_ item: AttachmentItem) -> some View {259        let isSelected = g.selection.contains(item.id)260        let info = item.info261        VStack(alignment: .leading, spacing: SPSpacing.s) {262            AttachmentThumbnail(info: info, side: 104, file: { [scene] in try? await scene.galleryFile(item) }).frame(maxWidth: .infinity)263            Text(info.name).font(SPFont.caption).foregroundStyle(SPColor.text).lineLimit(2, reservesSpace: true).truncationMode(.middle)264            Text([item.size.byteLabel, item.from?.displayName].compactMap { $0 }.joined(separator: " · ")).font(.caption2).foregroundStyle(SPColor.text3).lineLimit(1)265            if let d = item.receivedAt { Text(d.listLabel).font(.caption2).foregroundStyle(SPColor.text3) }266        }267        .padding(SPSpacing.m).frame(maxWidth: .infinity, alignment: .leading)268        .spCard(fill: isSelected ? SPColor.accentSoft : SPColor.surface)269        .overlay { if isSelected { RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous).stroke(SPColor.accent, lineWidth: 2) } }270        .overlay(alignment: .topTrailing) {271            if isSelected || g.selecting { Image(systemName: isSelected ? "checkmark.circle.fill" : "circle").font(.title3).foregroundStyle(isSelected ? SPColor.accent : SPColor.text3).background(Circle().fill(SPColor.surface).padding(2)).padding(6) }272        }273        .contentShape(RoundedRectangle(cornerRadius: SPRadius.card, style: .continuous))274        #if os(macOS)275        .gesture(TapGesture(count: 2).onEnded { open(item) })276        .simultaneousGesture(TapGesture().modifiers(.command).onEnded { toggle(item) })277        .onTapGesture { g.selection = [item.id] }278        #else279        .onTapGesture { if g.selecting { toggle(item) } else { open(item) } }280        .hoverEffect(.lift)281        #endif282        .draggable(AttachmentTransfer(name: info.name) { [scene] in try await scene.galleryFile(item) }) { DragPreview(title: info.name, count: 1) }283        .contextMenu {284            Button { open(item) } label: { Label("Coup d’œil", systemImage: "eye") }.disabled(item.isDangerous)285            Button { save(item) } label: { Label("Enregistrer sous…", systemImage: "square.and.arrow.down") }286            Button { share([item]) } label: { Label("Partager…", systemImage: "square.and.arrow.up") }.disabled(item.isDangerous)287            Divider()288            Button { scene.presentMessage(account: item.mailboxId, emailId: item.emailId) } label: { Label("Ouvrir le message", systemImage: "envelope.open") }289            Button { toggle(item) } label: { Label(isSelected ? L("Désélectionner") : L("Sélectionner"), systemImage: isSelected ? "circle" : "checkmark.circle") }290        }291        .accessibilityElement(children: .ignore)292        .accessibilityLabel(Text([info.name, item.size.byteLabel, item.from?.displayName ?? "", item.subject].filter { !$0.isEmpty }.joined(separator: ", ")))293        .accessibilityAddTraits(isSelected ? [.isButton, .isSelected] : .isButton)294        .accessibilityAction(named: Text("Coup d’œil")) { open(item) }295        .accessibilityAction(named: Text("Ouvrir le message")) { scene.presentMessage(account: item.mailboxId, emailId: item.emailId) }296        .accessibilityAction(named: Text(isSelected ? "Désélectionner" : "Sélectionner")) { toggle(item) }297    }298299    private var selectionBar: some View {300        let items = selected301        let total = items.reduce(0) { $0 + $1.size }302        return HStack(spacing: SPSpacing.l) {303            Text("\(items.count) sélectionnées · \(total.byteLabel)").font(SPFont.callout.weight(.medium)).foregroundStyle(SPColor.text2).lineLimit(1)304            Spacer(minLength: SPSpacing.m)305            Button { pickingFolder = true } label: { Label("Enregistrer dans un dossier…", systemImage: "folder.badge.plus") }306            Button { zip(items) } label: { Label("Télécharger en ZIP…", systemImage: "doc.zipper") }.disabled(items.count > AttachmentZipItem.maxItems || total > AttachmentZipItem.maxTotalBytes)307            Button { share(items) } label: { Label("Partager…", systemImage: "square.and.arrow.up") }.disabled(items.contains(where: \.isDangerous))308            Button { g.selection = []; g.selecting = false } label: { Image(systemName: "xmark.circle.fill").foregroundStyle(SPColor.text3) }.buttonStyle(.borderless).accessibilityLabel(Text("Tout désélectionner"))309        }310        #if os(iOS)311        .labelStyle(.iconOnly)312        #endif313        .buttonStyle(.bordered)314        .padding(.horizontal, SPSpacing.xl).padding(.vertical, SPSpacing.m)315        .background(SPColor.surface2)316        .overlay(alignment: .top) { Divider().overlay(SPColor.border) }317    }318319    // MARK: actions320321    private func toggle(_ item: AttachmentItem) { if g.selection.contains(item.id) { g.selection.remove(item.id) } else { g.selection.insert(item.id) } }322    private func fail(_ error: Error) { if let m = app.next.describe(error) { app.toast = Toast(message: m, kind: .error) } }323    private func run(_ label: String, _ body: @escaping @MainActor () async throws -> Void) {324        Task {325            g.working = label326            defer { g.working = nil }327            do { try await body() } catch { fail(error) }328        }329    }330331    private func open(_ item: AttachmentItem) {332        if item.isDangerous { risky = item; return }333        run(L("Téléchargement…")) { preview = try await scene.galleryFile(item) }334    }335    private func save(_ item: AttachmentItem, confirmed: Bool = false) {336        if !confirmed, item.isDangerous { risky = item; return }337        run(L("Téléchargement…")) { exportName = item.info.name; exportDoc = DataDocument(data: try await scene.galleryData(item)) }338    }339    private func zip(_ items: [AttachmentItem]) {340        run(L("Préparation du ZIP…")) { zipDoc = FileURLDocument(url: try await scene.galleryZip(items)) }341    }342    /// Writes each selected attachment into a folder the person chose (names made unique, never overwriting).343    private func saveSelection(into folder: URL) {344        let items = selected345        run(L("Enregistrement de \(items.count) fichiers…")) {346            let scoped = folder.startAccessingSecurityScopedResource()347            defer { if scoped { folder.stopAccessingSecurityScopedResource() } }348            var written = 0349            for item in items {350                let data = try await scene.galleryData(item)351                var url = folder.appendingPathComponent(item.info.name.replacingOccurrences(of: "/", with: "-"))352                var n = 2353                while FileManager.default.fileExists(atPath: url.path) {354                    let base = (item.info.name as NSString).deletingPathExtension, ext = (item.info.name as NSString).pathExtension355                    url = folder.appendingPathComponent(ext.isEmpty ? "\(base) \(n)" : "\(base) \(n).\(ext)"); n += 1356                }357                try data.write(to: url, options: .atomic)358                written += 1359            }360            app.toast = Toast(message: L("\(written) fichiers enregistrés"), kind: .success)361        }362    }363    private func share(_ items: [AttachmentItem]) {364        run(L("Téléchargement…")) {365            var urls: [URL] = []366            for item in items where !item.isDangerous { urls.append(try await scene.galleryFile(item)) }367            guard !urls.isEmpty else { return }368            #if os(macOS)369            guard let view = NSApp.keyWindow?.contentView else { return }370            NSSharingServicePicker(items: urls).show(relativeTo: CGRect(x: view.bounds.midX, y: 40, width: 1, height: 1), of: view, preferredEdge: .maxY)371            #else372            shareURLs = urls; showShare = true373            #endif374        }375    }376}377378#if os(iOS)379/// The system share sheet for files already in the engine's temporary folder.380struct ActivitySheet: UIViewControllerRepresentable {381    let urls: [URL]382    func makeUIViewController(context: Context) -> UIActivityViewController { UIActivityViewController(activityItems: urls, applicationActivities: nil) }383    func updateUIViewController(_ controller: UIActivityViewController, context: Context) {}384}385#endif386
Files main
Menu

Theme