DiskStorage.swift 14 KB

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