2
0

DiskStorage.swift 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665
  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 the concepts related to storage that stores a specific type of value in disk.
  28. ///
  29. /// This serves as a namespace for memory storage types. A ``DiskStorage/Backend`` with a particular
  30. /// ``DiskStorage/Config`` is used to define the storage.
  31. ///
  32. /// Refer to these composite types for further details.
  33. public enum DiskStorage {
  34. /// Represents a storage backend for the ``DiskStorage``.
  35. ///
  36. /// The value is serialized to binary data and stored as a file in the file system under a specified location.
  37. ///
  38. /// You can configure a ``DiskStorage/Backend`` in its ``DiskStorage/Backend/init(config:)`` by passing a
  39. /// ``DiskStorage/Config`` value or by modifying the ``DiskStorage/Backend/config`` property after it has been
  40. /// created. The ``DiskStorage/Backend`` will use the file's attributes to keep track of a file for its expiration
  41. /// or size limitation.
  42. public class Backend<T: DataTransformable>: @unchecked Sendable {
  43. private let propertyQueue = DispatchQueue(label: "com.onevcat.kingfisher.DiskStorage.Backend.propertyQueue")
  44. private var _config: Config
  45. /// The configuration used for this disk storage.
  46. ///
  47. /// It is a value you can set and use to configure the storage as needed.
  48. public var config: Config {
  49. get { propertyQueue.sync { _config } }
  50. set { propertyQueue.sync { _config = newValue } }
  51. }
  52. /// The final storage URL on disk of the disk storage ``DiskStorage/Backend``, considering the
  53. /// ``DiskStorage/Config/name`` and the ``DiskStorage/Config/cachePathBlock``.
  54. public let directoryURL: URL
  55. let metaChangingQueue: DispatchQueue
  56. // A shortcut (which contains false-positive) to improve matching performance.
  57. var maybeCached : Set<String>?
  58. let maybeCachedCheckingQueue = DispatchQueue(label: "com.onevcat.Kingfisher.maybeCachedCheckingQueue")
  59. // `false` if the storage initialized with an error.
  60. // This prevents unexpected forcibly crash when creating storage in the default cache.
  61. private var storageReady: Bool = true
  62. /// Creates a disk storage with the given ``DiskStorage/Config``.
  63. ///
  64. /// - Parameter config: The configuration used for this disk storage.
  65. /// - Throws: An error if the folder for storage cannot be obtained or created.
  66. public convenience init(config: Config) throws {
  67. self.init(noThrowConfig: config, creatingDirectory: false)
  68. try prepareDirectory()
  69. }
  70. // If `creatingDirectory` is `false`, the directory preparation will be skipped.
  71. // We need to call `prepareDirectory` manually after this returns.
  72. init(noThrowConfig config: Config, creatingDirectory: Bool) {
  73. var config = config
  74. let creation = Creation(config)
  75. self.directoryURL = creation.directoryURL
  76. // Break any possible retain cycle set by outside.
  77. config.cachePathBlock = nil
  78. _config = config
  79. metaChangingQueue = DispatchQueue(label: creation.cacheName)
  80. setupCacheChecking()
  81. if creatingDirectory {
  82. try? prepareDirectory()
  83. }
  84. }
  85. private func setupCacheChecking() {
  86. maybeCachedCheckingQueue.async {
  87. do {
  88. self.maybeCached = Set()
  89. try self.config.fileManager.contentsOfDirectory(atPath: self.directoryURL.path).forEach {
  90. fileName in
  91. self.maybeCached?.insert(fileName)
  92. }
  93. } catch {
  94. // Just disable the functionality if we fail to initialize it properly. This will just revert to
  95. // the behavior which is to check file existence on disk directly.
  96. self.maybeCached = nil
  97. }
  98. }
  99. }
  100. // Creates the storage folder.
  101. private func prepareDirectory() throws {
  102. let fileManager = config.fileManager
  103. let path = directoryURL.path
  104. guard !fileManager.fileExists(atPath: path) else { return }
  105. do {
  106. try fileManager.createDirectory(
  107. atPath: path,
  108. withIntermediateDirectories: true,
  109. attributes: nil)
  110. } catch {
  111. self.storageReady = false
  112. throw KingfisherError.cacheError(reason: .cannotCreateDirectory(path: path, error: error))
  113. }
  114. }
  115. /// Stores a value in the storage under the specified key and expiration policy.
  116. ///
  117. /// - Parameters:
  118. /// - value: The value to be stored.
  119. /// - key: The key to which the `value` will be stored. If there is already a value under the key,
  120. /// the old value will be overwritten by the new `value`.
  121. /// - expiration: The expiration policy used by this storage action.
  122. /// - writeOptions: Data writing options used for the new files.
  123. /// - Throws: An error during converting the value to a data format or during writing it to disk.
  124. public func store(
  125. value: T,
  126. forKey key: String,
  127. expiration: StorageExpiration? = nil,
  128. writeOptions: Data.WritingOptions = [],
  129. forcedExtension: String? = nil
  130. ) throws
  131. {
  132. guard storageReady else {
  133. throw KingfisherError.cacheError(reason: .diskStorageIsNotReady(cacheURL: directoryURL))
  134. }
  135. let expiration = expiration ?? config.expiration
  136. // The expiration indicates that already expired, no need to store.
  137. guard !expiration.isExpired else { return }
  138. let data: Data
  139. do {
  140. data = try value.toData()
  141. } catch {
  142. throw KingfisherError.cacheError(reason: .cannotConvertToData(object: value, error: error))
  143. }
  144. let fileURL = cacheFileURL(forKey: key, forcedExtension: forcedExtension)
  145. do {
  146. try data.write(to: fileURL, options: writeOptions)
  147. } catch {
  148. if error.isFolderMissing {
  149. // The whole cache folder is deleted. Try to recreate it and write file again.
  150. do {
  151. try prepareDirectory()
  152. try data.write(to: fileURL, options: writeOptions)
  153. } catch {
  154. throw KingfisherError.cacheError(
  155. reason: .cannotCreateCacheFile(fileURL: fileURL, key: key, data: data, error: error)
  156. )
  157. }
  158. } else {
  159. throw KingfisherError.cacheError(
  160. reason: .cannotCreateCacheFile(fileURL: fileURL, key: key, data: data, error: error)
  161. )
  162. }
  163. }
  164. let now = Date()
  165. let attributes: [FileAttributeKey : Any] = [
  166. // The last access date.
  167. .creationDate: now.fileAttributeDate,
  168. // The estimated expiration date.
  169. .modificationDate: expiration.estimatedExpirationSinceNow.fileAttributeDate
  170. ]
  171. do {
  172. try config.fileManager.setAttributes(attributes, ofItemAtPath: fileURL.path)
  173. } catch {
  174. try? config.fileManager.removeItem(at: fileURL)
  175. throw KingfisherError.cacheError(
  176. reason: .cannotSetCacheFileAttribute(
  177. filePath: fileURL.path,
  178. attributes: attributes,
  179. error: error
  180. )
  181. )
  182. }
  183. maybeCachedCheckingQueue.async {
  184. self.maybeCached?.insert(fileURL.lastPathComponent)
  185. }
  186. }
  187. /// Retrieves a value from the storage.
  188. /// - Parameters:
  189. /// - key: The cache key of the value.
  190. /// - extendingExpiration: The expiration policy used by this retrieval action.
  191. /// - Throws: An error during converting the data to a value or during the operation of disk files.
  192. /// - Returns: The value under `key` if it is valid and found in the storage; otherwise, `nil`.
  193. public func value(
  194. forKey key: String,
  195. forcedExtension: String? = nil,
  196. extendingExpiration: ExpirationExtending = .cacheTime
  197. ) throws -> T? {
  198. try value(
  199. forKey: key,
  200. referenceDate: Date(),
  201. actuallyLoad: true,
  202. extendingExpiration: extendingExpiration,
  203. forcedExtension: forcedExtension
  204. )
  205. }
  206. func value(
  207. forKey key: String,
  208. referenceDate: Date,
  209. actuallyLoad: Bool,
  210. extendingExpiration: ExpirationExtending,
  211. forcedExtension: String?
  212. ) throws -> T?
  213. {
  214. guard storageReady else {
  215. throw KingfisherError.cacheError(reason: .diskStorageIsNotReady(cacheURL: directoryURL))
  216. }
  217. let fileManager = config.fileManager
  218. let fileURL = cacheFileURL(forKey: key, forcedExtension: forcedExtension)
  219. let filePath = fileURL.path
  220. let fileMaybeCached = maybeCachedCheckingQueue.sync {
  221. return maybeCached?.contains(fileURL.lastPathComponent) ?? true
  222. }
  223. guard fileMaybeCached else {
  224. return nil
  225. }
  226. guard fileManager.fileExists(atPath: filePath) else {
  227. return nil
  228. }
  229. let meta: FileMeta
  230. do {
  231. let resourceKeys: Set<URLResourceKey> = [.contentModificationDateKey, .creationDateKey]
  232. meta = try FileMeta(fileURL: fileURL, resourceKeys: resourceKeys)
  233. } catch {
  234. throw KingfisherError.cacheError(
  235. reason: .invalidURLResource(error: error, key: key, url: fileURL))
  236. }
  237. if meta.expired(referenceDate: referenceDate) {
  238. return nil
  239. }
  240. if !actuallyLoad { return T.empty }
  241. do {
  242. let data = try Data(contentsOf: fileURL)
  243. let obj = try T.fromData(data)
  244. metaChangingQueue.async {
  245. meta.extendExpiration(with: self.config.fileManager, extendingExpiration: extendingExpiration)
  246. }
  247. return obj
  248. } catch {
  249. throw KingfisherError.cacheError(reason: .cannotLoadDataFromDisk(url: fileURL, error: error))
  250. }
  251. }
  252. /// Determines whether there is valid cached data under a given key.
  253. ///
  254. /// - Parameter key: The cache key of the value.
  255. /// - Returns: `true` if there is valid data under the key; otherwise, `false`.
  256. ///
  257. /// > This method does not actually load the data from disk, so it is faster than directly loading the cached
  258. /// value by checking the nullability of the ``DiskStorage/Backend/value(forKey:extendingExpiration:)`` method.
  259. public func isCached(forKey key: String, forcedExtension: String? = nil) -> Bool {
  260. return isCached(forKey: key, referenceDate: Date(), forcedExtension: forcedExtension)
  261. }
  262. /// Determines whether there is valid cached data under a given key and a reference date.
  263. ///
  264. /// - Parameters:
  265. /// - key: The cache key of the value.
  266. /// - referenceDate: A reference date to check whether the cache is still valid.
  267. ///
  268. /// - Returns: `true` if there is valid data under the key; otherwise, `false`.
  269. ///
  270. /// If you pass `Date()` as the `referenceDate`, this method is identical to
  271. /// ``DiskStorage/Backend/isCached(forKey:)``. Use the `referenceDate` to determine whether the cache is still
  272. /// valid for a future date.
  273. public func isCached(forKey key: String, referenceDate: Date, forcedExtension: String? = nil) -> Bool {
  274. do {
  275. let result = try value(
  276. forKey: key,
  277. referenceDate: referenceDate,
  278. actuallyLoad: false,
  279. extendingExpiration: .none,
  280. forcedExtension: forcedExtension
  281. )
  282. return result != nil
  283. } catch {
  284. return false
  285. }
  286. }
  287. /// Removes a value from a specified key.
  288. /// - Parameter key: The cache key of the value.
  289. /// - Throws: An error during the removal of the value.
  290. public func remove(forKey key: String, forcedExtension: String? = nil) throws {
  291. let fileURL = cacheFileURL(forKey: key, forcedExtension: forcedExtension)
  292. try removeFile(at: fileURL)
  293. }
  294. func removeFile(at url: URL) throws {
  295. try config.fileManager.removeItem(at: url)
  296. }
  297. /// Removes all values in this storage.
  298. /// - Throws: An error during the removal of the values.
  299. public func removeAll() throws {
  300. try removeAll(skipCreatingDirectory: false)
  301. }
  302. func removeAll(skipCreatingDirectory: Bool) throws {
  303. try config.fileManager.removeItem(at: directoryURL)
  304. if !skipCreatingDirectory {
  305. try prepareDirectory()
  306. }
  307. }
  308. /// The URL of the cached file with a given computed `key`.
  309. ///
  310. /// - Parameter key: The final computed key used when caching the image. Please note that usually this is not
  311. /// the ``Source/cacheKey`` of an image ``Source``. It is the computed key with the processor identifier
  312. /// considered.
  313. ///
  314. /// This method does not guarantee that an image is already cached at the returned URL. It just provides the URL
  315. /// where the image should be if it exists in the disk storage, with the given key.
  316. public func cacheFileURL(forKey key: String, forcedExtension: String? = nil) -> URL {
  317. let fileName = cacheFileName(forKey: key, forcedExtension: forcedExtension)
  318. return directoryURL.appendingPathComponent(fileName, isDirectory: false)
  319. }
  320. func cacheFileName(forKey key: String, forcedExtension: String? = nil) -> String {
  321. // TODO: Bad code... Consider refactoring.
  322. if config.usesHashedFileName {
  323. let hashedKey = key.kf.sha256
  324. if let ext = forcedExtension ?? config.pathExtension {
  325. return "\(hashedKey).\(ext)"
  326. } else if config.autoExtAfterHashedFileName,
  327. let ext = forcedExtension ?? key.kf.ext {
  328. return "\(hashedKey).\(ext)"
  329. }
  330. return hashedKey
  331. } else {
  332. if let ext = forcedExtension ?? config.pathExtension {
  333. return "\(key).\(ext)"
  334. }
  335. return key
  336. }
  337. }
  338. func allFileURLs(for propertyKeys: [URLResourceKey]) throws -> [URL] {
  339. let fileManager = config.fileManager
  340. guard let directoryEnumerator = fileManager.enumerator(
  341. at: directoryURL, includingPropertiesForKeys: propertyKeys, options: .skipsHiddenFiles) else
  342. {
  343. throw KingfisherError.cacheError(reason: .fileEnumeratorCreationFailed(url: directoryURL))
  344. }
  345. guard let urls = directoryEnumerator.allObjects as? [URL] else {
  346. throw KingfisherError.cacheError(reason: .invalidFileEnumeratorContent(url: directoryURL))
  347. }
  348. return urls
  349. }
  350. /// Removes all expired values from this storage.
  351. /// - Throws: A file manager error during the removal of the file.
  352. /// - Returns: The URLs for the removed files.
  353. public func removeExpiredValues() throws -> [URL] {
  354. return try removeExpiredValues(referenceDate: Date())
  355. }
  356. func removeExpiredValues(referenceDate: Date) throws -> [URL] {
  357. let propertyKeys: [URLResourceKey] = [
  358. .isDirectoryKey,
  359. .contentModificationDateKey
  360. ]
  361. let urls = try allFileURLs(for: propertyKeys)
  362. let keys = Set(propertyKeys)
  363. let expiredFiles = urls.filter { fileURL in
  364. do {
  365. let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
  366. if meta.isDirectory {
  367. return false
  368. }
  369. return meta.expired(referenceDate: referenceDate)
  370. } catch {
  371. return true
  372. }
  373. }
  374. try expiredFiles.forEach { url in
  375. try removeFile(at: url)
  376. }
  377. return expiredFiles
  378. }
  379. /// Removes all size-exceeded values from this storage.
  380. /// - Throws: A file manager error during the removal of the file.
  381. /// - Returns: The URLs for the removed files.
  382. ///
  383. /// This method checks ``DiskStorage/Config/sizeLimit`` and removes cached files in an LRU
  384. /// (Least Recently Used) way.
  385. public func removeSizeExceededValues() throws -> [URL] {
  386. if config.sizeLimit == 0 { return [] } // Back compatible. 0 means no limit.
  387. var size = try totalSize()
  388. if size < config.sizeLimit { return [] }
  389. let propertyKeys: [URLResourceKey] = [
  390. .isDirectoryKey,
  391. .creationDateKey,
  392. .fileSizeKey
  393. ]
  394. let keys = Set(propertyKeys)
  395. let urls = try allFileURLs(for: propertyKeys)
  396. var pendings: [FileMeta] = urls.compactMap { fileURL in
  397. guard let meta = try? FileMeta(fileURL: fileURL, resourceKeys: keys) else {
  398. return nil
  399. }
  400. return meta
  401. }
  402. // Sort by last access date. Most recent file first.
  403. pendings.sort(by: FileMeta.lastAccessDate)
  404. var removed: [URL] = []
  405. let target = config.sizeLimit / 2
  406. while size > target, let meta = pendings.popLast() {
  407. size -= UInt(meta.fileSize)
  408. try removeFile(at: meta.url)
  409. removed.append(meta.url)
  410. }
  411. return removed
  412. }
  413. /// Gets the total file size of the cache folder in bytes.
  414. public func totalSize() throws -> UInt {
  415. let propertyKeys: [URLResourceKey] = [.fileSizeKey]
  416. let urls = try allFileURLs(for: propertyKeys)
  417. let keys = Set(propertyKeys)
  418. let totalSize: UInt = urls.reduce(0) { size, fileURL in
  419. do {
  420. let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
  421. return size + UInt(meta.fileSize)
  422. } catch {
  423. return size
  424. }
  425. }
  426. return totalSize
  427. }
  428. }
  429. }
  430. extension DiskStorage {
  431. /// Represents the configuration used in a ``DiskStorage/Backend``.
  432. public struct Config: @unchecked Sendable {
  433. /// The file size limit on disk of the storage in bytes.
  434. ///
  435. /// `0` means no limit.
  436. public var sizeLimit: UInt
  437. /// The `StorageExpiration` used in this disk storage.
  438. ///
  439. /// The default is `.days(7)`, which means that the disk cache will expire in one week if not accessed anymore.
  440. public var expiration: StorageExpiration = .days(7)
  441. /// The preferred extension of the cache item. It will be appended to the file name as its extension.
  442. ///
  443. /// The default is `nil`, which means that the cache file does not contain a file extension.
  444. public var pathExtension: String? = nil
  445. /// Whether the cache file name will be hashed before storing.
  446. ///
  447. /// The default is `true`, which means that file name is hashed to protect user information (for example, the
  448. /// original download URL which is used as the cache key).
  449. public var usesHashedFileName = true
  450. /// Whether the image extension will be extracted from the original file name and appended to the hashed file
  451. /// name, which will be used as the cache key on disk.
  452. ///
  453. /// The default is `false`.
  454. public var autoExtAfterHashedFileName = false
  455. /// A closure that takes in the initial directory path and generates the final disk cache path.
  456. ///
  457. /// You can use it to fully customize your cache path.
  458. public var cachePathBlock: (@Sendable (_ directory: URL, _ cacheName: String) -> URL)! = {
  459. (directory, cacheName) in
  460. return directory.appendingPathComponent(cacheName, isDirectory: true)
  461. }
  462. /// The desired name of the disk cache.
  463. ///
  464. /// This name will be used as a part of the cache folder name by default.
  465. public let name: String
  466. let fileManager: FileManager
  467. let directory: URL?
  468. /// Creates a config value based on the given parameters.
  469. ///
  470. /// - Parameters:
  471. /// - name: The name of the cache. It is used as part of the storage folder and to identify the disk storage.
  472. /// Two storages with the same `name` would share the same folder on the disk, and this should be prevented.
  473. /// - sizeLimit: The size limit in bytes for all existing files in the disk storage.
  474. /// - fileManager: The `FileManager` used to manipulate files on the disk. The default is `FileManager.default`.
  475. /// - directory: The URL where the disk storage should reside. The storage will use this as the root folder,
  476. /// and append a path that is constructed by the input `name`. The default is `nil`, indicating that
  477. /// the cache directory under the user domain mask will be used.
  478. public init(
  479. name: String,
  480. sizeLimit: UInt,
  481. fileManager: FileManager = .default,
  482. directory: URL? = nil)
  483. {
  484. self.name = name
  485. self.fileManager = fileManager
  486. self.directory = directory
  487. self.sizeLimit = sizeLimit
  488. }
  489. }
  490. }
  491. extension DiskStorage {
  492. struct FileMeta {
  493. let url: URL
  494. let lastAccessDate: Date?
  495. let estimatedExpirationDate: Date?
  496. let isDirectory: Bool
  497. let fileSize: Int
  498. static func lastAccessDate(lhs: FileMeta, rhs: FileMeta) -> Bool {
  499. return lhs.lastAccessDate ?? .distantPast > rhs.lastAccessDate ?? .distantPast
  500. }
  501. init(fileURL: URL, resourceKeys: Set<URLResourceKey>) throws {
  502. let meta = try fileURL.resourceValues(forKeys: resourceKeys)
  503. self.init(
  504. fileURL: fileURL,
  505. lastAccessDate: meta.creationDate,
  506. estimatedExpirationDate: meta.contentModificationDate,
  507. isDirectory: meta.isDirectory ?? false,
  508. fileSize: meta.fileSize ?? 0)
  509. }
  510. init(
  511. fileURL: URL,
  512. lastAccessDate: Date?,
  513. estimatedExpirationDate: Date?,
  514. isDirectory: Bool,
  515. fileSize: Int)
  516. {
  517. self.url = fileURL
  518. self.lastAccessDate = lastAccessDate
  519. self.estimatedExpirationDate = estimatedExpirationDate
  520. self.isDirectory = isDirectory
  521. self.fileSize = fileSize
  522. }
  523. func expired(referenceDate: Date) -> Bool {
  524. return estimatedExpirationDate?.isPast(referenceDate: referenceDate) ?? true
  525. }
  526. func extendExpiration(with fileManager: FileManager, extendingExpiration: ExpirationExtending) {
  527. guard let lastAccessDate = lastAccessDate,
  528. let lastEstimatedExpiration = estimatedExpirationDate else
  529. {
  530. return
  531. }
  532. let attributes: [FileAttributeKey : Any]
  533. switch extendingExpiration {
  534. case .none:
  535. // not extending expiration time here
  536. return
  537. case .cacheTime:
  538. let originalExpiration: StorageExpiration =
  539. .seconds(lastEstimatedExpiration.timeIntervalSince(lastAccessDate))
  540. attributes = [
  541. .creationDate: Date().fileAttributeDate,
  542. .modificationDate: originalExpiration.estimatedExpirationSinceNow.fileAttributeDate
  543. ]
  544. case .expirationTime(let expirationTime):
  545. attributes = [
  546. .creationDate: Date().fileAttributeDate,
  547. .modificationDate: expirationTime.estimatedExpirationSinceNow.fileAttributeDate
  548. ]
  549. }
  550. try? fileManager.setAttributes(attributes, ofItemAtPath: url.path)
  551. }
  552. }
  553. }
  554. extension DiskStorage {
  555. struct Creation {
  556. let directoryURL: URL
  557. let cacheName: String
  558. init(_ config: Config) {
  559. let url: URL
  560. if let directory = config.directory {
  561. url = directory
  562. } else {
  563. url = config.fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
  564. }
  565. cacheName = "com.onevcat.Kingfisher.ImageCache.\(config.name)"
  566. directoryURL = config.cachePathBlock(url, cacheName)
  567. }
  568. }
  569. }
  570. fileprivate extension Error {
  571. var isFolderMissing: Bool {
  572. let nsError = self as NSError
  573. guard nsError.domain == NSCocoaErrorDomain, nsError.code == 4 else {
  574. return false
  575. }
  576. guard let underlyingError = nsError.userInfo[NSUnderlyingErrorKey] as? NSError else {
  577. return false
  578. }
  579. guard underlyingError.domain == NSPOSIXErrorDomain, underlyingError.code == 2 else {
  580. return false
  581. }
  582. return true
  583. }
  584. }