PulseCanvas / app / visionOS / VisionVideoFile.swift
| 1 | import Foundation |
| 2 | |
| 3 | /// A completed movie outlives the render sheet, a canceled picker and app relaunch. |
| 4 | enum VisionVideoFile { |
| 5 | static var directory: URL { |
| 6 | FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] |
| 7 | .appendingPathComponent("PulseCanvas-Completed-Video", isDirectory: true) |
| 8 | } |
| 9 | static func validate(_ url: URL) throws { |
| 10 | guard url.isFileURL, url.pathExtension.lowercased() == "mp4" else { throw CocoaError(.fileReadCorruptFile) } |
| 11 | let values = try url.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]) |
| 12 | guard values.isRegularFile == true, (values.fileSize ?? 0) > 0 else { throw CocoaError(.fileReadCorruptFile) } |
| 13 | } |
| 14 | static func recover(in directory: URL = Self.directory) -> URL? { |
| 15 | let url = directory.appendingPathComponent("PulseCanvas Video.mp4") |
| 16 | do { try validate(url); return url } catch { return nil } |
| 17 | } |
| 18 | /// Build 4 finished the movie in this temporary folder before its picker crashed. |
| 19 | /// Its final filename appears only after both encoding and audio muxing complete. |
| 20 | static func recoverPreviousRender(in temporary: URL = FileManager.default.temporaryDirectory, |
| 21 | cache: URL = Self.directory) -> URL? { |
| 22 | if let existing = recover(in: cache) { return existing } |
| 23 | let folders = (try? FileManager.default.contentsOfDirectory(at: temporary, |
| 24 | includingPropertiesForKeys: [.contentModificationDateKey], options: .skipsHiddenFiles)) ?? [] |
| 25 | let candidates = folders.filter { $0.lastPathComponent.hasPrefix("Vision-video-") } |
| 26 | .map { $0.appendingPathComponent("PulseCanvas Video.mp4") } |
| 27 | .filter { (try? $0.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true } |
| 28 | .sorted { ((try? $0.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast) |
| 29 | > ((try? $1.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate) ?? .distantPast) } |
| 30 | for url in candidates { if let retained = try? retain(url, in: cache) { return retained } } |
| 31 | return nil |
| 32 | } |
| 33 | static func retain(_ source: URL, in directory: URL = Self.directory) throws -> URL { |
| 34 | try validate(source) |
| 35 | try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) |
| 36 | let destination = directory.appendingPathComponent("PulseCanvas Video.mp4") |
| 37 | if source.standardizedFileURL == destination.standardizedFileURL { return destination } |
| 38 | if FileManager.default.fileExists(atPath: destination.path) { |
| 39 | _ = try FileManager.default.replaceItemAt(destination, withItemAt: source) |
| 40 | } else { try FileManager.default.moveItem(at: source, to: destination) } |
| 41 | return destination |
| 42 | } |
| 43 | } |