//! Finding people, reaching someone not on Cotton yet, and what one person//! shows another (Cotton Chat, 20 Nov 2026). The screens//! draw what these answer; the contract is `assets/design/chat/CONTRACT.md`//! ("Finding people and inviting them").//!//! ```text//! chat.contacts { search? } → { people: [{ number, name, theirName, contact, person, thread, hasPicture }] }//! chat.invite { thread? | number? } → { number, name, text, link, sms }//! chat.contact { thread } → the person's page: who, their picture, between you, mute choices, blocked//! chat.blocked {} → { people: [{ number, name, at }] }//! chat.profile {} → { name, picture, number }//! chat.profile.set { name?, picture?: path | null } → chat.profile's answer//! chat.profilePicture { number, dir } → { path } | { path: null }//! ```//!//! **Finding.** Nobody is found by their number (DISCOVERY OFF 1, 27 Nov//! 2026: no bulk contact discovery). The people here are those this phone//! already knows on Cotton: they wrote, were written to and accepted, or were//! added from Your people. The address book never leaves the phone.//!//! **Not on Cotton yet.** A message to a number not known on Cotton waits on//! this phone (still `queued`, its meta `cotton.waits`): there is no device to seal it for.//! The outbox asks the person's object to wait for that number//! (`POST /v1/chat/wait`, the one lookup left: one number the person picked,//! counted per account per day). It answers `waiting` whether or not the//! number is on Cotton; that person is asked, as an add from Your people//! asks, and the object is told when they accept, and every pass of the//! outbox asks `GET /v1/chat/reach` while anything waits. Reached, the//! messages go back to the queue and are sealed and sent as any other.//!//! **Profiles.** A person's own name and picture ride sealed inside each of//! their messages ([`Profile`]); the picture is a `cf1` file whose key is in//! the box. The person's own is kept on their own `message_contact` row//! (their number), so every one of their phones shows and sends the same.use std::collections::{BTreeMap, HashSet};use std::sync::Mutex;use rusqlite::types::ValueasSqlValue;use serde_json::{json, Map, Value};use cotton_client::transport::object::{bearer, ObjectRefusal};use cotton_core::chat::payload::{Picture, Profile, PROFILE_NAME_MAX};use cotton_core::chat::{files, ids, seal};use cotton_core::messages::app::list;use cotton_tools::mcp::dispatch::Ctx;use cotton_tools::mcp::handlers::common::{insert_row, update_row};usesuper::cotton_chat::{ask, bad, e164, iso, namespace, not_connected, now_iso, now_ms, one, person_of, read, refused, rows, text, thread_number, words, write, ws, CONTACTS, MESSAGES, THREADS};usecrate::methods::MethodError;usecrate::shell::client::ClientController;/// The methods this module answers (each also in `cotton_chat::METHODS`).pubconst METHODS: [&str; 7] = ["chat.blocked", "chat.contact", "chat.contacts", "chat.invite", "chat.profile", "chat.profile.set", "chat.profilePicture"];pubmod routes {pubconst WAIT: &str = "/v1/chat/wait";pubconst REACH: &str = "/v1/chat/reach";pubconst PEOPLE: &str = "/v1/chat/people";pubconst PROFILE_PICTURE: &str = "/v1/chat/profile-picture";pubfn profile_picture(file: &str) -> String { format!("/v1/chat/profile-pictures/{file}") }}/// A message waiting for its person to be on Cotton stays `queued` and says so in its meta, `cotton.waits`.pubfn waits(meta: &Value) -> bool { meta["cotton"]["waits"] == json!(true)}/// The queued messages of a thread (or of every thread) that wait for their person.fn waiting_ids(ctx: &mutCtx<'_>, thread: Option<&str>) -> Result<Vec<String>, String> {letmut params = vec![ws(ctx)];letmut query = format!("SELECT id, meta FROM {MESSAGES} WHERE workspace_id = ? AND send_state = 'queued' AND trashed_at IS NULL");ifletSome(thread) = thread { query.push_str(" AND thread_id = ?"); params.push(SqlValue::Text(thread.to_string())); }Ok(rows(ctx, &query, ¶ms)?.into_iter().filter(|r| waits(&super::cotton_chat::meta_value(r.get("meta").unwrap_or(&Value::Null)))).filter_map(|r| r.get("id").and_then(Value::as_str).map(str::to_string)).collect())}/// A message's `cotton.waits` set or cleared.fn set_waits(ctx: &mutCtx<'_>, id: &str, on: bool) -> Result<(), String> {let row = one(ctx, &format!("SELECT meta FROM {MESSAGES} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(id.to_string())])?;letmut meta = super::cotton_chat::meta_value(row.as_ref().and_then(|r| r.get("meta")).unwrap_or(&Value::Null));if !meta["cotton"].is_object() { meta["cotton"] = json!({}); }if on { meta["cotton"]["waits"] = json!(true); } elseifletSome(cotton) = meta["cotton"].as_object_mut() { cotton.remove("waits"); }letmut patch = Map::new(); patch.insert("meta".into(), meta);if !on { patch.insert("send_attempts".into(), json!(0)); } update_row(ctx, MESSAGES, id, patch).map_err(|f| f.to_string())}pub(crate) const OWN_PICTURE: &str = "chat-profile-picture";pubfn over(client: &ClientController, method: &str, request: &Value) -> Result<Value, MethodError> {match method {"chat.contacts" => contacts(client, request),"chat.invite" => invite(client, request),"chat.contact" => contact(client, request),"chat.blocked" => blocked(client),"chat.profile" => profile(client),"chat.profile.set" => profile_set(client, request),"chat.profilePicture" => profile_picture(client, request), other => Err(MethodError::new("unknown_method", format!("`{other}` is not a chat people method"))), }}// ── finding ─────────────────────────────────────────────────────────────/// The person's own number: remembered, else asked of their object once.fn own_number(client: &ClientController) -> Result<String, MethodError> {super::cotton_chat::my_number(client).ok_or_else(not_connected)}/// A number's `message_contact` row says it is on Cotton, made when new.fn mark_on_cotton(ctx: &mutCtx<'_>, ns: &str, number: &str, name: Option<&str>, person: Option<&str>) -> Result<String, String> {let digits = number.trim_start_matches('+').to_string();let now = now_iso(ctx);match one(ctx, &format!("SELECT id, on_cotton_at FROM {CONTACTS} WHERE workspace_id = ? AND phone_e164 = ?"), &[ws(ctx), SqlValue::Text(digits.clone())])? {Some(row) => {let id = row.get("id").and_then(Value::as_str).unwrap_or_default().to_string();if row.get("on_cotton_at").is_none_or(Value::is_null) {letmut patch = Map::new(); patch.insert("on_cotton_at".into(), json!(now)); update_row(ctx, CONTACTS, &id, patch).map_err(|f| f.to_string())?; }crate::phone::cotton_chat::contact_handle_here(ctx, ns, &id, &digits)?;Ok(id) }None => {let id = ids::contact_id(ns, number);letmut columns = Map::new(); columns.insert("phone_e164".into(), json!(digits)); columns.insert("display_name".into(), json!(name.unwrap_or(number)));ifletSome(person) = person { columns.insert("person_id".into(), json!(person)); } columns.insert("on_cotton_at".into(), json!(now)); insert_row(ctx, CONTACTS, &id, columns).map_err(|f| f.to_string())?;crate::phone::cotton_chat::contact_handle_here(ctx, ns, &id, &digits)?;Ok(id) } }}/// Tests: a number this phone already knows on Cotton (it wrote, accepted, or was added from Your people).#[cfg(test)]pub(crate) fn hold_on_cotton(client: &ClientController, number: &str) {let ns = namespace(client).expect("a namespace");let n = number.to_string(); write(client, "test.on_cotton", move |ctx| mark_on_cotton(ctx, &ns, &n, None, None).map(Value::from)).expect("marked on Cotton");}/// A number that wrote here is on Cotton: its contact (made by the landing) says so, if it did not already.pubfn mark_on_cotton_here(ctx: &mutCtx<'_>, number: &str) -> Result<(), String> {let digits = number.trim_start_matches('+').to_string();ifletSome(row) = one(ctx, &format!("SELECT id, on_cotton_at FROM {CONTACTS} WHERE workspace_id = ? AND phone_e164 = ?"), &[ws(ctx), SqlValue::Text(digits)])? {if row.get("on_cotton_at").is_none_or(Value::is_null) {letmut patch = Map::new(); patch.insert("on_cotton_at".into(), json!(now_iso(ctx))); update_row(ctx, CONTACTS, row.get("id").and_then(Value::as_str).unwrap_or_default(), patch).map_err(|f| f.to_string())?; } }Ok(())}/// One person on Cotton as a list draws them.fn person_row(client: &ClientController, number: &str, name: Option<&str>) -> Result<Value, MethodError> {let digits = number.trim_start_matches('+').to_string();let ns = namespace(client)?;let thread = super::cotton_chat::chat_with_number(client, &ns, number);let found = read(client, "chat.person.row", move |ctx| {let contact = one(ctx, &format!("SELECT id, display_name, profile FROM {CONTACTS} WHERE workspace_id = ? AND phone_e164 = ?"), &[ws(ctx), SqlValue::Text(digits.clone())])?;let has_thread = one(ctx, &format!("SELECT id FROM {THREADS} WHERE workspace_id = ? AND id = ? AND trashed_at IS NULL"), &[ws(ctx), SqlValue::Text(thread.clone())])?.is_some();Ok(json!({ "contact": contact.map(Value::Object), "thread": has_thread.then(|| thread.clone()) })) })?;let contact = &found["contact"];let theirs = profile_of(contact.get("profile").unwrap_or(&Value::Null));let (person, person_name) = person_of(client, number);Ok(json!({"number": number,"name": person_name.or(name.map(str::to_string)).or_else(|| contact.get("display_name").and_then(Value::as_str).map(str::to_string)).or_else(|| theirs.as_ref().and_then(|p| p.name.clone())),"theirName": theirs.as_ref().and_then(|p| p.name.clone()),"hasPicture": theirs.as_ref().is_some_and(|p| p.picture.is_some()),"contact": contact.get("id"),"person": person,"thread": found["thread"], }))}/// Everyone known on Cotton here, by name: who a new chat can be with.fn contacts(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let search = request.get("search").and_then(Value::as_str).map(|s| s.trim().to_lowercase()).filter(|s| !s.is_empty());let numbers = read(client, "chat.contacts", |ctx| {let rows = rows(ctx, &format!("SELECT phone_e164 FROM {CONTACTS} WHERE workspace_id = ? AND on_cotton_at IS NOT NULL AND (blocked IS NULL OR blocked = 0)"), &[ws(ctx)])?;Ok(Value::Array(rows.into_iter().filter_map(|r| r.get("phone_e164").and_then(Value::as_str).map(|d| json!(format!("+{d}")))).collect())) })?;let me = super::cotton_chat::me(client);letmut people = Vec::new();for number in numbers.as_array().into_iter().flatten().filter_map(Value::as_str) {ifSome(number) == me.as_deref() {continue; }let row = person_row(client, number, None)?;ifletSome(search) = &search {let name = row["name"].as_str().unwrap_or_default().to_lowercase();if !name.contains(search.as_str()) && !number.contains(search.as_str()) {continue; } } people.push(row); } people.sort_by_key(|v| v["name"].as_str().unwrap_or("~").to_lowercase());Ok(json!({ "people": people }))}// ── not on Cotton yet ───────────────────────────────────────────────────/// Whether the number's contact here says it is on Cotton.pub(crate) fn on_cotton(ctx: &mutCtx<'_>, number: &str) -> Result<bool, String> {let digits = number.trim_start_matches('+').to_string();Ok(one(ctx, &format!("SELECT on_cotton_at FROM {CONTACTS} WHERE workspace_id = ? AND phone_e164 = ?"), &[ws(ctx), SqlValue::Text(digits)])?.and_then(|r| r.get("on_cotton_at").cloned()).is_some_and(|v| !v.is_null()))}/// A Cotton conversation's reach: `on` (Cotton knows them) or `notYet`, and how many of its messages wait.pubfn reach_of(client: &ClientController, thread: &str) -> Result<Value, MethodError> {let number = thread_number(client, thread)?;let (n, t) = (number.clone(), thread.to_string());let found = read(client, "chat.reach", move |ctx| {let on = on_cotton(ctx, &n)?;let waiting = waiting_ids(ctx, Some(&t))?.len();Ok(json!({ "on": on, "waiting": waiting })) })?;let on = found["on"] == json!(true);letmut reach = json!({ "state": if on { "on" } else { "notYet" }, "waiting": found["waiting"], "number": number });// On the phone where Comms is the SMS app, the person may choose to text them instead, message by message, and// each such text says it is not private (DISCOVERY OFF 2). Never the default: a message written goes when they accept.if !on && super::chat_sms::texts_here(client)? {let lines = list::lines(); reach["sms"] = json!({ "instead": list::say(&lines, "app.reach.sms_instead", &[]), "mark": list::say(&lines, "app.goes.sms_not_private", &[]) }); }Ok(reach)}/// The person's object is asked to wait for this number now (`POST /v1/chat/wait`): their ask goes to that number if/// it is on Cotton, and this phone notes that it asked (`asked_at`), so every outbox pass asks whether they accepted./// True when they can be written to already (they accepted before).pubfn ask_now(client: &ClientController, number: &str) -> Result<bool, MethodError> {let answer = ask(client, "POST", routes::WAIT, Some(&json!({ "number": number }))).map_err(refused)?;if answer["state"] == json!("reached") { reached(client, number)?;returnOk(true); }let ns = namespace(client)?;let (n, (person, name)) = (number.to_string(), person_of(client, number)); write(client, "chat.asked", move |ctx| mark_asked(ctx, &ns, &n, name.as_deref(), person.as_deref()).map(|_| Value::Null))?;Ok(false)}/// Asks that could not go because nothing answered, by copy and number: tried again at each `wake` while the app runs./// Kept in memory only: an app closed before it is back online asks again when the chat is next started.static LATER: Mutex<Option<HashSet<(String, String)>>> = Mutex::new(None);/// This number's ask goes at the next `wake` that reaches the object.pub(crate) fn ask_later(client: &ClientController, number: &str) {ifletOk(mut held) = LATER.lock() { held.get_or_insert_with(HashSet::new).insert((namespace(client).unwrap_or_default(), number.to_string())); }}fn later_asks(client: &ClientController) -> Vec<String> {let ws = namespace(client).unwrap_or_default(); LATER.lock().ok().and_then(|held| held.as_ref().map(|h| h.iter().filter(|(w, _)| *w == ws).map(|(_, n)| n.clone()).collect())).unwrap_or_default()}fn forget_later(client: &ClientController, number: &str) {ifletOk(mut held) = LATER.lock() {ifletSome(h) = held.as_mut() { h.remove(&(namespace(client).unwrap_or_default(), number.to_string())); } }}/// A number's `message_contact` row notes when this phone asked them to chat on Cotton, made when new.fn mark_asked(ctx: &mutCtx<'_>, ns: &str, number: &str, name: Option<&str>, person: Option<&str>) -> Result<(), String> {// A copy whose contact table has no `asked_at` yet (its definition not come) keeps no mark: the ask still went.if !super::cotton_chat::holds(ctx, CONTACTS, "asked_at")? {returnOk(()); }let digits = number.trim_start_matches('+').to_string();let now = now_iso(ctx);letmut patch = Map::new(); patch.insert("asked_at".into(), json!(now));match one(ctx, &format!("SELECT id FROM {CONTACTS} WHERE workspace_id = ? AND phone_e164 = ?"), &[ws(ctx), SqlValue::Text(digits.clone())])? {Some(row) => update_row(ctx, CONTACTS, row.get("id").and_then(Value::as_str).unwrap_or_default(), patch).map_err(|f| f.to_string()).map(|_| ()),None => { patch.insert("phone_e164".into(), json!(digits)); patch.insert("display_name".into(), json!(name.unwrap_or(number)));ifletSome(person) = person { patch.insert("person_id".into(), json!(person)); } insert_row(ctx, CONTACTS, &ids::contact_id(ns, number), patch).map_err(|f| f.to_string()).map(|_| ()) } }}/// Whether this phone asked anyone who has not accepted yet: the outbox's pass then asks who did.fn asked_any(ctx: &mutCtx<'_>) -> Result<bool, String> {if !super::cotton_chat::holds(ctx, CONTACTS, "asked_at")? {returnOk(false); }Ok(one(ctx, &format!("SELECT id FROM {CONTACTS} WHERE workspace_id = ? AND asked_at IS NOT NULL AND on_cotton_at IS NULL LIMIT 1"), &[ws(ctx)])?.is_some())}/// Whether a number is known on Cotton here. Never asked of the server: nobody is found by their number/// (DISCOVERY OFF 1); a number not known waits, and its person is asked (`POST /v1/chat/wait`).pubfn check_one(client: &ClientController, number: &str) -> Result<bool, MethodError> {let n = number.to_string();Ok(read(client, "chat.on", move |ctx| on_cotton(ctx, &n).map(Value::from))? == json!(true))}/// The outbox's gate before one message's try: true when its person can be/// sealed for. A message to a number not known on Cotton waits (and the/// object is asked to wait for that number), unless the object answers that/// they can be written to now.pubfn gate(client: &ClientController, message: &str) -> Result<bool, ObjectRefusal> {let id = message.to_string();let row = read(client, "chat.gate", move |ctx| {Ok(one(ctx, &format!("SELECT t.external_key, t.id AS thread FROM {MESSAGES} m JOIN {THREADS} t ON t.id = m.thread_id WHERE m.workspace_id = ? AND m.id = ?"), &[ws(ctx), SqlValue::Text(id.clone())])?.map(Value::Object).unwrap_or(Value::Null)) }) .map_err(local)?;letSome(number) = row["external_key"].as_str().and_then(ids::number_of_key).map(str::to_string) else { returnOk(true) };let n = number.clone();if read(client, "chat.on", move |ctx| on_cotton(ctx, &n).map(Value::from)).map_err(local)? == json!(true) {returnOk(true); }let answer = ask(client, "POST", routes::WAIT, Some(&json!({ "number": number })))?;if answer["state"] == json!("reached") { reached(client, &number).map_err(local)?;returnOk(true); }let id = message.to_string(); write(client, "chat.waits", move |ctx| set_waits(ctx, &id, true).map(|_| Value::Null)).map_err(local)?;Ok(false)}/// Before the outbox's pass, while anything waits or anyone asked has not accepted: the numbers now reachable, their/// messages back in the queue.pubfn wake(client: &ClientController) -> Result<usize, MethodError> {// An ask that could not go at the chat's start (offline) goes now, once the object answers (DISCOVERY OFF 3).for number in later_asks(client) {match ask_now(client, &number) {Ok(_) => forget_later(client, &number),Err(e) if e.code == "offline" => {}// Refused (over the new-chats limit, signed out): said when it was first tried; not asked again unasked.Err(_) => forget_later(client, &number), } }let waiting = read(client, "chat.waiting.any", |ctx| Ok((!waiting_ids(ctx, None)?.is_empty() || asked_any(ctx)?).into()))?;if waiting != json!(true) {returnOk(0); }letOk(answer) = ask(client, "GET", routes::REACH, None) else { returnOk(0) };letmut woken = 0;for number in answer["reached"].as_array().into_iter().flatten().filter_map(Value::as_str) { woken += reached(client, number)?; }Ok(woken)}/// A number can be written to: its contact says on Cotton, and its waiting messages go back in the queue.fn reached(client: &ClientController, number: &str) -> Result<usize, MethodError> {let ns = namespace(client)?;let (n, (person, name)) = (number.to_string(), person_of(client, number));let thread = super::cotton_chat::chat_with_number(client, &ns, number);let woken = write(client, "chat.reached", move |ctx| { mark_on_cotton(ctx, &ns, &n, name.as_deref(), person.as_deref())?;// Their chat here is their Cotton chat from now on: an SMS chat (or one from WhatsApp first) with this number// moves over in place, its texts standing in it, and what is written next goes sealed (DISCOVERY OFF 2).super::cotton_chat::ensure_thread(ctx, &ns, &n, name.as_deref(), person.as_deref(), None, true)?;let ids_ = waiting_ids(ctx, Some(&thread))?;for id in &ids_ { set_waits(ctx, id, false)?; }Ok(json!(ids_.len())) })?;Ok(woken.as_u64().unwrap_or(0) as usize)}/// What the person sends someone not on Cotton themselves (a text from their/// own phone, or the share sheet): Cotton never sends it. Asking for it also/// asks the person's object to wait for that number, so the chat turns to/// "on Cotton" when they join.fn invite(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let number = match (request.get("thread").and_then(Value::as_str), request.get("number").and_then(Value::as_str)) { (Some(thread), _) => thread_number(client, thread)?, (None, Some(number)) => e164(number).ok_or_else(|| words("bad_number", "That isn't a phone number Cotton can use."))?, _ => returnErr(bad("thread", "a chat, or a number")), };let (_, name) = person_of(client, &number);let lines = list::lines();let link = list::say(&lines, "people.invite.link", &[]);let words_ = list::say(&lines, "people.invite.text", &[("link", &link)]);let answer = ask(client, "POST", routes::WAIT, Some(&json!({ "number": number })));ifletOk(answer) = &answer {if answer["state"] == json!("reached") { reached(client, &number)?; } }let sms = format!("sms:{number}?&body={}", percent(&words_));Ok(json!({ "number": number, "name": name, "text": words_, "link": link, "sms": sms, "waiting": answer.is_ok() }))}fn percent(text: &str) -> String { text.bytes() .map(|b| match b { b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => (b as char).to_string(), _ => format!("%{b:02X}"), }) .collect()}// ── profiles ────────────────────────────────────────────────────────────pubfn profile_of(raw: &Value) -> Option<Profile> {match raw {Value::String(text) => serde_json::from_str(text).ok(),Value::Object(_) => serde_json::from_value(raw.clone()).ok(), _ => None, }}/// The person's own profile as their messages carry it: their own contact row's, else none.pubfn own_profile(client: &ClientController) -> Option<Profile> {let me = super::cotton_chat::me(client)?;let digits = me.trim_start_matches('+').to_string();let found = read(client, "chat.own.profile", move |ctx| Ok(one(ctx, &format!("SELECT profile FROM {CONTACTS} WHERE workspace_id = ? AND phone_e164 = ?"), &[ws(ctx), SqlValue::Text(digits.clone())])?.and_then(|r| r.get("profile").cloned()).unwrap_or(Value::Null))).ok()?; profile_of(&found)}/// Someone's profile arriving in their message: kept on their contact when newer than the one held./// `ns` names a contact the landing has only just made (its write not read back yet).pubfn take_profile(ctx: &mutCtx<'_>, ns: &str, number: &str, profile: &Profile) -> Result<(), String> {let digits = number.trim_start_matches('+').to_string();let row = one(ctx, &format!("SELECT id, profile FROM {CONTACTS} WHERE workspace_id = ? AND phone_e164 = ?"), &[ws(ctx), SqlValue::Text(digits)])?;let id = row.as_ref().and_then(|r| r.get("id").and_then(Value::as_str).map(str::to_string)).unwrap_or_else(|| ids::contact_id(ns, number));let held = profile_of(row.as_ref().and_then(|r| r.get("profile")).unwrap_or(&Value::Null));if held.as_ref().is_some_and(|h| h.at >= profile.at) {returnOk(()); }letmut kept = profile.clone(); kept.name = kept.name.map(|n| n.trim().chars().take(PROFILE_NAME_MAX).collect::<String>()).filter(|n| !n.is_empty());letmut patch = Map::new(); patch.insert("profile".into(), json!(serde_json::to_string(&kept).unwrap_or_default())); update_row(ctx, CONTACTS, &id, patch).map_err(|f| f.to_string())}/// The card as this phone knows it, with no network (`chat.you`'s `profile`, You's first frame, owner build 24):/// [`profile`]'s name, number and picture, the number as this phone last learnt it. Before this run has learnt the/// number (Comms registers a moment after launch), the name is the person's own in the copy (`read.you`).pub(crate) fn profile_here(handle: &crate::handle::CottonHandle) -> Value {let held = handle.client();let client = &held;letSome(me) = super::cotton_chat::me(client) else {let name = crate::methods::dispatch(handle, "read.you", &json!({})).ok().and_then(|you| you["name"].as_str().map(str::trim).filter(|name| !name.is_empty()).map(str::to_string));return name.map_or_else(|| json!({}), |name| json!({ "name": name })); };let own = own_profile(client);letmut here = json!({ "number": me });ifletSome(name) = own.as_ref().and_then(|p| p.name.clone()).or_else(|| person_of(client, &me).1) { here["name"] = json!(name); }let path = client.layout().client_dir().join(OWN_PICTURE);if own.as_ref().is_some_and(|p| p.picture.is_some()) && path.exists() { here["picture"] = json!({ "path": path.to_string_lossy() }); } here}fn profile(client: &ClientController) -> Result<Value, MethodError> {let me = own_number(client)?;let own = own_profile(client);let account = person_of(client, &me).1;let path = client.layout().client_dir().join(OWN_PICTURE);let picture = own.as_ref().and_then(|p| p.picture.as_ref()).map(|_| if path.exists() { json!({ "path": path.to_string_lossy() }) } else { json!({ "path": null }) });Ok(json!({ "name": own.as_ref().and_then(|p| p.name.clone()).or(account), "picture": picture, "number": me }))}/// The person changes their own name or picture (`picture: null` takes it away).fn profile_set(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let me = own_number(client)?;letmut next = own_profile(client).unwrap_or_default();ifletSome(name) = request.get("name") {let name = name.as_str().map(|n| n.trim().to_string()).filter(|n| !n.is_empty());if name.as_ref().is_some_and(|n| n.chars().count() > PROFILE_NAME_MAX) {returnErr(words("name_too_long", "That name is too long.")); } next.name = name; }match request.get("picture") {Some(Value::Null) => { next.picture = None;// not a copy: people files.let _ = std::fs::remove_file(client.layout().client_dir().join(OWN_PICTURE)); }Some(Value::String(path)) => {let plain = std::fs::read(path).map_err(|e| MethodError::new("unreadable", format!("the picture could not be read ({e})")))?;let sealed = files::seal_file(&plain).ok_or_else(|| words("picture_too_large", "That picture is too large."))?;let answer = super::cotton_chat::put_typed(client, routes::PROFILE_PICTURE, &sealed.bytes, "application/octet-stream").map_err(refused)?;let file = answer["file"].as_str().ok_or_else(|| MethodError::new("refused", "the object kept no picture"))?.to_string();let mime = request.get("mime").and_then(Value::as_str).unwrap_or("image/jpeg").to_string(); next.picture = Some(Picture { file, key: seal::key_text(&sealed.key), sha256: sealed.sha256, mime, width: None, height: None, bytes: plain.len() as u64, kind: None, name: None, duration_ms: None, waveform: vec![], preview: None });// not a copy: people files. std::fs::write(client.layout().client_dir().join(OWN_PICTURE), &plain).map_err(|e| MethodError::new("unwritable", e.to_string()))?; }Some(_) => returnErr(bad("picture", "a picture's path, or null")),None => {} } next.at = now_ms(client);let ns = namespace(client)?;let (m, kept) = (me.clone(), serde_json::to_string(&next).unwrap_or_default()); write(client, "chat.profile.set", move |ctx| {let id = mark_on_cotton(ctx, &ns, &m, None, None)?;letmut patch = Map::new(); patch.insert("profile".into(), json!(kept)); update_row(ctx, CONTACTS, &id, patch).map_err(|f| f.to_string())?;Ok(Value::Null) })?; profile(client)}/// Someone's picture as they show it, fetched and opened into `dir` (kept by its hash); null when they show none.fn profile_picture(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let number = e164(text(request, "number")?).ok_or_else(|| bad("number", "a number starting with +"))?;let dir = std::path::PathBuf::from(text(request, "dir")?);let digits = number.trim_start_matches('+').to_string();let found = read(client, "chat.their.profile", move |ctx| Ok(one(ctx, &format!("SELECT profile FROM {CONTACTS} WHERE workspace_id = ? AND phone_e164 = ?"), &[ws(ctx), SqlValue::Text(digits.clone())])?.and_then(|r| r.get("profile").cloned()).unwrap_or(Value::Null)))?;letSome(picture) = profile_of(&found).and_then(|p| p.picture) else { returnOk(json!({ "path": null })) };let path = dir.join(format!("{}.picture", picture.sha256));if path.exists() {returnOk(json!({ "path": path.to_string_lossy(), "mime": picture.mime })); }let key = seal::key_from_text(&picture.key).ok_or_else(|| MethodError::new("unreadable", "the picture's key is not one"))?;let door = client.object_door().ok_or_else(not_connected)?;let (status, bytes) = door.address.send_bytes(door.exchange.as_ref(), "GET", &routes::profile_picture(&picture.file), bearer(&door.credential), None).map_err(refused)?;if status != 200 {returnOk(json!({ "path": null })); }let plain = files::open_file(&key, &bytes, &picture.sha256).ok_or_else(|| MethodError::new("unreadable", "The picture did not open."))?; std::fs::create_dir_all(&dir).map_err(|e| MethodError::new("unwritable", e.to_string()))?;// not a copy: people files. std::fs::write(&path, plain).map_err(|e| MethodError::new("unwritable", e.to_string()))?;Ok(json!({ "path": path.to_string_lossy(), "mime": picture.mime }))}// ── a person's page, and the blocked ────────────────────────────────────/// How long a mute may be chosen for: the label's line and its length (none: until unmuted).const MUTES: [(&str, Option<i64>); 3] = [("people.mute.hours8", Some(8 * 3_600_000)), ("people.mute.week", Some(7 * 24 * 3_600_000)), ("people.mute.always", None)];/// A person's page: who they are here and as they show themselves, what has passed between you, mute and block.fn contact(client: &ClientController, request: &Value) -> Result<Value, MethodError> {let thread = text(request, "thread")?.to_string();// An SMS chat's page (DECISIONS "SMS on Android"): its number where it has one, mute, and a block kept in his copy.ifletSome(mut answer) = super::chat_sms::contact_answer(client, &thread)? {let lines = list::lines();let now = now_ms(client); answer["mutes"] = json!(MUTES.iter().map(|(line, length)| json!({ "label": list::say(&lines, line, &[]), "until": length.map(|l| iso(now + l)) })).collect::<Vec<Value>>());returnOk(answer); }let number = thread_number(client, &thread)?;let row = person_row(client, &number, None)?;let reach = reach_of(client, &thread)?;let (t, phone_digits) = (thread.clone(), number.trim_start_matches('+').to_string());let found = read(client, "chat.contact", move |ctx| {let thread_row = one(ctx, &format!("SELECT muted_until FROM {THREADS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), SqlValue::Text(t.clone())])?;let contact = one(ctx, &format!("SELECT blocked FROM {CONTACTS} WHERE workspace_id = ? AND phone_e164 = ?"), &[ws(ctx), SqlValue::Text(phone_digits.clone())])?;let verified = super::chat_safety::verified_here(ctx, &format!("+{phone_digits}"))?;let messages = rows(ctx, &format!("SELECT body, meta FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND trashed_at IS NULL"), &[ws(ctx), SqlValue::Text(t.clone())])?;letmut between = BTreeMap::from([("photos", 0u64), ("videos", 0), ("voice", 0), ("files", 0), ("links", 0)]);for message in &messages {let meta = super::cotton_chat::meta_value(message.get("meta").unwrap_or(&Value::Null));for picture in meta["cotton"]["pictures"].as_array().into_iter().flatten() {let slot = match picture["kind"].as_str() {Some("video") => "videos",Some("voice") | Some("audio") => "voice",Some("file") => "files", _ => "photos", }; *between.entry(slot).or_default() += 1; }let body = message.get("body").and_then(Value::as_str).unwrap_or_default(); *between.entry("links").or_default() += body.split_whitespace().filter(|w| w.starts_with("http://") || w.starts_with("https://")).count() as u64; }Ok(json!({"mutedUntil": thread_row.and_then(|r| r.get("muted_until").cloned()).unwrap_or(Value::Null),"blocked": contact.and_then(|r| r.get("blocked").cloned()).is_some_and(|b| b == json!(true) || b == json!(1)),"between": between,"verified": verified, })) })?;let lines = list::lines();let now = now_ms(client);let mutes: Vec<Value> = MUTES.iter().map(|(line, length)| json!({ "label": list::say(&lines, line, &[]), "until": length.map(|l| iso(now + l)) })).collect();Ok(json!({"thread": thread,"number": number,"name": row["name"],"theirName": row["theirName"],"hasPicture": row["hasPicture"],"person": row["person"],"reach": reach["state"],"blocked": found["blocked"],"mutedUntil": found["mutedUntil"],"mutes": mutes,"between": found["between"],// Whether the person verified their safety number as it stands (chat.safety)."verified": found["verified"], }))}/// The people this person blocked, latest first, by the name they are known by here.fn blocked(client: &ClientController) -> Result<Value, MethodError> {letmut answer = ask(client, "GET", routes::PEOPLE, None).map_err(refused)?;super::circle::open_sealed(client, &mut answer);let people: Vec<Value> = answer["blocked"] .as_array() .into_iter() .flatten() .filter_map(|b| {let number = b["number"].as_str()?.to_string();let name = person_of(client, &number).1.or_else(|| b["name"].as_str().map(str::to_string));Some(json!({ "number": number, "name": name, "at": b["at"] })) }) .collect();Ok(json!({ "people": people }))}fn local(error: MethodError) -> ObjectRefusal {ObjectRefusal { status: 0, code: "local".into(), message: error.message }}#[cfg(test)]#[path = "chat_people_tests.rs"]mod tests;