Cotton code
1046 lines · 56.2 KB · SwiftRaw
// The DRAIN — what happens to a share after the sheet closes.//// The four classification rules the branches read — the zips, the pictures, the// recordings and the papers — live here rather than in four files because they// are one decision: **the branches are mutually exclusive only if they read// the same classification**, and two lists that must disagree in exactly one// direction is how a fix lands on only one of them. `shareFileKind` is that one rule, and// both the pictures branch and the recordings branch read it — which is what// keeps a shared clip out of the recordings branch.//// ── The eight branches, in this precedence ──────────────────────────────────//// | # | what arrived | where it goes |// |---|---|---|// | 0 | a Cotton package (`.cottonpkg`) | `package.import` NOW, and the person is told what came in |// | 1z | in Cotton Music, an album ZIP (a Bandcamp download) | `music.zip` then `music.capture` NOW, → the album |// | 1 | a chat export — a zip, or WhatsApp's `_chat.txt` | staged → `/messages/import` |// | 1g | a Goodreads library export (`Book Id,Title,Author` first) | the object's `import_goodreads` NOW, → the books |// | 1o | a podcast subscription list (a `.opml`, or XML whose root is `<opml`) | `import_opml` NOW, on the phone, → the shows |// | 1d | a folder, in Cotton Books or through Books' Add a folder | `books.folder` NOW, → the books |// | 1b | a book — an EPUB, or a PDF in Cotton Books | `capture.media` as a book NOW, → the book |// | 1f | a film or a folder of them — every video in Cotton Cinemas; in Cotton a video the core says is a film | `films.capture` NOW, → the film |// | 2 | a picture or a clip | `capture.media` NOW, → its photo or video |// | 3 | a recording | `meetings.create`, → the meeting |// | 4 | any other file | `capture.media` as a document NOW, → its page |// | 0f | what the core calls a download (`share.fetchLinks`) | the object's `fetch_add` NOW, → the download the Mac fetches |// | 5 | anything else | the URLs in it, one page row each, → the reader |//// The ORDER is half the rule and every neighbouring pair states why: a chat// export can carry a text label the URL extraction would happily misread, and a// `_chat.txt` is a `.txt` branch 4 would otherwise file as a document; a clip// reaching branch 3 or 4 would be claimed by either, since the recordings map// reads `.mp4` as `audio/mp4` (an audio-only mp4 is a real thing) and the// documents branch takes any picture too; and branch 4 takes// every file left, so ordering it first would swallow the three narrow kinds// above it.//// **The two book branches sit ahead of the pictures and the documents**: a// Goodreads export is a `.csv` branch 4 would file as a paper, and a book is// an EPUB (which nothing else reads) or, in Cotton Books (`ShareShelf`), a PDF// branch 4 would file as a document. In Cotton a PDF stays a document. The// book's title, author, language, ISBN, pages and cover are read FROM THE FILE// (`BookFile`), here, off the main actor.//// **The films' branch sits ahead of the pictures**: in Cotton Cinemas every// video is a film; in Cotton a clip's container is asked of the core first// (`onlyFilms`), and what it says is no film goes on to branch 2 as it always// did — never the reverse (5 Nov 2026).//// **Branch 0 outranks them all**: a package is a zip, and branch 1 would take// any zip for a chat export. It is decided by the name alone — a package's// extension is the one fact about it nothing else claims.//// ── What this port does NOT do, and why ──────────────────────────────────────//// **Branches 2, 3, 4 and 5 write a row.** Branch 1 hands the staged file to an// import screen another lane owns, because it ends in a question the person has// to answer — is this the chat you wanted.// Branch 2 asks nothing because there is nothing to answer: a picture is// bytes the person already holds, so the photo or video row is written at// once, exactly as the library picker's is, and the app opens that record in// Photos or Videos — no composer, no message box in between (the owner, 23// Oct 2026; it used to land on the capture composer carrying the picture,// the todo "a thought accepts pictures", 2026-09-27).// **Branch 3 asks nothing for the same reason**: a voice note somebody shared// in is a recording of something that happened, the one thing Cotton would do// with it is write it down, and a screen in between// asking "shall I?" is a question with one answer. It creates the meeting and// opens it, which is what sharing a voice note into Cotton meant before the// phone lost its producer (2026-09-14) and means again.//// **Branch 4 files ANY file as a document, and asks nothing either** (lane// door, 22 Oct 2026 — Rigby's import door). It used to land a paper on// `/documents/import` carrying the staged file, and that screen never took the// file: it opened its own picker, the share was lost and its copy stayed in// the app group. A file the three narrow branches do not take now becomes a// document row with its bytes in the store, exactly as the documents screen's// own Files pick does, and the app opens its page. That includes the file no// rule used to claim — a `.7z`, a `.key`, a file with no name — which was// reported and discarded: a person who shared a file into their own database// meant to keep it, and the core takes any type as a document// (`application/octet-stream` is on its list).//// **The staging is already done when the drain runs.** Before the rewrite each// branch copied the share container's file into the app's cache first, because// `resetShareIntent()` cleared that container and resetting early staged 0// bytes. In this tree the copy has moved one step earlier — the share extension// copies into the app group before it writes the mailbox entry — so the entry's// `path` IS the staged path and there is nothing left to copy. The behaviour is// unchanged; only the moment of the copy moved, and it moved because the// extension is the only process that can read what the sharing app handed over.//// **The failure posture**: each file branch wraps its work, reports the drop,// and STILL navigates to the bare import screen, so the person lands where they// would have gone by hand.//// **The clear is unconditional and is now structural.** `ShareMailbox.drain`// removes the whole list before any branch runs, which is `finally {// resetShareIntent() }` said once instead of five times.import Foundation// The four classification rules and the staged files are `CottonMailbox`'s// (`ShareClassification.swift`): the share extension knocks by the same rules// the drain files by, and it links no core.// MARK: - Where a share lands/// A file waiting for the screen that will ask about it.////// `path` is inside the app group's container and outlives this drain: the/// import screen reads it, and the import screen is what finishes with it.public struct StagedShare: Equatable, Sendable {    public var path: String    /// The name to show while asking. A chat export is named after the chat by    /// the app that made it, which is how the import knows whose it is without    /// asking.    public var name: String    public init(path: String, name: String) {        self.path = path        self.name = name    }}/// Where this share sends the app, and what it is carrying.////// **`Route` cannot carry the staged file and this lane does not add a case/// for it.** `Route.messagesImport` is the crate's own/// route string (design P6: the LIST is `phone/routes.rs::ROUTES`, and/// `RouteTableTests` holds the enum set-equal to it), and takes no parameter. So the file rides BESIDE the/// route rather than inside it: `RootView` holds a chat export in/// `ChatExportHandoff` until the import screen is hosted and takes it.public struct ShareLanding: Equatable, Sendable {    public var route: Route    /// Present for branch 1 only; absent for every branch that files its row    /// itself and for every fallback landing, where there is nothing left to    /// hand over.    public var staged: StagedShare?    /// The record is the first of many this intake brought (a Goodreads    /// library, several books chosen at once): it stands on its tool's whole    /// view — Books' All — where every one of them is, never on the list    /// page over the deck (the coordinator, 4 Nov 2026).    public var many: Bool    public init(route: Route, staged: StagedShare? = nil, many: Bool = false) {        self.route = route        self.staged = staged        self.many = many    }    /// One intake's landings as the app takes them: two or more records of    /// one table land once, at the first of them, as `many` (several books    /// chosen at once stand on All at the first, not on whichever came in    /// last); every other landing stands as it came, in order, before it.    public static func landed(_ landings: [ShareLanding]) -> [ShareLanding] {        let records = landings.filter { if case .tableRecord = $0.route { true } else { false } }        guard records.count > 1, case .tableRecord(let table, _) = records[0].route,              records.allSatisfy({ if case .tableRecord(table, _) = $0.route { true } else { false } })        else { return landings }        var first = records[0]        first.many = true        return landings.filter { if case .tableRecord = $0.route { false } else { true } } + [first]    }}// MARK: - What went wrong/// A share the drain could not finish, reported rather than swallowed.////// This app has no reporting seam yet, so the closure is injected and has NO/// default — a default no-op would be the silent fallback the repo bans, and/// making every caller answer the question is that ban made structural. It is/// the shape ``PendingLinkTrouble`` already has, and the route strings are/// spelled the same way, so the two halves of one story stay searchable/// together.public struct ShareIntakeTrouble: Equatable, Sendable {    public var route: String    public var what: String    /// What to TELL the person, or nil when there is nothing they can do.    ///    /// A report goes to Bugsink and the console, which is right for a lane's    /// owner and is nothing at all for the person who just shared a voice note    /// and watched it vanish (the walk of 15 Sep 2026: a refused audio import    /// showed no toast, no row and no word). The host shows this where it shows    /// every other refusal; `what` stays the developer's sentence and this is    /// the reader's.    ///    /// A SECOND field rather than reusing `what`, because the two are different    /// sentences: "shared recording not imported: noBytes(…)" is not something    /// to put on a screen.    public var say: String?    public init(route: String, what: String, say: String? = nil) {        self.route = route        self.what = what        self.say = say    }}/// The one thing the drain itself can find wrong before it asks anybody.enum ShareIntakeFailure: Error, Equatable {    /// The extension wrote an entry and the bytes it names are not there — a    /// copy that failed, or a file some earlier pass already consumed. It is a    /// failure rather than a silence because the person shared something and is    /// owed the screen they would have opened by hand.    case noBytes(String)    /// A recording arrived whose name says nothing about its container and    /// whose declared type says nothing either. The crate reads the path, and    /// there is nothing in this one to read.    case noContainerNamed(String)    /// A file past what its branch reads whole (a Goodreads export).    case tooLarge(String)}// MARK: - The drain/// Drain the share mailbox: six branches, in one precedence, once per share.////// An `actor` rather than a `@MainActor` type because its work is awaits across/// the boundary — `capture.media` copies bytes and `page.save` writes rows, both/// of which block the calling thread inside Rust and so must never be on the/// main one (design P5). The navigation it decides is handed OUT through a/// closure the host runs where navigation belongs.public actor ShareIntake {    private let core: any CottonCalling    private let media: any MediaCapturing    private let books: any BookShelving    private let music: MusicIntake    private let filmIntake: FilmIntake    private let shelf: ShareShelf    private let mailbox: ShareMailbox    private let files: any ShareInboxFiles    private let navigate: @Sendable (ShareLanding) -> Void    /// The landings of the intake running now, taken once it has run    /// (`ShareLanding.landed`).    private var landings: [ShareLanding] = []    private let report: @Sendable (ShareIntakeTrouble) -> Void    private let tell: @Sendable (String) -> Void    /// `shelf` says what this app files a PDF as (`ShareShelf.ofThisApp()`);    /// `books` is the core's own shelf unless a test hands in another.    public init(        core: any CottonCalling,        shelf: ShareShelf,        books: (any BookShelving)? = nil,        mailbox: ShareMailbox = ShareMailbox(),        files: any ShareInboxFiles = DiskShareInboxFiles(),        navigate: @escaping @Sendable (ShareLanding) -> Void,        report: @escaping @Sendable (ShareIntakeTrouble) -> Void,        tell: @escaping @Sendable (String) -> Void    ) {        self.core = core        self.media = CoreMediaCapture(core: core)        self.books = books ?? CoreBookShelf(core: core)        self.music = MusicIntake(core: core, progress: { done, total in MusicIntakeProgress.shared.say(done, of: total) })        self.filmIntake = FilmIntake(core: core, progress: { done, total, reading in FilmIntakeProgress.shared.say(done, of: total, reading: reading) })        self.shelf = shelf        self.mailbox = mailbox        self.files = files        self.navigate = navigate        self.report = report        self.tell = tell    }    /// Take everything waiting and act on it, oldest first.    ///    /// The list is REMOVED before the first branch runs (``ShareMailbox/drain``    /// says why), so a share is acted on exactly once whatever happens next.    /// Shares are handled in arrival order and the app is sent where they landed    /// once all are in, so two shares drained together leave the app on the    /// second one's screen — which is what sharing them in that order would have    /// done had the app been open — but for two or more records of one table    /// (several books), which land once, at the first (`ShareLanding.landed`).    ///    /// The caller decides WHEN: `scenePhase → .active`, and only once the gate    /// is ready, because every branch either writes a row or opens a screen and    /// neither is possible before a file is open. That is the port of    /// `useReaderIntake`'s `if (!workspaceId … ) return` (`:71`).    @discardableResult    public func drain() async -> Int {        let entries = mailbox.drain()        await take(entries)        return entries.count    }    /// Take these entries through the same branches, without the mailbox —    /// Settings › Bring in's door (`BringInRoute`). The files are already    /// staged in the app group, exactly as the share extension stages them.    ///    /// **Not a second drain**: nothing is read out of the mailbox, so a share    /// waiting there for its one retry keeps waiting for a later foreground    /// (`ShareArrivals`). A refusal here is put back the same way any other is,    /// and the next foreground's drain is its retry.    public func intake(_ entries: [ShareEntry]) async {        await take(entries)    }    /// A book's Add file: the EPUB or PDF chosen for the book `id`, which has    /// none, taken through the book branch into that book (`BookShelving`'s    /// `into`); the app lands on it.    public func intake(_ entries: [ShareEntry], intoBook id: String) async {        bookInto = id        defer { bookInto = nil }        await take(entries)    }    /// The book a file taken now is for (a book's Add file); nil, a book of its own.    private var bookInto: String?    /// Books' Add a folder: the folders chosen, staged, taken through the    /// book folder's branch in every app (in Cotton a folder is otherwise    /// songs); the app lands on the books.    public func intake(_ entries: [ShareEntry], foldersAreBooks: Bool) async {        self.foldersAreBooks = foldersAreBooks        defer { self.foldersAreBooks = false }        await take(entries)    }    /// A folder taken now is books (Books' Add a folder).    private var foldersAreBooks = false    /// The entries through their branches, oldest first, and the app sent    /// where they landed once all have: many records of one table land once,    /// at the first (`ShareLanding.landed`).    private func take(_ entries: [ShareEntry]) async {        landings = []        for entry in entries { await handle(entry) }        let landed = ShareLanding.landed(landings)        landings = []        for landing in landed { navigate(landing) }    }    /// Where a branch sends the app, taken when its intake has run.    private func land(_ landing: ShareLanding) {        landings.append(landing)    }    private func handle(_ entry: ShareEntry) async {        if await fetched(entry) { return }        if let file = SharedFile(entry) {            if isPackageShare(file) { return await package(entry, file) }            // In Cotton Music a ZIP is first an album (a Bandcamp download);            // one holding no song goes on to branch 1 as it always did.            if shelf.audioIsMusic, isZipShare(file), await albumZip(entry, file) { return }            // The whole of branch 1, and the only branch that may read the            // file: a `.txt` neither named nor typed as an export is decided by            // its first line (`looksLikeChatExport`).            if isChatExportShare(file, head: { files.head(file.path) }) {                return await chatExport(file)            }            if isGoodreadsShare(file, head: { files.head(file.path) }) { return await goodreads(entry, file) }            if isOpmlShare(file, head: { files.head(file.path) }) { return await opml(entry, file) }            if let format = shareBookFormat(file, shelf: shelf) { return await book(entry, file, format) }            if shelf.pdfIsBook || foldersAreBooks, isFolderShare(file) { return await bookFolder(entry, file) }            if shelf.videoIsFilm, isFilmShare(file) || isFolderShare(file) { return await films(entry, file, onlyFilms: false) }            if shelf.videoMayBeFilm, mayBeFilmShare(file) { return await films(entry, file, onlyFilms: true) }            if isPictureShare(file) { return await picture(file) }            if isFolderShare(file) { return await songs(entry, file) }            if isAudioShare(file), isSong(file) { return await songs(entry, file) }            if isAudioShare(file) { return await recording(entry, file) }            // Branch 4 takes every file left. The URL extraction still runs            // afterwards — a share can carry a file AND an address, and the            // address is a fact about what was shared whatever happened to the            // bytes beside it.            await document(entry, file)            return await pages(entry, lands: false)        }        await pages(entry, lands: true)    }    // ── 5f. A share that is a download ─────────────────────────────────────    /// Whether the core took this share as a download (`share.fetchLinks`,    /// whose rule it is), queued in the object by `fetch_add` and opened on    /// its row. A refusal (a phone not signed in, an object that cannot be    /// reached) says the act's own words and lands nothing: a magnet kept as    /// a web page would be a page nobody can read.    private func fetched(_ entry: ShareEntry) async -> Bool {        var request: [String: JSONValue] = [:]        for (key, value) in [("url", entry.url), ("text", entry.text), ("title", entry.title), ("file", entry.path), ("fileName", entry.fileName)] {            if let value { request[key] = .string(value) }        }        do {            let ids = try await core.callJSON(CottonMethod.shareFetchLinks, request)["fetch"]?.array?.compactMap(\.string) ?? []            guard let first = ids.first else { return false }            land(ShareLanding(route: .tableRecord(table: "fetch", id: first), many: ids.count > 1))        } catch {            report(ShareIntakeTrouble(route: "reader-intake/fetch", what: "fetch-not-queued: \(error)", say: (error as? CottonCallError)?.message))        }        return true    }    // ── 0. A Cotton package ────────────────────────────────────────────────    /// A `.cottonpkg` another device wrote (Settings › Export), arriving    /// through the share sheet or Settings › Bring in.    ///    /// **Imported at once and asks nothing**: the core mints every record as    /// this device's owner and writes its bytes into the media store    /// (`Packages.import`), and the person is told what came in — there is no    /// one screen to open for records across several tables. A refusal keeps    /// the bytes once for one more drain, then reports and discards, the    /// posture branches 3 and 4 share.    private func package(_ entry: ShareEntry, _ file: SharedFile) async {        do {            _ = try stage(file, fallbackName: "package.\(cottonPackageExtension)")            let done = try await Packages(core: core).import(path: file.path)            files.discard(file.path)            tell(Self.receipt(done))        } catch {            let said = (error as? CottonCallError)?.message ?? ShellLines.line("databases", "package.refused")            if files.exists(file.path), mailbox.reoffer(entry) {                report(                    ShareIntakeTrouble(                        route: "reader-intake/package-import",                        what: "package-import-reoffered: \(error)", say: said))            } else {                files.discard(file.path)                report(                    ShareIntakeTrouble(                        route: "reader-intake/package-import",                        what: "package-import-discarded: \(error)", say: said))            }        }    }    /// What the person is told an import did.    static func receipt(_ done: PackageImported) -> String {        let brought = String(done.brought)        if !done.refused.isEmpty {            return ShellLines.line(                "databases", "package.brought_some", ["n": brought, "refused": String(done.refused.count)])        }        if done.brought == 0 { return ShellLines.line("databases", "package.nothing_new") }        return ShellLines.line("databases", "package.brought", ["n": brought])    }    // ── 1. A chat export ──────────────────────────────────────────────────    /// A shared zip — or a WhatsApp `_chat.txt` — is a chat export, and it    /// outranks URL extraction: an export share can also carry a text label the    /// extraction would happily misread.    private func chatExport(_ file: SharedFile) async {        do {            let staged = try stage(file)            land(ShareLanding(route: .messagesImport, staged: staged))        } catch {            // A missing file leaves the person exactly where a non-share entry            // starts: the import screen's own picker. But an intake that            // silently drops what was shared is a fault worth a report.            report(                ShareIntakeTrouble(                    route: "reader-intake/zip-stage",                    what: "shared chat export not staged: \(error)"                )            )            land(ShareLanding(route: .messagesImport))        }    }    // ── 1g. A Goodreads library ───────────────────────────────────────────    /// The ceiling on a Goodreads export read whole: a library of tens of    /// thousands of books is a few megabytes, so anything past this is no    /// export.    static let goodreadsCeiling = 32 * 1024 * 1024    /// A Goodreads library export (desktop Goodreads › My Books › Import and    /// export), handed WHOLE to the object's `import_goodreads`, which reads it    /// by its header and makes one book per row (found again by its Goodreads    /// id, so a second export brings the first up to date). Nothing is made    /// on the phone: the books arrive by sync, and the app opens the books.    ///    /// Kept once, then let go, like the documents: a first refusal keeps the    /// file for one more drain, a second reports and discards.    private func goodreads(_ entry: ShareEntry, _ file: SharedFile) async {        do {            _ = try stage(file, fallbackName: "goodreads.csv")            let url = URL(fileURLWithPath: file.path)            let size = (try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0            guard size <= Self.goodreadsCeiling else { throw ShareIntakeFailure.tooLarge(file.path) }            let text = String(decoding: try Data(contentsOf: url), as: UTF8.self)            let first = try await books.importGoodreads(text)            files.discard(file.path)            tell(ShellLines.line("boot", "books.goodreads_sent"))            // The library lands on the deck's All view at its first book,            // never on the list page over the deck; an export of no books            // has nothing to stand on.            if let first { land(ShareLanding(route: .tableRecord(table: "book", id: first), many: true)) }        } catch {            let said = (error as? CottonCallError)?.message ?? ShellLines.line("boot", "books.goodreads_refused")            if files.exists(file.path), mailbox.reoffer(entry) {                report(ShareIntakeTrouble(route: "reader-intake/goodreads", what: "goodreads-reoffered: \(error)", say: said))            } else {                files.discard(file.path)                report(ShareIntakeTrouble(route: "reader-intake/goodreads", what: "goodreads-discarded: \(error)", say: said))            }            land(ShareLanding(route: ShareKnock.bookList))        }    }    // ── 1o. A podcast subscription list ───────────────────────────────────    /// The ceiling on an OPML file read whole: a list of a thousand shows is    /// a few hundred kilobytes, so anything past this is no subscription list.    static let opmlCeiling = 8 * 1024 * 1024    /// A podcast app's subscription list (AntennaPod, Pocket Casts, Overcast    /// and the rest export OPML), handed WHOLE to `import_opml`, which the    /// core runs on the phone, signed in or not: it subscribes to every feed    /// the list names not already held and reads them into this copy; a list    /// past one run's hundred is asked again while a run brings shows in    /// (`PodcastSubscriptions.bring`), each run's words said as they come. The    /// app stands on the first new one, among the shows. A refusal (a file    /// that is not OPML) is said in the core's words.    ///    /// Kept once, then let go, like the Goodreads export.    private func opml(_ entry: ShareEntry, _ file: SharedFile) async {        do {            _ = try stage(file, fallbackName: "subscriptions.opml")            let url = URL(fileURLWithPath: file.path)            let size = (try? url.resourceValues(forKeys: [.fileSizeKey]).fileSize) ?? 0            guard size <= Self.opmlCeiling else { throw ShareIntakeFailure.tooLarge(file.path) }            let text = String(decoding: try Data(contentsOf: url), as: UTF8.self)            let runs = try await PodcastSubscriptions(core: core).bring(text, said: tell)            files.discard(file.path)            let first = runs.lazy.flatMap(\.podcasts).first            land(first.map { ShareLanding(route: .tableRecord(table: "podcast", id: $0), many: true) } ?? ShareLanding(route: ShareKnock.podcastList))        } catch {            let said = (error as? CottonCallError)?.message ?? ShellLines.line("databases", "bring_in.unreadable")            if files.exists(file.path), mailbox.reoffer(entry) {                report(ShareIntakeTrouble(route: "reader-intake/opml", what: "opml-reoffered: \(error)", say: said))            } else {                files.discard(file.path)                report(ShareIntakeTrouble(route: "reader-intake/opml", what: "opml-discarded: \(error)", say: said))            }            land(ShareLanding(route: ShareKnock.podcastList))        }    }    // ── 1b. A book ────────────────────────────────────────────────────────    /// An EPUB, or a PDF in Cotton Books: read for what it says about itself    /// and kept as a `book` row with its bytes in the store (`BookShelving`),    /// then opened. The posture of the documents branch: a first refusal keeps    /// the bytes for one more drain, a second reports and discards.    private func book(_ entry: ShareEntry, _ file: SharedFile, _ format: BookFormat) async {        do {            _ = try stage(file, fallbackName: "book.\(format.rawValue)")            let id = try await books.shelve(URL(fileURLWithPath: file.path), format: format, fileName: file.fileName, into: bookInto)            files.discard(file.path)            land(ShareLanding(route: id.isEmpty ? ShareKnock.bookList : .tableRecord(table: "book", id: id)))        } catch {            let said = (error as? CottonCallError)?.message ?? ShellLines.line("boot", "books.refused")            if files.exists(file.path), mailbox.reoffer(entry) {                report(ShareIntakeTrouble(route: "reader-intake/book-add", what: "book-add-reoffered: \(error)", say: said))            } else {                files.discard(file.path)                report(ShareIntakeTrouble(route: "reader-intake/book-add", what: "book-add-discarded: \(error)", say: said))            }            land(ShareLanding(route: ShareKnock.bookList))        }    }    // ── 1d. A folder of books ─────────────────────────────────────────────    /// A folder (a Calibre library, or EPUBs and PDFs), shared into Cotton    /// Books or chosen at Books' Add a folder: every file in the tree handed    /// to the core's `books.folder`, which says what is a book and lands each    /// one; its words are said, each refused book's why with them, and the    /// app stands on the books' All at the first that is here. A folder the    /// core finds no book in is refused in its words. The documents' posture    /// on a refusal: kept for one more drain, then reported and gone.    private func bookFolder(_ entry: ShareEntry, _ file: SharedFile) async {        do {            _ = try stage(file, fallbackName: "books")            let answer = try await BookFolder.bring(BookFolder.files(in: URL(fileURLWithPath: file.path)), core: core)            files.discard(file.path)            tell(answer.said)            land(answer.landing.map { ShareLanding(route: .tableRecord(table: "book", id: $0), many: true) } ?? ShareLanding(route: ShareKnock.bookList))        } catch {            let said = (error as? CottonCallError)?.message ?? ShellLines.line("boot", "books.refused")            if files.exists(file.path), mailbox.reoffer(entry) {                report(ShareIntakeTrouble(route: "reader-intake/book-folder", what: "book-folder-reoffered: \(error)", say: said))            } else {                files.discard(file.path)                report(ShareIntakeTrouble(route: "reader-intake/book-folder", what: "book-folder-discarded: \(error)", say: said))            }            land(ShareLanding(route: ShareKnock.bookList))        }    }    // ── 1c. Songs ─────────────────────────────────────────────────────────    /// Whether a shared audio file is a song: always in Cotton Music; else a    /// format no recording comes in (`isMusicOnlyShare`), or a file whose tags    /// name a song (a voice memo or a WhatsApp voice note names none, and    /// stays a recording).    private func isSong(_ file: SharedFile) -> Bool {        if shelf.audioIsMusic { return true }        if isMusicOnlyShare(file) { return true }        return SongTagReader.read(URL(fileURLWithPath: file.path))?.tags.namesASong == true    }    /// An audio file, or a folder of them: read, kept as songs of their albums    /// with their bytes in the store (`MusicIntake`), then the last one that    /// came in opened. A file already here is said and opened. The documents'    /// posture on a refusal: kept for one more drain, then reported and gone.    private func songs(_ entry: ShareEntry, _ file: SharedFile) async {        do {            _ = try stage(file, fallbackName: "song")            let url = URL(fileURLWithPath: file.path)            let found = isFolderShare(file)                ? MusicIntake.songs(in: url, named: file.fileName ?? url.lastPathComponent)                : [MusicFile(url: url, sourcePath: file.fileName ?? url.lastPathComponent)]            guard !found.isEmpty else {                files.discard(file.path)                tell(ShellLines.line("music", "intake.folder_empty"))                return navigate(ShareLanding(route: ShareKnock.songList))            }            let result = try await music.bring(found)            files.discard(file.path)            if let said = result.said { tell(said) }            navigate(ShareLanding(route: result.landing.map { .tableRecord(table: "song", id: $0) } ?? ShareKnock.songList))        } catch {            MusicIntakeProgress.shared.done()            let said = (error as? CottonCallError)?.message ?? ShellLines.line("music", "intake.refused", ["name": file.fileName ?? ""])            if files.exists(file.path), mailbox.reoffer(entry) {                report(ShareIntakeTrouble(route: "reader-intake/song-add", what: "song-add-reoffered: \(error)", say: said))            } else {                files.discard(file.path)                report(ShareIntakeTrouble(route: "reader-intake/song-add", what: "song-add-discarded: \(error)", say: said))            }            navigate(ShareLanding(route: ShareKnock.songList))        }    }    // ── 1z. An album ZIP ──────────────────────────────────────────────────    /// In Cotton Music, a ZIP whose songs make one album (a Bandcamp    /// download, 7 Nov 2026) comes in as that album with its cover, its shop    /// and its booklet (`MusicIntake.bringZip`), and the app opens it. False    /// when it holds no song at all: it goes on to the branch a ZIP always    /// took. A ZIP that is no one album, or cannot be opened, is said; a    /// refused capture takes the documents' posture.    private func albumZip(_ entry: ShareEntry, _ file: SharedFile) async -> Bool {        let name = file.fileName ?? URL(fileURLWithPath: file.path).lastPathComponent        do {            _ = try stage(file, fallbackName: "album.zip")            switch try await music.bringZip(URL(fileURLWithPath: file.path), name: name) {            case .refused(noSongs: true, _):                MusicIntakeProgress.shared.done()                return false            case .refused(noSongs: false, let said):                MusicIntakeProgress.shared.done()                files.discard(file.path)                tell(said)                land(ShareLanding(route: ShareKnock.songList))            case .album(let result):                MusicIntakeProgress.shared.done()                files.discard(file.path)                if let said = result.said { tell(said) }                let landing: Route = result.album.map { .tableRecord(table: "music_album", id: $0) }                    ?? result.landing.map { .tableRecord(table: "song", id: $0) } ?? ShareKnock.songList                land(ShareLanding(route: landing))            }        } catch {            MusicIntakeProgress.shared.done()            let said = (error as? CottonCallError)?.message ?? ShellLines.line("music", "intake.refused", ["name": name])            if files.exists(file.path), mailbox.reoffer(entry) {                report(ShareIntakeTrouble(route: "reader-intake/album-zip", what: "album-zip-reoffered: \(error)", say: said))            } else {                files.discard(file.path)                report(ShareIntakeTrouble(route: "reader-intake/album-zip", what: "album-zip-discarded: \(error)", say: said))            }            land(ShareLanding(route: ShareKnock.songList))        }        return true    }    // ── 1f. Films ─────────────────────────────────────────────────────────    /// A video, or a folder of them: read, kept as films and episodes with    /// their bytes in the store (`FilmIntake`), then the last one that came    /// in opened. With `onlyFilms` (Cotton) a clip the core says is no film    /// goes on to the pictures' branch, as it always did. The documents'    /// posture on a refusal: kept for one more drain, then reported and gone.    private func films(_ entry: ShareEntry, _ file: SharedFile, onlyFilms: Bool) async {        do {            _ = try stage(file, fallbackName: "film")            let url = URL(fileURLWithPath: file.path)            let found = isFolderShare(file)                ? FilmIntake.films(in: url, named: file.fileName ?? url.lastPathComponent)                : [FilmFile(url: url, sourcePath: Self.filmName(file))]            guard !found.isEmpty else {                files.discard(file.path)                tell(ShellLines.line("cinemas", "intake.folder_empty"))                return land(ShareLanding(route: ShareKnock.filmList))            }            let result = try await filmIntake.bring(found, onlyFilms: onlyFilms)            FilmIntakeProgress.shared.done()            if onlyFilms, !result.notFilms.isEmpty { return await picture(file) }            files.discard(file.path)            if let said = result.said { tell(said) }            land(ShareLanding(route: result.landing.map { .tableRecord(table: $0.table, id: $0.id) } ?? ShareKnock.filmList))        } catch {            FilmIntakeProgress.shared.done()            let said = (error as? CottonCallError)?.message ?? ShellLines.line("cinemas", "intake.refused", ["name": file.fileName ?? ""])            if files.exists(file.path), mailbox.reoffer(entry) {                report(ShareIntakeTrouble(route: "reader-intake/film-add", what: "film-add-reoffered: \(error)", say: said))            } else {                files.discard(file.path)                report(ShareIntakeTrouble(route: "reader-intake/film-add", what: "film-add-discarded: \(error)", say: said))            }            land(ShareLanding(route: ShareKnock.filmList))        }    }    /// A film door's files (Plus › Add files, Add a folder), read where the    /// person keeps them, inside their security scope, and copied once —    /// into this device's store, by the core — never staged into the share    /// inbox first and never discarded: they are the person's own. Kept as    /// films and episodes, then the last one that came in opened; a refusal    /// is said.    public func films(inPlace urls: [URL]) async {        let scoped = urls.filter { $0.startAccessingSecurityScopedResource() }        defer { scoped.forEach { $0.stopAccessingSecurityScopedResource() } }        let found = urls.flatMap { url in            url.hasDirectoryPath                ? FilmIntake.films(in: url, named: url.lastPathComponent)                : [FilmFile(url: url, sourcePath: url.lastPathComponent)]        }        guard !found.isEmpty else {            tell(ShellLines.line("cinemas", "intake.folder_empty"))            return navigate(ShareLanding(route: ShareKnock.filmList))        }        do {            let result = try await filmIntake.bring(found, onlyFilms: false)            FilmIntakeProgress.shared.done()            if let said = result.said { tell(said) }            navigate(ShareLanding(route: result.landing.map { .tableRecord(table: $0.table, id: $0.id) } ?? ShareKnock.filmList))        } catch {            FilmIntakeProgress.shared.done()            tell((error as? CottonCallError)?.message ?? ShellLines.line("cinemas", "intake.refused", ["name": urls.first?.lastPathComponent ?? ""]))            navigate(ShareLanding(route: ShareKnock.filmList))        }    }    /// The name a shared film came in as, its container on it: the core    /// reads a film's title and year, or its series and episode, from it.    static func filmName(_ file: SharedFile) -> String {        let staged = URL(fileURLWithPath: file.path)        guard let name = file.fileName, !name.isEmpty else { return staged.lastPathComponent }        return shareFileExtension(name).isEmpty && !staged.pathExtension.isEmpty ? "\(name).\(staged.pathExtension)" : name    }    // ── 2. A picture or a clip ────────────────────────────────────────────    /// A photo out of the camera roll, a clip out of another app.    ///    /// **Unlike the three branches around it this one does NOT land on an import    /// screen: there is nothing to answer.** A picture is not locked, is not    /// somebody else's paper and spends no metered reading — it is bytes the    /// person already holds, so the row is written immediately, exactly as the    /// library picker's is.    ///    /// **It opens the record it just wrote**, a photo in Photos and a clip    /// in Videos, and asks nothing about it (the owner, 23 Oct 2026: a    /// picture shared in goes straight in, no composer between). A crate that    /// answered no record id (an answer this phone cannot name a picture by)    /// lands on the library instead — the row is there, under no name.    private func picture(_ file: SharedFile) async {        let video = shareFileKind(file) == .video        do {            _ = try stage(file)            // The capture composer's own helper (`CoreMediaCapture`): the tiers            // are made off the main actor — a 4 MB HEIC decode on the main            // actor is a visible stall on a share sheet the person is watching —            // from the file already in the app group, so nothing touches the            // radio, and the crate copies every tier into the store.            let landed = try await media.capture(                file: URL(fileURLWithPath: file.path),                mime: pictureContentType(file),                kind: video ? .video : .photo,                filename: file.fileName            )            // The bytes are in the content-addressed store now, so the            // extension's copy has done its job. Only on success: a capture            // that did not land is bytes nobody else is holding.            files.discard(file.path)            // One share carries one file, so the picture is ONE — and its kind            // is `shareFileKind`'s, the same rule that put this file in this            // branch.            guard !landed.recordId.isEmpty else {                land(ShareLanding(route: video ? .videos : .photos(show: nil)))                return            }            // On the library's deck at its card: a photo's and a video's            // media row has the picture's own id, and the fan brings a            // record of the table its Photos tile stands on (`fanBrings`),            // never a page of the photo pushed over the deck (Photos walk,            // 12 Nov 2026: three pictures chosen at Plus stood on a deck of            // their own, and the fan's views changed nothing under it).            land(ShareLanding(route: .tableRecord(table: "media", id: landed.recordId)))        } catch {            // The same posture as the branches around it: land where the person            // would have gone by hand, and report the drop.            report(                ShareIntakeTrouble(                    route: "reader-intake/picture-add",                    what: "shared picture not captured: \(error)"                )            )            land(ShareLanding(route: .photos(show: nil)))        }    }    // ── 3. A recording ────────────────────────────────────────────────────    /// A shared audio file IS a meeting, and this is where it becomes one.    ///    /// It stays third, and without it a voice memo would fall through to branch    /// 4 and be filed as a paper.    ///    /// **Like branch 2 it writes at once and asks nothing** — see the header.    ///    /// The title is the file's stem when the sharing app gave a name — a voice    /// note is called something, and "Voice note 2026-09-15" beats the day the    /// crate would otherwise stamp. With no name at all nothing is sent and the    /// crate names it.    ///    /// ## Kept once, then let go — and said out loud either way    ///    /// The copy is discarded on SUCCESS, because the crate has the bytes in the    /// store by then. A refusal used to leave it where it was for ever, on the    /// reasoning that bytes nobody else is holding are not deleted on this    /// app's opinion that the call failed. The reasoning is right and the    /// forever was not: the walk of 15 Sep 2026 left `.opus` and `.mp3` files    /// in the app group's `share-inbox/` with nothing that knew they were    /// there, and nothing on screen to say a share had failed at all.    ///    /// So a first failure KEEPS the bytes and puts the entry back    /// (``ShareMailbox/reoffer(_:)``) — the next foreground tries once more,    /// which is what rescues an import that failed because the file was not    /// open yet or the phone was mid-anything. A second failure REPORTS with    /// the reason and discards: bytes that two drains could not file are bytes    /// this app is keeping against a failure it has already had twice.    ///    /// **Both failures say something.** The person shared a recording; a lane    /// that only tells Bugsink is a lane that told nobody.    private func recording(_ entry: ShareEntry, _ file: SharedFile) async {        // The path as it stands, which a rescue rename may move — reported and        // discarded by its CURRENT name, never the one that was handed over.        var here = file.path        do {            let staged = try stage(file)            here = try meetingPath(staged, file)            let created = try await core.call(                CottonMethod.meetingsCreate,                MeetingCreateRequest(                    path: here,                    source: .import,                    title: file.fileName.map(MeetingAudioFormats.titleFromFileName),                    mime: MeetingAudioFormats.mime(forFileName: here)                ),                as: MeetingCreated.self            )            // The crate has copied the bytes into the store, so the extension's            // copy has done its job. The path DISCARDED is the one that was            // sent: a rescue rename moved it, and discarding the old name would            // leave the real file behind for ever.            files.discard(here)            land(ShareLanding(route: created.landing))        } catch {            let said = (error as? CottonCallError)?.message            if mailbox.reoffer(ShareEntry(entry, movedTo: here)) {                report(                    ShareIntakeTrouble(                        route: "reader-intake/audio-import",                        what: "shared recording not imported, kept for one more try: \(error)",                        say: said ?? "That recording didn't file. Cotton will try again."                    )                )            } else {                files.discard(here)                report(                    ShareIntakeTrouble(                        route: "reader-intake/audio-import",                        what: "shared recording not imported twice, discarded: \(error)",                        say: said ?? "That recording couldn't be filed."                    )                )            }            land(ShareLanding(route: .meetings(importing: false)))        }    }    /// The path to hand the crate, which must END in a container it reads.    ///    /// The staged copy usually already does — the share extension keeps the    /// source's extension for exactly this reason. When it does not, the    /// DECLARED type is what says which container the bytes are in, and the    /// copy is renamed to match. A share that says neither is a refusal, and it    /// is made HERE rather than three seconds later in the crate, because a    /// refusal this phone could have prevented is one it should have.    private func meetingPath(_ staged: StagedShare, _ file: SharedFile) throws -> String {        if MeetingAudioFormats.accepts(fileName: staged.path) { return staged.path }        let named =            MeetingAudioFormats.fileExtension(forDeclaredType: file.declared)            ?? (MeetingAudioFormats.accepts(fileName: file.nameOrPath)                ? shareFileExtension(file.nameOrPath) : nil)        guard let named else { throw ShareIntakeFailure.noContainerNamed(file.nameOrPath) }        guard let moved = files.renamed(staged.path, extension: named) else {            throw ShareIntakeFailure.noBytes(staged.path)        }        return moved    }    // ── 4. Any other file ─────────────────────────────────────────────────    /// A statement out of an email, a scan out of Files, a PDF, a spreadsheet,    /// an archive, a file with no name — kept as a document.    ///    /// **Filed at once, like branches 2 and 3**, through the same    /// `capture.media` the documents screen's own Files pick calls, so the    /// bytes are in the content-addressed store and the row names them before    /// the app opens its page. The core reads a document on the Mac when there    /// is one; on a phone with none it is still the person's file, kept.    ///    /// **Kept once, then let go — and said out loud either way**, the    /// recordings branch's posture and for the same reason: a first refusal    /// keeps the bytes and puts the entry back for one more drain, a second    /// reports in the core's own words and discards. A core that answers no    /// record id lands on the documents list, where the row is.    private func document(_ entry: ShareEntry, _ file: SharedFile) async {        do {            _ = try stage(file, fallbackName: "document")            let kept = try await media.capture(                file: URL(fileURLWithPath: file.path),                mime: documentContentType(file),                kind: .document,                filename: file.fileName            )            files.discard(file.path)            land(                ShareLanding(                    route: kept.recordId.isEmpty                        ? .documents(status: nil) : .documentsDocument(id: kept.recordId)                )            )        } catch {            let said = (error as? CottonCallError)?.message            if files.exists(file.path), mailbox.reoffer(entry) {                report(                    ShareIntakeTrouble(                        route: "reader-intake/document-add",                        what: "document-add-reoffered: \(error)",                        say: said ?? ShellLines.line("boot", "document_import.refused")                    )                )            } else {                files.discard(file.path)                report(                    ShareIntakeTrouble(                        route: "reader-intake/document-add",                        what: "document-add-discarded: \(error)",                        say: said ?? ShellLines.line("boot", "document_import.refused")                    )                )            }            land(ShareLanding(route: .documents(status: nil)))        }    }    // ── 5. The URLs ───────────────────────────────────────────────────────    /// The residue: a link, a page, or prose that may carry several links.    ///    /// **ONE call, and the crate makes one row per URL.** The extraction is    /// `page.save`'s own (`validate_pages`, `phone/page.rs:83-105`), which mints    /// a row per URL and answers `{ids}`. A Swift loop would need a second URL    /// regex up here, which is exactly what that file says the app must not    /// grow: two spellings of "what counts as a URL" is two spellings of one    /// page, which is two rows in the reading pile.    ///    /// The URL WINS over the text when both are present — a page share carries    /// both, and the address is the fact.    ///    /// **The link keeps the title the sharing app gave it** (Safari's is the    /// page's own), unless that title is only the address again: a card titled    /// by its title, its site beside it.    ///    /// **A share that was ONLY a link or prose closes on its card** — the    /// `page` row on the Web pages tool's tile, brought on the fan as a shared    /// book is (`fanBrings`); several links stand there at the first of them,    /// `many` — because the sheet opened the app for it (`ShareKnock`, the    /// owner's ruling of 23 Oct 2026) and an app that opens on nothing new has    /// not shown where it went. An address beside a file does not move the    /// app: the file's own branch has already landed it.    private func pages(_ entry: ShareEntry, lands: Bool) async {        let request: PageSaveRequest        if let url = entry.url?.trimmingCharacters(in: .whitespacesAndNewlines), !url.isEmpty {            let title = entry.title?.trimmingCharacters(in: .whitespacesAndNewlines)            request = .url(url, title: title?.isEmpty == false && title != url ? title : nil)        } else if let text = entry.text?.trimmingCharacters(in: .whitespacesAndNewlines),            !text.isEmpty        {            request = .text(text)        } else {            // Nothing to save, so nothing happens.            return        }        do {            let saved = try await core.call(CottonMethod.pageSave, request, as: PagesSaved.self)            guard lands else { return }            guard let first = saved.ids.first else { return land(ShareLanding(route: .reader)) }            land(ShareLanding(route: .tableRecord(table: "page", id: first), many: saved.ids.count > 1))        } catch {            // This app has no query cache to fail into, so the drop is            // reported, and a link-only share still lands where it would have.            report(                ShareIntakeTrouble(                    route: "reader-intake/page-save",                    what: "shared link not saved: \(error)"                )            )            if lands { land(ShareLanding(route: .reader)) }        }    }    // ── The staged file ───────────────────────────────────────────────────    /// The file this branch is about to hand on, or a failure.    ///    /// The COPY already happened — the share extension made it before it wrote    /// the mailbox entry, because it is the only process that can read what the    /// sharing app handed over. What is left is the check: bytes that are not    /// there are a failure, and they take the same path as any other — a    /// report, and the bare import screen.    private func stage(_ file: SharedFile, fallbackName: String = "") throws -> StagedShare {        guard files.exists(file.path) else { throw ShareIntakeFailure.noBytes(file.path) }        return StagedShare(path: file.path, name: file.fileName ?? fallbackName)    }}