AppModel.swift (34576B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import Foundation 3 import DivePlanner 4 import GitLite 5 import Observation 6 import Photos 7 import SubsurfaceLog 8 9 struct DiveSection: Identifiable { 10 let id: String 11 let title: String 12 let subtitle: String 13 var dives: [Dive] 14 } 15 16 @MainActor 17 @Observable 18 final class AppModel { 19 enum Phase { case launching, signedOut, ready } 20 enum SyncState: Equatable { case idle, syncing, failed(String) } 21 22 var phase = Phase.launching 23 var logbook = Logbook() 24 var syncState = SyncState.idle 25 var lastSync: Date? 26 var pending: [LogChange] = [] 27 var email = "" 28 var isDemo = false 29 /// The logbook lives on this iPhone only (and in its iCloud backup): no Subsurface cloud account. 30 var isLocal = false 31 var notices: [String] = [] 32 /// Copy of the logbook and of the settings in iCloud Drive. 33 let backup = LogbookBackup() 34 var units = Units(imperial: UserDefaults.standard.object(forKey: "imperial") as? Bool ?? (Locale.current.measurementSystem == .us)) 35 36 @ObservationIgnored private var repository: LogRepository? 37 @ObservationIgnored private var password = "" 38 @ObservationIgnored private var syncTask: Task<Void, Never>? 39 40 // MARK: Startup and account 41 42 func start() async { 43 guard phase == .launching else { return } 44 if ProcessInfo.processInfo.arguments.contains("-demo") { 45 await startDemo() 46 return 47 } 48 #if DEBUG 49 // Simulator testing against a real logbook: credentials come from the environment, never in a release build. 50 let environment = ProcessInfo.processInfo.environment 51 if let devEmail = environment["DEV_CLOUD_EMAIL"], let devPassword = environment["DEV_CLOUD_PASSWORD"] { 52 do { 53 try await signIn(email: devEmail, password: devPassword) 54 } catch { 55 phase = .signedOut 56 } 57 return 58 } 59 #endif 60 // Screenshots and tests: the buttons of the sign-in screen, without tapping them. 61 if LaunchOptions.flag("-restoreBackup") { 62 if (try? await restoreFromBackup()) == nil { phase = .signedOut } 63 return 64 } 65 if LaunchOptions.flag("-startLocal"), (try? await startLocal()) != nil { return } 66 if UserDefaults.standard.bool(forKey: Self.localKey) { 67 do { 68 try await openLocal() 69 phase = .ready 70 } catch { 71 phase = .signedOut 72 } 73 return 74 } 75 let saved = UserDefaults.standard.string(forKey: "email") ?? "" 76 guard !saved.isEmpty, let secret = Keychain.password(account: saved) else { 77 phase = .signedOut 78 await backup.refresh() 79 return 80 } 81 email = saved 82 password = secret 83 do { 84 try await open(account: saved) 85 phase = .ready 86 scheduleSync() 87 } catch { 88 phase = .signedOut 89 } 90 } 91 92 private static func storage(for account: String) throws -> URL { 93 let base = try FileManager.default.url(for: .applicationSupportDirectory, in: .userDomainMask, appropriateFor: nil, create: true) 94 let safe = String(account.map { $0.isLetter || $0.isNumber ? $0 : "_" }) 95 return base.appendingPathComponent("logbooks").appendingPathComponent(safe) 96 } 97 98 private func open(account: String) async throws { 99 let repo = try LogRepository(directory: try Self.storage(for: account), branch: account, 100 authorName: Brand.name, authorEmail: account) 101 repository = repo 102 try await reload() 103 } 104 105 private func reload() async throws { 106 guard let repository else { return } 107 logbook = try await repository.logbook() 108 pending = await repository.pending 109 lastSync = await repository.lastSync 110 if !isDemo { backup.schedule(repository: repository, account: isLocal ? "" : email) } 111 } 112 113 // MARK: Logbook without an account 114 115 private static let localKey = "localLogbook" 116 private static let localFolder = "_local" 117 118 private func openLocal() async throws { 119 let repo = try LogRepository(directory: try Self.storage(for: Self.localFolder), branch: "local", 120 authorName: Brand.name, authorEmail: "local") 121 repository = repo 122 isLocal = true 123 isDemo = false 124 email = "" 125 try await reload() 126 } 127 128 /// Starts (or goes back to) a logbook kept on this iPhone, optionally from the files of a backup. 129 func startLocal(files: [String: String]? = nil) async throws { 130 do { 131 try await openLocal() 132 guard let repository else { return } 133 if let files { 134 try await repository.discardPending() 135 try await repository.importTree(files: files) 136 } else if await repository.head == nil { 137 _ = try await repository.enqueue(.ensureSettings) 138 try await repository.commitPendingLocally() 139 } 140 UserDefaults.standard.set(true, forKey: Self.localKey) 141 try await reload() 142 syncState = .idle 143 phase = .ready 144 } catch { 145 isLocal = false 146 repository = nil 147 throw AppError.message(Self.describe(error)) 148 } 149 } 150 151 /// Restores the logbook from the iCloud backup, as a logbook without an account. 152 func restoreFromBackup() async throws { 153 let files = try await backup.restore() 154 units = Units(imperial: UserDefaults.standard.object(forKey: "imperial") as? Bool ?? units.imperial) 155 try await startLocal(files: files) 156 } 157 158 /// The Subsurface cloud account already holds dives: the user has to say which logbook stays. 159 struct CloudNotEmpty: Error { 160 let cloudDives: Int 161 let localDives: Int 162 } 163 164 /// Connects a logbook kept on this iPhone to a Subsurface cloud account. An account without dives receives the 165 /// logbook. When the account has dives too, `keepLocal` decides: true sends this iPhone's logbook (the cloud's 166 /// stays in its history), false takes the cloud's (this iPhone's stays in the iCloud backup history), nil 167 /// throws `CloudNotEmpty`. 168 func connectCloud(email rawEmail: String, password rawPassword: String, keepLocal: Bool? = nil) async throws { 169 guard isLocal, let local = repository else { return } 170 let account = SubsurfaceCloud.sanitize(email: rawEmail) 171 guard account.contains("@"), !rawPassword.isEmpty else { 172 throw AppError.message(String(localized: "Enter your email and password.")) 173 } 174 let transport = SubsurfaceCloud.transport(email: account, password: rawPassword) 175 do { 176 try await local.commitPendingLocally() 177 let files = try await local.exportFiles() 178 let localDives = logbook.dives.count 179 let cloud = try LogRepository(directory: try Self.storage(for: account), branch: account, 180 authorName: Brand.name, authorEmail: account) 181 _ = try await cloud.sync(transport: transport, appVersion: Brand.shortVersion) 182 let cloudDives = try await cloud.logbook().dives.count 183 if localDives > 0 { 184 if cloudDives > 0, keepLocal == nil { throw CloudNotEmpty(cloudDives: cloudDives, localDives: localDives) } 185 if cloudDives == 0 || keepLocal == true { 186 try await cloud.replaceRemote(files: files, transport: transport, appVersion: Brand.shortVersion) 187 } 188 } 189 Keychain.save(password: rawPassword, account: account) 190 UserDefaults.standard.set(account, forKey: "email") 191 UserDefaults.standard.removeObject(forKey: Self.localKey) 192 try? await local.erase() 193 repository = cloud 194 isLocal = false 195 email = account 196 password = rawPassword 197 try await reload() 198 scheduleSync() 199 } catch let error as CloudNotEmpty { 200 throw error 201 } catch { 202 throw AppError.message(Self.describe(error)) 203 } 204 } 205 206 /// Checks the credentials with the cloud, then downloads the logbook. 207 func signIn(email rawEmail: String, password rawPassword: String) async throws { 208 let account = SubsurfaceCloud.sanitize(email: rawEmail) 209 guard account.contains("@"), !rawPassword.isEmpty else { 210 throw AppError.message(String(localized: "Enter your email and password.")) 211 } 212 let transport = SubsurfaceCloud.transport(email: account, password: rawPassword) 213 do { 214 _ = try await GitClient(transport: transport, store: MemoryObjectStore()).refs() 215 } catch { 216 throw AppError.message(Self.describe(error)) 217 } 218 Keychain.save(password: rawPassword, account: account) 219 UserDefaults.standard.set(account, forKey: "email") 220 email = account 221 password = rawPassword 222 isDemo = false 223 try await open(account: account) 224 phase = .ready 225 await sync() 226 } 227 228 /// Leaves the account (or the demo, or erases a logbook kept without an account). With `keepLogbook`, the 229 /// logbook of a cloud account stays on this iPhone as a logbook without an account. 230 func signOut(keepLogbook: Bool = false) async { 231 syncTask?.cancel() 232 var kept: [String: String]? 233 if keepLogbook, !isDemo, !isLocal, let repository { kept = try? await repository.exportFiles() } 234 if let repository { try? await repository.erase() } 235 if isLocal { 236 UserDefaults.standard.removeObject(forKey: Self.localKey) 237 } else if !isDemo { 238 Keychain.delete(account: email) 239 UserDefaults.standard.removeObject(forKey: "email") 240 } 241 repository = nil 242 logbook = Logbook() 243 pending = [] 244 notices = [] 245 lastSync = nil 246 email = "" 247 password = "" 248 isDemo = false 249 isLocal = false 250 syncState = .idle 251 if let kept, (try? await startLocal(files: kept)) != nil { return } 252 phase = .signedOut 253 await backup.refresh() 254 } 255 256 func startDemo() async { 257 do { 258 let directory = FileManager.default.temporaryDirectory.appendingPathComponent("demo-logbook") 259 try? FileManager.default.removeItem(at: directory) 260 let repo = try LogRepository(directory: directory, branch: "demo", authorName: Brand.name, authorEmail: "demo@example.com") 261 try await repo.importTree(files: DemoData.files()) 262 repository = repo 263 isDemo = true 264 email = "demo@example.com" 265 try await reload() 266 phase = .ready 267 if LaunchOptions.flag("-demoChanges") { await demoChanges() } 268 } catch { 269 phase = .signedOut 270 } 271 } 272 273 /// End-to-end test of the editing pipeline (launch option `-demoChanges`). 274 private func demoChanges() async { 275 guard let latest = logbook.dives.first else { return } 276 do { 277 try await apply(.editDive(when: latest.when, number: latest.number, 278 fields: ["buddy": String(localized: "Edited by the test"), "rating": "1"])) 279 let uuid = newSiteUUID() 280 try await apply(.addSite(uuid: uuid, name: String(localized: "Site added by the test"), latitude: nil, longitude: nil)) 281 var dive = NewDive(when: latest.when + 86_400, number: logbook.nextNumber, durationSeconds: 1500, maxDepth: 9.5) 282 dive.siteUUID = uuid 283 try await apply(.addDive(dive)) 284 } catch { 285 let reason = Self.describe(error) 286 notices.append(String(localized: "Test failed: \(reason)")) 287 } 288 } 289 290 // MARK: Sync 291 292 func scheduleSync() { 293 syncTask?.cancel() 294 syncTask = Task { await sync() } 295 } 296 297 func sync() async { 298 guard let repository, syncState != .syncing else { return } 299 if isDemo || isLocal { 300 try? await repository.commitPendingLocally() 301 try? await reload() 302 return 303 } 304 syncState = .syncing 305 do { 306 let report = try await repository.sync(transport: SubsurfaceCloud.transport(email: email, password: password), 307 appVersion: Brand.shortVersion) 308 notices.append(contentsOf: report.dropped.map { (dropped: String) in String(localized: "Change dropped: \(dropped)") }) 309 try await reload() 310 syncState = .idle 311 } catch { 312 try? await reload() 313 syncState = .failed(Self.describe(error)) 314 } 315 } 316 317 static func describe(_ error: Error) -> String { 318 if let git = error as? GitError { 319 switch git { 320 case .unauthorized: 321 return String(localized: "Subsurface cloud rejected this email and password (response 401). Check them, or create an account if you don't have one yet.") 322 case .http(403): return String(localized: "Subsurface cloud denies access to this logbook (response 403).") 323 case .notFound: return String(localized: "No logbook found for this account.") 324 case .network(let what): return String(localized: "Couldn't connect: \(what)") 325 case .http(let code): return String(localized: "Subsurface cloud responded with an error (\(code)).") 326 case .pushRejected(let why): return String(localized: "The cloud rejected the upload: \(why)") 327 default: 328 // Unexpected cases: the library's developer description is the only detail available. 329 let detail = String(describing: git) 330 return String(localized: "Couldn't sync (\(detail)).") 331 } 332 } 333 if let app = error as? AppError { return app.description } 334 if let change = error as? ChangeError { 335 switch change { 336 case .diveNotFound: return String(localized: "The dive no longer exists in the logbook.") 337 case .diveAlreadyExists: return String(localized: "A dive already exists at this date and time.") 338 } 339 } 340 if let importError = error as? ImportError { 341 switch importError { 342 case .unknownFormat: 343 return String(localized: "File format not recognized. Supported formats: UDDF (.uddf), Shearwater Cloud export (.zip or dive_data.db) and Dive Shearwater database (watermelon.db).") 344 case .unreadable(let why): return String(localized: "Couldn't read the file: \(why)") 345 case .empty: return String(localized: "No dives in this file.") 346 } 347 } 348 return error.localizedDescription 349 } 350 351 /// One-line description of a pending change, for the list of changes waiting to be uploaded. 352 static func summary(_ change: LogChange) -> String { 353 switch change { 354 case .editDive(_, let number, let fields): 355 // Dive numbers are identifiers: formatted as plain text so they never get a thousands separator. 356 let dive = String(number) 357 let names = fields.keys.sorted().joined(separator: ", ") 358 return String(localized: "Dive \(dive) edited (\(names))") 359 case .addDive(let newDive): 360 let dive = String(newDive.number) 361 return String(localized: "Dive \(dive) added") 362 case .deleteDive(_, let number): 363 let dive = String(number) 364 return String(localized: "Dive \(dive) deleted") 365 case .addSite(_, let name, _, _): 366 return String(localized: "Site added: \(name)") 367 case .importDive(let imported, let number, _): 368 let dive = String(number) 369 let model = imported.model 370 return String(localized: "Dive \(dive) imported (\(model))") 371 case .ensureSettings: 372 return String(localized: "Logbook settings") 373 case .locateSite: 374 return String(localized: "Site position") 375 case .removeSite: 376 return String(localized: "Site removed") 377 case .renumberDive(_, let number, let newNumber): 378 let dive = String(number) 379 let renumbered = String(newNumber) 380 return String(localized: "Dive \(dive) renumbered to \(renumbered)") 381 case .setEquipment(_, let number, _, _, _): 382 let dive = String(number) 383 return String(localized: "Dive \(dive): equipment edited") 384 case .mergeDives(_, let number, let others): 385 let dive = String(number) 386 let merged = others.map { String($0.number) }.joined(separator: ", ") 387 return String(localized: "Dive \(dive) merged with \(merged)") 388 } 389 } 390 391 // MARK: Changes 392 393 func apply(_ change: LogChange) async throws { 394 guard let repository else { return } 395 do { 396 logbook = try await repository.enqueue(change) 397 pending = await repository.pending 398 } catch { 399 throw AppError.message(Self.describe(error)) 400 } 401 scheduleSync() 402 } 403 404 /// Identifier of a dive whose page asked for a merge: the dive list starts its selection with it. 405 var mergeRequest: String? 406 407 // MARK: File import 408 409 struct ImportCandidate: Identifiable { 410 let dive: ImportedDive 411 /// The logbook already has this dive from this computer. 412 let alreadyInLog: Bool 413 /// Number of the dive of the logbook that this one overlaps and will join as one more dive computer. 414 let mergesInto: Int? 415 var id: String { dive.id } 416 } 417 418 private func candidate(_ dive: ImportedDive, _ known: DiveMerge.Disposition? = nil) -> ImportCandidate { 419 switch known ?? DiveMerge.disposition(of: dive, among: logbook.dives) { 420 case .new: return ImportCandidate(dive: dive, alreadyInLog: false, mergesInto: nil) 421 case .duplicate: return ImportCandidate(dive: dive, alreadyInLog: true, mergesInto: nil) 422 case .merge(let existing): return ImportCandidate(dive: dive, alreadyInLog: false, mergesInto: existing.number) 423 } 424 } 425 426 /// Reads an export file and tells, for each dive, what the logbook already has at that time (see `DiveMerge`). 427 func importCandidates(from url: URL) async throws -> [ImportCandidate] { 428 let scoped = url.startAccessingSecurityScopedResource() 429 defer { if scoped { url.stopAccessingSecurityScopedResource() } } 430 let data: Data 431 do { 432 data = try Data(contentsOf: url) 433 } catch { 434 throw AppError.message(String(localized: "Couldn't read this file.")) 435 } 436 do { 437 return await importCandidates(for: try DiveImporter.dives(from: Array(data)), sorted: false) 438 } catch let error as ImportError { 439 throw AppError.message(Self.describe(error)) 440 } 441 } 442 443 /// Same, for dives that are already decoded (downloaded from a dive computer), most recent first. 444 func importCandidates(for dives: [ImportedDive], sorted: Bool = true) async -> [ImportCandidate] { 445 // The repository reads the profiles, which the dive list does not hold: it knows where each dive really ends. 446 let known = (try? await repository?.dispositions(of: dives)) ?? [:] 447 return (sorted ? dives.sorted { $0.when > $1.when } : dives).map { candidate($0, known[$0.id]) } 448 } 449 450 /// Adds the dives to the logbook, oldest first, creating any missing sites. A dive that overlaps one of the 451 /// logbook joins it as one more dive computer. Returns the number of dives added or merged. 452 func importDives(_ dives: [ImportedDive]) async throws -> Int { 453 guard let repository else { return 0 } 454 let added: Int 455 do { 456 let summary = try await repository.importDives(dives) 457 added = summary.added + summary.merged 458 try await reload() 459 } catch { 460 try? await reload() 461 throw AppError.message(Self.describe(error)) 462 } 463 pending = await repository.pending 464 scheduleSync() 465 return added 466 } 467 468 /// Merges dives of the logbook into one (see `LogRepository.mergeDives`). 469 func mergeDives(ids: Set<String>) async throws { 470 guard let repository else { return } 471 do { 472 logbook = try await repository.mergeDives(logbook.dives.filter { ids.contains($0.id) }) 473 pending = await repository.pending 474 } catch { 475 throw AppError.message(Self.describe(error)) 476 } 477 scheduleSync() 478 } 479 480 // MARK: Dives from Open Rémora and Open Mérou 481 482 /// Folder where a companion app drops its dives (shared app group); `-remoraFolder` and `-merouFolder` point 483 /// elsewhere, for tests in the simulator. 484 private func sharedFolder(of source: SharedDiveSource) -> URL? { 485 if let path = LaunchOptions.value(Self.folderOption(of: source)) { return URL(fileURLWithPath: path) } 486 return FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: RemoraImport.appGroup)? 487 .appendingPathComponent(source.folder, isDirectory: true) 488 } 489 490 private static func folderOption(of source: SharedDiveSource) -> String { 491 source == .openMerou ? "-merouFolder" : "-remoraFolder" 492 } 493 494 @ObservationIgnored private var importingSharedDives = false 495 496 /// Adds the dives waiting in the shared folders to the logbook, then removes their files. A dive that overlaps 497 /// one of the logbook joins it as one more dive computer. Nothing happens while no logbook is open (or in the 498 /// demo logbook, except for screenshots): the dives then stay pending on the side of the app that dropped them. 499 func importSharedDives() async { 500 guard phase == .ready, let repository, !importingSharedDives else { return } 501 importingSharedDives = true 502 defer { importingSharedDives = false } 503 // The alarms of the dive are written into the dive notes, in the user's language. 504 let alarmLabels = [ 505 "ascentFast": String(localized: "fast ascent"), 506 "ascentTooFast": String(localized: "ascent too fast"), 507 "ceilingViolated": String(localized: "ceiling violated"), 508 "ppO2High": String(localized: "high ppO2"), 509 "ppO2Critical": String(localized: "critical ppO2"), 510 "missedSafetyStop": String(localized: "missed safety stop"), 511 ] 512 let alarmsPrefix = String(localized: "Alarms: ") 513 var changed = false 514 for source in SharedDiveSource.all { 515 guard !isDemo || LaunchOptions.value(Self.folderOption(of: source)) != nil, let folder = sharedFolder(of: source) else { continue } 516 let app = source.name 517 var total = ImportSummary() 518 for file in RemoraImport.pendingFiles(in: folder) { 519 do { 520 let dive = try RemoraImport.dive(fromJSON: try Data(contentsOf: file), timeZone: .current, defaultModel: source.name, 521 alarmLabels: alarmLabels, alarmsPrefix: alarmsPrefix, 522 marksPrefix: String(localized: "Marks: ")) 523 let summary = try await repository.importDives([dive]) 524 total.added += summary.added 525 total.merged += summary.merged 526 RemoraImport.consume(file) // imported, merged, or already in the logbook: it is no longer pending 527 } catch { 528 let name = file.lastPathComponent 529 let reason = Self.describe(error) 530 notices.append(String(localized: "Couldn't read the \(app) dive (\(name)): \(reason)")) 531 } 532 } 533 if total.added > 0 { 534 notices.append(total.added == 1 ? String(localized: "1 \(app) dive added to the logbook.") 535 : String(localized: "\(total.added) \(app) dives added to the logbook.")) 536 } 537 if total.merged > 0 { 538 notices.append(total.merged == 1 ? String(localized: "1 \(app) dive merged with a dive already in the logbook.") 539 : String(localized: "\(total.merged) \(app) dives merged with dives already in the logbook.")) 540 } 541 changed = changed || total.added + total.merged > 0 542 } 543 try? await reload() 544 if changed { scheduleSync() } 545 } 546 547 // MARK: Dives and sites that have photos 548 549 /// What the photo library holds for each dive (empty until access is granted). 550 var photoPresence: [String: DivePhotoFinder.Presence] = [:] 551 /// Sites where at least one dive has photos or videos. 552 var sitesWithPhotos: Set<UInt32> = [] 553 @ObservationIgnored private var scanningPhotos = false 554 555 /// Looks, dive by dive, for photos or videos taken at that time. Without permission to access the photo 556 /// library, nothing happens. The time zone of each site is requested from Apple once, without hurrying. 557 func refreshPhotoPresence() async { 558 var status = PHPhotoLibrary.authorizationStatus(for: .readWrite) 559 // First time: ask as soon as the logbook is shown, so the list and the map can flag the dives that have 560 // photos. iOS never asks again; a refusal can be changed in Settings. 561 if status == .notDetermined, phase == .ready, !LaunchOptions.flag("-noPhotoPrompt") { 562 status = await PHPhotoLibrary.requestAuthorization(for: .readWrite) 563 } 564 guard status == .authorized || status == .limited, !scanningPhotos else { return } 565 scanningPhotos = true 566 defer { scanningPhotos = false } 567 let log = logbook 568 569 // First pass, right away, with the known or estimated time zones. 570 func scan() async -> [String: DivePhotoFinder.Presence] { 571 await Task.detached(priority: .utility) { 572 var found = [String: DivePhotoFinder.Presence]() 573 for dive in log.dives { 574 let site = log.site(of: dive) 575 let known = SiteTimeZone.cached(for: site) 576 let zone = known ?? SiteTimeZone.estimated(for: site) 577 let presence = DivePhotoFinder.presence(for: dive, zone: zone, slack: known == nil && site?.hasLocation == true ? 3600 : 0) 578 if presence.any { found[dive.id] = presence } 579 } 580 return found 581 }.value 582 } 583 func publish(_ found: [String: DivePhotoFinder.Presence]) { 584 photoPresence = found 585 sitesWithPhotos = Set(log.dives.filter { found[$0.id] != nil }.compactMap(\.siteUUID)) 586 } 587 publish(await scan()) 588 589 // Then look up the real time zones that are missing, one site at a time, and refine. 590 let used = Set(log.dives.compactMap(\.siteUUID)) 591 let missing = used.compactMap { log.sites[$0] }.filter { $0.hasLocation && SiteTimeZone.cached(for: $0) == nil } 592 guard !missing.isEmpty else { return } 593 for site in missing.prefix(80) { 594 _ = await SiteTimeZone.zone(for: site) 595 try? await Task.sleep(for: .seconds(1.5)) 596 } 597 publish(await scan()) 598 } 599 600 // MARK: Account creation 601 602 private var cloudUserAgent: String { "SubRascasse:\(Brand.shortVersion):iOS" } 603 604 /// Requests the account creation; the cloud then sends a code by email. 605 func createAccount(email: String, password: String) async throws -> CloudAccount.Status { 606 guard CloudAccount.isValid(email: SubsurfaceCloud.sanitize(email: email)) else { 607 throw AppError.message(String(localized: "This email is not valid.")) 608 } 609 guard CloudAccount.isValid(password: password) else { 610 throw AppError.message(String(localized: "Subsurface cloud passwords can only contain unaccented letters, digits and the characters @ . + _ -")) 611 } 612 do { 613 return try await CloudAccount.submit(email: email, password: password, userAgent: cloudUserAgent) 614 } catch { 615 throw AppError.message(Self.describe(error)) 616 } 617 } 618 619 /// Validates the code received by email. 620 func verifyAccount(email: String, password: String, pin: String) async throws -> CloudAccount.Status { 621 do { 622 return try await CloudAccount.submit(email: email, password: password, pin: pin.trimmingCharacters(in: .whitespaces), userAgent: cloudUserAgent) 623 } catch { 624 throw AppError.message(Self.describe(error)) 625 } 626 } 627 628 /// A dive of the logbook that still counts for a plan: how long before the plan it ended, and its profile. 629 struct EarlierDive: Identifiable { 630 let id: String 631 let title: String 632 /// Seconds between the end of the dive and the start of the plan. 633 let interval: Int 634 let prior: PriorDive 635 } 636 637 /// The dives of the logbook that ended less than 48 hours before `date`, oldest first, with their profiles. 638 func earlierDives(before date: Date) async -> [EarlierDive] { 639 let start = DiveDate.naive(from: date) 640 let candidates = logbook.dives.filter { !$0.isPlanned && $0.when < start && $0.when + $0.durationSeconds > start - 48 * 3600 }.sorted { $0.when < $1.when } 641 var found = [EarlierDive]() 642 for (index, dive) in candidates.enumerated() { 643 func gas(_ mix: GasMix) -> BreathingGas { BreathingGas(o2: mix.o2Fraction, he: mix.heFraction) } 644 let first = dive.cylinders.first.map { gas($0.gas) } ?? .air 645 let computer = await profile(of: dive).first 646 var samples = [PriorDive.Sample]() 647 if let computer, computer.samples.count > 1 { 648 let changes = computer.events.filter(\.isGasChange).sorted { $0.time < $1.time } 649 for sample in computer.samples { 650 var breathed = first 651 if let change = changes.last(where: { $0.time <= sample.time }) { 652 if let mix = change.gas { 653 breathed = gas(mix) 654 } else if let cylinder = change.cylinder, dive.cylinders.indices.contains(cylinder) { 655 breathed = gas(dive.cylinders[cylinder].gas) 656 } 657 } 658 samples.append(PriorDive.Sample(time: Double(sample.time), depth: sample.depth, gas: breathed)) 659 } 660 } else { 661 // No profile: a square dive at the maximum depth. 662 let duration = Double(max(dive.durationSeconds, 120)) 663 samples = [PriorDive.Sample(time: 0, depth: 0, gas: first), PriorDive.Sample(time: 60, depth: dive.maxDepth, gas: first), 664 PriorDive.Sample(time: duration - 60, depth: dive.maxDepth, gas: first), PriorDive.Sample(time: duration, depth: 0, gas: first)] 665 } 666 let end = dive.when + max(dive.durationSeconds, Int(samples.last?.time ?? 0)) 667 let next = index + 1 < candidates.count ? candidates[index + 1].when : start 668 let number = dive.number > 0 ? String(localized: "Dive \(dive.number)") : String(localized: "Dive") 669 found.append(EarlierDive(id: dive.id, title: "\(number) · \(siteName(of: dive))", interval: max(0, start - end), 670 prior: PriorDive(samples: samples, surfaceInterval: Double(max(0, next - end))))) 671 } 672 return found 673 } 674 675 /// The logbook, or some of its dives, as a UDDF document. 676 func uddf(dives: [Dive]? = nil) async throws -> String { 677 guard let repository else { return "" } 678 do { 679 return try await repository.uddf(dives: dives, generator: Brand.name, version: Brand.shortVersion) 680 } catch { 681 throw AppError.message(Self.describe(error)) 682 } 683 } 684 685 func profile(of dive: Dive) async -> [DiveComputer] { 686 guard let repository else { return [] } 687 return (try? await repository.profile(of: dive)) ?? [] 688 } 689 690 func setImperial(_ value: Bool) { 691 units.imperial = value 692 UserDefaults.standard.set(value, forKey: "imperial") 693 } 694 695 func newSiteUUID() -> UInt32 { 696 var uuid = UInt32.random(in: 1...UInt32.max) 697 while logbook.sites[uuid] != nil { uuid = UInt32.random(in: 1...UInt32.max) } 698 return uuid 699 } 700 701 // MARK: Derived views 702 703 func dive(id: String) -> Dive? { logbook.dives.first { $0.id == id } } 704 705 func siteName(of dive: Dive) -> String { 706 let name = logbook.site(of: dive)?.name ?? "" 707 return name.isEmpty ? String(localized: "Unknown site") : name 708 } 709 710 /// Dives grouped by trip, otherwise by month, most recent first. 711 func sections(matching search: String) -> [DiveSection] { 712 let needle = search.trimmingCharacters(in: .whitespaces).lowercased() 713 let dives = needle.isEmpty ? logbook.dives : logbook.dives.filter { dive in 714 let site = logbook.site(of: dive) 715 let haystack = [site?.name ?? "", site?.country ?? "", dive.buddy, dive.divemaster, dive.notes, dive.suit, 716 dive.tags.joined(separator: " "), logbook.trip(of: dive)?.location ?? "", String(dive.number)] 717 return haystack.contains { $0.lowercased().contains(needle) } 718 } 719 var sections = [DiveSection]() 720 for dive in dives { 721 let key = dive.tripID ?? DiveDate.monthKey(dive.when) 722 if sections.last?.id == key { 723 sections[sections.count - 1].dives.append(dive) 724 } else if let trip = logbook.trip(of: dive) { 725 sections.append(DiveSection(id: key, title: trip.location.isEmpty ? String(localized: "Trip") : trip.location, 726 subtitle: DiveDate.monthTitle(dive.when), dives: [dive])) 727 } else { 728 sections.append(DiveSection(id: key, title: DiveDate.monthTitle(dive.when), subtitle: "", dives: [dive])) 729 } 730 } 731 return sections 732 } 733 } 734 735 /// An error whose message is already localized and ready to show to the user. 736 enum AppError: Error, CustomStringConvertible { 737 case message(String) 738 var description: String { 739 switch self { case .message(let text): return text } 740 } 741 }