Cotton code
267 lines · 11.2 KB · RustRaw
//! WhatsApp profile pictures fill an EMPTY picture (owner's decision, 11 Oct//! 2026): a person whose avatar is empty, or a WhatsApp group whose thread has//! no picture, gets the one WhatsApp shows — and only while it is still//! WhatsApp's does a changed picture replace it.//!//! **Provenance is the object key.** A picture from WhatsApp is stored under//! `…/whatsapp/` in its holder's folder ([`whatsapp_avatar_key`],//! [`whatsapp_group_picture_key`]); every other writer of an avatar — the//! owner's pick, the People import, a face print — makes a key without it. So//! a picture someone chose is never WhatsApp's to replace, and choosing one//! ends WhatsApp's claim with nothing else to clear.//!//! Read-only on WhatsApp's side: the helper only ASKS for a profile picture//! (`picture`), and only for the chats [`wanted_chats`] names — the people and//! groups that could take one — so a stranger's picture is never fetched.use std::collections::BTreeSet;use cotton_core::import::whatsapp_keys::whatsapp_group_key;use cotton_core::import::adapters::wce::phone_from_jid;use cotton_core::media::keys::{is_whatsapp_picture_key, whatsapp_avatar_key, whatsapp_group_picture_key};use cotton_core::messages::resolve_contact::{find_contact_by_handle, normalize_contact_handle, ContactHandleKind};use cotton_store::file_identity::FileId;use cotton_store::outbox::LocalChange;use cotton_store::Driver;use rusqlite::types::Value as SqlValue;use serde_json::{Map, Value};use super::media_leg::MediaOutcome;use super::{count, IngestMediaFile, IngestNotes};use crate::messages_import::FileContacts;/// A person's chat on WhatsApp: `<digits>@s.whatsapp.net`.pub const PERSON_SERVER: &str = "@s.whatsapp.net";/// A group's: `<id>@g.us`.pub const GROUP_SERVER: &str = "@g.us";/// One profile picture the helper downloaded, for the chat it belongs to.#[derive(Debug, Clone, PartialEq)]pub struct ProfilePicture {    /// The person's or the group's JID.    pub jid: String,    pub is_group: bool,    pub file: IngestMediaFile,    /// The object key its bytes are already stored under — a serving Mac    /// stores a page's pictures BEFORE the hold that writes their rows, and    /// the hold only points at them.    pub stored: Option<String>,}/// Whose picture one is, as the file stands: the person or the group whose/// WhatsApp key it is stored under.#[derive(Debug, Clone, PartialEq, Eq)]pub enum Holder {    Person(String),    Group(String),}impl Holder {    /// The holder's WhatsApp key for bytes whose hash is `sha` and extension `ext`.    pub fn key(&self, file_id: &FileId, sha: &str, ext: &str) -> String {        match self {            Holder::Person(id) => whatsapp_avatar_key(file_id, id, sha, ext),            Holder::Group(id) => whatsapp_group_picture_key(file_id, id, sha, ext),        }    }}/// Who would take `picture` now — `None` for a chat nobody in the file is, or/// a holder whose picture someone chose (the apply counts both).pub fn holder(db: &Driver, workspace_id: &str, picture: &ProfilePicture) -> Result<Option<Holder>, String> {    Ok(match place(db, workspace_id, picture)? {        Place::Nobody | Place::Chosen => None,        Place::Person { id, .. } => Some(Holder::Person(id)),        Place::Group { id, .. } => Some(Holder::Group(id)),    })}/// Whether a holder whose picture is `current` takes one from WhatsApp: when/// it has none, or when the one it has is WhatsApp's own.pub fn takes_whatsapp_picture(current: Option<&str>) -> bool {    match current.map(str::trim) {        None | Some("") => true,        Some(key) => is_whatsapp_picture_key(key),    }}/// The chats whose WhatsApp picture this file would take now: every person a/// WhatsApp contact is linked to whose avatar is empty or WhatsApp's, and every/// WhatsApp group whose picture is. The helper asks WhatsApp about these and/// no others.pub fn wanted_chats(db: &Driver, workspace_id: &str) -> Result<BTreeSet<String>, String> {    let params = [SqlValue::Text(workspace_id.to_string())];    let mut wanted = BTreeSet::new();    // The contact's person is who(handle)'s, derived as it is read (PEOPLE BUILD 1b): a number several contacts    // share takes nobody's picture.    let people = db        .all(            &format!(                "SELECT c.phone_e164 AS phone, p.avatar_key AS avatar_key FROM cotton_msg_contacts c \                 JOIN cotton_people p ON p.id = {person} \                 WHERE c.workspace_id = ? AND c.phone_e164 IS NOT NULL AND p.archived_at IS NULL",                person = cotton_store::protocol::who::contact_person_sql(cotton_store::protocol::who::shared_held(db), "c"),            ),            &params,        )        .map_err(|error| error.to_string())?;    for row in &people {        let Some(phone) = row.text("phone").filter(|phone| !phone.is_empty() && phone.bytes().all(|b| b.is_ascii_digit())) else {            continue;        };        if takes_whatsapp_picture(row.text("avatar_key")) {            wanted.insert(format!("{phone}{PERSON_SERVER}"));        }    }    let groups = db        .all(            "SELECT external_key, photo_key FROM cotton_msg_threads \             WHERE workspace_id = ? AND kind = 'group' AND external_key LIKE 'wa:group:%@g.us'",            &params,        )        .map_err(|error| error.to_string())?;    for row in &groups {        let Some(jid) = row.text("external_key").and_then(|key| key.strip_prefix("wa:group:")) else {            continue;        };        if takes_whatsapp_picture(row.text("photo_key")) {            wanted.insert(jid.to_string());        }    }    Ok(wanted)}/// Where one picture would go, as the file stands.enum Place {    /// No person and no group in this file is this chat.    Nobody,    /// Its holder has a picture someone chose: it stays.    Chosen,    Person { id: String, current: Option<String> },    Group { id: String, current: Option<String> },}fn place(db: &Driver, workspace_id: &str, picture: &ProfilePicture) -> Result<Place, String> {    if picture.is_group {        let rows = db            .all(                "SELECT id, photo_key FROM cotton_msg_threads WHERE workspace_id = ? AND kind = 'group' AND external_key = ?",                &[                    SqlValue::Text(workspace_id.to_string()),                    SqlValue::Text(whatsapp_group_key(&picture.jid)),                ],            )            .map_err(|error| error.to_string())?;        let Some(row) = rows.first() else { return Ok(Place::Nobody) };        let current = row.text("photo_key").map(str::to_string);        if !takes_whatsapp_picture(current.as_deref()) {            return Ok(Place::Chosen);        }        return Ok(Place::Group { id: row.text("id").unwrap_or_default().to_string(), current });    }    if !picture.jid.ends_with(PERSON_SERVER) {        return Ok(Place::Nobody);    }    let Some(handle) = phone_from_jid(&picture.jid).and_then(|phone| normalize_contact_handle(ContactHandleKind::Phone, &phone))    else {        return Ok(Place::Nobody);    };    let contact = find_contact_by_handle(&FileContacts(db), workspace_id, &handle).map_err(|error| error.to_string())?;    let Some(contact) = contact else {        return Ok(Place::Nobody);    };    let person_id = db        .get(            &format!("SELECT {} AS person FROM cotton_msg_contacts c WHERE c.id = ?", cotton_store::protocol::who::contact_person_sql(cotton_store::protocol::who::shared_held(db), "c")),            &[SqlValue::Text(contact.id.clone())],        )        .map_err(|error| error.to_string())?        .and_then(|row| row.text("person").map(str::to_string));    let Some(person_id) = person_id else {        return Ok(Place::Nobody);    };    let rows = db        .all(            "SELECT avatar_key FROM cotton_people WHERE id = ? AND workspace_id = ? AND archived_at IS NULL",            &[SqlValue::Text(person_id.clone()), SqlValue::Text(workspace_id.to_string())],        )        .map_err(|error| error.to_string())?;    let Some(row) = rows.first() else { return Ok(Place::Nobody) };    let current = row.text("avatar_key").map(str::to_string);    if !takes_whatsapp_picture(current.as_deref()) {        return Ok(Place::Chosen);    }    Ok(Place::Person { id: person_id, current })}/// The rows a page of profile pictures changes, each picture stored with/// `store` under its holder's WhatsApp key first. A picture nobody in the file/// is, or whose holder has one someone chose, is counted and never stored./// Returns the changes and how many pictures were stored.pub fn picture_changes(    db: &Driver,    file_id: &FileId,    workspace_id: &str,    pictures: &[ProfilePicture],    store: &mut dyn FnMut(&IngestMediaFile, &dyn Fn(&str, &str) -> String) -> MediaOutcome,    notes: &mut IngestNotes,) -> Result<(Vec<LocalChange>, i64), String> {    let mut changes = Vec::new();    let mut stored = 0;    for picture in pictures {        let (table, row_id, column, current, key_for): (&str, String, &str, Option<String>, Box<dyn Fn(&str, &str) -> String>) =            match place(db, workspace_id, picture)? {                Place::Nobody => {                    count(notes, "picture:nobody", 1);                    continue;                }                Place::Chosen => {                    count(notes, "picture:chosenKept", 1);                    continue;                }                Place::Person { id, current } => {                    let holder = id.clone();                    let file_id = file_id.clone();                    ("cotton_people", id, "avatar_key", current, Box::new(move |sha, ext| whatsapp_avatar_key(&file_id, &holder, sha, ext)))                }                Place::Group { id, current } => {                    let holder = id.clone();                    let file_id = file_id.clone();                    ("cotton_msg_threads", id, "photo_key", current, Box::new(move |sha, ext| whatsapp_group_picture_key(&file_id, &holder, sha, ext)))                }            };        let outcome = match &picture.stored {            // Stored before the hold, and counted there.            Some(key) => MediaOutcome::Stored {                key: key.clone(),                content_type: String::new(),                size_bytes: 0,                name: String::new(),            },            None => {                let outcome = store(&picture.file, key_for.as_ref());                count(notes, &format!("picture:{}", outcome.note_key()), 1);                outcome            }        };        let MediaOutcome::Stored { key, .. } = outcome else { continue };        stored += 1;        if current.as_deref() == Some(key.as_str()) {            count(notes, "picture:unchanged", 1);            continue;        }        let mut patch = Map::new();        patch.insert(column.to_string(), Value::from(key));        if table == "cotton_people" {            // A print cut from a photo is no longer what the avatar shows.            patch.insert("avatar_photo_id".to_string(), Value::Null);        }        count(notes, if table == "cotton_people" { "picture:person" } else { "picture:group" }, 1);        changes.push(LocalChange::upsert(table, &row_id, patch));    }    Ok((changes, stored))}#[cfg(test)]#[path = "profile_pictures_tests.rs"]mod tests;