| 1 | import UIKit |
| 2 | import SwiftUI |
| 3 | import UniformTypeIdentifiers |
| 4 | import EquipoShareCore |
| 5 | import EquipoShareUI |
| 6 | |
| 7 | @MainActor final class ShareViewController: UIViewController { |
| 8 | private var model: ExtensionModel? |
| 9 | private var preparation: Task<Void, Never>? |
| 10 | private var watching: Task<Void, Never>? |
| 11 | #if DEBUG && targetEnvironment(simulator) |
| 12 | private var memory: ShareMemory? |
| 13 | #endif |
| 14 | override func viewDidLoad() { |
| 15 | super.viewDidLoad() |
| 16 | let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] |
| 17 | guard let staging = try? ShareStaging.begin() else { |
| 18 | extensionContext?.cancelRequest(withError: NSError(domain: NSCocoaErrorDomain, code: NSFileWriteUnknownError)); return |
| 19 | } |
| 20 | var transport: any ShareTransport = ShareHTTP() |
| 21 | #if DEBUG && targetEnvironment(simulator) |
| 22 | if let authority = try? ShareAuthentication().read(), authority.selection.origin.host == "share-fixture.invalid", authority.token == "fixture-share" { transport = ShareFixtureTransport() } |
| 23 | #endif |
| 24 | #if DEBUG && targetEnvironment(simulator) |
| 25 | if transport is ShareFixtureTransport { memory = ShareMemory() } |
| 26 | #endif |
| 27 | let sender = ShareSender(auth: ShareAuthentication(), transport: transport, journal: ShareJournal(directory: support.appendingPathComponent("send-journal"))) |
| 28 | let model = ExtensionModel(sender: sender, staging: staging); self.model = model |
| 29 | // The wrapper observes preparation and presents the same stable compose view. |
| 30 | let host = UIHostingController(rootView: ExtensionCompose(model: model, cancel: { [weak self] in self?.cancel() }, send: { [weak self] in self?.send() })) |
| 31 | addChild(host); view.addSubview(host.view); host.view.translatesAutoresizingMaskIntoConstraints = false |
| 32 | NSLayoutConstraint.activate([host.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), host.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), host.view.topAnchor.constraint(equalTo: view.topAnchor), host.view.bottomAnchor.constraint(equalTo: view.bottomAnchor)]) |
| 33 | host.didMove(toParent: self) |
| 34 | guard sender.selection != nil else { return } |
| 35 | let items = (extensionContext?.inputItems as? [NSExtensionItem]) ?? [] |
| 36 | preparation = Task { |
| 37 | await sender.loadProjects() |
| 38 | await model.prepare(items) |
| 39 | #if DEBUG && targetEnvironment(simulator) |
| 40 | self.memory?.save(to: support.appendingPathComponent("share-memory.json")) |
| 41 | #endif |
| 42 | } |
| 43 | watching = Task { [weak self] in |
| 44 | while !Task.isCancelled { |
| 45 | try? await Task.sleep(for: .seconds(1)) |
| 46 | guard let self, let selection = self.model?.sender.selection else { return } |
| 47 | if (try? ShareAuthentication().require(selection)) == nil { self.preparation?.cancel(); self.model?.revoke(); return } |
| 48 | } |
| 49 | } |
| 50 | } |
| 51 | private func send() { |
| 52 | guard let model, !model.preparing else { return } |
| 53 | model.sender.start { [weak self] in |
| 54 | self?.watching?.cancel() |
| 55 | self?.model?.cancel() |
| 56 | self?.extensionContext?.completeRequest(returningItems: nil) |
| 57 | } |
| 58 | } |
| 59 | private func cancel() { |
| 60 | preparation?.cancel(); watching?.cancel(); model?.cancel() |
| 61 | extensionContext?.cancelRequest(withError: NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError)) |
| 62 | } |
| 63 | deinit { preparation?.cancel(); watching?.cancel() } |
| 64 | } |
| 65 | |
| 66 | @MainActor @Observable private final class ExtensionModel { |
| 67 | let sender: ShareSender |
| 68 | let staging: URL |
| 69 | var preparing = false |
| 70 | var notice: String? |
| 71 | private var providers: [NSItemProvider] = [] |
| 72 | private var next = 0 |
| 73 | private var retry: Task<Void, Never>? |
| 74 | init(sender: ShareSender, staging: URL) { self.sender = sender; self.staging = staging } |
| 75 | func cancel() { retry?.cancel(); sender.cancel(); try? FileManager.default.removeItem(at: staging) } |
| 76 | func revoke() { sender.revoke(); cancel() } |
| 77 | func resume(skip: Bool = false) { |
| 78 | guard !preparing else { return } |
| 79 | if skip { next += 1 } |
| 80 | retry = Task { await process() } |
| 81 | } |
| 82 | func prepare(_ items: [NSExtensionItem]) async { |
| 83 | do { |
| 84 | guard items.count <= 8 else { throw AttachmentFailure.type } |
| 85 | for item in items { |
| 86 | let attachments = item.attachments ?? [] |
| 87 | guard attachments.count <= 8 - providers.count else { throw AttachmentFailure.type } |
| 88 | providers.append(contentsOf: attachments) |
| 89 | if attachments.isEmpty, let text = item.attributedContentText?.string { |
| 90 | guard text.utf8.count <= 16 * 1024 else { throw AttachmentFailure.tooLarge } |
| 91 | sender.text += (sender.text.isEmpty ? "" : "\n") + text |
| 92 | } |
| 93 | } |
| 94 | await process() |
| 95 | } catch { notice = ShareWords.text("api.attachment_type") } |
| 96 | } |
| 97 | private func process() async { |
| 98 | preparing = true; notice = nil |
| 99 | defer { preparing = false } |
| 100 | do { |
| 101 | while next < providers.count { |
| 102 | try Task.checkCancellation() |
| 103 | try await importProvider(providers[next]) |
| 104 | guard sender.text.utf8.count <= 16 * 1024 else { throw AttachmentFailure.tooLarge } |
| 105 | next += 1 |
| 106 | } |
| 107 | } catch is CancellationError { cancel() } |
| 108 | catch let error as AttachmentFailure { |
| 109 | notice = ShareWords.text(error == .tooLarge ? "api.attachment_too_large" : error == .pixels ? "api.attachment_pixels" : "api.attachment_type") |
| 110 | } catch { notice = ShareWords.text("api.attachment_type") } |
| 111 | } |
| 112 | private func importProvider(_ provider: NSItemProvider) async throws { |
| 113 | // URL shares are literal editable text, never fetched. |
| 114 | if provider.hasItemConformingToTypeIdentifier(UTType.url.identifier), !provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) { |
| 115 | let url = try await provider.loadURL() |
| 116 | guard ["http", "https"].contains(url.scheme?.lowercased() ?? "") else { throw AttachmentFailure.type } |
| 117 | try appendText(url.absoluteString) |
| 118 | return |
| 119 | } |
| 120 | let isText = provider.hasItemConformingToTypeIdentifier(UTType.plainText.identifier) && !provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) && ((provider.suggestedName ?? "") as NSString).pathExtension.isEmpty |
| 121 | guard let type = provider.registeredTypeIdentifiers.first(where: { id in |
| 122 | guard let type = UTType(id) else { return false } |
| 123 | return type.conforms(to: .image) || type.conforms(to: .data) || type.conforms(to: .content) |
| 124 | }) else { throw AttachmentFailure.type } |
| 125 | let url: URL, name: String, directory = staging |
| 126 | if provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) { |
| 127 | let source = try await provider.loadURL(type: UTType.fileURL.identifier) |
| 128 | name = provider.suggestedName ?? source.lastPathComponent |
| 129 | let worker = Task.detached { try AttachmentFile.stage(source, directory: directory) } |
| 130 | url = try await withTaskCancellationHandler { try await worker.value } onCancel: { worker.cancel() } |
| 131 | } else { |
| 132 | let staged = try await provider.stagedFile(type: type, directory: staging) |
| 133 | url = staged.url; name = provider.suggestedName ?? staged.name |
| 134 | } |
| 135 | defer { try? FileManager.default.removeItem(at: url) } |
| 136 | try Task.checkCancellation() |
| 137 | if isText { |
| 138 | let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() } |
| 139 | let bytes = try handle.read(upToCount: 32 * 1024 + 3) ?? Data() |
| 140 | try appendText(ShareText.decode(bytes)) |
| 141 | } else { |
| 142 | guard sender.files.count < AttachmentLimits.maxCount else { throw ShareFailure.server(422, "attachment_limit") } |
| 143 | let worker = Task.detached { try autoreleasepool { try AttachmentFile.prepareFile(url, directory: directory, name: name) } } |
| 144 | let file = try await withTaskCancellationHandler { try await worker.value } onCancel: { worker.cancel() } |
| 145 | try Task.checkCancellation(); try sender.add(file) |
| 146 | } |
| 147 | } |
| 148 | private func appendText(_ text: String) throws { |
| 149 | let value = sender.text + (sender.text.isEmpty ? "" : "\n") + text |
| 150 | guard value.utf8.count <= 16 * 1024 else { throw AttachmentFailure.tooLarge } |
| 151 | sender.text = value |
| 152 | } |
| 153 | } |
| 154 | private struct ExtensionCompose: View { |
| 155 | let model: ExtensionModel |
| 156 | let cancel: () -> Void |
| 157 | let send: () -> Void |
| 158 | var body: some View { ShareComposeView(sender: model.sender, preparing: model.preparing, notice: model.notice, retryInput: { model.resume() }, removeInput: { model.resume(skip: true) }, cancel: cancel, send: send) } |
| 159 | } |
| 160 | |
| 161 | @MainActor extension NSItemProvider { |
| 162 | func loadURL(type: String = UTType.url.identifier) async throws -> URL { |
| 163 | try await withCheckedThrowingContinuation { continuation in |
| 164 | loadItem(forTypeIdentifier: type, options: nil) { value, error in |
| 165 | if let error { continuation.resume(throwing: error) } |
| 166 | else if let url = value as? URL { continuation.resume(returning: url) } |
| 167 | else { continuation.resume(throwing: AttachmentFailure.type) } |
| 168 | } |
| 169 | } |
| 170 | } |
| 171 | func stagedFile(type: String, directory: URL) async throws -> (url: URL, name: String) { |
| 172 | // The provider may delete its URL as soon as this callback returns. |
| 173 | try await withCheckedThrowingContinuation { continuation in |
| 174 | loadFileRepresentation(forTypeIdentifier: type) { url, error in |
| 175 | do { |
| 176 | if let error { throw error } |
| 177 | guard let url else { throw AttachmentFailure.type } |
| 178 | continuation.resume(returning: (try AttachmentFile.stage(url, directory: directory), url.lastPathComponent)) |
| 179 | } catch { continuation.resume(throwing: error) } |
| 180 | } |
| 181 | } |
| 182 | } |
| 183 | } |
| 184 | |