-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathExposureService.swift
More file actions
353 lines (299 loc) · 13.8 KB
/
ExposureService.swift
File metadata and controls
353 lines (299 loc) · 13.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
//
// ExposureService.swift
// safesafe
//
// Created by Rafał Małczyński on 13/05/2020.
//
import ExposureNotification
import PromiseKit
protocol ExposureServiceDebugProtocol: class {
func detectExposures() -> Promise<Void>
}
@available(iOS 13.5, *)
protocol ExposureServiceProtocol: class {
var isExposureNotificationAuthorized: Bool { get }
var isExposureNotificationEnabled: Bool { get }
func activateManager() -> Promise<ENStatus>
func setExposureNotificationEnabled(_ setEnabled: Bool) -> Promise<Void>
func getDiagnosisKeys() -> Promise<[ENTemporaryExposureKey]>
func detectExposures() -> Promise<[Exposure]>
}
@available(iOS 13.5, *)
final class ExposureService: ExposureServiceProtocol {
enum Constants {
static let exposureInfoFullRangeRiskKey = "totalRiskScoreFullRange"
static let attenuationDurationThresholdsKey = "attenuationDurationThresholds"
}
// MARK: - Properties
private let exposureManager: ENManager
private let diagnosisKeysService: DiagnosisKeysDownloadServiceProtocol
private let configurationService: RemoteConfigProtocol
private let storageService: LocalStorageProtocol?
private var isCurrentlyDetectingExposures = false
var isExposureNotificationAuthorized: Bool {
ENManager.authorizationStatus == .authorized
}
var isExposureNotificationEnabled: Bool {
exposureManager.exposureNotificationEnabled
}
// MARK: - Life Cycle
init(
exposureManager: ENManager,
diagnosisKeysService: DiagnosisKeysDownloadServiceProtocol,
configurationService: RemoteConfigProtocol,
storageService: LocalStorageProtocol?
) {
self.exposureManager = exposureManager
self.diagnosisKeysService = diagnosisKeysService
self.configurationService = configurationService
self.storageService = storageService
if UIDevice.current.model == "iPhone" {
activateManager()
}
}
deinit {
exposureManager.invalidate()
}
// MARK: - Public methods
@discardableResult
func activateManager() -> Promise<ENStatus> {
guard exposureManager.exposureNotificationStatus == .unknown else {
return .value(exposureManager.exposureNotificationStatus)
}
return Promise { [weak self] seal in
guard let self = self else {
return seal.reject(InternalError.deinitialized)
}
self.exposureManager.activate { error in
if let error = error {
seal.reject(error)
} else {
seal.fulfill(self.exposureManager.exposureNotificationStatus)
}
}
}
}
func setExposureNotificationEnabled(_ setEnabled: Bool) -> Promise<Void> {
Promise { [weak self] seal in
self?.exposureManager.setExposureNotificationEnabled(setEnabled) { error in
if let error = error {
seal.reject(error)
} else {
seal.fulfill(())
}
}
}
}
func getDiagnosisKeys() -> Promise<[ENTemporaryExposureKey]> {
Promise { [weak self] seal in
let completion: ENGetDiagnosisKeysHandler = { exposureKeys, error in
if let error = error as? ENError {
switch error.code {
case .notAuthorized:
seal.reject(InternalError.shareKeysUserCanceled)
default:
seal.reject(error)
}
} else {
seal.fulfill(exposureKeys ?? [])
}
}
#if STAGE_DEBUG || DEV
self?.exposureManager.getTestDiagnosisKeys(completionHandler: completion)
#else
self?.exposureManager.getDiagnosisKeys(completionHandler: completion)
#endif
}
}
func detectExposures() -> Promise<[Exposure]> {
Promise { seal in
firstly { when(fulfilled:
makeExposureConfiguration(),
diagnosisKeysService.download()
)}
.then { configuration, keys -> Promise<(summary: ENExposureDetectionSummary, keysCount: Int)> in
if keys.isEmpty {
throw InternalError.detectExposuresNoKeys
} else {
return self.detectExposures(for: configuration, keys: keys)
}
}
.done { summary, numberOfKeys in
self.getExposureInfo(from: summary, numberOfKeys: numberOfKeys)
.done { exposures, riskCheck, analyzeCheck in
ExposureHistoryRiskCheckAgregated.update(with: analyzeCheck)
self.storageService?.append(exposures)
self.storageService?.append(analyzeCheck)
if let riskCheck = riskCheck {
self.storageService?.append(riskCheck)
}
seal.fulfill(exposures)
}
.catch {
seal.reject($0)
}
}
.catch {
seal.reject($0)
}
}
}
// MARK: - Private methods
private func countKeys(keys url: [URL]) -> Promise<(keysCount:Int, urls: [URL])> {
Promise { seal in
let protobufWorker = ProtobufWorker()
seal.fulfill((keysCount: protobufWorker.countAllKeys(urls: url), urls: url))
}
}
private func detectExposures(
for configuration: ENExposureConfiguration,
keys: [URL]
) -> Promise<(summary: ENExposureDetectionSummary, keysCount: Int)> {
return countKeys(keys: keys)
.then { keysCount, urls -> Promise<(summary: ENExposureDetectionSummary, keysCount: Int)> in
return Promise { [weak self] seal in
self?.exposureManager.detectExposures(
configuration: configuration,
diagnosisKeyURLs: keys
) { [weak self] summary, error in
guard let summary = summary, error == nil else {
console(error, type: .error)
seal.reject(error!)
return
}
console("📈 \(summary)", type: .regular)
seal.fulfill((summary: summary, keysCount: keysCount))
self?.diagnosisKeysService.deleteFiles()
}
}
}
}
private func getExposureInfo(
from summary: ENExposureDetectionSummary,
numberOfKeys: Int
) -> Promise<(exposures: [Exposure], riskCheck: ExposureHistoryRiskCheck?, analyzeCheck: ExposureHistoryAnalyzeCheck)> {
Promise { seal in
let userExplanation = "EXPOSURE_INFO_EXPLANATION".localized()
let esposureRisk = ExposureHistoryAnalyzeCheck(matchedKeyCount: Int(summary.matchedKeyCount), keysCount: numberOfKeys)
exposureManager.getExposureInfo(summary: summary, userExplanation: userExplanation) { exposureInfo, error in
guard let info = exposureInfo, error == nil else {
seal.reject(error!)
return
}
var exposures: [Exposure] = []
let riskChecks: [ExposureHistoryRiskCheck]
if info.isEmpty {
riskChecks = [.init(matchedKeyCount: Int(summary.matchedKeyCount), riskLevelFull: .zero)]
} else {
riskChecks = info.compactMap { info -> ExposureHistoryRiskCheck? in
guard let risk = info.metadata?[Constants.exposureInfoFullRangeRiskKey] as? Int else {
return nil
}
return .init(matchedKeyCount: Int(summary.matchedKeyCount), riskLevelFull: risk)
}
exposures = info.compactMap { info -> Exposure? in
guard let risk = info.metadata?[Constants.exposureInfoFullRangeRiskKey] as? Int else {
return nil
}
return .init(risk: risk, duration: info.duration * 60, date: info.date)
}
}
let highestRisk = riskChecks.sorted { $0.riskLevelFull > $1.riskLevelFull }.first
seal.fulfill((exposures: exposures, riskCheck: highestRisk, analyzeCheck: esposureRisk))
}
}
}
private func makeExposureConfiguration() -> Promise<ENExposureConfiguration> {
Promise { seal in
configurationService.configuration()
.done { response in
let configuration = ENExposureConfiguration()
configuration.attenuationLevelValues = response.exposure.attenuationScores.map { NSNumber(integerLiteral: $0) }
configuration.attenuationWeight = Double(response.exposure.attenuationWeigh)
configuration.daysSinceLastExposureLevelValues = response.exposure.daysSinceLastExposureScores.map { NSNumber(integerLiteral: $0) }
configuration.daysSinceLastExposureWeight = Double(response.exposure.daysSinceLastExposureWeight)
configuration.durationLevelValues = response.exposure.durationScores.map { NSNumber(integerLiteral: $0) }
configuration.durationWeight = Double(response.exposure.daysSinceLastExposureWeight)
configuration.transmissionRiskLevelValues = response.exposure.transmissionRiskScores.map { NSNumber(integerLiteral: $0) }
configuration.transmissionRiskWeight = Double(response.exposure.transmissionRiskWeight)
configuration.metadata = [Constants.attenuationDurationThresholdsKey: response.exposure.durationAtAttenuationThresholds]
seal.fulfill(configuration)
}
.recover { _ in
// Default configuration - in case something goes wrong on Firebase side
let configuration = ENExposureConfiguration()
configuration.attenuationLevelValues = [2,5,6,7,8,8,8,8]
configuration.attenuationWeight = 50
configuration.daysSinceLastExposureLevelValues = [7,8,8,8,8,8,8,8]
configuration.daysSinceLastExposureWeight = 50
configuration.durationLevelValues = [0,5,6,7,8,8,8,8]
configuration.durationWeight = 50
configuration.transmissionRiskLevelValues = [8,8,8,8,8,8,8,8]
configuration.transmissionRiskWeight = 50
configuration.metadata = [Constants.attenuationDurationThresholdsKey: [48, 58]]
seal.fulfill(configuration)
}
}
}
}
@available(iOS 13.5, *)
extension ExposureService: ExposureNotificationStatusProtocol {
var status: Promise<ServicesResponse.Status.ExposureNotificationStatus> {
guard UIDevice.current.model == "iPhone" else { return .value(.restricted) }
return activateManager().map {
if ENManager.authorizationStatus != .authorized {
return .off
} else {
switch $0 {
case .active: return .on
case .bluetoothOff, .disabled: return .off
default: return .restricted
}
}
}
}
func isBluetoothOn(delay: TimeInterval) -> Promise<Bool> {
guard UIDevice.current.model == "iPhone" else { return .value(false) }
if delay == .zero {
return activateManager().map { $0 != .bluetoothOff }
}
// Discussion: this is a workaround, because `exposureManager.exposureNotificationStatus` returns `.disabled` on first check
// and a moment later status is updated to `.bluetoothOff` (if BT is off in system settings). So we use short delay to manage this issue.
return after(seconds: delay)
.then { _ -> Promise<ENStatus> in
self.activateManager()
}.map { $0 != .bluetoothOff }
}
}
final class ExposureServiceDebug: ExposureServiceDebugProtocol {
@available(iOS 13.5, *)
static weak var exposureService: ExposureServiceProtocol?
@available(iOS 13.5, *)
func register(exposureService: ExposureServiceProtocol) {
Self.exposureService = exposureService
}
func detectExposures() -> Promise<Void> {
if #available(iOS 13.5, *) {
guard let service = Self.exposureService else {
return .value(())
}
resetLastDownloadTimestamp()
return service.detectExposures().asVoid()
} else {
return .value(())
}
}
private func resetLastDownloadTimestamp() {
let storage = RealmLocalStorage()
storage?.beginWrite()
var model: DiagnosisKeysDownloadInfoModel? = storage?.fetch(primaryKey: DiagnosisKeysDownloadInfoModel.identifier)
if model != nil {
model?.lastPackageTimestamp = 1
} else {
model = DiagnosisKeysDownloadInfoModel()
model?.lastPackageTimestamp = 1
}
storage?.append(model!, policy: .all)
try? storage?.commitWrite()
}
}