//! 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};usecrate::copy::{Change, Copy, CopyError};usecrate::ids;usecrate::object::{ObjectClient, ObjectError};/// What one batch did at the object.#[derive(Debug, Clone, Default, PartialEq)]pubstructSent {/// 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)]pubenumSinkError { #[error(transparent)]Object(#[from] ObjectError), #[error(transparent)]Copy(CopyError), #[error("{0}")]Io(String),}implFrom<CopyError> forSinkError {/// 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), } }}pubtypeResult<T> = std::result::Result<T, SinkError>;fn note(notes: &mutIngestNotes, key: &str) { *notes.entry(key.to_string()).or_insert(0) += 1;}/// A file the object now holds under `key`.#[derive(Debug, Clone, PartialEq)]pubstructUploaded {pub key: String,pub sha256: String,pub content_type: String,pub size: u64,}/// What opens the importer's copy on first need.typeCopyOpener<'a> = dynFn() -> std::result::Result<std::sync::Arc<Copy>, String> + 'a;pubstructObjectSink<'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<Box<CopyOpener<'a>>>, opened: std::sync::OnceLock<std::sync::Arc<Copy>>,}impl<'a> ObjectSink<'a> {pubfn new(object: &'a ObjectClient, database_id: implInto<String>) -> 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.pubfn with_copy_opener(mutself, open: implFn() -> std::result::Result<std::sync::Arc<Copy>, String> + 'a) -> ObjectSink<'a> {self.opener = Some(Box::new(open));self }/// The importer's own copy, which messages are decided over.pubfn with_copy(mutself, 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> {ifletSome(copy) = self.copy {returnOk(copy); }ifletSome(copy) = self.opened.get() {returnOk(copy); }letSome(open) = &self.opener else {returnErr(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)) }pubfn object(&self) -> &ObjectClient {self.object }pubfn 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.pubfn put_file( &self, path: &Path, name: Option<&str>, content_type: Option<&str>, sent: &mutSent, key_for: implFnOnce(&str, &str) -> String, ) -> Result<Option<Uploaded>> {let (sha256, size) = match ids::sha256_of_file(path) {Ok(read) => read,Err(error) if error.kind() == std::io::ErrorKind::NotFound => returnOk(None),Err(error) => returnErr(SinkError::Io(format!("{}: {error}", path.display()))), };if size == 0 {returnOk(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.pubfn put_sealed_file(&self, path: &Path, name: Option<&str>, content_type: Option<&str>, sent: &mutSent) -> Result<Option<(String, String, u64, String)>> {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).pubfn put_sealed_file_under( &self, path: &Path, name: Option<&str>, content_type: Option<&str>, sent: &mutSent, fk_of: implFnOnce(&str) -> Result<cotton_core::seal::file::FileKey>, ) -> Result<Option<(String, String, u64, String)>> {use cotton_core::seal::file;letmut plain = match std::fs::File::open(path) {Ok(opened) => opened,Err(error) if error.kind() == std::io::ErrorKind::NotFound => returnOk(None),Err(error) => returnErr(SinkError::Io(format!("{}: {error}", path.display()))), };let size = plain.metadata().map_err(|error| SinkError::Io(format!("{}: {error}", path.display())))?.len();if size == 0 {returnOk(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)?;letmut 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.pubfn send(&self, batch: IngestBatch) -> Result<Sent> {letmut 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<IngestMediaFile>, sent: &mutSent) -> 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() {returnOk(()); }// 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() {returnOk(()); } }let media: Vec<IngestMediaFile> = 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) {ifletSome(thread) = copy.outbox_thread(&message.external_id)? { batch.new_thread_id = Some(thread);break; } } }let sealed = copy.is_sealed("message");for file in media {letSome(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; }matchself.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), )?;letSome(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: &mutSent) -> Result<()> {if pictures.is_empty() {returnOk(()); }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)?;letmut still: Vec<WaitingPicture> = 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() {returnOk(()); }letmut changes = Vec::new();for (picture, was_waiting) in &asked {letSome(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 = matchself.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");ifletSome(kept) = keep_waiting(copy, picture, *was_waiting) { still.push(kept); }continue; } other => other?, };if *was_waiting {let _ = std::fs::remove_file(&picture.file.path); }letSome(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; }letmut 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: &mutSent) -> Result<()> {letmut changes = Vec::new();for message in &batch.messages {letSome(poll) = message.meta.as_ref().and_then(|meta| meta.get("poll")).filter(|poll| poll.is_object()) else { continue };letSome(id) = copy.held_message_id(&batch.channel, &message.external_id)? else { continue };letSome(row) = copy.row("message", &id)? else { continue };letmut 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());letmut 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() {returnOk(()); } *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: &mutSent) -> Result<()> {let deleted = copy.deleted_with_files()?;if deleted.is_empty() {returnOk(()); }let ids: Vec<String> = deleted.iter().map(|(id, _)| id.clone()).collect();letmut gone: Vec<String> = 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<Change> = ids .iter() .map(|id| {letmut 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: &mutSent) -> Result<()> {let copy = self.copy()?; copy.refresh(self.object)?;letmut changes: Vec<cotton_core::import::messages_engine::MessageChange> = Vec::new();for vote in votes {letSome(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();letSome(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: &mutSent) -> Result<()> {if work.assets.is_empty() {returnOk(()); }let library = work.library_path.clone();letmut sizes: std::collections::BTreeMap<String, u64> = 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.letSome(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.ifletSome(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);letmut 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.pubfn 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() {letSome(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)]structWaitingPicture { jid: String, is_group: bool, path: std::path::PathBuf, name: Option<String>, content_type: Option<String>,}implWaitingPicture {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<Vec<WaitingPicture>> {Ok(copy.kept(PICTURES_WAITING)?.and_then(|text| serde_json::from_str::<Vec<WaitingPicture>>(&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<WaitingPicture> {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() })}