Cotton code
167 lines · 10.6 KB · RustRaw
//! Cinemas' Give subtitles on this phone (SUBTITLE FILE, 25 Nov 2026): a//! picked .srt or .vtt kept sealed beside the film's stream, and the row asking//! the Mac to lay it. Invented films and subtitle text only.use serde_json::json;use super::*;use crate::shell::client::phone_tests::attached;const SRT: &str = "1\n00:00:01,000 --> 00:00:02,500\nAn invented line.\n";fn film(client: &ClientController, table: &str, file: Option<&str>) -> String {    let file = file.map(str::to_string);    let table = table.to_string();    let answer = client        .write_rows("test.film", &mut |ctx| {            let mut data = Map::new();            data.insert("title".into(), json!("Night Ferry"));            if table == "film" {                data.insert("kind".into(), json!("film"));                data.insert("status".into(), json!("want_to_watch"));            } else {                let mut series = Map::new();                series.insert("title".into(), json!("Lowmarsh"));                series.insert("kind".into(), json!("series"));                series.insert("status".into(), json!("want_to_watch"));                let series = super::super::songs::made(ctx, "film", series)?;                let mut season = Map::new();                season.insert("film".into(), json!(series));                season.insert("number".into(), json!(1));                season.insert("title".into(), json!("Season 1"));                data.insert("season".into(), json!(super::super::songs::made(ctx, "film_season", season)?));                data.insert("number".into(), json!(1));            }            if let Some(file) = &file {                data.insert("file".into(), json!(file));            }            let id = super::super::songs::made(ctx, &table, data)?;            Ok(json!({ "id": id }))        })        .expect("a film");    crate::authoring::own_answer(answer)["id"].as_str().expect("an id").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()}fn given(dir: &std::path::Path, name: &str, text: &str) -> String {    let path = dir.join(name);    std::fs::write(&path, text).expect("the file");    path.to_string_lossy().to_string()}// RULE (SUBTITLE FILE, 25 Nov 2026): a .srt picked on a film's page is kept sealed in the film's folder, queued up and pinned here, and the row asks the Mac (`subtitle_work` file) with the language its name says.#[test]fn a_picked_subtitle_file_is_kept_beside_the_stream_and_asks_the_mac() {    let (dir, client) = attached();    let master = format!("{}/films/f-ferry/master-0123456789ab.m3u8", crate::fixture::WORKSPACE);    let id = film(&client, "film", Some(&master));    let answer = give(&client, &json!({ "table": "film", "id": id, "path": given(dir.path(), "Night.Ferry.2019.en.srt", SRT) })).expect("given");    let key = answer["key"].as_str().expect("a key").to_string();    assert!(key.starts_with(&format!("{}/films/f-ferry/given/sub-", crate::fixture::WORKSPACE)) && key.ends_with(".srt"), "{key}");    assert_eq!(answer["language"], "en");    assert!(answer.get("said").is_none(), "the act's receipt says it, with the film's name: {answer}");    let row = record(&client, "film", &id);    assert_eq!((row["subtitle_given"].as_str(), row["subtitle_given_language"].as_str(), row["subtitle_work"].as_str()), (Some(key.as_str()), Some("en"), Some("file")));    assert_eq!(row["subtitle_note"], "Waiting for your Mac to add your subtitles");    let ledger = client.with_writer(|replica| Ok(cotton_store::media_ledger::media_by_key(replica.driver, &key).ok().flatten())).expect("the ledger");    assert!(ledger.is_some(), "queued to go up sealed for the Mac");    // The same bytes again name the same key; a name that says no language leaves it to the Mac.    let again = give(&client, &json!({ "table": "film", "id": id, "path": given(dir.path(), "The.Matrix.srt", SRT) })).expect("given again");    assert_eq!(again["key"], json!(key));    assert!(again["language"].is_null(), "a title's word is no language: {again}");    assert!(record(&client, "film", &id)["subtitle_given_language"].is_null());}// RULE: an episode takes a .vtt the same way.#[test]fn an_episode_takes_a_vtt() {    let (dir, client) = attached();    let master = format!("{}/films/e-reeds/master.m3u8", crate::fixture::WORKSPACE);    let id = film(&client, "film_episode", Some(&master));    let vtt = format!("WEBVTT\n\n{}", SRT.replace(',', "."));    let answer = give(&client, &json!({ "table": "film_episode", "id": id, "path": given(dir.path(), "S01E01.fr.vtt", &vtt) })).expect("given");    assert!(answer["key"].as_str().unwrap().ends_with(".vtt"));    assert_eq!(record(&client, "film_episode", &id)["subtitle_work"], "file");}// RULE: refused with nothing written: another kind of file, one with no cue, a film with no stream, a row that is no film.#[test]fn what_is_not_a_subtitle_for_a_streamed_film_is_refused_and_nothing_is_written() {    let (dir, client) = attached();    let streamed = film(&client, "film", Some(&format!("{}/films/f-a/master.m3u8", crate::fixture::WORKSPACE)));    let poster = film(&client, "film", None);    let refused = |table: &str, id: &str, path: String| give(&client, &json!({ "table": table, "id": id, "path": path })).expect_err("refused").message;    assert_eq!(refused("film", &streamed, given(dir.path(), "a.ass", SRT)), "this takes only a .srt, .vtt file");    assert_eq!(refused("film", &streamed, given(dir.path(), "b.srt", "no cues here")), "That file holds no subtitle lines: pick a .srt or .vtt file");    assert!(refused("film", &poster, given(dir.path(), "d.srt", SRT)).starts_with("This film has no stream yet"));    assert_eq!(refused("book", "x", given(dir.path(), "e.srt", SRT)), "Give subtitles is a film's or an episode's");    for id in [&streamed, &poster] {        assert!(record(&client, "film", id).get("subtitle_work").is_none_or(Value::is_null), "nothing written");    }}fn cinemas() -> (tempfile::TempDir, crate::handle::CottonHandle) {    let dir = tempfile::tempdir().expect("a temp container");    // Cotton Cinemas' flavour (apps/cotton/App/Flavours/cinemas/flavour.json), as the app opens.    let manifest = json!({        "genesis": "personal", "flavour": "cinemas", "name": "Cotton Cinemas", "ground": "velvet",        "databases": "single", "database": "personal", "fan": {"home": false, "tools": false, "opens": "cinemas"}, "kit": "cinemas",    });    let handle = crate::handle::CottonHandle::open(crate::handle::OpenConfig {        mode: crate::handle::OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None },        app_version: None,        time_zone: Some("Asia/Kolkata".to_string()),        device_secret: Some(crate::fixture::paired_secret()),        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: Some(manifest),    })    .expect("an open core");    crate::methods::dispatch(&handle, "workspace.startLocal", &json!({"deviceName": "An invented phone"})).expect("started");    (dir, handle)}// RULE (SUBTITLE FILE): Give subtitles is a film page's act whose pick step asks the phone for a file of its kinds; the picked copy's path, committed as the step's words, runs the act, and a file of another kind is refused by name.#[test]fn give_subtitles_asks_the_phone_for_a_file_and_its_path_runs_the_act() {    let (dir, handle) = cinemas();    let ask = |method: &str, request: Value| crate::methods::dispatch(&handle, method, &request);    let client = handle.client();    let database = client.read_rows("test", &mut |ctx| Ok(json!(ctx.file.id().to_string()))).expect("the database");    let id = film(&client, "film", Some(&format!("{}/films/f-ferry/master.m3u8", database.as_str().unwrap())));    let opened = ask("shell.opened", json!({"table": "film", "id": id, "timezone": "Asia/Kolkata"})).expect("opened");    let give = opened["acts"].as_array().unwrap().iter().find(|act| act["id"] == "give_subtitles").unwrap_or_else(|| panic!("Give subtitles offered: {opened}"));    assert_eq!(give["picks"], true, "{give}");    let step = ask("shell.opened", json!({"table": "film", "id": id, "step": "pick", "act": "give_subtitles", "timezone": "Asia/Kolkata"})).expect("the pick");    let file = &step["step"]["file"];    assert_eq!(file["accept"], json!(["srt", "vtt"]), "{step}");    assert_eq!(file["writes"]["kind"], "pick_file", "{step}");    let refused = ask("shell.input", json!({"op": "commit", "writes": file["writes"], "words": given(dir.path(), "Night.Ferry.ass", SRT), "timezone": "Asia/Kolkata"}));    let said = refused.map(|answer| answer.to_string()).unwrap_or_else(|error| error.message);    assert!(said.contains("this takes only a .srt, .vtt file"), "{said}");    let ran = ask("shell.input", json!({"op": "commit", "writes": file["writes"], "words": given(dir.path(), "Night.Ferry.en.srt", SRT), "timezone": "Asia/Kolkata"})).expect("ran");    assert!(ran.get("refusal").is_none(), "{ran}");    assert_eq!(ran["ran"]["receipt"], "Your Mac will add your subtitles to Night Ferry", "{ran}");    assert!(ran["ran"]["answer"].get("said").is_none(), "nothing drawn after the receipt hides it: {ran}");    let row = record(&client, "film", &id);    assert_eq!((row["subtitle_work"].as_str(), row["subtitle_given_language"].as_str()), (Some("file"), Some("en")), "{row}");    let again = ask("shell.opened", json!({"table": "film", "id": id, "timezone": "Asia/Kolkata"})).expect("opened again");    assert!(again["acts"].as_array().unwrap().iter().all(|act| act["id"] != "give_subtitles" && act["id"] != "find_subtitles"), "no ask is offered while the Mac has one: {again}");}// RULE (CINEMAS WALK, 25 Nov 2026): a film kept whole as the phone sent it takes a subtitle file too, beside its whole// file, and its note says the Mac makes its stream first; refusing it promised a conversion nothing made.#[test]fn a_film_kept_whole_takes_a_subtitle_file_and_waits_for_its_stream() {    let (dir, client) = attached();    let whole = film(&client, "film", Some(&format!("{}/films/f-b/whole.mp4", crate::fixture::WORKSPACE)));    let answer = give(&client, &json!({ "table": "film", "id": whole, "path": given(dir.path(), "Walk.en.srt", SRT) })).expect("taken");    assert_eq!(answer["key"].as_str().unwrap().rsplit_once("/given/").unwrap().0, format!("{}/films/f-b", crate::fixture::WORKSPACE));    let row = record(&client, "film", &whole);    assert_eq!(row["subtitle_work"], "file");    assert_eq!(row["subtitle_given_language"], "en");    assert_eq!(row["subtitle_note"], "Waiting for your Mac to make this film's stream and add your subtitles");}