Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Compose/ComposeCenter.swift3// Description: What every composer shares — the session's ONE Next API client and sealed store (`AppModel.next`: signatures, snippets,4// compose preferences, contact suggestions; no second store, no second directory), the sendable addresses with their server ids, recipient autocomplete, the messages held by undo send and their countdown5// toast, and the public entry points other features use to open or fill a composer.6import SPMailCore7import SwiftUI8#if os(macOS)9import AppKit10#else11import UIKit12#endif1314/// A message the server is holding (undo send): until `until` it can be taken back.15struct SendHold: Identifiable {16 let id: String17 var until: Date18 var subject: String19 var account: String20 /// The draft as it was when it was sent, with the bytes of its local attachments: reopening it loses nothing, even what the server's21 /// sanitiser normalised. Nil for a hold this device did not create in this session.22 var item: OutboxItem?23 var data: [String: Data] = [:]24 var relatedEmailId: String?25 var relation: OutgoingMessage.Relation?26 var isUndoing = false27}2829/// One row of the recipient autocomplete.30struct RecipientSuggestion: Identifiable, Hashable {31 enum Kind: Hashable { case contact(saved: Bool, favorite: Bool), group(id: String) }32 var name: String33 var email: String34 var kind: Kind35 var id: String { if case .group(let g) = kind { "group:\(g)" } else { email.lowercased() } }36 var address: EmailAddress { EmailAddress(name: name.isEmpty ? nil : name, email: email) }37 var isGroup: Bool { if case .group = kind { true } else { false } }38}3940@MainActor @Observable41final class ComposeCenter {42 @ObservationIgnored private static var centers: [ObjectIdentifier: ComposeCenter] = [:]43 static func center(for app: AppModel) -> ComposeCenter {44 if let c = centers[ObjectIdentifier(app)] { return c }45 let c = ComposeCenter(app: app)46 centers[ObjectIdentifier(app)] = c47 return c48 }4950 @ObservationIgnored weak var app: AppModel?51 /// The session's Next API client — the one of `NextServices` (same bearer, same 401 path).52 var next: NextAPI { app?.next.api ?? NextAPI(APIClient(baseURL: AppConfig.baseURL, userAgent: AppConfig.userAgent)) }53 @ObservationIgnored private var loading: Task<Void, Never>?54 @ObservationIgnored private var observers: [NSObjectProtocol] = []5556 var prefs = ComposePrefs()57 /// True once the preferences came from the server or its cache (before that the defaults are shown).58 var prefsKnown = false59 var signatures: [Signature] = []60 var snippets: [Snippet] = []61 var addresses: [MailAddress] = []62 var groups: [ContactGroup] = []63 var holds: [SendHold] = []64 /// How many outbox screens are on display. On iOS the floating countdown is not shown over them: it would cover the navigation bar,65 /// and each held message already has its countdown and « Annuler l’envoi » in its own row there.66 var outboxScreens = 067 /// The Next API is not there (an older server): the composer sends as 1.1.0 did, without undo, schedule or reminders.68 var nextUnavailable = false69 var lastError: String?7071 private init(app: AppModel) {72 self.app = app73 #if os(macOS)74 let quit = NSApplication.willTerminateNotification75 #else76 let quit = UIApplication.willTerminateNotification77 #endif78 observers.append(NotificationCenter.default.addObserver(forName: quit, object: nil, queue: .main) { [weak self] _ in MainActor.assumeIsolated { self?.flushComposersNow() } })79 #if os(iOS)80 observers.append(NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main) { [weak self] _ in MainActor.assumeIsolated { self?.flushComposersNow() } })81 #endif82 }8384 // MARK: cache8586 /// The sealed store of the Next collections: the session's shared one (`NextServices.store`). Nil before the session is ready and on87 /// a server without the Next API. It is wiped with the session (sign-out, revoked session) by `NextServices.wipe()`.88 var sharedStore: NextStore? {89 guard let app, app.phase == .ready || app.phase == .locked else { return nil }90 return app.next.store91 }92 private func cache() async -> NextStore? { sharedStore }9394 /// Sign-out or revoked session: nothing of the previous user stays in memory (the store itself is wiped by `NextServices`).95 func reset() {96 loading?.cancel(); loading = nil97 prefs = ComposePrefs(); prefsKnown = false98 signatures = []; snippets = []; addresses = []; groups = []; holds = []99 nextUnavailable = false; lastError = nil100 }101102 /// The folder the composer's own store used before it shared the session's (`…/next-compose`).103 static var legacyCacheDirectory: URL { AppConfig.cacheDirectory.appendingPathComponent("next-compose", isDirectory: true) }104 /// Deletes what that store left behind. Called at every launch; a no-op once the folder is gone.105 static func removeLegacyCache() { try? FileManager.default.removeItem(at: legacyCacheDirectory) }106107 /// The shared store changed (a refresh by `NextServices`, a replayed mutation): the composer's mirrors follow.108 func storeChanged() async { await readCache() }109110 private func readCache() async {111 guard let s = await cache() else { return }112 signatures = await s.signatures()113 snippets = await s.snippets()114 if let p = await s.composePrefs() { prefs = p; prefsKnown = true }115 }116117 /// Reads the cache at once, then refreshes it from the server (signatures, snippets, preferences, suggestions, addresses, groups).118 /// Calls made while a refresh runs wait for it.119 func load(force: Bool = false) async {120 if let loading { await loading.value; if !force { return } }121 let task = Task { [weak self] in122 guard let self, let app = self.app else { return }123 await self.readCache()124 if let rows = try? await app.store?.value("addresses", as: [MailAddress].self), self.addresses.isEmpty { self.addresses = rows }125 // a server without the Next API has no store: the composer sends as 1.1.0 did126 if app.phase == .ready || app.phase == .locked, app.next.store == nil, !app.next.isAvailable { self.nextUnavailable = true }127 guard app.isOnline, let s = await self.cache() else { return }128 _ = await s.flush()129 do {130 let report = try await s.refresh([.signatures, .snippets, .composePrefs, .suggestions, .favoriteContacts])131 if report.failed.values.contains(where: { $0.contains("404") || $0.contains("not_found") }) && report.refreshed.isEmpty { self.nextUnavailable = true } else if !report.refreshed.isEmpty { self.nextUnavailable = false }132 } catch { self.lastError = app.describe(error) }133 await self.readCache()134 if let fresh = try? await app.api.addresses() { self.addresses = fresh }135 if let g = try? await self.next.contactGroups() { self.groups = g }136 }137 loading = task138 await task.value139 loading = nil140 }141142 /// The preferences as the server holds them right now (the undo delay must never come from a stale cache when a message is sent).143 /// Throws when the server cannot be reached or has no Next API.144 func freshPrefs() async throws -> ComposePrefs {145 let p = try await next.composePrefs()146 prefs = p; prefsKnown = true147 return p148 }149150 func setPrefs(_ new: ComposePrefs) async {151 prefs = new152 guard let s = await cache() else { _ = try? await next.setComposePrefs(new); return }153 await s.setComposePrefs(new)154 _ = await s.flush()155 if let p = await s.composePrefs() { prefs = p }156 }157158 // MARK: signatures and snippets159160 func addressId(for email: String) -> String? { addresses.first { $0.address.lowercased() == email.lowercased() }?.id }161162 /// The signature a message from `sender` starts with: a managed signature that claims the address (for replies when it is one), else163 /// the legacy per-address signature.164 func defaultSignature(for sender: SenderIdentity, isReply: Bool) -> SignatureChoice? {165 if let id = addressId(for: sender.email), let s = Signature.defaultSignature(forAddress: id, isReply: isReply, in: signatures) { return SignatureChoice(s) }166 return sender.signature.isEmpty ? nil : SignatureChoice(id: "address:\(sender.email.lowercased())", text: sender.signature)167 }168 /// Every signature a block in a draft may have been inserted from (to tell an untouched block from an edited one).169 func knownSignatures(senders: [SenderIdentity]) -> [SignatureChoice] {170 signatures.map(SignatureChoice.init) + senders.filter { !$0.signature.isEmpty }.map { SignatureChoice(id: "address:\($0.email.lowercased())", text: $0.signature) }171 }172173 func saveSignature(id: String?, _ content: SignatureContent) async {174 guard let s = await cache() else { return }175 if let id { await s.updateSignature(id: id, content) } else { _ = await s.createSignature(content) }176 signatures = await s.signatures()177 let report = await s.flush()178 if let dropped = report.dropped.first { lastError = dropped.message }179 if app?.isOnline == true { _ = try? await s.refresh([.signatures]) }180 signatures = await s.signatures()181 }182 func deleteSignature(id: String) async {183 guard let s = await cache() else { return }184 await s.deleteSignature(id: id)185 signatures = await s.signatures()186 _ = await s.flush()187 }188 func saveSnippet(id: String?, _ content: SnippetContent) async {189 guard let s = await cache() else { return }190 if let id { await s.updateSnippet(id: id, content) } else { _ = await s.createSnippet(content) }191 snippets = await s.snippets()192 let report = await s.flush()193 if let dropped = report.dropped.first { lastError = dropped.message }194 if app?.isOnline == true { _ = try? await s.refresh([.snippets]) }195 snippets = await s.snippets()196 }197 func deleteSnippet(id: String) async {198 guard let s = await cache() else { return }199 await s.deleteSnippet(id: id)200 snippets = await s.snippets()201 _ = await s.flush()202 }203204 // MARK: recipients205206 /// Autocomplete: the server ranking (saved contacts, favourites, frequency × recency) when it answers, the cached suggestions and the207 /// correspondents of the local mail cache otherwise; contact groups whose name matches come first.208 func suggest(_ text: String, taken: Set<String>) async -> [RecipientSuggestion] {209 let q = text.trimmingCharacters(in: .whitespaces)210 guard !q.isEmpty, let app else { return [] }211 var out: [RecipientSuggestion] = []212 let folded = q.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: nil)213 for g in groups where g.name.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: nil).hasPrefix(folded) {214 out.append(RecipientSuggestion(name: g.name, email: "", kind: .group(id: g.id)))215 }216 var rows: [ContactSuggestion] = []217 if app.isOnline, !nextUnavailable, let server = try? await next.suggestContacts(q, limit: 8) { rows = server }218 if rows.isEmpty, let s = await cache() { rows = await s.suggest(q, limit: 8) }219 var seen = taken220 for r in rows where seen.insert(r.email.lowercased()).inserted {221 out.append(RecipientSuggestion(name: r.name, email: r.email, kind: .contact(saved: r.contactId != nil && r.kind != .suggested, favorite: r.favorite)))222 }223 // the correspondents this device has seen fill what is left (and are all there is offline on a fresh cache)224 if out.filter({ !$0.isGroup }).count < 6 {225 for a in ((try? await app.store?.suggestCorrespondents(q)) ?? []) where seen.insert(a.id).inserted {226 out.append(RecipientSuggestion(name: a.name ?? "", email: a.email, kind: .contact(saved: false, favorite: false)))227 }228 }229 return Array(out.prefix(8))230 }231232 /// The members of a contact group, as recipients.233 func members(ofGroup id: String) async -> [EmailAddress] {234 var out: [EmailAddress] = []235 if app?.isOnline == true, let page = try? await next.contacts(ContactQuery(group: id, limit: 200)) {236 for c in page.contacts { if let e = c.emails.first { out.append(EmailAddress(name: c.name.isEmpty ? nil : c.name, email: e.email)) } }237 } else if let s = await cache() {238 for c in await s.favoriteContacts() where c.groups.contains(id) { if let e = c.emails.first { out.append(EmailAddress(name: c.name.isEmpty ? nil : c.name, email: e.email)) } }239 }240 return out241 }242243 // MARK: undo send244245 func addHold(_ outcome: SendOutcome, item: OutboxItem?, data: [String: Data]) {246 guard let until = outcome.undoUntil else { return }247 holds.removeAll { $0.id == outcome.id }248 holds.append(SendHold(id: outcome.id, until: until, subject: item?.message.subject ?? "", account: item?.account ?? "", item: item, data: data,249 relatedEmailId: item?.message.relatedEmailId, relation: item?.message.relation))250 let id = outcome.id251 Task { [weak self] in252 try? await Task.sleep(for: .seconds(max(0.2, until.timeIntervalSinceNow) + 1.2))253 await self?.holdEnded(id)254 }255 }256257 /// The window closed without an undo: the server has taken the message. What it did with it is asked, never assumed.258 private func holdEnded(_ id: String) async {259 guard let n = holds.firstIndex(where: { $0.id == id }), !holds[n].isUndoing, let app else { return }260 let hold = holds.remove(at: n)261 var status: OutboundStatus?262 for _ in 0..<6 {263 status = try? await app.api.outbound(id: id)264 if let s = status, !s.isScheduled { break }265 try? await Task.sleep(for: .seconds(1.5))266 }267 await app.outbound.reload(force: true)268 guard let status else { return }269 switch status.status {270 case "sent", "delivered", "queued", "deferred":271 if let related = hold.relatedEmailId, let relation = hold.relation { await app.engines[hold.account]?.setKeyword(relation == .forward ? Keyword.forwarded : Keyword.answered, true, ids: [related]) }272 app.toast = Toast(message: OutboundLabels.label(status.status).text, kind: status.status == "queued" || status.status == "deferred" ? .info : .success)273 SPHaptics.success()274 case "failed", "bounced":275 app.toast = Toast(message: L("Échec — le message n’est pas parti") + (status.lastError.map { " (\($0))" } ?? ""), kind: .error)276 SPHaptics.warning()277 default: break278 }279 }280281 /// Undo: the server cancels the held message and keeps its draft and attachments; the composer reopens on what was written.282 /// Returns the id of the reopened composer, nil when the message had already left.283 @discardableResult284 func undo(_ id: String, open: Bool = true) async -> String? {285 guard let app else { return nil }286 let n = holds.firstIndex { $0.id == id }287 if let n { holds[n].isUndoing = true }288 let held: HeldMessage289 do { held = try await next.undoSend(id: id) } catch {290 if let n = holds.firstIndex(where: { $0.id == id }) { holds.remove(at: n) }291 let gone = (error as? APIError)?.status == 409 || (error as? NextError) == .notFound292 app.toast = Toast(message: gone ? L("Trop tard : le message est déjà parti.") : L("L’annulation n’a pas abouti : ") + (app.describe(error) ?? ""), kind: .error)293 return nil294 }295 let hold = n.flatMap { _ in holds.first { $0.id == id } }296 holds.removeAll { $0.id == id }297 Task { await app.outbound.reload(force: true) }298 let composer = await reopen(held, hold: hold)299 if open, let composer { app.main.composeRequest = composer }300 if composer == nil { app.toast = Toast(message: L("Envoi annulé — le message est dans « Brouillons »."), kind: .info) }301 return composer302 }303304 /// Rebuilds the draft of a message taken back. With the copy this device kept, nothing differs from what was written; without it,305 /// the server's content is used. Either way the draft the server kept becomes this draft's server copy (no second copy appears).306 private func reopen(_ held: HeldMessage, hold: SendHold?) async -> String? {307 guard let app, let store = app.store else { return nil }308 let account = hold?.account.isEmpty == false ? hold!.account : (held.mailboxId ?? app.main.currentAccount ?? "")309 guard let engine = app.engines[account] else { return nil }310 if app.senders.isEmpty { await app.loadSenders() }311 var item: OutboxItem312 if var kept = hold?.item {313 kept.state = .draft314 kept.submissionId = nil; kept.lastError = nil; kept.failureKind = nil; kept.submissionUncertain = nil315 kept.message.messageId = nil316 // the bytes the server kept: nothing has to be uploaded again317 for i in kept.message.attachments.indices {318 let a = kept.message.attachments[i]319 if let match = held.attachments.first(where: { $0.name == a.name && $0.size == a.size && ($0.cid.map(HTMLSanitizer.normalizedCID) == a.cid.map(HTMLSanitizer.normalizedCID) || !a.inline) }) { kept.message.attachments[i].blobId = match.blobId }320 else if hold?.data[a.id] != nil { kept.message.attachments[i].blobId = nil }321 }322 item = kept323 } else {324 let from = app.senders.first { $0.account == account && $0.email.lowercased() == held.from.lowercased() } ?? app.senders.first { $0.account == account && !$0.isAlias }325 guard let from else { return nil }326 item = OutboxItem(account: account, message: OutgoingMessage(held: held, from: from.address, identityId: from.jmapIdentityId))327 }328 item.serverEmailId = held.emailId329 item.serverCopyIsDraft = held.emailId != nil330 item.syncedDigest = nil331 item.needsDraftSync = true332 guard let saved = try? await engine.saveDraft(item, attachments: hold?.data ?? [:]) else { return nil }333 let model = ComposeModel(item: saved, senders: app.senders, engine: engine, store: store, app: app)334 if let data = hold?.data { model.adopt(data: data) }335 app.composers[saved.id] = model336 await app.reloadOutbox()337 return saved.id338 }339340 // MARK: quitting341342 /// The app is about to quit or be suspended: every open composer is written to the local outbox before it happens (bounded wait).343 private func flushComposersNow() {344 guard let app else { return }345 for composer in app.composers.values { composer.saveBeforeTermination() }346 }347}348349extension AppModel {350 /// Services shared by every composer of this session.351 var compose: ComposeCenter { ComposeCenter.center(for: self) }352353 // MARK: entry points for other features (AI writing, quick replies, contacts)354355 /// Opens a reply to `email` with `body` already written above the signature and the quoted original. Returns the composer (already356 /// presented in `scene`), or nil when the mailbox is not available.357 @discardableResult358 func openReply(to email: EmailSummary, body: String, all: Bool = false, in scene: MailScene? = nil) async -> ComposeModel? {359 let scene = scene ?? main360 await scene.compose(all ? .replyAll(email) : .reply(email))361 guard let id = scene.composeRequest, let composer = composers[id] else { return nil }362 composer.prependText(body)363 return composer364 }365366 /// Opens a new message to `recipients` with an optional subject and body.367 @discardableResult368 func openComposer(to recipients: [EmailAddress] = [], subject: String = "", body: String = "", in scene: MailScene? = nil) async -> ComposeModel? {369 let scene = scene ?? main370 await scene.compose(.new)371 guard let id = scene.composeRequest, let composer = composers[id] else { return nil }372 if !recipients.isEmpty { composer.to = recipients }373 if !subject.isEmpty { composer.setSubject(subject) }374 if !body.isEmpty { composer.prependText(body) }375 composer.edited()376 return composer377 }378}379380// MARK: - undo toast381382/// « Envoi dans N s » with its one action. Bottom-leading on macOS, top on iOS / iPadOS — where the app's toasts appear.383struct ComposeUndoToast: View {384 let hold: SendHold385 let center: ComposeCenter386387 var body: some View {388 TimelineView(.periodic(from: .now, by: 0.5)) { context in389 let left = max(0, Int(ceil(hold.until.timeIntervalSince(context.date))))390 HStack(spacing: SPSpacing.l) {391 if hold.isUndoing { ProgressView().controlSize(.small) } else { Image(systemName: "paperplane").foregroundStyle(SPColor.accent) }392 Text(hold.isUndoing ? L("Annulation…") : left > 0 ? L("Envoi dans \(left) s") : L("Envoi au serveur…"))393 .font(SPFont.callout).foregroundStyle(SPColor.text).monospacedDigit().lineLimit(1).fixedSize()394 if !hold.isUndoing, left > 0 {395 Button(L("Annuler l’envoi")) { Task { await center.undo(hold.id) } }396 .buttonStyle(.borderless).font(SPFont.callout.weight(.semibold)).foregroundStyle(SPColor.accent).fixedSize()397 .keyboardShortcut("z", modifiers: [.command, .shift, .option])398 #if os(iOS)399 .frame(minHeight: 44)400 #endif401 }402 }403 .padding(.horizontal, SPSpacing.xl).padding(.vertical, 6)404 #if os(macOS)405 .frame(minHeight: 36)406 #endif407 .spGlass(RoundedRectangle(cornerRadius: SPRadius.dialog, style: .continuous))408 .accessibilityElement(children: .contain)409 .accessibilityLabel(Text(left > 0 ? L("Envoi dans \(left) s") : L("Envoi au serveur…")))410 }411 }412}413414struct ComposeUndoHost: ViewModifier {415 let app: AppModel416 @Environment(\.accessibilityReduceMotion) private var reduceMotion417418 func body(content: Content) -> some View {419 let center = app.compose420 #if os(macOS)421 let alignment = Alignment.bottomLeading, edge = Edge.bottom422 #else423 let alignment = Alignment.top, edge = Edge.top424 #endif425 return content.overlay(alignment: alignment) {426 if let hold = center.holds.last, showsToast(center) {427 ComposeUndoToast(hold: hold, center: center)428 .padding(SPSpacing.xl)429 // the app's own toast keeps its place: the countdown sits next to it, never on it430 #if os(macOS)431 .padding(.bottom, app.toast == nil ? 0 : 52)432 #else433 .padding(.top, app.toast == nil ? 0 : 56)434 #endif435 .transition(reduceMotion ? .opacity : .move(edge: edge).combined(with: .opacity))436 .onAppear { AccessibilityNotification.Announcement(L("Message retenu : l’envoi peut encore être annulé.")).post() }437 .id(hold.id)438 }439 }440 .spAnimation(SPMotion.quick, value: center.holds.last?.id)441 }442}443444extension ComposeUndoHost {445 fileprivate func showsToast(_ center: ComposeCenter) -> Bool {446 #if os(iOS)447 center.outboxScreens == 0448 #else449 true450 #endif451 }452}453454extension View {455 /// Shows the undo-send countdown of the session in this window.456 func composeUndoHost(_ app: AppModel) -> some View { modifier(ComposeUndoHost(app: app)) }457}458