PulseCanvas / app / Sources / PulseCanvas / CloudProjectPackage.swift
| 1 | import Foundation |
| 2 | |
| 3 | struct CloudAudioInfo: Codable, Sendable { |
| 4 | var asset: String |
| 5 | var name: String |
| 6 | var bytes: Int |
| 7 | func validated() throws -> Self { |
| 8 | guard asset.count == 70, asset.hasSuffix(".audio"), |
| 9 | asset.dropLast(6).allSatisfy({ $0.isHexDigit && $0.isASCII }), |
| 10 | !name.isEmpty, name.count < 256, !name.contains("/"), name != ".", name != "..", !name.contains("\0"), |
| 11 | bytes > 0, bytes <= UserBackup.maximumSourceBytes else { throw CocoaError(.fileReadCorruptFile) } |
| 12 | return self |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | struct CloudProjectInfo: Codable, Sendable { |
| 17 | var title: String |
| 18 | var asset: String |
| 19 | var bytes: Int |
| 20 | var nativeOnly: Bool |
| 21 | var audio: CloudAudioInfo? |
| 22 | var isAvailableInEdition: Bool { |
| 23 | #if DIRECT_BUILD && !STORE_BUILD |
| 24 | true |
| 25 | #else |
| 26 | nativeOnly |
| 27 | #endif |
| 28 | } |
| 29 | func validated() throws -> Self { |
| 30 | guard !title.isEmpty, title.count <= 500, asset.count == 69, asset.hasSuffix(".json"), |
| 31 | asset.dropLast(5).allSatisfy({ $0.isHexDigit && $0.isASCII }), |
| 32 | bytes > 0, bytes < 8_000_000 else { throw CocoaError(.fileReadCorruptFile) } |
| 33 | if let audio { _ = try audio.validated() } |
| 34 | return self |
| 35 | } |
| 36 | } |
| 37 | |
| 38 | enum CloudProjectPackage { |
| 39 | static func fingerprint(_ data: Data) throws -> String { |
| 40 | var stamp = data |
| 41 | if let object = try JSONSerialization.jsonObject(with: data) as? [String: Any], |
| 42 | object["bundledSoundtrack"] == nil, let text = object["soundtrack"] as? String, let source = URL(string: text) { |
| 43 | let bookmark = (object["soundtrackBookmark"] as? String).flatMap { Data(base64Encoded: $0) } |
| 44 | let resolved = SecurityScopedAccess.resolve(bookmark: bookmark, fallback: source) |
| 45 | let lease = SecurityScopedAccess(url: resolved) |
| 46 | let values = try resolved.resourceValues(forKeys: [.fileSizeKey, .contentModificationDateKey]) |
| 47 | stamp.append(Data("\(values.fileSize ?? -1)|\(values.contentModificationDate?.timeIntervalSince1970 ?? 0)".utf8)) |
| 48 | withExtendedLifetime(lease) {} |
| 49 | } |
| 50 | return CloudSyncLedger.digest(stamp) |
| 51 | } |
| 52 | static func key(for data: Data, filename: String) throws -> String { |
| 53 | let object = try JSONSerialization.jsonObject(with: data) as? [String: Any] |
| 54 | if let id = object?["cloudProjectID"] as? String, !id.isEmpty, id.count <= 100 { return id } |
| 55 | return CloudSyncLedger.digest(Data(filename.utf8)) |
| 56 | } |
| 57 | static func make(_ data: Data, filename: String, key: String, in workspace: URL) throws -> (info: CloudProjectInfo, project: URL, audio: URL?) { |
| 58 | guard data.count < 8_000_000, var object = try JSONSerialization.jsonObject(with: data) as? [String: Any], |
| 59 | object["version"] as? Int == 1, object["appearance"] is [String: Any] else { throw CocoaError(.fileReadCorruptFile) } |
| 60 | object["cloudProjectID"] = key |
| 61 | try FileManager.default.createDirectory(at: workspace, withIntermediateDirectories: true) |
| 62 | var audioInfo: CloudAudioInfo?, audioFile: URL? |
| 63 | var lease: SecurityScopedAccess? |
| 64 | if object["bundledSoundtrack"] == nil, let text = object["soundtrack"] as? String, let source = URL(string: text) { |
| 65 | guard source.isFileURL else { throw CocoaError(.fileReadCorruptFile) } |
| 66 | let bookmark = (object["soundtrackBookmark"] as? String).flatMap { Data(base64Encoded: $0) } |
| 67 | let resolved = SecurityScopedAccess.resolve(bookmark: bookmark, fallback: source) |
| 68 | lease = SecurityScopedAccess(url: resolved) |
| 69 | let values = try resolved.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]) |
| 70 | guard values.isRegularFile == true, values.isSymbolicLink != true, |
| 71 | (values.fileSize ?? Int.max) <= UserBackup.maximumSourceBytes else { throw CocoaError(.fileReadCorruptFile) } |
| 72 | let staged = workspace.appendingPathComponent(UUID().uuidString) |
| 73 | try FileManager.default.copyItem(at: resolved, to: staged) |
| 74 | let audioAsset = try hashFile(staged) + ".audio" |
| 75 | let destination = workspace.appendingPathComponent(audioAsset) |
| 76 | try FileManager.default.moveItem(at: staged, to: destination) |
| 77 | audioFile = destination |
| 78 | audioInfo = try CloudAudioInfo(asset: audioAsset, name: resolved.lastPathComponent, |
| 79 | bytes: destination.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0).validated() |
| 80 | let portable = URL(fileURLWithPath: "/PulseCanvasCloud/" + source.lastPathComponent) |
| 81 | object["soundtrack"] = portable.absoluteString |
| 82 | } |
| 83 | object = try UserBackup.sanitized(object) as! [String: Any] |
| 84 | let projectData = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]) |
| 85 | let destination = workspace.appendingPathComponent(CloudSyncLedger.digest(projectData) + ".json") |
| 86 | try projectData.write(to: destination, options: .atomic) |
| 87 | withExtendedLifetime(lease) {} |
| 88 | var title = URL(fileURLWithPath: filename).deletingPathExtension().lastPathComponent |
| 89 | if title.count > 17, title.prefix(16).allSatisfy(\.isHexDigit), title.dropFirst(16).hasPrefix("-") { title = String(title.dropFirst(17)) } |
| 90 | let identities = object["effectIdentities"] as? [String: String] ?? [:] |
| 91 | let nativeOnly = !identities.isEmpty && identities.values.allSatisfy { $0.hasPrefix("native:") } |
| 92 | return (try CloudProjectInfo(title: String(title.prefix(500)), asset: destination.lastPathComponent, |
| 93 | bytes: projectData.count, nativeOnly: nativeOnly, audio: audioInfo).validated(), destination, audioFile) |
| 94 | } |
| 95 | static func hashFile(_ url: URL) throws -> String { |
| 96 | UserBackup.hash(try Data(contentsOf: url, options: .alwaysMapped)) |
| 97 | } |
| 98 | static func open(_ info: CloudProjectInfo, key: String, project: URL, audio: URL?, destination: URL) throws -> Data { |
| 99 | _ = try info.validated() |
| 100 | guard try project.resourceValues(forKeys: [.fileSizeKey]).fileSize == info.bytes, |
| 101 | try hashFile(project) + ".json" == info.asset, |
| 102 | var object = try JSONSerialization.jsonObject(with: Data(contentsOf: project)) as? [String: Any], |
| 103 | object["version"] as? Int == 1, object["appearance"] is [String: Any] else { throw CocoaError(.fileReadCorruptFile) } |
| 104 | // Check every downloaded asset before writing local files. |
| 105 | if let expected = info.audio { |
| 106 | guard let audio, try audio.resourceValues(forKeys: [.fileSizeKey]).fileSize == expected.bytes, |
| 107 | try hashFile(audio) + ".audio" == expected.asset else { throw CocoaError(.fileReadCorruptFile) } |
| 108 | } |
| 109 | object = try UserBackup.sanitized(object) as! [String: Any] |
| 110 | if let expected = info.audio, let audio { |
| 111 | try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true) |
| 112 | let localAudio = destination.appendingPathComponent(expected.name) |
| 113 | try FileManager.default.copyItem(at: audio, to: localAudio) |
| 114 | object["soundtrack"] = localAudio.absoluteString |
| 115 | } |
| 116 | object["cloudProjectID"] = key |
| 117 | return try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]) |
| 118 | } |
| 119 | } |