commit c27df568652a9d434479b7dbeb744140c7b27cbf
parent 4d681090fa505fc6626b38e7cfcfd950d47b4cae
Author: Jean Schurger <jean@schurger.org>
Date: Sat, 14 Nov 2026 14:40:52 -0500
Optional Subsurface cloud account; iCloud backup of the logbook and settings
- A logbook can live on the iPhone without an account (local repository in
the same format, changes committed locally). The sign-in screen offers it,
and to restore the iCloud backup. An account can be connected later: an
account without dives receives the logbook (replaceRemote), otherwise the
user picks which one stays. Signing out can keep the logbook.
- After each change the logbook is copied to the app's iCloud Drive folder as
a zip of the Subsurface git files, with what it holds, the settings and one
archive per day for a week. An empty logbook never replaces a backup.
- ZipArchive.archive, LogRepository.exportFiles and replaceRemote, tested
against a git server; -backupFolder stands in for iCloud in the simulator.
- French strings (also the keys that the string export derives with %@),
README, version 0.7.
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01K7deYG3yp7VDUZJzSBkvTc
Diffstat:
13 files changed, 1132 insertions(+), 75 deletions(-)
diff --git a/App/Localizable.xcstrings b/App/Localizable.xcstrings
@@ -361,6 +361,16 @@
}
}
},
+ "A copy of the logbook and of the settings goes to the Sub Rascasse folder of your iCloud Drive after each change, with one archive per day for the last week. Your photos are not copied.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Une copie du carnet et des réglages part dans le dossier Sub Rascasse de votre iCloud Drive après chaque modification, avec une archive par jour pour la dernière semaine. Vos photos ne sont pas copiées."
+ }
+ }
+ }
+ },
"A dive already exists at this date and time.": {
"localizations": {
"fr": {
@@ -841,6 +851,26 @@
}
}
},
+ "Connect": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Connecter"
+ }
+ }
+ }
+ },
+ "Connect to Subsurface cloud…": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Connecter au nuage Subsurface…"
+ }
+ }
+ }
+ },
"Connecting…": {
"localizations": {
"fr": {
@@ -921,6 +951,16 @@
}
}
},
+ "Couldn't write to iCloud Drive.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Impossible d'écrire dans iCloud Drive."
+ }
+ }
+ }
+ },
"Country": {
"localizations": {
"fr": {
@@ -1301,6 +1341,16 @@
}
}
},
+ "Dives are numbered by the logbook, not by the computer. After this import, the next dive will be no. %@: set the computer's counter to it if you want both to match.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Les plongées sont numérotées par le carnet, pas par l'ordinateur. Après cet import, la prochaine plongée sera la n° %@ : réglez le compteur de l'ordinateur sur ce numéro si vous voulez que les deux concordent."
+ }
+ }
+ }
+ },
"Dives are numbered by the logbook, not by the computer. After this import, the next dive will be no. %lld: set the computer's counter to it if you want both to match.": {
"localizations": {
"fr": {
@@ -1411,6 +1461,16 @@
}
}
},
+ "Downloading… %@ %%": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Téléchargement… %@ %%"
+ }
+ }
+ }
+ },
"Downloading… %lld %%": {
"localizations": {
"fr": {
@@ -1511,6 +1571,36 @@
}
}
},
+ "Erase": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Effacer"
+ }
+ }
+ }
+ },
+ "Erase the logbook from this iPhone": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Effacer le carnet de cet iPhone"
+ }
+ }
+ }
+ },
+ "Erase the logbook?": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Effacer le carnet ?"
+ }
+ }
+ }
+ },
"Events (%lld)": {
"localizations": {
"fr": {
@@ -1731,6 +1821,16 @@
}
}
},
+ "Keep my logbook on this iPhone": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Garder mon carnet sur cet iPhone"
+ }
+ }
+ }
+ },
"Keep the computer close to the iPhone and leave this screen open.": {
"localizations": {
"fr": {
@@ -1741,6 +1841,16 @@
}
}
},
+ "Keeping the logbook lets you go on without the Subsurface cloud. Nothing is deleted in the cloud either way.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Garder le carnet permet de continuer sans le nuage Subsurface. Dans les deux cas, rien n'est supprimé dans le nuage."
+ }
+ }
+ }
+ },
"Kelp forest, a wolffish in a crevice.": {
"localizations": {
"fr": {
@@ -1811,6 +1921,26 @@
}
}
},
+ "Logbook and settings": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Carnet et réglages"
+ }
+ }
+ }
+ },
+ "Logbook on this iPhone": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Carnet sur cet iPhone"
+ }
+ }
+ }
+ },
"Logbook settings": {
"localizations": {
"fr": {
@@ -2111,6 +2241,16 @@
}
}
},
+ "Next dive in the logbook: no. %@.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Prochaine plongée du carnet : n° %@."
+ }
+ }
+ }
+ },
"Next dive in the logbook: no. %lld.": {
"localizations": {
"fr": {
@@ -2141,6 +2281,16 @@
}
}
},
+ "No Subsurface cloud account: the logbook is kept on this iPhone. Connect an account to use it in Subsurface too, on a computer for instance.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Sans compte du nuage Subsurface : le carnet est gardé sur cet iPhone. Connectez un compte pour l'utiliser aussi dans Subsurface, sur un ordinateur par exemple."
+ }
+ }
+ }
+ },
"No cards yet": {
"localizations": {
"fr": {
@@ -2301,6 +2451,16 @@
}
}
},
+ "Not in this version": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Pas dans cette version"
+ }
+ }
+ }
+ },
"Not used": {
"localizations": {
"fr": {
@@ -2311,6 +2471,16 @@
}
}
},
+ "Not yet": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Pas encore"
+ }
+ }
+ }
+ },
"Notes": {
"localizations": {
"fr": {
@@ -2401,6 +2571,16 @@
}
}
},
+ "Or, without an account": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Ou, sans compte"
+ }
+ }
+ }
+ },
"Other computer": {
"localizations": {
"fr": {
@@ -2541,6 +2721,16 @@
}
}
},
+ "Restore the iCloud backup (%lld dives, %@)": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Restaurer la sauvegarde iCloud (%lld plongées, %@)"
+ }
+ }
+ }
+ },
"Rocky bottom and kelp": {
"localizations": {
"fr": {
@@ -2621,6 +2811,16 @@
}
}
},
+ "Send this iPhone's logbook to the account": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Envoyer le carnet de cet iPhone au compte"
+ }
+ }
+ }
+ },
"Series": {
"localizations": {
"fr": {
@@ -2681,6 +2881,26 @@
}
}
},
+ "Sign out and erase the copy": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Se déconnecter et effacer la copie"
+ }
+ }
+ }
+ },
+ "Sign out and keep the logbook on this iPhone": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Se déconnecter et garder le carnet sur cet iPhone"
+ }
+ }
+ }
+ },
"Sign out?": {
"localizations": {
"fr": {
@@ -3051,6 +3271,36 @@
}
}
},
+ "The account holds %1$lld dives, this iPhone %2$lld. The two are not mixed: the one you do not keep stays recoverable, in the history of the account or in the iCloud backups of the last week.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Le compte contient %1$lld plongées, cet iPhone %2$lld. Les deux ne sont pas mélangés : celui que vous ne gardez pas reste récupérable, dans l'historique du compte ou dans les sauvegardes iCloud de la dernière semaine."
+ }
+ }
+ }
+ },
+ "The account holds %@ dives, this iPhone %@. The two are not mixed: the one you do not keep stays recoverable, in the history of the account or in the iCloud backups of the last week.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Le compte contient %1$@ plongées, cet iPhone %2$@. Les deux ne sont pas mélangés : celui que vous ne gardez pas reste récupérable, dans l'historique du compte ou dans les sauvegardes iCloud de la dernière semaine."
+ }
+ }
+ }
+ },
+ "The account holds %lld dives, this iPhone %lld. The two are not mixed: the one you do not keep stays recoverable, in the history of the account or in the iCloud backups of the last week.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Le compte contient %1$lld plongées, cet iPhone %2$lld. Les deux ne sont pas mélangés : celui que vous ne gardez pas reste récupérable, dans l'historique du compte ou dans les sauvegardes iCloud de la dernière semaine."
+ }
+ }
+ }
+ },
"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.": {
"localizations": {
"fr": {
@@ -3071,6 +3321,36 @@
}
}
},
+ "The backup in iCloud could not be read. It may still be downloading: try again in a moment.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "La sauvegarde dans iCloud n'a pas pu être lue. Elle est peut-être encore en cours de téléchargement : réessayez dans un instant."
+ }
+ }
+ }
+ },
+ "The backup in iCloud is damaged.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "La sauvegarde dans iCloud est endommagée."
+ }
+ }
+ }
+ },
+ "The backup in iCloud is empty.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "La sauvegarde dans iCloud est vide."
+ }
+ }
+ }
+ },
"The cards are kept on this iPhone, and in its iPhone backup. The automatic copy to iCloud Drive comes in a later version.": {
"localizations": {
"fr": {
@@ -3201,6 +3481,26 @@
}
}
},
+ "The logbook is removed from this iPhone. The last copy saved in iCloud Drive, if any, stays there.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Le carnet est retiré de cet iPhone. La dernière copie enregistrée dans iCloud Drive, s'il y en a une, y reste."
+ }
+ }
+ }
+ },
+ "The logbook of this iPhone is sent to the account, then kept in sync with it. If the account already has dives, you choose which logbook stays.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Le carnet de cet iPhone est envoyé au compte, puis synchronisé avec lui. Si le compte a déjà des plongées, vous choisissez quel carnet reste."
+ }
+ }
+ }
+ },
"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.": {
"localizations": {
"fr": {
@@ -3221,6 +3521,16 @@
}
}
},
+ "This account already has a logbook": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Ce compte a déjà un carnet"
+ }
+ }
+ }
+ },
"This computer is no longer in range.": {
"localizations": {
"fr": {
@@ -3431,6 +3741,16 @@
}
}
},
+ "Use the account's logbook": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Utiliser le carnet du compte"
+ }
+ }
+ }
+ },
"Verification": {
"localizations": {
"fr": {
@@ -3521,6 +3841,16 @@
}
}
},
+ "Warning: %@ change(s) not yet uploaded will be lost if you erase the copy. Nothing is deleted in the cloud.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Attention : %@ modification(s) pas encore envoyée(s) seront perdues si vous effacez la copie. Rien n'est supprimé dans le nuage."
+ }
+ }
+ }
+ },
"Warning: %@ change(s) not yet uploaded will be lost. The copy of the logbook on this iPhone will be erased.": {
"localizations": {
"fr": {
@@ -3531,6 +3861,16 @@
}
}
},
+ "Warning: %lld change(s) not yet uploaded will be lost if you erase the copy. Nothing is deleted in the cloud.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Attention : %lld modification(s) pas encore envoyée(s) seront perdues si vous effacez la copie. Rien n'est supprimé dans le nuage."
+ }
+ }
+ }
+ },
"Warning: %lld change(s) not yet uploaded will be lost. The copy of the logbook on this iPhone will be erased.": {
"localizations": {
"fr": {
@@ -3641,6 +3981,16 @@
}
}
},
+ "Your dive log, on iPhone.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Votre carnet de plongée, sur iPhone."
+ }
+ }
+ }
+ },
"ascent too fast": {
"localizations": {
"fr": {
@@ -3731,6 +4081,36 @@
}
}
},
+ "iCloud Drive is not available on this iPhone.": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "iCloud Drive n'est pas disponible sur cet iPhone."
+ }
+ }
+ }
+ },
+ "iCloud Drive is off": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "iCloud Drive est désactivé"
+ }
+ }
+ }
+ },
+ "iCloud backup": {
+ "localizations": {
+ "fr": {
+ "stringUnit": {
+ "state": "translated",
+ "value": "Sauvegarde iCloud"
+ }
+ }
+ }
+ },
"missed safety stop": {
"localizations": {
"fr": {
diff --git a/App/Model/AppModel.swift b/App/Model/AppModel.swift
@@ -25,7 +25,11 @@ final class AppModel {
var pending: [LogChange] = []
var email = ""
var isDemo = false
+ /// The logbook lives on this iPhone only (and in its iCloud backup): no Subsurface cloud account.
+ var isLocal = false
var notices: [String] = []
+ /// Copy of the logbook and of the settings in iCloud Drive.
+ let backup = LogbookBackup()
var units = Units(imperial: UserDefaults.standard.object(forKey: "imperial") as? Bool ?? (Locale.current.measurementSystem == .us))
@ObservationIgnored private var repository: LogRepository?
@@ -52,9 +56,25 @@ final class AppModel {
return
}
#endif
+ // Screenshots and tests: the buttons of the sign-in screen, without tapping them.
+ if LaunchOptions.flag("-restoreBackup") {
+ if (try? await restoreFromBackup()) == nil { phase = .signedOut }
+ return
+ }
+ if LaunchOptions.flag("-startLocal"), (try? await startLocal()) != nil { return }
+ if UserDefaults.standard.bool(forKey: Self.localKey) {
+ do {
+ try await openLocal()
+ phase = .ready
+ } catch {
+ phase = .signedOut
+ }
+ return
+ }
let saved = UserDefaults.standard.string(forKey: "email") ?? ""
guard !saved.isEmpty, let secret = Keychain.password(account: saved) else {
phase = .signedOut
+ await backup.refresh()
return
}
email = saved
@@ -86,6 +106,100 @@ final class AppModel {
logbook = try await repository.logbook()
pending = await repository.pending
lastSync = await repository.lastSync
+ if !isDemo { backup.schedule(repository: repository, account: isLocal ? "" : email) }
+ }
+
+ // MARK: Logbook without an account
+
+ private static let localKey = "localLogbook"
+ private static let localFolder = "_local"
+
+ private func openLocal() async throws {
+ let repo = try LogRepository(directory: try Self.storage(for: Self.localFolder), branch: "local",
+ authorName: Brand.name, authorEmail: "local")
+ repository = repo
+ isLocal = true
+ isDemo = false
+ email = ""
+ try await reload()
+ }
+
+ /// Starts (or goes back to) a logbook kept on this iPhone, optionally from the files of a backup.
+ func startLocal(files: [String: String]? = nil) async throws {
+ do {
+ try await openLocal()
+ guard let repository else { return }
+ if let files {
+ try await repository.discardPending()
+ try await repository.importTree(files: files)
+ } else if await repository.head == nil {
+ _ = try await repository.enqueue(.ensureSettings)
+ try await repository.commitPendingLocally()
+ }
+ UserDefaults.standard.set(true, forKey: Self.localKey)
+ try await reload()
+ syncState = .idle
+ phase = .ready
+ } catch {
+ isLocal = false
+ repository = nil
+ throw AppError.message(Self.describe(error))
+ }
+ }
+
+ /// Restores the logbook from the iCloud backup, as a logbook without an account.
+ func restoreFromBackup() async throws {
+ let files = try await backup.restore()
+ units = Units(imperial: UserDefaults.standard.object(forKey: "imperial") as? Bool ?? units.imperial)
+ try await startLocal(files: files)
+ }
+
+ /// The Subsurface cloud account already holds dives: the user has to say which logbook stays.
+ struct CloudNotEmpty: Error {
+ let cloudDives: Int
+ let localDives: Int
+ }
+
+ /// Connects a logbook kept on this iPhone to a Subsurface cloud account. An account without dives receives the
+ /// logbook. When the account has dives too, `keepLocal` decides: true sends this iPhone's logbook (the cloud's
+ /// stays in its history), false takes the cloud's (this iPhone's stays in the iCloud backup history), nil
+ /// throws `CloudNotEmpty`.
+ func connectCloud(email rawEmail: String, password rawPassword: String, keepLocal: Bool? = nil) async throws {
+ guard isLocal, let local = repository else { return }
+ let account = SubsurfaceCloud.sanitize(email: rawEmail)
+ guard account.contains("@"), !rawPassword.isEmpty else {
+ throw AppError.message(String(localized: "Enter your email and password."))
+ }
+ let transport = SubsurfaceCloud.transport(email: account, password: rawPassword)
+ do {
+ try await local.commitPendingLocally()
+ let files = try await local.exportFiles()
+ let localDives = logbook.dives.count
+ let cloud = try LogRepository(directory: try Self.storage(for: account), branch: account,
+ authorName: Brand.name, authorEmail: account)
+ _ = try await cloud.sync(transport: transport, appVersion: Brand.shortVersion)
+ let cloudDives = try await cloud.logbook().dives.count
+ if localDives > 0 {
+ if cloudDives > 0, keepLocal == nil { throw CloudNotEmpty(cloudDives: cloudDives, localDives: localDives) }
+ if cloudDives == 0 || keepLocal == true {
+ try await cloud.replaceRemote(files: files, transport: transport, appVersion: Brand.shortVersion)
+ }
+ }
+ Keychain.save(password: rawPassword, account: account)
+ UserDefaults.standard.set(account, forKey: "email")
+ UserDefaults.standard.removeObject(forKey: Self.localKey)
+ try? await local.erase()
+ repository = cloud
+ isLocal = false
+ email = account
+ password = rawPassword
+ try await reload()
+ scheduleSync()
+ } catch let error as CloudNotEmpty {
+ throw error
+ } catch {
+ throw AppError.message(Self.describe(error))
+ }
}
/// Checks the credentials with the cloud, then downloads the logbook.
@@ -110,10 +224,16 @@ final class AppModel {
await sync()
}
- func signOut() async {
+ /// Leaves the account (or the demo, or erases a logbook kept without an account). With `keepLogbook`, the
+ /// logbook of a cloud account stays on this iPhone as a logbook without an account.
+ func signOut(keepLogbook: Bool = false) async {
syncTask?.cancel()
+ var kept: [String: String]?
+ if keepLogbook, !isDemo, !isLocal, let repository { kept = try? await repository.exportFiles() }
if let repository { try? await repository.erase() }
- if !isDemo {
+ if isLocal {
+ UserDefaults.standard.removeObject(forKey: Self.localKey)
+ } else if !isDemo {
Keychain.delete(account: email)
UserDefaults.standard.removeObject(forKey: "email")
}
@@ -125,8 +245,11 @@ final class AppModel {
email = ""
password = ""
isDemo = false
+ isLocal = false
syncState = .idle
+ if let kept, (try? await startLocal(files: kept)) != nil { return }
phase = .signedOut
+ await backup.refresh()
}
func startDemo() async {
@@ -172,7 +295,7 @@ final class AppModel {
func sync() async {
guard let repository, syncState != .syncing else { return }
- if isDemo {
+ if isDemo || isLocal {
try? await repository.commitPendingLocally()
try? await reload()
return
diff --git a/App/Model/Cards.swift b/App/Model/Cards.swift
@@ -71,7 +71,6 @@ final class CardStore {
@ObservationIgnored private var syncing = false
@ObservationIgnored private var syncAgain = false
- nonisolated static let containerIdentifier = "iCloud.org.schurger.subrascasse"
private nonisolated static let indexName = "cards.json"
init(directory: URL? = nil) {
@@ -192,7 +191,7 @@ final class CardStore {
/// Merges this iPhone's cards with the copy in iCloud Drive, both ways. Safe to call at any time.
func sync() {
- guard !LaunchOptions.flag("-demoCards"), Bundle.main.object(forInfoDictionaryKey: "CardsICloudBackup") as? Bool == true else {
+ guard !LaunchOptions.flag("-demoCards"), CloudDrive.isBuiltIn else {
backup = .notBuiltIn
return
}
@@ -247,19 +246,12 @@ final class CardStore {
nonisolated private static func merge(local: URL) -> Outcome {
let files = FileManager.default
// Asking for the container can take a while the first time: never on the main thread.
- guard files.ubiquityIdentityToken != nil,
- let container = files.url(forUbiquityContainerIdentifier: containerIdentifier) else { return .unavailable }
- let remote = container.appendingPathComponent("Documents/Cards", isDirectory: true)
- do {
- try files.createDirectory(at: remote, withIntermediateDirectories: true)
- } catch {
- return .failed(error.localizedDescription)
- }
+ guard let remote = CloudDrive.folder("Cards") else { return .unavailable }
// On a new iPhone the files are in iCloud but not downloaded yet: ask for them and give them a moment.
let remoteIndex = remote.appendingPathComponent(indexName)
- download(remoteIndex)
+ CloudDrive.download(remoteIndex)
let mine = read(local.appendingPathComponent(indexName))
- let theirs = coordinatedRead(remoteIndex).map { data -> [CertificationCard] in
+ let theirs = CloudDrive.coordinatedRead(remoteIndex).map { data -> [CertificationCard] in
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
return (try? decoder.decode([CertificationCard].self, from: data)) ?? []
@@ -277,16 +269,16 @@ final class CardStore {
try? files.removeItem(at: here)
photosChanged = true
}
- coordinatedRemove(there)
+ CloudDrive.coordinatedRemove(there)
} else if fromRemote || !files.fileExists(atPath: here.path) {
// The copy in iCloud is the newer one (or the only one): bring its photo here.
- download(there)
- if let data = coordinatedRead(there) {
+ CloudDrive.download(there)
+ if let data = CloudDrive.coordinatedRead(there) {
try? data.write(to: here, options: .atomic)
photosChanged = true
}
- } else if let data = try? Data(contentsOf: here), coordinatedRead(there) != data {
- coordinatedWrite(data, to: there)
+ } else if let data = try? Data(contentsOf: here), CloudDrive.coordinatedRead(there) != data {
+ CloudDrive.coordinatedWrite(data, to: there)
}
}
}
@@ -294,43 +286,8 @@ final class CardStore {
let encoder = JSONEncoder()
encoder.dateEncodingStrategy = .iso8601
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
- if let data = try? encoder.encode(merged) { coordinatedWrite(data, to: remoteIndex) }
+ if let data = try? encoder.encode(merged) { CloudDrive.coordinatedWrite(data, to: remoteIndex) }
}
return .merged(merged, photosChanged: photosChanged)
}
-
- /// Asks iCloud for a file that is not on the device yet, and waits a little for it.
- nonisolated private static func download(_ url: URL) {
- let files = FileManager.default
- let placeholder = url.deletingLastPathComponent().appendingPathComponent("." + url.lastPathComponent + ".icloud")
- guard files.fileExists(atPath: placeholder.path) || isNotDownloaded(url) else { return }
- try? files.startDownloadingUbiquitousItem(at: url)
- for _ in 0..<40 {
- if files.fileExists(atPath: url.path), !isNotDownloaded(url) { return }
- Thread.sleep(forTimeInterval: 0.25)
- }
- }
-
- nonisolated private static func isNotDownloaded(_ url: URL) -> Bool {
- guard let status = try? url.resourceValues(forKeys: [.ubiquitousItemDownloadingStatusKey]).ubiquitousItemDownloadingStatus else { return false }
- return status == .notDownloaded
- }
-
- nonisolated private static func coordinatedRead(_ url: URL) -> Data? {
- var data: Data?
- var error: NSError?
- NSFileCoordinator().coordinate(readingItemAt: url, options: [], error: &error) { data = try? Data(contentsOf: $0) }
- return data
- }
-
- nonisolated private static func coordinatedWrite(_ data: Data, to url: URL) {
- var error: NSError?
- NSFileCoordinator().coordinate(writingItemAt: url, options: .forReplacing, error: &error) { try? data.write(to: $0, options: .atomic) }
- }
-
- nonisolated private static func coordinatedRemove(_ url: URL) {
- guard FileManager.default.fileExists(atPath: url.path) else { return }
- var error: NSError?
- NSFileCoordinator().coordinate(writingItemAt: url, options: .forDeleting, error: &error) { try? FileManager.default.removeItem(at: $0) }
- }
}
diff --git a/App/Model/CloudDrive.swift b/App/Model/CloudDrive.swift
@@ -0,0 +1,80 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import Foundation
+
+/// The app's folder in the user's iCloud Drive ("Sub Rascasse" in the Files app), where backups go. Everything
+/// here blocks: call it off the main thread.
+enum CloudDrive {
+ static let containerIdentifier = "iCloud.org.schurger.subrascasse"
+
+ /// False for a build without the iCloud entitlements (see `CardsICloudBackup` in project.yml).
+ static var isBuiltIn: Bool { testFolder != nil || Bundle.main.object(forInfoDictionaryKey: "CardsICloudBackup") as? Bool == true }
+
+ /// "-backupFolder path": a plain folder stands in for iCloud Drive (the simulator has no iCloud account).
+ private static let testFolder: URL? = {
+ let arguments = ProcessInfo.processInfo.arguments
+ guard let index = arguments.firstIndex(of: "-backupFolder"), index + 1 < arguments.count else { return nil }
+ return URL(fileURLWithPath: arguments[index + 1], isDirectory: true)
+ }()
+
+ /// A folder of the app's iCloud Drive, created if needed; nil without an iCloud account or with iCloud Drive
+ /// turned off for the app.
+ static func folder(_ name: String) -> URL? {
+ let files = FileManager.default
+ if let testFolder {
+ let folder = testFolder.appendingPathComponent(name, isDirectory: true)
+ try? files.createDirectory(at: folder, withIntermediateDirectories: true)
+ return folder
+ }
+ guard isBuiltIn, files.ubiquityIdentityToken != nil,
+ let container = files.url(forUbiquityContainerIdentifier: containerIdentifier) else { return nil }
+ let folder = container.appendingPathComponent("Documents", isDirectory: true).appendingPathComponent(name, isDirectory: true)
+ do {
+ try files.createDirectory(at: folder, withIntermediateDirectories: true)
+ } catch {
+ return nil
+ }
+ return folder
+ }
+
+ /// The files of a folder, including those that are in iCloud but not downloaded yet (listed as ".name.icloud").
+ static func names(in folder: URL) -> [String] {
+ ((try? FileManager.default.contentsOfDirectory(atPath: folder.path)) ?? []).map { name in
+ name.hasPrefix(".") && name.hasSuffix(".icloud") ? String(name.dropFirst().dropLast(7)) : name
+ }
+ }
+
+ /// Asks iCloud for a file that is not on the device yet, and waits a little for it.
+ static func download(_ url: URL) {
+ let files = FileManager.default
+ let placeholder = url.deletingLastPathComponent().appendingPathComponent("." + url.lastPathComponent + ".icloud")
+ guard files.fileExists(atPath: placeholder.path) || isNotDownloaded(url) else { return }
+ try? files.startDownloadingUbiquitousItem(at: url)
+ for _ in 0..<40 {
+ if files.fileExists(atPath: url.path), !isNotDownloaded(url) { return }
+ Thread.sleep(forTimeInterval: 0.25)
+ }
+ }
+
+ static func isNotDownloaded(_ url: URL) -> Bool {
+ guard let status = try? url.resourceValues(forKeys: [.ubiquitousItemDownloadingStatusKey]).ubiquitousItemDownloadingStatus else { return false }
+ return status == .notDownloaded
+ }
+
+ static func coordinatedRead(_ url: URL) -> Data? {
+ var data: Data?
+ var error: NSError?
+ NSFileCoordinator().coordinate(readingItemAt: url, options: [], error: &error) { data = try? Data(contentsOf: $0) }
+ return data
+ }
+
+ static func coordinatedWrite(_ data: Data, to url: URL) {
+ var error: NSError?
+ NSFileCoordinator().coordinate(writingItemAt: url, options: .forReplacing, error: &error) { try? data.write(to: $0, options: .atomic) }
+ }
+
+ static func coordinatedRemove(_ url: URL) {
+ guard FileManager.default.fileExists(atPath: url.path) else { return }
+ var error: NSError?
+ NSFileCoordinator().coordinate(writingItemAt: url, options: .forDeleting, error: &error) { try? FileManager.default.removeItem(at: $0) }
+ }
+}
diff --git a/App/Model/LogbookBackup.swift b/App/Model/LogbookBackup.swift
@@ -0,0 +1,204 @@
+// SPDX-License-Identifier: GPL-2.0-only
+import CryptoKit
+import Foundation
+import GitLite
+import Observation
+import SubsurfaceLog
+import UIKit
+
+/// What a backup holds, readable without opening the archive.
+struct LogbookBackupInfo: Codable, Equatable {
+ var saved: Date
+ var dives: Int
+ var sites: Int
+ /// Subsurface cloud account the logbook belongs to; empty for a logbook kept without an account.
+ var account: String
+ var device: String
+ var appVersion: String
+}
+
+/// Copies the logbook and the settings to the app's iCloud Drive folder, a few seconds after each change:
+/// `Logbook/logbook.zip` (the files of the Subsurface git format, as Subsurface stores them), `logbook.json`
+/// (what it holds), `settings.plist`, and one archive per day in `history` for the last few days.
+@MainActor
+@Observable
+final class LogbookBackup {
+ enum State: Equatable {
+ case unknown
+ /// This build has no iCloud folder.
+ case notBuiltIn
+ /// No iCloud account, or iCloud Drive turned off for the app.
+ case unavailable
+ case working
+ case done(Date)
+ case failed(String)
+ }
+
+ private(set) var state = State.unknown
+ /// The backup found in iCloud, if any (offered on the sign-in screen).
+ private(set) var available: LogbookBackupInfo?
+
+ @ObservationIgnored private var task: Task<Void, Never>?
+ nonisolated private static let folderName = "Logbook"
+ nonisolated private static let hashKey = "backupHash"
+ nonisolated private static let historyDays = 7
+ /// Settings that describe this installation, not the user's choices: never copied.
+ nonisolated static let localOnlyKeys: Set<String> = ["email", "localLogbook", hashKey]
+
+ /// Backs the logbook up shortly: changes that follow each other closely make one backup.
+ func schedule(repository: LogRepository, account: String) {
+ guard CloudDrive.isBuiltIn else {
+ state = .notBuiltIn
+ return
+ }
+ task?.cancel()
+ task = Task { [weak self] in
+ try? await Task.sleep(for: .seconds(LaunchOptions.value("-backupFolder") != nil ? 1 : 4))
+ guard !Task.isCancelled else { return }
+ await self?.run(repository: repository, account: account)
+ }
+ }
+
+ private func run(repository: LogRepository, account: String) async {
+ guard let files = try? await repository.exportFiles(), let logbook = try? await repository.logbook() else { return }
+ // An empty logbook never replaces a backup: a fresh installation must not wipe what is in iCloud.
+ guard !logbook.dives.isEmpty else {
+ await refresh()
+ return
+ }
+ if state == .unknown || state == .unavailable { state = .working }
+ let info = LogbookBackupInfo(saved: Date(), dives: logbook.dives.count, sites: logbook.sites.count, account: account,
+ device: UIDevice.current.name, appVersion: Brand.version)
+ let settings = Self.settingsToSave()
+ let previousHash = UserDefaults.standard.string(forKey: Self.hashKey)
+ let outcome = await Task.detached(priority: .utility) {
+ Self.write(files: files, info: info, settings: settings, previousHash: previousHash)
+ }.value
+ switch outcome {
+ case .unavailable: state = .unavailable
+ case .failed(let message): state = .failed(message)
+ case .written(let hash):
+ UserDefaults.standard.set(hash, forKey: Self.hashKey)
+ state = .done(info.saved)
+ available = info
+ case .unchanged:
+ await refresh()
+ if case .done = state {} else { state = .done(available?.saved ?? info.saved) }
+ }
+ }
+
+ /// Looks at what iCloud holds.
+ func refresh() async {
+ guard CloudDrive.isBuiltIn else {
+ state = .notBuiltIn
+ return
+ }
+ let found = await Task.detached(priority: .utility) { () -> (reachable: Bool, info: LogbookBackupInfo?) in
+ guard let folder = CloudDrive.folder(Self.folderName) else { return (false, nil) }
+ let url = folder.appendingPathComponent("logbook.json")
+ CloudDrive.download(url)
+ guard let data = CloudDrive.coordinatedRead(url) else { return (true, nil) }
+ let decoder = JSONDecoder()
+ decoder.dateDecodingStrategy = .iso8601
+ return (true, try? decoder.decode(LogbookBackupInfo.self, from: data))
+ }.value
+ available = found.info
+ if !found.reachable {
+ state = .unavailable
+ } else if let info = found.info, state == .unknown || state == .unavailable || state == .working {
+ state = .done(info.saved)
+ } else if state == .unavailable {
+ state = .unknown
+ }
+ }
+
+ /// The files of the logbook in iCloud; the settings that this iPhone does not have yet are taken along.
+ func restore() async throws -> [String: String] {
+ let result = await Task.detached(priority: .userInitiated) { () -> Result<([String: String], [String: Any]), AppError> in
+ guard let folder = CloudDrive.folder(Self.folderName) else {
+ return .failure(.message(String(localized: "iCloud Drive is not available on this iPhone.")))
+ }
+ let url = folder.appendingPathComponent("logbook.zip")
+ CloudDrive.download(url)
+ guard let data = CloudDrive.coordinatedRead(url), let archive = try? ZipArchive(Array(data)) else {
+ return .failure(.message(String(localized: "The backup in iCloud could not be read. It may still be downloading: try again in a moment.")))
+ }
+ var files = [String: String]()
+ for entry in archive.entries {
+ guard let bytes = try? archive.contents(of: entry) else {
+ return .failure(.message(String(localized: "The backup in iCloud is damaged.")))
+ }
+ files[entry.name] = String(decoding: bytes, as: UTF8.self)
+ }
+ var settings = [String: Any]()
+ let settingsURL = folder.appendingPathComponent("settings.plist")
+ CloudDrive.download(settingsURL)
+ if let data = CloudDrive.coordinatedRead(settingsURL),
+ let list = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] {
+ settings = list
+ }
+ return .success((files, settings))
+ }.value
+ let (files, settings) = try result.get()
+ guard files["00-Subsurface"] != nil || !files.isEmpty else {
+ throw AppError.message(String(localized: "The backup in iCloud is empty."))
+ }
+ for (key, value) in settings where !Self.localOnlyKeys.contains(key) && UserDefaults.standard.object(forKey: key) == nil {
+ UserDefaults.standard.set(value, forKey: key)
+ }
+ return files
+ }
+
+ // MARK: Files
+
+ private enum Outcome {
+ case unavailable
+ case unchanged
+ case written(String)
+ case failed(String)
+ }
+
+ private static func settingsToSave() -> [String: Any] {
+ guard let domain = Bundle.main.bundleIdentifier.flatMap({ UserDefaults.standard.persistentDomain(forName: $0) }) else { return [:] }
+ return domain.filter { key, value in
+ !localOnlyKeys.contains(key) && !key.hasPrefix("Apple") && !key.hasPrefix("NS") && !key.hasPrefix("com.apple")
+ && PropertyListSerialization.propertyList(value, isValidFor: .binary)
+ }
+ }
+
+ nonisolated private static func write(files: [String: String], info: LogbookBackupInfo, settings: [String: Any], previousHash: String?) -> Outcome {
+ guard let folder = CloudDrive.folder(folderName) else { return .unavailable }
+ let archive = ZipArchive.archive(files.sorted { $0.key < $1.key }.map { ($0.key, Array($0.value.utf8)) })
+ let hash = SHA256.hash(data: Data(archive)).map { String(format: "%02x", $0) }.joined()
+ let latest = folder.appendingPathComponent("logbook.zip")
+ if hash == previousHash, CloudDrive.names(in: folder).contains("logbook.zip") {
+ writeSettings(settings, in: folder)
+ return .unchanged
+ }
+ CloudDrive.coordinatedWrite(Data(archive), to: latest)
+ guard CloudDrive.names(in: folder).contains("logbook.zip") else { return .failed(String(localized: "Couldn't write to iCloud Drive.")) }
+ let encoder = JSONEncoder()
+ encoder.dateEncodingStrategy = .iso8601
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ if let data = try? encoder.encode(info) { CloudDrive.coordinatedWrite(data, to: folder.appendingPathComponent("logbook.json")) }
+ writeSettings(settings, in: folder)
+
+ // One archive per day, the last few days: a mistake made today does not erase yesterday's logbook.
+ let history = folder.appendingPathComponent("history", isDirectory: true)
+ try? FileManager.default.createDirectory(at: history, withIntermediateDirectories: true)
+ let day = DateFormatter()
+ day.calendar = Calendar(identifier: .gregorian)
+ day.locale = Locale(identifier: "en_US_POSIX")
+ day.dateFormat = "yyyy-MM-dd"
+ CloudDrive.coordinatedWrite(Data(archive), to: history.appendingPathComponent("logbook-\(day.string(from: info.saved)).zip"))
+ let kept = CloudDrive.names(in: history).filter { $0.hasPrefix("logbook-") && $0.hasSuffix(".zip") }.sorted()
+ for name in kept.dropLast(historyDays) { CloudDrive.coordinatedRemove(history.appendingPathComponent(name)) }
+ return .written(hash)
+ }
+
+ nonisolated private static func writeSettings(_ settings: [String: Any], in folder: URL) {
+ guard let data = try? PropertyListSerialization.data(fromPropertyList: settings, format: .xml, options: 0) else { return }
+ let url = folder.appendingPathComponent("settings.plist")
+ if CloudDrive.coordinatedRead(url) != data { CloudDrive.coordinatedWrite(data, to: url) }
+ }
+}
diff --git a/App/Views/LoginView.swift b/App/Views/LoginView.swift
@@ -28,7 +28,7 @@ struct LoginView: View {
.padding(.top, 32)
Text(Brand.name)
.font(.largeTitle.bold())
- Text("Your Subsurface dive log, on iPhone.")
+ Text("Your dive log, on iPhone.")
.font(.subheadline)
.foregroundStyle(.secondary)
.multilineTextAlignment(.center)
@@ -78,11 +78,33 @@ struct LoginView: View {
}
.font(.subheadline)
- Button("Try a demo logbook") {
- Task { await model.startDemo() }
+ VStack(spacing: 10) {
+ Text("Or, without an account")
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+ if let found = model.backup.available {
+ Button {
+ run { try await model.restoreFromBackup() }
+ } label: {
+ Label("Restore the iCloud backup (\(found.dives) dives, \(found.saved.formatted(date: .abbreviated, time: .omitted)))",
+ systemImage: "icloud.and.arrow.down")
+ .frame(maxWidth: .infinity)
+ }
+ .buttonStyle(.bordered)
+ }
+ Button {
+ run { try await model.startLocal() }
+ } label: {
+ Text("Keep my logbook on this iPhone").frame(maxWidth: .infinity)
+ }
+ .buttonStyle(.bordered)
+ Button("Try a demo logbook") {
+ Task { await model.startDemo() }
+ }
+ .font(.subheadline)
}
- .font(.subheadline)
.disabled(busy)
+ .padding(.top, 8)
Text(disclaimer)
.font(.footnote)
@@ -94,6 +116,7 @@ struct LoginView: View {
}
.background(Color(.systemGroupedBackground))
.scrollDismissesKeyboard(.interactively)
+ .task { await model.backup.refresh() }
.sheet(isPresented: $creating) {
CreateAccountView { newEmail, newPassword in
email = newEmail
@@ -104,6 +127,20 @@ struct LoginView: View {
}
}
+ private func run(_ work: @escaping () async throws -> Void) {
+ guard !busy else { return }
+ busy = true
+ error = nil
+ Task {
+ do {
+ try await work()
+ } catch {
+ self.error = AppModel.describe(error)
+ }
+ busy = false
+ }
+ }
+
private func signIn() {
guard !busy, !email.isEmpty, !password.isEmpty else { return }
busy = true
diff --git a/App/Views/SettingsView.swift b/App/Views/SettingsView.swift
@@ -6,6 +6,7 @@ struct SettingsView: View {
@State private var confirmingSignOut = false
@State private var importing = false
@State private var downloading = false
+ @State private var connecting = LaunchOptions.flag("-connectCloud")
@State private var showingCards = LaunchOptions.flag("-cards")
@Environment(CardStore.self) private var cards
@@ -22,6 +23,14 @@ struct SettingsView: View {
Text("Changes stay on this iPhone and disappear when you leave the demo.")
.font(.footnote)
.foregroundStyle(.secondary)
+ } else if model.isLocal {
+ Label("Logbook on this iPhone", systemImage: "iphone")
+ Text("No Subsurface cloud account: the logbook is kept on this iPhone. Connect an account to use it in Subsurface too, on a computer for instance.")
+ .font(.footnote)
+ .foregroundStyle(.secondary)
+ Button { connecting = true } label: {
+ Label("Connect to Subsurface cloud…", systemImage: "cloud")
+ }
} else {
LabeledContent("Subsurface cloud", value: model.email)
LabeledContent("Last sync") {
@@ -44,6 +53,16 @@ struct SettingsView: View {
}
}
+ if !model.isDemo {
+ Section {
+ LabeledContent("Logbook and settings") { BackupStatus(state: model.backup.state) }
+ } header: {
+ Text("iCloud backup")
+ } footer: {
+ Text("A copy of the logbook and of the settings goes to the Sub Rascasse folder of your iCloud Drive after each change, with one archive per day for the last week. Your photos are not copied.")
+ }
+ }
+
if !model.pending.isEmpty {
Section("Waiting to upload") {
ForEach(Array(model.pending.enumerated()), id: \.offset) { _, change in
@@ -103,7 +122,8 @@ struct SettingsView: View {
}
Section {
- Button(model.isDemo ? String(localized: "Leave the demo") : String(localized: "Sign out"), role: .destructive) {
+ Button(model.isDemo ? String(localized: "Leave the demo")
+ : (model.isLocal ? String(localized: "Erase the logbook from this iPhone") : String(localized: "Sign out")), role: .destructive) {
confirmingSignOut = true
}
}
@@ -113,18 +133,125 @@ struct SettingsView: View {
.navigationDestination(isPresented: $showingCards) { CardsView() }
.modifier(FileImport(isPresented: $importing))
.modifier(DiveComputerImport(isPresented: $downloading))
- .confirmationDialog(model.isDemo ? String(localized: "Leave the demo?") : String(localized: "Sign out?"),
+ .sheet(isPresented: $connecting) { ConnectCloudView() }
+ .confirmationDialog(model.isDemo ? String(localized: "Leave the demo?")
+ : (model.isLocal ? String(localized: "Erase the logbook?") : String(localized: "Sign out?")),
isPresented: $confirmingSignOut, titleVisibility: .visible) {
- Button(model.isDemo ? String(localized: "Leave") : String(localized: "Sign out"), role: .destructive) {
- Task { await model.signOut() }
+ if model.isDemo {
+ Button("Leave", role: .destructive) { Task { await model.signOut() } }
+ } else if model.isLocal {
+ Button("Erase", role: .destructive) { Task { await model.signOut() } }
+ } else {
+ Button("Sign out and keep the logbook on this iPhone") { Task { await model.signOut(keepLogbook: true) } }
+ Button("Sign out and erase the copy", role: .destructive) { Task { await model.signOut() } }
}
} message: {
- if !model.isDemo, !model.pending.isEmpty {
- Text("Warning: \(model.pending.count) change(s) not yet uploaded will be lost. The copy of the logbook on this iPhone will be erased.")
+ if model.isLocal {
+ Text("The logbook is removed from this iPhone. The last copy saved in iCloud Drive, if any, stays there.")
+ } else if !model.isDemo, !model.pending.isEmpty {
+ Text("Warning: \(model.pending.count) change(s) not yet uploaded will be lost if you erase the copy. Nothing is deleted in the cloud.")
} else if !model.isDemo {
- Text("The copy of the logbook on this iPhone will be erased. Nothing is deleted in the cloud.")
+ Text("Keeping the logbook lets you go on without the Subsurface cloud. Nothing is deleted in the cloud either way.")
+ }
+ }
+ }
+ }
+}
+
+/// State of an iCloud backup, in a few words.
+struct BackupStatus: View {
+ let state: LogbookBackup.State
+
+ var body: some View {
+ switch state {
+ case .unknown: Text("Not yet").foregroundStyle(.secondary)
+ case .working: ProgressView()
+ case .notBuiltIn: Text("Not in this version").foregroundStyle(.secondary)
+ case .unavailable: Text("iCloud Drive is off").foregroundStyle(.orange)
+ case .done(let date): Text(date.formatted(.relative(presentation: .named)))
+ case .failed(let message): Text(message).foregroundStyle(.red)
+ }
+ }
+}
+
+/// Connects a logbook kept on this iPhone to a Subsurface cloud account.
+struct ConnectCloudView: View {
+ @Environment(AppModel.self) private var model
+ @Environment(\.dismiss) private var dismiss
+ @State private var email = ""
+ @State private var password = ""
+ @State private var busy = false
+ @State private var creating = false
+ @State private var error: String?
+ @State private var conflict: AppModel.CloudNotEmpty?
+
+ var body: some View {
+ NavigationStack {
+ Form {
+ Section {
+ TextField("Subsurface account email", text: $email)
+ .textContentType(.username)
+ .keyboardType(.emailAddress)
+ .textInputAutocapitalization(.never)
+ .autocorrectionDisabled()
+ SecureField("Password", text: $password)
+ .textContentType(.password)
+ } footer: {
+ Text("The logbook of this iPhone is sent to the account, then kept in sync with it. If the account already has dives, you choose which logbook stays.")
+ }
+ Section {
+ Button("Create an account") { creating = true }
+ Link("Forgot password?", destination: URL(string: "https://cloud.subsurface-divelog.org/passwordreset")!)
+ }
+ if let error {
+ Section { Text(error).foregroundStyle(.red) }
+ }
+ }
+ .navigationTitle("Subsurface cloud")
+ .navigationBarTitleDisplayMode(.inline)
+ .toolbar {
+ ToolbarItem(placement: .cancellationAction) { Button("Cancel") { dismiss() } }
+ ToolbarItem(placement: .confirmationAction) {
+ if busy { ProgressView() } else {
+ Button("Connect") { connect(keepLocal: nil) }.disabled(email.isEmpty || password.isEmpty)
+ }
}
}
+ .sheet(isPresented: $creating) {
+ CreateAccountView { newEmail, newPassword in
+ email = newEmail
+ password = newPassword
+ connect(keepLocal: nil)
+ }
+ }
+ .confirmationDialog("This account already has a logbook", isPresented: Binding(get: { conflict != nil }, set: { if !$0 { conflict = nil } }),
+ titleVisibility: .visible) {
+ Button("Send this iPhone's logbook to the account") { connect(keepLocal: true) }
+ Button("Use the account's logbook") { connect(keepLocal: false) }
+ Button("Cancel", role: .cancel) {}
+ } message: {
+ if let conflict {
+ Text("The account holds \(conflict.cloudDives) dives, this iPhone \(conflict.localDives). The two are not mixed: the one you do not keep stays recoverable, in the history of the account or in the iCloud backups of the last week.")
+ }
+ }
+ }
+ .interactiveDismissDisabled(busy)
+ }
+
+ private func connect(keepLocal: Bool?) {
+ guard !busy else { return }
+ busy = true
+ error = nil
+ Task {
+ do {
+ try await model.connectCloud(email: email, password: password, keepLocal: keepLocal)
+ dismiss()
+ } catch let found as AppModel.CloudNotEmpty {
+ conflict = found
+ } catch {
+ self.error = AppModel.describe(error)
+ }
+ busy = false
}
}
}
diff --git a/Packages/DiveKit/Sources/GitLite/Compression.swift b/Packages/DiveKit/Sources/GitLite/Compression.swift
@@ -63,6 +63,57 @@ public enum Inflate {
}
}
+public extension Inflate {
+ /// Raw "deflate" stream, as stored in a zip entry.
+ static func deflateRaw(_ input: [UInt8]) -> [UInt8] {
+ guard !input.isEmpty else { return [] }
+ var stream = z_stream()
+ guard deflateInit2_(&stream, Z_DEFAULT_COMPRESSION, Z_DEFLATED, -15, 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)
+ let written: Int = input.withUnsafeBufferPointer { inPtr in
+ output.withUnsafeMutableBufferPointer { outPtr in
+ stream.next_in = UnsafeMutablePointer(mutating: inPtr.baseAddress!)
+ 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])
+ }
+}
+
+public extension ZipArchive {
+ /// Writes a zip archive (deflate, no zip64): enough for a logbook, readable by any unzip tool.
+ static func archive(_ files: [(name: String, data: [UInt8])]) -> [UInt8] {
+ func le16(_ value: Int) -> [UInt8] { [UInt8(value & 0xFF), UInt8(value >> 8 & 0xFF)] }
+ func le32(_ value: Int) -> [UInt8] { le16(value & 0xFFFF) + le16(value >> 16 & 0xFFFF) }
+ var out = [UInt8]()
+ var directory = [UInt8]()
+ for file in files {
+ let name = Array(file.name.utf8)
+ let packed = Inflate.deflateRaw(file.data)
+ let stored = file.data.isEmpty || packed.isEmpty || packed.count >= file.data.count
+ let body = stored ? file.data : packed
+ let checksum = file.data.withUnsafeBufferPointer { Int(crc32(0, $0.baseAddress, UInt32($0.count))) }
+ // Version 2.0, UTF-8 names (bit 11), fixed date (1980-01-01): the archive only depends on its contents.
+ let common = le16(20) + le16(0x0800) + le16(stored ? 0 : 8) + le16(0) + le16(0x21)
+ + le32(checksum) + le32(body.count) + le32(file.data.count) + le16(name.count) + le16(0)
+ let offset = out.count
+ out += [0x50, 0x4b, 0x03, 0x04] + common + name + body
+ directory += [0x50, 0x4b, 0x01, 0x02] + le16(20) + common + le16(0) + le16(0) + le16(0) + le32(0) + le32(offset) + name
+ }
+ let start = out.count
+ out += directory
+ out += [0x50, 0x4b, 0x05, 0x06] + le16(0) + le16(0) + le16(files.count) + le16(files.count)
+ + le32(directory.count) + le32(start) + le16(0)
+ return out
+ }
+}
+
/// Minimal reader for a zip archive (no zip64, no encryption).
public struct ZipArchive {
public struct Entry {
diff --git a/Packages/DiveKit/Sources/SubsurfaceLog/Repository.swift b/Packages/DiveKit/Sources/SubsurfaceLog/Repository.swift
@@ -264,11 +264,47 @@ public actor LogRepository {
try save()
}
- /// Replaces the local logbook with a tree built locally (demo mode, without a server).
+ /// Every file of the logbook as the user sees it (pending changes included), by path: what a backup holds,
+ /// and what `importTree` takes back.
+ public func exportFiles() throws -> [String: String] {
+ var files = [String: String]()
+ func walk(_ tree: ObjectID, _ prefix: String) throws {
+ for entry in try store.tree(tree) {
+ let path = prefix.isEmpty ? entry.name : prefix + "/" + entry.name
+ if entry.isTree {
+ try walk(entry.id, path)
+ } else {
+ files[path] = String(decoding: try store.blob(entry.id), as: UTF8.self)
+ }
+ }
+ }
+ if let root = try workingTree() { try walk(root, "") }
+ return files
+ }
+
+ /// Sends a whole logbook to the server as the new state of the branch, on top of whatever is there (which
+ /// stays in the history), and makes it the local logbook. For a logbook kept without an account, the day its
+ /// owner connects one.
+ public func replaceRemote(files: [String: String], transport: GitTransport, appVersion: String = "0.1") async throws {
+ let client = GitClient(transport: transport, store: store)
+ let remoteHead = try await client.refs().branch(branch)
+ let recorder = RecordingStore(base: store)
+ let root = try LogEditor.buildTree(files: files, store: recorder)
+ let who = Commit.signature(name: authorName, email: authorEmail)
+ let message = "Logbook kept on the iPhone, now sent to the cloud\n\nCreated by \(authorName) \(appVersion)\n"
+ let commit = GitObject(type: .commit, data: Commit(tree: root, parents: remoteHead.map { [$0] } ?? [],
+ author: who, committer: who, message: message).serialize())
+ let commitID = try recorder.put(commit)
+ try await client.push(ref: "refs/heads/\(branch)", old: remoteHead, new: commitID, objects: recorder.objects)
+ state = State(head: commitID, lastSync: Date())
+ try save()
+ }
+
+ /// Replaces the local logbook with a tree built locally (no server: demo, logbook without an account, backup).
public func importTree(files: [String: String]) throws {
let root = try LogEditor.buildTree(files: files, store: store)
let who = Commit.signature(name: authorName, email: authorEmail)
- let commit = Commit(tree: root, parents: [], author: who, committer: who, message: "Demo logbook\n")
+ let commit = Commit(tree: root, parents: [], author: who, committer: who, message: "Logbook\n")
state = State(head: try store.put(GitObject(type: .commit, data: commit.serialize())))
try save()
}
diff --git a/Packages/DiveKit/Tests/SubsurfaceLogTests/SubsurfaceLogTests.swift b/Packages/DiveKit/Tests/SubsurfaceLogTests/SubsurfaceLogTests.swift
@@ -157,6 +157,62 @@ final class SubsurfaceLogTests: XCTestCase {
"duration 50:00 min\nbuddy \"Sam\"\ncylinder vol=11.1l\n")
}
+ /// A logbook kept without an account: exported, zipped, read back, then sent to an account that gets one.
+ func testLocalLogbookBackupAndConnect() async throws {
+ let (remote, _) = try Fixture.makeRemote()
+ let transport = LocalProcessTransport(repository: remote.directory)
+ let source = try LogRepository(directory: try LocalGit.temporaryDirectory("source"), branch: Fixture.branch,
+ authorName: "DiveLog", authorEmail: Fixture.branch)
+ _ = try await source.sync(transport: transport)
+ let original = try await source.logbook()
+ let files = try await source.exportFiles()
+ XCTAssertNotNil(files["00-Subsurface"])
+ XCTAssertGreaterThan(files.count, original.dives.count)
+
+ // Zip round trip, with names in sub-folders and an empty file.
+ let archive = ZipArchive.archive(files.sorted { $0.key < $1.key }.map { ($0.key, Array($0.value.utf8)) } + [("empty", [])])
+ XCTAssertTrue(ZipArchive.isZip(archive))
+ let read = try ZipArchive(archive)
+ XCTAssertEqual(read.entries.count, files.count + 1)
+ var restored = [String: String]()
+ for entry in read.entries where entry.name != "empty" {
+ restored[entry.name] = String(decoding: try read.contents(of: entry), as: UTF8.self)
+ }
+ XCTAssertEqual(restored, files)
+
+ // A logbook without a server: the backup comes back, a change is committed locally.
+ let local = try LogRepository(directory: try LocalGit.temporaryDirectory("alone"), branch: "local",
+ authorName: "DiveLog", authorEmail: "local")
+ try await local.importTree(files: restored)
+ var log = try await local.logbook()
+ XCTAssertEqual(log.dives.map(\.when), original.dives.map(\.when))
+ let first = try XCTUnwrap(log.dives.first)
+ log = try await local.enqueue(.editDive(when: first.when, number: first.number, fields: ["buddy": "Kept offline"]))
+ try await local.commitPendingLocally()
+ let stillPending = await local.pending
+ XCTAssertTrue(stillPending.isEmpty)
+ let kept = try await local.logbook()
+ XCTAssertEqual(kept.dives.first?.buddy, "Kept offline")
+
+ // The day an account is connected: the whole logbook goes up, on top of what the account held.
+ let cloud = try LogRepository(directory: try LocalGit.temporaryDirectory("cloud"), branch: Fixture.branch,
+ authorName: "DiveLog", authorEmail: Fixture.branch)
+ _ = try await cloud.sync(transport: transport)
+ let localFiles = try await local.exportFiles()
+ try await cloud.replaceRemote(files: localFiles, transport: transport)
+ try remote.git(["fsck", "--strict"])
+ let sent = try await cloud.logbook()
+ XCTAssertEqual(sent.dives.first?.buddy, "Kept offline")
+ let again = try LogRepository(directory: try LocalGit.temporaryDirectory("again"), branch: Fixture.branch,
+ authorName: "DiveLog", authorEmail: Fixture.branch)
+ _ = try await again.sync(transport: transport)
+ let fetched = try await again.logbook()
+ XCTAssertEqual(fetched.dives.first?.buddy, "Kept offline")
+ let fetchedFiles = try await again.exportFiles()
+ XCTAssertEqual(fetchedFiles, localFiles)
+ _ = try await cloud.sync(transport: transport)
+ }
+
/// Editing the equipment rewrites the lines that changed and nothing else.
func testEquipmentPatch() {
let file = """
diff --git a/README.md b/README.md
@@ -47,6 +47,12 @@ The app is available in English and French.
side, shown full screen. They are not part of the Subsurface logbook: they are kept on the iPhone and copied
automatically to the app's iCloud Drive folder (`iCloud.org.schurger.subrascasse`, `Documents/Cards`), merged
both ways at launch, so they come back on a new iPhone.
+- The Subsurface cloud account is optional: the logbook can live on the iPhone alone (same storage, a local git
+ repository in the Subsurface format, without a remote). An account can be connected later (an account without
+ dives receives the logbook; otherwise the user picks which one stays), and signing out can keep the logbook.
+- iCloud backup: after each change, the logbook goes to the app's iCloud Drive folder as `Logbook/logbook.zip`
+ (the files of the Subsurface git format), with `logbook.json` (what it holds), `settings.plist` and one archive
+ per day for a week in `history`. The sign-in screen offers to restore it. Photos are not copied.
- Creation of a Subsurface cloud account (email, password, code received by email).
- Demo logbook (a button on the sign-in screen, or the `-demo` launch option).
@@ -97,7 +103,7 @@ Not there yet: Subsurface XML import, dive planner.
Launch options: `-demo`, `-tab sites|stats|settings`, `-showDive N`, `-scroll notes|bottom`, `-edit`, `-newDive`,
`-demoChanges`, `-importFile path`, `-importAll`, `-createAccount`, `-remoraFolder path`, `-merouFolder path`,
-`-selectDives 12,13` (the selection that precedes a merge; with `-merge`, its confirmation), `-cards`, `-demoCards`, `-showCard`, `-editCard`, `-selectDives 12,13`, `-mergeNow`, `-diveComputer`
+`-selectDives 12,13` (the selection that precedes a merge; with `-merge`, its confirmation), `-startLocal`, `-restoreBackup`, `-backupFolder path` (a plain folder stands in for iCloud Drive), `-connectCloud`, `-cards`, `-demoCards`, `-showCard`, `-editCard`, `-selectDives 12,13`, `-mergeNow`, `-diveComputer`
(opens the download sheet; with `-fakeComputers` it lists made-up computers, the simulator having no Bluetooth).
### Validating on a real logbook
diff --git a/fastlane/Fastfile b/fastlane/Fastfile
@@ -75,10 +75,10 @@ platform :ios do
UI.message("TESTER #{email} already there")
end
texts = {
- "fr-CA" => ["Votre carnet de plongée Subsurface sur iPhone : lecture, profils, modification hors ligne, synchronisation avec le nuage Subsurface. Application indépendante de l'équipe de Subsurface.",
- "0.6 : Nouveau : sauvegarde automatique des cartes de certification dans iCloud Drive (Réglages, Cartes de certification ; un dossier Sub Rascasse apparaît dans Fichiers, iCloud Drive). Corrigé : toucher une plongée dans la liste l'ouvre de nouveau. Depuis la 0.5 : bouteilles et lest dans Modifier, cartes de certification, fusion de plongées depuis la liste (+) ou la fiche (menu ...)."],
- "en-CA" => ["Your Subsurface dive log on iPhone: browse, profiles, offline editing, sync with Subsurface cloud storage. Independent from the Subsurface team.",
- "0.6: New: automatic backup of the certification cards in iCloud Drive (Settings, Certification cards; a Sub Rascasse folder appears in Files, iCloud Drive). Fixed: tapping a dive in the list opens it again. Since 0.5: cylinders and weights in Edit, certification cards, merging dives from the list (+) or a dive page (... menu)."],
+ "fr-CA" => ["Votre carnet de plongée sur iPhone : profils, modification hors ligne, ordinateur de plongée en Bluetooth, synchronisation facultative avec le nuage Subsurface, sauvegarde iCloud. Application indépendante de l'équipe de Subsurface.",
+ "0.7 : Nouveau : (1) Sauvegarde iCloud complète : le carnet et les réglages sont copiés dans le dossier Sub Rascasse d'iCloud Drive après chaque modification (une archive par jour sur une semaine), en plus des cartes de certification ; les photos ne sont pas copiées. Réglages indique la date de la dernière sauvegarde. (2) Le compte du nuage Subsurface devient facultatif : on peut garder le carnet sur l'iPhone, restaurer la sauvegarde iCloud depuis l'écran d'accueil, connecter un compte plus tard, ou se déconnecter en gardant le carnet."],
+ "en-CA" => ["Your dive log on iPhone: profiles, offline editing, dive computer over Bluetooth, optional sync with Subsurface cloud storage, iCloud backup. Independent from the Subsurface team.",
+ "0.7: New: (1) Full iCloud backup: the logbook and the settings are copied to the Sub Rascasse folder of iCloud Drive after each change (one archive per day over a week), on top of the certification cards; photos are not copied. Settings shows the date of the last backup. (2) The Subsurface cloud account becomes optional: the logbook can stay on the iPhone, the iCloud backup can be restored from the welcome screen, an account can be connected later, and signing out can keep the logbook."],
}
_, locs = asc(:get, "/v1/apps/#{app.id}/betaAppLocalizations")
texts.each do |locale, (description, _)|
diff --git a/project.yml b/project.yml
@@ -13,7 +13,7 @@ settings:
base:
DEVELOPMENT_TEAM: CM5RQKJH56
CODE_SIGN_STYLE: Automatic
- MARKETING_VERSION: "0.6"
+ MARKETING_VERSION: "0.7"
CURRENT_PROJECT_VERSION: "1"
SWIFT_VERSION: "5.0"
targets: