DiskStorage.swift 10 KB

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