import Foundation import CloudKit import Security /// iCloud sync without a server: the Mac writes one snapshot record to the user's private CloudKit /// database, the iPhone reads it. Only the numbers travel; keys and tokens never leave the Keychain. /// (Same model as Inkspring's companion: the Mac is the source of truth, the phone is a viewer.) public actor SnapshotSync { public static let containerID = "iCloud.com.protomota.graphley" static let zone = CKRecordZone.ID(zoneName: "Analytics", ownerName: CKCurrentUserDefaultName) static let recordID = CKRecord.ID(recordName: "latest-snapshot", zoneID: zone) static let subscriptionID = "snapshot-changes" let containerID: String /// Nil when the build has no iCloud entitlement (unsigned dev builds): CloudKit traps instead of /// throwing in that case, so sync reports itself unavailable and the rest of the app keeps working. let database: CKDatabase? public init(containerID: String = SnapshotSync.containerID) { self.containerID = containerID database = Self.hasCloudKitEntitlement ? CKContainer(identifier: containerID).privateCloudDatabase : nil } public nonisolated var isAvailable: Bool { database != nil } public func accountReady() async -> Bool { guard isAvailable else { return false } return (try? await CKContainer(identifier: containerID).accountStatus()) == .available } /// "Connected" or "Unavailable", the Apple Account values the house iCloud Sync settings show /// (copied from Inkspring's MobileLibrary). Throws when iCloud can't be asked at all. public func accountStatusText() async throws -> String { guard isAvailable else { throw AnalyticsError.notAllowed("iCloud sync needs a signed build with the iCloud entitlement.") } return try await CKContainer(identifier: containerID).accountStatus() == .available ? "Connected" : "Unavailable" } /// When the snapshot in iCloud was refreshed on the Mac, or nil when iCloud has none. /// Reads only the date, not the payload, so the Mac can check its own push cheaply. public func remoteSnapshotDate() async throws -> Date? { let database = try requireDatabase() do { let results = try await database.records(for: [Self.recordID], desiredKeys: ["refreshedAt"]) guard let result = results[Self.recordID] else { return nil } return try result.get()["refreshedAt"] as? Date } catch let e as CKError where e.code == .unknownItem || e.code == .zoneNotFound { return nil } } /// Mac: write the latest snapshot. The JSON goes in a CKAsset so 90 days of data fits easily. public func push(_ snapshot: Snapshot) async throws { let database = try requireDatabase() try await ensureZone() let file = FileManager.default.temporaryDirectory.appendingPathComponent("snapshot-\(UUID().uuidString).json") try JSONEncoder.analytics.encode(snapshot).write(to: file) defer { try? FileManager.default.removeItem(at: file) } let record: CKRecord if let existing = try? await database.record(for: Self.recordID) { record = existing } else { record = CKRecord(recordType: "Snapshot", recordID: Self.recordID) } record["refreshedAt"] = snapshot.refreshedAt as NSDate record["payload"] = CKAsset(fileURL: file) // modifyRecords only throws for the whole request; a rejected record (for example a record type // missing from the Production schema) comes back in the per-record results and must be checked. let (saved, _) = try await database.modifyRecords(saving: [record], deleting: [], savePolicy: .changedKeys) if case .failure(let error)? = saved[Self.recordID] { throw error } } /// iPhone: read the latest snapshot, or nil before the Mac has synced once. public func pull() async throws -> Snapshot? { let database = try requireDatabase() do { let record = try await database.record(for: Self.recordID) guard let url = (record["payload"] as? CKAsset)?.fileURL else { return nil } return try JSONDecoder.analytics.decode(Snapshot.self, from: Data(contentsOf: url)) } catch let e as CKError where e.code == .unknownItem || e.code == .zoneNotFound { return nil } } /// iPhone: silent push when the Mac writes a new snapshot, so widgets and the app refresh. public func subscribe() async throws { let sub = CKRecordZoneSubscription(zoneID: Self.zone, subscriptionID: Self.subscriptionID) let info = CKSubscription.NotificationInfo(); info.shouldSendContentAvailable = true sub.notificationInfo = info _ = try await requireDatabase().modifySubscriptions(saving: [sub], deleting: []) } private func ensureZone() async throws { _ = try await requireDatabase().modifyRecordZones(saving: [CKRecordZone(zoneID: Self.zone)], deleting: []) } private func requireDatabase() throws -> CKDatabase { guard let database else { throw AnalyticsError.notAllowed("iCloud sync needs a signed build with the iCloud entitlement.") } return database } /// macOS can read its own entitlements. iOS can't, but an iOS app only runs signed with the /// entitlements from project.yml, so it is assumed there. static var hasCloudKitEntitlement: Bool { #if os(macOS) guard let task = SecTaskCreateFromSelf(nil), let value = SecTaskCopyValueForEntitlement(task, "com.apple.developer.icloud-services" as CFString, nil) else { return false } return (value as? [String])?.contains("CloudKit") ?? false #else return true #endif } } /// What the house "iCloud Sync" and "Diagnostics" settings show. Same fields and values as /// Inkspring's MobileLibrary (accountStatus, lastCheck, lastCloudContact, error, syncErrorCode), so every /// Protomota iCloud app reports sync the same way. See the app-factory skill. public struct CloudSyncStatus: Equatable, Sendable { /// "Not checked", "Connected" or "Unavailable". public var accountStatus = "Not checked" public var lastCheck: Date? public var lastCloudContact: Date? /// Whether iCloud has the Mac's snapshot; nil until checked. public var snapshotFound: Bool? /// When the snapshot in iCloud was refreshed on the Mac. public var snapshotDate: Date? public var error: String? /// " ()", e.g. "CKErrorDomain (12)". public var syncErrorCode: String? public init() {} public mutating func record(_ error: Error) { let failure = error as NSError syncErrorCode = "\(failure.domain) (\(failure.code))" self.error = error.localizedDescription } public mutating func clearError() { error = nil; syncErrorCode = nil } }