Cotton code
282 lines · 11.9 KB · RustRaw
//! What a conversation's last line SAYS in a list (spec §7.2), and the guard that//! decides whether it may move at all.//!//! The port of `packages/core/src/messages/preview.ts`.//!//! One implementation, because three surfaces read it: the chat list row, the//! thread denorm the relay writes into every member's file, and the push body.//! Three spellings of "Voice message · 0:12" would drift//! within a release — and the one that mattered was a lock screen saying "Photo"//! beside a list row saying "Voice message · 0:12", for the same message.//!//! Pure: no clock, no locale, no i18n. The strings are English (the only//! supported language) and are deliberately NOT Lingui macros — this module is//! imported by the server, which has no catalog.//!//! **The 140-character cap is in UTF-16 code units**, because//! `String.prototype.slice` counts them. Ported through//! [`super::slice_utf16`]; a cut at a code point or a byte would be a different//! string the first time somebody sends an emoji.use crate::messages::media_only::{body_is_wordless, media_only_kind_of, media_only_words};use crate::messages::{slice_utf16, truthy_number, truthy_str, MessageMedia, MessageMediaKind, MessageMeta};/// `MESSAGE_PREVIEW_MAX` — a list line's cap, in UTF-16 code units/// (re-exported by `cotton-core`'s `messages::limits`).pub const MESSAGE_PREVIEW_MAX: usize = 140;/// The body the WhatsApp text importer writes for a blank sender line/// (re-exported by `cotton-core`'s `import::normalize`).pub const UNSUPPORTED_MESSAGE_BODY: &str = "[unsupported message]";/// What a WhatsApp text export's blank sender line says in a list.////// The importer writes `[unsupported message]` for it — a MARKER, honest but/// addressed to whoever debugs the import, not to the person reading their own/// chat list. The row is real (a sticker, a location pin, a view-once photo) and/// it stays; what it SAYS is this. The phantom rows an album left behind are a/// different matter and migration v36 deletes them outright.pub fn not_in_export_preview() -> String {    crate::lines::resolve("conversation", "preview.not_in_export", &[])}/// The two spellings a `.vcf` arrives under. `x-vcard` is the older one.const VCARD_TYPES: [&str; 2] = ["text/vcard", "text/x-vcard"];/// The message columns a preview reads. The CALLER holds the row.#[derive(Debug, Clone, Default, PartialEq)]pub struct PreviewSource<'a> {    pub body: Option<&'a str>,    pub media: &'a [MessageMedia],    /// Set ⇒ the row says one thing and one thing only.    pub deleted_at: Option<&'a str>,    pub meta: Option<&'a MessageMeta>,}/// What an attachment is, for a renderer that has to choose a shape.////// An explicit `kind` wins; otherwise the content type decides. There is no third/// guess — an entry whose type says nothing is a `file`, which renders as a named/// chip and is always honest.////// vCard MIME types identify shared contact cards when no display kind is stored.pub fn media_kind_of(entry: &MessageMedia) -> MessageMediaKind {    if let Some(kind) = entry.kind {        return kind;    }    // `toLowerCase()` is a full Unicode fold in JavaScript and in Rust alike; a    // MIME type is ASCII in every row this reads, and the fold is applied to the    // whole string on both sides rather than per prefix.    let content_type = entry.content_type.to_lowercase();    if VCARD_TYPES.contains(&content_type.as_str()) {        return MessageMediaKind::Contact;    }    if content_type.starts_with("image/") {        return MessageMediaKind::Image;    }    if content_type.starts_with("video/") {        return MessageMediaKind::Video;    }    // An Ogg Opus recording is a WhatsApp voice note (PTT-….opus, …-AUDIO-….opus):    // WhatsApp records its voice notes so and an export keeps them so, while an    // audio FILE shared in a chat keeps its own format. The importer already    // treats every Ogg Opus as a voice note (its m4a rendition, Storage's    // "voice"); read the same way here, so an imported note gets the voice    // player, its list line and its waveform (CONTRACT "Voice player").    if matches!(content_type.split(';').next().unwrap_or("").trim(), "audio/ogg" | "audio/opus") {        return MessageMediaKind::Voice;    }    if content_type.starts_with("audio/") {        return MessageMediaKind::Audio;    }    MessageMediaKind::File}/// `m:ss`, or `h:mm:ss` past an hour. A bad number reads as zero, never NaN.////// The ONE way a length is written, for the chat list's line and the bubble alike/// (`messages::app::lay::length` calls this): rounded UP to the whole second, from/// the whole millisecond, so 2.4 s is 0:03 and only nothing is 0:00. Up, because/// both phones' players count down what is left rounded up: a note at rest says/// what its countdown starts from. Before (23 Nov 2026), the list floored and the/// bubble rounded, and a 2.6 s voice note read "Voice message · 0:02" in the list/// and 0:03 in its chat.////// Takes an `f64` because the column is a JSON number: an infinity or a NaN that/// reached a row must render as `0:00` rather than as a panic or an overflow.pub fn format_duration(ms: f64) -> String {    let total = if ms.is_finite() && ms > 0.0 {        (ms.round() / 1000.0).ceil()    } else {        0.0    };    // A duration past i64 is not a duration; the TypeScript would carry the float    // into `%` and print something nobody can read, so this saturates instead of    // wrapping. No row can reach it — 2⁶³ ms is 292 million years.    let total = if total >= i64::MAX as f64 {        i64::MAX    } else {        total as i64    };    let seconds = total % 60;    let minutes = (total / 60) % 60;    let hours = total / 3600;    if hours == 0 {        format!("{minutes}:{seconds:02}")    } else {        format!("{hours}:{minutes:02}:{seconds:02}")    }}/// The word for each kind, as an exhaustive `match` rather than a lookup table:/// the TypeScript declares `MEDIA_WORDS` as a `Record<MessageMediaKind, string>`,/// which is TOTAL over the union, so a kind added without a word must fail the/// BUILD here rather than render as `undefined` in somebody's chat list.fn media_word(kind: MessageMediaKind) -> String {    let key = match kind {        MessageMediaKind::Image => "preview.photo",        MessageMediaKind::Video => "preview.video",        MessageMediaKind::Audio => "preview.audio",        MessageMediaKind::Voice => "preview.voice",        MessageMediaKind::File => "preview.document",        MessageMediaKind::Contact => "preview.contact",    };    crate::lines::resolve("conversation", key, &[])}/// The word for an attachment, with the detail its kind carries.fn word_for(entry: &MessageMedia) -> String {    let kind = media_kind_of(entry);    let word = media_word(kind);    if kind == MessageMediaKind::Voice {        if let Some(duration) = truthy_number(entry.duration_ms) {            return format!("{word} · {}", format_duration(duration));        }    }    if kind == MessageMediaKind::File {        if let Some(name) = truthy_str(entry.name.as_deref()) {            return format!("{word} · {name}");        }    }    // Whose card it is, not what the file is called: `Rahul.vcf` says nothing a    // person scanning a list can use.    if kind == MessageMediaKind::Contact {        let who = entry            .contact            .as_ref()            .map(|contact| contact.name.as_str())            .or(entry.name.as_deref());        return match truthy_str(who) {            Some(who) => format!("{word}: {who}"),            None => word,        };    }    word}/// Whitespace collapses: a preview is one line, whatever the body did.////// `text.replace(/\s+/g, " ").trim()` in ECMAScript's whitespace class, which/// includes U+FEFF and excludes U+0085 — the store's own helper, so a body with a/// BOM in it previews identically on both sides.fn one_line(text: &str) -> String {    crate::js::collapse_whitespace_and_trim(text)}/// The list's line for one message.////// Order matters and is the spec's: deleted outranks everything (the row's/// content is gone and saying otherwise would be a lie), a system line is its own/// words, and an album is named by its FIRST entry — "Photo", not "3 photos",/// because the row is 72 points tall and the count belongs in the bubble.pub fn preview_for_message(source: &PreviewSource<'_>) -> String {    // `if (source.deletedAt)` is a truthiness test: an empty string is not a    // deletion, and a row whose column came back `''` still says what was said.    if source.deleted_at.is_some_and(|at| !at.is_empty()) {        return crate::lines::resolve("conversation", "preview.deleted", &[]);    }    let body = one_line(&crate::note_title::plain_preview(source.body.unwrap_or("")));    if source        .meta        .and_then(|meta| meta.system.as_ref())        .is_some_and(|system| system.is_truthy())    {        return slice_utf16(&body, MESSAGE_PREVIEW_MAX);    }    // A poll's body is the export's own multi-line rendering — "POLL:", the    // question, then every option and its count. One line of that says nothing,    // so the question is the line.    if let Some(poll) = source.meta.and_then(|meta| meta.poll.as_ref()) {        return slice_utf16(            &crate::lines::resolve("conversation", "preview.poll", &[("question", &one_line(&poll.question))]),            MESSAGE_PREVIEW_MAX,        );    }    // A media-only message's body is empty and its mark says what it carried;    // an old row's left-behind label reads as empty too.    let marked = media_only_kind_of(source.meta);    let body = if marked.is_some() && body_is_wordless(&body, true) { String::new() } else { body };    let Some(first) = source.media.first() else {        if let (true, Some(kind)) = (body.is_empty(), marked) {            return slice_utf16(&media_only_words(kind), MESSAGE_PREVIEW_MAX);        }        if body == UNSUPPORTED_MESSAGE_BODY {            return not_in_export_preview();        }        return slice_utf16(&body, MESSAGE_PREVIEW_MAX);    };    let word = word_for(first);    let line = if body.is_empty() {        word    } else {        format!("{word} · {body}")    };    slice_utf16(&line, MESSAGE_PREVIEW_MAX)}/// The two-argument form the pre-chat services call. Kept so a caller that only/// ever had a body and a media array does not have to build a struct; it/// delegates, so there is still one rule.pub fn message_preview(body: Option<&str>, media: &[MessageMedia]) -> String {    preview_for_message(&PreviewSource {        body,        media,        ..PreviewSource::default()    })}/// The denorm guard, ported from the Postgres AFTER trigger: an out-of-order row/// changes nothing. Without it, importing five-year-old messages would drag a live/// thread's preview back into 2021 — and with the relay writing into N files, a/// mirror arriving late would do the same to every member.////// The comparison is a STRING comparison, deliberately: both values are ISO/// instants written by the store's timestamp codec, which pads every field, so/// lexicographic order IS chronological order and no parse can fail in the middle/// of a write. JavaScript compares UTF-16 code units and Rust compares UTF-8/// bytes; over the ASCII these columns hold, the two orders are identical.pub fn should_advance_thread(last_message_at: Option<&str>, sent_at: &str) -> bool {    match last_message_at {        // `!lastMessageAt` is truthiness, so an EMPTY string is "no last message"        // and not "the earliest possible one".        None | Some("") => true,        Some(last) => sent_at >= last,    }}/// The same rule under the name the UI tracks import it by.////// [`preview_for_message`] takes a structural source; this takes "a message" —/// same rule, two names, no second implementation.pub fn message_preview_text(row: &PreviewSource<'_>) -> String {    preview_for_message(row)}#[cfg(test)]#[path = "preview_tests.rs"]mod tests;