Repository Public License
1//2// ORIX Audio3// File: ORIXAudio/Services/AppModel.swift4// Description: Root object: SwiftData container, library operations, services wiring, optional biometric lock.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8//9import Foundation10import LocalAuthentication11import Observation12import ORIXAudioCore13import SwiftData14import SwiftUI1516@MainActor @Observable17final class AppModel {18 let container: ModelContainer19 let context: ModelContext20 let settings: AppSettings21 let recorder: RecorderController22 let processing: ProcessingCenter23 let playback = PlaybackEngine()24 let actions: ActionRunner2526 private(set) var recoverable: [RecoverableCapture] = []27 private(set) var isLocked = false28 private(set) var importProgress: Double?29 var importError: String?30 /// Recording the UI should open (after stop, import or recovery).31 var pendingOpen: UUID?32 static let trashRetention: TimeInterval = 30 * 24 * 36003334 init(inMemory: Bool = false) {35 let schema = Schema([Recording.self, Folder.self, Workflow.self])36 let configuration = ModelConfiguration(schema: schema, isStoredInMemoryOnly: inMemory)37 // If the store can't be opened the audio files are still on disk; fall back to memory so the app stays usable.38 container = (try? ModelContainer(for: schema, configurations: configuration))39 ?? (try! ModelContainer(for: schema, configurations: ModelConfiguration(schema: schema, isStoredInMemoryOnly: true)))40 context = container.mainContext41 settings = AppSettings()42 recorder = RecorderController(settings: settings)43 processing = ProcessingCenter(context: context)44 actions = ActionRunner()45 actions.model = self46 isLocked = settings.requireBiometrics47 recorder.onFinished = { [weak self] result, sidecar in self?.store(result, sidecar: sidecar) }48 RecorderController.endStaleActivities()49 Workflow.seedDefaults(in: context, defaults: settings.defaults, localeIdentifier: settings.transcriptionLocaleIdentifier)50 purgeExpiredTrash()51 refreshRecoverable()52 LibraryFiles.purgeExports()53 }5455 // MARK: Library5657 @discardableResult58 func store(_ result: FinalizedRecording, sidecar: CaptureSidecar, recovered: Bool = false) -> Recording {59 let recording = Recording(id: result.id, title: sidecar.title, createdAt: sidecar.startedAt, kind: sidecar.preset.kind, source: .recorded,60 info: result.info, fileName: result.fileName)61 recording.markers = sidecar.markers62 recording.participants = sidecar.participants63 recording.localeIdentifier = sidecar.localeIdentifier64 context.insert(recording)65 try? context.save()66 postProcess(recording, trigger: .afterRecording)67 if !recovered { pendingOpen = recording.id }68 return recording69 }7071 private func postProcess(_ recording: Recording, trigger: WorkflowTrigger) {72 let automatic = ((try? context.fetch(FetchDescriptor<Workflow>())) ?? []).filter { $0.trigger == trigger }73 if automatic.isEmpty {74 if settings.analyzeAutomatically { processing.analyzeInBackground(recording) }75 } else {76 Task {77 if settings.analyzeAutomatically { try? await processing.analyze(recording) }78 for workflow in automatic { await actions.run(workflow, on: [recording]) }79 }80 }81 }8283 func importFiles(_ urls: [URL]) async {84 importError = nil85 for (i, url) in urls.enumerated() {86 importProgress = Double(i) / Double(urls.count)87 do {88 let count = Double(urls.count)89 let media = try await MediaImporter.importFile(at: url) { [weak self] p in Task { @MainActor in self?.importProgress = (Double(i) + p) / count } }90 let title = (media.originalName as NSString).deletingPathExtension91 let recording = Recording(id: media.id, title: title, kind: .imported, source: media.isVideo ? .importedVideo : .importedAudio, info: media.info, fileName: media.fileName)92 recording.originalFileName = media.originalName93 context.insert(recording)94 try? context.save()95 postProcess(recording, trigger: .afterImport)96 if urls.count == 1 { pendingOpen = recording.id }97 } catch {98 importError = "\(url.lastPathComponent): \(CoreText.describe(error))"99 }100 }101 importProgress = nil102 }103104 /// Adds a rendered audio file (editor "save as new", ORIX Actions) as a new recording. `produce` writes the file at the URL it is given.105 func addDerivedRecording(from original: Recording, titleSuffix: String, format: AudioExportFormat, produce: @Sendable @escaping (URL) throws -> Void) async throws -> Recording {106 let id = UUID()107 let folder = LibraryFiles.ensureFolder(for: id)108 let fileName = "audio.\(format.fileExtension)"109 let url = folder.appendingPathComponent(fileName)110 do {111 var info = try await Task.detached(priority: .userInitiated) { () throws -> AudioFileInfo in112 try produce(url)113 return try AudioFileReader.info(url: url)114 }.value115 info.fileName = fileName116 let recording = Recording(id: id, title: "\(original.title) \(titleSuffix)", kind: original.kind, source: .edited, info: info, fileName: fileName)117 recording.participants = original.participants118 recording.localeIdentifier = original.localeIdentifier119 recording.folder = original.folder120 context.insert(recording)121 try? context.save()122 if settings.analyzeAutomatically { processing.analyzeInBackground(recording) }123 return recording124 } catch {125 try? FileManager.default.removeItem(at: folder)126 throw error127 }128 }129130 func duplicate(_ recording: Recording) {131 let id = UUID()132 let destination = LibraryFiles.folder(for: id)133 guard (try? FileManager.default.copyItem(at: LibraryFiles.folder(for: recording.id), to: destination)) != nil,134 var info = try? AudioFileReader.info(url: destination.appendingPathComponent(recording.fileName)) else { return }135 info.fileName = recording.fileName136 let copy = Recording(id: id, title: String(localized: "\(recording.title) copy"), kind: recording.kind, source: recording.source, info: info, fileName: recording.fileName)137 copy.markersData = recording.markersData; copy.notes = recording.notes; copy.participants = recording.participants138 copy.transcriptStatusRaw = recording.transcriptStatusRaw; copy.analysisStatusRaw = recording.analysisStatusRaw; copy.hasNotes = recording.hasNotes139 copy.localeIdentifier = recording.localeIdentifier; copy.folder = recording.folder; copy.originalFileName = recording.originalFileName140 copy.peakDBFS = recording.peakDBFS; copy.integratedLUFS = recording.integratedLUFS141 context.insert(copy)142 try? context.save()143 }144145 func moveToTrash(_ recording: Recording) {146 if playback.loadedURL == recording.audioURL { playback.unload() }147 recording.deletedAt = .now148 try? context.save()149 }150151 func restore(_ recording: Recording) { recording.deletedAt = nil; try? context.save() }152153 /// Permanently removes the recording and every file derived from it.154 func purge(_ recording: Recording) {155 if playback.loadedURL == recording.audioURL { playback.unload() }156 try? FileManager.default.removeItem(at: LibraryFiles.folder(for: recording.id))157 context.delete(recording)158 try? context.save()159 }160161 private func purgeExpiredTrash() {162 let cutoff = Date.now.addingTimeInterval(-Self.trashRetention)163 let expired = (try? context.fetch(FetchDescriptor<Recording>(predicate: #Predicate { $0.deletedAt != nil }))) ?? []164 for r in expired where (r.deletedAt ?? .now) < cutoff { purge(r) }165 }166167 func recording(_ id: UUID) -> Recording? {168 try? context.fetch(FetchDescriptor<Recording>(predicate: #Predicate { $0.id == id })).first169 }170171 // MARK: Recovery172173 func refreshRecoverable() { recoverable = RecordingRecovery.scan(excluding: recorder.activeSessionID) }174175 func recover(_ capture: RecoverableCapture) async {176 do {177 let sidecar = capture.sidecar178 let result = try await Task.detached(priority: .userInitiated) { try RecordingFinalizer.finalize(sidecar) }.value179 var s = sidecar180 if !s.title.hasPrefix("↺") { s.title = "↺ " + s.title }181 let recording = store(result, sidecar: s, recovered: true)182 pendingOpen = recording.id183 } catch {184 importError = error.localizedDescription185 }186 refreshRecoverable()187 }188189 func discard(_ capture: RecoverableCapture) { capture.sidecar.remove(); refreshRecoverable() }190191 // MARK: Lock192193 func lockIfNeeded() { if settings.requireBiometrics, !recorder.isActive { isLocked = true } }194195 func unlock() async {196 guard isLocked else { return }197 let context = LAContext()198 var error: NSError?199 guard context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) else { isLocked = false; return } // no passcode set: nothing to lock with200 if (try? await context.evaluatePolicy(.deviceOwnerAuthentication, localizedReason: String(localized: "Unlock your recording library"))) == true { isLocked = false }201 }202}203204extension Workflow {205 /// Starter workflows, created once. They are ordinary workflows: editable and deletable.206 static func seedDefaults(in context: ModelContext, defaults: UserDefaults, localeIdentifier: String) {207 // Seeded once per library: never re-created after the user deletes them, but present in a brand-new store.208 let existing = (try? context.fetchCount(FetchDescriptor<Workflow>())) ?? 0209 guard existing == 0, !defaults.bool(forKey: "workflowsSeeded") else { return }210 defaults.set(true, forKey: "workflowsSeeded")211 context.insert(Workflow(name: String(localized: "Meeting notes"), steps: [.analyze, .transcribe(localeIdentifier: localeIdentifier), .summarize, .exportTranscript(format: .markdown)], symbol: "person.3.fill"))212 context.insert(Workflow(name: String(localized: "Clean up voice"), steps: [.analyze, .removeSilence(minimumSeconds: 1.5), .enhance(noiseReduction: 0.5, voice: true, highPassHz: 80), .normalize(targetPeakDBFS: -1), .convert(format: .aac)], symbol: "wand.and.stars"))213 context.insert(Workflow(name: String(localized: "Archive as lossless"), steps: [.convert(format: .alac), .analyze, .exportReport], symbol: "archivebox.fill"))214 context.insert(Workflow(name: String(localized: "Subtitles"), steps: [.transcribe(localeIdentifier: localeIdentifier), .exportTranscript(format: .srt), .exportTranscript(format: .vtt)], symbol: "captions.bubble.fill"))215 try? context.save()216 }217}218