Repository Public
1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/AppModel.swift3// Description: The app's shared state: session (passkey sign-in, 401, sign-out), mailboxes and their sync engines, folders and counters, outbox, composers,4// toasts. Everything a window navigates (folder, list, conversation, search) lives in a MailScene; lock, sync status and notifications are services.5import AuthenticationServices6import SPMailCore7import SwiftUI89enum SidebarItem: Hashable, Sendable {10 case mailbox(String)11 case unread12 case flagged13 /// One list across every mailbox (`GET /api/v1/messages`): inbox, unread, flagged, drafts, sent.14 case unified(UnifiedView)15 /// Sends waiting for their date on the server; they can be cancelled.16 case scheduled17 /// Local drafts not yet on the server, queued messages, and what the server answered for recent sends.18 case outbox19 // SP Mail Next — entries hidden unless the server announces the matching capability20 /// The Command Center (dashboard). Never the default screen.21 case dashboard22 /// Conversations carrying a user label (label id): a `label:` search across every mailbox.23 case label(String)24 /// A saved search / smart folder (id), opened as a list.25 case savedSearch(String)26 /// The operator search screen (also the target of ⌘F).27 case search28 case snoozed29 case followUps30 case contacts31 case attachments32}3334enum MailAction: Sendable {35 case markRead(Bool), flag(Bool), archive, delete, junk, move(String)36 /// Any other JMAP keyword through the engine's pending-operation queue: `$pinned`, a label keyword `lbl_…`.37 case keyword(String, Bool)38 static func pin(_ on: Bool) -> MailAction { .keyword(NextKeyword.pinned, on) }39}4041enum ComposeKind {42 case new43 case reply(EmailSummary), replyAll(EmailSummary), forward(EmailSummary)44 case outboxItem(OutboxItem)45 case serverDraft(EmailSummary)46 case mailto(URL)47}4849/// An unread conversation of any mailbox (menu bar extra).50struct RecentUnread: Identifiable, Hashable, Sendable {51 let account: String52 let thread: ThreadSummary53 var id: String { "\(account)/\(thread.id)" }54}5556@MainActor @Observable57final class AppModel {58 enum Phase { case launching, signedOut, locked, ready }5960 let settings = AppSettings()61 let api = APIClient(baseURL: AppConfig.baseURL, userAgent: AppConfig.userAgent)62 let monitor = NetworkMonitor()63 let sync = SyncStatusModel()64 let lock = LockController()65 /// SP Mail Next services (labels, snoozes, search, contacts, dashboard, intelligence): one API + store per session.66 let next = NextServices()67 /// What the server tracks for the messages sent through `/api/v1` (held, scheduled, delivery per recipient): shown in the outbox.68 let outbound = OutboundTracker()69 @ObservationIgnored var hooks = MailHooks()70 @ObservationIgnored private let secrets = AppConfig.secrets()71 @ObservationIgnored private let passkeys = PasskeyCoordinator()72 @ObservationIgnored private(set) var store: MailStore?73 @ObservationIgnored private(set) var engines: [String: SyncEngine] = [:]74 @ObservationIgnored private var eventTasks: [String: Task<Void, Never>] = [:]75 @ObservationIgnored private var activityTasks: [String: Task<Void, Never>] = [:]76 @ObservationIgnored private var launched = false77 @ObservationIgnored private var sceneRefs: [WeakScene] = []78 @ObservationIgnored private var mainClaimed = false7980 var phase: Phase = .launching81 var me: MeResponse?82 var accounts: [MeResponse.Box] = []83 /// Folders of every mailbox, keyed by mailbox id (each window shows those of its own mailbox).84 var mailboxesByAccount: [String: [Mailbox]] = [:]85 var unreadByAccount: [String: Int] = [:]86 var flaggedByAccount: [String: Int] = [:]87 var inboxUnread: [String: Int] = [:]88 var recentUnread: [RecentUnread] = []89 var outbox: [OutboxItem] = []90 var toast: Toast?91 var signInError: String?92 var isBusy = false93 var composers: [String: ComposeModel] = [:]94 var pushStatus = L("Non demandé")95 /// Every address the user can write from: mailboxes and their sendable aliases.96 var senders: [SenderIdentity] = []97 /// The window the app starts with (and the one the self-test drives). Other windows own their MailScene.98 @ObservationIgnored private(set) lazy var main = MailScene(app: self)99 @ObservationIgnored private(set) lazy var studio = StudioModel(app: self)100 /// Push, notifications, widgets and extensions, Spotlight, deep links, background work (Sources/Shared/System).101 @ObservationIgnored private(set) lazy var system = SystemServices(app: self)102103 init() { lock.app = self; next.app = self; outbound.app = self }104105 var accountMap: [String: String] { Dictionary(accounts.map { ($0.address.lowercased(), $0.id) }, uniquingKeysWith: { a, _ in a }) }106 var myAddresses: Set<String> { Set(accounts.map { $0.address.lowercased() }) }107 var totalInboxUnread: Int { inboxUnread.values.reduce(0, +) }108 /// What needs the person in the outbox: queued or refused messages, and unsent items of a mailbox that was removed.109 var outboxAttention: Int { outbox.filter { $0.state == .queuedOffline || $0.state == .failed || $0.state == .sending || isOrphan($0) }.count }110 var isOnline: Bool { get { sync.isOnline } set { sync.isOnline = newValue } }111 var isSyncing: Bool { sync.isSyncing }112 func mailboxes(for account: String?) -> [Mailbox] { account.flatMap { mailboxesByAccount[$0] } ?? [] }113 func box(_ account: String?) -> MeResponse.Box? { accounts.first { $0.id == account } }114 /// Short status messages go through the toast; setting a string keeps the former one-line API.115 var notice: String? {116 get { toast?.message }117 set { toast = newValue.map { Toast(message: $0) } }118 }119120 // MARK: scenes121122 /// Every live window state (the main one included), for events that concern all of them.123 var scenes: [MailScene] { sceneRefs.compactMap(\.scene) }124 func register(_ scene: MailScene) {125 sceneRefs.removeAll { $0.scene == nil }126 if !sceneRefs.contains(where: { $0.scene === scene }) { sceneRefs.append(WeakScene(scene: scene)) }127 }128 /// The state of a new window: the first one gets `main`, the next ones their own navigation state on the same session and engines.129 func claimScene() -> MailScene {130 if !mainClaimed { mainClaimed = true; return main }131 let s = MailScene(app: self)132 s.adopt(account: main.currentAccount)133 return s134 }135 /// The window came back on screen after `releaseScene` (its view kept the state).136 func reclaim(_ scene: MailScene) {137 if scene === main { mainClaimed = true }138 register(scene)139 }140 func releaseScene(_ scene: MailScene) {141 if scene === main { mainClaimed = false } else { sceneRefs.removeAll { $0.scene === scene || $0.scene == nil } }142 }143144 // MARK: launch and session145146 func launch() async {147 guard !launched else { return }148 launched = true149 CoreStrings.untitledAttachment = L("fichier")150 lock.start()151 _ = main152 ComposeCenter.removeLegacyCache() // the composer's former private store: it shares the session's now153 #if DEBUG154 if let t = AppConfig.devToken { api.token = t; try? secrets.write(SecretKeys.bearerToken, Data(t.utf8)) }155 #endif156 if api.token == nil, let d = try? secrets.read(SecretKeys.bearerToken) { api.token = String(decoding: d, as: UTF8.self) }157 guard api.token != nil else { phase = .signedOut; return }158 await start()159 }160161 private func openStore() -> MailStore? {162 if let store { return store }163 do {164 // a cache whose key is gone cannot be read: start clean rather than keep undecipherable rows165 if (try secrets.read(SecretKeys.cacheKey)) == nil { try? FileManager.default.removeItem(at: AppConfig.cacheDirectory) }166 let s = try MailStore(directory: AppConfig.cacheDirectory, secrets: secrets)167 store = s168 return s169 } catch {170 notice = L("Le cache local est inaccessible : ") + error.localizedDescription171 return nil172 }173 }174175 /// One sync engine per mailbox; safe to call again when the server-side list of mailboxes changed.176 private func attachEngines(_ store: MailStore) async {177 for box in accounts where engines[box.id] == nil {178 let e = SyncEngine(account: box.id, address: box.address, api: api, store: store)179 engines[box.id] = e180 let id = box.id181 eventTasks[id] = Task { [weak self] in182 for await event in e.events { await self?.handle(event, account: id) }183 }184 activityTasks[id] = Task { [weak self] in185 for await activity in e.activity { self?.handle(activity, account: id) }186 }187 await e.startLive(monitor: monitor)188 }189 }190191 /// A mailbox was removed on the server (administration): its engine is detached — the core stops it and wipes the account's cache192 /// (headers, bodies, pending operations, cached attachments, decrypted temporary files) — and no window keeps showing it.193 /// Its unsent drafts and queued messages are NOT destroyed: they stay sealed on the device and are listed in the outbox as194 /// « boîte retirée », where the person exports them (.eml) or deletes them. Nothing of them is ever sent from another mailbox.195 private func detach(account id: String) async {196 // an open composer of that mailbox: what was typed is written to the outbox before the composer goes197 for composer in composers.values where composer.item.account == id { composer.saveBeforeTermination() }198 if let e = engines.removeValue(forKey: id) { await e.detach(removingOutbox: false) }199 eventTasks.removeValue(forKey: id)?.cancel()200 activityTasks.removeValue(forKey: id)?.cancel()201 sync.forget(account: id)202 mailboxesByAccount[id] = nil; unreadByAccount[id] = nil; flaggedByAccount[id] = nil; inboxUnread[id] = nil203 recentUnread.removeAll { $0.account == id }204 system.accountDetached(id)205 for (key, composer) in composers where composer.item.account == id { composers[key] = nil }206 for scene in scenes { await scene.accountRemoved(id, fallback: accounts.first?.id) }207 }208209 #if DEBUG210 /// Self-test only: the mailbox disappears from this session exactly as when `/api/me` stops listing it (`refreshAccounts` → `detach`).211 /// `refreshAccounts()` brings it back afterwards (the server still lists it).212 func debugSimulateMailboxRemoval(_ id: String) async {213 accounts.removeAll { $0.id == id }214 await detach(account: id)215 await reloadMailboxes()216 await reloadOutbox()217 }218 #endif219220 /// Mailboxes can be added or removed on the server (administration): re-read the list when the app comes back to the foreground.221 func refreshAccounts() async {222 guard phase == .ready || phase == .locked, let store, let fresh = try? await api.me() else { return }223 let before = accounts.map(\.id)224 me = fresh225 try? await store.setValue("me", fresh)226 accounts = fresh.mailboxes.sorted { ($0.position ?? 0) < ($1.position ?? 0) }227 guard accounts.map(\.id) != before else { await loadSenders(); return }228 for gone in Set(engines.keys).subtracting(accounts.map(\.id)) { await detach(account: gone) }229 await attachEngines(store)230 await loadSenders()231 await reloadMailboxes()232 await reloadOutbox()233 }234235 /// Returning to the foreground: mailbox list, then one sync pass per window.236 func refreshAll() async {237 await refreshAccounts()238 for scene in scenes { await scene.refresh(accountsAlreadyRefreshed: true) }239 await next.refresh()240 }241242 private func start() async {243 guard let store = openStore() else { phase = .signedOut; return }244 do {245 let fresh = try await api.me()246 me = fresh247 try? await store.setValue("me", fresh)248 } catch let e as APIError where e.isUnauthorized {249 await sessionRevoked()250 return251 } catch {252 // offline at launch: the cached identity lets the person read what is already on the device253 guard let cached = try? await store.value("me", as: MeResponse.self) else {254 signInError = describe(error)255 phase = .signedOut256 return257 }258 me = cached259 isOnline = false260 }261 accounts = (me?.mailboxes ?? []).sorted { ($0.position ?? 0) < ($1.position ?? 0) }262 // Unsent drafts and queued messages of a mailbox this user no longer has are kept (outbox: « boîte retirée » — export or delete).263 // The one exception: items left by ANOTHER user of this device (a revoked session keeps its outbox sealed for the next sign-in of264 // the same person) are dropped — nobody is shown somebody else's drafts.265 let owner = me?.user.id ?? ""266 if let previous = UserDefaults.standard.string(forKey: Self.outboxOwnerKey), previous != owner {267 for item in (try? await store.outbox()) ?? [] where !accounts.contains(where: { $0.id == item.account }) { try? await store.deleteOutbox(item.id) }268 }269 if !owner.isEmpty { UserDefaults.standard.set(owner, forKey: Self.outboxOwnerKey) }270 await attachEngines(store)271 let saved = UserDefaults.standard.string(forKey: "currentAccount")272 let first = accounts.contains { $0.id == saved } ? saved : accounts.first?.id273 phase = settings.lockEnabled ? .locked : .ready274 lock.noteActivity()275 await reloadMailboxes()276 for scene in scenes { await scene.sessionStarted(account: first) }277 await reloadOutbox()278 await loadSenders()279 await next.start()280 Task { await outbound.reload(force: true) }281 // the first sync pass of the session (the window may never become « active » when the app is launched behind another one)282 Task { for scene in scenes { await scene.refresh(accountsAlreadyRefreshed: true) } }283 var prompt = true284 #if DEBUG285 if UserDefaults.standard.bool(forKey: "spmNoPrompts") { prompt = false } // unattended captures: no system permission sheet over the window286 #endif287 await system.sessionStarted(prompt: prompt)288 }289290 private func teardown() async {291 eventTasks.values.forEach { $0.cancel() }292 eventTasks = [:]293 activityTasks.values.forEach { $0.cancel() }294 activityTasks = [:]295 for e in engines.values { await e.stopLive() }296 engines = [:]297 composers = [:]298 accounts = []; mailboxesByAccount = [:]; unreadByAccount = [:]; flaggedByAccount = [:]; inboxUnread = [:]; recentUnread = []; outbox = []; senders = []299 for scene in scenes { scene.reset() }300 compose.reset()301 outbound.reset()302 await next.wipe()303 sync.reset()304 studio.reset()305 me = nil306 Notifier.setBadge(0)307 }308309 func signIn() async {310 isBusy = true; signInError = nil311 defer { isBusy = false }312 do {313 let ch = try await api.loginOptions()314 let assertion = try await passkeys.assertion(options: ch.options)315 let token = try await api.loginVerify(challengeId: ch.challengeId, response: assertion, client: AppConfig.clientInfo)316 try secrets.write(SecretKeys.bearerToken, Data(token.utf8))317 await start()318 } catch { signInError = describe(error) }319 }320321 /// Checks a pasted enrollment link and says what it is for.322 func checkEnrollment(_ link: String) async -> (token: String, check: EnrollCheck)? {323 signInError = nil324 guard let token = PasskeyCoordinator.enrollmentToken(from: link) else { signInError = L("Ce lien d’inscription n’est pas valide."); return nil }325 do { return (token, try await api.enrollCheck(token: token)) } catch { signInError = describe(error); return nil }326 }327328 func enroll(token: String, handle: String?, displayName: String?) async {329 isBusy = true; signInError = nil330 defer { isBusy = false }331 do {332 let ch = try await api.enrollOptions(token: token, handle: handle, displayName: displayName)333 let registration = try await passkeys.registration(options: ch.options)334 let bearer = try await api.enrollVerify(challengeId: ch.challengeId, response: registration, label: AppConfig.clientInfo.deviceName, client: AppConfig.clientInfo)335 try secrets.write(SecretKeys.bearerToken, Data(bearer.utf8))336 await start()337 } catch { signInError = describe(error) }338 }339340 /// Adds a passkey of this device to the signed-in account.341 func addPasskey(label: String) async throws {342 let ch = try await api.passkeyOptions()343 try await api.passkeyVerify(challengeId: ch.challengeId, response: try await passkeys.registration(options: ch.options), label: label)344 }345346 /// Sign-out: the session is revoked on the server, the local cache and its key are destroyed.347 func signOut() async {348 await system.sessionEnding()349 try? await api.logout()350 let s = store351 await teardown()352 try? await s?.destroy()353 store = nil354 UserDefaults.standard.removeObject(forKey: Self.outboxOwnerKey)355 try? secrets.delete(SecretKeys.bearerToken)356 api.token = nil357 system.sessionEnded()358 phase = .signedOut359 }360361 /// 401: the session was revoked elsewhere. Back to sign-in; unsent drafts and queued messages stay sealed on the device.362 func sessionRevoked() async {363 guard api.token != nil else { return }364 api.token = nil365 try? secrets.delete(SecretKeys.bearerToken)366 let s = store367 await teardown()368 try? await s?.wipeKeepingOutbox()369 system.sessionEnded()370 signInError = L("Cette session a été révoquée. Connectez-vous de nouveau ; vos brouillons non envoyés sont conservés sur cet appareil.")371 phase = .signedOut372 }373374 func describe(_ error: Error) -> String? {375 if let a = error as? ASAuthorizationError {376 if a.code == .canceled { return nil }377 return L("La clé d’accès n’a pas pu être utilisée : ") + a.localizedDescription378 }379 if let e = error as? APIError {380 if e.isOffline { return L("Le serveur est injoignable. Vérifiez la connexion.") }381 switch e.code {382 case "unknown_passkey": return L("Cette clé d’accès n’est associée à aucun compte SP Mail.")383 case "passkey_verification_failed": return L("La vérification de la clé d’accès a échoué.")384 case "invalid_token": return L("Ce lien d’inscription a expiré ou a déjà servi.")385 case "handle_taken": return L("Cet identifiant est déjà pris.")386 case "account_disabled": return L("Ce compte est désactivé.")387 case "rate_limited": return L("Trop de tentatives. Réessayez dans une minute.")388 default: return e.message.isEmpty ? e.code : e.message389 }390 }391 return error.localizedDescription392 }393394 // MARK: lock (see LockController)395396 func lockIfNeeded(force: Bool = false) { lock.lockIfNeeded(force: force) }397 func unlock() async { await lock.unlock() }398399 // MARK: engine events400401 private func handle(_ event: SyncEvent, account: String) async {402 switch event {403 case .mailboxesChanged:404 await reloadMailboxes()405 case .emailsChanged:406 for scene in scenes { await scene.emailsChanged(account: account) }407 await reloadRecentUnread()408 system.emailsChanged(account: account)409 case .outboxChanged:410 await reloadOutbox()411 case .newMail(let list):412 // Spotlight (opt-in, bounded by the privacy level) and the local notification — silent when the server announces mail by push413 await system.newMail(list, account: account)414 case .unauthorized:415 await sessionRevoked()416 case .connectivity(let online):417 sync.isOnline = online418 case .syncing:419 break // the indicator follows `SyncEngine.activity` (see below)420 }421 }422423 /// What the engine reports besides cache changes: its status for the quiet indicator, and the rare outcomes the person must hear about.424 private func handle(_ activity: SyncActivity, account: String) {425 switch activity {426 case .status(let status):427 sync.set(status, account: account)428 case .operationsRejected:429 toast = Toast(message: L("Des modifications faites hors ligne ont été refusées par le serveur ; l’état du serveur a été rétabli."), kind: .warning)430 case .draftConflict:431 toast = Toast(message: L("Ce brouillon a été modifié sur un autre appareil : les deux versions sont conservées."), kind: .warning)432 case .duplicateSendAvoided:433 toast = Toast(message: L("Ce message était déjà parti : il n’a pas été envoyé une seconde fois."), kind: .info)434 Task { await reloadOutbox() }435 }436 }437438 // MARK: shared folder state439440 func reloadMailboxes() async {441 guard let store else { return }442 for box in accounts {443 let list = (try? await store.mailboxes(box.id)) ?? []444 inboxUnread[box.id] = list.first { $0.role == "inbox" }?.unreadEmails ?? 0445 if mailboxesByAccount[box.id] != list { mailboxesByAccount[box.id] = list }446 unreadByAccount[box.id] = (try? await store.count(box.id, scope: .unread)) ?? 0447 flaggedByAccount[box.id] = (try? await store.count(box.id, scope: .flagged)) ?? 0448 }449 system.mailboxesReloaded()450 for scene in scenes { scene.mailboxesChanged() }451 await reloadRecentUnread()452 }453454 /// The five most recent unread conversations across mailboxes (menu bar extra).455 func reloadRecentUnread() async {456 guard let store else { recentUnread = []; return }457 var all: [RecentUnread] = []458 for box in accounts {459 guard let inbox = mailboxesByAccount[box.id]?.first(where: { $0.role == "inbox" }) else { continue }460 let rows = ((try? await store.threads(box.id, scope: .mailbox(inbox.id), threaded: true, limit: 40)) ?? []).filter { $0.unreadCount > 0 }461 all += rows.prefix(5).map { RecentUnread(account: box.id, thread: $0) }462 }463 let top = Array(all.sorted { $0.thread.email.receivedAt > $1.thread.email.receivedAt }.prefix(5))464 if top != recentUnread { recentUnread = top }465 }466467 func reloadOutbox() async {468 outbox = ((try? await store?.outbox()) ?? []).filter { !$0.message.isEmpty || $0.state != .draft }469 }470471 private static let outboxOwnerKey = "spm.outboxOwner"472473 /// The mailbox this unsent item belongs to is gone from the account (removed on the server, access withdrawn): it can no longer be474 /// edited or sent here — only exported or deleted.475 func isOrphan(_ item: OutboxItem) -> Bool { !accounts.contains { $0.id == item.account } }476477 /// An unsent message as an `.eml` file (with the attachments whose bytes are on the device), in the app's private temporary folder.478 func exportEML(of item: OutboxItem) async throws -> URL {479 guard let store else { throw StoreError(message: "no store") }480 var data: [String: Data] = [:]481 for a in item.message.attachments { if let d = try await store.attachmentData(a.id) { data[a.id] = d } }482 return try temporaryFile(named: EMLExport.fileName(subject: item.message.subject, date: item.updatedAt), data: OutgoingEML.data(item.message, attachments: data, date: item.updatedAt))483 }484485 /// Deletes an unsent item whose mailbox is gone (its sealed attachments with it). There is no server copy to remove.486 func deleteOrphan(_ item: OutboxItem) async {487 try? await store?.deleteOutbox(item.id)488 composers[item.id] = nil489 await reloadOutbox()490 }491492 /// Puts a refused or waiting message back in the queue and submits it again.493 func retry(_ item: OutboxItem) async {494 guard let e = engines[item.account] else { return }495 _ = await e.send(item)496 await reloadOutbox()497 }498499 // MARK: composing500501 /// Mailboxes and their sendable aliases (`GET /api/v1/addresses`), with the name and signature of each. Offline: the last list seen,502 /// or the mailboxes alone.503 func loadSenders() async {504 guard let store else { return }505 var rows = (try? await store.value("addresses", as: [MailAddress].self)) ?? []506 if let fresh = try? await api.addresses() { rows = fresh; try? await store.setValue("addresses", fresh) }507 var identities: [String: [Identity]] = [:]508 for box in accounts { identities[box.id] = (try? await engines[box.id]?.identities(refresh: isOnline)) ?? [] }509 let list = SenderIdentity.list(addresses: rows, identities: identities, accounts: accounts.map { (id: $0.id, address: $0.address, name: $0.display_name ?? "") })510 if list != senders { senders = list }511 }512513 /// Builds (or finds) the composer of a new message, a reply, a forward or a draft in mailbox `account`, and returns its id.514 /// `deliveredTo` are the envelope recipients of the original when it was opened from the unified list.515 func makeComposer(_ kind: ComposeKind, account: String, deliveredTo: [String] = []) async -> String? {516 guard let engine = engines[account], let store else { return nil }517 if senders.isEmpty { await loadSenders() }518 let mine = senders.filter { $0.account == account }519 guard let primary = mine.first(where: { !$0.isAlias }) ?? mine.first else { return nil }520 var item: OutboxItem521 let french = Locale.current.language.languageCode?.identifier != "en"522 func built(_ k: ReplyKind, _ e: EmailSummary) async -> OutboxItem {523 let body = try? await engine.body(for: e.id)524 // the reply leaves from the address the message was sent to (an alias included) when it is one of this mailbox's525 let from = SenderIdentity.forReply(to: e, among: mine, deliveredTo: deliveredTo, fallback: primary) ?? primary526 // "me" is this mailbox only: a message from another of my own mailboxes is answered like any other527 let me = Set(mine.map { $0.email.lowercased() } + [engine.address.lowercased()])528 return OutboxItem(account: account, message: ReplyBuilder.build(kind: k, original: e, body: body, identity: from.identity, me: me, labels: french ? .french : .english, locale: .current))529 }530 switch kind {531 case .new: item = OutboxItem(account: account, message: ReplyBuilder.blank(identity: primary.identity))532 case .reply(let e): item = await built(.reply, e)533 case .replyAll(let e): item = await built(.replyAll, e)534 case .forward(let e): item = await built(.forward, e)535 case .outboxItem(let existing):536 item = existing537 if let open = composers[existing.id] { return open.id }538 case .serverDraft(let e):539 guard let adopted = try? await engine.adoptServerDraft(e) else { notice = L("Ce brouillon n’est pas disponible hors ligne."); return nil }540 item = adopted541 if let open = composers[adopted.id] { return open.id }542 case .mailto(let url):543 var m = ReplyBuilder.blank(identity: primary.identity)544 let comps = URLComponents(url: url, resolvingAgainstBaseURL: false)545 m.to = AddressParser.parseList(comps?.path.removingPercentEncoding ?? "")546 for q in comps?.queryItems ?? [] {547 switch q.name.lowercased() {548 case "subject": m.subject = q.value ?? ""549 case "body": m.text = (q.value ?? "") + m.text550 case "cc": m.cc = AddressParser.parseList(q.value ?? "")551 case "bcc": m.bcc = AddressParser.parseList(q.value ?? "")552 default: break553 }554 }555 item = OutboxItem(account: account, message: m)556 }557 let model = ComposeModel(item: item, senders: senders, engine: engines[item.account] ?? engine, store: store, app: self)558 composers[item.id] = model559 return item.id560 }561562 /// A composer window restored after a relaunch: the draft is read back from the local outbox (it was saved there while typing).563 func restoreComposer(id: String) async -> ComposeModel? {564 if let open = composers[id] { return open }565 guard phase == .ready, let store, let item = try? await store.outboxItem(id), item.state == .draft || item.state == .failed, let engine = engines[item.account] else { return nil }566 if senders.isEmpty { await loadSenders() }567 let model = ComposeModel(item: item, senders: senders, engine: engine, store: store, app: self)568 composers[id] = model569 return model570 }571572 func composerClosed(_ id: String) { composers[id] = nil }573574 // MARK: attachments and export575576 func temporaryFile(named name: String, data: Data) throws -> URL {577 let dir = FileManager.default.temporaryDirectory.appendingPathComponent("spmail-files/\(UUID().uuidString)", isDirectory: true)578 try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)579 let safe = name.replacingOccurrences(of: "/", with: "-").replacingOccurrences(of: ":", with: "-")580 let url = dir.appendingPathComponent(safe.isEmpty || safe.hasPrefix(".") ? "fichier" : safe)581 try data.write(to: url, options: .completeFileProtectionUnlessOpen)582 return url583 }584 func emlFile(for email: EmailSummary, account: String) async throws -> URL {585 guard let engine = engines[account] else { throw StoreError(message: "no account") }586 return try temporaryFile(named: EMLExport.fileName(subject: email.subject, date: email.date), data: try await engine.exportEML(email))587 }588 static func purgeTemporaryFiles() {589 try? FileManager.default.removeItem(at: FileManager.default.temporaryDirectory.appendingPathComponent("spmail-files"))590 }591592 // MARK: push and background refresh593594 func didRegisterForPush(_ token: Data) async {595 await system.push.didRegister(token: token)596 switch system.push.registration {597 case .registered: pushStatus = L("Jeton enregistré auprès du serveur")598 case .failed(let reason): pushStatus = L("Enregistrement refusé : ") + reason599 default: break600 }601 }602 func didFailToRegisterForPush(_ error: Error) { system.push.didFail(error); pushStatus = L("Indisponible sur cette version : ") + error.localizedDescription }603604 /// One sync pass of every mailbox — what the iOS background refresh task runs when the system grants it time.605 func backgroundRefresh() async {606 _ = await BackgroundWork.refresh(self)607 }608}609610/// A window state held weakly by the shared model.611struct WeakScene { weak var scene: MailScene? }612