KingfisherManager+LivePhoto.swift 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  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. let fileURLs = source.resources.map {
  80. targetCache.possibleCacheFileURLIfOnDisk(
  81. forKey: $0.cacheKey,
  82. processorIdentifier: checkedOptions.processor.identifier,
  83. referenceFileType: $0.referenceFileType
  84. )
  85. }
  86. if fileURLs.contains(nil) {
  87. // not all file done. throw error
  88. }
  89. return LivePhotoLoadingInfoResult(
  90. fileURLs: fileURLs.compactMap { $0 },
  91. cacheType: missingResources.isEmpty ? .disk : .none,
  92. source: source,
  93. originalSource: source,
  94. data: {
  95. resourcesResult.map { $0.originalData }
  96. })
  97. }
  98. func missingResources(_ source: LivePhotoSource, options: KingfisherParsedOptionsInfo) -> [LivePhotoResource] {
  99. let missingResources: [LivePhotoResource]
  100. if options.forceRefresh {
  101. missingResources = source.resources
  102. } else {
  103. let targetCache = options.targetCache ?? cache
  104. missingResources = source.resources.reduce([], { r, resource in
  105. let cacheKey = resource.cacheKey
  106. let existingCachedFileURL = targetCache.possibleCacheFileURLIfOnDisk(
  107. forKey: cacheKey,
  108. processorIdentifier: options.processor.identifier,
  109. referenceFileType: resource.referenceFileType
  110. )
  111. if existingCachedFileURL == nil {
  112. return r + [resource]
  113. } else {
  114. return r
  115. }
  116. })
  117. }
  118. return missingResources
  119. }
  120. func downloadAndCache(
  121. resources: [LivePhotoResource],
  122. options: KingfisherParsedOptionsInfo
  123. ) async throws -> [LivePhotoResourceDownloadingResult] {
  124. if resources.isEmpty {
  125. return []
  126. }
  127. let downloader = options.downloader ?? downloader
  128. let cache = options.targetCache ?? cache
  129. return try await withThrowingTaskGroup(of: LivePhotoResourceDownloadingResult.self) { group in
  130. for resource in resources {
  131. group.addTask {
  132. let downloadedResource = try await downloader.downloadLivePhotoResource(
  133. with: resource.downloadURL,
  134. options: options
  135. )
  136. let fileExtension = resource.referenceFileType
  137. .determinedFileExtension(downloadedResource.originalData)
  138. try await cache.storeToDisk(
  139. downloadedResource.originalData,
  140. forKey: resource.cacheKey,
  141. processorIdentifier: options.processor.identifier,
  142. forcedExtension: fileExtension,
  143. expiration: options.diskCacheExpiration
  144. )
  145. return downloadedResource
  146. }
  147. }
  148. var result: [LivePhotoResourceDownloadingResult] = []
  149. for try await resource in group {
  150. result.append(resource)
  151. }
  152. return result
  153. }
  154. }
  155. }
  156. extension ImageCache {
  157. func possibleCacheFileURLIfOnDisk(
  158. forKey key: String,
  159. processorIdentifier identifier: String,
  160. referenceFileType: LivePhotoResource.FileType
  161. ) -> URL? {
  162. switch referenceFileType {
  163. case .heic, .mov:
  164. return cacheFileURLIfOnDisk(
  165. forKey: key, processorIdentifier: identifier, forcedExtension: referenceFileType.fileExtension
  166. )
  167. case .other(let ext):
  168. if ext.isEmpty {
  169. // The extension is not specified. Guess from the default values.
  170. let possibleFileTypes: [LivePhotoResource.FileType] = [.heic, .mov]
  171. for fileType in possibleFileTypes {
  172. let url = cacheFileURLIfOnDisk(
  173. forKey: key, processorIdentifier: identifier, forcedExtension: fileType.fileExtension
  174. )
  175. if url != nil {
  176. return url
  177. }
  178. }
  179. return nil
  180. } else {
  181. return cacheFileURLIfOnDisk(
  182. forKey: key, processorIdentifier: identifier, forcedExtension: ext
  183. )
  184. }
  185. }
  186. }
  187. }
  188. #endif