Cotton code
240 lines · 12.2 KB · RustRaw
//! `chat.export { thread? }` — one chat, or every chat, as a zip the phone//! hands to the share sheet (owner, 23 Nov 2026; CONTRACT.md "Export").//!//! - One chat: `<name>.zip` holding `<name>.txt` and `files/` with its//!   pictures, videos, voice messages and files.//! - Every chat (no `thread`): `Comms chats.zip` with a folder per chat, each//!   holding its `.txt` and `files/`.//!//! The text is [`cotton_core::export::chat_text`]'s: each message on its line//! with its day, clock (the person's zone) and speaker ("You" for the//! person's own), its attachments named where they lie. Only files already on//! this phone go in: an export never downloads a chat's files, and one not//! here is said in the line ("a picture, not on this phone"). What the person//! sees in the chat is what goes: a hidden or binned message, one before the//! chat was cleared, and a deleted chat stay out; Cotton's own Downloads chat//! is not a conversation and stays out of every chat. The zip is written//! under the data directory's `cache/exports/chats/` (emptied first) and//! answered by its path://!//! ```json//! { "path": "…/Asha.zip", "file_name": "Asha.zip", "mime": "application/zip", "count": 1, "files": 3, "missing": 1 }//! ```use std::io::Write as _;use std::path::PathBuf;use cotton_core::export::chat_text::{self, Attachment, Said};use super::*;/// One chat as read: its name and what was said, with each attachment's file where this phone holds one.struct Chat {    name: String,    said: Vec<(Said, Vec<Option<Found>>)>,}/// An attachment this phone holds: the file, and the name it was sent with.struct Found {    path: PathBuf,    name: String,}/// What an attachment was, in the reader's words.fn kind_said(lines: &LineSet, mime: &str, kind: Option<&str>) -> String {    let said = match kind {        Some("voice") => "voice",        Some("audio") => "audio",        Some("video") => "video",        Some("contact") => "contact",        Some("file") => "file",        _ if mime.starts_with("image/") => "picture",        _ if mime.starts_with("video/") => "video",        _ if mime.starts_with("audio/") => "audio",        _ => "file",    };    say(lines, &format!("app.export.kind.{said}"), &[])}pub(super) fn export(client: &ClientController, request: &Value) -> Result<Value, MethodError> {    let only = request.get("thread").and_then(Value::as_str).filter(|t| !t.is_empty()).map(str::to_string);    if only.as_deref() == Some(downloads::THREAD) {        return Err(MethodError::new("not_found", say(&list::lines(), "app.export.nothing", &[])));    }    let lines = list::lines();    let you = say(&lines, "app.thread.you", &[]);    let listed_you = say(&lines, "app.list.you", &[]);    // What each chat said, and each attachment as the copy names it (its key on this phone, or its file).    let read_chats = read(client, "chat.export", |ctx| {        let mut threads: Vec<Summary> = summaries(ctx, only.as_deref())?.into_iter().filter(|t| !t.deleted() && t.id != downloads::THREAD).collect();        threads.sort_by(|a, b| b.last_at.cmp(&a.last_at));        let named = names(ctx, &threads.iter().collect::<Vec<_>>(), &listed_you)?;        let mut out = Vec::new();        for t in &threads {            let who = named.get(&t.id).cloned().unwrap_or_default();            let mut sql = format!("SELECT {MESSAGE_COLUMNS} FROM {MESSAGES} WHERE workspace_id = ? AND thread_id = ? AND trashed_at IS NULL AND hidden_at IS NULL");            let mut params = vec![ws(ctx), text(t.id.clone())];            if let Some(cleared) = &t.cleared_before {                sql.push_str(" AND sent_at > ?");                params.push(text(cleared.clone()));            }            sql.push_str(" ORDER BY sent_at ASC, rowid ASC");            let mut said = Vec::new();            for m in rows(ctx, &sql, &params)? {                let media = media_of(&m);                let meta = meta_of(&m);                let deleted = s(&m, "deleted_at");                let row = Row { body: m.get("body").and_then(Value::as_str), media: &media, meta: meta.as_ref(), deleted_at: deleted.as_deref() };                let speaker = if row.event() {                    None                } else if s(&m, "direction").as_deref() == Some("out") {                    Some(you.clone())                } else if !t.group {                    Some(who.name.clone())                } else {                    Some(s(&m, "sender_participant_id").and_then(|seat| who.seats.get(&seat).map(|(n, _)| n.clone())).unwrap_or_else(|| cotton_core::messages::display::UNKNOWN_NAME.to_string()))                };                let as_value = Value::Object(m.clone());                let count = if row.deleted() { 0 } else { media.len() };                let attached: Vec<Spec> = (0..count).map(|i| spec(&as_value, i)).collect();                said.push((ms(&s(&m, "sent_at").unwrap_or_default()), speaker, bubble::text_of(&row), attached));            }            out.push((who.name.clone(), said));        }        Ok(out)    })?;    if read_chats.is_empty() {        return Err(MethodError::new(if only.is_some() { "not_found" } else { "refused" }, say(&lines, "app.export.nothing", &[])));    }    // Each attachment's file on this phone, never fetched.    let chats: Vec<Chat> = read_chats        .into_iter()        .map(|(name, said)| Chat {            name,            said: said                .into_iter()                .map(|(at, who, words, attached)| {                    let found = attached.iter().map(|a| local(client, a)).collect::<Vec<_>>();                    let files = attached                        .iter()                        .zip(&found)                        .map(|(a, f)| match f {                            Some(_) => Attachment::Here(String::new()),                            None => Attachment::NotHere(kind_said(&lines, &a.mime, a.kind.as_deref())),                        })                        .collect();                    (Said { at, who, words, files }, found)                })                .collect(),        })        .collect();    let dir = client.layout().exports_dir().join("chats");    // not a copy: an export.    let _ = std::fs::remove_dir_all(&dir);    std::fs::create_dir_all(&dir).map_err(|why| MethodError::new("unwritten", format!("the exports folder could not be made: {why}")))?;    let fallback = say(&lines, "app.export.chat_name", &[]);    let chat_names = chat_text::distinct(&chats.iter().map(|c| chat_text::file_name(&c.name, &fallback)).collect::<Vec<_>>());    let zip_name = match &only {        Some(_) => format!("{}.zip", chat_names[0]),        None => format!("{}.zip", say(&lines, "app.export.all_name", &[])),    };    let path = dir.join(&zip_name);    // not a copy: an export.    let file = std::fs::File::create(&path).map_err(|why| MethodError::new("unwritten", format!("{zip_name}: {why}")))?;    let mut zip = zip::ZipWriter::new(file);    let options = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated);    let fail = |why: String| MethodError::new("unwritten", format!("{zip_name}: {why}"));    let words = chat_text::Words {        heading: say(&lines, "app.export.heading", &[]),        exported: say(&lines, "app.export.exported", &[]),        attached: say(&lines, "app.export.attached", &[]),        not_here: say(&lines, "app.export.not_here", &[]),    };    let zone = client.time_zone().unwrap_or("Etc/UTC").to_string();    let now = cotton_chat::now_ms(client);    let (mut held, mut missing) = (0, 0);    for (chat, folder) in chats.into_iter().zip(&chat_names) {        let root = if only.is_some() { String::new() } else { format!("{folder}/") };        // The chat's files under the names they were sent with, made distinct.        let found: Vec<&Found> = chat.said.iter().flat_map(|(_, f)| f.iter().flatten()).collect();        let mut kept = chat_text::distinct(&found.iter().map(|f| f.name.clone()).collect::<Vec<_>>()).into_iter();        let mut said = Vec::new();        for (mut one, files) in chat.said {            for (slot, file) in one.files.iter_mut().zip(&files) {                match file {                    Some(file) => {                        let inside = format!("files/{}", kept.next().unwrap_or_else(|| file.name.clone()));                        let bytes = std::fs::read(&file.path).map_err(|why| fail(why.to_string()))?;                        zip.start_file(format!("{root}{inside}"), options).map_err(|why| fail(why.to_string()))?;                        zip.write_all(&bytes).map_err(|why| fail(why.to_string()))?;                        *slot = Attachment::Here(inside);                        held += 1;                    }                    None => missing += 1,                }            }            said.push(one);        }        let text = chat_text::transcript(&chat.name, &said, &zone, now, &words);        zip.start_file(format!("{root}{folder}.txt"), options).map_err(|why| fail(why.to_string()))?;        zip.write_all(text.as_bytes()).map_err(|why| fail(why.to_string()))?;    }    zip.finish().map_err(|why| fail(why.to_string()))?;    Ok(json!({ "path": path.to_string_lossy(), "file_name": zip_name, "mime": "application/zip", "count": chat_names.len(), "files": held, "missing": missing }))}/// One attachment as the copy names it: where its file may be on this phone, and what it is.struct Spec {    /// The person's own media key it is kept under (an import's file, a kept Cotton file).    key: Option<String>,    /// A file this phone is still sending.    path: Option<PathBuf>,    name: Option<String>,    mime: String,    kind: Option<String>,}/// Attachment `index` of a message row, counted as its bubble counts them (`chat_files::attached`).fn spec(row: &Value, index: usize) -> Spec {    use super::super::chat_files::{attached, Attached};    match attached(row, index) {        Some(Attached::Imported(media)) => Spec { key: Some(media.key.clone()), path: None, name: media.name.clone(), mime: media.content_type.clone(), kind: media.kind.and_then(|k| serde_json::to_value(k).ok()).and_then(|k| k.as_str().map(str::to_string)) },        Some(Attached::Cotton(at, picture)) => {            let meta = match &row["meta"] {                Value::String(t) => serde_json::from_str::<Value>(t).unwrap_or(Value::Null),                other => other.clone(),            };            let kept = meta["cotton"]["pictures"][at]["kept"].as_str().filter(|k| !k.is_empty()).map(str::to_string);            Spec { key: kept, path: None, name: picture.name.clone(), mime: picture.mime.clone(), kind: picture.kind.clone() }        }        Some(Attached::Pending(path, mime)) => Spec { key: None, path: Some(path), name: None, mime, kind: None },        None => Spec { key: None, path: None, name: None, mime: String::new(), kind: None },    }}/// An attachment's file on this phone, and the name it goes by; none when it is not here. Never fetched.fn local(client: &ClientController, spec: &Spec) -> Option<Found> {    use super::super::chat_files::extension;    let path = match (&spec.key, &spec.path) {        // As `media::land` looks: the key the store files it under, then whether its file is here.        (Some(key), _) => client            .with_file(|file| {                let key = super::super::media::object_key_of(file.driver, &file.identity.id().to_string(), key.clone());                Ok::<_, String>(super::super::media::local_path_of(file.driver, &key))            })            .ok()            .flatten()?,        (None, Some(path)) if path.is_file() => path.clone(),        _ => return None,    };    let plain = spec.name.as_deref().map(|n| chat_text::file_name(n.rsplit(['/', '\\']).next().unwrap_or_default(), "")).filter(|n| !n.is_empty());    let name = match plain {        Some(name) if !cotton_core::import::media_plan::extension_of(&name).is_empty() => name,        Some(name) => format!("{name}.{}", extension(None, &spec.mime)),        None => {            let stem: String = path.file_stem().map(|s| s.to_string_lossy().chars().take(16).collect()).unwrap_or_else(|| "file".to_string());            format!("{stem}.{}", extension(None, &spec.mime))        }    };    Some(Found { path, name })}