Repository Public
1// SP Notes iOS2// File: WidgetShared/WidgetTasks.swift3// Description: Tasks for the system surfaces (widgets, notifications, Spotlight, App Intents): the rule that turns a due date4// into a calendar day, the links to the app's task destinations, the tasks a widget shows (due today or overdue,5// read from the shared database) and the one write a widget is allowed to make — completing a task — which goes6// through the Core's `TasksRepository` (local row + outbox entry in one transaction) on a second connection.7//8// Author: Simon-Pierre Boucher9// Contact: contact@spboucher.ai10import Foundation11import os12import SPNotesCore1314// MARK: due dates1516/// How a task's due date is read on this device.17///18/// The server stores a due date given as a bare day (`YYYY-MM-DD`, no time) at **12:00:00 UTC** of that day. Such a date19/// means "that calendar day", wherever the device is: it is shown as that day (never shifted by the time zone) and its20/// notification fires at **09:00 local time** on that day. Any other instant is a timed due date: it is shown and notified21/// at that instant. (A task deliberately timed at exactly 12:00:00.000 UTC cannot be told apart and is treated as a bare day.)22enum TaskDueRule {23 static let notificationHour = 92425 private static var utc: Calendar {26 var calendar = Calendar(identifier: .gregorian)27 calendar.timeZone = TimeZone(identifier: "UTC")!28 return calendar29 }3031 static func isBareDay(_ due: Date) -> Bool {32 let parts = utc.dateComponents([.hour, .minute, .second, .nanosecond], from: due)33 return parts.hour == 12 && parts.minute == 0 && parts.second == 0 && (parts.nanosecond ?? 0) < 1_000_00034 }3536 /// Midnight, in `calendar`, of the day the task is due.37 static func localDay(_ due: Date, calendar: Calendar = .current) -> Date {38 guard isBareDay(due) else { return calendar.startOfDay(for: due) }39 let day = utc.dateComponents([.year, .month, .day], from: due)40 return calendar.date(from: DateComponents(year: day.year, month: day.month, day: day.day)) ?? calendar.startOfDay(for: due)41 }4243 /// True when the task is late: its day is before today, or its time has passed.44 static func isOverdue(_ due: Date, now: Date = Date(), calendar: Calendar = .current) -> Bool {45 isBareDay(due) ? localDay(due, calendar: calendar) < calendar.startOfDay(for: now) : due < now46 }4748 /// True when the task is due today or late (what the widget lists).49 static func isDueByToday(_ due: Date, now: Date = Date(), calendar: Calendar = .current) -> Bool {50 localDay(due, calendar: calendar) <= calendar.startOfDay(for: now)51 }5253 /// When the notification of a due date fires.54 static func notificationDate(_ due: Date, calendar: Calendar = .current) -> Date {55 guard isBareDay(due) else { return due }56 return calendar.date(byAdding: .hour, value: notificationHour, to: localDay(due, calendar: calendar)) ?? due57 }5859 /// The server's instant for a bare day: 12:00 UTC of the calendar day `localDate` falls on in `calendar`.60 static func bareDay(of localDate: Date, calendar: Calendar = .current) -> Date {61 let day = calendar.dateComponents([.year, .month, .day], from: localDate)62 return utc.date(from: DateComponents(year: day.year, month: day.month, day: day.day, hour: 12)) ?? localDate63 }6465 /// `YYYY-MM-DD` of the calendar day `localDate` falls on (`TasksRepository.create(dueDay:)`).66 static func dayString(of localDate: Date, calendar: Calendar = .current) -> String {67 let day = calendar.dateComponents([.year, .month, .day], from: localDate)68 return String(format: "%04d-%02d-%02d", day.year ?? 0, day.month ?? 0, day.day ?? 0)69 }7071 /// « Reporter à demain »: a bare day becomes tomorrow's day; a timed due date keeps its time of day, tomorrow.72 static func postponedToTomorrow(_ due: Date?, now: Date = Date(), calendar: Calendar = .current) -> Date {73 let tomorrow = calendar.date(byAdding: .day, value: 1, to: calendar.startOfDay(for: now)) ?? now.addingTimeInterval(86_400)74 guard let due, !isBareDay(due) else { return bareDay(of: tomorrow, calendar: calendar) }75 let time = calendar.dateComponents([.hour, .minute, .second], from: due)76 return calendar.date(bySettingHour: time.hour ?? 9, minute: time.minute ?? 0, second: time.second ?? 0, of: tomorrow) ?? tomorrow77 }78}7980// MARK: links8182/// The `spnotes://` links of the 2.0 destinations, built as text: the widget extension, the notifications and the quick83/// actions hand them to `AppModel.open(url:)`, which resolves them (`Shared/DeepLink.swift`).84enum SystemLinks {85 static let tasks = URL(string: "spnotes://tasks")!86 static let inbox = URL(string: "spnotes://inbox")!87 static let today = URL(string: "spnotes://today")!88 static let newNote = URL(string: "spnotes://new")!89 static let search = URL(string: "spnotes://search")!9091 /// `spnotes://capture[?kind=…]`.92 static func capture(kind: String? = nil) -> URL {93 guard let kind, !kind.isEmpty, kind.allSatisfy({ $0.isLetter && $0.isASCII }) else { return URL(string: "spnotes://capture")! }94 return URL(string: "spnotes://capture?kind=\(kind.lowercased())")!95 }9697 /// `spnotes://note/<id>[?block=<blockId>]`; nil when the id is not a note id. A block id that is not a plain token is left out.98 static func note(_ id: String, blockId: String? = nil) -> URL? {99 guard DeepLink.isValidNoteID(id) else { return nil }100 var text = "spnotes://note/\(id.lowercased())"101 if let blockId, isPlainToken(blockId) { text += "?block=\(blockId)" }102 return URL(string: text)103 }104105 /// Where a task leads: its note at its block, else the task list.106 static func task(pageId: String?, blockId: String?) -> URL {107 pageId.flatMap { note($0, blockId: blockId) } ?? tasks108 }109110 static func isPlainToken(_ text: String) -> Bool {111 !text.isEmpty && text.count <= 64 && text.unicodeScalars.allSatisfy { ($0.isASCII && ($0.properties.isAlphabetic || ("0"..."9").contains(Character($0)))) || $0 == "-" || $0 == "_" }112 }113}114115// MARK: what a widget shows116117/// A task as the widgets, the notifications and the system pickers see it.118struct WidgetTask: Sendable, Equatable, Identifiable {119 var id: String120 var title: String121 var dueAt: Date?122 var priority: String?123 var pageId: String?124 var blockId: String?125 /// Title of the note the task belongs to.126 var noteTitle: String?127 var isOverdue = false128129 var url: URL { SystemLinks.task(pageId: pageId, blockId: blockId) }130 var isHighPriority: Bool { priority == "high" }131132 init(id: String, title: String, dueAt: Date? = nil, priority: String? = nil, pageId: String? = nil, blockId: String? = nil, noteTitle: String? = nil, isOverdue: Bool = false) {133 self.id = id; self.title = title; self.dueAt = dueAt; self.priority = priority134 self.pageId = pageId; self.blockId = blockId; self.noteTitle = noteTitle; self.isOverdue = isOverdue135 }136137 init(_ task: TaskItem, noteTitle: String? = nil, now: Date = Date(), calendar: Calendar = .current) {138 self.init(id: task.id, title: task.title, dueAt: task.dueAt, priority: task.priority, pageId: task.pageId, blockId: task.blockId,139 noteTitle: noteTitle ?? task.pageTitle.map(WidgetNote.displayTitle), isOverdue: task.dueAt.map { TaskDueRule.isOverdue($0, now: now, calendar: calendar) } ?? false)140 }141}142143/// What the « Capture et tâches » widget has to show.144enum WidgetTasksContent: Sendable, Equatable {145 /// The database cannot be read (the app was never opened, or it has not been opened since the 2.0 update).146 case unavailable147 /// The app lock is on: no task text, no check buttons.148 case locked149 /// The tasks due today or late (possibly none), `more` others of the same kind that do not fit, `open` open tasks in all.150 case tasks([WidgetTask], more: Int, open: Int)151152 var tasks: [WidgetTask] {153 if case .tasks(let tasks, _, _) = self { return tasks }154 return []155 }156}157158extension WidgetDataProvider {159 /// Open tasks of the local copy, in the list order of the app (due date first, undated last, newest first).160 static func openTasks(in store: NotesStore) async throws -> [TaskItem] {161 let decoder = APIJSON.decoder()162 return try await store.tasks().filter { !$0.deleted }.compactMap { try? decoder.decode(TaskItem.self, from: $0.json) }163 .filter { !$0.isDone && $0.deletedAt == nil }164 .sorted { a, b in165 switch (a.dueAt, b.dueAt) {166 case (let x?, let y?) where x != y: return x < y167 case (.some, nil): return true168 case (nil, .some): return false169 default: return a.createdAt != b.createdAt ? a.createdAt > b.createdAt : a.id < b.id170 }171 }172 }173174 /// Open tasks with the title of their note (pickers, Spotlight, notifications).175 func openTasks(limit: Int = 200, now: Date = Date(), calendar: Calendar = .current) async -> [WidgetTask] {176 (try? await SharedNotesStore.read(databaseURL: databaseURL) { store in177 var result: [WidgetTask] = []178 for task in try await Self.openTasks(in: store).prefix(limit) {179 result.append(WidgetTask(task, noteTitle: await Self.noteTitle(of: task, in: store), now: now, calendar: calendar))180 }181 return result182 }) ?? []183 }184185 static func noteTitle(of task: TaskItem, in store: NotesStore) async -> String? {186 guard let pageId = task.pageId, let summary = try? await store.summary(id: pageId), summary.deletedAt == nil else { return nil }187 return WidgetNote.displayTitle(summary.title)188 }189190 /// The tasks due today or late, for the widget; `.locked` — and nothing read — while the app lock is on.191 func tasksContent(limit: Int, now: Date = Date(), calendar: Calendar = .current) async -> WidgetTasksContent {192 if lock.isEnabled { return .locked }193 do {194 return try await SharedNotesStore.read(databaseURL: databaseURL) { store in195 let open = try await Self.openTasks(in: store)196 let due = open.filter { task in task.dueAt.map { TaskDueRule.isDueByToday($0, now: now, calendar: calendar) } ?? false }197 var shown: [WidgetTask] = []198 for task in due.prefix(limit) {199 shown.append(WidgetTask(task, noteTitle: await Self.noteTitle(of: task, in: store), now: now, calendar: calendar))200 }201 return .tasks(shown, more: due.count - shown.count, open: open.count)202 }203 } catch {204 return .unavailable205 }206 }207}208209// MARK: the one write of the widget210211/// Completes a task from outside the screens (widget button, notification action, Shortcuts).212///213/// In the app process the app installs `useAppTasks`, and the write goes through the app's repositories (same connection,214/// sync scheduled at once). In the widget extension there is no app model: the shared database is opened READ-WRITE on a215/// second connection — only when the file is already at this build's schema version, so an extension never creates nor216/// migrates the database — and the change is written by the Core's `TasksRepository` (row + outbox entry, one transaction).217/// The app sends it at its next activation (`store.noteExternalChange()` + sync).218enum SharedTaskActions {219 typealias Completer = @Sendable (_ taskId: String, _ done: Bool) async throws -> Void220 private static let completer = OSAllocatedUnfairLock<Completer?>(initialState: nil)221222 static func useAppTasks(_ complete: @escaping Completer) { completer.withLock { $0 = complete } }223224 enum Outcome: Sendable, Equatable {225 case done226 /// The app lock is on: nothing is changed from outside the app.227 case locked228 /// The database is missing, older than this build (1.0 file: the app migrates it at its next launch) or unreadable.229 case unavailable230 /// The task no longer exists (or is already in that state on another device and was removed).231 case notFound232 case failed233 }234235 /// True when the file exists and already has this build's schema (the only file an extension may write).236 static func isWritable(databaseURL: URL) -> Bool {237 StoreBackup.peekVersion(path: databaseURL.path) == NotesStore.schemaVersion238 }239240 /// Sets a task done (or not). `databaseURL` forces the second-connection path on that file (extension, tests).241 @discardableResult242 static func setDone(taskId: String, _ done: Bool = true, databaseURL: URL? = nil, lock: WidgetLock = .shared, enforceLock: Bool = WidgetLock.isExtensionProcess) async -> Outcome {243 if enforceLock, lock.isEnabled { return .locked }244 if databaseURL == nil, let complete = completer.withLock({ $0 }) {245 do { try await complete(taskId, done); return .done }246 catch RepositoryError.notFound { return .notFound }247 catch { return .failed }248 }249 let url = databaseURL ?? SharedNotesStore.defaultDatabaseURL250 guard isWritable(databaseURL: url), case .opened(let store, let report) = NotesStore.open(url: url), !report.didMigrate else { return .unavailable }251 // No network from here: the repository only needs the client to exist (it is never called by `setDone`).252 let api = NotesAPI(client: HTTPClient(configuration: .production, tokenStore: InMemoryTokenStore(token: nil)))253 let tasks = TasksRepository(context: RepositoryContext(store: store, api: api, engine: nil))254 let outcome: Outcome255 do {256 if let task = try await tasks.task(id: taskId) {257 if task.isDone != done { try await tasks.setDone(id: taskId, done) }258 outcome = .done259 } else {260 outcome = .notFound261 }262 } catch RepositoryError.notFound {263 outcome = .notFound264 } catch {265 outcome = .failed266 }267 await store.close()268 return outcome269 }270}271