Cotton code
509 lines · 20.3 KB · RustRaw
//! The PURE half of the media leg — the port of//! `packages/import-core/src/mediaPlan.ts`.//!//! Classify every referenced attachment against the archive's contents and the//! caller's limits, and attach the result back onto envelope messages. The//! node CLI and the in-app importer both consume THIS, so "what may be kept"//! and "what a placeholder means" have exactly one spelling. The byte-moving//! half stays with each caller: the CLI mints an upload URL at the server and//! PUTs, the app inflates straight into the phone's media store and queues the//! mirror. Both end with a KEY.//!//! ## The limits are the CALLER'S, passed in//!//! Passed rather than defaulted, and required rather than optional. The//! ceilings live in `crate::media::keys::media_limits`, and both callers pass//! the `MediaKind::Message` one —//! one ceiling, one content-type list, the server's own — so a plan can be//! printed before a single byte moves, against the rules that will actually//! judge it. There is no default: a silent one would be a second opinion about//! what the server accepts, and the last time this had one it was a retired//! Worker's 25 MB.//!//! (In Rust `crate::media::media_limits` is right there, which makes the rule//! easier to break, not harder. It is kept: the plan a caller prints must be//! the plan its own uploader will be judged by, and a server that widens its//! own list must not silently re-classify an app's already-printed plan.)//!//! ## What the port could not keep//!//! `attachStoredMediaIndexed` takes a `Map<string, EnvelopeMessage[]>` — an//! index of LIVE REFERENCES into the chats, which it then mutates. Rust cannot//! hold many `&mut` into one `Vec` at once, so [`MessageIndex`] holds//! POSITIONS (`(chat, message)`) and the attach takes `&mut [NormalizedChat]`//! beside it. Same index, built once, same O(stored) attach; the borrow is//! taken at the call rather than held in the map.use std::collections::HashMap;use serde::{Deserialize, Serialize};use unicode_normalization::UnicodeNormalization;use crate::import::envelope::EnvelopeMedia;use crate::import::normalize::{MediaManifestEntry, NormalizedChat};use crate::import::text::{normalize_spaces, strip_bidi};use crate::import::vcard::VcardContact;/// A media file sitting next to the transcript —/// `packages/import-core/src/sourceTypes.ts`.////// The platform-neutral vocabulary for "what the operator pointed us at": the/// node package's `source.ts` (fs auto-detection) and the app's picker flow/// both speak it, and only the LOADING differs per platform. `SourceKind`, its/// other half, lands with `report`, its only reader.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct SourceMediaEntry {    pub name: String,    /// A JSON `number` in the TypeScript, so `f64` here — a zip entry's    /// uncompressed size, which every producer writes as an integer.    pub size: f64,}/// The last path segment — zip entry names only ever use `/`.fn last_segment(name: &str) -> &str {    match name.rfind('/') {        Some(cut) => &name[cut + 1..],        None => name,    }}/// Filename equality across the export's two halves.////// The transcript is character-normalized before parsing (exotic spaces/// folded — see `text.rs`), but the zip entry names are NOT: a macOS/// screenshot is literally named with a NARROW NO-BREAK SPACE before "AM", so/// the parsed reference and the archive entry differ by an invisible/// character. NFC on top, because macOS also likes decomposed accents in/// filenames.fn match_key(name: &str) -> String {    normalize_spaces(&strip_bidi(name)).nfc().collect()}/// Extension → content type, for an archive that names files and nothing else.////// A GUESS, deliberately: a WhatsApp export carries no MIME type, so this is/// how a `.opus` becomes `audio/opus`. What is ACCEPTED is not decided here —/// the caller's `limits.content_types` (the server's `MEDIA_LIMITS.message`)/// is the allowlist, and a type guessed but not listed classifies as/// `unsupported-type` rather than uploading and failing at the server.////// The ONE guess, shared by every caller that has a filename and no MIME type:/// a WhatsApp export, WhatsApp's own database (which stores no type at all)/// and the Mac's backup reader. A second table would be a second opinion about/// what a `.opus` is, and the last time this had one a voice note — the/// commonest attachment in a chat — lost its bytes for ever.////// A `match`, not a map, so the table is a compile-time constant and the/// lookup allocates only for the case fold.fn content_type_by_extension(lowercased: &str) -> Option<&'static str> {    Some(match lowercased {        "jpg" | "jpeg" => "image/jpeg",        "png" => "image/png",        "webp" => "image/webp",        "heic" => "image/heic",        "heif" => "image/heif",        "gif" => "image/gif",        "m4a" => "audio/m4a",        // WhatsApp's own voice-note container, and the video containers a        // phone records in. All four are on the server's message list; without        // them a voice note — the single most common attachment in a chat —        // was classified `unsupported-type` and lost its bytes forever.        "ogg" => "audio/ogg",        "opus" => "audio/opus",        "mov" => "video/quicktime",        "3gp" => "video/3gpp",        "mp3" => "audio/mpeg",        "aac" => "audio/aac",        "mp4" => "video/mp4",        "pdf" => "application/pdf",        "xls" => "application/vnd.ms-excel",        "xlsx" => "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",        "docx" => "application/vnd.openxmlformats-officedocument.wordprocessingml.document",        "zip" => "application/zip",        "html" => "text/html",        "doc" => "application/msword",        "ppt" => "application/vnd.ms-powerpoint",        "pptx" => "application/vnd.openxmlformats-officedocument.presentationml.presentation",        "txt" => "text/plain",        "csv" => "text/csv",        "vcf" => "text/vcard",        _ => return None,    })}/// The type an extension names, or `None` when this table has never heard of/// it. Case-insensitive, as the TypeScript's `ext.toLowerCase()` is.pub fn content_type_for_extension(ext: &str) -> Option<&'static str> {    content_type_by_extension(&ext.to_lowercase())}/// What a caller will accept: a byte ceiling and a content-type allowlist.#[derive(Debug, Clone, PartialEq)]pub struct MediaPlanLimits {    /// A JSON `number` in the TypeScript, and compared with `>` against a    /// source entry's size, so both stay `f64` here.    pub max_bytes: f64,    pub content_types: Vec<String>,}/// Why an attachment will or will not have its bytes moved.#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]#[serde(rename_all = "kebab-case")]pub enum MediaUploadStatus {    Uploadable,    UnsupportedType,    Oversize,    Missing,    Omitted,}impl MediaUploadStatus {    pub const fn as_str(self) -> &'static str {        match self {            MediaUploadStatus::Uploadable => "uploadable",            MediaUploadStatus::UnsupportedType => "unsupported-type",            MediaUploadStatus::Oversize => "oversize",            MediaUploadStatus::Missing => "missing",            MediaUploadStatus::Omitted => "omitted",        }    }}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct MediaUploadPlanEntry {    pub filename: String,    pub external_id: Option<String>,    pub status: MediaUploadStatus,    pub content_type: Option<String>,    pub size_bytes: Option<f64>,}/// The counts the dry-run report prints. Integers, as every other count in the/// report is.#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct MediaUploadCounts {    pub uploadable: i64,    pub unsupported_type: i64,    pub oversize: i64,    pub missing: i64,    pub omitted: i64,}#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct MediaUploadPlan {    pub entries: Vec<MediaUploadPlanEntry>,    pub counts: MediaUploadCounts,}/// The lowercase extension of a display filename, without the dot.pub fn extension_of(filename: &str) -> String {    let base = last_segment(filename);    match base.rfind('.') {        // JS `slice(dot + 1)` is in UTF-16 units, but `rfind` gives a BYTE        // offset at an ASCII `.`, which is a char boundary — the two agree.        Some(dot) => base[dot + 1..].to_lowercase(),        None => String::new(),    }}/// `00003011-Requirement.docx` → `Requirement.docx` — the iOS export counter/// is not a name.////// JS `/^\d+-/` without the `u` flag, so `\d` is `[0-9]`: a full-width `0`/// is NOT a counter and the name survives whole.pub fn display_name_for(filename: &str) -> String {    let base = last_segment(filename);    let digits = base.bytes().take_while(u8::is_ascii_digit).count();    if digits > 0 && base.as_bytes().get(digits) == Some(&b'-') {        base[digits + 1..].to_string()    } else {        base.to_string()    }}/// Classify every referenced attachment against the archive's contents and the/// caller's limits. Pure — the printable half of the media leg.pub fn plan_media_uploads(    media: &[MediaManifestEntry],    source_entries: &[SourceMediaEntry],    limits: &MediaPlanLimits,) -> MediaUploadPlan {    // Two lookups, exactly as the TypeScript builds them: the archive's own    // entry name, and its last segment — a `_chat.txt` reference is a bare    // filename while a zip entry may carry the export folder in front of it.    // Later duplicates overwrite earlier ones, which is JS `Map` construction    // from an array of pairs.    let mut by_source_name: HashMap<String, &SourceMediaEntry> = HashMap::new();    let mut by_base: HashMap<String, &SourceMediaEntry> = HashMap::new();    for entry in source_entries {        by_source_name.insert(match_key(&entry.name), entry);        by_base.insert(match_key(last_segment(&entry.name)), entry);    }    let mut entries: Vec<MediaUploadPlanEntry> = Vec::new();    let mut counts = MediaUploadCounts::default();    for item in media {        let Some(filename) = item.filename.as_deref().filter(|_| !item.omitted) else {            counts.omitted += 1;            entries.push(MediaUploadPlanEntry {                // `item.filename ?? "(omitted)"` — an omitted entry that still                // names its file keeps the name; only a null one is labelled.                filename: item                    .filename                    .clone()                    .unwrap_or_else(|| "(omitted)".to_string()),                external_id: item.external_id.clone(),                status: MediaUploadStatus::Omitted,                content_type: None,                size_bytes: None,            });            continue;        };        let source = by_source_name            .get(&match_key(filename))            .or_else(|| by_base.get(&match_key(last_segment(filename))));        let Some(source) = source else {            counts.missing += 1;            entries.push(MediaUploadPlanEntry {                filename: filename.to_string(),                external_id: item.external_id.clone(),                status: MediaUploadStatus::Missing,                content_type: None,                size_bytes: None,            });            continue;        };        // The archive's OWN name decides the type, never the transcript's        // reference: the file on disk is the thing being uploaded.        let guessed = content_type_by_extension(&extension_of(&source.name));        let content_type =            guessed.filter(|value| limits.content_types.iter().any(|allowed| allowed == *value));        let Some(content_type) = content_type else {            counts.unsupported_type += 1;            entries.push(MediaUploadPlanEntry {                filename: source.name.clone(),                external_id: item.external_id.clone(),                status: MediaUploadStatus::UnsupportedType,                content_type: None,                size_bytes: Some(source.size),            });            continue;        };        if source.size > limits.max_bytes {            counts.oversize += 1;            entries.push(MediaUploadPlanEntry {                filename: source.name.clone(),                external_id: item.external_id.clone(),                status: MediaUploadStatus::Oversize,                content_type: Some(content_type.to_string()),                size_bytes: Some(source.size),            });            continue;        }        counts.uploadable += 1;        entries.push(MediaUploadPlanEntry {            filename: source.name.clone(),            external_id: item.external_id.clone(),            status: MediaUploadStatus::Uploadable,            content_type: Some(content_type.to_string()),            size_bytes: Some(source.size),        });    }    MediaUploadPlan { entries, counts }}/// One attachment that landed: named by its object KEY, never by a URL.////// The key is the whole point. A `url` was a promise that some server would/// still be serving that byte range later — and the server in question is/// retired. A key is a content address inside the owner's own workspace/// prefix: the phone can answer it from disk on a plane, the server can/// presign a read of it, the export manifest can enumerate it, and deleting/// the record deletes the bytes. Both legs produce this shape now.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct MediaStoredResult {    pub filename: String,    pub external_id: Option<String>,    pub key: String,    pub content_type: String,    pub size_bytes: f64,    /// The card a `.vcf` turned out to be, read by whichever half moved the    /// bytes (the CLI has them in hand, the app reads the inflated file before    /// it moves it). Absent for every other attachment, and absent for a card    /// nothing readable came out of — the file is still attached either way.    #[serde(default, skip_serializing_if = "Option::is_none")]    pub contact: Option<VcardContact>,}/// The two content types a shared contact card arrives under.const VCARD_CONTENT_TYPES: [&str; 2] = ["text/vcard", "text/x-vcard"];/// Should this attachment's bytes be read as a contact card?////// Asked HERE so the CLI and the app decide it the same way — the alternative/// is one of them rendering a shared contact as a card and the other as a file/// chip, from the same archive.pub fn is_vcard_content_type(content_type: &str) -> bool {    let lowercased = content_type.to_lowercase();    VCARD_CONTENT_TYPES.contains(&lowercased.as_str())}/// One attachment whose bytes did not move, and why.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "camelCase")]pub struct MediaUploadFailure {    pub filename: String,    pub detail: String,}/// The keyed attachment produced by a completed media-store write.fn media_entry_for(result: &MediaStoredResult) -> EnvelopeMedia {    EnvelopeMedia {        key: result.key.clone(),        content_type: result.content_type.clone(),        name: Some(display_name_for(&result.filename)),        size_bytes: Some(result.size_bytes),        width: None,        height: None,        contact: result            .contact            .as_ref()            .map(|contact| serde_json::to_value(contact).expect("a vcard contact serialises")),        duration_ms: None,        playback_key: None,        playback_content_type: None,        file_key: None,        kind: None,        waveform: None,        preview: None,    }}/// Group results by the message they name, keeping the caller's order within/// each group and first-seen order across groups (a JS `Map`'s iteration/// order, which the indexed attach walks).fn group_by_external_id(stored: &[MediaStoredResult]) -> Vec<(&str, Vec<&MediaStoredResult>)> {    let mut order: Vec<&str> = Vec::new();    let mut groups: HashMap<&str, Vec<&MediaStoredResult>> = HashMap::new();    for result in stored {        // A result the mover could not tie to a message is dropped, not        // guessed at: `externalId === null` means nothing in this import        // claims it.        let Some(external_id) = result.external_id.as_deref() else {            continue;        };        let list = groups.entry(external_id).or_insert_with(|| {            order.push(external_id);            Vec::new()        });        list.push(result);    }    order        .into_iter()        .map(|id| {            let list = groups.remove(id).unwrap_or_default();            (id, list)        })        .collect()}/// The placeholder body existed only because there was nothing else to show;/// with the file itself attached it would just echo the filename.fn clear_placeholder(body: &mut String) {    if body.starts_with("[attachment") {        body.clear();    }}/// Attach media to its messages by object KEY — the one attach path there is.////// Mutates the chats in place — they are this run's working set, not shared/// state. Answers how many (message, result) pairs landed.pub fn attach_stored_media(chats: &mut [NormalizedChat], stored: &[MediaStoredResult]) -> i64 {    let grouped = group_by_external_id(stored);    let by_external_id: HashMap<&str, &Vec<&MediaStoredResult>> =        grouped.iter().map(|(id, list)| (*id, list)).collect();    let mut attached = 0i64;    for chat in chats.iter_mut() {        for message in chat.messages.iter_mut() {            let Some(matches) = by_external_id.get(message.external_id.as_str()) else {                continue;            };            message.media = Some(matches.iter().map(|r| media_entry_for(r)).collect());            clear_placeholder(&mut message.body);            attached += matches.len() as i64;        }    }    attached}/// Where one `external_id` lives: `(chat index, message index)` pairs.////// The TypeScript's index holds the message OBJECTS; Rust cannot hold many/// `&mut` into one `Vec`, so it holds positions and the attach takes the/// chats beside it. Same build-once, same O(stored) attach.pub type MessageIndex = HashMap<String, Vec<(usize, usize)>>;/// Index every envelope message by `external_id`.////// [`attach_stored_media`] walks EVERY message of EVERY chat per call, which/// was fine when it ran once per import and quadratic the moment it ran per/// batch: 56 batches × 27,580 messages of rescans on a phone's JS thread./// Build this once; each attach then touches only the messages it names.pub fn build_message_index(chats: &[NormalizedChat]) -> MessageIndex {    let mut index: MessageIndex = HashMap::new();    for (chat_ix, chat) in chats.iter().enumerate() {        for (message_ix, message) in chat.messages.iter().enumerate() {            index                .entry(message.external_id.clone())                .or_default()                .push((chat_ix, message_ix));        }    }    index}/// [`attach_stored_media`] through a prebuilt index — same attach, same/// placeholder clearing, O(stored) instead of O(messages). The two must stay/// equivalent; the tests pin them against each other.pub fn attach_stored_media_indexed(    chats: &mut [NormalizedChat],    index: &MessageIndex,    stored: &[MediaStoredResult],) -> i64 {    let mut attached = 0i64;    for (external_id, matches) in group_by_external_id(stored) {        let Some(positions) = index.get(external_id) else {            continue;        };        for (chat_ix, message_ix) in positions {            let Some(message) = chats                .get_mut(*chat_ix)                .and_then(|chat| chat.messages.get_mut(*message_ix))            else {                // A position the caller's own index no longer describes. The                // TypeScript cannot express this (its index holds the object),                // so the port refuses rather than inventing a message.                continue;            };            message.media = Some(matches.iter().map(|r| media_entry_for(r)).collect());            clear_placeholder(&mut message.body);            attached += matches.len() as i64;        }    }    attached}#[cfg(test)]#[path = "media_plan_tests.rs"]mod tests;