Cotton code
442 lines · 15.9 KB · RustRaw
//! What a mail body is stored as: the quoted reply history cut, the ceiling,//! the one-line preview, and HTML read as text.//!//! Copied, with their tests, from `cotton-tools`' `emails::engine_shim` and//! `emails::shared` and `cotton-server`'s `google::gmail_message` (the server//! crate retires on its own), so a message read here is stored as the old//! ingest stored it.//!//! A reply carries the whole conversation below it — the client pastes the//! prior thread under the new words. Every email is its own row, so that//! pasted history is pure duplication. The cut is deliberately conservative://! only at unambiguous, client-generated quote boundaries, and the body comes//! back UNCHANGED when there is none. Idempotent.use regex::Regex;use std::sync::OnceLock;/// A run of underscores/dashes on its own line — the divider Outlook/OWA and/// Gmail-web insert just before the quoted `From:` header.fn divider() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| Regex::new(r"^\s*[_-]{5,}\s*$").expect("a literal pattern"))}/// "-----Original Message-----" (Outlook, no divider line of its own).fn original_message() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| {        Regex::new(r"(?i)^\s*-{2,}\s*original message\s*-{2,}\s*$").expect("a literal pattern")    })}fn header_from() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| Regex::new(r"^\s*>?\s*From:\s?\S").expect("a literal pattern"))}fn header_sent_or_date() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| Regex::new(r"^\s*>?\s*(Sent|Date):\s?\S").expect("a literal pattern"))}/// The start of a Gmail-style attribution: `On <something>`.fn on_start() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| Regex::new(r"^\s*>?\s*On\b").expect("a literal pattern"))}fn wrote_end() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| Regex::new(r"\bwrote:\s*$").expect("a literal pattern"))}/// A `>`-quoted line — the plain-text quoting convention.fn quoted_line() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| Regex::new(r"^\s*>").expect("a literal pattern"))}/// How many lines a wrapped `On … wrote:` attribution may span.const ON_WRAP_LOOKAHEAD: usize = 4;/// The 0-based index of the first line that begins quoted history, or `None`/// when the body carries none. Scans top-down and answers the earliest/// boundary.fn quote_boundary(lines: &[&str]) -> Option<usize> {    for (index, line) in lines.iter().enumerate() {        if divider().is_match(line) || original_message().is_match(line) {            return Some(index);        }        // Outlook header block with no divider: `From:` immediately (within two        // lines) followed by `Sent:`/`Date:` — the PAIR, so a sentence that        // merely starts "From the data…" is never mistaken for a header.        if header_from().is_match(line) {            for offset in 1..=2 {                if let Some(next) = lines.get(index + offset) {                    if header_sent_or_date().is_match(next) {                        return Some(index);                    }                }            }        }        // Gmail attribution. Require the terminal `wrote:` (on this line or        // within a short wrap) so ordinary prose beginning "On Monday…" is        // never cut.        if on_start().is_match(line) {            let mut joined = (*line).to_string();            let end = (index + ON_WRAP_LOOKAHEAD).min(lines.len());            for (step, next) in lines[index..end].iter().enumerate() {                if step > 0 {                    joined = format!("{joined} {next}");                }                if wrote_end().is_match(joined.trim_end()) {                    return Some(index);                }            }        }        // A contiguous quoted region: the first `>`-prefixed line.        if quoted_line().is_match(line) {            return Some(index);        }    }    None}/// `body` with any trailing quoted-reply history removed.////// Unchanged when there is no quote boundary. When it cuts, it keeps everything/// above the boundary and trims trailing blank space. Never answers empty for a/// non-empty input: if the cut would blank the body (a body that is nothing but/// quoted history), the original is kept — the archive never loses a body to a/// formatting guess.pub fn strip_quoted_reply(body: &str) -> String {    if body.is_empty() {        return String::new();    }    // `body.split(/\r?\n/)` — a lone `\r` is NOT a break, so this splits on    // `\n` and drops one trailing `\r` per line rather than using `lines()`,    // which treats `\r\n` and `\n` the same but also refuses a final empty    // line the JavaScript keeps.    let lines: Vec<&str> = body        .split('\n')        .map(|line| line.strip_suffix('\r').unwrap_or(line))        .collect();    let Some(boundary) = quote_boundary(&lines) else {        return body.to_string();    };    let kept = lines[..boundary].join("\n");    let kept = kept.trim_end_matches(is_js_whitespace);    if kept.is_empty() {        body.to_string()    } else {        kept.to_string()    }}use crate::js::is_js_whitespace;/// The stored-body ceiling, in the UTF-16 units JavaScript's `length` counts.pub const EMAIL_BODY_MAX: usize = 65_536;pub const TRUNCATION_MARK: &str =    "\n\n[Cotton stored the first 65536 characters; the rest was cut at ingest]";/// `value.slice(0, max)` counted in UTF-16 units.pub fn utf16_clip(value: &str, max: usize) -> String {    let units: Vec<u16> = value.encode_utf16().collect();    if units.len() <= max {        return value.to_string();    }    String::from_utf16_lossy(&units[..max])}/// The body as it is stored: the quoted reply cut, then the ceiling with a/// visible mark.pub fn stored_body(body: &str) -> String {    let body = strip_quoted_reply(body);    if body.encode_utf16().count() > EMAIL_BODY_MAX {        format!("{}{TRUNCATION_MARK}", utf16_clip(&body, EMAIL_BODY_MAX))    } else {        body    }}/// The one-line preview: whitespace collapsed, then 140 UTF-16 units.pub fn derive_snippet(body: &str) -> Option<String> {    let mut flat = String::with_capacity(body.len());    let mut in_space = false;    for character in body.chars() {        if is_js_whitespace(character) {            in_space = true;            continue;        }        if in_space && !flat.is_empty() {            flat.push(' ');        }        in_space = false;        flat.push(character);    }    if flat.is_empty() {        return None;    }    let units: Vec<u16> = flat.encode_utf16().collect();    if units.len() <= 140 {        return Some(flat);    }    Some(format!("{}…", String::from_utf16_lossy(&units[..139])))}/// The Gmail labels that mean "do not archive this": the owner's own spam and/// bin, drafts that were never sent, and the old Talk archive.pub const REFUSED_LABELS: &[&str] = &["SPAM", "TRASH", "DRAFT", "CHAT"];/// The refused label a message carries, if any.pub fn refused_label(labels: &[String]) -> Option<&'static str> {    REFUSED_LABELS.iter().copied().find(|refused| labels.iter().any(|label| label == refused))}// ── HTML as text ────────────────────────────────────────────────────────────fn entity(name: &str) -> Option<&'static str> {    match name.to_lowercase().as_str() {        "amp" => Some("&"),        "lt" => Some("<"),        "gt" => Some(">"),        "quot" => Some("\""),        "apos" => Some("'"),        "nbsp" => Some(" "),        _ => None,    }}fn entity_re() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| Regex::new(r"&(#x?[0-9a-fA-F]+|[a-zA-Z]+);").expect("a literal entity"))}fn decode_entities(text: &str) -> String {    entity_re()        .replace_all(text, |captures: &regex::Captures<'_>| {            let whole = captures.get(0).map_or("", |m| m.as_str()).to_string();            let body = captures.get(1).map_or("", |m| m.as_str());            if let Some(rest) = body.strip_prefix('#') {                let code =                    if let Some(hex) = rest.strip_prefix('x').or_else(|| rest.strip_prefix('X')) {                        u32::from_str_radix(hex, 16).ok()                    } else {                        rest.parse::<u32>().ok()                    };                return code                    .filter(|code| *code > 0)                    .and_then(char::from_u32)                    .map_or(whole, |ch| ch.to_string());            }            entity(body).map_or(whole, str::to_string)        })        .into_owned()}fn html_res() -> &'static [(Regex, &'static str)] {    static RES: OnceLock<Vec<(Regex, &'static str)>> = OnceLock::new();    RES.get_or_init(|| {        // `(?is)` — case-insensitive, and `.` spans newlines, which is        // JavaScript's `[\s\S]` in the two block-stripping patterns.        let build = |pattern: &str, with: &'static str| {            (Regex::new(pattern).expect("a literal html pattern"), with)        };        vec![            build(r"(?is)<script\b[^>]*>.*?</script\s*>", ""),            build(r"(?is)<style\b[^>]*>.*?</style\s*>", ""),            build(r"(?s)<!--.*?-->", ""),            build(r"(?i)<br\s*/?>", "\n"),            // A list item is ONE line, not a paragraph — `</li>` closing into a            // blank line would double-space every bullet in a newsletter.            build(r"(?i)<li\b[^>]*>", "\n- "),            build(r"(?i)</li\s*>", ""),            build(                r"(?i)</(p|div|tr|h[1-6]|ul|ol|table|blockquote)\s*>",                "\n\n",            ),            build(r"(?i)<(p|div|tr|h[1-6]|table|blockquote)\b[^>]*>", "\n"),            build(r"<[^>]*>", ""),        ]    })}fn whitespace_res() -> &'static [(Regex, &'static str)] {    static RES: OnceLock<Vec<(Regex, &'static str)>> = OnceLock::new();    RES.get_or_init(|| {        vec![            (Regex::new(r"\r\n?").expect("a literal newline"), "\n"),            (Regex::new(r"[ \t]+").expect("a literal run"), " "),            (Regex::new(r" *\n *").expect("a literal margin"), "\n"),            (Regex::new(r"\n{3,}").expect("a literal gap"), "\n\n"),        ]    })}/// An HTML mail body as the text an archive stores.////// Deliberately small: the archive keeps what was written, and a full HTML/// parser in the ingest path would be a second thing to keep correct for no/// gain — nothing downstream renders this, it is read and searched as text.pub fn html_to_text(html: &str) -> String {    let mut text = html.to_string();    for (pattern, with) in html_res() {        text = pattern.replace_all(&text, *with).into_owned();    }    let mut text = decode_entities(&text);    for (pattern, with) in whitespace_res() {        text = pattern.replace_all(&text, *with).into_owned();    }    text.trim().to_string()}#[cfg(test)]mod tests {    use super::*;    #[test]    fn leaves_a_body_with_no_quoted_history_unchanged_byte_for_byte() {        let body = "Hi team,\n\nThe build is up. Please take a look.\n\nRegards,\nOwner";        assert_eq!(strip_quoted_reply(body), body);    }    #[test]    fn preserves_crlf_and_a_mid_word_from_in_a_clean_body() {        let body = "From the data we read this morning, the totals look right.\r\nRegards,\r\nOwner";        // No header pair follows, so nothing is cut — returned untouched.        assert_eq!(strip_quoted_reply(body), body);    }    #[test]    fn cuts_the_outlook_underscore_divider_and_everything_after_it() {        let body = [            "Hi Owner,",            "Please find our responses below.",            "",            "Regards,",            "Asha",            "Phno: +91 0123462250",            "",            "________________________________",            "From: Owner Example <owner@example.com>",            "Sent: Friday, August 28, 2026 11:34 AM",            "To: Asha Example <asha@example.com>",            "Subject: Re: Project update",            "",            "Hi Asha, everyone — the updated build is live ...",        ]        .join("\n");        assert_eq!(            strip_quoted_reply(&body),            "Hi Owner,\nPlease find our responses below.\n\nRegards,\nAsha\nPhno: +91 0123462250"        );    }    #[test]    fn cuts_a_gmail_on_date_name_wrote_attribution_on_one_line() {        let body = [            "Thanks Asha, that clarifies it.",            "",            "On Wed, Aug 26, 2026 at 12:50 PM Asha Example <asha@example.com> wrote:",            "> Please use the query below to list the active rows.",            "> WITH ...",        ]        .join("\n");        assert_eq!(strip_quoted_reply(&body), "Thanks Asha, that clarifies it.");    }    #[test]    fn cuts_a_gmail_attribution_that_wraps_across_lines_before_wrote() {        let body = [            "Got it, will revert.",            "",            "On Wed, 19 Aug 2026 at 6:33 PM, Asha Example",            "<asha@example.com>",            "wrote:",            "> After discussion with Vikram, here are the updated responses.",        ]        .join("\n");        assert_eq!(strip_quoted_reply(&body), "Got it, will revert.");    }    #[test]    fn cuts_a_bare_quoted_block() {        let body = "Sounds good.\n\n> earlier message text\n> more quoted text";        assert_eq!(strip_quoted_reply(body), "Sounds good.");    }    #[test]    fn cuts_an_outlook_original_message_banner() {        let body = "See below.\n\n-----Original Message-----\nFrom: someone\nSent: yesterday";        assert_eq!(strip_quoted_reply(body), "See below.");    }    #[test]    fn cuts_an_outlook_header_block_with_no_divider_line() {        let body = [            "Quick note before the call.",            "",            "From: Owner Example <owner@example.com>",            "Sent: Thursday, August 20, 2026 2:06 PM",            "To: Asha",            "Subject: Re: Project update",        ]        .join("\n");        assert_eq!(strip_quoted_reply(&body), "Quick note before the call.");    }    #[test]    fn does_not_cut_prose_that_merely_starts_with_on_monday() {        let body = "On Monday we should sync on the report query.\n\nThanks,\nOwner";        assert_eq!(strip_quoted_reply(body), body);    }    #[test]    fn does_not_cut_a_line_that_only_mentions_a_from_address_inside_a_sentence() {        let body = "From: field aside, the header looked fine to me.\nRegards";        assert_eq!(strip_quoted_reply(body), body);    }    #[test]    fn keeps_the_original_when_the_body_is_nothing_but_quoted_history() {        let body = "________________________________\nFrom: x\nSent: y";        assert_eq!(strip_quoted_reply(body), body);    }    #[test]    fn is_idempotent() {        let body = "Reply text.\n\nOn Wed, Aug 26, 2026 Asha <t@x.io> wrote:\n> old";        let once = strip_quoted_reply(body);        assert_eq!(strip_quoted_reply(&once), once);    }    #[test]    fn handles_an_empty_body() {        assert_eq!(strip_quoted_reply(""), "");    }    #[test]    fn a_long_body_is_cut_with_a_visible_mark_and_the_snippet_is_one_line() {        let long = "a".repeat(EMAIL_BODY_MAX + 10);        let stored = stored_body(&long);        assert!(stored.ends_with(TRUNCATION_MARK));        assert_eq!(derive_snippet("Hello\n\n  there").as_deref(), Some("Hello there"));        assert_eq!(derive_snippet(&"b".repeat(200)).unwrap().chars().count(), 140);    }    #[test]    fn html_reads_as_text() {        let text = html_to_text("<style>x{}</style><p>Total <b>12.00</b> &amp; more</p><ul><li>one</li></ul>");        assert!(text.starts_with("Total 12.00 & more"), "{text}");        assert!(text.contains("- one"));        assert!(!text.contains('<'));    }}