//! CINEMAS FILES, PROVEN ON DEV (the Worker fix 0932bbdbc1 and the core's 5bbd70c137): an invented person, a Cinemas//! phone through the C ABI against the dev Worker, brings in an invented film whose file goes up to the object, puts it//! in the Bin and syncs (the file is still held), undoes it and syncs (the row is live there again with its file),//! empties the Bin and syncs (what the object does with the folder is said), and moves another film under a new//! series and syncs (the episode's file is still held). Every number, name and byte is invented.//!//! SKIPPED unless COTTON_WALK_SERVER (the dev Worker) and COTTON_WALK_CODE_FILE (the dev sign-in code's file: read,//! never printed) are set. COTTON_WALK_RUN picks the invented number (+1555018<run><slot>). Never the live server.use std::ffi::{c_char, CStr, CString};use std::path::PathBuf;use std::time::{Duration, Instant};use base64::engine::general_purpose::URL_SAFE_NO_PAD;use base64::Engineas _;use cotton_ffi::{cotton_call, cotton_close, cotton_open, cotton_string_free, CottonHandle};use serde_json::{json, Value};use sha2::{Digest, Sha256};const APP_VERSION: &str = "headless-cinemas";const FLAVOUR: &str = "cinemas";const WAIT: Duration = Duration::from_secs(120);structWalk { server: String, code: String, run: String,}implWalk {fn from_env() -> Option<Walk> {let var = |name: &str| std::env::var(name).ok().map(|v| v.trim().to_string()).filter(|v| !v.is_empty());let (server, file) = (var("COTTON_WALK_SERVER")?, var("COTTON_WALK_CODE_FILE")?); assert!(server.contains("-dev") || server.contains("localhost") || server.contains("127.0.0.1"), "Cinemas files are proven on the dev server only, not {server}");let file = match file.strip_prefix("~/") {Some(rest) => PathBuf::from(std::env::var("HOME").expect("HOME")).join(rest),None => PathBuf::from(file), };let code = std::fs::read_to_string(&file).unwrap_or_else(|e| panic!("the dev code file {} could not be read: {e}", file.display())).trim().to_string();let run = var("COTTON_WALK_RUN").unwrap_or_else(|| format!("{:03}", (std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).unwrap().as_millis() % 900) + 100));Some(Walk { server, code, run }) }}structPhone { handle: *mutCottonHandle, container: tempfile::TempDir, private_key: String, number: String, credential: String, database: String,}implPhone {fn open(walk: &Walk) -> Phone {let container = tempfile::tempdir().expect("a tempdir"); std::fs::create_dir_all(container.path().join("cotton")).expect("the container");let number = format!("+1555018{}1", walk.run);let seed = format!("cotton headless cinemas {number} {:?}", std::time::SystemTime::now());let config = json!({"containerPath": container.path().join("cotton").to_string_lossy(),"appVersion": APP_VERSION,"timeZone": "Asia/Kolkata","deviceSecret": URL_SAFE_NO_PAD.encode(Sha256::digest(seed.as_bytes())),"flavor": "dev","manifest": manifest(&walk.server), });let text = CString::new(config.to_string()).expect("no NUL");letmut error: *mut c_char = std::ptr::null_mut();// SAFETY: a NUL-terminated config and a writable error slot, as the JNI hands them.let handle = unsafe { cotton_open(text.as_ptr(), &mut error) }; assert!(!handle.is_null(), "cotton_open refused: {}", take(error));Phone { handle, container, number, private_key: URL_SAFE_NO_PAD.encode(Sha256::digest(format!("vault {seed}").as_bytes())), credential: String::new(), database: String::new() } }fn call(&self, method: &str, request: Value) -> Result<Value, String> {let method_c = CString::new(method).expect("no NUL");let request_c = CString::new(request.to_string()).expect("no NUL");// SAFETY: a live handle and NUL-terminated strings; the answer is owned and freed by `take`.let answer = take(unsafe { cotton_call(self.handle, method_c.as_ptr(), request_c.as_ptr()) });let answer: Value = serde_json::from_str(&answer).map_err(|e| format!("{method}: the answer is not JSON ({e})"))?;if answer["ok"] == json!(true) {returnOk(answer["data"].clone()); }Err(format!("{method}: {} {}", answer["error"]["code"].as_str().unwrap_or("?"), answer["error"]["message"].as_str().unwrap_or("?"))) }fn must(&self, method: &str, request: Value) -> Value {self.call(method, request).unwrap_or_else(|e| panic!("{e}")) }fn sign_in(&mutself, walk: &Walk) {self.must("personal.standLocal", json!({ "signedOut": true }));let challenge = self.must("personal.code", json!({ "server": walk.server, "phone": self.number }));letmut ask = json!({ "server": walk.server, "challengeId": challenge["challengeId"], "code": walk.code });ifletSome(database) = challenge.get("databaseId").filter(|d| !d.is_null()) { ask["databaseId"] = database.clone(); }let answer = self.must("personal.signIn", ask);self.database = answer["databaseId"].as_str().or(challenge["databaseId"].as_str()).expect("a database").to_string();self.credential = answer["credential"].as_str().expect("a credential").to_string();self.must("personal.connect", json!({ "server": walk.server, "databaseId": self.database, "credential": self.credential, "deviceName": "headless cinemas", "appVersion": APP_VERSION }));for _ in0..30 {let status = self.must("seal.status", json!({}));if status["keyHeld"] == json!(true) {return; }if status["needsKey"] == json!(true) && status["founds"] == json!(true) {let _ = self.call("vault.unlock", json!({ "privateKey": self.private_key, "name": "headless cinemas" })); }let _ = self.call("sync.now", json!({})); std::thread::sleep(Duration::from_secs(1)); } panic!("the account's key was never held"); }fn sync(&self) {for _ in0..3 {let _ = self.call("sync.now", json!({})); std::thread::sleep(Duration::from_millis(700)); } }/// An invented film brought in as the phone's picker does: its bytes, read as a playable MP4.fn bring_in(&self, name: &str, bytes: usize) -> (String, String) {let path = self.container.path().join(name);let body: Vec<u8> = (0..bytes).map(|i| (i * 31 % 251) as u8).collect(); std::fs::write(&path, body).expect("the invented film");let answer = self.must("films.capture", json!({ "films": [{ "path": path.to_string_lossy(), "sourcePath": name, "minutes": 2.0, "video": "avc1", "audio": "mp4a", "height": 720, "bitrate": 900 }], "onlyFilms": false }));let film = &answer["films"][0]; assert_eq!(film["outcome"], "added", "{answer}"); (film["id"].as_str().expect("an id").to_string(), film["key"].as_str().expect("a key").to_string()) }}implDropforPhone {fn drop(&mutself) {// SAFETY: the pointer cotton_open answered, closed once.unsafe { cotton_close(self.handle) }; }}fn take(text: *mut c_char) -> String {if text.is_null() {returnString::new(); }// SAFETY: a string the core allocated, read once and freed by the core.let owned = unsafe { CStr::from_ptr(text) }.to_string_lossy().into_owned();unsafe { cotton_string_free(text) }; owned}fn manifest(server: &str) -> Value {let path = cotton_store::manifest_dir().join("../../apps/cotton/App/Flavours").join(FLAVOUR).join("flavour.json");letmut whole: Value = serde_json::from_str(&std::fs::read_to_string(&path).unwrap_or_else(|error| panic!("{} reads: {error}", path.display()))).expect("JSON");if whole["business"]["server"].is_object() || whole["business"]["server"].is_string() { whole["business"]["server"] = json!(server); } whole}/// The object's answer for a key: 200 held, 404 gone.fn held(walk: &Walk, phone: &Phone, key: &str) -> u16 {let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().expect("a runtime"); runtime.block_on(async { reqwest::Client::new().head(format!("{}/v1/media/{key}", walk.server)).bearer_auth(&phone.credential).send().await.map(|r| r.status().as_u16()).unwrap_or(0) })}/// The object's own row of `table` `id`, as a pull reads it: live with its `file`, deleted, or none.fn object_row(walk: &Walk, phone: &Phone, table: &str, id: &str) -> Option<Value> {let runtime = tokio::runtime::Builder::new_current_thread().enable_all().build().expect("a runtime"); runtime.block_on(async {letmut url = format!("{}/v1/sync?since=0&tables={table}&limit=10000", walk.server);letmut found = None;for _ in0..20 {let page: Value = reqwest::Client::new().get(&url).bearer_auth(&phone.credential).send().await.ok()?.json().await.ok()?;for row in page["rows"].as_array().cloned().unwrap_or_default() {if row["id"] == id { found = Some(row); } }match page["next"].as_str() {Some(next) => url = format!("{}/v1/sync?cursor={next}", walk.server),None => break, } } found })}fn until(what: &str, started: Instant, mut check: implFnMut() -> bool) {let waiting = Instant::now();while !check() { assert!(waiting.elapsed() < WAIT, "{what} did not happen in {} s ({:.0} s in)", WAIT.as_secs(), started.elapsed().as_secs_f64()); std::thread::sleep(Duration::from_secs(3)); }}fn step(line: &str, started: Instant) { println!("CINEMAS PROOF {line} ({:.1} s)", started.elapsed().as_secs_f64());}#[test]fn an_invented_film_keeps_its_files_through_the_bin_and_a_move() {letSome(walk) = Walk::from_env() else { eprintln!("skipped: COTTON_WALK_SERVER and COTTON_WALK_CODE_FILE are not set");return; };let started = Instant::now();letmut phone = Phone::open(&walk); phone.sign_in(&walk); step("signed in on dev, key founded", started);// 1. In, and up.let (id, key) = phone.bring_in("Proof Ferry (2021).mp4", 400_000); until("the film's file going up", started, || { phone.sync(); held(&walk, &phone, &key) == 200 }); step(&format!("brought in; the object holds {key}"), started);// 2. The Bin, then a sync: the object deletes the row and keeps the folder.let binned = phone.must("records.delete", json!({ "table": "film", "id": id })); phone.sync(); until("the delete reaching the object", started, || object_row(&walk, &phone, "film", &id).is_some_and(|row| row["deleted"] == json!(true))); assert_eq!(held(&walk, &phone, &key), 200, "in the Bin, the object must still hold the film's file"); step("in the Bin and synced: the row is deleted on the object, its file still held", started);// 3. Undo: the row comes back on the object with its file, and the file is there.let change = binned["change"]["id"].as_str().map(str::to_string);match change {Some(change) => { phone.must("records.undo", json!({ "change_id": change })); }None => { phone.must("cinemas.restore", json!({ "id": id })); } } phone.sync();let back = (|| {let waiting = Instant::now();loop { phone.sync();ifletSome(row) = object_row(&walk, &phone, "film", &id).filter(|row| row["deleted"] != json!(true)) {returnSome(row); }if waiting.elapsed() > WAIT {returnNone; } std::thread::sleep(Duration::from_secs(3)); } })();let page = phone.must("cinemas.title", json!({ "table": "film", "id": id }));let play = phone.must("shell.player", json!({ "op": "play", "table": "film", "id": id })); println!("CINEMAS PROOF undo on the phone: playable {} · now {}", page["playable"], play["now"]["kind"]);match &back {Some(row) => println!("CINEMAS PROOF undo on the object: the row is live again, file named: {}", row["data"].get("file").is_some()),None => println!("CINEMAS PROOF undo on the object: the row did NOT come back live in {} s", WAIT.as_secs()), } assert_eq!(held(&walk, &phone, &key), 200, "after Undo, the object holds the file"); step("undone and synced: the file is held", started);// 4. The Bin again, emptied: what the object does with the folder. phone.must("records.delete", json!({ "table": "film", "id": id })); phone.sync();let bin = phone.must("cinemas.bin", json!({})); assert!(bin.to_string().contains(&id), "the Bin lists the film after a sync: {bin}");let emptied = phone.must("cinemas.erase", json!({})); println!("CINEMAS PROOF the Bin emptied: {emptied}");let waiting = Instant::now();letmut gone = held(&walk, &phone, &key);while gone == 200 && waiting.elapsed() < Duration::from_secs(60) { phone.sync(); std::thread::sleep(Duration::from_secs(3)); gone = held(&walk, &phone, &key); } println!("CINEMAS PROOF after emptying the Bin, the object answers {gone} for the film's file");// 5. A film moved under a new series: the episode's file is still held after the sync.let (moved, moved_key) = phone.bring_in("Marshwatchers.mp4", 300_000); until("the second film's file going up", started, || { phone.sync(); held(&walk, &phone, &moved_key) == 200 });let episode = phone.must("cinemas.toEpisode", json!({ "id": moved, "series": { "new": "Proof Lowmarsh" }, "season": 1, "episode": 1 }));let episode_id = episode["id"].as_str().expect("the episode").to_string(); phone.sync(); until("the film's delete reaching the object", started, || object_row(&walk, &phone, "film", &moved).is_some_and(|row| row["deleted"] == json!(true))); until("the episode reaching the object", started, || object_row(&walk, &phone, "film_episode", &episode_id).is_some_and(|row| row["deleted"] != json!(true))); std::thread::sleep(Duration::from_secs(5)); assert_eq!(held(&walk, &phone, &moved_key), 200, "the episode's file must still be held after the move synced");let play = phone.must("shell.player", json!({ "op": "play", "table": "film_episode", "id": episode_id })); assert_eq!((play["now"]["table"].as_str(), play["now"]["file"].as_str()), (Some("film_episode"), Some(moved_key.as_str())), "{play}"); step("moved under a series and synced: the episode's file is held and it plays", started); assert_eq!(gone, 404, "the emptied Bin takes the film's folder off the object"); println!("CINEMAS PROOF PASSED ({:.1} s)", started.elapsed().as_secs_f64());}