//! Where every batch a reader emits goes: the personal object. //! //! Media before rows. A file is hashed, its key built, `HEAD` asks whether the //! object holds it, `PUT` sends it when it does not — in parts when it is over //! one request's limit — and only then does a row name the key. A PUT that fails fails the batch, so the reader's cursor (or //! the WhatsApp helper's ack) does not move past it and the next run sends it //! again; a file that is simply not on this Mac is counted and its row goes //! without it. //! //! Messages, and edits, deletes and reactions on messages already sent //! (`MessageChanges`), are decided HERE, by the messages engine run over the //! importer's own copy ([`crate::copy`], sealing plan L8): the copy is brought //! up to the object, the engine plans the thread, its contacts, participants, //! messages and reactions (then the reply links) over it, and the planned rows //! land through one `import_rows` act, sealed when their table is. The object //! matches nothing and reads no sealed word. Calls are decided here the same //! way ([`crate::calls`]), and so are the Photos library's pages //! ([`crate::photos`]): the object's `/v1/import/photos` is never called. WhatsApp statuses are //! not collected (owner, 22 Nov 2026). WhatsApp profile pictures are decided //! over the copy too ([`ObjectSink::send_pictures`]): one fills an empty photo, or //! one still WhatsApp's, and lands with the person's or the group's row. use std::path::Path; use chrono::Utc; use cotton_client::ingest::sources::photos::apple::{format_for, original_path_of, MediaKind, OriginalPath}; use cotton_client::ingest::sources::photos::PhotoWork; use cotton_client::ingest::{IngestBatch, IngestMediaFile, IngestNotes, IngestWork}; use cotton_core::import::envelope::{Direction, EnvelopeMedia, ImportBatch}; use serde_json::{json, Value}; use crate::copy::{Change, Copy, CopyError}; use crate::ids; use crate::object::{ObjectClient, ObjectError}; /// What one batch did at the object. #[derive(Debug, Clone, Default, PartialEq)] pub struct Sent { /// The source's own things the batch carried (messages, calls, the library's assets): a run's progress. pub rows: i64, /// Of those, the ones new at the object: what the panel's count adds. A thing read again (Bring everything in /// again) lands on itself and adds nothing; an edit or a reaction is not a new message. pub new: i64, /// Files put (not counting ones the object held already). pub uploaded: i64, /// Bytes put. pub bytes: i64, /// Counted reasons: missing files, work with no route, … pub notes: IngestNotes, } #[derive(Debug, thiserror::Error, PartialEq)] pub enum SinkError { #[error(transparent)] Object(#[from] ObjectError), #[error(transparent)] Copy(CopyError), #[error("{0}")] Io(String), } impl From for SinkError { /// The object's own refusal stays the object's, so a sign-out is one. fn from(error: CopyError) -> SinkError { match error { CopyError::Object(error) => SinkError::Object(error), other => SinkError::Copy(other), } } } pub type Result = std::result::Result; fn note(notes: &mut IngestNotes, key: &str) { *notes.entry(key.to_string()).or_insert(0) += 1; } /// A file the object now holds under `key`. #[derive(Debug, Clone, PartialEq)] pub struct Uploaded { pub key: String, pub sha256: String, pub content_type: String, pub size: u64, } /// What opens the importer's copy on first need. type CopyOpener<'a> = dyn Fn() -> std::result::Result, String> + 'a; pub struct ObjectSink<'a> { object: &'a ObjectClient, database_id: String, copy: Option<&'a Copy>, /// Opens the copy the first time a batch needs it, so a pass that sends /// no messages never opens it. opener: Option>>, opened: std::sync::OnceLock>, } impl<'a> ObjectSink<'a> { pub fn new(object: &'a ObjectClient, database_id: impl Into) -> ObjectSink<'a> { ObjectSink { object, database_id: database_id.into(), copy: None, opener: None, opened: std::sync::OnceLock::new(), } } /// The importer's own copy, opened by `open` the first time a batch of /// messages needs it. pub fn with_copy_opener(mut self, open: impl Fn() -> std::result::Result, String> + 'a) -> ObjectSink<'a> { self.opener = Some(Box::new(open)); self } /// The importer's own copy, which messages are decided over. pub fn with_copy(mut self, copy: &'a Copy) -> ObjectSink<'a> { self.copy = Some(copy); self } /// The copy, or a refusal by name: messages are never sent undecided. pub(crate) fn copy(&self) -> Result<&Copy> { if let Some(copy) = self.copy { return Ok(copy); } if let Some(copy) = self.opened.get() { return Ok(copy); } let Some(open) = &self.opener else { return Err(SinkError::Copy(CopyError::File("no copy is open: messages are decided over the importer's own copy".into()))); }; let copy = open().map_err(|why| SinkError::Copy(CopyError::File(why)))?; Ok(self.opened.get_or_init(|| copy)) } pub fn object(&self) -> &ObjectClient { self.object } pub fn database_id(&self) -> &str { &self.database_id } /// Put the file at `path` under the key `key_for(sha256, ext)` builds, /// unless the object holds it. `Ok(None)` when the file is not on this /// Mac (counted by the caller); an `Err` when the object refused or could /// not be reached — the row must not name the key. pub fn put_file( &self, path: &Path, name: Option<&str>, content_type: Option<&str>, sent: &mut Sent, key_for: impl FnOnce(&str, &str) -> String, ) -> Result> { let (sha256, size) = match ids::sha256_of_file(path) { Ok(read) => read, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), Err(error) => return Err(SinkError::Io(format!("{}: {error}", path.display()))), }; if size == 0 { return Ok(None); } let file_name = name.or_else(|| path.file_name().and_then(|n| n.to_str())); let ext = ids::extension_of(file_name, content_type); let content_type = ids::content_type_of(content_type, &ext); let key = key_for(&sha256, &ext); // A person's own file (a photo, video, book, song or film) is sealed // as it is read and never goes up open; any other goes as it is. let put = self.object.put_person_file(&key, path, size, &content_type)?; if put > 0 { sent.uploaded += 1; sent.bytes += put as i64; } Ok(Some(Uploaded { key, sha256, content_type, size, })) } /// A sealed table's file (sealing plan L8): sealed with a fresh per-file /// key (`cotton_core::seal::file`) into a scratch file, then put under a /// random key in this database's `sealed/` folder, in parts when it is /// over one request's limit. The object learns neither the bytes nor their /// hash. `Ok(None)` when the file is not on this Mac; the answer is the /// key, the file's own type, its plain size and the file key's text. pub fn put_sealed_file(&self, path: &Path, name: Option<&str>, content_type: Option<&str>, sent: &mut Sent) -> Result> { self.put_sealed_file_under(path, name, content_type, sent, |_| Ok(cotton_core::seal::file::FileKey::random())) } /// [`ObjectSink::put_sealed_file`] under the file key `fk_of` makes from /// the file's random object key (a story's derived one). pub fn put_sealed_file_under( &self, path: &Path, name: Option<&str>, content_type: Option<&str>, sent: &mut Sent, fk_of: impl FnOnce(&str) -> Result, ) -> Result> { use cotton_core::seal::file; let mut plain = match std::fs::File::open(path) { Ok(opened) => opened, Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(None), Err(error) => return Err(SinkError::Io(format!("{}: {error}", path.display()))), }; let size = plain.metadata().map_err(|error| SinkError::Io(format!("{}: {error}", path.display())))?.len(); if size == 0 { return Ok(None); } let file_name = name.or_else(|| path.file_name().and_then(|n| n.to_str())); let ext = ids::extension_of(file_name, content_type); let content_type = ids::content_type_of(content_type, &ext); let key = file::object_key(&self.database_id); let fk = fk_of(&key)?; let mut scratch = tempfile::NamedTempFile::new().map_err(|error| SinkError::Io(error.to_string()))?; let sealed_size = file::seal_file(&fk, &key, &mut plain, scratch.as_file_mut()).map_err(|error| SinkError::Io(format!("{}: {error}", path.display())))?; if sealed_size > crate::object::PART_BYTES { self.object.put_media_in_parts(&key, scratch.path(), sealed_size, "application/octet-stream")?; } else { let bytes = std::fs::read(scratch.path()).map_err(|error| SinkError::Io(error.to_string()))?; self.object.put_media(&key, bytes, "application/octet-stream")?; } sent.uploaded += 1; sent.bytes += sealed_size as i64; Ok(Some((key, content_type, size, fk.text()))) } /// Send one batch. pub fn send(&self, batch: IngestBatch) -> Result { let mut sent = Sent::default(); match batch.work { IngestWork::Messages { request, media } => self.send_messages(*request, media, &mut sent)?, IngestWork::Calls { calls } => { if !calls.is_empty() { let copy = self.copy()?; copy.refresh(self.object)?; let namespace = copy.namespace_for(&["call"])?; let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true); for chunk in calls.chunks(crate::object::IMPORT_ROWS) { let (_, landed) = copy.landing(self.object, |landing| { let changes = crate::calls::plan_calls(landing, &namespace, chunk, &now)?; landing.apply_as_named(&changes) })?; sent.new += landed.created_in(&["call"]); } sent.rows += calls.len() as i64; } } IngestWork::Photos(work) => self.send_photos(*work, &mut sent)?, IngestWork::MessageChanges { workspace_id, channel, changes } => { if !changes.is_empty() { let copy = self.copy()?; copy.refresh(self.object)?; for chunk in changes.chunks(crate::object::CHANGES_PER_CALL) { let input = json!({ "workspaceId": workspace_id, "channel": channel, "changes": chunk }); copy.landing(self.object, |landing| { let plan = landing.plan("changes", &input)?; landing.apply(&Change::from_plan(&plan["changes"])?) })?; } sent.rows += changes.len() as i64; self.erase_deleted_files(copy, &mut sent)?; } } IngestWork::PollVotes { workspace_id, channel, votes } => { if !votes.is_empty() { self.count_votes(&workspace_id, &channel, &votes, &mut sent)?; } } IngestWork::ProfilePictures { pictures, .. } => self.send_pictures(&pictures, &mut sent)?, } Ok(sent) } fn send_messages(&self, mut batch: ImportBatch, media: Vec, sent: &mut Sent) -> Result<()> { // The object decides the thread; a reservation the reader made is not // the Mac's to send. batch.new_thread_id = None; if batch.messages.is_empty() { return Ok(()); } // The copy first: whether messages are sealed decides how their files go up. let copy = self.copy()?; copy.refresh(self.object)?; // A message erased from the person's database (a chat's own timer, or a delete) is never brought back, its // file not even read: a new run, Bring everything in again and WhatsApp's history all pass it over. let ids: Vec<&str> = batch.messages.iter().map(|m| m.external_id.as_str()).collect(); let erased = copy.erased_of(&batch.channel, &ids)?; if !erased.is_empty() { *sent.notes.entry("erased:passedOver".to_string()).or_insert(0) += erased.len() as i64; sent.rows += erased.len() as i64; batch.messages.retain(|m| !erased.contains(&m.external_id)); if batch.messages.is_empty() { return Ok(()); } } let media: Vec = media.into_iter().filter(|file| !erased.contains(&file.external_id)).collect(); // A first text Comms sent to a number with no chat yet lands in the chat the phone named for it (the // outbox row's thread), so the person has one chat, not the phone's and then the import's. if batch.dm.is_some() { for message in batch.messages.iter().filter(|m| m.direction == Direction::Out) { if let Some(thread) = copy.outbox_thread(&message.external_id)? { batch.new_thread_id = Some(thread); break; } } } let sealed = copy.is_sealed("message"); for file in media { let Some(message) = batch .messages .iter_mut() .find(|message| message.external_id == file.external_id) else { note(&mut sent.notes, "media:no_message"); continue; }; let channel = batch.channel.clone(); let external_id = file.external_id.clone(); let (key, content_type, size, file_key) = if sealed { // A sealed file goes up under a random key: a message the // object holds with its file already is never read again. if copy.holds_message_media(&channel, &external_id)? { note(&mut sent.notes, "media:held"); continue; } match self.put_sealed_file(&file.path, file.name.as_deref(), file.content_type.as_deref(), sent)? { Some((key, content_type, size, file_key)) => (key, content_type, size, Some(file_key)), None => { note(&mut sent.notes, "media:missing"); continue; } } } else { let uploaded = self.put_file( &file.path, file.name.as_deref(), file.content_type.as_deref(), sent, |sha, ext| ids::message_media_key(&self.database_id, &channel, &external_id, sha, ext), )?; let Some(uploaded) = uploaded else { note(&mut sent.notes, "media:missing"); continue; }; (uploaded.key, uploaded.content_type, uploaded.size, None) }; message.media.get_or_insert_with(Vec::new).push(EnvelopeMedia { key, content_type, name: file.name.clone(), size_bytes: Some(size as f64), width: None, height: None, contact: None, duration_ms: None, playback_key: None, playback_content_type: None, file_key, kind: None, waveform: None, preview: None, }); } let rows = batch.messages.len() as i64; let namespace = copy.namespace_for(crate::copy::MESSAGE_TABLES)?; for chunk in batch.messages.chunks(cotton_core::import::envelope::MAX_BATCH_MESSAGES) { let part = ImportBatch { messages: chunk.to_vec(), ..batch.clone() }; let (_, landed) = land_messages(copy, self.object, &part, &namespace)?; sent.new += landed.created_in(&["message"]); } sent.rows += rows; self.fill_polls(copy, &batch, sent) } /// WhatsApp profile pictures (owner's decision, 11 Oct 2026; Comms showed no display pictures for WhatsApp /// chats, 24 Nov 2026): each fills the photo of the person its number is linked to, or the group's picture, /// when that is empty or still WhatsApp's, decided over the copy. The bytes go up under the holder's WhatsApp /// key (its provenance: a picture someone chose has no `/whatsapp/` and is never replaced) and the row lands /// through the copy, sealed when its table is. A chat no one in Cotton is, or whose picture someone chose, is /// counted and left. fn send_pictures(&self, pictures: &[cotton_client::ingest::profile_pictures::ProfilePicture], sent: &mut Sent) -> Result<()> { if pictures.is_empty() { return Ok(()); } let copy = self.copy()?; copy.refresh(self.object)?; // AVATAR SEAL 2 (3): a picture whose put waits for the data key (a face is sealed, and this Mac is not let in // yet) is kept beside the copy and tried again on the next page of pictures; the rest carry on. let waiting = waiting_pictures(copy)?; let mut still: Vec = Vec::new(); let asked: Vec<(cotton_client::ingest::profile_pictures::ProfilePicture, bool)> = waiting .iter() .filter(|kept| !pictures.iter().any(|p| p.jid == kept.jid)) .map(|kept| (kept.picture(), true)) .chain(pictures.iter().cloned().map(|p| (p, false))) .collect(); if asked.is_empty() { return Ok(()); } let mut changes = Vec::new(); for (picture, was_waiting) in &asked { let Some(holder) = copy.picture_holder(&picture.jid, picture.is_group)? else { note(&mut sent.notes, "picture:notTaken"); continue; }; let key_for = |sha: &str, ext: &str| match holder.table.as_str() { "thread" => ids::whatsapp_group_picture_key(&self.database_id, &holder.id, sha, ext), "message_contact" => ids::whatsapp_contact_picture_key(&self.database_id, &holder.id, sha, ext), _ => ids::whatsapp_avatar_key(&self.database_id, &holder.id, sha, ext), }; let uploaded = match self.put_file(&picture.file.path, picture.file.name.as_deref(), picture.file.content_type.as_deref(), sent, key_for) { Err(SinkError::Object(ref error)) if error.code() == Some(cotton_client::seal::SEAL_KEY_MISSING) => { note(&mut sent.notes, "picture:waitsForKey"); if let Some(kept) = keep_waiting(copy, picture, *was_waiting) { still.push(kept); } continue; } other => other?, }; if *was_waiting { let _ = std::fs::remove_file(&picture.file.path); } let Some(uploaded) = uploaded else { note(&mut sent.notes, "picture:missing"); continue; }; if holder.current.as_deref() == Some(uploaded.key.as_str()) { note(&mut sent.notes, "picture:unchanged"); continue; } let mut patch = serde_json::Map::new(); match holder.table.as_str() { "thread" => { patch.insert("photo_key".into(), Value::from(uploaded.key)); note(&mut sent.notes, "picture:group"); } "message_contact" => { patch.insert("avatar_key".into(), Value::from(uploaded.key)); note(&mut sent.notes, "picture:contact"); } _ => { patch.insert("avatar_key".into(), Value::from(uploaded.key)); // A print cut from a photo is no longer what the avatar shows. patch.insert("avatar_photo_id".into(), Value::Null); note(&mut sent.notes, "picture:person"); } } changes.push(Change { table: holder.table.clone(), id: holder.id, patch: Some(patch) }); } sent.rows += pictures.len() as i64; if !changes.is_empty() { // The holders' ids are the rows' own, as the copy holds them: never keyed again. copy.landing(self.object, |landing| landing.apply_as_named(&changes))?; } // A waiting picture replaced by a newer one of the same chat goes with it. for kept in waiting.iter().filter(|kept| pictures.iter().any(|p| p.jid == kept.jid)) { let _ = std::fs::remove_file(&kept.path); } let list = (!still.is_empty()).then(|| serde_json::to_string(&still).unwrap_or_default()); copy.keep(PICTURES_WAITING, list.as_deref())?; Ok(()) } /// Polls Cotton holds as words (owner, Comms 26 with the Mac on build 6, 23 Nov 2026: the OLD polls of his /// WhatsApp chats). A linked device before build 6 kept a poll's question and not its options; when WhatsApp /// hands the poll again ([`crate::old_polls`] asks the phone for it), the import knows the message and lands /// nothing new, so here the row it already is takes `meta.poll` beside what its meta holds: its id, its replies /// and its reactions stay, and the votes that came with it count on it. A row that holds a poll already is never /// touched, so a later read never resets counted votes. fn fill_polls(&self, copy: &Copy, batch: &ImportBatch, sent: &mut Sent) -> Result<()> { let mut changes = Vec::new(); for message in &batch.messages { let Some(poll) = message.meta.as_ref().and_then(|meta| meta.get("poll")).filter(|poll| poll.is_object()) else { continue }; let Some(id) = copy.held_message_id(&batch.channel, &message.external_id)? else { continue }; let Some(row) = copy.row("message", &id)? else { continue }; let mut meta = row.get("meta").and_then(Value::as_object).cloned().unwrap_or_default(); if meta.get("poll").is_some_and(Value::is_object) { continue; } meta.insert("poll".into(), poll.clone()); let mut patch = serde_json::Map::new(); patch.insert("meta".into(), Value::Object(meta)); changes.push(Change { table: "message".into(), id, patch: Some(patch) }); } if changes.is_empty() { return Ok(()); } *sent.notes.entry("poll:filled".to_string()).or_insert(0) += changes.len() as i64; copy.landing(self.object, |landing| landing.apply(&changes))?; Ok(()) } /// ERASES (owner, FEEDBACK-3, 23 Nov 2026: deleted in WhatsApp means deleted in Cotton). A message deleted for /// everyone keeps only its place ("This message was deleted"): its words went with the delete, and here its /// files go too, from the row and from his storage. Only those messages: a file another message still names /// stays. Run after each page of changes, so a delete that came before this build is cleaned on the first. fn erase_deleted_files(&self, copy: &Copy, sent: &mut Sent) -> Result<()> { let deleted = copy.deleted_with_files()?; if deleted.is_empty() { return Ok(()); } let ids: Vec = deleted.iter().map(|(id, _)| id.clone()).collect(); let mut gone: Vec = Vec::new(); for (_, keys) in &deleted { for key in keys { if !gone.contains(key) && !copy.file_named_elsewhere(key, &ids)? { gone.push(key.clone()); } } } let changes: Vec = ids .iter() .map(|id| { let mut patch = serde_json::Map::new(); patch.insert("media".into(), Value::Array(Vec::new())); patch.insert("body".into(), Value::from("")); Change { table: "message".into(), id: id.clone(), patch: Some(patch) } }) .collect(); copy.landing(self.object, |landing| landing.apply_as_named(&changes))?; // The rows name the files no more; then the files go. for key in &gone { self.object.delete_media(key)?; } *sent.notes.entry("erased:deletedFiles".to_string()).or_insert(0) += gone.len() as i64; Ok(()) } /// Votes on polls already in Cotton (WhatsApp's): each vote's picks read as the poll's option indexes over the /// copy, then planned as `MessageChange::Vote` (the rules replace that voter's entry and count again, CONTRACT /// "Polls shown") and landed sealed. A vote for a poll Cotton does not hold changes nothing and is counted. fn count_votes(&self, workspace_id: &str, channel: &str, votes: &[cotton_client::ingest::PollVote], sent: &mut Sent) -> Result<()> { let copy = self.copy()?; copy.refresh(self.object)?; let mut changes: Vec = Vec::new(); for vote in votes { let Some(id) = copy.held_message_id(channel, &vote.external_id)? else { note(&mut sent.notes, "vote:noPoll"); continue; }; let meta = copy.row("message", &id)?.and_then(|row| row.get("meta").and_then(Value::as_object).cloned()).unwrap_or_default(); let Some(options) = meta.get("poll").and_then(Value::as_object).and_then(|poll| cotton_core::import::poll::picked_options(poll, &vote.options)) else { note(&mut sent.notes, "vote:notAPoll"); continue; }; changes.push(cotton_core::import::messages_engine::MessageChange::Vote { external_id: vote.external_id.clone(), voter: vote.actor.clone(), options, at: vote.at.clone() }); } for chunk in changes.chunks(crate::object::CHANGES_PER_CALL) { let input = json!({ "workspaceId": workspace_id, "channel": channel, "changes": chunk }); copy.landing(self.object, |landing| { let plan = landing.plan("changes", &input)?; landing.apply(&Change::from_plan(&plan["changes"])?) })?; } sent.rows += votes.len() as i64; Ok(()) } /// One page of the library: each original put (sealed, as a person's own /// file is), then the page decided over the copy ([`crate::photos`]) and /// landed through `import_rows`, sealed when a table is. An asset whose /// original is not on this Mac goes into the plan with no sha256 and is /// counted there, never failed. fn send_photos(&self, mut work: PhotoWork, sent: &mut Sent) -> Result<()> { if work.assets.is_empty() { return Ok(()); } let library = work.library_path.clone(); let mut sizes: std::collections::BTreeMap = std::collections::BTreeMap::new(); for asset in work.assets.iter_mut() { // What the plan knows of the bytes is what this pass put, nothing the page carried in. asset.sha256 = None; // A type or a place the plan refuses before its bytes are asked about is never read. let Some(format) = format_for(asset.row.uti.as_deref()) else { continue }; if (asset.row.kind == 1) != (format.kind == MediaKind::Video) { continue; } let path = match original_path_of(asset.row.directory.as_deref(), asset.row.filename.as_deref(), asset.row.saved_asset_type) { OriginalPath::Library(rel) | OriginalPath::Shared(rel) => library.join(rel), OriginalPath::Referenced(abs) => abs.into(), OriginalPath::Unknown(_) => continue, }; let uploaded = self.put_file(&path, asset.row.filename.as_deref(), Some(format.content_type), sent, |sha, _| { crate::photos::media_key_of(&self.database_id, &format, sha) })?; // An original iCloud keeps off this Mac has no key to name: the plan counts it. if let Some(uploaded) = uploaded { sizes.insert(uploaded.key, uploaded.size); asset.sha256 = Some(uploaded.sha256); } } let copy = self.copy()?; copy.refresh(self.object)?; let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true); let mut new_person_id = crate::copy::uuid_v4; let (plan, landed) = copy.landing(self.object, |landing| { let plan = crate::photos::plan_photos(landing, &work, &self.database_id, &sizes, &now, &mut new_person_id)?; landing.apply_as_named(&plan.changes)?; Ok(plan) })?; // The page's pictures, never their sightings, faces or people. New are the pictures the library brings // for the first time: each one's library sighting is new (a picture already in Cotton from a chat gains // its first library sighting and counts; one read again has its sighting and does not). sent.rows += work.assets.len() as i64; sent.new += landed.created_in(&["sighting"]); for (key, by) in plan.notes { *sent.notes.entry(key).or_insert(0) += by; } Ok(()) } } /// One batch of messages decided over `copy` and landed: the engine plans the /// batch (`import`), its rows go into the copy, then each chat's reply links /// are planned over the rows that just landed (`replies`), and the whole goes /// to the object, as the Worker's `/v1/import/messages` did in one write. pub fn land_messages(copy: &Copy, object: &ObjectClient, batch: &ImportBatch, namespace: &str) -> std::result::Result<(Value, crate::copy::Landed), CopyError> { let now = Utc::now().to_rfc3339_opts(chrono::SecondsFormat::Millis, true); let input = json!({ "batch": batch, "namespace": namespace, "now": now }); copy.landing(object, |landing| { let plan = landing.plan("import", &input)?; landing.apply(&Change::from_plan(&plan["changes"])?)?; for chat in plan["chats"].as_array().into_iter().flatten() { let Some(thread) = chat.get("threadId").or_else(|| chat.get("thread_id")).and_then(Value::as_str) else { continue }; let links = landing.plan("replies", &json!({ "threadId": thread, "channel": batch.channel }))?; landing.apply(&Change::from_plan(&links["changes"])?)?; } Ok(plan) }) } /// Where the WhatsApp pictures waiting for the data key are listed, beside the copy's rows (AVATAR SEAL 2 (3)). const PICTURES_WAITING: &str = "pictures_waiting"; /// A WhatsApp picture whose put waits for the data key: its chat and its bytes, kept in a folder beside the copy. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] struct WaitingPicture { jid: String, is_group: bool, path: std::path::PathBuf, name: Option, content_type: Option, } impl WaitingPicture { fn picture(&self) -> cotton_client::ingest::profile_pictures::ProfilePicture { cotton_client::ingest::profile_pictures::ProfilePicture { jid: self.jid.clone(), is_group: self.is_group, file: IngestMediaFile { external_id: self.jid.clone(), path: self.path.clone(), name: self.name.clone(), content_type: self.content_type.clone() }, stored: None, } } } fn waiting_pictures(copy: &Copy) -> Result> { Ok(copy.kept(PICTURES_WAITING)?.and_then(|text| serde_json::from_str::>(&text).ok()).unwrap_or_default().into_iter().filter(|kept| kept.path.exists()).collect()) } /// Keep `picture` to try again: one already kept stays where it is; a new one's bytes are copied beside the copy /// (the link's staged file goes when its page is done). None when there is nowhere to keep it (counted, and left). fn keep_waiting(copy: &Copy, picture: &cotton_client::ingest::profile_pictures::ProfilePicture, already: bool) -> Option { let path = if already { picture.file.path.clone() } else { let folder = copy.folder()?.join("pictures-waiting"); std::fs::create_dir_all(&folder).ok()?; let name: String = picture.jid.chars().map(|c| if c.is_ascii_alphanumeric() || c == '.' || c == '-' { c } else { '_' }).collect(); let to = folder.join(name); std::fs::copy(&picture.file.path, &to).ok()?; to }; Some(WaitingPicture { jid: picture.jid.clone(), is_group: picture.is_group, path, name: picture.file.name.clone(), content_type: picture.file.content_type.clone() }) }