PulseCanvas / app · pulsecanvas.ai / Sources / PulseCanvas / CloudSyncService.swift
| 1 | import Combine |
| 2 | import Foundation |
| 3 | |
| 4 | @MainActor final class CloudSyncService: ObservableObject { |
| 5 | static let shared = CloudSyncService() |
| 6 | nonisolated static let containerID = "iCloud.com.protomota.pulsecanvas" |
| 7 | static let enabledKey = "PulseCanvas.iCloud.enabled.v1" |
| 8 | @Published private(set) var enabled: Bool |
| 9 | @Published private(set) var busy = false |
| 10 | @Published private(set) var status = String(localized: "iCloud sync is off. Your data stays on this device.") |
| 11 | @Published private(set) var projects: [CloudSyncChange] = [] |
| 12 | @Published private(set) var lastSync: Date? |
| 13 | private struct DiskState: Codable { |
| 14 | var ledger = CloudSyncLedger() |
| 15 | var account: String? |
| 16 | var projectHashes: [String: String] = [:] |
| 17 | var projectBases: [String: String] = [:] |
| 18 | var needsApplication = false |
| 19 | } |
| 20 | private var state = DiskState() |
| 21 | private var root: URL? |
| 22 | private var query: NSMetadataQuery? |
| 23 | private var observers: [NSObjectProtocol] = [] |
| 24 | private var queryObservers: [NSObjectProtocol] = [] |
| 25 | private var localTask: Task<Void, Never>? |
| 26 | private var periodic: Task<Void, Never>? |
| 27 | private var started = false |
| 28 | private var applying = false |
| 29 | private var generation = UUID() |
| 30 | private var again = false |
| 31 | private var confirmedAccountMerge = false |
| 32 | private var connecting = false |
| 33 | private var projectFailures: [String] = [] |
| 34 | private var invalidHistory = false |
| 35 | private let defaults: UserDefaults |
| 36 | private let support: URL |
| 37 | private var stateURL: URL { support.appendingPathComponent("CloudSync/state.json") } |
| 38 | private var workRoot: URL { support.appendingPathComponent("CloudSync/Work", isDirectory: true) } |
| 39 | private var changesFolder: URL? { root?.appendingPathComponent("PulseCanvasData/Changes", isDirectory: true) } |
| 40 | private var assetsFolder: URL? { root?.appendingPathComponent("Documents/Projects", isDirectory: true) } |
| 41 | private var audioFolder: URL? { root?.appendingPathComponent("Documents/Audio", isDirectory: true) } |
| 42 | |
| 43 | init(defaults: UserDefaults = .standard, support: URL? = nil) { |
| 44 | self.defaults = defaults |
| 45 | self.support = support ?? UserDataStorage.support |
| 46 | enabled = defaults.bool(forKey: Self.enabledKey) |
| 47 | if FileManager.default.fileExists(atPath: stateURL.path) { |
| 48 | do { |
| 49 | let saved = try JSONDecoder().decode(DiskState.self, from: Data(contentsOf: stateURL)) |
| 50 | _ = try CloudSyncLedger.read(CloudSyncLedger.encoded(saved.ledger)) |
| 51 | try saved.ledger.events.values.forEach(CloudSyncAppData.validate) |
| 52 | state = saved |
| 53 | } catch { |
| 54 | invalidHistory = true |
| 55 | enabled = false |
| 56 | defaults.set(false, forKey: Self.enabledKey) |
| 57 | status = String(localized: "iCloud sync history couldn't be read. Sync is off; local data and the original history were kept.") |
| 58 | } |
| 59 | } |
| 60 | } |
| 61 | func start() { |
| 62 | guard !started else { return }; started = true |
| 63 | observers.append(NotificationCenter.default.addObserver(forName: .pulseCanvasUserDataChanged, object: nil, queue: .main) { [weak self] _ in |
| 64 | Task { @MainActor in self?.localChanged() } |
| 65 | }) |
| 66 | observers.append(NotificationCenter.default.addObserver(forName: .NSUbiquityIdentityDidChange, object: nil, queue: .main) { [weak self] _ in |
| 67 | Task { @MainActor in |
| 68 | self?.setEnabled(false) |
| 69 | self?.status = String(localized: "Your Apple Account changed. Local data was kept. Confirm iCloud sync again to use the current account.") |
| 70 | } |
| 71 | }) |
| 72 | if enabled { connect() } |
| 73 | } |
| 74 | func setEnabled(_ value: Bool) { |
| 75 | guard !value || !invalidHistory else { |
| 76 | status = String(localized: "Sync history needs recovery before enabling iCloud. Local files and the unreadable history are preserved.") |
| 77 | return |
| 78 | } |
| 79 | confirmedAccountMerge = value |
| 80 | enabled = value; defaults.set(value, forKey: Self.enabledKey) |
| 81 | generation = UUID(); localTask?.cancel(); periodic?.cancel(); query?.stop(); query = nil; root = nil |
| 82 | queryObservers.forEach { NotificationCenter.default.removeObserver($0) }; queryObservers = [] |
| 83 | connecting = false |
| 84 | if value { start(); connect() } |
| 85 | else { status = String(localized: "iCloud sync is off. Local files and existing iCloud copies are kept."); projects = [] } |
| 86 | } |
| 87 | private func connect() { |
| 88 | guard enabled, root == nil, !connecting else { return } |
| 89 | connecting = true |
| 90 | status = String(localized: "Connecting to iCloud Drive…") |
| 91 | let ticket = generation |
| 92 | Task { |
| 93 | defer { if generation == ticket { connecting = false } } |
| 94 | let result = await Task.detached { () -> (URL?, Data?) in |
| 95 | let token = FileManager.default.ubiquityIdentityToken |
| 96 | let identity = token.flatMap { try? NSKeyedArchiver.archivedData(withRootObject: $0, requiringSecureCoding: true) } |
| 97 | return (FileManager.default.url(forUbiquityContainerIdentifier: Self.containerID), identity) |
| 98 | }.value |
| 99 | guard enabled, generation == ticket else { return } |
| 100 | guard let url = result.0, let identity = result.1 else { |
| 101 | status = String(localized: "iCloud Drive is unavailable. Sign in to iCloud and use an iCloud-enabled signed build. Your local data is safe.") |
| 102 | return |
| 103 | } |
| 104 | let account = CloudSyncLedger.digest(identity) |
| 105 | if state.account != account { |
| 106 | if state.account != nil && !confirmedAccountMerge { |
| 107 | setEnabled(false) |
| 108 | status = String(localized: "Your Apple Account changed. Confirm iCloud sync again before merging local data with this account.") |
| 109 | return |
| 110 | } |
| 111 | // Never upload the previous account's event history into a new one. |
| 112 | // Enabling the toggle explicitly confirms merging current local choices. |
| 113 | if state.account != nil { |
| 114 | let archive = stateURL.deletingLastPathComponent().appendingPathComponent("PreviousAccount-" + UUID().uuidString + ".json") |
| 115 | do { try CloudSyncLedger.encoded(state).write(to: archive, options: .atomic) } |
| 116 | catch { status = String(localized: "Couldn't preserve the previous account's sync history. Local data was kept."); return } |
| 117 | } |
| 118 | state = DiskState(); state.account = account |
| 119 | } |
| 120 | confirmedAccountMerge = false |
| 121 | root = url |
| 122 | do { |
| 123 | try FileManager.default.createDirectory(at: changesFolder!, withIntermediateDirectories: true) |
| 124 | try FileManager.default.createDirectory(at: assetsFolder!, withIntermediateDirectories: true) |
| 125 | try FileManager.default.createDirectory(at: audioFolder!, withIntermediateDirectories: true) |
| 126 | try save() |
| 127 | try watch() |
| 128 | startPeriodicChecks() |
| 129 | } catch { root = nil; query?.stop(); query = nil; status = String(localized: "Couldn't prepare iCloud sync: \(error.localizedDescription)") } |
| 130 | } |
| 131 | } |
| 132 | private func startPeriodicChecks() { |
| 133 | periodic?.cancel() |
| 134 | periodic = Task { [weak self] in |
| 135 | while !Task.isCancelled { |
| 136 | self?.syncNow() |
| 137 | do { try await Task.sleep(for: .seconds(30)) } catch { return } |
| 138 | } |
| 139 | } |
| 140 | } |
| 141 | private func watch() throws { |
| 142 | guard let changesFolder, let assetsFolder else { return } |
| 143 | let query = NSMetadataQuery() |
| 144 | query.searchScopes = [NSMetadataQueryUbiquitousDataScope, NSMetadataQueryUbiquitousDocumentsScope] |
| 145 | query.predicate = NSPredicate(format: "%K BEGINSWITH %@ OR %K BEGINSWITH %@", NSMetadataItemPathKey, |
| 146 | changesFolder.path + "/", NSMetadataItemPathKey, assetsFolder.path + "/") |
| 147 | for name in [Notification.Name.NSMetadataQueryDidFinishGathering, .NSMetadataQueryDidUpdate] { |
| 148 | queryObservers.append(NotificationCenter.default.addObserver(forName: name, object: query, queue: .main) { [weak self] _ in |
| 149 | Task { @MainActor in self?.syncNow() } |
| 150 | }) |
| 151 | } |
| 152 | self.query = query |
| 153 | guard query.start() else { throw CocoaError(.fileReadUnknown) } |
| 154 | } |
| 155 | private func localChanged() { |
| 156 | guard !applying, enabled else { return } |
| 157 | localTask?.cancel() |
| 158 | localTask = Task { [weak self] in |
| 159 | do { try await Task.sleep(for: .seconds(2)) } catch { return } |
| 160 | self?.syncNow() |
| 161 | } |
| 162 | } |
| 163 | private func save() throws { |
| 164 | try FileManager.default.createDirectory(at: stateURL.deletingLastPathComponent(), withIntermediateDirectories: true) |
| 165 | try CloudSyncLedger.encoded(state).write(to: stateURL, options: .atomic) |
| 166 | } |
| 167 | private func observeLocal() throws { |
| 168 | let snapshot = try CloudSyncAppData.snapshot(defaults: defaults) |
| 169 | var scope = snapshot.scope |
| 170 | for identity in state.ledger.baseline.keys where identity.hasPrefix("songFavorite:") { |
| 171 | if let event = state.ledger.heads[identity], let change = state.ledger.events[event], CloudSyncAppData.canDeleteSong(change) { |
| 172 | scope.insert(identity) |
| 173 | } |
| 174 | } |
| 175 | try state.ledger.observe(snapshot.values, scope: scope) |
| 176 | } |
| 177 | func syncNow() { |
| 178 | guard enabled else { return } |
| 179 | guard root != nil else { connect(); return } |
| 180 | if busy { again = true; return } |
| 181 | busy = true; status = String(localized: "Syncing with iCloud Drive…") |
| 182 | let ticket = generation |
| 183 | Task { |
| 184 | defer { |
| 185 | busy = false |
| 186 | if again { again = false; if enabled { syncNow() } } |
| 187 | } |
| 188 | do { |
| 189 | try observeLocal(); try save() |
| 190 | query?.disableUpdates() |
| 191 | let items = query?.results as? [NSMetadataItem] ?? [] |
| 192 | query?.enableUpdates() |
| 193 | let urls = items.compactMap { $0.value(forAttribute: NSMetadataItemURLKey) as? URL } |
| 194 | .filter { $0.deletingLastPathComponent().resolvingSymlinksInPath() == changesFolder?.resolvingSymlinksInPath() } |
| 195 | .filter { UUID(uuidString: $0.deletingPathExtension().lastPathComponent) != nil && state.ledger.events[$0.deletingPathExtension().lastPathComponent] == nil } |
| 196 | let incoming = try await Task.detached { |
| 197 | try urls.compactMap { url -> CloudSyncChange? in |
| 198 | guard try Self.downloaded(url) else { return nil } |
| 199 | let data = try Self.coordinatedRead(url) |
| 200 | guard data.count < 3_000_000 else { throw CocoaError(.fileReadCorruptFile) } |
| 201 | let change = try JSONDecoder().decode(CloudSyncChange.self, from: data) |
| 202 | guard change.event == url.deletingPathExtension().lastPathComponent else { throw CocoaError(.fileReadCorruptFile) } |
| 203 | return change |
| 204 | } |
| 205 | }.value |
| 206 | guard enabled, generation == ticket else { return } |
| 207 | try incoming.forEach(CloudSyncAppData.validate) |
| 208 | // Capture edits made while downloads were in flight before applying |
| 209 | // remote heads, so an async fetch cannot overwrite an unseen local edit. |
| 210 | try observeLocal() |
| 211 | let ready = state.ledger.readyChanges(incoming) |
| 212 | try state.ledger.merge(ready) |
| 213 | state.needsApplication = state.needsApplication || !ready.isEmpty |
| 214 | try save() // durable before changing the app's live choices |
| 215 | if state.needsApplication { |
| 216 | applying = true |
| 217 | defer { applying = false } |
| 218 | try CloudSyncAppData.apply(state.ledger.current.filter { $0.kind != .project }, defaults: defaults) |
| 219 | state.ledger.baseline = try CloudSyncAppData.snapshot(defaults: defaults).values |
| 220 | state.needsApplication = false |
| 221 | try save() |
| 222 | } |
| 223 | try await uploadProjects(ticket: ticket) |
| 224 | guard enabled, generation == ticket, let folder = changesFolder else { return } |
| 225 | let pending = state.ledger.pending.compactMap { state.ledger.events[$0] } |
| 226 | for change in pending { |
| 227 | guard enabled, generation == ticket else { return } |
| 228 | let data = try CloudSyncLedger.encoded(change) |
| 229 | let destination = folder.appendingPathComponent(change.event + ".json") |
| 230 | try await Task.detached { try Self.writeImmutable(data, to: destination) }.value |
| 231 | state.ledger.pending.remove(change.event) |
| 232 | } |
| 233 | // One checkpoint per batch. A crash replays immutable writes safely |
| 234 | // without rewriting the entire history for every favorite. |
| 235 | try save() |
| 236 | projects = state.ledger.current.filter { change in |
| 237 | guard change.kind == .project, !change.deleted, |
| 238 | let info = try? JSONDecoder().decode(CloudProjectInfo.self, from: change.payload) else { return false } |
| 239 | return info.isAvailableInEdition |
| 240 | }.sorted { $0.order > $1.order } |
| 241 | lastSync = Date() |
| 242 | status = projectFailures.isEmpty ? "Changes saved to iCloud Drive. Apple transfers them when a connection is available." |
| 243 | : "Other changes saved. \(projectFailures.count) project(s) need attention: \(projectFailures[0])" |
| 244 | if ready.count < incoming.count { status += " Waiting for earlier changes to finish downloading." } |
| 245 | } catch { |
| 246 | status = String(localized: "Sync needs attention: \(error.localizedDescription). Local data was kept; Sync now retries.") |
| 247 | } |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | private func uploadProjects(ticket: UUID) async throws { |
| 252 | guard let folder = assetsFolder, let audioFolder else { return } |
| 253 | projectFailures = [] |
| 254 | for url in UserBackup.savedProjects() where url.deletingLastPathComponent().lastPathComponent == "Projects" { |
| 255 | guard enabled, generation == ticket else { return } |
| 256 | let work = workRoot.appendingPathComponent(UUID().uuidString) |
| 257 | defer { try? FileManager.default.removeItem(at: work) } |
| 258 | do { |
| 259 | guard (try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? Int.max) < 8_000_000 else { throw CocoaError(.fileReadCorruptFile) } |
| 260 | let fingerprint = try Data(contentsOf: url) |
| 261 | let digest = try CloudProjectPackage.fingerprint(fingerprint) |
| 262 | if state.projectHashes[url.lastPathComponent] == digest { continue } |
| 263 | let key = try CloudProjectPackage.key(for: fingerprint, filename: url.lastPathComponent) |
| 264 | let result = try await Task.detached { |
| 265 | try CloudProjectPackage.make(fingerprint, filename: url.lastPathComponent, key: key, in: work) |
| 266 | }.value |
| 267 | guard enabled, generation == ticket else { return } |
| 268 | let destination = folder.appendingPathComponent(result.info.asset) |
| 269 | try await Task.detached { |
| 270 | if let audio = result.audio, let info = result.info.audio { |
| 271 | try Self.copyImmutable(audio, to: audioFolder.appendingPathComponent(info.asset)) |
| 272 | } |
| 273 | try Self.copyImmutable(result.project, to: destination) |
| 274 | }.value |
| 275 | guard enabled, generation == ticket else { return } |
| 276 | let revision = try state.ledger.editProject(key: key, payload: CloudSyncLedger.encoded(result.info), basedOn: state.projectBases[key]) |
| 277 | state.projectBases[key] = revision?.event ?? state.ledger.heads["project:" + key] |
| 278 | state.projectHashes[url.lastPathComponent] = digest; try save() |
| 279 | } catch { projectFailures.append("\(url.lastPathComponent): \(error.localizedDescription)") } |
| 280 | } |
| 281 | } |
| 282 | func openProject(_ change: CloudSyncChange) async throws -> Data { |
| 283 | guard enabled, let folder = assetsFolder else { throw CocoaError(.fileReadNoPermission) } |
| 284 | let info = try JSONDecoder().decode(CloudProjectInfo.self, from: change.payload).validated() |
| 285 | guard projects.contains(change), info.isAvailableInEdition else { throw CocoaError(.fileReadNoPermission) } |
| 286 | let source = folder.appendingPathComponent(info.asset) |
| 287 | let audio = info.audio.flatMap { audioFolder?.appendingPathComponent($0.asset) } |
| 288 | let destination = support.appendingPathComponent("CloudProjects/" + UUID().uuidString, isDirectory: true) |
| 289 | guard try Self.downloaded(source), try audio.map({ try Self.downloaded($0) }) ?? true else { |
| 290 | status = String(localized: "Downloading this project from iCloud. Try Open again when the download finishes.") |
| 291 | throw CocoaError(.fileReadUnknown) |
| 292 | } |
| 293 | let data = try await Task.detached { |
| 294 | try CloudProjectPackage.open(info, key: change.key, project: source, audio: audio, destination: destination) |
| 295 | }.value |
| 296 | try UserBackup.rememberProject(data, name: info.title + ".pulsecanvas") |
| 297 | state.projectBases[change.key] = change.event |
| 298 | try save() |
| 299 | return data |
| 300 | } |
| 301 | func removeProject(_ change: CloudSyncChange) { |
| 302 | guard enabled, projects.contains(change) else { return } |
| 303 | do { |
| 304 | _ = try state.ledger.edit(.project, key: change.key, payload: nil) |
| 305 | try save(); syncNow() |
| 306 | } catch { status = String(localized: "Couldn't remove the cloud project: \(error.localizedDescription)") } |
| 307 | } |
| 308 | |
| 309 | nonisolated static func downloaded(_ url: URL) throws -> Bool { |
| 310 | if !FileManager.default.fileExists(atPath: url.path) { |
| 311 | try? FileManager.default.startDownloadingUbiquitousItem(at: url) |
| 312 | return false |
| 313 | } |
| 314 | let values = try url.resourceValues(forKeys: [.isUbiquitousItemKey, .ubiquitousItemDownloadingStatusKey]) |
| 315 | if values.isUbiquitousItem == true && values.ubiquitousItemDownloadingStatus != .current && values.ubiquitousItemDownloadingStatus != .downloaded { |
| 316 | try FileManager.default.startDownloadingUbiquitousItem(at: url); return false |
| 317 | } |
| 318 | return true |
| 319 | } |
| 320 | nonisolated static func coordinatedRead(_ url: URL) throws -> Data { |
| 321 | var error: NSError?, result: Result<Data, Error>? |
| 322 | NSFileCoordinator().coordinate(readingItemAt: url, options: .withoutChanges, error: &error) { location in |
| 323 | result = Result { try Data(contentsOf: location) } |
| 324 | } |
| 325 | if let error { throw error } |
| 326 | guard let result else { throw CocoaError(.fileReadUnknown) } |
| 327 | return try result.get() |
| 328 | } |
| 329 | nonisolated static func writeImmutable(_ data: Data, to url: URL) throws { |
| 330 | var error: NSError?, failure: Error? |
| 331 | NSFileCoordinator().coordinate(writingItemAt: url, options: .forReplacing, error: &error) { location in |
| 332 | do { |
| 333 | if FileManager.default.fileExists(atPath: location.path) { |
| 334 | guard try Data(contentsOf: location) == data else { throw CocoaError(.fileWriteFileExists) } |
| 335 | } else { try data.write(to: location, options: .atomic) } |
| 336 | } catch { failure = error } |
| 337 | } |
| 338 | if let error { throw error }; if let failure { throw failure } |
| 339 | } |
| 340 | nonisolated static func copyImmutable(_ source: URL, to url: URL) throws { |
| 341 | var error: NSError?, failure: Error? |
| 342 | NSFileCoordinator().coordinate(writingItemAt: url, options: .forReplacing, error: &error) { location in |
| 343 | do { |
| 344 | if !FileManager.default.fileExists(atPath: location.path) { try FileManager.default.copyItem(at: source, to: location) } |
| 345 | guard try CloudProjectPackage.hashFile(location) == location.deletingPathExtension().lastPathComponent else { throw CocoaError(.fileReadCorruptFile) } |
| 346 | } catch { failure = error } |
| 347 | } |
| 348 | if let error { throw error }; if let failure { throw failure } |
| 349 | } |
| 350 | } |