//! Both adapters converge here: parsed source → §8 envelope + the dry-run //! report. The port of `packages/import-core/src/normalize.ts`. //! //! One normalizer means one place where direction, identity, idempotency and //! provenance are decided, and the adapters stay pure readers of their own //! formats. Adding Telegram later is a third adapter and nothing else. //! //! Identity (spec 2026-08-25): a sender's label is what the export wrote; a //! phone or a person is a HINT the caller may attach (`identity.rs` plans them //! from the address book). A label with no hint still imports — as an //! unidentified participant the person can name from the chat later. The //! message fingerprint never contains identity: it is the store's content //! fingerprint (`txt2:`), so naming someone later moves no id. //! //! ## Two things a Rust caller has to know //! //! **The adapters' parse results are declared HERE.** `ChatTxtParseResult`, //! `WceParseResult` and the rows they carry are this module's input, and this //! is the one module that reads all of them — the `media_items.rs` precedent //! (a row model lives in the engine that reads it). When `adapters/chat_txt` //! and `adapters/wce` are ported they must PRODUCE these types rather than //! redeclare their own, or the two halves of the import will drift in the one //! place a drift is invisible: the shape of the thing being normalized. //! //! **There is no `now`.** The TypeScript's `NormalizeOptions.now` is threaded //! into both builders and neither reads it; `options.now ?? new Date()` is the //! only clock in the file and its value is dead. A pure crate may not //! construct a clock, and porting a parameter nothing reads would be porting a //! latent one, so the option is gone. Every instant in the result comes out of //! the parse. use std::collections::{HashMap, HashSet}; use std::sync::OnceLock; use cotton_store::protocol::fingerprint::message::{ content_fingerprint, ContentFingerprintInput, ContentOccurrenceCounter, }; use cotton_store::protocol::js; use regex::Regex; use serde::{Deserialize, Serialize}; use serde_json::{Map, Value}; use thiserror::Error; use crate::import::envelope::{ Direction, EnvelopeCounterpart, EnvelopeMessage, EnvelopeReaction, EnvelopeThreadParticipant, }; use crate::import::group::{ group_external_key, is_encryption_boilerplate, is_group_event_body, is_group_pseudo_sender, latest_title, GroupTitleEvent, }; use crate::import::identity::{ group_title_events, human_senders, name_key, same_name, ParticipantHint, }; use crate::import::phone::{ looks_national_only, normalize_phone, promote_to_country, sender_looks_like_phone, }; use crate::import::poll::parse_poll_body; use crate::import::text::{collapse_whitespace, js_trim}; /// Provenance stamped into `meta.source` so a row's origin survives in the /// data. pub const WCE_SOURCE: &str = "whatsapp-chat-exporter"; pub const TXT_SOURCE: &str = "whatsapp-chat-txt"; /// A header with a sender and then NOTHING — no text, no attachment marker. /// The iOS exporter writes location pins, contact cards, polls and view-once /// media as exactly this blank shape. The server rejects a message with /// neither body nor media (and the DB CHECK agrees), so the blank gets an /// honest placeholder instead of sinking the whole batch. /// /// Declared in the store's `schema/msgAlbums.v36.ts`, where the migration that /// deletes these rows reads the same letters. The Rust store carries no port /// of the migration ladder yet, so this is the `EMBED_DIMS` precedent: the /// constant is declared here and proved BY PATH against the TypeScript, with /// the loud-null rule (`normalize_tests.rs`). Move it into `cotton-store` the /// day that schema is ported, and the guard moves with it. pub use cotton_rules::messages::preview::UNSUPPORTED_MESSAGE_BODY; // There is deliberately NO truncation heuristic here (ruling 2026-08-27): a // chat that began on an old phone looks exactly like a trimmed export, and the // warning read as an accusation on perfectly good imports. What the export // holds is what gets imported; the parser still records // `starts_with_encryption_notice` as a fact for anything that ever wants it. /// A second sender needs at least this much presence before a chat is called a /// group. const GROUP_MIN_MESSAGES: i64 = 2; const GROUP_MIN_SHARE: f64 = 0.02; // ───────────────────────────────────────────────────────────────────────────── // The adapters' output — this module's input // ───────────────────────────────────────────────────────────────────────────── /// Which component of `a/b/c` is the day. #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum DateOrder { Dmy, Mdy, Ymd, } impl DateOrder { pub const fn as_str(self) -> &'static str { match self { DateOrder::Dmy => "dmy", DateOrder::Mdy => "mdy", DateOrder::Ymd => "ymd", } } } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct TxtAttachment { /// File name inside the export zip, when the export carried media. pub filename: Option, /// True for `` / `image omitted` — the file is not in the /// export. pub omitted: bool, /// The marker as written, for the report. pub label: String, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct TxtMessage { pub sender: String, /// Local wall clock, `YYYY-MM-DDTHH:mm:ss`, with no zone applied yet. pub sent_at_local: String, /// UTC instant, after the adapter's `tzOffset` is applied. pub sent_at: String, pub body: String, pub attachment: Option, pub edited: bool, pub deleted: bool, /// This line is the ALBUM CONTAINER — the empty sender line WhatsApp /// writes immediately before a multi-photo album, with no text and no /// attachment marker of its own. It is scaffolding, not a message. pub album_container: bool, /// 1-based line of the header line. pub line: i64, } /// A recognised system line WITH its timestamp — kept, not just counted, /// because a group import wants the group's own story (creation, renames, /// member changes) in the timeline. The dm route keeps ignoring these. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct TxtSystemLine { pub text: String, pub sent_at: String, pub sent_at_local: String, pub line: i64, } /// One entry of the adapter's `senderCounts`. /// /// The TypeScript's is a `Map`, and its INSERTION ORDER is observable twice — /// `human_senders` hands the labels back in it, and `classify_export`'s /// descending sort is stable over it. So the port is an ordered list, not a /// `HashMap`, and an adapter must fill it in first-appearance order. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SenderCount { pub name: String, pub count: i64, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ChatTxtParseResult { pub messages: Vec, /// System lines recognised and skipped (encryption notice, group events…). pub system_lines: i64, /// The same system lines, timestamped, for the group route. pub system_messages: Vec, /// Lines that matched no header and belonged to no message — should be 0. pub unparsed_lines: i64, /// Album container lines recognised (and marked) in `messages`. pub album_containers: i64, pub date_order: DateOrder, /// False when the corpus was ambiguous and the fallback order was used. pub date_order_inferred: bool, /// A complete WhatsApp export opens with the end-to-end-encryption notice. /// Recorded as a FACT and nothing more (ruling 2026-08-27). pub starts_with_encryption_notice: bool, pub sender_counts: Vec, pub warnings: Vec, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WceReaction { /// The exporter stores a display NAME, or the literal "You" for the owner. pub actor_name: String, pub emoji: String, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WceMessage { /// The `messages` dict key — a DB row id. Unstable across exports. pub row_key: String, /// WhatsApp stanza id. The stable identity, and our `external_id`. pub key_id: Option, pub from_me: bool, /// ISO instant derived from `timestamp`, the only trustworthy time field. pub sent_at: String, /// `meta: true` — an E2E notice, group event, "Message deleted", missed /// call. pub is_system: bool, pub is_media: bool, /// Real text, with the exporter's `
` substitution reversed. pub text: String, pub caption: Option, pub mime: Option, /// `data` when `media` is true — a path INSIDE the export, never a URL. pub media_path: Option, /// The quoted message's `key_id`. pub reply_to_key_id: Option, pub sticker: bool, pub reactions: Vec, /// Group-only display name of the sender; null in a 1:1. pub sender: Option, /// `safe: true` — the exporter marked `data` as containing real HTML. pub contains_html: bool, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WceChat { pub jid: String, /// `WceChatKind`, left as a plain `String` on purpose: this module never /// branches on it, and a kind added by a newer adapter must deserialise /// rather than fail the whole export. pub kind: String, /// The counterparty's phone in canonical form; null when the JID carries /// none. pub phone: Option, pub name: Option, /// Per chat, and a merged export may mix them. pub device: Option, pub messages: Vec, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WceSkippedChat { pub jid: String, pub kind: String, pub name: Option, pub messages: i64, pub reason: String, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct WceParseResult { pub chats: Vec, pub skipped: Vec, /// Address-book shells the contacts pass created — expected, not a /// problem. pub empty_chats: i64, /// Messages dropped for having no usable timestamp. pub dropped_messages: i64, /// Messages whose `data` the exporter flagged as containing HTML. pub html_messages: i64, pub unknown_chat_fields: Vec, pub unknown_message_fields: Vec, pub warnings: Vec, } // ───────────────────────────────────────────────────────────────────────────── // The report // ───────────────────────────────────────────────────────────────────────────── /// One roster line of a group's report. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ReportParticipant { pub display_name: String, pub phone: Option, pub identified: bool, } /// The dry-run report for one conversation — `report.ts`'s `ChatReport`. Only /// the type comes over: the terminal renderer (`formatReport`) is the CLI's, /// and nothing in this crate prints. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ChatReport { /// Absent means "dm" — the shape predates groups. #[serde(default, skip_serializing_if = "Option::is_none")] pub kind: Option, /// Group only. #[serde(default, skip_serializing_if = "Option::is_none")] pub title: Option, /// Group only — the roster the thread block will carry. #[serde(default, skip_serializing_if = "Option::is_none")] pub participants: Option>, /// Group only — group events imported as system lines. #[serde(default, skip_serializing_if = "Option::is_none")] pub system_imported: Option, /// Canonical phone, or null when the source could not supply one. pub phone: Option, pub display_name: Option, pub messages: i64, pub inbound: i64, pub outbound: i64, pub first_sent_at: Option, pub last_sent_at: Option, /// Messages carrying a `reply_to_external_id`. pub reply_refs: i64, /// …of which the quoted message is not in this import. pub unresolved_reply_refs: i64, pub reactions: i64, pub attachments: i64, /// Attachments whose file is not in the export (``). pub omitted_media: i64, /// System lines / system messages recognised and skipped. pub system_skipped: i64, /// `_chat.txt` only — the empty sender lines WhatsApp writes before a /// multi-photo album, recognised as scaffolding and never made into rows. /// Counted so a person reading the report can see the difference between /// "the album imported cleanly" and "a line went missing". pub album_containers_dropped: i64, pub warnings: Vec, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct SkippedChatReport { pub label: String, pub messages: i64, pub reason: String, } fn empty_chat_report(phone: Option, display_name: Option) -> ChatReport { ChatReport { kind: None, title: None, participants: None, system_imported: None, phone, display_name, messages: 0, inbound: 0, outbound: 0, first_sent_at: None, last_sent_at: None, reply_refs: 0, unresolved_reply_refs: 0, reactions: 0, attachments: 0, omitted_media: 0, system_skipped: 0, album_containers_dropped: 0, warnings: Vec::new(), } } // ───────────────────────────────────────────────────────────────────────────── // The result // ───────────────────────────────────────────────────────────────────────────── #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct MediaManifestEntry { /// The sender's canonical phone when known; null for the owner, for system /// lines and for unidentified senders. pub phone: Option, pub external_id: Option, pub sent_at: String, pub filename: Option, pub mime: Option, /// Path as the SOURCE names it — inside the archive, not on this disk. pub source_path: Option, /// True when the export references a file it does not contain. pub omitted: bool, } // NOT `Eq`, for the reason `EnvelopeMessage` is not: an attachment's // `sizeBytes`, `width` and `height` are JSON numbers, so a float rides all the // way up here and a float has no total equality. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NormalizedChat { pub kind: String, /// dm: canonical contact phone when known. Group: always null. pub phone: Option, /// dm: contact display name. Group: the title again, for uniform labels. pub display_name: Option, /// Group only. pub title: Option, /// Group only — `wa:group:`, the thread's stable import identity. pub external_key: Option, /// Group only — the roster the thread block will carry, identified or not. pub participants: Vec, /// dm only — who the other side is: their label, plus a phone/person when /// known. pub counterpart: Option, pub messages: Vec, pub report: ChatReport, } // NOT `Eq`: a chat holds messages, a message holds attachments, and an // attachment's sizes are JSON numbers — a float has no total equality. #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct NormalizeResult { pub chats: Vec, pub skipped_chats: Vec, pub media: Vec, pub warnings: Vec, pub limitations: Vec, pub empty_chats: i64, pub dropped_messages: i64, } /// A sender label the caller could say something about. A bare phone string is /// the CLI's `--participants` file shape; the object is the app's. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(untagged)] pub enum ParticipantHintValue { Phone(String), Hint(ParticipantHint), } impl ParticipantHintValue { fn into_hint(self) -> ParticipantHint { match self { ParticipantHintValue::Phone(phone) => ParticipantHint { phone: Some(phone), person_id: None, }, ParticipantHintValue::Hint(hint) => hint, } } } #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct NormalizeOptions { /// Promote national numbers to international. Off unless the operator says /// so. pub country_code: Option, /// `_chat.txt` only — whose messages are outgoing. pub owner_name: Option, /// `_chat.txt` only — the owner's name came from memory and may not appear /// among the senders (a group they never spoke in). Without this, an owner /// nobody matches is a refusal, because a wrong owner inverts every /// direction. pub owner_may_silent: bool, /// `_chat.txt` only — the counterparty's number when the export shows a /// name. pub contact_phone: Option, /// `_chat.txt` only — the People record the counterparty is known to be. pub contact_person_id: Option, /// `_chat.txt` only — override the display name taken from the export. pub display_name: Option, /// Group exports only — sender label (as the export writes it, case- and /// whitespace-insensitive) → what is known about them. Labels with no /// entry import as unidentified participants; there are no synthetic /// phones, ever. /// /// An ordered list, because the TypeScript's `Record` is insertion-ordered /// and two labels that collapse to one `name_key` resolve LAST-wins. pub participants: Vec<(String, ParticipantHintValue)>, /// Group exports — override the title when no creation/rename event names /// one. pub group_title: Option, /// Group exports — override the derived `wa:group:` external key. pub group_key: Option, } /// The three refusals the TypeScript raises, plus the one the store can. /// /// `Display` is each `Error`'s own sentence VERBATIM, so a CLI or a route that /// already prints those keeps printing them. #[derive(Debug, Error, PartialEq, Eq)] pub enum NormalizeError { #[error( "--owner-name {owner_name} matches nobody in this export. \ The senders it contains are: {senders}. \ Pass the name exactly as it appears there." )] OwnerNameNotFound { /// Already `JSON.stringify`d, as the TypeScript interpolates it. owner_name: String, /// Already `JSON.stringify`d and joined with `", "`. senders: String, }, #[error( "A _chat.txt export identifies senders by display name, so --owner-name is required to tell your messages from theirs." )] OwnerNameRequired, #[error( "No creation or rename event in this export names the group, so pass --group-title. \ The title becomes the thread name and (slugged) its stable import key — keep it the same on re-imports." )] GroupTitleRequired, /// A message whose `sent_at` is not a parseable instant. The TypeScript /// throws out of `contentFingerprint` here; a pure library answers. #[error("{0}")] Fingerprint(String), } impl NormalizeError { fn owner_name_not_found(owner_name: &str, senders: &[String]) -> Self { NormalizeError::OwnerNameNotFound { owner_name: js::json_stringify(&Value::String(owner_name.to_string())), senders: senders .iter() .map(|name| js::json_stringify(&Value::String(name.clone()))) .collect::>() .join(", "), } } } fn fingerprint_error(error: cotton_rules::fingerprint::EncodeError) -> NormalizeError { NormalizeError::Fingerprint(error.to_string()) } // ───────────────────────────────────────────────────────────────────────────── // The format-neutral middle // ───────────────────────────────────────────────────────────────────────────── /// Stats are computed from THIS, so a chat whose counterpart could not be /// determined still produces a full report. #[derive(Debug, Clone)] struct PreparedMessage { direction: Direction, sent_at: String, body: String, /// Real source id, or `None` when the source has none and we must hash. source_id: Option, reply_to_external_id: Option, reactions: Vec, attachment: Option, meta: Map, /// Scaffolding, not a message: WhatsApp's empty sender line before a /// multi-photo album. It still walks the occurrence counter and then emits /// nothing — see `build_chat`. album_container: bool, } #[derive(Debug, Clone, Copy, PartialEq, Eq)] enum ReactionActor { Owner, Contact, } #[derive(Debug, Clone)] struct PreparedReaction { actor: ReactionActor, emoji: String, } /// One attachment, as either adapter describes it. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct PreparedAttachment { pub filename: Option, pub mime: Option, pub omitted: bool, /// The marker as the export wrote it (`image omitted`), for placeholder /// bodies. pub label: Option, } fn leading_number_prefix() -> &'static Regex { static RE: OnceLock = OnceLock::new(); RE.get_or_init(|| Regex::new(r"^[0-9]+-").expect("staging number")) } /// The wire body for a message that has no text of its own — an attachment /// line or an omitted-media marker. The server and the DB both (correctly) /// refuse a row with no content at all, and "nothing" would also be invisible /// in the app. /// /// Applied AFTER the external id is computed from the RAW parsed body, so the /// fingerprint of a media message never depends on what later happened to its /// file — the one property that keeps re-imports idempotent when an upload /// succeeds on one run and is skipped on another. pub fn media_placeholder_body(attachment: &PreparedAttachment) -> String { if attachment.omitted { return format!( "[{}]", attachment.label.as_deref().unwrap_or("media omitted") ); } match attachment.filename.as_deref() { Some(filename) => format!( "[attachment: {}]", leading_number_prefix().replace(filename, "") ), None => "[attachment]".to_string(), } } /// `meta.attachment` with keys only where there is a value. An omitted line /// has no filename and usually no mime — and writing `name: null` here is what /// once blanked a whole chat screen: the reader threw on it until 2026-08-27, /// and the rows written that way are on disk forever (the reader now accepts /// them). pub fn attachment_meta(attachment: &PreparedAttachment) -> Map { let mut out = Map::new(); out.insert("omitted".to_string(), Value::Bool(attachment.omitted)); if let Some(filename) = &attachment.filename { out.insert("name".to_string(), Value::String(filename.clone())); } if let Some(mime) = &attachment.mime { out.insert("mime".to_string(), Value::String(mime.clone())); } out } fn resolve_contact_phone(raw: Option<&str>, country_code: Option<&str>) -> Option { let raw = raw?; normalize_phone(&promote_to_country(raw, country_code)) } /// The body the fingerprint sees: the RAW text — an empty caption stays empty. fn wire_body(body: &str, attachment: Option<&PreparedAttachment>) -> String { if !body.is_empty() { return body.to_string(); } match attachment { Some(attachment) => media_placeholder_body(attachment), None => UNSUPPORTED_MESSAGE_BODY.to_string(), } } /// Envelope items + report for one conversation. /// /// `external_id` prefers the source's own id; the fallback is the store's /// content fingerprint, which needs nothing but the message — so a chat whose /// counterpart is only a name still imports, against a thread that waits for /// its person. fn build_chat( counterpart: Option, prepared: Vec, system_skipped: i64, source: &str, media: &mut Vec, ) -> Result { let phone = counterpart.as_ref().and_then(|c| c.phone.clone()); let display_name = counterpart .as_ref() .filter(|c| !sender_looks_like_phone(&c.label)) .map(|c| c.label.clone()); let mut report = empty_chat_report(phone.clone(), display_name.clone()); report.system_skipped = system_skipped; // `localeCompare` over there, bytes here. Every `sent_at` a normalizer // sees is `…Z` with millisecond precision, so the two orders coincide on // every input this can be handed; both sorts are stable, which is what // keeps two same-instant lines in file order. let mut sorted = prepared; sorted.sort_by(|a, b| a.sent_at.cmp(&b.sent_at)); let mut counter = ContentOccurrenceCounter::new(); let mut messages: Vec = Vec::new(); let known_ids: HashSet<&str> = sorted .iter() .filter_map(|item| item.source_id.as_deref()) .collect(); for item in &sorted { // ── Identity first, because this is where a container is dropped ──── // // ONLY a message with no id of its own consults the counter. A device // backup carries real ids, and advancing the sequence for one of those // would move what occurrence the id-less messages beside it land on — // a silent re-hash of rows nothing about this change should touch. // // An album container is always id-less, and it takes its slot BEFORE // it is dropped. Occurrence means "which of the identical same-minute // texts in the FILE is this", and a caption-less photo hashes the same // empty body as the container above it — so dropping the container // first would shift every album photo one occurrence down, give it a // new id, and duplicate the whole album on the next import. let external_id = match &item.source_id { Some(id) => id.clone(), None => { let occurrence = counter .next(&item.sent_at, &item.body) .map_err(fingerprint_error)?; if item.album_container { report.album_containers_dropped += 1; continue; } content_fingerprint(&ContentFingerprintInput { sent_at: &item.sent_at, body: &item.body, occurrence, }) .map_err(fingerprint_error)? } }; report.messages += 1; if item.direction == Direction::In { report.inbound += 1; } else { report.outbound += 1; } if report.first_sent_at.is_none() { report.first_sent_at = Some(item.sent_at.clone()); } report.last_sent_at = Some(item.sent_at.clone()); if let Some(reply_to) = &item.reply_to_external_id { report.reply_refs += 1; if !known_ids.contains(reply_to.as_str()) { report.unresolved_reply_refs += 1; } } report.reactions += item.reactions.len() as i64; if let Some(attachment) = &item.attachment { report.attachments += 1; if attachment.omitted { report.omitted_media += 1; } } let reactions: Vec = item .reactions .iter() .map(|reaction| EnvelopeReaction { emoji: reaction.emoji.clone(), actor: match reaction.actor { ReactionActor::Owner => "owner".to_string(), // `phone ?? "contact"` — a dm against an unidentified // person still records that SOMEBODY reacted. ReactionActor::Contact => { phone.clone().unwrap_or_else(|| "contact".to_string()) } }, at: None, }) .collect(); let mut meta = Map::new(); meta.insert("source".to_string(), Value::String(source.to_string())); for (key, value) in &item.meta { meta.insert(key.clone(), value.clone()); } if let Some(attachment) = &item.attachment { meta.insert( "attachment".to_string(), Value::Object(attachment_meta(attachment)), ); } messages.push(EnvelopeMessage { phone: phone.clone(), // A WhatsApp export names nobody by an address. email: None, sender_label: None, display_name: display_name.clone(), direction: item.direction, body: wire_body(&item.body, item.attachment.as_ref()), media: None, sent_at: item.sent_at.clone(), external_id: external_id.clone(), reply_to_external_id: item.reply_to_external_id.clone(), reactions: if reactions.is_empty() { None } else { Some(reactions) }, meta: Some(meta), }); if let Some(attachment) = &item.attachment { media.push(MediaManifestEntry { phone: phone.clone(), external_id: Some(external_id), sent_at: item.sent_at.clone(), filename: attachment.filename.clone(), mime: attachment.mime.clone(), source_path: attachment.filename.clone(), omitted: attachment.omitted, }); } } if let Some(phone) = phone.as_deref() { if looks_national_only(phone) { report.warnings.push(format!( "+{phone} has no country code, so it will NOT match the same person when they sign in from the app. Re-run with --country-code if this archive is from one country." )); } } Ok(NormalizedChat { kind: "dm".to_string(), phone, display_name, title: None, external_key: None, participants: Vec::new(), counterpart, messages, report, }) } // ───────────────────────────────────────────────────────────────────────────── // WhatsApp-Chat-Exporter JSON // ───────────────────────────────────────────────────────────────────────────── fn prepare_wce_message(message: &WceMessage) -> PreparedMessage { let mut meta = Map::new(); if message.sticker { meta.insert("sticker".to_string(), Value::Bool(true)); } if message.contains_html { meta.insert("contains_markup".to_string(), Value::Bool(true)); } PreparedMessage { direction: if message.from_me { Direction::Out } else { Direction::In }, sent_at: message.sent_at.clone(), body: message.text.clone(), source_id: message.key_id.clone(), reply_to_external_id: message.reply_to_key_id.clone(), reactions: message .reactions .iter() .map(|reaction| PreparedReaction { // The exporter records a display name and writes the literal // "You" for the owner's own reactions. In a 1:1 there is // exactly one other party, so anything that is not "You" is // the contact. actor: if reaction.actor_name == "You" { ReactionActor::Owner } else { ReactionActor::Contact }, emoji: reaction.emoji.clone(), }) .collect(), attachment: if message.is_media { Some(PreparedAttachment { filename: message.media_path.clone(), mime: message.mime.clone(), omitted: message.mime.as_deref() == Some("media"), label: None, }) } else { None }, meta, // A device backup has real ids and real message rows; there is no such // thing as an album container in it. album_container: false, } } pub fn normalize_wce( parsed: &WceParseResult, options: &NormalizeOptions, ) -> Result { let country_code = options.country_code.as_deref(); let mut media: Vec = Vec::new(); let mut chats: Vec = Vec::new(); let mut hashed_ids = 0i64; for chat in &parsed.chats { let phone = resolve_contact_phone(chat.phone.as_deref(), country_code); let system_messages = chat.messages.iter().filter(|m| m.is_system).count() as i64; let real: Vec<&WceMessage> = chat.messages.iter().filter(|m| !m.is_system).collect(); hashed_ids += real.iter().filter(|m| m.key_id.is_none()).count() as i64; let counterpart = match (&phone, &chat.name) { (Some(phone), name) => Some(EnvelopeCounterpart { label: name.clone().unwrap_or_else(|| format!("+{phone}")), email: None, phone: Some(phone.clone()), person_id: None, handle: None, }), (None, Some(name)) => Some(EnvelopeCounterpart { label: name.clone(), email: None, phone: None, person_id: None, handle: None, }), (None, None) => None, }; chats.push(build_chat( counterpart, real.into_iter().map(prepare_wce_message).collect(), system_messages, WCE_SOURCE, &mut media, )?); } let mut warnings = parsed.warnings.clone(); if hashed_ids > 0 { warnings.push(format!( "{hashed_ids} message(s) had no key_id and fell back to a content hash for idempotency. Re-importing the same file is still safe; importing a DIFFERENT export of the same messages may duplicate them." )); } if parsed.html_messages > 0 { warnings.push(format!( "{} message(s) were flagged by the exporter as containing HTML markup; their text is imported as-is.", parsed.html_messages )); } Ok(NormalizeResult { chats, skipped_chats: parsed .skipped .iter() .map(|skipped| SkippedChatReport { label: skipped.name.clone().unwrap_or_else(|| skipped.jid.clone()), messages: skipped.messages, reason: skipped.reason.clone(), }) .collect(), media, warnings, limitations: vec![ "reactions from an iOS backup (the exporter only reads them on Android)".to_string(), "edited/starred/forwarded flags (the exporter does not extract them)".to_string(), ], empty_chats: parsed.empty_chats, dropped_messages: parsed.dropped_messages, }) } // ───────────────────────────────────────────────────────────────────────────── // _chat.txt // ───────────────────────────────────────────────────────────────────────────── /// `meta` for one `_chat.txt` message: the flags the export decorates a line /// with, plus the poll a multi-line body turns out to be. /// /// ONE function for both routes on purpose — the dm and group normalizers read /// the same file, and a difference between them is a poll that reads as a poll /// in a group and as a paragraph in a one-to-one chat. fn txt_message_meta(message: &TxtMessage) -> Map { let mut meta = Map::new(); if message.edited { meta.insert("edited".to_string(), Value::Bool(true)); } if message.deleted { meta.insert("deleted".to_string(), Value::Bool(true)); } // The BODY is left exactly as the export wrote it: it is what the content // fingerprint hashes, so re-wording a poll would re-import every poll // already imported as a second copy. The reading goes beside the words. if let Some(poll) = parse_poll_body(&message.body) { meta.insert( "poll".to_string(), serde_json::to_value(poll).expect("a poll is plain data"), ); } meta } fn txt_attachment(attachment: &TxtAttachment) -> PreparedAttachment { PreparedAttachment { filename: attachment.filename.clone(), mime: None, omitted: attachment.omitted, label: Some(attachment.label.clone()), } } fn prepare_txt_message(message: &TxtMessage, direction: Direction) -> PreparedMessage { PreparedMessage { direction, sent_at: message.sent_at.clone(), body: message.body.clone(), // The text export carries no ids at all — every id here is a content // hash. source_id: None, reply_to_external_id: None, reactions: Vec::new(), attachment: message.attachment.as_ref().map(txt_attachment), meta: txt_message_meta(message), album_container: message.album_container, } } /// What the export is, once the owner is known. #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] #[serde(tag = "kind", rename_all = "lowercase")] pub enum ExportShape { Dm { /// The other person's label, or `None` when nobody but the owner /// spoke. counterpart: Option, /// Low-count extra "senders" — misread system lines, skipped with a /// warning. strays: Vec, }, Group { /// Every human sender except the owner, in order of first appearance. senders: Vec, titles: Vec, }, } fn is_owner(name: &str, owner_name: &str) -> bool { // WhatsApp writes the literal "You" for the owner in some locales, so it // is always accepted alongside the stated name. same_name(name, owner_name) || name == "You" } /// The one dm/group decision, shared by the normalizer and by the app (which /// needs the labels BEFORE normalizing, to gather identity candidates). A /// group is an export that names itself (a creation/rename event) or in which /// more than one other person has real presence. pub fn classify_export(parsed: &ChatTxtParseResult, owner_name: &str) -> ExportShape { let humans: HashSet<&str> = human_senders_ref(parsed); let mut counted: Vec<(&str, i64)> = parsed .sender_counts .iter() .filter(|entry| humans.contains(entry.name.as_str()) && !is_owner(&entry.name, owner_name)) .map(|entry| (entry.name.as_str(), entry.count)) .collect(); // Descending by count, STABLE — the TypeScript's `b[1] - a[1]`. counted.sort_by_key(|(_, count)| std::cmp::Reverse(*count)); let total: i64 = parsed.sender_counts.iter().map(|entry| entry.count).sum(); let denominator = total.max(1) as f64; let significant = counted .iter() .filter(|(_, count)| { *count >= GROUP_MIN_MESSAGES && (*count as f64) / denominator >= GROUP_MIN_SHARE }) .count(); let titles = group_title_events(parsed); if !titles.is_empty() || significant > 1 { let mut seen: HashSet<&str> = HashSet::new(); let mut senders: Vec = Vec::new(); for message in &parsed.messages { let sender = message.sender.as_str(); if !humans.contains(sender) || is_owner(sender, owner_name) || seen.contains(sender) { continue; } seen.insert(sender); senders.push(sender.to_string()); } return ExportShape::Group { senders, titles }; } ExportShape::Dm { counterpart: counted.first().map(|(name, _)| (*name).to_string()), strays: counted .iter() .skip(1) .map(|(name, _)| (*name).to_string()) .collect(), } } /// `human_senders` without the clones — the labels borrow the parse result. fn human_senders_ref(parsed: &ChatTxtParseResult) -> HashSet<&str> { let owned = human_senders(parsed); let wanted: HashSet = owned.into_iter().collect(); parsed .sender_counts .iter() .map(|entry| entry.name.as_str()) .filter(|name| wanted.contains(*name)) .collect() } pub fn normalize_chat_txt( parsed: &ChatTxtParseResult, options: &NormalizeOptions, ) -> Result { let owner_name = options .owner_name .as_deref() .filter(|name| !js_trim(name).is_empty()) .ok_or(NormalizeError::OwnerNameRequired)?; let sender_names: Vec<&str> = parsed .sender_counts .iter() .map(|entry| entry.name.as_str()) .collect(); if !sender_names.is_empty() && !sender_names.iter().any(|name| is_owner(name, owner_name)) && !options.owner_may_silent { return Err(NormalizeError::owner_name_not_found( owner_name, &human_senders(parsed), )); } let mut warnings = parsed.warnings.clone(); let shape = classify_export(parsed, owner_name); let (counterpart_label, strays) = match shape { ExportShape::Group { titles, .. } => { return normalize_group_chat_txt(parsed, options, owner_name, warnings, &titles); } ExportShape::Dm { counterpart, strays, } => (counterpart, strays), }; let stray_names: HashSet<&str> = strays.iter().map(String::as_str).collect(); if !stray_names.is_empty() { let stray_lines = parsed .messages .iter() .filter(|message| stray_names.contains(message.sender.as_str())) .count(); let listed = strays .iter() .map(|name| js::json_stringify(&Value::String(name.clone()))) .collect::>() .join(", "); warnings.push(format!( "{stray_lines} line(s) were attributed to {listed}, which look like misread system lines rather than participants. They were skipped." )); } let country_code = options.country_code.as_deref(); let raw_phone: Option<&str> = options.contact_phone.as_deref().or_else(|| { counterpart_label .as_deref() .filter(|label| sender_looks_like_phone(label)) }); let phone = resolve_contact_phone(raw_phone, country_code); let label = options .display_name .clone() .or_else(|| counterpart_label.as_deref().map(collapse_whitespace)); // `if (options.contactPersonId)` — the EMPTY string is falsy, so it is not // a person. let person_id = options .contact_person_id .clone() .filter(|value| !value.is_empty()); // `{ label: label ?? `+${phone}` }`, spelled as a total match so the // "neither" arm is the absence rather than a fallback string. let counterpart: Option = match (&label, &phone) { (Some(label), phone) => Some(EnvelopeCounterpart { label: label.clone(), email: None, phone: phone.clone(), person_id, handle: None, }), (None, Some(phone)) => Some(EnvelopeCounterpart { label: format!("+{phone}"), email: None, phone: Some(phone.clone()), person_id, handle: None, }), (None, None) => None, }; if counterpart.is_none() { warnings.push( "This export contains no messages from anyone but you, so there is no contact to import against." .to_string(), ); } // The notice is the chat's, not the person's: iOS attributes it to the // counterpart, and it is not a message anyone sent. let mut boilerplate_dropped = 0i64; let mut usable: Vec = Vec::new(); for message in &parsed.messages { if stray_names.contains(message.sender.as_str()) { continue; } if message.attachment.is_none() && is_encryption_boilerplate(&message.body) { boilerplate_dropped += 1; continue; } let direction = if is_owner(&message.sender, owner_name) { Direction::Out } else { Direction::In }; usable.push(prepare_txt_message(message, direction)); } let mut media: Vec = Vec::new(); let mut chat = build_chat( counterpart, usable, parsed.system_lines + boilerplate_dropped, TXT_SOURCE, &mut media, )?; if !parsed.date_order_inferred { chat.report.warnings.push(format!( "Dates were read as {} because the file did not prove an order. Check the date span above.", parsed.date_order.as_str() )); } Ok(NormalizeResult { chats: vec![chat], skipped_chats: Vec::new(), media, warnings, limitations: txt_limitations(), empty_chats: 0, dropped_messages: 0, }) } /// What a text export structurally cannot carry, in the words a person reads /// before they decide to import. /// /// REACTIONS are the line that matters most and is most often misread: /// nobody's reactions were dropped or skipped, they are simply not in the file /// — a `_chat.txt` has no emoji-reaction lines at all — and the sentence says /// both halves, including the route that DOES carry them. Faking them would be /// worse than the gap, and staying vague about it reads as a bug in the /// importer. fn txt_limitations() -> Vec { vec![ "reply relations — the text export does not record which message a reply quotes".to_string(), "reactions — a text export contains no reactions, so none can be imported. Nothing was skipped: WhatsApp does not write who reacted to what into this file. A device-backup import (route A) does carry them".to_string(), "who voted for what in a poll — the export gives each option's total and nothing else. The question, the options and the counts do import".to_string(), "message ids — every id is a content hash, so importing a DIFFERENT export of the same chat can duplicate messages".to_string(), "timezone — timestamps are device-local wall clock, interpreted with --tz-offset".to_string(), ] } // ───────────────────────────────────────────────────────────────────────────── // _chat.txt — GROUP route (spec 2026-08-16 §3, identity per 2026-08-25) // ───────────────────────────────────────────────────────────────────────────── /// One timeline item of a group thread — a person's message or a group event. #[derive(Debug, Clone)] struct PreparedGroupItem { /// Wire field — the sender's label, set only for inbound non-system /// messages. sender_label: Option, direction: Direction, sent_at: String, body: String, attachment: Option, meta: Map, /// Album scaffolding — counted by the occurrence counter, never emitted. album_container: bool, /// Source line — the chronological tiebreak within a shared timestamp. line: i64, } /// `label` → what is known, keyed by `name_key`. A later entry overwrites an /// earlier one, because `Map.set` does. fn hint_for(participants: &[(String, ParticipantHintValue)]) -> HashMap { let mut by_key = HashMap::new(); for (name, value) in participants { by_key.insert(name_key(name), value.clone().into_hint()); } by_key } fn normalize_group_chat_txt( parsed: &ChatTxtParseResult, options: &NormalizeOptions, owner_name: &str, mut warnings: Vec, titles: &[GroupTitleEvent], ) -> Result { // Reclassify the two attributed event disguises (see `group.rs`). A // message carrying an attachment or an edit mark is always a person, never // an event. let mut real_messages: Vec<&TxtMessage> = Vec::new(); let mut reclassified_events: Vec = Vec::new(); for message in &parsed.messages { let looks_like_event = message.attachment.is_none() && !message.edited && (is_group_pseudo_sender(&message.sender, titles) || is_group_event_body(&message.sender, &message.body)); if looks_like_event { reclassified_events.push(TxtSystemLine { text: message.body.clone(), sent_at: message.sent_at.clone(), sent_at_local: message.sent_at_local.clone(), line: message.line, }); } else { real_messages.push(message); } } let title = options .group_title .clone() .or_else(|| latest_title(titles).map(str::to_string)) .filter(|value| !js_trim(value).is_empty()) .ok_or(NormalizeError::GroupTitleRequired)?; let external_key = options .group_key .clone() .unwrap_or_else(|| group_external_key(&title)); // ── The roster: every human sender except the owner, hinted or not ────── let country_code = options.country_code.as_deref(); let lookup = hint_for(&options.participants); let mut participants: Vec = Vec::new(); let mut phone_by_label: HashMap> = HashMap::new(); let mut national_only: Vec = Vec::new(); for message in &real_messages { let key = name_key(&message.sender); if is_owner(&message.sender, owner_name) || phone_by_label.contains_key(&key) { continue; } let label = collapse_whitespace(&message.sender); let hint = lookup.get(&name_key(&label)); let raw_phone: Option = hint.and_then(|hint| hint.phone.clone()).or_else(|| { if sender_looks_like_phone(&label) { Some(label.clone()) } else { None } }); let phone = raw_phone .as_deref() .and_then(|raw| resolve_contact_phone(Some(raw), country_code)); if let Some(raw) = raw_phone.as_deref() { if phone.is_none() { warnings.push(format!( "{} was given the number {}, which is not usable — they import unidentified.", js::json_stringify(&Value::String(label.clone())), js::json_stringify(&Value::String(raw.to_string())) )); } } phone_by_label.insert(key, phone.clone()); participants.push(EnvelopeThreadParticipant { label: label.clone(), email: None, phone: phone.clone(), // `if (hint?.personId)` — an empty person id is falsy. person_id: hint .and_then(|hint| hint.person_id.clone()) .filter(|value| !value.is_empty()), handle: None, }); if let Some(phone) = phone.as_deref() { if looks_national_only(phone) { national_only.push(format!("{label} (+{phone})")); } } } if !national_only.is_empty() { warnings.push(format!( "No country code on: {} — they will NOT match the same person signing in from the app. Re-run with --country-code or fix the --participants file.", national_only.join(", ") )); } // ── The timeline: people's messages + the group's own events ──────────── let mut items: Vec = Vec::new(); for message in &real_messages { let outbound = is_owner(&message.sender, owner_name); items.push(PreparedGroupItem { sender_label: if outbound { None } else { Some(collapse_whitespace(&message.sender)) }, direction: if outbound { Direction::Out } else { Direction::In }, sent_at: message.sent_at.clone(), body: message.body.clone(), attachment: message.attachment.as_ref().map(txt_attachment), meta: txt_message_meta(message), album_container: message.album_container, line: message.line, }); } let mut boilerplate_dropped = 0i64; let events = parsed .system_messages .iter() .chain(reclassified_events.iter()); for event in events { if event.text.is_empty() { continue; } if is_encryption_boilerplate(&event.text) { boilerplate_dropped += 1; continue; } let mut meta = Map::new(); meta.insert("system".to_string(), Value::Bool(true)); items.push(PreparedGroupItem { sender_label: None, direction: Direction::In, sent_at: event.sent_at.clone(), body: event.text.clone(), attachment: None, meta, album_container: false, line: event.line, }); } let mut media: Vec = Vec::new(); let mut chat = build_group_chat( &title, &external_key, participants, &phone_by_label, items, &mut media, )?; chat.report.system_skipped = boilerplate_dropped; if !parsed.date_order_inferred { chat.report.warnings.push(format!( "Dates were read as {} because the file did not prove an order. Check the date span above.", parsed.date_order.as_str() )); } Ok(NormalizeResult { chats: vec![chat], skipped_chats: Vec::new(), media, warnings, limitations: txt_limitations(), empty_chats: 0, dropped_messages: 0, }) } fn build_group_chat( title: &str, external_key: &str, participants: Vec, phone_by_label: &HashMap>, items: Vec, media: &mut Vec, ) -> Result { let mut report = empty_chat_report(None, Some(title.to_string())); report.kind = Some("group".to_string()); report.title = Some(title.to_string()); report.participants = Some( participants .iter() .map(|participant| ReportParticipant { display_name: participant.label.clone(), phone: participant.phone.clone(), identified: participant.phone.is_some(), }) .collect(), ); let mut sorted = items; sorted.sort_by(|a, b| a.sent_at.cmp(&b.sent_at).then(a.line.cmp(&b.line))); let mut counter = ContentOccurrenceCounter::new(); let mut messages: Vec = Vec::new(); let mut system_imported = 0i64; for item in &sorted { // Every line the export wrote walks the counter, container included — // see `build_chat` for why the ghost slot is what keeps an album's // photos on the ids an earlier build already gave them. let occurrence = counter .next(&item.sent_at, &item.body) .map_err(fingerprint_error)?; if item.album_container { report.album_containers_dropped += 1; continue; } let is_system = item.meta.get("system") == Some(&Value::Bool(true)); report.messages += 1; if is_system { system_imported += 1; } else if item.direction == Direction::In { report.inbound += 1; } else { report.outbound += 1; } if report.first_sent_at.is_none() { report.first_sent_at = Some(item.sent_at.clone()); } report.last_sent_at = Some(item.sent_at.clone()); if let Some(attachment) = &item.attachment { report.attachments += 1; if attachment.omitted { report.omitted_media += 1; } } let external_id = content_fingerprint(&ContentFingerprintInput { sent_at: &item.sent_at, body: &item.body, occurrence, }) .map_err(fingerprint_error)?; let mut meta = Map::new(); meta.insert("source".to_string(), Value::String(TXT_SOURCE.to_string())); for (key, value) in &item.meta { meta.insert(key.clone(), value.clone()); } if let Some(attachment) = &item.attachment { meta.insert( "attachment".to_string(), Value::Object(attachment_meta(attachment)), ); } messages.push(EnvelopeMessage { phone: None, email: None, sender_label: item.sender_label.clone(), display_name: None, direction: item.direction, body: wire_body(&item.body, item.attachment.as_ref()), media: None, sent_at: item.sent_at.clone(), external_id: external_id.clone(), reply_to_external_id: None, reactions: None, meta: Some(meta), }); if let Some(attachment) = &item.attachment { media.push(MediaManifestEntry { phone: item .sender_label .as_deref() .and_then(|label| phone_by_label.get(&name_key(label)).cloned().flatten()), external_id: Some(external_id), sent_at: item.sent_at.clone(), filename: attachment.filename.clone(), mime: attachment.mime.clone(), source_path: attachment.filename.clone(), omitted: attachment.omitted, }); } } report.system_imported = Some(system_imported); Ok(NormalizedChat { kind: "group".to_string(), phone: None, display_name: Some(title.to_string()), title: Some(title.to_string()), external_key: Some(external_key.to_string()), participants, counterpart: None, messages, report, }) } #[cfg(test)] #[path = "normalize_tests.rs"] mod tests;