SPB Git

Repository Public

SpotlightIndex.swift 6.3 KB 111 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Sources/Shared/System/SpotlightIndex.swift3// Description: Core Spotlight indexing of senders and subjects — only when the person turned it on, and never beyond the notification4// privacy level (nothing at level `none` or with the device switch, senders only at level `sender`). One domain per mailbox, so a mailbox5// removal purges its items; items of messages that were destroyed or moved to the trash are deleted one by one; sign-out purges everything.6// A Spotlight result opens the conversation (`CSSearchableItemActionType`, see DeepLinkRouter).7import CoreSpotlight8import SPMailCore9import SwiftUI1011@MainActor12enum Spotlight {13    static let domain = "ai.spboucher.spmail.messages"14    private static let trackedLimit = 300015    private static var reconcileTasks: [String: Task<Void, Never>] = [:]1617    static func domain(account: String) -> String { "\(domain).\(account)" }18    static func identifier(account: String, emailId: String) -> String { "\(account)/\(emailId)" }19    nonisolated static func parse(identifier: String) -> (account: String, emailId: String)? {20        guard let slash = identifier.firstIndex(of: "/") else { return nil }21        let account = String(identifier[..<slash]), email = String(identifier[identifier.index(after: slash)...])22        return account.isEmpty || email.isEmpty ? nil : (account, email)23    }2425    /// The level items may be indexed at; nil = no indexing at all.26    static func level(_ app: AppModel) -> PushPreview? {27        guard app.settings.spotlightEnabled, !app.settings.hideNotificationContent else { return nil }28        switch app.system.push.prefs?.preview ?? .sender {29        case .full: return .full30        case .sender: return .sender31        default: return nil32        }33    }34    static func isAllowed(_ app: AppModel) -> Bool { level(app) != nil }3536    // ids indexed per mailbox, remembered so that they can be removed one by one later37    private static func trackedKey(_ account: String) -> String { "spotlight.ids.\(account)" }38    private static func tracked(_ account: String) -> [String] { UserDefaults.standard.stringArray(forKey: trackedKey(account)) ?? [] }39    private static func setTracked(_ ids: [String], _ account: String) {40        if ids.isEmpty { UserDefaults.standard.removeObject(forKey: trackedKey(account)) } else { UserDefaults.standard.set(Array(ids.suffix(trackedLimit)), forKey: trackedKey(account)) }41    }42    private static var trackedAccounts: [String] { UserDefaults.standard.dictionaryRepresentation().keys.filter { $0.hasPrefix("spotlight.ids.") }.map { String($0.dropFirst("spotlight.ids.".count)) } }4344    static func index(_ mails: [EmailSummary], account: String, level: PushPreview = .full) {45        guard !mails.isEmpty else { return }46        let items = mails.map { m -> CSSearchableItem in47            let a = CSSearchableItemAttributeSet(contentType: .emailMessage)48            if level == .full { a.subject = m.subject; a.title = m.subject.isEmpty ? m.sender?.displayName : m.subject } else { a.title = m.sender?.displayName }49            a.authorNames = m.from.map(\.displayName)50            a.authorEmailAddresses = m.from.map(\.email)51            a.contentCreationDate = m.date52            let item = CSSearchableItem(uniqueIdentifier: identifier(account: account, emailId: m.id), domainIdentifier: domain(account: account), attributeSet: a)53            item.expirationDate = Date().addingTimeInterval(90 * 86400)54            return item55        }56        CSSearchableIndex.default().indexSearchableItems(items) { _ in }57        var ids = tracked(account).filter { id in !mails.contains { $0.id == id } }58        ids.append(contentsOf: mails.map(\.id))59        setTracked(ids, account)60    }61    /// Convenience used by the sync events: indexes at the level allowed now, or not at all.62    static func index(_ mails: [EmailSummary], account: String, app: AppModel) {63        if let level = level(app) { index(mails, account: account, level: level) }64    }6566    static func remove(ids: [String], account: String) {67        guard !ids.isEmpty else { return }68        CSSearchableIndex.default().deleteSearchableItems(withIdentifiers: ids.map { identifier(account: account, emailId: $0) }) { _ in }69        let gone = Set(ids)70        setTracked(tracked(account).filter { !gone.contains($0) }, account)71    }72    /// A mailbox was removed from the account: everything indexed for it goes.73    static func remove(account: String) {74        CSSearchableIndex.default().deleteSearchableItems(withDomainIdentifiers: [domain(account: account)]) { _ in }75        setTracked([], account)76    }77    /// Sign-out, revoked session, indexing turned off, or a privacy level that forbids it.78    static func removeAll() {79        CSSearchableIndex.default().deleteAllSearchableItems { _ in }80        for account in trackedAccounts { setTracked([], account) }81    }8283    /// After a change in a mailbox: indexed messages that no longer exist, or now sit only in the trash or the junk folder, leave the84    /// index. Debounced per mailbox (one delta sync emits several events).85    static func reconcile(account: String, app: AppModel) {86        guard reconcileTasks[account] == nil, !tracked(account).isEmpty else { return }87        reconcileTasks[account] = Task {88            try? await Task.sleep(for: .seconds(2))89            reconcileTasks[account] = nil90            guard !Task.isCancelled else { return }91            if !isAllowed(app) { removeAll(); return }92            await reconcileNow(account: account, app: app)93        }94    }95    static func reconcileNow(account: String, app: AppModel) async {96        guard let store = app.store else { return }97        let ids = tracked(account)98        guard !ids.isEmpty else { return }99        let hidden = Set(app.mailboxes(for: account).filter { $0.role == "trash" || $0.role == "junk" }.map(\.id))100        let present = Dictionary(((try? await store.emails(account, ids: ids)) ?? []).map { ($0.id, $0) }, uniquingKeysWith: { a, _ in a })101        let gone = ids.filter { id in102            guard let e = present[id] else { return true }103            return !e.mailboxIds.isEmpty && e.mailboxIds.allSatisfy(hidden.contains)104        }105        remove(ids: gone, account: account)106    }107    #if DEBUG108    static func trackedIds(_ account: String) -> [String] { tracked(account) }109    #endif110}111
Files main
Menu

Theme