Cotton code
223 lines · 11.9 KB · RustRaw
//! `chat.notices {}`: what this phone's notifications should be now, read//! from its own copy (the rules are `cotton_core::messages::app::notices`).//!//! The shell asks after anything that could change them — a push landed, a//! socket frame, `chat.act read`, a sync, the app coming to the front — and//! makes its shade match the answer: so a notification goes once its chat is//! read here, on another of the person's phones (their read arrives as a//! receipt from their own device, `cotton_chat::apply_receipt`), or by its own//! Mark as read.//!//! "Unread" here is the message's own: theirs, live, not trashed, with no//! `read_at`, past the conversation's `read_seq` (or with no sequence yet: a//! message just landed from a push has none until the copy syncs).//!//! A missed call stays noticed until this phone's Calls list is opened//! (`chat.calls` with no `after`), or the chat with them is read, after it;//! what was seen when is this phone's own (`chat-notices.json` beside the//! copy), never synced.use std::collections::HashMap;use rusqlite::types::Value as SqlValue;use serde_json::{json, Map, Value};use cotton_core::messages::app::bubble::{self, Row};use cotton_core::messages::app::lay;use cotton_core::messages::app::list::{self, say};use cotton_core::messages::app::notices::{self as rules, MessageFacts, MissedFacts, NoticesAnswer, ThreadFacts};use cotton_core::messages::app::shapes::Picture;use cotton_core::messages::unread::is_muted;use cotton_tools::mcp::dispatch::Ctx;use super::super::chat_calls;use super::super::cotton_chat::{self, one, rows, ws, MESSAGES, THREADS};use super::{media_of, meta_of, ms, names, read, s, summaries, text, truthy, Clock, CONTACTS};use crate::methods::MethodError;use crate::shell::client::ClientController;/// What this phone saw when, beside the copy.const SEEN_FILE: &str = "chat-notices.json";/// The most unread messages one answer reads, newest first.const READ_MAX: usize = 400;/// A missed call older than this is no longer said.const MISSED_FOR_MS: i64 = 7 * 24 * 3_600_000;fn seen(client: &ClientController) -> Value {    std::fs::read(client.layout().client_dir().join(SEEN_FILE)).ok().and_then(|b| serde_json::from_slice(&b).ok()).unwrap_or_else(|| json!({}))}fn keep_seen(client: &ClientController, seen: &Value) {    let path = client.layout().client_dir().join(SEEN_FILE);    if let Some(parent) = path.parent() {        let _ = std::fs::create_dir_all(parent);    }    // not a copy: the notices seen.    let _ = std::fs::write(path, seen.to_string());}/// The chat with them read here: its missed calls are seen.pub(crate) fn seen_thread(client: &ClientController, thread: &str) {    let mut kept = seen(client);    if !kept["threads"].is_object() {        kept["threads"] = json!({});    }    kept["threads"][thread] = json!(cotton_chat::now_ms(client));    keep_seen(client, &kept);}/// This phone's Calls list opened: every missed call so far is seen.pub(crate) fn seen_calls(client: &ClientController) {    let mut kept = seen(client);    kept["calls"] = json!(cotton_chat::now_ms(client));    keep_seen(client, &kept);}/// The picture's file on this phone, when it is here.fn photo_path(ctx: &mut Ctx<'_>, key: Option<&str>) -> Option<String> {    let key = key?;    super::super::media::local_path_of(ctx.db(), key).filter(|p| p.exists()).map(|p| p.to_string_lossy().to_string())}pub(crate) fn answer(client: &ClientController) -> Result<NoticesAnswer, MethodError> {    let lines = list::lines();    let clock = Clock::of(client);    let now = clock.now.timestamp_millis();    let you = say(&lines, "app.list.you", &[]);    let kept = seen(client);    let calls_seen = kept["calls"].as_i64().unwrap_or(0);    let threads_seen: HashMap<String, i64> = kept["threads"].as_object().map(|m| m.iter().filter_map(|(k, v)| Some((k.clone(), v.as_i64()?))).collect()).unwrap_or_default();    let ns = cotton_chat::namespace(client).ok();    // Who he is, for a mention of him in a muted chat: his number as this phone knows it, and his own name.    let me = cotton_chat::own_number(client);    let my_name = me.as_ref().and_then(|_| crate::phone::chat_people::own_profile(client)).and_then(|p| p.name);    let (threads, missed) = read(client, "chat.notices", |ctx| {        let unread = rows(            ctx,            &format!(                "SELECT m.id, m.thread_id, m.direction, m.body, m.media, m.meta, m.mentions, m.sent_at, m.sender_participant_id, m.deleted_at, m.channel, m.origin                   FROM {MESSAGES} m JOIN {THREADS} t ON t.id = m.thread_id                  WHERE m.workspace_id = ? AND t.trashed_at IS NULL AND m.channel IN ('cotton', 'sms')                    AND m.direction = 'in' AND m.origin = 'live' AND m.read_at IS NULL AND m.trashed_at IS NULL AND m.hidden_at IS NULL                    AND (m.seq IS NULL OR m.seq > coalesce(t.read_seq, 0))                    AND (t.cleared_before IS NULL OR m.sent_at > t.cleared_before)                  ORDER BY m.sent_at DESC LIMIT {READ_MAX}"            ),            &[ws(ctx)],        )?;        // A call's centred line is the copy's own, never a message of theirs.        // A blocked sender's texts stand only in Blocked and say nothing (SENDERS.md; DECISIONS "SMS on Android").        let hidden = super::senders::hidden_threads(ctx)?;        let unread: Vec<Map<String, Value>> = unread            .into_iter()            .filter(|m| !cotton_chat::meta_value(m.get("meta").unwrap_or(&Value::Null))["system"].as_bool().unwrap_or(false))            .filter(|m| !m.get("thread_id").and_then(Value::as_str).is_some_and(|t| hidden.contains(t)))            .collect();        let mut by_thread: HashMap<String, Vec<Map<String, Value>>> = HashMap::new();        for m in unread {            if let Some(thread) = s(&m, "thread_id") {                by_thread.entry(thread).or_default().push(m);            }        }        let mut threads = Vec::new();        if !by_thread.is_empty() {            let all = summaries(ctx, None)?;            let wanted: Vec<_> = all.iter().filter(|t| by_thread.contains_key(&t.id)).collect();            let named = names(ctx, &wanted, &you)?;            for t in wanted {                let mut theirs = by_thread.remove(&t.id).unwrap_or_default();                theirs.reverse();                let first_at = theirs.first().and_then(|m| s(m, "sent_at")).unwrap_or_default();                // The person's own written after the first unread of theirs (a reply sent from the notification).                let mine = rows(                    ctx,                    &format!("SELECT id, thread_id, direction, body, media, meta, sent_at, deleted_at FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND direction = 'out' AND trashed_at IS NULL AND sent_at > ? ORDER BY sent_at DESC LIMIT {}", rules::LINES_MAX),                    &[ws(ctx), text(t.id.clone()), text(first_at)],                )?;                let mut all_lines: Vec<(bool, Map<String, Value>)> = theirs.into_iter().map(|m| (false, m)).chain(mine.into_iter().map(|m| (true, m))).collect();                all_lines.sort_by_key(|(_, m)| (s(m, "sent_at").unwrap_or_default(), s(m, "id").unwrap_or_default()));                let n = named.get(&t.id).cloned().unwrap_or_default();                let messages = all_lines                    .iter()                    .map(|(mine, m)| {                        let media = media_of(m);                        let meta = meta_of(m);                        let deleted = s(m, "deleted_at");                        let r = Row { body: m.get("body").and_then(Value::as_str), media: &media, meta: meta.as_ref(), deleted_at: deleted.as_deref() };                        let sender = if t.group && !mine { s(m, "sender_participant_id").and_then(|seat| n.seats.get(&seat).map(|(name, _)| name.clone())) } else { None };                        let mentions: Vec<String> = match m.get("mentions") {                            Some(Value::Array(items)) => items.iter().filter_map(Value::as_str).map(str::to_string).collect(),                            Some(Value::String(text)) => serde_json::from_str(text).unwrap_or_default(),                            _ => Vec::new(),                        };                        let mentions_me = !*mine && me.as_deref().is_some_and(|me| rules::mentions_me(m.get("body").and_then(Value::as_str).unwrap_or_default(), &mentions, me, my_name.as_deref()));                        MessageFacts { id: s(m, "id").unwrap_or_default(), at: ms(&s(m, "sent_at").unwrap_or_default()), mine: *mine, sender, text: bubble::line_of(&r), mentions_me }                    })                    .collect();                let blocked = match &t.contact {                    Some(contact) => one(ctx, &format!("SELECT * FROM {CONTACTS} WHERE workspace_id = ? AND id = ?"), &[ws(ctx), text(contact.clone())])?.is_some_and(|c| truthy(&c, "blocked")),                    None => false,                };                threads.push(ThreadFacts {                    thread: t.id.clone(),                    picture: Picture { photo: n.photo.clone(), initials: lay::initials(&n.name), tint: lay::tint(&t.id) },                    photo_path: photo_path(ctx, n.photo.as_deref()),                    name: n.name.clone(),                    group: t.group,                    request: t.request.as_deref() == Some("pending"),                    muted: is_muted(t.muted_until.as_deref(), &clock.now_iso()),                    blocked,                    messages,                });            }        }        let missed = missed_calls(ctx, ns.as_deref(), now, calls_seen, &threads_seen)?;        Ok((threads, missed))    })?;    Ok(rules::notices(&lines, &threads, &missed))}/// The missed calls not yet seen on this phone, at most a week old.fn missed_calls(ctx: &mut Ctx<'_>, ns: Option<&str>, now: i64, calls_seen: i64, threads_seen: &HashMap<String, i64>) -> Result<Vec<MissedFacts>, String> {    if !cotton_chat::holds(ctx, chat_calls::CALLS, "meta")? {        return Ok(Vec::new());    }    let since = cotton_chat::iso(calls_seen.max(now - MISSED_FOR_MS));    let found = rows(ctx, &format!("SELECT * FROM {} WHERE workspace_id = ? AND source = 'cotton' AND started_at > ? ORDER BY started_at DESC LIMIT 50", chat_calls::CALLS), &[ws(ctx), SqlValue::Text(since)])?;    let mut out = Vec::new();    for row in found {        let facts = chat_calls::facts_of(&row);        if !facts.missed || facts.group {            continue;        }        let at = ms(&s(&row, "started_at").unwrap_or_default());        let chat = cotton_chat::meta_value(row.get("meta").unwrap_or(&Value::Null))["chat"].clone();        let number = s(&row, "handle").or_else(|| chat["numbers"][0].as_str().map(str::to_string));        let thread = chat["thread"].as_str().map(str::to_string).or_else(|| Some(super::cotton_chat::chat_with(ctx, ns?, number.as_deref()?).ok()?));        if thread.as_ref().and_then(|t| threads_seen.get(t)).is_some_and(|seen| *seen >= at) {            continue;        }        let numbers: Vec<String> = number.iter().cloned().collect();        let who = chat_calls::who(ctx, &numbers)?;        let (name, photo) = number.as_ref().and_then(|n| who.get(n)).map_or_else(|| (number.clone().unwrap_or_default(), None), |w| (w.name.clone(), w.photo.clone()));        let thread = match thread {            Some(id) if cotton_chat::exists(ctx, THREADS, &id)? => Some(id),            _ => None,        };        let key = thread.clone().or(number.clone()).unwrap_or_else(|| s(&row, "id").unwrap_or_default());        out.push(MissedFacts {            call: s(&row, "id").unwrap_or_default(),            picture: Picture { photo: photo.clone(), initials: lay::initials(&name), tint: lay::tint(&key) },            photo_path: photo_path(ctx, photo.as_deref()),            name,            thread,            video: facts.video,            at,        });    }    Ok(out)}#[cfg(test)]#[path = "chat_notices_tests.rs"]mod tests;