import UIKit import SwiftUI import UniformTypeIdentifiers import EquipoShareCore import EquipoShareUI @MainActor final class ShareViewController: UIViewController { private var model: ExtensionModel? private var preparation: Task? private var watching: Task? #if DEBUG && targetEnvironment(simulator) private var memory: ShareMemory? #endif override func viewDidLoad() { super.viewDidLoad() let support = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] guard let staging = try? ShareStaging.begin() else { extensionContext?.cancelRequest(withError: NSError(domain: NSCocoaErrorDomain, code: NSFileWriteUnknownError)); return } var transport: any ShareTransport = ShareHTTP() #if DEBUG && targetEnvironment(simulator) if let authority = try? ShareAuthentication().read(), authority.selection.origin.host == "share-fixture.invalid", authority.token == "fixture-share" { transport = ShareFixtureTransport() } #endif #if DEBUG && targetEnvironment(simulator) if transport is ShareFixtureTransport { memory = ShareMemory() } #endif let sender = ShareSender(auth: ShareAuthentication(), transport: transport, journal: ShareJournal(directory: support.appendingPathComponent("send-journal"))) let model = ExtensionModel(sender: sender, staging: staging); self.model = model // The wrapper observes preparation and presents the same stable compose view. let host = UIHostingController(rootView: ExtensionCompose(model: model, cancel: { [weak self] in self?.cancel() }, send: { [weak self] in self?.send() })) addChild(host); view.addSubview(host.view); host.view.translatesAutoresizingMaskIntoConstraints = false 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)]) host.didMove(toParent: self) guard sender.selection != nil else { return } let items = (extensionContext?.inputItems as? [NSExtensionItem]) ?? [] preparation = Task { await sender.loadProjects() await model.prepare(items) #if DEBUG && targetEnvironment(simulator) self.memory?.save(to: support.appendingPathComponent("share-memory.json")) #endif } watching = Task { [weak self] in while !Task.isCancelled { try? await Task.sleep(for: .seconds(1)) guard let self, let selection = self.model?.sender.selection else { return } if (try? ShareAuthentication().require(selection)) == nil { self.preparation?.cancel(); self.model?.revoke(); return } } } } private func send() { guard let model, !model.preparing else { return } model.sender.start { [weak self] in self?.watching?.cancel() self?.model?.cancel() self?.extensionContext?.completeRequest(returningItems: nil) } } private func cancel() { preparation?.cancel(); watching?.cancel(); model?.cancel() extensionContext?.cancelRequest(withError: NSError(domain: NSCocoaErrorDomain, code: NSUserCancelledError)) } deinit { preparation?.cancel(); watching?.cancel() } } @MainActor @Observable private final class ExtensionModel { let sender: ShareSender let staging: URL var preparing = false var notice: String? private var providers: [NSItemProvider] = [] private var next = 0 private var retry: Task? init(sender: ShareSender, staging: URL) { self.sender = sender; self.staging = staging } func cancel() { retry?.cancel(); sender.cancel(); try? FileManager.default.removeItem(at: staging) } func revoke() { sender.revoke(); cancel() } func resume(skip: Bool = false) { guard !preparing else { return } if skip { next += 1 } retry = Task { await process() } } func prepare(_ items: [NSExtensionItem]) async { do { guard items.count <= 8 else { throw AttachmentFailure.type } for item in items { let attachments = item.attachments ?? [] guard attachments.count <= 8 - providers.count else { throw AttachmentFailure.type } providers.append(contentsOf: attachments) if attachments.isEmpty, let text = item.attributedContentText?.string { guard text.utf8.count <= 16 * 1024 else { throw AttachmentFailure.tooLarge } sender.text += (sender.text.isEmpty ? "" : "\n") + text } } await process() } catch { notice = ShareWords.text("api.attachment_type") } } private func process() async { preparing = true; notice = nil defer { preparing = false } do { while next < providers.count { try Task.checkCancellation() try await importProvider(providers[next]) guard sender.text.utf8.count <= 16 * 1024 else { throw AttachmentFailure.tooLarge } next += 1 } } catch is CancellationError { cancel() } catch let error as AttachmentFailure { notice = ShareWords.text(error == .tooLarge ? "api.attachment_too_large" : error == .pixels ? "api.attachment_pixels" : "api.attachment_type") } catch { notice = ShareWords.text("api.attachment_type") } } private func importProvider(_ provider: NSItemProvider) async throws { // URL shares are literal editable text, never fetched. if provider.hasItemConformingToTypeIdentifier(UTType.url.identifier), !provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) { let url = try await provider.loadURL() guard ["http", "https"].contains(url.scheme?.lowercased() ?? "") else { throw AttachmentFailure.type } try appendText(url.absoluteString) return } let isText = provider.hasItemConformingToTypeIdentifier(UTType.plainText.identifier) && !provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) && ((provider.suggestedName ?? "") as NSString).pathExtension.isEmpty guard let type = provider.registeredTypeIdentifiers.first(where: { id in guard let type = UTType(id) else { return false } return type.conforms(to: .image) || type.conforms(to: .data) || type.conforms(to: .content) }) else { throw AttachmentFailure.type } let url: URL, name: String, directory = staging if provider.hasItemConformingToTypeIdentifier(UTType.fileURL.identifier) { let source = try await provider.loadURL(type: UTType.fileURL.identifier) name = provider.suggestedName ?? source.lastPathComponent let worker = Task.detached { try AttachmentFile.stage(source, directory: directory) } url = try await withTaskCancellationHandler { try await worker.value } onCancel: { worker.cancel() } } else { let staged = try await provider.stagedFile(type: type, directory: staging) url = staged.url; name = provider.suggestedName ?? staged.name } defer { try? FileManager.default.removeItem(at: url) } try Task.checkCancellation() if isText { let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() } let bytes = try handle.read(upToCount: 32 * 1024 + 3) ?? Data() try appendText(ShareText.decode(bytes)) } else { guard sender.files.count < AttachmentLimits.maxCount else { throw ShareFailure.server(422, "attachment_limit") } let worker = Task.detached { try autoreleasepool { try AttachmentFile.prepareFile(url, directory: directory, name: name) } } let file = try await withTaskCancellationHandler { try await worker.value } onCancel: { worker.cancel() } try Task.checkCancellation(); try sender.add(file) } } private func appendText(_ text: String) throws { let value = sender.text + (sender.text.isEmpty ? "" : "\n") + text guard value.utf8.count <= 16 * 1024 else { throw AttachmentFailure.tooLarge } sender.text = value } } private struct ExtensionCompose: View { let model: ExtensionModel let cancel: () -> Void let send: () -> Void 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) } } @MainActor extension NSItemProvider { func loadURL(type: String = UTType.url.identifier) async throws -> URL { try await withCheckedThrowingContinuation { continuation in loadItem(forTypeIdentifier: type, options: nil) { value, error in if let error { continuation.resume(throwing: error) } else if let url = value as? URL { continuation.resume(returning: url) } else { continuation.resume(throwing: AttachmentFailure.type) } } } } func stagedFile(type: String, directory: URL) async throws -> (url: URL, name: String) { // The provider may delete its URL as soon as this callback returns. try await withCheckedThrowingContinuation { continuation in loadFileRepresentation(forTypeIdentifier: type) { url, error in do { if let error { throw error } guard let url else { throw AttachmentFailure.type } continuation.resume(returning: (try AttachmentFile.stage(url, directory: directory), url.lastPathComponent)) } catch { continuation.resume(throwing: error) } } } } }