//! A poll, as WhatsApp's text export writes one — the port of//! `packages/import-core/src/poll.ts`.//!//! The export renders a poll as an ordinary message body, several lines long://!//! ```text//! POLL://! Which day works for the site visit?//! OPTION: Thursday (3 votes)//! OPTION: Friday (1 vote)//! ```//!//! Everything about that is data — the question, the options, and how many//! people picked each — and until 2026-09-05 all of it imported as one//! undifferentiated paragraph nothing could read.//!//! ## Why this matches on SHAPE and not on the word "POLL"//!//! The keywords follow the exporting phone's WhatsApp UI language, not the//! chat's: a German phone writes `UMFRAGE:` / `OPTION:` / `(1 Stimme)`,//! Spanish `ENCUESTA:` / `OPCIÓN:` / `(4 votos)`, Portuguese `ENQUETE:` ///! `OPÇÃO:`, Italian `SONDAGGIO:` / `OPZIONE:` / `(2 voti)`. Matching the//! English word would silently import every non-English owner's polls as//! prose. So the grammar is structural: a single-token line ending in a colon,//! then the question, then a run of single-token lines each ending in//! `(<digits> <word>)`. The vote word itself is never read.//!//! The false positive this guards against is a person whose message opens with//! one all-caps word and a colon (`TOMORROW:`), which is why at least TWO//! option lines are required — WhatsApp cannot create a poll with fewer, and//! no ordinary message accidentally has two.//!//! ## What it does NOT do//!//! It does not rewrite the message body. The body stays exactly what the//! export wrote, because the body is what the content fingerprint hashes://! re-wording it would change the message's identity and re-import every poll//! anybody has already imported as a second copy. The reading is added BESIDE//! the words, in `meta.poll`.//!//! It does not record WHO voted for what. The export does not say — it gives//! totals and nothing else — and inventing a voter would be worse than the gap.use std::sync::OnceLock;use regex::Regex;use serde::{Deserialize, Serialize};usecrate::import::text::{js_trim, utf16_len, JS_DOT_CLASS, JS_WHITESPACE_CLASS};/// One choice on a poll, and how many people picked it.#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pubstructTxtPollOption {pub text: String,/// `Number(<digits>)` in the TypeScript.////// `i64`, not `f64`: the value is written into `meta.poll` as JSON and/// serde prints an integral `f64` as `3.0` where `JSON.stringify` prints/// `3` — a two-character difference in a stored patch. A count too wide/// for an `i64` refuses the whole poll rather than saturating silently;/// JavaScript would answer an imprecise `1e20` there, and a poll with/// nineteen digits of votes is not a poll.pub votes: i64,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pubstructTxtPoll {pub question: String,pub options: Vec<TxtPollOption>,}/// WhatsApp refuses a poll with fewer, so fewer is not a poll.const MIN_OPTIONS: usize = 2;/// A keyword is one token, no spaces and no colon of its own, 3–24 units long./// The LENGTH is checked in code rather than as a `{3,24}` quantifier: a/// JavaScript quantifier counts UTF-16 code units and Rust's counts/// characters, so a two-emoji keyword would be 4 units there and 2 chars here.const KEYWORD_MIN: usize = 3;const KEYWORD_MAX: usize = 24;fn header_re() -> &'staticRegex {static RE: OnceLock<Regex> = OnceLock::new(); RE.get_or_init(|| Regex::new(&format!("^([^{JS_WHITESPACE_CLASS}:]+):$")).expect("poll header"))}/// `OPTION: Thursday (3 votes)` — the count anchored at the end, text greedy,/// so an option may itself contain brackets or a colon.fn option_re() -> &'staticRegex {static RE: OnceLock<Regex> = OnceLock::new(); RE.get_or_init(|| {Regex::new(&format!(r"^([^{JS_WHITESPACE_CLASS}:]+):[ \t]+({JS_DOT_CLASS}*[^{JS_WHITESPACE_CLASS}])[ \t]+\(([0-9]+)[ \t]+[^{JS_WHITESPACE_CLASS}]+\)$" )) .expect("poll option") })}fn keyword_of<'a>(captures: ®ex::Captures<'a>) -> Option<&'a str> {let keyword = captures.get(1)?.as_str();let units = utf16_len(keyword);if (KEYWORD_MIN..=KEYWORD_MAX).contains(&units) {Some(keyword) } else {None }}/// Read a poll out of a message body, or answer `None` for an ordinary/// message.////// The body must already have been through `normalize_export_text` — the/// export writes a LEFT-TO-RIGHT MARK before `POLL:` and before every/// `OPTION:` on iOS, and German counts votes with a NARROW NO-BREAK SPACE/// inside the parentheses. Both are gone by the time a `TxtMessage` exists.pubfn parse_poll_body(body: &str) -> Option<TxtPoll> {let lines: Vec<&str> = body.split('\n').collect();if lines.len() < 2 + MIN_OPTIONS {returnNone; }let first = js_trim(lines[0]); header_re().captures(first).as_ref().and_then(keyword_of)?;// The options are the trailing run: walk back from the end while the lines// keep matching, which is what lets the QUESTION contain anything at all —// blank lines, colons, a line that looks like an option.letmut first_option = lines.len();letmut keyword: Option<String> = None;letmut options: Vec<TxtPollOption> = Vec::new();for index in (1..lines.len()).rev() {letSome(captures) = option_re().captures(js_trim(lines[index])) else {break; };letSome(found) = keyword_of(&captures) else {break; };match &keyword {None => keyword = Some(found.to_string()),Some(previous) if previous != found => break,Some(_) => {} }letOk(votes) = captures[3].parse::<i64>() else {break; }; options.insert(0,TxtPollOption { text: captures[2].to_string(), votes, }, ); first_option = index; }if options.len() < MIN_OPTIONS {returnNone; }let question = js_trim(&lines[1..first_option].join("\n")).to_string();if question.is_empty() {returnNone; }Some(TxtPoll { question, options })}/* ------------------------------------------------- a poll from WhatsApp -- *//// A poll that came through the WhatsApp link, as `meta.poll` holds it: the question, the options in WhatsApp's/// order each with its count, how many one voter may pick (0: any), and who picked what (owner, FEEDBACK-3, 23 Nov/// 2026: the counts and who voted for what, updating as votes arrive). Votes fill `voters` through/// `MessageChange::Vote` (`{ who: digits | "me", options: [index], at }`, CONTRACT "Polls shown").pubfn linked_poll(question: &str, options: &[String], selectable: u32) -> serde_json::Value { serde_json::json!({"question": question,"options": options.iter().map(|text| serde_json::json!({ "text": text, "votes": 0 })).collect::<Vec<_>>(),"selectable": selectable,"voters": [], })}/// WhatsApp's hash of an option: the SHA-256 of its words, as lowercase hex (a vote names its picks this way).pubfn option_hash(text: &str) -> String {use sha2::Digest; hex::encode(sha2::Sha256::digest(text.as_bytes()))}/// The options of `poll` (`meta.poll`) a vote picked, by their index, from WhatsApp's hashes of their words: what/// `MessageChange::Vote` carries (CONTRACT "Polls shown"). Picks that name no option of this poll are left out;/// `None` for a `meta.poll` with no options (not a poll a vote can count on).pubfn picked_options(poll: &serde_json::Map<String, serde_json::Value>, picked: &[String]) -> Option<Vec<u32>> {use serde_json::Value;let hashes: Vec<String> = poll .get("options") .and_then(Value::as_array)? .iter() .map(|o| option_hash(o.get("text").and_then(Value::as_str).unwrap_or_default())) .collect();if hashes.is_empty() {returnNone; }letmut chosen: Vec<u32> = picked.iter().filter_map(|p| hashes.iter().position(|h| h.eq_ignore_ascii_case(p)).map(|i| i as u32)).collect(); chosen.sort_unstable(); chosen.dedup();Some(chosen)}#[cfg(test)]#[path = "poll_tests.rs"]mod tests;