Reportage/Services/Prompts/PromptScheduler.swift (3396B)
1import Foundation
2import OSLog
3import UserNotifications
4
5
6
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
28
29
30
31struct PromptScheduler: Sendable {
32 var center: any NotificationScheduling = SystemNotifications()
33
34 private static let logger = Logger(subsystem: "net.inqk.reportage", category: "Prompts")
35
36
37
38
39
40
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
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
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}