-
Notifications
You must be signed in to change notification settings - Fork 24
Expand file tree
/
Copy pathExposureSummaryService.swift
More file actions
99 lines (74 loc) · 2.82 KB
/
ExposureSummaryService.swift
File metadata and controls
99 lines (74 loc) · 2.82 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
//
// ExposureSummaryService.swift
// safesafe
//
// Created by Rafał Małczyński on 24/05/2020.
//
import Foundation
protocol ExposureSummaryServiceProtocol: class {
func getExposureSummary() -> ExposureSummary
func clearExposureSummary() -> ExposureSummary
}
final class ExposureSummaryService: ExposureSummaryServiceProtocol {
private enum Constants {
static let dataExpirationDays = 14.0
static let dataExpirationSeconds = Constants.dataExpirationDays * 86400
}
// MARK: - Properties
private let storageService: LocalStorageProtocol?
private let freeTestService: FreeTestService
// MARK: - Lice Cycle
init(
storageService: LocalStorageProtocol?,
freeTestService: FreeTestService) {
self.storageService = storageService
self.freeTestService = freeTestService
}
// MARK: - Public methods
func getExposureSummary() -> ExposureSummary {
// If there are no exposures by now, return lowest risk
guard let highestRisk = getSanitizedExposures()
.sorted(by: { $0.risk > $1.risk })
.first?
.risk
else {
freeTestService.deleteGUID()
return ExposureSummary(riskLevel: .none)
}
let summary = ExposureSummary(fromFullRangeScore: highestRisk)
if summary.riskLevel != .high {
freeTestService.deleteGUID()
}
return summary
}
func clearExposureSummary() -> ExposureSummary {
guard let allExposures: [Exposure] = storageService?.fetch() else {
return getExposureSummary()
}
storageService?.beginWrite()
storageService?.remove(allExposures, completion: nil)
do {
try storageService?.commitWrite()
return getExposureSummary()
} catch {
console(error, type: .error)
return getExposureSummary()
}
}
// MARK: - Private methods
/// Removes expired data from local storage.
/// Returns exposures sorted by timestamp.
private func getSanitizedExposures() -> [Exposure] {
var exposures: [Exposure] = (storageService?.fetch() ?? []).sorted(by: { $0.date < $1.date })
let expirationBoundary = Date(timeIntervalSince1970: Date().timeIntervalSince1970 - Double(Constants.dataExpirationSeconds))
var expiredExposures = [Exposure]()
while (exposures.first?.date ?? expirationBoundary) < expirationBoundary {
if let exposure = exposures.first {
exposures.removeFirst()
expiredExposures.append(exposure)
}
}
storageService?.remove(expiredExposures, completion: nil)
return exposures
}
}