← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


Reportage/Services/Prompts/PromptScheduler.swift (3396B)

1import Foundation
2import OSLog
3import UserNotifications
4
5/// The parts of `UNUserNotificationCenter` the scheduler uses, so tests can
6/// stand in for it.
7protocol NotificationScheduling: Sendable {
8    func pendingIdentifiers() async -> [String]
9    func add(_ request: UNNotificationRequest) async throws
10    func removePending(_ identifiers: [String])
11}
12
13struct SystemNotifications: NotificationScheduling {
14    func pendingIdentifiers() async -> [String] {
15        await UNUserNotificationCenter.current().pendingNotificationRequests().map(\.identifier)
16    }
17
18    func add(_ request: UNNotificationRequest) async throws {
19        try await UNUserNotificationCenter.current().add(request)
20    }
21
22    func removePending(_ identifiers: [String]) {
23        UNUserNotificationCenter.current().removePendingNotificationRequests(withIdentifiers: identifiers)
24    }
25}
26
27/// Keeps the pending notifications in step with the plan. It runs whenever
28/// the app gets time (launch, foreground, a notification action, saving a
29/// report, background refresh) and only adds and removes the difference, so
30/// pending prompts aren't reshuffled.
31struct PromptScheduler: Sendable {
32    var center: any NotificationScheduling = SystemNotifications()
33
34    private static let logger = Logger(subsystem: "net.inqk.reportage", category: "Prompts")
35
36    /// Schedules from the saved settings, once any refresh already under
37    /// way has finished. Overlapping runs could otherwise remove each
38    /// other's prompts: a run that read the pending list after a newer one
39    /// added to it would delete the newer prompts as stale. The settings are
40    /// read when the run starts, so the last run uses the latest ones.
41    func refresh() async {
42        await PromptRefreshQueue.shared.run {
43            await reschedule(settings: .load(), secret: PromptSecret.value())
44        }
45    }
46
47    func reschedule(
48        settings: PromptSettings, secret: UInt64, now: Date = Date(), calendar: Calendar = .current
49    ) async {
50        let plan = PromptSchedule.horizon(
51            from: now, settings: settings, secret: secret, calendar: calendar)
52        let planned = Set(plan.map(\.identifier))
53        let pending = await center.pendingIdentifiers()
54        // Snoozed prompts are left alone unless prompts are turned off.
55        let stale = pending.filter { id in
56            guard let kind = PromptNotification.kind(ofIdentifier: id) else { return false }
57            return kind == .snoozed ? !settings.isEnabled : !planned.contains(id)
58        }
59        if !stale.isEmpty {
60            center.removePending(stale)
61        }
62        let existing = Set(pending)
63        for prompt in plan where !existing.contains(prompt.identifier) {
64            do {
65                try await center.add(PromptNotification.request(for: prompt))
66            } catch {
67                Self.logger.error("Couldn't schedule \(prompt.identifier): \(error)")
68            }
69        }
70    }
71}
72
73/// Runs refreshes one after another, in the order they were asked for.
74actor PromptRefreshQueue {
75    static let shared = PromptRefreshQueue()
76
77    private var last: Task<Void, Never>?
78
79    func run(_ operation: @escaping @Sendable () async -> Void) async {
80        let previous = last
81        let task = Task {
82            await previous?.value
83            await operation()
84        }
85        last = task
86        await task.value
87    }
88}