oficina / docs Public

Clone
git clone https://amadan.net/oficina/docs

Plain git — no account needed to clone.

Download

Download this file

1import Foundation
2import ImageIO
3import Observation
4import RastrilloApple
5#if os(macOS)
6import AppKit
7typealias DocsPlatformImage = NSImage
8#else
9import UIKit
10typealias DocsPlatformImage = UIImage
11#endif
12
13private final class ImageRedirectGuard: NSObject, URLSessionTaskDelegate, @unchecked Sendable {
14 func urlSession(_ session: URLSession, task: URLSessionTask, willPerformHTTPRedirection response: HTTPURLResponse,
15 newRequest request: URLRequest, completionHandler: @escaping (URLRequest?) -> Void) {
16 guard let url = request.url, ["http", "https"].contains(url.scheme ?? ""), url.user == nil, url.password == nil else {
17 completionHandler(nil); return
18 }
19 completionHandler(request)
20 }
21}
22
23/// Document image bytes live only in this screen's memory. External hosts receive
24/// no app credentials; same-origin protected assets use the ordinary client.
25@MainActor @Observable final class DocsImageStore {
26 private(set) var images: [String: DocsPlatformImage] = [:] {
27 didSet { changed?(images) }
28 }
29 /// Told of every change to `images`: the open document's surface draws
30 /// again only the blocks that hold an image that arrived.
31 @ObservationIgnored var changed: (([String: DocsPlatformImage]) -> Void)?
32 private var generation = UUID()
33 private var documentURL: URL?
34 private let session: URLSession = {
35 let config = URLSessionConfiguration.ephemeral
36 config.httpShouldSetCookies = false
37 config.urlCache = nil
38 config.timeoutIntervalForRequest = 20
39 return URLSession(configuration: config, delegate: ImageRedirectGuard(), delegateQueue: nil)
40 }()
41 static func sources(in projection: CRDTProjection) -> [String] {
42 projection.children.reduce(into: Set<String>()) { $0.formUnion(sources(in: $1)) }.sorted()
43 }
44 static func sources(in node: CRDTNode) -> Set<String> {
45 var found = Set<String>()
46 func visit(_ node: CRDTNode) {
47 if node.type == "image", let source = node.attrs?["src"] { found.insert(source) }
48 for child in node.children ?? [] { visit(child) }
49 }
50 visit(node)
51 return found
52 }
53 func images(forDocumentPath path: String, client: NativeTransport) -> [String: DocsPlatformImage] {
54 documentURL == URL(string: path, relativeTo: client.origin)?.absoluteURL ? images : [:]
55 }
56 static func resolvedURL(source: String, documentPath: String, origin: URL) -> URL? {
57 guard let document = URL(string: documentPath, relativeTo: origin)?.absoluteURL else { return nil }
58 return URL(string: source, relativeTo: document)?.absoluteURL
59 }
60 func load(sources: [String], client: NativeTransport, documentPath: String = "/") async {
61 let current = UUID(); generation = current
62 let document = URL(string: documentPath, relativeTo: client.origin)?.absoluteURL
63 if documentURL != document { images.removeAll(); documentURL = document }
64 images = images.filter { sources.contains($0.key) }
65 for source in sources where images[source] == nil {
66 guard !Task.isCancelled, generation == current else { return }
67 do {
68 let data: Data
69 if source.hasPrefix("data:image/"), let separator = source.firstIndex(of: ","), source[..<separator].hasSuffix(";base64") {
70 guard source.utf8.count <= 12 * 1024 * 1024,
71 let decoded = Data(base64Encoded: String(source[source.index(after: separator)...])) else { continue }
72 data = decoded
73 } else {
74 guard let url = Self.resolvedURL(source: source, documentPath: documentPath, origin: client.origin),
75 ["https", "http"].contains(url.scheme ?? ""), url.user == nil, url.password == nil else { continue }
76 if url.scheme == client.origin.scheme && url.host == client.origin.host && url.port == client.origin.port {
77 guard let parts = URLComponents(url: url, resolvingAgainstBaseURL: false) else { continue }
78 let path = parts.percentEncodedPath + (parts.percentEncodedQuery.map { "?" + $0 } ?? "")
79 let response = try await client.response(path, maxBytes: 8 * 1024 * 1024)
80 guard response.1 == 200 else { continue }
81 data = response.0
82 } else {
83 let (bytes, response) = try await session.bytes(from: url)
84 defer { bytes.task.cancel() }
85 guard (response as? HTTPURLResponse)?.statusCode == 200 else { continue }
86 var received = Data()
87 for try await byte in bytes {
88 try Task.checkCancellation()
89 guard received.count < 8 * 1024 * 1024 else { throw CRDTReplica.Failure.rejected }
90 received.append(byte)
91 }
92 data = received
93 }
94 }
95 guard !Task.isCancelled, generation == current, let image = DocsAttachments.decode(data) else { continue }
96 images[source] = image
97 } catch { if Task.isCancelled { return } }
98 }
99 }
100}
101
102@MainActor enum DocsAttachments {
103 static func decode(_ data: Data) -> DocsPlatformImage? {
104 guard let source = CGImageSourceCreateWithData(data as CFData, nil),
105 let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],
106 let width = properties[kCGImagePropertyPixelWidth] as? Int,
107 let height = properties[kCGImagePropertyPixelHeight] as? Int,
108 width > 0, height > 0, width <= 16_384, height <= 16_384,
109 width * height <= 40_000_000,
110 let image = CGImageSourceCreateThumbnailAtIndex(source, 0, [
111 kCGImageSourceCreateThumbnailFromImageAlways: true,
112 kCGImageSourceThumbnailMaxPixelSize: 2048,
113 kCGImageSourceCreateThumbnailWithTransform: true,
114 ] as CFDictionary) else { return nil }
115 #if os(macOS)
116 return NSImage(cgImage: image, size: NSSize(width: image.width, height: image.height))
117 #else
118 return UIImage(cgImage: image)
119 #endif
120 }
121 static func image(_ image: DocsPlatformImage?, alt: String?, maxWidth: CGFloat = 440) -> NSAttributedString {
122 let attachment = NSTextAttachment()
123 attachment.image = image
124 if let image {
125 let size = image.size
126 let scale = min(1, maxWidth / max(size.width, 1))
127 attachment.bounds = CGRect(x: 0, y: 0, width: size.width * scale, height: size.height * scale)
128 } else {
129 #if os(macOS)
130 attachment.image = NSImage(systemSymbolName: "photo", accessibilityDescription: alt)
131 #else
132 attachment.image = UIImage(systemName: "photo")
133 #endif
134 attachment.bounds = CGRect(x: 0, y: 0, width: 24, height: 24)
135 }
136 #if os(macOS)
137 attachment.image?.accessibilityDescription = alt
138 #endif
139 return NSAttributedString(attachment: attachment)
140 }
141 static func rule(width: CGFloat = 440) -> NSAttributedString {
142 let attachment = NSTextAttachment()
143 #if os(macOS)
144 attachment.image = NSImage(size: NSSize(width: width, height: 1), flipped: false) { rect in
145 NSColor.separatorColor.setFill(); rect.fill(); return true
146 }
147 #else
148 attachment.image = UIGraphicsImageRenderer(size: CGSize(width: width, height: 1)).image { context in
149 UIColor.separator.setFill(); context.fill(CGRect(x: 0, y: 0, width: width, height: 1))
150 }
151 #endif
152 attachment.bounds = CGRect(x: 0, y: 4, width: width, height: 1)
153 return NSAttributedString(attachment: attachment)
154 }
155}
156