PulseCanvas / app / Sources / PulseCanvas / UserBackupView.swift
| 1 | import SwiftUI |
| 2 | import UniformTypeIdentifiers |
| 3 | |
| 4 | struct UserBackupDocument: FileDocument { |
| 5 | static var readableContentTypes: [UTType] { [.zip, .json] } |
| 6 | var data: Data |
| 7 | init(data: Data) { self.data = data } |
| 8 | init(configuration: ReadConfiguration) throws { |
| 9 | guard let data = configuration.file.regularFileContents, data.count <= UserBackup.maximumSourceBytes + 32_000_000 else { throw UserBackup.fail(String(localized: "The backup is too large.")) } |
| 10 | self.data = data |
| 11 | } |
| 12 | func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { FileWrapper(regularFileWithContents: data) } |
| 13 | } |
| 14 | |
| 15 | /// Shared native file pickers and confirmation on Mac, iPhone/iPad and Vision Pro. |
| 16 | struct UserBackupView: View { |
| 17 | let currentProject: () throws -> Data? |
| 18 | let prepare: () -> Void |
| 19 | var openProject: ((Data) -> Void)? = nil |
| 20 | @State private var exporting = false |
| 21 | @State private var importing = false |
| 22 | @State private var addingProjects = false |
| 23 | @State private var busy = false |
| 24 | @State private var status = "" |
| 25 | @State private var document = UserBackupDocument(data: Data()) |
| 26 | @State private var pending: UserBackup.Archive? |
| 27 | @State private var confirmation = false |
| 28 | @State private var additionalProjects: [URL] = [] |
| 29 | @State private var leases: [SecurityScopedAccess] = [] |
| 30 | @State private var staged = false |
| 31 | @State private var savedProjects: [URL] = [] |
| 32 | @State private var exportWork: URL? |
| 33 | @State private var importWork: URL? |
| 34 | @State private var visible = false |
| 35 | |
| 36 | private var platform: String { |
| 37 | #if os(visionOS) |
| 38 | "visionOS" |
| 39 | #elseif os(iOS) |
| 40 | "iOS" |
| 41 | #else |
| 42 | "macOS" |
| 43 | #endif |
| 44 | } |
| 45 | |
| 46 | var body: some View { |
| 47 | VStack(alignment: .leading, spacing: 16) { |
| 48 | Label("Backup & Restore", systemImage: "externaldrive").font(.title2.bold()) |
| 49 | Text("Save your favorites, saved looks, projects, imported music and preferences in one ZIP file. Keep a copy outside this device.") |
| 50 | Text("Your current Studio project and app-managed files are included. Add older projects saved elsewhere to include them and their soundtracks. Downloaded public Radio caches, exported videos, sign-in data and purchase records are excluded.") |
| 51 | .font(.callout).foregroundStyle(.secondary) |
| 52 | Button("Add project files…", systemImage: "folder.badge.plus") { addingProjects = true } |
| 53 | .accessibilityIdentifier("backupAddProjects") |
| 54 | if !additionalProjects.isEmpty { Text("\(additionalProjects.count) additional projects selected").font(.caption) } |
| 55 | HStack(spacing: 12) { |
| 56 | Button("Export Backup", systemImage: "square.and.arrow.up") { exportBackup() } |
| 57 | .buttonStyle(.borderedProminent).accessibilityIdentifier("exportUserBackup") |
| 58 | Button("Import / Restore", systemImage: "square.and.arrow.down") { importing = true } |
| 59 | .buttonStyle(.bordered).accessibilityIdentifier("importUserBackup") |
| 60 | } |
| 61 | if busy { ProgressView("Preparing backup…") } |
| 62 | if !status.isEmpty { Text(status).font(.callout).textSelection(.enabled).accessibilityIdentifier("userBackupStatus") } |
| 63 | if let error = UserBackup.startupError { Text(error).foregroundStyle(.red) } |
| 64 | if let openProject, !savedProjects.isEmpty { |
| 65 | DisclosureGroup("Saved & restored projects") { |
| 66 | ForEach(savedProjects, id: \.self) { url in |
| 67 | Button(url.deletingPathExtension().lastPathComponent) { |
| 68 | do { prepare(); openProject(try Data(contentsOf: url)); status = String(localized: "Project opened. Close Settings to continue.") } |
| 69 | catch { status = error.localizedDescription } |
| 70 | } |
| 71 | } |
| 72 | } |
| 73 | } |
| 74 | #if os(macOS) |
| 75 | Button("Show saved projects in Finder") { |
| 76 | try? FileManager.default.createDirectory(at: UserBackup.documents, withIntermediateDirectories: true) |
| 77 | NSWorkspace.shared.open(UserBackup.documents) |
| 78 | } |
| 79 | #endif |
| 80 | Text("Backups include personal music files. Store them somewhere private.") |
| 81 | .font(.caption).foregroundStyle(.secondary) |
| 82 | DisclosureGroup("Backup library license") { |
| 83 | Text(Bundle.main.url(forResource: "ZIPFoundation-LICENSE", withExtension: "txt", subdirectory: "Legal") |
| 84 | .flatMap { try? String(contentsOf: $0, encoding: .utf8) } ?? "ZIPFoundation is licensed under MIT. See the matching source package for its full notice.") |
| 85 | .font(.caption).textSelection(.enabled) |
| 86 | } |
| 87 | }.disabled(busy || staged) |
| 88 | .onAppear { visible = true; savedProjects = UserBackup.savedProjects() } |
| 89 | .onDisappear { |
| 90 | visible = false |
| 91 | if !busy { document = UserBackupDocument(data: Data()); pending = nil; cleanExport(); cleanImport() } |
| 92 | } |
| 93 | .fileExporter(isPresented: $exporting, document: document, contentType: .zip, |
| 94 | defaultFilename: "PulseCanvas-Backup-\(Date().formatted(.iso8601.year().month().day().dateSeparator(.dash)))") { result in |
| 95 | switch result { |
| 96 | case .success: status = String(localized: "Backup saved.") |
| 97 | case .failure(let error): status = String(localized: "Backup wasn't saved: \(error.localizedDescription)") |
| 98 | } |
| 99 | document = UserBackupDocument(data: Data()) |
| 100 | cleanExport() |
| 101 | } |
| 102 | .fileImporter(isPresented: $addingProjects, allowedContentTypes: [.json, UTType(filenameExtension: "pulsecanvas") ?? .json, UTType(filenameExtension: "pulsevision") ?? .json], allowsMultipleSelection: true) { result in |
| 103 | do { |
| 104 | for url in try result.get() where !additionalProjects.contains(url) { |
| 105 | leases.append(SecurityScopedAccess(url: url)); additionalProjects.append(url) |
| 106 | } |
| 107 | } catch { status = error.localizedDescription } |
| 108 | } |
| 109 | .fileImporter(isPresented: $importing, allowedContentTypes: [.zip, .json]) { result in |
| 110 | do { |
| 111 | let url = try result.get() |
| 112 | let lease = SecurityScopedAccess(url: url) |
| 113 | busy = true |
| 114 | Task { |
| 115 | defer { busy = false; withExtendedLifetime(lease) {} } |
| 116 | do { |
| 117 | cleanImport() |
| 118 | let work = try workspace(); importWork = work |
| 119 | let archive = try await Task.detached { |
| 120 | url.pathExtension.lowercased() == "zip" ? try UserBackup.readZIP(url, workspace: work.appendingPathComponent("Files")) : try UserBackup.read(url) |
| 121 | }.value |
| 122 | guard visible else { cleanImport(); return } |
| 123 | guard archive.platform == platform else { throw UserBackup.fail(String(localized: "Restore this full backup on \(archive.platform). Individual PulseCanvas projects can be opened on other platforms.")) } |
| 124 | try validateProjects(archive) |
| 125 | pending = archive; confirmation = true |
| 126 | } catch { status = String(localized: "Nothing restored: \(error.localizedDescription)"); pending = nil; cleanImport() } |
| 127 | } |
| 128 | } catch { status = error.localizedDescription } |
| 129 | } |
| 130 | .alert("Restore this backup?", isPresented: $confirmation) { |
| 131 | Button("Cancel", role: .cancel) { pending = nil; cleanImport() } |
| 132 | Button("Restore", role: .destructive) { restore() } |
| 133 | } message: { |
| 134 | Text("This replaces the app’s saved data and preferences with the backup after you close and reopen PulseCanvas. Existing project files outside the app remain unchanged. Export a current backup first if you want to keep both.") |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | @MainActor private func exportBackup() { |
| 139 | prepare(); busy = true; status = "" |
| 140 | do { |
| 141 | let project = try currentProject() |
| 142 | let projects = additionalProjects, sourcePlatform = platform |
| 143 | Task { |
| 144 | defer { busy = false } |
| 145 | do { |
| 146 | cleanExport() |
| 147 | let work = try workspace(); exportWork = work |
| 148 | let zip = work.appendingPathComponent("PulseCanvas-Backup.zip") |
| 149 | let archive = try await Task.detached { |
| 150 | let archive = try UserBackup.collect(currentProject: project, additionalProjects: projects, platform: sourcePlatform) |
| 151 | try UserBackup.writeZIP(archive, to: zip) |
| 152 | return archive |
| 153 | }.value |
| 154 | guard visible else { cleanExport(); return } |
| 155 | try validateProjects(archive) |
| 156 | document = UserBackupDocument(data: try Data(contentsOf: zip, options: .alwaysMapped)); exporting = true |
| 157 | } catch { status = String(localized: "Nothing exported: \(error.localizedDescription)"); cleanExport() } |
| 158 | } |
| 159 | } catch { busy = false; status = String(localized: "Nothing exported: \(error.localizedDescription)") } |
| 160 | } |
| 161 | |
| 162 | @MainActor private func restore() { |
| 163 | guard let archive = pending else { return } |
| 164 | prepare(); busy = true |
| 165 | Task { |
| 166 | defer { busy = false; pending = nil; cleanImport() } |
| 167 | do { |
| 168 | let changed = try await Task.detached { try UserBackup.stageRestore(archive) }.value |
| 169 | staged = changed |
| 170 | status = changed ? "Backup ready to restore. Close and reopen PulseCanvas to finish. Your current session stays unchanged until then. Restored projects are in the restored Projects folder." : "This backup has already been restored. No duplicates were added." |
| 171 | } catch { status = String(localized: "Nothing restored: \(error.localizedDescription)") } |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | private func workspace() throws -> URL { |
| 176 | let root = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0] |
| 177 | .appendingPathComponent("PulseCanvas/BackupWork/\(UUID().uuidString)", isDirectory: true) |
| 178 | try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) |
| 179 | return root |
| 180 | } |
| 181 | private func cleanExport() { |
| 182 | if let exportWork { try? FileManager.default.removeItem(at: exportWork) } |
| 183 | exportWork = nil |
| 184 | } |
| 185 | private func cleanImport() { |
| 186 | if let importWork { try? FileManager.default.removeItem(at: importWork) } |
| 187 | importWork = nil |
| 188 | } |
| 189 | |
| 190 | @MainActor private func validateProjects(_ archive: UserBackup.Archive) throws { |
| 191 | let preferences = try UserBackup.preferenceValues(archive) |
| 192 | for (key, value) in preferences { |
| 193 | guard let data = value as? Data else { continue } |
| 194 | if key.hasSuffix(".appearances") { |
| 195 | let looks = try JSONDecoder().decode([String: VisualPreset].self, from: data) |
| 196 | guard looks.values.allSatisfy(\.isValid) else { throw UserBackup.fail(String(localized: "Invalid favorite appearance settings.")) } |
| 197 | } else if key == "PulseCanvas.studio.v1" || key == "PulseCanvas.metalStudio.v1" { |
| 198 | struct Saved: Decodable { var presets: [Int: VisualPreset]; var identities: [Int: String]? } |
| 199 | let saved = try JSONDecoder().decode(Saved.self, from: data) |
| 200 | guard saved.presets.values.allSatisfy(\.isValid), saved.presets.keys.allSatisfy({ (0..<100_000).contains($0) }) else { throw UserBackup.fail(String(localized: "Invalid saved visualizer settings.")) } |
| 201 | } else if key.hasSuffix("Pool.v1") { |
| 202 | let pool = try JSONDecoder().decode(VisualizerPool.self, from: data) |
| 203 | guard pool.collection.count < 100, pool.category.count < 200 else { throw UserBackup.fail(String(localized: "Invalid saved visualizer filter.")) } |
| 204 | } else if key.hasSuffix("favoriteSongs.v1") { |
| 205 | let songs = try JSONDecoder().decode([FavoriteRadioSong].self, from: data) |
| 206 | guard songs.count <= 2_000, songs.allSatisfy(\.isValid), Set(songs.map(\.id)).count == songs.count else { throw UserBackup.fail(String(localized: "Invalid saved song favorites.")) } |
| 207 | } else if key.hasSuffix("videoFormat.v1") { |
| 208 | struct Format: Decodable { var aspect: String; var resolution: Int; var fps: Int } |
| 209 | let format = try JSONDecoder().decode(Format.self, from: data) |
| 210 | guard SocialAspect(rawValue: format.aspect) != nil, [720, 1080, 2160].contains(format.resolution), |
| 211 | SocialExportController.supportedFrameRates.contains(format.fps) else { throw UserBackup.fail(String(localized: "Invalid saved export format.")) } |
| 212 | } |
| 213 | } |
| 214 | for file in archive.files where UserBackup.isProject(file.path) { |
| 215 | #if os(visionOS) |
| 216 | _ = try VisionProject.openPortable(file.data) |
| 217 | #else |
| 218 | let project = try JSONDecoder().decode(CreatorProject.self, from: file.data) |
| 219 | guard project.version == 1, project.appearance.isValid, project.visualPresets?.values.allSatisfy(\.isValid) ?? true, |
| 220 | project.scene >= 0, project.scene < 100_000, |
| 221 | project.visualPresets?.keys.allSatisfy({ (0..<100_000).contains($0) }) ?? true, |
| 222 | StudioTimeline.valid(project.timeline ?? [], sceneCount: 100_000), |
| 223 | SocialAspect(rawValue: project.aspect) != nil, [720, 1080, 2160].contains(project.resolution), |
| 224 | SocialExportController.supportedFrameRates.contains(project.fps), |
| 225 | project.barsPerSection.map({ (1...64).contains($0) }) ?? true else { throw UserBackup.fail(String(localized: "The backup contains an invalid project.")) } |
| 226 | #endif |
| 227 | } |
| 228 | } |
| 229 | } |