//! The content fingerprint of an imported message — the idempotency key for a //! source that carries no ids of its own (WhatsApp's `_chat.txt` export). //! //! `external_id` is unique per (thread, channel), so a re-import must reproduce //! the same ids or every run duplicates the history. The material is CONTENT //! ONLY: the UTC minute the message was sent, its whitespace-collapsed text, //! and its occurrence index among identical same-minute texts in file order. //! No sender, no phone, no direction — identity is decided at import time, can //! be corrected later, and must never move an id. //! //! It lives in the store, not the importer, because the file format owns what //! makes two rows the same row: the v5 migration computes exactly this from //! stored rows and the importer computes it from the export. use std::collections::HashMap; use sha2::{Digest, Sha256}; use super::{EncodeError, Result}; use crate::js; pub const CONTENT_EXTERNAL_ID_PREFIX: &str = "txt2:"; /// Minute precision, in UTC: exports round seconds off in some locales /// (Android writes `hh:mm`, iOS `h:mm:ss`), so the bucket is the coarser of the /// two or the same chat re-exported from another phone would hash differently. pub fn minute_bucket(iso_instant: &str) -> Result { let ms = js::parse_date_ms(iso_instant).ok_or_else(|| { EncodeError(format!( "minuteBucket: not a parseable instant: {iso_instant}" )) })?; let iso = js::to_iso_string(ms).ok_or_else(|| { EncodeError(format!( "minuteBucket: not a parseable instant: {iso_instant}" )) })?; Ok(iso.chars().take(16).collect()) } /// Layout is discarded, content is kept — a re-export can rewrap, never /// re-word. JS `body.replace(/\s+/g, " ").trim()`. pub fn normalize_body_for_id(body: &str) -> String { js::collapse_whitespace_and_trim(body) } /// JSON, not delimiter-joined: injective, so no body can forge another's /// material. pub(crate) fn material(parts: &[serde_json::Value]) -> String { js::json_stringify(&serde_json::Value::Array(parts.to_vec())) } /// `sha256(material)` as hex, truncated to 32 characters — the form every /// fingerprint in this module family uses. pub(crate) fn digest32(input: &str) -> String { hex::encode(Sha256::digest(input.as_bytes())) .chars() .take(32) .collect() } pub struct ContentFingerprintInput<'a> { pub sent_at: &'a str, pub body: &'a str, /// 0 for the first message with this (minute, body), 1 for the next, … pub occurrence: u64, } pub fn content_fingerprint(input: &ContentFingerprintInput<'_>) -> Result { let material = material(&[ minute_bucket(input.sent_at)?.into(), normalize_body_for_id(input.body).into(), input.occurrence.into(), ]); Ok(format!( "{CONTENT_EXTERNAL_ID_PREFIX}{}", digest32(&material) )) } /// Keyed on the same (minute, body) the hash uses, so two runs over one file /// walk the same sequence. One counter per THREAD: occurrence is scoped to the /// chat the message belongs to, because that is the scope `external_id` is /// unique in. #[derive(Default)] pub struct ContentOccurrenceCounter { seen: HashMap, } impl ContentOccurrenceCounter { pub fn new() -> Self { Self::default() } pub fn next(&mut self, sent_at: &str, body: &str) -> Result { let key = material(&[ minute_bucket(sent_at)?.into(), normalize_body_for_id(body).into(), ]); let count = self.seen.entry(key).or_insert(0); let value = *count; *count += 1; Ok(value) } }