Jotley / app / Shared / Models / Note+Extensions.swift
| 1 | import CoreData |
| 2 | import Foundation |
| 3 | |
| 4 | private final class TranscriptUtterancesCacheBox: NSObject { |
| 5 | let utterances: [TranscriptUtterance] |
| 6 | let payload: String? |
| 7 | let sourceText: String? |
| 8 | |
| 9 | init(_ utterances: [TranscriptUtterance], payload: String?, sourceText: String?) { |
| 10 | self.utterances = utterances |
| 11 | self.payload = payload |
| 12 | self.sourceText = sourceText |
| 13 | } |
| 14 | |
| 15 | var approximateCost: Int { |
| 16 | (payload?.utf8.count ?? 0) + (sourceText?.utf8.count ?? 0) + |
| 17 | utterances.reduce(0) { $0 + MemoryLayout<TranscriptUtterance>.stride + $1.text.utf8.count } |
| 18 | } |
| 19 | } |
| 20 | |
| 21 | private enum TranscriptUtteranceCache { |
| 22 | static let storage: NSCache<NSString, TranscriptUtterancesCacheBox> = { |
| 23 | let cache = NSCache<NSString, TranscriptUtterancesCacheBox>() |
| 24 | cache.countLimit = 64 |
| 25 | cache.totalCostLimit = 8 * 1024 * 1024 |
| 26 | return cache |
| 27 | }() |
| 28 | } |
| 29 | |
| 30 | public extension Note { |
| 31 | /// Legacy loading placeholders are not meaningful note content. The local |
| 32 | /// inference flow keeps temporary results separately from durable final text. |
| 33 | static let transcriptionLoadingPlaceholders: Set<String> = [ |
| 34 | "Transcribing audio...", |
| 35 | "Loading transcript...", |
| 36 | "Loading content...", |
| 37 | "Transcription in progress..." |
| 38 | ] |
| 39 | |
| 40 | static func isTranscriptionLoadingPlaceholder(_ value: String?) -> Bool { |
| 41 | guard let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines), |
| 42 | !trimmed.isEmpty else { |
| 43 | return false |
| 44 | } |
| 45 | return transcriptionLoadingPlaceholders.contains(trimmed) |
| 46 | } |
| 47 | |
| 48 | static func isMeaningfulSummaryText(_ summary: String?) -> Bool { |
| 49 | guard let trimmedSummary = summary?.trimmingCharacters(in: .whitespacesAndNewlines), |
| 50 | !trimmedSummary.isEmpty else { |
| 51 | return false |
| 52 | } |
| 53 | |
| 54 | return trimmedSummary != "Generating summary..." |
| 55 | } |
| 56 | |
| 57 | var timestampOrNow: Date { |
| 58 | self.timestamp ?? Date() |
| 59 | } |
| 60 | |
| 61 | var titleOrUntitled: String { |
| 62 | guard let trimmedTitle = self.title?.trimmingCharacters(in: .whitespacesAndNewlines), |
| 63 | !trimmedTitle.isEmpty, trimmedTitle != "Untitled", trimmedTitle != "Untitled Note" else { |
| 64 | return String(localized: "Untitled Note") |
| 65 | } |
| 66 | return trimmedTitle |
| 67 | } |
| 68 | |
| 69 | /// Check if the title is an auto-generated date stamp that can be replaced by a summary title |
| 70 | var isAutoGeneratedDateStampTitle: Bool { |
| 71 | guard let title = self.title?.trimmingCharacters(in: .whitespacesAndNewlines), !title.isEmpty else { |
| 72 | return false |
| 73 | } |
| 74 | |
| 75 | // If we have a timestamp, format it and compare |
| 76 | if let timestamp = self.timestamp { |
| 77 | let formattedDate = timestamp.formatted(date: .abbreviated, time: .shortened) |
| 78 | return title == formattedDate |
| 79 | } |
| 80 | |
| 81 | // Fallback: detect common date stamp patterns (e.g., "Jan 18, 3:45 PM") |
| 82 | // Pattern: [Month] [Day], [Time] [AM/PM] |
| 83 | let datePattern = "^[A-Z][a-z]{2}\\s+\\d{1,2},\\s+\\d{1,2}:\\d{2}\\s+[AP]M$" |
| 84 | if let regex = try? NSRegularExpression(pattern: datePattern, options: []) { |
| 85 | let range = NSRange(title.startIndex..., in: title) |
| 86 | return regex.firstMatch(in: title, options: [], range: range) != nil |
| 87 | } |
| 88 | |
| 89 | return false |
| 90 | } |
| 91 | |
| 92 | var hasMeaningfulSummaryText: Bool { |
| 93 | Self.isMeaningfulSummaryText(summary) |
| 94 | } |
| 95 | |
| 96 | var shouldGenerateSummaryTags: Bool { |
| 97 | LocalNoteOrganizationSettings.autoTags() && |
| 98 | tagSet.count < LocalNoteTags.maximumCount && |
| 99 | (tagSet.isEmpty || !hasMeaningfulSummaryText) |
| 100 | } |
| 101 | |
| 102 | func shouldReplaceTitleFromGeneratedSummary(forceReplaceTitle: Bool = false) -> Bool { |
| 103 | if forceReplaceTitle { |
| 104 | return true |
| 105 | } |
| 106 | |
| 107 | let currentTitle = title?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" |
| 108 | return currentTitle.isEmpty || |
| 109 | currentTitle == "Untitled" || |
| 110 | currentTitle == "Untitled Note" || |
| 111 | isAutoGeneratedDateStampTitle |
| 112 | } |
| 113 | |
| 114 | /// Recheck the current title at save time so an edit made during inference wins. |
| 115 | func generatedSummaryValues(_ summary: String, template: String, generatedTitle: String?) -> [String: Any] { |
| 116 | var values: [String: Any] = ["summary": summary, "summaryType": template] |
| 117 | if shouldReplaceTitleFromGeneratedSummary(), |
| 118 | let generatedTitle, !generatedTitle.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { |
| 119 | values["title"] = generatedTitle |
| 120 | } |
| 121 | return values |
| 122 | } |
| 123 | |
| 124 | /// Get tags as a comma-separated string |
| 125 | var tagsAsString: String? { |
| 126 | get { |
| 127 | // If we have Tag entities, convert them to a string |
| 128 | if let tagSet = self.tags as? Set<Tag>, !tagSet.isEmpty { |
| 129 | let tagNames = tagSet.compactMap { $0.name }.sorted() |
| 130 | return tagNames.joined(separator: ", ") |
| 131 | } |
| 132 | return nil |
| 133 | } |
| 134 | } |
| 135 | |
| 136 | /// Get all tag names as an array |
| 137 | var tagNames: [String] { |
| 138 | if let tagSet = self.tags as? Set<Tag>, !tagSet.isEmpty { |
| 139 | return tagSet.compactMap { $0.name }.sorted() |
| 140 | } |
| 141 | return [] |
| 142 | } |
| 143 | |
| 144 | /// Get Tag entities as a Set |
| 145 | var tagSet: Set<Tag> { |
| 146 | return (self.tags as? Set<Tag>) ?? Set() |
| 147 | } |
| 148 | |
| 149 | /// Get the canonical form of a tag for deduplication |
| 150 | static func getCanonicalTag(_ tag: String) -> String { |
| 151 | return tag.lowercased().components(separatedBy: CharacterSet.alphanumerics.inverted).joined() |
| 152 | } |
| 153 | |
| 154 | /// Format a tag for display |
| 155 | static func getFormattedTag(_ tag: String) -> String { |
| 156 | let spacesToDashes = tag.replacingOccurrences(of: " ", with: "-") |
| 157 | let validCharacters = CharacterSet.letters.union(CharacterSet(charactersIn: "-0123456789")) |
| 158 | return spacesToDashes.components(separatedBy: validCharacters.inverted).joined() |
| 159 | } |
| 160 | |
| 161 | /// Add a tag by name, creating a Tag entity if needed |
| 162 | func addTagByName(_ tagName: String, in context: NSManagedObjectContext) throws { |
| 163 | let canonicalName = Note.getCanonicalTag(tagName) |
| 164 | let formattedName = Note.getFormattedTag(tagName) |
| 165 | |
| 166 | // Check if tag already exists on this note |
| 167 | if tagSet.contains(where: { $0.canonicalName == canonicalName }) { |
| 168 | return // Already has this tag |
| 169 | } |
| 170 | guard tagSet.count < LocalNoteTags.maximumCount else { |
| 171 | throw LocalError.message("A note can have up to \(LocalNoteTags.maximumCount) tags. Remove a tag to add another.") |
| 172 | } |
| 173 | |
| 174 | // Fetch or create Tag entity |
| 175 | let fetchRequest: NSFetchRequest<Tag> = Tag.fetchRequest() |
| 176 | fetchRequest.predicate = NSPredicate(format: "canonicalName == %@", canonicalName) |
| 177 | |
| 178 | let existingTags = try context.fetch(fetchRequest) |
| 179 | let tag: Tag |
| 180 | |
| 181 | if let existingTag = existingTags.first { |
| 182 | tag = existingTag |
| 183 | } else { |
| 184 | // Create new Tag entity |
| 185 | tag = Tag(context: context) |
| 186 | tag.id = UUID() |
| 187 | tag.name = formattedName |
| 188 | tag.canonicalName = canonicalName |
| 189 | tag.createdAt = Date() |
| 190 | } |
| 191 | |
| 192 | // Add to relationship |
| 193 | self.addToTags(tag) |
| 194 | } |
| 195 | |
| 196 | // MARK: - Folder Helpers |
| 197 | |
| 198 | /// Assign this note to an existing folder entity. |
| 199 | func assignFolder(_ folder: Folder?) { |
| 200 | self.folder = folder |
| 201 | } |
| 202 | |
| 203 | /// Remove this note from its folder (note becomes unfiled). |
| 204 | func clearFolder() { |
| 205 | self.folder = nil |
| 206 | } |
| 207 | |
| 208 | /// Remove a tag by name |
| 209 | func removeTagByName(_ tagName: String) { |
| 210 | let canonicalName = Note.getCanonicalTag(tagName) |
| 211 | |
| 212 | // Find and remove the tag |
| 213 | if let tagToRemove = tagSet.first(where: { $0.canonicalName == canonicalName }) { |
| 214 | self.removeFromTags(tagToRemove) |
| 215 | } |
| 216 | } |
| 217 | |
| 218 | private var transcriptUtterancesJSONString: String? { |
| 219 | get { value(forKey: "transcriptUtterancesJSON") as? String } |
| 220 | set { setValue(newValue, forKey: "transcriptUtterancesJSON") } |
| 221 | } |
| 222 | |
| 223 | private var transcriptUtterancesCacheKey: NSString { |
| 224 | // Replace this note's previous revision instead of retaining every live update. |
| 225 | objectID.uriRepresentation().absoluteString as NSString |
| 226 | } |
| 227 | |
| 228 | internal var storedTranscriptUtterances: [TranscriptUtterance] { |
| 229 | guard let payload = transcriptUtterancesJSONString, |
| 230 | let data = payload.data(using: .utf8) else { |
| 231 | return [] |
| 232 | } |
| 233 | |
| 234 | do { |
| 235 | return try JSONDecoder().decode([TranscriptUtterance].self, from: data) |
| 236 | } catch { |
| 237 | return [] |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | internal var transcriptUtterances: [TranscriptUtterance] { |
| 242 | let cacheKey = transcriptUtterancesCacheKey |
| 243 | let payload = transcriptUtterancesJSONString |
| 244 | let sourceText = transcription |
| 245 | if let cached = TranscriptUtteranceCache.storage.object(forKey: cacheKey), |
| 246 | cached.payload == payload, cached.sourceText == sourceText { |
| 247 | return cached.utterances |
| 248 | } |
| 249 | |
| 250 | let stored = storedTranscriptUtterances |
| 251 | let resolved: [TranscriptUtterance] |
| 252 | |
| 253 | if !stored.isEmpty { |
| 254 | resolved = stored.contains { $0.timestampLabel != nil } |
| 255 | ? stored |
| 256 | : TranscriptUtterance.displayParagraphs(stored) |
| 257 | } else { |
| 258 | let fallback = TranscriptUtterance.fallbackUtterances(from: transcription ?? "") |
| 259 | resolved = fallback.contains { $0.timestampLabel != nil } |
| 260 | ? fallback |
| 261 | : TranscriptUtterance.coalescedForDisplay(fallback) |
| 262 | } |
| 263 | |
| 264 | let cached = TranscriptUtterancesCacheBox(resolved, payload: payload, sourceText: sourceText) |
| 265 | TranscriptUtteranceCache.storage.setObject(cached, forKey: cacheKey, cost: cached.approximateCost) |
| 266 | return resolved |
| 267 | } |
| 268 | |
| 269 | internal func setTranscriptUtterances(_ utterances: [TranscriptUtterance]) { |
| 270 | let sanitized = TranscriptUtterance.coalescedForDisplay(utterances) |
| 271 | |
| 272 | guard !sanitized.isEmpty else { |
| 273 | transcriptUtterancesJSONString = nil |
| 274 | TranscriptUtteranceCache.storage.removeObject(forKey: transcriptUtterancesCacheKey) |
| 275 | return |
| 276 | } |
| 277 | |
| 278 | do { |
| 279 | let data = try JSONEncoder().encode(sanitized) |
| 280 | transcriptUtterancesJSONString = String(data: data, encoding: .utf8) |
| 281 | let cached = TranscriptUtterancesCacheBox(sanitized, payload: transcriptUtterancesJSONString, sourceText: transcription) |
| 282 | TranscriptUtteranceCache.storage.setObject(cached, forKey: transcriptUtterancesCacheKey, cost: cached.approximateCost) |
| 283 | } catch { |
| 284 | transcriptUtterancesJSONString = nil |
| 285 | TranscriptUtteranceCache.storage.removeObject(forKey: transcriptUtterancesCacheKey) |
| 286 | } |
| 287 | } |
| 288 | } |
| 289 | |
| 290 | // Save text and its display paragraphs together, preserving unrelated note fields. |
| 291 | extension Note { |
| 292 | @MainActor func saveEditedTranscript(_ draft: TranscriptEditDraft, in store: SharedPersistenceController) throws { |
| 293 | guard (transcription ?? "") == draft.originalText, |
| 294 | storedTranscriptUtterances == draft.originalUtterances else { |
| 295 | throw LocalError.message("This transcript changed while you were editing. Close the editor and reopen it to edit the latest text.") |
| 296 | } |
| 297 | guard draft.hasChanges else { return } |
| 298 | try store.saveNoteChanges(self, values: ["transcription": draft.text, |
| 299 | "transcriptUtterancesJSON": String(decoding: try JSONEncoder().encode(draft.savedUtterances), as: UTF8.self)]) |
| 300 | } |
| 301 | |
| 302 | @MainActor func saveEditedSummary(_ text: String, original: String, in store: SharedPersistenceController) throws { |
| 303 | guard (summary ?? "") == original else { |
| 304 | throw LocalError.message("This summary changed while you were editing. Close the editor and reopen it to edit the latest text.") |
| 305 | } |
| 306 | guard text != original else { return } |
| 307 | try store.saveNoteChanges(self, values: ["summary": text]) |
| 308 | } |
| 309 | |
| 310 | @MainActor func saveEditedTranscript(_ text: String, original: String, in store: SharedPersistenceController) throws { |
| 311 | guard (transcription ?? "") == original else { |
| 312 | throw LocalError.message("This transcript changed while you were editing. Close the editor and reopen it to edit the latest text.") |
| 313 | } |
| 314 | guard text != original else { return } |
| 315 | let paragraphs = TranscriptUtterance.fallbackUtterances(from: text) |
| 316 | try store.saveNoteChanges(self, values: ["transcription": text, |
| 317 | "transcriptUtterancesJSON": String(decoding: try JSONEncoder().encode(paragraphs), as: UTF8.self)]) |
| 318 | } |
| 319 | } |