subrascasse

Sub Rascasse: an iPhone dive log for Subsurface cloud storage, with a pure-Swift git client (GPL-2.0)
git clone https://git.schurger.org/subrascasse.git
Log | Files | Refs | README | LICENSE

commit 8ae285555ab75412e69cb6f2cda8e4407f73bd64
parent 2cb231783c073be6146a663a6b6e52690ed18b75
Author: Jean Schurger <jean@schurger.org>
Date:   Fri, 13 Nov 2026 16:46:40 -0500

Import Shearwater Cloud exports (zip or database, full PNF profiles) and create Subsurface cloud accounts

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYG3yp7VDUZJzSBkvTc

Diffstat:
MApp/Model/AppModel.swift | 88+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MApp/Views/DiveListView.swift | 16+++++++++++++++-
AApp/Views/ImportView.swift | 259+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MApp/Views/LoginView.swift | 14+++++++++++++-
MApp/Views/SettingsView.swift | 5+++++
APackages/DiveKit/Sources/GitLite/Compression.swift | 126+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MPackages/DiveKit/Sources/SubsurfaceLog/Changes.swift | 14++++++++++++++
APackages/DiveKit/Sources/SubsurfaceLog/Import.swift | 288+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MPackages/DiveKit/Sources/SubsurfaceLog/Repository.swift | 54++++++++++++++++++++++++++++++++++++++++++++++++++++++
APackages/DiveKit/Tests/SubsurfaceLogTests/ImportTests.swift | 229+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
MREADME.md | 8++++++--
11 files changed, 1097 insertions(+), 4 deletions(-)

diff --git a/App/Model/AppModel.swift b/App/Model/AppModel.swift @@ -201,6 +201,94 @@ final class AppModel { scheduleSync() } + // MARK: Import de fichiers + + struct ImportCandidate: Identifiable { + let dive: ImportedDive + let alreadyInLog: Bool + var id: String { dive.id } + } + + /// Lit un fichier d'export et dit, pour chaque plongée, si le carnet l'a déjà (même heure de début à 2 minutes près). + func importCandidates(from url: URL) throws -> [ImportCandidate] { + let scoped = url.startAccessingSecurityScopedResource() + defer { if scoped { url.stopAccessingSecurityScopedResource() } } + let data: Data + do { + data = try Data(contentsOf: url) + } catch { + throw AppError.message("Impossible de lire ce fichier.") + } + do { + let known = logbook.dives.map(\.when) + return try DiveImporter.dives(from: Array(data)).map { dive in + ImportCandidate(dive: dive, alreadyInLog: known.contains { abs($0 - dive.when) < 120 }) + } + } catch let error as ImportError { + throw AppError.message(error.description) + } + } + + /// Ajoute les plongées au carnet, de la plus ancienne à la plus récente, en créant les lieux qui manquent. + /// Rend le nombre de plongées ajoutées. + func importDives(_ dives: [ImportedDive]) async throws -> Int { + guard let repository else { return 0 } + var added = 0 + do { + for dive in dives.sorted(by: { $0.when < $1.when }) { + var siteUUID: UInt32? + let name = dive.site.trimmingCharacters(in: .whitespacesAndNewlines) + if !name.isEmpty { + if let existing = logbook.sites.values.first(where: { $0.name.compare(name, options: [.caseInsensitive, .diacriticInsensitive]) == .orderedSame }) { + siteUUID = existing.uuid + } else { + let uuid = newSiteUUID() + logbook = try await repository.enqueue(.addSite(uuid: uuid, name: name, latitude: nil, longitude: nil)) + siteUUID = uuid + } + } + do { + logbook = try await repository.enqueue(.importDive(dive, number: logbook.nextNumber, siteUUID: siteUUID)) + added += 1 + } catch ChangeError.diveAlreadyExists { + continue + } + } + } catch { + pending = await repository.pending + throw AppError.message(Self.describe(error)) + } + pending = await repository.pending + scheduleSync() + return added + } + + // MARK: Création de compte + + private var cloudUserAgent: String { "SubRascasse:\(Brand.shortVersion):iOS" } + + /// Demande la création du compte ; le nuage envoie alors un code par courriel. + func createAccount(email: String, password: String) async throws -> CloudAccount.Status { + guard CloudAccount.isValid(email: SubsurfaceCloud.sanitize(email: email)) else { throw AppError.message("Ce courriel n'est pas valide.") } + guard CloudAccount.isValid(password: password) else { + throw AppError.message("Le nuage Subsurface n'accepte dans le mot de passe que des lettres sans accent, des chiffres et les signes @ . + _ -") + } + do { + return try await CloudAccount.submit(email: email, password: password, userAgent: cloudUserAgent) + } catch { + throw AppError.message(Self.describe(error)) + } + } + + /// Valide le code reçu par courriel. + func verifyAccount(email: String, password: String, pin: String) async throws -> CloudAccount.Status { + do { + return try await CloudAccount.submit(email: email, password: password, pin: pin.trimmingCharacters(in: .whitespaces), userAgent: cloudUserAgent) + } catch { + throw AppError.message(Self.describe(error)) + } + } + func profile(of dive: Dive) async -> [DiveComputer] { guard let repository else { return [] } return (try? await repository.profile(of: dive)) ?? [] diff --git a/App/Views/DiveListView.swift b/App/Views/DiveListView.swift @@ -5,6 +5,7 @@ struct DiveListView: View { @Environment(AppModel.self) private var model @State private var search = "" @State private var adding = false + @State private var importing = false @State private var path: [String] = [] @State private var appliedLaunchOptions = false @@ -49,10 +50,23 @@ struct DiveListView: View { if model.syncState == .syncing { ProgressView() } } ToolbarItem(placement: .topBarTrailing) { - Button { adding = true } label: { Label("Ajouter une plongée", systemImage: "plus") } + Menu { + Button { adding = true } label: { Label("Nouvelle plongée", systemImage: "square.and.pencil") } + Button { importing = true } label: { Label("Importer un fichier…", systemImage: "square.and.arrow.down") } + } label: { + Label("Ajouter", systemImage: "plus") + } } } .sheet(isPresented: $adding) { NewDiveView() } + .modifier(FileImport(isPresented: $importing)) + .onChange(of: model.logbook.dives.count) { + // Option de capture : ouvrir une plongée qui vient d'être importée. + if path.isEmpty, let number = LaunchOptions.value("-showDive").flatMap({ Int($0) }), + let dive = model.logbook.dives.first(where: { $0.number == number }) { + path = [dive.id] + } + } .onAppear { guard !appliedLaunchOptions else { return } appliedLaunchOptions = true diff --git a/App/Views/ImportView.swift b/App/Views/ImportView.swift @@ -0,0 +1,259 @@ +import SubsurfaceLog +import SwiftUI +import UniformTypeIdentifiers + +/// Choix d'un fichier à importer, puis aperçu des plongées trouvées avant de les ajouter au carnet. +struct FileImport: ViewModifier { + @Environment(AppModel.self) private var model + @Binding var isPresented: Bool + @State private var batch: ImportBatch? + @State private var error: String? + + /// L'option de lancement `-importFile chemin` (captures d'écran) n'ouvre l'aperçu qu'une fois. + @MainActor private static var launchOptionUsed = false + + func body(content: Content) -> some View { + content + .fileImporter(isPresented: $isPresented, allowedContentTypes: [.zip, .database, .data], allowsMultipleSelection: false) { result in + switch result { + case .success(let urls): + if let url = urls.first { open(url) } + case .failure(let failure): + error = failure.localizedDescription + } + } + .sheet(item: $batch) { ImportSheet(batch: $0) } + .alert("Import impossible", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) { + Button("OK", role: .cancel) {} + } message: { + Text(error ?? "") + } + .onAppear { + guard !Self.launchOptionUsed, let path = LaunchOptions.value("-importFile") else { return } + Self.launchOptionUsed = true + open(URL(fileURLWithPath: path)) + } + } + + private func open(_ url: URL) { + do { + batch = ImportBatch(name: url.lastPathComponent, candidates: try model.importCandidates(from: url)) + } catch { + self.error = AppModel.describe(error) + } + } +} + +struct ImportBatch: Identifiable { + let id = UUID() + let name: String + let candidates: [AppModel.ImportCandidate] +} + +struct ImportSheet: View { + @Environment(AppModel.self) private var model + @Environment(\.dismiss) private var dismiss + let batch: ImportBatch + + @State private var selected: Set<String> = [] + @State private var loaded = false + @State private var working = false + @State private var error: String? + + private var fresh: [AppModel.ImportCandidate] { batch.candidates.filter { !$0.alreadyInLog } } + + var body: some View { + NavigationStack { + List { + Section { + ForEach(batch.candidates) { candidate in + Button { + guard !candidate.alreadyInLog else { return } + if selected.contains(candidate.id) { selected.remove(candidate.id) } else { selected.insert(candidate.id) } + } label: { + row(candidate) + } + .buttonStyle(.plain) + .disabled(candidate.alreadyInLog || working) + } + } header: { + Text(batch.name) + } footer: { + Text("Les plongées choisies sont ajoutées au carnet avec leur profil complet, puis envoyées au nuage Subsurface. Celles que le carnet contient déjà (même heure de début) sont laissées de côté.") + } + if let error { + Section { Text(error).foregroundStyle(.red) } + } + } + .navigationTitle(selected.count == 1 ? "1 plongée choisie" : "\(selected.count) plongées choisies") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } } + ToolbarItem(placement: .confirmationAction) { + Button("Importer", action: run) + .disabled(selected.isEmpty || working) + } + ToolbarItem(placement: .bottomBar) { + if !fresh.isEmpty { + Button(selected.count == fresh.count ? "Tout décocher" : "Tout cocher") { + selected = selected.count == fresh.count ? [] : Set(fresh.map(\.id)) + } + .disabled(working) + } + } + } + .onAppear { + guard !loaded else { return } + loaded = true + selected = Set(fresh.map(\.id)) + if LaunchOptions.flag("-importAll") { run() } + } + } + } + + private func row(_ candidate: AppModel.ImportCandidate) -> some View { + let dive = candidate.dive + let date = Date(timeIntervalSince1970: TimeInterval(dive.when)) + .formatted(Date.FormatStyle(date: .abbreviated, time: .shortened, timeZone: TimeZone(identifier: "UTC")!)) + return HStack(spacing: 12) { + Image(systemName: candidate.alreadyInLog ? "checkmark.circle.badge.xmark" : (selected.contains(candidate.id) ? "checkmark.circle.fill" : "circle")) + .font(.title3) + .foregroundStyle(candidate.alreadyInLog ? Color.secondary : Color.accentColor) + VStack(alignment: .leading, spacing: 3) { + Text(dive.site.isEmpty ? "Lieu inconnu" : dive.site) + .font(.body.weight(.medium)) + .foregroundStyle(candidate.alreadyInLog ? Color.secondary : Color.primary) + Text(candidate.alreadyInLog ? "\(date) · déjà dans le carnet" : date) + .font(.caption) + .foregroundStyle(.secondary) + } + Spacer(minLength: 8) + VStack(alignment: .trailing, spacing: 3) { + Text(model.units.depth(dive.maxDepth)) + .font(.callout.monospacedDigit().weight(.semibold)) + .foregroundStyle(candidate.alreadyInLog ? Color.secondary : Color.primary) + Text(Units.duration(dive.durationSeconds)) + .font(.caption.monospacedDigit()) + .foregroundStyle(.secondary) + } + } + .padding(.vertical, 2) + .contentShape(Rectangle()) + } + + private func run() { + let dives = batch.candidates.filter { selected.contains($0.id) }.map(\.dive) + guard !dives.isEmpty else { return } + working = true + Task { + do { + _ = try await model.importDives(dives) + dismiss() + } catch { + self.error = AppModel.describe(error) + working = false + } + } + } +} + +/// Création d'un compte du nuage Subsurface : courriel et mot de passe, puis code reçu par courriel. +struct CreateAccountView: View { + @Environment(AppModel.self) private var model + @Environment(\.dismiss) private var dismiss + /// Appelé quand le compte est prêt, pour enchaîner sur la connexion. + let onReady: (String, String) -> Void + + @State private var email = "" + @State private var password = "" + @State private var confirmation = "" + @State private var pin = "" + @State private var waitingForPIN = false + @State private var busy = false + @State private var error: String? + + var body: some View { + NavigationStack { + Form { + Section { + TextField("Courriel", text: $email) + .textContentType(.username) + .keyboardType(.emailAddress) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + .disabled(waitingForPIN) + SecureField("Mot de passe", text: $password) + .textContentType(.newPassword) + .disabled(waitingForPIN) + if !waitingForPIN { + SecureField("Mot de passe, encore", text: $confirmation) + .textContentType(.newPassword) + } + } footer: { + Text("Le compte est créé dans le nuage Subsurface (cloud.subsurface-divelog.org), le service gratuit du projet Subsurface. Il servira aussi dans Subsurface sur ordinateur. Mot de passe : lettres sans accent, chiffres et @ . + _ - seulement.") + } + if waitingForPIN { + Section { + TextField("Code reçu par courriel", text: $pin) + .keyboardType(.numbersAndPunctuation) + .textInputAutocapitalization(.never) + .autocorrectionDisabled() + } header: { + Text("Vérification") + } footer: { + Text("Le nuage Subsurface vient d'envoyer un code à \(email). Il peut mettre quelques minutes à arriver ; regardez aussi dans les indésirables.") + } + } + if let error { + Section { Label(error, systemImage: "exclamationmark.triangle.fill").foregroundStyle(.red).font(.footnote) } + } + Section { + Button(action: submit) { + HStack { + if busy { ProgressView() } + Text(waitingForPIN ? "Valider le code" : "Créer le compte") + } + } + .disabled(busy || !ready) + } + } + .navigationTitle("Nouveau compte") + .navigationBarTitleDisplayMode(.inline) + .toolbar { + ToolbarItem(placement: .cancellationAction) { Button("Annuler") { dismiss() } } + } + } + } + + private var ready: Bool { + if waitingForPIN { return !pin.trimmingCharacters(in: .whitespaces).isEmpty } + return !email.isEmpty && !password.isEmpty && password == confirmation + } + + private func submit() { + busy = true + error = nil + Task { + do { + let status = waitingForPIN + ? try await model.verifyAccount(email: email, password: password, pin: pin) + : try await model.createAccount(email: email, password: password) + switch status { + case .verified: + dismiss() + onReady(email, password) + case .needsPIN: + waitingForPIN = true + case .invalidPIN: + waitingForPIN = true + error = "Ce code n'est pas le bon." + case .rejected(let message): + error = "Le nuage Subsurface a refusé : \(message)" + } + } catch { + self.error = AppModel.describe(error) + } + busy = false + } + } +} diff --git a/App/Views/LoginView.swift b/App/Views/LoginView.swift @@ -5,6 +5,7 @@ struct LoginView: View { @State private var email = "" @State private var password = "" @State private var busy = false + @State private var creating = LaunchOptions.flag("-createAccount") @State private var error: String? @FocusState private var focus: Field? @@ -65,13 +66,17 @@ struct LoginView: View { .buttonStyle(.borderedProminent) .disabled(busy || email.isEmpty || password.isEmpty) + Button("Créer un compte") { creating = true } + .font(.subheadline) + .disabled(busy) + Button("Essayer avec un carnet de démonstration") { Task { await model.startDemo() } } .font(.subheadline) .disabled(busy) - Text("Le compte est celui du nuage Subsurface (cloud.subsurface-divelog.org), créé depuis Subsurface. Vos identifiants ne sont envoyés qu'à ce service et le mot de passe reste dans le trousseau de l'iPhone.\n\n\(Brand.name) est une application indépendante, sans lien avec l'équipe de Subsurface.") + Text("Le compte est celui du nuage Subsurface (cloud.subsurface-divelog.org), le même que dans Subsurface. Vos identifiants ne sont envoyés qu'à ce service et le mot de passe reste dans le trousseau de l'iPhone.\n\n\(Brand.name) est une application indépendante, sans lien avec l'équipe de Subsurface.") .font(.footnote) .foregroundStyle(.secondary) .multilineTextAlignment(.center) @@ -81,6 +86,13 @@ struct LoginView: View { } .background(Color(.systemGroupedBackground)) .scrollDismissesKeyboard(.interactively) + .sheet(isPresented: $creating) { + CreateAccountView { newEmail, newPassword in + email = newEmail + password = newPassword + signIn() + } + } } } diff --git a/App/Views/SettingsView.swift b/App/Views/SettingsView.swift @@ -3,6 +3,7 @@ import SwiftUI struct SettingsView: View { @Environment(AppModel.self) private var model @State private var confirmingSignOut = false + @State private var importing = false var body: some View { NavigationStack { @@ -54,6 +55,9 @@ struct SettingsView: View { LabeledContent("Plongées", value: "\(model.logbook.dives.count)") LabeledContent("Lieux", value: "\(model.logbook.sites.count)") LabeledContent("Voyages", value: "\(model.logbook.trips.count)") + Button { importing = true } label: { + Label("Importer un fichier…", systemImage: "square.and.arrow.down") + } ForEach(model.logbook.warnings, id: \.self) { warning in Label(warning, systemImage: "exclamationmark.triangle") .font(.footnote) @@ -78,6 +82,7 @@ struct SettingsView: View { } .listStyle(.insetGrouped) .navigationTitle("Réglages") + .modifier(FileImport(isPresented: $importing)) .confirmationDialog(model.isDemo ? "Quitter la démonstration ?" : "Se déconnecter ?", isPresented: $confirmingSignOut, titleVisibility: .visible) { Button(model.isDemo ? "Quitter" : "Se déconnecter", role: .destructive) { Task { await model.signOut() } diff --git a/Packages/DiveKit/Sources/GitLite/Compression.swift b/Packages/DiveKit/Sources/GitLite/Compression.swift @@ -0,0 +1,126 @@ +import Foundation +import zlib + +/// Décompression pour les fichiers importés : gzip, et archives zip (entrées stockées ou « deflate »). +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 + } + + public static func decompress(_ input: [UInt8], format: Format, limit: Int = 256 << 20) throws -> [UInt8] { + guard !input.isEmpty else { return [] } + var stream = z_stream() + guard inflateInit2_(&stream, format.rawValue, ZLIB_VERSION, Int32(MemoryLayout<z_stream>.size)) == Z_OK else { + throw GitError.malformed("zlib : initialisation") + } + defer { inflateEnd(&stream) } + var output = [UInt8]() + var chunk = [UInt8](repeating: 0, count: 64 * 1024) + var status: Int32 = Z_OK + try input.withUnsafeBufferPointer { inPtr in + stream.next_in = UnsafeMutablePointer(mutating: inPtr.baseAddress!) + stream.avail_in = UInt32(input.count) + while status != Z_STREAM_END { + let produced: Int = chunk.withUnsafeMutableBufferPointer { outPtr in + stream.next_out = outPtr.baseAddress! + stream.avail_out = UInt32(outPtr.count) + status = inflate(&stream, Z_NO_FLUSH) + return outPtr.count - Int(stream.avail_out) + } + guard status == Z_OK || status == Z_STREAM_END else { throw GitError.malformed("données compressées invalides (\(status))") } + output.append(contentsOf: chunk[0..<produced]) + guard output.count <= limit else { throw GitError.malformed("fichier trop volumineux") } + if produced == 0, stream.avail_in == 0, status != Z_STREAM_END { throw GitError.malformed("données compressées tronquées") } + } + } + return output + } + + /// Compresse au format gzip (sert aux tests). + public static func gzip(_ input: [UInt8]) -> [UInt8] { + var stream = z_stream() + guard deflateInit2_(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 31, 8, Z_DEFAULT_STRATEGY, ZLIB_VERSION, + Int32(MemoryLayout<z_stream>.size)) == Z_OK else { return [] } + defer { deflateEnd(&stream) } + var output = [UInt8](repeating: 0, count: Int(deflateBound(&stream, UInt(input.count))) + 64) + var dummy: UInt8 = 0 + let written: Int = input.withUnsafeBufferPointer { inPtr in + withUnsafeMutablePointer(to: &dummy) { dummyPtr in + output.withUnsafeMutableBufferPointer { outPtr in + stream.next_in = inPtr.baseAddress.map { UnsafeMutablePointer(mutating: $0) } ?? dummyPtr + stream.avail_in = UInt32(input.count) + stream.next_out = outPtr.baseAddress! + stream.avail_out = UInt32(outPtr.count) + _ = deflate(&stream, Z_FINISH) + return outPtr.count - Int(stream.avail_out) + } + } + } + return Array(output[0..<written]) + } +} + +/// Lecture minimale d'une archive zip (sans zip64 ni chiffrement). +public struct ZipArchive { + public struct Entry { + public let name: String + let method: Int + let compressedSize: Int + let localOffset: Int + } + + public let entries: [Entry] + private let data: [UInt8] + + public static func isZip(_ data: [UInt8]) -> Bool { + data.count > 4 && data[0] == 0x50 && data[1] == 0x4b && data[2] == 0x03 && data[3] == 0x04 + } + + public init(_ data: [UInt8]) throws { + self.data = data + func u16(_ i: Int) -> Int { Int(data[i]) | Int(data[i + 1]) << 8 } + func u32(_ i: Int) -> Int { u16(i) | u16(i + 2) << 16 } + // Fin du répertoire central : on la cherche depuis la fin (un commentaire peut la suivre). + var end = data.count - 22 + var found = -1 + while end >= 0, end >= data.count - 22 - 65_535 { + if data[end] == 0x50, data[end + 1] == 0x4b, data[end + 2] == 0x05, data[end + 3] == 0x06 { found = end; break } + end -= 1 + } + guard found >= 0 else { throw GitError.malformed("archive zip illisible") } + let count = u16(found + 10) + var pos = u32(found + 16) + var list = [Entry]() + for _ in 0..<count { + guard pos + 46 <= data.count, u32(pos) == 0x0201_4b50 else { throw GitError.malformed("archive zip : répertoire") } + let nameLength = u16(pos + 28), extraLength = u16(pos + 30), commentLength = u16(pos + 32) + guard pos + 46 + nameLength <= data.count else { throw GitError.malformed("archive zip : nom") } + let name = String(decoding: data[(pos + 46)..<(pos + 46 + nameLength)], as: UTF8.self) + list.append(Entry(name: name, method: u16(pos + 10), compressedSize: u32(pos + 20), localOffset: u32(pos + 42))) + pos += 46 + nameLength + extraLength + commentLength + } + entries = list + } + + public func contents(of entry: Entry) throws -> [UInt8] { + func u16(_ i: Int) -> Int { Int(data[i]) | Int(data[i + 1]) << 8 } + let pos = entry.localOffset + guard pos + 30 <= data.count, data[pos] == 0x50, data[pos + 1] == 0x4b, data[pos + 2] == 0x03, data[pos + 3] == 0x04 else { + throw GitError.malformed("archive zip : entrée") + } + let start = pos + 30 + u16(pos + 26) + u16(pos + 28) + guard start + entry.compressedSize <= data.count else { throw GitError.malformed("archive zip tronquée") } + let raw = Array(data[start..<(start + entry.compressedSize)]) + switch entry.method { + case 0: return raw + case 8: return try Inflate.decompress(raw, format: .raw) + default: throw GitError.malformed("archive zip : compression non prise en charge") + } + } + + public func contents(named name: String) throws -> [UInt8]? { + guard let entry = entries.first(where: { $0.name == name || $0.name.hasSuffix("/" + name) }) else { return nil } + return try contents(of: entry) + } +} diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Changes.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Changes.swift @@ -37,6 +37,8 @@ public enum LogChange: Codable, Sendable, Equatable { case addDive(NewDive) case deleteDive(when: Int, number: Int) case addSite(uuid: UInt32, name: String, latitude: Double?, longitude: Double?) + /// Plongée venue d'un fichier externe, avec son profil complet. + case importDive(ImportedDive, number: Int, siteUUID: UInt32?) public var summary: String { switch self { @@ -45,6 +47,7 @@ public enum LogChange: Codable, Sendable, Equatable { case .addDive(let dive): return "plongée \(dive.number) ajoutée" case .deleteDive(_, let number): return "plongée \(number) supprimée" case .addSite(_, let name, _, _): return "lieu ajouté : \(name)" + case .importDive(let dive, let number, _): return "plongée \(number) importée (\(dive.model))" } } } @@ -260,6 +263,17 @@ public enum LogEditor { let path = divePath(when: dive.when) result = try replacing(root: current, path: path, with: .tree(path.last!, tree), store: store) + case .importDive(let dive, let number, let siteUUID): + if try LogWalker.find(when: dive.when, number: nil, root: current, store: store) != nil { + throw ChangeError.diveAlreadyExists(dive.when) + } + let diveBlob = try store.putBlob(diveFile(dive, siteUUID: siteUUID)) + let computerBlob = try store.putBlob(computerFile(dive)) + let name = number > 0 ? "Dive-\(number)" : "Dive" + let tree = try store.putTree([.blob(name, diveBlob), .blob("Divecomputer", computerBlob)]) + let path = divePath(when: dive.when) + result = try replacing(root: current, path: path, with: .tree(path.last!, tree), store: store) + case .deleteDive(let when, let number): guard let directory = try LogWalker.find(when: when, number: number, root: current, store: store) else { throw ChangeError.diveNotFound(when) diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Import.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Import.swift @@ -0,0 +1,288 @@ +import Foundation +import GitLite +import SQLite3 + +/// Plongée lue dans un fichier externe, avec son profil complet, prête à entrer dans le carnet. +public struct ImportedDive: Codable, Sendable, Equatable, Identifiable { + public struct Sample: Codable, Sendable, Equatable { + public var time: Int // secondes + public var depth: Double // mètres + public var temperature: Double? // °C + public var pressure1: Double? // bar, émetteur 1 + public var pressure2: Double? // bar, émetteur 2 + public var stopDepth = 0.0 // mètres ; 0 = pas de palier + public var decoTime = 0 // secondes : durée du palier, ou marge sans palier + public var tts = 0 // secondes + public var cns = 0 // % + public var o2 = 21 // % + public var he = 0 // % + + public init(time: Int, depth: Double) { + self.time = time + self.depth = depth + } + } + + public var when: Int + public var durationSeconds: Int + public var model = "" + public var serial = "" + public var sourceID = "" + public var site = "" + public var buddy = "" + public var notes = "" + public var surfacePressureBar: Double? + public var salinity: Int? // g/l + public var decoModel: String? + public var samples: [Sample] = [] + + public init(when: Int, durationSeconds: Int) { + self.when = when + self.durationSeconds = durationSeconds + } + + public var id: String { sourceID.isEmpty ? String(when) : sourceID } + public var maxDepth: Double { samples.map(\.depth).max() ?? 0 } + public var meanDepth: Double { samples.isEmpty ? 0 : samples.reduce(0) { $0 + $1.depth } / Double(samples.count) } + public var minTemperature: Double? { samples.compactMap(\.temperature).min() } + + /// Mélanges respirés, dans l'ordre où ils apparaissent. + public var gases: [GasMix] { + var list = [GasMix]() + for sample in samples where sample.o2 > 0 || sample.he > 0 { + let mix = GasMix(o2Permille: sample.o2 == 21 && sample.he == 0 ? 0 : sample.o2 * 10, hePermille: sample.he * 10) + if !list.contains(mix) { list.append(mix) } + } + return list.isEmpty ? [.air] : list + } +} + +public enum ImportError: Error, Equatable, CustomStringConvertible { + case unknownFormat + case unreadable(String) + case empty + + 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 .unreadable(let why): return "Fichier illisible : \(why)" + case .empty: return "Aucune plongée dans ce fichier." + } + } +} + +public enum DiveImporter { + /// Reconnaît le format d'un fichier et en tire les plongées, de la plus récente à la plus ancienne. + public static func dives(from data: [UInt8]) throws -> [ImportedDive] { + var database = data + if ZipArchive.isZip(data) { + do { + let archive = try ZipArchive(data) + guard let inner = try archive.contents(named: "dive_data.db") else { throw ImportError.unknownFormat } + database = inner + } catch let error as GitError { + throw ImportError.unreadable(error.description) + } + } + guard database.starts(with: Array("SQLite format 3".utf8)) else { throw ImportError.unknownFormat } + let dives = try ShearwaterCloud.dives(database: database) + guard !dives.isEmpty else { throw ImportError.empty } + return dives.sorted { $0.when > $1.when } + } +} + +/// 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 { + static func dives(database: [UInt8]) throws -> [ImportedDive] { + let url = FileManager.default.temporaryDirectory.appendingPathComponent("import-\(UUID().uuidString).db") + try Data(database).write(to: url) + defer { try? FileManager.default.removeItem(at: url) } + + var handle: OpaquePointer? + guard sqlite3_open_v2(url.path, &handle, SQLITE_OPEN_READONLY, nil) == SQLITE_OK, let db = handle else { + sqlite3_close(handle) + throw ImportError.unreadable("base de données") + } + 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 + from log_data l left join dive_details d on d.DiveId = l.log_id + """ + var statement: OpaquePointer? + guard sqlite3_prepare_v2(db, sql, -1, &statement, nil) == SQLITE_OK else { throw ImportError.unknownFormat } + defer { sqlite3_finalize(statement) } + + func text(_ column: Int32) -> String { + sqlite3_column_text(statement, column).map { String(cString: $0) } ?? "" + } + + 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 } + 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) + decode(records, into: &dive) + guard !dive.samples.isEmpty else { continue } + if dive.durationSeconds <= 0 { dive.durationSeconds = dive.samples.last?.time ?? 0 } + out.append(dive) + } + return out + } + + static func timestamp(_ text: String) -> Int? { + let numbers = text.split(whereSeparator: { !$0.isNumber }).compactMap { Int($0) } + guard numbers.count >= 5 else { return nil } + return NaiveTime.timestamp(year: numbers[0], month: numbers[1], day: numbers[2], hour: numbers[3], minute: numbers[4], + second: numbers.count > 5 ? numbers[5] : 0) + } + + /// « Petrel 3[B72CDA1C]#9 2025-9-6 11-27-54.swlogzp » + static func timestamp(fromFileName name: String) -> Int? { + guard let hash = name.firstIndex(of: "#"), let space = name[hash...].firstIndex(of: " ") else { return nil } + return timestamp(String(name[space...])) + } + + static func decode(_ data: [UInt8], into dive: inout ImportedDive) { + func be16(_ record: ArraySlice<UInt8>, _ offset: Int) -> Int { + Int(record[record.startIndex + offset]) << 8 | Int(record[record.startIndex + offset + 1]) + } + var imperial = false + var interval = 10_000 + var samples = [ArraySlice<UInt8>]() + var index = 0 + while index + 32 <= data.count { + let record = data[index..<(index + 32)] + index += 32 + switch record[record.startIndex] { + case 0x01: samples.append(record) + case 0x10: + imperial = record[record.startIndex + 8] == 1 + dive.decoModel = "GF \(record[record.startIndex + 4])/\(record[record.startIndex + 5])" + case 0x11: + let mbar = be16(record, 16) + if mbar > 500 { dive.surfacePressureBar = Double(mbar) / 1000 } + case 0x13: + let density = be16(record, 3) + if density > 900, density < 1100 { dive.salinity = density } + case 0x15: + let ms = be16(record, 23) + if ms > 0 { interval = ms } + default: break + } + } + let feet = 0.3048 + var time = 0 + for record in samples { + let start = record.startIndex + time += interval + let rawDepth = Double(be16(record, 1)) / 10 + var sample = ImportedDive.Sample(time: time / 1000, depth: imperial ? rawDepth * feet : rawDepth) + var temperature = Int(Int8(bitPattern: record[start + 14])) + if temperature < 0 { + temperature += 102 + if temperature > 0 { temperature = 0 } + } + sample.temperature = imperial ? (Double(temperature) - 32) * 5 / 9 : Double(temperature) + let stop = Double(be16(record, 3)) + sample.stopDepth = imperial ? stop * feet : stop + sample.tts = be16(record, 5) * 60 + sample.o2 = Int(record[start + 8]) + sample.he = Int(record[start + 9]) + sample.decoTime = Int(record[start + 10]) * 60 + sample.cns = Int(record[start + 23]) + // Pression des émetteurs : 12 bits de poids faible, en unités de 2 psi ; ≥ 0xFFF0 = pas de mesure. + func pressure(_ offset: Int) -> Double? { + let raw = be16(record, offset) + guard raw < 0xFFF0, raw & 0x0FFF != 0 else { return nil } + return (Double(raw & 0x0FFF) * 2 * 0.0689476 * 10).rounded() / 10 + } + sample.pressure1 = pressure(28) + sample.pressure2 = pressure(20) + dive.samples.append(sample) + } + } +} + +extension LogEditor { + /// Fichier « Dive » d'une plongée importée. + static func diveFile(_ dive: ImportedDive, siteUUID: UInt32?) -> String { + var text = "duration \(LogFormat.minutes(dive.durationSeconds)) min\n" + if let siteUUID, let line = line(.site, String(siteUUID, radix: 16)) { text += line } + if let line = line(.buddy, dive.buddy) { text += line } + if let line = line(.notes, dive.notes) { text += line } + for (index, gas) in dive.gases.enumerated() { + text += "cylinder" + if gas.o2Permille > 0 { text += " o2=\(LogFormat.milli(gas.o2Permille * 100))%" } + if gas.hePermille > 0 { text += " he=\(LogFormat.milli(gas.hePermille * 100))%" } + if index == 0 { + let pressures = dive.samples.compactMap(\.pressure1) + if let first = pressures.first, let last = pressures.last, first > last { + text += " start=\(LogFormat.milli(first))bar end=\(LogFormat.milli(last))bar" + } + } + text += "\n" + } + return text + } + + /// Fichier « Divecomputer » d'une plongée importée ; les valeurs ne sont écrites que lorsqu'elles changent. + static func computerFile(_ dive: ImportedDive) -> String { + var text = "model \(LogFormat.quote(dive.model))\n" + text += "maxdepth \(LogFormat.milli(dive.maxDepth))m\n" + text += "meandepth \(LogFormat.milli(dive.meanDepth))m\n" + if let temperature = dive.minTemperature { text += "watertemp \(LogFormat.milli(temperature))°C\n" } + if let pressure = dive.surfacePressureBar { text += "surfacepressure \(LogFormat.milli(pressure))bar\n" } + if let salinity = dive.salinity { text += "salinity \(salinity)g/l\n" } + if !dive.serial.isEmpty { text += "keyvalue \"Serial\" \(LogFormat.quote(dive.serial))\n" } + if let model = dive.decoModel { text += "keyvalue \"Deco model\" \(LogFormat.quote(model))\n" } + + // Changements de gaz. + let gases = dive.gases + var current: GasMix? + var first = true + for sample in dive.samples where sample.o2 > 0 || sample.he > 0 { + let mix = GasMix(o2Permille: sample.o2 == 21 && sample.he == 0 ? 0 : sample.o2 * 10, hePermille: sample.he * 10) + guard mix != current else { continue } + current = mix + let cylinder = gases.firstIndex(of: mix) ?? 0 + let seconds = first ? 0 : sample.time + first = false + text += "event \(LogFormat.minutes(seconds)) type=25 flags=\(cylinder + 1) name=\"gaschange\" cylinder=\(cylinder)" + text += " o2=\(LogFormat.milli(sample.o2 * 1000))%" + if sample.he > 0 { text += " he=\(LogFormat.milli(sample.he * 1000))%" } + text += "\n" + } + + var lastTemp: Double?, lastP1: Double?, lastP2: Double? + var lastNDL = -1, lastTTS = 0, lastInDeco = false, lastStopTime = 0, lastStopDepth = 0.0, lastCNS = 0 + for sample in dive.samples { + var line = String(format: "%3d:%02d", sample.time / 60, sample.time % 60) + " \(LogFormat.milli(sample.depth))m" + if let t = sample.temperature, t != lastTemp { line += " \(LogFormat.milli(t))°C"; lastTemp = t } + if let p = sample.pressure1, p != lastP1 { line += " \(LogFormat.milli(p))bar:0"; lastP1 = p } + if let p = sample.pressure2, p != lastP2 { line += " \(LogFormat.milli(p))bar:1"; lastP2 = p } + let inDeco = sample.stopDepth > 0 + let ndl = inDeco ? 0 : sample.decoTime + if ndl != lastNDL { line += " ndl=\(LogFormat.minutes(ndl))"; lastNDL = ndl } + if sample.tts != lastTTS { line += " tts=\(LogFormat.minutes(sample.tts))"; lastTTS = sample.tts } + if inDeco != lastInDeco { line += " in_deco=\(inDeco ? 1 : 0)"; lastInDeco = inDeco } + let stopTime = inDeco ? sample.decoTime : 0 + if stopTime != lastStopTime { line += " stoptime=\(LogFormat.minutes(stopTime))"; lastStopTime = stopTime } + if sample.stopDepth != lastStopDepth { line += " stopdepth=\(LogFormat.milli(sample.stopDepth))m"; lastStopDepth = sample.stopDepth } + if sample.cns != lastCNS { line += " cns=\(sample.cns)%"; lastCNS = sample.cns } + text += line + "\n" + } + return text + } +} diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Repository.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Repository.swift @@ -23,6 +23,60 @@ public enum SubsurfaceCloud { } } +/// Compte du nuage Subsurface : création et vérification par le code reçu par courriel. +/// Même échange que Subsurface (`core/cloudstorage.cpp`) : un texte « courriel mot-de-passe [code] » envoyé en POST. +public enum CloudAccount { + public enum Status: Equatable, Sendable { + case verified // compte prêt + case needsPIN // un code a été envoyé par courriel + case invalidPIN + case rejected(String) // message du serveur + } + + public static func isValid(email: String) -> Bool { + email.count <= 254 && email.range(of: "^[a-zA-Z0-9.+_-]{1,64}@[a-zA-Z0-9.+_-]+\\.[a-zA-Z0-9+_-]{2,}$", options: .regularExpression) != nil + } + + /// Le nuage n'accepte que lettres, chiffres et « @ . + _ - » dans le mot de passe. + public static func isValid(password: String) -> Bool { + password.range(of: "^[a-zA-Z0-9@.+_-]+$", options: .regularExpression) != nil + } + + public static func status(fromReply reply: String) -> Status { + let text = reply.trimmingCharacters(in: .whitespacesAndNewlines) + switch text { + case "[VERIFIED]", "[OK]": return .verified + case "[VERIFY]": return .needsPIN + case "Invalid PIN": return .invalidPIN + default: return .rejected(text.isEmpty ? "réponse vide" : String(text.prefix(200))) + } + } + + public static func request(email: String, password: String, pin: String?, host: String = SubsurfaceCloud.defaultHost, + userAgent: String) -> URLRequest { + var request = URLRequest(url: URL(string: "https://\(host)/\(pin == nil ? "storage" : "verify")")!) + request.httpMethod = "POST" + request.setValue("text/plain", forHTTPHeaderField: "Content-Type") + request.setValue("text/xml, text/plain", forHTTPHeaderField: "Accept") + request.setValue(userAgent, forHTTPHeaderField: "User-Agent") + let fields = [SubsurfaceCloud.sanitize(email: email), password] + (pin.map { [$0] } ?? []) + request.httpBody = Data(fields.joined(separator: " ").utf8) + return request + } + + /// Sans `pin` : crée le compte (ou confirme qu'il existe). Avec `pin` : valide le code reçu par courriel. + public static func submit(email: String, password: String, pin: String? = nil, userAgent: String, + session: URLSession = .shared) async throws -> Status { + let data: Data + do { + (data, _) = try await session.data(for: request(email: email, password: password, pin: pin, userAgent: userAgent)) + } catch { + throw GitError.network(error.localizedDescription) + } + return status(fromReply: String(decoding: data, as: UTF8.self)) + } +} + public struct SyncReport: Sendable, Equatable { public var downloaded = false public var sent: [String] = [] diff --git a/Packages/DiveKit/Tests/SubsurfaceLogTests/ImportTests.swift b/Packages/DiveKit/Tests/SubsurfaceLogTests/ImportTests.swift @@ -0,0 +1,229 @@ +import XCTest +import GitLite +import GitTestSupport +import SQLite3 +@testable import SubsurfaceLog + +final class ImportTests: XCTestCase { + /// Enregistrement PNF de 32 octets. + private func record(_ type: UInt8, _ fill: (inout [UInt8]) -> Void) -> [UInt8] { + var bytes = [UInt8](repeating: 0, count: 32) + bytes[0] = type + fill(&bytes) + return bytes + } + + private func put16(_ bytes: inout [UInt8], _ offset: Int, _ value: Int) { + bytes[offset] = UInt8(value >> 8) + bytes[offset + 1] = UInt8(value & 255) + } + + /// Journal fictif : 6 échantillons toutes les 10 s, un changement de gaz, un palier. + private func syntheticLog(imperial: Bool = false) -> [UInt8] { + var log = [UInt8]() + log += record(0x10) { $0[4] = 45; $0[5] = 95; $0[8] = imperial ? 1 : 0 } + log += record(0x11) { self.put16(&$0, 16, 1013) } + log += record(0x13) { self.put16(&$0, 3, 1025) } + log += record(0x15) { self.put16(&$0, 23, 10_000) } + let samples: [(depth: Int, temp: Int8, stop: Int, time: Int, tts: Int, o2: Int, psi2: Int, cns: Int)] = [ + (52, 20, 0, 99, 1, 32, 1450, 0), (150, 18, 0, 60, 2, 32, 1440, 1), (305, 12, 0, 12, 4, 32, 0, 1), + (300, 12, 3, 2, 6, 32, 1300, 2), (60, 14, 0, 99, 1, 50, 1250, 2), (10, 19, 0, 99, 0, 50, 0xFFFF, 2), + ] + for s in samples { + log += record(0x01) { + self.put16(&$0, 1, s.depth) + self.put16(&$0, 3, s.stop) + self.put16(&$0, 5, s.tts) + $0[8] = UInt8(s.o2) + $0[10] = UInt8(s.time) + $0[12] = 0x10 + $0[14] = UInt8(bitPattern: s.temp) + $0[23] = UInt8(s.cns) + self.put16(&$0, 28, s.psi2) + self.put16(&$0, 20, 0xFFFF) + } + } + log += record(0xFF) { _ in } + return log + } + + /// Base au schéma de l'export Shearwater Cloud, réduite aux colonnes lues. + private func makeDatabase(log: [UInt8]) throws -> [UInt8] { + let url = try LocalGit.temporaryDirectory("sw").appendingPathComponent("dive_data.db") + var db: OpaquePointer? + XCTAssertEqual(sqlite3_open(url.path, &db), SQLITE_OK) + defer { sqlite3_close(db) } + let schema = """ + create table log_data(log_id varchar primary key, file_name varchar, format varchar, data_bytes_1 blob); + create table dive_details(DiveId varchar primary key, DiveDate datetime, DiveLengthTime varchar, Site varchar, Location varchar, + Buddy varchar, Notes varchar, SerialNumber varchar); + insert into dive_details values('42', '2025-09-06 11:27:54', '55', 'Carrière du Nord', '', 'Sam', 'Belle "visi"', 'ABCD1234'); + """ + XCTAssertEqual(sqlite3_exec(db, schema, nil, nil, nil), SQLITE_OK) + var statement: OpaquePointer? + XCTAssertEqual(sqlite3_prepare_v2(db, "insert into log_data values('42', 'Petrel 3[ABCD1234]#9 2025-9-6 11-27-54.swlogzp', 'sw-pnf', ?)", -1, &statement, nil), SQLITE_OK) + let blob = [UInt8(0), 0, 0, 0] + Inflate.gzip(log) + blob.withUnsafeBufferPointer { _ = sqlite3_bind_blob(statement, 1, $0.baseAddress, Int32($0.count), unsafeBitCast(-1, to: sqlite3_destructor_type.self)) } + XCTAssertEqual(sqlite3_step(statement), SQLITE_DONE) + sqlite3_finalize(statement) + sqlite3_close(db) + db = nil + return Array(try Data(contentsOf: url)) + } + + func testGzipAndZip() throws { + let payload = Array("bonjour ".utf8) + [UInt8](repeating: 7, count: 100_000) + XCTAssertEqual(try Inflate.decompress(Inflate.gzip(payload), format: .gzip), payload) + + let directory = try LocalGit.temporaryDirectory("zip") + try Data(payload).write(to: directory.appendingPathComponent("dive_data.db")) + try Data("x".utf8).write(to: directory.appendingPathComponent("SyncReport.txt")) + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/zip") + process.arguments = ["-q", "export.zip", "SyncReport.txt", "dive_data.db"] + process.currentDirectoryURL = directory + try process.run() + process.waitUntilExit() + let archive = try ZipArchive(Array(try Data(contentsOf: directory.appendingPathComponent("export.zip")))) + XCTAssertEqual(archive.entries.map(\.name), ["SyncReport.txt", "dive_data.db"]) + XCTAssertEqual(try archive.contents(named: "dive_data.db"), payload) + XCTAssertNil(try archive.contents(named: "absent")) + } + + func testShearwaterImport() throws { + let dives = try DiveImporter.dives(from: try makeDatabase(log: syntheticLog())) + XCTAssertEqual(dives.count, 1) + let dive = dives[0] + XCTAssertEqual(dive.when, Fixture.when(2025, 9, 6, 11, 27, 54)) + XCTAssertEqual(dive.durationSeconds, 55) + XCTAssertEqual(dive.model, "Shearwater Petrel 3") + XCTAssertEqual(dive.serial, "ABCD1234") + XCTAssertEqual(dive.site, "Carrière du Nord") + XCTAssertEqual(dive.buddy, "Sam") + XCTAssertEqual(dive.decoModel, "GF 45/95") + XCTAssertEqual(dive.surfacePressureBar, 1.013) + XCTAssertEqual(dive.salinity, 1025) + XCTAssertEqual(dive.samples.map(\.time), [10, 20, 30, 40, 50, 60]) + XCTAssertEqual(dive.samples.map(\.depth), [5.2, 15, 30.5, 30, 6, 1]) + XCTAssertEqual(dive.samples.map(\.temperature), [20, 18, 12, 12, 14, 19]) + XCTAssertEqual(dive.samples[0].pressure1, 199.9) // 1450 × 2 psi + XCTAssertNil(dive.samples[2].pressure1) // pas de mesure + XCTAssertNil(dive.samples[5].pressure1) // émetteur muet + XCTAssertNil(dive.samples[0].pressure2) + XCTAssertEqual(dive.samples[3].stopDepth, 3) + XCTAssertEqual(dive.samples[3].decoTime, 120) + XCTAssertEqual(dive.samples[1].decoTime, 3600) + XCTAssertEqual(dive.gases.map(\.label), ["EAN32", "EAN50"]) + XCTAssertEqual(dive.maxDepth, 30.5) + + // Unités impériales : pieds et °F convertis. + let imperial = try DiveImporter.dives(from: try makeDatabase(log: syntheticLog(imperial: true)))[0] + XCTAssertEqual(imperial.samples[2].depth, 30.5 * 0.3048, accuracy: 0.001) + XCTAssertEqual(try XCTUnwrap(imperial.samples[0].temperature), (20.0 - 32) * 5 / 9, accuracy: 0.001) + + XCTAssertThrowsError(try DiveImporter.dives(from: Array("pas une base".utf8))) { + XCTAssertEqual($0 as? ImportError, .unknownFormat) + } + } + + /// 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() + let transport = LocalProcessTransport(repository: remote.directory) + let repo = try LogRepository(directory: try LocalGit.temporaryDirectory("local"), branch: Fixture.branch, + authorName: "DiveLog", authorEmail: Fixture.branch) + _ = try await repo.sync(transport: transport) + let imported = try DiveImporter.dives(from: try makeDatabase(log: syntheticLog()))[0] + var log = try await repo.enqueue(.importDive(imported, number: 44, siteUUID: 0x7f3a1b2c)) + XCTAssertEqual(log.dives.count, 4) + + // Deux fois la même plongée : refusée. + do { + try await repo.enqueue(.importDive(imported, number: 45, siteUUID: nil)) + XCTFail("aurait dû échouer") + } catch let error as ChangeError { + XCTAssertEqual(error, .diveAlreadyExists(imported.when)) + } + + let report = try await repo.sync(transport: transport) + XCTAssertEqual(report.sent.count, 1) + try remote.git(["fsck", "--strict"]) + XCTAssertEqual(try remote.text(["show", "\(Fixture.branch):2025/09/06-Sat-11=27=54/Dive-44"]), + "duration 0:55 min\ndivesiteid 7f3a1b2c\nbuddy \"Sam\"\nnotes \"Belle \\\"visi\\\"\"\ncylinder o2=32.0% start=199.9bar end=172.4bar\ncylinder o2=50.0%") + let computerText = try remote.text(["show", "\(Fixture.branch):2025/09/06-Sat-11=27=54/Divecomputer"]) + XCTAssertEqual(computerText, """ + model "Shearwater Petrel 3" + maxdepth 30.5m + meandepth 14.617m + watertemp 12.0°C + surfacepressure 1.013bar + salinity 1025g/l + keyvalue "Serial" "ABCD1234" + keyvalue "Deco model" "GF 45/95" + event 0:00 type=25 flags=1 name="gaschange" cylinder=0 o2=32.0% + event 0:50 type=25 flags=2 name="gaschange" cylinder=1 o2=50.0% + 0:10 5.2m 20.0°C 199.9bar:0 ndl=99:00 tts=1:00 + 0:20 15.0m 18.0°C 198.6bar:0 ndl=60:00 tts=2:00 cns=1% + 0:30 30.5m 12.0°C ndl=12:00 tts=4:00 + 0:40 30.0m 179.3bar:0 ndl=0:00 tts=6:00 in_deco=1 stoptime=2:00 stopdepth=3.0m cns=2% + 0:50 6.0m 14.0°C 172.4bar:0 ndl=99:00 tts=1:00 in_deco=0 stoptime=0:00 stopdepth=0.0m + 1:00 1.0m 19.0°C tts=0:00 + """) + + log = try await repo.logbook() + let dive = try XCTUnwrap(log.dive(when: imported.when)) + XCTAssertEqual(dive.number, 44) + XCTAssertEqual(log.site(of: dive)?.name, "Carrière Morrison") + XCTAssertEqual(dive.cylinders.map(\.gas.label), ["EAN32", "EAN50"]) + XCTAssertEqual(dive.maxDepth, 30.5) + XCTAssertEqual(dive.waterTemperature, 12) + let computers = try await repo.profile(of: dive) + let computer = try XCTUnwrap(computers.first) + XCTAssertEqual(computer.samples.map(\.depth), imported.samples.map(\.depth)) + XCTAssertEqual(computer.samples.map(\.temperature), imported.samples.map(\.temperature)) + XCTAssertEqual(computer.samples[3].stopDepth, 3) + XCTAssertTrue(computer.samples[3].inDeco) + XCTAssertFalse(computer.samples[4].inDeco) + XCTAssertEqual(computer.samples[1].ndl, 3600) + XCTAssertEqual(computer.events.filter(\.isGasChange).map { $0.gas?.label }, ["EAN32", "EAN50"]) + XCTAssertEqual(computer.extra.first, KeyValue(key: "Serial", value: "ABCD1234")) + } + + /// Vrai export Shearwater Cloud (SHEARWATER_EXPORT = chemin du .zip ou de dive_data.db), hors dépôt. + func testRealShearwaterExport() throws { + guard let path = ProcessInfo.processInfo.environment["SHEARWATER_EXPORT"] else { throw XCTSkip("SHEARWATER_EXPORT non défini") } + let dives = try DiveImporter.dives(from: Array(try Data(contentsOf: URL(fileURLWithPath: path)))) + XCTAssertGreaterThan(dives.count, 0) + for dive in dives { + let c = NaiveTime.components(dive.when) + let pressures = dive.samples.compactMap(\.pressure1) + print("IMPORT \(c.year!)-\(c.month!)-\(c.day!) \(c.hour!):\(c.minute!) \(dive.model) durée=\(dive.durationSeconds) max=\(dive.maxDepth) moy=\(String(format: "%.2f", dive.meanDepth)) tmin=\(dive.minTemperature ?? -99) gaz=\(dive.gases.map(\.label)) \(dive.decoModel ?? "") surf=\(dive.surfacePressureBar ?? 0) sal=\(dive.salinity ?? 0) éch=\(dive.samples.count) pas=\(dive.samples.first?.time ?? 0) bar=\(pressures.first ?? 0)→\(pressures.last ?? 0) paliers=\(Set(dive.samples.map(\.stopDepth)).sorted()) lieu=\(dive.site.count) binôme=\(dive.buddy.isEmpty ? 0 : 1)") + XCTAssertGreaterThan(dive.maxDepth, 3) + XCTAssertLessThan(dive.maxDepth, 80) + XCTAssertGreaterThan(dive.samples.count, 50) + XCTAssertFalse(LogEditor.computerFile(dive).isEmpty) + } + } + + func testCloudAccountReplies() { + XCTAssertEqual(CloudAccount.status(fromReply: "[VERIFY]"), .needsPIN) + XCTAssertEqual(CloudAccount.status(fromReply: "[VERIFIED]\n"), .verified) + XCTAssertEqual(CloudAccount.status(fromReply: "[OK]"), .verified) + XCTAssertEqual(CloudAccount.status(fromReply: "Invalid PIN"), .invalidPIN) + XCTAssertEqual(CloudAccount.status(fromReply: "Invalid request format"), .rejected("Invalid request format")) + XCTAssertTrue(CloudAccount.isValid(email: "jean.test+plongee@example.com")) + XCTAssertFalse(CloudAccount.isValid(email: "jean@example")) + XCTAssertFalse(CloudAccount.isValid(email: "jean example@example.com")) + XCTAssertTrue(CloudAccount.isValid(password: "Abc123@.+_-")) + XCTAssertFalse(CloudAccount.isValid(password: "mot de passe")) + XCTAssertFalse(CloudAccount.isValid(password: "été2026!")) + XCTAssertFalse(CloudAccount.isValid(password: "")) + + let create = CloudAccount.request(email: " Jean@Example.com", password: "secret1", pin: nil, userAgent: "test") + XCTAssertEqual(create.url?.absoluteString, "https://cloud.subsurface-divelog.org/storage") + XCTAssertEqual(create.httpBody.map { String(decoding: $0, as: UTF8.self) }, "jean@example.com secret1") + let verify = CloudAccount.request(email: "jean@example.com", password: "secret1", pin: "1234", userAgent: "test") + XCTAssertEqual(verify.url?.absoluteString, "https://cloud.subsurface-divelog.org/verify") + XCTAssertEqual(verify.httpBody.map { String(decoding: $0, as: UTF8.self) }, "jean@example.com secret1 1234") + } +} diff --git a/README.md b/README.md @@ -12,9 +12,13 @@ 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, + 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). - Carnet de démonstration (bouton sur l'écran de connexion, ou option de lancement `-demo`). -Pas encore : téléchargement depuis un ordinateur de plongée, création de compte, photos, planificateur, anglais. +Pas encore : téléchargement depuis un ordinateur de plongée, import XML de Subsurface, photos, planificateur, anglais. ## Organisation @@ -39,7 +43,7 @@ Le code vit sur hotrats, Swift et Xcode tournent sur chunga. make shot SHOT=fiche ARGS="-showDive 11" Options de lancement : `-demo`, `-tab sites|stats|settings`, `-showDive N`, `-scroll notes|bottom`, `-edit`, -`-newDive`, `-demoChanges`. +`-newDive`, `-demoChanges`, `-importFile chemin`, `-importAll`, `-createAccount`. Valider sur un vrai carnet : `SUBSURFACE_TREE=/chemin/arbre swift test --filter testExternalTree` (dossier disposé comme l'arbre git : `00-Subsurface`, `01-Divesites/`, `aaaa/mm/…`).