← All repositories

reportage

A life-logging app for iPhone

git clone https://code.inqk.net/reportage.git


Reportage/Views/Settings/DataSection.swift (13166B)

1import CoreTransferable
2import OSLog
3import SwiftUI
4import UniformTypeIdentifiers
5
6/// Importing a Reporter or Reportage export, exporting the store as JSON, improving
7/// earlier reports on the Historical Data screen, and deleting everything.
8struct DataSection: View {
9    @Environment(\.reportStore) private var store
10    @Environment(HealthFiller.self) private var healthFiller: HealthFiller?
11    @Environment(AddressUpdater.self) private var addressUpdater: AddressUpdater?
12    @State private var task: DataTask?
13    @State private var isChoosingImport = false
14    @State private var exported: ExportFile?
15    @State private var outcome: Outcome?
16    @State private var isConfirmingDelete = false
17
18    private enum DataTask {
19        case importing
20        case exporting
21        case deleting
22    }
23
24    /// What's shown in an alert once a task finishes.
25    private struct Outcome {
26        let title: LocalizedStringKey
27        let message: String
28    }
29
30    var body: some View {
31        Section {
32            Button {
33                isChoosingImport = true
34            } label: {
35                TaskLabel("Import Reports", isRunning: task == .importing)
36            }
37            .disabled(task != nil || store == nil || addressUpdater?.isUpdating == true)
38            .settingsRow()
39            Button {
40                Task { await export() }
41            } label: {
42                TaskLabel("Export Reports", isRunning: task == .exporting)
43            }
44            .disabled(task != nil || store == nil)
45            .settingsRow()
46            NavigationLink {
47                HistoricalDataView(isBlocked: task == .importing || task == .deleting)
48            } label: {
49                LabeledContent("Historical Data") {
50                    if healthFiller?.isFillingPast == true || addressUpdater?.isUpdating == true {
51                        ProgressView()
52                    }
53                }
54            }
55            .settingsRow()
56            Button(role: .destructive) {
57                isConfirmingDelete = true
58            } label: {
59                TaskLabel("Delete All Data", isRunning: task == .deleting)
60            }
61            .disabled(
62                task != nil || store == nil || healthFiller?.isFillingPast == true
63                    || addressUpdater?.isUpdating == true)
64            .settingsRow()
65        } header: {
66            SettingsHeading("Data")
67        }
68        .fileImporter(isPresented: $isChoosingImport, allowedContentTypes: [.json]) { result in
69            switch result {
70            case .success(let url):
71                Task { await importArchive(at: url) }
72            case .failure(let error):
73                outcome = Outcome(title: "Couldn't Import", message: error.localizedDescription)
74            }
75        }
76        .fileExporter(
77            isPresented: isSavingExport,
78            item: exported,
79            contentTypes: [.json],
80            defaultFilename: exported?.url.lastPathComponent
81        ) { result in
82            if case .failure(let error) = result {
83                outcome = Outcome(title: "Couldn't Export", message: error.localizedDescription)
84            }
85            finishExport()
86        } onCancellation: {
87            finishExport()
88        }
89        .alert("Delete All Data?", isPresented: $isConfirmingDelete) {
90            Button("Cancel", role: .cancel) {}
91            Button("Delete All Data", role: .destructive) {
92                Task { await deleteAll() }
93            }
94        } message: {
95            Text("Every report, question, place and person in Reportage will be deleted. This can't be undone, so export first to keep a copy.")
96        }
97        .alert(outcome?.title ?? "", isPresented: isShowingOutcome, presenting: outcome) { _ in
98            Button("OK") {}
99        } message: { outcome in
100            Text(outcome.message)
101        }
102    }
103
104    private var isShowingOutcome: Binding<Bool> {
105        Binding(
106            get: { outcome != nil },
107            set: { if !$0 { outcome = nil } })
108    }
109
110    private var isSavingExport: Binding<Bool> {
111        Binding(
112            get: { exported != nil },
113            set: { if !$0 { finishExport() } })
114    }
115
116    private func importArchive(at url: URL) async {
117        guard let store else { return }
118        task = .importing
119        defer { task = nil }
120        let isScoped = url.startAccessingSecurityScopedResource()
121        defer { if isScoped { url.stopAccessingSecurityScopedResource() } }
122        do {
123            let message = try await Self.importArchive(at: url, persistence: store.persistence)
124            outcome = Outcome(title: "Import Finished", message: message)
125        } catch {
126            Self.logger.error("Couldn't import: \(error)")
127            outcome = Outcome(title: "Couldn't Import", message: error.localizedDescription)
128        }
129        // Imported questions and vocabulary change how reports read.
130        NotificationCenter.default.post(name: .summaryLookupChanged, object: nil)
131    }
132
133    /// Imports either kind of export, telling them apart by their contents,
134    /// and returns what to tell the user.
135    @concurrent
136    private static func importArchive(
137        at url: URL,
138        persistence: PersistenceController
139    ) async throws -> String {
140        let data = try Data(contentsOf: url, options: .mappedIfSafe)
141        switch try ArchiveFormat(data: data) {
142        case .reporter:
143            let summary = try await ReporterImporter(persistence: persistence).importArchive(data)
144            log(summary)
145            return message(for: summary)
146        case .reportage:
147            let summary = try await ReportageImporter(persistence: persistence).importArchive(data)
148            log(summary)
149            return message(for: summary)
150        }
151    }
152
153    private func export() async {
154        guard let store else { return }
155        task = .exporting
156        defer { task = nil }
157        let date = Date().formatted(.iso8601.year().month().day())
158        let url = URL.temporaryDirectory.appending(path: "Reportage \(date).json")
159        do {
160            let summary = try await ReportageExporter(persistence: store.persistence)
161                .export(to: url)
162            Self.logger.info("Exported \(summary.reports) reports, \(summary.questions) questions, \(summary.tokens) tokens")
163            exported = ExportFile(url: url)
164        } catch {
165            Self.logger.error("Couldn't export: \(error)")
166            outcome = Outcome(title: "Couldn't Export", message: error.localizedDescription)
167        }
168    }
169
170    private func deleteAll() async {
171        guard let store else { return }
172        task = .deleting
173        defer { task = nil }
174        do {
175            try await store.deleteAll()
176            try await store.seedDefaultQuestionsIfNeeded()
177            Self.logger.info("Deleted all data")
178        } catch {
179            Self.logger.error("Couldn't delete all data: \(error)")
180            outcome = Outcome(title: "Couldn't Delete", message: error.localizedDescription)
181        }
182    }
183
184    /// Removes the temporary copy once it's been saved or the save cancelled.
185    private func finishExport() {
186        guard let exported else { return }
187        try? FileManager.default.removeItem(at: exported.url)
188        self.exported = nil
189    }
190
191    nonisolated private static let logger = Logger(subsystem: "net.inqk.reportage", category: "Data")
192
193    /// Counts and fallbacks only: IDs, never the contents of reports.
194    nonisolated private static func log(_ summary: ReporterImportSummary) {
195        logger.info(
196            """
197            Imported \(summary.reportsInserted) reports (\(summary.reportsAlreadyPresent) already present), \
198            \(summary.questionsInserted) questions (\(summary.questionsUpdated) updated, \
199            \(summary.defaultQuestionsArchived) defaults archived), \
200            \(summary.tokensInserted) tokens (\(summary.tokensAlreadyPresent) already present); \
201            \(summary.fallbacks.count) fallbacks, \(summary.failures.count) failures
202            """)
203        for warning in summary.warnings {
204            Self.logger.notice("Import warning: \(warning)")
205        }
206        for failure in summary.failures {
207            Self.logger.error("Snapshot \(failure.index) (\(failure.reportID ?? "no ID")) failed: \(failure.message)")
208        }
209    }
210
211    nonisolated static func message(for summary: ReporterImportSummary) -> String {
212        var lines: [String] = []
213        if summary.reportsInserted == 0 {
214            lines.append(String(localized: "No new reports. Everything in this export was already imported."))
215        } else {
216            lines.append(
217                inflected(
218                    "Added ^[\(summary.reportsInserted) report](inflect: true) and ^[\(summary.questionsInserted) question](inflect: true)."
219                ))
220        }
221        if summary.reportsAlreadyPresent > 0 {
222            lines.append(inflected("^[\(summary.reportsAlreadyPresent) report](inflect: true) had already been imported."))
223        }
224        if summary.defaultQuestionsArchived > 0 {
225            lines.append(String(localized: "The surveys now ask Reporter's questions instead of the default ones."))
226        }
227        if !summary.failures.isEmpty {
228            lines.append(inflected("Skipped ^[\(summary.failures.count) report](inflect: true) that couldn't be read."))
229        }
230        return lines.joined(separator: "\n\n")
231    }
232
233    /// Counts only, never the contents of reports.
234    nonisolated private static func log(_ summary: ReportageImportSummary) {
235        func counts(_ counts: ReportageImportSummary.Counts) -> String {
236            "\(counts.inserted) added, \(counts.updated) updated, \(counts.unchanged) unchanged"
237        }
238        logger.info(
239            """
240            Imported a Reportage export: reports \(counts(summary.reports)); \
241            questions \(counts(summary.questions)); tokens \(counts(summary.tokens)); \
242            \(summary.failures.count) failures
243            """)
244        for failure in summary.failures {
245            Self.logger.error("Report \(failure.index) failed: \(failure.message)")
246        }
247    }
248
249    nonisolated static func message(for summary: ReportageImportSummary) -> String {
250        var lines: [String] = []
251        let reports = summary.reports
252        if reports.changed == 0 && summary.questions.changed == 0 && summary.tokens.changed == 0 {
253            lines.append(String(localized: "No changes. Everything in this export is already in Reportage."))
254        } else {
255            if reports.inserted > 0 {
256                lines.append(inflected("Added ^[\(reports.inserted) report](inflect: true)."))
257            }
258            if reports.updated > 0 {
259                lines.append(
260                    inflected("Updated ^[\(reports.updated) report](inflect: true) with a newer version from the export."))
261            }
262            let questions = summary.questions.changed
263            let names = summary.tokens.changed
264            if questions > 0 && names > 0 {
265                lines.append(
266                    inflected(
267                        "Added or updated ^[\(questions) question](inflect: true) and ^[\(names) name](inflect: true)."
268                    ))
269            } else if questions > 0 {
270                lines.append(inflected("Added or updated ^[\(questions) question](inflect: true)."))
271            } else if names > 0 {
272                lines.append(inflected("Added or updated ^[\(names) name](inflect: true)."))
273            }
274            if reports.unchanged > 0 {
275                lines.append(inflected("^[\(reports.unchanged) report](inflect: true) had no newer changes."))
276            }
277        }
278        if !summary.failures.isEmpty {
279            lines.append(inflected("Skipped ^[\(summary.failures.count) report](inflect: true) that couldn't be read."))
280        }
281        return lines.joined(separator: "\n\n")
282    }
283
284    /// `resource` with its counted words inflected. A plain `String` keeps
285    /// the inflection markup as written; an attributed string applies it.
286    nonisolated private static func inflected(_ resource: String.LocalizationValue) -> String {
287        String(AttributedString(localized: resource).characters)
288    }
289}
290
291/// A button's title, with a spinner while its task runs.
292struct TaskLabel: View {
293    let title: LocalizedStringKey
294    let isRunning: Bool
295
296    init(_ title: LocalizedStringKey, isRunning: Bool) {
297        self.title = title
298        self.isRunning = isRunning
299    }
300
301    var body: some View {
302        HStack {
303            Text(title)
304            Spacer()
305            if isRunning {
306                ProgressView()
307            }
308        }
309        .contentShape(.rect)
310    }
311}
312
313/// A finished export, waiting to be saved.
314private struct ExportFile: Transferable {
315    let url: URL
316
317    static var transferRepresentation: some TransferRepresentation {
318        FileRepresentation(exportedContentType: .json) { file in
319            SentTransferredFile(file.url)
320        }
321        // Without a name, the file exporter crashes setting the empty name
322        // on the file it saves.
323        .suggestedFileName { $0.url.lastPathComponent }
324    }
325}