//! A group EVENT, read out of a message's `meta`, and the one English sentence//! that goes in its body.//!//! The port of `packages/core/src/messages/groupEvent.ts`.//!//! Two readers, two needs, and the split between them is the whole point://!//! * the APP renders per VIEWER, in the catalog's second person — "You created//! the group" for the person who did it, "Asha created the group" for//! everyone else. That lives in the app (`lib/messages/groupEventLine.ts`),//! because only the app has Lingui and only the reader knows who they are.//! * the BODY column is viewer-NEUTRAL and written once, here. It has to be: the//! row is mirrored verbatim into every member's file, and the same bytes are//! read by search, by the chat-list preview, by an assistant over MCP and by//! any build older than this change. A body that said "you" would be true in//! exactly one file.//!//! That is the chat rule this module encodes: **a group event is a structured row//! its actor authored, and the server writes no line of its own.** The server//! fills a blank actor from the envelope's SIGNED author on the way out and does//! nothing else — it never composes a sentence, because a sentence composed by//! the server would be the server claiming to have witnessed something.//!//! Pure: no clock, no locale, no store. The strings are English (the only//! supported language, `[english-only-no-translations]`) and are deliberately NOT//! Lingui macros — the server imports this module and has no catalog, exactly as//! [`super::preview`] explains for its own strings.use serde_json::Value;usecrate::constants::GroupEventKind;usecrate::messages::{js_trim, GroupEvent, MessageMeta, MessageSystem};/// Is this `meta.system` the structured form rather than the bare flag?pubfn is_group_event(system: Option<&MessageSystem>) -> bool { matches!(system, Some(MessageSystem::Event(_)))}/// The event behind a system row, or `None`.////// `None` for a row that is not a system line AND for one written before events/// were structured (`system: true` plus a body). Both are ordinary: an imported/// WhatsApp archive is full of the second kind and always will be, so a caller/// that gets `None` falls back to the body rather than treating it as drift.pubfn group_event_of(meta: Option<&MessageMeta>) -> Option<&GroupEvent> {match meta.and_then(|meta| meta.system.as_ref()) {Some(MessageSystem::Event(event)) => Some(event), _ => None, }}/// "Meera" · "Meera and Asha" · "Meera, Asha and Dev".pubfn join_names(names: &[String]) -> String {match names { [] => String::new(), [only] => only.clone(), [head @ .., last] => format!("{} and {last}", head.join(", ")), }}/// The actor value that means "the owner of the file this row is written in",/// spelt out rather than left blank.////// `null` is the spelling a LIVE row uses, because the server fills a blank actor/// with the envelope's author on the way to every other member's file. An/// IMPORTED row never travels — the relay ignores a row whose origin is not/// `live` — so the Mac's importer stamps this literal instead of a blank it would/// be the only reader of.////// Two spellings, one meaning, and [`is_owner_actor`] is the ONE place that knows/// it. Never compare an actor to either value by hand.////// It is also the word every chat READ substitutes for the owner — a reaction's/// `by`, an outbound message's `from` — and the one the phone's own half then/// compares against to find the reader's own reaction. Producer and reader are/// in different crates, so a bare literal on either side is a word that can/// drift with nothing to notice; this const is what makes them the same word.pubconst OWNER_ACTOR: &str = "owner";/// Whether an actor is this file's own owner — absent, or [`OWNER_ACTOR`].////// The TypeScript takes `string | null | undefined` and answers yes to both/// absences; Rust has one absence, so `None` covers them both.pubfn is_owner_actor(actor: Option<&str>) -> bool {match actor {None => true,Some(value) => value == OWNER_ACTOR, }}/// What to call somebody, given a namer that answers for this file.////// Takes `None` — a null actor means "this file's owner", and the file that WROTE/// the row is the one that knows their name.////// A phone is a real answer, not a placeholder: "919876500001" is somebody a/// reader can recognise, and a generic word would be strictly less information.fn name_of<F>(phone: Option<&str>, name_for: &F) -> Stringwhere F: Fn(Option<&str>) -> Option<String>,{let given = name_for(phone);let given = given.as_deref().map(js_trim).unwrap_or("");if !given.is_empty() {return given.to_string(); }// `OWNER_ACTOR` is not a number and must never be printed as one — an unnamed// owner is "Someone", the same answer a blank actor gets.match phone {Some(phone) if !is_owner_actor(Some(phone)) => phone.to_string(), _ => "Someone".to_string(), }}/// The viewer-neutral English sentence for an event — what goes in the body.////// Third person throughout, including for the actor: this string is read in N/// files and only one of them belongs to the person who acted.////// `name_for` is the TypeScript's `GroupEventNameFor`, a function from a phone (or/// `None`, the file's owner) to a display name. It stays a callback rather than a/// map because the app resolves a name through its contact store and the server/// through the file, and neither can hand the other a finished table.pubfn group_event_sentence<F>(event: &GroupEvent, name_for: &F) -> Stringwhere F: Fn(Option<&str>) -> Option<String>,{let actor = name_of(event.actor.as_deref(), name_for);// "someone" only when a participant carried no phone at all — structurally// impossible in a Cotton group (every participant is a contact) and still// better than a sentence that stops mid-air.let named: Vec<String> = event .subjects .as_deref() .unwrap_or(&[]) .iter() .map(|phone| name_of(Some(phone), name_for)) .collect();let joined = join_names(&named);let subjects = if joined.is_empty() {"someone" } else { &joined };// An exhaustive `match` and NOT a lookup table: the TypeScript's `switch` is// exhaustive by type, and a kind added to `GROUP_EVENT_KINDS` without a// sentence must fail the BUILD here rather than return an empty line into a// timeline.match event.kind {GroupEventKind::Created => format!("{actor} created the group"),GroupEventKind::Added => format!("{actor} added {subjects}"),GroupEventKind::Removed => format!("{actor} removed {subjects}"),GroupEventKind::Left => format!("{actor} left"),GroupEventKind::Renamed => format!("{actor} changed the group name to \u{201c}{}\u{201d}", event.title.as_deref().unwrap_or("") ),GroupEventKind::Photo => format!("{actor} changed the group photo"),GroupEventKind::Description => format!("{actor} changed the group description"), }}/// Why an untrusted `meta.system` could not be read as an event.////// `Display` is the TypeScript's thrown sentence VERBATIM, `JSON.stringify` of/// the offending value included, so a handler can pass it to the error envelope/// unchanged and a log line still names what was actually in the column.#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]#[error("{0}")]pubstructGroupEventParseError(pubString);/// `JSON.stringify(value)` for the one shape these messages need — the store's/// own JS-faithful stringifier, so `undefined` (an ABSENT key) prints as the/// literal `undefined` exactly as the template literal does.fn stringify(value: Option<&Value>) -> String {match value {None => "undefined".to_string(),Some(value) => cotton_store::protocol::js::json_stringify(value), }}/// Read an event off untrusted JSON, or refuse.////// Shares the asymmetry of every other `meta` parser: a PRESENT key with the/// wrong shape is drift and refuses (only this repo's own code writes it), while/// extra keys inside it are ignored. An unknown `kind` refuses too — the list is/// the constraint, and a row nobody can render is worse than a loud failure.pubfn parse_group_event( value: &serde_json::Map<String, Value>,) -> Result<GroupEvent, GroupEventParseError> {let kind_value = value.get("kind");let kind = kind_value .and_then(Value::as_str) .and_then(GroupEventKind::parse) .ok_or_else(|| {let known: Vec<&str> = GroupEventKind::ALL.iter().map(|kind| kind.as_str()).collect();GroupEventParseError(format!("Unexpected value for cotton_msg_messages.meta.system.kind: {}. Expected one of {}.", stringify(kind_value), known.join(", ") )) })?;let actor_value = value.get("actor");let actor = match actor_value {None | Some(Value::Null) => None,Some(Value::String(actor)) => Some(actor.clone()),Some(other) => {returnErr(GroupEventParseError(format!("Unexpected value for cotton_msg_messages.meta.system.actor: {}. Expected a phone or null.", cotton_store::protocol::js::json_stringify(other) ))) } };// A blank actor reads as null: the file that wrote it had nothing to say// about who acted, which is exactly what "the owner of this file" means.let actor = actor.filter(|actor| !actor.is_empty());letmut event = GroupEvent { kind, actor, subjects: None, title: None, };match value.get("subjects") {None | Some(Value::Null) => {}Some(Value::Array(items)) if items.iter().all(Value::is_string) => { event.subjects = Some( items .iter() .map(|item| item.as_str().unwrap_or_default().to_string()) .collect(), ); }Some(other) => {returnErr(GroupEventParseError(format!("Unexpected value for cotton_msg_messages.meta.system.subjects: {}. Expected an array of phones.", cotton_store::protocol::js::json_stringify(other) ))) } }// Only a string survives: `title: 7` is neither kept nor refused, exactly as// the TypeScript's `if (typeof title === "string")` decides.ifletSome(Value::String(title)) = value.get("title") { event.title = Some(title.clone()); }Ok(event)}#[cfg(test)]#[path = "group_event_tests.rs"]mod tests;