Cotton code
298 lines · 14.9 KB · RustRaw
//! SEND TO A FRIEND, PROVEN ON DEV (Cinemas): two invented people, each a Cinemas phone through the C ABI against the//! dev Worker. A writes to B in Comms (the thread the object's people list reads, send.ts people() → chat.peopleOf),//! brings in an invented film whose file goes up, sees B in Send's list, and sends the film; B finds it in its inbox,//! keeps it, and the film stands on B's phone with its file held by B's object and plays. 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 numbers (+1555017<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::Engine as _;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-send";const FLAVOUR: &str = "cinemas";const WAIT: Duration = Duration::from_secs(150);struct Walk {    server: String,    code: String,    run: String,}impl Walk {    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"), "a send is 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 })    }    fn number(&self, slot: u32) -> String {        format!("+1555017{}{slot}", self.run)    }}struct Phone {    handle: *mut CottonHandle,    container: tempfile::TempDir,    name: &'static str,    number: String,    private_key: String,    chat_key: String,    credential: String,}impl Phone {    fn open(walk: &Walk, slot: u32, name: &'static str) -> Phone {        let container = tempfile::tempdir().expect("a tempdir");        std::fs::create_dir_all(container.path().join("cotton")).expect("the container");        let number = walk.number(slot);        let seed = format!("cotton headless cinemas send {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");        let mut 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(), "{name}: cotton_open refused: {}", take(error));        let private_key = URL_SAFE_NO_PAD.encode(Sha256::digest(format!("vault {seed}").as_bytes()));        Phone { handle, container, name, number, private_key, chat_key: String::new(), credential: 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) {            return Ok(answer["data"].clone());        }        Err(format!("{} {method}: {} {}", self.name, 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}"))    }    /// The call with this phone's chat key added, as ChatEngine adds it.    fn keyed(&self, method: &str, mut request: Value) -> Value {        request["privateKey"] = json!(self.chat_key);        self.must(method, request)    }    /// Sign in (the SignIn form's calls, then `personal.connect`), found the account's key, and register a chat key.    fn sign_in(&mut self, walk: &Walk) {        self.must("personal.standLocal", json!({ "signedOut": true }));        let challenge = self.must("personal.code", json!({ "server": walk.server, "phone": self.number }));        let mut ask = json!({ "server": walk.server, "challengeId": challenge["challengeId"], "code": walk.code });        if let Some(database) = challenge.get("databaseId").filter(|d| !d.is_null()) {            ask["databaseId"] = database.clone();        }        let answer = self.must("personal.signIn", ask);        let 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": database, "credential": self.credential, "deviceName": format!("headless cinemas send {}", self.name), "appVersion": APP_VERSION }));        let mut held = false;        for _ in 0..30 {            let status = self.must("seal.status", json!({}));            if status["keyHeld"] == json!(true) {                held = true;                break;            }            if status["needsKey"] == json!(true) && status["founds"] == json!(true) {                let _ = self.call("vault.unlock", json!({ "privateKey": self.private_key, "name": "headless cinemas send" }));            }            let _ = self.call("sync.now", json!({}));            std::thread::sleep(Duration::from_secs(1));        }        assert!(held, "{}: the account's key was never held", self.name);        self.chat_key = self.must("chat.key", json!({}))["privateKey"].as_str().expect("chat.key minted a key").to_string();        self.keyed("chat.register", json!({ "ratchet": true }));    }    fn sync(&self) {        for _ in 0..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 * 37 % 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())    }}impl Drop for Phone {    fn drop(&mut self) {        // SAFETY: the pointer cotton_open answered, closed once.        unsafe { cotton_close(self.handle) };    }}fn take(text: *mut c_char) -> String {    if text.is_null() {        return String::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");    let mut 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)    })}fn until(what: &str, started: Instant, mut check: impl FnMut() -> 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 SEND PROOF {line} ({:.1} s)", started.elapsed().as_secs_f64());}/// Every film-like row of the library (films and episodes) as cinemas.home lists them, by title.fn titles(home: &Value) -> Vec<(String, String, String)> {    let mut out = Vec::new();    for row in home["rows"].as_array().into_iter().flatten() {        for item in row["items"].as_array().into_iter().flatten() {            if let (Some(t), Some(i), Some(title)) = (item["table"].as_str(), item["id"].as_str(), item["title"].as_str()) {                out.push((t.to_string(), i.to_string(), title.to_string()));            }        }    }    out}#[test]fn a_film_sent_to_a_friend_in_comms_lands_on_their_phone_and_plays() {    let Some(walk) = Walk::from_env() else {        eprintln!("skipped: COTTON_WALK_SERVER and COTTON_WALK_CODE_FILE are not set");        return;    };    let started = Instant::now();    let mut a = Phone::open(&walk, 1, "A");    let mut b = Phone::open(&walk, 2, "B");    a.sign_in(&walk);    b.sign_in(&walk);    step(&format!("A and B signed in on dev (run {})", walk.run), started);    // 1. Nobody yet: Send's list is empty before A talks to anyone in Comms.    let (film, key) = a.bring_in("Proof Harbour (2019).mp4", 300_000);    let a_database = key.split('/').next().unwrap_or_default().to_string();    until("A's film going up", started, || {        a.sync();        held(&walk, &a, &key) == 200    });    let before = a.must("send.offer", json!({ "table": "film", "id": film }));    assert_eq!(before["people"].as_array().map(Vec::len), Some(0), "nobody before a Comms thread: {before}");    step("A's film is up; Send lists nobody yet", started);    // 2. A writes to B in Comms (nobody is found by their number: B sees A's ask), B accepts and answers: each is in    // the other's people.    let thread = a.must("chat.start", json!({ "number": b.number }));    let ab = thread["thread"].as_str().expect("a thread").to_string();    a.keyed("chat.send", json!({ "thread": ab, "body": "a film for you" }));    until("A's message reaching B", started, || {        b.keyed("chat.incoming", json!({}));        b.must("chat.list", json!({})).to_string().contains(&a.number)    });    let list = b.must("chat.list", json!({}));    let ba = list["rows"].as_array().or(list["threads"].as_array()).into_iter().flatten()        .find(|r| r.to_string().contains(&a.number)).and_then(|r| r["thread"].as_str().or(r["id"].as_str())).expect("B's thread with A").to_string();    let _ = b.call("chat.accept", json!({ "thread": ba }));    b.keyed("chat.send", json!({ "thread": ba, "body": "thanks" }));    step("A and B talk in Comms", started);    // 3. A sends: B stands in Send's list, and the send leaves.    let mut offer = Value::Null;    until("B standing in A's Send list", started, || {        offer = a.must("send.offer", json!({ "table": "film", "id": film }));        offer["people"].as_array().into_iter().flatten().any(|p| p["number"] == json!(b.number))    });    assert_eq!(offer["sendable"], json!(true), "the film is sendable: {offer}");    let sent = a.must("send.make", json!({ "table": "film", "id": film, "to": b.number }));    let send_id = sent["id"].as_str().expect("a send id").to_string();    println!("CINEMAS SEND PROOF sent: {} · {} bytes · {}", sent["title"], sent["bytes"], sent["receipt"]);    step("A sent the film to B", started);    // 4. B finds it in the inbox and keeps it; the film lands on B's phone.    until("the send in B's inbox", started, || b.must("send.inbox", json!({})).to_string().contains(&send_id));    let kept = b.must("send.keep", json!({ "id": send_id }));    println!("CINEMAS SEND PROOF B kept it: state {}", kept["state"]);    let mut landed: Option<(String, String)> = None;    until("the film landing in B's library", started, || {        let _ = b.call("send.inbox", json!({}));        b.sync();        landed = titles(&b.must("cinemas.home", json!({}))).into_iter().find(|(_, _, t)| t.contains("Proof Harbour")).map(|(t, i, _)| (t, i));        landed.is_some()    });    let (table, id) = landed.expect("the landed film");    step(&format!("the film stands in B's library ({table})"), started);    // 5. It plays on B, from a file B's own object holds (B's row names it under B's database; the player streams it).    let mut last = String::new();    let waiting = Instant::now();    let file = loop {        b.sync();        let row = b.must("records.get", json!({ "table": table, "id": id }));        let file = row["data"]["file"].as_str().map(str::to_string);        let code = file.as_deref().map(|f| held(&walk, &b, f));        last = format!("B's row names {file:?}; B's object answers {code:?}");        if code == Some(200) {            break file.unwrap();        }        assert!(waiting.elapsed() < WAIT, "B's copy of the file did not stand in {} s: {last}", WAIT.as_secs());        std::thread::sleep(Duration::from_secs(3));    };    assert!(!file.starts_with(&a_database), "B's film names a file of B's own, not A's: {file}");    let play = b.must("shell.player", json!({ "op": "play", "table": table, "id": id }));    assert_eq!(play["now"]["kind"], json!("film"), "{play}");    assert!(play["now"]["stream"].as_str().is_some_and(|s| !s.is_empty()), "B's player has a stream: {play}");    step(&format!("it plays on B: {} ({last})", play["now"]["title"]), started);    println!("CINEMAS SEND PROOF PASSED ({:.1} s)", started.elapsed().as_secs_f64());}