DiveStore.swift (5981B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 // Settings and logbook of the dive computer, saved as JSON in Documents/DiveComputer, and the hand-over 3 // of every real dive to Sub Rascasse (see docs/SHARING.md). Simulated dives are never saved nor shared. 4 import Foundation 5 import Observation 6 import RemoraDeco 7 8 @MainActor @Observable 9 final class DiveStore: DiveLogStore { 10 /// App group shared with Sub Rascasse (same team) and folder of the dives waiting to be imported: 11 /// one `<uuid>.json` (DiveLog) and one `<uuid>.uddf` per dive. Part of the contract: do not rename. 12 static let appGroup = "group.org.schurger.dive" 13 static let outboxPath = "OpenMerou/Dives" 14 15 private(set) var logbook = Logbook() 16 var settings = UserSettings() 17 /// The depth source is the simulated housing: dives ending now are simulations. 18 var simulated = false 19 /// Dives waiting for Sub Rascasse (files still in the outbox). 20 private(set) var pending = 0 21 /// False when the app group is not available: the dives then stay in the app's Documents. 22 let sharedFolderAvailable: Bool 23 private(set) var lastError: String? 24 25 private let folder: URL 26 /// Where the dive files are dropped: the shared folder, or Documents/DiveComputer/Dives without it. 27 let outbox: URL 28 private var demo = false 29 private var logbookURL: URL { folder.appendingPathComponent("logbook.json") } 30 private var settingsURL: URL { folder.appendingPathComponent("settings.json") } 31 32 static let encoder: JSONEncoder = { 33 let e = JSONEncoder() 34 e.dateEncodingStrategy = .iso8601 35 e.outputFormatting = [.sortedKeys] 36 return e 37 }() 38 39 static let decoder: JSONDecoder = { 40 let d = JSONDecoder() 41 d.dateDecodingStrategy = .iso8601 42 return d 43 }() 44 45 static var defaultFolder: URL { 46 FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0].appendingPathComponent("DiveComputer") 47 } 48 49 static var sharedContainer: URL? { 50 FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: appGroup) 51 } 52 53 /// `sharedContainer`: root of the app group (nil when the app does not belong to it). 54 init(folder: URL = DiveStore.defaultFolder, sharedContainer: URL? = DiveStore.sharedContainer) { 55 self.folder = folder 56 let fallback = folder.appendingPathComponent("Dives", isDirectory: true) 57 sharedFolderAvailable = sharedContainer != nil 58 outbox = sharedContainer?.appendingPathComponent(Self.outboxPath, isDirectory: true) ?? fallback 59 try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) 60 if let data = try? Data(contentsOf: logbookURL), 61 let book = try? Self.decoder.decode(Logbook.self, from: data) { logbook = book } 62 if let data = try? Data(contentsOf: settingsURL), 63 let saved = try? Self.decoder.decode(UserSettings.self, from: data) { settings = saved } 64 // Dives kept in Documents while the shared folder was missing move there once it exists. 65 if sharedFolderAvailable, let kept = try? FileManager.default.contentsOfDirectory(at: fallback, includingPropertiesForKeys: nil), !kept.isEmpty { 66 try? FileManager.default.createDirectory(at: outbox, withIntermediateDirectories: true) 67 for file in kept { try? FileManager.default.moveItem(at: file, to: outbox.appendingPathComponent(file.lastPathComponent)) } 68 } 69 refreshOutbox() 70 } 71 72 /// Last real dive. 73 var lastDive: DiveLog? { logbook.realDives.last } 74 75 /// Hours before flying according to the recorded dives (0 = no more restriction). 76 func noFlyHours(at date: Date = Date()) -> Double { 77 SurfaceAdvice.noFlyHours(logbook: logbook, at: date, surfacePressure: standardSurfacePressure) 78 } 79 80 func add(_ dive: DiveLog) -> DiveLog { 81 guard !simulated, !demo else { 82 var copy = dive 83 copy.source = .simulation 84 return copy 85 } 86 logbook.add(dive) 87 saveLogbook() 88 let saved = logbook.dives.first { $0.id == dive.id } ?? dive 89 share(saved) 90 return saved 91 } 92 93 func saveSettings() { 94 guard !demo, settings.problems.isEmpty, let data = try? Self.encoder.encode(settings) else { return } 95 try? data.write(to: settingsURL, options: .atomic) 96 } 97 98 func refreshOutbox() { 99 guard !demo else { return } 100 let files = (try? FileManager.default.contentsOfDirectory(atPath: outbox.path)) ?? [] 101 pending = files.filter { $0.hasSuffix(".json") }.count 102 } 103 104 private func saveLogbook() { 105 guard let data = try? Self.encoder.encode(logbook) else { return } 106 try? data.write(to: logbookURL, options: .atomic) 107 } 108 109 private func share(_ dive: DiveLog) { 110 do { 111 try FileManager.default.createDirectory(at: outbox, withIntermediateDirectories: true) 112 let base = outbox.appendingPathComponent(dive.id.uuidString) 113 let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0" 114 try Self.encoder.encode(dive).write(to: base.appendingPathExtension("json"), options: .atomic) 115 try UDDF.export([dive], generatorName: DiveSession.computerName, generatorVersion: version) 116 .write(to: base.appendingPathExtension("uddf"), atomically: true, encoding: .utf8) 117 } catch { 118 lastError = String(localized: "Shared folder: \(error.localizedDescription)") 119 } 120 refreshOutbox() 121 } 122 123 /// Screenshots (`-demoLogbook`): one dive an hour and a half ago, in memory only; nothing is written. 124 func seedDemo() { 125 demo = true 126 var dive = DemoProfile.reef.record(start: Date().addingTimeInterval(-2.2 * 3600), settings: settings, logbook: Logbook()) 127 dive.computerModel = DiveSession.computerName 128 logbook = Logbook() 129 logbook.add(dive) 130 pending = 1 131 } 132 }