Sources/OrgPresentation/RemoteImages.swift

74 lines · 3279 bytes

5 symbols in this file
 1import CryptoKit
 2import Foundation
 3import Observation
 4
 5/// `org-display-remote-inline-images`: images at http and https links, fetched in the
 6/// background. `download` keeps them while the app runs; `cache` keeps them on disk too.
 7@MainActor
 8@Observable
 9public final class RemoteImages {
10    public static let shared = RemoteImages()
11
12    public enum Mode: String, Sendable {
13        case skip, download, cache
14    }
15
16    /// Changes when an image arrives, for views that show them.
17    public private(set) var version = 0
18    @ObservationIgnored private var memory: [URL: Data] = [:]
19    @ObservationIgnored private var loading: Set<URL> = []
20    @ObservationIgnored private var failed: Set<URL> = []
21    @ObservationIgnored private var waiting: [URL: [@MainActor () -> Void]] = [:]
22    @ObservationIgnored let directory: URL
23    @ObservationIgnored let fetch: @Sendable (URL) async throws -> Data
24
25    public init(directory: URL = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0].appendingPathComponent("RemoteImages"),
26                fetch: @escaping @Sendable (URL) async throws -> Data = RemoteImages.download) {
27        self.directory = directory
28        self.fetch = fetch
29    }
30
31    /// An http(s) GET; other statuses than 2xx fail.
32    public nonisolated static func download(_ url: URL) async throws -> Data {
33        let (data, response) = try await URLSession.shared.data(from: url)
34        if let http = response as? HTTPURLResponse, !(200..<300).contains(http.statusCode) { throw URLError(.badServerResponse) }
35        return data
36    }
37
38    /// The image's data when it's here; otherwise nil, and `loaded` runs when it has come.
39    /// A link that failed isn't fetched again while the app runs.
40    public func data(for url: URL, mode: Mode, loaded: @escaping @MainActor () -> Void) -> Data? {
41        guard mode != .skip, let scheme = url.scheme?.lowercased(), scheme == "http" || scheme == "https" else { return nil }
42        if let data = memory[url] { return data }
43        if mode == .cache, let data = try? Data(contentsOf: file(url)) {
44            memory[url] = data
45            return data
46        }
47        guard !failed.contains(url) else { return nil }
48        waiting[url, default: []].append(loaded)
49        guard loading.insert(url).inserted else { return nil }
50        let fetch = self.fetch
51        Task {
52            let data = try? await fetch(url)
53            loading.remove(url)
54            if let data {
55                memory[url] = data
56                if mode == .cache {
57                    try? FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)
58                    try? data.write(to: file(url), options: .atomic)
59                }
60            } else {
61                failed.insert(url)
62            }
63            version += 1
64            for callback in waiting.removeValue(forKey: url) ?? [] { callback() }
65        }
66        return nil
67    }
68
69    /// The cached copy's file, named by a hash of the link.
70    func file(_ url: URL) -> URL {
71        let hash = SHA256.hash(data: Data(url.absoluteString.utf8)).map { String(format: "%02x", $0) }.joined()
72        return directory.appendingPathComponent(hash + (url.pathExtension.isEmpty ? "" : "." + url.pathExtension))
73    }
74}