Cotton code
217 lines · 9.9 KB · RustRaw
//! CHANGES to messages already in the file: an edit, a delete for everyone, a//! reaction put on or taken off. The import above writes NEW rows only; a//! linked device also sees what happens to a message after it arrived, and//! those land here, on the row the message's own id names.//!//! A change whose message is not in the file (older than anything read, or//! never read) changes nothing and is counted, never kept for later: the row//! it would change does not exist, and a reader that brings that message later//! brings it as it stands then.use super::*;/// One change, keyed by the WhatsApp (or other channel) id of the message it changes.#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]#[serde(rename_all = "camelCase", tag = "kind")]pub enum MessageChange {    /// New text for an earlier message.    Edit { external_id: String, body: String, at: String },    /// Deleted for everyone: the row stays, its words go.    Revoke { external_id: String, at: String },    /// A reaction by `actor` (`"owner"` or a phone); an empty emoji takes it off.    Reaction { external_id: String, actor: String, emoji: String, at: String },    /// A vote on a poll by `voter` (`"owner"` or a phone): the options they hold now, by place in the poll's    /// `options` (WhatsApp sends the whole choice each time); none takes their vote back (CONTRACT "Polls shown").    Vote { external_id: String, voter: String, options: Vec<u32>, at: String },}impl MessageChange {    pub fn external_id(&self) -> &str {        match self {            MessageChange::Edit { external_id, .. }            | MessageChange::Revoke { external_id, .. }            | MessageChange::Reaction { external_id, .. }            | MessageChange::Vote { external_id, .. } => external_id,        }    }}/// What a batch of changes did, by kind.#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize)]pub struct ChangesReport {    pub edited: i64,    pub revoked: i64,    pub reacted: i64,    pub unreacted: i64,    /// Votes put on, changed or taken back on a poll.    pub voted: i64,    /// Changes whose message is not in the file.    pub missing: i64,}/// The ops for one batch of changes on `channel`, in order: a later change to/// the same message wins because it is written later.pub fn plan_message_changes<D: ImportDriver + ?Sized>(    db: &D,    workspace_id: &str,    channel: &str,    changes: &[MessageChange],) -> Result<(Vec<Change>, ChangesReport), ImportError> {    let mut ops = Vec::new();    let mut report = ChangesReport::default();    // A reaction's actor is keyed as the import keys it: code-less, in the    // owner's own number's country.    let region = db.owner_region(workspace_id)?;    // A message's meta as this batch has left it: two votes (or an edit and a vote) on one message in one batch each    // build on the one before, since the ops are applied only after the whole batch is planned.    let mut metas: BTreeMap<String, Map<String, Value>> = BTreeMap::new();    for change in changes {        let Some(target) = db            .message_by_external_id(workspace_id, channel, change.external_id())            .map_err(|error| ImportError::Driver(error.to_string()))?        else {            report.missing += 1;            continue;        };        // A marker of a message the person's own timer erased (CONTRACT.md "WhatsApp through the Mac"): the message        // is gone, so an edit, a delete or a reaction to it has nothing to change, and never writes words back.        if target.meta.get("cotton").and_then(|cotton| cotton.get("erased")).is_some() {            report.missing += 1;            continue;        }        match change {            MessageChange::Edit { body, at, .. } => {                let body = js_trim(body);                if body.is_empty() {                    report.missing += 1;                    continue;                }                let mut meta = metas.get(&target.id).cloned().unwrap_or_else(|| target.meta.clone());                meta.insert("edited".into(), Value::Bool(true));                metas.insert(target.id.clone(), meta.clone());                let mut patch = Map::new();                patch.insert("body".into(), Value::from(body.to_string()));                patch.insert("edited_at".into(), Value::from(at.as_str()));                patch.insert("meta".into(), Value::Object(meta));                ops.push(upsert(MESSAGES, &target.id, patch));                if target.newest {                    ops.push(thread_preview(&target, body, None));                }                report.edited += 1;            }            MessageChange::Revoke { at, .. } => {                let mut patch = Map::new();                patch.insert("body".into(), Value::from(""));                patch.insert("deleted_at".into(), Value::from(at.as_str()));                ops.push(upsert(MESSAGES, &target.id, patch));                if target.newest {                    ops.push(thread_preview(&target, "", Some(at)));                }                report.revoked += 1;            }            MessageChange::Reaction { actor, emoji, at, .. } => {                let resolved = if actor == "owner" {                    Some(REACTION_ACTOR_SELF.to_string())                } else {                    normalize_phone_in(actor, region)                };                let Some(resolved) = resolved else {                    report.missing += 1;                    continue;                };                let Ok(id) = reaction_row_id(&target.id, &resolved) else {                    report.missing += 1;                    continue;                };                let emoji = js_trim(emoji);                if emoji.is_empty() {                    // An emptied reaction takes its relation row back: a                    // Retract, so a later reaction at the id makes it live again.                    ops.push(Change::retract(REACTIONS, &id));                    report.unreacted += 1;                    continue;                }                let mut patch = Map::new();                patch.insert("id".into(), Value::from(id.as_str()));                patch.insert("workspace_id".into(), Value::from(workspace_id));                patch.insert("thread_id".into(), Value::from(target.thread_id.as_str()));                patch.insert("message_id".into(), Value::from(target.id.as_str()));                patch.insert("actor".into(), Value::from(resolved.as_str()));                patch.insert("emoji".into(), Value::from(emoji.to_string()));                patch.insert("created_at".into(), Value::from(at.as_str()));                ops.push(upsert(REACTIONS, &id, patch));                report.reacted += 1;            }            MessageChange::Vote { voter, options, at, .. } => {                // On a poll only; the voter keyed as a reaction's actor is, the owner as the poll's own "me".                let mut meta = metas.get(&target.id).cloned().unwrap_or_else(|| target.meta.clone());                let Some(poll) = meta.get("poll").and_then(|p| serde_json::from_value::<MessagePoll>(p.clone()).ok()) else {                    report.missing += 1;                    continue;                };                let who = if voter == "owner" { Some(POLL_ME.to_string()) } else { normalize_phone_in(voter, region) };                let Some(who) = who else {                    report.missing += 1;                    continue;                };                meta.insert("poll".into(), serde_json::to_value(voted(poll, &who, options, at)).unwrap_or(Value::Null));                metas.insert(target.id.clone(), meta.clone());                let mut patch = Map::new();                patch.insert("meta".into(), Value::Object(meta));                ops.push(upsert(MESSAGES, &target.id, patch));                report.voted += 1;            }        }    }    Ok((ops, report))}/// The owner's own vote on a poll (`voters[].who`).pub const POLL_ME: &str = "me";/// `poll` with `who`'s vote now `options` (their entry replaced whole; none takes it back), each option's `votes`/// counted again from the voters. Options past the poll's end are dropped; a poll with no `selectable` yet takes/// any number (the Mac's link writes it).pub fn voted(mut poll: MessagePoll, who: &str, options: &[u32], at: &str) -> MessagePoll {    let count = poll.options.len() as u32;    let mut chosen: Vec<u32> = options.iter().copied().filter(|i| *i < count).collect();    chosen.sort_unstable();    chosen.dedup();    poll.voters.retain(|v| v.who != who);    if !chosen.is_empty() {        poll.voters.push(MessagePollVoter { who: who.to_string(), options: chosen, at: Some(at.to_string()) });    }    for (i, option) in poll.options.iter_mut().enumerate() {        option.votes = poll.voters.iter().filter(|v| v.options.contains(&(i as u32))).count() as f64;    }    poll}/// The thread's list line after its newest message changed: the same rule the/// import wrote it with, over the message as it now stands. `last_message_at`/// stays, because the message did not move.fn thread_preview(target: &ChangeTarget, body: &str, deleted_at: Option<&str>) -> Change {    let meta: Option<MessageMeta> = serde_json::from_value(Value::Object(target.meta.clone())).ok();    let line = preview_for_message(&PreviewSource {        body: Some(body),        media: &target.media,        deleted_at,        meta: meta.as_ref(),    });    let mut patch = Map::new();    patch.insert("last_message_preview".into(), Value::from(line));    upsert(THREADS, &target.thread_id, patch)}/// A message a change names, as the driver finds it.#[derive(Debug, Clone, PartialEq)]pub struct ChangeTarget {    pub id: String,    pub thread_id: String,    pub meta: Map<String, Value>,    pub media: Vec<MessageMedia>,    /// The thread's list line was made from this message (its `sent_at` is the    /// thread's `last_message_at`), so changing it changes that line too.    pub newest: bool,}