You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

425 lines
16 KiB

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