Cotton code
249 lines · 12.2 KB · SwiftRaw
// What a share hands over, read into the mailbox: the `NSExtensionItem`s an// app shares, each file COPIED into the app group, one `ShareEntry` per file,// or one for the item's address or prose. Moved here from the share// extension's `ShareViewController` (8 Nov 2026) so the// one reader is the extension's AND a development build's walk: Safari's share// sheet does not open "More" under XCUITest, so `testWalkUrlShare` hands the// app an item with a URL attachment (`-walk-share <url>`) and it lands through// this very method, the mailbox and the drain, as a share from the sheet does.import Foundationimport UniformTypeIdentifiers/// Main-actor, as the extension's view controller it came from: an/// `NSItemProvider` is not Sendable, and it never leaves this actor; only the/// Sendable values its callbacks answer come back.@MainActorpublic enum ShareItems {    private struct Staged: Sendable {        let path: String        let fileName: String?        /// What the drain's four classification rules read. `nil` when the        /// system had nothing worth declaring — see `shareDeclaredType(forType:)`.        let mimeType: String?    }    /// Write one mailbox entry per FILE an item carried — or one for its    /// address or prose when it carried no file — and answer them.    ///    /// The activation rules admit one URL, one web page or one text selection,    /// and up to twenty pictures, clips or files (`project.yml`). Several    /// photos chosen in Photos arrive as one item with several attachments or    /// as several items, and either way each file is its OWN entry: the drain    /// reads one file per entry, and a second file folded into the first    /// entry's would be bytes copied into the app group that nothing ever    /// files. The item's address, prose and title ride on its first entry,    /// where the drain's last branch still reads them.    ///    /// The entries come BACK rather than being acted on here: whether one of    /// them opens the app is `ShareOpener`'s rule, and this method's job is the    /// copy and the write.    ///    /// `stamp` is when it arrived, as the mailbox writes dates; `bundleIdentifier`    /// names the app group the files are copied into. The share extension    /// calls this with what the sheet handed it, and a development build's walk    /// (`-walk-share`) with an item it made, so a walk drives the very path a    /// share takes where XCUITest cannot drive the sheet.    @MainActor    public static func accept(_ items: [NSExtensionItem], stamp: String,                              bundleIdentifier: String? = Bundle.main.bundleIdentifier) async -> [ShareEntry] {        guard let storage = DefaultsShareMailboxStorage(bundleIdentifier: bundleIdentifier)        else {            // No App Group is no channel — the platform's answer, not a            // failure to handle. There is nowhere to report it from an            // extension that draws nothing, so the share is dropped rather than            // half-written. Nothing was written, so nothing knocks either.            return []        }        let mailbox = ShareMailbox(storage: storage)        var written: [ShareEntry] = []        for item in items {            let providers = item.attachments ?? []            var staged: [Staged] = []            var url: String?            var text: String?            for provider in providers {                // THE TYPES, IN THE LOG. A share that goes nowhere is decided                // entirely by what the provider registered, and a device log                // is the only place anyone can read that back — the walk of 15                // Sep 2026 could see neither this nor which opener answered.                Log.write(                    "share: provider registered \(provider.registeredTypeIdentifiers) "                        + "named \(shareSanitisedFileName(provider.suggestedName) ?? "nothing")"                )                if let source = fileSource(of: provider) {                    Log.write("share: staging as \(source)")                    if let one = await stage(provider, source: source, bundleIdentifier: bundleIdentifier) { staged.append(one) }                    continue                }                if url == nil, provider.hasItemConformingToTypeIdentifier(UTType.url.identifier) {                    url = await loadURL(provider)?.absoluteString                    continue                }                if text == nil,                    provider.hasItemConformingToTypeIdentifier(UTType.plainText.identifier)                {                    text = await loadText(provider)                }            }            // A page share carries the title here; a link share usually carries            // nothing. Recorded either way, because the channel has a place for            // it and the sharing app is the only one that knows it.            let title = item.attributedContentText?.string            // The kind is what ARRIVED, in the order the drain's precedence            // reads them: bytes outrank an address, and an address outranks            // prose. A file share can also carry a text label — it is carried            // across on the FIRST file's entry rather than dropped, because the            // drain's file branches claim the file and its last branch reads            // the address beside it.            if staged.isEmpty {                let kind: ShareKind                if url != nil {                    kind = .url                } else if text != nil {                    kind = .text                } else {                    continue                }                let entry = ShareEntry(at: stamp, kind: kind.rawValue, url: url, text: text, title: title)                mailbox.append(entry)                written.append(entry)                continue            }            for (index, file) in staged.enumerated() {                let first = index == 0                let entry = ShareEntry(                    at: stamp,                    kind: ShareKind.file.rawValue,                    url: first ? url : nil,                    text: first ? text : nil,                    title: first ? title : nil,                    path: file.path,                    fileName: file.fileName,                    mimeType: file.mimeType                )                mailbox.append(entry)                written.append(entry)            }        }        return written    }    /// How to load this provider's FILE, or `nil` when it is not carrying one.    ///    /// The RULE is `CottonMailbox`'s (`shareFileSource`), because this target is in    /// no test bundle and a rule nothing executable holds is a rule that    /// drifts. What is here is the two things only an `NSItemProvider` can    /// answer: what it registered, and what it would call the file.    private static func fileSource(of provider: NSItemProvider) -> ShareFileSource? {        shareFileSource(            registered: provider.registeredTypeIdentifiers,            suggestedName: provider.suggestedName        )    }    /// Copy the bytes into the app group, under a name nothing can collide with.    ///    /// **The copy happens INSIDE the callback**, because the URL is borrowed for    /// the length of that call and the directory it points at is torn down after    /// it. The source extension is kept on the copy (`stageSharedFile`): a bare    /// id would leave the drain's rules with nothing to read when a share    /// declares no type.    ///    /// **Which callback depends on what the provider registered**, and that is    /// root cause C of the 15 Sep 2026 walk. `loadFileRepresentation` under    /// `public.file-url` does NOT hand over the shared file: it writes a    /// property list holding the string `file:///…/sample.xyz`, 261 bytes with    /// no extension, which the drain then rejected as "no extension" while the    /// real file was never read at all. A `.txt` export and every type this app    /// has no concrete UTI for arrived that way. So a URL source is asked for    /// its URL and the file THAT names is copied; a concrete one still goes    /// through `loadFileRepresentation`, which for a concrete type really is a    /// file. **A property list is never written into the inbox.**    ///    /// The NAME kept on the entry is the sharing app's, sanitised — it is the    /// only hint `import.whatsappExport` has about whose chat this is, and the    /// staged copy's own UUID name carries none.    private static func stage(_ provider: NSItemProvider, source: ShareFileSource, bundleIdentifier: String?) async -> Staged? {        guard let directory = ShareChannel.inboxDirectory(bundleIdentifier: bundleIdentifier)        else { return nil }        let mime = shareDeclaredType(forType: source.identifier)        let suggested = shareSanitisedFileName(provider.suggestedName)        return await withCheckedContinuation { (continuation: CheckedContinuation<Staged?, Never>) in            let copy: @Sendable (URL?) -> Void = { url in                guard let url else {                    continuation.resume(returning: nil)                    return                }                do {                    let path = try stageSharedFile(from: url, into: directory)                    continuation.resume(                        returning: Staged(                            path: path,                            // The provider's own name first: for a file URL the                            // borrowed URL is usually the real one, but for a                            // file representation it is a temporary copy the                            // system named, and the two disagree often enough                            // that only one of them can be the rule.                            fileName: suggested                                ?? shareSanitisedFileName(url.lastPathComponent),                            mimeType: mime                        )                    )                } catch {                    Log.warn("share: the staged copy failed: \(error)")                    continuation.resume(returning: nil)                }            }            switch source {            case .url(let identifier):                provider.loadItem(forTypeIdentifier: identifier, options: nil) { value, _ in                    // `loadItem` under a URL type answers an `NSURL`; some                    // providers answer the `Data` of one instead.                    if let url = value as? URL {                        copy(url)                        return                    }                    if let data = value as? Data,                        let text = String(data: data, encoding: .utf8),                        let url = URL(string: text), url.isFileURL                    {                        copy(url)                        return                    }                    Log.warn("share: a file-url provider answered no URL")                    copy(nil)                }            case .representation(let identifier):                _ = provider.loadFileRepresentation(forTypeIdentifier: identifier) { url, _ in                    copy(url)                }            }        }    }    private static func loadURL(_ provider: NSItemProvider) async -> URL? {        await withCheckedContinuation { (continuation: CheckedContinuation<URL?, Never>) in            provider.loadItem(forTypeIdentifier: UTType.url.identifier, options: nil) { value, _ in                let url = value as? URL                // A `file:` URL is bytes, not an address, and it has already had                // its chance at the file branch above. Handing it to the drain                // as a web URL would put a path in the reading pile.                continuation.resume(returning: (url?.isFileURL ?? true) ? nil : url)            }        }    }    private static func loadText(_ provider: NSItemProvider) async -> String? {        await withCheckedContinuation { (continuation: CheckedContinuation<String?, Never>) in            provider.loadItem(forTypeIdentifier: UTType.plainText.identifier, options: nil) {                value, _ in                continuation.resume(returning: value as? String)            }        }    }}