PulseCanvas / app · pulsecanvas.ai / Sources / PulseCanvas / CloudSyncAppData.swift
| 1 | import Foundation |
| 2 | |
| 3 | /// Only portable user choices cross devices. Volume, playback state, authorization |
| 4 | /// bookmarks, support clicks and downloaded public Radio caches stay on each device. |
| 5 | @MainActor enum CloudSyncAppData { |
| 6 | struct SavedLooks: Codable { var presets: [Int: VisualPreset]; var identities: [Int: String]? } |
| 7 | static let visionLooksKey = "PulseCanvas.cloudLooks.v1" |
| 8 | private static func normalized(_ saved: SavedLooks, library: ProjectMPresets) -> [Int: VisualPreset] { |
| 9 | var result: [Int: VisualPreset] = [:] |
| 10 | for scene in saved.presets.keys.sorted() where !library.isRetiredScene(scene, identities: saved.identities) { |
| 11 | guard let look = saved.presets[scene], look.isValid, |
| 12 | let resolved = try? library.migratedScene(scene, identities: saved.identities), |
| 13 | library.availableScenes.contains(resolved), result[resolved] == nil else { continue } |
| 14 | result[resolved] = look |
| 15 | } |
| 16 | return result |
| 17 | } |
| 18 | static func canDeleteSong(_ change: CloudSyncChange) -> Bool { |
| 19 | #if os(visionOS) |
| 20 | guard let song = try? JSONDecoder().decode(FavoriteRadioSong.self, from: change.payload) else { return false } |
| 21 | return song.sourceURL.absoluteString == "https://radio.pulsecanvas.si/stations.json" |
| 22 | #else |
| 23 | return true |
| 24 | #endif |
| 25 | } |
| 26 | static func snapshot(defaults: UserDefaults = .standard, library suppliedLibrary: ProjectMPresets? = nil) throws -> (values: [String: Data], scope: Set<String>) { |
| 27 | let library = suppliedLibrary ?? .shared |
| 28 | var values: [String: Data] = [:], scope = Set<String>() |
| 29 | let backup = try FavoritesBackup.read(library.exportFavorites()) |
| 30 | for scene in library.availableScenes { |
| 31 | let id = library.identity(for: scene) |
| 32 | scope.insert("visualFavorite:" + id); scope.insert("look:" + id) |
| 33 | } |
| 34 | for favorite in backup.favorites { values["visualFavorite:" + favorite.id] = try CloudSyncLedger.encoded(favorite) } |
| 35 | #if os(visionOS) |
| 36 | if let data = defaults.data(forKey: visionLooksKey), let looks = try? JSONDecoder().decode([String: VisualPreset].self, from: data) { |
| 37 | for (id, look) in looks where look.isValid { values["look:" + id] = try CloudSyncLedger.encoded(look) } |
| 38 | } |
| 39 | #else |
| 40 | #if STORE_BUILD |
| 41 | let key = "PulseCanvas.metalStudio.v1" |
| 42 | #else |
| 43 | let key = "PulseCanvas.studio.v1" |
| 44 | #endif |
| 45 | if let data = defaults.data(forKey: key), let saved = try? JSONDecoder().decode(SavedLooks.self, from: data) { |
| 46 | for (scene, look) in normalized(saved, library: library) { |
| 47 | values["look:" + library.identity(for: scene)] = try CloudSyncLedger.encoded(look) |
| 48 | } |
| 49 | } |
| 50 | #endif |
| 51 | if let data = defaults.data(forKey: "PulseCanvas.radio.favoriteSongs.v1") { |
| 52 | let songs = try JSONDecoder().decode([FavoriteRadioSong].self, from: data) |
| 53 | for song in songs where song.isValid && song.sourceURL.scheme == "https" && song.catalogURL.scheme == "https" { |
| 54 | let portable = FavoriteRadioSong(track: song.track, sourceURL: song.sourceURL, catalogURL: song.catalogURL, |
| 55 | stationID: song.stationID, folderBookmark: nil) |
| 56 | values["songFavorite:" + song.id] = try CloudSyncLedger.encoded(portable) |
| 57 | } |
| 58 | } |
| 59 | // Songs removed from a successfully refreshed local library are explicit |
| 60 | // changes. The caller adds its previous local song IDs to this scope. |
| 61 | scope.formUnion(values.keys.filter { $0.hasPrefix("songFavorite:") }) |
| 62 | return (values, scope) |
| 63 | } |
| 64 | |
| 65 | static func validate(_ change: CloudSyncChange) throws { |
| 66 | _ = try change.validated() |
| 67 | guard !change.deleted else { return } |
| 68 | switch change.kind { |
| 69 | case .visualFavorite: |
| 70 | let value = try JSONDecoder().decode(FavoritesBackup.Favorite.self, from: change.payload) |
| 71 | guard value.id == change.key, value.appearance?.isValid ?? true, (value.name?.count ?? 0) < 1000 else { throw CocoaError(.fileReadCorruptFile) } |
| 72 | case .songFavorite: |
| 73 | let value = try JSONDecoder().decode(FavoriteRadioSong.self, from: change.payload) |
| 74 | guard value.id == change.key, value.isValid, value.folderBookmark == nil, |
| 75 | value.sourceURL.scheme == "https", value.catalogURL.scheme == "https" else { throw CocoaError(.fileReadCorruptFile) } |
| 76 | case .look: |
| 77 | guard try JSONDecoder().decode(VisualPreset.self, from: change.payload).isValid else { throw CocoaError(.fileReadCorruptFile) } |
| 78 | case .project: |
| 79 | _ = try JSONDecoder().decode(CloudProjectInfo.self, from: change.payload).validated() |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | static func apply(_ changes: [CloudSyncChange], defaults: UserDefaults = .standard, library suppliedLibrary: ProjectMPresets? = nil) throws { |
| 84 | let library = suppliedLibrary ?? .shared |
| 85 | try changes.forEach(validate) |
| 86 | let favorites = try changes.filter { $0.kind == .visualFavorite && !$0.deleted }.map { |
| 87 | try JSONDecoder().decode(FavoritesBackup.Favorite.self, from: $0.payload) |
| 88 | } |
| 89 | library.applyCloudFavorites(favorites, removed: Set(changes.filter { $0.kind == .visualFavorite && $0.deleted }.map(\.key))) |
| 90 | var songs = (defaults.data(forKey: "PulseCanvas.radio.favoriteSongs.v1").flatMap { try? JSONDecoder().decode([FavoriteRadioSong].self, from: $0) } ?? []) |
| 91 | for change in changes where change.kind == .songFavorite { |
| 92 | songs.removeAll { $0.id == change.key } |
| 93 | if !change.deleted { songs.append(try JSONDecoder().decode(FavoriteRadioSong.self, from: change.payload)) } |
| 94 | } |
| 95 | defaults.set(try CloudSyncLedger.encoded(songs.sorted { $0.id < $1.id }), forKey: "PulseCanvas.radio.favoriteSongs.v1") |
| 96 | let scenes = Dictionary(uniqueKeysWithValues: library.availableScenes.map { (library.identity(for: $0), $0) }) |
| 97 | #if os(visionOS) |
| 98 | var looks = defaults.data(forKey: visionLooksKey).flatMap { try? JSONDecoder().decode([String: VisualPreset].self, from: $0) } ?? [:] |
| 99 | for change in changes where change.kind == .look && scenes[change.key] != nil { |
| 100 | looks[change.key] = change.deleted ? nil : try JSONDecoder().decode(VisualPreset.self, from: change.payload) |
| 101 | } |
| 102 | defaults.set(try CloudSyncLedger.encoded(looks), forKey: visionLooksKey) |
| 103 | #else |
| 104 | #if STORE_BUILD |
| 105 | let key = "PulseCanvas.metalStudio.v1" |
| 106 | #else |
| 107 | let key = "PulseCanvas.studio.v1" |
| 108 | #endif |
| 109 | var saved = defaults.data(forKey: key).flatMap { try? JSONDecoder().decode(SavedLooks.self, from: $0) } ?? SavedLooks(presets: [:]) |
| 110 | let normalized = normalized(saved, library: library) |
| 111 | if normalized != saved.presets, defaults.data(forKey: key + ".beforeICloud") == nil { |
| 112 | defaults.set(defaults.data(forKey: key), forKey: key + ".beforeICloud") |
| 113 | } |
| 114 | saved.presets = normalized |
| 115 | for change in changes where change.kind == .look { |
| 116 | guard let scene = scenes[change.key] else { continue } |
| 117 | saved.presets[scene] = change.deleted ? nil : try JSONDecoder().decode(VisualPreset.self, from: change.payload) |
| 118 | } |
| 119 | saved.identities = library.identities(for: Set(saved.presets.keys)) |
| 120 | defaults.set(try CloudSyncLedger.encoded(saved), forKey: key) |
| 121 | #endif |
| 122 | NotificationCenter.default.post(name: .pulseCanvasCloudDataApplied, object: nil) |
| 123 | } |
| 124 | } |