SPB Git

Repository Public

ProjectPackage.swift 12.4 KB 256 lines swift

1// SP Lecture Studio — LectureStorage2// File: Packages/LectureStorage/Sources/ProjectPackage.swift3// Description: Reads and writes a .slecture package directory (atomic manifest, edits, transcript, waveform cache, PDF copy, checksums).4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import Foundation8import CryptoKit9import LectureCore1011public enum StorageError: Error, Equatable, CustomStringConvertible {12    case notAPackage(String)13    case manifestMissing14    case manifestUnreadable(String)15    case newerSchema(found: Int, supported: Int)16    case pdfMissing17    case alreadyExists(String)18    case io(String)1920    public var description: String {21        switch self {22        case .notAPackage(let p): "not a .slecture package: \(p)"23        case .manifestMissing: "manifest.json is missing"24        case .manifestUnreadable(let m): "manifest.json cannot be read: \(m)"25        case .newerSchema(let f, let s): "project schema \(f) is newer than this version supports (\(s))"26        case .pdfMissing: "the PDF copy is missing from the package"27        case .alreadyExists(let p): "already exists: \(p)"28        case .io(let m): m29        }30    }31}3233public enum Hashing {34    /// Streaming SHA-256 of a file (constant memory).35    public static func sha256(of url: URL) throws -> String {36        let handle = try FileHandle(forReadingFrom: url)37        defer { try? handle.close() }38        var hasher = SHA256()39        while let chunk = try handle.read(upToCount: 1 << 20), !chunk.isEmpty { hasher.update(data: chunk) }40        return hasher.finalize().map { String(format: "%02x", $0) }.joined()41    }42    public static func sha256(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() }43}4445/// Handle on one `.slecture` package directory. All paths stored in the manifest are relative to `url`.46public struct ProjectPackage: Sendable, Hashable {47    public let url: URL48    public init(url: URL) { self.url = url.standardizedFileURL }4950    public func url(_ relative: String) -> URL { url.appendingPathComponent(relative) }51    public var manifestURL: URL { url(ProjectLayout.manifest) }52    public var eventsURL: URL { url(ProjectLayout.events) }53    public var pdfURL: URL { url(ProjectLayout.pdfFile) }54    public var mediaURL: URL { url(ProjectLayout.mediaDirectory) }55    public var exists: Bool { FileManager.default.fileExists(atPath: manifestURL.path) }5657    static func encoder() -> JSONEncoder {58        let e = JSONEncoder(); e.dateEncodingStrategy = .iso8601; e.outputFormatting = [.prettyPrinted, .sortedKeys, .withoutEscapingSlashes]; return e59    }60    static func decoder() -> JSONDecoder { let d = JSONDecoder(); d.dateDecodingStrategy = .iso8601; return d }6162    /// File protection: readable after the first unlock so that a recording can continue while the device is locked.63    static func protect(_ url: URL) {64        #if os(iOS)65        try? FileManager.default.setAttributes([.protectionKey: FileProtectionType.completeUntilFirstUserAuthentication], ofItemAtPath: url.path)66        #endif67    }6869    // MARK: Creation7071    /// Creates a new package in `directory`. The PDF (if any) is copied; the original file is never modified.72    @discardableResult73    public static func create(in directory: URL, manifest: ProjectManifest, pdf: URL? = nil, pdfPageCount: Int = 0) throws -> ProjectPackage {74        let fm = FileManager.default75        try fm.createDirectory(at: directory, withIntermediateDirectories: true)76        let pkg = ProjectPackage(url: uniqueURL(in: directory, baseName: safeFileName(manifest.title)))77        try fm.createDirectory(at: pkg.url, withIntermediateDirectories: false)78        protect(pkg.url)79        for dir in [ProjectLayout.pdfDirectory, ProjectLayout.mediaDirectory, ProjectLayout.cacheDirectory, ProjectLayout.thumbnailsDirectory, ProjectLayout.exportsDirectory] {80            try fm.createDirectory(at: pkg.url(dir), withIntermediateDirectories: true)81        }82        var m = manifest83        if let pdf { m.pdf = try pkg.importPDF(from: pdf, pageCount: pdfPageCount) }84        fm.createFile(atPath: pkg.eventsURL.path, contents: nil)85        try pkg.saveManifest(m)86        return pkg87    }8889    public static func safeFileName(_ title: String) -> String {90        let bad = CharacterSet(charactersIn: "/\\:*?\"<>|\n\r\t").union(.controlCharacters)91        var s = title.components(separatedBy: bad).joined(separator: " ").trimmingCharacters(in: .whitespaces)92        s = s.split(separator: " ", omittingEmptySubsequences: true).joined(separator: " ")93        while s.hasPrefix(".") { s.removeFirst() }94        if s.isEmpty { s = "Lecture" }95        return String(s.prefix(80))96    }9798    public static func uniqueURL(in directory: URL, baseName: String, ext: String = ProjectLayout.packageExtension) -> URL {99        var candidate = directory.appendingPathComponent(baseName).appendingPathExtension(ext)100        var n = 2101        while FileManager.default.fileExists(atPath: candidate.path) {102            candidate = directory.appendingPathComponent("\(baseName) \(n)").appendingPathExtension(ext); n += 1103        }104        return candidate105    }106107    public func importPDF(from source: URL, pageCount: Int) throws -> PDFSource {108        let fm = FileManager.default109        try fm.createDirectory(at: url(ProjectLayout.pdfDirectory), withIntermediateDirectories: true)110        if fm.fileExists(atPath: pdfURL.path) { try fm.removeItem(at: pdfURL) }111        try fm.copyItem(at: source, to: pdfURL)112        Self.protect(pdfURL)113        let size = (try fm.attributesOfItem(atPath: pdfURL.path)[.size] as? NSNumber)?.int64Value ?? 0114        return PDFSource(path: ProjectLayout.pdfFile, originalName: source.lastPathComponent, sha256: try Hashing.sha256(of: pdfURL), byteCount: size, pageCount: pageCount)115    }116117    // MARK: Manifest118119    public func loadManifest() throws -> ProjectManifest {120        guard FileManager.default.fileExists(atPath: manifestURL.path) else { throw StorageError.manifestMissing }121        let data: Data122        do { data = try Data(contentsOf: manifestURL) } catch { throw StorageError.manifestUnreadable(error.localizedDescription) }123        return try ManifestMigrator.decode(data)124    }125126    /// Atomic replace: a crash leaves either the previous manifest or the new one, never a partial file.127    public func saveManifest(_ manifest: ProjectManifest) throws {128        var m = manifest; m.modifiedAt = Date(); m.schemaVersion = ProjectManifest.currentSchema129        try Self.writeAtomically(try Self.encoder().encode(m), to: manifestURL)130    }131132    static func writeAtomically(_ data: Data, to url: URL) throws {133        try data.write(to: url, options: [.atomic])134        protect(url)135    }136137    // MARK: Events, edits, transcript, caches138139    public func loadEvents() -> EventCoding.ParseResult {140        guard let data = try? Data(contentsOf: eventsURL) else { return EventCoding.ParseResult() }141        return EventCoding.parse(data)142    }143144    public func loadEdits() -> EditHistory {145        guard let data = try? Data(contentsOf: url(ProjectLayout.edits)), let h = try? Self.decoder().decode(EditHistory.self, from: data) else { return EditHistory() }146        return h147    }148    public func saveEdits(_ history: EditHistory) throws {149        let e = JSONEncoder(); e.dateEncodingStrategy = .iso8601; e.outputFormatting = [.sortedKeys]150        try Self.writeAtomically(try e.encode(history), to: url(ProjectLayout.edits))151    }152153    public func loadTranscript() -> Transcript? {154        guard let data = try? Data(contentsOf: url(ProjectLayout.transcript)) else { return nil }155        return try? Self.decoder().decode(Transcript.self, from: data)156    }157    public func saveTranscript(_ t: Transcript?) throws {158        let u = url(ProjectLayout.transcript)159        guard let t else { try? FileManager.default.removeItem(at: u); return }160        try Self.writeAtomically(try Self.encoder().encode(t), to: u)161    }162163    public func loadEnvelope() -> Envelope? {164        guard let data = try? Data(contentsOf: url(ProjectLayout.waveform)) else { return nil }165        return try? JSONDecoder().decode(Envelope.self, from: data)166    }167    public func saveEnvelope(_ env: Envelope) throws {168        try FileManager.default.createDirectory(at: url(ProjectLayout.cacheDirectory), withIntermediateDirectories: true)169        try Self.writeAtomically(try JSONEncoder().encode(env), to: url(ProjectLayout.waveform))170    }171172    // MARK: Diagnostics173174    public func diskUsage() -> Int64 { Self.directorySize(url) }175176    public static func directorySize(_ url: URL) -> Int64 {177        guard let e = FileManager.default.enumerator(at: url, includingPropertiesForKeys: [.totalFileAllocatedSizeKey, .isRegularFileKey]) else { return 0 }178        var total: Int64 = 0179        for case let f as URL in e {180            let v = try? f.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .isRegularFileKey])181            if v?.isRegularFile == true { total += Int64(v?.totalFileAllocatedSize ?? 0) }182        }183        return total184    }185186    public struct Diagnostics: Sendable, Hashable {187        public var missingPDF = false188        public var pdfChecksumMismatch = false189        public var missingSegments: [MediaSegment] = []190        public var corruptSegments: [MediaSegment] = []191        public var skippedEventLines = 0192        public var isHealthy: Bool { !missingPDF && !pdfChecksumMismatch && missingSegments.isEmpty && corruptSegments.isEmpty }193    }194195    /// Checks that everything the manifest refers to is present. `deep` also verifies SHA-256 checksums.196    public func diagnose(_ manifest: ProjectManifest, deep: Bool = false) -> Diagnostics {197        var d = Diagnostics()198        let fm = FileManager.default199        if let pdf = manifest.pdf {200            if !fm.fileExists(atPath: url(pdf.path).path) { d.missingPDF = true }201            else if deep, (try? Hashing.sha256(of: url(pdf.path))) != pdf.sha256 { d.pdfChecksumMismatch = true }202        }203        for seg in manifest.sessions.flatMap(\.segments) {204            let u = url(seg.path)205            if !fm.fileExists(atPath: u.path) { d.missingSegments.append(seg) }206            else if deep, let sum = seg.sha256, (try? Hashing.sha256(of: u)) != sum { d.corruptSegments.append(seg) }207        }208        d.skippedEventLines = loadEvents().skippedLines209        return d210    }211212    public static func freeDiskSpace(at url: URL) -> Int64 {213        let v = try? url.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey, .volumeAvailableCapacityKey])214        if let important = v?.volumeAvailableCapacityForImportantUsage, important > 0 { return important }215        return Int64(v?.volumeAvailableCapacity ?? 0)216    }217}218219/// Schema migrations operate on the raw JSON so that old packages keep opening after the model evolves.220public enum ManifestMigrator {221    typealias JSONObject = [String: Any]222223    public static func decode(_ data: Data) throws -> ProjectManifest {224        guard var obj = (try? JSONSerialization.jsonObject(with: data)) as? JSONObject else { throw StorageError.manifestUnreadable("not a JSON object") }225        let version = obj["schemaVersion"] as? Int ?? 1226        if version > ProjectManifest.currentSchema { throw StorageError.newerSchema(found: version, supported: ProjectManifest.currentSchema) }227        var v = version228        while v < ProjectManifest.currentSchema {229            switch v {230            case 1: obj = migrate1to2(obj)231            default: break232            }233            v += 1234        }235        obj["schemaVersion"] = ProjectManifest.currentSchema236        do {237            return try ProjectPackage.decoder().decode(ProjectManifest.self, from: JSONSerialization.data(withJSONObject: obj))238        } catch { throw StorageError.manifestUnreadable(String(describing: error)) }239    }240241    /// Schema 1 (development builds): single `course` string, no `lastPage`, no `publishingDestination`, no `exports`, no `createdWith`.242    static func migrate1to2(_ old: JSONObject) -> JSONObject {243        var o = old244        if o["courseCode"] == nil { o["courseCode"] = (o["course"] as? String) ?? "" }245        o.removeValue(forKey: "course")246        if o["lastPage"] == nil { o["lastPage"] = 0 }247        if o["publishingDestination"] == nil { o["publishingDestination"] = "" }248        if o["exports"] == nil { o["exports"] = [Any]() }249        if o["createdWith"] == nil { o["createdWith"] = "SP Lecture Studio" }250        if o["coverPage"] == nil { o["coverPage"] = 0 }251        if o["archived"] == nil { o["archived"] = false }252        if o["notes"] == nil { o["notes"] = [String: Any]() }253        return o254    }255}256
Files main
Menu

Theme