Cotton code
321 lines · 14.2 KB · SwiftRaw
// Bringing a recording in from Files.//// Three things decide whether this works on a train with a voice note in// iCloud Drive: what the picker OFFERS, that the bytes are copied while the// security scope is still open, and that the copy is dropped afterwards. Each// is a section below, and none of them needs a picker, a container or a// boundary — the file is a real one under the temporary directory, the holding// area is a `MeetingAudioStore` over the same, and the core is scripted.import CottonKitimport UniformTypeIdentifiersimport XCTest@testable import CottonUI// MARK: - The holding area, without an App Group/// What `AppGroupMeetingAudioStore` is on a phone, under a temporary directory/// a test process actually has. The ledger is what the cases assert on: this is/// the seam that says whether a copy was made and whether it was dropped.private struct TempAudioStore: MeetingAudioStore {    let root: URL    final class Ledger: @unchecked Sendable {        private let lock = NSLock()        private(set) var opened: [String] = []        private(set) var discarded: [String] = []        func open(_ name: String) {            lock.lock()            defer { lock.unlock() }            opened.append(name)        }        func drop(_ act: String) {            lock.lock()            defer { lock.unlock() }            discarded.append(act)        }    }    let ledger = Ledger()    func captures() -> [MeetingCaptureOnDisk] { MeetingFiles.captures(under: root) }    func open(act: String, named: String) throws -> URL {        ledger.open(named)        let directory = root.appendingPathComponent(act, isDirectory: true)        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)        return directory.appendingPathComponent(named)    }    func discard(act: String) {        ledger.drop(act)        try? FileManager.default.removeItem(at: root.appendingPathComponent(act, isDirectory: true))    }}private let meetingId = "9a7c1f22-0b3d-4e55-8a91-6f0c2d4b8e77"private let meetingAnswer = ScriptedCore.Reply.ok(    #"{"id":"\#(meetingId)","route":"/meetings/meeting/\#(meetingId)","key":"ws-1/meetings/\#(meetingId)/full.m4a"}"#)private struct AskedMeeting: Decodable {    let path: String    let source: String    let title: String?    let mime: String?    let startedAt: String?    let durationMs: Int?}@MainActorfinal class MeetingImportTests: XCTestCase {    private var scratch = FileManager.default.temporaryDirectory    override func setUpWithError() throws {        scratch = FileManager.default.temporaryDirectory            .appendingPathComponent("cotton-import-\(UUID().uuidString)", isDirectory: true)        try FileManager.default.createDirectory(at: scratch, withIntermediateDirectories: true)    }    override func tearDownWithError() throws {        try? FileManager.default.removeItem(at: scratch)    }    /// A file sitting where a picked one would be. Not in the holding area —    /// the whole point of staging is that it starts somewhere this app does not    /// own.    private func picked(_ name: String, bytes: String = "not really audio") throws -> URL {        let url = scratch.appendingPathComponent(name)        try Data(bytes.utf8).write(to: url)        return url    }    private func store() -> TempAudioStore {        TempAudioStore(            root: scratch.appendingPathComponent("holding", isDirectory: true))    }    // ── What the picker offers ────────────────────────────────────────────    /// A picker that offered a container the crate refuses is a picker that    /// lied: the person chooses a file, watches a copy happen and then reads a    /// refusal. So everything on this list is audio the crate takes.    func testEveryTypeOfferedIsAudioAndNothingOfferedIsAMovie() {        let offered = MeetingImport.pickerTypes        XCTAssertTrue(offered.contains(.audio), "the family itself is the first entry")        // The two Xiph types are this APP's declarations, and a test bundle        // carries no `UTImportedTypeDeclarations` — so the system answers them        // as types with no registered conformance here. The declaration itself        // is held by the case below.        let declaredByThisApp = Set([MeetingImport.ogg, MeetingImport.opus])        for type in offered where !declaredByThisApp.contains(type) {            XCTAssertTrue(                type == .audio || type.conforms(to: .audio),                "\(type.identifier) is on a recordings picker and is not audio"            )            XCTAssertFalse(                type.conforms(to: .movie),                """                \(type.identifier) is a movie. `public.mpeg-4` conforms to both, \                and offering it fills a recordings picker with every video on \                the phone — an audio-only mp4 arrives through the share sheet.                """            )        }    }    /// iOS ships no type for either, so this app declares them    /// (`project.yml`'s `UTImportedTypeDeclarations`). Without the declaration    /// a WhatsApp voice note reaches the picker as `public.data` and cannot be    /// chosen at all — which is the exact file this is for.    ///    /// Asserted as VALUES, never as identifier strings: a Mac already knows    /// `org.xiph.ogg` and answers with its own `org.xiph.ogg-audio`, so the    /// identifier on the list is the system's and differs by platform. What has    /// to be true on both is that the type this app asks for is on the picker.    func testTheTwoXiphTypesThisAppDeclaresAreOffered() {        let offered = MeetingImport.pickerTypes        XCTAssertTrue(offered.contains(MeetingImport.ogg), offered.map(\.identifier).description)        XCTAssertTrue(offered.contains(MeetingImport.opus), offered.map(\.identifier).description)    }    func testNoTypeIsOfferedTwice() {        let identifiers = MeetingImport.pickerTypes.map(\.identifier)        XCTAssertEqual(identifiers.count, Set(identifiers).count, identifiers.description)    }    // ── The copy ──────────────────────────────────────────────────────────    /// **The name is kept, extension and all.** The crate reads a meeting's    /// container off the FILE's name, so a copy renamed to a bare id is a copy    /// the crate refuses.    func testStagingKeepsTheFilesOwnNameSoTheContainerSurvives() throws {        let files = store()        let source = try picked("Board review.m4a")        let staged = try MeetingImport.stage(source, into: files)        XCTAssertEqual(files.ledger.opened, ["Board review.m4a"])        XCTAssertTrue(staged.path.hasSuffix("/Board review.m4a"), staged.path)        XCTAssertTrue(staged.path.contains(staged.act), "and it sits under its own act")        XCTAssertTrue(FileManager.default.fileExists(atPath: staged.path))        XCTAssertTrue(            FileManager.default.fileExists(atPath: source.path(percentEncoded: false)),            "the original is untouched — it is still in Files, where the person left it"        )    }    func testACopyThatCannotBeMadeTakesTheHalfMadeDirectoryWithIt() throws {        let files = store()        let missing = scratch.appendingPathComponent("never-existed.m4a")        XCTAssertThrowsError(try MeetingImport.stage(missing, into: files)) { error in            XCTAssertEqual(error as? MeetingFilesFailure, .couldNotCopy)        }        XCTAssertEqual(            files.ledger.discarded.count, 1,            "an act directory with nothing in it is not left behind in the container"        )    }    // ── The whole act ─────────────────────────────────────────────────────    func testAPickedRecordingBecomesAMeetingAndTheCopyIsDropped() async throws {        let core = ScriptedCore([CottonMethod.meetingsCreate: meetingAnswer])        let files = store()        let source = try picked("Board review.m4a")        let created = try await MeetingImport.bring(source, through: ScreenWriter(core: core), into: files)        XCTAssertEqual(created.landing, .meetingsMeeting(id: meetingId))        let calls = await core.calls        XCTAssertEqual(calls.map(\.method), [CottonMethod.meetingsCreate])        let sent = try JSONDecoder().decode(AskedMeeting.self, from: Data(calls[0].requestJSON.utf8))        XCTAssertEqual(sent.source, "import")        XCTAssertEqual(sent.title, "Board review", "the file's own stem names the meeting")        XCTAssertEqual(sent.mime, "audio/mp4")        XCTAssertNil(sent.startedAt, "a file does not say when it was recorded, and a guess is worse")        XCTAssertNil(sent.durationMs, "nor how long it ran — the crate reads that off the bytes")        XCTAssertTrue(sent.path.hasSuffix("/Board review.m4a"), sent.path)        XCTAssertEqual(files.ledger.discarded.count, 1)        XCTAssertFalse(            FileManager.default.fileExists(atPath: sent.path),            "the crate has the bytes, so this app's copy has done its job"        )    }    /// **Different from the share sheet's rule, on purpose.** A shared copy is    /// KEPT on a refusal because the sharing app has already let go of the    /// original. A picked file is still in Files: the person can pick it again,    /// and a second copy kept for ever would be this app hoarding against a    /// failure it did not have.    func testARefusedImportStillDropsTheCopyBecauseTheFileIsStillInFiles() async throws {        let core = ScriptedCore([            CottonMethod.meetingsCreate:                .refuse(code: "too_large", message: "this recording is over the ceiling")        ])        let files = store()        let source = try picked("Long one.m4a")        do {            _ = try await MeetingImport.bring(source, through: ScreenWriter(core: core), into: files)            XCTFail("a refusal is not a success")        } catch let refusal as CottonCallError {            XCTAssertEqual(                refusal.message, "this recording is over the ceiling",                "and the crate's own sentence is what the screen shows, not one written up here"            )        }        XCTAssertEqual(files.ledger.discarded.count, 1)        XCTAssertTrue(            FileManager.default.fileExists(atPath: source.path(percentEncoded: false)),            "and the original is still there to pick again"        )    }    /// A picker can be talked past — a type the system mapped wrongly, a file    /// renamed by hand — so the extension is checked BEFORE a byte is copied.    func testAFileThatIsNotARecordingIsRefusedBeforeAnythingIsCopied() async throws {        let core = ScriptedCore([CottonMethod.meetingsCreate: meetingAnswer])        let files = store()        let source = try picked("minutes.txt")        do {            _ = try await MeetingImport.bring(source, through: ScreenWriter(core: core), into: files)            XCTFail("a .txt is not a recording")        } catch let refusal as MeetingImportFailure {            XCTAssertEqual(refusal, .notARecording("txt"))            XCTAssertTrue(refusal.errorDescription?.contains(".txt") == true, refusal.errorDescription ?? "")        }        XCTAssertEqual(files.ledger.opened, [], "no copy was made to reach a refusal")        let calls = await core.calls        XCTAssertEqual(calls, [], "and the boundary was never asked")    }    // ── Where it lands, and what it leaves behind ─────────────────────────    /// **The `?import=1` entry is spent by the landing.**    ///    /// It is an intent, not a place: the Meetings screen raises the picker in    /// its `.task`, and a `.task` runs again every time the screen comes back.    /// The walk of 15 Sep 2026 imported a recording, took Back off the meeting,    /// and had the Files picker thrown up over the list it had just returned    /// to — for ever, every time.    func testTheLandingReplacesTheImportIntentRatherThanStackingOverIt() {        let landing = Route.meetingsMeeting(id: meetingId)        let after = MeetingImport.landed(landing, over: [.home, .meetings(importing: true)])        XCTAssertEqual(after, [.home, .meetings(importing: false), landing])        XCTAssertFalse(            after.contains(.meetings(importing: true)),            "nothing left on the stack asks for the picker again: \(after)"        )        XCTAssertEqual(            after.dropLast().last, .meetings(importing: false),            "and Back is the list the new meeting is in, not whatever was under the fan"        )    }    /// The plus circle raises the same picker from a plain `/meetings`. There    /// is no intent there to spend, and replacing the list would leave the    /// person with no list to go back to.    func testAnImportFromTheListItselfIsAPlainPush() {        let landing = Route.meetingsMeeting(id: meetingId)        XCTAssertEqual(            MeetingImport.landed(landing, over: [.home, .meetings(importing: false)]),            [.home, .meetings(importing: false), landing]        )        XCTAssertEqual(MeetingImport.landed(landing, over: []), [landing], "and at the root it is one")    }    /// Only the TOP entry is the one being stood on. An `?import=1` further    /// down was spent by its own landing and is not this import's to rewrite.    func testAnImportIntentDeeperInTheStackIsLeftAlone() {        let landing = Route.meetingsMeeting(id: meetingId)        let deep: [Route] = [.meetings(importing: true), .meetingsMeeting(id: "example-earlier")]        XCTAssertEqual(MeetingImport.landed(landing, over: deep), deep + [landing])    }    func testAFileWithNoExtensionSaysThatInsteadOfNamingOne() async throws {        let core = ScriptedCore()        let files = store()        let source = try picked("recording")        do {            _ = try await MeetingImport.bring(source, through: ScreenWriter(core: core), into: files)            XCTFail("a file with no container is not a recording either")        } catch let refusal as MeetingImportFailure {            XCTAssertEqual(refusal, .notARecording(""))        }    }}