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

ImportView.swift (14917B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import SubsurfaceLog
      3 import SwiftUI
      4 import UniformTypeIdentifiers
      5 
      6 /// Picks a file to import, then previews the dives found before adding them to the logbook.
      7 struct FileImport: ViewModifier {
      8     @Environment(AppModel.self) private var model
      9     @Binding var isPresented: Bool
     10     @State private var batch: ImportBatch?
     11     @State private var error: String?
     12 
     13     /// The `-importFile path` launch option (screenshots) opens the preview only once.
     14     @MainActor private static var launchOptionUsed = false
     15 
     16     func body(content: Content) -> some View {
     17         content
     18             .fileImporter(isPresented: $isPresented, allowedContentTypes: [.zip, .database, .xml, .data], allowsMultipleSelection: false) { result in
     19                 switch result {
     20                 case .success(let urls):
     21                     if let url = urls.first { open(url) }
     22                 case .failure(let failure):
     23                     error = failure.localizedDescription
     24                 }
     25             }
     26             .sheet(item: $batch) { ImportSheet(batch: $0) }
     27             .alert("Import failed", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) {
     28                 Button("OK", role: .cancel) {}
     29             } message: {
     30                 Text(error ?? "")
     31             }
     32             .onAppear {
     33                 guard !Self.launchOptionUsed, let path = LaunchOptions.value("-importFile") else { return }
     34                 Self.launchOptionUsed = true
     35                 open(URL(fileURLWithPath: path))
     36             }
     37     }
     38 
     39     private func open(_ url: URL) {
     40         Task {
     41             do {
     42                 batch = ImportBatch(name: url.lastPathComponent, candidates: try await model.importCandidates(from: url))
     43             } catch {
     44                 self.error = AppModel.describe(error)
     45             }
     46         }
     47     }
     48 }
     49 
     50 struct ImportBatch: Identifiable {
     51     let id = UUID()
     52     let name: String
     53     let candidates: [AppModel.ImportCandidate]
     54     /// Called once the selected dives are in the logbook.
     55     var onImported: (() -> Void)?
     56     /// True for dives downloaded from a dive computer, whose own dive counter may need adjusting.
     57     var fromComputer = false
     58 
     59     init(name: String, candidates: [AppModel.ImportCandidate], fromComputer: Bool = false, onImported: (() -> Void)? = nil) {
     60         self.name = name
     61         self.candidates = candidates
     62         self.fromComputer = fromComputer
     63         self.onImported = onImported
     64     }
     65 }
     66 
     67 struct ImportSheet: View {
     68     @Environment(AppModel.self) private var model
     69     @Environment(\.dismiss) private var dismiss
     70     let batch: ImportBatch
     71 
     72     @State private var selected: Set<String> = []
     73     @State private var loaded = false
     74     @State private var working = false
     75     @State private var error: String?
     76 
     77     private var fresh: [AppModel.ImportCandidate] { batch.candidates.filter { !$0.alreadyInLog } }
     78 
     79     var body: some View {
     80         NavigationStack {
     81             List {
     82                 Section {
     83                     ForEach(batch.candidates) { candidate in
     84                         Button {
     85                             guard !candidate.alreadyInLog else { return }
     86                             if selected.contains(candidate.id) { selected.remove(candidate.id) } else { selected.insert(candidate.id) }
     87                         } label: {
     88                             row(candidate)
     89                         }
     90                         .buttonStyle(.plain)
     91                         .disabled(candidate.alreadyInLog || working)
     92                     }
     93                 } header: {
     94                     Text(batch.name)
     95                 } footer: {
     96                     VStack(alignment: .leading, spacing: 8) {
     97                         Text("The selected dives are added to the logbook with their full profile, then uploaded to the Subsurface cloud. A dive that overlaps one already in the logbook joins it as one more dive computer; a dive the logbook already has from this computer is skipped.")
     98                         if batch.fromComputer {
     99                             // The logbook numbers the dives itself; the computer's own counter is not used.
    100                             Text("Dives are numbered by the logbook, not by the computer. After this import, the next dive will be no. \(model.logbook.nextNumber + selected.count): set the computer's counter to it if you want both to match.")
    101                         }
    102                     }
    103                 }
    104                 if let error {
    105                     Section { Text(error).foregroundStyle(.red) }
    106                 }
    107             }
    108             .navigationTitle(selected.count == 1 ? String(localized: "1 dive selected") : String(localized: "\(selected.count) dives selected"))
    109             .navigationBarTitleDisplayMode(.inline)
    110             .toolbar {
    111                 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
    112                 ToolbarItem(placement: .confirmationAction) {
    113                     Button("Import", action: run)
    114                         .disabled(selected.isEmpty || working)
    115                 }
    116                 ToolbarItem(placement: .bottomBar) {
    117                     if !fresh.isEmpty {
    118                         Button(selected.count == fresh.count ? String(localized: "Deselect all") : String(localized: "Select all")) {
    119                             selected = selected.count == fresh.count ? [] : Set(fresh.map(\.id))
    120                         }
    121                         .disabled(working)
    122                     }
    123                 }
    124             }
    125             .onAppear {
    126                 guard !loaded else { return }
    127                 loaded = true
    128                 // Dips shorter than two minutes (computer got wet at the surface) are not selected by default.
    129                 selected = Set(fresh.filter { $0.dive.durationSeconds >= 120 }.map(\.id))
    130                 if LaunchOptions.flag("-importAll") { run() }
    131             }
    132         }
    133     }
    134 
    135     private func row(_ candidate: AppModel.ImportCandidate) -> some View {
    136         let dive = candidate.dive
    137         let date = Date(timeIntervalSince1970: TimeInterval(dive.when))
    138             .formatted(Date.FormatStyle(date: .abbreviated, time: .shortened, timeZone: TimeZone(identifier: "UTC")!))
    139         return HStack(spacing: 12) {
    140             Image(systemName: candidate.alreadyInLog ? "checkmark.circle.badge.xmark" : (selected.contains(candidate.id) ? "checkmark.circle.fill" : "circle"))
    141                 .font(.title3)
    142                 .foregroundStyle(candidate.alreadyInLog ? Color.secondary : Color.accentColor)
    143             VStack(alignment: .leading, spacing: 3) {
    144                 Text(dive.site.isEmpty ? String(localized: "Unknown site") : dive.site)
    145                     .font(.body.weight(.medium))
    146                     .foregroundStyle(candidate.alreadyInLog ? Color.secondary : Color.primary)
    147                 Text(subtitle(candidate, date: date))
    148                     .font(.caption)
    149                     .foregroundStyle(.secondary)
    150             }
    151             Spacer(minLength: 8)
    152             VStack(alignment: .trailing, spacing: 3) {
    153                 Text(model.units.depth(dive.maxDepth))
    154                     .font(.callout.monospacedDigit().weight(.semibold))
    155                     .foregroundStyle(candidate.alreadyInLog ? Color.secondary : Color.primary)
    156                 Text(Units.duration(dive.durationSeconds))
    157                     .font(.caption.monospacedDigit())
    158                     .foregroundStyle(.secondary)
    159             }
    160         }
    161         .padding(.vertical, 2)
    162         .contentShape(Rectangle())
    163     }
    164 
    165     private func subtitle(_ candidate: AppModel.ImportCandidate, date: String) -> String {
    166         if candidate.alreadyInLog { return String(localized: "\(date) · already in the logbook") }
    167         // Dive numbers are identifiers: formatted as plain text so they never get a thousands separator.
    168         if let number = candidate.mergesInto.map({ String($0) }) { return String(localized: "\(date) · will be merged with dive \(number)") }
    169         return date
    170     }
    171 
    172     private func run() {
    173         let dives = batch.candidates.filter { selected.contains($0.id) }.map(\.dive)
    174         guard !dives.isEmpty else { return }
    175         working = true
    176         Task {
    177             do {
    178                 _ = try await model.importDives(dives)
    179                 batch.onImported?()
    180                 dismiss()
    181             } catch {
    182                 self.error = AppModel.describe(error)
    183                 working = false
    184             }
    185         }
    186     }
    187 }
    188 
    189 /// Creates a Subsurface cloud account: email and password, then the code received by email.
    190 struct CreateAccountView: View {
    191     @Environment(AppModel.self) private var model
    192     @Environment(\.dismiss) private var dismiss
    193     /// Called once the account is ready, to carry on with signing in.
    194     let onReady: (String, String) -> Void
    195 
    196     @State private var email = ""
    197     @State private var password = ""
    198     @State private var confirmation = ""
    199     @State private var pin = ""
    200     @State private var waitingForPIN = false
    201     @State private var busy = false
    202     @State private var error: String?
    203 
    204     var body: some View {
    205         NavigationStack {
    206             Form {
    207                 Section {
    208                     TextField("Email", text: $email)
    209                         .textContentType(.username)
    210                         .keyboardType(.emailAddress)
    211                         .textInputAutocapitalization(.never)
    212                         .autocorrectionDisabled()
    213                         .disabled(waitingForPIN)
    214                     SecureField("Password", text: $password)
    215                         .textContentType(.newPassword)
    216                         .disabled(waitingForPIN)
    217                     if !waitingForPIN {
    218                         SecureField("Password, again", text: $confirmation)
    219                             .textContentType(.newPassword)
    220                     }
    221                 } footer: {
    222                     Text("The account is created in the Subsurface cloud (cloud.subsurface-divelog.org), the free service of the Subsurface project. It also works in Subsurface on a computer. Password: unaccented letters, digits and @ . + _ - only.")
    223                 }
    224                 if waitingForPIN {
    225                     Section {
    226                         TextField("Code received by email", text: $pin)
    227                             .keyboardType(.numbersAndPunctuation)
    228                             .textInputAutocapitalization(.never)
    229                             .autocorrectionDisabled()
    230                     } header: {
    231                         Text("Verification")
    232                     } footer: {
    233                         Text("The Subsurface cloud just sent a code to \(email). It may take a few minutes to arrive; check your junk folder too.")
    234                     }
    235                 }
    236                 if let error {
    237                     Section { Label(error, systemImage: "exclamationmark.triangle.fill").foregroundStyle(.red).font(.footnote) }
    238                 }
    239                 Section {
    240                     Button(action: submit) {
    241                         HStack {
    242                             if busy { ProgressView() }
    243                             Text(waitingForPIN ? String(localized: "Verify code") : String(localized: "Create account"))
    244                         }
    245                     }
    246                     .disabled(busy || !ready)
    247                 }
    248             }
    249             .navigationTitle("New account")
    250             .navigationBarTitleDisplayMode(.inline)
    251             .toolbar {
    252                 ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
    253             }
    254         }
    255     }
    256 
    257     private var ready: Bool {
    258         if waitingForPIN { return !pin.trimmingCharacters(in: .whitespaces).isEmpty }
    259         return !email.isEmpty && !password.isEmpty && password == confirmation
    260     }
    261 
    262     private func submit() {
    263         busy = true
    264         error = nil
    265         Task {
    266             do {
    267                 let status = waitingForPIN
    268                     ? try await model.verifyAccount(email: email, password: password, pin: pin)
    269                     : try await model.createAccount(email: email, password: password)
    270                 switch status {
    271                 case .verified:
    272                     dismiss()
    273                     onReady(email, password)
    274                 case .needsPIN:
    275                     waitingForPIN = true
    276                 case .invalidPIN:
    277                     waitingForPIN = true
    278                     error = String(localized: "That code is incorrect.")
    279                 case .rejected(let message):
    280                     error = String(localized: "The Subsurface cloud refused: \(message)")
    281                 }
    282             } catch {
    283                 self.error = AppModel.describe(error)
    284             }
    285             busy = false
    286         }
    287     }
    288 }
    289 
    290 /// A UDDF document on its way to the Files app.
    291 struct UDDFFile: FileDocument {
    292     static let type = UTType(filenameExtension: "uddf", conformingTo: .xml) ?? .xml
    293     static var readableContentTypes: [UTType] { [type] }
    294     var text: String
    295 
    296     init(text: String) { self.text = text }
    297 
    298     init(configuration: ReadConfiguration) throws {
    299         text = String(decoding: configuration.file.regularFileContents ?? Data(), as: UTF8.self)
    300     }
    301 
    302     func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
    303         FileWrapper(regularFileWithContents: Data(text.utf8))
    304     }
    305 }
    306 
    307 /// Writes the logbook, or the given dives, as a UDDF file that other dive log programs read.
    308 struct UDDFExport: ViewModifier {
    309     @Environment(AppModel.self) private var model
    310     @Binding var isPresented: Bool
    311     /// nil: the whole logbook.
    312     var dives: [Dive]?
    313     var fileName = "logbook"
    314     @State private var document: UDDFFile?
    315     @State private var error: String?
    316 
    317     func body(content: Content) -> some View {
    318         content
    319             .onChange(of: isPresented) {
    320                 guard isPresented else { return }
    321                 Task {
    322                     do {
    323                         document = UDDFFile(text: try await model.uddf(dives: dives))
    324                     } catch {
    325                         self.error = AppModel.describe(error)
    326                         isPresented = false
    327                     }
    328                 }
    329             }
    330             .fileExporter(isPresented: Binding(get: { document != nil }, set: { if !$0 { document = nil; isPresented = false } }),
    331                           document: document, contentType: UDDFFile.type, defaultFilename: fileName) { result in
    332                 if case .failure(let failure) = result { error = failure.localizedDescription }
    333                 document = nil
    334                 isPresented = false
    335             }
    336             .alert("Export failed", isPresented: Binding(get: { error != nil }, set: { if !$0 { error = nil } })) {
    337                 Button("OK", role: .cancel) {}
    338             } message: {
    339                 Text(error ?? "")
    340             }
    341     }
    342 }