SPB Git

Repository Public

PlatformServices.swift 9.2 KB 154 lines swift

1// Author: Simon-Pierre Boucher — contact@spboucher.ai2// File: Features/Platform/PlatformServices.swift3// Description: macOS integration that lives outside the windows: Core Spotlight index of the notes (title, excerpt, tags; removed on trash, purge and sign-out; behind a setting) and native notifications for task due dates (permission asked at first use; behind a setting).4import AppKit5import CoreSpotlight6import UserNotifications7import UniformTypeIdentifiers8import SPNotesCore9import SPNotesStore10import SPNotesAPI1112/// What Spotlight knows about a note. Built from the local summary only: nothing leaves the Mac.13nonisolated struct SpotlightEntry: Equatable, Sendable {14    static let domain = "ai.spboucher.spnotes.notes"15    let id: String, title: String, excerpt: String, tags: [String], updatedAt: Date16    init(_ p: PageSummary) { id = p.id; title = p.title.isEmpty || p.title == "Untitled" ? "Sans titre" : p.title; excerpt = String(p.preview.prefix(300)); tags = p.tags; updatedAt = p.updatedAt }17    /// A note is searchable when it is neither in the trash nor a row of a database.18    static func isIndexable(_ p: PageSummary) -> Bool { p.deletedAt == nil }19    var item: CSSearchableItem {20        let a = CSSearchableItemAttributeSet(contentType: .text)21        a.title = title; a.displayName = title; a.contentDescription = excerpt; a.keywords = tags; a.contentModificationDate = updatedAt22        a.contentURL = Route(pageId: id).url23        return CSSearchableItem(uniqueIdentifier: id, domainIdentifier: Self.domain, attributeSet: a)24    }25}2627/// The index operations, behind a protocol so that tests can observe them without touching the system index.28nonisolated protocol SpotlightIndexing: Sendable {29    func index(_ entries: [SpotlightEntry]) async30    func remove(ids: [String]) async31    func removeAll() async32}33nonisolated struct SystemSpotlightIndex: SpotlightIndexing {34    func index(_ entries: [SpotlightEntry]) async { guard CSSearchableIndex.isIndexingAvailable(), !entries.isEmpty else { return }; try? await CSSearchableIndex.default().indexSearchableItems(entries.map(\.item)) }35    func remove(ids: [String]) async { guard !ids.isEmpty else { return }; try? await CSSearchableIndex.default().deleteSearchableItems(withIdentifiers: ids) }36    func removeAll() async { try? await CSSearchableIndex.default().deleteSearchableItems(withDomainIdentifiers: [SpotlightEntry.domain]) }37}3839/// A due-date reminder to schedule: the morning of the day (9:00), or the exact time when the task has one.40nonisolated struct TaskReminder: Equatable, Sendable {41    let taskId: String, title: String, fireDate: Date, pageId: String?, blockId: String?42    static let prefix = "task-due-"43    var identifier: String { Self.prefix + taskId }44    /// Reminders for the open tasks whose due moment is still ahead.45    static func plan(_ tasks: [TaskItem], now: Date = Date()) -> [TaskReminder] {46        tasks.compactMap { t in47            guard t.status != "done", t.deletedAt == nil, let due = t.dueAt else { return nil }48            var utc = Calendar(identifier: .gregorian); utc.timeZone = TimeZone(identifier: "UTC")!49            let c = utc.dateComponents([.year, .month, .day, .hour, .minute, .second], from: due)50            let bareDay = c.hour == 12 && c.minute == 0 && c.second == 051            let fire = bareDay ? (Calendar.current.date(from: DateComponents(year: c.year, month: c.month, day: c.day, hour: 9)) ?? due) : due52            return fire > now ? TaskReminder(taskId: t.id, title: t.title, fireDate: fire, pageId: t.pageId, blockId: t.blockId) : nil53        }.sorted { $0.fireDate < $1.fireDate }.prefix(60).map { $0 }54    }55}56nonisolated protocol ReminderScheduling: Sendable {57    func authorized(requesting: Bool) async -> Bool58    func replaceAll(_ reminders: [TaskReminder]) async59}60nonisolated struct SystemReminderScheduler: ReminderScheduling {61    func authorized(requesting: Bool) async -> Bool {62        let center = UNUserNotificationCenter.current()63        let status = await center.notificationSettings().authorizationStatus64        if status == .authorized || status == .provisional { return true }65        guard requesting, status == .notDetermined else { return false }66        return (try? await center.requestAuthorization(options: [.alert, .sound])) ?? false67    }68    func replaceAll(_ reminders: [TaskReminder]) async {69        let center = UNUserNotificationCenter.current()70        let existing = await center.pendingNotificationRequests().map(\.identifier).filter { $0.hasPrefix(TaskReminder.prefix) }71        center.removePendingNotificationRequests(withIdentifiers: existing)72        for r in reminders {73            let content = UNMutableNotificationContent(); content.title = "Tâche à faire"; content.body = r.title; content.sound = .default74            if let page = r.pageId { content.userInfo = ["url": Route(pageId: page, blockId: r.blockId).url.absoluteString] } else { content.userInfo = ["url": "spnotes://go/tasks"] }75            let trigger = UNCalendarNotificationTrigger(dateMatching: Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: r.fireDate), repeats: false)76            try? await center.add(UNNotificationRequest(identifier: r.identifier, content: content, trigger: trigger))77        }78    }79}8081@Observable final class PlatformServices: NSObject, UNUserNotificationCenterDelegate {82    @ObservationIgnored weak var env: AppEnvironment?83    @ObservationIgnored var spotlight: any SpotlightIndexing = SystemSpotlightIndex()84    @ObservationIgnored var reminders: any ReminderScheduling = SystemReminderScheduler()85    private(set) var notificationsDenied = false86    @ObservationIgnored private var indexTask: Task<Void, Never>?87    @ObservationIgnored private var reminderTask: Task<Void, Never>?88    @ObservationIgnored private var lastReminders: [TaskReminder]?8990    func start() {91        guard let env, !env.options.isHostedTest, !env.options.inMemory else { return }92        UNUserNotificationCenter.current().delegate = self93        Task { await reindexAll() }94    }9596    // MARK: Spotlight9798    /// Rebuilds the whole index from the local store (launch, setting switched on, library replaced).99    func reindexAll() async {100        guard let env else { return }101        await spotlight.removeAll()102        guard env.preferences.spotlightIndexing, !env.isBlocked else { return }103        let all = ((try? await env.store.summaries(list: .all, limit: 20_000)) ?? []) + ((try? await env.store.summaries(list: .archived, limit: 20_000)) ?? [])104        await spotlight.index(all.filter(SpotlightEntry.isIndexable).map(SpotlightEntry.init))105    }106    /// Pages changed in the store: index the live ones, remove the ones that left (trash, purge).107    func pagesChanged(_ ids: [String]) {108        guard let env, env.preferences.spotlightIndexing, !ids.isEmpty else { return }109        let previous = indexTask110        indexTask = Task { [weak self] in111            await previous?.value112            guard let self, let env = self.env else { return }113            var live: [SpotlightEntry] = [], gone: [String] = []114            for id in ids { if let p = try? await env.store.summary(id: id), SpotlightEntry.isIndexable(p) { live.append(SpotlightEntry(p)) } else { gone.append(id) } }115            await self.spotlight.index(live); await self.spotlight.remove(ids: gone)116        }117    }118    func libraryReset() { Task { await reindexAll() } }119    /// Sign-out and « ne plus indexer »: nothing of the notes stays in the system index.120    func clearIndex() async { await indexTask?.value; await spotlight.removeAll() }121    /// Waits for the queued index updates (tests).122    func flushIndex() async { await indexTask?.value }123124    // MARK: Task notifications125126    func tasksChanged(_ tasks: [TaskItem]) {127        guard let env, env.preferences.taskNotifications else { return }128        let plan = TaskReminder.plan(tasks.filter { $0.status != "done" })129        guard plan != lastReminders else { return }130        lastReminders = plan131        let previous = reminderTask132        reminderTask = Task { [weak self] in133            await previous?.value134            guard let self else { return }135            // the permission is asked the first time there is something to announce, not at launch136            guard await self.reminders.authorized(requesting: !plan.isEmpty) else { if !plan.isEmpty { self.notificationsDenied = true }; return }137            self.notificationsDenied = false138            await self.reminders.replaceAll(plan)139        }140    }141    func notificationsSettingChanged() async {142        lastReminders = nil143        guard let env else { return }144        if env.preferences.taskNotifications { tasksChanged(env.tasks.tasks) } else { await reminders.replaceAll([]) }145    }146    func flushReminders() async { await reminderTask?.value }147148    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse) async {149        guard let s = response.notification.request.content.userInfo["url"] as? String, let url = URL(string: s) else { return }150        await MainActor.run { AppDelegate.shared?.handle(url: url) }151    }152    nonisolated func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification) async -> UNNotificationPresentationOptions { [.banner, .sound] }153}154
Files main
Menu

Theme