//! WhatsApp as a linked device: the live stream and the on-demand history of a//! number this Mac is linked to, read from the `cotton-whatsapp-link` helper.//!//! The helper (apps/cotton-whatsapp-link, Go over whatsmeow) holds the session//! and keeps every message it has not yet handed over in a durable outbox. This//! reader PULLS that outbox over the helper's Unix socket (`events`), turns it//! into the same batches the iPhone-backup reader makes, and ACKS a page only//! after every batch from it was written — so a message is never lost between//! the helper and the file, and a re-read writes nothing twice.//!//! **One row per WhatsApp message across every door.** A linked device sees//! WhatsApp's own message ids — the stanza ids the iPhone backup stores — so a//! message read both ways meets the unique index. Groups are keyed by JID//! exactly as the backup keys them, and the reserved thread id is the backup's//! own derivation, so the two readers land in one thread. An export row (no id,//! keyed by minute + text) is taken over by the import engine when the same//! message arrives here.//!//! This module only reads. What goes into a chat is the owner's own taps in//! Comms (texts, replies, files, reactions, edits, deletes for everyone, polls,//! votes, and a block or a chat's delete), through the `outbox` the Mac drains//! (`crates/cotton-mac/src/outbox.rs`) and the helper's send files.use std::collections::{BTreeMap, BTreeSet};use std::io::{BufRead, BufReader, Write};use std::os::unix::net::UnixStream;use std::path::{Path, PathBuf};use std::sync::Mutex;use std::time::Duration;use cotton_core::import::whatsapp_keys::{whatsapp_group_key, whatsapp_thread_id};use cotton_core::import::adapters::wce::phone_from_jid;use cotton_core::import::messages_engine::{MessageChange, MEDIA_ONLY_META};use cotton_core::import::envelope::{Direction, EnvelopeCounterpart, EnvelopeMedia, EnvelopeMessage, EnvelopeThread, EnvelopeThreadParticipant,ImportBatch,};use cotton_store::file_identity::Namespace;use cotton_store::protocol::js;use serde::Deserialize;use serde_json::{json, Map, Value};usecrate::ingest::{ count, Emit, IngestBatch, IngestMediaFile, IngestNotes, IngestSource, IngestWork, ReadOutcome,SourceId, SourceStatus, Triggers, MAX_ENVELOPES_PER_BATCH,};/// The helper's protocol version; a helper speaking another is refused.pubconst PROTOCOL_VERSION: i64 = 1;/// What every row this reader writes says it came from (`meta.source.service`).pubconst LINK_SERVICE: &str = "WhatsApp linked device";/// The socket inside the helper's folder. The folder also holds the helper's/// session store and outbox; its path must stay short (a Unix socket path is/// capped at 104 bytes on macOS).pubconst SOCKET_NAME: &str = "link.sock";/// How many outbox events one `events` call asks for.const PAGE: usize = 500;/// A group whose name the helper never learned still needs a title: the/// thread table refuses a blank one.const UNNAMED_GROUP: &str = "WhatsApp group";pubstructWhatsappLinkSourceInput {pub workspace_id: String,pub namespace: Namespace,/// This machine's label, for provenance.pub device: String,/// The helper's folder: `link.sock`, `outbox.db`, `sessions.db`.pub dir: PathBuf,/// Where downloaded attachments are written before the media leg takes them.pub media_dir: PathBuf,}pubstructWhatsappLinkSource { workspace_id: String, namespace: Namespace, device: String, dir: PathBuf, media_dir: PathBuf,/// Download each picture through the helper. Off where the pass has/// nowhere to keep the bytes ([`Self::without_media`]). fetch_media: bool,/// History (the phone's backlog) older than this — unix seconds — is not/// downloaded ([`Self::history_pictures_since`]); live messages always are. history_since: Option<i64>,/// The chats whose WhatsApp profile picture the file would take, as it/// said at the last [`IngestSource::read_settings`]/// (`profile_pictures::wanted_chats`): the helper is told these, and a/// picture for any other chat is passed over. pictures_wanted: Mutex<BTreeSet<String>>,}/// The chat WhatsApp posts every status (stories) to. Cotton collects/// messages only (owner, 22 Nov 2026): a status a helper from before still/// holds is passed over, counted, and acked with its page.pubconst STATUS_CHAT: &str = "status@broadcast";/// Whether a chat JID is the status feed.pubfn is_status_chat(jid: &str) -> bool { jid == STATUS_CHAT}implWhatsappLinkSource {/// A reader that never asks the helper for a picture's bytes: its message/// is still written (its words, or none), and no history backlog waits on/// a download per picture it cannot keep.pubfn without_media(mutself) -> WhatsappLinkSource {self.fetch_media = false;self }/// Download a HISTORY message's picture only when it was sent at or after/// `since` (unix seconds): a backlog of years must not wait on one round/// trip per picture, most of which WhatsApp no longer holds. Its message/// is still written, saying what it was. Live messages are always fetched./// The chats whose WhatsApp profile picture would be taken, from a host that holds its rows elsewhere (the/// Mac, over its copy) and so has no [`IngestSource::read_settings`] file to read them from.pubfn with_pictures_wanted(self, wanted: BTreeSet<String>) -> WhatsappLinkSource { *self.pictures_wanted.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = wanted;self }pubfn history_pictures_since(mutself, since: i64) -> WhatsappLinkSource {self.history_since = Some(since);self }pubfn new(input: WhatsappLinkSourceInput) -> WhatsappLinkSource {WhatsappLinkSource { workspace_id: input.workspace_id, namespace: input.namespace, device: input.device, dir: input.dir, media_dir: input.media_dir, fetch_media: true, history_since: None, pictures_wanted: Mutex::new(BTreeSet::new()), } }fn socket(&self) -> PathBuf {self.dir.join(SOCKET_NAME) }}/// The digest of a list of chats, as the helper answers it in `hello`/// (`pictures`): the hex SHA-256 of the sorted JIDs, one per line. The Go side/// is apps/cotton-whatsapp-link/pictures.go `picturesDigest`.pubfn pictures_digest(chats: &BTreeSet<String>) -> String {use sha2::{Digest, Sha256};let joined = chats.iter().map(String::as_str).collect::<Vec<_>>().join("\n"); hex::encode(Sha256::digest(joined.as_bytes()))}/// Tell the helper which chats' profile pictures it may ask WhatsApp about/// (`pictures`), when its own list (the digest in `hello`) differs — the/// serving Mac drains every few seconds, and an unchanged list is never sent/// again. A helper too old to keep a list says no digest and is told nothing:/// its messages still come.fn tell_pictures( client: &mutLinkClient, hello: &Value, wanted: &BTreeSet<String>, notes: &mutIngestNotes,) -> Result<(), String> {letSome(theirs) = hello.get("pictures").and_then(Value::as_str) else {returnOk(()); };if theirs == pictures_digest(wanted) {returnOk(()); }let chats: Vec<&String> = wanted.iter().collect(); client .call("pictures", json!({ "chats": chats }), Duration::from_secs(30)) .map_err(|error| error.to_string())?; count(notes, "picture:told", wanted.len() as i64);Ok(())}/* ------------------------------------------------------------ the wire -- *//// One durable event from the helper's outbox. The Go side of this contract is/// apps/cotton-whatsapp-link/protocol.go; change both.#[derive(Debug, Clone, Deserialize)]pubstructWireEvent {pub seq: i64,pub event: String, #[serde(default)]pub account: String, #[serde(default)]pub chat: String, #[serde(default)]pub name: String, #[serde(default)]pub is_group: bool, #[serde(default)]pub target: String, #[serde(default)]pub state: String, #[serde(default)]pub message: Option<WireMessage>,/// poll_vote: the options picked, as WhatsApp hashes them. #[serde(default)]pub votes: Vec<String>,}/// A poll's options in WhatsApp's order and how many one voter may pick (0: any).#[derive(Debug, Clone, Default, Deserialize)]pubstructWirePoll { #[serde(default)]pub options: Vec<String>, #[serde(default)]pub selectable: u32,}#[derive(Debug, Clone, Deserialize)]pubstructWireMessage {pub id: String,pub chat: String, #[serde(default)]pub sender: String, #[serde(default)]pub from_me: bool, #[serde(default)]pub is_group: bool, #[serde(default)]pub chat_name: String,pub ts: i64, #[serde(default)]pub push_name: String,pub kind: String, #[serde(default)]pub text: String, #[serde(default)]pub quoted_id: String, #[serde(default)]pub edit_of: String, #[serde(default)]pub reaction_to: String,/// Handed back to the helper unchanged in a `media` request. #[serde(default)]pub media: Option<Value>,/// kind poll: its options (`text` is the question). #[serde(default)]pub poll: Option<WirePoll>,/// A file the owner sent from Cotton: the media it lands with, his own copy already in Cotton (the Mac's outbox/// hands it to the helper as `landed`). Never fetched from WhatsApp, never stored again. #[serde(default)]pub landed: Option<Vec<EnvelopeMedia>>,/// kind call: the call's facts in `CallFacts`' shape (the helper's calls.go; chat CONTRACT "WhatsApp calls"). #[serde(default)]pub call: Option<Value>, #[serde(default)]pub origin: String,}/// Why a call to the helper failed.#[derive(Debug)]pubenumLinkError {/// No helper listening: WhatsApp is not linked on this Mac, or the helper is not running.Absent(String),Io(String),/// The helper answered `ok: false`.Refused(String),}impl std::fmt::DisplayforLinkError {fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {matchself {LinkError::Absent(detail) => write!(f, "the WhatsApp helper is not running: {detail}"),LinkError::Io(detail) => write!(f, "talking to the WhatsApp helper failed: {detail}"),LinkError::Refused(detail) => write!(f, "the WhatsApp helper refused: {detail}"), } }}/// A blocking JSON-lines client for the helper's socket — requests only; this/// reader never subscribes.pubstructLinkClient { reader: BufReader<UnixStream>, writer: UnixStream, next_id: i64,}implLinkClient {pubfn connect(socket: &Path) -> Result<LinkClient, LinkError> {if !socket.exists() {returnErr(LinkError::Absent(format!("no socket at {}", socket.display() ))); }let stream =UnixStream::connect(socket).map_err(|error| LinkError::Absent(error.to_string()))?;let writer = stream .try_clone() .map_err(|error| LinkError::Io(error.to_string()))?;Ok(LinkClient { reader: BufReader::new(stream), writer, next_id: 1, }) }/// One request, waiting up to `timeout` for its reply.pubfn call(&mutself, op: &str, args: Value, timeout: Duration) -> Result<Value, LinkError> {let id = self.next_id;self.next_id += 1;letmut request = match args {Value::Object(map) => map, _ => Map::new(), }; request.insert("id".into(), Value::from(id)); request.insert("op".into(), Value::from(op));letmut line = serde_json::to_vec(&Value::Object(request)) .map_err(|error| LinkError::Io(error.to_string()))?; line.push(b'\n');self.writer .write_all(&line) .map_err(|error| LinkError::Io(error.to_string()))?;self.reader .get_ref() .set_read_timeout(Some(timeout)) .map_err(|error| LinkError::Io(error.to_string()))?;loop {letmut text = String::new();let read = self .reader .read_line(&mut text) .map_err(|error| LinkError::Io(error.to_string()))?;if read == 0 {returnErr(LinkError::Io("the helper closed the socket".into())); }let reply: Value = serde_json::from_str(&text).map_err(|error| LinkError::Io(error.to_string()))?;if reply.get("reply").and_then(Value::as_i64) != Some(id) {continue; }if reply.get("ok").and_then(Value::as_bool) == Some(true) {returnOk(reply.get("result").cloned().unwrap_or(Value::Null)); }let error = reply .get("error") .and_then(Value::as_str) .unwrap_or("no reason given");returnErr(LinkError::Refused(error.to_string())); } }/// `hello`, refusing a helper that speaks another protocol version.pubfn hello(&mutself) -> Result<Value, LinkError> {let hello = self.call("hello", json!({}), Duration::from_secs(10))?;let version = hello.get("version").and_then(Value::as_i64).unwrap_or(0);if version != PROTOCOL_VERSION {returnErr(LinkError::Refused(format!("the helper speaks protocol {version}, this build speaks {PROTOCOL_VERSION}" ))); }Ok(hello) }}/* ------------------------------------------------------- the batching -- *//// The messages of one chat on one linked number, in outbox order.#[derive(Default)]structChat { account: String, jid: String, is_group: bool, name: String, messages: Vec<WireMessage>,}/// What the batches of one outbox page need from the helper's media cache.pubtraitMediaFetch {/// Download one attachment to `dest`. `Ok(false)` when the file cannot be/// had: WhatsApp no longer holds it, or its pointer can fetch nothing (the/// helper's `unfetchable`). An `Err` is worth asking again: the page waits.fn fetch(&mutself, account: &str, pointer: &Value, dest: &Path) -> Result<bool, String>;/// Whether this message's picture is asked for at all. A message whose/// picture was never fetched, or cannot be had, is still written — saying/// what it was when it has no words.fn fetching(&self, _message: &WireMessage) -> bool {true }/// Download the profile picture WhatsApp shows for `chat` to `dest`./// `Ok(false)` when there is none, or its owner hides it from this number.fn picture(&mutself, _account: &str, _chat: &str, _dest: &Path) -> Result<bool, String> {Ok(false) }}/// The fetch a reader without media uses: it never asks.structNoMedia;implMediaFetchforNoMedia {fn fetch(&mutself, _account: &str, _pointer: &Value, _dest: &Path) -> Result<bool, String> {Ok(false) }fn fetching(&self, _message: &WireMessage) -> bool {false }}/// Turn one page of outbox events into import batches, with each batch's/// attachments already on disk.pubfn batches_from_events( events: &[WireEvent], workspace_id: &str, namespace: &Namespace, device: &str, media_dir: &Path, media: &mutdynMediaFetch, notes: &mutIngestNotes,) -> Result<Vec<(ImportBatch, Vec<IngestMediaFile>)>, String> {letmut order: Vec<(String, String)> = Vec::new();letmut chats: BTreeMap<(String, String), Chat> = BTreeMap::new();for event in events {match event.event.as_str() {"message" => {}// A change to a message already written: `changes_from_events`."revoke" => continue,// A vote on a poll already written: `votes_from_events`."poll_vote" => continue,// A chat's profile picture changed: `pictures_from_events`."picture" => continue, other => { count(notes, &format!("read:{other}"), 1);continue; } }letSome(message) = event.message.clone() else { count(notes, "noMessage", 1);continue; };// Edits and reactions change a row that already exists:// `changes_from_events` carries them, after this page's new rows.if !message.edit_of.is_empty() || message.kind == "reaction" || !message.reaction_to.is_empty() {continue; }// A status is not collected: passed over, counted.if is_status_chat(&message.chat) { count(notes, "status:passedOver", 1);continue; }let key = (event.account.clone(), message.chat.clone());let chat = chats.entry(key.clone()).or_insert_with(|| { order.push(key.clone());Chat { account: event.account.clone(), jid: message.chat.clone(), is_group: message.is_group, ..Chat::default() } });if !message.chat_name.trim().is_empty() { chat.name = message.chat_name.trim().to_string(); } chat.messages.push(message); }letmut out = Vec::new();for key in order {let chat = chats.remove(&key).expect("every ordered key has its chat"); out.extend(chat_batches( &chat, workspace_id, namespace, device, media_dir, media, notes, )?); }Ok(out)}/// The page's profile pictures, each downloaded through the helper: the/// newest event per chat, and only for a chat in `wanted` — one whose person/// or group would take it. A picture its owner hides, or one removed, is/// counted and leaves the holder as it is.pubfn pictures_from_events( events: &[WireEvent], wanted: &BTreeSet<String>, media_dir: &Path, media: &mutdynMediaFetch, notes: &mutIngestNotes,) -> Result<Vec<crate::ingest::profile_pictures::ProfilePicture>, String> {letmut newest: BTreeMap<String, &WireEvent> = BTreeMap::new();for event in events.iter().filter(|event| event.event == "picture" && !event.chat.is_empty()) { newest.insert(event.chat.clone(), event); }letmut pictures = Vec::new();for (chat, event) in newest {if !wanted.contains(&chat) { count(notes, "picture:notWanted", 1);continue; }let file_name = format!("picture-{}-{}.jpg", safe_component(&chat), safe_component(&event.target));let dest = media_dir.join(safe_component(&event.account)).join(&file_name);if !media.picture(&event.account, &chat, &dest)? { count(notes, "picture:hidden", 1);continue; } count(notes, "picture:read", 1); pictures.push(crate::ingest::profile_pictures::ProfilePicture { jid: chat.clone(), is_group: event.is_group || chat.ends_with(crate::ingest::profile_pictures::GROUP_SERVER), file: IngestMediaFile { external_id: chat, path: dest, name: Some(file_name), content_type: Some("image/jpeg".to_string()), }, stored: None, }); }Ok(pictures)}/// The page's changes to messages already written — edits, deletes for/// everyone, reactions put on or taken off — in outbox order, so the last word/// on a message is the one that stands. Applied AFTER the page's new rows, so a/// message and its edit in one page land as the edited message./// The page's votes on polls, in order: each a voter's whole choice. A vote whose voter has no number (a hidden id/// the helper could not resolve) is counted and left out.pubfn votes_from_events(events: &[WireEvent], notes: &mutIngestNotes) -> Vec<crate::ingest::PollVote> {letmut votes = Vec::new();for event in events.iter().filter(|e| e.event == "poll_vote" && !e.target.is_empty()) {letSome(message) = event.message.as_ref() else { continue };letSome(at) = js::to_iso_string(message.ts.saturating_mul(1000)) else { count(notes, "noDate", 1);continue; };let actor = if message.from_me {Some("owner".to_string()) } else { phone_from_jid(&message.sender).filter(|_| message.sender.ends_with("@s.whatsapp.net")) };letSome(actor) = actor else { count(notes, "vote:withoutPhone", 1);continue; }; count(notes, "change:vote", 1); votes.push(crate::ingest::PollVote { external_id: event.target.clone(), actor, options: event.votes.clone(), at }); } votes}pubfn changes_from_events(events: &[WireEvent], notes: &mutIngestNotes) -> Vec<MessageChange> {letmut changes = Vec::new();for event in events {letSome(message) = event.message.as_ref() else {continue; };// A status is not collected: no edit, reaction or delete-for-everyone// of one reaches a message row.if is_status_chat(&message.chat) || is_status_chat(&event.chat) {continue; }letSome(at) = js::to_iso_string(message.ts.saturating_mul(1000)) else { count(notes, "noDate", 1);continue; };if event.event == "revoke" {if event.target.is_empty() {continue; } count(notes, "change:revoke", 1); changes.push(MessageChange::Revoke { external_id: event.target.clone(), at });continue; }if event.event != "message" {continue; }if !message.edit_of.is_empty() { count(notes, "change:edit", 1); changes.push(MessageChange::Edit { external_id: message.edit_of.clone(), body: message.text.clone(), at, }); } elseif !message.reaction_to.is_empty() {let actor = if message.from_me {Some("owner".to_string()) } else {let from = if message.sender.is_empty() { &message.chat } else { &message.sender }; phone_from_jid(from).filter(|_| from.ends_with("@s.whatsapp.net")) };letSome(actor) = actor else { count(notes, "change:reactionWithoutPhone", 1);continue; }; count(notes, "change:reaction", 1); changes.push(MessageChange::Reaction { external_id: message.reaction_to.clone(), actor, emoji: message.text.clone(), at, }); } } changes}fn chat_batches( chat: &Chat, workspace_id: &str, namespace: &Namespace, device: &str, media_dir: &Path, media: &mutdynMediaFetch, notes: &mutIngestNotes,) -> Result<Vec<(ImportBatch, Vec<IngestMediaFile>)>, String> {let counterpart_phone = if chat.is_group {None } else { phone_from_jid(&chat.jid) };if !chat.is_group && (counterpart_phone.is_none() || !chat.jid.ends_with("@s.whatsapp.net")) {// A chat known only by a hidden id (LID) names no number to key a// person by; the helper resolves those when the session knows the number. count(notes, "dmWithoutPhone", chat.messages.len() as i64);returnOk(Vec::new()); }let identity = if chat.is_group { format!("group:{}", chat.jid) } else { format!("dm:{}", counterpart_phone.as_deref().unwrap_or("")) };// A sender's label is fixed at their first message in the page, so every// message names a participant the thread block carries.letmut label_by_sender: BTreeMap<String, String> = BTreeMap::new();letmut participants: Vec<EnvelopeThreadParticipant> = Vec::new();letmut envelopes: Vec<EnvelopeMessage> = Vec::new();letmut files: Vec<IngestMediaFile> = Vec::new();for message in &chat.messages {letSome(sent_at) = js::to_iso_string(message.ts.saturating_mul(1000)) else { count(notes, "noDate", 1);continue; };letmut attached: Option<IngestMediaFile> = None;// The message had a file that is not coming with it: never asked for,// gone from WhatsApp, or one its pointer cannot fetch.letmut left_behind = false;let landed = message.landed.clone().filter(|media| !media.is_empty() && media.iter().all(|m| !m.key.is_empty()));if landed.is_some() { count(notes, "media:landedFromCotton", 1); } elseifletSome(pointer) = message.media.as_ref() {if !media.fetching(message) { count(notes, "media:notFetched", 1); left_behind = true; } else {let (file_name, content_type) = media_name(message, pointer);let dest = media_dir .join(safe_component(&chat.account)) .join(&file_name);if media.fetch(&chat.account, pointer, &dest)? { attached = Some(IngestMediaFile { external_id: message.id.clone(), path: dest, name: Some(file_name), content_type, }); } else { count(notes, "media:gone", 1); left_behind = true; } } }// A file left behind, with no words: the row still needs a body (a// message holds words or media), so it says what it was — the message// was sent, and a reply may name it.let label = left_behind.then(|| media_label(message));// A call: its facts go in `meta.call`, which the core draws as the call's line and the chat's last line; its// body is the same words, so the chat's stored preview says it too.let call = message .call .clone() .and_then(|facts| serde_json::from_value::<cotton_core::messages::app::calls::CallFacts>(facts).ok());let call_words = call.as_ref().map(|facts| cotton_core::messages::app::calls::line(&cotton_core::messages::app::list::lines(), facts));let body = ifletSome(words) = call_words.as_deref() { words } elseif !message.text.trim().is_empty() { message.text.as_str() } elseifletSome(label) = label.as_deref() { label } else {"" };if body.is_empty() && attached.is_none() && landed.is_none() { count(notes, &format!("empty:{}", message.kind), 1);continue; }let sender_label = if chat.is_group && !message.from_me {let phone = phone_from_jid(&message.sender);let sender_key = if message.sender.is_empty() { message.push_name.clone() } else { message.sender.clone() };let label = label_by_sender .entry(sender_key) .or_insert_with(|| {let label = if message.push_name.trim().is_empty() { phone.clone().unwrap_or_else(|| "Unknown".to_string()) } else { message.push_name.trim().to_string() }; participants.push(EnvelopeThreadParticipant { label: label.clone(), phone: phone .clone() .filter(|_| message.sender.ends_with("@s.whatsapp.net")), email: None, person_id: None, handle: None, }); label }) .clone();Some(label) } else {None };letmut source = Map::new(); source.insert("service".into(), Value::from(LINK_SERVICE)); source.insert("device".into(), Value::from(device)); source.insert("account".into(), Value::from(chat.account.as_str())); source.insert("externalId".into(), Value::from(message.id.as_str()));// Where the message sits for the helper: `history` asks the phone for// what came before this message, by chat and sender JID. source.insert("chat".into(), Value::from(chat.jid.as_str()));if !message.sender.is_empty() { source.insert("sender".into(), Value::from(message.sender.as_str())); } source.insert("sessionType".into(),Value::from(if chat.is_group { "group" } else { "dm" }), ); source.insert("messageType".into(), Value::from(message.kind.as_str())); source.insert("origin".into(), Value::from(message.origin.as_str()));letmut meta = Map::new(); meta.insert("source".into(), Value::Object(source));ifletSome(facts) = call.as_ref().and_then(|facts| serde_json::to_value(facts).ok()) { meta.insert("call".into(), facts); }ifletSome(poll) = message.poll.as_ref().filter(|p| message.kind == "poll" && !p.options.is_empty()) {// The question, the options and their counts, beside the words (as a text export's poll lands), and// who picked what once votes come. meta.insert("poll".into(), cotton_core::import::poll::linked_poll(message.text.trim(), &poll.options, poll.selectable)); }if message.media.is_some() && message.text.trim().is_empty() {// A picture and nothing else: how the engine finds the export's// '[image omitted]' line this message is, and what it says when// its bytes never arrive. meta.insert(MEDIA_ONLY_META.into(), Value::from(message.kind.as_str())); }ifletSome(file) = attached { files.push(file); } envelopes.push(EnvelopeMessage { phone: None, email: None, sender_label, display_name: None, direction: if message.from_me {Direction::Out } else {Direction::In }, body: body.to_string(), media: landed, sent_at, external_id: message.id.clone(), reply_to_external_id: Some(message.quoted_id.clone()).filter(|id| !id.is_empty()), reactions: None, meta: Some(meta), }); }let title = if chat.name.is_empty() {if chat.is_group { UNNAMED_GROUP.to_string() } else { counterpart_phone.clone().unwrap_or_default() } } else { chat.name.clone() };let thread_id = whatsapp_thread_id(namespace, &identity);letmut out = Vec::new();for chunk in envelopes.chunks(MAX_ENVELOPES_PER_BATCH) {let ids: std::collections::HashSet<&str> = chunk.iter().map(|m| m.external_id.as_str()).collect();let batch = ImportBatch { workspace_id: workspace_id.to_string(), channel: "whatsapp".to_string(), thread: chat.is_group.then(|| EnvelopeThread { kind: "group".to_string(), title: title.clone(), external_key: whatsapp_group_key(&chat.jid), participants: participants.clone(), }), dm: (!chat.is_group).then(|| EnvelopeCounterpart { label: title.clone(), phone: counterpart_phone.clone(), email: None, person_id: None, handle: None, }), messages: chunk.to_vec(), new_thread_id: Some(thread_id.clone()), };let chunk_files = files .iter() .filter(|file| ids.contains(file.external_id.as_str())) .cloned() .collect(); out.push((batch, chunk_files)); }Ok(out)}/// A file name for an attachment: the document's own name, else the message id/// with the extension its type implies.fn media_name(message: &WireMessage, pointer: &Value) -> (String, Option<String>) {let mimetype = pointer .get("mimetype") .and_then(Value::as_str) .map(|value| value.split(';').next().unwrap_or("").trim().to_string()) .filter(|value| !value.is_empty());ifletSome(name) = pointer .get("file_name") .and_then(Value::as_str) .filter(|name| !name.trim().is_empty()) {return ( format!("{}-{}", safe_component(&message.id), safe_component(name)), mimetype, ); }let ext = match mimetype.as_deref() {Some("image/jpeg") => "jpg",Some("image/png") => "png",Some("image/webp") => "webp",Some("image/gif") => "gif",Some("video/mp4") => "mp4",Some("audio/ogg") => "ogg",Some("audio/mpeg") => "mp3",Some("audio/mp4") => "m4a",Some("application/pdf") => "pdf", _ => "bin", }; (format!("{}.{ext}", safe_component(&message.id)), mimetype)}/// One path component, never a way out of the folder./// What a picture never fetched is called in its message's place — the/// words a thread's preview uses for the same kind.fn media_label(message: &WireMessage) -> String {match message.kind.as_str() {"image" => "Photo".to_string(),"video" => "Video".to_string(),"voice" => "Voice message".to_string(),"audio" => "Audio".to_string(),"sticker" => "Sticker".to_string(),"document" => {let name = message .media .as_ref() .and_then(|media| media.get("file_name")) .and_then(Value::as_str) .filter(|name| !name.trim().is_empty());match name {Some(name) => format!("Document · {name}"),None => "Document".to_string(), } } _ => "Attachment".to_string(), }}fn safe_component(text: &str) -> String {let cleaned: String = text .chars() .map(|c| {if c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_' | '@') { c } else { '_' } }) .collect();let trimmed = cleaned.trim_start_matches('.');if trimmed.is_empty() {"_".to_string() } else { trimmed.to_string() }}/// What the media folder holds for one pointer.#[derive(Debug, PartialEq, Eq)]pub(crate) enumHeld {Absent,/// The pointer's own SHA-256 (`file_sha256`, base64) — or, for a pointer/// naming none, its `file_length`.Whole,/// Something else under its name: not the file the pointer names.Wrong,}/// Whether `dest` already holds the file `pointer` names. The helper writes/// a download beside it and renames it into place, so a file there is whole/// unless it is another file; its hash says which. The hash alone: the helper/// checks every download against it, while WhatsApp's `file_length` can/// disagree with the very bytes it verifies — judged by length, such a file/// would be thrown away and fetched again on every pass of a refused page.pub(crate) fn held_whole(dest: &Path, pointer: &Value) -> Held {use base64::Engineas _;use sha2::Digestas _;letOk(meta) = std::fs::metadata(dest) else {returnHeld::Absent; };if !meta.is_file() {returnHeld::Wrong; }letSome(expected) = pointer .get("file_sha256") .and_then(Value::as_str) .and_then(|text| base64::engine::general_purpose::STANDARD.decode(text).ok())else {returnmatch pointer.get("file_length").and_then(Value::as_u64) {Some(length) if meta.len() != length => Held::Wrong, _ => Held::Whole, }; };letOk(mut file) = std::fs::File::open(dest) else {returnHeld::Wrong; };letmut hasher = sha2::Sha256::new();if std::io::copy(&mut file, &mut hasher).is_err() {returnHeld::Wrong; }if hasher.finalize().as_slice() == expected.as_slice() {Held::Whole } else {Held::Wrong }}/// Whether the helper's refusal of a `media` request says the file cannot be/// had, however often it is asked: `gone` from WhatsApp's servers, or/// `unfetchable: <why>` — a pointer without what a download needs (old/// history carries ones with no direct path), or bytes that are not the file/// it names. Every other refusal is worth asking again.pub(crate) fn cannot_be_had(reason: &str) -> bool { reason == "gone" || reason.starts_with("unfetchable: ")}/// Media fetched through the helper's `media` request.structHelperMedia<'a> { client: &'a mutLinkClient, history_since: Option<i64>,}implMediaFetchforHelperMedia<'_> {fn fetching(&self, message: &WireMessage) -> bool {matchself.history_since {Some(since) if message.origin == "history" => message.ts >= since, _ => true, } }fn fetch(&mutself, account: &str, pointer: &Value, dest: &Path) -> Result<bool, String> {// Downloaded on an earlier pass whose page did not land: the bytes// stay until it does, and are never fetched from WhatsApp again.match held_whole(dest, pointer) {Held::Whole => returnOk(true),Held::Wrong => { std::fs::remove_file(dest).map_err(|error| format!("{}: {error}", dest.display()))?; }Held::Absent => {} }let args = json!({ "account": account, "media": pointer, "dest": dest.to_string_lossy() });matchself.client.call("media", args, Duration::from_secs(300)) {Ok(_) => Ok(true),Err(LinkError::Refused(reason)) if cannot_be_had(&reason) => Ok(false),// Any other failure is retried on the next pass: the page is not// acknowledged, so its messages wait in the helper's outbox.Err(error) => Err(error.to_string()), } }fn picture(&mutself, account: &str, chat: &str, dest: &Path) -> Result<bool, String> {// Fetched on an earlier pass whose page did not land (the helper// renames a download into place, so a file there is whole).if dest.is_file() {returnOk(true); }let args = json!({ "account": account, "chat": chat, "dest": dest.to_string_lossy() });matchself.client.call("picture", args, Duration::from_secs(120)) {Ok(_) => Ok(true),Err(LinkError::Refused(reason)) if reason == "gone" => Ok(false),Err(error) => Err(error.to_string()), } }}/* ------------------------------------------------- into a held file -- *//// What one batch of this reader's wrote into a file the caller holds itself.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]pubstructApplied {pub written: i64,pub skipped: i64,}/// One batch of this reader's, written straight into a file this process/// holds — a SERVING Mac's own file, where no ingest queue exists (the queue/// is a replica's, and a serving Mac keeps none of the file it serves). Words,/// edits, deletes and reactions are written through the same engine as the/// queue's; a picture's bytes go straight into `store`, the object store this/// Mac serves its phones from, keyed to the thread the rows land in. Without a/// store (or a thread to key to) the message keeps its words, or says what it/// was, and the picture is counted (`media:notStoredWhenServing`).#[allow(clippy::too_many_arguments)]pubfn apply_to_file( db: &cotton_store::Driver, namespace: &Namespace, batch: IngestBatch, store: Option<(&cotton_store::file_identity::FileId, &dyncrate::messages_import::media::PutObject)>, clock: &dyncrate::seams::Clock, random: &dyncrate::seams::Random, ids: &mutdyn cotton_store::outbox::IdSource, held: cotton_store::mint::Held, notes: &mutIngestNotes,) -> Result<Applied, String> {match batch.work {IngestWork::Messages { request, media } => {letmut request = *request;if !media.is_empty() {let thread = match store {Some(_) => crate::messages_import::resolve_thread(db, &request)?,None => None, };match (store, thread) { (Some((file_id, store)), Some(thread_id)) => { request.new_thread_id = Some(thread_id.clone());let (next, stored) = crate::messages_import::media::attach_media_served( file_id, &thread_id, store, &request, &media, ); request = next;for (key, value) in stored { count(notes, &key, value); } } _ => count(notes, "media:notStoredWhenServing", media.len() as i64), } }let request = &request;let report = crate::messages_import::import_messages_as( db, namespace, request, clock, random, ids, held, ) .map_err(|error| error.to_string())?;Ok(Applied { written: report.totals.inserted, skipped: report.totals.skipped, }) }IngestWork::MessageChanges { workspace_id, channel, changes, } => {let report = crate::messages_import::apply_message_changes_as( db, &workspace_id, &channel, &changes, clock, ids, held, ) .map_err(|error| error.to_string())?;Ok(Applied { written: report.edited + report.revoked + report.reacted + report.unreacted, skipped: 0, }) }// Votes are counted where the poll is decided, on the Mac over its copy (cotton-mac's sink); a file applied// here keeps the poll as it landed.IngestWork::PollVotes { votes, .. } => { count(notes, "vote:notAppliedHere", votes.len() as i64);Ok(Applied::default()) }IngestWork::ProfilePictures { workspace_id, pictures } => {letSome((file_id, store)) = store else { count(notes, "picture:notStoredWhenServing", pictures.len() as i64);returnOk(Applied::default()); };letmut put = |file: &IngestMediaFile, key_for: &dynFn(&str, &str) -> String| {crate::messages_import::media::put_one_file_keyed(file_id, store, file, key_for) };let (changes, _) = crate::ingest::profile_pictures::picture_changes( db, file_id, &workspace_id, &pictures, &mut put, notes, )?;if !changes.is_empty() {crate::messages_import::write_changes_by( db, &changes, clock, ids, held,"messages-import","apply_profile_pictures", )?; }Ok(Applied { written: changes.len() as i64, skipped: 0, }) } _ => Ok(Applied::default()), }}/* ----------------------------------------------------------- the source -- */implIngestSourceforWhatsappLinkSource {fn id(&self) -> SourceId {SourceId::WhatsappLink }fn probe(&self) -> SourceStatus {letmut client = matchLinkClient::connect(&self.socket()) {Ok(client) => client,Err(LinkError::Absent(_)) => {returnSourceStatus::not_found("WhatsApp is not linked on this Mac.") }Err(error) => returnSourceStatus::error(error.to_string()), };match client.hello() {Ok(hello) => {SourceStatus::ready(hello.get("pending").and_then(Value::as_i64).unwrap_or(0)) }Err(error) => SourceStatus::error(error.to_string()), } }fn read(&self, cursor: Option<&str>, emit: Emit<'_>) -> Result<ReadOutcome, String> {letmut notes = IngestNotes::new();letmut client = matchLinkClient::connect(&self.socket()) {Ok(client) => client,Err(LinkError::Absent(_)) => { count(&mut notes, "unavailable", 1);returnOk(ReadOutcome { cursor: cursor.unwrap_or("").to_string(), notes, }); }Err(error) => returnErr(error.to_string()), };let hello = client.hello().map_err(|error| error.to_string())?;let wanted = self.pictures_wanted.lock().map_err(|_| "the pictures list is poisoned".to_string())?.clone();ifself.fetch_media { tell_pictures(&mut client, &hello, &wanted, &mut notes)?; }// Always from the start of what the helper still holds: everything// acknowledged is gone from its outbox, and a helper whose outbox was// recreated restarts its numbering, so a remembered seq could skip.letmut last = cursor.unwrap_or("").to_string();// Every file this page fetched, kept until the helper is told the// page landed: a page refused part way is read again on the next// pass, and its media must not be fetched from WhatsApp again.letmut staged_page: Vec<PathBuf> = Vec::new();loop {let page = client .call("events", json!({ "after": 0, "limit": PAGE }),Duration::from_secs(60), ) .map_err(|error| error.to_string())?;let events: Vec<WireEvent> = serde_json::from_value( page.get("events") .cloned() .unwrap_or(Value::Array(Vec::new())), ) .map_err(|error| format!("the helper's events did not parse: {error}"))?;letSome(top) = events.iter().map(|event| event.seq).max() else {break; };let batches = {letmut helper = HelperMedia { client: &mut client, history_since: self.history_since, };letmut none = NoMedia;let media: &mutdynMediaFetch = ifself.fetch_media { &mut helper } else { &mut none }; batches_from_events( &events, &self.workspace_id, &self.namespace, &self.device, &self.media_dir, media, &mut notes, )? };for (batch, files) in batches {let read = batch.messages.len() as i64;let staged: Vec<PathBuf> = files.iter().map(|file| file.path.clone()).collect(); emit(IngestBatch { work: IngestWork::Messages { request: Box::new(batch), media: files, }, read, cursor: None, })?; staged_page.extend(staged); }let pictures = {letmut helper = HelperMedia { client: &mut client, history_since: self.history_since, };letmut none = NoMedia;let media: &mutdynMediaFetch = ifself.fetch_media { &mut helper } else { &mut none }; pictures_from_events(&events, &wanted, &self.media_dir, media, &mut notes)? };if !pictures.is_empty() {let read = pictures.len() as i64;let staged: Vec<PathBuf> = pictures.iter().map(|picture| picture.file.path.clone()).collect(); emit(IngestBatch { work: IngestWork::ProfilePictures { workspace_id: self.workspace_id.clone(), pictures, }, read, cursor: None, })?; staged_page.extend(staged); }let votes = votes_from_events(&events, &mut notes);if !votes.is_empty() {let read = votes.len() as i64; emit(IngestBatch { work: IngestWork::PollVotes { workspace_id: self.workspace_id.clone(), channel: "whatsapp".to_string(), votes, }, read, cursor: None, })?; }let changes = changes_from_events(&events, &mut notes);if !changes.is_empty() {let read = changes.len() as i64; emit(IngestBatch { work: IngestWork::MessageChanges { workspace_id: self.workspace_id.clone(), channel: "whatsapp".to_string(), changes, }, read, cursor: None, })?; } client .call("ack", json!({ "seq": top }), Duration::from_secs(30)) .map_err(|error| error.to_string())?;// The page landed and its bytes are in the store, so the helper's// downloads are only staging copies now: drop them, or the cache// grows by every picture ever linked.for path in staged_page.drain(..) {let _ = std::fs::remove_file(path); } last = format!("seq:{top}");if events.len() < PAGE {break; } }Ok(ReadOutcome { cursor: last, notes, }) }fn read_settings(&self, db: &cotton_store::Driver, workspace_id: &str) -> Result<(), String> {let wanted = crate::ingest::profile_pictures::wanted_chats(db, workspace_id)?; *self.pictures_wanted.lock().map_err(|_| "the pictures list is poisoned".to_string())? = wanted;Ok(()) }fn triggers(&self) -> Triggers {Triggers {// The helper's outbox journal changes with every message it keeps. watch: vec![self.dir.join("outbox.db-wal")], every_ms: 60_000, } }}#[cfg(test)]#[path = "whatsapp_link_tests.rs"]pub(crate) mod tests;