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
import Foundation
struct AvatarCachePolicy {
let expires: Date
let allowsStorage: Bool
private let requiresValidation: Bool
private let requiresFreshness: Bool
var allowsDisplayWhileValidating: Bool {
allowsStorage && !requiresValidation && (!requiresFreshness || expires > Date())
}
init(response: HTTPURLResponse, now: Date = Date()) {
let directives = (response.value(forHTTPHeaderField: "Cache-Control") ?? "")
.lowercased().split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }
allowsStorage = !directives.contains("no-store")
&& !(response.value(forHTTPHeaderField: "Vary") ?? "").contains("*")
requiresValidation = directives.contains { $0 == "no-cache" || $0.hasPrefix("no-cache=") }
requiresFreshness = directives.contains("must-revalidate")
guard allowsStorage, !requiresValidation else {
expires = .distantPast
return
}
let age = max(0, Double(response.value(forHTTPHeaderField: "Age") ?? "") ?? 0)
let serverDate = Self.date(response.value(forHTTPHeaderField: "Date"))
let currentAge = max(age, serverDate.map { max(0, now.timeIntervalSince($0)) } ?? 0)
if let directive = directives.first(where: { $0.hasPrefix("max-age=") }),
let lifetime = Double(directive.dropFirst(8).trimmingCharacters(in: CharacterSet(charactersIn: "\""))),
lifetime.isFinite {
expires = now.addingTimeInterval(max(0, lifetime - currentAge))
} else if let expiration = Self.date(response.value(forHTTPHeaderField: "Expires")) {
expires = now.addingTimeInterval(max(0, expiration.timeIntervalSince(serverDate ?? now) - currentAge))
} else {
// Let URLSession handle validation and heuristic freshness when no lifetime is supplied.
expires = .distantPast
}
}
private static func date(_ value: String?) -> Date? {
guard let value else { return nil }
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss zzz"
return formatter.date(from: value)
}
}