Glimmer / app · glimmertoday.ai / native / Glimmer / PersonalReminders.swift
| 1 | import Foundation |
| 2 | import Observation |
| 3 | import UserNotifications |
| 4 | |
| 5 | @MainActor @Observable |
| 6 | final class PersonalReminders { |
| 7 | static let shared = PersonalReminders() |
| 8 | private static let prefix = "glimmer.personal-todo." |
| 9 | private let center = UNUserNotificationCenter.current() |
| 10 | private let delegate = ForegroundReminders() |
| 11 | private var next: [PersonalTodo]? |
| 12 | private var reconciling = false |
| 13 | private(set) var schedulingFailed = false |
| 14 | private(set) var authorization: UNAuthorizationStatus = .notDetermined |
| 15 | |
| 16 | private init() { |
| 17 | center.delegate = delegate |
| 18 | } |
| 19 | |
| 20 | /// Ask only after a person saves a reminder in the app. |
| 21 | func authorize() async -> Bool { |
| 22 | let settings = await center.notificationSettings() |
| 23 | authorization = settings.authorizationStatus |
| 24 | if settings.authorizationStatus == .notDetermined { |
| 25 | let granted = (try? await center.requestAuthorization(options: [.alert, .sound])) == true |
| 26 | authorization = await center.notificationSettings().authorizationStatus |
| 27 | return granted |
| 28 | } |
| 29 | return Self.allowsNotifications(settings.authorizationStatus) |
| 30 | } |
| 31 | |
| 32 | func refresh(_ tasks: [PersonalTodo]) { |
| 33 | next = tasks |
| 34 | guard !reconciling else { return } |
| 35 | reconciling = true |
| 36 | Task { |
| 37 | while let tasks = next { |
| 38 | next = nil |
| 39 | await reconcile(tasks) |
| 40 | } |
| 41 | reconciling = false |
| 42 | } |
| 43 | } |
| 44 | |
| 45 | nonisolated static func upcoming(_ tasks: [PersonalTodo], now: Date, limit: Int) -> [PersonalTodo] { |
| 46 | tasks.filter { task in |
| 47 | !task.completed && (task.reminderAt.map { $0 > now } ?? false) |
| 48 | } |
| 49 | .sorted { ($0.reminderAt ?? .distantFuture, $0.id.uuidString) < ($1.reminderAt ?? .distantFuture, $1.id.uuidString) } |
| 50 | .prefix(max(0, limit)) |
| 51 | .map { $0 } |
| 52 | } |
| 53 | |
| 54 | private static func allowsNotifications(_ status: UNAuthorizationStatus) -> Bool { |
| 55 | status == .authorized || status == .provisional |
| 56 | } |
| 57 | |
| 58 | private func reconcile(_ tasks: [PersonalTodo]) async { |
| 59 | let pending = await center.pendingNotificationRequests() |
| 60 | let ours = pending.filter { $0.identifier.hasPrefix(Self.prefix) } |
| 61 | let settings = await center.notificationSettings() |
| 62 | authorization = settings.authorizationStatus |
| 63 | let limit = Self.allowsNotifications(settings.authorizationStatus) ? 60 - (pending.count - ours.count) : 0 |
| 64 | let wanted = Self.upcoming(tasks, now: .now, limit: limit) |
| 65 | let identifiers = Set(wanted.map(identifier(for:))) |
| 66 | let removals = ours.map(\.identifier).filter { !identifiers.contains($0) } |
| 67 | if !removals.isEmpty { center.removePendingNotificationRequests(withIdentifiers: removals) } |
| 68 | |
| 69 | let openReminders = Set(tasks.filter { !$0.completed && $0.reminderAt != nil }.map(identifier(for:))) |
| 70 | let delivered = await center.deliveredNotifications() |
| 71 | let outdated = delivered.map { $0.request.identifier } |
| 72 | .filter { $0.hasPrefix(Self.prefix) && !openReminders.contains($0) } |
| 73 | if !outdated.isEmpty { center.removeDeliveredNotifications(withIdentifiers: outdated) } |
| 74 | |
| 75 | var failed = false |
| 76 | var calendar = Calendar(identifier: .gregorian) |
| 77 | calendar.timeZone = TimeZone(secondsFromGMT: 0)! |
| 78 | for task in wanted { |
| 79 | guard let date = task.reminderAt else { continue } |
| 80 | let matching = calendar.dateComponents(in: calendar.timeZone, from: date) |
| 81 | var components = DateComponents() |
| 82 | components.calendar = calendar |
| 83 | components.timeZone = calendar.timeZone |
| 84 | components.year = matching.year |
| 85 | components.month = matching.month |
| 86 | components.day = matching.day |
| 87 | components.hour = matching.hour |
| 88 | components.minute = matching.minute |
| 89 | components.second = matching.second |
| 90 | let id = identifier(for: task) |
| 91 | if let existing = ours.first(where: { $0.identifier == id }), |
| 92 | let trigger = existing.trigger as? UNCalendarNotificationTrigger, |
| 93 | trigger.dateComponents == components, existing.content.body == task.title { continue } |
| 94 | let content = UNMutableNotificationContent() |
| 95 | content.title = "Glimmer reminder" |
| 96 | content.body = task.title |
| 97 | content.sound = .default |
| 98 | let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false) |
| 99 | guard trigger.nextTriggerDate() != nil else { continue } |
| 100 | do { |
| 101 | try await center.add(UNNotificationRequest(identifier: id, content: content, trigger: trigger)) |
| 102 | } catch { |
| 103 | failed = true |
| 104 | } |
| 105 | } |
| 106 | schedulingFailed = failed |
| 107 | } |
| 108 | |
| 109 | private func identifier(for task: PersonalTodo) -> String { Self.prefix + task.id.uuidString } |
| 110 | } |
| 111 | |
| 112 | private final class ForegroundReminders: NSObject, UNUserNotificationCenterDelegate { |
| 113 | func userNotificationCenter(_ center: UNUserNotificationCenter, |
| 114 | willPresent notification: UNNotification) async -> UNNotificationPresentationOptions { |
| 115 | [.banner, .list, .sound] |
| 116 | } |
| 117 | } |