SPB Git

Repository Public

SharedStateWriter.swift 8.4 KB 153 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/System/SharedStateWriter.swift3// Description: The app side of the shared container (decision D-N10): copies the session token to the shared keychain group (the app's own4// entry is kept), writes the extension state (lock, privacy level, mailboxes) and, after each sync, the sealed widget snapshot limited by the5// notification preview level — then asks WidgetKit to reload (no polling by the widgets). Imports the drafts queued by the share extension.6// Everything is cleared on sign-out. The mail database never leaves the app container.7import CryptoKit8import SPMailCore9import SPMailSystem10import SwiftUI11import WidgetKit1213@MainActor14final class SharedStateWriter {15    unowned let app: AppModel16    let next: NextAPI17    let store = SharedStore.open()18    private var snapshotTask: Task<Void, Never>?19    private var lastState: ExtensionState?20    private var lastSnapshotDigest = ""21    private var lastSnapshotAt = Date.distantPast22    private var reminders: [Reminder] = []23    private var remindersAt = Date.distantPast24    private var importing = false2526    init(app: AppModel, next: NextAPI) { self.app = app; self.next = next }2728    // MARK: session2930    func sessionStarted() {31        store.migrateToken(from: AppConfig.secrets())32        writeState()33    }34    func sessionEnded() {35        snapshotTask?.cancel(); snapshotTask = nil36        store.clear(baseURL: AppConfig.baseURL.absoluteString)37        lastState = nil; lastSnapshotDigest = ""; lastSnapshotAt = .distantPast; reminders = []; remindersAt = .distantPast38        WidgetCenter.shared.reloadAllTimelines()39    }4041    // MARK: extension state4243    /// The preview level content may be shared at: the account preference, lowered to nothing by the device switch.44    var previewLevel: PushPreview {45        if app.settings.hideNotificationContent { return .none }46        let p = app.system.push.prefs?.preview ?? .sender47        return p == .unknown ? .none : p48    }4950    func currentState() -> ExtensionState {51        let signedIn = app.phase == .ready || app.phase == .locked52        let lock = LockSnapshot(enabled: app.settings.lockEnabled, afterMinutes: app.settings.lockAfterMinutes, locked: app.phase == .locked, leftAt: AppActivity.isActive ? nil : (app.lock.leftAt ?? lastState?.lock.leftAt ?? Date()))53        return ExtensionState(signedIn: signedIn, preview: app.system.push.prefs?.preview ?? .sender, hideContent: app.settings.hideNotificationContent, lock: lock,54                              mailboxes: app.accounts.map { ExtensionState.Box(id: $0.id, address: $0.address, name: $0.display_name ?? "") },55                              defaultMailboxId: app.main.currentAccount ?? app.accounts.first?.id, baseURL: AppConfig.baseURL.absoluteString)56    }5758    /// Written whenever something the extensions depend on changes: session, lock, leaving or returning to the app, privacy switches.59    func writeState() {60        guard app.phase != .launching else { return }61        guard app.phase != .signedOut else { return } // sign-out wrote the signed-out state already62        var state = currentState()63        if let last = lastState { var same = last; same.updatedAt = state.updatedAt; if same == state { return } }64        state.updatedAt = Date()65        store.write(state)66        let lockChanged = lastState?.lock != state.lock || lastState?.hideContent != state.hideContent || lastState?.preview != state.preview || lastState?.signedIn != state.signedIn67        lastState = state68        if lockChanged { WidgetCenter.shared.reloadAllTimelines() }69    }7071    // MARK: widget snapshot7273    /// After a sync or a change of counters; several calls within a moment produce one snapshot.74    func scheduleSnapshot() {75        guard snapshotTask == nil else { return }76        snapshotTask = Task { [weak self] in77            try? await Task.sleep(for: .milliseconds(1500))78            guard let self, !Task.isCancelled else { return }79            self.snapshotTask = nil80            await self.writeSnapshot()81        }82    }8384    func buildSnapshot() async -> WidgetSnapshot? {85        guard app.phase == .ready || app.phase == .locked, let mail = app.store else { return nil }86        let prefs = app.system.push.prefs87        let unread = app.accounts.filter { prefs?.isMuted(mailbox: $0.id) != true }.map { WidgetSnapshot.MailboxCount(mailboxId: $0.id, address: $0.address, unread: app.inboxUnread[$0.id] ?? 0) }88        var recent: [SearchResult] = []89        let iso = ISO8601DateFormatter()90        for box in app.accounts where prefs?.isMuted(mailbox: box.id) != true {91            guard let inbox = app.mailboxes(for: box.id).first(where: { $0.role == "inbox" }) else { continue }92            for row in ((try? await mail.threads(box.id, scope: .mailbox(inbox.id), threaded: true, limit: WidgetSnapshot.maxConversations)) ?? []) {93                let e = row.email94                let json: JSONValue = ["mailbox_id": .string(box.id), "email_id": .string(e.id), "thread_id": .string(e.threadId), "subject": .string(e.subject), "preview": .string(e.preview),95                                       "from": .array(e.from.map { ["name": .string($0.name ?? ""), "email": .string($0.email)] }), "received_at": .string(iso.string(from: e.receivedAt)),96                                       "keywords": .object(row.unreadCount > 0 ? [:] : [Keyword.seen: true])]97                if let r = SearchResult(json: json) { recent.append(r) }98            }99        }100        // due reminders come from the server (nothing in the local cache knows them); refreshed at most every five minutes, kept when offline101        if app.isOnline, Date().timeIntervalSince(remindersAt) > 300 {102            remindersAt = Date()103            if let due = try? await next.reminders(status: .due) { reminders = due }104        }105        return WidgetSnapshot(unread: unread, recent: recent, reminders: reminders, preview: previewLevel, limit: WidgetSnapshot.maxConversations)106    }107108    func writeSnapshot() async {109        guard let snapshot = await buildSnapshot() else { return }110        var stable = snapshot111        stable.generatedAt = .distantPast112        let digest = (try? JSONEncoder().encode(stable)).map { SHA256.hash(data: $0).map { String(format: "%02x", $0) }.joined() } ?? UUID().uuidString113        // unchanged content is rewritten only to keep the snapshot from looking stale (widgets say so after an hour)114        guard digest != lastSnapshotDigest || Date().timeIntervalSince(lastSnapshotAt) > 20 * 60 else { return }115        store.write(snapshot)116        lastSnapshotDigest = digest; lastSnapshotAt = Date()117        writeState()118        WidgetCenter.shared.reloadAllTimelines()119    }120121    // MARK: share extension hand-off122123    /// Turns each draft queued by the share extension into a draft of the app (recipients, subject, note, attachments) and opens the last124    /// one in a composer. Only while the app is unlocked.125    @discardableResult126    func importSharedDrafts() async -> [String] {127        guard app.phase == .ready, !importing else { return [] }128        importing = true129        defer { importing = false }130        var opened: [String] = []131        let queue = store.shareQueue132        for draft in queue.pending() {133            let account = draft.mailboxId.flatMap { app.engines[$0] != nil ? $0 : nil } ?? app.main.currentAccount ?? app.accounts.first?.id134            guard let account, let id = await app.makeComposer(.new, account: account), let composer = app.composers[id] else { continue }135            composer.to = draft.to.flatMap { AddressParser.parseList($0) }136            composer.subject = draft.subject137            if !draft.note.isEmpty { composer.prependText(draft.note) } // through the composer's entry point: the signature block keeps its tag138            for file in draft.files {139                let dir = FileManager.default.temporaryDirectory.appendingPathComponent("spmail-files/share-\(UUID().uuidString)", isDirectory: true)140                try? FileManager.default.createDirectory(at: dir, withIntermediateDirectories: true)141                let url = dir.appendingPathComponent(file.name.replacingOccurrences(of: "/", with: "-"))142                if (try? queue.open(file, of: draft, to: url)) != nil { composer.addAttachment(url: url) }143                try? FileManager.default.removeItem(at: dir)144            }145            composer.edited()146            queue.remove(draft.id)147            opened.append(id)148        }149        if let last = opened.last { app.system.router.present(composer: last) }150        return opened151    }152}153
Files main
Menu

Theme