DiskStorage.swift 15 KB

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