PulseCanvas / app / Sources / PulseCanvas / UserBackup.swift
| 1 | import CryptoKit |
| 2 | import Foundation |
| 3 | |
| 4 | extension Notification.Name { |
| 5 | static let pulseCanvasOpenBackupProject = Notification.Name("PulseCanvas.openBackupProject") |
| 6 | } |
| 7 | |
| 8 | /// A portable, versioned JSON document, including the audio needed to reopen projects. |
| 9 | /// Only explicitly owned settings and storage are included; never defaults wholesale. |
| 10 | enum UserBackup { |
| 11 | static let startupError: String? = { |
| 12 | do { try activatePendingRestore(); return nil } |
| 13 | catch { return "Restore could not finish: \(error.localizedDescription) Your previous data is still in use." } |
| 14 | }() |
| 15 | static let format = "PulseCanvas User Backup" |
| 16 | static let maximumBytes = 512_000_000 |
| 17 | static let maximumSourceBytes = 100_000_000_000 |
| 18 | static let activeKey = "PulseCanvas.backup.active.v1" |
| 19 | static let preferenceKeys: Set<String> = [ |
| 20 | "PulseCanvas.effectFavorites.v1", "PulseCanvas.effectFavorites.v1.appearances", |
| 21 | "PulseCanvas.metalEffectFavorites.v1", "PulseCanvas.metalEffectFavorites.v1.appearances", |
| 22 | "PulseCanvas.studio.v1", "PulseCanvas.metalStudio.v1", |
| 23 | "PulseCanvas.visualizerPool.v1", "PulseCanvas.metalVisualizerPool.v1", |
| 24 | "PulseCanvas.radio.favoriteSongs.v1", "PulseCanvas.radio.favoriteSongsOnly.v1", |
| 25 | "PulseCanvas.radio.station", "PulseCanvas.radio.bars", "PulseCanvas.radio.volume", |
| 26 | "PulseCanvas.radio.catalogURL", "PulseCanvas.radio.personalCatalog.v1", "PulseCanvas.radio.personalActive.v1", |
| 27 | "PulseCanvas.videoFormat.v1", "PulseCanvas.presentationMatchAspect.v1", "PulseCanvas.onboarding.completed.v1" |
| 28 | ] |
| 29 | |
| 30 | struct File: Codable, Sendable { |
| 31 | var path: String |
| 32 | var originalURL: String |
| 33 | var sha256: String |
| 34 | var data: Data |
| 35 | var byteCount: Int |
| 36 | init(path: String, originalURL: String, sha256: String, data: Data) { |
| 37 | self.path = path; self.originalURL = originalURL; self.sha256 = sha256; self.data = data; byteCount = data.count |
| 38 | } |
| 39 | } |
| 40 | struct Archive: Codable, Sendable { |
| 41 | var format = UserBackup.format |
| 42 | var version = 1 |
| 43 | var id = UUID() |
| 44 | var created = Date() |
| 45 | var platform: String |
| 46 | var preferences: Data |
| 47 | var files: [File] |
| 48 | } |
| 49 | struct Failure: LocalizedError { |
| 50 | let message: String |
| 51 | var errorDescription: String? { message } |
| 52 | } |
| 53 | struct Storage: Sendable { |
| 54 | var documents: URL |
| 55 | var support: URL |
| 56 | var backups: URL |
| 57 | var domain: String |
| 58 | static var standard: Storage { |
| 59 | return Storage(documents: UserDataStorage.defaultDocuments, |
| 60 | support: UserDataStorage.defaultSupport, backups: UserDataStorage.backupRoot, |
| 61 | domain: Bundle.main.bundleIdentifier ?? "PulseCanvas") |
| 62 | } |
| 63 | func root(_ name: String, defaults: UserDefaults) -> URL { |
| 64 | if let text = defaults.string(forKey: activeKey), let id = UUID(uuidString: text) { |
| 65 | return backups.appendingPathComponent("Restores/\(id.uuidString)/\(name)", isDirectory: true) |
| 66 | } |
| 67 | return name == "Documents" ? documents : support |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | static var documents: URL { Storage.standard.root("Documents", defaults: .standard) } |
| 72 | static var support: URL { Storage.standard.root("Support", defaults: .standard) } |
| 73 | |
| 74 | static func savedProjects() -> [URL] { |
| 75 | let root = documents.resolvingSymlinksInPath() |
| 76 | guard let iterator = FileManager.default.enumerator(at: root, includingPropertiesForKeys: [.isRegularFileKey], options: [.skipsHiddenFiles]) else { return [] } |
| 77 | return iterator.compactMap { $0 as? URL }.filter { isProject($0.path) && (try? $0.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true } |
| 78 | .sorted { $0.lastPathComponent.localizedStandardCompare($1.lastPathComponent) == .orderedAscending } |
| 79 | } |
| 80 | |
| 81 | static func hash(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() } |
| 82 | static func fail(_ message: String) -> Failure { Failure(message: message) } |
| 83 | |
| 84 | /// Saved external project files are also retained internally for future backups. |
| 85 | @discardableResult |
| 86 | static func rememberProject(_ data: Data, name: String) throws -> Data { |
| 87 | let folder = documents.appendingPathComponent("Projects", isDirectory: true) |
| 88 | try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) |
| 89 | let filename = String(hash(Data(name.utf8)).prefix(16)) + "-" + URL(fileURLWithPath: name).deletingPathExtension().lastPathComponent + ".pulsecanvas" |
| 90 | var destination = folder.appendingPathComponent(filename) |
| 91 | var portable = data |
| 92 | if var object = try JSONSerialization.jsonObject(with: data) as? [String: Any], object["appearance"] != nil { |
| 93 | if object["cloudProjectID"] == nil { object["cloudProjectID"] = hash(Data(filename.utf8)) } |
| 94 | if let id = object["cloudProjectID"] as? String, |
| 95 | let existing = try FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil).first(where: { url in |
| 96 | guard let saved = try? Data(contentsOf: url), |
| 97 | let value = try? JSONSerialization.jsonObject(with: saved) as? [String: Any] else { return false } |
| 98 | return value["cloudProjectID"] as? String == id |
| 99 | }) { destination = existing } |
| 100 | portable = try JSONSerialization.data(withJSONObject: object, options: [.sortedKeys]) |
| 101 | } |
| 102 | try portable.write(to: destination, options: .atomic) |
| 103 | NotificationCenter.default.post(name: .pulseCanvasUserDataChanged, object: nil) |
| 104 | return portable |
| 105 | } |
| 106 | |
| 107 | static func export(currentProject: Data?, additionalProjects: [URL] = [], platform: String, |
| 108 | defaults: UserDefaults = .standard, storage: Storage = .standard) throws -> Data { |
| 109 | let archive = try collect(currentProject: currentProject, additionalProjects: additionalProjects, platform: platform, defaults: defaults, storage: storage) |
| 110 | guard archive.files.reduce(0, { $0 + $1.byteCount }) < maximumBytes / 2 else { throw fail(String(localized: "Use ZIP export for this music library.")) } |
| 111 | let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys] |
| 112 | let data = try encoder.encode(archive) |
| 113 | guard data.count < maximumBytes else { throw fail(String(localized: "Use ZIP export for this music library.")) } |
| 114 | return data |
| 115 | } |
| 116 | |
| 117 | static func collect(currentProject: Data?, additionalProjects: [URL] = [], platform: String, |
| 118 | defaults: UserDefaults = .standard, storage: Storage = .standard) throws -> Archive { |
| 119 | let fm = FileManager.default |
| 120 | var files: [File] = [] |
| 121 | var sources = Set<String>() |
| 122 | var total = 0 |
| 123 | func add(_ data: Data, at path: String, source: String) throws { |
| 124 | guard safePath(path), !files.contains(where: { $0.path == path }) else { throw fail(String(localized: "Duplicate or invalid backup path.")) } |
| 125 | total += data.count |
| 126 | guard total <= maximumSourceBytes, files.count < 20_000 else { |
| 127 | throw fail(String(localized: "This backup exceeds 100 GB or 20,000 files. Nothing was exported.")) |
| 128 | } |
| 129 | files.append(File(path: path, originalURL: source, sha256: hash(data), data: data)) |
| 130 | if !source.isEmpty { sources.insert(source) } |
| 131 | } |
| 132 | func addURL(_ url: URL, at path: String) throws { |
| 133 | let values = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]) |
| 134 | guard values.isRegularFile == true, values.isSymbolicLink != true, |
| 135 | (values.fileSize ?? maximumSourceBytes + 1) <= maximumSourceBytes else { throw fail(String(localized: "Cannot back up \(url.lastPathComponent). It is missing, too large, or a symbolic link.")) } |
| 136 | try add(Data(contentsOf: url, options: .mappedIfSafe), at: path, source: url.absoluteString) |
| 137 | } |
| 138 | let roots = ["Documents": storage.root("Documents", defaults: defaults), "Support": storage.root("Support", defaults: defaults)] |
| 139 | for name in roots.keys.sorted() { |
| 140 | let root = roots[name]!.resolvingSymlinksInPath() |
| 141 | guard fm.fileExists(atPath: root.path) else { continue } |
| 142 | var readError: Error? |
| 143 | guard let iterator = fm.enumerator(at: root, includingPropertiesForKeys: [.isRegularFileKey, .isSymbolicLinkKey], |
| 144 | options: [.skipsHiddenFiles], errorHandler: { _, error in readError = error; return false }) else { |
| 145 | if fm.fileExists(atPath: root.path) { throw fail(String(localized: "Could not read saved app data.")) } |
| 146 | continue |
| 147 | } |
| 148 | for case let url as URL in iterator { |
| 149 | let relative = String(url.path.dropFirst(root.path.count + 1)) |
| 150 | let values = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey]) |
| 151 | if values.isSymbolicLink == true { throw fail(String(localized: "A saved data folder contains a symbolic link: \(relative)")) } |
| 152 | guard values.isRegularFile == true else { continue } |
| 153 | let component = relative.split(separator: "/").first.map(String.init) ?? "" |
| 154 | let owned = name == "Support" |
| 155 | ? ["PersonalRadio", "StudioMusic", "ProjectM", "ImportedRadio", "CloudProjects"].contains(component) |
| 156 | : ["Projects", "StudioMusic"].contains(component) || ["pulsecanvas", "pulsevision", "mp3", "m4a", "wav", "aiff", "aif", "aac", "caf", "flac"].contains(url.pathExtension.lowercased()) || relative == "Studio-autosave.json" |
| 157 | if owned { try addURL(url, at: name + "/" + relative) } |
| 158 | } |
| 159 | if let readError { throw readError } |
| 160 | } |
| 161 | if let currentProject { |
| 162 | files.removeAll { $0.path == "Documents/Backup-current.pulsecanvas" } |
| 163 | try add(currentProject, at: "Documents/Backup-current.pulsecanvas", source: "") |
| 164 | } |
| 165 | for url in additionalProjects { |
| 166 | let access = SecurityScopedAccess(url: url) |
| 167 | try addURL(url, at: "Documents/Projects/\(UUID().uuidString)-\(url.deletingPathExtension().lastPathComponent).pulsecanvas") |
| 168 | withExtendedLifetime(access) {} |
| 169 | } |
| 170 | // Older Creators libraries may refer to local catalogs rather than an |
| 171 | // app-managed PersonalRadio copy. Retain the catalog's relative structure. |
| 172 | var catalogs: [(URL, Data?)] = [] |
| 173 | if let text = defaults.string(forKey: "PulseCanvas.radio.catalogURL"), let url = URL(string: text), url.isFileURL { |
| 174 | catalogs.append((url, defaults.data(forKey: "PulseCanvas.radio.folderBookmark"))) |
| 175 | } |
| 176 | if let data = defaults.data(forKey: "PulseCanvas.radio.favoriteSongs.v1"), |
| 177 | let songs = try JSONSerialization.jsonObject(with: data) as? [[String: Any]] { |
| 178 | for song in songs { |
| 179 | let bookmark = (song["folderBookmark"] as? String).flatMap { Data(base64Encoded: $0) } |
| 180 | for key in ["sourceURL", "catalogURL"] { |
| 181 | if let text = song[key] as? String, let url = URL(string: text), url.isFileURL { catalogs.append((url, bookmark)) } |
| 182 | } |
| 183 | } |
| 184 | } |
| 185 | for (catalog, bookmark) in catalogs where !sources.contains(catalog.absoluteString) { |
| 186 | let directory = SecurityScopedAccess.resolve(bookmark: bookmark, fallback: catalog.deletingLastPathComponent()) |
| 187 | let access = SecurityScopedAccess(url: directory) |
| 188 | let base = catalog.deletingLastPathComponent().standardizedFileURL |
| 189 | let prefix = "Support/ImportedRadio/" + String(hash(Data(base.absoluteString.utf8)).prefix(16)) + "/" |
| 190 | var queue = [catalog] |
| 191 | while !queue.isEmpty { |
| 192 | let reference = queue.removeLast() |
| 193 | if sources.contains(reference.absoluteString) { continue } |
| 194 | guard reference.standardizedFileURL.path.hasPrefix(base.path + "/") else { throw fail(String(localized: "A local music catalog refers outside its folder.")) } |
| 195 | let relative = String(reference.standardizedFileURL.path.dropFirst(base.path.count + 1)) |
| 196 | let resolved = directory.appendingPathComponent(relative) |
| 197 | try addURL(resolved, at: prefix + relative) |
| 198 | files[files.count - 1].originalURL = reference.absoluteString; sources.insert(reference.absoluteString) |
| 199 | if reference.pathExtension.lowercased() == "json" { |
| 200 | guard files.last!.data.count < 2_000_000, |
| 201 | let json = try JSONSerialization.jsonObject(with: files.last!.data) as? [String: Any], json["version"] as? Int == 1 else { throw fail(String(localized: "Invalid local music catalog.")) } |
| 202 | let records = (json["tracks"] as? [[String: Any]] ?? []) + (json["stations"] as? [[String: Any]] ?? []) |
| 203 | guard records.count <= 500 else { throw fail(String(localized: "Too many entries in a local music catalog.")) } |
| 204 | for record in records { |
| 205 | guard let path = record["audio"] as? String ?? record["catalog"] as? String, |
| 206 | let url = URL(string: path, relativeTo: reference)?.absoluteURL, url.isFileURL else { throw fail(String(localized: "Invalid local music file reference.")) } |
| 207 | queue.append(url) |
| 208 | } |
| 209 | } |
| 210 | } |
| 211 | withExtendedLifetime(access) {} |
| 212 | } |
| 213 | // Follow project soundtrack references, including files outside the sandbox. |
| 214 | // Capture each external source once; references are rewritten on restore. |
| 215 | for file in files where isProject(file.path) { |
| 216 | let object = try JSONSerialization.jsonObject(with: file.data) |
| 217 | for url in referencedFiles(object) where !sources.contains(url.absoluteString) { |
| 218 | let bookmark = (object as? [String: Any])?["soundtrackBookmark"] as? String |
| 219 | let resolved = SecurityScopedAccess.resolve(bookmark: bookmark.flatMap { Data(base64Encoded: $0) }, fallback: url) |
| 220 | let access = SecurityScopedAccess(url: resolved) |
| 221 | // Keep the original filename: the player derives its title from |
| 222 | // it. A unique parent separates different songs with equal names. |
| 223 | try addURL(resolved, at: "Documents/BackupAudio/\(UUID().uuidString)/\(url.lastPathComponent)") |
| 224 | files[files.count - 1].originalURL = url.absoluteString; sources.insert(url.absoluteString) |
| 225 | withExtendedLifetime(access) {} |
| 226 | } |
| 227 | } |
| 228 | for index in files.indices where isProject(files[index].path) { |
| 229 | let data = try JSONSerialization.data(withJSONObject: sanitized(JSONSerialization.jsonObject(with: files[index].data)), options: [.sortedKeys]) |
| 230 | files[index].data = data; files[index].sha256 = hash(data); files[index].byteCount = data.count |
| 231 | } |
| 232 | var preferences: [String: Any] = [:] |
| 233 | for key in preferenceKeys { |
| 234 | if let value = defaults.object(forKey: key) { |
| 235 | // UserDefaults stores URLs as bookmark data; export a plain URL instead. |
| 236 | if key == "PulseCanvas.radio.personalCatalog.v1", let url = defaults.url(forKey: key) { |
| 237 | preferences[key] = url.absoluteString |
| 238 | } else { preferences[key] = try sanitized(value) } |
| 239 | } |
| 240 | } |
| 241 | let plist = try PropertyListSerialization.data(fromPropertyList: preferences, format: .binary, options: 0) |
| 242 | let archive = Archive(platform: platform, preferences: plist, files: files) |
| 243 | try validate(archive) |
| 244 | return archive |
| 245 | } |
| 246 | |
| 247 | static func read(_ url: URL) throws -> Archive { |
| 248 | guard (try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? maximumBytes) < maximumBytes else { throw fail(String(localized: "This backup is too large.")) } |
| 249 | return try decode(Data(contentsOf: url, options: .mappedIfSafe)) |
| 250 | } |
| 251 | static func decode(_ data: Data) throws -> Archive { |
| 252 | guard data.count < maximumBytes else { throw fail(String(localized: "This backup is too large.")) } |
| 253 | let archive = try JSONDecoder().decode(Archive.self, from: data) |
| 254 | try validate(archive) |
| 255 | return archive |
| 256 | } |
| 257 | static func validate(_ archive: Archive) throws { |
| 258 | guard archive.format == format, archive.version == 1, archive.files.count <= 20_000, |
| 259 | ["macOS", "iOS", "visionOS"].contains(archive.platform), |
| 260 | archive.preferences.count < 32_000_000 else { throw fail(String(localized: "Choose a supported PulseCanvas user backup.")) } |
| 261 | let values = try preferenceValues(archive) |
| 262 | guard Set(values.keys).isSubset(of: preferenceKeys) else { throw fail(String(localized: "This backup includes unsupported settings.")) } |
| 263 | try validatePreferences(values) |
| 264 | var paths = Set<String>(), total = 0 |
| 265 | for file in archive.files { |
| 266 | total += file.data.count |
| 267 | guard total <= maximumSourceBytes, file.byteCount == file.data.count, safePath(file.path), paths.insert(file.path.lowercased()).inserted, |
| 268 | hash(file.data) == file.sha256 else { throw fail(String(localized: "The backup contains a damaged or duplicate file.")) } |
| 269 | if !file.originalURL.isEmpty { |
| 270 | guard let url = URL(string: file.originalURL), url.isFileURL, url.user == nil, url.password == nil else { throw fail(String(localized: "Invalid original file location.")) } |
| 271 | } |
| 272 | if isProject(file.path) { |
| 273 | let object = try JSONSerialization.jsonObject(with: file.data) |
| 274 | guard let project = object as? [String: Any], project["version"] as? Int == 1, |
| 275 | project["scene"] is NSNumber || project["clips"] is [Any] else { throw fail(String(localized: "A project in the backup is invalid.")) } |
| 276 | } |
| 277 | } |
| 278 | // A file must never also be the parent of another entry. |
| 279 | for path in paths { |
| 280 | var components = path.split(separator: "/"); components.removeLast() |
| 281 | while components.count > 1 { |
| 282 | guard !paths.contains(components.joined(separator: "/")) else { throw fail(String(localized: "Conflicting backup paths.")) } |
| 283 | components.removeLast() |
| 284 | } |
| 285 | } |
| 286 | let sources = Set(archive.files.map(\.originalURL)) |
| 287 | for file in archive.files where isProject(file.path) { |
| 288 | for url in referencedFiles(try JSONSerialization.jsonObject(with: file.data)) { |
| 289 | guard sources.contains(url.absoluteString) else { throw fail(String(localized: "A project’s soundtrack is missing from this backup.")) } |
| 290 | } |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | static func safePath(_ path: String) -> Bool { |
| 295 | let parts = path.split(separator: "/", omittingEmptySubsequences: false) |
| 296 | return path.utf8.count < 1024 && parts.count >= 2 && ["Documents", "Support"].contains(String(parts[0])) |
| 297 | && parts.allSatisfy { !$0.isEmpty && $0 != "." && $0 != ".." && !$0.contains("\\") && !$0.contains("\0") } |
| 298 | } |
| 299 | static func preferenceValues(_ archive: Archive) throws -> [String: Any] { |
| 300 | guard let values = try PropertyListSerialization.propertyList(from: archive.preferences, options: [], format: nil) as? [String: Any] else { throw fail(String(localized: "Invalid saved settings.")) } |
| 301 | return values |
| 302 | } |
| 303 | static func validatePreferences(_ values: [String: Any]) throws { |
| 304 | for (key, value) in values { |
| 305 | if key.contains("Favorites.v1") && !key.hasSuffix("appearances") || key.hasSuffix("clickedActions.v1") { |
| 306 | guard let strings = value as? [String], strings.count <= 100_000, |
| 307 | strings.allSatisfy({ !$0.isEmpty && $0.count < 1024 }), Set(strings).count == strings.count else { throw fail(String(localized: "Invalid saved favorites or actions.")) } |
| 308 | } else if key.hasSuffix(".appearances") || key.contains("Studio.v1") || key == "PulseCanvas.studio.v1" |
| 309 | || key.contains("Pool.v1") || key.hasSuffix("favoriteSongs.v1") || key.hasSuffix("videoFormat.v1") { |
| 310 | guard let data = value as? Data, data.count < 16_000_000 else { throw fail(String(localized: "Invalid saved settings data.")) } |
| 311 | let json = try JSONSerialization.jsonObject(with: data) |
| 312 | guard json is [String: Any] || key.hasSuffix("favoriteSongs.v1") && json is [Any] else { throw fail(String(localized: "Invalid saved settings data.")) } |
| 313 | } else if key.hasSuffix("catalogURL") || key.hasSuffix("personalCatalog.v1") { |
| 314 | guard let string = value as? String, let url = URL(string: string), |
| 315 | url.isFileURL || url.scheme == "https" && url.host != nil, |
| 316 | url.user == nil, url.password == nil, url.query == nil else { throw fail(String(localized: "Invalid saved music location.")) } |
| 317 | } else if key.hasSuffix("station") || key.hasSuffix("lastSuccessfulSaveID.v1") { |
| 318 | guard let string = value as? String, string.count < 1024 else { throw fail(String(localized: "Invalid saved selection.")) } |
| 319 | } else { |
| 320 | guard let number = value as? NSNumber, number.doubleValue.isFinite, |
| 321 | (0...1_000_000_000).contains(number.doubleValue) else { throw fail(String(localized: "Invalid saved preference.")) } |
| 322 | } |
| 323 | } |
| 324 | } |
| 325 | static func isProject(_ path: String) -> Bool { |
| 326 | ["pulsecanvas", "pulsevision"].contains(URL(fileURLWithPath: path).pathExtension.lowercased()) || path.hasSuffix("/Studio-autosave.json") |
| 327 | } |
| 328 | static func referencedFiles(_ object: Any) -> [URL] { |
| 329 | if let dictionary = object as? [String: Any] { |
| 330 | return dictionary.flatMap { key, value -> [URL] in |
| 331 | if ["soundtrack", "externalAudioURL"].contains(key), let string = value as? String, let url = URL(string: string), url.isFileURL { return [url] } |
| 332 | if key == "macProject", let string = value as? String, let data = Data(base64Encoded: string), |
| 333 | let json = try? JSONSerialization.jsonObject(with: data) { return referencedFiles(json) } |
| 334 | return referencedFiles(value) |
| 335 | } |
| 336 | } |
| 337 | return (object as? [Any])?.flatMap(referencedFiles) ?? [] |
| 338 | } |
| 339 | static func sanitized(_ object: Any, urls: [String: String] = [:]) throws -> Any { |
| 340 | if let dictionary = object as? [String: Any] { |
| 341 | let excluded: Set<String> = ["soundtrackbookmark", "folderbookmark", "password", "token", "apikey", "secret", "authorization", "session"] |
| 342 | return try dictionary.filter { !excluded.contains($0.key.lowercased()) }.mapValues { try sanitized($0, urls: urls) } |
| 343 | } |
| 344 | if let array = object as? [Any] { return try array.map { try sanitized($0, urls: urls) } } |
| 345 | if let string = object as? String { |
| 346 | if let replacement = urls[string] { return replacement } |
| 347 | // Vision's retained Mac project is JSON encoded as base64. |
| 348 | if let data = Data(base64Encoded: string), let json = try? JSONSerialization.jsonObject(with: data) { |
| 349 | return try JSONSerialization.data(withJSONObject: sanitized(json, urls: urls), options: [.sortedKeys]).base64EncodedString() |
| 350 | } |
| 351 | } |
| 352 | if let data = object as? Data, let json = try? JSONSerialization.jsonObject(with: data) { |
| 353 | return try JSONSerialization.data(withJSONObject: sanitized(json, urls: urls), options: [.sortedKeys]) |
| 354 | } |
| 355 | return object |
| 356 | } |
| 357 | |
| 358 | /// Stage a complete immutable restore, then atomically publish a small pending marker. |
| 359 | /// Live models keep their current files/preferences until the next cold launch. |
| 360 | static func stageRestore(_ archive: Archive, defaults: UserDefaults = .standard, storage: Storage = .standard) throws -> Bool { |
| 361 | try validate(archive) |
| 362 | if defaults.string(forKey: activeKey) == archive.id.uuidString { return false } |
| 363 | let fm = FileManager.default |
| 364 | let root = storage.backups.appendingPathComponent("Restores/\(archive.id.uuidString)", isDirectory: true) |
| 365 | let staging = storage.backups.appendingPathComponent("Staging-\(UUID().uuidString)", isDirectory: true) |
| 366 | try fm.createDirectory(at: staging, withIntermediateDirectories: true) |
| 367 | try fm.createDirectory(at: root.deletingLastPathComponent(), withIntermediateDirectories: true) |
| 368 | defer { try? fm.removeItem(at: staging) } |
| 369 | var mapping: [String: String] = [:] |
| 370 | for file in archive.files where !file.originalURL.isEmpty { mapping[file.originalURL] = root.appendingPathComponent(file.path).absoluteString } |
| 371 | for file in archive.files { |
| 372 | var data = file.data |
| 373 | if isProject(file.path) { |
| 374 | data = try JSONSerialization.data(withJSONObject: sanitized(JSONSerialization.jsonObject(with: data), urls: mapping), options: [.sortedKeys]) |
| 375 | } |
| 376 | let destination = staging.appendingPathComponent(file.path) |
| 377 | try fm.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true) |
| 378 | try data.write(to: destination, options: .atomic) |
| 379 | } |
| 380 | var preferences = try preferenceValues(archive) |
| 381 | preferences = try sanitized(preferences, urls: mapping) as! [String: Any] |
| 382 | let data = try PropertyListSerialization.data(fromPropertyList: preferences, format: .binary, options: 0) |
| 383 | try data.write(to: staging.appendingPathComponent("preferences.plist"), options: .atomic) |
| 384 | // An identical pending import is idempotent; a different import never merges into it. |
| 385 | var metadata = archive |
| 386 | for index in metadata.files.indices { metadata.files[index].data = Data() } |
| 387 | let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys] |
| 388 | let fingerprint = hash(try encoder.encode(metadata)) |
| 389 | try Data(fingerprint.utf8).write(to: staging.appendingPathComponent("fingerprint"), options: .atomic) |
| 390 | if fm.fileExists(atPath: root.path) { |
| 391 | guard try Data(contentsOf: root.appendingPathComponent("fingerprint")) == Data(fingerprint.utf8) else { throw fail(String(localized: "A different backup uses this identity. Nothing restored.")) } |
| 392 | } else { try fm.moveItem(at: staging, to: root) } |
| 393 | let marker = try JSONEncoder().encode(archive.id) |
| 394 | try marker.write(to: storage.backups.appendingPathComponent("pending.json"), options: .atomic) |
| 395 | return true |
| 396 | } |
| 397 | |
| 398 | /// Run before any app models are constructed. One persistent-domain write commits |
| 399 | /// the settings and new storage generation together; old user files remain intact. |
| 400 | static func activatePendingRestore(defaults: UserDefaults = .standard, storage: Storage = .standard) throws { |
| 401 | let pending = storage.backups.appendingPathComponent("pending.json") |
| 402 | guard FileManager.default.fileExists(atPath: pending.path) else { return } |
| 403 | let id = try JSONDecoder().decode(UUID.self, from: Data(contentsOf: pending)) |
| 404 | if defaults.string(forKey: activeKey) == id.uuidString { |
| 405 | try? FileManager.default.removeItem(at: pending) |
| 406 | return |
| 407 | } |
| 408 | let root = storage.backups.appendingPathComponent("Restores/\(id.uuidString)") |
| 409 | let plist = try Data(contentsOf: root.appendingPathComponent("preferences.plist")) |
| 410 | guard var values = try PropertyListSerialization.propertyList(from: plist, options: [], format: nil) as? [String: Any], |
| 411 | Set(values.keys).isSubset(of: preferenceKeys) else { throw fail(String(localized: "The pending restore is invalid. Your previous data has been kept.")) } |
| 412 | let personalKey = "PulseCanvas.radio.personalCatalog.v1" |
| 413 | let personalURL = (values.removeValue(forKey: personalKey) as? String).flatMap(URL.init(string:)) |
| 414 | // Match the URL representation UserDefaults.url(forKey:) expects, without |
| 415 | // importing another machine's security-scoped authorization bookmarks. |
| 416 | if let personalURL { values[personalKey] = try NSKeyedArchiver.archivedData(withRootObject: personalURL, requiringSecureCoding: true) } |
| 417 | var domain = defaults.persistentDomain(forName: storage.domain) ?? [:] |
| 418 | for key in preferenceKeys { domain.removeValue(forKey: key) } |
| 419 | domain.removeValue(forKey: "PulseCanvas.radio.folderBookmark") |
| 420 | // Restoring an old snapshot must not silently publish it to other devices. |
| 421 | domain["PulseCanvas.iCloud.enabled.v1"] = false |
| 422 | domain.merge(values) { _, restored in restored } |
| 423 | domain[activeKey] = id.uuidString |
| 424 | let previous = defaults.persistentDomain(forName: storage.domain) ?? [:] |
| 425 | defaults.setPersistentDomain(domain, forName: storage.domain) |
| 426 | guard defaults.synchronize() else { |
| 427 | defaults.setPersistentDomain(previous, forName: storage.domain) |
| 428 | defaults.synchronize() |
| 429 | throw fail(String(localized: "The restore settings couldn't be saved. Your previous data is still in use.")) |
| 430 | } |
| 431 | try? FileManager.default.removeItem(at: pending) |
| 432 | } |
| 433 | } |