//! **who(handle)**: the person a way of reaching somebody names (PEOPLE BUILD //! 1, 1b). Every matcher asks this, so the chat list, Senders, mail, calls, //! Days, Privacy, Secrets and shared albums can never disagree about who a //! number is. //! //! The rule: //! - the handle is read by the ONE normaliser //! ([`cotton_rules::handles::normalize_contact_handle_in`]); a value it does //! not read names nobody; //! - only a LIVING person holds a handle: one in the bin or archived names //! nobody (a recycled number an old contact still carries is not theirs to //! answer for), and neither does a handle in the bin; //! - one person holds a handle on `cotton_person_handles` (unique per //! `(workspace, kind, normalised)`); any other contact holding it too keeps //! it on `cotton_shared_handle` (a household landline, an office line). A //! handle more than one living contact holds is [`Who::Shared`]: who it is //! answers every holder, never the first as if certain; //! - a chat contact whose handles name two different people names nobody. //! //! A chat contact's person is DERIVED by the same rule at read time //! ([`contact_person_sql`]): a person who gains a number tomorrow names the //! chats already there, with nothing rewritten. //! //! `shared_handle` is a kit table, laid where the kit is: a copy that does not //! hold it ([`shared_held`] false) holds no shared handle either, so every //! statement here takes `shared` and reads the table only where it is. use rusqlite::types::Value; use cotton_rules::handles::{normalize_contact_handle_in, HandleKind}; use cotton_rules::phone::Region; use crate::driver::Driver; use crate::error::Result; /// The local table a contact's share of somebody else's handle is kept in /// (the kit's `shared_handle`). pub const SHARED_TABLE: &str = "cotton_shared_handle"; /// One holder of a handle. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Holder { pub id: String, pub full_name: String, } /// Who a handle names. #[derive(Debug, Clone, PartialEq, Eq)] pub enum Who { Nobody, One(Holder), /// More than one living contact holds it, by name. Shared(Vec), } impl Who { /// The one person, when there is exactly one. pub fn one(&self) -> Option<&Holder> { match self { Who::One(holder) => Some(holder), _ => None, } } } /// The handle `raw` in the form [`who`] matches, or `None` when the one /// normaliser does not read it (then it names nobody). pub fn who_key(kind: HandleKind, raw: &str, region: Option) -> Option<(&'static str, String)> { normalize_contact_handle_in(kind, raw, region).map(|handle| (kind.as_str(), handle.value)) } /// Whether this copy holds the kit's `shared_handle` (a copy that does not /// holds no shared handle). pub fn shared_held(db: &Driver) -> bool { db.get("SELECT 1 AS one FROM sqlite_master WHERE type = 'table' AND name = ?", &[Value::Text(SHARED_TABLE.to_string())]) .ok() .flatten() .is_some() } /// Every living holder of `(kind, normalised)` in `workspace`, by name. pub fn who(db: &Driver, workspace: &str, kind: &str, normalised: &str) -> Result { let text = |s: &str| Value::Text(s.to_string()); let rows = db.all( &format!( "SELECT p.id AS id, p.full_name AS full_name FROM cotton_people p WHERE p.id IN ({holders}) ORDER BY p.full_name, p.id", holders = holders_sql(shared_held(db), "?1", "?2", "?3"), ), &[text(workspace), text(kind), text(normalised)], )?; let mut holders: Vec = rows .iter() .filter_map(|row| Some(Holder { id: row.text("id")?.to_string(), full_name: row.text("full_name").unwrap_or_default().to_string() })) .collect(); Ok(match holders.len() { 0 => Who::Nobody, 1 => Who::One(holders.remove(0)), _ => Who::Shared(holders), }) } /// The living holders of a handle, as a sub-select of person ids: `ws`, `kind` /// and `value` are column expressions or placeholders of the caller's query, /// never caller data, because they are interpolated. pub fn holders_sql(shared: bool, ws: &str, kind: &str, value: &str) -> String { let own = format!( "SELECT wh.person_id FROM cotton_person_handles wh JOIN cotton_people wp ON wp.id = wh.person_id \ WHERE wh.workspace_id = {ws} AND wh.kind = {kind} AND wh.normalised = {value} AND wh.trashed_at IS NULL AND wp.trashed_at IS NULL AND wp.archived_at IS NULL" ); if !shared { return own; } format!( "{own} \ UNION SELECT ws_.person FROM {SHARED_TABLE} ws_ JOIN cotton_people wp ON wp.id = ws_.person \ WHERE ws_.workspace_id = {ws} AND ws_.kind = {kind} AND ws_.normalised = {value} AND ws_.deleted_at IS NULL AND wp.trashed_at IS NULL AND wp.archived_at IS NULL" ) } /// The ONE person a handle names, as an SQL expression; NULL when nobody, or /// when it is shared. pub fn person_of_handle_sql(shared: bool, ws: &str, kind: &str, value: &str) -> String { format!("(SELECT CASE WHEN COUNT(*) = 1 THEN MIN(who_h.person_id) END FROM ({holders}) who_h)", holders = holders_sql(shared, ws, kind, value)) } /// Whether more than one living contact holds a handle, as an SQL expression. pub fn handle_shared_sql(shared: bool, ws: &str, kind: &str, value: &str) -> String { if !shared { return "0".to_string(); } format!("((SELECT COUNT(*) FROM ({holders}) who_s) > 1)", holders = holders_sql(shared, ws, kind, value)) } /// Every holder's name of a SHARED handle, joined by `joiner` in name order, /// as an SQL expression; NULL unless it is shared. `joiner` is an SQL string /// literal the caller gives (`' & '`). pub fn shared_names_sql(shared: bool, ws: &str, kind: &str, value: &str, joiner: &str) -> String { if !shared { return "NULL".to_string(); } format!( "(SELECT CASE WHEN COUNT(*) > 1 THEN group_concat(who_n.full_name, {joiner}) END FROM (SELECT np.full_name AS full_name FROM cotton_people np WHERE np.id IN ({holders}) ORDER BY np.full_name, np.id) who_n)", holders = holders_sql(shared, ws, kind, value), ) } /// A chat contact's person, DERIVED (`c` is the caller's alias for a /// `cotton_msg_contacts` row): the one person its number names; nobody when /// its number is shared (whatever was linked before); else the one person its /// handles name (two different people, or a shared handle: nobody); else the /// person it was linked to by hand, while that person is living. NULL when /// nobody. pub fn contact_person_sql(shared: bool, c: &str) -> String { let (ws, phone) = (format!("{c}.workspace_id"), format!("{c}.phone_e164")); let shared_leg = if shared { format!( "UNION ALL SELECT ws_.person FROM cotton_msg_contact_handles wc JOIN {SHARED_TABLE} ws_ ON ws_.workspace_id = wc.workspace_id AND ws_.kind = wc.kind AND ws_.normalised = wc.value JOIN cotton_people wp ON wp.id = ws_.person \ WHERE wc.contact_id = {c}.id AND ws_.deleted_at IS NULL AND wp.trashed_at IS NULL AND wp.archived_at IS NULL" ) } else { String::new() }; format!( "(CASE WHEN {shared} THEN NULL ELSE COALESCE({by_phone}, \ (SELECT CASE WHEN COUNT(DISTINCT who_c.pid) = 1 THEN MIN(who_c.pid) END FROM (\ SELECT wh.person_id AS pid FROM cotton_msg_contact_handles wc JOIN cotton_person_handles wh ON wh.workspace_id = wc.workspace_id AND wh.kind = wc.kind AND wh.normalised = wc.value JOIN cotton_people wp ON wp.id = wh.person_id \ WHERE wc.contact_id = {c}.id AND wh.trashed_at IS NULL AND wp.trashed_at IS NULL AND wp.archived_at IS NULL \ {shared_leg}) who_c), \ (SELECT lp.id FROM cotton_people lp WHERE lp.id = {c}.person_id AND lp.trashed_at IS NULL AND lp.archived_at IS NULL)) END)", shared = handle_shared_sql(shared, &ws, "'phone'", &phone), by_phone = person_of_handle_sql(shared, &ws, "'phone'", &phone), ) } /// The names of everyone a chat contact's number is shared by (`' & '` /// between them), as an SQL expression over the caller's alias `c`; NULL /// unless it is shared. What a call or a chat from a household landline is /// called instead of one of them. pub fn contact_shared_names_sql(shared: bool, c: &str) -> String { shared_names_sql(shared, &format!("{c}.workspace_id"), "'phone'", &format!("{c}.phone_e164"), "' & '") } #[cfg(test)] #[path = "who_tests.rs"] mod tests;