DiskStorage.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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. public class DiskStorage<T: DataTransformable> {
  28. public struct Config {
  29. let name: String
  30. let fileManager: FileManager
  31. let directory: URL?
  32. public var expiration: StorageExpiration
  33. var cachePathBlock: ((_ directory: URL, _ cacheName: String) -> URL)! = {
  34. (directory, cacheName) in
  35. return directory.appendingPathComponent(cacheName, isDirectory: true)
  36. }
  37. var pathExtension: String?
  38. var sizeLimit: Int
  39. init(
  40. name: String,
  41. fileManager: FileManager = .default,
  42. directory: URL? = nil,
  43. expiration: StorageExpiration = .days(7),
  44. pathExtension: String? = nil,
  45. sizeLimit: Int)
  46. {
  47. self.name = name
  48. self.fileManager = fileManager
  49. self.directory = directory
  50. self.expiration = expiration
  51. self.pathExtension = pathExtension
  52. self.sizeLimit = sizeLimit
  53. }
  54. }
  55. var config: Config
  56. let directoryURL: URL
  57. let onFileRemoved = Delegate<URL, Void>()
  58. let onCacheRemoved = Delegate<(), Void>()
  59. init(config: Config) throws {
  60. self.config = config
  61. let url: URL
  62. if let directory = config.directory {
  63. url = directory
  64. } else {
  65. url = try config.fileManager.url(
  66. for: .cachesDirectory,
  67. in: .userDomainMask,
  68. appropriateFor: nil,
  69. create: true)
  70. }
  71. let cacheName = "com.onevcat.Kingfisher.ImageCache.\(config.name)"
  72. directoryURL = config.cachePathBlock(url, cacheName)
  73. try prepareDirectory()
  74. }
  75. func prepareDirectory() throws {
  76. let fileManager = config.fileManager
  77. let path = directoryURL.path
  78. guard !config.fileManager.fileExists(atPath: path) else { return }
  79. do {
  80. try fileManager.createDirectory(
  81. atPath: path,
  82. withIntermediateDirectories: true,
  83. attributes: nil)
  84. } catch {
  85. throw KingfisherError.cacheError(reason: .cannotCreateDirectory(path: path, error: error))
  86. }
  87. }
  88. func store(
  89. value: T,
  90. forKey key: String,
  91. expiration: StorageExpiration? = nil) throws
  92. {
  93. let object = StorageObject(value, expiration: expiration ?? config.expiration)
  94. let data: Data
  95. do {
  96. data = try value.toData()
  97. } catch {
  98. throw KingfisherError.cacheError(reason: .cannotConvertToData(object: value, error: error))
  99. }
  100. let fileURL = cacheFileURL(forKey: key)
  101. let now = Date()
  102. let attributes: [FileAttributeKey : Any] = [
  103. .creationDate: now,
  104. .modificationDate: object.estimatedExpiration
  105. ]
  106. config.fileManager.createFile(atPath: fileURL.path, contents: data, attributes: attributes)
  107. }
  108. func value(forKey key: String) throws -> T? {
  109. return try value(forKey: key, actuallyLoad: true)
  110. }
  111. func value(forKey key: String, actuallyLoad: Bool) throws -> T? {
  112. let fileManager = config.fileManager
  113. let fileURL = cacheFileURL(forKey: key)
  114. let filePath = fileURL.path
  115. guard fileManager.fileExists(atPath: filePath) else {
  116. return nil
  117. }
  118. let resourceKeys: Set<URLResourceKey> = [.contentModificationDateKey]
  119. do {
  120. let meta = try fileURL.resourceValues(forKeys: resourceKeys)
  121. guard let expiration = meta.contentModificationDate, expiration.isFuture else {
  122. return nil
  123. }
  124. if actuallyLoad {
  125. do {
  126. let data = try Data(contentsOf: fileURL)
  127. return try T.fromData(data)
  128. } catch {
  129. throw KingfisherError.cacheError(reason: .cannotLoadDataFromDisk(url: fileURL, error: error))
  130. }
  131. } else {
  132. return T.empty
  133. }
  134. } catch {
  135. throw KingfisherError.cacheError(
  136. reason: .invalidURLResource(error: error, key: key, url: fileURL, resourceKeys: resourceKeys))
  137. }
  138. }
  139. func isCached(forKey key: String) -> Bool {
  140. do {
  141. guard let _ = try value(forKey: key, actuallyLoad: false) else { return false }
  142. return true
  143. } catch {
  144. return false
  145. }
  146. }
  147. func extendExpriration(forKey key: String, lastAccessDate: Date, nextExpiration: StorageExpiration) throws {
  148. let fileURL = cacheFileURL(forKey: key)
  149. let attributes: [FileAttributeKey : Any] = [
  150. .creationDate: lastAccessDate,
  151. .modificationDate: nextExpiration.dateSince(lastAccessDate)
  152. ]
  153. try config.fileManager.setAttributes(attributes, ofItemAtPath: fileURL.path)
  154. }
  155. func remove(forKey key: String) throws {
  156. let fileURL = cacheFileURL(forKey: key)
  157. try removeFile(at: fileURL)
  158. }
  159. func removeFile(at url: URL) throws {
  160. try config.fileManager.removeItem(at: url)
  161. onFileRemoved.call(url)
  162. }
  163. func removeAll() throws {
  164. try removeAll(skipCreatingDirectory: false)
  165. }
  166. func removeAll(skipCreatingDirectory: Bool) throws {
  167. try config.fileManager.removeItem(at: directoryURL)
  168. onCacheRemoved.call()
  169. if !skipCreatingDirectory {
  170. try prepareDirectory()
  171. }
  172. }
  173. func cacheFileURL(forKey key: String) -> URL {
  174. let fileName = cacheFileName(forKey: key)
  175. return directoryURL.appendingPathComponent(fileName)
  176. }
  177. func cacheFileName(forKey key: String) -> String {
  178. let hashedKey = key.kf.md5
  179. if let ext = config.pathExtension {
  180. return "\(hashedKey).\(ext)"
  181. }
  182. return hashedKey
  183. }
  184. func allFileURLs(for propertyKeys: [URLResourceKey]) throws -> [URL] {
  185. let fileManager = config.fileManager
  186. guard let directoryEnumerator = fileManager.enumerator(
  187. at: directoryURL, includingPropertiesForKeys: propertyKeys, options: .skipsHiddenFiles) else
  188. {
  189. throw KingfisherError.cacheError(reason: .fileEnumeratorCreationFailed(url: directoryURL))
  190. }
  191. guard let urls = directoryEnumerator.allObjects as? [URL] else {
  192. throw KingfisherError.cacheError(reason: .invalidFileEnumeratorContent(url: directoryURL))
  193. }
  194. return urls
  195. }
  196. func removeExpiredValues() throws -> [URL] {
  197. let propertyKeys: [URLResourceKey] = [
  198. .isDirectoryKey,
  199. .contentModificationDateKey
  200. ]
  201. let urls = try allFileURLs(for: propertyKeys)
  202. let keys = Set(propertyKeys)
  203. let expiredFiles = urls.filter { fileURL in
  204. do {
  205. let resourceValues = try fileURL.resourceValues(forKeys: keys)
  206. if resourceValues.isDirectory == true {
  207. return false
  208. }
  209. if let modificationDate = resourceValues.contentModificationDate {
  210. return modificationDate.isPast
  211. }
  212. return true
  213. } catch {
  214. return true
  215. }
  216. }
  217. try expiredFiles.forEach { url in
  218. try removeFile(at: url)
  219. }
  220. return expiredFiles
  221. }
  222. func removeSizeExceededValues() throws -> [URL] {
  223. if config.sizeLimit == 0 { return [] } // Back compatible. 0 means no limit.
  224. var size = try totalSize()
  225. if size < config.sizeLimit { return [] }
  226. let propertyKeys: [URLResourceKey] = [
  227. .isDirectoryKey,
  228. .creationDateKey,
  229. .totalFileAllocatedSizeKey
  230. ]
  231. let keys = Set(propertyKeys)
  232. let urls = try allFileURLs(for: propertyKeys)
  233. var pendings: [(url: URL, meta: URLResourceValues)] = urls.compactMap { fileURL in
  234. guard let resourceValues = try? fileURL.resourceValues(forKeys: keys) else {
  235. return nil
  236. }
  237. return (url: fileURL, meta: resourceValues)
  238. }
  239. let distancePast = Date.distantPast
  240. pendings.sort {
  241. $0.meta.creationDate ?? distancePast > $1.meta.creationDate ?? distancePast
  242. }
  243. var removed: [URL] = []
  244. let target = config.sizeLimit / 2
  245. while size >= target, let item = pendings.popLast() {
  246. size -= UInt(item.meta.totalFileAllocatedSize ?? 0)
  247. try removeFile(at: item.url)
  248. removed.append(item.url)
  249. }
  250. return removed
  251. }
  252. func totalSize() throws -> UInt {
  253. let propertyKeys: [URLResourceKey] = [
  254. .isDirectoryKey,
  255. .totalFileAllocatedSizeKey
  256. ]
  257. let urls = try allFileURLs(for: propertyKeys)
  258. let keys = Set(propertyKeys)
  259. let totalSize: UInt = urls.reduce(0) { size, fileURL in
  260. do {
  261. let resourceValues = try fileURL.resourceValues(forKeys: keys)
  262. return size + UInt(resourceValues.totalFileAllocatedSize ?? 0)
  263. } catch {
  264. return size
  265. }
  266. }
  267. return totalSize
  268. }
  269. }