Cotton code
257 lines · 10.1 KB · RustRaw
//! What a message and a chat SAY to the person reading them, as opposed to//! what the importer wrote down.//!//! An importer's body can be a MARKER — `[unsupported message]`,//! `[attachment: Asha.vcf]`, `[image omitted]` — honest, but addressed to//! whoever debugs the import. Every reader of the generic record reads//! (`cotton_tools::mcp::handlers::tables::chat_views`) says these words//! instead, so the chat list, a conversation and a kept message agree.//!//! Pure: no clock, no locale. English, the only supported language.use crate::transforms::note_title::plain_preview;use crate::import::normalize::UNSUPPORTED_MESSAGE_BODY;use crate::messages::preview::{preview_for_message, PreviewSource, not_in_export_preview};use crate::messages::media_only::{body_is_wordless, media_only_kind_of, media_only_words};use crate::messages::MessagePoll;/// What a deleted message says, everywhere.pub const DELETED_WORDS: &str = "This message was deleted";/// What a chat with nothing in it says where its last line would be.pub const NO_MESSAGES_WORDS: &str = "No messages";/// What a chat is called when nothing names it.pub const UNKNOWN_NAME: &str = "(unknown)";const PHOTO_ENDINGS: [&str; 6] = ["jpg", "jpeg", "png", "webp", "heic", "gif"];const VIDEO_ENDINGS: [&str; 4] = ["mp4", "mov", "3gp", "m4v"];const AUDIO_ENDINGS: [&str; 6] = ["opus", "ogg", "m4a", "mp3", "aac", "wav"];/// The words for a body that is only an importer's marker; `None` for a body/// somebody wrote.////// `[unsupported message]` is "Not included in the export"; `[attachment:/// name]` names the file by what it is ("Contact: Asha", "Photo", "Document ·/// name"); `[image omitted]` is "Image not included in the export".pub fn marker_words(body: &str) -> Option<String> {    let body = body.trim();    if body == UNSUPPORTED_MESSAGE_BODY {        return Some(not_in_export_preview());    }    let inner = body.strip_prefix('[')?.strip_suffix(']')?;    if inner.contains(['[', ']', '\n']) {        return None;    }    if inner == "attachment" {        return Some("Attachment".to_string());    }    if let Some(name) = inner.strip_prefix("attachment: ") {        let name = name.trim();        let (stem, ending) = match name.rsplit_once('.') {            Some((stem, ending)) => (stem.trim(), ending.to_lowercase()),            None => (name, String::new()),        };        let ending = ending.as_str();        return Some(if ending == "vcf" {            if stem.is_empty() { "Contact".to_string() } else { format!("Contact: {stem}") }        } else if PHOTO_ENDINGS.contains(&ending) {            "Photo".to_string()        } else if VIDEO_ENDINGS.contains(&ending) {            "Video".to_string()        } else if AUDIO_ENDINGS.contains(&ending) {            "Audio".to_string()        } else {            format!("Document · {name}")        });    }    if let Some(what) = inner.strip_suffix(" omitted") {        let what = what.trim();        let mut letters = what.chars();        let first = letters.next()?;        return Some(format!(            "{}{} not included in the export",            first.to_uppercase(),            letters.as_str()        ));    }    None}/// A stored last line as a chat's slip says it: a marker in its words, a/// blank one as "No messages", and Markdown read as prose — a message's body/// is Markdown (message.json), and a slip never shows the markers typed.pub fn list_line(stored: Option<&str>) -> String {    let line = stored.unwrap_or("").trim();    if line.is_empty() {        return NO_MESSAGES_WORDS.to_string();    }    marker_words(line).unwrap_or_else(|| plain_preview(line))}/// One message's line in a list of messages: the preview every surface/// writes, with a marker in its words and the body's Markdown read as prose/// (`**Saturday**` is "Saturday", a list's dashes are gone). A system line/// and a marker are left as they are: nobody typed Markdown into them.pub fn message_line(source: &PreviewSource<'_>) -> String {    let system = source.meta.and_then(|meta| meta.system.as_ref()).is_some_and(|system| system.is_truthy());    let plain = source        .body        .filter(|body| !system && marker_words(body).is_none())        .map(plain_preview);    let read = PreviewSource { body: plain.as_deref().or(source.body), ..source.clone() };    let line = preview_for_message(&read);    marker_words(&line).unwrap_or(line)}/// A poll as the words of its note: the question, then each option and its/// count.pub fn poll_words(poll: &MessagePoll) -> String {    let mut lines = vec![format!("Poll · {}", poll.question.trim())];    for option in &poll.options {        let votes = if option.votes.is_finite() && option.votes > 0.0 { option.votes as i64 } else { 0 };        let noun = if votes == 1 { "vote" } else { "votes" };        lines.push(format!("• {} — {votes} {noun}", option.text.trim()));    }    lines.join("\n")}/// The words of a message's note in its conversation.////// A deleted message says only that; a poll is its question and options; a/// marker beside media that IS drawn says nothing (the media is the message);/// a marker alone is its words; anything else is what was written.pub fn note_words(source: &PreviewSource<'_>) -> String {    if source.deleted_at.is_some_and(|at| !at.is_empty()) {        return DELETED_WORDS.to_string();    }    let body = source.body.unwrap_or("");    let system = source        .meta        .and_then(|meta| meta.system.as_ref())        .is_some_and(|system| system.is_truthy());    if system {        return body.to_string();    }    if let Some(poll) = source.meta.and_then(|meta| meta.poll.as_ref()) {        return poll_words(poll);    }    // A media-only message: drawn media is the message; with none drawn, its    // mark says what it carried, in the kit's words.    if let Some(kind) = media_only_kind_of(source.meta) {        if body_is_wordless(body, true) {            return if source.media.is_empty() { media_only_words(kind) } else { String::new() };        }    }    match marker_words(body) {        Some(_) if !source.media.is_empty() => String::new(),        Some(words) => words,        None => body.to_string(),    }}/// The name on a contact card shared as a message with nothing else in it/// (an importer's `[attachment: Asha.vcf]`): `Some("Asha")`, or `Some("")`/// for a card nobody named; `None` for any other body. A conversation draws/// it as a card, never as the words "Contact: Asha".pub fn shared_contact(body: &str) -> Option<String> {    let inner = body.trim().strip_prefix("[attachment: ")?.strip_suffix(']')?;    if inner.contains(['[', ']', '\n']) {        return None;    }    let (stem, ending) = inner.trim().rsplit_once('.')?;    (ending.eq_ignore_ascii_case("vcf")).then(|| stem.trim().to_string())}/// Whether a message is an ASIDE: a line about the conversation rather than/// something said in it — a deleted message, or one the export left out and/// carried no media for. A conversation writes an aside in pencil, never as/// a note somebody wrote. A system line, a poll, and a marker that names a/// thing (a contact, a document) are not asides.pub fn is_aside(source: &PreviewSource<'_>) -> bool {    if source.deleted_at.is_some_and(|at| !at.is_empty()) {        return true;    }    let system = source        .meta        .and_then(|meta| meta.system.as_ref())        .is_some_and(|system| system.is_truthy());    if system || source.meta.is_some_and(|meta| meta.poll.is_some()) || !source.media.is_empty() {        return false;    }    let body = source.body.unwrap_or("").trim();    body == UNSUPPORTED_MESSAGE_BODY        || body.strip_prefix('[').and_then(|inner| inner.strip_suffix(']')).is_some_and(|inner| {            !inner.contains(['[', ']', '\n']) && inner.ends_with(" omitted")        })}/// A dm's name: the person it is filed under, else the contact's own name,/// else the export's title, else the number, else another address, never/// blank and never a date.pub fn direct_name(    person: Option<&str>,    contact: Option<&str>,    title: Option<&str>,    phone: Option<&str>,    handle: Option<&str>,) -> String {    fn said(value: Option<&str>) -> Option<&str> {        value.map(str::trim).filter(|value| !value.is_empty())    }    if let Some(name) = said(person).or(said(contact)).or(said(title)) {        return name.to_string();    }    if let Some(phone) = said(phone) {        return crate::import::phone::phone_words(phone)            .unwrap_or_else(|| if phone.starts_with('+') { phone.to_string() } else { format!("+{phone}") });    }    said(handle).unwrap_or(UNKNOWN_NAME).to_string()}/// A group's name: its title, else its members' names (three, then how many/// more), never blank.pub fn group_name(title: Option<&str>, members: &[String]) -> String {    if let Some(title) = title.map(str::trim).filter(|title| !title.is_empty()) {        return title.to_string();    }    let named: Vec<&str> = members        .iter()        .map(|name| name.trim())        .filter(|name| !name.is_empty())        .collect();    if named.is_empty() {        return "(untitled group)".to_string();    }    let shown = named.iter().take(3).copied().collect::<Vec<_>>().join(", ");    if named.len() > 3 {        format!("{shown} +{}", named.len() - 3)    } else {        shown    }}/// Reactions as one handwritten line: each emoji once, in first-seen order,/// with its count past one ("❤️ 2 · 👍").pub fn reaction_line(emojis: &[String]) -> Option<String> {    let mut seen: Vec<(&str, usize)> = Vec::new();    for emoji in emojis.iter().map(|emoji| emoji.trim()).filter(|emoji| !emoji.is_empty()) {        match seen.iter_mut().find(|(known, _)| *known == emoji) {            Some((_, count)) => *count += 1,            None => seen.push((emoji, 1)),        }    }    if seen.is_empty() {        return None;    }    Some(        seen.iter()            .map(|(emoji, count)| if *count > 1 { format!("{emoji} {count}") } else { (*emoji).to_string() })            .collect::<Vec<_>>()            .join(" · "),    )}#[cfg(test)]#[path = "display_tests.rs"]mod tests;