DiskStorage.swift 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497
  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 a set of conception related to storage which stores a certain type of value in disk.
  28. /// This is a namespace for the disk storage types. A `Backend` with a certain `Config` will be used to describe the
  29. /// storage. See these composed types for more information.
  30. public enum DiskStorage {
  31. /// Represents a storage back-end for the `DiskStorage`. The value is serialized to data
  32. /// and stored as file in the file system under a specified location.
  33. ///
  34. /// You can config a `DiskStorage.Backend` in its initializer by passing a `DiskStorage.Config` value.
  35. /// or modifying the `config` property after it being created. `DiskStorage` will use file's attributes to keep
  36. /// track of a file for its expiration or size limitation.
  37. public class Backend<T: DataTransformable> {
  38. /// The config used for this disk storage.
  39. public var config: Config
  40. // The final storage URL on disk, with `name` and `cachePathBlock` considered.
  41. public let directoryURL: URL
  42. let metaChangingQueue: DispatchQueue
  43. var maybeCached : Set<String>?
  44. let maybeCachedCheckingQueue = DispatchQueue(label: "com.onevcat.Kingfisher.maybeCachedCheckingQueue")
  45. /// Creates a disk storage with the given `DiskStorage.Config`.
  46. ///
  47. /// - Parameter config: The config used for this disk storage.
  48. /// - Throws: An error if the folder for storage cannot be got or created.
  49. public init(config: Config) throws {
  50. var config = config
  51. let url: URL
  52. if let directory = config.directory {
  53. url = directory
  54. } else {
  55. url = try config.fileManager.url(
  56. for: .cachesDirectory,
  57. in: .userDomainMask,
  58. appropriateFor: nil,
  59. create: true)
  60. }
  61. let cacheName = "com.onevcat.Kingfisher.ImageCache.\(config.name)"
  62. directoryURL = config.cachePathBlock(url, cacheName)
  63. // Break any possible retain cycle set by outside.
  64. config.cachePathBlock = nil
  65. self.config = config
  66. metaChangingQueue = DispatchQueue(label: cacheName)
  67. try prepareDirectory()
  68. maybeCachedCheckingQueue.async {
  69. do {
  70. self.maybeCached = Set()
  71. try config.fileManager.contentsOfDirectory(atPath: self.directoryURL.path).forEach { fileName in
  72. self.maybeCached?.insert(fileName)
  73. }
  74. } catch {
  75. // Just disable the functionality if we fail to initialize it properly. This will just revert to
  76. // the behavior which is to check file existence on disk directly.
  77. self.maybeCached = nil
  78. }
  79. }
  80. }
  81. // Creates the storage folder.
  82. func prepareDirectory() throws {
  83. let fileManager = config.fileManager
  84. let path = directoryURL.path
  85. guard !fileManager.fileExists(atPath: path) else { return }
  86. do {
  87. try fileManager.createDirectory(
  88. atPath: path,
  89. withIntermediateDirectories: true,
  90. attributes: nil)
  91. } catch {
  92. throw KingfisherError.cacheError(reason: .cannotCreateDirectory(path: path, error: error))
  93. }
  94. }
  95. func store(
  96. value: T,
  97. forKey key: String,
  98. expiration: StorageExpiration? = nil) throws
  99. {
  100. let expiration = expiration ?? config.expiration
  101. // The expiration indicates that already expired, no need to store.
  102. guard !expiration.isExpired else { return }
  103. let data: Data
  104. do {
  105. data = try value.toData()
  106. } catch {
  107. throw KingfisherError.cacheError(reason: .cannotConvertToData(object: value, error: error))
  108. }
  109. let fileURL = cacheFileURL(forKey: key)
  110. do {
  111. try data.write(to: fileURL)
  112. } catch {
  113. throw KingfisherError.cacheError(
  114. reason: .cannotCreateCacheFile(fileURL: fileURL, key: key, data: data, error: error)
  115. )
  116. }
  117. let now = Date()
  118. let attributes: [FileAttributeKey : Any] = [
  119. // The last access date.
  120. .creationDate: now.fileAttributeDate,
  121. // The estimated expiration date.
  122. .modificationDate: expiration.estimatedExpirationSinceNow.fileAttributeDate
  123. ]
  124. do {
  125. try config.fileManager.setAttributes(attributes, ofItemAtPath: fileURL.path)
  126. } catch {
  127. try? config.fileManager.removeItem(at: fileURL)
  128. throw KingfisherError.cacheError(
  129. reason: .cannotSetCacheFileAttribute(
  130. filePath: fileURL.path,
  131. attributes: attributes,
  132. error: error
  133. )
  134. )
  135. }
  136. maybeCachedCheckingQueue.async {
  137. self.maybeCached?.insert(fileURL.lastPathComponent)
  138. }
  139. }
  140. func value(forKey key: String, extendingExpiration: ExpirationExtending = .cacheTime) throws -> T? {
  141. return try value(forKey: key, referenceDate: Date(), actuallyLoad: true, extendingExpiration: extendingExpiration)
  142. }
  143. func value(
  144. forKey key: String,
  145. referenceDate: Date,
  146. actuallyLoad: Bool,
  147. extendingExpiration: ExpirationExtending) throws -> T?
  148. {
  149. let fileManager = config.fileManager
  150. let fileURL = cacheFileURL(forKey: key)
  151. let filePath = fileURL.path
  152. let fileMaybeCached = maybeCachedCheckingQueue.sync {
  153. return maybeCached?.contains(fileURL.lastPathComponent) ?? true
  154. }
  155. guard fileMaybeCached else {
  156. return nil
  157. }
  158. guard fileManager.fileExists(atPath: filePath) else {
  159. return nil
  160. }
  161. let meta: FileMeta
  162. do {
  163. let resourceKeys: Set<URLResourceKey> = [.contentModificationDateKey, .creationDateKey]
  164. meta = try FileMeta(fileURL: fileURL, resourceKeys: resourceKeys)
  165. } catch {
  166. throw KingfisherError.cacheError(
  167. reason: .invalidURLResource(error: error, key: key, url: fileURL))
  168. }
  169. if meta.expired(referenceDate: referenceDate) {
  170. return nil
  171. }
  172. if !actuallyLoad { return T.empty }
  173. do {
  174. let data = try Data(contentsOf: fileURL)
  175. let obj = try T.fromData(data)
  176. metaChangingQueue.async {
  177. meta.extendExpiration(with: fileManager, extendingExpiration: extendingExpiration)
  178. }
  179. return obj
  180. } catch {
  181. throw KingfisherError.cacheError(reason: .cannotLoadDataFromDisk(url: fileURL, error: error))
  182. }
  183. }
  184. func isCached(forKey key: String) -> Bool {
  185. return isCached(forKey: key, referenceDate: Date())
  186. }
  187. func isCached(forKey key: String, referenceDate: Date) -> Bool {
  188. do {
  189. let result = try value(
  190. forKey: key,
  191. referenceDate: referenceDate,
  192. actuallyLoad: false,
  193. extendingExpiration: .none
  194. )
  195. return result != nil
  196. } catch {
  197. return false
  198. }
  199. }
  200. func remove(forKey key: String) throws {
  201. let fileURL = cacheFileURL(forKey: key)
  202. try removeFile(at: fileURL)
  203. }
  204. func removeFile(at url: URL) throws {
  205. try config.fileManager.removeItem(at: url)
  206. }
  207. func removeAll() throws {
  208. try removeAll(skipCreatingDirectory: false)
  209. }
  210. func removeAll(skipCreatingDirectory: Bool) throws {
  211. try config.fileManager.removeItem(at: directoryURL)
  212. if !skipCreatingDirectory {
  213. try prepareDirectory()
  214. }
  215. }
  216. /// The URL of the cached file with a given computed `key`.
  217. ///
  218. /// - Note:
  219. /// This method does not guarantee there is an image already cached in the returned URL. It just gives your
  220. /// the URL that the image should be if it exists in disk storage, with the give key.
  221. ///
  222. /// - Parameter key: The final computed key used when caching the image. Please note that usually this is not
  223. /// the `cacheKey` of an image `Source`. It is the computed key with processor identifier considered.
  224. public func cacheFileURL(forKey key: String) -> URL {
  225. let fileName = cacheFileName(forKey: key)
  226. return directoryURL.appendingPathComponent(fileName, isDirectory: false)
  227. }
  228. func cacheFileName(forKey key: String) -> String {
  229. if config.usesHashedFileName {
  230. let hashedKey = key.kf.md5
  231. if let ext = config.pathExtension {
  232. return "\(hashedKey).\(ext)"
  233. }
  234. return hashedKey
  235. } else {
  236. if let ext = config.pathExtension {
  237. return "\(key).\(ext)"
  238. }
  239. return key
  240. }
  241. }
  242. func allFileURLs(for propertyKeys: [URLResourceKey]) throws -> [URL] {
  243. let fileManager = config.fileManager
  244. guard let directoryEnumerator = fileManager.enumerator(
  245. at: directoryURL, includingPropertiesForKeys: propertyKeys, options: .skipsHiddenFiles) else
  246. {
  247. throw KingfisherError.cacheError(reason: .fileEnumeratorCreationFailed(url: directoryURL))
  248. }
  249. guard let urls = directoryEnumerator.allObjects as? [URL] else {
  250. throw KingfisherError.cacheError(reason: .invalidFileEnumeratorContent(url: directoryURL))
  251. }
  252. return urls
  253. }
  254. func removeExpiredValues(referenceDate: Date = Date()) throws -> [URL] {
  255. let propertyKeys: [URLResourceKey] = [
  256. .isDirectoryKey,
  257. .contentModificationDateKey
  258. ]
  259. let urls = try allFileURLs(for: propertyKeys)
  260. let keys = Set(propertyKeys)
  261. let expiredFiles = urls.filter { fileURL in
  262. do {
  263. let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
  264. if meta.isDirectory {
  265. return false
  266. }
  267. return meta.expired(referenceDate: referenceDate)
  268. } catch {
  269. return true
  270. }
  271. }
  272. try expiredFiles.forEach { url in
  273. try removeFile(at: url)
  274. }
  275. return expiredFiles
  276. }
  277. func removeSizeExceededValues() throws -> [URL] {
  278. if config.sizeLimit == 0 { return [] } // Back compatible. 0 means no limit.
  279. var size = try totalSize()
  280. if size < config.sizeLimit { return [] }
  281. let propertyKeys: [URLResourceKey] = [
  282. .isDirectoryKey,
  283. .creationDateKey,
  284. .fileSizeKey
  285. ]
  286. let keys = Set(propertyKeys)
  287. let urls = try allFileURLs(for: propertyKeys)
  288. var pendings: [FileMeta] = urls.compactMap { fileURL in
  289. guard let meta = try? FileMeta(fileURL: fileURL, resourceKeys: keys) else {
  290. return nil
  291. }
  292. return meta
  293. }
  294. // Sort by last access date. Most recent file first.
  295. pendings.sort(by: FileMeta.lastAccessDate)
  296. var removed: [URL] = []
  297. let target = config.sizeLimit / 2
  298. while size > target, let meta = pendings.popLast() {
  299. size -= UInt(meta.fileSize)
  300. try removeFile(at: meta.url)
  301. removed.append(meta.url)
  302. }
  303. return removed
  304. }
  305. /// Get the total file size of the folder in bytes.
  306. func totalSize() throws -> UInt {
  307. let propertyKeys: [URLResourceKey] = [.fileSizeKey]
  308. let urls = try allFileURLs(for: propertyKeys)
  309. let keys = Set(propertyKeys)
  310. let totalSize: UInt = urls.reduce(0) { size, fileURL in
  311. do {
  312. let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
  313. return size + UInt(meta.fileSize)
  314. } catch {
  315. return size
  316. }
  317. }
  318. return totalSize
  319. }
  320. }
  321. }
  322. extension DiskStorage {
  323. /// Represents the config used in a `DiskStorage`.
  324. public struct Config {
  325. /// The file size limit on disk of the storage in bytes. 0 means no limit.
  326. public var sizeLimit: UInt
  327. /// The `StorageExpiration` used in this disk storage. Default is `.days(7)`,
  328. /// means that the disk cache would expire in one week.
  329. public var expiration: StorageExpiration = .days(7)
  330. /// The preferred extension of cache item. It will be appended to the file name as its extension.
  331. /// Default is `nil`, means that the cache file does not contain a file extension.
  332. public var pathExtension: String? = nil
  333. /// Default is `true`, means that the cache file name will be hashed before storing.
  334. public var usesHashedFileName = true
  335. let name: String
  336. let fileManager: FileManager
  337. let directory: URL?
  338. var cachePathBlock: ((_ directory: URL, _ cacheName: String) -> URL)! = {
  339. (directory, cacheName) in
  340. return directory.appendingPathComponent(cacheName, isDirectory: true)
  341. }
  342. /// Creates a config value based on given parameters.
  343. ///
  344. /// - Parameters:
  345. /// - name: The name of cache. It is used as a part of storage folder. It is used to identify the disk
  346. /// storage. Two storages with the same `name` would share the same folder in disk, and it should
  347. /// be prevented.
  348. /// - sizeLimit: The size limit in bytes for all existing files in the disk storage.
  349. /// - fileManager: The `FileManager` used to manipulate files on disk. Default is `FileManager.default`.
  350. /// - directory: The URL where the disk storage should live. The storage will use this as the root folder,
  351. /// and append a path which is constructed by input `name`. Default is `nil`, indicates that
  352. /// the cache directory under user domain mask will be used.
  353. public init(
  354. name: String,
  355. sizeLimit: UInt,
  356. fileManager: FileManager = .default,
  357. directory: URL? = nil)
  358. {
  359. self.name = name
  360. self.fileManager = fileManager
  361. self.directory = directory
  362. self.sizeLimit = sizeLimit
  363. }
  364. }
  365. }
  366. extension DiskStorage {
  367. struct FileMeta {
  368. let url: URL
  369. let lastAccessDate: Date?
  370. let estimatedExpirationDate: Date?
  371. let isDirectory: Bool
  372. let fileSize: Int
  373. static func lastAccessDate(lhs: FileMeta, rhs: FileMeta) -> Bool {
  374. return lhs.lastAccessDate ?? .distantPast > rhs.lastAccessDate ?? .distantPast
  375. }
  376. init(fileURL: URL, resourceKeys: Set<URLResourceKey>) throws {
  377. let meta = try fileURL.resourceValues(forKeys: resourceKeys)
  378. self.init(
  379. fileURL: fileURL,
  380. lastAccessDate: meta.creationDate,
  381. estimatedExpirationDate: meta.contentModificationDate,
  382. isDirectory: meta.isDirectory ?? false,
  383. fileSize: meta.fileSize ?? 0)
  384. }
  385. init(
  386. fileURL: URL,
  387. lastAccessDate: Date?,
  388. estimatedExpirationDate: Date?,
  389. isDirectory: Bool,
  390. fileSize: Int)
  391. {
  392. self.url = fileURL
  393. self.lastAccessDate = lastAccessDate
  394. self.estimatedExpirationDate = estimatedExpirationDate
  395. self.isDirectory = isDirectory
  396. self.fileSize = fileSize
  397. }
  398. func expired(referenceDate: Date) -> Bool {
  399. return estimatedExpirationDate?.isPast(referenceDate: referenceDate) ?? true
  400. }
  401. func extendExpiration(with fileManager: FileManager, extendingExpiration: ExpirationExtending) {
  402. guard let lastAccessDate = lastAccessDate,
  403. let lastEstimatedExpiration = estimatedExpirationDate else
  404. {
  405. return
  406. }
  407. let attributes: [FileAttributeKey : Any]
  408. switch extendingExpiration {
  409. case .none:
  410. // not extending expiration time here
  411. return
  412. case .cacheTime:
  413. let originalExpiration: StorageExpiration =
  414. .seconds(lastEstimatedExpiration.timeIntervalSince(lastAccessDate))
  415. attributes = [
  416. .creationDate: Date().fileAttributeDate,
  417. .modificationDate: originalExpiration.estimatedExpirationSinceNow.fileAttributeDate
  418. ]
  419. case .expirationTime(let expirationTime):
  420. attributes = [
  421. .creationDate: Date().fileAttributeDate,
  422. .modificationDate: expirationTime.estimatedExpirationSinceNow.fileAttributeDate
  423. ]
  424. }
  425. try? fileManager.setAttributes(attributes, ofItemAtPath: url.path)
  426. }
  427. }
  428. }