//! Contacts in and out of files (CONTACTS, 28 Nov 2026): `contacts.import` and `contacts.export`. //! //! ```text //! contacts.import {text, format?: "vcf" | "csv"} (format read from the text when absent) //! → { read, made, already, photos, groups, skipped, said } //! contacts.export {ids?: [person id], version?: "4.0" | "3.0", private?: bool} //! (notes, group names and the Cotton id go out with the whole book, and with chosen cards only when `private`) //! → { filename: "Contacts.vcf", mime: "text/vcard", count, text } //! ``` //! //! THE SAME DOOR AS THE ADDRESS BOOK. A card read from a `.vcf` or a Google CSV (`cotton_rules::contacts_io`) goes in //! exactly as a card from the phone's address book does: through `sync_device_contacts`, which holds the handle rules //! (the number and email normaliser, a card already seen landing on its contact, and never two people merged by an //! import; a pair that may be one person is a Same person? suggestion). Each card's source id is `file:`, or //! `file:` of its name, numbers and emails when it has no UID, so importing the same file again changes nothing. //! //! After the cards: an embedded photo becomes the new contact's picture (`capture.avatar`, the address book's own //! path), and each group the file names is a People group (`groups.create`, or `groups.update` adding to one of the //! same name), made by him. A photo given as a link is never fetched. //! //! Export writes every contact (or those asked) with its numbers, emails, organisation, title, city, birthday, groups //! and picture, as vCard 4.0 (the default) or 3.0. The shell saves the text and offers the share sheet. use std::collections::BTreeMap; use base64::Engine as _; use serde_json::{json, Value}; use sha2::{Digest, Sha256}; use cotton_core::cotton_rules::contacts_io::{self, Birthday, Card, Labelled, Photo, Version}; use crate::handle::CottonHandle; use crate::methods::{dispatch, MethodError}; pub const METHODS: [&str; 2] = ["contacts.export", "contacts.import"]; /// People's table, as `records.*` and `groups.*` name it. const PERSON: &str = "person"; /// A picture larger than this is left out of an import (an address-book picture is a few hundred KB at most). const PHOTO_MAX_BYTES: usize = 5 * 1024 * 1024; /// A file larger than this is refused before it is read (about 50,000 cards without pictures). const TEXT_MAX_BYTES: usize = contacts_io::FILE_MAX_BYTES; pub fn call(handle: &CottonHandle, method: &str, request: &Value) -> Result { match method { "contacts.import" => import(handle, request), "contacts.export" => export(handle, request), other => Err(MethodError::new("unknown_method", format!("{other} is not a contacts file method"))), } } fn bad(message: &str) -> MethodError { MethodError::new("bad_request", message) } /// `vcf` or `csv`: as asked, else read from the text (`BEGIN:VCARD` anywhere near the top is a vCard). fn format_of(request: &Value, text: &str) -> Result<&'static str, MethodError> { match request.get("format").and_then(Value::as_str) { Some("vcf" | "vcard") => Ok("vcf"), Some("csv" | "google_csv") => Ok("csv"), Some(_) => Err(bad("`format` is vcf or csv")), None => Ok(if text.chars().take(4096).collect::().to_ascii_uppercase().contains("BEGIN:VCARD") { "vcf" } else { "csv" }), } } /// The card's source id: its UID, else a hash of what makes it this card. pub fn source_id(card: &Card) -> String { if let Some(uid) = card.uid.as_ref().filter(|u| !u.trim().is_empty()) { return format!("file:{}", uid.trim()); } let mut hash = Sha256::new(); hash.update(card.full_name.as_bytes()); for p in &card.phones { hash.update(b"\x1fp"); hash.update(p.value.as_bytes()); } for e in &card.emails { hash.update(b"\x1fe"); hash.update(e.value.as_bytes()); } let digest = hash.finalize(); format!("file:{}", digest.iter().take(12).map(|b| format!("{b:02x}")).collect::()) } /// The card as the address book's import takes it (`sync_device_contacts`' `contacts[]`). pub fn device_card(card: &Card) -> Value { let mut out = json!({ "deviceContactId": source_id(card), "fullName": card.full_name, "phones": card.phones.iter().map(|p| p.value.clone()).collect::>(), "emails": card.emails.iter().map(|e| e.value.clone()).collect::>(), }); if let Some(org) = &card.org { out["org"] = json!(org); } if let Some(role) = &card.role_title { out["roleTitle"] = json!(role); } if let Some(city) = &card.city { out["city"] = json!(city); } if let Some(b) = card.birthday { out["birthday"] = match b.year { Some(year) => json!({ "month": b.month, "day": b.day, "year": year }), None => json!({ "month": b.month, "day": b.day }), }; } out } fn import(handle: &CottonHandle, request: &Value) -> Result { let text = request.get("text").and_then(Value::as_str).ok_or_else(|| bad("`text` is the file's text"))?; if text.len() > TEXT_MAX_BYTES { return Err(MethodError::new("too_large", contacts_io::file_too_large())); } let read = match format_of(request, text)? { "vcf" => contacts_io::read_vcf(text), _ => contacts_io::read_google_csv(text), }; // AUDIT D: a file past what one import takes (cards, groups, a field's length) is refused whole, in one plain line. if let Some(line) = contacts_io::over_limits(&read) { return Err(MethodError::new("too_large", line)); } // One card per source id: a file that holds the same card twice reads it once. let mut seen = std::collections::BTreeSet::new(); let cards: Vec = read.cards.into_iter().filter(|c| seen.insert(source_id(c))).collect(); if cards.is_empty() { return Ok(json!({ "read": 0, "made": 0, "already": 0, "photos": 0, "groups": 0, "skipped": read.skipped, "said": "There were no contacts in this file." })); } let written = dispatch(handle, "write", &json!({ "tool": "sync_device_contacts", "args": { "contacts": cards.iter().map(device_card).collect::>() } }))?; let answer = written.get("answer").unwrap_or(&written); let made_ids: BTreeMap = answer["people"] .as_array() .into_iter() .flatten() .filter_map(|p| Some((p["deviceContactId"].as_str()?.to_string(), p["id"].as_str()?.to_string()))) .collect(); let made = answer["inserted"].as_u64().unwrap_or(made_ids.len() as u64); let already = answer["skipped"].as_u64().unwrap_or(0); // Pictures and groups, for the contacts this import made (one already there keeps its own). let mut photos = 0; let mut notes = 0; let mut grouped: BTreeMap> = BTreeMap::new(); for card in &cards { let Some(id) = made_ids.get(&source_id(card)) else { continue }; if let Some(photo) = &card.photo { if put_photo(handle, id, photo).is_ok() { photos += 1; } } if let Some(note) = &card.note { if put_note(handle, id, note).is_ok() { notes += 1; } } for group in &card.groups { grouped.entry(group.clone()).or_default().push(id.clone()); } } let groups = file_groups(handle, &grouped)?; // Labels on the numbers and addresses, and organisations as such (CONTACT KINDS), for the contacts made. let made_cards: Vec<(String, &Card)> = cards.iter().filter_map(|c| made_ids.get(&source_id(c)).map(|id| (id.clone(), c))).collect(); if !made_cards.is_empty() { super::cotton_chat::write(&handle.client(), "contacts.import", |ctx| { for (id, card) in &made_cards { let labelled = |list: &[Labelled]| list.iter().map(|l| (l.value.clone(), l.label.as_deref().and_then(super::contacts_labels::label_word))).collect::>(); super::contacts_labels::label_held(ctx, id, &labelled(&card.phones), &labelled(&card.emails))?; if card.organisation { let mut state = serde_json::Map::new(); state.insert("kind".into(), json!("organisation")); // A copy without Contacts' tables yet keeps the contact as a person. let _ = super::contacts_app::put_state(ctx, id, state); } } cotton_tools::mcp::dispatch::Ctx::commit(ctx).map_err(|e| e.to_string())?; Ok(json!({})) })?; } let said = match (made, already) { (0, _) => "Every contact in this file is already here.".to_string(), (made, 0) => format!("Added {made} {}.", if made == 1 { "contact" } else { "contacts" }), (made, already) => format!("Added {made} {}; {already} were already here.", if made == 1 { "contact" } else { "contacts" }), }; Ok(json!({ "read": cards.len(), "made": made, "already": already, "photos": photos, "notes": notes, "groups": groups, "skipped": read.skipped, "said": said })) } /// The picture through the address book's own path: the bytes to a file, then `capture.avatar`. fn put_photo(handle: &CottonHandle, person: &str, photo: &Photo) -> Result<(), MethodError> { let bytes = base64::engine::general_purpose::STANDARD .decode(photo.base64.trim_end_matches('=')) .or_else(|_| base64::engine::general_purpose::STANDARD_NO_PAD.decode(photo.base64.trim_end_matches('='))) .map_err(|_| bad("a picture in the file is not base64"))?; if bytes.is_empty() || bytes.len() > PHOTO_MAX_BYTES { return Err(bad("a picture in the file is empty or too large")); } let ext = match photo.mime.as_str() { "image/png" => "png", "image/gif" => "gif", _ => "jpg", }; // Staged in the app's own data folder under a random name, never the system's temp folder (AUDIT E: on Android // Rust's temp folder can be the shared /data/local/tmp, and the name was guessable). let dir = handle.client().layout().root().join("tmp"); std::fs::create_dir_all(&dir).map_err(|e| MethodError::new("write_refused", format!("the picture could not be staged: {e}")))?; let path = dir.join(format!("contact-{:032x}.{ext}", rand::random::())); // not a copy: a vCard picture staged in the temp folder for capture.avatar. std::fs::write(&path, &bytes).map_err(|e| MethodError::new("write_refused", format!("the picture could not be staged: {e}")))?; let done = dispatch(handle, "capture.avatar", &json!({ "personId": person, "path": path.to_string_lossy(), "mime": photo.mime, "filename": format!("contact.{ext}") })); // not a copy: the staged picture, taken in. let _ = std::fs::remove_file(&path); done.map(|_| ()) } /// A card's note, kept on the contact's own state (`person_state.note`): a Contacts table, so it goes up with the /// contact at sign-in. (It was a `cotton_person_notes` row, whose table no tool draws since TABLE DROP 1: a note /// imported signed out stayed behind at sign-in, "kept", Android 28 Nov 2026.) A note already there is kept, the /// card's added after it. fn put_note(handle: &CottonHandle, person: &str, body: &str) -> Result<(), MethodError> { super::cotton_chat::write(&handle.client(), "contacts.import", |ctx| { let had = super::contacts_app::state_of(ctx, person)?.and_then(|s| s.get("note").and_then(Value::as_str).map(str::to_string)).filter(|n| !n.trim().is_empty()); if had.as_deref().is_some_and(|n| n.contains(body)) { return Ok(json!({})); } let mut patch = serde_json::Map::new(); patch.insert("note".into(), json!(had.map_or_else(|| body.to_string(), |had| format!("{had}\n\n{body}")))); super::contacts_app::put_state(ctx, person, patch)?; cotton_tools::mcp::dispatch::Ctx::commit(ctx).map_err(|e| e.to_string())?; Ok(json!({})) }) .map(|_| ()) } /// Each group named in the file, as a People group: added to one of the same name, or made. Answers how many. fn file_groups(handle: &CottonHandle, grouped: &BTreeMap>) -> Result { if grouped.is_empty() { return Ok(0); } let listed = dispatch(handle, "groups.list", &json!({ "table": PERSON }))?; let existing: BTreeMap = listed["groups"] .as_array() .into_iter() .flatten() .filter_map(|g| Some((g["name"].as_str()?.to_lowercase(), g["id"].as_str()?.to_string()))) .collect(); for (name, people) in grouped { match existing.get(&name.to_lowercase()) { Some(id) => dispatch(handle, "groups.update", &json!({ "id": id, "add": people }))?, None => dispatch(handle, "groups.create", &json!({ "table": PERSON, "name": name, "records": people }))?, }; } Ok(grouped.len()) } // ── export ──────────────────────────────────────────────────────────────── fn export(handle: &CottonHandle, request: &Value) -> Result { let version = match request.get("version").and_then(Value::as_str) { None | Some("4.0" | "4") => Version::V4, Some("3.0" | "3") => Version::V3, Some(_) => return Err(bad("`version` is 4.0 or 3.0")), }; let asked: Option> = request.get("ids").and_then(Value::as_array).map(|ids| ids.iter().filter_map(|v| v.as_str().map(str::to_string)).collect()); // AUDIT D: his notes about a person, his group names and the card's id inside Cotton are his own. The whole book // (his own copy) carries them; chosen cards (Share contact hands one to someone else) carry them only when the // request says `private: true`. let private = request.get("private").and_then(Value::as_bool).unwrap_or(asked.is_none()); let people = match &asked { Some(ids) if ids.is_empty() => Vec::new(), Some(ids) => list(handle, json!({ "table": PERSON, "ids": ids }))?, None => list_all(handle)?, }; // Groups: every People group's members, read once per group. let mut groups_of: BTreeMap> = BTreeMap::new(); let listed = dispatch(handle, "groups.list", &json!({ "table": PERSON }))?; for group in listed["groups"].as_array().into_iter().flatten() { let (Some(id), Some(name)) = (group["id"].as_str(), group["name"].as_str()) else { continue }; for member in list(handle, json!({ "table": PERSON, "where": { "group": id }, "limit": 500 }))? { if let Some(person) = member["id"].as_str() { groups_of.entry(person.to_string()).or_default().push(name.to_string()); } } } // Notes: every person's, oldest first, joined as one card's NOTE. Read from their store table, as the import // writes them: the `person_note` table definition is retired (TABLE DROP 1), the notes are not. let mut notes_of: BTreeMap> = BTreeMap::new(); let notes = handle .client() .read_rows("contacts.export", &mut |ctx| { let held = ctx.db().get("SELECT 1 AS one FROM sqlite_master WHERE type = 'table' AND name = 'cotton_person_notes'", &[]).map_err(|e| e.to_string())?.is_some(); if !held { return Ok(json!([])); } // A copy holds one workspace's notes; a binned one stays out where the table can bin. let binned = ctx.db().get("SELECT 1 AS one FROM pragma_table_info('cotton_person_notes') WHERE name = 'trashed_at'", &[]).map_err(|e| e.to_string())?.is_some(); let live = if binned { "WHERE trashed_at IS NULL" } else { "" }; let found = super::cotton_chat::rows(ctx, &format!("SELECT person_id, body, noted_at FROM cotton_person_notes {live} ORDER BY noted_at, id"), &[])?; Ok(Value::from(found.into_iter().map(Value::Object).collect::>())) }) .map_err(|why| MethodError::new("unreadable", why))?; // The notes kept on each contact's state (what an import writes now), after any older ones. let kept = super::cotton_chat::read(&handle.client(), "contacts.export", |ctx| { if !super::contacts_app::held(ctx, super::contacts_app::STATE) { return Ok(json!([])); } let has_note = ctx.db().get(&format!("SELECT 1 AS one FROM pragma_table_info('{}') WHERE name = 'note'", super::contacts_app::STATE), &[]).map_err(|e| e.to_string())?.is_some(); if !has_note { return Ok(json!([])); } let found = super::cotton_chat::rows( ctx, &format!("SELECT person AS person_id, note AS body, coalesce(updated_at, '') AS noted_at FROM {} WHERE workspace_id = ? AND deleted_at IS NULL AND coalesce(note, '') <> ''", super::contacts_app::STATE), &[super::cotton_chat::ws(ctx)], )?; Ok(Value::from(found.into_iter().map(Value::Object).collect::>())) })?; let notes = Value::from(notes.as_array().cloned().unwrap_or_default().into_iter().chain(kept.as_array().cloned().unwrap_or_default()).collect::>()); for note in notes.as_array().into_iter().flatten() { if let (Some(person), Some(body)) = (note["person_id"].as_str(), note["body"].as_str()) { notes_of.entry(person.to_string()).or_default().push((note["noted_at"].as_str().unwrap_or_default().to_string(), body.to_string())); } } let (reach_of, kind_of) = reach_and_kinds(handle)?; let cards: Vec = people .iter() .filter(|p| p["data"]["trashed_at"].is_null()) .map(|p| { let id = p["id"].as_str().unwrap_or_default(); let mut card = card_of(&p["data"]); card.uid = private.then(|| id.to_string()); if let Some(reach) = reach_of.get(id) { card.phones = reach.iter().filter(|(k, _, _)| k == "phone").map(|(_, value, label)| Labelled { value: value.clone(), label: label.clone() }).collect(); card.emails = reach.iter().filter(|(k, _, _)| k == "email").map(|(_, value, label)| Labelled { value: value.clone(), label: label.clone() }).collect(); } card.organisation = kind_of.get(id).is_some_and(|k| k == "organisation"); card.groups = if private { groups_of.get(id).cloned().unwrap_or_default() } else { Vec::new() }; card.note = notes_of.get(id).filter(|_| private).map(|notes| { let mut notes = notes.clone(); notes.sort(); notes.into_iter().map(|(_, body)| body).collect::>().join("\n\n") }); card.photo = p["data"]["avatar_key"].as_str().and_then(|key| photo_of(handle, key)); card }) .filter(|c| !c.full_name.trim().is_empty()) .collect(); Ok(json!({ "filename": "Contacts.vcf", "mime": "text/vcard", "count": cards.len(), "text": contacts_io::write_vcf(&cards, version) })) } /// Each contact's own numbers and addresses with their labels, in his order, and each contact's kind. type Reach = std::collections::HashMap)>>; fn reach_and_kinds(handle: &CottonHandle) -> Result<(Reach, std::collections::HashMap), MethodError> { let answer = super::cotton_chat::read(&handle.client(), "contacts.export", |ctx| { let labels = super::contacts_labels::all_labels(ctx)?; let handles = super::cotton_chat::rows(ctx, "SELECT id, person_id, kind, value FROM cotton_person_handles WHERE workspace_id = ?1 AND trashed_at IS NULL AND kind IN ('phone', 'email') ORDER BY person_id, position, rowid", &[super::cotton_chat::ws(ctx)])?; let mut reach = serde_json::Map::new(); for h in handles { let (Some(id), Some(person), Some(kind), Some(value)) = (h.get("id").and_then(Value::as_str), h.get("person_id").and_then(Value::as_str), h.get("kind").and_then(Value::as_str), h.get("value").and_then(Value::as_str)) else { continue }; let list = reach.entry(person.to_string()).or_insert_with(|| json!([])); list.as_array_mut().expect("a list").push(json!([kind, value, labels.get(id)])); } let mut kinds = serde_json::Map::new(); if super::contacts_app::held(ctx, super::contacts_app::STATE) { for s in super::cotton_chat::rows(ctx, &format!("SELECT person, kind FROM {} WHERE workspace_id = ?1 AND kind IS NOT NULL", super::contacts_app::STATE), &[super::cotton_chat::ws(ctx)])? { if let (Some(p), Some(k)) = (s.get("person").and_then(Value::as_str), s.get("kind").and_then(Value::as_str)) { kinds.insert(p.to_string(), json!(k)); } } } Ok(json!({ "reach": reach, "kinds": kinds })) })?; let mut reach = Reach::new(); for (person, list) in answer["reach"].as_object().into_iter().flatten() { let items = list.as_array().into_iter().flatten().filter_map(|e| Some((e[0].as_str()?.to_string(), e[1].as_str()?.to_string(), e[2].as_str().map(str::to_string)))).collect(); reach.insert(person.clone(), items); } let kinds = answer["kinds"].as_object().into_iter().flatten().filter_map(|(p, k)| Some((p.clone(), k.as_str()?.to_string()))).collect(); Ok((reach, kinds)) } fn list(handle: &CottonHandle, request: Value) -> Result, MethodError> { let listed = dispatch(handle, "records.list", &request)?; Ok(listed["records"].as_array().cloned().unwrap_or_default()) } fn list_all(handle: &CottonHandle) -> Result, MethodError> { let mut out = Vec::new(); let mut page = 0u64; loop { let listed = dispatch(handle, "records.list", &json!({ "table": PERSON, "limit": 500, "page": page, "total": false }))?; let got = listed["records"].as_array().cloned().unwrap_or_default(); let count = got.len(); out.extend(got); match listed["next_page"].as_u64() { Some(next) if count > 0 && next > page => page = next, _ => break, } } Ok(out) } /// A list column, whether it arrives as a list or as its JSON text. fn strings(value: &Value) -> Vec { match value { Value::Array(items) => items.iter().filter_map(|v| v.as_str().map(str::to_string).or_else(|| v.get("value").and_then(Value::as_str).map(str::to_string))).collect(), Value::String(text) => serde_json::from_str::(text).ok().filter(Value::is_array).map(|v| strings(&v)).unwrap_or_else(|| text.split(',').map(|s| s.trim().to_string()).filter(|s| !s.is_empty()).collect()), _ => Vec::new(), } } fn text(data: &Value, key: &str) -> Option { data.get(key).and_then(Value::as_str).map(str::trim).filter(|s| !s.is_empty()).map(str::to_string) } /// A `person` row's data as a card (no picture, groups or uid: the caller adds them). pub fn card_of(data: &Value) -> Card { let number = |key: &str| data.get(key).and_then(|v| v.as_i64().or_else(|| v.as_f64().map(|f| f as i64)).or_else(|| v.as_str().and_then(|s| s.parse().ok()))); let birthday = match (number("birth_month"), number("birth_day")) { (Some(month), Some(day)) if (1..=12).contains(&month) && (1..=31).contains(&day) => Some(Birthday { month: month as u32, day: day as u32, year: number("birth_year").map(|y| y as i32) }), _ => None, }; let organisation = data.get("kind").and_then(Value::as_str) == Some("organisation"); Card { uid: None, full_name: text(data, "full_name").unwrap_or_default(), organisation, phones: strings(data.get("phones").unwrap_or(&Value::Null)).into_iter().map(|value| Labelled { value, label: None }).collect(), emails: strings(data.get("emails").unwrap_or(&Value::Null)).into_iter().map(|value| Labelled { value, label: None }).collect(), org: text(data, "org"), role_title: text(data, "role_title"), city: text(data, "city"), birthday, note: None, photo: None, groups: Vec::new(), } } /// A contact's picture, when its bytes are on this phone (the original, else the largest held). fn photo_of(handle: &CottonHandle, key: &str) -> Option { let found = dispatch(handle, "read.mediaPath", &json!({ "key": key, "tier": "original" })).ok()?; let path = found["path"].as_str()?; let bytes = std::fs::read(path).ok().filter(|b| !b.is_empty() && b.len() <= PHOTO_MAX_BYTES)?; let mime = if bytes.starts_with(&[0x89, b'P', b'N', b'G']) { "image/png" } else if bytes.starts_with(b"GIF8") { "image/gif" } else { "image/jpeg" }; Some(Photo { mime: mime.to_string(), base64: base64::engine::general_purpose::STANDARD.encode(bytes) }) } #[cfg(test)] #[path = "contacts_io_tests.rs"] pub(crate) mod tests;