import CoreData import Foundation private final class TranscriptUtterancesCacheBox: NSObject { let utterances: [TranscriptUtterance] let payload: String? let sourceText: String? init(_ utterances: [TranscriptUtterance], payload: String?, sourceText: String?) { self.utterances = utterances self.payload = payload self.sourceText = sourceText } var approximateCost: Int { (payload?.utf8.count ?? 0) + (sourceText?.utf8.count ?? 0) + utterances.reduce(0) { $0 + MemoryLayout.stride + $1.text.utf8.count } } } private enum TranscriptUtteranceCache { static let storage: NSCache = { let cache = NSCache() cache.countLimit = 64 cache.totalCostLimit = 8 * 1024 * 1024 return cache }() } public extension Note { /// Legacy loading placeholders are not meaningful note content. The local /// inference flow keeps temporary results separately from durable final text. static let transcriptionLoadingPlaceholders: Set = [ "Transcribing audio...", "Loading transcript...", "Loading content...", "Transcription in progress..." ] static func isTranscriptionLoadingPlaceholder(_ value: String?) -> Bool { guard let trimmed = value?.trimmingCharacters(in: .whitespacesAndNewlines), !trimmed.isEmpty else { return false } return transcriptionLoadingPlaceholders.contains(trimmed) } static func isMeaningfulSummaryText(_ summary: String?) -> Bool { guard let trimmedSummary = summary?.trimmingCharacters(in: .whitespacesAndNewlines), !trimmedSummary.isEmpty else { return false } return trimmedSummary != "Generating summary..." } var timestampOrNow: Date { self.timestamp ?? Date() } var titleOrUntitled: String { guard let trimmedTitle = self.title?.trimmingCharacters(in: .whitespacesAndNewlines), !trimmedTitle.isEmpty, trimmedTitle != "Untitled", trimmedTitle != "Untitled Note" else { return String(localized: "Untitled Note") } return trimmedTitle } /// Check if the title is an auto-generated date stamp that can be replaced by a summary title var isAutoGeneratedDateStampTitle: Bool { guard let title = self.title?.trimmingCharacters(in: .whitespacesAndNewlines), !title.isEmpty else { return false } // If we have a timestamp, format it and compare if let timestamp = self.timestamp { let formattedDate = timestamp.formatted(date: .abbreviated, time: .shortened) return title == formattedDate } // Fallback: detect common date stamp patterns (e.g., "Jan 18, 3:45 PM") // Pattern: [Month] [Day], [Time] [AM/PM] let datePattern = "^[A-Z][a-z]{2}\\s+\\d{1,2},\\s+\\d{1,2}:\\d{2}\\s+[AP]M$" if let regex = try? NSRegularExpression(pattern: datePattern, options: []) { let range = NSRange(title.startIndex..., in: title) return regex.firstMatch(in: title, options: [], range: range) != nil } return false } var hasMeaningfulSummaryText: Bool { Self.isMeaningfulSummaryText(summary) } var shouldGenerateSummaryTags: Bool { LocalNoteOrganizationSettings.autoTags() && tagSet.count < LocalNoteTags.maximumCount && (tagSet.isEmpty || !hasMeaningfulSummaryText) } func shouldReplaceTitleFromGeneratedSummary(forceReplaceTitle: Bool = false) -> Bool { if forceReplaceTitle { return true } let currentTitle = title?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "" return currentTitle.isEmpty || currentTitle == "Untitled" || currentTitle == "Untitled Note" || isAutoGeneratedDateStampTitle } /// Recheck the current title at save time so an edit made during inference wins. func generatedSummaryValues(_ summary: String, template: String, generatedTitle: String?) -> [String: Any] { var values: [String: Any] = ["summary": summary, "summaryType": template] if shouldReplaceTitleFromGeneratedSummary(), let generatedTitle, !generatedTitle.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { values["title"] = generatedTitle } return values } /// Get tags as a comma-separated string var tagsAsString: String? { get { // If we have Tag entities, convert them to a string if let tagSet = self.tags as? Set, !tagSet.isEmpty { let tagNames = tagSet.compactMap { $0.name }.sorted() return tagNames.joined(separator: ", ") } return nil } } /// Get all tag names as an array var tagNames: [String] { if let tagSet = self.tags as? Set, !tagSet.isEmpty { return tagSet.compactMap { $0.name }.sorted() } return [] } /// Get Tag entities as a Set var tagSet: Set { return (self.tags as? Set) ?? Set() } /// Get the canonical form of a tag for deduplication static func getCanonicalTag(_ tag: String) -> String { return tag.lowercased().components(separatedBy: CharacterSet.alphanumerics.inverted).joined() } /// Format a tag for display static func getFormattedTag(_ tag: String) -> String { let spacesToDashes = tag.replacingOccurrences(of: " ", with: "-") let validCharacters = CharacterSet.letters.union(CharacterSet(charactersIn: "-0123456789")) return spacesToDashes.components(separatedBy: validCharacters.inverted).joined() } /// Add a tag by name, creating a Tag entity if needed func addTagByName(_ tagName: String, in context: NSManagedObjectContext) throws { let canonicalName = Note.getCanonicalTag(tagName) let formattedName = Note.getFormattedTag(tagName) // Check if tag already exists on this note if tagSet.contains(where: { $0.canonicalName == canonicalName }) { return // Already has this tag } guard tagSet.count < LocalNoteTags.maximumCount else { throw LocalError.message("A note can have up to \(LocalNoteTags.maximumCount) tags. Remove a tag to add another.") } // Fetch or create Tag entity let fetchRequest: NSFetchRequest = Tag.fetchRequest() fetchRequest.predicate = NSPredicate(format: "canonicalName == %@", canonicalName) let existingTags = try context.fetch(fetchRequest) let tag: Tag if let existingTag = existingTags.first { tag = existingTag } else { // Create new Tag entity tag = Tag(context: context) tag.id = UUID() tag.name = formattedName tag.canonicalName = canonicalName tag.createdAt = Date() } // Add to relationship self.addToTags(tag) } // MARK: - Folder Helpers /// Assign this note to an existing folder entity. func assignFolder(_ folder: Folder?) { self.folder = folder } /// Remove this note from its folder (note becomes unfiled). func clearFolder() { self.folder = nil } /// Remove a tag by name func removeTagByName(_ tagName: String) { let canonicalName = Note.getCanonicalTag(tagName) // Find and remove the tag if let tagToRemove = tagSet.first(where: { $0.canonicalName == canonicalName }) { self.removeFromTags(tagToRemove) } } private var transcriptUtterancesJSONString: String? { get { value(forKey: "transcriptUtterancesJSON") as? String } set { setValue(newValue, forKey: "transcriptUtterancesJSON") } } private var transcriptUtterancesCacheKey: NSString { // Replace this note's previous revision instead of retaining every live update. objectID.uriRepresentation().absoluteString as NSString } internal var storedTranscriptUtterances: [TranscriptUtterance] { guard let payload = transcriptUtterancesJSONString, let data = payload.data(using: .utf8) else { return [] } do { return try JSONDecoder().decode([TranscriptUtterance].self, from: data) } catch { return [] } } internal var transcriptUtterances: [TranscriptUtterance] { let cacheKey = transcriptUtterancesCacheKey let payload = transcriptUtterancesJSONString let sourceText = transcription if let cached = TranscriptUtteranceCache.storage.object(forKey: cacheKey), cached.payload == payload, cached.sourceText == sourceText { return cached.utterances } let stored = storedTranscriptUtterances let resolved: [TranscriptUtterance] if !stored.isEmpty { resolved = stored.contains { $0.timestampLabel != nil } ? stored : TranscriptUtterance.displayParagraphs(stored) } else { let fallback = TranscriptUtterance.fallbackUtterances(from: transcription ?? "") resolved = fallback.contains { $0.timestampLabel != nil } ? fallback : TranscriptUtterance.coalescedForDisplay(fallback) } let cached = TranscriptUtterancesCacheBox(resolved, payload: payload, sourceText: sourceText) TranscriptUtteranceCache.storage.setObject(cached, forKey: cacheKey, cost: cached.approximateCost) return resolved } internal func setTranscriptUtterances(_ utterances: [TranscriptUtterance]) { let sanitized = TranscriptUtterance.coalescedForDisplay(utterances) guard !sanitized.isEmpty else { transcriptUtterancesJSONString = nil TranscriptUtteranceCache.storage.removeObject(forKey: transcriptUtterancesCacheKey) return } do { let data = try JSONEncoder().encode(sanitized) transcriptUtterancesJSONString = String(data: data, encoding: .utf8) let cached = TranscriptUtterancesCacheBox(sanitized, payload: transcriptUtterancesJSONString, sourceText: transcription) TranscriptUtteranceCache.storage.setObject(cached, forKey: transcriptUtterancesCacheKey, cost: cached.approximateCost) } catch { transcriptUtterancesJSONString = nil TranscriptUtteranceCache.storage.removeObject(forKey: transcriptUtterancesCacheKey) } } } // Save text and its display paragraphs together, preserving unrelated note fields. extension Note { @MainActor func saveEditedTranscript(_ draft: TranscriptEditDraft, in store: SharedPersistenceController) throws { guard (transcription ?? "") == draft.originalText, storedTranscriptUtterances == draft.originalUtterances else { throw LocalError.message("This transcript changed while you were editing. Close the editor and reopen it to edit the latest text.") } guard draft.hasChanges else { return } try store.saveNoteChanges(self, values: ["transcription": draft.text, "transcriptUtterancesJSON": String(decoding: try JSONEncoder().encode(draft.savedUtterances), as: UTF8.self)]) } @MainActor func saveEditedSummary(_ text: String, original: String, in store: SharedPersistenceController) throws { guard (summary ?? "") == original else { throw LocalError.message("This summary changed while you were editing. Close the editor and reopen it to edit the latest text.") } guard text != original else { return } try store.saveNoteChanges(self, values: ["summary": text]) } @MainActor func saveEditedTranscript(_ text: String, original: String, in store: SharedPersistenceController) throws { guard (transcription ?? "") == original else { throw LocalError.message("This transcript changed while you were editing. Close the editor and reopen it to edit the latest text.") } guard text != original else { return } let paragraphs = TranscriptUtterance.fallbackUtterances(from: text) try store.saveNoteChanges(self, values: ["transcription": text, "transcriptUtterancesJSON": String(decoding: try JSONEncoder().encode(paragraphs), as: UTF8.self)]) } }