SPB Git

Repository Public

ShareModel.swift 9.5 KB 158 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/ShareExtension/ShareModel.swift3// Description: State of the share extension: what was shared (text, links, images, files — files stay on disk and are streamed, never4// loaded whole), the compact draft (sender, recipients, subject, note) and its two exits: send through the API with the session token of5// the shared keychain group, or queue the draft, sealed, for the app. While SP Mail is locked only the queue is offered.6import Foundation7import SPMailCore8import SPMailSystem9import SwiftUI10import UniformTypeIdentifiers1112@MainActor @Observable13final class ShareModel {14    struct Item: Identifiable, Hashable, Sendable {15        let id = UUID()16        var name: String17        var type: String18        var size: Int19        var url: URL20    }21    enum Phase: Equatable { case loading, editing, working(String), done(String), failed(String) }2223    @ObservationIgnored let store = SharedStore.open()24    @ObservationIgnored let state: ExtensionState?25    @ObservationIgnored private let token: String?26    @ObservationIgnored private let draftId = UUID().uuidString27    @ObservationIgnored private let workDirectory = FileManager.default.temporaryDirectory.appendingPathComponent("spmail-share-\(UUID().uuidString)", isDirectory: true)2829    var phase: Phase = .loading30    var mailboxId: String?31    var to = ""32    var subject = ""33    var note = ""34    var items: [Item] = []3536    init() {37        state = store.state()38        token = store.token()39        mailboxId = state?.defaultMailbox?.id40    }4142    var isSignedIn: Bool { state?.signedIn == true && token != nil && !(state?.mailboxes.isEmpty ?? true) }43    var mailboxes: [ExtensionState.Box] { state?.mailboxes ?? [] }44    var mailbox: ExtensionState.Box? { mailboxes.first { $0.id == mailboxId } ?? state?.defaultMailbox }45    var totalSize: Int { items.reduce(0) { $0 + $1.size } }46    var tooLarge: Bool { totalSize > ShareDelivery.maxTotalBytes }47    var recipients: [EmailAddress] { AddressParser.parseList(to).filter { $0.email.contains("@") && !$0.email.hasSuffix("@") } }48    /// Sending needs the app unlocked: behind the app lock a share can only wait, sealed, for the app.49    var appLocked: Bool { state?.lock.conceals() ?? true }50    var canSend: Bool { isSignedIn && !appLocked && !recipients.isEmpty && !tooLarge && phase == .editing }51    /// Files need the App Group container; text-only drafts can always be queued.52    var canQueue: Bool { isSignedIn && !tooLarge && phase == .editing && (items.isEmpty || store.shareQueue.acceptsFiles) }5354    // MARK: loading what was shared5556    func load(_ context: NSExtensionContext?) async {57        try? FileManager.default.createDirectory(at: workDirectory, withIntermediateDirectories: true)58        var lines: [String] = []59        for item in (context?.inputItems as? [NSExtensionItem]) ?? [] {60            if subject.isEmpty, let title = item.attributedTitle?.string, !title.isEmpty { subject = String(title.prefix(200)) }61            let providers = item.attachments ?? []62            var carriedText = false63            for provider in providers {64                if provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) || Self.isFile(provider) {65                    if let file = await Self.loadFile(provider, into: workDirectory, index: items.count) { items.append(file) }66                } else if provider.hasItemConformingToTypeIdentifier(UTType.url.identifier) {67                    if let url = await Self.loadURL(provider) { lines.append(url.absoluteString); carriedText = true }68                } else if provider.hasItemConformingToTypeIdentifier(UTType.plainText.identifier) {69                    if let text = await Self.loadText(provider) { lines.append(text); carriedText = true }70                }71            }72            if !carriedText, let text = item.attributedContentText?.string, !text.isEmpty { lines.append(text) }73        }74        note = lines.joined(separator: "\n\n")75        phase = .editing76    }7778    /// Anything that is a document, an image or a movie rather than a string or a link.79    private static func isFile(_ p: NSItemProvider) -> Bool {80        let types = p.registeredTypeIdentifiers.compactMap { UTType($0) }81        if types.contains(where: { $0.conforms(to: .url) && !$0.conforms(to: .fileURL) }) || types.contains(where: { $0.conforms(to: .plainText) }) && types.count == 1 { return false }82        return types.contains { $0.conforms(to: .image) || $0.conforms(to: .movie) || $0.conforms(to: .audio) || $0.conforms(to: .pdf) || $0.conforms(to: .archive) || ($0.conforms(to: .data) && !$0.conforms(to: .text)) || $0.conforms(to: .content) && !$0.conforms(to: .text) }83    }8485    /// Asks the provider for a file on disk and copies it next to us (the provider's file disappears when the handler returns). The86    /// copy is done by the file system: no attachment goes through memory.87    private static func loadFile(_ p: NSItemProvider, into directory: URL, index: Int) async -> Item? {88        let preferred = p.registeredTypeIdentifiers.first { id in UTType(id).map { !$0.conforms(to: .url) || $0.conforms(to: .fileURL) } ?? true } ?? UTType.data.identifier89        let type = preferred == UTType.fileURL.identifier ? UTType.data.identifier : preferred90        let suggested = p.suggestedName91        return await withCheckedContinuation { continuation in92            _ = p.loadFileRepresentation(forTypeIdentifier: type) { url, _ in93                guard let url else { continuation.resume(returning: nil); return }94                let ut = UTType(filenameExtension: url.pathExtension) ?? UTType(type)95                var name = suggested ?? url.lastPathComponent96                if (name as NSString).pathExtension.isEmpty, let ext = ut?.preferredFilenameExtension ?? (url.pathExtension.isEmpty ? nil : url.pathExtension) { name += ".\(ext)" }97                name = name.replacingOccurrences(of: "/", with: "-")98                let folder = directory.appendingPathComponent("item-\(index)", isDirectory: true)99                let destination = folder.appendingPathComponent(name)100                do {101                    try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)102                    try FileManager.default.copyItem(at: url, to: destination)103                    let size = (try? destination.resourceValues(forKeys: [.fileSizeKey]))?.fileSize ?? 0104                    continuation.resume(returning: Item(name: name, type: ut?.preferredMIMEType ?? "application/octet-stream", size: size, url: destination))105                } catch { continuation.resume(returning: nil) }106            }107        }108    }109    private static func loadURL(_ p: NSItemProvider) async -> URL? {110        await withCheckedContinuation { c in _ = p.loadObject(ofClass: URL.self) { url, _ in c.resume(returning: url) } }111    }112    private static func loadText(_ p: NSItemProvider) async -> String? {113        await withCheckedContinuation { c in _ = p.loadObject(ofClass: String.self) { text, _ in c.resume(returning: text) } }114    }115116    func remove(_ item: Item) {117        items.removeAll { $0.id == item.id }118        try? FileManager.default.removeItem(at: item.url.deletingLastPathComponent())119    }120    func cleanUp() { try? FileManager.default.removeItem(at: workDirectory) }121122    // MARK: exits123124    private var sources: [ShareSource] { items.map { ShareSource(url: $0.url, name: $0.name, type: $0.type) } }125126    /// Sends now, through the API. On failure the draft stays on screen (and can still be queued for the app).127    func send() async {128        guard canSend, let token, let from = mailbox else { return }129        phase = .working(String(localized: "Envoi…"))130        let api = APIClient(baseURL: ExtConfig.baseURL(state), token: token, userAgent: "SPMail-Share/\(Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "0")")131        do {132            let outcome = try await ShareDelivery.send(api: api, from: from.address, to: recipients, subject: subject, note: note, files: sources, idempotencyKey: draftId)133            phase = .done(outcome.waitsForApproval ? String(localized: "Le message attend votre approbation dans SP Mail.") : String(localized: "Message remis au serveur."))134        } catch let e as APIError where e.isUnauthorized {135            phase = .failed(String(localized: "La session a expiré. Ouvrez SP Mail pour vous reconnecter."))136        } catch let e as APIError where e.isOffline {137            phase = .failed(String(localized: "Le serveur est injoignable. Vous pouvez enregistrer le brouillon : il vous attendra dans SP Mail."))138        } catch {139            phase = .failed((error as? LocalizedError)?.errorDescription ?? error.localizedDescription)140        }141    }142143    /// Hands the draft to the app: sealed in the shared container, imported the next time SP Mail is opened.144    func queue() async {145        guard canQueue else { return }146        phase = .working(String(localized: "Enregistrement…"))147        let draft = ShareDraft(id: draftId, mailboxId: mailbox?.id, to: to.isEmpty ? [] : [to], subject: subject, note: note)148        let queue = store.shareQueue, sources = sources149        let result: Result<ShareDraft, Error> = await Task.detached(priority: .userInitiated) { Result { try queue.enqueue(draft, sources: sources) } }.value150        switch result {151        case .success: phase = .done(String(localized: "Brouillon enregistré : il vous attend dans SP Mail."))152        case .failure(let error): phase = .failed((error as? LocalizedError)?.errorDescription ?? error.localizedDescription)153        }154    }155    /// After a failure: back to the draft.156    func retry() { phase = .editing }157}158
Files main
Menu

Theme