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
import Foundation
import ImageIO
import UIKit
@MainActor
final class AvatarStore {
nonisolated static let maximumImageBytes = 5 * 1024 * 1024
final class Entry {
let image: UIImage
let ringColors: AvatarRingColors
let policy: AvatarCachePolicy
init(image: UIImage, policy: AvatarCachePolicy) {
self.image = image
self.ringColors = image.cgImage.map(AvatarRingColors.calculate) ?? .fallback
self.policy = policy
}
}
private let cache = NSCache<NSURL, Entry>()
private let session: URLSession
private var requests: [URL: (UUID, Task<Entry?, Never>)] = [:]
private var generation = UUID()
init(
session: URLSession = {
let configuration = URLSessionConfiguration.ephemeral
configuration.urlCache = URLCache(memoryCapacity: 32 * 1024 * 1024, diskCapacity: 0)
configuration.requestCachePolicy = .useProtocolCachePolicy
return URLSession(configuration: configuration)
}()
) {
self.session = session
cache.totalCostLimit = 200 * 1024 * 1024
cache.countLimit = 10_000
}
func cachedImage(for url: URL) -> UIImage? {
cachedAvatar(for: url)?.image
}
func cachedAvatar(for url: URL) -> Entry? {
let url = AvatarImageURL.thumbnail(url)
guard let entry = cache.object(forKey: url as NSURL) else { return nil }
guard entry.policy.expires > Date() else {
cache.removeObject(forKey: url as NSURL)
return nil
}
return entry
}
func image(for url: URL) async -> UIImage? {
await avatar(for: url)?.image
}
func avatar(for url: URL) async -> Entry? {
let url = AvatarImageURL.thumbnail(url)
if let entry = cachedAvatar(for: url) { return entry }
let currentGeneration = generation
if let request = requests[url] {
let image = await request.1.value
return generation == currentGeneration ? image : nil
}
let id = UUID()
let session = session
let task = Task.detached { () -> Entry? in
do {
let (data, response) = try await session.data(from: url)
guard let response = response as? HTTPURLResponse, (200..<300).contains(response.statusCode),
data.count <= Self.maximumImageBytes
else { return nil }
guard let image = Self.decode(data) else { return nil }
return Entry(image: image, policy: AvatarCachePolicy(response: response))
} catch {
return nil
}
}
requests[url] = (id, task)
let image = await task.value
guard generation == currentGeneration else { return nil }
if requests[url]?.0 == id {
requests[url] = nil
if let image, image.policy.allowsStorage, image.policy.expires > Date() {
let cost = (image.image.cgImage.map { $0.bytesPerRow * $0.height }) ?? 0
cache.setObject(image, forKey: url as NSURL, cost: cost)
}
}
return generation == currentGeneration ? image : nil
}
nonisolated static func decode(_ data: Data, maximumPixelSize: Int = 256) -> UIImage? {
guard let source = CGImageSourceCreateWithData(data as CFData, nil) else { return nil }
let options: [CFString: Any] = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceThumbnailMaxPixelSize: maximumPixelSize,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceShouldCacheImmediately: true
]
guard let image = CGImageSourceCreateThumbnailAtIndex(source, 0, options as CFDictionary) else { return nil }
return UIImage(cgImage: image)
}
func clear() {
generation = UUID()
for request in requests.values { request.1.cancel() }
requests.removeAll()
cache.removeAllObjects()
session.configuration.urlCache?.removeAllCachedResponses()
}
}