174 lines · 10.7 KB · RustRaw
//! `developer.inventWhatsappFaces` — COTTON DEV ONLY: WhatsApp chats as the Mac's link lands them, whose people carry//! a profile picture, and a poll to vote in, for a walk on a phone with no Mac (owner via the coordinator, 24 Nov 2026://! "people's display pictures no longer show in chats that come through WhatsApp"; CONTRACT "WhatsApp profile//! pictures"). The real Cotton refuses it by name.//!//! ```text//! developer.inventWhatsappFaces {} → { threads: [<id>…], pictures: <n> }//! ```//!//! Three people and a group, every name and number invented, in the shapes CONTRACT gives the Mac://! - Meena, a person linked to her contact, her picture on the person (`…/people/<person>/whatsapp/<sha>.png`);//! - Ravi, a contact with no person, his picture on his contact (`…/messages/contacts/<contact>/whatsapp/<sha>.png`);//! - Tara, the same, met only in the group;//! - "Lake trip", the three of them, its own picture on the group, and a poll from Ravi to vote in.//!//! The copy reads as linked (a message's `meta.source` names the linked device), so writing in these chats goes to//! WhatsApp through the Mac. Run again, it writes no row twice (each row's id is fixed) and puts the pictures again.use serde_json::{json, Map, Value};use sha2::{Digest, Sha256};use super::cotton_chat::{put_typed, write};use crate::handle::CottonHandle;use crate::methods::MethodError;use cotton_tools::mcp::handlers::common::{insert_row, update_row};const MEENA_PERSON: &str = "dev-wa-person-meena";const MEENA: &str = "dev-wa-contact-meena";const RAVI: &str = "dev-wa-contact-ravi";const TARA: &str = "dev-wa-contact-tara";const MEENA_CHAT: &str = "11111111-1111-4111-8111-00000000de01";const RAVI_CHAT: &str = "11111111-1111-4111-8111-00000000de02";const LAKE: &str = "11111111-1111-4111-8111-00000000de03";const LINK_ACCOUNT: &str = "15550100900@s.whatsapp.net";pub fn invent(handle: &CottonHandle, _request: &Value) -> Result<Value, MethodError> { if handle.flavor() != cotton_core::flavor::Flavor::Dev { return Err(MethodError::new("not_dev", "developer.inventWhatsappFaces answers only in Cotton Dev")); } let client = handle.client(); let database = client.current_database().map_err(|why| MethodError::new("no_database", why))?; if client.object_door().is_none() { return Err(MethodError::new("sign_in_first", "invented WhatsApp chats are a signed-in phone's")); } let failed = |why: String| MethodError::new("invent_failed", why); // Each picture's bytes first, put on the object as the Mac's sink stores a file before a row names it. let mut put = |folder: String, colour: [u8; 3]| -> Result<String, MethodError> { let bytes = solid_png(96, colour); let sha = hex::encode(Sha256::digest(&bytes)); let path = format!("{database}/{folder}/whatsapp/{sha}.png"); put_typed(&client, &format!("/v1/media/{path}"), &bytes, "image/png").map_err(|refusal| failed(format!("{path}: {}", refusal.message)))?; Ok(path) }; let meena_face = put(format!("people/{MEENA_PERSON}"), [0xD9, 0x73, 0x5B])?; let ravi_face = put(format!("messages/contacts/{RAVI}"), [0x3E, 0x7C, 0xB1])?; let tara_face = put(format!("messages/contacts/{TARA}"), [0x4F, 0x9D, 0x69])?; let lake_face = put(format!("messages/{LAKE}"), [0x2B, 0x5D, 0x8C])?; let now = chrono::Utc::now(); let at = move |minutes_ago: i64| super::cotton_chat::iso((now - chrono::Duration::minutes(minutes_ago)).timestamp_millis()); write(&client, "developer.inventWhatsappFaces", move |ctx| { let row = |pairs: Value| -> Map<String, Value> { pairs.as_object().cloned().unwrap_or_default() }; let exists = |ctx: &mut cotton_tools::mcp::dispatch::Ctx<'_>, table: &str, id: &str| -> Result<bool, String> { Ok(super::cotton_chat::one(ctx, &format!("SELECT id FROM {table} WHERE workspace_id = ? AND id = ?"), &[super::cotton_chat::ws(ctx), rusqlite::types::Value::Text(id.to_string())])?.is_some()) }; let put_row = |ctx: &mut cotton_tools::mcp::dispatch::Ctx<'_>, table: &str, id: &str, columns: Value| -> Result<(), String> { if exists(ctx, table, id)? { // Run again: the pictures stand where CONTRACT puts them now. let pictures: Map<String, Value> = row(columns).into_iter().filter(|(k, _)| k == "avatar_key" || k == "photo_key").collect(); return if pictures.is_empty() { Ok(()) } else { update_row(ctx, table, id, pictures).map_err(|f| f.to_string()) }; } insert_row(ctx, table, id, row(columns)).map_err(|f| f.to_string()) }; put_row(ctx, "cotton_people", MEENA_PERSON, json!({ "full_name": "Meena Invented", "avatar_key": meena_face.as_str() }))?; put_row(ctx, "cotton_msg_contacts", MEENA, json!({ "phone_e164": "15550107201", "display_name": "Meena", "person_id": MEENA_PERSON }))?; put_row(ctx, "cotton_msg_contacts", RAVI, json!({ "phone_e164": "15550107202", "display_name": "Ravi Invented", "avatar_key": ravi_face.as_str() }))?; put_row(ctx, "cotton_msg_contacts", TARA, json!({ "phone_e164": "15550107203", "display_name": "Tara Invented", "avatar_key": tara_face.as_str() }))?; put_row(ctx, "cotton_msg_threads", MEENA_CHAT, json!({ "kind": "dm", "external_key": "15550107201@s.whatsapp.net", "contact_id": MEENA, "last_message_at": at(30), "read_seq": 0 }))?; put_row(ctx, "cotton_msg_threads", RAVI_CHAT, json!({ "kind": "dm", "external_key": "15550107202@s.whatsapp.net", "contact_id": RAVI, "photo_key": Value::Null, "last_message_at": at(20), "read_seq": 0 }))?; put_row(ctx, "cotton_msg_threads", LAKE, json!({ "kind": "group", "external_key": "120363000000000077@g.us", "title": "Lake trip", "photo_key": lake_face.as_str(), "last_message_at": at(5), "read_seq": 0 }))?; for (seat, contact, name, me) in [("dev-wa-seat-me", None, "You", true), ("dev-wa-seat-meena", Some(MEENA), "Meena", false), ("dev-wa-seat-ravi", Some(RAVI), "Ravi Invented", false), ("dev-wa-seat-tara", Some(TARA), "Tara Invented", false)] { put_row(ctx, "cotton_msg_thread_participants", seat, json!({ "thread_id": LAKE, "contact_id": contact, "display_name": name, "is_self": me }))?; } let source = |chat: &str| json!({ "source": { "service": "WhatsApp linked device", "account": LINK_ACCOUNT, "chat": chat } }); let message = |thread: &str, seat: Option<&str>, body: &str, minutes_ago: i64, seq: i64, chat: &str, extra: Value| { let mut m = json!({ "thread_id": thread, "direction": "in", "channel": "whatsapp", "origin": "imported", "body": body, "sent_at": at(minutes_ago), "seq": seq, "sender_participant_id": seat, "meta": source(chat) }); if let (Some(m), Some(extra)) = (m.as_object_mut(), extra.as_object()) { for (k, v) in extra { if k == "meta" { if let (Some(meta), Some(more)) = (m.get_mut("meta").and_then(Value::as_object_mut), v.as_object()) { meta.extend(more.clone()); } } else { m.insert(k.clone(), v.clone()); } } } m }; put_row(ctx, "cotton_msg_messages", "dev-wa-m-meena-1", message(MEENA_CHAT, None, "Leaving now, see you at the jetty", 30, 1, "15550107201@s.whatsapp.net", json!({ "external_id": "DEVWAMEENA1" })))?; put_row(ctx, "cotton_msg_messages", "dev-wa-m-ravi-1", message(RAVI_CHAT, None, "Got the boat tickets", 20, 1, "15550107202@s.whatsapp.net", json!({ "external_id": "DEVWARAVI1" })))?; put_row(ctx, "cotton_msg_messages", "dev-wa-m-lake-1", message(LAKE, Some("dev-wa-seat-tara"), "Boat at nine?", 12, 1, "120363000000000077@g.us", json!({ "external_id": "DEVWALAKE1" })))?; put_row(ctx, "cotton_msg_messages", "dev-wa-m-lake-2", message(LAKE, Some("dev-wa-seat-meena"), "Nine works", 10, 2, "120363000000000077@g.us", json!({ "external_id": "DEVWALAKE2" })))?; let poll = json!({ "question": "Lunch after the boat?", "options": [{ "text": "Dosa", "votes": 1 }, { "text": "Thali", "votes": 0 }, { "text": "Pizza", "votes": 0 }], "selectable": 1, "voters": [{ "who": "15550107203", "options": [0], "at": at(6) }] }); put_row(ctx, "cotton_msg_messages", "dev-wa-m-lake-poll", message(LAKE, Some("dev-wa-seat-ravi"), "Lunch after the boat?", 5, 3, "120363000000000077@g.us", json!({ "external_id": "DEVWALAKEPOLL", "meta": { "poll": poll } })))?; Ok(Value::Null) })?; Ok(json!({ "threads": [MEENA_CHAT, RAVI_CHAT, LAKE], "pictures": 4 }))}/// A `side`-square PNG of one colour: stored (uncompressed) deflate, so no image crate is needed.fn solid_png(side: u32, rgb: [u8; 3]) -> Vec<u8> { let mut raw = Vec::with_capacity(((side * 3 + 1) * side) as usize); for _ in 0..side { raw.push(0); for _ in 0..side { raw.extend_from_slice(&rgb); } } let mut z = vec![0x78, 0x01]; for (i, block) in raw.chunks(65_535).enumerate() { let last = (i + 1) * 65_535 >= raw.len(); z.push(u8::from(last)); let len = block.len() as u16; z.extend_from_slice(&len.to_le_bytes()); z.extend_from_slice(&(!len).to_le_bytes()); z.extend_from_slice(block); } let (mut a, mut b) = (1u32, 0u32); for byte in &raw { a = (a + u32::from(*byte)) % 65_521; b = (b + a) % 65_521; } z.extend_from_slice(&((b << 16) | a).to_be_bytes()); let mut png = vec![0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]; let mut chunk = |kind: &[u8; 4], data: &[u8]| { png.extend_from_slice(&(data.len() as u32).to_be_bytes()); let mut body = kind.to_vec(); body.extend_from_slice(data); png.extend_from_slice(&body); png.extend_from_slice(&crc32(&body).to_be_bytes()); }; let mut header = Vec::new(); header.extend_from_slice(&side.to_be_bytes()); header.extend_from_slice(&side.to_be_bytes()); header.extend_from_slice(&[8, 2, 0, 0, 0]); chunk(b"IHDR", &header); chunk(b"IDAT", &z); chunk(b"IEND", &[]); png}fn crc32(bytes: &[u8]) -> u32 { let mut crc = 0xFFFF_FFFFu32; for byte in bytes { crc ^= u32::from(*byte); for _ in 0..8 { crc = if crc & 1 != 0 { (crc >> 1) ^ 0xEDB8_8320 } else { crc >> 1 }; } } !crc}#[cfg(test)]mod tests { /// The invented picture is a PNG a reader opens: its signature, its header, and the CRC of its header chunk. #[test] fn the_invented_face_is_a_png() { let png = super::solid_png(4, [1, 2, 3]); assert_eq!(&png[..8], &[0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A]); assert_eq!(&png[12..16], b"IHDR"); assert_eq!(super::crc32(b"IEND"), 0xAE42_6082, "IEND's well-known CRC"); }}