DiskStorage.swift 28 KB

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