Cotton code
627 lines · 45.1 KB · RustRaw
//! `shell.player`'s films and series' episodes: what they deal, where they start,//! what they play from, and what their reports write.use std::sync::Arc;use cotton_client::transport::object::ObjectAddress;use cotton_client::transport::scripted::{Reply, ScriptedExchange};use serde_json::json;use super::super::call;use super::*;use crate::phone::personal_object::ObjectDoor;use crate::shell::client::phone_tests::attached;fn ask(client: &ClientController, request: Value) -> Value {    call(client, &request).unwrap_or_else(|error| panic!("{request} was refused: {} {}", error.code, error.message))}fn made_row(client: &ClientController, table: &str, data: Value) -> String {    let made = crate::phone::records::call(client, "records.create", &json!({"table": table, "data": data})).expect("a row");    ["/record/id", "/id", "/after/id", "/change/after/id"].iter().find_map(|pointer| made.pointer(pointer).and_then(Value::as_str)).unwrap_or_else(|| panic!("an id: {made}")).to_string()}fn record(client: &ClientController, table: &str, id: &str) -> Value {    crate::phone::records::call(client, "records.get", &json!({"table": table, "id": id})).expect("the record")["data"].clone()}/// Columns no person writes (a feed's, the intake's), written as their/// producer writes them.fn landed(client: &ClientController, table: &str, id: &str, columns: &[(&str, Value)]) {    let patch: Map<String, Value> = columns.iter().map(|(column, value)| (column.to_string(), value.clone())).collect();    client        .write_rows("test.landed", &mut |ctx| {            crate::phone::songs::patched(ctx, table, id, patch.clone())?;            Ok(Value::Null)        })        .expect("the columns");}fn film(client: &ClientController, title: &str, file: &str, minutes: f64) -> String {    let id = made_row(client, "film", json!({"title": title, "kind": "film"}));    landed(client, "film", &id, &[("file", json!(file)), ("minutes", json!(minutes))]);    id}const CREDENTIAL: &str = "ctd_11111111-1111-4111-8111-111111111111_test-credential";fn door(client: &ClientController, replies: impl IntoIterator<Item = Reply>) -> Arc<ScriptedExchange> {    let exchange = ScriptedExchange::new(replies);    client.set_object_door(Some(Arc::new(ObjectDoor {        address: ObjectAddress::open("https://cottondb.example.test").expect("an address"),        exchange: exchange.clone(),        credential: CREDENTIAL.to_string(),    })));    exchange}// RULE (shell.player kinds, 6 Nov 2026): a film this phone does not keep streams from the address the core signs, signed again on refresh_link and not twice in a minute; with no door it says so in the film's words; kept, it names its file or its bundle; `tracks` are the cinema row's.#[test]fn a_film_plays_from_a_link_the_core_signs() {    let (_dir, client) = attached();    let whole = "11111111-1111-4111-8111-111111111111/films/f1/master.m3u8";    let id = film(&client, "Night Ferry", whole, 100.0);    let offline = ask(&client, json!({"op": "play", "table": "film", "id": id}));    assert_eq!((offline["now"]["kind"].as_str(), offline["now"].get("stream")), (Some("film"), None));    assert_eq!(offline["refusal"], "Night Ferry is not on this phone, and there is no network to stream it from.");    let signed = |n: u32| json!({"url": format!("https://cottondb.example.test/v1/stream/tok{n}/{whole}"), "expires_at": "2026-11-06T12:00:00.000Z"}).to_string();    let exchange = door(&client, [Reply::ok(&signed(1)), Reply::ok(&signed(2))]);    let streaming = ask(&client, json!({"op": "play", "table": "film", "id": id}));    assert_eq!(streaming["now"]["stream"].as_str(), Some(format!("https://cottondb.example.test/v1/stream/tok1/{whole}").as_str()));    assert!(!streaming.to_string().contains(CREDENTIAL));    assert_eq!(        streaming["now"]["tracks"],        json!({"subtitles": true, "subtitle_language": null, "audio_language": null, "choice": null, "offset_ms": 0,               "timing": {"title": "Subtitle timing", "earlier": "Earlier", "later": "Later", "reset": "Reset", "said": "In time"}})    );    // The cinema names no language: the phone's, by its primary tag (android parity, 17 Nov 2026).    assert_eq!(ask(&client, json!({"phone_language": "te-IN"}))["now"]["tracks"]["subtitle_language"], "te");    assert_eq!(ask(&client, json!({}))["now"]["stream"], streaming["now"]["stream"], "the link stands while it plays");    let soon = ask(&client, json!({"op": "refresh_link"}));    assert_eq!(soon["refusal"], "This film could not be played just now", "signed again within a minute: refused");    assert_eq!(exchange.calls(), 1);    let master = "11111111-1111-4111-8111-111111111111/films/f2b/master.m3u8";    let kept = film(&client, "Paper Comets", master, 90.0);    crate::phone::films::write(&client, &json!({"key": master, "state": "kept", "bookmark": "Ym9va21hcms="})).expect("kept");    let bundle = ask(&client, json!({"op": "play", "table": "film", "id": kept}));    assert_eq!((bundle["now"]["bundle"].as_str(), bundle["now"].get("stream")), (Some("Ym9va21hcms="), None));}// RULE (17 Nov 2026): a film's subtitle choice and timing are its own, kept on its row so they follow// it to every device: the player reports the track chosen (or off) and steps the timing a tenth of a second earlier or// later, or back in time; `tracks` carries both with the control's words, the core's; the timing stops at half a minute.#[test]fn a_films_subtitle_choice_and_timing_are_its_own() {    let (_dir, client) = attached();    let id = film(&client, "Harbour Lights", "11111111-1111-4111-8111-111111111111/films/f5/master.m3u8", 95.0);    ask(&client, json!({"op": "play", "table": "film", "id": id}));    let chosen = ask(&client, json!({"op": "subtitles", "choice": {"language": "fr", "name": "French (made on your Mac)"}}));    assert_eq!(chosen["now"]["tracks"]["choice"], json!({"language": "fr", "name": "French (made on your Mac)"}));    assert_eq!(record(&client, "film", &id)["subtitle_choice"], json!({"language": "fr", "name": "French (made on your Mac)"}).to_string());    assert_eq!(ask(&client, json!({"op": "subtitles", "choice": "off"}))["now"]["tracks"]["choice"], "off");    let refused = call(&client, &json!({"op": "subtitles", "choice": {"name": "no language"}})).expect_err("a choice names its language");    assert_eq!(refused.code, "bad_request");    let later = |n: usize| (0..n).fold(Value::Null, |_, _| ask(&client, json!({"op": "subtitle_timing", "step": 1})));    let three = later(3);    assert_eq!((three["now"]["tracks"]["offset_ms"].as_i64(), three["now"]["tracks"]["timing"]["said"].as_str()), (Some(300), Some("0.3 s later")));    let earlier = (0..5).fold(Value::Null, |_, _| ask(&client, json!({"op": "subtitle_timing", "step": -1})));    assert_eq!((earlier["now"]["tracks"]["offset_ms"].as_i64(), earlier["now"]["tracks"]["timing"]["said"].as_str()), (Some(-200), Some("0.2 s earlier")));    assert_eq!(record(&client, "film", &id)["subtitle_offset"].as_f64(), Some(-200.0), "kept on the row: it follows the film");    let reset = ask(&client, json!({"op": "subtitle_timing", "step": 0}));    assert_eq!((reset["now"]["tracks"]["offset_ms"].as_i64(), reset["now"]["tracks"]["timing"]["said"].as_str()), (Some(0), Some("In time")));    assert_eq!(call(&client, &json!({"op": "subtitle_timing", "step": 5})).expect_err("a step is one press").code, "bad_request");    // Played again (another device reads the same row), the film opens with its own.    landed(&client, "film", &id, &[("subtitle_offset", json!(29_950)), ("subtitle_choice", json!("off"))]);    let again = ask(&client, json!({"op": "play", "table": "film", "id": id}));    assert_eq!((again["now"]["tracks"]["choice"].as_str(), again["now"]["tracks"]["offset_ms"].as_i64()), (Some("off"), Some(29_950)));    assert_eq!(later(2)["now"]["tracks"]["offset_ms"].as_i64(), Some(TIMING_LIMIT_MS), "half a minute is as far as it goes");}// RULE (R6): a whole film is sealed where the object keeps it, so it plays from the phone's own door at// 127.0.0.1: the player is handed that address (never the object's, never a bearer), and what the door answers is the// film itself, opened from Range reads of the sealed file. With no data key here it is refused, not streamed open.#[test]fn a_sealed_whole_film_plays_from_the_phones_own_door() {    use std::io::{Read as _, Write as _};    let (_dir, client) = attached();    let db = "11111111-1111-4111-8111-111111111111";    let whole = format!("{db}/films/f9/whole.mp4");    let id = film(&client, "Glass Tide", &whole, 100.0);    let film_bytes: Vec<u8> = (0..150_000u32).map(|i| (i % 241) as u8).collect();    door(&client, []);    let refused = ask(&client, json!({"op": "play", "table": "film", "id": id}));    assert_eq!(refused["now"].get("stream"), None, "no data key: nothing streams");    let dk = cotton_core::seal::DataKey::from_bytes([9; 32]);    client.data_keys().hold(db, &dk);    let root = cotton_core::seal::keys::file_root(&dk, db).unwrap();    let fk = cotton_core::seal::file::person_file_key(&root, &whole);    let mut sealed = Vec::new();    cotton_core::seal::file::SealingReader::new(&fk, &whole, std::io::Cursor::new(film_bytes.clone()), film_bytes.len() as u64).read_to_end(&mut sealed).unwrap();    let whole_reply = || Reply::new(206, sealed.clone()).with_header("content-range", &format!("bytes 0-{}/{}", sealed.len() - 1, sealed.len()));    let exchange = door(&client, [whole_reply(), whole_reply(), whole_reply()]);    let playing = ask(&client, json!({"op": "play", "table": "film", "id": id}));    let url = playing["now"]["stream"].as_str().unwrap_or_else(|| panic!("a stream: {playing}")).to_string();    assert!(url.starts_with("http://127.0.0.1:") && url.ends_with("/film.mp4"), "{url}");    assert!(!playing.to_string().contains(CREDENTIAL));    assert_eq!(exchange.nth(0).header("range"), Some(format!("bytes=0-{}", cotton_core::seal::file::HEAD + cotton_client::media::remote::WINDOW - 1).as_str()));    let rest = url.strip_prefix("http://").unwrap();    let (host, path) = rest.split_once('/').unwrap();    let mut stream = std::net::TcpStream::connect(host).unwrap();    write!(stream, "GET /{path} HTTP/1.1\r\nHost: {host}\r\nRange: bytes=70000-70099\r\n\r\n").unwrap();    let mut answer = Vec::new();    stream.read_to_end(&mut answer).unwrap();    let split = answer.windows(4).position(|w| w == b"\r\n\r\n").unwrap();    assert!(String::from_utf8_lossy(&answer[..split]).starts_with("HTTP/1.1 206"));    assert_eq!(&answer[split + 4..], &film_bytes[70_000..70_100]);    let cast = ask(&client, json!({"op": "cast"}));    assert_eq!(cast["refusal"].as_str(), Some("Glass Tide plays only on this phone: a TV cannot play its file."));}// RULE (PLAYER START, 26 Nov 2026; RELAY 2): a film's page opening prepares its play: `prepare` fetches its first// window from the object while the page is read, plays nothing and queues nothing; Play then opens it from what was// fetched, asking the object nothing more. On mobile data, while this phone's films keep to Wi-Fi, nothing is// fetched; with no data key here, nothing. `unprepare` lets the prepared film's windows go, and `release` (the app// gone to the background) every film's; a film stopped lets go of its windows too.#[test]fn a_film_prepared_as_its_page_opens_plays_without_asking_again() {    use std::io::Read as _;    let (_dir, client) = attached();    let db = "11111111-1111-4111-8111-111111111111";    let whole = format!("{db}/films/f19/whole.mp4");    let id = film(&client, "Paper Lanterns", &whole, 100.0);    door(&client, []);    assert_eq!(ask(&client, json!({"op": "prepare", "table": "film", "id": id, "network": "wifi"}))["prepared"], false, "no data key: nothing fetched");    let dk = cotton_core::seal::DataKey::from_bytes([9; 32]);    client.data_keys().hold(db, &dk);    let root = cotton_core::seal::keys::file_root(&dk, db).unwrap();    let fk = cotton_core::seal::file::person_file_key(&root, &whole);    let film_bytes: Vec<u8> = (0..90_000u32).map(|i| (i % 239) as u8).collect();    let mut sealed = Vec::new();    cotton_core::seal::file::SealingReader::new(&fk, &whole, std::io::Cursor::new(film_bytes.clone()), film_bytes.len() as u64).read_to_end(&mut sealed).unwrap();    let reply = || Reply::new(206, sealed.clone()).with_header("content-range", &format!("bytes 0-{}/{}", sealed.len() - 1, sealed.len()));    let exchange = door(&client, [reply(), reply()]);    let mine = |kept: Vec<(String, usize)>| kept.into_iter().find(|(film, _)| *film == whole).map(|(_, held)| held);    // Mobile data, the phone's films keeping to Wi-Fi (the default): nothing fetched, said or unsaid.    assert_eq!(ask(&client, json!({"op": "prepare", "table": "film", "id": id, "network": "cellular"}))["prepared"], false);    assert_eq!(ask(&client, json!({"op": "prepare", "table": "film", "id": id}))["prepared"], false, "unsaid is mobile data");    assert_eq!(exchange.seen().len(), 0);    let prepared = ask(&client, json!({"op": "prepare", "table": "film", "id": id, "network": "wifi"}));    assert_eq!(prepared["prepared"], true, "{prepared}");    assert!(prepared.get("now").is_none(), "prepare answers no player: {prepared}");    let wait = |n: usize| {        let started = std::time::Instant::now();        while exchange.seen().len() < n && started.elapsed() < std::time::Duration::from_secs(10) {            std::thread::sleep(std::time::Duration::from_millis(20));        }    };    wait(1);    assert_eq!(exchange.seen().len(), 1, "the first window fetched ahead of Play, and nothing after it");    // The page left: its windows go.    ask(&client, json!({"op": "unprepare"}));    assert_eq!(mine(kept_now(&client)), None, "unprepared: let go");    ask(&client, json!({"op": "prepare", "table": "film", "id": id, "network": "wifi"}));    wait(2);    let playing = ask(&client, json!({"op": "play", "table": "film", "id": id}));    assert!(playing["now"]["stream"].as_str().is_some_and(|url| url.starts_with("http://127.0.0.1:")), "{playing}");    assert_eq!(exchange.seen().len(), 2, "Play asks the object nothing more");    assert!(mine(kept_now(&client)).is_some_and(|held| held >= 1), "playing: kept");    // The app goes to the background: every film's windows go.    assert_eq!(ask(&client, json!({"op": "release"}))["released"], true);    assert_eq!(mine(kept_now(&client)), None, "released: let go");    assert!(call(&client, &json!({"op": "prepare", "table": "song", "id": id})).is_err(), "only a film's or an episode's page prepares");}// RULE (Android Cinemas, 15 Nov 2026): a film playing is cast by the address the object signs, minted for the receiver even when this phone keeps the film (a receiver reads no file of the phone's and holds no bearer), reused within a minute; its type and HLS segment kind and, when it lies in the film's folder, its poster under the same token; a MOV whole file is refused in the film's words, and so is a film with no network to sign it; nothing playing, or a song, is not cast.#[test]fn a_film_is_cast_by_its_signed_address_alone() {    let (_dir, client) = attached();    let db = "11111111-1111-4111-8111-111111111111";    let master = format!("{db}/films/f1/master.m3u8");    let id = film(&client, "Night Ferry", &master, 100.0);    landed(&client, "film", &id, &[("poster", json!(format!("{db}/films/f1/poster.jpg")))]);    crate::phone::films::write(&client, &json!({"key": master, "state": "kept", "bookmark": "Ym9va21hcms="})).expect("kept");    assert_eq!(call(&client, &json!({"op": "cast"})).map_err(|error| error.code), Err("bad_request".to_string()), "nothing playing is cast");    let kept = ask(&client, json!({"op": "play", "table": "film", "id": id}));    assert_eq!(kept["now"]["bundle"].as_str(), Some("Ym9va21hcms="));    let offline = ask(&client, json!({"op": "cast"}));    assert_eq!((offline.get("cast"), offline["refusal"].as_str()), (None, Some("Night Ferry is not on this phone, and there is no network to stream it from.")));    let signed = json!({"url": format!("https://cottondb.example.test/v1/stream/tok1/{master}"), "expires_at": "2026-11-15T12:00:00.000Z"}).to_string();    let exchange = door(&client, [Reply::ok(&signed)]);    let cast = ask(&client, json!({"op": "cast"}));    assert_eq!(cast["cast"], json!({        "url": format!("https://cottondb.example.test/v1/stream/tok1/{master}"),        "content_type": "application/x-mpegURL", "hls_segments": "fmp4", "title": "Night Ferry",        "poster": format!("https://cottondb.example.test/v1/stream/tok1/{db}/films/f1/poster.jpg"),        "expires_at": "2026-11-15T12:00:00.000Z",    }));    assert!(!cast.to_string().contains(CREDENTIAL), "the receiver is handed no bearer");    assert_eq!(cast["now"]["bundle"].as_str(), Some("Ym9va21hcms="), "the phone plays on from what it keeps");    assert_eq!(ask(&client, json!({"op": "cast"}))["cast"]["url"], cast["cast"]["url"], "within a minute the link is reused");    assert_eq!(exchange.calls(), 1);    let mov = film(&client, "Paper Comets", &format!("{db}/films/f2/whole.mov"), 90.0);    ask(&client, json!({"op": "play", "table": "film", "id": mov}));    let refused = ask(&client, json!({"op": "cast"}));    assert_eq!((refused.get("cast"), refused["refusal"].as_str()), (None, Some("Paper Comets plays only on this phone: a TV cannot play its file.")));    assert_eq!(cast_type(&format!("{db}/films/f3/whole.M4V")), None, "a whole film is sealed: a TV holds no key to open it (R6)");}// RULE (shell.player kinds, 6 Nov 2026): a film's reports write its resume point and watching, one watch row per play with the seconds heard; past nine tenths it is watched and its point cleared; Play resumes inside the window, Play from the start at nought; a film with no stream yet says why.#[test]fn a_films_reports_write_its_point_and_its_watch() {    let (_dir, client) = attached();    let id = film(&client, "Night Ferry", "db/films/f/whole.mp4", 100.0);    let playing = ask(&client, json!({"op": "play", "table": "film", "id": id}));    // RULE (film-progress-flood, 17 Nov 2026): a film reports where it stands once a minute while it plays, an episode every    // fifteen seconds; a pause, a stop and the end report at once.    assert_eq!(playing["now"]["save_every_s"].as_f64(), Some(60.0));    ask(&client, json!({"listened": {"table": "film", "id": id, "at_s": 1234.4, "seconds": 15.0, "device": "Invented iPhone"}}));    ask(&client, json!({"listened": {"table": "film", "id": id, "at_s": 1249.0, "seconds": 30.0}}));    let row = record(&client, "film", &id);    assert_eq!((row["position"].as_f64(), row["status"].as_str()), (Some(1249.0), Some("watching")));    assert!(row["position_at"].as_str().is_some(), "the resume point the poster's strip reads");    let watches = crate::phone::records::call(&client, "records.list", &json!({"table": "watch", "limit": 10})).expect("watches")["records"].as_array().cloned().unwrap_or_default();    assert_eq!(watches.len(), 1, "one watch row per play");    assert_eq!((watches[0]["data"]["seconds"].as_f64(), watches[0]["data"]["device"].as_str()), (Some(30.0), Some("Invented iPhone")));    let resumed = ask(&client, json!({"op": "play", "table": "film", "id": id}));    assert_eq!(resumed["now"]["resume_at_s"].as_f64(), Some(1249.0));    ask(&client, json!({"listened": {"table": "film", "id": id, "at_s": 5500.0, "seconds": 4000.0, "duration_s": 6000.0}}));    let watched = record(&client, "film", &id);    assert_eq!((watched["status"].as_str(), watched["position"].as_f64()), (Some("watched"), None));    assert!(watched["watched_on"].as_str().is_some());    let waiting = made_row(&client, "film", json!({"title": "Paper Comets", "kind": "film"}));    landed(&client, "film", &waiting, &[("needs_mac", json!(true))]);    let refused = ask(&client, json!({"op": "play", "table": "film", "id": waiting}));    assert_eq!(refused["refusal"], "Paper Comets is converting on your Mac. It plays once the stream lands.");}// RULE (film-progress-flood, 17 Nov 2026): a report at the place the film already holds writes nothing of it, however much// later it comes: `position_at` alone moving is no change of place, and every write of a film row is a post to the object.#[test]fn a_report_at_the_place_the_film_holds_queues_nothing() {    let (_dir, client, clock) = crate::shell::client::phone_tests::attached_on_a_clock();    let id = film(&client, "Night Ferry", "db/films/f/whole.mp4", 100.0);    ask(&client, json!({"op": "play", "table": "film", "id": id}));    ask(&client, json!({"listened": {"table": "film", "id": id, "at_s": 1249.0, "seconds": 30.0}}));    let queued = |client: &ClientController| client.with_file(|f| Ok(cotton_store::outbox::pending_count(f.driver).expect("the outbox"))).expect("the file");    let (before, at) = (queued(&client), record(&client, "film", &id)["position_at"].clone());    clock.advance(chrono::Duration::seconds(40));    ask(&client, json!({"listened": {"table": "film", "id": id, "at_s": 1249.2, "seconds": 30.0}}));    assert_eq!(queued(&client), before, "a pause at the same second, with no more heard, queues nothing");    assert_eq!(record(&client, "film", &id)["position_at"], at);    clock.advance(chrono::Duration::seconds(60));    ask(&client, json!({"listened": {"table": "film", "id": id, "at_s": 1309.0, "seconds": 90.0}}));    assert_eq!(record(&client, "film", &id)["position"].as_f64(), Some(1309.0), "a place moved is written");    assert!(queued(&client) > before);}/// An invented series: one season, three episodes with files.fn series(client: &ClientController) -> (String, Vec<String>) {    let series = made_row(client, "film", json!({"title": "Lowmarsh", "kind": "series"}));    let season = made_row(client, "film_season", json!({"film": series, "number": 1, "title": "Season 1"}));    let episodes = (1..=3)        .map(|n| {            let id = made_row(client, "film_episode", json!({"season": season, "series": series, "number": n, "title": format!("Invented {n}")}));            landed(client, "film_episode", &id, &[("file", json!(format!("db/films/{id}/whole.mp4"))), ("minutes", json!(25))]);            id        })        .collect();    (series, episodes)}// RULE (shell.player kinds, 6 Nov 2026): a series plays its episode in progress with the rest after it as the queue, counted in after ten seconds; a finished episode is watched and next plays the one after; with autoplay_next off an episode plays alone.#[test]fn a_series_plays_on_through_its_episodes() {    let (_dir, client) = attached();    let (series_id, episodes) = series(&client);    let answer = ask(&client, json!({"op": "play", "table": "film", "id": series_id}));    let now = &answer["now"];    assert_eq!((now["table"].as_str(), now["id"].as_str(), now["caption"].as_str(), now["title"].as_str()), (Some("film_episode"), Some(episodes[0].as_str()), Some("S1 E1 · Invented 1"), Some("Lowmarsh")));    assert_eq!((now["next_after_s"].as_f64(), now["series"].as_str()), (Some(10.0), Some(series_id.as_str())));    assert_eq!(answer["queue"].as_array().unwrap().iter().map(|item| item["id"].as_str().unwrap().to_string()).collect::<Vec<_>>(), episodes[1..]);    ask(&client, json!({"listened": {"table": "film_episode", "id": episodes[0], "at_s": 600.0, "seconds": 600.0}}));    assert!(record(&client, "film", &series_id)["position_at"].as_str().is_some(), "the series keeps a resume point, its poster's strip");    let next = ask(&client, json!({"op": "next", "listened": {"table": "film_episode", "id": episodes[0], "at_s": 1500.0, "seconds": 1500.0, "ended": "finished"}}));    assert_eq!(record(&client, "film_episode", &episodes[0])["status"], "watched");    assert_eq!((next["now"]["id"].as_str(), next["now"]["resume_at_s"].as_f64()), (Some(episodes[1].as_str()), Some(0.0)));    let resumed = ask(&client, json!({"op": "play", "table": "film", "id": series_id}));    assert_eq!(resumed["now"]["id"].as_str(), Some(episodes[1].as_str()), "the first not watched");    crate::phone::records::call(&client, "records.create", &json!({"table": "face_settings", "data": {"table": "cinema", "face": "apple", "autoplay_next": false, "subtitles_on": false, "audio_language": "hi"}})).expect("the cinema row");    let alone = ask(&client, json!({"op": "play", "table": "film_episode", "id": episodes[1]}));    assert_eq!((alone["queue"].as_array().map(Vec::len), alone["now"]["next_after_s"].as_f64()), (Some(0), Some(0.0)));    let tracks = &alone["now"]["tracks"];    assert_eq!((&tracks["subtitles"], &tracks["subtitle_language"], &tracks["audio_language"]), (&json!(false), &Value::Null, &json!("hi")), "the cinema row's");}// RULE (shell.player kinds, 6 Nov 2026): a saved place in the first five or the last fifteen seconds of what it lasts is the start.#[test]fn a_saved_place_starts_inside_its_window() {    assert_eq!((resume_at(4.9, 1000.0), resume_at(5.0, 1000.0), resume_at(984.9, 1000.0), resume_at(985.0, 1000.0), resume_at(3000.0, 0.0)), (0.0, 5.0, 984.9, 0.0, 3000.0));}/// A non-loopback IPv4 this machine holds, standing in for the phone's Wi-Fi address.fn a_wifi_address() -> Option<std::net::IpAddr> {    cotton_client::media::lan::interfaces().into_iter().map(|(_, ip)| ip).find(|ip| matches!(ip, std::net::IpAddr::V4(v4) if !v4.is_loopback() && !v4.is_link_local() && !v4.is_unspecified()))}fn answers_at(url: &str) -> bool {    let host = url.strip_prefix("http://").and_then(|rest| rest.split('/').next()).unwrap();    std::net::TcpStream::connect(host).is_ok()}// RULE (cinemas-airplay, 18 Nov 2026; airplay-refused): a sealed film plays from the phone's own door at 127.0.0.1,// which no TV reaches. Routed to a TV, it is offered on the phone's Wi-Fi address at a door of its own (a new path, never// the loopback's), one door for the play, checked after `check_after_s`; a receiver not seen playing it stays// the receiver's (owner, 18 Nov 2026). A failure the player reports on the TV, no Wi-Fi address, the route back to// the phone and the play's end each shut that door, and the first two say once, in the film's words, that it plays// through the phone. A film the object signs an address for is the// receiver's as it is. Nothing playing is routed, and a route is one of four.#[test]fn a_sealed_film_on_a_tv_is_offered_on_the_wifi_address_or_plays_through_the_phone() {    use std::io::Read as _;    let (_dir, client) = attached();    let db = "11111111-1111-4111-8111-111111111111";    let whole = format!("{db}/films/f9/whole.mp4");    let id = film(&client, "Glass Tide", &whole, 100.0);    assert_eq!(call(&client, &json!({"op": "route", "to": "external"})).map_err(|error| error.code), Err("bad_request".to_string()), "nothing playing is routed");    let dk = cotton_core::seal::DataKey::from_bytes([9; 32]);    client.data_keys().hold(db, &dk);    let root = cotton_core::seal::keys::file_root(&dk, db).unwrap();    let fk = cotton_core::seal::file::person_file_key(&root, &whole);    let film_bytes: Vec<u8> = (0..150_000u32).map(|i| (i % 241) as u8).collect();    let mut sealed = Vec::new();    cotton_core::seal::file::SealingReader::new(&fk, &whole, std::io::Cursor::new(film_bytes.clone()), film_bytes.len() as u64).read_to_end(&mut sealed).unwrap();    let whole_reply = || Reply::new(206, sealed.clone()).with_header("content-range", &format!("bytes 0-{}/{}", sealed.len() - 1, sealed.len()));    door(&client, [whole_reply(), whole_reply()]);    let playing = ask(&client, json!({"op": "play", "table": "film", "id": id}));    let own = playing["now"]["stream"].as_str().unwrap_or_else(|| panic!("a stream: {playing}")).to_string();    assert!(own.starts_with("http://127.0.0.1:"), "{own}");    assert_eq!(call(&client, &json!({"op": "route", "to": "away"})).map_err(|error| error.code), Err("bad_request".to_string()));    let through_phone = json!({"to": "phone", "said": "Glass Tide is playing through this phone."});    super::super::WIFI.with(|wifi| wifi.set(Some(None)));    assert_eq!(ask(&client, json!({"op": "route", "to": "external"}))["route"], through_phone, "no Wi-Fi address: through the phone");    let Some(ip) = a_wifi_address() else {        return eprintln!("no non-loopback IPv4 here: the Wi-Fi door itself is not shown");    };    super::super::WIFI.with(|wifi| wifi.set(Some(Some(ip))));    let on_tv = ask(&client, json!({"op": "route", "to": "external"}));    let lan = on_tv["route"]["stream"].as_str().unwrap_or_else(|| panic!("a Wi-Fi address: {on_tv}")).to_string();    assert_eq!((on_tv["route"]["to"].as_str(), on_tv["route"]["check_after_s"].as_f64()), (Some("receiver"), Some(ADVANCE_WITHIN_S)));    assert!(lan.starts_with(&format!("http://{ip}:")) && lan.ends_with("/film.mp4"), "{lan}");    assert_ne!(lan.split('/').nth(3), own.split('/').nth(3), "a path of its own, never the loopback's");    assert_eq!(on_tv["now"]["stream"].as_str(), Some(own.as_str()), "the phone's own address stands for the phone");    assert!(!on_tv.to_string().contains(CREDENTIAL));    assert_eq!(ask(&client, json!({"op": "route", "to": "external"}))["route"]["stream"].as_str(), Some(lan.as_str()), "one door for the play");    assert!(answers_at(&lan));    // Asked before the time is up, it is checked again for the time left.    let early = ask(&client, json!({"op": "route", "to": "check", "at_s": 0.0}))["route"].clone();    assert_eq!(early["stream"].as_str(), Some(lan.as_str()));    assert!(early["check_after_s"].as_f64().is_some_and(|left| left > 0.5 && left <= ADVANCE_WITHIN_S), "{early}");    // The time is up and the receiver never took the film: it stays on the TV all the same (owner, 18 Nov 2026: a    // film sent to a TV is never pulled back to the phone for not being seen to play), its door open, checked again.    later(ADVANCE_WITHIN_S + 1.0);    assert_eq!(ask(&client, json!({"op": "route", "to": "check", "at_s": 9.0}))["route"], json!({"to": "receiver", "stream": lan, "check_after_s": CHECK_EVERY_S}));    assert!(answers_at(&lan), "not seen playing: the door stays open");    later(0.0);    let again = ask(&client, json!({"op": "route", "to": "external"}))["route"]["stream"].as_str().unwrap().to_string();    assert_eq!(again, lan, "one door for the play");    assert_eq!(ask(&client, json!({"op": "route", "to": "failed"}))["route"], through_phone);    assert!(!answers_at(&again), "failed on the TV: the door is shut");    let back = ask(&client, json!({"op": "route", "to": "external"}))["route"]["stream"].as_str().unwrap().to_string();    assert_eq!(ask(&client, json!({"op": "route", "to": "phone"}))["route"], json!({"to": "phone"}), "back on the phone: nothing to say");    assert!(!answers_at(&back), "back on the phone: the door is shut");    let ending = ask(&client, json!({"op": "route", "to": "external"}))["route"]["stream"].as_str().unwrap().to_string();    ask(&client, json!({"op": "clear"}));    assert!(!answers_at(&ending), "the play over: the door is shut");    // A film of a database this phone holds no key for plays from the object's signed address.    let master = "22222222-2222-4222-8222-222222222222/films/f1/master.m3u8";    let open = film(&client, "Night Ferry", master, 100.0);    let signed = json!({"url": format!("https://cottondb.example.test/v1/stream/tok1/{master}"), "expires_at": "2026-11-18T12:00:00.000Z"}).to_string();    door(&client, [Reply::ok(&signed)]);    let streaming = ask(&client, json!({"op": "play", "table": "film", "id": open}));    assert!(streaming["now"]["stream"].as_str().is_some_and(|url| url.starts_with("https://")), "{streaming}");    let watched = json!({"to": "receiver", "check_after_s": ADVANCE_WITHIN_S});    assert_eq!(ask(&client, json!({"op": "route", "to": "external", "at_s": 40.0}))["route"], watched, "the object's address is the receiver's as it is, watched");    later(ADVANCE_WITHIN_S);    assert_eq!(ask(&client, json!({"op": "route", "to": "check", "at_s": 47.0}))["route"], json!({"to": "receiver", "check_after_s": CHECK_EVERY_S}), "seen advancing: it plays on");    later(ADVANCE_WITHIN_S + CHECK_EVERY_S);    assert_eq!(ask(&client, json!({"op": "route", "to": "check", "at_s": 57.0, "paused": false}))["route"]["to"], "receiver");    later(ADVANCE_WITHIN_S + CHECK_EVERY_S + STALL_WITHIN_S);    assert_eq!(ask(&client, json!({"op": "route", "to": "check", "at_s": 57.0}))["route"], json!({"to": "receiver", "check_after_s": CHECK_EVERY_S}), "it stood still: it stays on the TV");    later(0.0);    super::super::WIFI.with(|wifi| wifi.set(None));}/// The test's clock this many seconds past this machine's.fn later(seconds: f64) {    super::super::LATER.with(|later| later.set(std::time::Duration::from_secs_f64(seconds)));}// RULE (airplay-refused, 18 Nov 2026): fetched is not playing. A film handed to a TV plays on there only once it is seen// to advance: the phone's time moving as the film does and, for a film at the Wi-Fi door, the receiver taking the film// itself (a segment), not just its index. Never seen within `ADVANCE_WITHIN_S`, or later standing still for// `STALL_WITHIN_S` while the phone says it plays, it plays through the phone. Paused, nothing is judged.#[test]fn a_film_on_a_tv_must_be_seen_to_advance() {    use std::time::{Duration, Instant};    let t0 = Instant::now();    let at = |s: f64| t0 + Duration::from_secs_f64(s);    let seen = |at_s: f64, taken_at: Option<Option<Instant>>| Seen { at_s: Some(at_s), paused: false, taken_at };    // Advance seen: the phone's time moved and the receiver took a segment.    let mut watch = Watch::new("f", t0, Some(100.0));    assert_eq!(judge(&mut watch, &seen(100.0, Some(None)), at(2.0)), Verdict::Watching(6.0), "nothing yet: checked again for the time left");    assert_eq!(judge(&mut watch, &seen(106.0, Some(Some(at(5.0)))), at(8.0)), Verdict::Plays);    assert_eq!(judge(&mut watch, &seen(116.0, Some(Some(at(17.0)))), at(18.0)), Verdict::Plays, "and plays on");    // The index alone (the owner's Mac, 18 Nov 2026): the phone even shows its time moving, but the receiver never took    // the film itself.    let mut index_only = Watch::new("f", t0, Some(0.0));    assert_eq!(judge(&mut index_only, &seen(8.0, Some(None)), at(8.0)), Verdict::Stalled);    // The receiver took a segment but the phone's time never moved (waiting on a receiver that refused).    let mut frozen = Watch::new("f", t0, Some(0.0));    assert_eq!(judge(&mut frozen, &seen(0.0, Some(Some(at(3.0)))), at(8.0)), Verdict::Stalled);    // A seek is not the film playing: the time moved further than the time between.    let mut sought = Watch::new("f", t0, Some(0.0));    assert_eq!(judge(&mut sought, &seen(600.0, Some(Some(at(3.0)))), at(7.8)), Verdict::Stalled, "a check a little early is the time up");    // A stall later in the film: the receiver stops taking it while the phone says it plays, or the phone's time stands.    let mut quiet = Watch::new("f", t0, Some(0.0));    assert_eq!(judge(&mut quiet, &seen(7.0, Some(Some(at(6.0)))), at(8.0)), Verdict::Plays);    assert_eq!(judge(&mut quiet, &seen(17.0, Some(Some(at(10.0)))), at(18.0)), Verdict::Plays);    assert_eq!(judge(&mut quiet, &seen(27.0, Some(Some(at(10.0)))), at(28.0)), Verdict::Plays, "a buffer's breathing is not a stall");    assert_eq!(judge(&mut quiet, &seen(47.0, Some(Some(at(10.0)))), at(48.0)), Verdict::Stalled, "nothing taken for STALL_WITHIN_S");    let mut standing = Watch::new("f", t0, Some(0.0));    assert_eq!(judge(&mut standing, &seen(7.0, Some(Some(at(6.0)))), at(8.0)), Verdict::Plays);    assert_eq!(judge(&mut standing, &seen(7.0, Some(Some(at(17.0)))), at(18.0)), Verdict::Plays);    assert_eq!(judge(&mut standing, &seen(7.0, Some(Some(at(37.0)))), at(38.0)), Verdict::Stalled, "the phone's time stood for STALL_WITHIN_S");    // A kept film (or the object's address): no door, the phone's time alone shows it.    let mut kept = Watch::new("f", t0, Some(50.0));    assert_eq!(judge(&mut kept, &seen(57.0, None), at(8.0)), Verdict::Plays);    assert_eq!(judge(&mut kept, &seen(67.0, None), at(18.0)), Verdict::Plays);    assert_eq!(judge(&mut kept, &seen(67.0, None), at(38.0)), Verdict::Plays, "twenty seconds still is not yet a stall");    assert_eq!(judge(&mut kept, &seen(67.0, None), at(48.0)), Verdict::Stalled, "a TV that stalls without failing is caught for a kept film");    let mut kept_dark = Watch::new("f", t0, Some(50.0));    assert_eq!(judge(&mut kept_dark, &seen(50.0, None), at(8.0)), Verdict::Stalled, "never seen playing");    // Paused, nothing is judged, and the window starts again when it plays.    let mut paused = Watch::new("f", t0, Some(0.0));    assert_eq!(judge(&mut paused, &Seen { at_s: Some(0.0), paused: true, taken_at: Some(None) }, at(8.0)), Verdict::Watching(CHECK_EVERY_S));    assert_eq!(judge(&mut paused, &seen(0.0, Some(None)), at(12.0)), Verdict::Watching(4.0));    assert_eq!(judge(&mut paused, &seen(5.0, Some(Some(at(13.0)))), at(16.0)), Verdict::Plays);    assert_eq!(judge(&mut paused, &Seen { at_s: Some(5.0), paused: true, taken_at: Some(Some(at(13.0))) }, at(60.0)), Verdict::Watching(CHECK_EVERY_S), "a long pause is no stall");    assert_eq!(judge(&mut paused, &seen(6.0, Some(Some(at(13.0)))), at(70.0)), Verdict::Plays, "played again, its buffer full: the quiet counts from the pause");}/// A frame as the player writes it: a file of invented bytes.fn frame(dir: &std::path::Path, name: &str, bytes: &[u8]) -> String {    let path = dir.join(name);    std::fs::write(&path, bytes).expect("the frame");    path.display().to_string()}fn choice_ids(answer: &Value) -> Vec<String> {    answer["now"]["more"]["choices"].as_array().expect("the choices").iter().map(|choice| choice["id"].as_str().expect("an id").to_string()).collect()}// RULE (film-poster-pick, 18 Nov 2026): a film's "more" choices are the core's: subtitle timing for a film that carries subtitles, Use this frame, and Back to the original picture only once a frame is worn.#[test]fn a_films_more_choices_are_the_cores() {    let (dir, client) = attached();    let id = made_row(&client, "film", json!({"title": "Invented Reel", "poster": "db/media/found.jpg"}));    landed(&client, "film", &id, &[("file", json!("db/films/reel/master.m3u8"))]);    let playing = ask(&client, json!({"op": "play", "table": "film", "id": id}));    assert_eq!(playing["now"]["more"]["title"], "More");    assert_eq!(choice_ids(&playing), ["subtitle_timing", "use_frame"]);    let choices = &playing["now"]["more"]["choices"];    assert_eq!((choices[0]["label"].as_str(), choices[0]["needs"].as_str()), (Some("Subtitle timing"), Some("subtitles")));    assert_eq!((choices[1]["label"].as_str(), choices[1]["failed"].as_str()), (Some("Use this frame as the poster"), Some("This frame could not be kept just now.")));    let picked = ask(&client, json!({"op": "use_frame", "path": frame(dir.path(), "one.jpg", b"one"), "at_s": 61.5}));    assert_eq!(choice_ids(&picked), ["subtitle_timing", "use_frame", "original_picture"]);    assert_eq!(picked["now"]["more"]["choices"][2]["label"], "Back to the original picture");}// RULE (film-poster-pick, 18 Nov 2026): a frame picked is worn as the film's poster, sealed media under a picture key, with the poster it replaced and where it was taken remembered; a second frame keeps the first original, and going back wears it again and forgets the pick.#[test]fn a_picked_frame_is_worn_and_the_original_comes_back() {    let (dir, client) = attached();    let id = made_row(&client, "film", json!({"title": "Invented Reel", "poster": "db/media/found.jpg"}));    landed(&client, "film", &id, &[("file", json!("db/films/reel/master.m3u8"))]);    ask(&client, json!({"op": "play", "table": "film", "id": id}));    let first = ask(&client, json!({"op": "use_frame", "path": frame(dir.path(), "one.jpg", b"one"), "at_s": 61.5}));    assert_eq!(first["said"], "This frame is the poster now.");    let worn = record(&client, "film", &id);    let kept = worn["poster"].as_str().expect("the frame's key").to_string();    assert_ne!(kept, "db/media/found.jpg");    assert_eq!(first["now"]["cover"].as_str(), Some(kept.as_str()), "the lock screen wears it too");    assert_eq!((worn["poster_before"].as_str(), worn["poster_from"].as_f64()), (Some("db/media/found.jpg"), Some(61.5)));    ask(&client, json!({"op": "use_frame", "path": frame(dir.path(), "two.jpg", b"two"), "at_s": 90}));    let again = record(&client, "film", &id);    assert_ne!(again["poster"].as_str(), Some(kept.as_str()));    assert_eq!((again["poster_before"].as_str(), again["poster_from"].as_f64()), (Some("db/media/found.jpg"), Some(90.0)), "the original is still the one to go back to");    let back = ask(&client, json!({"op": "original_picture"}));    assert_eq!(back["said"], "The original picture is back.");    assert_eq!(back["now"]["cover"], "db/media/found.jpg");    assert_eq!(choice_ids(&back), ["subtitle_timing", "use_frame"]);    let gone = record(&client, "film", &id);    assert_eq!(gone["poster"], "db/media/found.jpg");    assert!(gone["poster_before"].is_null() && gone["poster_from"].is_null(), "{gone}");    assert!(call(&client, &json!({"op": "original_picture"})).is_err(), "no frame is worn to go back from");}// RULE (film-poster-pick, 18 Nov 2026): an episode's frame is its still, in the still's words, and a film that wore no picture goes back to wearing none.#[test]fn an_episodes_frame_is_its_still() {    let (dir, client) = attached();    let series = made_row(&client, "film", json!({"title": "Invented Serial", "kind": "series"}));    let season = made_row(&client, "film_season", json!({"title": "Season 1", "film": series, "number": 1}));    let id = made_row(&client, "film_episode", json!({"title": "Pilot", "season": season, "series": series, "number": 1}));    landed(&client, "film_episode", &id, &[("file", json!("db/films/pilot/master.m3u8"))]);    let playing = ask(&client, json!({"op": "play", "table": "film_episode", "id": id}));    assert_eq!(playing["now"]["more"]["choices"][1]["label"], "Use this frame as the still");    let picked = ask(&client, json!({"op": "use_frame", "path": frame(dir.path(), "still.png", b"still"), "at_s": 12}));    assert_eq!(picked["said"], "This frame is the still now.");    let worn = record(&client, "film_episode", &id);    assert!(worn["still"].as_str().is_some_and(|key| !key.is_empty()));    assert_eq!(worn["still_from"].as_f64(), Some(12.0));    ask(&client, json!({"op": "original_picture"}));    assert!(record(&client, "film_episode", &id)["still"].is_null());}// RULE (film-poster-pick, 18 Nov 2026): a frame is only ever picked for the film playing, from a file the core can keep, at a place in the film.#[test]fn a_frame_is_refused_without_its_film_file_or_place() {    let (dir, client) = attached();    let path = frame(dir.path(), "one.jpg", b"one");    assert_eq!(call(&client, &json!({"op": "use_frame", "path": path, "at_s": 1})).expect_err("nothing plays").code, "bad_request");    let id = made_row(&client, "film", json!({"title": "Invented Reel", "poster": "db/media/found.jpg"}));    landed(&client, "film", &id, &[("file", json!("db/films/reel/master.m3u8"))]);    ask(&client, json!({"op": "play", "table": "film", "id": id}));    assert_eq!(call(&client, &json!({"op": "use_frame", "at_s": 1})).expect_err("no file").code, "bad_request");    assert_eq!(call(&client, &json!({"op": "use_frame", "path": path})).expect_err("no place").code, "bad_request");    assert!(call(&client, &json!({"op": "use_frame", "path": frame(dir.path(), "one.txt", b"one"), "at_s": 1})).is_err(), "no picture's type");    assert_eq!(record(&client, "film", &id)["poster"], "db/media/found.jpg", "a refused frame changes nothing");}// RULE (film-poster-pick, 18 Nov 2026): a database whose film table has not taken the columns a pick is remembered in neither offers a frame nor takes one: the frame would be worn and the original lost.#[test]fn a_frame_is_not_taken_where_the_original_could_not_be_kept() {    let (dir, client) = attached();    let id = made_row(&client, "film", json!({"title": "Invented Reel", "poster": "db/media/found.jpg"}));    landed(&client, "film", &id, &[("file", json!("db/films/reel/master.m3u8"))]);    client        .with_writer(|file| {            let held = file.driver.all("SELECT definition FROM cotton_table_definitions WHERE id = 'film'", &[]).map_err(|error| error.to_string())?;            let text = match held.first().and_then(|row| row.columns().iter().find(|(name, _)| name == "definition").map(|(_, value)| value.clone())) {                Some(rusqlite::types::Value::Text(text)) => text,                other => return Err(format!("the film definition: {other:?}")),            };            let mut older: Value = serde_json::from_str(&text).map_err(|error| error.to_string())?;            let gone = ["poster_before", "poster_from"];            older["columns"].as_array_mut().expect("columns").retain(|column| !gone.contains(&column["key"].as_str().unwrap_or_default()));            older["seal"]["clear"].as_array_mut().expect("clear").retain(|key| !gone.contains(&key.as_str().unwrap_or_default()));            let sql = "UPDATE cotton_table_definitions SET definition = ? WHERE id = 'film'";            file.driver.run(sql, &[rusqlite::types::Value::Text(older.to_string())]).map_err(|error| error.to_string())?;            crate::fixture::receipted(file.driver, sql);            Ok(())        })        .expect("the older definition");    let playing = ask(&client, json!({"op": "play", "table": "film", "id": id}));    assert_eq!(choice_ids(&playing), ["subtitle_timing"], "no frame is offered");    assert!(call(&client, &json!({"op": "use_frame", "path": frame(dir.path(), "one.jpg", b"one"), "at_s": 5})).is_err());    assert_eq!(record(&client, "film", &id)["poster"], "db/media/found.jpg", "the poster stands");}