Cotton code
488 lines · 19.1 KB · RustRaw
//! A shared contact card, read out of the `.vcf` a WhatsApp export carries —//! the port of `packages/import-core/src/vcard.ts`.//!//! Sharing a contact in WhatsApp attaches a vCard. The export names the file//! like any other attachment, so until 2026-09-05 it imported as a chip reading//! `Rahul.vcf` — a file nobody would ever tap, in place of the card the chat//! actually showed. This reads the four things a bubble needs (who, their//! numbers, their addresses, where they work) so the app can draw the card and//! offer to save the person.//!//! ## Deliberately small//!//! A vCard can carry a photo, a postal address, a birthday and thirty other//! properties. Everything copied out of the file and into a message row is a//! copy of somebody's details living somewhere nobody expects to find them, so//! this takes the four a chat bubble shows and leaves the rest in the file,//! where the person who was sent it can still open it. Same reason there is no//! vCard WRITER here: Cotton never regenerates somebody's card.//!//! ## The format, and the two things that actually bite//!//! vCard is line-based (`PROPERTY;PARAM=VALUE:value`), but://!//!   * **LINES FOLD.** A long value continues on the next line, marked by a//!     leading space or tab, and the marker is not part of the value.//!     Unfolding first is the difference between a phone number and half a//!     phone number.//!   * **ANDROID QUOTED-PRINTABLE.** A card with a non-ASCII name is written//!     `N;CHARSET=UTF-8;ENCODING=QUOTED-PRINTABLE:=E0=A4=B0…`, and read raw//!     that is a name made of equals signs. The TypeScript decodes it by//!     turning `=XX` into `%XX` and handing the result to//!     `decodeURIComponent`, which does the UTF-8 part — `TextDecoder` is not//!     something that package may assume (it runs inside Hermes) and `Buffer`//!     is banned outright. This port spells the percent-decode out (see//!     [`decode_uri_component`]) rather than reaching for a URL crate, because//!     the exact FAILURE behaviour is what the fallback depends on.//!//! A file may hold SEVERAL cards (WhatsApp writes one `BEGIN:VCARD` block per//! person when you share more than one). The first is read; the file itself//! still carries them all, and is still the attachment.use serde::{Deserialize, Serialize};use cotton_store::protocol::js::is_js_whitespace;/// The readable part of one vCard.#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]pub struct VcardContact {    /// `FN`, else the assembled `N`, else `ORG`, else the first phone.    pub name: String,    pub phones: Vec<String>,    pub emails: Vec<String>,    /// The TypeScript's `org?:` — absent, never `null`.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub org: Option<String>,}/// `String.prototype.trim()` — the ECMAScript whitespace class, which is NOT/// Rust's `str::trim`.////// The two disagree in both directions: JavaScript trims U+FEFF and Rust does/// not, Rust trims U+0085 and JavaScript does not. Here the trim decides/// whether a `TEL` value counts as EMPTY and is therefore dropped, so a card/// whose number is padded with a BOM must lose the BOM on both sides or the/// phone and the CLI disagree about whether that person has a number at all./// `summaries`, `stores` and `chunk` each carry the same helper for the same/// reason.fn js_trim(s: &str) -> &str {    s.trim_matches(is_js_whitespace)}/// Undo RFC 6350 folding: a line beginning with a space or tab continues the/// previous one.////// The fold MARK is not part of the value, so the halves join directly —/// `EMAIL:anita.rao.dispatch` + ` @example.test` is one address, not two words./// Line terminators are normalised first (`\r\n` and a lone `\r` both become/// `\n`) so the split is one rule.fn unfold(text: &str) -> Vec<String> {    let normalised = normalise_line_endings(text);    let mut out: Vec<String> = Vec::new();    for line in normalised.split('\n') {        if !out.is_empty() && (line.starts_with(' ') || line.starts_with('\t')) {            // `line.slice(1)` — the marker is one UTF-16 unit and one ASCII            // byte, so the byte cut is the same cut.            let last = out.len() - 1;            out[last].push_str(&line[1..]);            continue;        }        out.push(line.to_string());    }    out}/// `replace(/\r\n?/g, "\n")` — CRLF and a lone CR both become LF.fn normalise_line_endings(text: &str) -> String {    let mut out = String::with_capacity(text.len());    let mut chars = text.chars().peekable();    while let Some(ch) = chars.next() {        if ch == '\r' {            if chars.peek() == Some(&'\n') {                chars.next();            }            out.push('\n');        } else {            out.push(ch);        }    }    out}/// `decodeURIComponent`, as a `Result` rather than a thrown `URIError`.////// Two failures, both of which the caller turns into "leave the value as it/// was": a `%` not followed by two hex digits, and a percent-escaped byte run/// that is not valid UTF-8. The second is the one that matters — an Android/// card whose quoted-printable is truncated mid-character must come back as/// the equals signs it literally holds, not as replacement characters, because/// a name of U+FFFD is worse than a name a human can still read the bytes of.////// Consecutive escapes are gathered into ONE byte run and validated together./// That is equivalent to the specification's per-character walk on every/// input: a lead byte with a bad continuation, an overlong form and a/// surrogate-encoding are each rejected by `String::from_utf8` exactly as/// `decodeURIComponent` rejects them.fn decode_uri_component(input: &str) -> Result<String, ()> {    let bytes = input.as_bytes();    let mut out = String::with_capacity(input.len());    let mut pending: Vec<u8> = Vec::new();    let mut i = 0usize;    while i < bytes.len() {        if bytes[i] == b'%' {            if i + 2 >= bytes.len() {                return Err(());            }            let hi = (bytes[i + 1] as char).to_digit(16).ok_or(())?;            let lo = (bytes[i + 2] as char).to_digit(16).ok_or(())?;            pending.push(((hi << 4) | lo) as u8);            i += 3;            continue;        }        if !pending.is_empty() {            out.push_str(&String::from_utf8(std::mem::take(&mut pending)).map_err(|_| ())?);        }        // A non-escape character passes through as itself. `input` is a Rust        // `&str`, so indexing forward by the character's own UTF-8 length can        // never split one.        let ch = input[i..].chars().next().ok_or(())?;        out.push(ch);        i += ch.len_utf8();    }    if !pending.is_empty() {        out.push_str(&String::from_utf8(pending).map_err(|_| ())?);    }    Ok(out)}/// `=E0=A4=B0` → the characters it encodes. Unreadable input is left as it was.fn decode_quoted_printable(value: &str) -> String {    // The soft line break. In practice this never fires — `unfold` has already    // split on every newline, so a value reaching here holds none — but it is    // the TypeScript's own first step and is ported rather than reasoned away.    let joined = value.replace("=\n", "");    // `%` first, so a literal percent in the card survives the round trip:    // `100%=20off` becomes `100%25%20off`, which decodes back to `100% off`.    let mut escaped = String::with_capacity(joined.len());    let bytes = joined.as_bytes();    let mut i = 0usize;    while i < bytes.len() {        if bytes[i] == b'%' {            escaped.push_str("%25");            i += 1;            continue;        }        if bytes[i] == b'='            && i + 2 < bytes.len()            && bytes[i + 1].is_ascii_hexdigit()            && bytes[i + 2].is_ascii_hexdigit()        {            escaped.push('%');            escaped.push(bytes[i + 1] as char);            escaped.push(bytes[i + 2] as char);            i += 3;            continue;        }        let ch = joined[i..].chars().next().expect("i is a char boundary");        escaped.push(ch);        i += ch.len_utf8();    }    decode_uri_component(&escaped).unwrap_or(joined)}/// `\,` `\;` `\n` `\\` — vCard's own escapes, which survive folding.////// A backslash at the very end of a value escapes nothing and stays as itself,/// which is what makes `ORG:Fixture\; Works` read as `Fixture\ · Works`: the/// SPLIT on `;` happens before this runs, so the escaped semicolon has already/// separated two components and left the backslash stranded. That is the/// TypeScript's behaviour and the port keeps it — a "fix" here would change/// somebody's company name on one side of an import and not the other.fn unescape_value(value: &str) -> String {    let mut out = String::with_capacity(value.len());    let mut chars = value.chars().peekable();    while let Some(ch) = chars.next() {        if ch != '\\' {            out.push(ch);            continue;        }        match chars.peek() {            Some('n') | Some('N') => {                chars.next();                out.push('\n');            }            Some(&escaped @ (',' | ';' | '\\')) => {                chars.next();                out.push(escaped);            }            _ => out.push('\\'),        }    }    out}/// One `PROPERTY;PARAM=VALUE:value` line, split.struct VcardLine {    property: String,    value: String,}fn split_line(line: &str) -> Option<VcardLine> {    // `indexOf(":")` — `:` is ASCII and cannot appear inside a multi-byte    // character, so the byte offset is the code-unit offset.    let colon = line.find(':')?;    if colon == 0 {        return None;    }    let head = &line[..colon];    let mut value = line[colon + 1..].to_string();    let mut parts = head.split(';');    let property = parts.next().unwrap_or("");    // `/ENCODING=QUOTED-PRINTABLE/i` — spelled as an ASCII fold rather than a    // Rust `(?i)` regex, because Rust's is Unicode-aware and would match a    // parameter written with U+017F or U+212A where JavaScript's `i` (no `u`    // flag) refuses to fold a non-ASCII code point onto an ASCII one.    if parts.any(|param| {        param            .to_ascii_uppercase()            .contains("ENCODING=QUOTED-PRINTABLE")    }) {        value = decode_quoted_printable(&value);    }    Some(VcardLine {        property: js_trim(property).to_uppercase(),        value,    })}/// `N:Rao;Anita;;;` → `Anita Rao`. Empty components drop out.////// The five components are family, given, middle, prefix and suffix, and they/// are re-ordered into reading order: `N:Rao;Anita;Kumari;Dr.;Jr.` is/// `Dr. Anita Kumari Rao Jr.`. Fewer than five is normal (`N:Rao;;;;`), and a/// sixth is ignored — the TypeScript destructures exactly five with `""`/// defaults.fn name_from_structured(value: &str) -> String {    let parts: Vec<String> = value        .split(';')        .map(|part| js_trim(&unescape_value(part)).to_string())        .collect();    let at = |index: usize| parts.get(index).map(String::as_str).unwrap_or("");    let (family, given, middle, prefix, suffix) = (at(0), at(1), at(2), at(3), at(4));    [prefix, given, middle, family, suffix]        .into_iter()        .filter(|part| !part.is_empty())        .collect::<Vec<_>>()        .join(" ")}/// Unescape, trim, and append unless the list already holds it.////// A card that lists one number under `CELL` and again under `HOME` is one/// number, not two, and the ORDER is first-seen — a `HashSet` would lose it,/// and the first number is the one the name falls back to.fn push_unique(list: &mut Vec<String>, value: &str) {    let trimmed = js_trim(&unescape_value(value)).to_string();    if !trimmed.is_empty() && !list.contains(&trimmed) {        list.push(trimmed);    }}/// Read the FIRST vCard in `text`, or answer `None` when there is nothing/// readable in it.////// No name and no number is not a contact card, and inventing a label for it/// would put a row in the chat that says less than the file.pub fn parse_vcard(text: &str) -> Option<VcardContact> {    let lines = unfold(text);    let mut phones: Vec<String> = Vec::new();    let mut emails: Vec<String> = Vec::new();    let mut formatted = String::new();    let mut structured = String::new();    let mut org = String::new();    let mut started = false;    for raw in &lines {        let Some(line) = split_line(js_trim(raw)) else {            continue;        };        if line.property == "BEGIN" && js_trim(&line.value).to_uppercase() == "VCARD" {            // A second card in the same file: stop, the first one is the answer.            if started {                break;            }            started = true;            continue;        }        if line.property == "END" {            break;        }        if !started {            continue;        }        // The `is_empty` guards are "the FIRST one wins": a card with two `FN`        // lines keeps the first, never the last. `TEL` and `EMAIL` are the        // opposite — every one is kept, in order — which is why they carry no        // guard.        match line.property.as_str() {            "FN" if formatted.is_empty() => {                formatted = js_trim(&unescape_value(&line.value)).to_string();            }            "N" if structured.is_empty() => {                structured = name_from_structured(&line.value);            }            "TEL" => push_unique(&mut phones, &line.value),            "EMAIL" => push_unique(&mut emails, &line.value),            "ORG" if org.is_empty() => {                // The split happens BEFORE the unescape, so `Fixture\;                // Works` really is two components over there too.                org = line                    .value                    .split(';')                    .map(|part| js_trim(&unescape_value(part)).to_string())                    .filter(|part| !part.is_empty())                    .collect::<Vec<_>>()                    .join(" \u{b7} ");            }            _ => {}        }    }    let first_phone = phones.first().cloned().unwrap_or_default();    let name = [        formatted.as_str(),        structured.as_str(),        org.as_str(),        first_phone.as_str(),    ]    .into_iter()    .find(|candidate| !candidate.is_empty())?    .to_string();    // The company is carried only when it is not ALREADY the name — a card    // that has nothing but an `ORG` shows it once, as the label, not twice.    let org_field = if !org.is_empty() && org != name {        Some(org)    } else {        None    };    Some(VcardContact {        name,        phones,        emails,        org: org_field,    })}/// A birthday as a card says it: the month and day, and the year when known.#[derive(Debug, Clone, Copy, PartialEq, Eq)]pub struct Birthday {    pub year: Option<i64>,    pub month: i64,    pub day: i64,}/// One card of a contacts file, as a person record reads it — what a/// contacts IMPORT takes ([`crate::import::package_readers`]), which is more/// than a chat bubble shows ([`parse_vcard`]): a person's own `.vcf` is their/// address book, brought in on purpose.#[derive(Debug, Clone, PartialEq, Eq, Default)]pub struct VcardCard {    /// `UID`, when the card has one: what names it across exports.    pub uid: Option<String>,    /// `FN`, else the assembled `N`, else `ORG`, else the first phone.    pub name: String,    pub phones: Vec<String>,    pub emails: Vec<String>,    pub org: Option<String>,    pub title: Option<String>,    pub note: Option<String>,    pub birthday: Option<Birthday>,}/// `BDAY`: `19900115`, `1990-01-15`, `--0115` or `--01-15`, perhaps with a/// time after a `T`. Apple writes year 1604 for a birthday with no year.fn birthday_of(value: &str) -> Option<Birthday> {    let date = js_trim(value).split('T').next().unwrap_or("");    let (year, rest) = match date.strip_prefix("--") {        Some(rest) => (None, rest.replace('-', "")),        None => {            let digits = date.replace('-', "");            if digits.len() != 8 {                return None;            }            (digits[..4].parse::<i64>().ok().filter(|year| *year != 1604), digits[4..].to_string())        }    };    if rest.len() != 4 || !rest.bytes().all(|byte| byte.is_ascii_digit()) {        return None;    }    let (month, day) = (rest[..2].parse::<i64>().ok()?, rest[2..].parse::<i64>().ok()?);    ((1..=12).contains(&month) && (1..=31).contains(&day)).then_some(Birthday { year, month, day })}fn some_text(value: &str) -> Option<String> {    Some(js_trim(&unescape_value(value)).to_string()).filter(|text| !text.is_empty())}/// Every card in a contacts file, in order. A card with nothing to call its/// person by is left out.pub fn parse_vcards(text: &str) -> Vec<VcardCard> {    let mut cards = Vec::new();    let mut current: Option<(VcardCard, String, String)> = None;    for raw in &unfold(text) {        let Some(line) = split_line(js_trim(raw)) else {            continue;        };        let value = js_trim(&line.value).to_uppercase();        if line.property == "BEGIN" && value == "VCARD" {            current = Some((VcardCard::default(), String::new(), String::new()));            continue;        }        let Some((card, formatted, structured)) = current.as_mut() else {            continue;        };        match line.property.as_str() {            "END" if value == "VCARD" => {                let Some((mut card, formatted, structured)) = current.take() else { continue };                let first_phone = card.phones.first().cloned().unwrap_or_default();                let org = card.org.clone().unwrap_or_default();                let Some(name) = [formatted.as_str(), structured.as_str(), org.as_str(), first_phone.as_str()]                    .into_iter()                    .find(|candidate| !candidate.is_empty())                else {                    continue;                };                card.name = name.to_string();                cards.push(card);            }            "FN" if formatted.is_empty() => *formatted = js_trim(&unescape_value(&line.value)).to_string(),            "N" if structured.is_empty() => *structured = name_from_structured(&line.value),            "TEL" => push_unique(&mut card.phones, &line.value),            "EMAIL" => push_unique(&mut card.emails, &line.value),            "ORG" if card.org.is_none() => {                let org = line                    .value                    .split(';')                    .map(|part| js_trim(&unescape_value(part)).to_string())                    .filter(|part| !part.is_empty())                    .collect::<Vec<_>>()                    .join(" \u{b7} ");                card.org = Some(org).filter(|org| !org.is_empty());            }            "TITLE" if card.title.is_none() => card.title = some_text(&line.value),            "NOTE" if card.note.is_none() => card.note = some_text(&line.value),            "UID" if card.uid.is_none() => card.uid = some_text(&line.value),            "BDAY" if card.birthday.is_none() => card.birthday = birthday_of(&line.value),            _ => {}        }    }    cards}#[cfg(test)]#[path = "vcard_tests.rs"]mod tests;