//! A chat moved into a shared database: its participants must be admitted //! members of the destination. People records alone confer no membership; the //! owner is exempt. use cotton_core::messages::{ members::{outsiders, ChatMember}, resolve_contact::{ handle_key, normalize_contact_handle, people_by_handle, ContactDriver, ContactError, ContactHandle, ContactHandleKind, ContactRow, MatchedPerson, PersonHandleRow, }, }; use cotton_store::{member_person, Driver, Result, StoreError}; use rusqlite::types::Value as Sql; use std::collections::{BTreeMap, BTreeSet}; fn text(s: &str) -> Sql { Sql::Text(s.into()) } pub fn people(db: &Driver, database: &str) -> Result> { let mut ids = BTreeSet::new(); for row in db.all( "SELECT DISTINCT person_key FROM cotton_admissions WHERE workspace_id=?", &[text(database)], )? { if let Some(key) = row.text("person_key") { if let Some(person) = member_person::bound_person(db, database, key)? { ids.insert(person.person_id); } } } people_by_handle(&Admitted { db, ids }, database).map_err(|e| StoreError::refused(e.0)) } /// Check the entire history's participants, including departed seats. A /// signed owner act may publish their older messages, too. pub fn refusal( source: &Driver, source_id: &str, destination: &Driver, destination_id: &str, thread: &str, ) -> Result> { let mut chat = chat(source, source_id, thread)? .ok_or_else(|| StoreError::refused("That chat is not here."))?; let seats=source.all("SELECT contact_id,display_name,is_self FROM cotton_msg_thread_participants WHERE workspace_id=? AND thread_id=? ORDER BY created_at,id",&[text(source_id),text(thread)])?; if seats.is_empty() && chat.members.is_empty() { chat.members .push(ChatMember { name: "Unknown participant".into(), handles: Vec::new(), }); } if !seats.is_empty() { chat.members.clear(); for seat in seats { if seat.int("is_self") == Some(1) { continue; } chat.members.push(member( source, seat.text("contact_id"), seat.text("display_name").map(str::to_owned), )?); } } let missing = outsiders(&chat.members, &people(destination, destination_id)?); if missing.is_empty() { return Ok(None); } let name = destination .get( "SELECT name FROM cotton_workspaces WHERE id=?", &[text(destination_id)], )? .and_then(|r| r.text("name").map(str::to_owned)) .unwrap_or_else(|| "that database".into()); Ok(Some(format!( "This chat cannot be moved into {name}: {} are not admitted members. Admit them first.", missing.join(", ") ))) } /// A supporting contact belongs to the destination's admitted Person, not a /// private Person id from the source directory. Conflicting handles refuse. pub fn person_for_contact( source: &Driver, destination: &Driver, database: &str, contact: &str, ) -> Result> { let member = member(source, Some(contact), None)?; let people = people(destination, database)?; let matched: BTreeMap = member .handles .iter() .filter_map(|(kind, value)| { let handle = ContactHandleKind::parse(kind).and_then(|k| normalize_contact_handle(k, value))?; let person = people.get(&handle_key(&handle))?; Some((person.id.clone(), person.clone())) }) .collect(); if matched.len() > 1 { return Err(StoreError::refused("This contact's handles name different admitted people. Resolve who the contact is before moving it.")); } Ok(matched.into_values().next()) } struct Admitted<'a> { db: &'a Driver, ids: BTreeSet, } impl ContactDriver for Admitted<'_> { fn people_handles( &self, database: &str, kind: ContactHandleKind, ) -> std::result::Result, ContactError> { Ok(self .db .all("SELECT p.id,p.full_name,h.normalised AS value FROM cotton_person_handles h JOIN cotton_people p ON p.id=h.person_id WHERE h.workspace_id=? AND p.workspace_id=? AND h.kind=? AND h.trashed_at IS NULL AND p.trashed_at IS NULL", &[text(database),text(database),text(kind.as_str())]) .map_err(|e| ContactError(e.to_string()))? .into_iter() .filter(|r| r.text("id").is_some_and(|id| self.ids.contains(id))) .map(|r| PersonHandleRow { id: r.text("id").unwrap_or_default().into(), full_name: r.text("full_name").map(str::to_owned), value: r.text("value").map(str::to_owned), }) .collect()) } fn contact_by_handle( &self, _: &str, _: &ContactHandle, ) -> std::result::Result, ContactError> { Ok(None) } fn contact_by_phone( &self, _: &str, _: &str, ) -> std::result::Result, ContactError> { Ok(None) } } /// The name a member with nothing else to be called by is refused under. pub const UNNAMED: &str = "Someone with no name or number"; fn said(value: Option<&str>) -> Option { value.map(str::trim).filter(|value| !value.is_empty()).map(str::to_string) } /// A chat as a move sees it: what it is called, and everybody in it but the /// owner. #[derive(Debug, Clone, PartialEq, Eq)] pub struct Chat { pub id: String, pub name: String, pub members: Vec, } /// The chat `thread_id` of the personal database, or `None` when there is no /// such chat (or it is in the bin). /// /// A group's members are its seats that have not left, the owner's own seat /// left out; a private chat's one member is the chat's contact. A seat with no /// contact is a member all the same, with no handle to be matched by. pub fn chat(db: &Driver, workspace_id: &str, thread_id: &str) -> Result> { let Some(thread) = db.get( "SELECT kind, title, contact_id FROM cotton_msg_threads WHERE workspace_id = ? AND id = ? AND trashed_at IS NULL", &[text(workspace_id), text(thread_id)], )? else { return Ok(None); }; let title = said(thread.text("title")); let mut members = Vec::new(); if thread.text("kind") == Some("group") { for seat in db.all( "SELECT contact_id, display_name FROM cotton_msg_thread_participants WHERE thread_id = ? AND left_at IS NULL AND COALESCE(is_self, 0) = 0 ORDER BY created_at, id", &[text(thread_id)], )? { members.push(member(db, seat.text("contact_id"), said(seat.text("display_name")))?); } } else { members.push(member(db, thread.text("contact_id"), title.clone())?); } let name = match (&title, members.as_slice()) { (Some(title), _) => title.clone(), (None, [only]) => only.name.clone(), (None, _) => "This chat".to_string(), }; Ok(Some(Chat { id: thread_id.to_string(), name, members })) } /// One member: the contact's phone and handles, and the best name the /// personal database has for them — the person they are in People, the /// contact's own name, the name the chat showed, then a number or a handle. pub(super) fn member(db: &Driver, contact_id: Option<&str>, shown: Option) -> Result { let contact = match contact_id.filter(|id| !id.is_empty()) { None => None, Some(id) => db .get( "SELECT c.id, c.display_name, c.phone_e164, (SELECT p.full_name FROM cotton_people p WHERE p.id = c.person_id) AS person_name FROM cotton_msg_contacts c WHERE c.id = ?", &[text(id)], )?, }; let Some(contact) = contact else { return Ok(ChatMember { name: shown.unwrap_or_else(|| UNNAMED.to_string()), handles: Vec::new() }); }; let mut handles: Vec<(String, String)> = Vec::new(); if let Some(phone) = said(contact.text("phone_e164")) { handles.push(("phone".to_string(), phone)); } for row in db.all( "SELECT kind, value FROM cotton_msg_contact_handles WHERE contact_id = ? ORDER BY created_at, id", &[text(contact.text("id").unwrap_or_default())], )? { if let (Some(kind), Some(value)) = (row.text("kind"), said(row.text("value"))) { let handle = (kind.to_string(), value); if !handles.contains(&handle) { handles.push(handle); } } } let name = said(contact.text("person_name")) .or_else(|| said(contact.text("display_name"))) .or(shown) .or_else(|| handles.first().map(|(_, value)| value.clone())) .unwrap_or_else(|| UNNAMED.to_string()); Ok(ChatMember { name, handles }) }