Cotton code
189 lines · 12.3 KB · SwiftRaw
import CottonKitimport CottonValuesimport Foundationimport XCTest@testable import CottonUI/// A film's or an episode's record plays in Apple's player, dealt by the/// core's one player (`shell.player`); everything else that plays is the one viewer's/// (`FilmPlayer`). What this phone keeps of a film's file — a stream's bundle/// or a whole file — goes through the core's device-local store/// (`FilmHereStore`, `phone::films`); where it was stopped is the record's.final class FilmStreamTests: XCTestCase {    private func film(_ key: String?, id: String = "film/1", table: String = "film") -> ViewerItem {        ViewerItem(id: id, kind: .video, key: key, title: "Synthetic Test Pattern", record: ViewerRecord(table: table, id: id))    }    /// RULE (Cinemas, 5 Nov 2026): A film's or a film episode's record plays as a film whatever its file is — a stream, a whole file, or none yet (a series) — and a clip shared in, a picture or a document stays the viewer's.    func testWhichPlayerForWhichFile() {        XCTAssertEqual(FilmPlayer.of(film("db/films/f1/master.m3u8")), .cinema)        XCTAssertEqual(FilmPlayer.of(film("db/films/f1/whole.mp4")), .cinema)        XCTAssertEqual(FilmPlayer.of(film(nil)), .cinema, "a series plays its episode in progress")        XCTAssertEqual(FilmPlayer.of(film("db/films/e1/whole.mov", table: "film_episode")), .cinema)        XCTAssertEqual(FilmPlayer.of(ViewerItem(id: "v", kind: .video, key: "db/videos/clip.mp4")), .viewer)        XCTAssertEqual(FilmPlayer.of(ViewerItem(id: "v", kind: .video, key: "db/films/f1/master.m3u8", record: ViewerRecord(table: "video", id: "v"))), .viewer)        XCTAssertEqual(FilmPlayer.of(ViewerItem(id: "p", kind: .photo, key: "db/photos/a.jpg")), .viewer)        XCTAssertTrue(FilmKey.streams("db/films/f1/MASTER.M3U8 "))        XCTAssertFalse(FilmKey.streams("db/films/f1/whole.mp4"))    }    /// RULE: A tap on a film opens Apple's player alone — the viewer stays shut — and a set the viewer opens never walks onto a film: one kind of thing, one player.    @MainActor    func testTheViewerNeverHoldsAFilm() {        let presenter = ViewerPresenter()        var played: [String] = []        presenter.streams = { played.append($0.id) }        let clip = ViewerItem(id: "video/clip", kind: .video, key: "db/videos/clip.mp4")        let whole = film("db/films/f1/whole.mp4", id: "film/f1")        let photo = ViewerItem(id: "photo/1", kind: .photo, key: "db/photos/a.jpg")        presenter.open(ViewerSet(items: [clip, whole, photo], start: 1))        XCTAssertEqual(played, ["film/f1"])        XCTAssertNil(presenter.current, "the viewer stays shut")        presenter.open(ViewerSet(items: [clip, whole, photo], start: 2))        XCTAssertEqual(presenter.current?.items.map(\.id), ["video/clip", "photo/1"])        XCTAssertEqual(presenter.showing, "photo/1")        XCTAssertEqual(played, ["film/f1"], "a picture opened is not a film played")    }    /// RULE: A film's record opens as a film carrying its title and poster, by its definition alone.    func testAFilmsRecordOpensAsAFilmWithItsTitle() throws {        let fixture = try XCTUnwrap(try DefinitionCatalogue.fixture(in: CottonUIResources.bundle))        let definition = try XCTUnwrap(fixture.tables.first { $0.id == "film" })        let record = TableRecord(id: "f1", values: ["title": .text("Synthetic Test Pattern"), "file": .text("db/films/f1/whole.mp4"),                                                    "poster": .text("db/films/f1/poster.jpg"),                                                    TableRecord.saidKey: .object(["slip": .object(["title": .text("Synthetic Test Pattern")])])])        let item = try XCTUnwrap(ViewerItem(record: record, definition: definition))        XCTAssertEqual(FilmPlayer.of(item), .cinema)        XCTAssertEqual(item.record, ViewerRecord(table: "film", id: "f1"))        XCTAssertEqual(item.title, "Synthetic Test Pattern")        XCTAssertEqual(item.poster, "db/films/f1/poster.jpg")    }    /// RULE (Cinemas, 5 Nov 2026): A film converting on the Mac (no file yet, no poster frame) is still a film: its tap goes to the core, whose refusal is said, never nothing; its card stores `needs_mac` in the state place ahead of its status, for the stub.    func testAFilmWaitingForTheMacTapsToTheCoreAndSaysSo() throws {        let fixture = try XCTUnwrap(try DefinitionCatalogue.fixture(in: CottonUIResources.bundle))        let definition = try XCTUnwrap(fixture.tables.first { $0.id == "film" })        let record = TableRecord(id: "f9", values: ["title": .text("Synthetic Slow Reel"), "kind": .text("film"),                                                    "status": .text("want_to_watch"), "needs_mac": .bool(true)])        let item = try XCTUnwrap(ViewerItem(record: record, definition: definition))        XCTAssertEqual(FilmPlayer.of(item), .cinema)        XCTAssertNil(item.key)        XCTAssertEqual(DeckCardFill.stored(definition, record: record)["state"], "needs_mac")        let converted = TableRecord(id: "f9", values: ["status": .text("watched"), "needs_mac": .bool(false)])        XCTAssertEqual(DeckCardFill.stored(definition, record: converted)["state"], "watched")    }    /// RULE: What this phone keeps of a film round-trips through the core: keeping, then a stream's bundle kept by its bookmark or a whole file adopted from where it landed, then forgotten; a kept whole file's Remove download is the core's `films.remove`. No place is kept here: it is the record's.    func testTheKeptFilmStoreRoundTrips() async throws {        let core = FilmsHere()        let store = FilmHereStore(core: core)        let stream = "db/films/f1/master.m3u8"        let whole = "db/films/f2/whole.mp4"        let bookmark = Data([0x62, 0x6F, 0x6F, 0x6B, 0x00, 0xFF])        var here = try await store.read(stream)        XCTAssertEqual(here, FilmHere())        try await store.keeping(stream)        here = try await store.read(stream)        XCTAssertEqual(here, FilmHere(bookmark: nil, state: .keeping))        try await store.kept(stream, bookmark: bookmark)        here = try await store.read(stream)        XCTAssertEqual(here, FilmHere(bookmark: bookmark, state: .kept))        try await store.forget(stream)        here = try await store.read(stream)        XCTAssertEqual(here, FilmHere())        try await store.adopt(whole, from: URL(fileURLWithPath: "/tmp/films-coming/landed"))        XCTAssertEqual(core.written[whole]?["from"], .string("/tmp/films-coming/landed"))        here = try await store.read(whole)        XCTAssertEqual(here.state, .kept)        try await store.remove(whole)        XCTAssertEqual(core.removed, [whole])        XCTAssertFalse(core.written.values.contains { $0["position"] != nil }, "no place is kept on this phone")    }    /// RULE: The film's address is minted by the core, which alone holds the bearer: Swift asks `media.stream` with the file's key and reads back an address and nothing else.    func testTheStreamIsMintedThroughTheCore() async throws {        let core = FilmsHere()        let url = try await FilmStreamGrant.mint("db/films/f1/master.m3u8", core: core)        XCTAssertEqual(url.absoluteString, "https://cotton.example.test/v1/stream/tok/db/films/f1/master.m3u8")        XCTAssertEqual(core.minted, ["db/films/f1/master.m3u8"])    }    /// RULE: a film's Play answers the platform's one `play`, the core's player answered whole; Keep everything's `keep_films` carries its words.    func testPlayAndKeepFilmsDecode() throws {        struct Answer: Decodable {            let action: RecordPlatformAction?            init(from decoder: Decoder) throws { action = try RecordPlatformAction.fromAnswer(decoder) }        }        let play = #"{"platform_action":"play","now":{"kind":"film","table":"film","id":"f1","title":"Synthetic Test Pattern","artist":"","duration_s":0,"gain_db":0,"file":"db/films/f1/whole.mp4","resume_at_s":0,"skip_s":15,"save_every_s":15,"played_after":0.9,"next_after_s":0,"tracks":{"subtitles":true,"subtitle_language":null,"audio_language":null}},"queue":[],"at":{"index":0,"of":1},"played_after_s":0,"settings":{"crossfade_s":0,"gapless":true,"replay_gain":"off","speed":1,"sleep_minutes":0,"shuffle":false},"face":"song.hifi","faces":[],"words":{"nothing":"n","offline":"o","refused":"r","locked":"l"}}"#        guard case .play(let answer)? = try JSONDecoder().decode(Answer.self, from: Data(play.utf8)).action else { return XCTFail() }        XCTAssertEqual(answer.playing?.marquee, "Synthetic Test Pattern", "a film's marquee is its title")        XCTAssertEqual(answer.playing?.file, "db/films/f1/whole.mp4")        let keep = #"{"on":true,"said":"Every film stays on this phone.","platform_action":"keep_films"}"#        XCTAssertEqual(try JSONDecoder().decode(Answer.self, from: Data(keep.utf8)).action, .keepFilms(said: "Every film stays on this phone."))    }}/// What this phone keeps of its films: the budget and On this phone's line.final class FilmKeepingTests: XCTestCase {    /// RULE: a keep fits this phone's budget or is refused; On this phone's top line counts the films it lists and the episodes kept in one and many, says the size (megabytes under a gigabyte), and how long ago this phone backed up.    func testTheBudgetAndTheTopLine() {        let knobs = FilmKeeping(keep_everything: false, cellular: false, budget_gb: 64)        XCTAssertTrue(knobs.fits(4_000_000_000, beside: 60_000_000_000))        XCTAssertFalse(knobs.fits(4_000_000_001, beside: 60_000_000_000))        XCTAssertEqual(knobs.budgetSaid, "64 GB")        let film = FilmKeepable(table: "film", id: "f1", values: ["file": .text("db/films/f1/whole.mp4"), "minutes": .number(100), "bitrate": .number(8000)])        XCTAssertEqual(film?.bytes, 6_000_000_000)        XCTAssertNil(FilmKeepable(table: "film", id: "f2", values: ["title": .text("No file")]), "a poster alone is nothing to keep")        XCTAssertEqual(FilmKeeping.head(films: 14, episodes: 2, bytes: 38_000_000_000, backedUp: "1 h ago"), "14 films · 2 episodes · 38 GB · synced 1 h ago")        XCTAssertEqual(FilmKeeping.head(films: 1, episodes: 1, bytes: 2_500_000_000, backedUp: nil), "1 film · 1 episode · 2.5 GB")        XCTAssertEqual(FilmKeeping.size(2_600_000), "2.6 MB", "a few small files never read as nothing")        XCTAssertEqual(FilmKeeping.size(640_000_000), "640 MB")        XCTAssertEqual(FilmKeeping.size(0), "0 MB")        let now = Date(timeIntervalSince1970: 1_800_000_000)        XCTAssertEqual(FilmKeeping.ago(now.addingTimeInterval(-3_700), now: now), "1 h ago")        XCTAssertEqual(FilmKeeping.ago(now.addingTimeInterval(-2 * 86_400), now: now), "2 days ago")    }}/// The core's `films.here.*`, `films.remove` and `media.stream` as/// `phone::films` answers them: a field given is written, `null` clears it.private final class FilmsHere: CottonCalling, @unchecked Sendable {    private(set) var written: [String: [String: JSONValue]] = [:]    private(set) var minted: [String] = []    private(set) var removed: [String] = []    func callRaw(_ method: String, requestJSON: String) async throws -> String {        let request = try JSONDecoder().decode([String: JSONValue].self, from: Data(requestJSON.utf8))        guard case .string(let key)? = request["key"] else { return #"{"ok":false,"error":{"code":"bad_request","message":"no key"}}"# }        switch method {        case CottonMethod.mediaStream:            minted.append(key)            return #"{"ok":true,"data":{"url":"https://cotton.example.test/v1/stream/tok/\#(key)","expires_at":"2026-11-04T12:00:00Z"}}"#        case CottonMethod.filmsRemove:            removed.append(key)            written[key] = nil            return #"{"ok":true,"data":{"key":"\#(key)","freed_bytes":1}}"#        case CottonMethod.filmsHereWrite:            var here = written[key] ?? [:]            for (field, value) in request where field != "key" {                if case .null = value { here[field] = nil } else { here[field] = value }            }            if here["state"] == nil { here = [:] }            written[key] = here        default:            break        }        var answer = (written[key] ?? [:]).filter { $0.key != "from" }        answer["key"] = .string(key)        let data = String(decoding: try JSONEncoder().encode(answer), as: UTF8.self)        return #"{"ok":true,"data":\#(data)}"#    }    func subscribe(_ handler: @escaping @Sendable (CottonEvent) -> Void) {}    func close() {}}