2
0

DiskStorage.swift 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678
  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. // TODO: Bad code... Consider refactoring.
  335. if config.usesHashedFileName {
  336. let hashedKey = key.kf.sha256
  337. if let ext = forcedExtension ?? config.pathExtension {
  338. return "\(hashedKey).\(ext)"
  339. } else if config.autoExtAfterHashedFileName,
  340. let ext = forcedExtension ?? key.kf.ext {
  341. return "\(hashedKey).\(ext)"
  342. }
  343. return hashedKey
  344. } else {
  345. if let ext = forcedExtension ?? config.pathExtension {
  346. return "\(key).\(ext)"
  347. }
  348. return key
  349. }
  350. }
  351. func allFileURLs(for propertyKeys: [URLResourceKey]) throws -> [URL] {
  352. let fileManager = config.fileManager
  353. guard let directoryEnumerator = fileManager.enumerator(
  354. at: directoryURL, includingPropertiesForKeys: propertyKeys, options: .skipsHiddenFiles) else
  355. {
  356. throw KingfisherError.cacheError(reason: .fileEnumeratorCreationFailed(url: directoryURL))
  357. }
  358. guard let urls = directoryEnumerator.allObjects as? [URL] else {
  359. throw KingfisherError.cacheError(reason: .invalidFileEnumeratorContent(url: directoryURL))
  360. }
  361. return urls
  362. }
  363. /// Removes all expired 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. public func removeExpiredValues() throws -> [URL] {
  367. return try removeExpiredValues(referenceDate: Date())
  368. }
  369. func removeExpiredValues(referenceDate: Date) throws -> [URL] {
  370. let propertyKeys: [URLResourceKey] = [
  371. .isDirectoryKey,
  372. .contentModificationDateKey
  373. ]
  374. let urls = try allFileURLs(for: propertyKeys)
  375. let keys = Set(propertyKeys)
  376. let expiredFiles = urls.filter { fileURL in
  377. do {
  378. let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
  379. if meta.isDirectory {
  380. return false
  381. }
  382. return meta.expired(referenceDate: referenceDate)
  383. } catch {
  384. return true
  385. }
  386. }
  387. try expiredFiles.forEach { url in
  388. try removeFile(at: url)
  389. }
  390. return expiredFiles
  391. }
  392. /// Removes all size-exceeded values from this storage.
  393. /// - Throws: A file manager error during the removal of the file.
  394. /// - Returns: The URLs for the removed files.
  395. ///
  396. /// This method checks ``DiskStorage/Config/sizeLimit`` and removes cached files in an LRU
  397. /// (Least Recently Used) way.
  398. public func removeSizeExceededValues() throws -> [URL] {
  399. if config.sizeLimit == 0 { return [] } // Back compatible. 0 means no limit.
  400. var size = try totalSize()
  401. if size < config.sizeLimit { return [] }
  402. let propertyKeys: [URLResourceKey] = [
  403. .isDirectoryKey,
  404. .creationDateKey,
  405. .fileSizeKey
  406. ]
  407. let keys = Set(propertyKeys)
  408. let urls = try allFileURLs(for: propertyKeys)
  409. var pendings: [FileMeta] = urls.compactMap { fileURL in
  410. guard let meta = try? FileMeta(fileURL: fileURL, resourceKeys: keys) else {
  411. return nil
  412. }
  413. return meta
  414. }
  415. // Sort by last access date. Most recent file first.
  416. pendings.sort(by: FileMeta.lastAccessDate)
  417. var removed: [URL] = []
  418. let target = config.sizeLimit / 2
  419. while size > target, let meta = pendings.popLast() {
  420. size -= UInt(meta.fileSize)
  421. try removeFile(at: meta.url)
  422. removed.append(meta.url)
  423. }
  424. return removed
  425. }
  426. /// Gets the total file size of the cache folder in bytes.
  427. public func totalSize() throws -> UInt {
  428. let propertyKeys: [URLResourceKey] = [.fileSizeKey]
  429. let urls = try allFileURLs(for: propertyKeys)
  430. let keys = Set(propertyKeys)
  431. let totalSize: UInt = urls.reduce(0) { size, fileURL in
  432. do {
  433. let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
  434. return size + UInt(meta.fileSize)
  435. } catch {
  436. return size
  437. }
  438. }
  439. return totalSize
  440. }
  441. }
  442. }
  443. extension DiskStorage {
  444. /// Represents the configuration used in a ``DiskStorage/Backend``.
  445. public struct Config: @unchecked Sendable {
  446. /// The file size limit on disk of the storage in bytes.
  447. ///
  448. /// `0` means no limit.
  449. public var sizeLimit: UInt
  450. /// The `StorageExpiration` used in this disk storage.
  451. ///
  452. /// The default is `.days(7)`, which means that the disk cache will expire in one week if not accessed anymore.
  453. public var expiration: StorageExpiration = .days(7)
  454. /// The preferred extension of the cache item. It will be appended to the file name as its extension.
  455. ///
  456. /// The default is `nil`, which means that the cache file does not contain a file extension.
  457. public var pathExtension: String? = nil
  458. /// Whether the cache file name will be hashed before storing.
  459. ///
  460. /// The default is `true`, which means that file name is hashed to protect user information (for example, the
  461. /// original download URL which is used as the cache key).
  462. public var usesHashedFileName = true
  463. /// Whether the image extension will be extracted from the original file name and appended to the hashed file
  464. /// name, which will be used as the cache key on disk.
  465. ///
  466. /// The default is `false`.
  467. public var autoExtAfterHashedFileName = false
  468. /// A closure that takes in the initial directory path and generates the final disk cache path.
  469. ///
  470. /// You can use it to fully customize your cache path.
  471. public var cachePathBlock: (@Sendable (_ directory: URL, _ cacheName: String) -> URL)! = {
  472. (directory, cacheName) in
  473. return directory.appendingPathComponent(cacheName, isDirectory: true)
  474. }
  475. /// The desired name of the disk cache.
  476. ///
  477. /// This name will be used as a part of the cache folder name by default.
  478. public let name: String
  479. let fileManager: FileManager
  480. let directory: URL?
  481. /// Creates a config value based on the given parameters.
  482. ///
  483. /// - Parameters:
  484. /// - name: The name of the cache. It is used as part of the storage folder and to identify the disk storage.
  485. /// Two storages with the same `name` would share the same folder on the disk, and this should be prevented.
  486. /// - sizeLimit: The size limit in bytes for all existing files in the disk storage.
  487. /// - fileManager: The `FileManager` used to manipulate files on the disk. The default is `FileManager.default`.
  488. /// - directory: The URL where the disk storage should reside. The storage will use this as the root folder,
  489. /// and append a path that is constructed by the input `name`. The default is `nil`, indicating that
  490. /// the cache directory under the user domain mask will be used.
  491. public init(
  492. name: String,
  493. sizeLimit: UInt,
  494. fileManager: FileManager = .default,
  495. directory: URL? = nil)
  496. {
  497. self.name = name
  498. self.fileManager = fileManager
  499. self.directory = directory
  500. self.sizeLimit = sizeLimit
  501. }
  502. }
  503. }
  504. extension DiskStorage {
  505. struct FileMeta {
  506. let url: URL
  507. let lastAccessDate: Date?
  508. let estimatedExpirationDate: Date?
  509. let isDirectory: Bool
  510. let fileSize: Int
  511. static func lastAccessDate(lhs: FileMeta, rhs: FileMeta) -> Bool {
  512. return lhs.lastAccessDate ?? .distantPast > rhs.lastAccessDate ?? .distantPast
  513. }
  514. init(fileURL: URL, resourceKeys: Set<URLResourceKey>) throws {
  515. let meta = try fileURL.resourceValues(forKeys: resourceKeys)
  516. self.init(
  517. fileURL: fileURL,
  518. lastAccessDate: meta.creationDate,
  519. estimatedExpirationDate: meta.contentModificationDate,
  520. isDirectory: meta.isDirectory ?? false,
  521. fileSize: meta.fileSize ?? 0)
  522. }
  523. init(
  524. fileURL: URL,
  525. lastAccessDate: Date?,
  526. estimatedExpirationDate: Date?,
  527. isDirectory: Bool,
  528. fileSize: Int)
  529. {
  530. self.url = fileURL
  531. self.lastAccessDate = lastAccessDate
  532. self.estimatedExpirationDate = estimatedExpirationDate
  533. self.isDirectory = isDirectory
  534. self.fileSize = fileSize
  535. }
  536. func expired(referenceDate: Date) -> Bool {
  537. return estimatedExpirationDate?.isPast(referenceDate: referenceDate) ?? true
  538. }
  539. func extendExpiration(with fileManager: FileManager, extendingExpiration: ExpirationExtending) {
  540. guard let lastAccessDate = lastAccessDate,
  541. let lastEstimatedExpiration = estimatedExpirationDate else
  542. {
  543. return
  544. }
  545. let attributes: [FileAttributeKey : Any]
  546. switch extendingExpiration {
  547. case .none:
  548. // not extending expiration time here
  549. return
  550. case .cacheTime:
  551. let originalExpiration: StorageExpiration =
  552. .seconds(lastEstimatedExpiration.timeIntervalSince(lastAccessDate))
  553. attributes = [
  554. .creationDate: Date().fileAttributeDate,
  555. .modificationDate: originalExpiration.estimatedExpirationSinceNow.fileAttributeDate
  556. ]
  557. case .expirationTime(let expirationTime):
  558. attributes = [
  559. .creationDate: Date().fileAttributeDate,
  560. .modificationDate: expirationTime.estimatedExpirationSinceNow.fileAttributeDate
  561. ]
  562. }
  563. try? fileManager.setAttributes(attributes, ofItemAtPath: url.path)
  564. }
  565. }
  566. }
  567. extension DiskStorage {
  568. struct Creation {
  569. let directoryURL: URL
  570. let cacheName: String
  571. init(_ config: Config) {
  572. let url: URL
  573. if let directory = config.directory {
  574. url = directory
  575. } else {
  576. url = config.fileManager.urls(for: .cachesDirectory, in: .userDomainMask)[0]
  577. }
  578. cacheName = "com.onevcat.Kingfisher.ImageCache.\(config.name)"
  579. directoryURL = config.cachePathBlock(url, cacheName)
  580. }
  581. }
  582. }
  583. fileprivate extension Error {
  584. var isFolderMissing: Bool {
  585. let nsError = self as NSError
  586. guard nsError.domain == NSCocoaErrorDomain, nsError.code == 4 else {
  587. return false
  588. }
  589. guard let underlyingError = nsError.userInfo[NSUnderlyingErrorKey] as? NSError else {
  590. return false
  591. }
  592. guard underlyingError.domain == NSPOSIXErrorDomain, underlyingError.code == 2 else {
  593. return false
  594. }
  595. return true
  596. }
  597. }