Branchwell

Jotley / app / Shared / Services / LibraryBackup.swift

1import Foundation
2import CoreData
3import CryptoKit
4
5public struct LibraryBackupItem: Codable, Equatable, Sendable {
6 public var entity: String
7 public var id: UUID
8 public var text: [String: String]
9 public var dates: [String: Date]
10 public var numbers: [String: Double]
11 public var noteID: UUID?
12 public var folderID: UUID?
13 public var tagIDs: [UUID]
14}
15
16public struct LibraryBackup: Codable, Equatable, Sendable {
17 public var format: String
18 public var version: Int
19 public var createdAt: Date
20 public var items: [LibraryBackupItem]
21 public var templates: [CustomSummaryTemplate]
22 public var noteCount: Int { items.filter { $0.entity == "Note" }.count }
23}
24
25public struct LibraryRestoreResult: Equatable, Sendable {
26 public let notesAdded: Int
27 public let recordsAdded: Int
28 public let templatesAdded: Int
29 public let recordsKept: Int
30}
31
32/// Portable text data only. No database files, device paths, credentials,
33/// support sessions or microphone state enter this format.
34public enum LibraryBackupService {
35 public static let byteLimit = 256 * 1024 * 1024
36 private struct Fields {
37 var text: Set<String> = []
38 var dates: Set<String> = []
39 var numbers: [String: ClosedRange<Double>] = [:]
40 var ownsNote = false
41 }
42 private static let schema: [String: Fields] = [
43 "Folder": Fields(text: ["name"], dates: ["createdAt"], numbers: ["sortOrder": Double(Int32.min)...Double(Int32.max)]),
44 "Tag": Fields(text: ["name", "canonicalName"], dates: ["createdAt"]),
45 "Note": Fields(text: ["title", "transcription", "cleantranscription", "summary", "summaryType", "notes", "noteType", "sourceDescription", "sourceURL", "transcriptUtterancesJSON"], dates: ["timestamp", "trashedAt"]),
46 "NoteChatMessage": Fields(text: ["role", "content"], dates: ["timestamp"], ownsNote: true),
47 "RecordingMarker": Fields(text: ["label"], numbers: ["timestamp": 0...Double.greatestFiniteMagnitude], ownsNote: true)
48 ]
49
50 public static func decode(_ data: Data) throws -> LibraryBackup {
51 guard data.count <= byteLimit else { throw LocalError.message("Choose a Jotley backup smaller than 256 MB.") }
52 let backup: LibraryBackup
53 do { backup = try JSONDecoder().decode(LibraryBackup.self, from: data) }
54 catch { throw LocalError.message("This file is not a readable Jotley library backup. No data was changed.") }
55 try validate(backup)
56 return backup
57 }
58
59 public static func encode(_ backup: LibraryBackup) throws -> Data {
60 try validate(backup)
61 let encoder = JSONEncoder()
62 encoder.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]
63 let data = try encoder.encode(backup)
64 guard data.count <= byteLimit else { throw LocalError.message("This library exceeds the 256 MB portable backup limit.") }
65 return data
66 }
67
68 public static func validate(_ backup: LibraryBackup) throws {
69 guard backup.format == "ai.jotley.library-backup", backup.version == 1,
70 backup.createdAt.timeIntervalSinceReferenceDate.isFinite, backup.items.count <= 500_000,
71 backup.templates.count <= 100 else { throw invalid() }
72 var ids: [String: Set<UUID>] = [:]
73 for item in backup.items {
74 guard let fields = schema[item.entity], ids[item.entity, default: []].insert(item.id).inserted,
75 Set(item.text.keys).isSubset(of: fields.text), Set(item.dates.keys).isSubset(of: fields.dates),
76 Set(item.numbers.keys).isSubset(of: Set(fields.numbers.keys)),
77 item.dates.values.allSatisfy({ $0.timeIntervalSinceReferenceDate.isFinite }),
78 Set(item.tagIDs).count == item.tagIDs.count else { throw invalid() }
79 for (key, value) in item.numbers {
80 guard value.isFinite, fields.numbers[key]?.contains(value) == true,
81 key != "sortOrder" || value.rounded() == value else { throw invalid() }
82 }
83 guard fields.ownsNote == (item.noteID != nil),
84 item.entity == "Note" || (item.folderID == nil && item.tagIDs.isEmpty) else { throw invalid() }
85 if item.entity == "NoteChatMessage", !["user", "assistant"].contains(item.text["role"] ?? "") { throw invalid() }
86 }
87 for item in backup.items {
88 if let id = item.noteID, ids["Note"]?.contains(id) != true { throw invalid() }
89 if let id = item.folderID, ids["Folder"]?.contains(id) != true { throw invalid() }
90 if item.tagIDs.contains(where: { ids["Tag"]?.contains($0) != true }) { throw invalid() }
91 }
92 var templateIDs = Set<UUID>()
93 for record in backup.templates {
94 guard templateIDs.insert(record.id).inserted, !record.deleted,
95 !record.name.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
96 record.name.count <= 60,
97 !record.instructions.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
98 record.instructions.utf8.count <= 2000,
99 record.createdAt.timeIntervalSinceReferenceDate.isFinite,
100 record.updatedAt.timeIntervalSinceReferenceDate.isFinite else { throw invalid() }
101 }
102 }
103
104 @MainActor public static func export(from store: SharedPersistenceController,
105 templates: SummaryTemplateStore) throws -> LibraryBackup {
106 try store.requireLibraryBackupAccess()
107 let templateRecords = try templates.backupRecords()
108 try store.save()
109 var items: [LibraryBackupItem] = []
110 for entity in schema.keys.sorted() {
111 guard let fields = schema[entity], store.container.managedObjectModel.entitiesByName[entity] != nil else { throw invalid() }
112 let expectedFields = fields.text.union(fields.dates).union(fields.numbers.keys).union(["id"]).union(fields.ownsNote ? ["noteId"] : [])
113 guard Set(store.container.managedObjectModel.entitiesByName[entity]!.attributesByName.keys) == expectedFields else {
114 throw LocalError.message("This version of the library needs a newer backup format. No data was changed.")
115 }
116 let objects = try store.context.fetch(NSFetchRequest<NSManagedObject>(entityName: entity))
117 for object in objects {
118 let text = fields.text.reduce(into: [String: String]()) { if let value = object.value(forKey: $1) as? String { $0[$1] = value } }
119 let dates = fields.dates.reduce(into: [String: Date]()) { if let value = object.value(forKey: $1) as? Date { $0[$1] = value } }
120 let numbers = fields.numbers.keys.reduce(into: [String: Double]()) { if let value = object.value(forKey: $1) as? NSNumber { $0[$1] = value.doubleValue } }
121 let folder = entity == "Note" ? object.value(forKey: "folder") as? NSManagedObject : nil
122 let tags = entity == "Note" ? object.value(forKey: "tags") as? Set<NSManagedObject> ?? [] : []
123 items.append(LibraryBackupItem(entity: entity, id: identifier(object), text: text, dates: dates, numbers: numbers,
124 noteID: fields.ownsNote ? object.value(forKey: "noteId") as? UUID : nil,
125 folderID: folder.map(identifier), tagIDs: tags.map(identifier).sorted { $0.uuidString < $1.uuidString }))
126 }
127 }
128 let result = LibraryBackup(format: "ai.jotley.library-backup", version: 1, createdAt: Date(),
129 items: items.sorted { ($0.entity, $0.id.uuidString) < ($1.entity, $1.id.uuidString) }, templates: templateRecords)
130 try validate(result)
131 return result
132 }
133
134 /// Merge-only restore: matching IDs always keep the current user's data.
135 /// All validation/template capacity checks precede the Core Data transaction.
136 @MainActor public static func restore(_ backup: LibraryBackup, to store: SharedPersistenceController,
137 templates: SummaryTemplateStore) throws -> LibraryRestoreResult {
138 try validate(backup)
139 try store.requireLibraryBackupAccess()
140 let templatePlan = try templates.prepareBackupImport(backup.templates)
141 try store.save() // A failed restore must not roll back unrelated edits.
142 var existing: [String: [UUID: NSManagedObject]] = [:]
143 for entity in schema.keys {
144 guard store.container.managedObjectModel.entitiesByName[entity] != nil else { throw invalid() }
145 for object in try store.context.fetch(NSFetchRequest<NSManagedObject>(entityName: entity)) {
146 let id = identifier(object)
147 guard existing[entity]?[id] == nil else { throw LocalError.message("The current library contains duplicate identifiers. No backup was restored.") }
148 existing[entity, default: [:]][id] = object
149 }
150 }
151 var added: [(LibraryBackupItem, NSManagedObject)] = []
152 do {
153 // A fresh installation already has Personal/Study/Work folders.
154 // Reuse unambiguous matching names instead of duplicating them.
155 for item in backup.items where ["Folder", "Tag"].contains(item.entity) && existing[item.entity]?[item.id] == nil {
156 let name = normalizedName(item.text["name"] ?? "")
157 let matches = existing[item.entity, default: [:]].values.filter { normalizedName($0.text("name")) == name }
158 if !name.isEmpty, matches.count == 1 { existing[item.entity, default: [:]][item.id] = matches.first }
159 }
160 for item in backup.items where existing[item.entity]?[item.id] == nil {
161 let object = NSEntityDescription.insertNewObject(forEntityName: item.entity, into: store.context)
162 object.setValue(item.id, forKey: "id")
163 for (key, value) in item.text { object.setValue(value, forKey: key) }
164 for (key, value) in item.dates { object.setValue(value, forKey: key) }
165 for (key, value) in item.numbers { object.setValue(NSNumber(value: value), forKey: key) }
166 if let noteID = item.noteID { object.setValue(noteID, forKey: "noteId") }
167 existing[item.entity, default: [:]][item.id] = object
168 added.append((item, object))
169 }
170 for (item, object) in added where item.entity == "Note" {
171 if let id = item.folderID { object.setValue(existing["Folder"]?[id], forKey: "folder") }
172 object.setValue(NSSet(array: item.tagIDs.compactMap { existing["Tag"]?[$0] }), forKey: "tags")
173 }
174 try store.save()
175 } catch {
176 store.context.rollback()
177 throw LocalError.message("The backup could not be restored. Your existing notes were preserved.")
178 }
179 templates.applyBackupImport(templatePlan)
180 return LibraryRestoreResult(notesAdded: added.filter { $0.0.entity == "Note" }.count,
181 recordsAdded: added.count, templatesAdded: templatePlan.added, recordsKept: backup.items.count - added.count)
182 }
183
184 @MainActor private static func identifier(_ object: NSManagedObject) -> UUID {
185 if let id = object.value(forKey: "id") as? UUID { return id }
186 // Legacy nil IDs get a repeatable portable identity without modifying
187 // the source library merely to export it.
188 let digest = SHA256.hash(data: Data(object.objectID.uriRepresentation().absoluteString.utf8))
189 let bytes = Array(digest.prefix(16))
190 return UUID(uuid: (bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]))
191 }
192
193 private static func invalid() -> LocalError {
194 .message("This backup has an unsupported format, invalid fields or broken note relationships. No data was changed.")
195 }
196
197 private static func normalizedName(_ name: String) -> String {
198 name.trimmingCharacters(in: .whitespacesAndNewlines).folding(options: [.caseInsensitive, .diacriticInsensitive], locale: Locale(identifier: "en_US_POSIX"))
199 }
200}