KingfisherManager+LivePhoto.swift 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212
  1. //
  2. // KingfisherManager+LivePhoto.swift
  3. // Kingfisher
  4. //
  5. // Created by onevcat on 2024/10/01.
  6. //
  7. // Copyright (c) 2024 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. #if !os(watchOS)
  27. @preconcurrency import Photos
  28. public struct LivePhotoLoadingInfoResult: Sendable {
  29. /// Retrieves the live photo disk URLs from this result.
  30. public let fileURLs: [URL]
  31. /// Retrieves the cache source of the image, indicating from which cache layer it was retrieved.
  32. ///
  33. /// If the image was freshly downloaded from the network and not retrieved from any cache, `.none` will be returned.
  34. /// Otherwise, ``CacheType/disk`` will be returned for the live photo. ``CacheType/memory`` is not available for
  35. /// live photos since it may take too much memory. All cached live photos are loaded from disk only.
  36. public let cacheType: CacheType
  37. /// The ``LivePhotoSource`` to which this result is related. This indicates where the `livePhoto` referenced by
  38. /// `self` is located.
  39. public let source: LivePhotoSource
  40. /// The original ``LivePhotoSource`` from which the retrieval task begins. It may differ from the ``source`` property.
  41. /// When an alternative source loading occurs, the ``source`` will represent the replacement loading target, while the
  42. /// ``originalSource`` will retain the initial ``source`` that initiated the image loading process.
  43. public let originalSource: LivePhotoSource
  44. /// Retrieves the data associated with this result.
  45. ///
  46. /// When this result is obtained from a network download (when `cacheType == .none`), calling this method returns
  47. /// the downloaded data. If the result is from the cache, it serializes the image using the specified cache
  48. /// serializer from the loading options and returns the result.
  49. ///
  50. /// - Note: Retrieving this data can be a time-consuming operation, so it is advisable to store it if you need to
  51. /// use it multiple times and avoid frequent calls to this method.
  52. public let data: @Sendable () -> [Data]
  53. }
  54. extension KingfisherManager {
  55. public func retrieveLivePhoto(
  56. with source: LivePhotoSource,
  57. options: KingfisherOptionsInfo? = nil,
  58. progressBlock: DownloadProgressBlock? = nil,
  59. referenceTaskIdentifierChecker: (() -> Bool)? = nil
  60. ) async throws -> LivePhotoLoadingInfoResult {
  61. let fullOptions = currentDefaultOptions + (options ?? .empty)
  62. var checkedOptions = KingfisherParsedOptionsInfo(fullOptions)
  63. if checkedOptions.processor == DefaultImageProcessor.default {
  64. // The default processor is a default behavior so we replace it silently.
  65. checkedOptions.processor = LivePhotoImageProcessor.default
  66. } else if checkedOptions.processor != LivePhotoImageProcessor.default {
  67. assertionFailure("[Kingfisher] Using of custom processors during loading of live photo resource is not supported.")
  68. checkedOptions.processor = LivePhotoImageProcessor.default
  69. }
  70. if let checker = referenceTaskIdentifierChecker {
  71. checkedOptions.onDataReceived?.forEach {
  72. $0.onShouldApply = checker
  73. }
  74. }
  75. // TODO. We ignore the retry of live photo and the progress now to suppress the complexity.
  76. let missingResources = missingResources(source, options: checkedOptions)
  77. let resourcesResult = try await downloadAndCache(resources: missingResources, options: checkedOptions)
  78. let targetCache = checkedOptions.targetCache ?? cache
  79. var fileURLs = [URL]()
  80. for resource in source.resources {
  81. let url = targetCache.possibleCacheFileURLIfOnDisk(resource: resource, options: checkedOptions)
  82. guard let url else {
  83. // This should not happen normally if the previous `downloadAndCache` done without issue, but in case.
  84. throw KingfisherError.cacheError(reason: .missingLivePhotoResourceOnDisk(resource))
  85. }
  86. fileURLs.append(url)
  87. }
  88. return LivePhotoLoadingInfoResult(
  89. fileURLs: fileURLs,
  90. cacheType: missingResources.isEmpty ? .disk : .none,
  91. source: source,
  92. originalSource: source,
  93. data: {
  94. resourcesResult.map { $0.originalData }
  95. })
  96. }
  97. func missingResources(_ source: LivePhotoSource, options: KingfisherParsedOptionsInfo) -> [LivePhotoResource] {
  98. let missingResources: [LivePhotoResource]
  99. if options.forceRefresh {
  100. missingResources = source.resources
  101. } else {
  102. let targetCache = options.targetCache ?? cache
  103. missingResources = source.resources.reduce([], { r, resource in
  104. let cachedFileURL = targetCache.possibleCacheFileURLIfOnDisk(resource: resource, options: options)
  105. if cachedFileURL == nil {
  106. return r + [resource]
  107. } else {
  108. return r
  109. }
  110. })
  111. }
  112. return missingResources
  113. }
  114. func downloadAndCache(
  115. resources: [LivePhotoResource],
  116. options: KingfisherParsedOptionsInfo
  117. ) async throws -> [LivePhotoResourceDownloadingResult] {
  118. if resources.isEmpty {
  119. return []
  120. }
  121. let downloader = options.downloader ?? downloader
  122. let cache = options.targetCache ?? cache
  123. return try await withThrowingTaskGroup(of: LivePhotoResourceDownloadingResult.self) { group in
  124. for resource in resources {
  125. group.addTask {
  126. let downloadedResource = try await downloader.downloadLivePhotoResource(
  127. with: resource.downloadURL,
  128. options: options
  129. )
  130. let fileExtension = resource.referenceFileType
  131. .determinedFileExtension(downloadedResource.originalData)
  132. try await cache.storeToDisk(
  133. downloadedResource.originalData,
  134. forKey: resource.cacheKey,
  135. processorIdentifier: options.processor.identifier,
  136. forcedExtension: fileExtension,
  137. expiration: options.diskCacheExpiration
  138. )
  139. return downloadedResource
  140. }
  141. }
  142. var result: [LivePhotoResourceDownloadingResult] = []
  143. for try await resource in group {
  144. result.append(resource)
  145. }
  146. return result
  147. }
  148. }
  149. }
  150. extension ImageCache {
  151. func possibleCacheFileURLIfOnDisk(
  152. resource: LivePhotoResource,
  153. options: KingfisherParsedOptionsInfo
  154. ) -> URL? {
  155. possibleCacheFileURLIfOnDisk(
  156. forKey: resource.cacheKey,
  157. processorIdentifier: options.processor.identifier,
  158. referenceFileType: resource.referenceFileType
  159. )
  160. }
  161. func possibleCacheFileURLIfOnDisk(
  162. forKey key: String,
  163. processorIdentifier identifier: String,
  164. referenceFileType: LivePhotoResource.FileType
  165. ) -> URL? {
  166. switch referenceFileType {
  167. case .heic, .mov:
  168. return cacheFileURLIfOnDisk(
  169. forKey: key, processorIdentifier: identifier, forcedExtension: referenceFileType.fileExtension
  170. )
  171. case .other(let ext):
  172. if ext.isEmpty {
  173. // The extension is not specified. Guess from the default values.
  174. let possibleFileTypes: [LivePhotoResource.FileType] = [.heic, .mov]
  175. for fileType in possibleFileTypes {
  176. let url = cacheFileURLIfOnDisk(
  177. forKey: key, processorIdentifier: identifier, forcedExtension: fileType.fileExtension
  178. )
  179. if url != nil {
  180. return url
  181. }
  182. }
  183. return nil
  184. } else {
  185. return cacheFileURLIfOnDisk(
  186. forKey: key, processorIdentifier: identifier, forcedExtension: ext
  187. )
  188. }
  189. }
  190. }
  191. }
  192. #endif