Repository Public
1// SP Notes iOS2// File: Core/TaskNotifications.swift3// Description: Local notifications for the due dates of open tasks (2.0). The tasks live in the store (and sync); this type only4// mirrors them into the notification centre: rescheduled from the store at launch and after every task change,5// cancelled when a task is done or deleted, capped under the system limit of 64 pending requests (nearest first,6// room left for the 1.0 note reminders, which `ReminderScheduler` keeps scheduling untouched under its own7// `reminder-…` identifiers). Rule for the time: see `TaskDueRule` — a bare day (noon UTC on the server) notifies at8// 09:00 local time that day, a timed due date at its time. Actions: « Terminer », « Reporter à demain ».9// Opt-in: permission is asked the first time the user sets a due date, or from Réglages.10//11// Author: Simon-Pierre Boucher12// Contact: contact@spboucher.ai13import Foundation14import Observation15import SPNotesCore16import UserNotifications1718/// One notification to have pending.19struct PlannedTaskNotification: Sendable, Equatable {20 var taskId: String21 var title: String22 /// Title of the note the task belongs to.23 var subtitle: String?24 var fireDate: Date25 var dueAt: Date26 var pageId: String?27 var blockId: String?2829 var identifier: String { TaskNotificationPlan.identifier(taskId) }30}3132/// The pure part: which notifications should be pending.33enum TaskNotificationPlan {34 /// Never collides with `ReminderScheduler.identifier` (`reminder-<id>`).35 static let prefix = "task-"36 /// iOS keeps at most 64 pending local notifications per app (the soonest ones).37 static let systemLimit = 6438 /// Requests left to the 1.0 note reminders even when they are not scheduled yet.39 static let reservedForReminders = 244041 static func identifier(_ taskId: String) -> String { prefix + taskId }42 static func taskId(fromIdentifier identifier: String) -> String? { identifier.hasPrefix(prefix) ? String(identifier.dropFirst(prefix.count)) : nil }4344 /// How many task notifications may be pending when `otherPending` requests (note reminders) already are.45 static func capacity(otherPending: Int) -> Int {46 max(0, min(systemLimit - reservedForReminders, systemLimit - otherPending))47 }4849 /// The notifications of the open tasks with a due date still to come, nearest first, at most `capacity`.50 /// `reminderTaskIds`: tasks that are the server copy of a 1.0 note reminder — the reminder already notifies.51 static func plan(tasks: [WidgetTask], reminderTaskIds: Set<String> = [], now: Date = Date(), calendar: Calendar = .current, capacity: Int) -> [PlannedTaskNotification] {52 tasks.compactMap { task -> PlannedTaskNotification? in53 guard let due = task.dueAt, !reminderTaskIds.contains(task.id) else { return nil }54 let fire = TaskDueRule.notificationDate(due, calendar: calendar)55 guard fire > now else { return nil }56 return PlannedTaskNotification(taskId: task.id, title: task.title, subtitle: task.noteTitle, fireDate: fire, dueAt: due, pageId: task.pageId, blockId: task.blockId)57 }58 .sorted { $0.fireDate != $1.fireDate ? $0.fireDate < $1.fireDate : $0.taskId < $1.taskId }59 .prefix(max(0, capacity)).map { $0 }60 }61}6263enum TaskNotificationAuthorization: Sendable, Equatable { case notDetermined, authorized, denied }6465/// The notification centre, behind a protocol so the scheduling rules are tested without the system.66protocol TaskNotificationCenter: Sendable {67 func authorization() async -> TaskNotificationAuthorization68 func requestAuthorization() async -> Bool69 func pendingIdentifiers() async -> [String]70 func add(_ notification: PlannedTaskNotification) async71 func remove(identifiers: [String]) async72 func registerCategory() async73}7475struct SystemTaskNotificationCenter: TaskNotificationCenter {76 private var center: UNUserNotificationCenter { .current() }7778 func authorization() async -> TaskNotificationAuthorization {79 switch await center.notificationSettings().authorizationStatus {80 case .authorized, .provisional, .ephemeral: return .authorized81 case .denied: return .denied82 default: return .notDetermined83 }84 }8586 func requestAuthorization() async -> Bool { (try? await center.requestAuthorization(options: [.alert, .sound, .badge])) ?? false }8788 func pendingIdentifiers() async -> [String] { await center.pendingNotificationRequests().map(\.identifier) }8990 func add(_ notification: PlannedTaskNotification) async {91 let content = UNMutableNotificationContent()92 content.title = notification.title93 if let subtitle = notification.subtitle, !subtitle.isEmpty { content.subtitle = subtitle }94 content.sound = .default95 content.categoryIdentifier = TaskNotifications.category96 content.threadIdentifier = "tasks"97 var info = [TaskNotifications.taskIdKey: notification.taskId, TaskNotifications.dueKey: APIDate.string(from: notification.dueAt)]98 if let pageId = notification.pageId { info[TaskNotifications.pageIdKey] = pageId }99 if let blockId = notification.blockId { info[TaskNotifications.blockIdKey] = blockId }100 content.userInfo = info101 let components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute, .second], from: notification.fireDate)102 try? await center.add(UNNotificationRequest(identifier: notification.identifier, content: content, trigger: UNCalendarNotificationTrigger(dateMatching: components, repeats: false)))103 }104105 func remove(identifiers: [String]) async {106 guard !identifiers.isEmpty else { return }107 center.removePendingNotificationRequests(withIdentifiers: identifiers)108 }109110 func registerCategory() async {111 let complete = UNNotificationAction(identifier: TaskNotifications.completeAction, title: String(localized: "Terminer"), options: [])112 let postpone = UNNotificationAction(identifier: TaskNotifications.postponeAction, title: String(localized: "Reporter à demain"), options: [])113 let category = UNNotificationCategory(identifier: TaskNotifications.category, actions: [complete, postpone], intentIdentifiers: [], options: [])114 // The categories of other features (none in 1.0) are kept.115 var categories = await center.notificationCategories().filter { $0.identifier != TaskNotifications.category }116 categories.insert(category)117 center.setNotificationCategories(categories)118 }119}120121@MainActor122@Observable123final class TaskNotifications {124 nonisolated static let category = "ai.spboucher.spnotes.ios.task-due"125 nonisolated static let completeAction = "task.complete"126 nonisolated static let postponeAction = "task.tomorrow"127 /// Keys of the notification's `userInfo` — distinct from `ReminderScheduler.noteIdKey` on purpose: a task notification is128 /// never mistaken for a note reminder (nor cancelled with the reminders of a note).129 nonisolated static let taskIdKey = "taskId", pageIdKey = "taskPageId", blockIdKey = "taskBlockId", dueKey = "taskDue"130 nonisolated static let enabledKey = "tasks.notifications.enabled"131132 /// The user's choice (off until a due date is first set or the row of Réglages is turned on).133 private(set) var isEnabled: Bool134 /// Refused in the system settings: the row of Réglages explains it.135 private(set) var isDenied = false136 /// What the last pass left pending (tests, diagnostics).137 private(set) var scheduled: [PlannedTaskNotification] = []138139 @ObservationIgnored private let store: NotesStore140 @ObservationIgnored private let tasks: TasksRepository141 @ObservationIgnored private let center: any TaskNotificationCenter142 @ObservationIgnored private let defaults: UserDefaults143 @ObservationIgnored private var observer: Task<Void, Never>?144 @ObservationIgnored private var pending: Task<Void, Never>?145146 init(store: NotesStore, tasks: TasksRepository, center: any TaskNotificationCenter = SystemTaskNotificationCenter(), defaults: UserDefaults = .standard) {147 self.store = store148 self.tasks = tasks149 self.center = center150 self.defaults = defaults151 isEnabled = defaults.bool(forKey: Self.enabledKey)152 }153154 /// True once the user chose (either way): the first due date then no longer asks.155 var hasDecided: Bool { defaults.object(forKey: Self.enabledKey) != nil }156157 // MARK: the user's choice158159 /// Réglages → « Notifications des tâches ». Turning it on asks the system permission if needed; returns the resulting state.160 @discardableResult161 func setEnabled(_ wanted: Bool) async -> Bool {162 if wanted {163 var status = await center.authorization()164 if status == .notDetermined { status = await center.requestAuthorization() ? .authorized : .denied }165 isDenied = status == .denied166 isEnabled = status == .authorized167 } else {168 isEnabled = false169 }170 defaults.set(isEnabled, forKey: Self.enabledKey)171 await reschedule()172 return isEnabled173 }174175 /// To call when the user sets a due date on a task in the app: the first time, asks whether notifications are wanted176 /// (the system prompt); afterwards does nothing.177 func userDidSetDueDate() async {178 guard !hasDecided else { return }179 await setEnabled(true)180 }181182 /// Reads the system state (the row of Réglages shows why nothing arrives when notifications were refused later).183 func refreshAuthorization() async {184 let status = await center.authorization()185 isDenied = status == .denied && (isEnabled || hasDecided)186 }187188 // MARK: scheduling189190 /// Follows the store: every change of the tasks (and a reset) reschedules, coalesced. Idempotent. Never asks permission.191 func start() {192 guard observer == nil else { return }193 observer = Task { [weak self, store] in194 await self?.center.registerCategory()195 await self?.reschedule()196 for await change in await store.changes() {197 switch change {198 case .entities(let kind, _) where kind == EntityKind.task.rawValue: self?.rescheduleSoon()199 case .reset, .reminders: self?.rescheduleSoon()200 default: break201 }202 }203 }204 }205206 private func rescheduleSoon() {207 pending?.cancel()208 pending = Task { [weak self] in209 try? await Task.sleep(for: .milliseconds(400))210 guard !Task.isCancelled else { return }211 await self?.reschedule()212 }213 }214215 /// Makes the pending task notifications equal to the plan: stale ones removed, the others added (or replaced).216 func reschedule(now: Date = Date(), calendar: Calendar = .current) async {217 let all = await center.pendingIdentifiers()218 let mine = all.filter { $0.hasPrefix(TaskNotificationPlan.prefix) }219 guard isEnabled, await center.authorization() == .authorized else {220 await center.remove(identifiers: mine)221 scheduled = []222 return223 }224 var open: [WidgetTask] = []225 if let items = try? await WidgetDataProvider.openTasks(in: store) {226 for task in items where task.dueAt != nil {227 open.append(WidgetTask(task, noteTitle: await WidgetDataProvider.noteTitle(of: task, in: store), now: now, calendar: calendar))228 }229 }230 // A 1.0 note reminder is a task on the server: it comes back in the task list, and already has its own notification.231 let reminderTaskIds = Set(((try? await store.upcomingReminders(from: Date(timeIntervalSince1970: 0), limit: 1_000)) ?? []).compactMap(\.serverTaskId))232 let plan = TaskNotificationPlan.plan(tasks: open, reminderTaskIds: reminderTaskIds, now: now, calendar: calendar,233 capacity: TaskNotificationPlan.capacity(otherPending: all.count - mine.count))234 let wanted = Set(plan.map(\.identifier))235 await center.remove(identifiers: mine.filter { !wanted.contains($0) })236 for notification in plan { await center.add(notification) }237 scheduled = plan238 }239240 // MARK: responses241242 /// What a response to a task notification asks for.243 enum Response: Equatable, Sendable {244 case complete(taskId: String)245 case postpone(taskId: String, due: Date?)246 /// A tap: the link to open (the task's note at its block, else the task list).247 case open(URL)248 }249250 /// Reads a response from the texts of the notification (`nil` = not a task notification).251 nonisolated static func response(action: String, category: String, userInfo: [String: String]) -> Response? {252 guard category == Self.category, let taskId = userInfo[taskIdKey], !taskId.isEmpty else { return nil }253 switch action {254 case completeAction: return .complete(taskId: taskId)255 case postponeAction: return .postpone(taskId: taskId, due: userInfo[dueKey].flatMap(APIDate.parse))256 case UNNotificationDismissActionIdentifier: return nil257 default: return .open(SystemLinks.task(pageId: userInfo[pageIdKey], blockId: userInfo[blockIdKey]))258 }259 }260261 /// Runs a background action through the tasks repository (local first, synchronised like any edit). Returns the link to262 /// open for a tap.263 @discardableResult264 func perform(_ response: Response, now: Date = Date(), calendar: Calendar = .current) async -> URL? {265 switch response {266 case .complete(let taskId):267 _ = try? await tasks.setDone(id: taskId, true)268 case .postpone(let taskId, let due):269 let current = (try? await tasks.task(id: taskId))?.dueAt ?? due270 _ = try? await tasks.update(id: taskId, TaskEdit(dueAt: .value(TaskDueRule.postponedToTomorrow(current, now: now, calendar: calendar))))271 case .open(let url):272 return url273 }274 await reschedule(now: now, calendar: calendar)275 return nil276 }277}278