Glimmer / app · glimmertoday.ai / native / Glimmer / JournalCloud.swift
| 1 | import CryptoKit |
| 2 | import Foundation |
| 3 | |
| 4 | struct JournalCloudState: Codable { |
| 5 | var enabled = false |
| 6 | var device = UUID() |
| 7 | var account: Data? |
| 8 | var acceptAccountChange = false |
| 9 | var replica: JournalReplica |
| 10 | } |
| 11 | |
| 12 | /// Keep the journal readable by existing releases, backups and the local MCP command. |
| 13 | struct SavedJournal: Codable { |
| 14 | var journal: Journal |
| 15 | var cloud: JournalCloudState? |
| 16 | |
| 17 | private enum CodingKeys: String, CodingKey { case cloud = "_glimmerCloud" } |
| 18 | |
| 19 | init(journal: Journal, cloud: JournalCloudState?) { |
| 20 | self.journal = journal |
| 21 | self.cloud = cloud |
| 22 | } |
| 23 | |
| 24 | init(from decoder: Decoder) throws { |
| 25 | journal = try Journal(from: decoder) |
| 26 | cloud = try decoder.container(keyedBy: CodingKeys.self).decodeIfPresent(JournalCloudState.self, forKey: .cloud) |
| 27 | } |
| 28 | |
| 29 | func encode(to encoder: Encoder) throws { |
| 30 | try journal.encode(to: encoder) |
| 31 | var container = encoder.container(keyedBy: CodingKeys.self) |
| 32 | try container.encodeIfPresent(cloud, forKey: .cloud) |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | /// Each installation writes its own file. No device has to overwrite another device's snapshot. |
| 37 | @MainActor |
| 38 | final class JournalCloud { |
| 39 | struct Connection: Equatable, Sendable { |
| 40 | let folder: URL |
| 41 | let account: Data |
| 42 | } |
| 43 | |
| 44 | struct Exchange: Sendable { |
| 45 | var remote = JournalReplica() |
| 46 | var own: JournalReplica? |
| 47 | var downloading = false |
| 48 | } |
| 49 | |
| 50 | private var query: NSMetadataQuery? |
| 51 | private var connection: Connection? |
| 52 | |
| 53 | nonisolated static let container = "iCloud.com.protomota.glimmer" |
| 54 | nonisolated static let fileExtension = "glimmerjournal" |
| 55 | |
| 56 | func stop() { |
| 57 | query?.stop() |
| 58 | query = nil |
| 59 | connection = nil |
| 60 | } |
| 61 | |
| 62 | func files(in connection: Connection) throws -> [URL]? { |
| 63 | if self.connection != connection { |
| 64 | stop() |
| 65 | let query = NSMetadataQuery() |
| 66 | query.searchScopes = [NSMetadataQueryUbiquitousDataScope] |
| 67 | query.predicate = NSPredicate(format: "%K ENDSWITH %@", NSMetadataItemFSNameKey, "." + Self.fileExtension) |
| 68 | guard query.start() else { throw CocoaError(.fileReadUnknown) } |
| 69 | self.query = query |
| 70 | self.connection = connection |
| 71 | } |
| 72 | guard let query, !query.isGathering else { return nil } |
| 73 | query.disableUpdates() |
| 74 | defer { query.enableUpdates() } |
| 75 | let folder = connection.folder.standardizedFileURL.path |
| 76 | return query.results.compactMap { result in |
| 77 | guard let item = result as? NSMetadataItem, |
| 78 | let url = item.value(forAttribute: NSMetadataItemURLKey) as? URL, |
| 79 | url.deletingLastPathComponent().standardizedFileURL.path == folder, |
| 80 | UUID(uuidString: url.deletingPathExtension().lastPathComponent) != nil else { return nil } |
| 81 | return url |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | nonisolated static func connect() throws -> Connection? { |
| 86 | guard let account = identity(), |
| 87 | let root = FileManager.default.url(forUbiquityContainerIdentifier: container) else { return nil } |
| 88 | try requireAccount(account) |
| 89 | let folder = root.appending(path: "JournalV1", directoryHint: .isDirectory) |
| 90 | return Connection(folder: folder, account: account) |
| 91 | } |
| 92 | |
| 93 | nonisolated static func pull(_ files: [URL], device: UUID, in connection: Connection) throws -> Exchange { |
| 94 | try requireAccount(connection.account) |
| 95 | var exchange = Exchange() |
| 96 | for file in files { |
| 97 | let metadata = try file.resourceValues(forKeys: [.ubiquitousItemDownloadingStatusKey]) |
| 98 | if let status = metadata.ubiquitousItemDownloadingStatus, status != .current { |
| 99 | try FileManager.default.startDownloadingUbiquitousItem(at: file) |
| 100 | exchange.downloading = true |
| 101 | continue |
| 102 | } |
| 103 | let saved = try read(file) |
| 104 | exchange.remote.merge(saved) |
| 105 | if UUID(uuidString: file.deletingPathExtension().lastPathComponent) == device { exchange.own = saved } |
| 106 | } |
| 107 | try requireAccount(connection.account) |
| 108 | return exchange |
| 109 | } |
| 110 | |
| 111 | nonisolated static func push(_ replica: JournalReplica, device: UUID, in connection: Connection) throws -> Bool { |
| 112 | try requireAccount(connection.account) |
| 113 | let url = connection.folder.appending(path: device.uuidString + "." + fileExtension) |
| 114 | try FileManager.default.createDirectory(at: connection.folder, withIntermediateDirectories: true) |
| 115 | try write(replica, to: url) { try requireAccount(connection.account) } |
| 116 | return try uploaded(device: device, in: connection) |
| 117 | } |
| 118 | |
| 119 | nonisolated static func uploaded(device: UUID, in connection: Connection) throws -> Bool { |
| 120 | try requireAccount(connection.account) |
| 121 | let url = connection.folder.appending(path: device.uuidString + "." + fileExtension) |
| 122 | return try url.resourceValues(forKeys: [.ubiquitousItemIsUploadedKey]).ubiquitousItemIsUploaded == true |
| 123 | } |
| 124 | |
| 125 | nonisolated static func read(_ file: URL) throws -> JournalReplica { |
| 126 | var coordinationError: NSError? |
| 127 | var readResult: Result<JournalReplica, Error>? |
| 128 | NSFileCoordinator().coordinate(readingItemAt: file, options: [], error: &coordinationError) { url in |
| 129 | readResult = Result { |
| 130 | let decoder = JSONDecoder() |
| 131 | var merged = try decoder.decode(JournalReplica.self, from: Data(contentsOf: url)) |
| 132 | for conflict in NSFileVersion.unresolvedConflictVersionsOfItem(at: url) ?? [] { |
| 133 | let version = try decoder.decode(JournalReplica.self, from: Data(contentsOf: conflict.url)) |
| 134 | merged.merge(version) |
| 135 | } |
| 136 | return merged |
| 137 | } |
| 138 | } |
| 139 | if let coordinationError { throw coordinationError } |
| 140 | guard let readResult else { throw CocoaError(.fileReadUnknown) } |
| 141 | return try readResult.get() |
| 142 | } |
| 143 | |
| 144 | nonisolated static func write(_ replica: JournalReplica, to file: URL, beforeWrite: () throws -> Void = {}) throws { |
| 145 | let data = try JSONEncoder().encode(replica) |
| 146 | var coordinationError: NSError? |
| 147 | var writeResult: Result<Void, Error>? |
| 148 | NSFileCoordinator().coordinate(writingItemAt: file, options: .forReplacing, error: &coordinationError) { url in |
| 149 | writeResult = Result { |
| 150 | try beforeWrite() |
| 151 | try data.write(to: url, options: .atomic) |
| 152 | } |
| 153 | } |
| 154 | if let coordinationError { throw coordinationError } |
| 155 | guard let writeResult else { throw CocoaError(.fileWriteUnknown) } |
| 156 | try writeResult.get() |
| 157 | } |
| 158 | |
| 159 | private nonisolated static func identity() -> Data? { |
| 160 | guard let token = FileManager.default.ubiquityIdentityToken, |
| 161 | let encoded = try? NSKeyedArchiver.archivedData(withRootObject: token, requiringSecureCoding: true) else { return nil } |
| 162 | return Data(SHA256.hash(data: encoded)) |
| 163 | } |
| 164 | |
| 165 | private nonisolated static func requireAccount(_ account: Data) throws { |
| 166 | guard identity() == account else { throw CocoaError(.userCancelled) } |
| 167 | } |
| 168 | } |