DomainDig/DataResetService.swift

76 lines · 2528 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        let defaults = UserDefaults.standard
51        defaults.removePersistentDomain(forName: bundleIdentifier)
52        defaults.synchronize()
53    }
54
55    private nonisolated static func removeTemporaryFiles() throws {
56        let tempDirectory = FileManager.default.temporaryDirectory
57        let urls = try FileManager.default.contentsOfDirectory(
58            at: tempDirectory,
59            includingPropertiesForKeys: nil,
60            options: [.skipsHiddenFiles]
61        )
62
63        for url in urls {
64            try? FileManager.default.removeItem(at: url)
65        }
66    }
67
68    private nonisolated static func deleteIntegrationSecret(reference: String) {
69        let query: [String: Any] = [
70            kSecClass as String: kSecClassGenericPassword,
71            kSecAttrAccount as String: reference
72        ]
73
74        SecItemDelete(query as CFDictionary)
75    }
76}