DiskStorage.swift 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649
  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 = []) throws
  129. {
  130. guard storageReady else {
  131. throw KingfisherError.cacheError(reason: .diskStorageIsNotReady(cacheURL: directoryURL))
  132. }
  133. let expiration = expiration ?? config.expiration
  134. // The expiration indicates that already expired, no need to store.
  135. guard !expiration.isExpired else { return }
  136. let data: Data
  137. do {
  138. data = try value.toData()
  139. } catch {
  140. throw KingfisherError.cacheError(reason: .cannotConvertToData(object: value, error: error))
  141. }
  142. let fileURL = cacheFileURL(forKey: key)
  143. do {
  144. try data.write(to: fileURL, options: writeOptions)
  145. } catch {
  146. if error.isFolderMissing {
  147. // The whole cache folder is deleted. Try to recreate it and write file again.
  148. do {
  149. try prepareDirectory()
  150. try data.write(to: fileURL, options: writeOptions)
  151. } catch {
  152. throw KingfisherError.cacheError(
  153. reason: .cannotCreateCacheFile(fileURL: fileURL, key: key, data: data, error: error)
  154. )
  155. }
  156. } else {
  157. throw KingfisherError.cacheError(
  158. reason: .cannotCreateCacheFile(fileURL: fileURL, key: key, data: data, error: error)
  159. )
  160. }
  161. }
  162. let now = Date()
  163. let attributes: [FileAttributeKey : Any] = [
  164. // The last access date.
  165. .creationDate: now.fileAttributeDate,
  166. // The estimated expiration date.
  167. .modificationDate: expiration.estimatedExpirationSinceNow.fileAttributeDate
  168. ]
  169. do {
  170. try config.fileManager.setAttributes(attributes, ofItemAtPath: fileURL.path)
  171. } catch {
  172. try? config.fileManager.removeItem(at: fileURL)
  173. throw KingfisherError.cacheError(
  174. reason: .cannotSetCacheFileAttribute(
  175. filePath: fileURL.path,
  176. attributes: attributes,
  177. error: error
  178. )
  179. )
  180. }
  181. maybeCachedCheckingQueue.async {
  182. self.maybeCached?.insert(fileURL.lastPathComponent)
  183. }
  184. }
  185. /// Retrieves a value from the storage.
  186. /// - Parameters:
  187. /// - key: The cache key of the value.
  188. /// - extendingExpiration: The expiration policy used by this retrieval action.
  189. /// - Throws: An error during converting the data to a value or during the operation of disk files.
  190. /// - Returns: The value under `key` if it is valid and found in the storage; otherwise, `nil`.
  191. public func value(forKey key: String, extendingExpiration: ExpirationExtending = .cacheTime) throws -> T? {
  192. try value(forKey: key, referenceDate: Date(), actuallyLoad: true, extendingExpiration: extendingExpiration)
  193. }
  194. func value(
  195. forKey key: String,
  196. referenceDate: Date,
  197. actuallyLoad: Bool,
  198. extendingExpiration: ExpirationExtending) throws -> T?
  199. {
  200. guard storageReady else {
  201. throw KingfisherError.cacheError(reason: .diskStorageIsNotReady(cacheURL: directoryURL))
  202. }
  203. let fileManager = config.fileManager
  204. let fileURL = cacheFileURL(forKey: key)
  205. let filePath = fileURL.path
  206. let fileMaybeCached = maybeCachedCheckingQueue.sync {
  207. return maybeCached?.contains(fileURL.lastPathComponent) ?? true
  208. }
  209. guard fileMaybeCached else {
  210. return nil
  211. }
  212. guard fileManager.fileExists(atPath: filePath) else {
  213. return nil
  214. }
  215. let meta: FileMeta
  216. do {
  217. let resourceKeys: Set<URLResourceKey> = [.contentModificationDateKey, .creationDateKey]
  218. meta = try FileMeta(fileURL: fileURL, resourceKeys: resourceKeys)
  219. } catch {
  220. throw KingfisherError.cacheError(
  221. reason: .invalidURLResource(error: error, key: key, url: fileURL))
  222. }
  223. if meta.expired(referenceDate: referenceDate) {
  224. return nil
  225. }
  226. if !actuallyLoad { return T.empty }
  227. do {
  228. let data = try Data(contentsOf: fileURL)
  229. let obj = try T.fromData(data)
  230. metaChangingQueue.async {
  231. meta.extendExpiration(with: self.config.fileManager, extendingExpiration: extendingExpiration)
  232. }
  233. return obj
  234. } catch {
  235. throw KingfisherError.cacheError(reason: .cannotLoadDataFromDisk(url: fileURL, error: error))
  236. }
  237. }
  238. /// Determines whether there is valid cached data under a given key.
  239. ///
  240. /// - Parameter key: The cache key of the value.
  241. /// - Returns: `true` if there is valid data under the key; otherwise, `false`.
  242. ///
  243. /// > This method does not actually load the data from disk, so it is faster than directly loading the cached
  244. /// value by checking the nullability of the ``DiskStorage/Backend/value(forKey:extendingExpiration:)`` method.
  245. public func isCached(forKey key: String) -> Bool {
  246. return isCached(forKey: key, referenceDate: Date())
  247. }
  248. /// Determines whether there is valid cached data under a given key and a reference date.
  249. ///
  250. /// - Parameters:
  251. /// - key: The cache key of the value.
  252. /// - referenceDate: A reference date to check whether the cache is still valid.
  253. ///
  254. /// - Returns: `true` if there is valid data under the key; otherwise, `false`.
  255. ///
  256. /// If you pass `Date()` as the `referenceDate`, this method is identical to
  257. /// ``DiskStorage/Backend/isCached(forKey:)``. Use the `referenceDate` to determine whether the cache is still
  258. /// valid for a future date.
  259. public func isCached(forKey key: String, referenceDate: Date) -> Bool {
  260. do {
  261. let result = try value(
  262. forKey: key,
  263. referenceDate: referenceDate,
  264. actuallyLoad: false,
  265. extendingExpiration: .none
  266. )
  267. return result != nil
  268. } catch {
  269. return false
  270. }
  271. }
  272. /// Removes a value from a specified key.
  273. /// - Parameter key: The cache key of the value.
  274. /// - Throws: An error during the removal of the value.
  275. public func remove(forKey key: String) throws {
  276. let fileURL = cacheFileURL(forKey: key)
  277. try removeFile(at: fileURL)
  278. }
  279. func removeFile(at url: URL) throws {
  280. try config.fileManager.removeItem(at: url)
  281. }
  282. /// Removes all values in this storage.
  283. /// - Throws: An error during the removal of the values.
  284. public func removeAll() throws {
  285. try removeAll(skipCreatingDirectory: false)
  286. }
  287. func removeAll(skipCreatingDirectory: Bool) throws {
  288. try config.fileManager.removeItem(at: directoryURL)
  289. if !skipCreatingDirectory {
  290. try prepareDirectory()
  291. }
  292. }
  293. /// The URL of the cached file with a given computed `key`.
  294. ///
  295. /// - Parameter key: The final computed key used when caching the image. Please note that usually this is not
  296. /// the ``Source/cacheKey`` of an image ``Source``. It is the computed key with the processor identifier
  297. /// considered.
  298. ///
  299. /// This method does not guarantee that an image is already cached at the returned URL. It just provides the URL
  300. /// where the image should be if it exists in the disk storage, with the given key.
  301. public func cacheFileURL(forKey key: String) -> URL {
  302. let fileName = cacheFileName(forKey: key)
  303. return directoryURL.appendingPathComponent(fileName, isDirectory: false)
  304. }
  305. func cacheFileName(forKey key: String) -> String {
  306. if config.usesHashedFileName {
  307. let hashedKey = key.kf.sha256
  308. if let ext = config.pathExtension {
  309. return "\(hashedKey).\(ext)"
  310. } else if config.autoExtAfterHashedFileName,
  311. let ext = key.kf.ext {
  312. return "\(hashedKey).\(ext)"
  313. }
  314. return hashedKey
  315. } else {
  316. if let ext = config.pathExtension {
  317. return "\(key).\(ext)"
  318. }
  319. return key
  320. }
  321. }
  322. func allFileURLs(for propertyKeys: [URLResourceKey]) throws -> [URL] {
  323. let fileManager = config.fileManager
  324. guard let directoryEnumerator = fileManager.enumerator(
  325. at: directoryURL, includingPropertiesForKeys: propertyKeys, options: .skipsHiddenFiles) else
  326. {
  327. throw KingfisherError.cacheError(reason: .fileEnumeratorCreationFailed(url: directoryURL))
  328. }
  329. guard let urls = directoryEnumerator.allObjects as? [URL] else {
  330. throw KingfisherError.cacheError(reason: .invalidFileEnumeratorContent(url: directoryURL))
  331. }
  332. return urls
  333. }
  334. /// Removes all expired values from this storage.
  335. /// - Throws: A file manager error during the removal of the file.
  336. /// - Returns: The URLs for the removed files.
  337. public func removeExpiredValues() throws -> [URL] {
  338. return try removeExpiredValues(referenceDate: Date())
  339. }
  340. func removeExpiredValues(referenceDate: Date) throws -> [URL] {
  341. let propertyKeys: [URLResourceKey] = [
  342. .isDirectoryKey,
  343. .contentModificationDateKey
  344. ]
  345. let urls = try allFileURLs(for: propertyKeys)
  346. let keys = Set(propertyKeys)
  347. let expiredFiles = urls.filter { fileURL in
  348. do {
  349. let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
  350. if meta.isDirectory {
  351. return false
  352. }
  353. return meta.expired(referenceDate: referenceDate)
  354. } catch {
  355. return true
  356. }
  357. }
  358. try expiredFiles.forEach { url in
  359. try removeFile(at: url)
  360. }
  361. return expiredFiles
  362. }
  363. /// Removes all size-exceeded values from this storage.
  364. /// - Throws: A file manager error during the removal of the file.
  365. /// - Returns: The URLs for the removed files.
  366. ///
  367. /// This method checks ``DiskStorage/Config/sizeLimit`` and removes cached files in an LRU
  368. /// (Least Recently Used) way.
  369. public func removeSizeExceededValues() throws -> [URL] {
  370. if config.sizeLimit == 0 { return [] } // Back compatible. 0 means no limit.
  371. var size = try totalSize()
  372. if size < config.sizeLimit { return [] }
  373. let propertyKeys: [URLResourceKey] = [
  374. .isDirectoryKey,
  375. .creationDateKey,
  376. .fileSizeKey
  377. ]
  378. let keys = Set(propertyKeys)
  379. let urls = try allFileURLs(for: propertyKeys)
  380. var pendings: [FileMeta] = urls.compactMap { fileURL in
  381. guard let meta = try? FileMeta(fileURL: fileURL, resourceKeys: keys) else {
  382. return nil
  383. }
  384. return meta
  385. }
  386. // Sort by last access date. Most recent file first.
  387. pendings.sort(by: FileMeta.lastAccessDate)
  388. var removed: [URL] = []
  389. let target = config.sizeLimit / 2
  390. while size > target, let meta = pendings.popLast() {
  391. size -= UInt(meta.fileSize)
  392. try removeFile(at: meta.url)
  393. removed.append(meta.url)
  394. }
  395. return removed
  396. }
  397. /// Gets the total file size of the cache folder in bytes.
  398. public func totalSize() throws -> UInt {
  399. let propertyKeys: [URLResourceKey] = [.fileSizeKey]
  400. let urls = try allFileURLs(for: propertyKeys)
  401. let keys = Set(propertyKeys)
  402. let totalSize: UInt = urls.reduce(0) { size, fileURL in
  403. do {
  404. let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
  405. return size + UInt(meta.fileSize)
  406. } catch {
  407. return size
  408. }
  409. }
  410. return totalSize
  411. }
  412. }
  413. }
  414. extension DiskStorage {
  415. /// Represents the configuration used in a ``DiskStorage/Backend``.
  416. public struct Config: @unchecked Sendable {
  417. /// The file size limit on disk of the storage in bytes.
  418. ///
  419. /// `0` means no limit.
  420. public var sizeLimit: UInt
  421. /// The `StorageExpiration` used in this disk storage.
  422. ///
  423. /// The default is `.days(7)`, which means that the disk cache will expire in one week if not accessed anymore.
  424. public var expiration: StorageExpiration = .days(7)
  425. /// The preferred extension of the cache item. It will be appended to the file name as its extension.
  426. ///
  427. /// The default is `nil`, which means that the cache file does not contain a file extension.
  428. public var pathExtension: String? = nil
  429. /// Whether the cache file name will be hashed before storing.
  430. ///
  431. /// The default is `true`, which means that file name is hashed to protect user information (for example, the
  432. /// original download URL which is used as the cache key).
  433. public var usesHashedFileName = true
  434. /// Whether the image extension will be extracted from the original file name and appended to the hashed file
  435. /// name, which will be used as the cache key on disk.
  436. ///
  437. /// The default is `false`.
  438. public var autoExtAfterHashedFileName = false
  439. /// A closure that takes in the initial directory path and generates the final disk cache path.
  440. ///
  441. /// You can use it to fully customize your cache path.
  442. public var cachePathBlock: (@Sendable (_ directory: URL, _ cacheName: String) -> URL)! = {
  443. (directory, cacheName) in
  444. return directory.appendingPathComponent(cacheName, isDirectory: true)
  445. }
  446. /// The desired name of the disk cache.
  447. ///
  448. /// This name will be used as a part of the cache folder name by default.
  449. public let name: String
  450. let fileManager: FileManager
  451. let directory: URL?
  452. /// Creates a config value based on the given parameters.
  453. ///
  454. /// - Parameters:
  455. /// - name: The name of the cache. It is used as part of the storage folder and to identify the disk storage.
  456. /// Two storages with the same `name` would share the same folder on the disk, and this should be prevented.
  457. /// - sizeLimit: The size limit in bytes for all existing files in the disk storage.
  458. /// - fileManager: The `FileManager` used to manipulate files on the disk. The default is `FileManager.default`.
  459. /// - directory: The URL where the disk storage should reside. The storage will use this as the root folder,
  460. /// and append a path that is constructed by the input `name`. The default is `nil`, indicating that
  461. /// the cache directory under the user domain mask will be used.
  462. public init(
  463. name: String,
  464. sizeLimit: UInt,
  465. fileManager: FileManager = .default,
  466. directory: URL? = nil)
  467. {
  468. self.name = name
  469. self.fileManager = fileManager
  470. self.directory = directory
  471. self.sizeLimit = sizeLimit
  472. }
  473. }
  474. }
  475. extension DiskStorage {
  476. struct FileMeta {
  477. let url: URL
  478. let lastAccessDate: Date?
  479. let estimatedExpirationDate: Date?
  480. let isDirectory: Bool
  481. let fileSize: Int
  482. static func lastAccessDate(lhs: FileMeta, rhs: FileMeta) -> Bool {
  483. return lhs.lastAccessDate ?? .distantPast > rhs.lastAccessDate ?? .distantPast
  484. }
  485. init(fileURL: URL, resourceKeys: Set<URLResourceKey>) throws {
  486. let meta = try fileURL.resourceValues(forKeys: resourceKeys)
  487. self.init(
  488. fileURL: fileURL,
  489. lastAccessDate: meta.creationDate,
  490. estimatedExpirationDate: meta.contentModificationDate,
  491. isDirectory: meta.isDirectory ?? false,
  492. fileSize: meta.fileSize ?? 0)
  493. }
  494. init(
  495. fileURL: URL,
  496. lastAccessDate: Date?,
  497. estimatedExpirationDate: Date?,
  498. isDirectory: Bool,
  499. fileSize: Int)
  500. {
  501. self.url = fileURL
  502. self.lastAccessDate = lastAccessDate
  503. self.estimatedExpirationDate = estimatedExpirationDate
  504. self.isDirectory = isDirectory
  505. self.fileSize = fileSize
  506. }
  507. func expired(referenceDate: Date) -> Bool {
  508. return estimatedExpirationDate?.isPast(referenceDate: referenceDate) ?? true
  509. }
  510. func extendExpiration(with fileManager: FileManager, extendingExpiration: ExpirationExtending) {
  511. guard let lastAccessDate = lastAccessDate,
  512. let lastEstimatedExpiration = estimatedExpirationDate else
  513. {
  514. return
  515. }
  516. let attributes: [FileAttributeKey : Any]
  517. switch extendingExpiration {
  518. case .none:
  519. // not extending expiration time here
  520. return
  521. case .cacheTime:
  522. let originalExpiration: StorageExpiration =
  523. .seconds(lastEstimatedExpiration.timeIntervalSince(lastAccessDate))
  524. attributes = [
  525. .creationDate: Date().fileAttributeDate,
  526. .modificationDate: originalExpiration.estimatedExpirationSinceNow.fileAttributeDate
  527. ]
  528. case .expirationTime(let expirationTime):
  529. attributes = [
  530. .creationDate: Date().fileAttributeDate,
  531. .modificationDate: expirationTime.estimatedExpirationSinceNow.fileAttributeDate
  532. ]
  533. }
  534. try? fileManager.setAttributes(attributes, ofItemAtPath: url.path)
  535. }
  536. }
  537. }
  538. extension DiskStorage {
  539. struct Creation {
  540. let directoryURL: URL
  541. let cacheName: String
  542. init(_ config: Config) {
  543. let url: URL
  544. if let directory = config.directory {
  545. url = directory
  546. } else {
  547. url = config.fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
  548. }
  549. cacheName = "com.onevcat.Kingfisher.ImageCache.\(config.name)"
  550. directoryURL = config.cachePathBlock(url, cacheName)
  551. }
  552. }
  553. }
  554. fileprivate extension Error {
  555. var isFolderMissing: Bool {
  556. let nsError = self as NSError
  557. guard nsError.domain == NSCocoaErrorDomain, nsError.code == 4 else {
  558. return false
  559. }
  560. guard let underlyingError = nsError.userInfo[NSUnderlyingErrorKey] as? NSError else {
  561. return false
  562. }
  563. guard underlyingError.domain == NSPOSIXErrorDomain, underlyingError.code == 2 else {
  564. return false
  565. }
  566. return true
  567. }
  568. }