SPB Git

Repository Public License

SettingsDataCard.swift 10.4 KB 184 lines swift

1// ORIX Alarm2// File: App/Features/Settings/SettingsDataCard.swift3// Description: Data section of Settings: export to a JSON file (share or save), import with replacement confirmation, erase everything with double confirmation.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import AlarmCore8import SwiftUI9import UniformTypeIdentifiers1011/// The exported archive as a document for the system "save to Files" sheet.12nonisolated struct ArchiveDocument: FileDocument {13    static let readableContentTypes: [UTType] = [.json]14    var data: Data15    init(data: Data) { self.data = data }16    init(configuration: ReadConfiguration) throws { data = configuration.file.regularFileContents ?? Data() }17    func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper { FileWrapper(regularFileWithContents: data) }18}1920struct SettingsDataCard: View {21    @Environment(AppModel.self) private var model2223    private struct ReadyExport: Equatable { var url: URL; var data: Data }24    private struct PendingImport: Identifiable { let id = UUID(); var data: Data; var archive: ExportArchive }25    private struct Notice: Identifiable { let id = UUID(); var title: String; var message: String }2627    @State private var export: ReadyExport?28    @State private var showsExporter = false29    @State private var showsImporter = false30    @State private var pendingImport: PendingImport?31    @State private var showsEraseFirst = false32    @State private var showsEraseSecond = false33    @State private var isWorking = false34    @State private var notice: Notice?3536    var body: some View {37        VStack(alignment: .leading, spacing: 12) {38            Overline("Data")39            Text("\(model.alarms.count) alarms, \(model.savedScenarios.count) saved scenarios, \(model.qrTags.count) QR tags and \(model.events.count) history events are stored on this iPhone.")40                .font(.orixCaption).foregroundStyle(Theme.textSecondary)41                .accessibilityIdentifier("settings.data.summary")4243            Button { prepareExport() } label: { Label("Export my data", systemImage: "square.and.arrow.up") }44                .buttonStyle(SecondaryButtonStyle())45                .accessibilityIdentifier("settings.export")46            if let export {47                VStack(alignment: .leading, spacing: 10) {48                    Label("Export file ready", systemImage: "checkmark.circle.fill").font(.orixHeadline).foregroundStyle(Theme.success)49                    Text("\(export.url.lastPathComponent) · \(ByteCountFormatter.string(fromByteCount: Int64(export.data.count), countStyle: .file)). It contains your alarms, scenarios, settings, sleep plan and history in readable JSON. QR tags are stored as digests, never as their content.")50                        .font(.orixCaption).foregroundStyle(Theme.textSecondary)51                    HStack(spacing: 10) {52                        ShareLink(item: export.url) { Label("Share", systemImage: "square.and.arrow.up") }53                            .buttonStyle(SecondaryButtonStyle())54                            .accessibilityIdentifier("settings.export.share")55                        Button { showsExporter = true } label: { Label("Save to Files", systemImage: "folder") }56                            .buttonStyle(SecondaryButtonStyle())57                            .accessibilityIdentifier("settings.export.save")58                            .fileExporter(isPresented: $showsExporter, document: ArchiveDocument(data: export.data), contentType: .json,59                                          defaultFilename: export.url.deletingPathExtension().lastPathComponent) { result in60                                if case .failure(let error) = result { notice = Notice(title: String(localized: "The file could not be saved"), message: error.localizedDescription) }61                            }62                    }63                }64                .padding(14)65                .background(Theme.success.opacity(0.10), in: RoundedRectangle(cornerRadius: 16, style: .continuous))66                .accessibilityIdentifier("settings.export.ready")67            }6869            Button { showsImporter = true } label: { Label("Import a backup", systemImage: "square.and.arrow.down") }70                .buttonStyle(SecondaryButtonStyle())71                .disabled(isWorking)72                .accessibilityIdentifier("settings.import")73                .fileImporter(isPresented: $showsImporter, allowedContentTypes: [.json]) { result in readImport(result) }7475            Button(role: .destructive) { showsEraseFirst = true } label: {76                Label("Erase everything", systemImage: "trash").foregroundStyle(Theme.danger)77            }78            .buttonStyle(SecondaryButtonStyle())79            .disabled(isWorking)80            .accessibilityIdentifier("settings.erase")81            Text("Erasing removes every alarm from iOS and deletes all data of the app on this iPhone.")82                .font(.orixCaption).foregroundStyle(Theme.textSecondary)83        }84        .glassCard()85        // Import: confirm the replacement, showing what the file holds.86        .alert("Replace everything with this backup?", isPresented: Binding(get: { pendingImport != nil }, set: { if !$0 { pendingImport = nil } }), presenting: pendingImport) { pending in87            Button("Replace everything", role: .destructive) { runImport(pending) }.accessibilityIdentifier("settings.import.confirm")88            Button("Cancel", role: .cancel) { pendingImport = nil }89        } message: { pending in90            Text("The backup of \(pending.archive.exportedAt.formatted(date: .abbreviated, time: .shortened)) holds \(pending.archive.library.alarms.count) alarms and \(pending.archive.history.events.count) history events. Your current alarms, settings and history (\(model.alarms.count) alarms, \(model.events.count) events) will be deleted and replaced. This cannot be undone.")91        }92        // Erase: two separate confirmations.93        .confirmationDialog("Erase all alarms, scenarios, QR tags, settings and history?", isPresented: $showsEraseFirst, titleVisibility: .visible) {94            Button("Erase everything…", role: .destructive) { showsEraseSecond = true }.accessibilityIdentifier("settings.erase.first")95            Button("Cancel", role: .cancel) {}96        } message: {97            Text("Consider exporting your data first.")98        }99        .alert("Erase everything for good?", isPresented: $showsEraseSecond) {100            Button("Erase", role: .destructive) { runErase() }.accessibilityIdentifier("settings.erase.confirm")101            Button("Keep my data", role: .cancel) {}102        } message: {103            Text("\(model.alarms.count) alarms and \(model.events.count) history events will be deleted. No alarm will ring afterwards. This cannot be undone.")104        }105        .alert(notice?.title ?? "", isPresented: Binding(get: { notice != nil }, set: { if !$0 { notice = nil } })) {106            Button("OK") { notice = nil }107        } message: {108            Text(notice?.message ?? "")109        }110    }111112    // MARK: Export113    private func prepareExport() {114        do {115            let data = try model.exportArchive()116            let day = model.calendar.dateComponents([.year, .month, .day], from: model.now())   // local date, not UTC117            let stamp = String(format: "%04d-%02d-%02d", day.year ?? 0, day.month ?? 0, day.day ?? 0)118            let directory = FileManager.default.temporaryDirectory.appendingPathComponent("ORIXAlarmExport", isDirectory: true)119            try? FileManager.default.removeItem(at: directory)       // only the latest export is kept in the temporary folder120            try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)121            let url = directory.appendingPathComponent("orix-alarm-export-\(stamp).json")122            try data.write(to: url, options: [.atomic, .completeFileProtection])123            export = ReadyExport(url: url, data: data)124            Haptics.play(.success)125        } catch {126            export = nil127            notice = Notice(title: String(localized: "Export failed"), message: error.localizedDescription)128            Haptics.play(.failure)129        }130    }131132    // MARK: Import133    private func readImport(_ result: Result<URL, Error>) {134        do {135            let url = try result.get()136            let scoped = url.startAccessingSecurityScopedResource()137            defer { if scoped { url.stopAccessingSecurityScopedResource() } }138            let data = try Data(contentsOf: url)139            // Decode before asking: a file that is not an ORIX Alarm export never reaches the confirmation.140            let archive = try ExportArchive.decode(data)141            pendingImport = PendingImport(data: data, archive: archive)142        } catch let error as CocoaError where error.code == .userCancelled {143            return144        } catch {145            notice = Notice(title: String(localized: "This file cannot be imported"),146                            message: String(localized: "It is not a valid ORIX Alarm export, or it could not be read. Nothing was changed.") + "\n\n" + error.localizedDescription)147            Haptics.play(.failure)148        }149    }150151    private func runImport(_ pending: PendingImport) {152        pendingImport = nil153        isWorking = true154        Task {155            do {156                try await model.importArchive(pending.data)157                SoundFX.isEnabled = model.settings.soundEffectsEnabled158                Haptics.isEnabled = model.settings.hapticsEnabled159                await SleepReminders.sync(plan: model.sleepPlan)160                export = nil161                notice = Notice(title: String(localized: "Backup imported"),162                                message: String(localized: "\(model.alarms.count) alarms were restored and registered again with iOS. Use “Check alarms now” to verify them."))163                Haptics.play(.success)164            } catch {165                notice = Notice(title: String(localized: "Import failed"), message: String(localized: "Nothing was changed.") + "\n\n" + error.localizedDescription)166                Haptics.play(.failure)167            }168            isWorking = false169        }170    }171172    // MARK: Erase173    private func runErase() {174        isWorking = true175        Task {176            await model.eraseEverything()177            SoundFX.isEnabled = model.settings.soundEffectsEnabled178            export = nil179            isWorking = false180            notice = Notice(title: String(localized: "Everything was erased"), message: String(localized: "All alarms were removed from iOS and the app's data was deleted."))181        }182    }183}184
Files main
Menu

Theme