KingfisherManager+LivePhoto.swift 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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. @preconcurrency import Photos
  27. public struct LivePhotoLoadingInfoResult: Sendable {
  28. /// Retrieves the live photo disk URLs from this result.
  29. public let fileURLs: [URL]
  30. /// Retrieves the cache source of the image, indicating from which cache layer it was retrieved.
  31. ///
  32. /// If the image was freshly downloaded from the network and not retrieved from any cache, `.none` will be returned.
  33. /// Otherwise, ``CacheType/disk`` will be returned for the live photo. ``CacheType/memory`` is not available for
  34. /// live photos since it may take too much memory. All cached live photos are loaded from disk only.
  35. public let cacheType: CacheType
  36. /// The ``LivePhotoSource`` to which this result is related. This indicates where the `livePhoto` referenced by
  37. /// `self` is located.
  38. public let source: LivePhotoSource
  39. /// The original ``LivePhotoSource`` from which the retrieval task begins. It may differ from the ``source`` property.
  40. /// When an alternative source loading occurs, the ``source`` will represent the replacement loading target, while the
  41. /// ``originalSource`` will retain the initial ``source`` that initiated the image loading process.
  42. public let originalSource: LivePhotoSource
  43. /// Retrieves the data associated with this result.
  44. ///
  45. /// When this result is obtained from a network download (when `cacheType == .none`), calling this method returns
  46. /// the downloaded data. If the result is from the cache, it serializes the image using the specified cache
  47. /// serializer from the loading options and returns the result.
  48. ///
  49. /// - Note: Retrieving this data can be a time-consuming operation, so it is advisable to store it if you need to
  50. /// use it multiple times and avoid frequent calls to this method.
  51. public let data: @Sendable () -> [Data]
  52. }
  53. extension KingfisherManager {
  54. public func retrieveLivePhoto(
  55. with source: LivePhotoSource,
  56. options: KingfisherOptionsInfo? = nil,
  57. progressBlock: DownloadProgressBlock? = nil,
  58. referenceTaskIdentifierChecker: (() -> Bool)? = nil
  59. ) async throws -> LivePhotoLoadingInfoResult {
  60. let fullOptions = currentDefaultOptions + (options ?? .empty)
  61. var checkedOptions = KingfisherParsedOptionsInfo(fullOptions)
  62. if checkedOptions.processor == DefaultImageProcessor.default {
  63. // The default processor is a default behavior so we replace it silently.
  64. checkedOptions.processor = LivePhotoImageProcessor.default
  65. } else if checkedOptions.processor != LivePhotoImageProcessor.default {
  66. assertionFailure("[Kingfisher] Using of custom processors during loading of live photo resource is not supported.")
  67. checkedOptions.processor = LivePhotoImageProcessor.default
  68. }
  69. if let checker = referenceTaskIdentifierChecker {
  70. checkedOptions.onDataReceived?.forEach {
  71. $0.onShouldApply = checker
  72. }
  73. }
  74. // TODO. We ignore the retry of live photo now to suppress the complexity.
  75. let missingResources = missingResources(source, options: checkedOptions)
  76. let resourcesResult = try await downloadAndCache(resources: missingResources, options: checkedOptions)
  77. let targetCache = checkedOptions.targetCache ?? cache
  78. let fileURLs = source.resources.map {
  79. targetCache.cacheFileURLIfOnDisk(
  80. forKey: $0.cacheKey,
  81. processorIdentifier: checkedOptions.processor.identifier
  82. )
  83. }
  84. if fileURLs.contains(nil) {
  85. // not all file done. throw error
  86. }
  87. return LivePhotoLoadingInfoResult(
  88. fileURLs: fileURLs.compactMap { $0 },
  89. cacheType: missingResources.isEmpty ? .disk : .none,
  90. source: source,
  91. originalSource: source,
  92. data: {
  93. resourcesResult.map { $0.originalData }
  94. })
  95. }
  96. func missingResources(_ source: LivePhotoSource, options: KingfisherParsedOptionsInfo) -> [LivePhotoResource] {
  97. let missingResources: [LivePhotoResource]
  98. if options.forceRefresh {
  99. missingResources = source.resources
  100. } else {
  101. let targetCache = options.targetCache ?? cache
  102. missingResources = source.resources.reduce([], { r, resource in
  103. let cacheKey = resource.cacheKey
  104. let existingCachedFileURL = targetCache.cacheFileURLIfOnDisk(
  105. forKey: cacheKey,
  106. processorIdentifier: options.processor.identifier
  107. )
  108. if existingCachedFileURL == nil {
  109. return r + [resource]
  110. } else {
  111. return r
  112. }
  113. })
  114. }
  115. return missingResources
  116. }
  117. func downloadAndCache(
  118. resources: [LivePhotoResource],
  119. options: KingfisherParsedOptionsInfo
  120. ) async throws -> [LivePhotoResourceDownloadingResult] {
  121. if resources.isEmpty {
  122. return []
  123. }
  124. let downloader = options.downloader ?? downloader
  125. let cache = options.targetCache ?? cache
  126. return try await withThrowingTaskGroup(of: LivePhotoResourceDownloadingResult.self) { group in
  127. for resource in resources {
  128. group.addTask {
  129. let downloadedResource = try await downloader.downloadLivePhotoResource(
  130. with: resource.downloadURL,
  131. options: options
  132. )
  133. let fileExtension = resource.referenceFileType
  134. .determinedFileExtension(downloadedResource.originalData)
  135. try await cache.storeToDisk(
  136. downloadedResource.originalData,
  137. forKey: resource.cacheKey,
  138. processorIdentifier: options.processor.identifier,
  139. forcedExtension: fileExtension,
  140. expiration: options.diskCacheExpiration
  141. )
  142. return downloadedResource
  143. }
  144. }
  145. var result: [LivePhotoResourceDownloadingResult] = []
  146. for try await resource in group {
  147. result.append(resource)
  148. }
  149. return result
  150. }
  151. }
  152. }