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.

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