Repository Public
1// SP Notes Core2// File: Sources/SPNotesStore/NotesStore+History.swift3// Description: Conflict records, local history snapshots (with pruning and restore) and reminders.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation89extension NotesStore {10 // MARK: - Conflicts1112 private static func decodeConflict(_ r: Row) -> ConflictRecord {13 ConflictRecord(pageId: r.string(0),14 server: ServerCopy(version: Int(r.int(1)), title: r.string(2), content: r.data(3), properties: r.data(4), updatedAt: r.date(5)),15 detectedAt: r.date(6))16 }1718 private static let conflictColumns = "page_id, version, title, content, properties, updated_at, detected_at"1920 /// Records (or replaces) the conflict of a page with the server's copy and sets `syncState = conflict`.21 /// Local content is untouched. Pages in conflict are left out of `pagesNeedingPush()` until resolved.22 public func recordConflict(pageId: String, server: ServerCopy, detectedAt: Date = Date()) throws {23 try write {24 _ = try requirePage(pageId)25 try db.run("""26 INSERT INTO conflicts(page_id, version, title, content, properties, updated_at, detected_at) VALUES(?, ?, ?, ?, ?, ?, ?)27 ON CONFLICT(page_id) DO UPDATE SET version=excluded.version, title=excluded.title, content=excluded.content,28 properties=excluded.properties, updated_at=excluded.updated_at, detected_at=excluded.detected_at29 """, [pageId, server.version, server.title, server.content, server.properties, server.updatedAt, detectedAt])30 try refreshState(pageId)31 pending.conflicts = true32 pending.pages.insert(pageId)33 }34 }3536 public func conflict(pageId: String) throws -> ConflictRecord? {37 try db.first("SELECT \(Self.conflictColumns) FROM conflicts WHERE page_id=?", [pageId], Self.decodeConflict)38 }3940 /// All conflicts, oldest first.41 public func conflicts() throws -> [ConflictRecord] {42 try db.query("SELECT \(Self.conflictColumns) FROM conflicts ORDER BY detected_at, page_id", [], Self.decodeConflict)43 }4445 /// Drops the conflict record without changing the page content; `syncState` goes back to what the flags say.46 public func clearConflict(pageId: String) throws {47 try write { try removeConflict(pageId) }48 }4950 func removeConflict(_ pageId: String) throws {51 if try db.run("DELETE FROM conflicts WHERE page_id=?", [pageId]) > 0 {52 pending.conflicts = true53 pending.pages.insert(pageId)54 }55 try refreshState(pageId)56 }5758 // MARK: - Local versions5960 public static let maxLocalVersionsPerPage = 1006162 /// Saves a history snapshot of the page's current title and content. Returns nil (and writes nothing) when63 /// they are identical to the latest snapshot. Keeps the newest 100 snapshots per page.64 @discardableResult65 public func snapshot(pageId: String, reason: String) throws -> LocalVersionInfo? {66 try write {67 let page = try requirePage(pageId).page68 return try takeSnapshot(of: page, reason: reason, now: nowMillis())69 }70 }7172 func takeSnapshot(of page: PageRecord, reason: String, now: Int64) throws -> LocalVersionInfo? {73 let latest = try db.first("SELECT title, content FROM local_versions WHERE page_id=? ORDER BY seq DESC LIMIT 1", [page.id]) {74 ($0.string(0), $0.data(1))75 }76 if let latest, latest.0 == page.title, latest.1 == page.content { return nil }77 let id = Self.newId()78 try db.run("""79 INSERT INTO local_versions(id, page_id, created_at, title, content, word_count, reason, plain_text, preview) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?)80 """, [id, page.id, now, page.title, page.content, page.wordCount, reason, page.plainText, page.preview])81 try db.run("""82 DELETE FROM local_versions WHERE page_id=?183 AND seq NOT IN (SELECT seq FROM local_versions WHERE page_id=?1 ORDER BY seq DESC LIMIT \(Self.maxLocalVersionsPerPage))84 """, [page.id])85 return LocalVersionInfo(id: id, pageId: page.id, createdAt: Date(millis: now), title: page.title, wordCount: page.wordCount, reason: reason)86 }8788 /// Snapshots of a page, newest first (without the content).89 public func localVersions(pageId: String) throws -> [LocalVersionInfo] {90 try db.query("SELECT id, page_id, created_at, title, word_count, reason FROM local_versions WHERE page_id=? ORDER BY seq DESC", [pageId]) {91 LocalVersionInfo(id: $0.string(0), pageId: $0.string(1), createdAt: $0.date(2), title: $0.string(3), wordCount: Int($0.int(4)), reason: $0.string(5))92 }93 }9495 public func localVersion(id: String) throws -> LocalVersion? {96 try db.first("SELECT id, page_id, created_at, title, content, word_count, reason, plain_text, preview FROM local_versions WHERE id=?", [id]) {97 LocalVersion(id: $0.string(0), pageId: $0.string(1), createdAt: $0.date(2), title: $0.string(3), content: $0.data(4),98 wordCount: Int($0.int(5)), reason: $0.string(6), plainText: $0.string(7), preview: $0.string(8))99 }100 }101102 /// Brings a snapshot back: snapshots the current state first (reason "before-restore"), then applies the103 /// snapshot's title and content as an ordinary local edit (dirty, to be pushed). Returns the page.104 @discardableResult105 public func restoreVersion(id versionId: String) throws -> PageRecord {106 try write {107 guard let version = try localVersion(id: versionId) else { throw StoreError.notFound("local version \(versionId)") }108 let loaded = try requirePage(version.pageId)109 let now = nowMillis()110 _ = try takeSnapshot(of: loaded.page, reason: "before-restore", now: now)111 _ = try applyContentEdit(loaded, title: version.title, content: version.content, properties: nil, plainText: version.plainText,112 wordCount: version.wordCount, preview: version.preview, now: now)113 return try requirePage(version.pageId).page114 }115 }116117 // MARK: - Reminders118119 private static let reminderColumns = "id, page_id, title, due_at, done, server_task_id, dirty, deleted, edit_seq, created_at, updated_at"120121 private static func decodeReminder(_ r: Row) -> ReminderRecord {122 ReminderRecord(id: r.string(0), pageId: r.optString(1), title: r.string(2), dueAt: r.optDate(3), done: r.bool(4),123 serverTaskId: r.optString(5), dirty: r.bool(6), deleted: r.bool(7), editSeq: r.int(8), createdAt: r.date(9),124 updatedAt: r.date(10))125 }126127 public func reminder(id: String) throws -> ReminderRecord? {128 try db.first("SELECT \(Self.reminderColumns) FROM reminders WHERE id=?", [id], Self.decodeReminder)129 }130131 private func requireReminder(_ id: String) throws -> ReminderRecord {132 guard let record = try reminder(id: id) else { throw StoreError.notFound("reminder \(id)") }133 return record134 }135136 /// Creates a reminder (dirty). `serverTaskId` is set when it mirrors a task that already exists on the137 /// server, in which case it is stored clean.138 @discardableResult139 public func createReminder(id: String? = nil, pageId: String? = nil, title: String, dueAt: Date? = nil, done: Bool = false,140 serverTaskId: String? = nil) throws -> ReminderRecord {141 try write {142 let reminderId = (id ?? Self.newId()).lowercased()143 guard try reminder(id: reminderId) == nil else { throw StoreError.invalid("reminder \(reminderId) already exists") }144 let now = nowMillis()145 try db.run("""146 INSERT INTO reminders(id, page_id, title, due_at, done, server_task_id, dirty, edit_seq, created_at, updated_at) VALUES(?, ?, ?, ?, ?, ?, ?, 1, ?, ?)147 """, [reminderId, pageId, title, dueAt, done, serverTaskId, serverTaskId == nil, now, now])148 pending.reminders = true149 return try requireReminder(reminderId)150 }151 }152153 /// Updates the given fields (nil = unchanged; `dueAt: .some(nil)` clears the date). Marks the reminder dirty.154 @discardableResult155 public func updateReminder(id: String, title: String? = nil, dueAt: Date?? = nil, done: Bool? = nil) throws -> ReminderRecord {156 try write {157 let current = try requireReminder(id)158 let newTitle = title ?? current.title159 let newDue = dueAt ?? current.dueAt160 let newDone = done ?? current.done161 guard newTitle != current.title || newDue?.millis != current.dueAt?.millis || newDone != current.done else { return current }162 try db.run("UPDATE reminders SET title=?, due_at=?, done=?, dirty=1, edit_seq=edit_seq+1, updated_at=? WHERE id=?",163 [newTitle, newDue, newDone, nowMillis(), id])164 pending.reminders = true165 return try requireReminder(id)166 }167 }168169 /// Deletes a reminder. Never on the server: the row disappears. Otherwise it is kept as `deleted` + `dirty`170 /// until `markReminderSynced`.171 public func deleteReminder(id: String) throws {172 try write {173 let current = try requireReminder(id)174 if current.serverTaskId == nil {175 try db.run("DELETE FROM reminders WHERE id=?", [id])176 } else {177 try db.run("UPDATE reminders SET deleted=1, dirty=1, edit_seq=edit_seq+1, updated_at=? WHERE id=?", [nowMillis(), id])178 }179 pending.reminders = true180 }181 }182183 /// Reminders of a page (not deleted), by due date then creation.184 public func reminders(pageId: String) throws -> [ReminderRecord] {185 try db.query("""186 SELECT \(Self.reminderColumns) FROM reminders WHERE page_id=? AND deleted=0 ORDER BY due_at IS NULL, due_at, created_at, id187 """, [pageId], Self.decodeReminder)188 }189190 /// Reminders not done, not deleted, with a due date; soonest first. `from` nil includes overdue ones.191 public func upcomingReminders(from: Date? = nil, limit: Int = 100) throws -> [ReminderRecord] {192 try db.query("""193 SELECT \(Self.reminderColumns) FROM reminders WHERE deleted=0 AND done=0 AND due_at IS NOT NULL AND due_at>=? ORDER BY due_at, id LIMIT ?194 """, [from?.millis ?? Int64.min, limit], Self.decodeReminder)195 }196197 /// Reminders with local changes to push (including deleted ones), oldest change first.198 public func dirtyReminders() throws -> [ReminderRecord] {199 try db.query("SELECT \(Self.reminderColumns) FROM reminders WHERE dirty=1 ORDER BY updated_at, id", [], Self.decodeReminder)200 }201202 /// The server acknowledged the reminder as pushed at `pushedEditSeq`. Records the task id; clears `dirty`203 /// only when the reminder did not change meanwhile; removes the row when it was a pushed deletion.204 public func markReminderSynced(id: String, serverTaskId: String?, pushedEditSeq: Int64) throws {205 try write {206 guard let current = try reminder(id: id) else { return }207 pending.reminders = true208 if current.editSeq == pushedEditSeq, current.deleted {209 try db.run("DELETE FROM reminders WHERE id=?", [id])210 return211 }212 try db.run("UPDATE reminders SET server_task_id=coalesce(?, server_task_id), dirty=CASE WHEN edit_seq=? THEN 0 ELSE 1 END WHERE id=?",213 [serverTaskId, pushedEditSeq, id])214 }215 }216}217