Cotton code
154 lines · 8.5 KB · RustRaw
//! Disappearing and starred messages between two phones on one relay//! (chat-search, 21 Nov 2026). Invented numbers and words.use super::*;impl Phone {    fn act(&self, thread: &str, act: &str, extra: Value) -> Value {        let mut request = json!({ "act": act, "thread": thread });        if let (Some(r), Some(e)) = (request.as_object_mut(), extra.as_object()) {            r.extend(e.clone());        }        let answer = self.call("chat.act", request);        self.call("chat.flush", json!({}));        answer    }    fn page(&self, thread: &str) -> Value {        self.call("chat.thread", json!({ "thread": thread }))    }    fn row_where(&self, sql: &str, value: &str) -> Option<serde_json::Map<String, Value>> {        self.handle.client().with_writer(|replica| Ok(replica.driver.get(sql, &[rusqlite::types::Value::Text(value.to_string())]).map_err(|e| e.to_string())?.map(|r| crate::phone::passwords::json_row(&r)))).unwrap()    }    /// A message by its words, in this phone's copy.    fn said(&self, words: &str) -> Option<serde_json::Map<String, Value>> {        self.row_where("SELECT * FROM cotton_msg_messages WHERE body = ?", words)    }    /// Time passes for one message: its moment to disappear is made past.    fn age(&self, id: &str) {        self.handle            .client()            .with_writer(|replica| replica.driver.run("UPDATE cotton_msg_messages SET meta = json_set(meta, '$.cotton.expiresAt', '2000-01-01T00:00:00.000Z') WHERE id = ?", &[rusqlite::types::Value::Text(id.to_string())]).map(|_| ()).map_err(|e| e.to_string()))            .unwrap();    }}fn events(page: &Value) -> Vec<String> {    page["items"].as_array().unwrap().iter().filter(|i| i["item"] == "event").map(|i| i["text"].as_str().unwrap().to_string()).collect()}fn ms(at: &str) -> i64 {    chrono::DateTime::parse_from_rfc3339(at).unwrap().timestamp_millis()}// RULE: Either person sets a chat's timer and both see it: the line says who set it, to each reader; a message written while it is on names when it goes on both phones, by the writer's clock; turned off, new messages stay.#[test]fn a_timer_set_by_one_side_holds_on_both() {    let (_relay, p) = world(&[ASHA, BEN], &[(ASHA, BEN)]);    let asha = p[0].start(BEN);    p[0].write(BEN, "hello before");    p[1].sync();    let ben = p[1].start(ASHA);    let set = p[0].act(&asha, "timer", json!({ "seconds": 604_800 }));    assert_eq!(set["flush"], true);    let mine = p[0].page(&asha);    assert_eq!(mine["timer"]["seconds"], 604_800);    assert_eq!(mine["timer"]["label"], "Disappearing messages: 7 days");    assert!(mine["timer"]["note"].as_str().unwrap().contains("screenshot"));    assert!(events(&mine).iter().any(|e| e == "You turned on disappearing messages. New messages will disappear 7 days after they're sent."), "{:?}", events(&mine));    p[1].sync();    let theirs = p[1].page(&ben);    assert_eq!(theirs["timer"]["seconds"], 604_800, "the other side sees the same timer");    assert!(events(&theirs).iter().any(|e| e.ends_with("turned on disappearing messages. New messages will disappear 7 days after they're sent.") && !e.starts_with("You")), "{:?}", events(&theirs));    p[0].write(BEN, "gone in a week");    p[1].sync();    let sent = p[0].said("gone in a week").expect("Asha keeps it");    let got = p[1].said("gone in a week").expect("Ben has it");    let at = |row: &serde_json::Map<String, Value>| {        let meta: Value = serde_json::from_str(row["meta"].as_str().unwrap()).unwrap();        (ms(meta["cotton"]["expiresAt"].as_str().unwrap()), ms(meta["cotton"]["written_at"].as_str().unwrap()))    };    let (gone_here, written_here) = at(&sent);    let (gone_there, _) = at(&got);    assert_eq!(gone_here - written_here, 604_800_000, "a week after it was written");    assert_eq!(gone_there, gone_here, "both phones by the writer's clock");    assert!(p[0].said("hello before").unwrap()["meta"].as_str().unwrap().contains("expiresAt") == false, "what came before stays");    // Ben turns it off: Asha's next words stay.    p[1].act(&ben, "timer", json!({ "seconds": 0 }));    p[0].sync();    let after = p[0].page(&asha);    assert_eq!(after["timer"]["seconds"], 0);    assert!(after["timer"].get("label").is_none());    assert!(events(&after).iter().any(|e| e.ends_with("turned off disappearing messages.") && !e.starts_with("You")), "{:?}", events(&after));    p[0].write(BEN, "this one stays");    p[1].sync();    assert!(!p[1].said("this one stays").unwrap()["meta"].as_str().unwrap().contains("expiresAt"));    // Setting what is already set says nothing new.    assert_eq!(p[0].act(&asha, "timer", json!({ "seconds": 0 }))["flush"], false);    assert_eq!(p[0].refused("chat.act", json!({ "act": "timer", "thread": asha, "seconds": 5 })), "invalid_request");}// RULE: A message whose moment has come is erased from the copy on the next answer, on each phone that holds it: its row, its reactions and its search entry go; nothing else does.#[test]fn a_disappeared_message_is_erased_from_each_phone() {    let (_relay, p) = world(&[ASHA, BEN], &[(ASHA, BEN)]);    let asha = p[0].start(BEN);    p[0].act(&asha, "timer", json!({ "seconds": 86_400 }));    p[0].write(BEN, "a secret picnic plan");    p[0].write(BEN, "and another plan");    p[1].sync();    let ben = p[1].start(ASHA);    let theirs = p[1].said("a secret picnic plan").unwrap()["id"].as_str().unwrap().to_string();    p[1].act(&ben, "react", json!({ "message": theirs, "emoji": "👍" }));    assert_eq!(p[1].call("chat.search", json!({ "text": "picnic" }))["messages"].as_array().unwrap().len(), 1);    let mine = p[0].said("a secret picnic plan").unwrap()["id"].as_str().unwrap().to_string();    p[0].age(&mine);    p[1].age(&theirs);    crate::phone::chat_timer::sweep(&p[0].handle.client()).map_err(|e| e.message).unwrap();    assert_eq!(crate::phone::chat_timer::sweep(&p[1].handle.client()).map_err(|e| e.message).unwrap(), 1, "Ben's one message due");    let page = p[1].page(&ben);    assert!(p[0].said("a secret picnic plan").is_none(), "gone from Asha's copy");    assert!(p[1].said("a secret picnic plan").is_none(), "gone from Ben's copy");    assert!(p[1].row_where("SELECT * FROM cotton_msg_reactions WHERE message_id = ?", &theirs).is_none(), "its reaction with it");    assert!(page["items"].as_array().unwrap().iter().all(|i| i["message"] != json!(theirs)));    assert!(p[1].call("chat.search", json!({ "text": "picnic" }))["messages"].as_array().unwrap().is_empty(), "and from search");    assert!(p[0].said("and another plan").is_some() && p[1].said("and another plan").is_some(), "what is not due stays");}// RULE: Starring is the person's own: a starred message says so and offers Unstar, the starred list holds it newest starred first, and the other person learns nothing.#[test]fn a_starred_message_is_the_persons_own() {    let (_relay, p) = world(&[ASHA, BEN], &[(ASHA, BEN)]);    let asha = p[0].start(BEN);    p[0].write(BEN, "the train is at seven");    p[0].write(BEN, "platform four");    p[1].sync();    let first = p[0].said("the train is at seven").unwrap()["id"].as_str().unwrap().to_string();    let second = p[0].said("platform four").unwrap()["id"].as_str().unwrap().to_string();    assert_eq!(p[0].call("chat.starred", json!({}))["empty"], "Nothing starred yet. Hold a message and choose Star to keep it here.");    let starred = p[0].act(&asha, "star", json!({ "message": first }));    assert_eq!(starred["said"], "Starred");    assert_eq!(starred["bubble"]["starred"], true);    assert!(starred["bubble"]["actions"].as_array().unwrap().contains(&json!("unstar")));    std::thread::sleep(std::time::Duration::from_millis(5));    p[0].act(&asha, "star", json!({ "message": second }));    let list = p[0].call("chat.starred", json!({}));    assert_eq!(list["title"], "Starred messages");    let ids: Vec<&str> = list["messages"].as_array().unwrap().iter().map(|m| m["message"].as_str().unwrap()).collect();    assert_eq!(ids, [second.as_str(), first.as_str()], "newest starred first");    assert_eq!(list["messages"][1]["line"], "the train is at seven");    assert_eq!(list["messages"][1]["thread"], json!(asha));    p[1].sync();    assert!(p[1].said("the train is at seven").unwrap()["starred_at"].is_null(), "Ben learns nothing");    let unstarred = p[0].act(&asha, "unstar", json!({ "message": first }));    assert_eq!(unstarred["bubble"].get("starred"), None);    assert!(unstarred["bubble"]["actions"].as_array().unwrap().contains(&json!("star")));    assert_eq!(p[0].call("chat.starred", json!({}))["messages"].as_array().unwrap().len(), 1);}