Cotton code
250 lines · 13.6 KB · RustRaw
//! PLAYER START, TIMED ON DEV (owner, 26 Nov 2026: "the player doesn't come up immediately… 4 to 8 seconds"): what the//! core and the object spend between a tap on Play and the first frame's bytes, for a film the Mac laid as a sealed//! HLS folder (as all of his are) that this phone does not keep.//!//! Two phases, COTTON_PS_PHASE://! - `found`: a fresh Cinemas phone signs in to an invented number, founds the vault and writes a recovery code to//!   COTTON_PS_CODE_OUT (mode 600, never printed), for the box to join as the person's Mac//!   (the Mac stand-in's `join`) and import an invented film (`pnpm film:import`).//! - `time`: another fresh phone signs in to the same number, opens the vault with that code, syncs, and times, cold//!   and then warm: `shell.player { op: play }` (the core's answer: the signed or local address), then what the system//!   player asks first through that address: the master, the first variant's playlist, its init segment and first two//!   segments, and the default subtitles playlist if there is one. Each step prints one `PLAYER START` line.//!//! SKIPPED unless COTTON_WALK_SERVER (dev), COTTON_WALK_CODE_FILE, COTTON_PS_NUMBER and COTTON_PS_PHASE are set.use std::ffi::{c_char, CStr, CString};use std::io::{Read, Write};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};fn var(name: &str) -> Option<String> {    std::env::var(name).ok().filter(|v| !v.trim().is_empty())}fn home(path: &str) -> PathBuf {    match path.strip_prefix("~/") {        Some(rest) => PathBuf::from(std::env::var("HOME").expect("HOME")).join(rest),        None => PathBuf::from(path),    }}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}struct Phone {    handle: *mut CottonHandle,    _container: tempfile::TempDir,    private_key: String,}impl Phone {    fn open(server: &str, number: &str) -> Phone {        let container = tempfile::tempdir().expect("a tempdir");        std::fs::create_dir_all(container.path().join("cotton")).expect("the container");        let seed = format!("cotton player start {number} {:?}", std::time::SystemTime::now());        let path = cotton_store::manifest_dir().join("../../apps/cotton/App/Flavours/cinemas/flavour.json");        let mut manifest: Value = serde_json::from_str(&std::fs::read_to_string(&path).expect("the manifest")).expect("JSON");        manifest["business"]["server"] = json!(server);        let config = json!({            "containerPath": container.path().join("cotton").to_string_lossy(),            "appVersion": "headless-player-start",            "timeZone": "Asia/Kolkata",            "deviceSecret": URL_SAFE_NO_PAD.encode(Sha256::digest(seed.as_bytes())),            "flavor": "dev",            "manifest": manifest,        });        let text = CString::new(config.to_string()).unwrap();        let mut error: *mut c_char = std::ptr::null_mut();        // SAFETY: a NUL-terminated config and a writable error slot.        let handle = unsafe { cotton_open(text.as_ptr(), &mut error) };        assert!(!handle.is_null(), "cotton_open: {}", take(error));        let private_key = URL_SAFE_NO_PAD.encode(Sha256::digest(format!("vault {seed}").as_bytes()));        Phone { handle, _container: container, private_key }    }    fn call(&self, method: &str, request: Value) -> Result<Value, String> {        let m = CString::new(method).unwrap();        let r = CString::new(request.to_string()).unwrap();        // SAFETY: a live handle and NUL-terminated strings.        let answer: Value = serde_json::from_str(&take(unsafe { cotton_call(self.handle, m.as_ptr(), r.as_ptr()) })).unwrap();        if answer["ok"] == json!(true) {            Ok(answer["data"].clone())        } else {            Err(format!("{method}: {}", answer["error"]))        }    }    fn sign_in(&self, server: &str, number: &str, otp: &str) {        self.call("personal.standLocal", json!({ "signedOut": true })).unwrap();        let challenge = self.call("personal.code", json!({ "server": server, "phone": number })).unwrap();        let mut ask = json!({ "server": server, "challengeId": challenge["challengeId"], "code": otp });        if let Some(d) = challenge.get("databaseId").filter(|d| !d.is_null()) {            ask["databaseId"] = d.clone();        }        let answer = self.call("personal.signIn", ask).unwrap();        let database = answer["databaseId"].as_str().or(challenge["databaseId"].as_str()).expect("a database").to_string();        let credential = answer["credential"].as_str().expect("a credential").to_string();        self.call("personal.connect", json!({ "server": server, "databaseId": database, "credential": credential, "deviceName": "player start", "appVersion": "headless-player-start", "unmetered": true })).unwrap();    }    fn hold_key(&self, code: Option<&str>) {        for _ in 0..30 {            let status = self.call("seal.status", json!({})).unwrap();            if status["keyHeld"] == json!(true) {                return;            }            if status["needsKey"] == json!(true) {                match (status["founds"] == json!(true), code) {                    (true, _) => drop(self.call("vault.unlock", json!({ "privateKey": self.private_key, "name": "player start" }))),                    (false, Some(code)) => drop(self.call("recovery.open", json!({ "code": code, "privateKey": self.private_key, "name": "player start" }))),                    _ => {}                }            }            let _ = self.call("sync.now", json!({}));            std::thread::sleep(Duration::from_secs(2));        }        panic!("the key was never held");    }}impl Drop for Phone {    fn drop(&mut self) {        // SAFETY: the pointer cotton_open answered, closed once.        unsafe { cotton_close(self.handle) };    }}/// One plain HTTP/1.1 GET to the phone's own loopback door, as the system player makes it: the status, the body, the/// time to its first byte and to its last.fn get(url: &str) -> (u16, Vec<u8>, Duration, Duration) {    let rest = url.strip_prefix("http://").expect("a loopback address");    let (host, path) = rest.split_once('/').map(|(h, p)| (h, format!("/{p}"))).unwrap_or((rest, "/".into()));    let started = Instant::now();    let mut s = std::net::TcpStream::connect(host).expect("the loopback door");    write!(s, "GET {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n\r\n").unwrap();    let mut first = [0u8; 1];    s.read_exact(&mut first).expect("a first byte");    let ttfb = started.elapsed();    let mut all = vec![first[0]];    s.read_to_end(&mut all).unwrap();    let done = started.elapsed();    let text = String::from_utf8_lossy(&all);    let status = text.split_whitespace().nth(1).and_then(|s| s.parse().ok()).unwrap_or(0);    let body = all.windows(4).position(|w| w == b"\r\n\r\n").map(|at| all[at + 4..].to_vec()).unwrap_or_default();    (status, body, ttfb, done)}fn beside(base: &str, name: &str) -> String {    if name.starts_with("http") {        return name.to_string();    }    format!("{}/{name}", base.rsplit_once('/').map(|(b, _)| b).unwrap_or(base))}fn timed_get(what: &str, url: &str) -> Vec<u8> {    if url.starts_with("https://") {        // The object's signed address (a master laid before R6): curl times it, the address never printed.        let out = std::process::Command::new("curl").args(["-s", "-o", "/dev/stdout", "-w", "\n%{http_code} %{time_starttransfer} %{time_total}", url]).output().expect("curl");        let text = out.stdout;        let at = text.iter().rposition(|b| *b == b'\n').unwrap_or(0);        let tail = String::from_utf8_lossy(&text[at + 1..]).to_string();        let parts: Vec<&str> = tail.split_whitespace().collect();        let ms = |s: &str| (s.parse::<f64>().unwrap_or(0.0) * 1000.0) as u64;        println!("PLAYER START   {what:<26} {} first byte {:>5} ms, whole {:>5} ms, {} KB", parts.first().unwrap_or(&"?"), ms(parts.get(1).unwrap_or(&"0")), ms(parts.get(2).unwrap_or(&"0")), at / 1024);        return text[..at].to_vec();    }    let (status, body, ttfb, done) = get(url);    println!("PLAYER START   {what:<26} {status} first byte {:>5} ms, whole {:>5} ms, {} KB", ttfb.as_millis(), done.as_millis(), body.len() / 1024);    body}/// The system player's first asks, timed, from the address `play` answered.fn first_asks(master_url: &str) {    let master = String::from_utf8_lossy(&timed_get("master", master_url)).to_string();    let subtitles = master.lines().find(|l| l.starts_with("#EXT-X-MEDIA") && l.contains("TYPE=SUBTITLES") && l.contains("DEFAULT=YES")).and_then(|l| l.split("URI=\"").nth(1)).and_then(|r| r.split('"').next()).map(str::to_string);    let Some(variant) = master.lines().find(|l| !l.is_empty() && !l.starts_with('#')) else { panic!("a master with no variant: {master}") };    let variant_url = beside(master_url, variant);    let playlist = String::from_utf8_lossy(&timed_get("variant playlist", &variant_url)).to_string();    if let Some(init) = playlist.lines().find(|l| l.starts_with("#EXT-X-MAP")).and_then(|l| l.split("URI=\"").nth(1)).and_then(|r| r.split('"').next()) {        timed_get("init segment", &beside(&variant_url, init));    }    for (n, segment) in playlist.lines().filter(|l| !l.is_empty() && !l.starts_with('#')).take(2).enumerate() {        timed_get(&format!("segment {}", n + 1), &beside(&variant_url, segment));    }    if let Some(subs) = subtitles {        timed_get("default subtitles playlist", &beside(master_url, &subs));    }}#[test]fn the_player_start_is_timed() {    let (Some(server), Some(number), Some(phase)) = (var("COTTON_WALK_SERVER"), var("COTTON_PS_NUMBER"), var("COTTON_PS_PHASE")) else {        eprintln!("SKIPPED: no COTTON_WALK_SERVER, COTTON_PS_NUMBER and COTTON_PS_PHASE");        return;    };    assert!(server.contains("-dev"), "dev only, not {server}");    let otp = var("COTTON_WALK_CODE_FILE").map(|f| std::fs::read_to_string(home(&f)).expect("the dev code file").trim().to_string()).expect("the dev sign-in code");    let phone = Phone::open(&server, &number);    phone.sign_in(&server, &number, &otp);    if phase == "found" {        phone.hold_key(None);        let made = phone.call("recovery.make", json!({ "privateKey": phone.private_key })).unwrap();        let out = home(&var("COTTON_PS_CODE_OUT").expect("COTTON_PS_CODE_OUT"));        std::fs::write(&out, made["code"].as_str().expect("a code")).unwrap();        #[cfg(unix)]        std::fs::set_permissions(&out, std::os::unix::fs::PermissionsExt::from_mode(0o600)).unwrap();        println!("PLAYER START founded {number}; recovery code kept in {}", out.display());        return;    }    let code = std::fs::read_to_string(home(&var("COTTON_PS_CODE_FILE").expect("COTTON_PS_CODE_FILE"))).unwrap().trim().to_string();    phone.hold_key(Some(&code));    let mut film: Option<String> = None;    for _ in 0..30 {        let _ = phone.call("sync.now", json!({}));        let home = phone.call("cinemas.home", json!({})).unwrap_or_default();        film = home["rows"].as_array().into_iter().flatten().flat_map(|r| r["items"].as_array().cloned().unwrap_or_default()).find(|i| i["preparing"] != json!(true) && i["table"] == json!("film")).and_then(|i| i["id"].as_str().map(str::to_string));        if film.is_some() {            break;        }        std::thread::sleep(Duration::from_secs(2));    }    let film = film.expect("a playable film on Home");    // COTTON_PS_PREPARE=1: the shell's prepare as the title page opens, then a few seconds on the page before Play    // (a fresh process each run, so nothing is held from an earlier play).    let prepare = std::env::var_os("COTTON_PS_PREPARE").is_some();    let rounds: &[&str] = if prepare { &["prepared on the page, first play", "played again"] } else { &["cold, first play", "played again", "played again"] };    for round in rounds {        println!("PLAYER START {round}");        let started = Instant::now();        let title = phone.call("cinemas.title", json!({ "table": "film", "id": film })).unwrap();        println!("PLAYER START   {:<26}     {:>5} ms (the page's answer, for reference)", "cinemas.title", started.elapsed().as_millis());        if prepare && round.starts_with("prepared") {            let started = Instant::now();            let prepared = phone.call("shell.player", json!({ "op": "prepare", "table": "film", "id": film })).unwrap();            println!("PLAYER START   {:<26}     {:>5} ms, prepared {}", "shell.player prepare", started.elapsed().as_millis(), prepared["prepared"]);            std::thread::sleep(Duration::from_secs(3));        }        let started = Instant::now();        let play = phone.call("shell.player", json!({ "op": "play", "table": "film", "id": film })).unwrap();        let url = play["now"]["stream"].as_str().or(play["now"]["file"].as_str()).unwrap_or_default().to_string();        println!("PLAYER START   {:<26}     {:>5} ms, plays from {}", "shell.player play", started.elapsed().as_millis(), if url.starts_with("http://127.0.0.1") { "the phone's door (sealed)" } else if url.is_empty() { "nothing" } else { "the object's signed address" });        let _ = title;        if url.starts_with("http") {            first_asks(&url);        }        let _ = phone.call("shell.player", json!({ "op": "clear" }));    }}