-
Notifications
You must be signed in to change notification settings - Fork 355
Expand file tree
/
Copy pathDiskStorage.swift
More file actions
332 lines (280 loc) · 9.56 KB
/
Copy pathDiskStorage.swift
File metadata and controls
332 lines (280 loc) · 9.56 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
import Foundation
/// Save objects to file on disk
final public class DiskStorage<Key: Hashable, Value> {
enum Error: Swift.Error {
case fileEnumeratorFailed
}
/// File manager to read/write to the disk
public let fileManager: FileManager
/// Configuration
private let config: DiskConfig
/// The computed path `directory+name`
public let path: String
/// The closure to be called when single file has been removed
var onRemove: ((String) -> Void)?
private let transformer: Transformer<Value>
private let hasher = Hasher.constantAccrossExecutions()
// MARK: - Initialization
public convenience init(config: DiskConfig, fileManager: FileManager = FileManager.default, transformer: Transformer<Value>) throws {
let url: URL
if let directory = config.directory {
url = directory
} else {
url = try fileManager.url(
for: .cachesDirectory,
in: .userDomainMask,
appropriateFor: nil,
create: true
)
}
// path
let path = url.appendingPathComponent(config.name, isDirectory: true).path
self.init(config: config, fileManager: fileManager, path: path, transformer: transformer)
try createDirectory()
if let protectionType = config.protectionType {
try setDirectoryAttributes([
FileAttributeKey.protectionKey: protectionType
])
}
}
public required init(config: DiskConfig, fileManager: FileManager = FileManager.default, path: String, transformer: Transformer<Value>) {
self.config = config
self.fileManager = fileManager
self.path = path
self.transformer = transformer
}
}
extension DiskStorage: StorageAware {
public var allKeys: [Key] { [] }
public var allObjects: [Value] { [] }
public func entry(forKey key: Key) throws -> Entry<Value> {
let filePath = makeFilePath(for: key)
let data = try Data(contentsOf: URL(fileURLWithPath: filePath, isDirectory: false))
let attributes = try fileManager.attributesOfItem(atPath: filePath)
let object = try transformer.fromData(data)
guard let date = attributes[.modificationDate] as? Date else {
throw StorageError.malformedFileAttributes
}
return Entry(
object: object,
expiry: Expiry.date(date),
filePath: filePath
)
}
public func setObject(_ object: Value, forKey key: Key, expiry: Expiry? = nil) throws {
let expiry = expiry ?? config.expiry
let data = try transformer.toData(object)
let filePath = makeFilePath(for: key)
_ = fileManager.createFile(atPath: filePath, contents: data, attributes: nil)
try fileManager.setAttributes([.modificationDate: expiry.date], ofItemAtPath: filePath)
}
public func removeObject(forKey key: Key) throws {
let filePath = makeFilePath(for: key)
try fileManager.removeItem(atPath: filePath)
onRemove?(filePath)
}
public func removeAll() throws {
try fileManager.removeItem(atPath: path)
try createDirectory()
}
public func removeExpiredObjects() throws {
let storageURL = URL(fileURLWithPath: path, isDirectory: true)
let resourceKeys: [URLResourceKey] = [
.isDirectoryKey,
.contentModificationDateKey,
.totalFileAllocatedSizeKey
]
var resourceObjects = [ResourceObject]()
var filesToDelete = [URL]()
var totalSize: UInt = 0
let fileEnumerator = fileManager.enumerator(
at: storageURL,
includingPropertiesForKeys: resourceKeys,
options: .skipsHiddenFiles,
errorHandler: nil
)
guard let urlArray = fileEnumerator?.allObjects as? [URL] else {
throw Error.fileEnumeratorFailed
}
for url in urlArray {
let resourceValues = try url.resourceValues(forKeys: Set(resourceKeys))
guard resourceValues.isDirectory != true else {
continue
}
if let expiryDate = resourceValues.contentModificationDate, expiryDate.inThePast {
filesToDelete.append(url)
continue
}
if let fileSize = resourceValues.totalFileAllocatedSize {
totalSize += UInt(fileSize)
resourceObjects.append((url: url, resourceValues: resourceValues))
}
}
// Remove expired objects
for url in filesToDelete {
try fileManager.removeItem(at: url)
onRemove?(url.path)
}
// Remove objects if storage size exceeds max size
try removeResourceObjects(resourceObjects, totalSize: totalSize)
}
public func removeExpiredObjects(expiryPeriod: TimeInterval? = nil) throws {
let storageURL = URL(fileURLWithPath: path)
let resourceKeys: [URLResourceKey] = [
.isDirectoryKey,
.contentModificationDateKey,
.contentAccessDateKey,
.totalFileAllocatedSizeKey
]
var resourceObjects = [ResourceObject]()
var filesToDelete = [URL]()
var totalSize: UInt = 0
let fileEnumerator = fileManager.enumerator(
at: storageURL,
includingPropertiesForKeys: resourceKeys,
options: .skipsHiddenFiles,
errorHandler: nil
)
guard let urlArray = fileEnumerator?.allObjects as? [URL] else {
throw Error.fileEnumeratorFailed
}
for url in urlArray {
let resourceValues = try url.resourceValues(forKeys: Set(resourceKeys))
guard resourceValues.isDirectory != true else {
continue
}
if let expiryPeriod = expiryPeriod,
let accessDate = resourceValues.contentAccessDate,
accessDate.addingTimeInterval(expiryPeriod) < Date() {
filesToDelete.append(url)
continue
} else if expiryPeriod == nil,
let expiryDate = resourceValues.contentModificationDate,
expiryDate.inThePast {
filesToDelete.append(url)
continue
}
if let fileSize = resourceValues.totalFileAllocatedSize {
totalSize += UInt(fileSize)
resourceObjects.append((url: url, resourceValues: resourceValues))
}
}
// Remove expired
for url in filesToDelete {
try fileManager.removeItem(at: url)
onRemove?(url.path)
}
// Enforce size limits
try removeResourceObjects(resourceObjects, totalSize: totalSize)
}
public func removeInMemoryObject(forKey key: Key) throws { }
}
extension DiskStorage {
/**
Sets attributes on the disk cache folder.
- Parameter attributes: Directory attributes
*/
func setDirectoryAttributes(_ attributes: [FileAttributeKey: Any]) throws {
try fileManager.setAttributes(attributes, ofItemAtPath: path)
}
}
typealias ResourceObject = (url: Foundation.URL, resourceValues: URLResourceValues)
extension DiskStorage {
/**
Builds file name from the key.
- Parameter key: Unique key to identify the object in the cache
- Returns: A md5 string
*/
func makeFileName(for key: Key) -> String {
if let key = key as? String {
let fileExtension = (key as NSString).pathExtension
let fileName = MD5(key)
switch fileExtension.isEmpty {
case true:
return fileName
case false:
return "\(fileName).\(fileExtension)"
}
}
var hasher = self.hasher
key.hash(into: &hasher)
return String(hasher.finalize())
}
/**
Builds file path from the key.
- Parameter key: Unique key to identify the object in the cache
- Returns: A string path based on key
*/
func makeFilePath(for key: Key) -> String {
return "\(path)/\(makeFileName(for: key))"
}
func createDirectory() throws {
guard !fileManager.fileExists(atPath: path) else {
return
}
try fileManager.createDirectory(atPath: path, withIntermediateDirectories: true,
attributes: nil)
}
/**
Removes objects if storage size exceeds max size.
- Parameter objects: Resource objects to remove
- Parameter totalSize: Total size
*/
func removeResourceObjects(_ objects: [ResourceObject], totalSize: UInt) throws {
guard config.maxSize > 0 && totalSize > config.maxSize else {
return
}
var totalSize = totalSize
let targetSize = config.maxSize / 2
let sortedFiles = objects.sorted {
if let time1 = $0.resourceValues.contentModificationDate?.timeIntervalSinceReferenceDate,
let time2 = $1.resourceValues.contentModificationDate?.timeIntervalSinceReferenceDate {
return time1 < time2
} else {
return false
}
}
for file in sortedFiles {
try fileManager.removeItem(at: file.url)
onRemove?(file.url.path)
if let fileSize = file.resourceValues.totalFileAllocatedSize {
totalSize -= UInt(fileSize)
}
if totalSize < targetSize {
break
}
}
}
/**
Removes the object from the cache if it's expired.
- Parameter key: Unique key to identify the object in the cache
*/
func removeObjectIfExpired(forKey key: Key) throws {
let filePath = makeFilePath(for: key)
let attributes = try fileManager.attributesOfItem(atPath: filePath)
if let expiryDate = attributes[.modificationDate] as? Date, expiryDate.inThePast {
try fileManager.removeItem(atPath: filePath)
onRemove?(filePath)
}
}
}
public extension DiskStorage {
func transform<U>(transformer: Transformer<U>) -> DiskStorage<Key, U> {
let storage = DiskStorage<Key, U>(
config: config,
fileManager: fileManager,
path: path,
transformer: transformer
)
return storage
}
}
public extension DiskStorage {
/// Calculates the total size of the cache directory in bytes.
var totalSize: Int? {
if let directory = URL(string: self.path), let size = self.fileManager.sizeOfDirectory(at: directory) {
return size
}
return nil
}
}