Cotton code
284 lines · 11.1 KB · RustRaw
//! Cotton Chat's notifications, as the phones post them//! (20 Nov 2026): `chat.notices` answers every notification this phone should//! be showing now, and the phone makes its notification shade match it —//! posts what is new, updates what changed, and takes away every one of its//! own that is no longer listed. That one rule is how a notification clears//! once its chat is read anywhere: here, on another phone of the person's//! (their read lands here as a receipt from their own device), or by the//! notification's own Mark as read.//!//! The rules are pure: the SQL that gathers the facts is `cotton-ffi`'s//! (`phone::chat_app`'s `notices`). Nothing here reads a store or a clock.//!//! * A conversation is noticed while it holds something of theirs unread, it//!   is not muted, and its person is not blocked.//! * A stranger's request says the chat set's "New message" alone: never who,//!   never what, and no picture (a stranger's words never reach the lock//!   screen).//! * The lines are the newest of theirs that are unread (at most//!   [`LINES_MAX`]), and the person's own written after the first of them (a//!   reply sent from the notification shows as theirs, "You").//! * A missed call is noticed until this phone's Calls list is opened, or the//!   chat with them is read, after it.use serde::{Deserialize, Serialize};use super::list::say;use super::shapes::Picture;use crate::rules::shell_lines::LineSet;/// The most lines one conversation's notification carries.pub const LINES_MAX: usize = 6;/// One conversation's facts, as the copy holds them.#[derive(Debug, Clone, PartialEq)]pub struct ThreadFacts {    pub thread: String,    /// The name Chat calls the conversation by (its person, the contact, the number, a group's name).    pub name: String,    pub picture: Picture,    /// The picture's file on this phone, when it is here.    pub photo_path: Option<String>,    pub group: bool,    /// A stranger's request not yet answered.    pub request: bool,    pub muted: bool,    pub blocked: bool,    /// Its unread messages from them and the person's own after the first, oldest first.    pub messages: Vec<MessageFacts>,}#[derive(Debug, Clone, Default, PartialEq)]pub struct MessageFacts {    pub id: String,    /// Milliseconds since the epoch.    pub at: i64,    pub mine: bool,    /// In a group, the sender's name; else none.    pub sender: Option<String>,    /// The message as one line ("Photo" for a photo alone).    pub text: String,    /// It mentions him ([`mentions_me`]): a muted chat still notices it.    pub mentions_me: bool,}/// Whether a message of theirs mentions him (the owner, 24 Nov 2026: in a muted group he would still expect to hear/// when someone mentions him, as WhatsApp does): its `mentions` hold his number, or its words say `@` and his/// number or his name as a mention ([`crate::messages::mentions`]'s scanner, so what is highlighted and what rings/// never drift apart). `me` is his number, with or without `+`.pub fn mentions_me(body: &str, mentions: &[String], me: &str, my_name: Option<&str>) -> bool {    let my_digits: String = me.chars().filter(char::is_ascii_digit).collect();    if my_digits.is_empty() {        return false;    }    if mentions.iter().any(|m| m.chars().filter(char::is_ascii_digit).collect::<String>() == my_digits) {        return true;    }    let mut candidates = vec![        crate::messages::mentions::MentionCandidate { phone: my_digits.clone(), name: my_digits.clone() },        crate::messages::mentions::MentionCandidate { phone: my_digits.clone(), name: format!("+{my_digits}") },    ];    if let Some(name) = my_name.map(str::trim).filter(|n| !n.is_empty()) {        candidates.push(crate::messages::mentions::MentionCandidate { phone: my_digits.clone(), name: name.to_string() });    }    !crate::messages::mentions::extract_mentions(body, &candidates).is_empty()}/// One missed call's facts.#[derive(Debug, Clone, PartialEq)]pub struct MissedFacts {    pub call: String,    pub thread: Option<String>,    pub name: String,    pub picture: Picture,    pub photo_path: Option<String>,    pub video: bool,    pub at: i64,}/// `chat.notices {}` → what this phone's notification shade should hold.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct NoticesAnswer {    /// One per conversation, newest first. Post each under its `thread`    /// (Android: the notification's tag; iPhone: its thread identifier), and    /// take away every chat notification of this phone's that is not here.    pub notices: Vec<Notice>,    /// The missed calls to say, newest first; one notification each, under    /// its `call`; take away every missed-call notification not here.    pub missed: Vec<Missed>,    pub words: NoticeWords,}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct Notice {    pub thread: String,    /// The conversation's name; "New message" for a request.    pub title: String,    /// Initials and tint always; `photo` is the picture's media key.    pub picture: Picture,    /// The picture's file on this phone, when it is here: draw it as the    /// sender's picture (MessagingStyle's Person icon, INPerson's image).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub photo_path: Option<String>,    pub group: bool,    pub request: bool,    /// Oldest first. Empty for a request: say `title` alone.    pub lines: Vec<NoticeLine>,    /// How many of theirs are unread (the lines may be fewer).    pub unread: u32,    /// The newest line's time, ms: the notification's `when`.    pub at: i64,    /// Reply and Mark as read may be offered (not on a request, which is    /// answered in the chat: Accept, Block, Delete).    pub actions: bool,    /// A stable key for the conversation's shortcut and the phone's    /// communication notification (Android's shortcut id, iPhone's    /// conversation identifier).    pub key: String,}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct NoticeLine {    pub id: String,    /// Who said it: none for the other person of a one-to-one (draw the    /// notice's own person), "You" for the person's own, a member's name in a group.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub from: Option<String>,    pub mine: bool,    pub text: String,    pub at: i64,}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct Missed {    pub call: String,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub thread: Option<String>,    /// "Missed voice call", "Missed video call".    pub title: String,    /// Who: the person's name as Chat says it.    pub text: String,    pub picture: Picture,    #[serde(default, skip_serializing_if = "Option::is_none")]    pub photo_path: Option<String>,    pub video: bool,    pub at: i64,    /// "Call back": `chat.call {call}`.    pub back: String,}/// The words the notifications need beyond each notice's own.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct NoticeWords {    /// The messages channel's name ("Chat").    pub channel: String,    /// The missed calls channel's name.    pub missed_channel: String,    pub reply: String,    /// The reply field's hint.    pub reply_hint: String,    pub mark_read: String,    /// The person themself, in MessagingStyle and as a line's `from`.    pub you: String,    /// What a notification says when the phone could not read its message (a box that did not open in time).    pub new_message: String,}pub fn words(lines: &LineSet) -> NoticeWords {    NoticeWords {        channel: say(lines, "push.channel", &[]),        missed_channel: say(lines, "app.notice.missed_channel", &[]),        reply: say(lines, "app.notice.reply", &[]),        reply_hint: say(lines, "app.notice.reply_hint", &[]),        mark_read: say(lines, "app.notice.mark_read", &[]),        you: say(lines, "app.list.you", &[]),        new_message: say(lines, "push.title", &[]),    }}/// One conversation's notice, or none when it should show nothing.pub fn notice(lines: &LineSet, facts: &ThreadFacts) -> Option<Notice> {    // A mention of him overrides mute (never a block): the chat stays quiet for everything else.    if facts.blocked || (facts.muted && !facts.messages.iter().any(|m| !m.mine && m.mentions_me)) {        return None;    }    let first_theirs = facts.messages.iter().position(|m| !m.mine)?;    let unread = facts.messages.iter().filter(|m| !m.mine).count() as u32;    let at = facts.messages.iter().map(|m| m.at).max().unwrap_or(0);    if facts.request {        let title = say(lines, "push.title", &[]);        return Some(Notice {            thread: facts.thread.clone(),            picture: Picture { photo: None, initials: String::new(), tint: facts.picture.tint },            photo_path: None,            title,            group: false,            request: true,            lines: Vec::new(),            unread,            at,            actions: false,            key: facts.thread.clone(),        });    }    let you = say(lines, "app.list.you", &[]);    let after: Vec<&MessageFacts> = facts.messages[first_theirs..].iter().collect();    // The newest LINES_MAX, kept in order.    let skip = after.len().saturating_sub(LINES_MAX);    let lines_out = after        .into_iter()        .skip(skip)        .map(|m| NoticeLine {            id: m.id.clone(),            from: if m.mine { Some(you.clone()) } else if facts.group { m.sender.clone() } else { None },            mine: m.mine,            text: m.text.clone(),            at: m.at,        })        .collect();    Some(Notice {        thread: facts.thread.clone(),        title: facts.name.clone(),        picture: facts.picture.clone(),        photo_path: facts.photo_path.clone(),        group: facts.group,        request: false,        lines: lines_out,        unread,        at,        actions: true,        key: facts.thread.clone(),    })}/// Every notice, newest first.pub fn notices(lines: &LineSet, threads: &[ThreadFacts], missed: &[MissedFacts]) -> NoticesAnswer {    let mut notices: Vec<Notice> = threads.iter().filter_map(|t| notice(lines, t)).collect();    notices.sort_by(|a, b| b.at.cmp(&a.at).then_with(|| a.thread.cmp(&b.thread)));    let mut missed: Vec<Missed> = missed.iter().map(|m| missed_notice(lines, m)).collect();    missed.sort_by(|a, b| b.at.cmp(&a.at).then_with(|| a.call.cmp(&b.call)));    NoticesAnswer { notices, missed, words: words(lines) }}pub fn missed_notice(lines: &LineSet, facts: &MissedFacts) -> Missed {    Missed {        call: facts.call.clone(),        thread: facts.thread.clone(),        title: say(lines, if facts.video { "app.call.missed.video" } else { "app.call.missed.voice" }, &[]),        text: facts.name.clone(),        picture: facts.picture.clone(),        photo_path: facts.photo_path.clone(),        video: facts.video,        at: facts.at,        back: say(lines, "app.call.back", &[]),    }}#[cfg(test)]#[path = "notices_tests.rs"]mod tests;