Jotley / app / Shared / Services / SharedPersistence.swift
| 1 | import Foundation |
| 2 | import CoreData |
| 3 | import Combine |
| 4 | import CloudKit |
| 5 | |
| 6 | /// CloudKit uses signed app entitlements and the user's iCloud account, never API keys. |
| 7 | public enum NoteSyncMode: Equatable { |
| 8 | case localOnly |
| 9 | case privateICloud(containerIdentifier: String) |
| 10 | |
| 11 | public static let preferenceKey = "jotleyPrivateICloudSyncEnabled" |
| 12 | public static let containerInfoKey = "JotleyCloudKitContainerIdentifier" |
| 13 | |
| 14 | public static func configuredIdentifier(in info: [String: Any]) -> String? { |
| 15 | guard !LocalPaths.isIsolatedTest(info: info), |
| 16 | let value = info[containerInfoKey] as? String, |
| 17 | value.hasPrefix("iCloud."), value.count > 7, |
| 18 | value.unicodeScalars.allSatisfy({ CharacterSet(charactersIn: "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789.-").contains($0) }) else { return nil } |
| 19 | return value |
| 20 | } |
| 21 | public static func application(info: [String: Any] = Bundle.main.infoDictionary ?? [:], |
| 22 | defaults: UserDefaults = .standard) -> NoteSyncMode { |
| 23 | // A missing preference enables sync; an explicit user opt-out survives upgrades. |
| 24 | let enabled = defaults.object(forKey: preferenceKey) as? Bool ?? true |
| 25 | guard enabled, let identifier = configuredIdentifier(in: info) else { return .localOnly } |
| 26 | return .privateICloud(containerIdentifier: identifier) |
| 27 | } |
| 28 | public var isEnabled: Bool { if case .privateICloud = self { return true }; return false } |
| 29 | |
| 30 | public func storeDescription(at url: URL, inMemory: Bool) throws -> NSPersistentStoreDescription { |
| 31 | let description = NSPersistentStoreDescription(url: url) |
| 32 | if inMemory { description.type = NSInMemoryStoreType } |
| 33 | else { |
| 34 | #if os(iOS) |
| 35 | // A session starts on an unlocked device. Keep encrypted note writes |
| 36 | // available after that first unlock while the microphone runs locked. |
| 37 | description.setOption(FileProtectionType.completeUntilFirstUserAuthentication as NSObject, |
| 38 | forKey: NSPersistentStoreFileProtectionKey) |
| 39 | #endif |
| 40 | // Keep history while local-only so re-enabling sync uses the same store. |
| 41 | description.setOption(true as NSNumber, forKey: NSPersistentHistoryTrackingKey) |
| 42 | description.setOption(true as NSNumber, forKey: NSPersistentStoreRemoteChangeNotificationPostOptionKey) |
| 43 | if case .privateICloud(let identifier) = self { |
| 44 | guard Self.configuredIdentifier(in: [Self.containerInfoKey: identifier]) != nil else { |
| 45 | throw LocalError.message("The iCloud container identifier is invalid. No store was opened.") |
| 46 | } |
| 47 | let options = NSPersistentCloudKitContainerOptions(containerIdentifier: identifier) |
| 48 | options.databaseScope = .private |
| 49 | description.cloudKitContainerOptions = options |
| 50 | } |
| 51 | } |
| 52 | description.shouldMigrateStoreAutomatically = true |
| 53 | description.shouldInferMappingModelAutomatically = true |
| 54 | description.shouldAddStoreAsynchronously = false |
| 55 | return description |
| 56 | } |
| 57 | } |
| 58 | |
| 59 | public enum LocalError: LocalizedError { |
| 60 | case message(String) |
| 61 | public var errorDescription: String? { |
| 62 | switch self { case .message(let text): return text } |
| 63 | } |
| 64 | } |
| 65 | |
| 66 | public enum LocalPaths { |
| 67 | public static let bundleID = "com.protomota.jotley.local-development" |
| 68 | static func isIsolatedTest(info: [String: Any]) -> Bool { |
| 69 | info["JotleyIsolatedLocalTest"] as? Bool == true |
| 70 | } |
| 71 | static func libraryDirectoryName(info: [String: Any]) -> String { |
| 72 | isIsolatedTest(info: info) ? "JotleySignedLocalTest" : "JotleyLocalDevelopment" |
| 73 | } |
| 74 | public static func root() throws -> URL { |
| 75 | let base = try FileManager.default.url(for: .applicationSupportDirectory, |
| 76 | in: .userDomainMask, appropriateFor: nil, create: true) |
| 77 | let root = base.appendingPathComponent(libraryDirectoryName(info: Bundle.main.infoDictionary ?? [:]), isDirectory: true) |
| 78 | try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) |
| 79 | return root |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | /// Never opens the installed cloud app's store. No automatic repair or destructive recovery. |
| 84 | @MainActor |
| 85 | public final class SharedPersistenceController: ObservableObject { |
| 86 | public static let activeNotesPredicate = NSPredicate(format: "trashedAt == nil") |
| 87 | public static let trashedNotesPredicate = NSPredicate(format: "trashedAt != nil") |
| 88 | |
| 89 | public let container: NSPersistentContainer |
| 90 | public let root: URL |
| 91 | public let syncMode: NoteSyncMode |
| 92 | @Published public private(set) var ready = false |
| 93 | @Published public private(set) var errorMessage: String? |
| 94 | private var activeRecording: (noteID: NSManagedObjectID, lease: UUID)? |
| 95 | private var noteOperations: [UUID: NSManagedObjectID] = [:] |
| 96 | |
| 97 | private static let bundledModel: NSManagedObjectModel? = { |
| 98 | #if SWIFT_PACKAGE |
| 99 | let bundle = Bundle.module |
| 100 | #else |
| 101 | let bundle = Bundle.main |
| 102 | #endif |
| 103 | guard let url = bundle.url(forResource: "JotleyNotes", withExtension: "momd") else { return nil } |
| 104 | return NSManagedObjectModel(contentsOf: url) |
| 105 | }() |
| 106 | |
| 107 | public init(root: URL? = nil, inMemory: Bool = false, model: NSManagedObjectModel? = nil, |
| 108 | syncMode: NoteSyncMode = .localOnly) throws { |
| 109 | self.syncMode = inMemory ? .localOnly : syncMode |
| 110 | self.root = try root ?? (inMemory ? FileManager.default.temporaryDirectory.appendingPathComponent("JotleyPreview-\(UUID().uuidString)") : LocalPaths.root()) |
| 111 | try FileManager.default.createDirectory(at: self.root, withIntermediateDirectories: true) |
| 112 | guard let resolvedModel = model ?? Self.bundledModel else { |
| 113 | throw LocalError.message("The bundled notes model could not be loaded. No data was changed.") |
| 114 | } |
| 115 | if self.syncMode.isEnabled { |
| 116 | container = NSPersistentCloudKitContainer(name: "JotleyNotes", managedObjectModel: resolvedModel) |
| 117 | } else { |
| 118 | container = NSPersistentContainer(name: "JotleyNotes", managedObjectModel: resolvedModel) |
| 119 | } |
| 120 | let storeURL = self.root.appendingPathComponent("JotleyNotes.sqlite") |
| 121 | let isNewLibrary = !FileManager.default.fileExists(atPath: storeURL.path) |
| 122 | let description = try self.syncMode.storeDescription(at: storeURL, inMemory: inMemory) |
| 123 | container.persistentStoreDescriptions = [description] |
| 124 | container.loadPersistentStores { [weak self] _, error in |
| 125 | // Synchronous completion on the initiating main thread. |
| 126 | MainActor.assumeIsolated { |
| 127 | self?.errorMessage = error.map { "Unable to open local notes: \($0.localizedDescription). The store was preserved." } |
| 128 | self?.ready = error == nil |
| 129 | } |
| 130 | } |
| 131 | container.viewContext.mergePolicy = NSMergeByPropertyObjectTrumpMergePolicy |
| 132 | container.viewContext.automaticallyMergesChangesFromParent = true |
| 133 | container.viewContext.undoManager = UndoManager() |
| 134 | if ready && !inMemory { |
| 135 | if isNewLibrary, resolvedModel.entitiesByName["Folder"] != nil { |
| 136 | for name in ["Personal", "Study", "Work"] { |
| 137 | // Resolve against this store's model, including isolated test |
| 138 | // stores, rather than Core Data's global subclass lookup. |
| 139 | let folder = NSEntityDescription.insertNewObject(forEntityName: "Folder", into: context) |
| 140 | folder.setValue(UUID(), forKey: "id") |
| 141 | folder.setValue(name, forKey: "name") |
| 142 | folder.setValue(Date(), forKey: "createdAt") |
| 143 | folder.setValue(0, forKey: "sortOrder") |
| 144 | } |
| 145 | try save() |
| 146 | } |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | /// One capture owner per store, independent of which window initiated it. |
| 151 | public func beginRecording(_ note: NSManagedObject) throws -> UUID { |
| 152 | guard ready, note.managedObjectContext === context, !note.isDeleted, |
| 153 | Self.activeNotesPredicate.evaluate(with: note) else { |
| 154 | throw LocalError.message("This note is unavailable.") |
| 155 | } |
| 156 | guard activeRecording == nil else { throw LocalError.message("Finish the current transcription first.") } |
| 157 | guard !noteOperations.values.contains(note.objectID) else { throw LocalError.message("Finish generating this note's content before recording it.") } |
| 158 | if note.objectID.isTemporaryID { try context.obtainPermanentIDs(for: [note]) } |
| 159 | let lease = UUID() |
| 160 | activeRecording = (note.objectID, lease) |
| 161 | return lease |
| 162 | } |
| 163 | public func endRecording(lease: UUID) { |
| 164 | if activeRecording?.lease == lease { activeRecording = nil } |
| 165 | } |
| 166 | |
| 167 | /// Track asynchronous generation across windows; external edits must not |
| 168 | /// race a result that will be saved after an await. |
| 169 | public func beginNoteOperation(for noteID: NSManagedObjectID) -> UUID { |
| 170 | let lease = UUID() |
| 171 | noteOperations[lease] = noteID |
| 172 | return lease |
| 173 | } |
| 174 | public func endNoteOperation(lease: UUID) { noteOperations.removeValue(forKey: lease) } |
| 175 | |
| 176 | public func requireLibraryBackupAccess() throws { |
| 177 | guard ready else { throw LocalError.message(errorMessage ?? "The notes library is unavailable.") } |
| 178 | guard activeRecording == nil, noteOperations.isEmpty else { |
| 179 | throw LocalError.message("Finish transcription and content generation before backing up or restoring notes.") |
| 180 | } |
| 181 | } |
| 182 | |
| 183 | public func requireExternalWriteAccess(to note: NSManagedObject) throws { |
| 184 | guard ready, note.managedObjectContext === context, !note.isDeleted, |
| 185 | Self.activeNotesPredicate.evaluate(with: note) else { |
| 186 | throw LocalError.message("This note is unavailable.") |
| 187 | } |
| 188 | guard activeRecording?.noteID != note.objectID else { |
| 189 | throw LocalError.message("Finish recording this note before modifying it through MCP.") |
| 190 | } |
| 191 | guard !noteOperations.values.contains(note.objectID) else { |
| 192 | throw LocalError.message("Finish generating this note's content before modifying it through MCP.") |
| 193 | } |
| 194 | } |
| 195 | |
| 196 | public func deleteNote(_ note: NSManagedObject) throws { |
| 197 | try setTrashDate(Date(), on: note, expecting: Self.activeNotesPredicate) |
| 198 | } |
| 199 | |
| 200 | public func restoreNote(_ note: NSManagedObject) throws { |
| 201 | try setTrashDate(nil, on: note, expecting: Self.trashedNotesPredicate) |
| 202 | } |
| 203 | |
| 204 | private func setTrashDate(_ date: Date?, on note: NSManagedObject, expecting predicate: NSPredicate) throws { |
| 205 | try checkTrashAccess(to: note, expecting: predicate) |
| 206 | try save() |
| 207 | note.setValue(date, forKey: "trashedAt") |
| 208 | do { try save() } |
| 209 | catch { context.rollback(); throw error } |
| 210 | } |
| 211 | |
| 212 | private func checkTrashAccess(to note: NSManagedObject, expecting predicate: NSPredicate) throws { |
| 213 | guard ready, note.managedObjectContext === context, !note.isDeleted, predicate.evaluate(with: note) else { |
| 214 | throw LocalError.message("This note is unavailable.") |
| 215 | } |
| 216 | guard activeRecording?.noteID != note.objectID else { |
| 217 | throw LocalError.message("Stop this transcription before deleting its note.") |
| 218 | } |
| 219 | guard !noteOperations.values.contains(note.objectID) else { |
| 220 | throw LocalError.message("Finish generating this note's content before moving or deleting it.") |
| 221 | } |
| 222 | } |
| 223 | |
| 224 | public func permanentlyDeleteNotes(_ notes: [NSManagedObject]) throws { |
| 225 | for note in notes { |
| 226 | try checkTrashAccess(to: note, expecting: Self.trashedNotesPredicate) |
| 227 | } |
| 228 | try save() // Rollback below must not discard unrelated pending edits. |
| 229 | let ids = notes.compactMap(\.localNoteID) |
| 230 | var children: [NSManagedObject] = [] |
| 231 | for entity in ["NoteChatMessage", "RecordingMarker"] |
| 232 | where !ids.isEmpty && container.managedObjectModel.entitiesByName[entity] != nil { |
| 233 | let request = NSFetchRequest<NSManagedObject>(entityName: entity) |
| 234 | request.predicate = NSPredicate(format: "noteId IN %@", ids) |
| 235 | children += try context.fetch(request) |
| 236 | } |
| 237 | // Undo must not resurrect permanently deleted notes or their history. |
| 238 | let undoManager = context.undoManager |
| 239 | undoManager?.disableUndoRegistration() |
| 240 | defer { undoManager?.enableUndoRegistration() } |
| 241 | for object in children + notes { context.delete(object) } |
| 242 | do { try save() } |
| 243 | catch { context.rollback(); throw error } |
| 244 | } |
| 245 | |
| 246 | public var context: NSManagedObjectContext { container.viewContext } |
| 247 | public func chatMessages(noteID: UUID) throws -> [LocalChatMessage] { |
| 248 | let request = NSFetchRequest<NSManagedObject>(entityName: "NoteChatMessage") |
| 249 | request.predicate = NSPredicate(format: "noteId == %@", noteID as CVarArg) |
| 250 | request.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: true)] |
| 251 | return try context.fetch(request).compactMap { object in |
| 252 | guard let id = object.value(forKey: "id") as? UUID, |
| 253 | let role = object.value(forKey: "role") as? String, |
| 254 | ["user", "assistant"].contains(role), |
| 255 | let text = object.value(forKey: "content") as? String else { return nil } |
| 256 | return LocalChatMessage(id: id, role: role, content: text, |
| 257 | timestamp: object.value(forKey: "timestamp") as? Date ?? .distantPast) |
| 258 | } |
| 259 | } |
| 260 | public func saveChatMessage(_ message: LocalChatMessage, noteID: UUID) throws { |
| 261 | let noteRequest = NSFetchRequest<NSManagedObject>(entityName: "Note") |
| 262 | noteRequest.predicate = NSPredicate(format: "id == %@ AND trashedAt == nil", noteID as CVarArg) |
| 263 | noteRequest.fetchLimit = 1 |
| 264 | guard ready, ["user", "assistant"].contains(message.role), !message.content.isEmpty, |
| 265 | try !context.fetch(noteRequest).isEmpty else { |
| 266 | throw LocalError.message("This note is unavailable. The answer was not saved.") |
| 267 | } |
| 268 | // Date() can have identical values for quick successive messages, |
| 269 | // particularly in Simulator. Preserve append order after a reload. |
| 270 | let lastRequest = NSFetchRequest<NSManagedObject>(entityName: "NoteChatMessage") |
| 271 | lastRequest.predicate = NSPredicate(format: "noteId == %@", noteID as CVarArg) |
| 272 | lastRequest.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: false)] |
| 273 | lastRequest.fetchLimit = 1 |
| 274 | let previous = try context.fetch(lastRequest).first?.value(forKey: "timestamp") as? Date |
| 275 | let timestamp = previous.map { max(message.timestamp, $0.addingTimeInterval(0.001)) } ?? message.timestamp |
| 276 | let object = NSEntityDescription.insertNewObject(forEntityName: "NoteChatMessage", into: context) |
| 277 | object.setValue(message.id, forKey: "id"); object.setValue(noteID, forKey: "noteId") |
| 278 | object.setValue(message.role, forKey: "role"); object.setValue(message.content, forKey: "content") |
| 279 | object.setValue(timestamp, forKey: "timestamp") |
| 280 | do { try save() } catch { context.delete(object); throw error } |
| 281 | } |
| 282 | public func clearChat(noteID: UUID) throws { |
| 283 | try save() |
| 284 | let request = NSFetchRequest<NSManagedObject>(entityName: "NoteChatMessage") |
| 285 | request.predicate = NSPredicate(format: "noteId == %@", noteID as CVarArg) |
| 286 | for object in try context.fetch(request) { context.delete(object) } |
| 287 | do { try save() } catch { context.rollback(); throw error } |
| 288 | } |
| 289 | public func notes() throws -> [NSManagedObject] { |
| 290 | guard ready else { throw LocalError.message(errorMessage ?? "Local store is unavailable.") } |
| 291 | let request = NSFetchRequest<NSManagedObject>(entityName: "Note") |
| 292 | request.predicate = Self.activeNotesPredicate |
| 293 | request.sortDescriptors = [NSSortDescriptor(key: "timestamp", ascending: false)] |
| 294 | return try context.fetch(request) |
| 295 | } |
| 296 | public func create(title: String, text: String = "", id: UUID = UUID(), noteType: String = "local") throws -> NSManagedObject { |
| 297 | guard ready else { throw LocalError.message("Local store is unavailable.") } |
| 298 | let note = NSEntityDescription.insertNewObject(forEntityName: "Note", into: context) |
| 299 | note.setValue(id, forKey: "id") |
| 300 | note.setValue(Date(), forKey: "timestamp") |
| 301 | note.setValue(title, forKey: "title") |
| 302 | note.setValue(text, forKey: "transcription") |
| 303 | note.setValue(noteType, forKey: "noteType") |
| 304 | do { try save() } |
| 305 | catch { context.delete(note); throw error } |
| 306 | return note |
| 307 | } |
| 308 | /// Commit generated content together, restoring all affected values if the |
| 309 | /// store rejects the save. Preserve other pending edits in the context. |
| 310 | public func tagLibrary() throws -> [LocalTagCandidate] { |
| 311 | let request = NSFetchRequest<NSManagedObject>(entityName: "Tag") |
| 312 | request.relationshipKeyPathsForPrefetching = ["notes"] |
| 313 | return try context.fetch(request).compactMap { tag in |
| 314 | guard let name = tag.value(forKey: "name") as? String, !name.isEmpty else { return nil } |
| 315 | return LocalTagCandidate(name: name, usageCount: (tag.value(forKey: "notes") as? NSSet)?.count ?? 0) |
| 316 | } |
| 317 | } |
| 318 | public func saveNoteChanges(_ note: NSManagedObject, values: [String: Any], replacingTags: [String]? = nil) throws { |
| 319 | try saveNoteChanges(note, values: values, replacingTags: replacingTags, autoFolder: nil) |
| 320 | } |
| 321 | |
| 322 | func saveNoteChanges(_ note: NSManagedObject, values: [String: Any], replacingTags: [String]? = nil, |
| 323 | addingGeneratedTags: [String]? = nil, |
| 324 | autoFolder: LocalNoteFolder?, projectName: String? = nil, filingSource: String = "") throws { |
| 325 | guard ready, note.managedObjectContext === context, !note.isDeleted, |
| 326 | Self.activeNotesPredicate.evaluate(with: note) else { |
| 327 | throw LocalError.message("This note is unavailable.") |
| 328 | } |
| 329 | guard values.keys.allSatisfy({ note.entity.attributesByName[$0] != nil }) else { |
| 330 | throw LocalError.message("Generated content contains an unsupported note field.") |
| 331 | } |
| 332 | let previous = values.keys.map { ($0, note.value(forKey: $0)) } |
| 333 | var previousTags: NSSet? |
| 334 | var createdTags: [NSManagedObject] = [] |
| 335 | var createdFolder: NSManagedObject? |
| 336 | var assignedFolder = false |
| 337 | do { |
| 338 | if let tagNames = replacingTags ?? addingGeneratedTags { |
| 339 | let request = NSFetchRequest<NSManagedObject>(entityName: "Tag") |
| 340 | request.relationshipKeyPathsForPrefetching = ["notes"] |
| 341 | let existing = try context.fetch(request).sorted { |
| 342 | let lhs = ($0.value(forKey: "notes") as? NSSet)?.count ?? 0 |
| 343 | let rhs = ($1.value(forKey: "notes") as? NSSet)?.count ?? 0 |
| 344 | if lhs != rhs { return lhs > rhs } |
| 345 | return $0.objectID.uriRepresentation().absoluteString < $1.objectID.uriRepresentation().absoluteString |
| 346 | } |
| 347 | let library = existing.compactMap { tag -> LocalTagCandidate? in |
| 348 | guard let name = tag.value(forKey: "name") as? String else { return nil } |
| 349 | return LocalTagCandidate(name: name, usageCount: (tag.value(forKey: "notes") as? NSSet)?.count ?? 0) |
| 350 | } |
| 351 | let currentTags = (note.value(forKey: "tags") as? NSSet)?.copy() as? NSSet ?? NSSet() |
| 352 | var selected = replacingTags == nil ? currentTags.allObjects.compactMap { $0 as? NSManagedObject } : [] |
| 353 | let limit = LocalNoteTags.maximumCount - selected.count |
| 354 | let excluded = Set(selected.map { LocalNoteTags.key($0.text("name")) }) |
| 355 | let names = LocalNoteTags.resolvedNames(tagNames, library: library, limit: limit, excluding: excluded) |
| 356 | for name in names { |
| 357 | if let tag = existing.first(where: { LocalNoteTags.key($0.text("name")) == LocalNoteTags.key(name) }) { |
| 358 | selected.append(tag) |
| 359 | } else { |
| 360 | let tag = NSEntityDescription.insertNewObject(forEntityName: "Tag", into: context) |
| 361 | tag.setValue(UUID(), forKey: "id"); tag.setValue(name, forKey: "name") |
| 362 | tag.setValue(name.lowercased().components(separatedBy: CharacterSet.alphanumerics.inverted).joined(), forKey: "canonicalName") |
| 363 | tag.setValue(Date(), forKey: "createdAt") |
| 364 | createdTags.append(tag); selected.append(tag) |
| 365 | } |
| 366 | } |
| 367 | previousTags = currentTags |
| 368 | note.setValue(NSSet(array: selected), forKey: "tags") |
| 369 | } |
| 370 | if let name = autoFolder?.name, note.value(forKey: "folder") == nil { |
| 371 | let request = NSFetchRequest<NSManagedObject>(entityName: "Folder") |
| 372 | request.sortDescriptors = [NSSortDescriptor(key: "createdAt", ascending: true)] |
| 373 | let folders = try context.fetch(request) |
| 374 | let project = projectName?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" |
| 375 | let primaryProject = project.count >= 3 && project.count <= 32 && |
| 376 | project.split(whereSeparator: \.isWhitespace).count <= 4 && |
| 377 | project.contains(where: \.isLetter) && Self.mentionsFolder(project, in: filingSource) ? project : nil |
| 378 | let miscName = LocalNoteFolder.general.name ?? "Misc" |
| 379 | let broadNames = ["Work", "Personal", "Study", "Ideas", "General", miscName] |
| 380 | let projectFolders = folders.filter { folder in |
| 381 | let title = folder.text("name").trimmingCharacters(in: .whitespacesAndNewlines) |
| 382 | return title.count >= 3 && !broadNames.contains { $0.caseInsensitiveCompare(title) == .orderedSame } && |
| 383 | Self.mentionsFolder(title, in: filingSource) |
| 384 | } |
| 385 | let explicitMatch = primaryProject.flatMap { project in |
| 386 | folders.first { $0.text("name").caseInsensitiveCompare(project) == .orderedSame } |
| 387 | } |
| 388 | let existingProject = projectFolders.max { $0.text("name").count < $1.text("name").count } |
| 389 | let broadMatch = folders.first { $0.text("name").caseInsensitiveCompare(name) == .orderedSame } |
| 390 | let miscMatch = folders.first { $0.text("name").caseInsensitiveCompare(miscName) == .orderedSame } |
| 391 | let maxFolders = 10 |
| 392 | var folder = explicitMatch ?? existingProject |
| 393 | if folder == nil { |
| 394 | let canCreateProject = folders.count < maxFolders - 1 || (folders.count < maxFolders && miscMatch != nil) |
| 395 | if let primaryProject, canCreateProject { |
| 396 | createdFolder = insertAutoFolder(named: primaryProject) |
| 397 | folder = createdFolder |
| 398 | } else if let broadMatch { |
| 399 | folder = broadMatch |
| 400 | } else if folders.count < maxFolders - 1 || (folders.count < maxFolders && miscMatch != nil) { |
| 401 | createdFolder = insertAutoFolder(named: name) |
| 402 | folder = createdFolder |
| 403 | } else if let miscMatch { |
| 404 | folder = miscMatch |
| 405 | } else { |
| 406 | // Libraries already at the limit still get one catch-all folder. |
| 407 | createdFolder = insertAutoFolder(named: miscName) |
| 408 | folder = createdFolder |
| 409 | } |
| 410 | } |
| 411 | if let folder { |
| 412 | note.setValue(folder, forKey: "folder") |
| 413 | assignedFolder = true |
| 414 | } |
| 415 | } |
| 416 | for (key, value) in values { note.setValue(value, forKey: key) } |
| 417 | try save() |
| 418 | } catch { |
| 419 | for (key, value) in previous { note.setValue(value, forKey: key) } |
| 420 | if let previousTags { note.setValue(previousTags, forKey: "tags") } |
| 421 | for tag in createdTags { context.delete(tag) } |
| 422 | if assignedFolder { note.setValue(nil, forKey: "folder") } |
| 423 | if let createdFolder { context.delete(createdFolder) } |
| 424 | throw error |
| 425 | } |
| 426 | } |
| 427 | |
| 428 | private static func mentionsFolder(_ name: String, in text: String) -> Bool { |
| 429 | func normalized(_ value: String) -> String { |
| 430 | value.lowercased().split { !$0.isLetter && !$0.isNumber }.joined(separator: " ") |
| 431 | } |
| 432 | let name = normalized(name) |
| 433 | return !name.isEmpty && " \(normalized(text)) ".contains(" \(name) ") |
| 434 | } |
| 435 | |
| 436 | private func insertAutoFolder(named name: String) -> NSManagedObject { |
| 437 | let folder = NSEntityDescription.insertNewObject(forEntityName: "Folder", into: context) |
| 438 | folder.setValue(UUID(), forKey: "id") |
| 439 | folder.setValue(name, forKey: "name") |
| 440 | folder.setValue(Date(), forKey: "createdAt") |
| 441 | return folder |
| 442 | } |
| 443 | |
| 444 | func organizeCompletedRecording(_ note: NSManagedObject, locale: Locale) { |
| 445 | let transcript = note.text("transcription") |
| 446 | guard LocalNoteOrganizationSettings.autoFolders(), note.value(forKey: "folder") == nil, |
| 447 | !transcript.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return } |
| 448 | let id = note.objectID |
| 449 | let lease = beginNoteOperation(for: id) |
| 450 | Task { [weak self] in |
| 451 | guard let self else { return } |
| 452 | defer { self.endNoteOperation(lease: lease) } |
| 453 | let organization = try? await LocalNoteTags.generateOrganization(from: "", transcript: transcript, |
| 454 | library: [], locale: locale, autoTags: false, autoFolder: true) |
| 455 | guard let current = try? self.context.existingObject(with: id), |
| 456 | !current.isDeleted, current.text("transcription") == transcript, |
| 457 | LocalNoteOrganizationSettings.autoFolders(), current.value(forKey: "folder") == nil else { return } |
| 458 | let category = organization?.folder.name == nil ? LocalNoteFolder.inferred(from: transcript) : organization?.folder |
| 459 | do { |
| 460 | try self.saveNoteChanges(current, values: [:], autoFolder: category, |
| 461 | projectName: organization?.projectName, filingSource: transcript) |
| 462 | } catch { |
| 463 | print("Could not organize the completed note: \(error)") |
| 464 | } |
| 465 | } |
| 466 | } |
| 467 | public func save() throws { |
| 468 | guard ready else { throw LocalError.message("Local store is unavailable; no changes were saved.") } |
| 469 | if context.hasChanges { try context.save() } |
| 470 | } |
| 471 | } |
| 472 | |
| 473 | public extension NSManagedObject { |
| 474 | func text(_ key: String) -> String { value(forKey: key) as? String ?? "" } |
| 475 | var localNoteID: UUID? { value(forKey: "id") as? UUID } |
| 476 | } |
| 477 | |
| 478 | public struct LocalUtterance: Codable, Equatable, Sendable { |
| 479 | public var text: String |
| 480 | public var start: Double |
| 481 | public var end: Double |
| 482 | public init(text: String, start: Double, end: Double) { |
| 483 | self.text = text; self.start = start; self.end = end |
| 484 | } |
| 485 | } |
| 486 | |
| 487 | /// Tentative results replace one another; only final results enter the durable transcript. |
| 488 | public struct LocalTranscript: Sendable { |
| 489 | public private(set) var utterances: [LocalUtterance] = [] |
| 490 | public private(set) var tentative = "" |
| 491 | public private(set) var tentativeStart: Double? |
| 492 | public private(set) var tentativeEnd: Double? |
| 493 | public init() {} |
| 494 | public mutating func accept(text: String, start: Double, end: Double, final: Bool) { |
| 495 | if final { |
| 496 | tentative = ""; tentativeStart = nil; tentativeEnd = nil |
| 497 | // A repeated final range replaces that range, rather than duplicating text. |
| 498 | if let index = utterances.firstIndex(where: { abs($0.start - start) < 0.001 }) { |
| 499 | utterances[index] = .init(text: text, start: start, end: end) |
| 500 | } else { utterances.append(.init(text: text, start: start, end: end)) } |
| 501 | utterances.sort { $0.start < $1.start } |
| 502 | } else { tentative = text; tentativeStart = start; tentativeEnd = end } |
| 503 | } |
| 504 | public var text: String { utterances.map(\.text).joined(separator: " ") } |
| 505 | public var displayText: String { [text, tentative].filter { !$0.isEmpty }.joined(separator: " ") } |
| 506 | } |
| 507 | |
| 508 | /// Jotley never saves audio. Removes audio left by earlier versions, confined to |
| 509 | /// the two legacy audio directories. Notes, transcripts and the database stay intact. |
| 510 | public enum LegacyAudioCleanup { |
| 511 | public static func remove(in root: URL, fileManager: FileManager = .default) throws { |
| 512 | for directory in ["Recordings", "DeletedRecordings"] { |
| 513 | let url = root.appendingPathComponent(directory, isDirectory: true) |
| 514 | if fileManager.fileExists(atPath: url.path) { try fileManager.removeItem(at: url) } |
| 515 | } |
| 516 | } |
| 517 | } |