Loader.swift (20010B)
1 // SPDX-License-Identifier: GPL-2.0-only 2 import Foundation 3 import GitLite 4 5 /// Dive directory found in the repository tree. 6 struct DiveDirectory { 7 var path: [String] 8 var tree: ObjectID 9 var when: Int 10 var tripID: String? 11 } 12 13 /// Walks the git tree of a Subsurface logbook: 14 /// `yyyy/mm/[dd-Trip~hex/][[yyyy-]mm-]dd-Day-hh=mm=ss[~hex]/{Dive-N, Divecomputer…}`. 15 enum LogWalker { 16 static func nonUnique(_ name: String) -> Substring { name.prefix { $0 != "~" } } 17 18 /// Date and time of a dive directory, or nil if the name is not one. 19 static func diveTime(name: String, year: Int?, month: Int?) -> Int? { 20 let base = Array(nonUnique(name).utf8) 21 guard base.count >= 15 else { return nil } 22 let sep = base[base.count - 3] 23 guard sep == 0x3a || sep == 0x3d else { return nil } 24 let timeStart = base.count - 8 25 guard timeStart >= 1, base[timeStart - 1] == 0x2d else { return nil } 26 let time = String(decoding: base[timeStart...], as: UTF8.self) 27 let hms = time.split(whereSeparator: { $0 == ":" || $0 == "=" }).compactMap { Int($0) } 28 guard hms.count == 3, (0..<24).contains(hms[0]), (0..<60).contains(hms[1]), (0...60).contains(hms[2]) else { return nil } 29 // Before the time: [[yyyy-]mm-]dd-Day 30 let head = String(decoding: base[..<(timeStart - 1)], as: UTF8.self) 31 var fields = head.split(separator: "-").map(String.init) 32 guard fields.count >= 2 else { return nil } 33 fields.removeLast() // day of the week 34 guard let day = Int(fields.removeLast()) else { return nil } 35 var y = year, m = month 36 if let last = fields.popLast(), let value = Int(last) { m = value } 37 if let last = fields.popLast(), let value = Int(last) { y = value } 38 guard let y, let m, y > 1930, y < 3000, (1...12).contains(m), (1...31).contains(day) else { return nil } 39 return NaiveTime.timestamp(year: y, month: m, day: day, hour: hms[0], minute: hms[1], second: hms[2]) 40 } 41 42 static func isTripName(_ name: String) -> Bool { 43 let digits = name.prefix { $0.isASCII && $0.isNumber } 44 return digits.count == 2 && name.dropFirst(2).hasPrefix("-") 45 } 46 47 static func diveDirectories(root: ObjectID, store: ObjectStore) throws -> [DiveDirectory] { 48 var out = [DiveDirectory]() 49 for yearEntry in try store.tree(root) where yearEntry.isTree { 50 guard yearEntry.name.count == 4, let year = Int(yearEntry.name) else { continue } 51 for monthEntry in try store.tree(yearEntry.id) where monthEntry.isTree { 52 guard monthEntry.name.count == 2, let month = Int(monthEntry.name) else { continue } 53 let base = [yearEntry.name, monthEntry.name] 54 for entry in try store.tree(monthEntry.id) where entry.isTree { 55 if let when = diveTime(name: entry.name, year: year, month: month) { 56 out.append(DiveDirectory(path: base + [entry.name], tree: entry.id, when: when, tripID: nil)) 57 } else if isTripName(entry.name) { 58 let tripPath = base + [entry.name] 59 let tripID = tripPath.joined(separator: "/") 60 for inner in try store.tree(entry.id) where inner.isTree { 61 if let when = diveTime(name: inner.name, year: year, month: month) { 62 out.append(DiveDirectory(path: tripPath + [inner.name], tree: inner.id, when: when, tripID: tripID)) 63 } 64 } 65 } 66 } 67 } 68 } 69 return out 70 } 71 72 /// Directory of the dive at `when` (and with number `number` if several share that time). 73 static func find(when: Int, number: Int?, root: ObjectID, store: ObjectStore) throws -> DiveDirectory? { 74 let matches = try diveDirectories(root: root, store: store).filter { $0.when == when } 75 if matches.count > 1, let number { 76 for candidate in matches { 77 let names = try store.tree(candidate.tree).map(\.name) 78 if names.contains(where: { diveNumber(fileName: $0) == number }) { return candidate } 79 } 80 } 81 return matches.first 82 } 83 84 /// Number carried by "Dive-12" or "Dive-12~abcdef0"; nil if this is not the dive file. 85 static func diveNumber(fileName: String) -> Int? { 86 guard fileName.hasPrefix("Dive"), !fileName.hasPrefix("Divecomputer") else { return nil } 87 let suffix = nonUnique(fileName).dropFirst(4) 88 if suffix.isEmpty { return 0 } 89 guard suffix.hasPrefix("-") else { return nil } 90 return Int(suffix.dropFirst()) ?? 0 91 } 92 } 93 94 public enum LogLoader { 95 /// Reads the whole logbook from the root tree. Profiles (samples) are not loaded: see `loadProfile`. 96 public static func load(root: ObjectID, store: ObjectStore) throws -> Logbook { 97 var log = Logbook() 98 let rootEntries = try store.tree(root) 99 100 if let settings = rootEntries.first(where: { !$0.isTree && $0.name == "00-Subsurface" }) { 101 for line in LogFormat.lines(try store.blob(settings.id)) { 102 switch line.keyword { 103 case "version": log.settings.version = LogFormat.integer(line.argument) 104 case "units": log.settings.units = String(line.argument) 105 case "autogroup": log.settings.autogroup = true 106 default: break 107 } 108 } 109 if log.settings.version > 3 { 110 log.warnings.append("Logbook saved in a newer format (version \(log.settings.version)).") 111 } 112 } 113 114 if let sites = rootEntries.first(where: { $0.isTree && $0.name == "01-Divesites" }) { 115 for entry in try store.tree(sites.id) where !entry.isTree && entry.name.hasPrefix("Site-") { 116 let hex = LogWalker.nonUnique(entry.name).dropFirst(5) 117 guard let uuid = UInt32(hex, radix: 16) else { continue } 118 log.sites[uuid] = parseSite(uuid: uuid, data: try store.blob(entry.id)) 119 } 120 } 121 122 for directory in try LogWalker.diveDirectories(root: root, store: store) { 123 do { 124 if let tripID = directory.tripID, log.trips[tripID] == nil { 125 log.trips[tripID] = try loadTrip(id: tripID, directory: directory, root: root, store: store) 126 } 127 log.dives.append(try loadDive(directory, store: store, log: &log)) 128 } catch { 129 log.warnings.append("Unreadable dive (\(directory.path.joined(separator: "/"))): \(error)") 130 } 131 } 132 log.dives.sort { ($0.when, $0.number) > ($1.when, $1.number) } 133 return log 134 } 135 136 private static func loadTrip(id: String, directory: DiveDirectory, root: ObjectID, store: ObjectStore) throws -> Trip { 137 var trip = Trip(id: id) 138 var tree = root 139 for component in directory.path.dropLast() { 140 guard let next = try store.tree(tree).first(where: { $0.name == component }) else { return trip } 141 tree = next.id 142 } 143 if let file = try store.tree(tree).first(where: { !$0.isTree && $0.name == "00-Trip" }) { 144 for line in LogFormat.lines(try store.blob(file.id)) { 145 switch line.keyword { 146 case "location": trip.location = line.strings.first ?? "" 147 case "notes": trip.notes = line.strings.first ?? "" 148 default: break 149 } 150 } 151 } 152 return trip 153 } 154 155 static func parseSite(uuid: UInt32, data: [UInt8]) -> DiveSite { 156 var site = DiveSite(uuid: uuid) 157 for line in LogFormat.lines(data) { 158 switch line.keyword { 159 case "name": site.name = line.strings.first ?? "" 160 case "description": site.description = line.strings.first ?? "" 161 case "notes": site.notes = line.strings.first ?? "" 162 case "gps": 163 let parts = line.argument.split(separator: " ") 164 if parts.count >= 2 { 165 site.latitude = LogFormat.number(parts[0]) 166 site.longitude = LogFormat.number(parts[1]) 167 } 168 case "geo": 169 // `geo cat 2 origin 0 "Canada"`: category 2 is the country. 170 let parts = line.argument.split(separator: " ") 171 if parts.count >= 2, parts[0] == "cat", parts[1] == "2" { site.country = line.strings.first } 172 default: break 173 } 174 } 175 return site 176 } 177 178 /// `withSamples` also reads the profiles, which gives each computer its real duration. 179 static func loadDive(_ directory: DiveDirectory, store: ObjectStore, log: inout Logbook, withSamples: Bool = false) throws -> Dive { 180 var dive = Dive(when: directory.when) 181 dive.path = directory.path 182 dive.tripID = directory.tripID 183 var legacyLocation: String? 184 var legacyGPS: (Double, Double)? 185 for entry in try store.tree(directory.tree) where !entry.isTree { 186 if entry.name.hasPrefix("Divecomputer") { 187 dive.computerBlobs.append(entry.id) 188 dive.computers.append(parseComputer(try store.blob(entry.id), withSamples: withSamples, diveWhen: directory.when)) 189 } else if let number = LogWalker.diveNumber(fileName: entry.name) { 190 dive.number = number 191 dive.diveFile = entry.name 192 dive.diveBlob = entry.id 193 parseDive(try store.blob(entry.id), into: &dive, location: &legacyLocation, gps: &legacyGPS) 194 } 195 } 196 // Old logbooks: location and position written in the dive, without a site record. 197 if dive.siteUUID == nil, legacyLocation != nil || legacyGPS != nil { 198 let name = legacyLocation ?? "" 199 if let existing = log.sites.values.first(where: { !name.isEmpty && $0.name == name }) { 200 dive.siteUUID = existing.uuid 201 } else { 202 var uuid = LogFormat.stableHash(name.isEmpty ? "\(directory.when)" : name) | 1 203 while log.sites[uuid] != nil { uuid &+= 2 } 204 var site = DiveSite(uuid: uuid) 205 site.name = name 206 site.latitude = legacyGPS?.0 207 site.longitude = legacyGPS?.1 208 log.sites[uuid] = site 209 dive.siteUUID = uuid 210 } 211 } 212 if dive.durationSeconds == 0 { 213 dive.durationSeconds = dive.computers.compactMap(\.durationSeconds).max() ?? 0 214 } 215 return dive 216 } 217 218 static func parseDive(_ data: [UInt8], into dive: inout Dive, location: inout String?, gps: inout (Double, Double)?) { 219 for line in LogFormat.lines(data) { 220 let arg = line.argument 221 switch line.keyword { 222 case "duration": dive.durationSeconds = LogFormat.duration(arg) 223 case "rating": dive.rating = LogFormat.integer(arg) 224 case "visibility": dive.visibility = LogFormat.integer(arg) 225 case "wavesize": dive.waveSize = LogFormat.integer(arg) 226 case "current": dive.current = LogFormat.integer(arg) 227 case "surge": dive.surge = LogFormat.integer(arg) 228 case "chill": dive.chill = LogFormat.integer(arg) 229 case "invalid": dive.invalid = true 230 case "tags": dive.tags = line.strings 231 case "divesiteid": dive.siteUUID = UInt32(arg.trimmingCharacters(in: .whitespaces), radix: 16) 232 case "divemaster": dive.divemaster = line.strings.first ?? "" 233 case "buddy": dive.buddy = line.strings.first ?? "" 234 case "suit": dive.suit = line.strings.first ?? "" 235 case "notes": dive.notes = line.strings.first ?? "" 236 case "location": location = line.strings.first 237 case "gps": 238 let parts = arg.split(separator: " ") 239 if parts.count >= 2 { gps = (LogFormat.number(parts[0]), LogFormat.number(parts[1])) } 240 case "airtemp": dive.airTemperatureOverride = LogFormat.number(arg) 241 case "watertemp": dive.waterTemperatureOverride = LogFormat.number(arg) 242 case "cylinder": 243 var c = Cylinder() 244 for (key, value) in LogFormat.keyValues(arg, strings: line.strings) { 245 switch key { 246 case "vol": c.volumeLiters = LogFormat.number(value) 247 case "workpressure": c.workPressureBar = LogFormat.number(value) 248 case "description": c.description = value 249 case "o2": c.gas.o2Permille = Int((LogFormat.number(value) * 10).rounded()) 250 case "he": c.gas.hePermille = Int((LogFormat.number(value) * 10).rounded()) 251 case "start": c.startBar = LogFormat.number(value) 252 case "end": c.endBar = LogFormat.number(value) 253 case "use": c.use = value 254 default: break 255 } 256 } 257 dive.cylinders.append(c) 258 case "weightsystem": 259 var w = WeightSystem() 260 for (key, value) in LogFormat.keyValues(arg, strings: line.strings) { 261 switch key { 262 case "weight": w.kilograms = LogFormat.number(value) 263 case "description": w.description = value 264 default: break 265 } 266 } 267 dive.weights.append(w) 268 default: break 269 } 270 } 271 } 272 273 /// `diveWhen` is the start of the dive: a computer that started at another time says so with its own 274 /// `date` and `time` lines (several computers on one dive), and `when` is then filled in. 275 static func parseComputer(_ data: [UInt8], withSamples: Bool, diveWhen: Int? = nil) -> DiveComputer { 276 var dc = DiveComputer() 277 var previous: Sample? 278 var date: [Int]?, time: [Int]? 279 for line in LogFormat.lines(data, skipSamples: !withSamples) { 280 guard let first = line.text.utf8.first else { continue } 281 if first == 0x20 || (first >= 0x30 && first <= 0x39) { 282 let sample = parseSample(line.text, previous: previous) 283 dc.samples.append(sample) 284 previous = sample 285 continue 286 } 287 let arg = line.argument 288 switch line.keyword { 289 case "model": dc.model = line.strings.first ?? "" 290 case "deviceid": dc.deviceID = String(arg) 291 case "diveid": dc.diveID = String(arg) 292 case "date": date = arg.split(separator: "-").compactMap { Int($0) } 293 case "time": time = arg.split(separator: ":").compactMap { Int($0) } 294 case "duration": dc.durationSeconds = LogFormat.duration(arg) 295 case "dctype": dc.diveMode = String(arg) 296 case "maxdepth": dc.maxDepth = LogFormat.number(arg) 297 case "meandepth": dc.meanDepth = LogFormat.number(arg) 298 case "airtemp": dc.airTemperature = LogFormat.number(arg) 299 case "watertemp": dc.waterTemperature = LogFormat.number(arg) 300 case "surfacepressure": dc.surfacePressureBar = LogFormat.number(arg) 301 case "salinity": dc.salinity = LogFormat.number(arg) 302 case "keyvalue": 303 if line.strings.count == 2 { dc.extra.append(KeyValue(key: line.strings[0], value: line.strings[1])) } 304 case "event": 305 dc.events.append(parseEvent(arg, strings: line.strings)) 306 default: break 307 } 308 } 309 if withSamples, let last = dc.samples.last { 310 if dc.maxDepth == nil { dc.maxDepth = dc.samples.map(\.depth).max() } 311 if dc.durationSeconds == nil { dc.durationSeconds = last.time } 312 } 313 if date?.count == 3 || time?.count == 3, let diveWhen { 314 let base = NaiveTime.components(diveWhen) 315 let d = date?.count == 3 ? date! : [base.year!, base.month!, base.day!] 316 let t = time?.count == 3 ? time! : [base.hour!, base.minute!, base.second!] 317 dc.when = NaiveTime.timestamp(year: d[0], month: d[1], day: d[2], hour: t[0], minute: t[1], second: t[2]) 318 } 319 return dc 320 } 321 322 static func parseEvent<S: StringProtocol>(_ text: S, strings: [String]) -> DiveEvent { 323 var event = DiveEvent() 324 let trimmed = text.drop { $0 == " " } 325 let timeToken = trimmed.prefix { $0 != " " } 326 event.time = LogFormat.duration(timeToken) 327 for (key, value) in LogFormat.keyValues(trimmed.dropFirst(timeToken.count), strings: strings) { 328 switch key { 329 case "type": event.type = LogFormat.integer(value) 330 case "flags": event.flags = LogFormat.integer(value) 331 case "value": event.value = LogFormat.integer(value) 332 case "name": event.name = value 333 case "cylinder": event.cylinder = LogFormat.integer(value) 334 case "o2": 335 var gas = event.gas ?? GasMix() 336 gas.o2Permille = Int((LogFormat.number(value) * 10).rounded()) 337 event.gas = gas 338 case "he": 339 var gas = event.gas ?? GasMix() 340 gas.hePermille = Int((LogFormat.number(value) * 10).rounded()) 341 event.gas = gas 342 default: break 343 } 344 } 345 return event 346 } 347 348 /// A sample carries over the values of the previous one (except cylinder pressure, which is interpolated). 349 static func parseSample(_ text: String, previous: Sample?) -> Sample { 350 var sample = previous ?? Sample() 351 sample.pressures = [] 352 var defaultSensor = 0 353 var first = true 354 for token in text.split(separator: " ", omittingEmptySubsequences: true) { 355 if first { 356 first = false 357 sample.time = LogFormat.duration(token) 358 continue 359 } 360 guard let c = token.utf8.first else { continue } 361 if c >= 0x61 && c <= 0x7a { 362 let parts = token.split(separator: "=", maxSplits: 1) 363 let key = parts[0] 364 let value = parts.count > 1 ? parts[1] : "" 365 switch key { 366 case "sensor": defaultSensor = LogFormat.integer(value) 367 case "ndl": sample.ndl = LogFormat.duration(value) 368 case "tts": sample.tts = LogFormat.duration(value) 369 case "in_deco": sample.inDeco = LogFormat.integer(value) != 0 370 case "stoptime": sample.stopTime = LogFormat.duration(value) 371 case "stopdepth": sample.stopDepth = LogFormat.number(value) 372 case "cns": sample.cns = LogFormat.integer(value) 373 case "heartbeat": sample.heartbeat = LogFormat.integer(value) 374 case "po2": sample.setpoint = LogFormat.number(value) 375 default: break 376 } 377 continue 378 } 379 let value = LogFormat.number(token) 380 let unit = token.drop { ($0.isASCII && $0.isNumber) || $0 == "." || $0 == "-" || $0 == "+" } 381 if unit.hasPrefix("m") { 382 sample.depth = value 383 } else if unit.hasPrefix("b") { 384 var sensor = defaultSensor 385 if let colon = unit.firstIndex(of: ":") { sensor = LogFormat.integer(unit[unit.index(after: colon)...]) } 386 sample.pressures.append(SensorPressure(sensor: sensor, bar: value)) 387 } else { 388 sample.temperature = value 389 } 390 } 391 return sample 392 } 393 394 /// Loads the full profiles of the computers of a dive. 395 public static func loadProfile(of dive: Dive, store: ObjectStore) throws -> [DiveComputer] { 396 try dive.computerBlobs.map { parseComputer(try store.blob($0), withSamples: true, diveWhen: dive.when) } 397 } 398 }