Cotton code
441 lines · 16.2 KB · RustRaw
//! Who is who in an export — the port of `packages/import-core/src/identity.ts`//! (spec `2026-08-25-cotton-whatsapp-import-identity-design.md` §2–§3).//!//! Decided from the export's own shape plus the candidate lists the caller//! holds, never by asking. The app supplies its People, its messaging contacts//! and the existing thread's members; the CLI supplies a file name. This//! module only matches, and it matches EXACTLY — a name that is not an exact,//! unique hit stays unidentified rather than being guessed, because a wrong//! identity files someone's words under a person who never said them.use std::collections::HashMap;use std::sync::OnceLock;use regex::Regex;use serde::{Deserialize, Serialize};use crate::import::group::{    extract_group_titles, is_encryption_boilerplate, is_group_pseudo_sender, GroupTitleEvent,    TitleCandidate,};use crate::import::normalize::ChatTxtParseResult;use crate::import::phone::{normalize_phone, promote_to_country, sender_looks_like_phone};use crate::import::text::{collapse_whitespace, js_trim};/// The comparison key for a sender label: layout and case are not identity.pub fn name_key(name: &str) -> String {    collapse_whitespace(name).to_lowercase()}pub fn same_name(a: &str, b: &str) -> bool {    name_key(a) == name_key(b)}/// `WhatsApp Chat - <title>` (iOS) or `WhatsApp Chat with <title>` (Android).////// `(.+)` is spelled out as "any code point that is not a LineTerminator",/// because JavaScript's `.` also excludes U+2028 and U+2029 and Rust's does/// not — a file name is caller-controlled text and the two classes would/// disagree on it.fn file_title() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| {        Regex::new(r"(?i)^WhatsApp Chat (?:-|with) ([^\n\r\u{2028}\u{2029}]+)$")            .expect("file title")    })}fn extension() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| Regex::new(r"(?i)\.(?:zip|txt)$").expect("extension"))}fn staging_prefix() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    RE.get_or_init(|| Regex::new(r"^[0-9]{10,}-").expect("staging prefix"))}/// `decodeURIComponent`, answering `None` where it would raise a `URIError`.////// A pure library may not panic on a name a stranger's file system produced,/// and the TypeScript's own `catch` says what to do instead: keep the name as/// it is. Escapes are decoded as UTF-8 — a run of `%XX` that is not a valid/// sequence is the error JavaScript raises, and it is the error answered here.fn decode_uri_component(input: &str) -> Option<String> {    let bytes = input.as_bytes();    let mut out = String::with_capacity(input.len());    let mut pending: Vec<u8> = Vec::new();    let mut index = 0usize;    while index < bytes.len() {        if bytes[index] == b'%' {            if index + 2 >= bytes.len() {                return None;            }            let hex = std::str::from_utf8(&bytes[index + 1..index + 3]).ok()?;            if !hex.bytes().all(|b| b.is_ascii_hexdigit()) {                return None;            }            pending.push(u8::from_str_radix(hex, 16).ok()?);            index += 3;            continue;        }        if !pending.is_empty() {            out.push_str(&String::from_utf8(std::mem::take(&mut pending)).ok()?);        }        // `input` is valid UTF-8, so this walks whole characters.        let char_len = input[index..].chars().next()?.len_utf8();        out.push_str(&input[index..index + char_len]);        index += char_len;    }    if !pending.is_empty() {        out.push_str(&String::from_utf8(pending).ok()?);    }    Some(out)}/// The chat's own name, from the export's file name — also behind a staging/// prefix (`<millis>-…`) or inside a file URI.pub fn chat_title_from_file_name(file_name: Option<&str>) -> Option<String> {    // `if (!fileName)` — an EMPTY name is falsy in JavaScript, so it answers    // null before anything is parsed.    let name = file_name.filter(|value| !value.is_empty())?;    let last = name.rsplit('/').next().unwrap_or(name);    let decoded = decode_uri_component(last).unwrap_or_else(|| last.to_string());    let without_extension = extension().replace(&decoded, "");    let without_prefix = staging_prefix().replace(&without_extension, "");    let base = js_trim(&without_prefix);    file_title()        .captures(base)        .map(|captures| collapse_whitespace(&captures[1]))}/// iOS attributes the encryption notice to the chat itself — the counterpart/// of a dm, the name of a group — so its "sender" is the chat's title. Android/// and older iOS builds write the notice unattributed; then there is no title/// here and the file name is the only hint.pub fn chat_title_from_notice(parse: &ChatTxtParseResult) -> Option<String> {    let first = parse.messages.iter().min_by_key(|message| message.line)?;    if is_encryption_boilerplate(&first.body) {        Some(collapse_whitespace(&first.sender))    } else {        None    }}/// Creation/rename titles, read from both the bare system lines and the/// attributed ones.pub fn group_title_events(parse: &ChatTxtParseResult) -> Vec<GroupTitleEvent> {    let mut candidates: Vec<TitleCandidate<'_>> = Vec::new();    for event in &parse.system_messages {        candidates.push(TitleCandidate {            text: &event.text,            sent_at: &event.sent_at,        });    }    for message in &parse.messages {        candidates.push(TitleCandidate {            text: &message.body,            sent_at: &message.sent_at,        });    }    extract_group_titles(&candidates)}/// Everyone who speaks, minus the group's own name: iOS attributes group/// events (and the notice) to the group as if it were a person.pub fn human_senders(parse: &ChatTxtParseResult) -> Vec<String> {    let titles = group_title_events(parse);    let notice = chat_title_from_notice(parse);    let is_group = !titles.is_empty();    parse        .sender_counts        .iter()        .filter(|entry| {            if is_group_pseudo_sender(&entry.name, &titles) {                return false;            }            if is_group {                if let Some(notice) = notice.as_deref() {                    if same_name(&entry.name, notice) {                        return false;                    }                }            }            true        })        .map(|entry| entry.name.clone())        .collect()}#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct OwnerHints {    /// **Every** name this workspace's owner has been seen under in an export    /// of this channel, most recent first.    ///    /// A list rather than the latest one, because the owner is one person with    /// several spellings — a contact name here, a number there, a nickname a    /// group gave them — and remembering only the last of them asked "which one    /// is you?" again on the very next export (the walk of 15 Sep 2026).    #[serde(default, skip_serializing_if = "Vec::is_empty")]    pub remembered_names: Vec<String>,    /// The owner's Cotton display name, matched exactly against the senders.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub owner_display_name: Option<String>,    /// The chat's title from outside the transcript (the file name); overrides    /// the notice.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub chat_title: Option<String>,}/// How the owner was decided — the TypeScript's string union.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "kebab-case")]pub enum OwnerHow {    DmTitle,    Remembered,    LiteralYou,    DisplayName,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct OwnerResolution {    pub name: String,    pub how: OwnerHow,    /// True when the name came from memory but nobody in the export carries it    /// — a group the owner never spoke in. The normalizer then accepts an    /// owner with no lines instead of refusing.    pub may_silent: bool,}/// Which sender is the owner, in order of certainty://////   1. a 1:1 export names exactly two people, and one of them IS the chat's///      title — the other is you;///   2. ANY name you have been seen under (remembered per channel, most recent///      first); present among the senders, or absent in a group you may simply///      not have spoken in;///   3. the literal `You` some locales write;///   4. your Cotton display name, exactly.////// `None` means the export cannot say — the caller asks, once, and remembers.pub fn resolve_owner(parse: &ChatTxtParseResult, hints: &OwnerHints) -> Option<OwnerResolution> {    let senders = human_senders(parse);    let is_group = !group_title_events(parse).is_empty();    let title = hints        .chat_title        .clone()        .or_else(|| chat_title_from_notice(parse));    if !is_group && senders.len() == 2 {        if let Some(title) = title.as_deref() {            let other: Vec<&String> = senders                .iter()                .filter(|sender| !same_name(sender, title))                .collect();            if other.len() == 1 {                return Some(OwnerResolution {                    name: other[0].clone(),                    how: OwnerHow::DmTitle,                    may_silent: false,                });            }        }    }    // An all-whitespace remembered name is skipped, not matched.    let remembered: Vec<&str> = hints        .remembered_names        .iter()        .map(|value| js_trim(value))        .filter(|value| !value.is_empty())        .collect();    // EVERY remembered name is tried for a sender before any of them is taken    // as the silent answer: an export naming the owner by a spelling they gave    // two exports ago is still an export that names them.    for name in &remembered {        if let Some(present) = senders.iter().find(|sender| same_name(sender, name)) {            return Some(OwnerResolution {                name: present.clone(),                how: OwnerHow::Remembered,                may_silent: false,            });        }    }    if let Some(latest) = remembered.first() {        if is_group || senders.len() > 2 {            return Some(OwnerResolution {                name: (*latest).to_string(),                how: OwnerHow::Remembered,                may_silent: true,            });        }    }    if let Some(you) = senders.iter().find(|sender| sender.as_str() == "You") {        return Some(OwnerResolution {            name: you.clone(),            how: OwnerHow::LiteralYou,            may_silent: false,        });    }    let display = hints        .owner_display_name        .as_deref()        .map(js_trim)        .filter(|value| !value.is_empty());    if let Some(display) = display {        if let Some(present) = senders.iter().find(|sender| same_name(sender, display)) {            return Some(OwnerResolution {                name: present.clone(),                how: OwnerHow::DisplayName,                may_silent: false,            });        }    }    None}/// What the caller knows about one sender label, handed to the normalizer.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ParticipantHint {    /// Canonical phone (digits, no `+`).    #[serde(default, skip_serializing_if = "Option::is_none")]    pub phone: Option<String>,    /// A People record this label is known to be.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub person_id: Option<String>,}/// The existing thread's participants — a label already listed with a number/// stays that number.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct ThreadMember {    pub label: String,    pub phone: Option<String>,}/// A messaging contact by display name (canonical phone).#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct IdentityContact {    pub name: String,    pub phone: String,}/// The candidate lists the caller holds. Phones are canonical unless noted.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct IdentitySources {    pub thread_members: Vec<ThreadMember>,    pub contacts: Vec<IdentityContact>,}/// One matched label and what was found for it.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct IdentityHint {    pub label: String,    #[serde(flatten)]    pub hint: ParticipantHint,}#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct IdentityPlan {    /// Label → what was found, in the order the labels were asked about. Only    /// matched labels appear.    ///    /// An ordered LIST rather than a map: the TypeScript's    /// `Record<string, ParticipantHint>` is insertion-ordered, the normalizer    /// takes the same ordered shape for its `participants` option, and where    /// two labels collapse to one `name_key` the LAST one wins — which a    /// `HashMap` keyed by label could not express.    pub hints: Vec<IdentityHint>,    pub matched: Vec<String>,    pub unidentified: Vec<String>,}fn canonical(raw: &str, country_code: Option<&str>) -> Option<String> {    normalize_phone(&promote_to_country(raw, country_code))}/// Match each label, in order: the label IS a number (an unsaved contact);/// this thread already lists the label as a participant; a messaging contact/// WhatsApp already showed under this label. Anything else stays/// unidentified — no guesses, the person can be named from the chat later.////// A person is never found here by name (PEOPLE BUILD 2): who a number/// belongs to is who(handle)'s, read when the contact is (`contact_person_sql`),/// so a hint carries a number and never a person.pub fn plan_participants(    labels: &[String],    sources: &IdentitySources,    country_code: Option<&str>,) -> IdentityPlan {    // `if (member.phone)` — a member listed with an EMPTY phone is not seated,    // because the empty string is falsy. A later duplicate label overwrites an    // earlier one, as `Map.set` does.    let mut members: HashMap<String, String> = HashMap::new();    for member in &sources.thread_members {        if let Some(phone) = member.phone.as_deref().filter(|value| !value.is_empty()) {            members.insert(name_key(&member.label), phone.to_string());        }    }    // Contacts are FIRST-wins (`if (!contacts.has(key))`).    let mut contacts: HashMap<String, String> = HashMap::new();    for contact in &sources.contacts {        contacts            .entry(name_key(&contact.name))            .or_insert_with(|| contact.phone.clone());    }    let mut plan = IdentityPlan::default();    for label in labels {        let key = name_key(label);        let mut hint: Option<ParticipantHint> = None;        if sender_looks_like_phone(label) {            if let Some(phone) = canonical(label, country_code) {                hint = Some(ParticipantHint {                    phone: Some(phone),                    person_id: None,                });            }        }        if hint.is_none() {            if let Some(seated) = members.get(&key) {                hint = Some(ParticipantHint {                    phone: Some(seated.clone()),                    person_id: None,                });            }        }        if hint.is_none() {            if let Some(contact) = contacts.get(&key) {                hint = Some(ParticipantHint {                    phone: Some(contact.clone()),                    person_id: None,                });            }        }        match hint {            Some(hint) => {                plan.hints.push(IdentityHint {                    label: label.clone(),                    hint,                });                plan.matched.push(label.clone());            }            None => plan.unidentified.push(label.clone()),        }    }    plan}#[cfg(test)]#[path = "identity_tests.rs"]mod tests;