DomainDig/DataResetService.swift
82 lines · 2860 bytes
1import Foundation
2import Security
3
4enum DataResetService {
5 enum ResetError: LocalizedError {
6 case missingBundleIdentifier
7
8 var errorDescription: String? {
9 switch self {
10 case .missingBundleIdentifier:
11 "DomainDig could not determine its local storage identifier."
12 }
13 }
14 }
15
16 static func wipeAllLocalData(viewModel: DomainViewModel) async throws {
17 let secretReferences = await MainActor.run {
18 IntegrationService.shared.localSecretReferences() + LocalAPIService.shared.localSecretReferences()
19 }
20
21 try await Task.detached(priority: .userInitiated) {
22 try performPersistentWipe(secretReferences: secretReferences)
23 }.value
24
25 await LookupRuntime.shared.clearCache()
26 await LocalNotificationService.shared.clearAllNotifications()
27
28 await MainActor.run {
29 IntegrationService.shared.resetAfterLocalWipe()
30 LocalAPIService.shared.resetAfterLocalWipe()
31 CloudSyncService.shared.resetLocalStateAfterWipe()
32 PurchaseService.shared.resetCachedStateAfterLocalWipe()
33 _ = DomainMonitoringScheduler.shared.syncSchedule()
34 }
35
36 await viewModel.applyLocalDataReset()
37 }
38
39 private nonisolated static func performPersistentWipe(secretReferences: [String]) throws {
40 guard let bundleIdentifier = Bundle.main.bundleIdentifier else {
41 throw ResetError.missingBundleIdentifier
42 }
43
44 for reference in secretReferences {
45 deleteIntegrationSecret(reference: reference)
46 }
47
48 try removeTemporaryFiles()
49
50 // History is a directory in Application Support since the v2 store
51 // migration, so clearing the `UserDefaults` domain no longer reaches
52 // it. A reset that left it behind would leave the user's snapshots on
53 // the device after they asked for everything to go.
54 HistoryFileStore.removeAll()
55
56 let defaults = UserDefaults.standard
57 defaults.removePersistentDomain(forName: bundleIdentifier)
58 defaults.synchronize()
59 }
60
61 private nonisolated static func removeTemporaryFiles() throws {
62 let tempDirectory = FileManager.default.temporaryDirectory
63 let urls = try FileManager.default.contentsOfDirectory(
64 at: tempDirectory,
65 includingPropertiesForKeys: nil,
66 options: [.skipsHiddenFiles]
67 )
68
69 for url in urls {
70 try? FileManager.default.removeItem(at: url)
71 }
72 }
73
74 private nonisolated static func deleteIntegrationSecret(reference: String) {
75 let query: [String: Any] = [
76 kSecClass as String: kSecClassGenericPassword,
77 kSecAttrAccount as String: reference
78 ]
79
80 SecItemDelete(query as CFDictionary)
81 }
82}