//! `import.whatsappExport` — a `_chat.txt` export, shared out of WhatsApp or//! picked from Files, read on this phone and written into its own replica.//!//! Route 2 of the procedure “Import years of WhatsApp history into Messages”, back after the port//! stubbed it. **Nothing here decides anything about a message.** Parsing,//! who the owner is, who a sender is, which thread a chat lands in and what a//! re-import skips are all `cotton_core::import`'s, and the rows are written//! through `cotton_client::messages_import` — the applier the Mac's ingest//! sources write with. What this module owns is the ORDER, and the two things//! only a phone knows: where the file is, and which zone its owner stands in.//!//! ## The order, and why//!//! 1. **Read the file** — a `.txt` whole, a `.zip` in place through ranged//! reads (`ZipRangeReader` over a file handle): a 229 MB export costs one//! `_chat.txt` of memory, never the archive.//! 2. **Decide the owner** — `resolve_owner`: a 1:1 export names two people//! and one is the file's title, so the other is you; else the name you//! have been seen under (EVERY one of them, remembered per channel on//! the workspace row);//! else the literal `You`. When none decides the answer is//! `{"needs":"ownerName","senders":[…]}` — a decision for the screen, not//! a refusal — and the name it sends back is remembered for next time.//! 3. **Identify the senders** — `plan_participants`: a label that is a//! number, or a contact WhatsApp already showed under the label; everyone//! else imports as an unidentified participant. No number is ever//! invented, and no person is found by name: a contact's person is who//! its number names (PEOPLE BUILD 2).//! 4. **Normalise** into the envelope, then **probe** the thread the rows//! will land in (a probe never writes) — the media key carries the//! thread, so this has to come before a byte moves.//! 5. **Bytes** — only for messages the probe says WILL insert, so a re-run//! copies and queues nothing: each file is inflated out of the zip into//! a scratch folder and handed to the same media leg the Mac uses,//! which hashes it into the content-addressed store and queues the//! upload in `_media`. Omitted, oversize and unsupported files are//! counted; the message lands without its picture.//! 6. **Rows** — `import_messages`, batch by batch, through the outbox.//!//! Idempotence is the engine's: every message id is a content fingerprint and//! the unique index on `(thread, channel, external_id)` is the guard, so the//! same export twice answers `imported: 0`.use std::fs::File;use std::os::unix::fs::FileExt;use std::path::{Path, PathBuf};use serde_json::{json, Value};use cotton_client::messages_import::media::{attach_media, MediaLeg};use cotton_client::messages_import::{ resolve_thread, write_changes, FileContacts, MediaFile,};use cotton_client::seams::uuid_v4;use cotton_core::import::adapters::chat_txt::{parse_chat_txt, ChatTxtOptions};use cotton_core::import::normalize::ChatTxtParseResult;use cotton_core::import::group::{group_external_key, latest_title};use cotton_core::import::identity::{ chat_title_from_file_name, human_senders, plan_participants, resolve_owner, IdentityContact,IdentitySources, OwnerHints,};use cotton_core::import::media_plan::{ plan_media_uploads, MediaPlanLimits, MediaUploadStatus, SourceMediaEntry,};use cotton_core::import::messages_engine::{probe_import, self_names, set_self_name_change};use cotton_core::import::normalize::{ classify_export, normalize_chat_txt, ExportShape, NormalizeOptions, NormalizeResult,ParticipantHintValue,};use cotton_core::import::post::{batch_body, plan_batches};use cotton_core::import::zip::{ is_content_entry, list_zip_entries_ranged, read_zip_entry_ranged, ZipEntry, ZipError,ZipRangeReader,};use cotton_core::media::keys::{media_limits, MediaKind};use cotton_store::outbox::LocalChange;use cotton_store::Driver;usecrate::handle::CottonHandle;usecrate::methods::MethodError;usecrate::phone::io_trouble::io_refusal;usecrate::shell::client::{ClientController, ImportSeams};/// The method's name, and the label its answer is stamped with.pubconst METHOD: &str = "import.whatsappExport";/// The one channel a `_chat.txt` can be.const CHANNEL: &str = "whatsapp";/// Spec §8's request cap, kept so a chat's reply links resolve within a part.const BATCH_SIZE: i64 = 500;/// The default country a national number is promoted into. The runbook's:/// route 2 defaults to `91` and warns on one it cannot promote.const DEFAULT_COUNTRY_CODE: &str = "91";/// The tables an import touches — what the `data` event names so the inbox/// and the thread re-read.const TABLES: &[&str] = &["cotton_msg_threads","cotton_msg_messages","cotton_msg_thread_participants","cotton_msg_contacts","cotton_workspaces","cotton_imports",];/// What the app asked for.#[derive(Debug, Clone, PartialEq, Eq)]pubstructImportArgs {pub path: PathBuf,/// **What the file was called where it came from**, when the caller knows.////// Two things read it, and the staged path can answer neither. The share/// extension copies into the app group under a UUID, so `path` is/// `…/9F3C-…-A1.zip` — which means `chat_title_from_file_name` saw no/// title and the owner of a 1:1 export whose name was right there on the/// file was asked for anyway (the walk of 15 Sep 2026, finding a), and/// every refusal named a sandbox path at somebody who shared a file/// (finding b). A LEAF name, never a path: see ``display_name``.pub file_name: Option<String>,/// The sender who is the owner, when the screen has asked. Otherwise/// decided (step 2) or asked for.pub owner_name: Option<String>,/// The wall-clock offset the export was written in, `"+05:30"`.pub tz_offset: String,pub country_code: String,}implImportArgs {/// See ``display_name``.fn display_name(&self) -> String { display_name(&self.path, self.file_name.as_deref()) }}/// **The one name a person is ever shown, and the one the owner inference/// reads.** The caller's `fileName` when it gave one, else the file's own leaf/// — and NEVER `path.display()`, which on this phone is a sandbox path a person/// cannot act on and did not ask to see.fn display_name(path: &Path, file_name: Option<&str>) -> String {ifletSome(name) = file_name {return name.to_string(); } path.file_name() .and_then(|value| value.to_str()) .unwrap_or("that file") .to_string()}/// A caller-supplied name, reduced to a leaf with nothing in it that could read/// as a path. The sharing app wrote it, so it is a stranger's text.pub(crate) fn sanitise_file_name(name: &str) -> Option<String> {let leaf = name.rsplit(['/', '\\']).next().unwrap_or(name).trim();let cleaned: String = leaf.chars().filter(|c| !c.is_control()).collect();let cleaned = cleaned.trim();if cleaned.is_empty() || cleaned == "." || cleaned == ".." {returnNone; }Some(cleaned.to_string())}pubfn validate(request: &Value) -> Result<ImportArgs, MethodError> {let args = request.get("args").and_then(Value::as_object).cloned().or_else(|| { request.as_object().cloned() });let args = args.unwrap_or_default();if args.contains_key("bytes") {returnErr(MethodError::new("bad_request","bytes never cross this boundary — write the export to disk and pass its `path`", )); }let path = args .get("path") .and_then(Value::as_str) .map(str::trim) .filter(|value| !value.is_empty()) .ok_or_else(|| MethodError::new("bad_request", "`path` is required: the export file"))?;let path = PathBuf::from(path);let file_name = args .get("fileName") .and_then(Value::as_str) .and_then(sanitise_file_name);// Built before the two refusals below, because both of them name the file// and neither may name a path.let shown = display_name(&path, file_name.as_deref());let extension = path .extension() .and_then(|value| value.to_str()) .map(str::to_ascii_lowercase) .unwrap_or_default();if extension != "txt" && extension != "zip" {returnErr(MethodError::new("bad_request", format!("{shown} is not a WhatsApp export: expected a _chat.txt file or the .zip WhatsApp shares" ), )); }ifletErr(error) = std::fs::metadata(&path) {returnErr(MethodError::new("bad_request", io_refusal(format!("there is no file to import at {shown}"), &path, &error), )); }let owner_name = args .get("ownerName") .and_then(Value::as_str) .map(str::trim) .filter(|value| !value.is_empty()) .map(str::to_string);let tz_offset = args .get("tzOffset") .and_then(Value::as_str) .map(str::trim) .filter(|value| !value.is_empty()) .unwrap_or("+05:30") .to_string();let country_code = args .get("countryCode") .and_then(Value::as_str) .map(str::trim) .filter(|value| !value.is_empty()) .unwrap_or(DEFAULT_COUNTRY_CODE) .to_string();Ok(ImportArgs { path, file_name, owner_name, tz_offset, country_code, })}/// `import.whatsappExport`.pubfn import(handle: &CottonHandle, request: &Value) -> Result<Value, MethodError> {let args = validate(request)?;let client = handle.client();let answer = run(&client, &args)?;Ok(answer)}// ── the source ────────────────────────────────────────────────────────────/// A `.zip` read in place: every read is a range off the handle, so the/// archive is never in memory at once.pub(crate) structFileRanges { file: File, size: u64,}implFileRanges {/// `shown` is the file's DISPLAY name — every message out of this module/// names that and never the path (``display_name``).pub(crate) fn open(path: &Path, shown: &str) -> Result<FileRanges, MethodError> {let unreadable = |error: std::io::Error| {MethodError::new("unreadable", io_refusal(format!("{shown} could not be read"), path, &error), ) };let file = File::open(path).map_err(unreadable)?;let size = file.metadata().map_err(unreadable)?.len();Ok(FileRanges { file, size }) }}implZipRangeReaderforFileRanges {fn size(&self) -> u64 {self.size }fn read(&self, offset: u64, length: u64) -> Result<Vec<u8>, ZipError> {letmut out = vec![0u8; length as usize];self.file .read_exact_at(&mut out, offset) .map_err(|error| ZipError::Reader(format!("read {offset}+{length}: {error}")))?;Ok(out) }}/// Where the transcript came from, and what else the source holds.enumSource {Text,Zip { reader: FileRanges, entries: Vec<ZipEntry>, },}implSource {/// The zip's content entries as the media plan wants them: full name and/// size. A `.txt` holds no files at all, so its plan marks every/// attachment missing.fn media_entries(&self) -> Vec<SourceMediaEntry> {matchself {Source::Text => Vec::new(),Source::Zip { entries, .. } => entries .iter() .map(|entry| SourceMediaEntry { name: entry.name.clone(), size: entry.uncompressed_size as f64, }) .collect(), } }}/// The transcript, and the source it was read out of.fn open_source(path: &Path, shown: &str) -> Result<(String, Source), MethodError> {let extension = path .extension() .and_then(|value| value.to_str()) .map(str::to_ascii_lowercase) .unwrap_or_default();if extension == "txt" {let bytes = std::fs::read(path).map_err(|error| {MethodError::new("unreadable", io_refusal(format!("{shown} could not be read"), path, &error), ) })?;returnOk((String::from_utf8_lossy(&bytes).into_owned(), Source::Text)); }let reader = FileRanges::open(path, shown)?;let entries: Vec<ZipEntry> = list_zip_entries_ranged(&reader) .map_err(|error| MethodError::new("unreadable", format!("{shown}: {error}")))? .into_iter() .filter(is_content_entry) .collect();let transcripts: Vec<&ZipEntry> = entries .iter() .filter(|entry| {let name = entry.name.rsplit('/').next().unwrap_or(&entry.name); name.eq_ignore_ascii_case("_chat.txt") }) .collect();let transcript = match transcripts.as_slice() { [one] => *one, [] => {// Some exporters name the transcript after the chat. Accept a// single `.txt` when there is exactly one; two is ambiguous.let texts: Vec<&ZipEntry> = entries .iter() .filter(|entry| entry.name.to_ascii_lowercase().ends_with(".txt")) .collect();match texts.as_slice() { [one] => *one, _ => {returnErr(MethodError::new("bad_request", format!("{shown} holds no _chat.txt, so it is not a WhatsApp export"), )) } } } _ => {returnErr(MethodError::new("bad_request", format!("{shown} holds more than one _chat.txt; share one chat at a time"), )) } };let bytes = read_zip_entry_ranged(&reader, transcript) .map_err(|error| MethodError::new("unreadable", format!("{shown}: {error}")))?;Ok((String::from_utf8_lossy(&bytes).into_owned(),Source::Zip { reader, entries }, ))}// ── what the file already knows ───────────────────────────────────────────/// Read before the owner is decided: the name this owner was last seen under/// on this channel, and the people the file can identify a sender against.structKnown {/// EVERY name the owner has answered with on this channel, most recent/// first — not the latest one. `messages_engine::self_names` says why. remembered_owners: Vec<String>, sources: IdentitySources,}fn known(db: &Driver, workspace_id: &str) -> Result<Known, String> {let file = FileContacts(db);let remembered_owners = self_names(&file, workspace_id, CHANNEL).map_err(|error| error.to_string())?;// Messaging contacts by display name — the primary phone, which is what a// sender label resolves to. `cotton_msg_contacts` has no declared// statement for "all of them"; this one is scoped to the workspace like// every read of it.let contacts = db .all("SELECT display_name, phone_e164 FROM cotton_msg_contacts \ WHERE workspace_id = ? AND phone_e164 IS NOT NULL AND phone_e164 <> ''", &[rusqlite::types::Value::Text(workspace_id.to_string())], ) .map_err(|error| error.to_string())? .iter() .filter_map(|row| {Some(IdentityContact { name: row.text("display_name")?.to_string(), phone: row.text("phone_e164")?.to_string(), }) }) .collect();// No person is looked up by name here (PEOPLE BUILD 2): a contact's// person is who its number names, read when the contact is.Ok(Known { remembered_owners, sources: IdentitySources { thread_members: Vec::new(), contacts, }, })}// ── the run ───────────────────────────────────────────────────────────────/// The whole act over a controller, so a test can drive it without a handle.pubfn run(client: &ClientController, args: &ImportArgs) -> Result<Value, MethodError> {// MESSAGES LIVE IN THE PERSONAL DATABASE ALONE: an export imported while// a project is on screen is read against and written into the person's// own file, never the one the call named.let _personal = client .name_database(None) .map_err(|reason| MethodError::new("bad_request", reason))?;let shown = args.display_name();let (transcript, source) = open_source(&args.path, &shown)?;let parsed = parse_chat_txt( &transcript, &ChatTxtOptions { tz_offset: args.tz_offset.clone(), ..ChatTxtOptions::default() }, ) .map_err(|error| MethodError::new("bad_request", error.to_string()))?;if parsed.messages.is_empty() {returnErr(MethodError::new("bad_request", format!("{shown} reads as no messages at all — is it a WhatsApp chat export?"), )); }// THE NAME THE FILE CAME UNDER, not the staged copy's. `WhatsApp Chat -// Asha Rao.zip` names the OTHER party, which is how a 1:1 export decides// the owner without asking — and the share extension's UUID copy carries// none of that (the walk of 15 Sep 2026, finding a).let file_name = Some(shown.clone());let workspace_id = client .with_file(|file| Ok(file.workspace_id.to_string())) .map_err(|reason| MethodError::new("unreadable", reason))?;let known = client .with_file(|file| known(file.driver, file.workspace_id)) .map_err(|reason| MethodError::new("unreadable", reason))?;// 2. The owner: the screen's answer wins; else decided; else asked for.let (owner_name, owner_may_silent) = match &args.owner_name {Some(name) => (name.clone(), false),None => match resolve_owner( &parsed, &OwnerHints { remembered_names: known.remembered_owners.clone(), owner_display_name: None, chat_title: chat_title_from_file_name(file_name.as_deref()), }, ) {Some(resolved) => (resolved.name, resolved.may_silent),None => {returnOk(json!({"needs": "ownerName","senders": human_senders(&parsed),"fileName": file_name, })) } }, };// 3 + 4. Identify the senders and normalise.let normalized = normalize(&parsed, &owner_name, owner_may_silent, file_name.as_deref(), &known.sources, args) .map_err(|reason| MethodError::new("bad_request", reason))?;letSome(chat) = normalized.chats.first() else {returnErr(MethodError::new("bad_request","this export contains no messages from anyone but you, so there is no chat to import", )); };let kind = chat.kind.clone();let title = chat .title .clone() .or_else(|| chat.display_name.clone()) .or_else(|| chat.counterpart.as_ref().map(|c| c.label.clone()));let batches = plan_batches(&normalized.chats, BATCH_SIZE).map_err(|error| MethodError::new("bad_request", error.to_string()))?;// The plan for the bytes, off the zip's own directory — no file has been// read yet, and a `.txt` has none to read.let limits = media_limits(MediaKind::Message);let plan = plan_media_uploads( &normalized.media, &source.media_entries(), &MediaPlanLimits { max_bytes: limits.max_bytes as f64, content_types: limits.content_types.iter().map(|value| (*value).to_string()).collect(), }, );let omitted_or_absent = plan.counts.omitted + plan.counts.missing + plan.counts.oversize + plan.counts.unsupported_type;let scratch = client .layout() .client_dir() .join("import-scratch") .join(client.scratch_name());// What the Imports tool's history calls this run: the chat, by the name// the import settled on, else the file it came in.let run_title = match (&kind, &title) { (_, None) => format!("WhatsApp chat {shown}"), (kind, Some(name)) if kind == "group" => format!("WhatsApp group {name}"), (_, Some(name)) => format!("WhatsApp chat with {name}"), };let device_key = client.device_key().get();let sealing = sealing_key(client)?;let outcome = client.import_rows(METHOD, TABLES, &mut |seams| { write_all(seams, &workspace_id, device_key.as_deref(), &owner_name, &run_title, &batches, &plan, &source, &scratch, sealing.as_ref()) });// not a copy: an import's files.let _ = std::fs::remove_dir_all(&scratch);letmut answer = outcome.map_err(|reason| MethodError::new("write_refused", reason))?;ifletValue::Object(map) = &mut answer { map.insert("kind".to_string(), json!(kind)); map.insert("title".to_string(), json!(title)); map.insert("ownerName".to_string(), json!(owner_name));ifletSome(Value::Object(media)) = map.get_mut("media") { media.insert("omitted".to_string(), json!(omitted_or_absent)); } map.insert("warnings".to_string(), json!(normalized.warnings)); }Ok(answer)}fn normalize( parsed: &ChatTxtParseResult, owner_name: &str, owner_may_silent: bool, file_name: Option<&str>, sources: &IdentitySources, args: &ImportArgs,) -> Result<NormalizeResult, String> {let country = Some(args.country_code.as_str());letmut options = NormalizeOptions { country_code: Some(args.country_code.clone()), owner_name: Some(owner_name.to_string()), owner_may_silent, contact_phone: None, contact_person_id: None, display_name: None, participants: Vec::new(), group_title: None, group_key: None, };match classify_export(parsed, owner_name) {ExportShape::Dm { counterpart, .. } => {ifletSome(label) = counterpart {let plan = plan_participants(std::slice::from_ref(&label), sources, country);ifletSome(hint) = plan.hints.first() { options.contact_phone = hint.hint.phone.clone(); options.contact_person_id = hint.hint.person_id.clone(); }// The file's title names the chat the way WhatsApp did; the// sender label is what the transcript says. Prefer the label:// it is what the contact row will be matched by next time. options.display_name = Some(label); } }ExportShape::Group { senders, titles } => {let title = latest_title(&titles) .map(str::to_string) .or_else(|| chat_title_from_file_name(file_name));letSome(title) = title else {returnErr("no creation or rename event in this export names the group, and the file name does not either" .to_string(), ); }; options.group_key = Some(group_external_key(&title)); options.group_title = Some(title);let plan = plan_participants(&senders, sources, country); options.participants = plan .hints .into_iter() .map(|hint| (hint.label, ParticipantHintValue::Hint(hint.hint))) .collect(); } } normalize_chat_txt(parsed, &options).map_err(|error| error.to_string())}/// The data key and database id this import keys its sealed rows' ids/// under, when the kit seals a table it writes: none when nothing it writes/// is sealed. A sealed table with no data key held is refused by name/// (`seal_key_missing`): an import under the plain namespace would land/// another id for every contact and reaction the Mac lands under the keyed/// one, and nothing is ever landed open in its place.fn sealing_key(client: &ClientController) -> Result<Option<(cotton_core::seal::DataKey, String)>, MethodError> {use cotton_client::seal::DataKeyStoreas _;let tables = cotton_client::transport::object::ObjectTables::personal();if !TABLES.iter().any(|t| tables.ours(t).or_else(|| tables.object(t)).is_some_and(|t| t.seal.is_some())) {returnOk(None); }let database = client.current_database().map_err(|why| MethodError::new("not_attached", why))?;let dk = client .data_keys() .data_key(&database) .map_err(|why| MethodError::new("could_not_read", why))? .ok_or_else(|| MethodError::new(cotton_client::seal::SEAL_KEY_MISSING, "chats are sealed, and this phone holds no data key yet: open the vault once (Face ID), then import again"))?;Ok(Some((dk, database)))}/// Everything under the replica lock: the thread, the bytes, the rows, and/// the run's line in the Imports tool's history.#[allow(clippy::too_many_arguments)]fn write_all( seams: &mutImportSeams<'_>, workspace_id: &str, device_key: Option<&str>, owner_name: &str, run_title: &str, batches: &[cotton_core::import::post::Batch], plan: &cotton_core::import::media_plan::MediaUploadPlan, source: &Source, scratch: &Path, sealing: Option<&(cotton_core::seal::DataKey, String)>,) -> Result<Value, String> {let db = &seams.replica.driver;let identity = &seams.replica.identity;// Sealed chats are made under the keyed namespace and keyed ids, as the Mac's import makes them.let keys = sealing.map(|(dk, database_id)| cotton_client::messages_import::KeyedIds { dk, database_id });let namespace = match &keys {Some(k) => cotton_store::file_identity::Namespace::of_database(&cotton_client::seal::keyed_namespace(k.dk, k.database_id, identity.namespace().as_str()).map_err(|e| e.to_string())?),None => identity.namespace().clone(), };let file = FileContacts(db);// The name the screen or the resolver settled on is remembered, so the// next export of this channel does not ask.ifletSome(change) = set_self_name_change(&file, workspace_id, CHANNEL, owner_name) .map_err(|error| error.to_string())? { write_changes(db, &[change.into()], seams.clock, seams.ids)?; }// One reserved id for the whole chat: every part of it lands in the same// thread, and the media key needs that thread before a byte moves.let reserved = uuid_v4(seams.random);letmut thread_id: Option<String> = None;letmut imported = 0i64;letmut skipped = 0i64;letmut copied = 0i64;for batch in batches {let body = batch_body(batch, workspace_id, Some(&reserved));let landing = match &thread_id {Some(id) => id.clone(),None => resolve_thread(db, &body)?.unwrap_or_else(|| reserved.clone()), }; thread_id = Some(landing.clone());// 5. Bytes, only for messages this batch will actually insert.let probe = probe_import(&file, &body).map_err(|error| error.to_string())?;let inserting: std::collections::BTreeSet<&str> = probe .chats .iter() .flat_map(|chat| chat.new_external_ids.iter().map(String::as_str)) .collect();let files = stage_files(source, plan, &inserting, scratch)?;let leg = MediaLeg { layout: seams.layout, file: identity.id(), thread_id: &landing, clock: seams.clock, };let (body, notes) = attach_media(&leg, db, &body, &files); copied += notes.get("media:stored").copied().unwrap_or(0); hold_originals(seams, workspace_id, device_key, &body)?;// 6. Rows.let report = cotton_client::messages_import::import_messages_keyed(db, &namespace, &body, seams.clock, seams.random, seams.ids, keys.as_ref()) .map_err(|error| error.to_string())?; imported += report.totals.inserted; skipped += report.totals.skipped;ifletSome(group) = report.group { thread_id = Some(group.thread_id); } elseifletSome(chat) = report.chats.first() { thread_id = Some(chat.thread_id.clone()); } }// 7. The run, once, if it changed anything: a second import of the same// export skips every message, and that is still a run worth a line.if cotton_tools::imports::changed(imported, skipped) {let row = cotton_tools::imports::row( workspace_id, cotton_tools::imports::ImportSource::ChatExport, run_title, imported, skipped, cotton_tools::imports::this_device(db).as_deref(), &seams.clock.now_iso(), );let change = LocalChange::upsert(cotton_tools::imports::TABLE, &uuid_v4(seams.random), row); write_changes(db, &[change], seams.clock, seams.ids)?; }Ok(json!({"thread": thread_id,"imported": imported,"skipped": skipped,"media": { "copied": copied }, }))}/// This phone's HOLD of every original the batch just stored, as a capture/// writes one (`phone::media`): it is how the serving Mac tells "on its way/// from the phone" from "on no machine" (todo 5365af8f). Without it an/// imported picture is a key nobody admits to holding until its upload lands,/// and the media-index sweep leaves it for the daily reconcile.////// A phone that cannot hold yet (no device key, its device row not folded/// here) writes none — a state, never a refusal; the bytes still upload.fn hold_originals( seams: &mutImportSeams<'_>, workspace_id: &str, device_key: Option<&str>, body: &cotton_core::import::envelope::ImportBatch,) -> Result<(), String> {let db = &seams.replica.driver;let device_id = match cotton_client::media::holds::holder_in(db, workspace_id, device_key)? {Ok(device_id) => device_id,Err(sentence) => { tracing::warn!("import.whatsappExport: imported pictures are here and their holds wait — {sentence}");returnOk(()); } };let now_ms = seams.clock.now().timestamp_millis();for media in body.messages.iter().flat_map(|message| message.media.iter().flatten()) { cotton_store::media_holdings::record_holding( db, workspace_id, &device_id, &media.key, cotton_store::media_holdings::Tier::Original, media.size_bytes.unwrap_or(0.0) as i64, now_ms, seams.ids, cotton_store::mint::Held::Replica, ) .map_err(|error| error.to_string())?; }Ok(())}/// Inflate the files the plan calls uploadable — for the messages named — into/// the scratch folder, as the media leg's input.fn stage_files( source: &Source, plan: &cotton_core::import::media_plan::MediaUploadPlan, inserting: &std::collections::BTreeSet<&str>, scratch: &Path,) -> Result<Vec<MediaFile>, String> {letSource::Zip { reader, entries } = source else {returnOk(Vec::new()); };letmut files = Vec::new();for entry in &plan.entries {if entry.status != MediaUploadStatus::Uploadable {continue; }letSome(external_id) = entry.external_id.as_deref() else {continue; };if !inserting.contains(external_id) {continue; }// The plan matched on the full name or its last segment; find the// entry the same way.letSome(zipped) = entries.iter().find(|zipped| { zipped.name == entry.filename || zipped.name.rsplit('/').next().unwrap_or(&zipped.name) == entry.filename }) else {continue; };let bytes = read_zip_entry_ranged(reader, zipped).map_err(|error| error.to_string())?; std::fs::create_dir_all(scratch).map_err(|error| error.to_string())?;let leaf = entry.filename.rsplit('/').next().unwrap_or(&entry.filename).to_string();let path = scratch.join(format!("{}-{leaf}", files.len()));// not a copy: an import's files. std::fs::write(&path, bytes).map_err(|error| error.to_string())?; files.push(MediaFile { external_id: external_id.to_string(), path, name: Some(leaf), content_type: entry.content_type.clone(), }); }Ok(files)}#[cfg(test)]#[path = "whatsapp_import_tests.rs"]mod tests;