DiskStorage.swift 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  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 KingfisherError2.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 = try value.toData()
  98. let fileURL = cacheFileURL(forKey: key)
  99. let now = Date()
  100. let attributes: [FileAttributeKey : Any] = [
  101. .creationDate: now,
  102. .modificationDate: object.estimatedExpiration
  103. ]
  104. config.fileManager.createFile(atPath: fileURL.path, contents: data, attributes: attributes)
  105. }
  106. func value(forKey key: String) throws -> T? {
  107. return try value(forKey: key, actuallyLoad: true)
  108. }
  109. func value(forKey key: String, actuallyLoad: Bool) throws -> T? {
  110. let fileManager = config.fileManager
  111. let fileURL = cacheFileURL(forKey: key)
  112. let filePath = fileURL.path
  113. guard fileManager.fileExists(atPath: filePath) else {
  114. return nil
  115. }
  116. let resourceKeys: Set<URLResourceKey> = [.contentModificationDateKey]
  117. do {
  118. let meta = try fileURL.resourceValues(forKeys: resourceKeys)
  119. guard let expiration = meta.contentModificationDate else {
  120. throw KingfisherError2.cacheError(reason: .invalidModificationDate(key: key, url: fileURL))
  121. }
  122. guard expiration.isFuture else {
  123. return nil
  124. }
  125. if actuallyLoad {
  126. let data = try Data(contentsOf: fileURL)
  127. return try T.fromData(data)
  128. } else {
  129. return T.empty
  130. }
  131. } catch {
  132. throw KingfisherError2.cacheError(
  133. reason: .invalidURLResource(error: error, key: key, url: fileURL, resourceKeys: resourceKeys))
  134. }
  135. }
  136. func isCached(forKey key: String) -> Bool {
  137. do {
  138. guard let _ = try value(forKey: key, actuallyLoad: false) else { return false }
  139. return true
  140. } catch {
  141. return false
  142. }
  143. }
  144. func extendExpriration(forKey key: String, lastAccessDate: Date, nextExpiration: StorageExpiration) throws {
  145. let fileURL = cacheFileURL(forKey: key)
  146. let attributes: [FileAttributeKey : Any] = [
  147. .creationDate: lastAccessDate,
  148. .modificationDate: nextExpiration.dateSince(lastAccessDate)
  149. ]
  150. try config.fileManager.setAttributes(attributes, ofItemAtPath: fileURL.path)
  151. }
  152. func remove(forKey key: String) throws {
  153. let fileURL = cacheFileURL(forKey: key)
  154. try removeFile(at: fileURL)
  155. }
  156. func removeFile(at url: URL) throws {
  157. try config.fileManager.removeItem(at: url)
  158. onFileRemoved.call(url)
  159. }
  160. func removeAll() throws {
  161. try removeAll(skipCreatingDirectory: false)
  162. }
  163. func removeAll(skipCreatingDirectory: Bool) throws {
  164. try config.fileManager.removeItem(at: directoryURL)
  165. onCacheRemoved.call()
  166. if !skipCreatingDirectory {
  167. try prepareDirectory()
  168. }
  169. }
  170. func cacheFileURL(forKey key: String) -> URL {
  171. let fileName = cacheFileName(forKey: key)
  172. return directoryURL.appendingPathComponent(fileName)
  173. }
  174. func cacheFileName(forKey key: String) -> String {
  175. let hashedKey = key.kf.md5
  176. if let ext = config.pathExtension {
  177. return "\(hashedKey).\(ext)"
  178. }
  179. return hashedKey
  180. }
  181. func allFileURLs(for propertyKeys: [URLResourceKey]) throws -> [URL] {
  182. let fileManager = config.fileManager
  183. guard let directoryEnumerator = fileManager.enumerator(
  184. at: directoryURL, includingPropertiesForKeys: propertyKeys, options: .skipsHiddenFiles) else
  185. {
  186. throw KingfisherError2.cacheError(reason: .fileEnumeratorCreationFailed(url: directoryURL))
  187. }
  188. guard let urls = directoryEnumerator.allObjects as? [URL] else {
  189. throw KingfisherError2.cacheError(reason: .invalidFileEnumeratorContent(url: directoryURL))
  190. }
  191. return urls
  192. }
  193. func removeExpiredValues() throws -> [URL] {
  194. let propertyKeys: [URLResourceKey] = [
  195. .isDirectoryKey,
  196. .contentModificationDateKey
  197. ]
  198. let urls = try allFileURLs(for: propertyKeys)
  199. let keys = Set(propertyKeys)
  200. let expiredFiles = urls.filter { fileURL in
  201. do {
  202. let resourceValues = try fileURL.resourceValues(forKeys: keys)
  203. if resourceValues.isDirectory == true {
  204. return false
  205. }
  206. if let modificationDate = resourceValues.contentModificationDate {
  207. return modificationDate.isPast
  208. }
  209. return true
  210. } catch {
  211. return true
  212. }
  213. }
  214. try expiredFiles.forEach { url in
  215. try removeFile(at: url)
  216. }
  217. return expiredFiles
  218. }
  219. func removeSizeExceededValues() throws -> [URL] {
  220. if config.sizeLimit == 0 { return [] } // Back compatible. 0 means no limit.
  221. var size = try totalSize()
  222. if size < config.sizeLimit { return [] }
  223. let propertyKeys: [URLResourceKey] = [
  224. .isDirectoryKey,
  225. .creationDateKey,
  226. .totalFileAllocatedSizeKey
  227. ]
  228. let keys = Set(propertyKeys)
  229. let urls = try allFileURLs(for: propertyKeys)
  230. var pendings: [(url: URL, meta: URLResourceValues)] = urls.compactMap { fileURL in
  231. guard let resourceValues = try? fileURL.resourceValues(forKeys: keys) else {
  232. return nil
  233. }
  234. return (url: fileURL, meta: resourceValues)
  235. }
  236. let distancePast = Date.distantPast
  237. pendings.sort {
  238. $0.meta.creationDate ?? distancePast > $1.meta.creationDate ?? distancePast
  239. }
  240. var removed: [URL] = []
  241. let target = config.sizeLimit / 2
  242. while size >= target, let item = pendings.popLast() {
  243. size -= (item.meta.totalFileAllocatedSize ?? 0)
  244. try removeFile(at: item.url)
  245. removed.append(item.url)
  246. }
  247. return removed
  248. }
  249. func totalSize() throws -> Int {
  250. let propertyKeys: [URLResourceKey] = [
  251. .isDirectoryKey,
  252. .totalFileAllocatedSizeKey
  253. ]
  254. let urls = try allFileURLs(for: propertyKeys)
  255. let keys = Set(propertyKeys)
  256. let totalSize = urls.reduce(0) { size, fileURL in
  257. do {
  258. let resourceValues = try fileURL.resourceValues(forKeys: keys)
  259. return size + (resourceValues.totalFileAllocatedSize ?? 0)
  260. } catch {
  261. return size
  262. }
  263. }
  264. return totalSize
  265. }
  266. }