import Foundation import ImageIO import UIKit import UniformTypeIdentifiers enum ImageDownloadError: Error, Equatable { case httpStatus(Int) case imageTooLarge case gifTooLarge } enum GIFDownload { static let byteLimit = 15 * 1024 * 1024 static let imageByteLimit = 64 * 1024 * 1024 static func load( _ url: URL, configuration: URLSessionConfiguration = .default ) async throws -> (Data, URLResponse) { let download = ChunkedImageDownload(configuration: configuration) return try await withTaskCancellationHandler { try await download.load(url) } onCancel: { download.cancel() } } static func validate(_ data: Data) throws { guard !RemoteImageDecoder.isGIF(data) || data.count <= byteLimit else { throw ImageDownloadError.gifTooLarge } guard data.count <= imageByteLimit else { throw ImageDownloadError.imageTooLarge } } } struct ImageDownloadBuffer { private(set) var data = Data() mutating func append(_ chunk: Data) throws { let prefix = Data((data.prefix(6) + chunk.prefix(max(0, 6 - data.count))).prefix(6)) if RemoteImageDecoder.isGIF(prefix) && chunk.count > GIFDownload.byteLimit - data.count { throw ImageDownloadError.gifTooLarge } guard chunk.count <= GIFDownload.imageByteLimit - data.count else { throw ImageDownloadError.imageTooLarge } data.append(chunk) } } final class ChunkedImageDownload: NSObject, URLSessionDataDelegate, @unchecked Sendable { private let lock = NSLock() private let configuration: URLSessionConfiguration private var task: URLSessionDataTask? private var session: URLSession? private var continuation: CheckedContinuation<(Data, URLResponse), Error>? private var cancelled = false private var buffer = ImageDownloadBuffer() private var response: URLResponse? private var downloadError: ImageDownloadError? init(configuration: URLSessionConfiguration) { self.configuration = configuration super.init() } func load(_ url: URL) async throws -> (Data, URLResponse) { try await withCheckedThrowingContinuation { continuation in lock.lock() if cancelled { lock.unlock() continuation.resume(throwing: CancellationError()) return } self.continuation = continuation let queue = OperationQueue() queue.maxConcurrentOperationCount = 1 queue.qualityOfService = .utility let session = URLSession(configuration: configuration, delegate: self, delegateQueue: queue) self.session = session let task = session.dataTask(with: url) self.task = task lock.unlock() task.resume() } } func cancel() { lock.lock() cancelled = true let task = task lock.unlock() task?.cancel() } func urlSession( _ session: URLSession, dataTask: URLSessionDataTask, didReceive response: URLResponse, completionHandler: @escaping (URLSession.ResponseDisposition) -> Void ) { guard let http = response as? HTTPURLResponse else { completionHandler(.cancel) return } guard (200..<300).contains(http.statusCode) else { downloadError = .httpStatus(http.statusCode) completionHandler(.cancel) return } guard response.expectedContentLength <= Int64(GIFDownload.imageByteLimit) else { downloadError = .imageTooLarge completionHandler(.cancel) return } self.response = response completionHandler(.allow) } func urlSession(_ session: URLSession, dataTask: URLSessionDataTask, didReceive chunk: Data) { do { try buffer.append(chunk) } catch let error as ImageDownloadError { downloadError = error dataTask.cancel() } catch { dataTask.cancel() } } func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) { lock.lock() let continuation = continuation self.continuation = nil self.task = nil self.session = nil lock.unlock() defer { session.finishTasksAndInvalidate() } if let downloadError { continuation?.resume(throwing: downloadError) } else if let error { continuation?.resume(throwing: error) } else if let response { continuation?.resume(returning: (buffer.data, response)) } else { continuation?.resume(throwing: URLError(.badServerResponse)) } } } actor ImageDecodeQueue { struct InlineImage { let image: UIImage let borderColors: AvatarRingColors } static let shared = ImageDecodeQueue() func decode(_ data: Data, resolution: RemoteImageDecoder.Resolution = .thumbnail) -> UIImage? { guard !Task.isCancelled else { return nil } return RemoteImageDecoder.decode(data, resolution: resolution) } func decodeInline(_ data: Data) -> InlineImage? { guard let image = decode(data) else { return nil } let frame = image.images?.first ?? image let colors = frame.cgImage.map(AvatarRingColors.calculate) ?? .fallback return InlineImage(image: image, borderColors: colors) } } enum RemoteImageDecoder { enum Resolution { case thumbnail case fullSize } static func isGIF(_ data: Data) -> Bool { data.starts(with: Data("GIF87a".utf8)) || data.starts(with: Data("GIF89a".utf8)) } static func decode(_ data: Data, resolution: Resolution = .thumbnail) -> UIImage? { guard let source = CGImageSourceCreateWithData(data as CFData, nil), CGImageSourceGetCount(source) > 0 else { return nil } let sourceType = CGImageSourceGetType(source) as String? if sourceType == UTType.gif.identifier { return decodeGIF(source, resolution: resolution) } return decodeFrame(source, at: 0, resolution: resolution) } private static func decodeGIF(_ source: CGImageSource, resolution: Resolution) -> UIImage? { let count = CGImageSourceGetCount(source) let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any] guard let width = properties?[kCGImagePropertyPixelWidth] as? Int, let height = properties?[kCGImagePropertyPixelHeight] as? Int, (1...4096).contains(width), (1...4096).contains(height), width * height <= 8_000_000, count <= 500 else { return nil } guard count > 1 else { return decodeFrame(source, at: 0, resolution: resolution) } let pixelsPerFrame = resolution == .thumbnail ? min(width, 720) * min(height, 720) : width * height let frameLimit = max(2, min(30, 10_000_000 / max(1, pixelsPerFrame))) let step = max(1, Int(ceil(Double(count) / Double(frameLimit)))) var frames: [UIImage] = [] var duration: TimeInterval = 0 for index in stride(from: 0, to: count, by: step) { guard let frame = decodeFrame(source, at: index, resolution: resolution) else { continue } frames.append(frame) let frameProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) as? [CFString: Any] let gifProperties = frameProperties?[kCGImagePropertyGIFDictionary] as? [CFString: Any] let delay = (gifProperties?[kCGImagePropertyGIFUnclampedDelayTime] as? TimeInterval) ?? (gifProperties?[kCGImagePropertyGIFDelayTime] as? TimeInterval) ?? 0.1 duration += max(0.02, delay) * Double(min(step, count - index)) } guard frames.count > 1 else { return frames.first } return UIImage.animatedImage(with: frames, duration: max(duration, 0.1)) } private static func decodeFrame(_ source: CGImageSource, at index: Int, resolution: Resolution) -> UIImage? { let maximumPixelSize: Int if resolution == .fullSize { let properties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) as? [CFString: Any] guard let width = properties?[kCGImagePropertyPixelWidth] as? Int, let height = properties?[kCGImagePropertyPixelHeight] as? Int, width > 0, height > 0 else { return nil } maximumPixelSize = max(width, height) } else { maximumPixelSize = 720 } let options: [CFString: Any] = [ kCGImageSourceCreateThumbnailFromImageAlways: true, kCGImageSourceThumbnailMaxPixelSize: maximumPixelSize, kCGImageSourceCreateThumbnailWithTransform: true, kCGImageSourceShouldCacheImmediately: true ] guard let image = CGImageSourceCreateThumbnailAtIndex(source, index, options as CFDictionary) else { return nil } return UIImage(cgImage: image) } }