commit f0ee41f7dd083f5155b887bd56d838e597056609
parent 820a7eb0a0c099c3d0584b8acc801974fe35f08e
Author: Jean Schurger <jean@schurger.org>
Date: Fri, 13 Nov 2026 17:50:18 -0500
Import the Dive Shearwater app database (watermelon.db); divelog-cli inspect; very short dips unchecked by default
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYG3yp7VDUZJzSBkvTc
Diffstat:
6 files changed, 134 insertions(+), 18 deletions(-)
diff --git a/App/Views/ImportView.swift b/App/Views/ImportView.swift
@@ -105,7 +105,8 @@ struct ImportSheet: View {
.onAppear {
guard !loaded else { return }
loaded = true
- selected = Set(fresh.map(\.id))
+ // Les trempettes de moins de deux minutes (ordinateur mouillé en surface) ne sont pas cochées d'office.
+ selected = Set(fresh.filter { $0.dive.durationSeconds >= 120 }.map(\.id))
if LaunchOptions.flag("-importAll") { run() }
}
}
diff --git a/Packages/DiveKit/Sources/GitLite/Compression.swift b/Packages/DiveKit/Sources/GitLite/Compression.swift
@@ -6,6 +6,7 @@ public enum Inflate {
public enum Format: Int32 {
case gzip = 31 // 16 + 15 : en-tête gzip
case raw = -15 // flux « deflate » nu, comme dans un zip
+ case auto = 47 // 32 + 15 : gzip ou zlib, reconnu à l'en-tête
}
public static func decompress(_ input: [UInt8], format: Format, limit: Int = 256 << 20) throws -> [UInt8] {
diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Import.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Import.swift
@@ -64,7 +64,7 @@ public enum ImportError: Error, Equatable, CustomStringConvertible {
public var description: String {
switch self {
- case .unknownFormat: return "Format de fichier non reconnu. Formats acceptés : export Shearwater Cloud (.zip ou dive_data.db)."
+ case .unknownFormat: return "Format de fichier non reconnu. Formats acceptés : export Shearwater Cloud (.zip ou dive_data.db) et base de Dive Shearwater (watermelon.db)."
case .unreadable(let why): return "Fichier illisible : \(why)"
case .empty: return "Aucune plongée dans ce fichier."
}
@@ -94,6 +94,9 @@ public enum DiveImporter {
/// Export de Shearwater Cloud : base SQLite `dive_data.db`, journaux au format PNF (enregistrements de 32 octets,
/// compressés en gzip). Disposition des champs d'après libdivecomputer (`shearwater_predator_parser.c`).
enum ShearwaterCloud {
+ /// Lit l'une des deux bases de Shearwater : l'export de Shearwater Cloud (`log_data` + `dive_details`, journaux
+ /// en blob) ou la base de l'app Dive Shearwater (`dive_log_data` + `dive_details` + `geo_site` + `dive_buddy`,
+ /// journaux en base64). Les journaux sont les mêmes dans les deux.
static func dives(database: [UInt8]) throws -> [ImportedDive] {
let url = FileManager.default.temporaryDirectory.appendingPathComponent("import-\(UUID().uuidString).db")
try Data(database).write(to: url)
@@ -106,33 +109,80 @@ enum ShearwaterCloud {
}
defer { sqlite3_close(db) }
- let sql = """
- select l.log_id, l.file_name, l.data_bytes_1, l.format, d.DiveDate, d.DiveLengthTime, d.Site, d.Location, d.Buddy, d.Notes, d.SerialNumber
+ // Colonnes rendues, dans l'ordre : identifiant, modèle, journal, format, date, durée, lieu, binômes, notes, série.
+ let cloud = """
+ select l.log_id, l.file_name, l.data_bytes_1, l.format, d.DiveDate, d.DiveLengthTime,
+ coalesce(nullif(d.Site, ''), d.Location), d.Buddy, d.Notes, d.SerialNumber
from log_data l left join dive_details d on d.DiveId = l.log_id
"""
+ let app = """
+ select l.id, c.dive_computer_product, l.data_bytes_1, l.format, d.date_timestamp, c.duration_sec,
+ g.common_name, d.dive_buddy_ids, d.notes, c.dive_computer_serial
+ from dive_log_data l left join dive_details d on d.id = l.id
+ left join calculated_dive_log_samples c on c.id = l.id
+ left join geo_site g on g.id = d.dive_location
+ """
var statement: OpaquePointer?
- guard sqlite3_prepare_v2(db, sql, -1, &statement, nil) == SQLITE_OK else { throw ImportError.unknownFormat }
+ var fromApp = false
+ if sqlite3_prepare_v2(db, cloud, -1, &statement, nil) != SQLITE_OK {
+ sqlite3_finalize(statement)
+ statement = nil
+ guard sqlite3_prepare_v2(db, app, -1, &statement, nil) == SQLITE_OK else { throw ImportError.unknownFormat }
+ fromApp = true
+ }
defer { sqlite3_finalize(statement) }
func text(_ column: Int32) -> String {
sqlite3_column_text(statement, column).map { String(cString: $0) } ?? ""
}
+ var buddies = [String: String]()
+ if fromApp {
+ var names: OpaquePointer?
+ if sqlite3_prepare_v2(db, "select id, name from dive_buddy", -1, &names, nil) == SQLITE_OK {
+ while sqlite3_step(names) == SQLITE_ROW {
+ if let id = sqlite3_column_text(names, 0), let name = sqlite3_column_text(names, 1) {
+ buddies[String(cString: id)] = String(cString: name)
+ }
+ }
+ }
+ sqlite3_finalize(names)
+ }
+
var out = [ImportedDive]()
while sqlite3_step(statement) == SQLITE_ROW {
- guard text(3).isEmpty || text(3) == "sw-pnf", let bytes = sqlite3_column_blob(statement, 2) else { continue }
- let blob = Array(UnsafeBufferPointer(start: bytes.assumingMemoryBound(to: UInt8.self), count: Int(sqlite3_column_bytes(statement, 2))))
- guard blob.count > 4, let records = try? Inflate.decompress(Array(blob[4...]), format: .gzip),
- let when = timestamp(text(4)) ?? timestamp(fromFileName: text(1)) else { continue }
+ guard text(3).isEmpty || text(3) == "sw-pnf" else { continue }
+ let blob: [UInt8]
+ if fromApp {
+ guard let decoded = Data(base64Encoded: text(2)) else { continue }
+ blob = Array(decoded)
+ } else {
+ guard let bytes = sqlite3_column_blob(statement, 2) else { continue }
+ blob = Array(UnsafeBufferPointer(start: bytes.assumingMemoryBound(to: UInt8.self), count: Int(sqlite3_column_bytes(statement, 2))))
+ }
+ guard blob.count > 4, let records = try? Inflate.decompress(Array(blob[4...]), format: .auto) else { continue }
+ let identifier = text(0)
+ let when: Int?
+ if fromApp {
+ // L'identifiant se termine par l'heure de début (locale, à la seconde) ; la fiche l'arrondit à la minute.
+ when = timestamp(fromIdentifier: identifier) ?? Int(text(4))
+ } else {
+ when = timestamp(text(4)) ?? timestamp(fromFileName: text(1))
+ }
+ guard let when else { continue }
var dive = ImportedDive(when: when, durationSeconds: Int(Double(text(5)) ?? 0))
- dive.sourceID = text(0)
- dive.serial = text(10)
- let name = text(1)
- let model = name.prefix { $0 != "[" }.trimmingCharacters(in: .whitespaces)
- dive.model = model.isEmpty ? "Shearwater" : "Shearwater \(model)"
- dive.site = [text(6), text(7)].first { !$0.isEmpty } ?? ""
- dive.buddy = text(8)
- dive.notes = text(9)
+ dive.sourceID = identifier
+ dive.serial = text(9)
+ let product = fromApp ? text(1) : text(1).prefix { $0 != "[" }.trimmingCharacters(in: .whitespaces)
+ dive.model = product.isEmpty ? "Shearwater" : "Shearwater \(product)"
+ dive.site = text(6)
+ if fromApp {
+ let ids = (try? JSONDecoder().decode([String].self, from: Data(text(7).utf8))) ?? []
+ dive.buddy = ids.compactMap { buddies[$0] }.joined(separator: ", ")
+ } else {
+ dive.buddy = text(7)
+ }
+ dive.notes = text(8)
decode(records, into: &dive)
guard !dive.samples.isEmpty else { continue }
if dive.durationSeconds <= 0 { dive.durationSeconds = dive.samples.last?.time ?? 0 }
@@ -141,6 +191,13 @@ enum ShearwaterCloud {
return out
}
+ /// Identifiant de journal Shearwater : 9 chiffres fixes puis l'heure de début en secondes.
+ static func timestamp(fromIdentifier identifier: String) -> Int? {
+ guard identifier.count == 19, identifier.allSatisfy(\.isNumber), let value = Int(identifier.suffix(10)),
+ value > 946_684_800, value < 4_102_444_800 else { return nil }
+ return value
+ }
+
static func timestamp(_ text: String) -> Int? {
let numbers = text.split(whereSeparator: { !$0.isNumber }).compactMap { Int($0) }
guard numbers.count >= 5 else { return nil }
diff --git a/Packages/DiveKit/Sources/divelog-cli/main.swift b/Packages/DiveKit/Sources/divelog-cli/main.swift
@@ -14,6 +14,23 @@ func fail(_ message: String) -> Never {
let arguments = CommandLine.arguments.dropFirst()
let environment = ProcessInfo.processInfo.environment
+// « inspect » ne touche à aucun réseau : il montre ce qu'un fichier contient.
+if arguments.first == "inspect", let path = arguments.dropFirst().first {
+ do {
+ let dives = try DiveImporter.dives(from: Array(try Data(contentsOf: URL(fileURLWithPath: path))))
+ print("\(dives.count) plongées dans le fichier")
+ for dive in dives {
+ let c = NaiveTime.components(dive.when)
+ let date = String(format: "%04d-%02d-%02d %02d:%02d:%02d", c.year ?? 0, c.month ?? 0, c.day ?? 0, c.hour ?? 0, c.minute ?? 0, c.second ?? 0)
+ let pressures = dive.samples.compactMap(\.pressure1)
+ print(" \(date) \(String(format: "%5.1f", dive.maxDepth)) m \(String(format: "%3d", dive.durationSeconds / 60)) min \(dive.model) \(dive.gases.map(\.label).joined(separator: "+")) \(dive.decoModel ?? "") \(Int(pressures.first ?? 0))→\(Int(pressures.last ?? 0)) bar éch=\(dive.samples.count) lieu=\(dive.site.isEmpty ? "-" : dive.site) binôme=\(dive.buddy.isEmpty ? "-" : dive.buddy) notes=\(dive.notes.count)")
+ }
+ exit(0)
+ } catch {
+ fail("échec : \(error)")
+ }
+}
+
guard let command = arguments.first, let email = environment["CLOUD_EMAIL"], let password = environment["CLOUD_PASSWORD"] else {
fail("usage : CLOUD_EMAIL=… CLOUD_PASSWORD=… divelog-cli list | import <fichier>")
}
diff --git a/Packages/DiveKit/Tests/SubsurfaceLogTests/ImportTests.swift b/Packages/DiveKit/Tests/SubsurfaceLogTests/ImportTests.swift
@@ -126,6 +126,45 @@ final class ImportTests: XCTestCase {
}
}
+ /// Base de l'app Dive Shearwater (WatermelonDB) : journaux en base64, lieux et binômes dans des tables à part.
+ func testDiveShearwaterAppDatabase() throws {
+ let url = try LocalGit.temporaryDirectory("dsw").appendingPathComponent("watermelon.db")
+ var db: OpaquePointer?
+ XCTAssertEqual(sqlite3_open(url.path, &db), SQLITE_OK)
+ let log = Data([UInt8(0), 0, 0, 0] + Inflate.gzip(syntheticLog())).base64EncodedString()
+ let schema = """
+ create table dive_log_data(id primary key, format, data_bytes_1);
+ create table dive_details(id primary key, date_timestamp, dive_buddy_ids, notes, dive_location);
+ create table calculated_dive_log_samples(id primary key, duration_sec, dive_computer_serial, dive_computer_product);
+ create table geo_site(id primary key, common_name);
+ create table dive_buddy(id primary key, name);
+ insert into dive_log_data values('1203799431757158074', 'sw-pnf', '\(log)');
+ insert into dive_details values('1203799431757158074', 1757158020, '["b1","b2"]', 'Free flow', 's1');
+ insert into calculated_dive_log_samples values('1203799431757158074', 55, 'ABCD1234', 'Petrel 3');
+ insert into geo_site values('s1', 'Forest');
+ insert into dive_buddy values('b1', 'Sam');
+ insert into dive_buddy values('b2', 'Alex');
+ insert into dive_log_data values('1203799431757160635', 'sw-pnf', '\(log)');
+ """
+ XCTAssertEqual(sqlite3_exec(db, schema, nil, nil, nil), SQLITE_OK)
+ sqlite3_close(db)
+ let dives = try DiveImporter.dives(from: Array(try Data(contentsOf: url)))
+ XCTAssertEqual(dives.count, 2)
+ let dive = try XCTUnwrap(dives.last)
+ XCTAssertEqual(dive.when, Fixture.when(2025, 9, 6, 11, 27, 54)) // l'heure exacte vient de l'identifiant
+ XCTAssertEqual(dive.durationSeconds, 55)
+ XCTAssertEqual(dive.model, "Shearwater Petrel 3")
+ XCTAssertEqual(dive.serial, "ABCD1234")
+ XCTAssertEqual(dive.site, "Forest")
+ XCTAssertEqual(dive.buddy, "Sam, Alex")
+ XCTAssertEqual(dive.notes, "Free flow")
+ XCTAssertEqual(dive.samples.map(\.depth), [5.2, 15, 30.5, 30, 6, 1])
+ // Journal sans fiche : importé quand même, daté par son identifiant.
+ XCTAssertEqual(dives[0].when, 1_757_160_635)
+ XCTAssertEqual(dives[0].site, "")
+ XCTAssertEqual(dives[0].durationSeconds, 60)
+ }
+
/// La plongée importée entre dans le carnet, part au serveur et se relit à l'identique.
func testImportedDiveRoundTrip() async throws {
let (remote, _) = try Fixture.makeRemote()
diff --git a/README.md b/README.md
@@ -12,7 +12,8 @@ sans lien avec l'équipe de Subsurface.
- Modification hors ligne : lieu, binôme, guide, combinaison, étiquettes, évaluation, visibilité, notes ;
ajout d'une plongée à la main, création d'un lieu, suppression. Envoi à la synchronisation suivante.
- Carte et liste des lieux, statistiques, unités métriques ou impériales.
-- Import d'un export Shearwater Cloud (`.zip` ou `dive_data.db`) : profils complets, gaz, paliers, pression,
+- Import d'un export Shearwater Cloud (`.zip` ou `dive_data.db`) ou de la base de l'app Dive Shearwater
+ (`watermelon.db`, dans `~/Library/Containers/com.shearwater.dive/Data/Documents` quand l'app iOS tourne sur un Mac) : profils complets, gaz, paliers, pression,
lieux créés au besoin, doublons écartés. Décodage PNF d'après libdivecomputer (`shearwater_predator_parser.c`),
https://github.com/libdivecomputer/libdivecomputer.
- Création d'un compte du nuage Subsurface (courriel, mot de passe, code reçu par courriel).