Cotton code
203 lines · 7.9 KB · RustRaw
//! Which picture a conversation, or a call, is drawn with.//!//! The paper screens draw a person as an instant print when there is a//! photograph of them and as a typed card when there is not, and a group as its//! OWN photograph — one print, never a cluster of its members' faces. So each//! row these reads answer carries the object KEY of that picture, and nothing//! else: bytes never cross the boundary, and the print that goes on screen asks//! `read.mediaPath` for a path to it — the read that never fetches, the way//! every other renderer in the app does (`MediaFetchSweepTests`). The bytes//! arrive through the app's `media.ensure` fetch path.//!//! **The rule, once.** A conversation that belongs to a PERSON wears the//! person's `avatar_key`; a group, or a conversation with a number no person//! was ever matched to, wears the thread's own `photo_key`. A call wears its//! person's `avatar_key`. Absent is `null`, never an empty string, so the app's//! print-or-card decision is one `nil` check.//!//! These are the phone's reads rather than the tools' answers on purpose: an//! assistant asking `list_message_threads` has no use for an object key it//! cannot draw, and the MCP projection stays what it was.use std::collections::BTreeMap;use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value};use cotton_tools::mcp::dispatch::Ctx;/// A blank key is no key.fn key_of(value: Option<&str>) -> Value {    match value.map(str::trim).filter(|key| !key.is_empty()) {        Some(key) => Value::from(key),        None => Value::Null,    }}/// `id → avatar_key` for the people named, in one read.fn avatar_keys(ctx: &Ctx<'_>, people: &[String]) -> Result<BTreeMap<String, Value>, String> {    if people.is_empty() {        return Ok(BTreeMap::new());    }    let marks = vec!["?"; people.len()].join(",");    let mut bound = vec![SqlValue::Text(ctx.workspace_id.to_string())];    bound.extend(people.iter().map(|id| SqlValue::Text(id.clone())));    Ok(ctx        .db()        .all(            &format!(                "SELECT id, avatar_key FROM cotton_people WHERE workspace_id = ? AND id IN ({marks})"            ),            &bound,        )        .map_err(|error| error.to_string())?        .iter()        .filter_map(|row| Some((row.text("id")?.to_string(), key_of(row.text("avatar_key")))))        .collect())}/// One conversation's picture, and — for a group — how many people are in it.struct ThreadFace {    picture: Value,    members: Option<i64>,}/// `thread id → face` for the threads named, in one read.////// The person's photograph outranks the thread's own: a WhatsApp import stamps/// a DM with whatever picture the contact had that day, and the person's page/// is where the owner chose one.fn thread_faces(ctx: &Ctx<'_>, threads: &[String]) -> Result<BTreeMap<String, ThreadFace>, String> {    if threads.is_empty() {        return Ok(BTreeMap::new());    }    let marks = vec!["?"; threads.len()].join(",");    let mut bound = vec![SqlValue::Text(ctx.workspace_id.to_string())];    bound.extend(threads.iter().map(|id| SqlValue::Text(id.clone())));    Ok(ctx        .db()        .all(            &format!(                "SELECT t.id AS id, t.kind AS kind, t.photo_key AS photo_key,                        p.avatar_key AS avatar_key,                        (SELECT COUNT(*) FROM cotton_msg_thread_participants m                          WHERE m.thread_id = t.id AND m.left_at IS NULL) AS members                   FROM cotton_msg_threads t                   LEFT JOIN cotton_msg_contacts c ON c.id = t.contact_id                   LEFT JOIN cotton_people p ON p.id = {person}                  WHERE t.workspace_id = ? AND t.id IN ({marks})",                person = cotton_store::protocol::who::contact_person_sql(cotton_store::protocol::who::shared_held(ctx.db()), "c")            ),            &bound,        )        .map_err(|error| error.to_string())?        .iter()        .filter_map(|row| {            let id = row.text("id")?.to_string();            let group = row.text("kind") == Some("group");            let picture = if group {                key_of(row.text("photo_key"))            } else {                match key_of(row.text("avatar_key")) {                    Value::Null => key_of(row.text("photo_key")),                    found => found,                }            };            Some((                id,                ThreadFace {                    picture,                    members: if group { row.int("members") } else { None },                },            ))        })        .collect())}fn text(row: &Value, key: &str) -> Option<String> {    row.get(key).and_then(Value::as_str).map(str::to_string)}/// Stamp `pictureKey` on every inbox row.////// A row folded from one person's several numbers carries `personId` and the/// person's photograph; any other row is read off the thread it opens.pub fn stamp_inbox(ctx: &Ctx<'_>, rows: &mut [Value]) -> Result<(), String> {    let people: Vec<String> = rows.iter().filter_map(|row| text(row, "personId")).collect();    let threads: Vec<String> = rows        .iter()        .filter(|row| row.get("personId").and_then(Value::as_str).is_none())        .filter_map(|row| text(row, "id"))        .collect();    let avatars = avatar_keys(ctx, &people)?;    let faces = thread_faces(ctx, &threads)?;    for row in rows.iter_mut() {        let picture = match (text(row, "personId"), text(row, "id")) {            (Some(person), _) => avatars.get(&person).cloned().unwrap_or(Value::Null),            (None, Some(thread)) => faces                .get(&thread)                .map(|face| face.picture.clone())                .unwrap_or(Value::Null),            (None, None) => Value::Null,        };        if let Some(object) = row.as_object_mut() {            object.insert("pictureKey".to_string(), picture);        }    }    Ok(())}/// Stamp `pictureKey` — and, for a group, `memberCount` — on a conversation's/// header. `thread_id` is the single thread asked for, or `None` for a/// conversation read by person.pub fn stamp_thread(    ctx: &Ctx<'_>,    thread_id: Option<&str>,    out: &mut Map<String, Value>,) -> Result<(), String> {    let Some(Value::Object(head)) = out.get_mut("thread") else {        return Ok(());    };    let person = head.get("personId").and_then(Value::as_str).map(str::to_string);    let (picture, members) = match (person, thread_id) {        (Some(person), _) => (            avatar_keys(ctx, std::slice::from_ref(&person))?                .remove(&person)                .unwrap_or(Value::Null),            None,        ),        (None, Some(thread)) => {            let thread = thread.to_string();            match thread_faces(ctx, std::slice::from_ref(&thread))?.remove(&thread) {                Some(face) => (face.picture, face.members),                None => (Value::Null, None),            }        }        (None, None) => (Value::Null, None),    };    head.insert("pictureKey".to_string(), picture);    if let Some(members) = members {        head.insert("memberCount".to_string(), Value::from(members));    }    Ok(())}/// Stamp `avatarKey` on every call whose number was matched to a person.pub fn stamp_calls(ctx: &Ctx<'_>, answer: &mut Value) -> Result<(), String> {    let Some(calls) = answer.get_mut("calls").and_then(Value::as_array_mut) else {        return Ok(());    };    let mut people: Vec<String> = calls.iter().filter_map(|call| text(call, "personId")).collect();    people.sort();    people.dedup();    let avatars = avatar_keys(ctx, &people)?;    for call in calls.iter_mut() {        let picture = text(call, "personId")            .and_then(|person| avatars.get(&person).cloned())            .unwrap_or(Value::Null);        if let Some(object) = call.as_object_mut() {            object.insert("avatarKey".to_string(), picture);        }    }    Ok(())}