//! Films on this phone: the stream minted through the object's door, what //! this device keeps of a film and how its record says so. use std::sync::Arc; use cotton_client::transport::object::ObjectAddress; use cotton_client::transport::scripted::{Reply, ScriptedExchange}; use serde_json::json; use super::*; use crate::shell::client::phone_tests::attached; const CREDENTIAL: &str = "ctd_11111111-1111-4111-8111-111111111111_test-credential"; const MASTER: &str = "11111111-1111-4111-8111-111111111111/films/film-1/master.m3u8"; fn door(replies: impl IntoIterator) -> (ObjectDoor, Arc) { let exchange = ScriptedExchange::new(replies); let door = ObjectDoor { address: ObjectAddress::open("https://cottondb.example.test").expect("an address"), exchange: exchange.clone(), credential: CREDENTIAL.to_string(), }; (door, exchange) } fn film(client: &ClientController, file: Option<&str>) -> String { let made = crate::phone::records::call(client, "records.create", &json!({"table": "film", "data": {"title": "Synthetic Test Pattern", "kind": "film"}})).expect("a film"); let id = ["/record/id", "/id", "/after/id", "/change/after/id"] .iter() .find_map(|pointer| made.pointer(pointer).and_then(Value::as_str)) .unwrap_or_else(|| panic!("the film's id: {made}")) .to_string(); // The file is no person's to type: the intake writes it, as here. if let Some(file) = file { client .write_rows("test.file", &mut |ctx| { let mut patch = Map::new(); patch.insert("file".into(), json!(file)); crate::phone::songs::patched(ctx, "film", &id, patch)?; Ok(Value::Null) }) .expect("a file"); } id } fn on_phone(client: &ClientController, id: &str) -> Value { let record = crate::phone::records::call(client, "records.get", &json!({"table": "film", "id": id})).expect("the film"); record["data"][ON_PHONE].clone() } // RULE: a film's stream is one POST of its master's key to the object's stream route, under this phone's credential; Swift gets the address and expiry, never the bearer. #[test] fn the_stream_is_minted_through_the_objects_door() { let signed = json!({"url": format!("https://cottondb.example.test/v1/stream/tok/{MASTER}"), "expires_at": "2026-11-04T12:00:00.000Z"}); let (object, exchange) = door([Reply::ok(&signed.to_string())]); let answer = stream(&object, &json!({"key": MASTER})).expect("an address"); assert_eq!(answer, signed); assert!(!answer.to_string().contains(CREDENTIAL)); let sent = exchange.only(); assert_eq!((sent.method.as_str(), sent.path.as_str()), ("POST", "/v1/media/stream")); assert_eq!(sent.header("authorization"), Some(format!("Bearer {CREDENTIAL}").as_str())); assert_eq!(serde_json::from_slice::(&sent.body).expect("json"), json!({"key": MASTER})); } // RULE: the object's refusal reaches the player by its own word and status, so an expired token (403) is told apart from a dropped line. #[test] fn the_objects_refusal_is_said_by_its_word() { let (expired, _) = door([Reply::json(403, r#"{"code":"forbidden","message":"not yours"}"#)]); let refused = stream(&expired, &json!({"key": MASTER})).expect_err("refused"); assert_eq!(refused.code, "forbidden"); let (quiet, exchange) = door(Vec::::new()); assert_eq!(stream(&quiet, &json!({"key": "db/films/f/movie.mp4"})).expect_err("not a master").code, "bad_request"); assert!(exchange.seen().is_empty(), "nothing but a master is asked for"); } // RULE: what this device keeps of a film's stream — its bundle's bookmark and its state — reads back as written and null clears both; a kept stream names its bundle; where the film was stopped is the record's, never this file's. #[test] fn a_films_bundle_round_trips_on_this_device() { let (_dir, client) = attached(); let kept = |key: &str| read(&client, &json!({"key": key})).expect("read"); assert_eq!(kept(MASTER), json!({"key": MASTER, "bookmark": null, "state": null})); write(&client, &json!({"key": MASTER, "state": "keeping"})).expect("keeping"); write(&client, &json!({"key": MASTER, "state": "kept", "bookmark": "Ym9va21hcms="})).expect("kept"); assert_eq!(kept(MASTER), json!({"key": MASTER, "bookmark": "Ym9va21hcms=", "state": "kept"})); write(&client, &json!({"key": MASTER, "state": null})).expect("removed"); assert_eq!(kept(MASTER), json!({"key": MASTER, "bookmark": null, "state": null})); assert_eq!(write(&client, &json!({"key": MASTER, "state": "kept"})).expect_err("a bundle").code, "bad_request"); assert_eq!(write(&client, &json!({"key": MASTER, "position": 42.5, "state": null})).expect_err("no place here").code, "bad_request"); assert_eq!(write(&client, &json!({"key": MASTER, "state": "lost"})).expect_err("no such state").code, "bad_request"); let whole = "11111111-1111-4111-8111-111111111111/films/film-2/whole.mp4"; assert_eq!(write(&client, &json!({"key": whole, "state": "kept"})).expect_err("not on this phone").code, "not_here", "a whole film is kept once its file is here"); } // RULE: a film's or an episode's record answers what this device keeps of it — absent, keeping, kept — where its file is a stream or a whole film; a film with no file says nothing; a season and a series answer from their episodes. #[test] fn a_films_record_says_what_this_device_keeps_of_it() { let (_dir, client) = attached(); let streaming = film(&client, Some(MASTER)); let bare = film(&client, None); let clip = film(&client, Some("db/films/clip/clip.mp4")); assert_eq!(on_phone(&client, &streaming), json!(ABSENT)); assert_eq!(on_phone(&client, &bare), Value::Null); assert_eq!(on_phone(&client, &clip), Value::Null); write(&client, &json!({"key": MASTER, "state": "keeping"})).expect("keeping"); assert_eq!(on_phone(&client, &streaming), json!(KEEPING)); let listed = crate::phone::records::call(&client, "records.list", &json!({"table": "film"})).expect("the films"); let row = listed["records"].as_array().expect("records").iter().find(|row| row["id"] == streaming.as_str()).expect("listed"); assert_eq!(row["data"][ON_PHONE], json!(KEEPING)); assert_eq!(whole_state([Some(KEPT), Some(KEPT)]), Some(KEPT)); assert_eq!(whole_state([Some(KEPT), Some(KEEPING)]), Some(KEEPING)); assert_eq!(whole_state([Some(KEPT), Some(ABSENT)]), Some(ABSENT), "a season half kept offers Keep season"); assert_eq!(whole_state(std::iter::empty::>()), None); } // RULE: Keep on phone stands on a film whose file is not kept here and Remove download on one kept; a film with no file offers neither. #[test] fn a_films_acts_follow_what_this_device_keeps() { let (_dir, client) = attached(); let acts = |id: &str| -> Vec { let answer = crate::phone::opened::call(&client, &json!({"table": "film", "id": id})).expect("the fan"); answer["acts"].as_array().expect("actions").iter().filter_map(|a| a["id"].as_str().map(str::to_string)).collect() }; let streaming = film(&client, Some(MASTER)); let bare = film(&client, None); let offered = acts(&streaming); assert!(offered.contains(&"keep_on_phone".to_string()), "{offered:?}"); assert!(!offered.contains(&"remove_download".to_string()), "{offered:?}"); let none = acts(&bare); assert!(!none.iter().any(|id| id == "keep_on_phone" || id == "remove_download"), "{none:?}"); write(&client, &json!({"key": MASTER, "state": "kept", "bookmark": "Ym9va21hcms="})).expect("kept"); let kept = acts(&streaming); assert!(kept.contains(&"remove_download".to_string()), "{kept:?}"); assert!(!kept.contains(&"keep_on_phone".to_string()), "{kept:?}"); } // RULE: Keep on phone comes only from a film, a season or an episode not kept here, Remove download only from one keeping or kept, and neither from another table's row — so no page can make the phone download. #[test] fn a_films_flows_come_only_from_a_film_in_the_state_they_are_for() { let (_dir, client) = attached(); let id = film(&client, Some(MASTER)); let flow = |name: &str, table: &str| flow_origin(&client, name, table, &id); assert!(flow("keepFilm", "film").is_ok()); assert!(flow("removeFilmDownload", "film").is_err(), "nothing kept to remove"); assert!(flow("keepFilm", "todo").is_err(), "only a film's record"); write(&client, &json!({"key": MASTER, "state": "kept", "bookmark": "Ym9va21hcms="})).expect("kept"); assert!(flow("keepFilm", "film").is_err(), "kept already"); assert!(flow("removeFilmDownload", "film").is_ok()); } // RULE: a book's one file streams as a film's master does: the object signs its key and the phone downloads it in the background from that address (`BookKeeper`); any other plain file is refused before anything is asked. #[test] fn a_books_file_is_signed_through_the_same_door() { let book = format!("11111111-1111-4111-8111-111111111111/books/{}.epub", "a".repeat(64)); let signed = json!({"url": format!("https://cottondb.example.test/v1/stream/tok/{book}"), "expires_at": "2026-11-04T12:00:00.000Z"}); let (object, exchange) = door([Reply::ok(&signed.to_string())]); assert_eq!(stream(&object, &json!({"key": book})).expect("an address"), signed); assert_eq!(serde_json::from_slice::(&exchange.only().body).expect("json"), json!({"key": book})); let (quiet, exchange) = door(Vec::::new()); let document = "11111111-1111-4111-8111-111111111111/22222222-2222-4222-8222-222222222222/notes.pdf"; assert_eq!(stream(&quiet, &json!({"key": document})).expect_err("not a book").code, "bad_request"); assert!(exchange.seen().is_empty()); } // RULE (Cinemas gaps walk, 5 Nov 2026): a whole film that came down is kept when its bytes are the ones its record holds (`sha256`) — its key `whole.` names no digest, as a book's does — and refused in a film's words when they are not. #[test] fn a_whole_film_that_came_down_is_kept_by_the_digest_its_record_holds() { use sha2::Digest; let (dir, client) = attached(); let bytes = b"invented whole film bytes"; let digest = format!("{:x}", sha2::Sha256::digest(bytes)); let key = format!("{}/films/f1/whole.mp4", crate::fixture::WORKSPACE); let id = film(&client, Some(&key)); client .write_rows("test.sha", &mut |ctx| { let mut patch = Map::new(); patch.insert("sha256".into(), json!(digest)); crate::phone::songs::patched(ctx, "film", &id, patch)?; Ok(Value::Null) }) .expect("a digest"); let wrong = dir.path().join("wrong.mp4"); std::fs::write(&wrong, b"other bytes").expect("a file"); let refused = write(&client, &json!({"key": key, "state": "kept", "from": wrong.to_string_lossy()})).expect_err("not this film"); assert_eq!(refused.code, "not_this_film"); let came = dir.path().join("came.mp4"); std::fs::write(&came, bytes).expect("a file"); write(&client, &json!({"key": key, "state": "kept", "from": came.to_string_lossy()})).expect("kept by its record's digest"); assert_eq!(on_phone(&client, &id), "kept"); } // RULE (owner on Cotton Cinemas 1.0 (4), 7 Nov 2026): Keep on phone on a whole film whose record holds no digest is refused before anything comes down, in a person's words naming the film. #[test] fn a_whole_film_with_no_digest_is_refused_before_it_comes_down_in_words() { let (_dir, client) = attached(); let key = format!("{}/films/f2/whole.mp4", crate::fixture::WORKSPACE); let id = film(&client, Some(&key)); let refused = write(&client, &json!({"key": key, "state": "keeping"})).expect_err("no digest"); assert_eq!(refused.code, "no_digest"); assert_eq!(refused.message, "Synthetic Test Pattern cannot be kept on this phone yet: Cotton has nothing to check its download against. It still plays when you are online."); assert_eq!(on_phone(&client, &id), "absent", "nothing is keeping"); } /// A record made with `data`, its file written as the intake writes it. fn made_with_file(client: &ClientController, table: &str, data: Value, file: &str) -> String { let made = crate::phone::records::call(client, "records.create", &json!({"table": table, "data": data})).expect("a record"); let id = ["/record/id", "/id", "/after/id", "/change/after/id"] .iter() .find_map(|pointer| made.pointer(pointer).and_then(Value::as_str)) .unwrap_or_else(|| panic!("the record's id: {made}")) .to_string(); if !file.is_empty() { client .write_rows("test.file", &mut |ctx| { let mut patch = Map::new(); patch.insert("file".into(), json!(file)); crate::phone::songs::patched(ctx, table, &id, patch)?; Ok(Value::Null) }) .expect("a file"); } id } /// An invented film's stream, by its folder's name. fn whole_key(name: &str) -> String { format!("11111111-1111-4111-8111-111111111111/films/{name}/master.m3u8") } /// A plan's files by their folders' names. fn keys(plan: &Value) -> Vec { plan["files"].as_array().unwrap().iter().map(|file| file["key"].as_str().unwrap().split('/').nth(2).unwrap().to_string()).collect() } // RULE (Android Cinemas, 12 Nov 2026: the keeper decides nothing): what a keep brings down is the core's — a film its own file, a series every episode in its seasons' order, a season its episodes — leaving out what this phone keeps or is keeping, and stopping, in the kit's words, at the first that would pass this phone's budget beside what it keeps (its whole files and the bundles the platform measured); Keep everything plans only while it is on. #[test] fn a_keep_plans_its_files_within_the_budget() { let (_dir, client) = attached(); let film = made_with_file(&client, "film", json!({"title": "Synthetic Feature", "kind": "film", "minutes": 100, "bitrate": 4000}), "11111111-1111-4111-8111-111111111111/films/feature/master.m3u8"); let series = made_with_file(&client, "film", json!({"title": "Synthetic Serial", "kind": "series"}), ""); let first = made_with_file(&client, "film_season", json!({"film": series, "number": 1, "title": "Season 1"}), ""); let second = made_with_file(&client, "film_season", json!({"film": series, "number": 2, "title": "Season 2"}), ""); let episode = |season: &str, season_number: u32, number: u32, file: &str| made_with_file(&client, "film_episode", json!({"title": format!("Synthetic {season_number}x{number}"), "season": season, "series": series, "number": number, "minutes": 40, "bitrate": 4000}), file); episode(&second, 2, 1, &whole_key("s2e1")); episode(&first, 1, 2, &whole_key("s1e2")); episode(&first, 1, 1, &whole_key("s1e1")); episode(&first, 1, 3, ""); let plan = keep_plan(&client, &json!({"table": "film", "id": film})).expect("a film's plan"); assert_eq!(plan["files"], json!([{"table": "film", "id": film, "key": "11111111-1111-4111-8111-111111111111/films/feature/master.m3u8", "title": "Synthetic Feature", "streams": true}])); assert_eq!(plan["cellular"], false); assert!(plan.get("refusal").is_none(), "{plan}"); let whole = keep_plan(&client, &json!({"table": "film", "id": series})).expect("a series' plan"); assert_eq!(keys(&whole), ["s1e1", "s1e2", "s2e1"], "every episode with a file, in its seasons' order"); assert_eq!(keys(&keep_plan(&client, &json!({"table": "film_season", "id": first})).unwrap()), ["s1e1", "s1e2"]); // What this phone keeps or is keeping comes down no second time. write(&client, &json!({"key": whole_key("s1e1"), "state": "keeping"})).expect("keeping"); assert_eq!(keys(&keep_plan(&client, &json!({"table": "film_season", "id": first})).unwrap()), ["s1e2"]); // Remove download's files are the ones it keeps or is keeping, budget aside. assert_eq!(keys(&keep_plan(&client, &json!({"table": "film", "id": series, "held": true})).unwrap()), ["s1e1"]); // Past the budget (64 GB): the plan stops at the first that would pass it, and says so. let full = keep_plan(&client, &json!({"table": "film", "id": series, "bundle_bytes": 62_000_000_000u64})).expect("a full phone's plan"); assert_eq!(keys(&full), ["s1e2"], "{full}"); assert!(full["refusal"].as_str().is_some_and(|said| said.contains("64 GB")), "{full}"); // Keep everything plans only while it is on. assert_eq!(keys(&keep_plan(&client, &json!({"everything": true})).unwrap()), Vec::::new()); keep_everything(&client, &json!({"on": true})).expect("on"); assert_eq!(keys(&keep_plan(&client, &json!({"everything": true})).unwrap()), ["feature", "s1e2", "s2e1"]); assert!(keep_plan(&client, &json!({"table": "watch", "id": film})).is_err(), "only a film's, a season's or an episode's"); }