SPB Git

Repository Public License

LibraryFiles.swift 6.4 KB 113 lines swift

1//2//  ORIX Audio3//  File: ORIXAudio/Services/LibraryFiles.swift4//  Description: On-disk layout of the library: one folder per recording, sidecar files, capture masters, protection class.5//6//  Author: Simon-Pierre Boucher7//  Contact: contact@spboucher.ai8//9import Foundation10import ORIXAudioCore1112/// Application Support/ORIXAudio/13///   Recordings/<uuid>/   audio.<ext>, waveform.owf, analysis.json, transcript.json, notes.json, edit.json14///   Capture/             <uuid>.caf (PCM master being recorded) + <uuid>.json (session sidecar)15///   Exports/             temporary files handed to the share sheet16enum LibraryFiles {17    /// Files must stay writable while the device is locked (recording in a pocket), so the class is18    /// "protected until first unlock after boot" rather than "complete" — which would fail every write under lock.19    static let protection = FileProtectionType.completeUntilFirstUserAuthentication2021    static let root: URL = {22        let base = (try? FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true))23            ?? FileManager.default.temporaryDirectory24        return make(base.appendingPathComponent("ORIXAudio", isDirectory: true))25    }()26    static let recordings = make(root.appendingPathComponent("Recordings", isDirectory: true))27    static let capture = make(root.appendingPathComponent("Capture", isDirectory: true))28    static var exports: URL { make(FileManager.default.temporaryDirectory.appendingPathComponent("Exports", isDirectory: true)) }2930    @discardableResult static func make(_ url: URL) -> URL {31        if !FileManager.default.fileExists(atPath: url.path) {32            try? FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: [.protectionKey: protection])33        }34        return url35    }3637    static func folder(for id: UUID) -> URL { recordings.appendingPathComponent(id.uuidString, isDirectory: true) }38    static func ensureFolder(for id: UUID) -> URL { make(folder(for: id)) }3940    static func waveformURL(_ id: UUID) -> URL { folder(for: id).appendingPathComponent("waveform.owf") }41    static func analysisURL(_ id: UUID) -> URL { folder(for: id).appendingPathComponent("analysis.json") }42    static func transcriptURL(_ id: UUID) -> URL { folder(for: id).appendingPathComponent("transcript.json") }43    static func notesURL(_ id: UUID) -> URL { folder(for: id).appendingPathComponent("notes.json") }44    static func editURL(_ id: UUID) -> URL { folder(for: id).appendingPathComponent("edit.json") }4546    private static let encoder: JSONEncoder = { let e = JSONEncoder(); e.dateEncodingStrategy = .iso8601; return e }()47    private static let decoder: JSONDecoder = { let d = JSONDecoder(); d.dateDecodingStrategy = .iso8601; return d }()4849    /// Atomic write with the library's protection class: the old file stays intact unless the new one is complete.50    static func write(_ data: Data, to url: URL) throws {51        try data.write(to: url, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication])52    }53    static func save<T: Encodable>(_ value: T, to url: URL) throws { try write(encoder.encode(value), to: url) }54    static func load<T: Decodable>(_ type: T.Type, from url: URL) -> T? {55        guard let data = try? Data(contentsOf: url) else { return nil }56        return try? decoder.decode(type, from: data)57    }5859    static func transcript(_ id: UUID) -> Transcript? { load(Transcript.self, from: transcriptURL(id)) }60    static func analysis(_ id: UUID) -> AnalysisReport? { load(AnalysisReport.self, from: analysisURL(id)) }61    static func notes(_ id: UUID) -> MeetingNotes? { load(MeetingNotes.self, from: notesURL(id)) }62    static func waveform(_ id: UUID) -> WaveformSummary? { (try? Data(contentsOf: waveformURL(id))).flatMap(WaveformSummary.init(serialized:)) }6364    static func freeDiskSpace() -> Int64 {65        let values = try? root.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey])66        return values?.volumeAvailableCapacityForImportantUsage ?? 067    }6869    static func size(of url: URL) -> Int64 { ((try? FileManager.default.attributesOfItem(atPath: url.path)[.size]) as? NSNumber)?.int64Value ?? 0 }7071    static func folderSize(_ id: UUID) -> Int64 {72        let files = (try? FileManager.default.contentsOfDirectory(at: folder(for: id), includingPropertiesForKeys: nil)) ?? []73        return files.reduce(0) { $0 + size(of: $1) }74    }7576    /// A unique, shareable file URL in the temporary Exports folder.77    static func exportURL(name: String, ext: String) -> URL {78        let safe = name.components(separatedBy: CharacterSet(charactersIn: "/\\:?%*|\"<>\n")).joined(separator: "-").trimmingCharacters(in: .whitespaces)79        let dir = make(exports.appendingPathComponent(UUID().uuidString, isDirectory: true))80        return dir.appendingPathComponent("\(safe.isEmpty ? "ORIX Audio" : safe).\(ext)")81    }8283    static func purgeExports() { try? FileManager.default.removeItem(at: exports) }84}8586/// Sidecar written next to a capture master so an interrupted session can be rebuilt.87struct CaptureSidecar: Codable, Sendable {88    var id: UUID89    var title: String90    var startedAt: Date91    var preset: RecordingPreset92    var markers: [Marker]93    var participants: String94    var localeIdentifier: String?9596    var cafURL: URL { LibraryFiles.capture.appendingPathComponent("\(id.uuidString).caf") }97    var url: URL { LibraryFiles.capture.appendingPathComponent("\(id.uuidString).json") }98    func save() { try? LibraryFiles.save(self, to: url) }99    func remove() { try? FileManager.default.removeItem(at: cafURL); try? FileManager.default.removeItem(at: url) }100}101102enum Formatters {103    static func sampleRate(_ hz: Double) -> String {104        let k = hz / 1000105        return k == k.rounded() ? "\(Int(k)) kHz" : String(format: "%.1f kHz", k)106    }107    static func bytes(_ n: Int64) -> String { ByteCountFormatter.string(fromByteCount: n, countStyle: .file) }108    static func frequency(_ hz: Double) -> String { hz >= 1000 ? String(format: "%.2f kHz", hz / 1000) : String(format: "%.0f Hz", hz) }109    static func dB(_ v: Double, unit: String = "dB") -> String { v <= -150 ? "−∞ \(unit)" : String(format: "%.1f %@", v, unit).replacingOccurrences(of: "-", with: "−") }110    static func duration(_ t: Double) -> String { Timecode.clock(t) }111    static func date(_ d: Date) -> String { d.formatted(date: .abbreviated, time: .shortened) }112}113
Files main
Menu

Theme