SPB Git

Repository Public

Compose.swift 44.4 KB 809 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Compose.swift3// Description: The composer's model — one draft being written: recipients, sender and signature, the rich text (Sources/Shared/Compose/4// RichTextEditor.swift), inline images and attachments, local-first autosave with honest states, and sending: through `/api/v1` with the5// server-side undo hold, a schedule or a reminder when the server is there; through the durable outbox when it is not.6//7// Sending rule (never lost, never twice): the draft is on the device before anything is sent. Online, the message goes through8// `POST /api/v1/messages/send` under an Idempotency-Key derived from the draft's content: an answer that never arrives is asked again9// with the same key (the server replays its first answer), and the draft stays locked until the server has said what it did. Offline —10// the server was not reached at all — the message is queued in the outbox (JMAP, client Message-ID), which has no undo window.11import PhotosUI12import SPMailCore13import SwiftUI14import UniformTypeIdentifiers1516/// What a recipient token field needs from its owner (the composer, the « send a template » dialog).17@MainActor18protocol RecipientHost: AnyObject {19    func edited()20    func suggestions(for prefix: String) async -> [EmailAddress]21    /// Richer autocomplete rows (saved contacts, favourites, groups). Defaults to `suggestions(for:)`.22    func recipientSuggestions(for prefix: String) async -> [RecipientSuggestion]23    func members(ofGroup id: String) async -> [EmailAddress]24    /// A token dragged into `field` leaves the field it came from. Returns false when the host does not own the other fields.25    func moveRecipient(_ address: EmailAddress, to field: RecipientFieldKind) -> Bool26}27extension RecipientHost {28    func recipientSuggestions(for prefix: String) async -> [RecipientSuggestion] {29        await suggestions(for: prefix).map { RecipientSuggestion(name: $0.name ?? "", email: $0.email, kind: .contact(saved: false, favorite: false)) }30    }31    func members(ofGroup id: String) async -> [EmailAddress] { [] }32    func moveRecipient(_ address: EmailAddress, to field: RecipientFieldKind) -> Bool { false }33}3435enum RecipientFieldKind: String, Sendable { case to, cc, bcc }3637/// How a message leaves.38enum SendMode: Equatable {39    case now40    case later(Date)41    /// Send now and be reminded at that date — only if nobody replied, when `onlyIfNoReply`.42    case remind(Date, onlyIfNoReply: Bool)43}4445/// A stored template to send in place of a draft, with the values of its variables. `token` names this attempt in the idempotency key.46struct TemplateDelivery: Equatable {47    var templateId: String48    var values: [String: String]49    var token = String(UUID().uuidString.prefix(12))50}5152/// What the server (or the outbox) did with a send request.53enum SendResult {54    /// Held by the server for the undo delay: it can still be taken back.55    case held(SendOutcome)56    /// Handed to the mail server (`sent`), or waiting on the server (`queued`).57    case accepted(SendOutcome)58    case scheduled(SendOutcome)59    case pendingApproval(SendOutcome)60    /// Accepted by the mail server through the outbox (no hold): what 1.1.0 called « accepté ».61    case acceptedByOutbox62    case queuedOffline63    /// Recipients on the sensitive list: nothing was queued, the person must confirm.64    case needsConfirmation([String])65    /// The server did not say what it did with the request; the draft is locked until it does.66    case unconfirmed67    case failed(String)68}6970@MainActor @Observable71final class ComposeModel: Identifiable, RecipientHost {72    enum Status: Equatable { case editing, saving, savedLocally, savedOnServer, sending, queuedOffline, accepted, unconfirmed, failed(String) }7374    nonisolated let id: String75    var item: OutboxItem76    var to: [EmailAddress]77    var cc: [EmailAddress]78    var bcc: [EmailAddress]79    var subject: String80    /// Every address the user can write from; `availableSenders` is what this message may switch to.81    var senders: [SenderIdentity]82    var senderId: String83    /// Every attachment this session knows: files, and inline images (those no longer referenced do not travel).84    var attachments: [OutgoingAttachment]85    var includeQuote = true86    var showCcBcc: Bool87    var status: Status = .editing88    var attachmentError: String?89    /// Another device replaced or removed the server copy of this draft: both versions were kept.90    var conflictNotice = false91    /// Bumped by the menu « Format » (attach a file, insert a picture, edit the link, snippets, templates).92    var attachRequest = 093    var imageRequest = 094    var linkRequest = 095    var snippetRequest = 096    var templateRequest = 097    /// Bumped by ⇧⌘D: the view runs the same checks as its Send button.98    var sendRequest = 099    /// The rich text of the body. The quoted original is not part of it.100    @ObservationIgnored let editor = RichTextController()101    /// The writing assistant's request and proposal for this draft (Sources/Shared/Compose/WritingAssistant.swift).102    @ObservationIgnored let assistant = WritingAssistant()103    /// A template send the server refused to queue until the sensitive recipients are confirmed (see `deliverTemplate`).104    @ObservationIgnored var pendingTemplate: TemplateDelivery?105    @ObservationIgnored private var newData: [String: Data] = [:]106    @ObservationIgnored private var originals: [String: Data] = [:]107    @ObservationIgnored private var images: [String: PlatformImage] = [:]108    @ObservationIgnored private var autosave: Task<Void, Never>?109    @ObservationIgnored private var dirty = false110    @ObservationIgnored private var finished = false111    @ObservationIgnored private var prepared = false112    @ObservationIgnored private var seenConflict: Date?113    @ObservationIgnored private let quoted: (text: String?, html: String?)114    @ObservationIgnored private(set) var engine: SyncEngine115    @ObservationIgnored let store: MailStore116    @ObservationIgnored weak var app: AppModel?117118    static let attachmentLimit = 25_000_000119120    init(item: OutboxItem, senders: [SenderIdentity], engine: SyncEngine, store: MailStore, app: AppModel) {121        id = item.id122        var item = item123        self.senders = senders124        self.engine = engine125        self.store = store126        self.app = app127        // the editable part as rich text; whatever the composer cannot represent stays whole in the untouched block128        var m = item.message129        let doc = NSMutableAttributedString(attributedString: RichBody.load(&m))130        item.message = m131        self.item = item132        to = m.to; cc = m.cc; bcc = m.bcc; subject = m.subject133        attachments = m.attachments134        quoted = (m.quotedText, m.quotedHTML)135        seenConflict = item.conflictedAt136        let mine = senders.filter { $0.account == item.account }137        let from = mine.first { $0.email.lowercased() == m.from.email.lowercased() } ?? mine.first { !$0.isAlias } ?? mine.first138        senderId = from?.id ?? ""139        showCcBcc = !m.cc.isEmpty || !m.bcc.isEmpty140        if let from { RichSignature.tagLegacy(in: doc, signatureText: from.signature, id: "address:\(from.email.lowercased())") }141        editor.setDocument(doc)142        editor.onChange = { [weak self] in self?.edited() }143        editor.snippets = { [weak self] in self?.app?.compose.snippets ?? [] }144        editor.onSnippet = { [weak self] s in if let self, self.subject.isEmpty, let subject = s.subject, !subject.isEmpty { self.subject = subject } }145        editor.onFiles = { [weak self] urls in self?.addDropped(urls: urls) }146        editor.onImages = { [weak self] list in for d in list { self?.addInlineImage(data: d, name: "image.png") } }147        editor.imageProvider = { [weak self] cid in self?.images[cid] }148        editor.allowedCIDs = { [weak self] in Set(self?.attachments.compactMap { $0.inline ? $0.cid.map(HTMLSanitizer.normalizedCID) : nil } ?? []) }149    }150151    // MARK: sender152153    var sender: SenderIdentity? { senders.first { $0.id == senderId } }154    var isReply: Bool { item.message.relation == .reply || !item.message.inReplyTo.isEmpty }155    /// A reply, a forward or a message whose attachments already sit on the server belongs to its mailbox: only that mailbox's addresses156    /// (itself and its aliases) are offered. A new message may leave from any mailbox.157    var canChangeMailbox: Bool { item.message.relation == nil && item.message.inReplyTo.isEmpty && !attachments.contains { $0.blobId != nil } && !isLocked }158    var availableSenders: [SenderIdentity] { canChangeMailbox ? senders : senders.filter { $0.account == item.account } }159    var senderGroups: [(mailbox: String, senders: [SenderIdentity])] {160        var out: [(mailbox: String, senders: [SenderIdentity])] = []161        for s in availableSenders {162            if let n = out.firstIndex(where: { $0.senders.first?.account == s.account }) { out[n].senders.append(s) } else { out.append((senders.first { $0.account == s.account && !$0.isAlias }?.email ?? s.email, [s])) }163        }164        return out165    }166167    private func defaultSignature(for s: SenderIdentity?) -> SignatureChoice? {168        guard let s else { return nil }169        return app?.compose.defaultSignature(for: s, isReply: isReply) ?? (s.signature.isEmpty ? nil : SignatureChoice(id: "address:\(s.email.lowercased())", text: s.signature))170    }171172    /// The From picker changed: the signature block of the previous address is replaced by the new one's default (never duplicated, never173    /// when the person edited or removed it, typed text untouched); when the new address belongs to another mailbox, the draft moves to174    /// that mailbox's engine.175    func senderChanged(from oldId: String) {176        guard let new = sender, let old = senders.first(where: { $0.id == oldId }), old.id != new.id else { return }177        swapSignature(old: defaultSignature(for: old), new: defaultSignature(for: new), force: false)178        if new.account != item.account, let next = app?.engines[new.account] {179            let previous = engine, serverCopy = item.serverEmailId180            item.account = new.account181            item.serverEmailId = nil182            engine = next183            if let serverCopy { Task { await previous.destroy(ids: [serverCopy]) } } // the copy in the other mailbox's Drafts184        }185        edited()186    }187188    private func swapSignature(old: SignatureChoice?, new: SignatureChoice?, force: Bool) {189        let doc = editor.document190        let known = app?.compose.knownSignatures(senders: senders) ?? senders.filter { !$0.signature.isEmpty }.map { SignatureChoice(id: "address:\($0.email.lowercased())", text: $0.signature) }191        guard let swap = RichSignature.swap(in: doc, old: old, new: new, known: known, force: force) else { return }192        let caret = editor.selection193        editor.edit(swap.range, with: swap.replacement, select: caret.location <= swap.range.location ? caret : nil, actionName: L("Signature"))194    }195196    /// The id of the signature whose block is in the text, if any.197    var currentSignatureId: String? {198        let doc = editor.storage199        guard let r = RichSignature.range(in: doc), r.length > 0 else { return nil }200        return doc.attribute(RichKey.signature, at: r.location, effectiveRange: nil) as? String201    }202    /// An explicit choice in the signature picker (nil = none): replaces the block even when it was edited.203    func chooseSignature(_ choice: SignatureChoice?) {204        swapSignature(old: nil, new: choice, force: true)205        if choice == nil, let r = RichSignature.range(in: editor.document) {206            // « none »: the block goes, with its blank line207            let s = editor.storage.string as NSString208            var whole = r209            while whole.location > 0, s.character(at: whole.location - 1) == 0x0A, r.location - whole.location < 2 { whole = NSRange(location: whole.location - 1, length: whole.length + 1) }210            editor.edit(whole, with: NSAttributedString(), actionName: L("Signature"))211        }212    }213214    // MARK: content215216    /// The typed text as plain text (the quoted original is not part of it).217    var plainText: String { editor.plainText }218    var hasQuote: Bool { quoted.text != nil || quoted.html != nil }219    var quotedPreview: String { quoted.text ?? quoted.html.map(HTMLText.plainText(fromHTML:)) ?? "" }220    /// True when the block under the text is the original of a reply or a forward (else it is content the composer keeps as it is).221    var quoteIsOriginal: Bool { item.message.relation != nil || (quoted.html ?? "").contains("gmail_quote") || !item.message.inReplyTo.isEmpty }222    var isLocked: Bool { status == .sending || status == .unconfirmed }223    var canSend: Bool { !(to + cc + bcc).isEmpty && !isLocked }224    var missingSubject: Bool { subject.trimmingCharacters(in: .whitespaces).isEmpty }225    var isRich: Bool { RichText.isRich(editor.storage) }226    /// The attachments shown in the tray (inline images live in the text).227    var files: [OutgoingAttachment] { attachments.filter { !$0.inline } }228    var totalAttachmentBytes: Int { currentAttachments().reduce(0) { $0 + $1.size } }229230    private func currentAttachments() -> [OutgoingAttachment] { InlineParts.reconciled(attachments, text: editor.storage, quotedHTML: includeQuote ? quoted.html : nil) }231232    /// The message as it stands in the editor.233    func currentMessage() -> OutgoingMessage {234        var m = item.message235        if let sender { m.identityId = sender.jmapIdentityId; m.from = sender.address }236        m.to = to; m.cc = cc; m.bcc = bcc; m.subject = subject237        m.quotedText = quoted.text; m.quotedHTML = quoted.html238        RichBody.store(editor.document, in: &m, attachments: attachments, includeQuote: includeQuote)239        return m240    }241242    /// The 1.1.0 view of the body, kept for callers that build text with Foundation attributes (bold, italic, strikethrough, code, link).243    var body: AttributedString {244        get {245            var out = AttributedString()246            let doc = editor.document247            doc.enumerateAttributes(in: NSRange(location: 0, length: doc.length)) { attrs, r, _ in248                var piece = AttributedString((doc.string as NSString).substring(with: r))249                var intent: InlinePresentationIntent = []250                if attrs[RichKey.bold] != nil { intent.insert(.stronglyEmphasized) }251                if attrs[RichKey.italic] != nil { intent.insert(.emphasized) }252                if attrs[RichKey.strike] != nil { intent.insert(.strikethrough) }253                if attrs[RichKey.code] != nil { intent.insert(.code) }254                if !intent.isEmpty { piece.inlinePresentationIntent = intent }255                if let l = attrs[RichKey.link] as? String { piece.link = URL(string: l) }256                out += piece257            }258            return out259        }260        set {261            let doc = NSMutableAttributedString()262            for run in newValue.runs {263                var attrs: [NSAttributedString.Key: Any] = [RichKey.block: RichBlock.body.rawValue]264                let intent = run.inlinePresentationIntent ?? []265                if intent.contains(.stronglyEmphasized) { attrs[RichKey.bold] = true }266                if intent.contains(.emphasized) { attrs[RichKey.italic] = true }267                if intent.contains(.strikethrough) { attrs[RichKey.strike] = true }268                if intent.contains(.code) { attrs[RichKey.code] = true }269                if let l = run.link?.absoluteString, let safe = RichImport.safeLink(l) { attrs[RichKey.link] = safe }270                doc.append(NSAttributedString(string: RichText.normalizedNewlines(String(newValue[run.range].characters)), attributes: attrs))271            }272            if let s = sender { RichSignature.tagLegacy(in: doc, signatureText: s.signature, id: "address:\(s.email.lowercased())") }273            editor.setDocument(doc)274            edited()275        }276    }277278    // MARK: entry points for other features (AI writing assistance, quick replies)279280    /// The text the person wrote, as plain text — without the quoted original.281    var currentPlainText: String { editor.plainText }282    /// The selected text (empty when there is only an insertion point).283    var selectedPlainText: String { (editor.storage.string as NSString).substring(with: editor.selection).replacingOccurrences(of: RichText.attachmentCharacter, with: "") }284    /// Inserts text at the insertion point — over the selection when `replacingSelection` — as one undoable edit.285    func insertText(_ text: String, replacingSelection: Bool = true) { editor.insert(text: text, replacingSelection: replacingSelection) }286    /// Inserts HTML (reduced to the composer's subset) at the insertion point.287    func insertHTML(_ html: String) { editor.insert(rich: RichHTML.parse(html, mode: .paste, allowedCIDs: []).text) }288    /// Replaces everything the person wrote above the signature (a rewritten draft). Undoable.289    func replaceText(_ text: String) {290        let end = RichSignature.range(in: editor.document).map { max(0, $0.location - 2) } ?? editor.storage.length291        editor.edit(NSRange(location: 0, length: end), with: RichText.attributed(fromPlain: text))292    }293    /// Puts text at the very top of the message (a suggested reply), above the signature and the quoted original.294    func prependText(_ text: String) {295        guard !text.isEmpty else { return }296        editor.edit(NSRange(location: 0, length: 0), with: RichText.attributed(fromPlain: text), select: NSRange(location: (text as NSString).length, length: 0))297    }298    func setSubject(_ text: String) { subject = text; edited() }299300    // MARK: lifecycle301302    /// Loads what the composer needs from the session (signatures, snippets, preferences), gives a NEW message the default signature of303    /// its sender, fetches the pictures of inline images, and resumes a send whose answer never came. Called once the view is up.304    func prepare() async {305        guard !prepared, let app else { return }306        prepared = true307        let fresh = ((try? await store.outboxItem(id)) ?? nil) == nil308        if fresh, app.compose.signatures.isEmpty { await app.compose.load() } else { Task { await app.compose.load() } }309        if fresh, !dirty, let s = sender {310            // what the builder inserted is the legacy per-address signature: the managed default for this address (or for replies) replaces it311            let legacy = s.signature.isEmpty ? nil : SignatureChoice(id: "address:\(s.email.lowercased())", text: s.signature)312            let wanted = defaultSignature(for: s)313            if wanted != legacy, wanted?.text != legacy?.text || !(wanted?.html.isEmpty ?? true) {314                swapSignature(old: legacy, new: wanted, force: false)315                editor.undo.removeAllActions()316                dirty = false317                if status == .saving { status = .editing; autosave?.cancel() }318            }319            editor.selection = NSRange(location: 0, length: 0)320        }321        await loadImages()322        if PendingSend.load(id)?.digest == currentMessage().contentDigest { status = .unconfirmed }323    }324325    /// Every edit lands here: written to the device right away (short debounce), then pushed to the server Drafts mailbox.326    func edited() {327        guard !finished, !isLocked else { return }328        dirty = true329        status = .saving330        autosave?.cancel()331        autosave = Task { [weak self] in332            try? await Task.sleep(for: .milliseconds(600))333            guard !Task.isCancelled else { return }334            await self?.saveLocally()335            try? await Task.sleep(for: .milliseconds(1800))336            guard !Task.isCancelled else { return }337            await self?.pushToServer()338        }339    }340341    /// Stops the pending autosave and waits for the one already running (a save or a draft push that passed its cancellation342    /// checks goes on to its end): nothing of it may land after the send or the discard that follows.343    private func settleAutosave() async {344        let running = autosave345        running?.cancel()346        await running?.value347    }348349    /// Saves now: on the device, then on the server when it can be reached.350    func save() async {351        autosave?.cancel()352        await saveLocally()353        await pushToServer()354    }355356    private func saveLocally() async {357        guard dirty, !finished else { return }358        dirty = false359        item.message = currentMessage()360        guard !item.message.isEmpty else { status = .editing; return }361        do {362            let data = newData363            item = try await engine.saveDraft(item, attachments: data)364            for k in data.keys { newData[k] = nil }365            mergeBlobIds(from: item.message.attachments)366            if !dirty { status = app?.isOnline == false ? .savedLocally : .saving }367        } catch { status = .failed(error.localizedDescription) }368    }369370    private func pushToServer() async {371        guard !finished, !item.message.isEmpty else { return }372        guard app?.isOnline != false, let synced = try? await engine.syncDraft(id: item.id) else {373            if !dirty, status == .saving { status = .savedLocally }374            return375        }376        guard !finished else { return }377        item.serverEmailId = synced.serverEmailId378        item.serverCopyIsDraft = synced.serverCopyIsDraft379        item.syncedDigest = synced.syncedDigest380        mergeBlobIds(from: synced.message.attachments)381        if let at = synced.conflictedAt, at != seenConflict { seenConflict = at; item.conflictedAt = at; conflictNotice = true }382        if !dirty { status = synced.needsDraftSync ? .savedLocally : .savedOnServer }383    }384385    private func mergeBlobIds(from saved: [OutgoingAttachment]) {386        for s in saved { if let n = attachments.firstIndex(where: { $0.id == s.id }), attachments[n].blobId != s.blobId { attachments[n].blobId = s.blobId } }387    }388389    func discard() async {390        finished = true391        await settleAutosave()392        PendingSend.clear(id)393        await engine.discardDraft(id: item.id)394    }395396    /// Closing the window keeps the draft (saved one last time) unless it is empty.397    func close() async {398        autosave?.cancel()399        if !finished {400            if currentMessage().isEmpty { await engine.discardDraft(id: item.id) } else { dirty = true; await save() }401        }402        app?.composerClosed(id)403    }404405    /// The app is quitting: the draft is written to the local outbox before the process ends (the engine works off the main thread, so406    /// a bounded wait here is safe). Nothing is pushed to the server.407    func saveBeforeTermination() {408        guard !finished, dirty || status == .saving else { return }409        autosave?.cancel()410        var snapshot = item411        snapshot.message = currentMessage()412        guard !snapshot.message.isEmpty else { return }413        let engine = engine, data = newData414        let done = DispatchSemaphore(value: 0)415        Task.detached { _ = try? await engine.saveDraft(snapshot, attachments: data); done.signal() }416        _ = done.wait(timeout: .now() + 1.5)417        dirty = false418    }419420    /// Bytes handed back by an undone send (the store dropped them when the message left).421    func adopt(data: [String: Data]) {422        for (k, v) in data where attachments.contains(where: { $0.id == k }) { originals[k] = originals[k] ?? v }423        Task { await loadImages(extra: data) }424    }425426    // MARK: attachments427428    func addAttachment(name: String, type: String, data: Data) {429        guard totalAttachmentBytes + data.count <= Self.attachmentLimit else { attachmentError = L("Les pièces jointes dépassent 25 Mo."); return }430        let a = OutgoingAttachment(name: name, type: type, size: data.count)431        newData[a.id] = data432        attachments.append(a)433        attachmentError = nil434        edited()435    }436437    func addAttachment(url: URL) {438        let scoped = url.startAccessingSecurityScopedResource()439        defer { if scoped { url.stopAccessingSecurityScopedResource() } }440        guard let data = try? Data(contentsOf: url) else { attachmentError = L("Ce fichier ne peut pas être lu."); return }441        let type = UTType(filenameExtension: url.pathExtension)?.preferredMIMEType ?? "application/octet-stream"442        addAttachment(name: url.lastPathComponent, type: type, data: data)443    }444445    /// Files dropped or pasted in the text: pictures go inline, the rest is attached.446    func addDropped(urls: [URL]) {447        for url in urls {448            if UTType(filenameExtension: url.pathExtension)?.conforms(to: .image) == true {449                let scoped = url.startAccessingSecurityScopedResource()450                let data = try? Data(contentsOf: url)451                if scoped { url.stopAccessingSecurityScopedResource() }452                if let data { addInlineImage(data: data, name: url.lastPathComponent); continue }453            }454            addAttachment(url: url)455        }456    }457458    func removeAttachment(_ a: OutgoingAttachment) {459        attachments.removeAll { $0.id == a.id }460        newData[a.id] = nil461        Task { try? await store.deleteAttachmentData(a.id) }462        edited()463    }464465    /// Reorders the tray: `id` goes before `target` (nil = to the end).466    func moveAttachment(_ id: String, before target: String?) {467        guard id != target, let from = attachments.firstIndex(where: { $0.id == id }) else { return }468        let moved = attachments.remove(at: from)469        let index = target.flatMap { t in attachments.firstIndex { $0.id == t } } ?? attachments.count470        attachments.insert(moved, at: index)471        edited()472    }473474    /// The bytes of an attachment, wherever they are: added in this session, sealed in the local outbox, or already on the server.475    func bytes(of a: OutgoingAttachment) async throws -> Data {476        if let d = newData[a.id] { return d }477        if let d = try await store.attachmentData(a.id) { return d }478        if let d = originals[a.id] { return d }479        if let blob = a.blobId { return try await engine.download(BodyPart(blobId: blob, size: a.size, name: a.name, type: a.type, cid: a.cid), inline: a.inline) }480        throw StoreError(message: "attachment \(a.name) is missing from the device")481    }482    /// A readable copy for Quick Look and thumbnails.483    func temporaryFile(for a: OutgoingAttachment) async -> URL? {484        guard let data = try? await bytes(of: a) else { return nil }485        return try? app?.temporaryFile(named: a.name, data: data)486    }487488    // MARK: inline images489490    /// Inserts a picture in the text at the insertion point: stored as an inline part with a Content-ID, referenced as `cid:` in the HTML.491    /// Large photos are reduced first; formats mail clients do not show (HEIC, TIFF) are converted.492    func addInlineImage(data: Data, name: String) {493        Task {494            guard let prepared = await Task.detached(operation: { InlineImageCodec.prepare(data, name: name) }).value else {495                // not a picture after all: an ordinary attachment496                addAttachment(name: name, type: UTType(filenameExtension: (name as NSString).pathExtension)?.preferredMIMEType ?? "application/octet-stream", data: data)497                return498            }499            guard totalAttachmentBytes + prepared.data.count <= Self.attachmentLimit else { attachmentError = L("Les pièces jointes dépassent 25 Mo."); return }500            let cid = RichImage.makeCID(domain: sender?.address.domain ?? "spmail")501            let a = OutgoingAttachment(name: prepared.name, type: prepared.type, size: prepared.data.count, cid: cid, inline: true)502            newData[a.id] = prepared.data503            originals[a.id] = prepared.data504            images[cid] = InlineImageCodec.image(from: prepared.data)505            attachments.append(a)506            attachmentError = nil507            // shown at half its pixel width (Retina photos), never wider than the « large » preset508            let natural = max(1, prepared.pixelWidth / 2)509            editor.insert(image: RichImage(cid: cid, name: prepared.name, width: natural > 560 ? 560 : (prepared.pixelWidth > 560 ? natural : nil)))510        }511    }512513    /// Applies a size preset to the selected image. A photo much larger than the preset is re-encoded at twice its display width, so the514    /// message does not carry pixels nobody sees.515    func resizeSelectedImage(to preset: RichImage.Preset) {516        guard let image = editor.imageAtSelection else { return }517        editor.resizeSelectedImage(to: preset)518        guard let width = preset.width, let n = attachments.firstIndex(where: { $0.inline && $0.cid.map(HTMLSanitizer.normalizedCID) == image.cid }) else { return }519        let a = attachments[n]520        Task {521            var known = originals[a.id]522            if known == nil { known = try? await bytes(of: a) }523            guard let source = known else { return }524            originals[a.id] = source525            guard let smaller = await Task.detached(operation: { InlineImageCodec.prepare(source, name: a.name, maxPixel: width * 2) }).value, smaller.data.count < a.size,526                  let i = attachments.firstIndex(where: { $0.id == a.id }) else { return }527            attachments[i].size = smaller.data.count528            attachments[i].type = smaller.type529            attachments[i].name = smaller.name530            attachments[i].blobId = nil531            newData[a.id] = smaller.data532            edited()533        }534    }535536    /// Decodes the pictures of the inline images so the editor can show them (from this session, the local outbox or the server).537    private func loadImages(extra: [String: Data] = [:]) async {538        var changed = false539        for a in attachments where a.inline {540            guard let cid = a.cid.map(HTMLSanitizer.normalizedCID), images[cid] == nil else { continue }541            var data = extra[a.id]542            if data == nil { data = try? await bytes(of: a) }543            if let data, let image = InlineImageCodec.image(from: data) { images[cid] = image; changed = true }544        }545        if changed { editor.imagesChanged() }546    }547548    // MARK: recipients549550    func suggestions(for prefix: String) async -> [EmailAddress] {551        await recipientSuggestions(for: prefix).filter { !$0.isGroup }.map(\.address)552    }553    func recipientSuggestions(for prefix: String) async -> [RecipientSuggestion] {554        let taken = Set((to + cc + bcc).map(\.id))555        guard let app else { return [] }556        return await app.compose.suggest(prefix, taken: taken)557    }558    func members(ofGroup id: String) async -> [EmailAddress] { await app?.compose.members(ofGroup: id) ?? [] }559    func moveRecipient(_ address: EmailAddress, to field: RecipientFieldKind) -> Bool {560        to.removeAll { $0.id == address.id }; cc.removeAll { $0.id == address.id }; bcc.removeAll { $0.id == address.id }561        switch field { case .to: to.append(address); case .cc: cc.append(address); showCcBcc = true; case .bcc: bcc.append(address); showCcBcc = true }562        edited()563        return true564    }565    var recipientIssues: RecipientIssues { RecipientIssues.check(to: to, cc: cc, bcc: bcc) }566    func removeDuplicateRecipients() {567        let unique = RecipientIssues.deduplicated(to: to, cc: cc, bcc: bcc)568        to = unique.to; cc = unique.cc; bcc = unique.bcc569        edited()570    }571572    // MARK: sending — outbox (JMAP)573574    /// Sends through the durable outbox, as 1.1.0 did: no undo window. The returned state is what the server said — `accepted` — or575    /// `queuedOffline` when it could not be reached.576    func send() async -> OutboxState {577        await settleAutosave()578        finished = true579        status = .sending580        item.message = currentMessage()581        let data = newData582        newData = [:]583        let result = await engine.send(item, attachments: data)584        item = result585        switch result.state {586        case .accepted: status = .accepted587        case .queuedOffline, .sending: status = .queuedOffline588        case .failed, .draft:589            status = .failed(result.lastError ?? "")590            finished = false591        }592        return result.state593    }594595    private func sendThroughOutbox() async -> SendResult {596        switch await send() {597        case .accepted: return .acceptedByOutbox598        case .queuedOffline, .sending: return .queuedOffline599        case .failed, .draft: return .failed(item.lastError ?? "")600        }601    }602603    // MARK: sending — /api/v1 (undo hold, schedule, reminder)604605    /// Sends the message. See the rule at the top of this file.606    func deliver(_ mode: SendMode = .now, confirmSensitive: Bool = false) async -> SendResult {607        guard let app, !finished else { return .failed("") }608        let previous = status609        status = .sending // locked at once: a second click on « Envoyer » finds the composer busy610        await settleAutosave()611        status = .sending612        // 1. on the device first613        var message = currentMessage()614        item.message = message615        do {616            let data = newData617            item = try await engine.saveDraft(item, attachments: data)618            for k in data.keys { newData[k] = nil }619            mergeBlobIds(from: item.message.attachments)620            dirty = false621        } catch { status = .failed(error.localizedDescription); return .failed(error.localizedDescription) }622        message = item.message623        let center = app.compose624        // the device knows it is offline: nothing is tried, the outbox takes the message (a schedule or a reminder needs the server)625        if !app.isOnline {626            if mode != .now { status = .savedLocally; return .failed(L("Programmer un envoi ou un rappel exige une connexion au serveur.")) }627            return await sendThroughOutbox()628        }629        // 2. is the server there? Its preferences carry the undo delay — read now, never from a stale copy630        let prefs: ComposePrefs631        do { prefs = try await center.freshPrefs() } catch {632            let unreachable = (error as? APIError)?.isOffline == true || !app.isOnline633            let noNext = (error as? NextError) == .notFound || (error as? APIError)?.status == 404634            guard unreachable || noNext else { status = .failed(app.describe(error) ?? ""); return .failed(app.describe(error) ?? "") }635            if noNext { center.nextUnavailable = true }636            // nothing was sent anywhere: the outbox takes the message (a schedule or a reminder needs the server)637            if mode != .now { status = .savedLocally; return .failed(L("Programmer un envoi ou un rappel exige une connexion au serveur.")) }638            return await sendThroughOutbox()639        }640        // 3. attachments as files of the sending mailbox (ids remembered: a retry sends the very same request)641        var pending = PendingSend.load(id).flatMap { $0.digest == message.contentDigest ? $0 : nil } ?? PendingSend(digest: message.contentDigest)642        var refs: [SendAttachment] = [], kept: [String: Data] = [:]643        do {644            for a in message.attachments {645                var fileId = pending.files[a.id]646                if fileId == nil || a.blobId == nil {647                    let data: Data648                    do { data = try await bytes(of: a) } catch let e as APIError where e.status == 404 && a.blobId != nil {649                        // the server copy of the draft was replaced meanwhile (a draft sync in flight) and its blobs went with it:650                        // the ids of the current copy are read, then the bytes are asked once more651                        guard let synced = try? await engine.syncDraft(id: item.id), let fresh = synced.message.attachments.first(where: { $0.id == a.id }), fresh.blobId != a.blobId else { throw e }652                        mergeBlobIds(from: synced.message.attachments)653                        data = try await bytes(of: fresh)654                    }655                    if a.blobId == nil || originals[a.id] != nil { kept[a.id] = data }656                    if fileId == nil { fileId = try await center.next.uploadFile(data, name: a.name, type: a.type.isEmpty ? "application/octet-stream" : a.type, address: message.from.email) }657                }658                guard let fileId else { continue }659                pending.files[a.id] = fileId660                let cid = a.inline ? a.cid.flatMap(ComposeSend.acceptableCID) : nil661                refs.append(SendAttachment(fileId: fileId, filename: a.name, inline: cid != nil && InlineParts.isInlineImageType(a.type), cid: cid != nil && InlineParts.isInlineImageType(a.type) ? cid : nil))662            }663        } catch {664            if (error as? APIError)?.isOffline == true, mode == .now { return await sendThroughOutbox() } // still nothing sent665            let text = app.describe(error) ?? error.localizedDescription666            status = .failed(text)667            return .failed(text)668        }669        var request = SendRequest(message, attachments: refs)670        var options = SendOptions(confirmSensitive: confirmSensitive)671        switch mode {672        case .now: options.undoSeconds = prefs.undoSeconds673        case .later(let date): request.sendAt = date674        case .remind(let date, let onlyIfNoReply): options.undoSeconds = prefs.undoSeconds; options.remindAt = date; options.remindIfNoReply = onlyIfNoReply675        }676        pending.key = ComposeSend.idempotencyKey(itemId: id, digest: message.contentDigest, options: options, sendAt: request.sendAt, files: message.attachments.compactMap { pending.files[$0.id] })677        PendingSend.store(pending, for: id)678        // 4. the request. An answer that does not come is asked again under the same key.679        var attempt = 0680        while true {681            attempt += 1682            do {683                let outcome = try await center.next.send(request, options: options, idempotencyKey: pending.key)684                PendingSend.clear(id)685                if outcome.outbound.status == "failed" {686                    let text = outcome.outbound.lastError ?? L("Le serveur de courrier a refusé le message.")687                    status = .failed(text)688                    return .failed(text)689                }690                // the server holds the message now: the local draft and its copy in Drafts have done their job691                finished = true692                var snapshot = item693                snapshot.message = message694                await engine.discardDraft(id: item.id)695                status = .accepted696                // the local item is gone: the outbox follows the send through what the server tracks (hold, schedule, delivery)697                app.outbound.note(subject: message.subject, for: outcome.id)698                Task { await app.outbound.reload(force: true) }699                if outcome.canUndo { center.addHold(outcome, item: snapshot, data: kept); return .held(outcome) }700                if let related = message.relatedEmailId, let relation = message.relation, !outcome.outbound.isScheduled, outcome.outbound.status != "pending_approval" {701                    await engine.setKeyword(relation == .forward ? Keyword.forwarded : Keyword.answered, true, ids: [related])702                }703                if outcome.outbound.isScheduled { return .scheduled(outcome) }704                if outcome.outbound.status == "pending_approval" { return .pendingApproval(outcome) }705                return .accepted(outcome)706            } catch NextError.confirmationRequired(let recipients) {707                PendingSend.clear(id)708                status = previous == .sending ? .editing : previous709                return .needsConfirmation(recipients)710            } catch {711                let api = error as? APIError712                let code = api?.code ?? ""713                if code == "unknown_file" || code == "file_expired", attempt == 1 {714                    // a file uploaded for an earlier attempt expired: upload again, as a new request715                    PendingSend.clear(id)716                    status = previous717                    return await deliver(mode, confirmSensitive: confirmSensitive)718                }719                let uncertain = api?.isOffline == true || (api?.status ?? 0) >= 500 || code == "idempotency_in_progress" || (error as? NextError).map { if case .rateLimited = $0 { true } else { false } } == true || error is URLError720                if uncertain {721                    if attempt < 4 { try? await Task.sleep(for: .seconds(Double(attempt) * 1.5)); continue }722                    status = .unconfirmed723                    return .unconfirmed724                }725                // the server answered and refused: nothing was queued726                PendingSend.clear(id)727                let text = api.flatMap { $0.message.isEmpty ? nil : $0.message } ?? app.describe(error) ?? error.localizedDescription728                status = .failed(text)729                return .failed(text)730            }731        }732    }733734    // MARK: sending — a stored template in place of this draft735736    /// Sends a stored template to this draft's recipients (the server renders it, its layout kept), with the user's undo delay. The same737    /// rules as `deliver`: a sensitive recipient makes the server ask first — nothing is queued, `.needsConfirmation` is returned and the738    /// template waits in `pendingTemplate` for the confirmation (`deliverTemplate(pending, confirmSensitive: true)`).739    /// The draft the template replaces is discarded only once the server took the message.740    func deliverTemplate(_ delivery: TemplateDelivery, confirmSensitive: Bool = false) async -> SendResult {741        guard let app, let sender, !finished, !isLocked else { return .failed("") }742        let previous = status743        status = .sending744        await settleAutosave()745        status = .sending746        var request = TemplateSend(from: sender.email, to: to, templateId: delivery.templateId, variables: delivery.values.filter { !$0.value.isEmpty }, subject: subject.isEmpty ? nil : subject)747        request.cc = cc; request.bcc = bcc748        let center = app.compose749        do {750            let prefs = (try? await center.freshPrefs()) ?? center.prefs751            // the confirmation changes the body: it is another request, under another key752            let key = "spm-tpl-\(id)-\(delivery.templateId)-\(delivery.token)\(confirmSensitive ? "-c" : "")"753            let outcome = try await center.next.sendTemplate(request, options: SendOptions(undoSeconds: prefs.undoSeconds, confirmSensitive: confirmSensitive), idempotencyKey: key)754            pendingTemplate = nil755            if outcome.outbound.status == "failed" {756                let text = outcome.outbound.lastError ?? L("Le serveur de courrier a refusé le message.")757                status = .failed(text)758                return .failed(text)759            }760            app.outbound.note(subject: subject, for: outcome.id)761            Task { await app.outbound.reload(force: true) }762            await discard()763            status = .accepted764            if outcome.canUndo { center.addHold(outcome, item: nil, data: [:]); return .held(outcome) }765            if outcome.outbound.isScheduled { return .scheduled(outcome) }766            if outcome.outbound.status == "pending_approval" { return .pendingApproval(outcome) }767            return .accepted(outcome)768        } catch NextError.confirmationRequired(let recipients) {769            pendingTemplate = delivery770            status = previous == .sending ? .editing : previous771            return .needsConfirmation(recipients)772        } catch {773            pendingTemplate = nil774            let text = (error as? APIError).flatMap { $0.message.isEmpty ? nil : $0.message } ?? app.describe(error) ?? error.localizedDescription775            status = .failed(text)776            return .failed(text)777        }778    }779780    /// The person gives up on an unconfirmed send and goes back to editing. The server may have taken the message: the interface says so.781    func unlockAfterUnconfirmedSend() {782        guard status == .unconfirmed else { return }783        PendingSend.clear(id)784        status = .editing785    }786}787788/// The send in flight of a draft: its Idempotency-Key and the files already uploaded for it. Kept across relaunches (no content, no789/// address — ids only) so that « was it sent? » is always asked with the same key.790struct PendingSend: Codable {791    var key = ""792    var digest: String793    var files: [String: String] = [:]794    private static let defaultsKey = "spm.compose.pendingSends"795    private static func all() -> [String: PendingSend] {796        (UserDefaults.standard.data(forKey: defaultsKey)).flatMap { try? JSONDecoder().decode([String: PendingSend].self, from: $0) } ?? [:]797    }798    static func load(_ id: String) -> PendingSend? { all()[id] }799    static func store(_ p: PendingSend, for id: String) {800        var a = all(); a[id] = p801        if let d = try? JSONEncoder().encode(a) { UserDefaults.standard.set(d, forKey: defaultsKey) }802    }803    static func clear(_ id: String) {804        var a = all()805        guard a.removeValue(forKey: id) != nil else { return }806        if a.isEmpty { UserDefaults.standard.removeObject(forKey: defaultsKey) } else if let d = try? JSONEncoder().encode(a) { UserDefaults.standard.set(d, forKey: defaultsKey) }807    }808}809
Files main
Menu

Theme