DiskStorage.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  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, the old
  120. /// 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. /// - forcedExtension: The file extension, if exists.
  124. /// - Throws: An error during converting the value to a data format or during writing it to disk.
  125. public func store(
  126. value: T,
  127. forKey key: String,
  128. expiration: StorageExpiration? = nil,
  129. writeOptions: Data.WritingOptions = [],
  130. forcedExtension: String? = nil
  131. ) throws
  132. {
  133. guard storageReady else {
  134. throw KingfisherError.cacheError(reason: .diskStorageIsNotReady(cacheURL: directoryURL))
  135. }
  136. let expiration = expiration ?? config.expiration
  137. // The expiration indicates that already expired, no need to store.
  138. guard !expiration.isExpired else { return }
  139. let data: Data
  140. do {
  141. data = try value.toData()
  142. } catch {
  143. throw KingfisherError.cacheError(reason: .cannotConvertToData(object: value, error: error))
  144. }
  145. let fileURL = cacheFileURL(forKey: key, forcedExtension: forcedExtension)
  146. do {
  147. try data.write(to: fileURL, options: writeOptions)
  148. } catch {
  149. if error.isFolderMissing {
  150. // The whole cache folder is deleted. Try to recreate it and write file again.
  151. do {
  152. try prepareDirectory()
  153. try data.write(to: fileURL, options: writeOptions)
  154. } catch {
  155. throw KingfisherError.cacheError(
  156. reason: .cannotCreateCacheFile(fileURL: fileURL, key: key, data: data, error: error)
  157. )
  158. }
  159. } else {
  160. throw KingfisherError.cacheError(
  161. reason: .cannotCreateCacheFile(fileURL: fileURL, key: key, data: data, error: error)
  162. )
  163. }
  164. }
  165. let now = Date()
  166. let attributes: [FileAttributeKey : Any] = [
  167. // The last access date.
  168. .creationDate: now.fileAttributeDate,
  169. // The estimated expiration date.
  170. .modificationDate: expiration.estimatedExpirationSinceNow.fileAttributeDate
  171. ]
  172. do {
  173. try config.fileManager.setAttributes(attributes, ofItemAtPath: fileURL.path)
  174. } catch {
  175. try? config.fileManager.removeItem(at: fileURL)
  176. throw KingfisherError.cacheError(
  177. reason: .cannotSetCacheFileAttribute(
  178. filePath: fileURL.path,
  179. attributes: attributes,
  180. error: error
  181. )
  182. )
  183. }
  184. maybeCachedCheckingQueue.async {
  185. self.maybeCached?.insert(fileURL.lastPathComponent)
  186. }
  187. }
  188. /// Retrieves a value from the storage.
  189. /// - Parameters:
  190. /// - key: The cache key of the value.
  191. /// - forcedExtension: The file extension, if exists.
  192. /// - extendingExpiration: The expiration policy used by this retrieval action.
  193. /// - Throws: An error during converting the data to a value or during the operation of disk files.
  194. /// - Returns: The value under `key` if it is valid and found in the storage; otherwise, `nil`.
  195. public func value(
  196. forKey key: String,
  197. forcedExtension: String? = nil,
  198. extendingExpiration: ExpirationExtending = .cacheTime
  199. ) throws -> T? {
  200. try value(
  201. forKey: key,
  202. referenceDate: Date(),
  203. actuallyLoad: true,
  204. extendingExpiration: extendingExpiration,
  205. forcedExtension: forcedExtension
  206. )
  207. }
  208. func value(
  209. forKey key: String,
  210. referenceDate: Date,
  211. actuallyLoad: Bool,
  212. extendingExpiration: ExpirationExtending,
  213. forcedExtension: String?
  214. ) throws -> T?
  215. {
  216. guard storageReady else {
  217. throw KingfisherError.cacheError(reason: .diskStorageIsNotReady(cacheURL: directoryURL))
  218. }
  219. let fileManager = config.fileManager
  220. let fileURL = cacheFileURL(forKey: key, forcedExtension: forcedExtension)
  221. let filePath = fileURL.path
  222. let fileMaybeCached = maybeCachedCheckingQueue.sync {
  223. return maybeCached?.contains(fileURL.lastPathComponent) ?? true
  224. }
  225. guard fileMaybeCached else {
  226. return nil
  227. }
  228. guard fileManager.fileExists(atPath: filePath) else {
  229. return nil
  230. }
  231. let meta: FileMeta
  232. do {
  233. let resourceKeys: Set<URLResourceKey> = [.contentModificationDateKey, .creationDateKey]
  234. meta = try FileMeta(fileURL: fileURL, resourceKeys: resourceKeys)
  235. } catch {
  236. throw KingfisherError.cacheError(
  237. reason: .invalidURLResource(error: error, key: key, url: fileURL))
  238. }
  239. if meta.expired(referenceDate: referenceDate) {
  240. return nil
  241. }
  242. if !actuallyLoad { return T.empty }
  243. do {
  244. let data = try Data(contentsOf: fileURL)
  245. let obj = try T.fromData(data)
  246. metaChangingQueue.async {
  247. meta.extendExpiration(with: self.config.fileManager, extendingExpiration: extendingExpiration)
  248. }
  249. return obj
  250. } catch {
  251. throw KingfisherError.cacheError(reason: .cannotLoadDataFromDisk(url: fileURL, error: error))
  252. }
  253. }
  254. /// Determines whether there is valid cached data under a given key.
  255. ///
  256. /// - Parameters:
  257. /// - key: The cache key of the value.
  258. /// - forcedExtension: The file extension, if exists.
  259. /// - Returns: `true` if there is valid data under the key and file extension; otherwise, `false`.
  260. ///
  261. /// > This method does not actually load the data from disk, so it is faster than directly loading the cached
  262. /// value by checking the nullability of the
  263. /// ``DiskStorage/Backend/value(forKey:forcedExtension:extendingExpiration:)`` method.
  264. public func isCached(forKey key: String, forcedExtension: String? = nil) -> Bool {
  265. return isCached(forKey: key, referenceDate: Date(), forcedExtension: forcedExtension)
  266. }
  267. /// Determines whether there is valid cached data under a given key and a reference date.
  268. ///
  269. /// - Parameters:
  270. /// - key: The cache key of the value.
  271. /// - referenceDate: A reference date to check whether the cache is still valid.
  272. /// - forcedExtension: The file extension, if exists.
  273. ///
  274. /// - Returns: `true` if there is valid data under the key; otherwise, `false`.
  275. ///
  276. /// If you pass `Date()` as the `referenceDate`, this method is identical to
  277. /// ``DiskStorage/Backend/isCached(forKey:forcedExtension:)``. Use the `referenceDate` to determine whether the
  278. /// cache is still valid for a future date.
  279. public func isCached(forKey key: String, referenceDate: Date, forcedExtension: String? = nil) -> Bool {
  280. do {
  281. let result = try value(
  282. forKey: key,
  283. referenceDate: referenceDate,
  284. actuallyLoad: false,
  285. extendingExpiration: .none,
  286. forcedExtension: forcedExtension
  287. )
  288. return result != nil
  289. } catch {
  290. return false
  291. }
  292. }
  293. /// Removes a value from a specified key.
  294. /// - Parameters:
  295. /// - key: The cache key of the value.
  296. /// - forcedExtension: The file extension, if exists.
  297. /// - Throws: An error during the removal of the value.
  298. public func remove(forKey key: String, forcedExtension: String? = nil) throws {
  299. let fileURL = cacheFileURL(forKey: key, forcedExtension: forcedExtension)
  300. try removeFile(at: fileURL)
  301. }
  302. func removeFile(at url: URL) throws {
  303. try config.fileManager.removeItem(at: url)
  304. }
  305. /// Removes all values in this storage.
  306. /// - Throws: An error during the removal of the values.
  307. public func removeAll() throws {
  308. try removeAll(skipCreatingDirectory: false)
  309. }
  310. func removeAll(skipCreatingDirectory: Bool) throws {
  311. try config.fileManager.removeItem(at: directoryURL)
  312. if !skipCreatingDirectory {
  313. try prepareDirectory()
  314. }
  315. }
  316. /// The URL of the cached file with a given computed `key`.
  317. /// - Parameters:
  318. /// - key: The final computed key used when caching the image. Please note that usually this is not
  319. /// the ``Source/cacheKey`` of an image ``Source``. It is the computed key with the processor identifier
  320. /// considered.
  321. /// - forcedExtension: The file extension, if exists.
  322. /// - Returns: The expected file URL on the disk based on the `key` and the `forcedExtension`.
  323. ///
  324. /// This method does not guarantee that an image is already cached at the returned URL. It just provides the URL
  325. /// where the image should be if it exists in the disk storage, with the given key and file extension.
  326. ///
  327. public func cacheFileURL(forKey key: String, forcedExtension: String? = nil) -> URL {
  328. let fileName = cacheFileName(forKey: key, forcedExtension: forcedExtension)
  329. return directoryURL.appendingPathComponent(fileName, isDirectory: false)
  330. }
  331. func cacheFileName(forKey key: String, forcedExtension: String? = nil) -> String {
  332. // TODO: Bad code... Consider refactoring.
  333. if config.usesHashedFileName {
  334. let hashedKey = key.kf.sha256
  335. if let ext = forcedExtension ?? config.pathExtension {
  336. return "\(hashedKey).\(ext)"
  337. } else if config.autoExtAfterHashedFileName,
  338. let ext = forcedExtension ?? key.kf.ext {
  339. return "\(hashedKey).\(ext)"
  340. }
  341. return hashedKey
  342. } else {
  343. if let ext = forcedExtension ?? config.pathExtension {
  344. return "\(key).\(ext)"
  345. }
  346. return key
  347. }
  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. }