Cotton code
161 lines · 8.3 KB · RustRaw
//! **Where each contact came from** (`person_source`, PEOPLE BUILD 1; owner, 27 Nov 2026): one row per original//! record a contact was made from or attached to — a card in the phone's contacts (per device), a WhatsApp id, a//! Cotton account, a mail address, a person in Apple Photos, a Health import, a contacts file, or typed.//!//! Every import and sync asks [`person_of`] FIRST, so a record already seen lands on its contact even after the//! owner renamed it or merged it into another (a merge moves `person` like every other link), and a re-import never//! makes a twin. A row's id is derived from what the source is (kind, device, its id there), so two devices writing//! the same source write one row.use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value};use crate::mcp::dispatch::Ctx;use crate::mcp::handlers::common::{insert_row, now_iso};use crate::mcp::protocol::ToolFailure;/// The local table the `person_source` kit table is kept in.pub const TABLE: &str = "cotton_person_source";/// One original record.#[derive(Debug, Clone, PartialEq, Eq)]pub struct Source {    /// `address_book`, `whatsapp`, `cotton`, `mail`, `apple_photos`, `health`, `vcard` or `typed`.    pub kind: &'static str,    /// The device the id belongs to, where an id is only that device's (an address-book card); empty otherwise.    pub device: String,    /// Its id there.    pub source_id: String,    /// The name as that source gave it.    pub name: Option<String>,    /// For a card: what the card says (its name folded and its whole set of numbers and addresses, hashed), the same    /// on every device that holds the card, so a second phone's copy of it lands on the same contact.    pub card_key: Option<String>,}impl Source {    /// A card in this device's contacts.    pub fn address_book(device: &str, card: &str, name: &str) -> Source {        Source { kind: "address_book", device: device.to_string(), source_id: card.to_string(), name: Some(name.to_string()).filter(|n| !n.trim().is_empty()), card_key: None }    }    /// With what the card says ([`card_key`]).    pub fn keyed(mut self, card_key: String) -> Source {        self.card_key = Some(card_key);        self    }    /// The row id every device derives for this source.    pub fn id(&self, namespace: &str) -> String {        cotton_core::cotton_rules::ids::person_source_id(namespace, self.kind, &self.device, &self.source_id)    }}fn failed(error: impl std::fmt::Display) -> ToolFailure {    ToolFailure::new(error.to_string())}/// The writer's own device id (`_meta.device_id`): what an address-book card id belongs to.pub fn this_device(ctx: &Ctx<'_>) -> Result<String, ToolFailure> {    Ok(ctx        .db()        .get("SELECT device_id FROM _meta", &[])        .map_err(failed)?        .and_then(|row| row.text("device_id").map(str::to_string))        .unwrap_or_default())}/// The contact this source already belongs to, while that contact is not in the bin.pub fn person_of(ctx: &Ctx<'_>, source: &Source) -> Result<Option<String>, ToolFailure> {    let row = ctx        .db()        .get(            &format!("SELECT s.person AS person FROM {TABLE} s JOIN cotton_people p ON p.id = s.person WHERE s.workspace_id = ? AND s.kind = ? AND coalesce(s.device, '') = ? AND s.source_id = ? AND s.deleted_at IS NULL AND p.trashed_at IS NULL LIMIT 1"),            &[                SqlValue::Text(ctx.workspace_id.to_string()),                SqlValue::Text(source.kind.to_string()),                SqlValue::Text(source.device.clone()),                SqlValue::Text(source.source_id.clone()),            ],        )        .map_err(failed)?;    Ok(row.and_then(|row| row.text("person").map(str::to_string)))}/// Keep that `person` came from `source`. Written once: a source already kept stays where it is.pub fn record(ctx: &mut Ctx<'_>, person: &str, source: &Source) -> Result<(), ToolFailure> {    let id = source.id(&ctx.file.namespace().to_string());    let held = ctx.db().get(&format!("SELECT 1 AS one FROM {TABLE} WHERE id = ?"), &[SqlValue::Text(id.clone())]).map_err(failed)?;    if held.is_some() {        return Ok(());    }    let now = now_iso(ctx);    let mut patch = Map::new();    patch.insert("workspace_id".into(), Value::from(ctx.workspace_id.to_string()));    patch.insert("person".into(), Value::from(person));    patch.insert("kind".into(), Value::from(source.kind));    patch.insert("device".into(), Value::from(source.device.clone()));    patch.insert("source_id".into(), Value::from(source.source_id.clone()));    patch.insert("name".into(), source.name.clone().map_or(Value::Null, Value::from));    patch.insert("card_key".into(), source.card_key.clone().map_or(Value::Null, Value::from));    patch.insert("first_seen".into(), Value::from(now.clone()));    patch.insert("created_at".into(), Value::from(now.clone()));    patch.insert("updated_at".into(), Value::from(now));    insert_row(ctx, TABLE, &id, patch)}/// What a card says, the same on every device holding it: its name folded (case and spacing are not identity) and/// its whole set of numbers and addresses, each read with no region guessed (so a number written without its country/// code is kept as written), hashed under the database's namespace. `nth` tells apart two cards one device holds/// that say exactly the same thing (two "Uncle" cards with no number are two people).pub fn card_key(namespace: &str, name: &str, handles: &[(&'static str, String)], nth: usize) -> String {    let folded = cotton_core::cotton_rules::js::collapse_whitespace_and_trim(name).to_lowercase();    let mut said: Vec<String> = handles.iter().map(|(kind, value)| format!("{kind}:{value}")).collect();    said.sort();    said.dedup();    let nth = nth.to_string();    let mut parts: Vec<&str> = vec![namespace, &folded, &nth];    parts.extend(said.iter().map(String::as_str));    cotton_core::cotton_rules::ids::derived_id("person_card", &parts)}/// The living contact a card saying exactly `card_key` was brought in as, on any device: a second phone's copy of a/// card the first phone brought in.pub fn person_of_card(ctx: &Ctx<'_>, card_key: &str) -> Result<Option<String>, ToolFailure> {    let row = ctx        .db()        .get(            &format!("SELECT s.person AS person FROM {TABLE} s JOIN cotton_people p ON p.id = s.person WHERE s.workspace_id = ? AND s.kind = 'address_book' AND s.card_key = ? AND s.deleted_at IS NULL AND p.trashed_at IS NULL AND p.archived_at IS NULL ORDER BY s.created_at, s.id LIMIT 1"),            &[SqlValue::Text(ctx.workspace_id.to_string()), SqlValue::Text(card_key.to_string())],        )        .map_err(failed)?;    Ok(row.and_then(|row| row.text("person").map(str::to_string)))}/// Keep that `person` holds a handle another contact holds too (`shared_handle`): a household landline, an office/// line. Its id is derived from the person and the handle, so two devices writing it write one row; written once.////// A copy that does not hold the table yet (an object the kit keep has not reached) keeps no share: the number stays/// with the contact holding it, as before shares were kept, and the import goes on.pub fn share(ctx: &mut Ctx<'_>, person: &str, kind: &str, value: &str, normalised: &str, source: Option<&str>) -> Result<(), ToolFailure> {    let table = cotton_store::protocol::who::SHARED_TABLE;    if !cotton_store::protocol::who::shared_held(ctx.db()) {        return Ok(());    }    let id = cotton_core::cotton_rules::ids::derived_id("shared_handle", &[&ctx.file.namespace().to_string(), person, kind, normalised]);    let held = ctx.db().get(&format!("SELECT 1 AS one FROM {table} WHERE id = ?"), &[SqlValue::Text(id.clone())]).map_err(failed)?;    if held.is_some() {        return Ok(());    }    let now = now_iso(ctx);    let mut patch = Map::new();    patch.insert("workspace_id".into(), Value::from(ctx.workspace_id.to_string()));    patch.insert("person".into(), Value::from(person));    patch.insert("kind".into(), Value::from(kind));    patch.insert("value".into(), Value::from(value.trim()));    patch.insert("normalised".into(), Value::from(normalised));    patch.insert("source".into(), source.map_or(Value::Null, Value::from));    patch.insert("created_at".into(), Value::from(now.clone()));    patch.insert("updated_at".into(), Value::from(now));    insert_row(ctx, table, &id, patch)}