Cotton code
573 lines · 20.4 KB · RustRaw
//! PRIMARY ADAPTER — WhatsApp-Chat-Exporter (KnugiHK, MIT) JSON. The port of//! `packages/import-core/src/adapters/wce.ts`.//!//! The user runs the exporter against their own local iPhone/Android backup and//! we read its JSON. This is the route spec §2.3 makes primary because it is the//! only one that carries real message ids, the reply graph and reactions, has no//! message cap, and cannot be vetoed by a counterparty's Advanced Chat Privacy//! setting.//!//! ## Schema pinned at//!//! commit `9537b4c05085a0e6ed85aa8ef4cc5e1555d3fec6` (branch `main`), package//! version 0.13.0. Sources read: `data_model.py` (ChatStore / Message and their//! `to_json`), `utility.py` (`get_chat_type`, `get_reply_id`), the iOS and//! Android handlers (field population), and `__main__.py` (`export_json` ///! `export_multiple_json`).//!//! ## Shape//!//! ```json//! { "<jid>": { "name": null, "type": null, "my_avatar": null,//!              "their_avatar": null, "their_avatar_thumb": null,//!              "status": null, "media_base": "",//!              "messages": { "<db row id>": { } } } }//! ```//!//! `--per-chat` writes one file per chat with the SAME single-key wrapper, so//! both layouts parse identically here.//!//! ## Why this reader is deliberately paranoid//!//! Since commit `ae6e8ba7` (2025-05-11) both `to_json` methods are bare//! `__dict__` dumps, so the field set is EMERGENT: any attribute the tool sets//! anywhere lands in the JSON, and can appear or vanish with no release note and//! no version marker in the file. `from_json` on their side is `.get`-based and//! tolerates 8 of 19 fields being absent; this reader matches that posture —//! unknown keys are collected and reported once, missing optionals default, and//! only a genuinely unusable message (no timestamp) is dropped, counted.//!//! Field-level traps encoded below, all confirmed in source://!//! * `messages` is keyed by DB ROW ID, which is NOT stable across re-exports.//!   Identity is `key_id` (the WhatsApp stanza id) — that is our `external_id`.//! * `reply` holds the quoted message's `key_id`, not a row id — so it maps//!   straight onto `reply_to_external_id` with no index to build.//! * `timestamp` is the ONLY trustworthy time source. `time`,//!   `received_timestamp` and `read_timestamp` are pre-formatted display strings//!   rendered in the exporting machine's local zone, and that zone is computed//!   with a `.seconds`-instead-of-`.total_seconds()` bug that yields 19.0 for a//!   UTC-5 machine. Never read them. (That is also why this module needs no//!   zone argument at all: the one field it reads is an absolute instant.)//! * `data` doubles as the media PATH when `media` is true; the text then lives//!   in `caption`.//! * Newlines inside `data` are rewritten to `<br>` on both platforms.//! * `reactions` is a FLAT `{ "<sender name>": "<emoji>" }` map with no//!   timestamps, and is Android-only (iOS always `{}`).//! * There is no `is_group` flag — the JID suffix is the only marker.//! * The contacts pass creates a ChatStore for EVERY address-book entry, so most//!   chats in a big export have zero messages and often a null name.//!//! The parse result types live in [`crate::import::normalize`] — the one module//! that reads all of them — and this adapter produces them rather than declaring//! its own.use std::sync::OnceLock;use cotton_store::protocol::js;use regex::Regex;use serde::{Deserialize, Serialize};use serde_json::{Map, Value};use thiserror::Error;use crate::import::normalize::{WceChat, WceMessage, WceParseResult, WceReaction, WceSkippedChat};use crate::import::phone::normalize_phone;/// What a JID says the conversation is.#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum WceChatKind {    Personal,    Group,    Calls,    StatusBroadcast,    BroadcastChannel,    Lid,    Exported,    Unknown,}impl WceChatKind {    /// The TypeScript's own string, which is what    /// [`crate::import::normalize::WceChat::kind`] carries on the wire.    pub const fn as_str(self) -> &'static str {        match self {            WceChatKind::Personal => "personal",            WceChatKind::Group => "group",            WceChatKind::Calls => "calls",            WceChatKind::StatusBroadcast => "status_broadcast",            WceChatKind::BroadcastChannel => "broadcast_channel",            WceChatKind::Lid => "lid",            WceChatKind::Exported => "exported",            WceChatKind::Unknown => "unknown",        }    }}/// The one refusal this adapter raises. `Display` is the TypeScript's sentence/// VERBATIM.#[derive(Debug, Clone, PartialEq, Eq, Error)]pub enum WceError {    #[error(        "This does not look like WhatsApp-Chat-Exporter JSON: the top level should be an object keyed by JID."    )]    NotAnExport,}/// Fields this reader understands, at 0.13.0. Anything else is reported once.const KNOWN_CHAT_FIELDS: [&str; 8] = [    "name",    "type",    "my_avatar",    "their_avatar",    "their_avatar_thumb",    "status",    "media_base",    "messages",];const KNOWN_MESSAGE_FIELDS: [&str; 19] = [    "from_me",    "timestamp",    "time",    "media",    "key_id",    "meta",    "data",    "sender",    "safe",    "mime",    "message_type",    "received_timestamp",    "read_timestamp",    "reply",    "quoted_data",    "caption",    "thumb",    "sticker",    "reactions",];/// The exporter's synthetic "WhatsApp Calls" pseudo-chat.const CALLS_JID: &str = "000000000000000";/// The exporter's synthetic key for its own `-e` text-import path.const EXPORTED_JID: &str = "ExportedChat";/// Mirrors `utility.get_chat_type()`, plus the `@lid` case that classifier does/// not have. A LID is WhatsApp's privacy-preserving linked identifier: its user/// part is NOT a phone number, so treating it as one would file a conversation/// under an invented contact. Skipped, loudly.pub fn classify_jid(jid: &str) -> WceChatKind {    if jid == CALLS_JID {        return WceChatKind::Calls;    }    if jid == EXPORTED_JID {        return WceChatKind::Exported;    }    if jid == "status@broadcast" {        return WceChatKind::StatusBroadcast;    }    if jid.ends_with("@lid") {        return WceChatKind::Lid;    }    if jid.ends_with("@s.whatsapp.net") {        return WceChatKind::Personal;    }    if jid.ends_with("@g.us") {        return WceChatKind::Group;    }    if jid.ends_with("@broadcast") {        return WceChatKind::BroadcastChannel;    }    WceChatKind::Unknown}/// `919876543210@s.whatsapp.net` → `919876543210`.////// This answers a number for a LID too (its user part is all digits), which is/// why the guard that matters is [`classify_jid`] and not this — nothing may/// call this on a JID it has not classified first.pub fn phone_from_jid(jid: &str) -> Option<String> {    // `jid.split("@")[0]`, then the `:device` suffix a multi-device JID carries.    let user = jid.split('@').next().unwrap_or("");    normalize_phone(user.split(':').next().unwrap_or(""))}fn br_re() -> &'static Regex {    static RE: OnceLock<Regex> = OnceLock::new();    // JS `/<br\s*\/?>/gi`; `\s` is the ECMAScript class, spelled out because    // Rust's differs at U+FEFF and U+0085.    RE.get_or_init(|| {        Regex::new(&format!(            r"(?i)<br[{}]*/?>",            crate::import::text::JS_WHITESPACE_CLASS        ))        .expect("br")    })}/// The exporter rewrites every newline in `data` to `<br>` on both platforms.pub fn reverse_br_substitution(input: &str) -> String {    br_re().replace_all(input, "\n").into_owned()}/// JS `typeof value === "string" ? value : Number.isFinite(value) ? String(value) : null`.////// The number branch is not theoretical: a JID whose contact name is all digits/// comes back from the exporter as a JSON number, and `key_id` has been seen as/// one in hand-merged files.fn as_string(value: Option<&Value>) -> Option<String> {    match value? {        Value::String(text) => Some(text.clone()),        // A `serde_json` number is always finite, which is `Number.isFinite`.        Value::Number(number) => number.as_f64().map(js::number_to_string),        _ => None,    }}/// The exporter coerces these with `bool(...)`, but hand-edited or older files/// have been seen carrying 0/1 — accept both rather than silently reading a/// truthy `0` as false or a `1` as… also false.fn as_bool(value: Option<&Value>) -> bool {    match value {        Some(Value::Bool(flag)) => *flag,        Some(Value::Number(number)) => number.as_f64().is_some_and(|value| value != 0.0),        _ => false,    }}/// Earliest plausible WhatsApp message — the service launched in 2009./// `Date.UTC(2009, 0, 1) / 1000`.const MIN_TIMESTAMP_SECONDS: f64 = 1_230_768_000.0;/// The largest value read as SECONDS; anything above it is taken as/// milliseconds from a hand-merged file.const MAX_SECONDS_VALUE: f64 = 9_999_999_999.0;/// `timestamp` → ISO instant. The exporter already divides millisecond values/// down, but a hand-merged file can carry raw milliseconds, so the same guard is/// applied here rather than trusting the producer.////// Takes a `Value` because the TypeScript takes `unknown` — a string timestamp/// is `None`, not a parse. Two of the TypeScript's rejections cannot be/// expressed in JSON at all and so cannot be tested here: `undefined` (absence,/// which arrives as [`Value::Null`] or a missing key) and `NaN` (a/// `serde_json::Number` is always finite). Both answer `None` by the same/// branch that rejects a string.pub fn timestamp_to_iso(value: Option<&Value>) -> Option<String> {    let number = match value? {        Value::Number(number) => number.as_f64()?,        _ => return None,    };    if !number.is_finite() || number <= 0.0 {        return None;    }    let seconds = if number > MAX_SECONDS_VALUE {        number / 1000.0    } else {        number    };    if seconds < MIN_TIMESTAMP_SECONDS {        return None;    }    // `new Date(seconds * 1000)`: `TimeClip` truncates toward zero, so a    // fractional second keeps its milliseconds and loses everything below them.    js::to_iso_string((seconds * 1000.0).trunc() as i64)}/// The order JavaScript walks a plain object's own keys, which/// `Object.entries` and `Object.keys` both follow and `serde_json`'s/// insertion-order map does not: **integer-like keys first, in ascending/// numeric order, then every other key in insertion order.**////// This is not pedantry here. `messages` is keyed by DB ROW ID — every key is/// an integer-like string — so a file whose rows happen to be written out of/// order (a merged export, a hand-edited one) is walked ascending by the/// TypeScript and in file order by a naive Rust port. The messages are sorted/// by instant afterwards, and that sort is STABLE on both sides, so two rows/// sharing one timestamp would come out in a different order — a difference/// that shows up as two conversations reading differently and nowhere else.////// "Integer-like" is the spec's array-index test: a canonical decimal string for/// a value below 2^32 − 1, so `"007"` and `"-1"` are ordinary keys.fn js_key_order(map: &Map<String, Value>) -> Vec<&String> {    let mut indexes: Vec<(u32, &String)> = Vec::new();    let mut rest: Vec<&String> = Vec::new();    for key in map.keys() {        match array_index(key) {            Some(index) => indexes.push((index, key)),            None => rest.push(key),        }    }    indexes.sort_by_key(|(index, _)| *index);    indexes        .into_iter()        .map(|(_, key)| key)        .chain(rest)        .collect()}fn array_index(key: &str) -> Option<u32> {    if key.is_empty() || !key.bytes().all(|byte| byte.is_ascii_digit()) {        return None;    }    if key.len() > 1 && key.starts_with('0') {        return None;    }    let index = key.parse::<u32>().ok()?;    if index == u32::MAX {        return None;    }    Some(index)}fn parse_reactions(value: Option<&Value>) -> Vec<WceReaction> {    let Some(Value::Object(map)) = value else {        return Vec::new();    };    let mut out = Vec::new();    for key in js_key_order(map) {        if let Some(Value::String(emoji)) = map.get(key) {            if !emoji.is_empty() {                out.push(WceReaction {                    actor_name: key.clone(),                    emoji: emoji.clone(),                });            }        }    }    out}struct MessageParse {    message: Option<WceMessage>,    unknown_fields: Vec<String>,    html: bool,}fn parse_message(row_key: &str, raw: &Value) -> MessageParse {    let Value::Object(map) = raw else {        return MessageParse {            message: None,            unknown_fields: Vec::new(),            html: false,        };    };    let unknown_fields: Vec<String> = js_key_order(map)        .into_iter()        .filter(|key| !KNOWN_MESSAGE_FIELDS.contains(&key.as_str()))        .cloned()        .collect();    let Some(sent_at) = timestamp_to_iso(map.get("timestamp")) else {        return MessageParse {            message: None,            unknown_fields,            html: false,        };    };    let is_media = as_bool(map.get("media"));    let data = as_string(map.get("data"));    let caption = as_string(map.get("caption"));    let contains_html = as_bool(map.get("safe"));    // `data` is the media PATH when `media` is true; the words live in    // `caption`.    let text = if is_media {        caption.clone().unwrap_or_default()    } else {        reverse_br_substitution(data.as_deref().unwrap_or(""))    };    MessageParse {        message: Some(WceMessage {            row_key: row_key.to_string(),            key_id: as_string(map.get("key_id")),            from_me: as_bool(map.get("from_me")),            sent_at,            is_system: as_bool(map.get("meta")),            is_media,            text,            caption,            mime: as_string(map.get("mime")),            media_path: if is_media { data } else { None },            reply_to_key_id: as_string(map.get("reply")),            sticker: as_bool(map.get("sticker")),            reactions: parse_reactions(map.get("reactions")),            sender: as_string(map.get("sender")),            contains_html,        }),        unknown_fields,        html: contains_html,    }}/// Push a value onto an insertion-ordered set — the TypeScript's `Set`, whose/// iteration order is observable in the warning sentence and in/// `unknown*Fields`.fn insert_once(set: &mut Vec<String>, value: &str) {    if !set.iter().any(|held| held == value) {        set.push(value.to_string());    }}/// Read a WCE JSON document. Accepts both the whole-export layout and a/// `--per-chat` file, since they are the same shape.////// Group / broadcast / calls / LID chats are SKIPPED with a counted reason/// (spec §2.3: groups are out of scope for v1, and the schema keeps `kind` as/// the seam for when they arrive).pub fn parse_wce_json(document: &Value) -> Result<WceParseResult, WceError> {    let mut warnings: Vec<String> = Vec::new();    let Value::Object(top) = document else {        return Err(WceError::NotAnExport);    };    let mut chats: Vec<WceChat> = Vec::new();    let mut skipped: Vec<WceSkippedChat> = Vec::new();    let mut unknown_chat_fields: Vec<String> = Vec::new();    let mut unknown_message_fields: Vec<String> = Vec::new();    let mut empty_chats: i64 = 0;    let mut dropped_messages: i64 = 0;    let mut html_messages: i64 = 0;    for jid in js_key_order(top) {        let Some(Value::Object(raw_chat)) = top.get(jid) else {            warnings.push(format!("Chat \"{jid}\" is not an object and was ignored."));            continue;        };        for key in js_key_order(raw_chat) {            if !KNOWN_CHAT_FIELDS.contains(&key.as_str()) {                insert_once(&mut unknown_chat_fields, key);            }        }        let name = as_string(raw_chat.get("name"));        let device = as_string(raw_chat.get("type"));        let empty = Map::new();        let raw_messages = match raw_chat.get("messages") {            Some(Value::Object(map)) => map,            _ => &empty,        };        let message_count = raw_messages.len() as i64;        // The contacts pass creates a shell for every address-book entry. These        // are the majority of a real export and are not worth reporting        // individually.        if message_count == 0 {            empty_chats += 1;            continue;        }        let kind = classify_jid(jid);        if kind != WceChatKind::Personal {            skipped.push(WceSkippedChat {                jid: jid.clone(),                kind: kind.as_str().to_string(),                name,                messages: message_count,                reason: match kind {                    WceChatKind::Group => "group chat — out of scope for v1".to_string(),                    WceChatKind::Lid => "LID chat — the JID carries no phone number, so the contact cannot be identified".to_string(),                    other => format!("{} chat — not a person-to-person conversation", other.as_str()),                },            });            continue;        }        let Some(phone) = phone_from_jid(jid) else {            skipped.push(WceSkippedChat {                jid: jid.clone(),                kind: kind.as_str().to_string(),                name,                messages: message_count,                reason: "the JID does not contain a usable phone number".to_string(),            });            continue;        };        let mut messages: Vec<WceMessage> = Vec::new();        for row_key in js_key_order(raw_messages) {            let parsed = parse_message(row_key, &raw_messages[row_key]);            for field in &parsed.unknown_fields {                insert_once(&mut unknown_message_fields, field);            }            if parsed.html {                html_messages += 1;            }            match parsed.message {                None => dropped_messages += 1,                Some(message) => messages.push(message),            }        }        // Secondary group signal: in a 1:1 the exporter leaves `sender` null on        // every row. A populated one means the JID lied (or the file was        // merged).        if messages            .iter()            .any(|message| message.sender.is_some() && !message.from_me)        {            skipped.push(WceSkippedChat {                jid: jid.clone(),                kind: WceChatKind::Group.as_str().to_string(),                name,                messages: message_count,                reason: "messages carry per-sender names, so this is a group despite its JID"                    .to_string(),            });            continue;        }        // JS `a.sentAt.localeCompare(b.sentAt)` on a fixed-width ISO instant        // (`YYYY-MM-DDTHH:mm:ss.sssZ` — the timestamp guards keep every year        // inside 2009…2286, so the expanded-year form never appears). ICU and        // code-unit order agree on a set of strings that differ only in ASCII        // digits at the same offsets, so this is a byte sort. Both sorts are        // STABLE, which is what keeps two rows sharing an instant in row-id        // order.        messages.sort_by(|left, right| left.sent_at.cmp(&right.sent_at));        chats.push(WceChat {            jid: jid.clone(),            kind: kind.as_str().to_string(),            phone: Some(phone),            name,            device,            messages,        });    }    if !unknown_message_fields.is_empty() {        warnings.push(format!(            "The export carries message fields this reader does not know: {}. They were ignored — the exporter's JSON is a __dict__ dump with no version marker, so new fields appear without notice.",            unknown_message_fields.join(", ")        ));    }    if !unknown_chat_fields.is_empty() {        warnings.push(format!(            "The export carries chat fields this reader does not know: {}. They were ignored.",            unknown_chat_fields.join(", ")        ));    }    if dropped_messages > 0 {        warnings.push(format!(            "{dropped_messages} message(s) had no usable timestamp and were skipped."        ));    }    Ok(WceParseResult {        chats,        skipped,        empty_chats,        dropped_messages,        html_messages,        unknown_chat_fields,        unknown_message_fields,        warnings,    })}#[cfg(test)]#[path = "wce_tests.rs"]mod tests;