Repository.swift (21251B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import Foundation 3 import GitLite 4 5 /// Addresses of the Subsurface cloud (git storage over HTTPS, Basic authentication with email + password). 6 public enum SubsurfaceCloud { 7 public static let defaultHost = "cloud.subsurface-divelog.org" 8 9 /// Same sanitizing as Subsurface: lowercase, then letters, digits and "@ . _ + -" only. 10 public static func sanitize(email: String) -> String { 11 String(email.lowercased().unicodeScalars.filter { 12 ($0.isASCII && ($0.properties.isAlphabetic || $0.properties.numericType != nil)) || "@._+-".unicodeScalars.contains($0) 13 }.map(Character.init)) 14 } 15 16 /// The user's repository: `https://host/git/<email>`, branch `<email>`. 17 public static func repositoryURL(email: String, host: String = defaultHost) -> URL { 18 URL(string: "https://\(host)/git/")!.appendingPathComponent(sanitize(email: email)) 19 } 20 21 public static func transport(email: String, password: String, host: String = defaultHost) -> HTTPTransport { 22 let clean = sanitize(email: email) 23 return HTTPTransport(baseURL: repositoryURL(email: clean, host: host), username: clean, password: password) 24 } 25 } 26 27 /// Subsurface cloud account: creation, and verification with the code received by email. 28 /// Same exchange as Subsurface (`core/cloudstorage.cpp`): a text "email password [code]" sent by POST. 29 public enum CloudAccount { 30 public enum Status: Equatable, Sendable { 31 case verified // account ready 32 case needsPIN // a code was sent by email 33 case invalidPIN 34 case rejected(String) // message from the server 35 } 36 37 public static func isValid(email: String) -> Bool { 38 email.count <= 254 && email.range(of: "^[a-zA-Z0-9.+_-]{1,64}@[a-zA-Z0-9.+_-]+\\.[a-zA-Z0-9+_-]{2,}$", options: .regularExpression) != nil 39 } 40 41 /// The cloud only accepts letters, digits and "@ . + _ -" in the password. 42 public static func isValid(password: String) -> Bool { 43 password.range(of: "^[a-zA-Z0-9@.+_-]+$", options: .regularExpression) != nil 44 } 45 46 public static func status(fromReply reply: String) -> Status { 47 let text = reply.trimmingCharacters(in: .whitespacesAndNewlines) 48 switch text { 49 case "[VERIFIED]", "[OK]": return .verified 50 case "[VERIFY]": return .needsPIN 51 case "Invalid PIN": return .invalidPIN 52 default: return .rejected(text.isEmpty ? "empty reply" : String(text.prefix(200))) 53 } 54 } 55 56 public static func request(email: String, password: String, pin: String?, host: String = SubsurfaceCloud.defaultHost, 57 userAgent: String) -> URLRequest { 58 var request = URLRequest(url: URL(string: "https://\(host)/\(pin == nil ? "storage" : "verify")")!) 59 request.httpMethod = "POST" 60 request.setValue("text/plain", forHTTPHeaderField: "Content-Type") 61 request.setValue("text/xml, text/plain", forHTTPHeaderField: "Accept") 62 request.setValue(userAgent, forHTTPHeaderField: "User-Agent") 63 let fields = [SubsurfaceCloud.sanitize(email: email), password] + (pin.map { [$0] } ?? []) 64 request.httpBody = Data(fields.joined(separator: " ").utf8) 65 return request 66 } 67 68 /// Without `pin`: creates the account (or confirms that it exists). With `pin`: validates the code received by email. 69 public static func submit(email: String, password: String, pin: String? = nil, userAgent: String, 70 session: URLSession = .shared) async throws -> Status { 71 let data: Data 72 do { 73 (data, _) = try await session.data(for: request(email: email, password: password, pin: pin, userAgent: userAgent)) 74 } catch { 75 throw GitError.network(error.localizedDescription) 76 } 77 return status(fromReply: String(decoding: data, as: UTF8.self)) 78 } 79 } 80 81 /// What an import did: dives added as new dives, and dives merged into a dive that was already there. 82 public struct ImportSummary: Sendable, Equatable { 83 public var added = 0 84 public var merged = 0 85 public init() {} 86 } 87 88 public struct SyncReport: Sendable, Equatable { 89 public var downloaded = false 90 public var sent: [String] = [] 91 public var dropped: [String] = [] 92 public var head: ObjectID? 93 public init() {} 94 } 95 96 /// Store that records what is written to it, to know which objects to send to the server. 97 final class RecordingStore: ObjectStore, @unchecked Sendable { 98 let base: ObjectStore 99 private var recorded = [ObjectID: GitObject]() 100 private let lock = NSLock() 101 102 init(base: ObjectStore) { self.base = base } 103 104 func get(_ id: ObjectID) -> GitObject? { base.get(id) } 105 func contains(_ id: ObjectID) -> Bool { base.contains(id) } 106 func put(_ object: GitObject) throws -> ObjectID { 107 let id = try base.put(object) 108 lock.lock(); defer { lock.unlock() } 109 recorded[id] = object 110 return id 111 } 112 113 var objects: [GitObject] { 114 lock.lock(); defer { lock.unlock() } 115 return Array(recorded.values) 116 } 117 } 118 119 /// Local copy of the logbook: git objects on disk, last known state of the server, and pending changes. 120 public actor LogRepository { 121 struct State: Codable { 122 var head: ObjectID? 123 var shallow: [ObjectID] = [] 124 var pending: [LogChange] = [] 125 var lastSync: Date? 126 } 127 128 public nonisolated let directory: URL 129 public nonisolated let branch: String 130 public nonisolated let authorName: String 131 public nonisolated let authorEmail: String 132 public nonisolated let store: FileObjectStore 133 private var state: State 134 private var stateURL: URL { directory.appendingPathComponent("state.json") } 135 136 public init(directory: URL, branch: String, authorName: String, authorEmail: String) throws { 137 self.directory = directory 138 self.branch = branch 139 self.authorName = authorName 140 self.authorEmail = authorEmail 141 try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) 142 self.store = try FileObjectStore(directory: directory.appendingPathComponent("objects")) 143 if let data = try? Data(contentsOf: directory.appendingPathComponent("state.json")), 144 let decoded = try? JSONDecoder().decode(State.self, from: data) { 145 self.state = decoded 146 } else { 147 self.state = State() 148 } 149 } 150 151 public var pending: [LogChange] { state.pending } 152 public var head: ObjectID? { state.head } 153 public var lastSync: Date? { state.lastSync } 154 155 private func save() throws { 156 try JSONEncoder().encode(state).write(to: stateURL, options: .atomic) 157 } 158 159 private func headTree() throws -> ObjectID? { 160 try state.head.map { try store.commit($0).tree } 161 } 162 163 /// Working tree: last state of the server + pending changes (those that no longer apply are skipped). 164 private func workingTree() throws -> ObjectID? { 165 var root = try headTree() 166 for change in state.pending { 167 if let next = try? LogEditor.apply(change, root: root, store: store) { root = next } 168 } 169 return root 170 } 171 172 /// The logbook as the user should see it, local changes included. 173 public func logbook() throws -> Logbook { 174 guard let root = try workingTree() else { return Logbook() } 175 return try LogLoader.load(root: root, store: store) 176 } 177 178 public func profile(of dive: Dive) throws -> [DiveComputer] { 179 try LogLoader.loadProfile(of: dive, store: store) 180 } 181 182 /// Adds a change to the queue; fails if it does not apply to the current logbook. 183 @discardableResult 184 public func enqueue(_ change: LogChange) throws -> Logbook { 185 let root = try LogEditor.apply(change, root: try workingTree(), store: store) 186 state.pending.append(change) 187 try save() 188 return try LogLoader.load(root: root, store: store) 189 } 190 191 /// What importing each dive would do (see `DiveMerge.disposition`), by dive identifier. Unlike a look at the 192 /// dive list, this reads the profiles around each dive, so a dive made of several immersions is known up to 193 /// the end of its last one, not only for the time spent underwater. 194 public func dispositions(of dives: [ImportedDive]) throws -> [String: DiveMerge.Disposition] { 195 guard let root = try workingTree() else { return [:] } 196 var found = [String: DiveMerge.Disposition]() 197 for dive in dives { found[dive.id] = try LogEditor.disposition(of: dive, root: root, store: store).0 } 198 return found 199 } 200 201 /// Queues the imported dives, from the oldest to the most recent: sites created as needed (matched by 202 /// name), numbers continuing the logbook's. A dive that overlaps one of the logbook joins it as one more dive 203 /// computer (see `DiveMerge.disposition`); the same dive from the same computer is left aside. 204 @discardableResult 205 public func importDives(_ dives: [ImportedDive]) throws -> ImportSummary { 206 var summary = ImportSummary() 207 var log = try logbook() 208 for dive in dives.sorted(by: { $0.when < $1.when }) { 209 var existing: Dive? 210 if let root = try workingTree() { 211 switch try LogEditor.disposition(of: dive, root: root, store: store).0 { 212 case .duplicate: continue 213 case .merge(let found): existing = found 214 case .new: break 215 } 216 } 217 var siteUUID: UInt32? 218 let name = dive.site.trimmingCharacters(in: .whitespacesAndNewlines) 219 // A dive that already has its site keeps it. 220 if !name.isEmpty, existing?.siteUUID == nil { 221 if let existing = log.sites.values.first(where: { $0.name.compare(name, options: [.caseInsensitive, .diacriticInsensitive]) == .orderedSame }) { 222 siteUUID = existing.uuid 223 // The site exists without a position and the file provides one: set it. 224 if !existing.hasLocation, let latitude = dive.latitude, let longitude = dive.longitude { 225 log = try enqueue(.locateSite(uuid: existing.uuid, latitude: latitude, longitude: longitude)) 226 } 227 } else { 228 var uuid = UInt32.random(in: 1...UInt32.max) 229 while log.sites[uuid] != nil { uuid = UInt32.random(in: 1...UInt32.max) } 230 log = try enqueue(.addSite(uuid: uuid, name: name, latitude: dive.latitude, longitude: dive.longitude)) 231 siteUUID = uuid 232 } 233 } 234 do { 235 log = try enqueue(.importDive(dive, number: existing?.number ?? log.nextNumber, siteUUID: siteUUID)) 236 if existing == nil { summary.added += 1 } else { summary.merged += 1 } 237 } catch ChangeError.diveAlreadyExists { 238 continue 239 } 240 } 241 return summary 242 } 243 244 /// Queues the merge of dives of the logbook into one: the earliest keeps its date, number, site and notes, the 245 /// others fill its gaps and bring their dive computers (see `LogEditor.merged`). The numbers of the dives that 246 /// disappear are not left empty: the dives numbered after them move down. 247 @discardableResult 248 public func mergeDives(_ dives: [Dive]) throws -> Logbook { 249 let ordered = dives.sorted { ($0.when, $0.number) < ($1.when, $1.number) } 250 guard let target = ordered.first, ordered.count > 1 else { return try logbook() } 251 let others = ordered.dropFirst().map { DiveRef(when: $0.when, number: $0.number) } 252 var log = try enqueue(.mergeDives(when: target.when, number: target.number, others: others)) 253 let freed = Set(others.map(\.number).filter { $0 > 0 && $0 != target.number }).subtracting(log.dives.map(\.number)) 254 guard let lowest = freed.min() else { return log } 255 for dive in log.dives.sorted(by: { $0.number < $1.number }) where dive.number > lowest { 256 let shift = freed.filter { $0 < dive.number }.count 257 log = try enqueue(.renumberDive(when: dive.when, number: dive.number, newNumber: dive.number - shift)) 258 } 259 return log 260 } 261 262 public func discardPending() throws { 263 state.pending = [] 264 try save() 265 } 266 267 /// Every file of the logbook as the user sees it (pending changes included), by path: what a backup holds, 268 /// and what `importTree` takes back. 269 public func exportFiles() throws -> [String: String] { 270 var files = [String: String]() 271 func walk(_ tree: ObjectID, _ prefix: String) throws { 272 for entry in try store.tree(tree) { 273 let path = prefix.isEmpty ? entry.name : prefix + "/" + entry.name 274 if entry.isTree { 275 try walk(entry.id, path) 276 } else { 277 files[path] = String(decoding: try store.blob(entry.id), as: UTF8.self) 278 } 279 } 280 } 281 if let root = try workingTree() { try walk(root, "") } 282 return files 283 } 284 285 /// The logbook (or some of its dives) as a UDDF document, profiles included. 286 public func uddf(dives only: [Dive]? = nil, generator: String, version: String) throws -> String { 287 let log = try logbook() 288 let exported = try (only ?? log.dives).map { dive in 289 UDDF.ExportedDive(dive: dive, computers: try LogLoader.loadProfile(of: dive, store: store), site: log.site(of: dive)) 290 } 291 return UDDF.document(exported, generator: generator, version: version) 292 } 293 294 /// Sends a whole logbook to the server as the new state of the branch, on top of whatever is there (which 295 /// stays in the history), and makes it the local logbook. For a logbook kept without an account, the day its 296 /// owner connects one. 297 public func replaceRemote(files: [String: String], transport: GitTransport, appVersion: String = "0.1") async throws { 298 let client = GitClient(transport: transport, store: store) 299 let remoteHead = try await client.refs().branch(branch) 300 let recorder = RecordingStore(base: store) 301 let root = try LogEditor.buildTree(files: files, store: recorder) 302 let who = Commit.signature(name: authorName, email: authorEmail) 303 let message = "Logbook kept on the iPhone, now sent to the cloud\n\nCreated by \(authorName) \(appVersion)\n" 304 let commit = GitObject(type: .commit, data: Commit(tree: root, parents: remoteHead.map { [$0] } ?? [], 305 author: who, committer: who, message: message).serialize()) 306 let commitID = try recorder.put(commit) 307 try await client.push(ref: "refs/heads/\(branch)", old: remoteHead, new: commitID, objects: recorder.objects) 308 state = State(head: commitID, lastSync: Date()) 309 try save() 310 } 311 312 /// Replaces the local logbook with a tree built locally (no server: demo, logbook without an account, backup). 313 public func importTree(files: [String: String]) throws { 314 let root = try LogEditor.buildTree(files: files, store: store) 315 let who = Commit.signature(name: authorName, email: authorEmail) 316 let commit = Commit(tree: root, parents: [], author: who, committer: who, message: "Logbook\n") 317 state = State(head: try store.put(GitObject(type: .commit, data: commit.serialize()))) 318 try save() 319 } 320 321 /// Commits the pending changes to the local logbook without sending anything (demo mode). 322 public func commitPendingLocally() throws { 323 guard !state.pending.isEmpty, let root = try workingTree() else { return } 324 let who = Commit.signature(name: authorName, email: authorEmail) 325 let commit = Commit(tree: root, parents: state.head.map { [$0] } ?? [], author: who, committer: who, message: "Local changes\n") 326 state.head = try store.put(GitObject(type: .commit, data: commit.serialize())) 327 state.pending = [] 328 try save() 329 } 330 331 /// Erases the local copy (sign-out). 332 public func erase() throws { 333 state = State() 334 try? FileManager.default.removeItem(at: directory) 335 try FileManager.default.createDirectory(at: store.directory, withIntermediateDirectories: true) 336 } 337 338 /// Fetches the state of the server, replays the pending changes on top of it and sends them. 339 public func sync(transport: GitTransport, appVersion: String = "0.1") async throws -> SyncReport { 340 var lastError: Error = GitError.pushRejected("too many attempts") 341 for _ in 0..<3 { 342 do { 343 return try await syncOnce(transport: transport, appVersion: appVersion) 344 } catch let error as GitError { 345 // Another device pushed between our fetch and our push: start over. 346 guard case .pushRejected = error else { throw error } 347 lastError = error 348 } 349 } 350 throw lastError 351 } 352 353 private func syncOnce(transport: GitTransport, appVersion: String) async throws -> SyncReport { 354 var report = SyncReport() 355 let client = GitClient(transport: transport, store: store) 356 let remote = try await client.refs() 357 let remoteHead = remote.branch(branch) 358 359 if let remoteHead { 360 if remoteHead != state.head || !store.contains(remoteHead) { 361 try await download(remoteHead, client: client, capabilities: remote.capabilities, fresh: false) 362 report.downloaded = true 363 } 364 // Makes sure the whole tree is there; otherwise, fresh copy. 365 do { 366 _ = try LogLoader.load(root: try store.commit(remoteHead).tree, store: store) 367 } catch let error as GitError { 368 guard case .missingObject = error else { throw error } 369 try await download(remoteHead, client: client, capabilities: remote.capabilities, fresh: true) 370 report.downloaded = true 371 } 372 } else { 373 // Account without a logbook on the server. 374 state.head = nil 375 state.shallow = [] 376 } 377 return try await finish(report: report, client: client, remoteHead: remoteHead, appVersion: appVersion) 378 } 379 380 /// Downloads the state `remoteHead` (without history). First incrementally from what we already have, 381 /// then, if the server refuses or the local copy is incomplete, in full. 382 private func download(_ remoteHead: ObjectID, client: GitClient, capabilities: Set<String>, fresh: Bool) async throws { 383 let known = fresh ? nil : state.head.flatMap { store.contains($0) ? $0 : nil } 384 var done = false 385 if let known { 386 do { 387 state.shallow = try await client.fetch(want: remoteHead, have: [known], shallow: state.shallow, depth: 1, 388 capabilities: capabilities) 389 done = true 390 } catch let error as GitError { 391 switch error { 392 case .network, .unauthorized, .notFound, .http: throw error 393 default: break 394 } 395 } 396 } 397 if !done { 398 state.shallow = try await client.fetch(want: remoteHead, depth: 1, capabilities: capabilities) 399 } 400 state.head = remoteHead 401 try save() 402 } 403 404 private func finish(report initial: SyncReport, client: GitClient, remoteHead: ObjectID?, appVersion: String) async throws -> SyncReport { 405 var report = initial 406 if !state.pending.isEmpty { 407 let recorder = RecordingStore(base: store) 408 let base = try remoteHead.map { try store.commit($0).tree } 409 var root = base 410 var applied = [LogChange]() 411 for change in state.pending { 412 do { 413 root = try LogEditor.apply(change, root: root, store: recorder) 414 applied.append(change) 415 } catch let error as ChangeError { 416 report.dropped.append("\(change.summary): \(error)") 417 } 418 } 419 if let root, root != base, !applied.isEmpty { 420 let who = Commit.signature(name: authorName, email: authorEmail) 421 let lines = applied.map { "- \($0.summary)\n" }.joined() 422 let message = "Changes made: \n\n\(lines)\nCreated by \(authorName) \(appVersion)\n" 423 let commit = GitObject(type: .commit, data: Commit(tree: root, parents: remoteHead.map { [$0] } ?? [], 424 author: who, committer: who, message: message).serialize()) 425 let commitID = try recorder.put(commit) 426 try await client.push(ref: "refs/heads/\(branch)", old: remoteHead, new: commitID, objects: recorder.objects) 427 state.head = commitID 428 if remoteHead == nil { state.shallow = [] } 429 report.sent = applied.map(\.summary) 430 } 431 state.pending = [] 432 } 433 state.lastSync = Date() 434 report.head = state.head 435 try save() 436 return report 437 } 438 }