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

LogbookBackup.swift (10125B)


      1 // SPDX-License-Identifier: GPL-2.0-only
      2 import CryptoKit
      3 import Foundation
      4 import GitLite
      5 import Observation
      6 import SubsurfaceLog
      7 import UIKit
      8 
      9 /// What a backup holds, readable without opening the archive.
     10 struct LogbookBackupInfo: Codable, Equatable {
     11     var saved: Date
     12     var dives: Int
     13     var sites: Int
     14     /// Subsurface cloud account the logbook belongs to; empty for a logbook kept without an account.
     15     var account: String
     16     var device: String
     17     var appVersion: String
     18 }
     19 
     20 /// Copies the logbook and the settings to the app's iCloud Drive folder, a few seconds after each change:
     21 /// `Logbook/logbook.zip` (the files of the Subsurface git format, as Subsurface stores them), `logbook.json`
     22 /// (what it holds), `settings.plist`, and one archive per day in `history` for the last few days.
     23 @MainActor
     24 @Observable
     25 final class LogbookBackup {
     26     enum State: Equatable {
     27         case unknown
     28         /// This build has no iCloud folder.
     29         case notBuiltIn
     30         /// No iCloud account, or iCloud Drive turned off for the app.
     31         case unavailable
     32         case working
     33         case done(Date)
     34         case failed(String)
     35     }
     36 
     37     private(set) var state = State.unknown
     38     /// The backup found in iCloud, if any (offered on the sign-in screen).
     39     private(set) var available: LogbookBackupInfo?
     40 
     41     @ObservationIgnored private var task: Task<Void, Never>?
     42     nonisolated private static let folderName = "Logbook"
     43     nonisolated private static let hashKey = "backupHash"
     44     nonisolated private static let historyDays = 7
     45     /// Settings that describe this installation, not the user's choices: never copied.
     46     nonisolated static let localOnlyKeys: Set<String> = ["email", "localLogbook", hashKey]
     47 
     48     /// Backs the logbook up shortly: changes that follow each other closely make one backup.
     49     func schedule(repository: LogRepository, account: String) {
     50         guard CloudDrive.isBuiltIn else {
     51             state = .notBuiltIn
     52             return
     53         }
     54         task?.cancel()
     55         task = Task { [weak self] in
     56             try? await Task.sleep(for: .seconds(LaunchOptions.value("-backupFolder") != nil ? 1 : 4))
     57             guard !Task.isCancelled else { return }
     58             await self?.run(repository: repository, account: account)
     59         }
     60     }
     61 
     62     private func run(repository: LogRepository, account: String) async {
     63         guard let files = try? await repository.exportFiles(), let logbook = try? await repository.logbook() else { return }
     64         // An empty logbook never replaces a backup: a fresh installation must not wipe what is in iCloud.
     65         guard !logbook.dives.isEmpty else {
     66             await refresh()
     67             return
     68         }
     69         if state == .unknown || state == .unavailable { state = .working }
     70         let info = LogbookBackupInfo(saved: Date(), dives: logbook.dives.count, sites: logbook.sites.count, account: account,
     71                                      device: UIDevice.current.name, appVersion: Brand.version)
     72         let settings = Self.settingsToSave()
     73         let previousHash = UserDefaults.standard.string(forKey: Self.hashKey)
     74         let outcome = await Task.detached(priority: .utility) {
     75             Self.write(files: files, info: info, settings: settings, previousHash: previousHash)
     76         }.value
     77         switch outcome {
     78         case .unavailable: state = .unavailable
     79         case .failed(let message): state = .failed(message)
     80         case .written(let hash):
     81             UserDefaults.standard.set(hash, forKey: Self.hashKey)
     82             state = .done(info.saved)
     83             available = info
     84         case .unchanged:
     85             await refresh()
     86             if case .done = state {} else { state = .done(available?.saved ?? info.saved) }
     87         }
     88     }
     89 
     90     /// Looks at what iCloud holds.
     91     func refresh() async {
     92         guard CloudDrive.isBuiltIn else {
     93             state = .notBuiltIn
     94             return
     95         }
     96         let found = await Task.detached(priority: .utility) { () -> (reachable: Bool, info: LogbookBackupInfo?) in
     97             guard let folder = CloudDrive.folder(Self.folderName) else { return (false, nil) }
     98             let url = folder.appendingPathComponent("logbook.json")
     99             CloudDrive.download(url)
    100             guard let data = CloudDrive.coordinatedRead(url) else { return (true, nil) }
    101             let decoder = JSONDecoder()
    102             decoder.dateDecodingStrategy = .iso8601
    103             return (true, try? decoder.decode(LogbookBackupInfo.self, from: data))
    104         }.value
    105         available = found.info
    106         if !found.reachable {
    107             state = .unavailable
    108         } else if let info = found.info, state == .unknown || state == .unavailable || state == .working {
    109             state = .done(info.saved)
    110         } else if state == .unavailable {
    111             state = .unknown
    112         }
    113     }
    114 
    115     /// The files of the logbook in iCloud; the settings that this iPhone does not have yet are taken along.
    116     func restore() async throws -> [String: String] {
    117         let result = await Task.detached(priority: .userInitiated) { () -> Result<([String: String], [String: Any]), AppError> in
    118             guard let folder = CloudDrive.folder(Self.folderName) else {
    119                 return .failure(.message(String(localized: "iCloud Drive is not available on this iPhone.")))
    120             }
    121             let url = folder.appendingPathComponent("logbook.zip")
    122             CloudDrive.download(url)
    123             guard let data = CloudDrive.coordinatedRead(url), let archive = try? ZipArchive(Array(data)) else {
    124                 return .failure(.message(String(localized: "The backup in iCloud could not be read. It may still be downloading: try again in a moment.")))
    125             }
    126             var files = [String: String]()
    127             for entry in archive.entries {
    128                 guard let bytes = try? archive.contents(of: entry) else {
    129                     return .failure(.message(String(localized: "The backup in iCloud is damaged.")))
    130                 }
    131                 files[entry.name] = String(decoding: bytes, as: UTF8.self)
    132             }
    133             var settings = [String: Any]()
    134             let settingsURL = folder.appendingPathComponent("settings.plist")
    135             CloudDrive.download(settingsURL)
    136             if let data = CloudDrive.coordinatedRead(settingsURL),
    137                let list = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String: Any] {
    138                 settings = list
    139             }
    140             return .success((files, settings))
    141         }.value
    142         let (files, settings) = try result.get()
    143         guard files["00-Subsurface"] != nil || !files.isEmpty else {
    144             throw AppError.message(String(localized: "The backup in iCloud is empty."))
    145         }
    146         for (key, value) in settings where !Self.localOnlyKeys.contains(key) && UserDefaults.standard.object(forKey: key) == nil {
    147             UserDefaults.standard.set(value, forKey: key)
    148         }
    149         return files
    150     }
    151 
    152     // MARK: Files
    153 
    154     private enum Outcome {
    155         case unavailable
    156         case unchanged
    157         case written(String)
    158         case failed(String)
    159     }
    160 
    161     private static func settingsToSave() -> [String: Any] {
    162         guard let domain = Bundle.main.bundleIdentifier.flatMap({ UserDefaults.standard.persistentDomain(forName: $0) }) else { return [:] }
    163         return domain.filter { key, value in
    164             !localOnlyKeys.contains(key) && !key.hasPrefix("Apple") && !key.hasPrefix("NS") && !key.hasPrefix("com.apple")
    165                 && PropertyListSerialization.propertyList(value, isValidFor: .binary)
    166         }
    167     }
    168 
    169     nonisolated private static func write(files: [String: String], info: LogbookBackupInfo, settings: [String: Any], previousHash: String?) -> Outcome {
    170         guard let folder = CloudDrive.folder(folderName) else { return .unavailable }
    171         let archive = ZipArchive.archive(files.sorted { $0.key < $1.key }.map { ($0.key, Array($0.value.utf8)) })
    172         let hash = SHA256.hash(data: Data(archive)).map { String(format: "%02x", $0) }.joined()
    173         let latest = folder.appendingPathComponent("logbook.zip")
    174         if hash == previousHash, CloudDrive.names(in: folder).contains("logbook.zip") {
    175             writeSettings(settings, in: folder)
    176             return .unchanged
    177         }
    178         CloudDrive.coordinatedWrite(Data(archive), to: latest)
    179         guard CloudDrive.names(in: folder).contains("logbook.zip") else { return .failed(String(localized: "Couldn't write to iCloud Drive.")) }
    180         let encoder = JSONEncoder()
    181         encoder.dateEncodingStrategy = .iso8601
    182         encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
    183         if let data = try? encoder.encode(info) { CloudDrive.coordinatedWrite(data, to: folder.appendingPathComponent("logbook.json")) }
    184         writeSettings(settings, in: folder)
    185 
    186         // One archive per day, the last few days: a mistake made today does not erase yesterday's logbook.
    187         let history = folder.appendingPathComponent("history", isDirectory: true)
    188         try? FileManager.default.createDirectory(at: history, withIntermediateDirectories: true)
    189         let day = DateFormatter()
    190         day.calendar = Calendar(identifier: .gregorian)
    191         day.locale = Locale(identifier: "en_US_POSIX")
    192         day.dateFormat = "yyyy-MM-dd"
    193         CloudDrive.coordinatedWrite(Data(archive), to: history.appendingPathComponent("logbook-\(day.string(from: info.saved)).zip"))
    194         let kept = CloudDrive.names(in: history).filter { $0.hasPrefix("logbook-") && $0.hasSuffix(".zip") }.sorted()
    195         for name in kept.dropLast(historyDays) { CloudDrive.coordinatedRemove(history.appendingPathComponent(name)) }
    196         return .written(hash)
    197     }
    198 
    199     nonisolated private static func writeSettings(_ settings: [String: Any], in folder: URL) {
    200         guard let data = try? PropertyListSerialization.data(fromPropertyList: settings, format: .xml, options: 0) else { return }
    201         let url = folder.appendingPathComponent("settings.plist")
    202         if CloudDrive.coordinatedRead(url) != data { CloudDrive.coordinatedWrite(data, to: url) }
    203     }
    204 }