DiskStorage.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493
  1. //
  2. // DiskStorage.swift
  3. // Kingfisher
  4. //
  5. // Created by Wei Wang on 2018/10/15.
  6. //
  7. // Copyright (c) 2019 Wei Wang <onevcat@gmail.com>
  8. //
  9. // Permission is hereby granted, free of charge, to any person obtaining a copy
  10. // of this software and associated documentation files (the "Software"), to deal
  11. // in the Software without restriction, including without limitation the rights
  12. // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  13. // copies of the Software, and to permit persons to whom the Software is
  14. // furnished to do so, subject to the following conditions:
  15. //
  16. // The above copyright notice and this permission notice shall be included in
  17. // all copies or substantial portions of the Software.
  18. //
  19. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  20. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  21. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  22. // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  23. // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  24. // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  25. // THE SOFTWARE.
  26. import Foundation
  27. /// Represents a set of conception related to storage which stores a certain type of value in disk.
  28. /// This is a namespace for the disk storage types. A `Backend` with a certain `Config` will be used to describe the
  29. /// storage. See these composed types for more information.
  30. public enum DiskStorage {
  31. /// Represents a storage back-end for the `DiskStorage`. The value is serialized to data
  32. /// and stored as file in the file system under a specified location.
  33. ///
  34. /// You can config a `DiskStorage.Backend` in its initializer by passing a `DiskStorage.Config` value.
  35. /// or modifying the `config` property after it being created. `DiskStorage` will use file's attributes to keep
  36. /// track of a file for its expiration or size limitation.
  37. public class Backend<T: DataTransformable> {
  38. /// The config used for this disk storage.
  39. public var config: Config
  40. // The final storage URL on disk, with `name` and `cachePathBlock` considered.
  41. public let directoryURL: URL
  42. let metaChangingQueue: DispatchQueue
  43. var maybeCached : Set<String>?
  44. let maybeCachedCheckingQueue = DispatchQueue(label: "com.onevcat.Kingfisher.maybeCachedCheckingQueue")
  45. /// Creates a disk storage with the given `DiskStorage.Config`.
  46. ///
  47. /// - Parameter config: The config used for this disk storage.
  48. /// - Throws: An error if the folder for storage cannot be got or created.
  49. public init(config: Config) throws {
  50. self.config = config
  51. let url: URL
  52. if let directory = config.directory {
  53. url = directory
  54. } else {
  55. url = try config.fileManager.url(
  56. for: .cachesDirectory,
  57. in: .userDomainMask,
  58. appropriateFor: nil,
  59. create: true)
  60. }
  61. let cacheName = "com.onevcat.Kingfisher.ImageCache.\(config.name)"
  62. directoryURL = config.cachePathBlock(url, cacheName)
  63. metaChangingQueue = DispatchQueue(label: cacheName)
  64. try prepareDirectory()
  65. maybeCachedCheckingQueue.async {
  66. do {
  67. self.maybeCached = Set()
  68. try config.fileManager.contentsOfDirectory(atPath: self.directoryURL.path).forEach { fileName in
  69. self.maybeCached?.insert(fileName)
  70. }
  71. } catch {
  72. // Just disable the functionality if we fail to initialize it properly. This will just revert to
  73. // the behavior which is to check file existence on disk directly.
  74. self.maybeCached = nil
  75. }
  76. }
  77. }
  78. // Creates the storage folder.
  79. func prepareDirectory() throws {
  80. let fileManager = config.fileManager
  81. let path = directoryURL.path
  82. guard !fileManager.fileExists(atPath: path) else { return }
  83. do {
  84. try fileManager.createDirectory(
  85. atPath: path,
  86. withIntermediateDirectories: true,
  87. attributes: nil)
  88. } catch {
  89. throw KingfisherError.cacheError(reason: .cannotCreateDirectory(path: path, error: error))
  90. }
  91. }
  92. func store(
  93. value: T,
  94. forKey key: String,
  95. expiration: StorageExpiration? = nil) throws
  96. {
  97. let expiration = expiration ?? config.expiration
  98. // The expiration indicates that already expired, no need to store.
  99. guard !expiration.isExpired else { return }
  100. let data: Data
  101. do {
  102. data = try value.toData()
  103. } catch {
  104. throw KingfisherError.cacheError(reason: .cannotConvertToData(object: value, error: error))
  105. }
  106. let fileURL = cacheFileURL(forKey: key)
  107. do {
  108. try data.write(to: fileURL)
  109. } catch {
  110. throw KingfisherError.cacheError(
  111. reason: .cannotCreateCacheFile(fileURL: fileURL, key: key, data: data, error: error)
  112. )
  113. }
  114. let now = Date()
  115. let attributes: [FileAttributeKey : Any] = [
  116. // The last access date.
  117. .creationDate: now.fileAttributeDate,
  118. // The estimated expiration date.
  119. .modificationDate: expiration.estimatedExpirationSinceNow.fileAttributeDate
  120. ]
  121. do {
  122. try config.fileManager.setAttributes(attributes, ofItemAtPath: fileURL.path)
  123. } catch {
  124. try? config.fileManager.removeItem(at: fileURL)
  125. throw KingfisherError.cacheError(
  126. reason: .cannotSetCacheFileAttribute(
  127. filePath: fileURL.path,
  128. attributes: attributes,
  129. error: error
  130. )
  131. )
  132. }
  133. maybeCachedCheckingQueue.async {
  134. self.maybeCached?.insert(fileURL.lastPathComponent)
  135. }
  136. }
  137. func value(forKey key: String, extendingExpiration: ExpirationExtending = .cacheTime) throws -> T? {
  138. return try value(forKey: key, referenceDate: Date(), actuallyLoad: true, extendingExpiration: extendingExpiration)
  139. }
  140. func value(
  141. forKey key: String,
  142. referenceDate: Date,
  143. actuallyLoad: Bool,
  144. extendingExpiration: ExpirationExtending) throws -> T?
  145. {
  146. let fileManager = config.fileManager
  147. let fileURL = cacheFileURL(forKey: key)
  148. let filePath = fileURL.path
  149. let fileMaybeCached = maybeCachedCheckingQueue.sync {
  150. return maybeCached?.contains(fileURL.lastPathComponent) ?? true
  151. }
  152. guard fileMaybeCached else {
  153. return nil
  154. }
  155. guard fileManager.fileExists(atPath: filePath) else {
  156. return nil
  157. }
  158. let meta: FileMeta
  159. do {
  160. let resourceKeys: Set<URLResourceKey> = [.contentModificationDateKey, .creationDateKey]
  161. meta = try FileMeta(fileURL: fileURL, resourceKeys: resourceKeys)
  162. } catch {
  163. throw KingfisherError.cacheError(
  164. reason: .invalidURLResource(error: error, key: key, url: fileURL))
  165. }
  166. if meta.expired(referenceDate: referenceDate) {
  167. return nil
  168. }
  169. if !actuallyLoad { return T.empty }
  170. do {
  171. let data = try Data(contentsOf: fileURL)
  172. let obj = try T.fromData(data)
  173. metaChangingQueue.async {
  174. meta.extendExpiration(with: fileManager, extendingExpiration: extendingExpiration)
  175. }
  176. return obj
  177. } catch {
  178. throw KingfisherError.cacheError(reason: .cannotLoadDataFromDisk(url: fileURL, error: error))
  179. }
  180. }
  181. func isCached(forKey key: String) -> Bool {
  182. return isCached(forKey: key, referenceDate: Date())
  183. }
  184. func isCached(forKey key: String, referenceDate: Date) -> Bool {
  185. do {
  186. let result = try value(
  187. forKey: key,
  188. referenceDate: referenceDate,
  189. actuallyLoad: false,
  190. extendingExpiration: .none
  191. )
  192. return result != nil
  193. } catch {
  194. return false
  195. }
  196. }
  197. func remove(forKey key: String) throws {
  198. let fileURL = cacheFileURL(forKey: key)
  199. try removeFile(at: fileURL)
  200. }
  201. func removeFile(at url: URL) throws {
  202. try config.fileManager.removeItem(at: url)
  203. }
  204. func removeAll() throws {
  205. try removeAll(skipCreatingDirectory: false)
  206. }
  207. func removeAll(skipCreatingDirectory: Bool) throws {
  208. try config.fileManager.removeItem(at: directoryURL)
  209. if !skipCreatingDirectory {
  210. try prepareDirectory()
  211. }
  212. }
  213. /// The URL of the cached file with a given computed `key`.
  214. ///
  215. /// - Note:
  216. /// This method does not guarantee there is an image already cached in the returned URL. It just gives your
  217. /// the URL that the image should be if it exists in disk storage, with the give key.
  218. ///
  219. /// - Parameter key: The final computed key used when caching the image. Please note that usually this is not
  220. /// the `cacheKey` of an image `Source`. It is the computed key with processor identifier considered.
  221. public func cacheFileURL(forKey key: String) -> URL {
  222. let fileName = cacheFileName(forKey: key)
  223. return directoryURL.appendingPathComponent(fileName, isDirectory: false)
  224. }
  225. func cacheFileName(forKey key: String) -> String {
  226. if config.usesHashedFileName {
  227. let hashedKey = key.kf.md5
  228. if let ext = config.pathExtension {
  229. return "\(hashedKey).\(ext)"
  230. }
  231. return hashedKey
  232. } else {
  233. if let ext = config.pathExtension {
  234. return "\(key).\(ext)"
  235. }
  236. return key
  237. }
  238. }
  239. func allFileURLs(for propertyKeys: [URLResourceKey]) throws -> [URL] {
  240. let fileManager = config.fileManager
  241. guard let directoryEnumerator = fileManager.enumerator(
  242. at: directoryURL, includingPropertiesForKeys: propertyKeys, options: .skipsHiddenFiles) else
  243. {
  244. throw KingfisherError.cacheError(reason: .fileEnumeratorCreationFailed(url: directoryURL))
  245. }
  246. guard let urls = directoryEnumerator.allObjects as? [URL] else {
  247. throw KingfisherError.cacheError(reason: .invalidFileEnumeratorContent(url: directoryURL))
  248. }
  249. return urls
  250. }
  251. func removeExpiredValues(referenceDate: Date = Date()) throws -> [URL] {
  252. let propertyKeys: [URLResourceKey] = [
  253. .isDirectoryKey,
  254. .contentModificationDateKey
  255. ]
  256. let urls = try allFileURLs(for: propertyKeys)
  257. let keys = Set(propertyKeys)
  258. let expiredFiles = urls.filter { fileURL in
  259. do {
  260. let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
  261. if meta.isDirectory {
  262. return false
  263. }
  264. return meta.expired(referenceDate: referenceDate)
  265. } catch {
  266. return true
  267. }
  268. }
  269. try expiredFiles.forEach { url in
  270. try removeFile(at: url)
  271. }
  272. return expiredFiles
  273. }
  274. func removeSizeExceededValues() throws -> [URL] {
  275. if config.sizeLimit == 0 { return [] } // Back compatible. 0 means no limit.
  276. var size = try totalSize()
  277. if size < config.sizeLimit { return [] }
  278. let propertyKeys: [URLResourceKey] = [
  279. .isDirectoryKey,
  280. .creationDateKey,
  281. .fileSizeKey
  282. ]
  283. let keys = Set(propertyKeys)
  284. let urls = try allFileURLs(for: propertyKeys)
  285. var pendings: [FileMeta] = urls.compactMap { fileURL in
  286. guard let meta = try? FileMeta(fileURL: fileURL, resourceKeys: keys) else {
  287. return nil
  288. }
  289. return meta
  290. }
  291. // Sort by last access date. Most recent file first.
  292. pendings.sort(by: FileMeta.lastAccessDate)
  293. var removed: [URL] = []
  294. let target = config.sizeLimit / 2
  295. while size > target, let meta = pendings.popLast() {
  296. size -= UInt(meta.fileSize)
  297. try removeFile(at: meta.url)
  298. removed.append(meta.url)
  299. }
  300. return removed
  301. }
  302. /// Get the total file size of the folder in bytes.
  303. func totalSize() throws -> UInt {
  304. let propertyKeys: [URLResourceKey] = [.fileSizeKey]
  305. let urls = try allFileURLs(for: propertyKeys)
  306. let keys = Set(propertyKeys)
  307. let totalSize: UInt = urls.reduce(0) { size, fileURL in
  308. do {
  309. let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
  310. return size + UInt(meta.fileSize)
  311. } catch {
  312. return size
  313. }
  314. }
  315. return totalSize
  316. }
  317. }
  318. }
  319. extension DiskStorage {
  320. /// Represents the config used in a `DiskStorage`.
  321. public struct Config {
  322. /// The file size limit on disk of the storage in bytes. 0 means no limit.
  323. public var sizeLimit: UInt
  324. /// The `StorageExpiration` used in this disk storage. Default is `.days(7)`,
  325. /// means that the disk cache would expire in one week.
  326. public var expiration: StorageExpiration = .days(7)
  327. /// The preferred extension of cache item. It will be appended to the file name as its extension.
  328. /// Default is `nil`, means that the cache file does not contain a file extension.
  329. public var pathExtension: String? = nil
  330. /// Default is `true`, means that the cache file name will be hashed before storing.
  331. public var usesHashedFileName = true
  332. let name: String
  333. let fileManager: FileManager
  334. let directory: URL?
  335. var cachePathBlock: ((_ directory: URL, _ cacheName: String) -> URL)! = {
  336. (directory, cacheName) in
  337. return directory.appendingPathComponent(cacheName, isDirectory: true)
  338. }
  339. /// Creates a config value based on given parameters.
  340. ///
  341. /// - Parameters:
  342. /// - name: The name of cache. It is used as a part of storage folder. It is used to identify the disk
  343. /// storage. Two storages with the same `name` would share the same folder in disk, and it should
  344. /// be prevented.
  345. /// - sizeLimit: The size limit in bytes for all existing files in the disk storage.
  346. /// - fileManager: The `FileManager` used to manipulate files on disk. Default is `FileManager.default`.
  347. /// - directory: The URL where the disk storage should live. The storage will use this as the root folder,
  348. /// and append a path which is constructed by input `name`. Default is `nil`, indicates that
  349. /// the cache directory under user domain mask will be used.
  350. public init(
  351. name: String,
  352. sizeLimit: UInt,
  353. fileManager: FileManager = .default,
  354. directory: URL? = nil)
  355. {
  356. self.name = name
  357. self.fileManager = fileManager
  358. self.directory = directory
  359. self.sizeLimit = sizeLimit
  360. }
  361. }
  362. }
  363. extension DiskStorage {
  364. struct FileMeta {
  365. let url: URL
  366. let lastAccessDate: Date?
  367. let estimatedExpirationDate: Date?
  368. let isDirectory: Bool
  369. let fileSize: Int
  370. static func lastAccessDate(lhs: FileMeta, rhs: FileMeta) -> Bool {
  371. return lhs.lastAccessDate ?? .distantPast > rhs.lastAccessDate ?? .distantPast
  372. }
  373. init(fileURL: URL, resourceKeys: Set<URLResourceKey>) throws {
  374. let meta = try fileURL.resourceValues(forKeys: resourceKeys)
  375. self.init(
  376. fileURL: fileURL,
  377. lastAccessDate: meta.creationDate,
  378. estimatedExpirationDate: meta.contentModificationDate,
  379. isDirectory: meta.isDirectory ?? false,
  380. fileSize: meta.fileSize ?? 0)
  381. }
  382. init(
  383. fileURL: URL,
  384. lastAccessDate: Date?,
  385. estimatedExpirationDate: Date?,
  386. isDirectory: Bool,
  387. fileSize: Int)
  388. {
  389. self.url = fileURL
  390. self.lastAccessDate = lastAccessDate
  391. self.estimatedExpirationDate = estimatedExpirationDate
  392. self.isDirectory = isDirectory
  393. self.fileSize = fileSize
  394. }
  395. func expired(referenceDate: Date) -> Bool {
  396. return estimatedExpirationDate?.isPast(referenceDate: referenceDate) ?? true
  397. }
  398. func extendExpiration(with fileManager: FileManager, extendingExpiration: ExpirationExtending) {
  399. guard let lastAccessDate = lastAccessDate,
  400. let lastEstimatedExpiration = estimatedExpirationDate else
  401. {
  402. return
  403. }
  404. let attributes: [FileAttributeKey : Any]
  405. switch extendingExpiration {
  406. case .none:
  407. // not extending expiration time here
  408. return
  409. case .cacheTime:
  410. let originalExpiration: StorageExpiration =
  411. .seconds(lastEstimatedExpiration.timeIntervalSince(lastAccessDate))
  412. attributes = [
  413. .creationDate: Date().fileAttributeDate,
  414. .modificationDate: originalExpiration.estimatedExpirationSinceNow.fileAttributeDate
  415. ]
  416. case .expirationTime(let expirationTime):
  417. attributes = [
  418. .creationDate: Date().fileAttributeDate,
  419. .modificationDate: expirationTime.estimatedExpirationSinceNow.fileAttributeDate
  420. ]
  421. }
  422. try? fileManager.setAttributes(attributes, ofItemAtPath: url.path)
  423. }
  424. }
  425. }