Branchwell

Inkspring / app · inkspring.ai / native-mac / Sources / Inkspring / LocalVideo.swift

Raw 5.6 KB on 3299148fb8af57afc73c4a39f59b66f2ac2bca32
1import AVFoundation
2import CryptoKit
3import Foundation
4
5func fileDigest(_ url: URL, limit: Int64 = 4 * 1024 * 1024 * 1024) throws -> (hash: String, size: Int64) {
6 let input = try FileHandle(forReadingFrom: url)
7 defer { try? input.close() }
8 var digest = SHA256()
9 var size: Int64 = 0
10 while let chunk = try input.read(upToCount: 1024 * 1024), !chunk.isEmpty {
11 size += Int64(chunk.count)
12 guard size <= limit else { throw WorkspaceError("This file exceeds the allowed size.") }
13 digest.update(data: chunk)
14 }
15 return (digest.finalize().map { String(format: "%02x", $0) }.joined(), size)
16}
17
18struct VideoMetadata: Sendable {
19 static let types = ["mp4": "video/mp4", "mov": "video/quicktime", "webm": "video/webm"]
20 let duration: Double
21 let width: Int
22 let height: Int
23 let frameRate: Float
24
25 static func inspect(_ url: URL) async throws -> Self {
26 if url.pathExtension.lowercased() == "webm" {
27 return try await Task.detached(priority: .utility) { try WebMMetadata.inspect(url) }.value
28 }
29 let asset = AVURLAsset(url: url)
30 do {
31 let duration = try await asset.load(.duration).seconds
32 guard duration.isFinite, (0...600).contains(duration), duration > 0,
33 let track = try await asset.loadTracks(withMediaType: .video).first else {
34 throw WorkspaceError("Choose a playable video of up to ten minutes.")
35 }
36 let (dimensions, transform, fps) = try await track.load(.naturalSize, .preferredTransform, .nominalFrameRate)
37 let size = CGRect(origin: .zero, size: dimensions).applying(transform).size
38 guard [size.width, size.height].allSatisfy({ (360...4096).contains($0) }) else {
39 throw WorkspaceError("Video width and height must each be between 360 and 4,096 pixels.")
40 }
41 return Self(duration: duration, width: Int(size.width.rounded()), height: Int(size.height.rounded()), frameRate: fps)
42 } catch let error as WorkspaceError {
43 throw error
44 } catch {
45 try Task.checkCancellation()
46 throw WorkspaceError("This video couldn’t be opened. Try an H.264 MP4 or MOV file.")
47 }
48 }
49}
50
51extension Workspace {
52 func attachVideo(_ source: URL) async throws -> [String: Any] {
53 guard let directory else { throw WorkspaceError("The workspace is unavailable.") }
54 let fileExtension = source.pathExtension.lowercased()
55 let attributes = try source.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey, .contentModificationDateKey])
56 guard let type = VideoMetadata.types[fileExtension],
57 attributes.isRegularFile == true, attributes.isSymbolicLink != true,
58 let size = attributes.fileSize, (1...4 * 1024 * 1024 * 1024).contains(size) else {
59 throw WorkspaceError("Choose a local MP4, MOV, or WebM video up to 4 GB.")
60 }
61 let metadata = try await VideoMetadata.inspect(source)
62 try Task.checkCancellation()
63 let videos = directory.appending(path: "videos", directoryHint: .isDirectory)
64 let originalModification = attributes.contentModificationDate
65 let (target, hash) = try await Task.detached(priority: .utility) {
66 try storeVideo(source, in: videos, expectedSize: size, modification: originalModification)
67 }.value
68 try Task.checkCancellation()
69 var record = WorkspaceRecord.new("local-video")
70 record["name"] = source.lastPathComponent
71 record["path"] = target.path
72 record["hash"] = hash
73 record["type"] = type
74 record.fields["size"] = size
75 record.fields["duration"] = metadata.duration
76 record.fields["width"] = metadata.width
77 record.fields["height"] = metadata.height
78 record.fields["mtime"] = try target.resourceValues(forKeys: [.contentModificationDateKey])
79 .contentModificationDate.map { $0.timeIntervalSince1970 * 1000 }
80 try save(record)
81 return ["id": record.id, "name": record["name"], "size": size, "duration": metadata.duration,
82 "width": metadata.width, "height": metadata.height]
83 }
84}
85
86private func storeVideo(_ source: URL, in directory: URL, expectedSize: Int, modification: Date?) throws -> (URL, String) {
87 let manager = FileManager.default
88 try manager.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700])
89 let media = try fileDigest(source)
90 let target = directory.appending(path: media.hash + "." + source.pathExtension.lowercased())
91 let current = try source.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey])
92 guard media.size == expectedSize, current.fileSize == expectedSize, current.contentModificationDate == modification else {
93 throw WorkspaceError("The video changed while it was being attached.")
94 }
95 if manager.fileExists(atPath: target.path) {
96 guard try fileDigest(target) == media else { throw WorkspaceError("An attached video file has changed.") }
97 } else {
98 let temporary = directory.appending(path: ".attach-\(UUID().uuidString)")
99 defer { try? manager.removeItem(at: temporary) }
100 try manager.copyItem(at: source, to: temporary)
101 guard try fileDigest(temporary) == media else { throw WorkspaceError("The video changed while it was being attached.") }
102 do {
103 try manager.linkItem(at: temporary, to: target)
104 } catch CocoaError.fileWriteFileExists {
105 guard try fileDigest(target) == media else { throw WorkspaceError("An attached video file has changed.") }
106 }
107 }
108 return (target, media.hash)
109}