//! The chat in front on the Messages face, where the chat is the face (no //! fan): one chat's slips, every word from `kits/shell/lines/chat.json`, so a //! shell only draws. Which chat is in front, the stream's order, its quiet //! count, search and the top button are `shell.stream`'s //! (`methods/shell_stream.rs`); this reads the one chat it names. //! //! ```text //! chat.slips {thread} → {thread, name, number?, cotton, request?:{title, line, accept, block, refuse}, //! blocked?:{line, unblock}, //! slips:[{message, body, out, when, day, state?, failed, pictures?}], words:{write, send, picture}} //! ``` //! //! Slips run oldest to newest, the whole chat (a screen read never takes a //! page by number, reads_tests); each says when //! (the clock under its day) and the day it heads. My own Cotton slips say //! their delivery state in the chat set's words (`state.*`), and a failed one //! says so, so a tap can try it again (`chat.retry`). A stranger's chat //! carries the request card's words until it is answered. A chat whose //! person this phone blocked says so where the typing line stands, with //! Unblock (`chat.unblock`). A slip that carries pictures says how many //! (`pictures`), each opened by `chat.picture {message, index, dir}`. use rusqlite::types::Value as SqlValue; use serde_json::{json, Map, Value}; use cotton_core::records::page::{stamp_parts, DateWords}; use cotton_core::rules::shell_lines::resolve; use cotton_tools::mcp::dispatch::Ctx; use super::cotton_chat::{bad, meta_value, person_of, read, rows, ws, MESSAGES, THREADS}; use crate::methods::MethodError; use crate::shell::client::ClientController; const CONTACTS: &str = "cotton_msg_contacts"; fn say(line: &str, fills: &[(&str, &str)]) -> String { resolve("chat", line, &[], fills).unwrap_or_default() } /// The typing line's words, said once per read. pub fn words() -> Value { let lines = ["write", "send", "picture"]; Value::Object(lines.iter().map(|line| (line.to_string(), json!(say(&format!("slips.{line}"), &[])))).collect()) } /// Stamp parts for one ISO moment in the reader's zone, now. struct Clock { zone: String, now: chrono::DateTime, dates: &'static DateWords, } impl Clock { fn of(client: &ClientController) -> Self { Self { zone: client.time_zone().unwrap_or("Etc/UTC").to_string(), now: client.clock().now(), dates: DateWords::shipped() } } /// Under a day's heading (a slip): the clock, and the heading itself. fn slip(&self, at: &str) -> (String, String) { stamp_parts(at, &self.zone, self.now, self.dates).map(|p| (p.under_day, p.heading)).unwrap_or_default() } } fn text(row: &Map, key: &str) -> Option { row.get(key).and_then(Value::as_str).map(str::trim).filter(|t| !t.is_empty()).map(str::to_string) } fn number_of(external_key: &str) -> String { external_key.strip_prefix("cotton:").unwrap_or(external_key).to_string() } fn holds(ctx: &mut Ctx<'_>, table: &str, column: &str) -> Result { let found = rows(ctx, &format!("SELECT name FROM pragma_table_info('{table}') WHERE name = ?"), &[SqlValue::Text(column.into())])?; Ok(!found.is_empty()) } /// `chat.slips`. pub fn slips(client: &ClientController, request: &Value) -> Result { let thread = request.get("thread").and_then(Value::as_str).filter(|t| !t.is_empty()).ok_or_else(|| bad("thread", "a chat's id"))?.to_string(); let clock = Clock::of(client); let t = thread.clone(); let found = read(client, "chat.slips", move |ctx| { let mut column = |table: &str, alias: &str, field: &str| -> Result { Ok(if holds(ctx, table, field)? { format!("{alias}.{field}") } else { "NULL".into() }) }; let (request, own, title) = (column(THREADS, "t", "request")?, column(THREADS, "t", "name")?, column(THREADS, "t", "title")?); let blocked = column(CONTACTS, "c", "blocked")?; let head = rows( ctx, &format!("SELECT t.external_key, c.display_name, {own} AS own_name, {title} AS title, {request} AS request, {blocked} AS blocked FROM {THREADS} t LEFT JOIN {CONTACTS} c ON c.id = t.contact_id WHERE t.workspace_id = ? AND t.id = ? AND t.trashed_at IS NULL"), &[ws(ctx), SqlValue::Text(t.clone())], )?; let slips = rows( ctx, &format!("SELECT id, body, direction, sent_at, send_state, meta FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND trashed_at IS NULL ORDER BY sent_at ASC"), &[ws(ctx), SqlValue::Text(t.clone())], )?; Ok(json!({ "head": head.into_iter().next(), "slips": slips })) })?; let Some(head) = found.get("head").and_then(Value::as_object) else { return Err(MethodError::new("not_found", say("refused.not_found", &[]))); }; let address = text(head, "external_key").unwrap_or_default(); let cotton = address.starts_with("cotton:"); let number = number_of(&address); // Named as the stream names it: a Cotton chat by the person this phone knows, else its contact, else the // thread's own name or title (an archive has no number and no contact of its own), else the number. let name = if cotton { person_of(client, &number).1 } else { None } .or_else(|| text(head, "display_name").filter(|n| *n != number)) .or_else(|| text(head, "own_name")) .or_else(|| text(head, "title")) .unwrap_or_else(|| number.clone()); let slips: Vec = found["slips"] .as_array() .into_iter() .flatten() .filter_map(Value::as_object) .map(|m| { let out = text(m, "direction").as_deref() == Some("out"); let (when, day) = clock.slip(&text(m, "sent_at").unwrap_or_default()); let state = text(m, "send_state").filter(|_| out && cotton); let mut slip = json!({ "message": text(m, "id"), "body": text(m, "body").unwrap_or_default(), "out": out, "when": when, "day": day, "failed": state.as_deref() == Some("failed") }); let pictures = meta_value(m.get("meta").unwrap_or(&Value::Null))["cotton"]["pictures"].as_array().map_or(0, Vec::len); if pictures > 0 { slip["pictures"] = json!(pictures); } if let Some(state) = state { slip["state"] = json!(say(&format!("state.{state}"), &[])); } slip }) .collect(); let mut answer = json!({ "thread": thread, "name": name, "cotton": cotton, "slips": slips, "words": words() }); if cotton { answer["number"] = json!(number); } if text(head, "request").as_deref() == Some("pending") { let known = name != number; let title = if known { say("request.title", &[("name", &name)]) } else { say("request.unknown_title", &[]) }; answer["request"] = json!({ "title": title, "line": say("request.line", &[]), "accept": say("request.accept", &[]), "block": say("request.block", &[]), "refuse": say("request.refuse", &[]) }); } if cotton && answer.get("request").is_none() && truthy(head.get("blocked")) { answer["blocked"] = json!({ "line": say("blocked.line", &[]), "unblock": say("blocked.unblock", &[]) }); } Ok(answer) } /// A boolean column as SQLite keeps it: 1, true, or "true". fn truthy(value: Option<&Value>) -> bool { match value { Some(Value::Bool(on)) => *on, Some(Value::Number(n)) => n.as_i64().unwrap_or(0) != 0, Some(Value::String(t)) => t == "1" || t == "true", _ => false, } } #[cfg(test)] #[path = "chat_face_tests.rs"] mod tests;