Cotton code
472 lines · 24.7 KB · RustRaw
//! Talk: the message shapes beyond a plain direct chat (a group with members,//! an imported chat, pictures, voice notes and files, reactions, kept//! messages, a pinned, a muted and an archived chat, a number with no name,//! a chat with nothing in it), the phone's call history, meetings with their//! transcript, summary and decisions, the statuses people posted — and, on a few people, what makes a//! person's page more than a card: notes about them and the things they are//! linked to.//!//! MOSTLY NO BYTES ARE WRITTEN. A media message names an object that is not//! there (the bubble draws its placeholder, a voice note its waveform), and a//! meeting's audio is marked released where a walk should see that state. The//! exceptions are what a walk has to PLAY: the first meeting's recording and//! the first chat's film, voice note and file are generated in code//! (`sound`, `film`, `paper`) and handed to the media sink.//! Calls and meetings have no tool that makes them — the phone's importer and//! the meetings pipeline do — so they are stamped patches in those writers'//! shapes, and EVERY MEETING IS FINISHED (ready or failed): a queued one would//! be picked up for transcription.use super::{call, id_of, iso, object, refused, Env, Household};use crate::mcp::dispatch::Ctx;use crate::mcp::handlers::chat::messages::star_message;use crate::mcp::handlers::chat::threads::{set_thread_archived, set_thread_muted, set_thread_pinned};use crate::mcp::handlers::common::{insert_row, update_row};use crate::mcp::handlers::owner::work::create_link;use crate::mcp::handlers::records_1::notes::create_note;use crate::mcp::handlers::records_1::todos::create_todo;use crate::messages::sink::queue_changes;use crate::synthetic::sound::{self, Hum};use crate::synthetic::{film, names, paper};use chrono::{DateTime, Duration, Utc};use sha2::{Digest, Sha256};use cotton_core::constants::{MessageChannel, MessageDirection, MessageMediaKind, MessageOrigin};use cotton_core::messages::apply_message_write::{    apply_message_write, ApplyMessageWriteError, MessageWriteInput, MessageWriteThread,};use cotton_core::messages::ids::reaction_row_id;use cotton_core::messages::MessageMedia;use cotton_store::protocol::derived_id;use cotton_store::{Result, StoreError};use serde_json::{json, Value};/// Every table written here, for the household's recount.pub(super) const TABLES: &[&str] = &[    "cotton_msg_contacts",    "cotton_msg_threads",    "cotton_msg_thread_participants",    "cotton_msg_messages",    "cotton_msg_reactions",    "cotton_call_log",    "cotton_stories",    "cotton_links",    "cotton_todos",    "cotton_notes",];/// How long the first chat's film and voice note play.const PLAYABLE_FILM_SECONDS: u32 = 4;const PLAYABLE_VOICE_MS: i64 = 6_000;/// One message into one thread, as `write_messages` writes them.struct Send<'a> {    thread: &'a str,    at: DateTime<Utc>,    direction: MessageDirection,    body: Option<&'a str>,    media: &'a [MessageMedia],    /// The group member who said it.    sender: Option<&'a str>,    reply_to: Option<&'a str>,    /// An imported chat's own id for the message.    external: Option<&'a str>,}/// Writes `send`, answering the message's id. `last` is the thread's newest/// message so far, which the write keeps in step.fn send(ctx: &mut Ctx<'_>, env: &Env<'_>, last: &mut Option<String>, send: Send<'_>) -> Result<String> {    let message_id = ctx.new_uuid();    let sent_at = iso(send.at);    ctx.now = send.at;    let imported = send.external.is_some();    let input = MessageWriteInput {        body: send.body,        media: send.media,        sender_participant_id: send.sender,        reply_to_id: send.reply_to,        external_id: send.external,        channel: imported.then_some(MessageChannel::Whatsapp),        origin: imported.then_some(MessageOrigin::Imported),        ..MessageWriteInput::new(            MessageWriteThread { id: send.thread, workspace_id: env.workspace_id, last_message_at: last.as_deref() },            &message_id,            send.direction,            &sent_at,            &sent_at,        )    };    let writer = ctx.writer().map_err(refused("message"))?;    apply_message_write(|changes| queue_changes(writer, changes), &input).map_err(|error| match error {        ApplyMessageWriteError::Refused(refusal) => StoreError::refused(format!("synthetic household: message: {refusal}")),        ApplyMessageWriteError::Sink(refusal) => StoreError::refused(format!("synthetic household: message: {refusal}")),    })?;    ctx.commit().map_err(refused("message"))?;    *last = Some(sent_at);    Ok(message_id)}impl Household<'_> {    pub(super) fn write_message_shapes(&mut self) -> Result<()> {        let env = &self.env;        let rng = env.rng();        let people = &self.people;        // The people `write_messages` gave a contact and a direct chat.        let chatting = env.plan.message_threads.min(people.len());        if chatting < 5 {            return Ok(());        }        let namespace = env.file.namespace();        let contact = |n: usize| derived_id::msg_contact_id(namespace, &people[n].phone_digits);        let direct = |n: usize| derived_id::dm_thread_id(namespace, &contact(n));        let media = |thread: &str, kind: MessageMediaKind, content_type: &str, ext: &str| MessageMedia {            key: cotton_core::media::keys::message_media_key(env.file.id(), thread, &env.hex(64), ext),            content_type: content_type.to_string(),            kind: Some(kind),            size_bytes: Some(rng.between(20_000, 2_000_000) as f64),            ..MessageMedia::default()        };        env.once(env.now - Duration::days(21), |ctx| {            // ── Two groups: one talked in here, one brought in from WhatsApp. ──            for (key, title, description, imported) in [                ("synthetic-group-cousins", "The cousins", "Birthdays, lifts and who has the big pot.", false),                ("synthetic-whatsapp-allotment", "Allotment committee", "Imported from a WhatsApp export.", true),            ] {                let thread = derived_id::group_thread_id(namespace, key);                let row = object(json!({ "kind": "group", "title": title, "description": description, "external_key": key }));                insert_row(ctx, "cotton_msg_threads", &thread, row).map_err(refused("group chat"))?;                ctx.commit().map_err(refused("group chat"))?;                let me = ctx.new_uuid();                let row = object(json!({ "thread_id": thread, "is_self": true, "role": "admin" }));                insert_row(ctx, "cotton_msg_thread_participants", &me, row).map_err(refused("group member"))?;                let mut members: Vec<String> = Vec::new();                for (n, person) in people.iter().enumerate().take(4) {                    let id = ctx.new_uuid();                    let mut row = object(json!({                        "thread_id": thread, "contact_id": contact(n), "display_name": person.name,                        "role": if n == 0 { "admin" } else { "member" },                    }));                    // One of them left a while ago; what they said stays.                    if n == 3 {                        row.insert("left_at".into(), Value::from(iso(env.now - Duration::days(6))));                    }                    insert_row(ctx, "cotton_msg_thread_participants", &id, row).map_err(refused("group member"))?;                    members.push(id);                }                ctx.commit().map_err(refused("group member"))?;                let mut last: Option<String> = None;                let mut said: Vec<String> = Vec::new();                let count = 36;                for n in 0..count {                    let at = env.now - Duration::days(20) + Duration::minutes(n * (20 * 24 * 60 / count) + rng.between(0, 240));                    let mine = rng.chance(30);                    let external = imported.then(|| format!("synthetic-wa-{n}"));                    let attached = match n {                        7 => vec![MessageMedia {                            width: Some(1200.0),                            height: Some(900.0),                            name: Some("IMG-0041.jpg".into()),                            ..media(&thread, MessageMediaKind::Image, "image/jpeg", "jpg")                        }],                        13 => vec![MessageMedia {                            duration_ms: Some(17_000.0),                            waveform: Some((0..64).map(|_| rng.between(5, 100) as f64 / 100.0).collect()),                            ..media(&thread, MessageMediaKind::Voice, "audio/ogg", "ogg")                        }],                        19 => vec![MessageMedia {                            name: Some("Minutes.pdf".into()),                            ..media(&thread, MessageMediaKind::File, "application/pdf", "pdf")                        }],                        26 => vec![MessageMedia {                            width: Some(720.0),                            height: Some(1280.0),                            duration_ms: Some(42_000.0),                            ..media(&thread, MessageMediaKind::Video, "video/mp4", "mp4")                        }],                        _ => Vec::new(),                    };                    // A picture or a voice note often comes with no words.                    let body = (attached.is_empty() || n == 7).then(|| *rng.pick(names::GROUP_LINES));                    // A line the export left out, and one written in Markdown.                    let body = match n {                        3 => Some("[unsupported message]"),                        22 => Some("To bring on Saturday:\n- the **big** pot\n- two folding chairs\n- the `hall` key"),                        _ => body,                    };                    let reply_to = (n == 10).then(|| said[8].clone());                    let id = send(                        ctx,                        env,                        &mut last,                        Send {                            thread: &thread,                            at: at.min(env.now),                            direction: if mine { MessageDirection::Out } else { MessageDirection::In },                            body,                            media: &attached,                            sender: if mine { Some(&me) } else { Some(&members[rng.below(members.len())]) },                            reply_to: reply_to.as_deref(),                            external: external.as_deref(),                        },                    )?;                    said.push(id);                }                // Reactions: the owner's and other people's, two on one message.                for (n, actor, emoji) in [(7, "self", "❤️"), (7, people[1].phone_digits.as_str(), "😂"), (12, people[2].phone_digits.as_str(), "👍"), (30, "self", "👍")] {                    let id = reaction_row_id(&said[n], actor)                        .map_err(|error| StoreError::refused(format!("synthetic household: reaction: {error}")))?;                    let row = object(json!({ "thread_id": thread, "message_id": said[n], "actor": actor, "emoji": emoji }));                    insert_row(ctx, "cotton_msg_reactions", &id, row).map_err(refused("reaction"))?;                }                ctx.commit().map_err(refused("reaction"))?;                for n in [5, 19, 33] {                    call("kept message", star_message(ctx, &object(json!({ "messageId": said[n], "starred": true }))))?;                }                // One message its sender deleted: the line stays, its words do not.                let patch = object(json!({ "deleted_at": iso(env.now - Duration::days(4)) }));                update_row(ctx, "cotton_msg_messages", &said[16], patch).map_err(refused("deleted message"))?;                ctx.commit().map_err(refused("deleted message"))?;            }            // ── Direct chats: pinned, muted. ──            ctx.now = env.now - Duration::days(2);            call("pinned chat", set_thread_pinned(ctx, &object(json!({ "threadId": direct(0), "pinned": true }))))?;            let args = object(json!({ "threadId": direct(1), "until": "9999-12-31T00:00:00Z" }));            call("muted chat", set_thread_muted(ctx, &args))?;            // ── Three more numbers: an archived chat, a number with no name            //    and no person, a chat with nothing in it yet. ──            for (digits, name, lines, archived) in [                ("12025550101", Some("Old landlord"), 4, true),                ("12025550102", None, 2, false),                ("12025550103", Some("New neighbour"), 0, false),            ] {                let contact_id = derived_id::msg_contact_id(namespace, digits);                let mut row = object(json!({ "phone_e164": digits }));                if let Some(name) = name {                    row.insert("display_name".into(), Value::from(name));                }                insert_row(ctx, "cotton_msg_contacts", &contact_id, row).map_err(refused("message contact"))?;                let thread = derived_id::dm_thread_id(namespace, &contact_id);                let row = object(json!({ "kind": "dm", "contact_id": contact_id }));                insert_row(ctx, "cotton_msg_threads", &thread, row).map_err(refused("message thread"))?;                ctx.commit().map_err(refused("message thread"))?;                let mut last: Option<String> = None;                for n in 0..lines {                    let at = env.now - Duration::days(if archived { 200 } else { 1 }) + Duration::minutes(n * 7);                    let said = Send {                        thread: &thread,                        at,                        direction: if archived && n % 2 == 1 { MessageDirection::Out } else { MessageDirection::In },                        body: Some(*rng.pick(names::MESSAGE_LINES)),                        media: &[],                        sender: None,                        reply_to: None,                        external: None,                    };                    send(ctx, env, &mut last, said)?;                }                if archived {                    ctx.now = env.now - Duration::days(190);                    call("archived chat", set_thread_archived(ctx, &object(json!({ "threadId": thread, "archived": true }))))?;                }            }            Ok(())        })?;        self.write_playable_messages()    }    /// The first chat in the list — the pinned one, and its newest lines —    /// ends with one of each thing a conversation draws beyond words, and    /// each with its bytes really there: a film (H.264 in an MP4), a voice    /// note (a WAV), a file (a PDF) and a line written in Markdown. Each    /// object is content-addressed under the chat's folder    /// (`message_media_key`) and handed to the media sink, which is where the    /// served object store keeps it — so the phone's Fetch delivers it.    fn write_playable_messages(&mut self) -> Result<()> {        let env = &self.env;        let chatting = env.plan.message_threads.min(self.people.len());        if chatting < 5 {            return Ok(());        }        let namespace = env.file.namespace();        let thread = derived_id::dm_thread_id(namespace, &derived_id::msg_contact_id(namespace, &self.people[0].phone_digits));        let stored = |bytes: &[u8], content_type: &str, ext: &str, kind: MessageMediaKind| -> Result<MessageMedia> {            let key = cotton_core::media::keys::message_media_key(env.file.id(), &thread, &hex::encode(Sha256::digest(bytes)), ext);            self.put(&key, bytes)?;            Ok(MessageMedia { kind: Some(kind), size_bytes: Some(bytes.len() as f64), ..MessageMedia::new(&key, content_type) })        };        let film = MessageMedia {            width: Some(film::WIDTH as f64),            height: Some(film::HEIGHT as f64),            duration_ms: Some(f64::from(PLAYABLE_FILM_SECONDS * 1000)),            name: Some("Sunset from the hill.mp4".into()),            ..stored(&film::mp4(PLAYABLE_FILM_SECONDS), "video/mp4", "mp4", MessageMediaKind::Video)?        };        let hums: Vec<Hum> = [(0, 1_400, 190.0), (1_700, 3_300, 210.0), (3_700, 5_600, 180.0)]            .iter()            .map(|&(from_ms, to_ms, hz)| Hum { from_ms, to_ms, hz })            .collect();        let voice_samples = sound::samples(PLAYABLE_VOICE_MS, &hums);        let voice = MessageMedia {            duration_ms: Some(PLAYABLE_VOICE_MS as f64),            waveform: Some(sound::waveform(&voice_samples)),            ..stored(&sound::wav(&voice_samples), "audio/wav", "wav", MessageMediaKind::Voice)?        };        let paper = paper::pdf(            "Allotment plot 14: planting plan",            &["Bed one: beans and peas, after the frost.", "Bed two: potatoes (earlies), then leeks.", "Bed three: onions, garlic and the herb corner.", "Water butts: check the lids before the summer."],        );        let file = MessageMedia {            name: Some("Planting plan.pdf".into()),            ..stored(&paper, "application/pdf", "pdf", MessageMediaKind::File)?        };        let markdown = "Plan for **Saturday**:\n\n- pick up the *trailer* at nine\n- drop the old shelves at the tip\n- lunch at ours\n\nThe tip's hours are on [example.com](https://example.com/tip-hours).";        let last = self.env.db.get("SELECT last_message_at FROM cotton_msg_threads WHERE id = ?", &[rusqlite::types::Value::Text(thread.clone())])?;        let mut last = last.and_then(|row| row.text("last_message_at").map(str::to_string));        let lines: [(i64, MessageDirection, Option<&str>, Vec<MessageMedia>); 4] = [            (40, MessageDirection::In, None, vec![film]),            (30, MessageDirection::In, None, vec![voice]),            (20, MessageDirection::Out, Some("Here's the plan for the plot."), vec![file]),            (10, MessageDirection::In, Some(markdown), Vec::new()),        ];        env.once(env.now - Duration::minutes(40), |ctx| {            for (ago, direction, body, media) in &lines {                let said = Send {                    thread: &thread,                    at: env.now - Duration::minutes(*ago),                    direction: *direction,                    body: *body,                    media,                    sender: None,                    reply_to: None,                    external: None,                };                send(ctx, env, &mut last, said)?;            }            Ok(())        })    }    /// `cotton_call_log` in the phone importer's shape: answered both ways,    /// missed, cancelled, a number in nobody's contacts and a withheld one.    pub(super) fn write_calls(&mut self) -> Result<()> {        let env = &self.env;        let rng = env.rng();        let people = &self.people;        let chatting = env.plan.message_threads.min(people.len());        let namespace = env.file.namespace();        let mut calls: Vec<(DateTime<Utc>, usize)> = (0..48).map(|n| (env.now - Duration::minutes(rng.between(30, 60 * 24 * 45)), n)).collect();        calls.sort_by_key(|item| item.0);        env.once(env.now, |ctx| {            for (at, n) in &calls {                let id = derived_id::call_log_id(namespace, "ios_call_history", &format!("synthetic-call-{n}"));                let (direction, outcome) = match rng.below(10) {                    0..=3 => ("in", "answered"),                    4..=6 => ("out", "answered"),                    7..=8 => ("in", "missed"),                    _ => ("out", "cancelled"),                };                let duration = if outcome == "answered" { rng.between(20, 2_400) } else { 0 };                let mut row = object(json!({                    "source": "ios_call_history",                    "external_id": format!("synthetic-call-{n}"),                    "provider": *rng.pick(&["cellular", "cellular", "cellular", "whatsapp", "facetime_audio", "facetime_video"]),                    "direction": direction,                    "outcome": outcome,                    "started_at": iso(*at),                    "duration_s": duration,                    "device": "iPhone",                    "meta": {},                }));                match n % 8 {                    // A number in nobody's contacts.                    6 => {                        row.insert("handle".into(), Value::from(format!("9995557{:05}", n * 131)));                    }                    // Withheld: no number at all.                    7 => {}                    _ if chatting > 0 => {                        let person = &people[rng.below(chatting)];                        row.insert("handle".into(), Value::from(person.phone_digits.clone()));                        row.insert("contact_id".into(), Value::from(derived_id::msg_contact_id(namespace, &person.phone_digits)));                        row.insert("person_id".into(), Value::from(person.id.clone()));                    }                    _ => {}                }                insert_row(ctx, "cotton_call_log", &id, row).map_err(refused("call"))?;            }            ctx.commit().map_err(refused("call"))?;            Ok(())        })    }    /// `cotton_stories` as the WhatsApp reader keeps them: statuses from the    /// people you chat with, one still up in the app, the rest past its expiry    /// and kept here, one kept for good, one a picture whose bytes are not    /// there. The reader makes them, so they are stamped rows like the calls.    pub(super) fn write_stories(&mut self) -> Result<()> {        let env = &self.env;        let chatting = env.plan.message_threads.min(self.people.len());        if chatting == 0 {            return Ok(());        }        let people = &self.people[..chatting];        let namespace = env.file.namespace();        let posts: [(&str, &str, i64, bool); 4] = [            ("text", "First swim of the season, the water is still cold", 3, false),            ("image", "The market had the first figs", 20, false),            ("text", "Back from the hills, phone off for a week", 50, true),            ("text", "Sold out by noon, thank you all", 120, false),        ];        env.once(env.now, |ctx| {            for (n, (kind, caption, hours_ago, kept)) in posts.iter().enumerate() {                let external = format!("synthetic-story-{n}");                let person = &people[n % people.len()];                let posted = env.now - Duration::hours(*hours_ago);                let mut row = object(json!({                    "source": "whatsapp",                    "account": "me",                    "external_id": external,                    "person_id": person.id,                    "sender": person.phone_digits,                    "sender_label": person.name,                    "kind": kind,                    "caption": caption,                    "posted_at": iso(posted),                    "expires_at": iso(posted + Duration::hours(24)),                    "kept": kept,                }));                if *kind == "image" {                    row.insert("media_key".into(), Value::from(cotton_core::media::keys::message_media_key(env.file.id(), "stories", &env.hex(64), "jpg")));                    row.insert("media_content_type".into(), Value::from("image/jpeg"));                }                insert_row(ctx, "cotton_stories", &derived_id::story_id(namespace, "whatsapp", &external), row).map_err(refused("story"))?;            }            ctx.commit().map_err(refused("story"))        })    }    /// On the first few people: open todos and a note linked to them    /// (`create_link`), so a person's page has its sections.    pub(super) fn write_people_shapes(&mut self) -> Result<()> {        let env = &self.env;        let people = &self.people;        env.once(env.now - Duration::days(3), |ctx| {            for person in people.iter().take(4) {                let mut linked: Vec<(&str, String)> = Vec::new();                for (title, days) in [(format!("Call {} back", person.first), 1), (format!("Send {} the photos", person.first), 4)] {                    let args = object(json!({ "title": title, "dueAt": iso(env.day_at(days, 11, 0)) }));                    linked.push(("todo", id_of("todo", &call("todo about a person", create_todo(ctx, &args))?)?));                }                let args = object(json!({ "title": format!("Things {} recommended", person.first), "body": env.sentences(2, 4) }));                linked.push(("note", id_of("note", &call("note about a person", create_note(ctx, &args))?)?));                for (kind, id) in linked {                    let args = object(json!({ "fromKind": kind, "fromId": id, "toKind": "person", "toId": person.id }));                    call("person link", create_link(ctx, &args))?;                }            }            Ok(())        })    }}