Cotton code
214 lines · 10.7 KB · RustRaw
//! THE HEADLESS CALL (`pnpm android:core-walk`'s calling half): a one-to-one//! call's signalling driven through the C ABI the Android app's JNI wraps,//! against the DEV Worker, no emulator, no media. Phone a and phone b sign in//! as Cotton Comms; b files an Android push token as the app files its FCM//! one (`calls.pushToken {platform: android}`); a calls b by number//! (`calls.start`); b is handed the ring a push would hand it//! (`calls.incoming {room}`) and its object answers who is calling; a hangs up//! and b's ring stops. What it proves is the core and the Worker's half of the//! Android ring, and whether this Worker can ring an Android phone at all://! b's object keeps a ring only where the Worker holds an FCM account//! (`canRing`, apps/business/src/calling/calls.ts), so `not_ringing` on b's//! join says the Worker has no FCM_SERVICE_ACCOUNT.//!//! SKIPPED unless COTTON_WALK_SERVER, COTTON_WALK_PHONE, COTTON_WALK_PHONE_B//! and COTTON_WALK_CODE_FILE are set (the Android core walk sets them).//! The token b files is a placeholder (no Firebase client exists for Calling//! yet): the Worker's push to it fails and drops it, after the ring is kept.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-call";struct Walk {    server: String,    code: String,    phone: String,    phone_b: Option<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, phone, file) = (var("COTTON_WALK_SERVER")?, var("COTTON_WALK_PHONE")?, var("COTTON_WALK_CODE_FILE")?);        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();        assert!(!code.is_empty(), "the dev code file {} is empty", file.display());        Some(Walk { server, code, phone, phone_b: var("COTTON_WALK_PHONE_B") })    }}/// A refusal as the boundary answers one: its code and sentence.#[derive(Debug)]struct Refused(String);impl std::fmt::Display for Refused {    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {        f.write_str(&self.0)    }}/// One phone: a core opened over its own container, as the app opens it.struct Phone {    handle: *mut CottonHandle,    _container: tempfile::TempDir,    number: String,}impl Phone {    fn open(walk: &Walk, number: &str) -> Result<Phone, Refused> {        let container = tempfile::tempdir().map_err(|e| Refused(format!("no tempdir: {e}")))?;        let config = json!({            "containerPath": container.path().join("cotton").to_string_lossy(),            "appVersion": APP_VERSION,            "timeZone": "Asia/Kolkata",            "deviceSecret": device_secret(number),            "flavor": "dev",            "manifest": manifest(&walk.server),        });        std::fs::create_dir_all(container.path().join("cotton")).map_err(|e| Refused(e.to_string()))?;        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) };        if handle.is_null() {            return Err(Refused(format!("cotton_open refused: {}", take(error))));        }        Ok(Phone { handle, _container: container, number: number.to_string() })    }    fn call(&self, method: &str, request: Value) -> Result<Value, Refused> {        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| Refused(format!("{method}: the answer is not JSON ({e})")))?;        if answer["ok"] == json!(true) {            return Ok(answer["data"].clone());        }        let error = &answer["error"];        Err(Refused(format!("{method}: {} {}", error["code"].as_str().unwrap_or("?"), error["message"].as_str().unwrap_or("?"))))    }    /// The SignIn form through the core, then the connect `Session.signIn` makes.    fn sign_in(&self, walk: &Walk) -> Result<String, Refused> {        self.call("personal.standLocal", json!({ "signedOut": true }))?;        let challenge = self.call("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.call("personal.signIn", ask)?;        let database = answer["databaseId"].as_str().or(challenge["databaseId"].as_str()).ok_or_else(|| Refused("personal.signIn named no database".into()))?.to_string();        let credential = answer["credential"].as_str().ok_or_else(|| Refused("personal.signIn granted no credential".into()))?;        self.call("personal.connect", json!({ "server": walk.server, "databaseId": database, "credential": credential, "deviceName": "headless call", "appVersion": APP_VERSION }))?;        Ok(database)    }}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: an owned string from the C ABI, freed once with its own free.    let owned = unsafe { CStr::from_ptr(text) }.to_string_lossy().into_owned();    unsafe { cotton_string_free(text) };    owned}/// The same device seed for the same number on every run, so a walk files one/// device in each object rather than a new one each push.fn device_secret(number: &str) -> String {    URL_SAFE_NO_PAD.encode(Sha256::digest(format!("cotton headless call device {number}").as_bytes()))}/// The flavour's flavour.json as the Android shell sends it (`OpenConfig.manifest`):/// every key kept, `business.server`'s `{real, dev}` collapsed to the walk's server.fn manifest(server: &str) -> Value {    let path = cotton_store::manifest_dir().join("../../apps/cotton/App/Flavours").join("messages").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"] = json!(server);    }    whole}fn phase(answer: &Value) -> String {    answer["call"]["phase"].as_str().unwrap_or("?").to_string()}fn effects(answer: &Value) -> Vec<String> {    answer["effects"].as_array().into_iter().flatten().map(|e| e["do"].as_str().unwrap_or("?").to_string()).collect()}#[test]fn a_call_rings_an_android_phone_through_the_core_against_the_dev_worker() {    let Some(walk) = Walk::from_env() else {        eprintln!("headless call skipped: COTTON_WALK_SERVER, COTTON_WALK_PHONE and COTTON_WALK_CODE_FILE are not all set");        return;    };    let number_b = walk.phone_b.clone().expect("COTTON_WALK_PHONE_B: the phone called");    let a = Phone::open(&walk, &walk.phone).unwrap_or_else(|e| panic!("phone a: {e}"));    let b = Phone::open(&walk, &number_b).unwrap_or_else(|e| panic!("phone b: {e}"));    a.sign_in(&walk).unwrap_or_else(|e| panic!("a signing in: {e}"));    b.sign_in(&walk).unwrap_or_else(|e| panic!("b signing in: {e}"));    let _ = a.call("people.add", json!({ "number": b.number }));    let _ = b.call("people.add", json!({ "number": a.number }));    println!("CALL signed in: a and b connected as Cotton Calling");    // b's push token, as the app files Firebase's.    let token = format!("walk-placeholder-{}", "x".repeat(40));    b.call("calls.pushToken", json!({ "platform": "android", "token": token })).unwrap_or_else(|e| panic!("b's token: {e}"));    println!("CALL token: b filed an android token");    // a calls b.    let started = a.call("calls.start", json!({ "number": b.number, "video": false })).unwrap_or_else(|e| panic!("a calling b: {e}"));    let room = started["call"]["room"].as_str().map(str::to_string);    println!("CALL start: a {} {:?}, room {}", phase(&started), effects(&started), room.as_deref().map(|r| &r[..6]).unwrap_or("none"));    let room = room.expect("calls.start answered the room");    assert!(effects(&started).iter().any(|e| e == "open_socket"), "a's start opens the room's socket");    // The ring is handed to b as the push would hand it, once b's object has had it.    let waited = Instant::now();    let rung = loop {        std::thread::sleep(Duration::from_secs(2));        let answer = b.call("calls.incoming", json!({ "room": room, "video": false })).unwrap_or_else(|e| panic!("b's ring: {e}"));        let ended = phase(&answer) == "ended";        println!("CALL incoming: b {} {:?} reason {} name {}", phase(&answer), effects(&answer), answer["call"]["reason"], answer["call"]["name"]);        if !ended || waited.elapsed() > Duration::from_secs(12) {            break answer;        }        let _ = b.call("calls.state", json!({}));    };    let ringing = phase(&rung) == "ringing_in";    // a hangs up; b's ring is stopped as the stop push would stop it.    let ended = a.call("calls.end", json!({})).unwrap_or_else(|e| panic!("a hanging up: {e}"));    println!("CALL end: a {} {:?} reason {}", phase(&ended), effects(&ended), ended["call"]["reason"]);    if ringing {        let stopped = b.call("calls.stop", json!({ "room": room, "reason": "cancelled" })).unwrap_or_else(|e| panic!("b's stop: {e}"));        println!("CALL stop: b {} {:?} reason {}", phase(&stopped), effects(&stopped), stopped["call"]["reason"]);    }    let _ = a.call("personal.standLocal", json!({ "signedOut": true }));    let _ = b.call("personal.standLocal", json!({ "signedOut": true }));    assert!(ringing, "b's object kept no ring for a's call: this Worker cannot ring an Android phone (no FCM_SERVICE_ACCOUNT?)");    println!("CALL PASS");}