//! `get_record`'s `page`: the record page in one read //! (`cotton_core::records::page::record_page_read`), read through this //! database's own generic reads — the same answer the phone's //! `records.page` gives. use cotton_core::definitions::TableDefinition; use cotton_core::records::page::{HandleActivity, PageSource}; use serde_json::{json, Map, Value}; use super::{get_record_by_table, list_answer, Total, MAX_PAGE_SIZE}; use crate::mcp::dispatch::Ctx; use cotton_core::rules::mail_predicate; struct CtxPages<'a, 'b> { ctx: &'a mut Ctx<'b>, } fn rows_of(answer: &Value) -> Vec<(String, Map)> { answer["records"] .as_array() .into_iter() .flatten() .filter_map(|record| Some((record["id"].as_str()?.to_string(), record["data"].as_object()?.clone()))) .collect() } fn args(value: Value) -> Map { value.as_object().cloned().unwrap_or_default() } impl PageSource for CtxPages<'_, '_> { fn line_rows(&mut self) -> Vec { crate::presentation::line_rows(self.ctx.read.driver(), self.ctx.workspace_id) } fn definition(&mut self, table: &str) -> Option { super::definition(self.ctx, table).ok() } fn record(&mut self, table: &str, id: &str) -> Result, String> { let record = get_record_by_table(self.ctx, &args(json!({ "table": table, "id": id }))).map_err(|failure| failure.to_string())?; // A read answers a deleted record too; its page is gone. if !record["deleted_at"].is_null() { let definition = self.definition(table).ok_or_else(|| format!("there is no table {table:?}"))?; return Err(cotton_core::records::receipt::no_longer_here(&definition)); } Ok(record["data"].as_object().cloned().unwrap_or_default()) } fn records(&mut self, table: &str, ids: &[String]) -> Result)>, String> { let mut found = Vec::new(); for some in ids.chunks(MAX_PAGE_SIZE as usize) { let answer = list_answer(self.ctx, &args(json!({ "table": table, "ids": some })), Total::Skipped).map_err(|failure| failure.to_string())?; found.extend(rows_of(&answer)); } Ok(found) } fn list(&mut self, table: &str, filter: &Map, limit: usize) -> Result<(u64, Vec<(String, Map)>), String> { let answer = list_answer(self.ctx, &args(json!({ "table": table, "where": filter, "limit": limit.max(1) })), Total::Counted) .map_err(|failure| failure.to_string())?; let mut rows = rows_of(&answer); rows.truncate(limit); Ok((answer["total"].as_u64().unwrap_or_default(), rows)) } fn active_project_slugs(&mut self) -> Vec { let mut slugs = Vec::new(); let mut page = Some(0_u64); while let Some(at) = page { let asked = json!({ "table": "project", "where": { "status": "active" }, "page": at, "limit": MAX_PAGE_SIZE }); let Ok(answer) = list_answer(self.ctx, &args(asked), Total::Skipped) else { break }; slugs.extend(rows_of(&answer).into_iter().filter_map(|(_, data)| data.get("slug")?.as_str().map(str::to_string))); page = answer["next_page"].as_u64().filter(|next| *next > at); } slugs } /// A page's list over a read is the phone's to draw; here it draws none. fn read(&mut self, name: &str, _args: &Map) -> Result { Err(format!("get_record reads no `read.{name}`")) } fn now(&mut self) -> Option> { Some(self.ctx.now) } fn definitions(&mut self) -> Vec { crate::definitions::shared_table_definitions(self.ctx).map(|found| found.definitions.clone()).unwrap_or_default() } fn handle_activity(&mut self, kind: &str, normalised: &str) -> Vec { handle_activity(self.ctx, kind, normalised) } } /// Where this database holds activity with a handle, one row per channel /// with its newest stamp: messages in a direct chat with a contact the /// handle names, or sent by one in a group, on their own channel; calls with /// the number (a WhatsApp call is WhatsApp's, any other a call); mail from /// or among the address. A database without one of these stores answers /// what the others hold. const HANDLE_ACTIVITY: &str = "WITH contacts AS ( SELECT contact_id FROM cotton_msg_contact_handles WHERE workspace_id = ?1 AND kind = ?2 AND value = ?3 ) SELECT m.channel AS channel, MAX(m.sent_at) AS at FROM cotton_msg_messages m JOIN cotton_msg_threads t ON t.id = m.thread_id WHERE m.workspace_id = ?1 AND m.deleted_at IS NULL AND t.trashed_at IS NULL AND ((t.kind = 'dm' AND t.contact_id IN (SELECT contact_id FROM contacts)) OR m.sender_participant_id IN (SELECT id FROM cotton_msg_thread_participants WHERE contact_id IN (SELECT contact_id FROM contacts))) GROUP BY m.channel"; const CALL_ACTIVITY: &str = "SELECT CASE WHEN provider = 'whatsapp' THEN 'whatsapp' ELSE 'call' END AS channel, MAX(started_at) AS at FROM cotton_call_log WHERE workspace_id = ?1 AND (handle = ?2 OR contact_id IN (SELECT contact_id FROM cotton_msg_contact_handles WHERE workspace_id = ?1 AND kind = 'phone' AND value = ?2)) GROUP BY 1"; static MAIL_ACTIVITY: std::sync::LazyLock = std::sync::LazyLock::new(|| { format!( "SELECT 'mail' AS channel, MAX(sent_at) AS at FROM cotton_emails WHERE workspace_id = ?1 AND {live_mail} AND (lower(from_email) = ?2 OR thread_id IN (SELECT thread_id FROM cotton_email_participants WHERE workspace_id = ?1 AND lower(email) = ?2))", live_mail = mail_predicate::live("") ) }); /// The evidence [`cotton_core::records::page::channels_for_handle`] orders, /// read from this database's own message, call and mail stores — the phone's /// `records.page` reads it through the same function. pub fn handle_activity(ctx: &Ctx<'_>, kind: &str, normalised: &str) -> Vec { use rusqlite::types::Value as Sql; let text = |value: &str| Sql::Text(value.to_string()); let workspace = text(ctx.workspace_id); let mut asks = vec![(HANDLE_ACTIVITY, vec![workspace.clone(), text(kind), text(normalised)])]; match kind { "phone" => asks.push((CALL_ACTIVITY, vec![workspace, text(normalised)])), "email" => asks.push((MAIL_ACTIVITY.as_str(), vec![workspace, text(&normalised.to_lowercase())])), _ => {} } let mut found = Vec::new(); for (sql, params) in asks { // A store this database does not keep holds no evidence. let Ok(rows) = ctx.read.driver().all(sql, ¶ms) else { continue }; found.extend(rows.iter().filter_map(|row| { Some(HandleActivity { channel: row.text("channel")?.to_string(), at: row.text("at")?.to_string() }) })); } found } /// The page of `table`'s record `id` standing on `view`, or why none could /// be made (the record itself still answers). pub fn page(ctx: &mut Ctx<'_>, table: &str, id: &str, view: Option<&str>) -> Result { let read = cotton_core::records::page::record_page_read(&mut CtxPages { ctx }, table, id, view)?; serde_json::to_value(read).map_err(|error| error.to_string()) }