DiskStorage.swift 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407
  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. /// Creates a disk storage with the given `DiskStorage.Config`.
  44. ///
  45. /// - Parameter config: The config used for this disk storage.
  46. /// - Throws: An error if the folder for storage cannot be got or created.
  47. public init(config: Config) throws {
  48. self.config = config
  49. let url: URL
  50. if let directory = config.directory {
  51. url = directory
  52. } else {
  53. url = try config.fileManager.url(
  54. for: .cachesDirectory,
  55. in: .userDomainMask,
  56. appropriateFor: nil,
  57. create: true)
  58. }
  59. let cacheName = "com.onevcat.Kingfisher.ImageCache.\(config.name)"
  60. directoryURL = config.cachePathBlock(url, cacheName)
  61. metaChangingQueue = DispatchQueue(label: cacheName)
  62. try prepareDirectory()
  63. }
  64. // Creates the storage folder.
  65. func prepareDirectory() throws {
  66. let fileManager = config.fileManager
  67. let path = directoryURL.path
  68. guard !fileManager.fileExists(atPath: path) else { return }
  69. do {
  70. try fileManager.createDirectory(
  71. atPath: path,
  72. withIntermediateDirectories: true,
  73. attributes: nil)
  74. } catch {
  75. throw KingfisherError.cacheError(reason: .cannotCreateDirectory(path: path, error: error))
  76. }
  77. }
  78. func store(
  79. value: T,
  80. forKey key: String,
  81. expiration: StorageExpiration? = nil) throws
  82. {
  83. let expiration = expiration ?? config.expiration
  84. // The expiration indicates that already expired, no need to store.
  85. guard !expiration.isExpired else { return }
  86. let data: Data
  87. do {
  88. data = try value.toData()
  89. } catch {
  90. throw KingfisherError.cacheError(reason: .cannotConvertToData(object: value, error: error))
  91. }
  92. let fileURL = cacheFileURL(forKey: key)
  93. let now = Date()
  94. let attributes: [FileAttributeKey : Any] = [
  95. // The last access date.
  96. .creationDate: now.fileAttributeDate,
  97. // The estimated expiration date.
  98. .modificationDate: expiration.estimatedExpirationSinceNow.fileAttributeDate
  99. ]
  100. config.fileManager.createFile(atPath: fileURL.path, contents: data, attributes: attributes)
  101. }
  102. func value(forKey key: String) throws -> T? {
  103. return try value(forKey: key, referenceDate: Date(), actuallyLoad: true)
  104. }
  105. func value(forKey key: String, referenceDate: Date, actuallyLoad: Bool) throws -> T? {
  106. let fileManager = config.fileManager
  107. let fileURL = cacheFileURL(forKey: key)
  108. let filePath = fileURL.path
  109. guard fileManager.fileExists(atPath: filePath) else {
  110. return nil
  111. }
  112. let meta: FileMeta
  113. do {
  114. let resourceKeys: Set<URLResourceKey> = [.contentModificationDateKey, .creationDateKey]
  115. meta = try FileMeta(fileURL: fileURL, resourceKeys: resourceKeys)
  116. } catch {
  117. throw KingfisherError.cacheError(
  118. reason: .invalidURLResource(error: error, key: key, url: fileURL))
  119. }
  120. if meta.expired(referenceDate: referenceDate) {
  121. return nil
  122. }
  123. if !actuallyLoad { return T.empty }
  124. do {
  125. let data = try Data(contentsOf: fileURL)
  126. let obj = try T.fromData(data)
  127. metaChangingQueue.async { meta.extendExpiration(with: fileManager) }
  128. return obj
  129. } catch {
  130. throw KingfisherError.cacheError(reason: .cannotLoadDataFromDisk(url: fileURL, error: error))
  131. }
  132. }
  133. func isCached(forKey key: String) -> Bool {
  134. return isCached(forKey: key, referenceDate: Date())
  135. }
  136. func isCached(forKey key: String, referenceDate: Date) -> Bool {
  137. do {
  138. guard let _ = try value(forKey: key, referenceDate: referenceDate, actuallyLoad: false) else {
  139. return false
  140. }
  141. return true
  142. } catch {
  143. return false
  144. }
  145. }
  146. func remove(forKey key: String) throws {
  147. let fileURL = cacheFileURL(forKey: key)
  148. try removeFile(at: fileURL)
  149. }
  150. func removeFile(at url: URL) throws {
  151. try config.fileManager.removeItem(at: url)
  152. }
  153. func removeAll() throws {
  154. try removeAll(skipCreatingDirectory: false)
  155. }
  156. func removeAll(skipCreatingDirectory: Bool) throws {
  157. try config.fileManager.removeItem(at: directoryURL)
  158. if !skipCreatingDirectory {
  159. try prepareDirectory()
  160. }
  161. }
  162. func cacheFileURL(forKey key: String) -> URL {
  163. let fileName = cacheFileName(forKey: key)
  164. return directoryURL.appendingPathComponent(fileName)
  165. }
  166. func cacheFileName(forKey key: String) -> String {
  167. let hashedKey = key.kf.md5
  168. if let ext = config.pathExtension {
  169. return "\(hashedKey).\(ext)"
  170. }
  171. return hashedKey
  172. }
  173. func allFileURLs(for propertyKeys: [URLResourceKey]) throws -> [URL] {
  174. let fileManager = config.fileManager
  175. guard let directoryEnumerator = fileManager.enumerator(
  176. at: directoryURL, includingPropertiesForKeys: propertyKeys, options: .skipsHiddenFiles) else
  177. {
  178. throw KingfisherError.cacheError(reason: .fileEnumeratorCreationFailed(url: directoryURL))
  179. }
  180. guard let urls = directoryEnumerator.allObjects as? [URL] else {
  181. throw KingfisherError.cacheError(reason: .invalidFileEnumeratorContent(url: directoryURL))
  182. }
  183. return urls
  184. }
  185. func removeExpiredValues(referenceDate: Date = Date()) throws -> [URL] {
  186. let propertyKeys: [URLResourceKey] = [
  187. .isDirectoryKey,
  188. .contentModificationDateKey
  189. ]
  190. let urls = try allFileURLs(for: propertyKeys)
  191. let keys = Set(propertyKeys)
  192. let expiredFiles = urls.filter { fileURL in
  193. do {
  194. let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
  195. if meta.isDirectory {
  196. return false
  197. }
  198. return meta.expired(referenceDate: referenceDate)
  199. } catch {
  200. return true
  201. }
  202. }
  203. try expiredFiles.forEach { url in
  204. try removeFile(at: url)
  205. }
  206. return expiredFiles
  207. }
  208. func removeSizeExceededValues() throws -> [URL] {
  209. if config.sizeLimit == 0 { return [] } // Back compatible. 0 means no limit.
  210. var size = try totalSize()
  211. if size < config.sizeLimit { return [] }
  212. let propertyKeys: [URLResourceKey] = [
  213. .isDirectoryKey,
  214. .creationDateKey,
  215. .fileSizeKey
  216. ]
  217. let keys = Set(propertyKeys)
  218. let urls = try allFileURLs(for: propertyKeys)
  219. var pendings: [FileMeta] = urls.compactMap { fileURL in
  220. guard let meta = try? FileMeta(fileURL: fileURL, resourceKeys: keys) else {
  221. return nil
  222. }
  223. return meta
  224. }
  225. // Sort by last access date. Most recent file first.
  226. pendings.sort(by: FileMeta.lastAccessDate)
  227. var removed: [URL] = []
  228. let target = config.sizeLimit / 2
  229. while size > target, let meta = pendings.popLast() {
  230. size -= UInt(meta.fileSize)
  231. try removeFile(at: meta.url)
  232. removed.append(meta.url)
  233. }
  234. return removed
  235. }
  236. /// Get the total file size of the folder in bytes.
  237. func totalSize() throws -> UInt {
  238. let propertyKeys: [URLResourceKey] = [.fileSizeKey]
  239. let urls = try allFileURLs(for: propertyKeys)
  240. let keys = Set(propertyKeys)
  241. let totalSize: UInt = urls.reduce(0) { size, fileURL in
  242. do {
  243. let meta = try FileMeta(fileURL: fileURL, resourceKeys: keys)
  244. return size + UInt(meta.fileSize)
  245. } catch {
  246. return size
  247. }
  248. }
  249. return totalSize
  250. }
  251. }
  252. }
  253. extension DiskStorage {
  254. /// Represents the config used in a `DiskStorage`.
  255. public struct Config {
  256. /// The file size limit on disk of the storage in bytes. 0 means no limit.
  257. public var sizeLimit: UInt
  258. /// The `StorageExpiration` used in this disk storage. Default is `.days(7)`,
  259. /// means that the disk cache would expire in one week.
  260. public var expiration: StorageExpiration = .days(7)
  261. /// The preferred extension of cache item. It will be appended to the file name as its extension.
  262. /// Default is `nil`, means that the cache file does not contain a file extension.
  263. public var pathExtension: String? = nil
  264. let name: String
  265. let fileManager: FileManager
  266. let directory: URL?
  267. var cachePathBlock: ((_ directory: URL, _ cacheName: String) -> URL)! = {
  268. (directory, cacheName) in
  269. return directory.appendingPathComponent(cacheName, isDirectory: true)
  270. }
  271. /// Creates a config value based on given parameters.
  272. ///
  273. /// - Parameters:
  274. /// - name: The name of cache. It is used as a part of storage folder. It is used to identify the disk
  275. /// storage. Two storages with the same `name` would share the same folder in disk, and it should
  276. /// be prevented.
  277. /// - sizeLimit: The size limit in bytes for all existing files in the disk storage.
  278. /// - fileManager: The `FileManager` used to manipulate files on disk. Default is `FileManager.default`.
  279. /// - directory: The URL where the disk storage should live. The storage will use this as the root folder,
  280. /// and append a path which is constructed by input `name`. Default is `nil`, indicates that
  281. /// the cache directory under user domain mask will be used.
  282. public init(
  283. name: String,
  284. sizeLimit: UInt,
  285. fileManager: FileManager = .default,
  286. directory: URL? = nil)
  287. {
  288. self.name = name
  289. self.fileManager = fileManager
  290. self.directory = directory
  291. self.sizeLimit = sizeLimit
  292. }
  293. }
  294. }
  295. extension DiskStorage {
  296. struct FileMeta {
  297. let url: URL
  298. let lastAccessDate: Date?
  299. let estimatedExpirationDate: Date?
  300. let isDirectory: Bool
  301. let fileSize: Int
  302. static func lastAccessDate(lhs: FileMeta, rhs: FileMeta) -> Bool {
  303. return lhs.lastAccessDate ?? .distantPast > rhs.lastAccessDate ?? .distantPast
  304. }
  305. init(fileURL: URL, resourceKeys: Set<URLResourceKey>) throws {
  306. let meta = try fileURL.resourceValues(forKeys: resourceKeys)
  307. self.init(
  308. fileURL: fileURL,
  309. lastAccessDate: meta.creationDate,
  310. estimatedExpirationDate: meta.contentModificationDate,
  311. isDirectory: meta.isDirectory ?? false,
  312. fileSize: meta.fileSize ?? 0)
  313. }
  314. init(
  315. fileURL: URL,
  316. lastAccessDate: Date?,
  317. estimatedExpirationDate: Date?,
  318. isDirectory: Bool,
  319. fileSize: Int)
  320. {
  321. self.url = fileURL
  322. self.lastAccessDate = lastAccessDate
  323. self.estimatedExpirationDate = estimatedExpirationDate
  324. self.isDirectory = isDirectory
  325. self.fileSize = fileSize
  326. }
  327. func expired(referenceDate: Date) -> Bool {
  328. return estimatedExpirationDate?.isPast(referenceDate: referenceDate) ?? true
  329. }
  330. func extendExpiration(with fileManager: FileManager) {
  331. guard let lastAccessDate = lastAccessDate,
  332. let lastEstimatedExpiration = estimatedExpirationDate else
  333. {
  334. return
  335. }
  336. let originalExpiration: StorageExpiration =
  337. .seconds(lastEstimatedExpiration.timeIntervalSince(lastAccessDate))
  338. let attributes: [FileAttributeKey : Any] = [
  339. .creationDate: Date().fileAttributeDate,
  340. .modificationDate: originalExpiration.estimatedExpirationSinceNow.fileAttributeDate
  341. ]
  342. try? fileManager.setAttributes(attributes, ofItemAtPath: url.path)
  343. }
  344. }
  345. }