SPB Git

Repository Public

MailScene.swift 33.3 KB 623 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/Model/MailScene.swift3// Description: The navigation state of ONE window (main window, an extra iPad scene, a message window): mailbox, folder, list, search, unified list,4// conversation — and the actions on them. Session, engines, folders and composers are shared through AppModel.5import SPMailCore6import SwiftUI78/// What a message window shows; Codable so that SwiftUI restores the window after a relaunch.9struct MessageRef: Codable, Hashable, Sendable {10    var account: String11    var emailId: String12    /// True: the whole conversation of the message; false: this message alone.13    var conversation: Bool14}1516@MainActor @Observable17final class MailScene: Identifiable {18    nonisolated let id = UUID()19    @ObservationIgnored unowned let app: AppModel20    /// When the server was last asked for the pinned messages of a folder (`account/mailbox`).21    @ObservationIgnored private var pinnedChecked: [String: Date] = [:]22    let list = ListState()23    let search = SearchState()24    let unified = UnifiedState()25    let reader = ReaderState()26    /// SP Mail Next state of this window: search, cross-mailbox lists, pickers, contacts, attachments (see MailScene+Next.swift).27    let next = NextSceneState()28    /// A message window: a reader without sidebar or list.29    let isDetached: Bool3031    var currentAccount: String?32    var selection: SidebarItem?33    var scheduled: [OutboundStatus] = []34    var scheduledError: String?35    var composeRequest: String?36    var showSettings = false37    var showPalette = false38    var showStudio = false39    /// Bumped to open the template studio (its own window on macOS, a full-screen cover on iOS / iPadOS).40    var studioRequest = 041    /// Bumped by ⌘F: the list gives the keyboard focus to its search field.42    var focusSearchToken = 043    /// Bumped to bring the reader column in front on compact widths (keyboard navigation, screenshot fixtures).44    var detailRequest = 045    /// Bumped by « Nouveau dossier… » from a menu or the command palette.46    var newFolderRequest = 04748    init(app: AppModel, detached: Bool = false) {49        self.app = app50        isDetached = detached51        app.register(self)52    }5354    // MARK: derived5556    var activeAccount: String? { reader.account ?? currentAccount }57    var engine: SyncEngine? { activeAccount.flatMap { app.engines[$0] } }58    var isUnified: Bool { if case .unified = selection { return true } else { return false } }59    var currentBox: MeResponse.Box? { app.box(currentAccount) }60    var mailboxes: [Mailbox] { app.mailboxes(for: currentAccount) }61    /// Folders of the mailbox that holds the message being read (differs from `mailboxes` for a message opened from the unified list).62    var activeMailboxes: [Mailbox] { app.mailboxes(for: activeAccount) }63    var customMailboxes: [Mailbox] { mailboxes.filter { $0.knownRole == nil && !$0.isSnoozedFolder } }64    var unreadCount: Int { currentAccount.flatMap { app.unreadByAccount[$0] } ?? 0 }65    var flaggedCount: Int { currentAccount.flatMap { app.flaggedByAccount[$0] } ?? 0 }66    func mailbox(_ role: MailboxRole) -> Mailbox? { mailboxes.first { $0.role == role.rawValue } }67    /// Rows shown by the list: search results when a search is active, else the folder.68    var rows: [ThreadSummary] { next.insightRows ?? search.rows ?? list.threads }69    var hasSelection: Bool { !list.selectedIds.isEmpty }7071    static func title(of m: Mailbox) -> String {72        switch m.knownRole {73        case .inbox: L("Boîte de réception"); case .drafts: L("Brouillons"); case .sent: L("Envoyés"); case .archive: L("Archives"); case .junk: L("Indésirables"); case .trash: L("Corbeille"); case .none: m.name74        }75    }76    static func icon(of m: Mailbox) -> String {77        switch m.knownRole {78        case .inbox: "tray"; case .drafts: "doc"; case .sent: "paperplane"; case .archive: "archivebox"; case .junk: "xmark.bin"; case .trash: "trash"; case .none: "folder"79        }80    }81    var listTitle: String {82        switch selection {83        case .mailbox(let id): mailboxes.first { $0.id == id }.map(Self.title(of:)) ?? ""84        case .unread: L("Non lus"); case .flagged: L("Avec drapeau"); case .outbox: L("Boîte d’envoi"); case .scheduled: L("Programmés")85        case .unified(let v): UnifiedListView.title(v)86        case .dashboard, .label, .savedSearch, .search, .snoozed, .followUps, .contacts, .attachments: nextTitle87        case .none: ""88        }89    }9091    // MARK: session9293    func sessionStarted(account: String?) async {94        guard !isDetached else { return }95        currentAccount = account96        if selection == nil { selection = mailbox(.inbox).map { .mailbox($0.id) } }97        await reloadThreads()98        Task { await refreshPinned() }99    }100101    /// A new window on a session that is already running.102    func adopt(account: String?) {103        guard app.phase == .ready || app.phase == .locked else { return }104        currentAccount = account105        selection = mailbox(.inbox).map { .mailbox($0.id) }106        Task { await reloadThreads() }107    }108109    func reset() {110        list.reset(); search.clear(); unified.reset(); reader.reset(); next.reset()111        selection = nil; scheduled = []; scheduledError = nil; composeRequest = nil; currentAccount = nil112        pinnedChecked = [:]113    }114115    /// The mailbox was removed on the server: this window stops showing it.116    func accountRemoved(_ id: String, fallback: String?) async {117        unified.rows.removeAll { $0.account == id }118        if reader.account == id { reader.reset(); list.selectedIds = []; unified.selection = nil }119        guard currentAccount == id else { return }120        currentAccount = nil121        list.reset(); search.clear(); reader.reset(); selection = nil122        if let fallback { await switchAccount(fallback) }123    }124125    /// The folders arrived (first synchronisation after sign-in): a window that shows nothing yet opens the inbox.126    func mailboxesChanged() {127        guard !isDetached, selection == nil, let inbox = mailbox(.inbox) else { return }128        selection = .mailbox(inbox.id)129        didSelectSidebar()130    }131132    func emailsChanged(account: String) async {133        if isUnified { scheduleUnifiedReload() }134        if account == currentAccount { await reloadThreads() }135        if account == activeAccount { await refreshConversation() }136    }137138    // MARK: sidebar and list139140    func switchAccount(_ id: String) async {141        guard id != currentAccount, app.engines[id] != nil else { return }142        currentAccount = id143        if self === app.main { UserDefaults.standard.set(id, forKey: "currentAccount") }144        selection = nil; list.reset(); search.clear(); reader.reset()145        selection = mailbox(.inbox).map { .mailbox($0.id) }146        await reloadThreads()147    }148149    func didSelectSidebar() {150        list.selectedIds = []; reader.clearConversation(); list.limit = 200; search.clear()151        if reader.account != nil { reader.account = nil; reader.clearBodies() }152        unified.selection = nil153        next.selection = []; next.openRowId = nil; next.insightFilter = nil; next.insightRows = nil154        switch selection {155        case .dashboard, .label, .savedSearch, .search, .snoozed, .followUps, .contacts, .attachments: unified.rows = []; list.threads = []; nextDidSelectSidebar()156        case .unified: unified.rows = []; unified.cursor = nil; Task { await reloadUnified() }157        case .scheduled: Task { await reloadScheduled() }158        default: unified.rows = []; list.threads = []; list.isLoading = true; Task { await reloadThreads(); await refreshPinned() }159        }160    }161162    func reloadThreads() async {163        guard let store = app.store, let account = currentAccount else { list.threads = []; list.isLoading = false; return }164        list.generation += 1165        let generation = list.generation166        let scope: ListScope167        switch selection {168        case .mailbox(let id): scope = .mailbox(id)169        case .unread: scope = .unread170        case .flagged: scope = .flagged171        case .outbox, .unified, .scheduled, .none, .dashboard, .label, .savedSearch, .search, .snoozed, .followUps, .contacts, .attachments: list.threads = []; list.isLoading = false; return172        }173        var rows = (try? await store.threads(account, scope: scope, threaded: app.settings.threaded, limit: list.limit)) ?? []174        // pinned conversations first (folder lists only) — across the WHOLE folder, not only the loaded window: the pinned messages the175        // server listed for this folder (see `refreshPinned`) are merged in, so a pinned old conversation is never buried176        if case .mailbox(let box) = selection {177            let pinned = (try? await app.engines[account]?.cachedEmails(inMailbox: box, withKeyword: NextKeyword.pinned)) ?? []178            rows = PinOrder.merged(rows, pinned: pinned, threaded: app.settings.threaded)179        }180        guard generation == list.generation else { return }181        if rows != list.threads { list.threads = rows }182        list.isLoading = false183    }184185    /// Asks the server which messages of the folder on screen are pinned (`Email/query` with `hasKeyword: "$pinned"`), wherever they sit186    /// in the folder, then reloads the list when the answer changed. Quiet: once per folder and minute unless `force`; offline, the last187    /// answer stays in use.188    func refreshPinned(force: Bool = false) async {189        guard case .mailbox(let box) = selection, let account = currentAccount, let engine = app.engines[account], app.isOnline else { return }190        let key = "\(account)/\(box)"191        if !force, let last = pinnedChecked[key], Date().timeIntervalSince(last) < 60 { return }192        pinnedChecked[key] = Date()193        let before = ((try? await engine.cachedEmails(inMailbox: box, withKeyword: NextKeyword.pinned)) ?? []).map(\.id)194        guard let fresh = try? await engine.emails(inMailbox: box, withKeyword: NextKeyword.pinned), !fresh.offline else { return }195        if fresh.results.map(\.id) != before, selection == .mailbox(box), currentAccount == account { await reloadThreads() }196    }197198    /// Called when the last row appears: show more cached rows, then ask the server for older messages of the folder.199    func loadMore(after row: ThreadSummary) async {200        guard !search.isActive, row.id == list.threads.last?.id, !list.isLoadingMore else { return }201        list.isLoadingMore = true202        defer { list.isLoadingMore = false }203        if list.threads.count >= list.limit {204            list.limit += 200205            await reloadThreads()206            return207        }208        guard case .mailbox(let id) = selection, let box = mailboxes.first(where: { $0.id == id }), let store = app.store, let account = currentAccount, let engine = app.engines[account] else { return }209        let have = (try? await store.count(account, scope: .mailbox(id))) ?? 0210        guard have < box.totalEmails, let n = try? await engine.loadOlder(mailboxId: id), n > 0 else { return }211        list.limit += n212        await reloadThreads()213    }214215    func refresh(accountsAlreadyRefreshed: Bool = false) async {216        if !accountsAlreadyRefreshed { await app.refreshAccounts() }217        guard let engine else { return }218        do { try await engine.syncNow() } catch {219            if !(error is CancellationError), let m = app.describe(error) {220                app.notice = m221                if (error as? APIError)?.isOffline != true { app.sync.lastError = m }222            }223        }224        await app.reloadMailboxes()225        await reloadThreads()226        await refreshPinned(force: true)227        if isUnified { await reloadUnified() } else if selection == .scheduled { await reloadScheduled() }228        await app.next.refresh()229        await app.outbound.reload() // after the sync: what the server says of the recent sends230    }231232    /// The per-mailbox part of the sidebar, in order (⌘1…9 and the command palette).233    var sidebarOrder: [SidebarItem] {234        let system = mailboxes.filter { $0.knownRole != nil }235        var items: [SidebarItem] = system.filter { $0.knownRole == .inbox }.map { .mailbox($0.id) } + [.unread, .flagged]236        items += system.filter { $0.knownRole != .inbox }.map { .mailbox($0.id) } + [.outbox] + customMailboxes.map { .mailbox($0.id) }237        return items238    }239    /// ⌘1…9: the n-th entry of the per-mailbox part of the sidebar (⌘0 is « Toutes les boîtes »).240    func selectSidebar(index: Int) {241        let items = sidebarOrder242        if items.indices.contains(index) { selection = items[index] }243    }244245    /// Arrow-key equivalents from the menus: the next / previous conversation of the list.246    func selectAdjacent(_ delta: Int) {247        if nextSelectAdjacent(delta) { return }248        if isUnified {249            guard !unified.rows.isEmpty else { return }250            let n = unified.rows.firstIndex { $0.id == unified.selection }.map { $0 + delta } ?? (delta > 0 ? 0 : unified.rows.count - 1)251            guard unified.rows.indices.contains(n) else { return }252            let row = unified.rows[n]253            Task { await openUnified(row) }254            return255        }256        let rows = rows257        guard !rows.isEmpty else { return }258        let current = rows.firstIndex { list.selectedIds.contains($0.id) }259        let n = current.map { $0 + delta } ?? (delta > 0 ? 0 : rows.count - 1)260        guard rows.indices.contains(n) else { return }261        list.selectedIds = [rows[n].id]262        didChangeSelection()263        detailRequest += 1264    }265266    // MARK: conversation267268    func didChangeSelection() {269        guard list.selectedIds.count == 1, let id = list.selectedIds.first else {270            if list.selectedIds.isEmpty { reader.clearConversation() }271            return272        }273        Task { await open(emailId: id) }274    }275276    func open(emailId: String) async {277        guard let store = app.store, let account = currentAccount, let head = rows.first(where: { $0.id == emailId })?.email else { return }278        if head.isDraft { await compose(.serverDraft(head)); return }279        let threaded = app.settings.threaded && !search.isActive280        let thread = threaded ? ((try? await store.threadEmails(account, threadId: head.threadId)) ?? [head]).filter { !$0.isDraft } : [head]281        reader.conversation = thread.isEmpty ? [head] : thread282        reader.focusedEmailId = head.id283        await loadBody(head.id)284        if threaded { await completeThread(head, account: account) }285        if app.settings.markReadOnOpen {286            let unread = reader.conversation.filter { !$0.isSeen }.map(\.id)287            if !unread.isEmpty { await engine?.markSeen(true, ids: unread) }288        }289    }290291    /// The conversation as the SERVER defines it (`SyncEngine.thread`): messages older than the synced window or filed in another folder292    /// join the cached ones shown at once. Nothing changes if the person moved on meanwhile.293    func completeThread(_ head: EmailSummary, account: String) async {294        guard let engine = app.engines[account], let full = try? await engine.thread(head.threadId) else { return }295        let emails = full.emails.filter { !$0.isDraft }296        guard reader.focusedEmailId == head.id, activeAccount == account, emails.contains(where: { $0.id == head.id }), emails != reader.conversation else { return }297        reader.conversation = emails298    }299300    /// A message window: the message (or its conversation) read through the engine of ITS mailbox, without any list.301    func openDetached(_ ref: MessageRef) async -> Bool {302        guard let store = app.store, let engine = app.engines[ref.account] else { return false }303        reader.account = ref.account304        try? await engine.ensureCached(ids: [ref.emailId])305        guard let head = (try? await store.email(ref.account, id: ref.emailId)) ?? nil else { return false }306        let thread = ref.conversation ? ((try? await store.threadEmails(ref.account, threadId: head.threadId)) ?? []).filter { !$0.isDraft } : []307        reader.conversation = thread.contains { $0.id == head.id } ? thread : [head]308        reader.focusedEmailId = head.id309        list.selectedIds = [head.id]310        await loadBody(head.id)311        if ref.conversation { await completeThread(head, account: ref.account) }312        return true313    }314315    func focus(_ id: String) async {316        reader.focusedEmailId = id317        await loadBody(id)318    }319320    func refreshConversation() async {321        guard let store = app.store, let account = activeAccount, !reader.conversation.isEmpty else { return }322        var updated: [EmailSummary] = []323        for e in reader.conversation { if let fresh = try? await store.email(account, id: e.id) { updated.append(fresh) } }324        if updated.isEmpty { reader.clearConversation(); list.selectedIds = [] } else if updated != reader.conversation { reader.conversation = updated }325    }326327    func loadBody(_ id: String) async { await reader.loadBody(id, engine: engine, describe: app.describe) }328329    func replyTarget() -> EmailSummary? { reader.focusedEmail ?? rows.first { list.selectedIds.contains($0.id) }?.email }330331    // MARK: actions332333    /// The messages an action applies to: every message of the selected conversations that lives in the current folder.334    func targets(_ heads: Set<String>) async -> [String] {335        if isDetached { return reader.conversation.isEmpty ? Array(heads) : reader.conversation.map(\.id) }336        guard app.settings.threaded, !search.isActive, !isUnified, let store = app.store, let account = currentAccount else { return Array(heads) }337        var out: [String] = []338        for id in heads {339            guard let head = list.threads.first(where: { $0.id == id }), head.count > 1 else { out.append(id); continue }340            let all = (try? await store.threadEmails(account, threadId: head.threadId)) ?? []341            switch selection {342            case .mailbox(let box): out += all.filter { $0.mailboxIds.contains(box) }.map(\.id)343            default: out += all.map(\.id)344            }345        }346        return out.isEmpty ? Array(heads) : out347    }348349    /// Where each message sits before a move, so that « Annuler » can put it back.350    func origins(account: String, ids: [String]) async -> [String: String] {351        guard let store = app.store else { return [:] }352        var out: [String: String] = [:]353        for id in ids { if let box = ((try? await store.email(account, id: id)) ?? nil)?.mailboxIds.first { out[id] = box } }354        return out355    }356357    /// The toast after a move, with « Annuler » when every message can be put back (nothing was destroyed).358    func announceMove(_ action: MailAction, account: String, origins: [String: String], count: Int) {359        let trash = app.mailboxes(for: account).first { $0.role == MailboxRole.trash.rawValue }?.id360        let message: String361        switch action {362        case .archive: message = L("Archivé")363        case .delete: message = origins.values.contains { $0 == trash } ? L("Supprimé définitivement") : L("Placé dans la corbeille")364        case .junk: message = L("Marqué comme indésirable")365        case .move: message = L("Déplacé")366        default: return367        }368        var toast = Toast(message: message)369        var destroyed = false370        if case .delete = action { destroyed = origins.values.contains { $0 == trash } }371        if !destroyed, origins.count == count, let engine = app.engines[account] {372            toast.actionTitle = L("Annuler")373            toast.action = { [weak self] in374                for (box, group) in Dictionary(grouping: origins.keys, by: { origins[$0] ?? "" }) where !box.isEmpty { await engine.move(ids: group, to: box) }375                await self?.reloadThreads()376                if self?.isUnified == true { await self?.reloadUnified() }377            }378        }379        app.toast = toast380    }381382    func perform(_ action: MailAction, on ids: Set<String>? = nil) async {383        let heads = ids ?? list.selectedIds384        guard !heads.isEmpty, let engine, let account = activeAccount else { return }385        let all = await targets(heads)386        var before: [String: String] = [:]387        var failed = false388        switch action { case .archive, .delete, .junk, .move: before = await origins(account: account, ids: all); default: break }389        do {390            switch action {391            case .markRead(let v): await engine.markSeen(v, ids: all)392            case .flag(let v): await engine.setFlagged(v, ids: all)393            case .archive: try await engine.archive(ids: all, folderName: L("Archives"))394            case .delete: try await engine.delete(ids: all)395            case .junk: try await engine.markJunk(ids: all)396            case .move(let box): await engine.move(ids: all, to: box)397            case .keyword(let k, let v): await engine.setKeyword(k, v, ids: all)398            }399        } catch { failed = true; app.toast = Toast(message: app.describe(error) ?? "", kind: .error) }400        switch action {401        case .archive, .delete, .junk, .move:402            if !failed { announceMove(action, account: account, origins: before, count: all.count) }403            list.selectedIds.subtract(heads)404            if list.selectedIds.isEmpty { reader.clearConversation() }405            if search.isActive { search.results?.removeAll { heads.contains($0.id) } }406            if isUnified { unified.rows.removeAll { $0.account == account && heads.contains($0.email.id) }; unified.selection = nil }407        case .markRead(let v): if isUnified { unified.patch(account: account, ids: heads) { $0.setKeyword(Keyword.seen, v) } }408        case .flag(let v): if isUnified { unified.patch(account: account, ids: heads) { $0.setKeyword(Keyword.flagged, v) } }409        case .keyword(let k, let v): if isUnified { unified.patch(account: account, ids: heads) { $0.setKeyword(k, v) } }410        }411        nextDidPerform(action, account: account, ids: heads)412    }413414    /// Toggle helpers for menus and shortcuts: act on the selection as a whole.415    func toggleFlag() async {416        if isUnified || isDetached || readsRemote { await perform(.flag(reader.conversation.contains { !$0.isFlagged })); return }417        let anyUnflagged = rows.contains { list.selectedIds.contains($0.id) && !$0.anyFlagged }418        await perform(.flag(anyUnflagged))419    }420    func toggleRead() async {421        if isUnified || isDetached || readsRemote { await perform(.markRead(reader.conversation.contains { !$0.isSeen })); return }422        let anyUnread = rows.contains { list.selectedIds.contains($0.id) && $0.unreadCount > 0 }423        await perform(.markRead(anyUnread))424    }425426    /// Snooze goes through `AppModel.hooks.snooze` (installed by NextServices when the server supports it): the picker opens in this window.427    /// Against an older server the action says so instead of doing nothing silently.428    func snooze(ids: Set<String>, account: String? = nil) async {429        guard let account = account ?? activeAccount, !ids.isEmpty else { return }430        app.next.requestingScene = self431        // a conversation is snoozed whole: every message of it that sits in the current folder432        let all = account == currentAccount && !readsRemote ? await targets(ids) : Array(ids)433        if let hook = app.hooks.snooze { await hook(all, account) } else { app.toast = Toast(message: L("La mise en veille n’est pas disponible sur ce serveur."), kind: .info) }434    }435436    // MARK: folders437438    func createFolder(_ name: String) async {439        do { _ = try await currentAccount.flatMap { app.engines[$0] }?.createMailbox(name: name) } catch { app.notice = app.describe(error) }440    }441    func renameFolder(_ id: String, to name: String) async {442        do { try await currentAccount.flatMap { app.engines[$0] }?.renameMailbox(id: id, name: name) } catch { app.notice = app.describe(error) }443    }444    func deleteFolder(_ id: String) async {445        do {446            try await currentAccount.flatMap { app.engines[$0] }?.deleteMailbox(id: id)447            if selection == .mailbox(id) { selection = mailbox(.inbox).map { .mailbox($0.id) }; didSelectSidebar() }448        } catch { app.notice = app.describe(error) }449    }450451    // MARK: search452453    func runSearch() async {454        let text = search.trimmed455        guard !text.isEmpty, let engine = currentAccount.flatMap({ app.engines[$0] }) else { search.results = nil; return }456        search.isSearching = true457        defer { search.isSearching = false }458        var f = SearchFilter(text: text)459        f.unreadOnly = search.unreadOnly460        f.hasAttachment = search.attachmentsOnly461        do {462            let r = try await engine.search(f)463            guard text == search.trimmed else { return }464            search.results = r.results465            search.isOffline = r.offline466        } catch { if !(error is CancellationError) { app.notice = app.describe(error) } }467    }468469    // MARK: composing470471    func compose(_ kind: ComposeKind) async {472        var account = activeAccount473        var delivered: [String] = []474        switch kind {475        case .outboxItem(let item): account = item.account476        case .reply(let e), .replyAll(let e), .forward(let e): if let a = account { delivered = unified.deliveredTo(account: a, emailId: e.id) }477        default: break478        }479        guard let account, let id = await app.makeComposer(kind, account: account, deliveredTo: delivered) else { return }480        composeRequest = id481    }482483    // MARK: unified list (all mailboxes)484485    /// Live sync events of any mailbox refresh the unified list (debounced: one delta sync emits several events).486    private func scheduleUnifiedReload() {487        unified.refresh?.cancel()488        unified.refresh = Task { [weak self] in489            try? await Task.sleep(for: .milliseconds(500))490            if !Task.isCancelled { await self?.reloadUnified() }491        }492    }493494    func reloadUnified() async {495        guard case .unified(let view) = selection else { return }496        unified.generation += 1497        let generation = unified.generation498        if unified.rows.isEmpty { unified.isLoading = true }499        defer { if generation == unified.generation { unified.isLoading = false } }500        do {501            // keep as many rows as were on screen (pages already walked), in one request when possible502            let page = try await app.api.unifiedMessages(view, accounts: app.accountMap, limit: min(100, max(50, unified.rows.count)))503            guard generation == unified.generation, selection == .unified(view) else { return }504            unified.rows = page.messages; unified.cursor = page.nextCursor; unified.isOffline = false505        } catch let e as APIError where e.isOffline {506            // offline: what the local caches hold for this view, merged by date507            let local = (try? await app.store?.unified(view, accounts: app.accounts.map { (id: $0.id, address: $0.address) })) ?? []508            guard generation == unified.generation, selection == .unified(view) else { return }509            unified.rows = local; unified.cursor = nil; unified.isOffline = true510        } catch let e as APIError where e.isUnauthorized {511            await app.sessionRevoked()512        } catch { if !(error is CancellationError) { app.notice = app.describe(error) } }513    }514515    func loadMoreUnified(after row: UnifiedMessage) async {516        guard case .unified(let view) = selection, row.id == unified.rows.last?.id, let cursor = unified.cursor, !list.isLoadingMore else { return }517        list.isLoadingMore = true518        defer { list.isLoadingMore = false }519        guard let page = try? await app.api.unifiedMessages(view, accounts: app.accountMap, cursor: cursor, limit: 50), selection == .unified(view), cursor == unified.cursor else { return }520        let known = Set(unified.rows.map(\.id))521        unified.rows += page.messages.filter { !known.contains($0.id) }522        unified.cursor = page.nextCursor523    }524525    /// Opens a row of the unified list in the reader, through the engine of ITS mailbox: every later action (flag, archive, delete, reply)526    /// then acts on that mailbox.527    func openUnified(_ row: UnifiedMessage) async {528        unified.selection = row.id529        guard let account = row.account, let engine = app.engines[account], let store = app.store else {530            // the row could not be tied to a mailbox engine: read-only fallback through /api/v1531            reader.account = nil; list.selectedIds = []; reader.conversation = [row.email]; reader.focusedEmailId = row.email.id532            do { reader.bodies[row.email.id] = try await app.api.v1Body(id: row.id); await reader.prepare(row.email.id); try? await app.api.v1SetFlags(id: row.id, unread: false) } catch { reader.bodyErrors[row.email.id] = app.describe(error) }533            return534        }535        if reader.account != account { reader.clearBodies() }536        reader.account = account537        try? await engine.ensureCached(ids: [row.email.id])538        let head = ((try? await store.email(account, id: row.email.id)) ?? nil) ?? row.email539        if head.isDraft { await compose(.serverDraft(head)); return }540        let thread = app.settings.threaded ? ((try? await store.threadEmails(account, threadId: head.threadId)) ?? []).filter { !$0.isDraft } : []541        reader.conversation = thread.contains { $0.id == head.id } ? thread : [head]542        reader.focusedEmailId = head.id543        list.selectedIds = [head.id]544        await loadBody(head.id)545        if app.settings.threaded { await completeThread(head, account: account) }546        if app.settings.markReadOnOpen {547            let unread = reader.conversation.filter { !$0.isSeen }.map(\.id)548            if !unread.isEmpty { await engine.markSeen(true, ids: unread); unified.patch(account: account, ids: Set(unread)) { $0.setKeyword(Keyword.seen, true) } }549        }550    }551552    /// An action on rows of the unified list, each sent to the mailbox that holds the message.553    func performUnified(_ action: MailAction, on rows: [UnifiedMessage]) async {554        for (account, group) in Dictionary(grouping: rows, by: { $0.account ?? "" }) {555            let ids = group.map(\.email.id)556            do {557                if let engine = app.engines[account] {558                    try? await engine.ensureCached(ids: ids)559                    var before: [String: String] = [:]560                    switch action { case .archive, .delete, .junk, .move: before = await origins(account: account, ids: ids); default: break }561                    switch action {562                    case .markRead(let v): await engine.markSeen(v, ids: ids)563                    case .flag(let v): await engine.setFlagged(v, ids: ids)564                    case .archive: try await engine.archive(ids: ids, folderName: L("Archives"))565                    case .delete: try await engine.delete(ids: ids)566                    case .junk: try await engine.markJunk(ids: ids)567                    case .move(let box): await engine.move(ids: ids, to: box)568                    case .keyword(let k, let v): await engine.setKeyword(k, v, ids: ids)569                    }570                    announceMove(action, account: account, origins: before, count: ids.count)571                } else {572                    for row in group {573                        switch action {574                        case .markRead(let v): try await app.api.v1SetFlags(id: row.id, unread: !v)575                        case .flag(let v): try await app.api.v1SetFlags(id: row.id, starred: v)576                        case .archive: try await app.api.v1Move(id: row.id, folder: "archive")577                        case .delete: try await app.api.v1Trash(id: row.id)578                        case .junk: try await app.api.v1Move(id: row.id, folder: "junk")579                        case .move, .keyword: break580                        }581                    }582                }583            } catch { app.toast = Toast(message: app.describe(error) ?? "", kind: .error) }584        }585        let touched = Set(rows.map(\.id))586        switch action {587        case .archive, .delete, .junk, .move:588            unified.rows.removeAll { touched.contains($0.id) }589            if let open = unified.selection, touched.contains(open) { unified.selection = nil; reader.clearConversation(); list.selectedIds = [] }590        case .markRead(let v): unified.patch(rowIds: touched) { $0.setKeyword(Keyword.seen, v) }591        case .flag(let v): unified.patch(rowIds: touched) { $0.setKeyword(Keyword.flagged, v) }592        case .keyword(let k, let v): unified.patch(rowIds: touched) { $0.setKeyword(k, v) }593        }594        next.selection.subtract(touched)595    }596597    func reloadScheduled() async {598        do { scheduled = try await app.api.scheduledSends(); scheduledError = nil }599        catch let e as APIError where e.isOffline { scheduledError = L("Les envois programmés ne sont visibles qu’en ligne.") }600        catch { scheduledError = app.describe(error) }601    }602603    func cancelScheduled(_ item: OutboundStatus) async {604        do { try await app.api.cancelScheduled(id: item.id); app.notice = L("Envoi programmé annulé — rien n’est parti") }605        catch let e as APIError where e.code == "not_cancellable" { app.notice = L("Trop tard : ce message n’est plus en attente.") }606        catch { app.notice = app.describe(error) }607        await reloadScheduled()608    }609610    // MARK: attachments and export611612    /// Downloads an attachment into the app's private temporary folder (Quick Look, share, save).613    func file(for part: BodyPart) async throws -> URL {614        guard let engine else { throw StoreError(message: "no account") }615        // from the sealed attachment cache when present (works offline); the decrypted copy lives in the store's temporary folder616        return try await engine.attachmentFile(for: part)617    }618    func emlFile(for email: EmailSummary) async throws -> URL {619        guard let account = activeAccount else { throw StoreError(message: "no account") }620        return try await app.emlFile(for: email, account: account)621    }622}623
Files main
Menu

Theme