Cotton code
147 lines · 9.3 KB · RustRaw
//! `contacts.import` and `contacts.export` on a phone with no account. Every card invented.use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};use base64::Engine as _;use serde_json::{json, Value};use crate::handle::{CottonHandle, OpenConfig, OpenMode};use crate::methods::dispatch;/// A Contacts copy with no account: the People kit, so its tools draw people and their groups.pub(crate) fn phone(dir: &tempfile::TempDir) -> CottonHandle {    let handle = CottonHandle::open(OpenConfig {        mode: OpenMode::Phone { container_path: dir.path().to_string_lossy().to_string(), previous_container_path: None },        app_version: None,        time_zone: Some("Asia/Kolkata".to_string()),        device_secret: Some(crate::fixture::paired_secret()),        vault_secret: None,        flavor: cotton_core::flavor::Flavor::Real,        manifest: Some(json!({ "genesis": "personal", "flavour": "contacts", "name": "Cotton Contacts", "databases": "single", "database": "personal", "business": { "server": { "real": "https://cottondb.com", "dev": "https://cottondb-dev.example" } }, "fan": { "home": false, "tools": false }, "kit": "people", "ground": "blank" })),    })    .expect("an open core");    dispatch(&handle, "workspace.startLocal", &json!({ "deviceName": "An invented phone" })).expect("started on the phone");    dispatch(&handle, "seal.useKey", &json!({ "key": URL_SAFE_NO_PAD.encode([7u8; 32]) })).expect("a key held");    handle}fn ask(handle: &CottonHandle, method: &str, request: Value) -> Value {    dispatch(handle, method, &request).unwrap_or_else(|error| panic!("{method} {request}: {error:?}"))}/// A one-pixel PNG.const PIXEL: &[u8] = &[    0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x48, 0x44, 0x52, 0x00, 0x00, 0x00, 0x01, 0x00, 0x00, 0x00, 0x01, 0x08, 0x06, 0x00, 0x00, 0x00, 0x1F, 0x15, 0xC4,    0x89, 0x00, 0x00, 0x00, 0x0D, 0x49, 0x44, 0x41, 0x54, 0x78, 0x9C, 0x63, 0xF8, 0xCF, 0xC0, 0xF0, 0x1F, 0x00, 0x05, 0x00, 0x01, 0xFF, 0x89, 0x99, 0x3D, 0x1D, 0x00, 0x00, 0x00, 0x00, 0x49, 0x45,    0x4E, 0x44, 0xAE, 0x42, 0x60, 0x82,];fn vcf() -> String {    format!(        "BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Asha Menon\r\nN:Menon;Asha;;;\r\nTEL;TYPE=CELL:+91 98765 00001\r\nTEL;TYPE=WORK:+91 22 0000 0002\r\nEMAIL;TYPE=HOME:asha@example.com\r\nEMAIL;TYPE=WORK:asha@work.example\r\nORG:Invented Labs\r\nBDAY:1990-05-17\r\nNOTE:Met at the invented conference\r\nCATEGORIES:Family\r\nPHOTO;ENCODING=b;TYPE=PNG:{}\r\nUID:asha-card\r\nEND:VCARD\r\nBEGIN:VCARD\r\nVERSION:3.0\r\nORG:Invented Bakery\r\nTEL;TYPE=WORK:+91 20 0000 0004\r\nEND:VCARD\r\nBEGIN:VCARD\r\nVERSION:4.0\r\nFN:Ravi Shah\r\nTEL;VALUE=uri;TYPE=cell:tel:+91-98765-00003\r\nCATEGORIES:Family,Badminton\r\nEND:VCARD\r\n",        STANDARD.encode(PIXEL)    )}#[test]fn imports_a_vcard_file_once_with_its_numbers_groups_and_picture_and_exports_it_back() {    let dir = tempfile::tempdir().expect("a dir");    let handle = phone(&dir);    let first = ask(&handle, "contacts.import", json!({ "text": vcf() }));    assert_eq!(first["read"], 3, "{first}");    assert_eq!(first["made"], 3, "{first}");    assert_eq!(first["photos"], 1, "{first}");    assert_eq!(first["groups"], 2, "{first}");    assert_eq!(first["notes"], 1, "{first}");    // The same file again changes nothing.    let again = ask(&handle, "contacts.import", json!({ "text": vcf() }));    assert_eq!(again["made"], 0, "{again}");    assert_eq!(again["already"], 3, "{again}");    let groups = ask(&handle, "groups.list", json!({ "table": "person" }));    let names: Vec<&str> = groups["groups"].as_array().unwrap().iter().filter_map(|g| g["name"].as_str()).collect();    assert!(names.contains(&"Family") && names.contains(&"Badminton"), "{groups}");    assert_eq!(names.iter().filter(|n| **n == "Family").count(), 1, "a group named twice is one group");    let out = ask(&handle, "contacts.export", json!({}));    assert_eq!(out["count"], 3, "{out}");    assert_eq!(out["filename"], "Contacts.vcf");    let text = out["text"].as_str().unwrap();    assert!(text.contains("VERSION:4.0"));    let back = cotton_core::cotton_rules::contacts_io::read_vcf(text).cards;    let asha = back.iter().find(|c| c.full_name == "Asha Menon").expect("Asha exported");    assert_eq!(asha.phones.iter().map(|p| p.label.as_deref()).collect::<Vec<_>>(), vec![Some("Mobile"), Some("Work")], "{text}");    assert_eq!(asha.emails.iter().map(|e| e.label.as_deref()).collect::<Vec<_>>(), vec![Some("Home"), Some("Work")], "{text}");    let bakery = back.iter().find(|c| c.full_name == "Invented Bakery").expect("the bakery exported");    assert!(bakery.organisation, "an organisation goes out as one: {text}");    // On the page: the label, and the kind.    let home = ask(&handle, "contacts.home", json!({ "kind": "organisation" }));    assert_eq!(home["sections"][0]["rows"][0]["words"], "Invented Bakery", "{home}");    assert_eq!(asha.emails.len(), 2, "{text}");    assert_eq!(asha.org.as_deref(), Some("Invented Labs"));    assert_eq!(asha.birthday.map(|b| (b.month, b.day, b.year)), Some((5, 17, Some(1990))));    assert_eq!(asha.groups, vec!["Family".to_string()]);    assert!(asha.photo.is_some(), "the picture goes out with the card");    assert_eq!(asha.note.as_deref(), Some("Met at the invented conference"));    let ravi = back.iter().find(|c| c.full_name == "Ravi Shah").expect("Ravi exported");    let mut ravi_groups = ravi.groups.clone();    ravi_groups.sort();    assert_eq!(ravi_groups, vec!["Badminton".to_string(), "Family".to_string()]);    let v3 = ask(&handle, "contacts.export", json!({ "version": "3.0" }));    assert!(v3["text"].as_str().unwrap().contains("VERSION:3.0"));    // AUDIT D: Share contact (chosen cards, for someone else) carries no notes, no group names, no Cotton id; the    // person's own copy of chosen cards does when it says `private`.    let id = asha.uid.clone().expect("the whole book names each card's id");    let shared = ask(&handle, "contacts.export", json!({ "ids": [id.clone()] }));    let text = shared["text"].as_str().unwrap();    let card = &cotton_core::cotton_rules::contacts_io::read_vcf(text).cards[0];    assert_eq!(card.full_name, "Asha Menon");    assert_eq!((card.note.as_deref(), card.groups.len(), card.uid.as_deref()), (None, 0, None), "{text}");    assert!(!text.contains("invented conference") && !text.contains("Family"), "{text}");    let own = ask(&handle, "contacts.export", json!({ "ids": [id], "private": true }));    assert!(own["text"].as_str().unwrap().contains("invented conference"));}// AUDIT D: a file past what one import takes is refused whole, in one plain line, and nothing of it is written.#[test]fn a_file_past_the_limits_is_refused_in_one_plain_line_and_nothing_is_made() {    let dir = tempfile::tempdir().expect("a dir");    let handle = phone(&dir);    let text = format!("BEGIN:VCARD\r\nVERSION:3.0\r\nFN:Long Note\r\nNOTE:{}\r\nEND:VCARD\r\nBEGIN:VCARD\r\nVERSION:3.0\r\nFN:Fine\r\nEND:VCARD\r\n", "n".repeat(70_000));    let refused = dispatch(&handle, "contacts.import", &json!({ "text": text })).expect_err("refused");    assert_eq!((refused.code.as_str(), refused.message.as_str()), ("too_large", "In this file, \u{201c}Long Note\u{201d} has a note longer than 64 KB. Shorten it and try again."));    assert_eq!(ask(&handle, "records.list", json!({ "table": "person" }))["records"].as_array().map(Vec::len), Some(0));}#[test]fn imports_a_google_csv_and_never_makes_a_second_contact_for_a_card_already_read() {    let dir = tempfile::tempdir().expect("a dir");    let handle = phone(&dir);    let csv = "First Name,Last Name,Labels,E-mail 1 - Label,E-mail 1 - Value,Phone 1 - Label,Phone 1 - Value\nDev,Nair,* myContacts ::: Work,Work,dev@example.org,Mobile,+91 98765 00008\nMeera,Iyer,* myContacts,,,Mobile,+91 98765 00009\n";    let first = ask(&handle, "contacts.import", json!({ "text": csv, "format": "csv" }));    assert_eq!(first["made"], 2, "{first}");    assert_eq!(first["groups"], 1, "{first}");    let again = ask(&handle, "contacts.import", json!({ "text": csv }));    assert_eq!(again["made"], 0, "{again}");    let empty = ask(&handle, "contacts.import", json!({ "text": "BEGIN:VCARD\nVERSION:3.0\nEND:VCARD\n" }));    assert_eq!(empty["read"], 0);    assert!(dispatch(&handle, "contacts.import", &json!({})).is_err(), "no text, no import");}/// RULE (Android, 28 Nov 2026): a file imported before sign-in leaves nothing behind at sign-in: every change it/// made is the person's and goes with the contacts (the card's note on the contact's own state), or is bookkeeping/// the adopt answers by rule (the Imports history line). None is "kept".#[test]fn a_file_imported_signed_out_leaves_nothing_behind_at_sign_in() {    let dir = tempfile::tempdir().expect("a dir");    let handle = phone(&dir);    assert_eq!(ask(&handle, "contacts.import", json!({ "text": vcf() }))["notes"], 1);    let path = handle.client().with_file(|f| Ok(handle.client().layout().replica(f.workspace_id))).unwrap();    let persons = crate::phone::personal_object::persons_rows(&path).unwrap();    let left: Vec<String> = cotton_client::unsent::unsent_changes(&path)        .unwrap()        .into_iter()        .filter(|c| !persons.holds(&c.table, &c.row_id) && !cotton_client::founding::is_founding(&c.table) && !crate::phone::adopt::answered_by_rule(&c.table))        .map(|c| c.table)        .collect();    assert!(left.is_empty(), "left behind at sign-in: {left:?}");}