A tiny friend in your Mac's notch and on your iPhone that keeps an eye on your AI coding agents: Claude Code, Codex, Cursor, Gemini CLI, Antigravity and more. Approve from the notch or your Lock Screen.
Swift ai-agentsanthropicantigravityclaudeclaude-codecodexcursordynamic-islandgemini-cliiosiphonlinuxmacosmacos-appmenubar-appnotchopen-sourceswiftswiftuiwindows
Windows and Linux: WhatsApp (experimental), as on the Mac
Claude0453d296f7eb
diff --git a/windows/Cargo.lock b/windows/Cargo.lockindex e7b6b499..8c2db7f3 100644--- a/windows/Cargo.lock+++ b/windows/Cargo.lock@@ -729,6 +729,7 @@ dependencies = ["keyring","libc","mdns-sd",+ "miniz_oxide 0.8.9","qrcode","rcgen","reqwest 0.12.28",diff --git a/windows/README.md b/windows/README.mdindex 01ba7b62..33efc0a7 100644--- a/windows/README.md+++ b/windows/README.md@@ -305,6 +305,64 @@ minute while a CI is running, and as soon as you open the card on data olderthan a minute; contributions every 30 minutes. Nothing is fetched while the pillis off or Coucou is paused.+## WhatsApp (experimental)++The same as on the Mac. Your WhatsApp messages in the island, through a+gateway that runs on this computer. It is off until you turn it on in+**Settings… → Integrations → WhatsApp**. It is unofficial: use it on your own+account only, because WhatsApp may restrict accounts that abuse it.++**Setting it up**++- **Install WhatsApp** downloads [GOWA](https://github.com/aldinokemal/go-whatsapp-web-multidevice),+ the open-source gateway, from its GitHub releases. It picks the zip for this+ system (Windows or Linux, amd64 or arm64) and checks it against the SHA-256+ GOWA publishes; nothing is installed if they differ.+- Coucou then unpacks GOWA into `%LOCALAPPDATA%\Coucou\GOWA` (Windows) or+ `~/.local/share/coucou/GOWA` (Linux) and starts it on `127.0.0.1` only, with+ media downloads off. It stops GOWA when Coucou quits.+- Scan the QR code in Settings with your phone: **WhatsApp › Settings › Linked+ devices › Link a device**.+- **Update** fetches the latest GOWA. Nothing goes to GitHub except on these+ two clicks.++**Using it**++- The island lists one row per conversation, with its initials, name, last+ message and unread count. Photos, voice messages and other media show as a+ label; Coucou never downloads them.+- Click a conversation for its last ten messages and a reply field. **Enter**+ sends, **Shift+Enter** starts a new line and **Escape** goes back. Nothing is+ ever sent without your Enter or click.+- On a new message Mochi smiles, with the "pop" sound if sounds are on.+- Groups stay quiet unless you are mentioned. A right-click on a row ignores+ that chat.+- Read receipts are sent only when you open a conversation, or only when you+ reply if you turn that setting off.++**Your own gateway**++Under **Advanced** you can use your own GOWA or [OpenWA](https://github.com/rmyndharis/OpenWA)+at a local address, with its credential (GOWA's `user:password` or OpenWA's+API key), and change the port of Coucou's webhook (47823).++- The address and the credential are stored in the Credential Manager or the+ Secret Service, never on disk.+- New messages arrive on a webhook bound to `127.0.0.1` and signed by the+ gateway. When the webhook isn't working, Coucou checks for new messages+ every 20 s instead.+- Messages stay in memory only: they are never logged or saved, and they are+ forgotten when Coucou quits or WhatsApp is turned off.+- Nothing runs while the integration or its pill is off.++**Different from the Mac**++- There is no macOS Focus to follow, so "Stay quiet during a Focus" is not+ offered.+- The card's ↗ opens WhatsApp Web, as there is no WhatsApp app here to bring+ forward.+- You type the path to your own GOWA binary instead of picking it.+## New versionsCoucou can tell you when a new version is out, and on Windows install it in onediff --git a/windows/src-tauri/Cargo.toml b/windows/src-tauri/Cargo.tomlindex 6619c6fc..a60d49af 100644--- a/windows/src-tauri/Cargo.toml+++ b/windows/src-tauri/Cargo.toml@@ -49,6 +49,10 @@ sherpa-onnx = { version = "1.13.8", default-features = false, features = ["stati# The microphone, and the computer's own sound for the Notetaker (WASAPI# loopback on Windows, a PulseAudio/PipeWire monitor on Linux). Apache-2.0.cpal = "0.18"+# WhatsApp's "Install WhatsApp" takes GOWA's binary out of the zip GOWA publishes (whatsapp/archive.rs):+# the raw DEFLATE decoder only, already in the tree through png (the same 0.8.9), so nothing new is+# downloaded or compiled. MIT/Zlib/Apache-2.0.+miniz_oxide = "0.8"[target.'cfg(windows)'.dependencies]keyring = { version = "3", features = ["windows-native"] }diff --git a/windows/src-tauri/src/lib.rs b/windows/src-tauri/src/lib.rsindex c8f57a90..5e544f80 100644--- a/windows/src-tauri/src/lib.rs+++ b/windows/src-tauri/src/lib.rs@@ -38,6 +38,7 @@ mod update;mod voice;#[cfg(windows)]mod webview_drop;+mod whatsapp;use std::process::Command;use std::sync::atomic::{AtomicBool, Ordering};@@ -130,6 +131,7 @@ fn save_settings(app: AppHandle, shared: State<Shared>, settings: Settings) {}integrations::settings_saved(&app, &settings.active_integrations);spotify::sync(&app, &settings.active_integrations);+ whatsapp::sync(&settings.active_integrations);if shortcuts_changed {shortcuts::apply(&app, &settings.shortcuts);}@@ -910,6 +912,17 @@ pub fn run() {spotify::spotify_control,spotify::spotify_open,spotify::spotify_installed,+ whatsapp::whatsapp_island,+ whatsapp::whatsapp_open,+ whatsapp::whatsapp_close,+ whatsapp::whatsapp_send,+ whatsapp::whatsapp_ignore,+ whatsapp::whatsapp_unignore,+ whatsapp::whatsapp_settings,+ whatsapp::whatsapp_set_options,+ whatsapp::whatsapp_save_gateway,+ whatsapp::whatsapp_test,+ whatsapp::whatsapp_install,flow::flow_status,flow::flow_set_prefs,flow::flow_history,@@ -995,6 +1008,8 @@ pub fn run() {phone_link::start_if_enabled(&handle);integrations::start(handle.clone());spotify::sync(&handle, &loaded.active_integrations);+ // WhatsApp (experimental): nothing runs unless it is turned on and its pill is active.+ whatsapp::start(&handle, &loaded.active_integrations);shortcuts::apply(&handle, &loaded.shortcuts);// New versions: nothing goes to GitHub until the user agrees (update.rs).update::start(handle.clone());@@ -1016,6 +1031,8 @@ pub fn run() {if let tauri::RunEvent::Exit = event {phone_link::stop_on_exit(app);notes::shutdown(app);+ // GOWA started by Coucou stops with it; the conversations were only in memory.+ whatsapp::shutdown();}});}diff --git a/windows/src-tauri/src/phone_link/tests.rs b/windows/src-tauri/src/phone_link/tests.rsindex 266164cf..5ca80388 100644--- a/windows/src-tauri/src/phone_link/tests.rs+++ b/windows/src-tauri/src/phone_link/tests.rs@@ -1841,8 +1841,10 @@ fn every_secret_the_phone_link_stores_is_in_the_keystores_key_list() {] {assert!(crate::secrets::INTERNAL_KEYS.contains(&key), "{key} is not in secrets::INTERNAL_KEYS");}- // And nothing in the list is a stray: each one is used by the phone link.- assert_eq!(crate::secrets::INTERNAL_KEYS.len(), 6);+ // And nothing in the list is a stray: each one is used by the phone link, or by WhatsApp+ // (checked in whatsapp/mod.rs).+ let whatsapp = crate::secrets::INTERNAL_KEYS.iter().filter(|k| k.starts_with("whatsapp-")).count();+ assert_eq!(crate::secrets::INTERNAL_KEYS.len() - whatsapp, 6);}#[test]diff --git a/windows/src-tauri/src/secrets.rs b/windows/src-tauri/src/secrets.rsindex 9f23b35d..cfac93ee 100644--- a/windows/src-tauri/src/secrets.rs+++ b/windows/src-tauri/src/secrets.rs@@ -62,7 +62,8 @@ pub fn present(key: &str) -> bool {// ── Entries only Rust reads and writes ───────────────────────────────────────//-// The phone link's certificate, key and pairing token, and the relay's room, end-to-end key and access key.+// The phone link's certificate, key and pairing token, the relay's room, end-to-end key and access key,+// and WhatsApp's gateway address, credential and webhook secret.// They are not in KNOWN_KEYS// on purpose: the island has `secret_present` / `secret_set` / `secret_clear`// for those, and none of the three may be reachable from a webview.@@ -75,6 +76,11 @@ pub const INTERNAL_KEYS: &[&str] = &["phone-relay-room","phone-relay-key","phone-relay-access",+ // WhatsApp's gateway address, its credential (GOWA's user:password or OpenWA's API key) and+ // the webhook's signing secret: set from Settings through whatsapp_save_gateway, read by Rust only.+ "whatsapp-url",+ "whatsapp-api-key",+ "whatsapp-webhook-secret",];/// Whether the keystore would accept this key through `get_internal` / `set_internal`.diff --git a/windows/src-tauri/src/whatsapp/archive.rs b/windows/src-tauri/src/whatsapp/archive.rsnew file mode 100644index 00000000..8df52692--- /dev/null+++ b/windows/src-tauri/src/whatsapp/archive.rs@@ -0,0 +1,158 @@+// Just enough of the zip format to take GOWA's binary out of the zip it publishes: the central+// directory, stored and deflated entries, nothing else (no zip64, no encryption, no streaming).+// The zip's SHA-256 has already been checked against GOWA's own when this runs; the reader is+// still strict, because it is the only parser here that faces a downloaded file.++/// No binary Coucou unpacks is bigger than this (GOWA's are about 40 MB).+pub const MAX_ENTRY: usize = 200 * 1024 * 1024;++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Entry {+ pub name: String,+ method: u16,+ compressed: usize,+ size: usize,+ local_offset: usize,+}++fn u16_at(data: &[u8], at: usize) -> Option<u16> {+ Some(u16::from_le_bytes(data.get(at..at + 2)?.try_into().ok()?))+}++fn u32_at(data: &[u8], at: usize) -> Option<u32> {+ Some(u32::from_le_bytes(data.get(at..at + 4)?.try_into().ok()?))+}++/// The entries of the central directory, in order.+pub fn entries(zip: &[u8]) -> Option<Vec<Entry>> {+ // The end record is the last 22 bytes, plus a comment of up to 64 KB.+ let lowest = zip.len().saturating_sub(22 + 65_535);+ let end = (lowest..=zip.len().checked_sub(22)?).rev().find(|&i| u32_at(zip, i) == Some(0x0605_4b50))?;+ let count = u16_at(zip, end + 10)? as usize;+ let mut at = u32_at(zip, end + 16)? as usize;+ let mut out = Vec::with_capacity(count);+ for _ in 0..count {+ if u32_at(zip, at)? != 0x0201_4b50 {+ return None;+ }+ let flags = u16_at(zip, at + 8)?;+ let method = u16_at(zip, at + 10)?;+ let compressed = u32_at(zip, at + 20)?;+ let size = u32_at(zip, at + 24)?;+ let name_len = u16_at(zip, at + 28)? as usize;+ let extra_len = u16_at(zip, at + 30)? as usize;+ let comment_len = u16_at(zip, at + 32)? as usize;+ let local_offset = u32_at(zip, at + 42)?;+ // Encrypted, or zip64 (sizes in an extra field): not GOWA's zips.+ if flags & 1 != 0 || compressed == u32::MAX || size == u32::MAX || local_offset == u32::MAX {+ return None;+ }+ let name = String::from_utf8(zip.get(at + 46..at + 46 + name_len)?.to_vec()).ok()?;+ out.push(Entry { name, method, compressed: compressed as usize, size: size as usize, local_offset: local_offset as usize });+ at += 46 + name_len + extra_len + comment_len;+ }+ Some(out)+}++/// The bytes of one entry, inflated; None when it is damaged, too big, or not stored/deflated.+pub fn read(zip: &[u8], entry: &Entry) -> Option<Vec<u8>> {+ if entry.size > MAX_ENTRY || entry.compressed > zip.len() {+ return None;+ }+ let at = entry.local_offset;+ if u32_at(zip, at)? != 0x0403_4b50 {+ return None;+ }+ let start = at + 30 + u16_at(zip, at + 26)? as usize + u16_at(zip, at + 28)? as usize;+ let raw = zip.get(start..start.checked_add(entry.compressed)?)?;+ let data = match entry.method {+ 0 => raw.to_vec(),+ 8 => miniz_oxide::inflate::decompress_to_vec_with_limit(raw, entry.size).ok()?,+ _ => return None,+ };+ (data.len() == entry.size).then_some(data)+}++#[cfg(test)]+mod tests {+ use super::*;++ /// A zip as `zip` makes it: one stored entry and one deflated entry.+ fn build(files: &[(&str, &[u8], bool)]) -> Vec<u8> {+ let mut zip = Vec::new();+ let mut central = Vec::new();+ for (name, data, deflate) in files {+ let body = if *deflate { miniz_oxide::deflate::compress_to_vec(data, 6) } else { data.to_vec() };+ let method: u16 = if *deflate { 8 } else { 0 };+ let offset = zip.len() as u32;+ zip.extend_from_slice(&0x0403_4b50u32.to_le_bytes());+ zip.extend_from_slice(&[20, 0, 0, 0]);+ zip.extend_from_slice(&method.to_le_bytes());+ zip.extend_from_slice(&[0; 8]); // time, date, crc+ zip.extend_from_slice(&(body.len() as u32).to_le_bytes());+ zip.extend_from_slice(&(data.len() as u32).to_le_bytes());+ zip.extend_from_slice(&(name.len() as u16).to_le_bytes());+ zip.extend_from_slice(&0u16.to_le_bytes());+ zip.extend_from_slice(name.as_bytes());+ zip.extend_from_slice(&body);++ central.extend_from_slice(&0x0201_4b50u32.to_le_bytes());+ central.extend_from_slice(&[20, 3, 20, 0, 0, 0]);+ central.extend_from_slice(&method.to_le_bytes());+ central.extend_from_slice(&[0; 8]);+ central.extend_from_slice(&(body.len() as u32).to_le_bytes());+ central.extend_from_slice(&(data.len() as u32).to_le_bytes());+ central.extend_from_slice(&(name.len() as u16).to_le_bytes());+ central.extend_from_slice(&[0; 12]); // extra, comment, disk, attributes (internal + external)+ central.extend_from_slice(&offset.to_le_bytes());+ central.extend_from_slice(name.as_bytes());+ }+ let cd_offset = zip.len() as u32;+ zip.extend_from_slice(¢ral);+ zip.extend_from_slice(&0x0605_4b50u32.to_le_bytes());+ zip.extend_from_slice(&[0; 4]);+ zip.extend_from_slice(&(files.len() as u16).to_le_bytes());+ zip.extend_from_slice(&(files.len() as u16).to_le_bytes());+ zip.extend_from_slice(&(central.len() as u32).to_le_bytes());+ zip.extend_from_slice(&cd_offset.to_le_bytes());+ zip.extend_from_slice(&0u16.to_le_bytes());+ zip+ }++ #[test]+ fn reads_stored_and_deflated_entries() {+ let binary: Vec<u8> = (0..50_000u32).map(|i| (i % 251) as u8).collect();+ let zip = build(&[("README.md", b"hello", false), ("linux-amd64", &binary, true)]);+ let list = entries(&zip).unwrap();+ assert_eq!(list.iter().map(|e| e.name.as_str()).collect::<Vec<_>>(), ["README.md", "linux-amd64"]);+ assert_eq!(read(&zip, &list[0]).unwrap(), b"hello");+ assert_eq!(read(&zip, &list[1]).unwrap(), binary);+ }++ #[test]+ fn refuses_what_is_not_a_clean_zip() {+ assert_eq!(entries(b""), None);+ assert_eq!(entries(b"not a zip at all, just text"), None);+ let zip = build(&[("a", b"abcdef", true)]);+ let list = entries(&zip).unwrap();+ // Cut short.+ assert_eq!(entries(&zip[..zip.len() - 5]), None);+ // A size that lies.+ let mut lying = list[0].clone();+ lying.size = 3;+ assert_eq!(read(&zip, &lying), None);+ lying.size = MAX_ENTRY + 1;+ assert_eq!(read(&zip, &lying), None);+ // A damaged body.+ let mut broken = zip.clone();+ let start = 30 + 1;+ for b in &mut broken[start..start + 4] {+ *b ^= 0xFF;+ }+ assert_ne!(read(&broken, &list[0]).as_deref(), Some(&b"abcdef"[..]));+ // An unknown method.+ let mut other = list[0].clone();+ other.method = 12;+ assert_eq!(read(&zip, &other), None);+ }+}diff --git a/windows/src-tauri/src/whatsapp/gateway.rs b/windows/src-tauri/src/whatsapp/gateway.rsnew file mode 100644index 00000000..ff82592a--- /dev/null+++ b/windows/src-tauri/src/whatsapp/gateway.rs@@ -0,0 +1,771 @@+// What the two local WhatsApp gateways send and answer, turned into `Message`. Port of+// WhatsAppGateway.swift: every field name comes from each gateway's docs and source code:+// GOWA — github.com/aldinokemal/go-whatsapp-web-multidevice (docs/webhook-payload.md, docs/openapi.yaml)+// OpenWA — github.com/rmyndharis/OpenWA (docs/06-api-specification.md)+// Nothing parsed here is logged or written anywhere.++use std::collections::HashMap;++use serde_json::Value;++use super::model::{self, constant_time_eq, Media, Message};++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Kind {+ Gowa,+ Openwa,+}++impl Kind {+ pub fn from_name(name: &str) -> Kind {+ if name == "openwa" { Kind::Openwa } else { Kind::Gowa }+ }++ pub fn default_url(self) -> &'static str {+ match self {+ Kind::Gowa => "http://127.0.0.1:3000",+ Kind::Openwa => "http://127.0.0.1:2785",+ }+ }++ /// The header carrying the webhook's HMAC-SHA256 ("sha256=<hex>"), lowercased.+ pub fn signature_header(self) -> &'static str {+ match self {+ Kind::Gowa => "x-hub-signature-256",+ Kind::Openwa => "x-openwa-signature",+ }+ }+}++/// What one webhook delivery holds for Coucou.+#[derive(Debug, PartialEq)]+pub enum WebhookEvent {+ Message(Message),+ /// A valid delivery Coucou has no use for (receipts, reactions, a test ping…).+ Ignored,+}++pub fn hex(bytes: &[u8]) -> String {+ bytes.iter().map(|b| format!("{b:02x}")).collect()+}++/// "sha256=<lowercase hex>" of HMAC-SHA256(secret, body): what both gateways send.+pub fn signature(body: &[u8], secret: &str) -> String {+ let key = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, secret.as_bytes());+ format!("sha256={}", hex(ring::hmac::sign(&key, body).as_ref()))+}++/// True when the delivery carries the signature `secret` gives, over the raw body bytes.+pub fn verify(kind: Kind, headers: &HashMap<String, String>, body: &[u8], secret: &str) -> bool {+ if secret.is_empty() {+ return false;+ }+ let Some(sent) = headers.get(kind.signature_header()) else { return false };+ sent.starts_with("sha256=") && constant_time_eq(sent, &signature(body, secret))+}++fn text(v: Option<&Value>) -> Option<String> {+ v.and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_string)+}++/// Parses one delivery. None when it isn't JSON at all. `me` is this account's JID or number.+pub fn parse_webhook(kind: Kind, body: &[u8], me: Option<&str>) -> Option<WebhookEvent> {+ let json: Value = serde_json::from_slice(body).ok()?;+ if !json.is_object() {+ return None;+ }+ Some(match kind {+ Kind::Gowa => parse_gowa(&json, me),+ Kind::Openwa => parse_openwa(&json, me),+ })+}++/// `{"event":"message","device_id":"<own JID>","payload":{id, chat_id, from, from_name,+/// sender_display_name, timestamp (RFC3339), is_from_me, body, image|video|audio|document|…}}`+fn parse_gowa(json: &Value, me: Option<&str>) -> WebhookEvent {+ if json.get("event").and_then(Value::as_str) != Some("message") {+ return WebhookEvent::Ignored;+ }+ let Some(p) = json.get("payload").filter(|p| p.is_object()) else { return WebhookEvent::Ignored };+ let (Some(id), Some(chat)) = (text(p.get("id")), text(p.get("chat_id"))) else { return WebhookEvent::Ignored };+ let from = text(p.get("from")).unwrap_or_else(|| chat.clone());+ let body = p.get("body").and_then(Value::as_str).unwrap_or("").to_string();+ let mine = me.map(str::to_string).or_else(|| text(json.get("device_id")));+ let mut m = Message::new(&id, &chat, &from, &body, rfc3339_ms(p.get("timestamp").and_then(Value::as_str)).unwrap_or_else(now_ms));+ m.sender_name = text(p.get("sender_display_name")).or_else(|| text(p.get("from_name"))).unwrap_or_default();+ m.media = gowa_media(p);+ m.from_me = p.get("is_from_me").and_then(Value::as_bool).unwrap_or(false);+ m.mentions_me = model::is_group(&chat) && model::text_mentions(&body, mine.as_deref());+ WebhookEvent::Message(m)+}++/// GOWA puts each media under its own key; only the label matters to Coucou.+pub fn gowa_media(p: &Value) -> Media {+ let has = |k: &str| p.get(k).is_some_and(|v| !v.is_null());+ if has("image") {+ Media::Image+ } else if has("video") || has("video_note") {+ Media::Video+ } else if has("audio") {+ Media::Voice { seconds: None }+ } else if has("document") {+ Media::Document { name: text(p.get("document").and_then(|d| d.get("filename"))) }+ } else if has("sticker") {+ Media::Sticker+ } else if has("location") || has("live_location") {+ Media::Location+ } else if has("contact") || has("contacts_array") {+ Media::Contact+ } else if has("poll") {+ Media::Other+ } else {+ Media::None+ }+}++/// `{"event":"message.received"|"message.sent","sessionId","data":{id, from, to, chatId, author,+/// body, type, timestamp (epoch s), fromMe, isGroup, mentionedIds, contact{name, pushName}, media{filename}}}`+fn parse_openwa(json: &Value, me: Option<&str>) -> WebhookEvent {+ let event = json.get("event").and_then(Value::as_str);+ if event != Some("message.received") && event != Some("message.sent") {+ return WebhookEvent::Ignored;+ }+ let Some(d) = json.get("data").filter(|d| d.is_object()) else { return WebhookEvent::Ignored };+ let Some(id) = text(d.get("id")) else { return WebhookEvent::Ignored };+ let Some(chat) = text(d.get("chatId")).or_else(|| text(d.get("from"))) else { return WebhookEvent::Ignored };+ let kind = d.get("type").and_then(Value::as_str).unwrap_or("text");+ if kind == "revoked" {+ return WebhookEvent::Ignored;+ }+ let from_me = d.get("fromMe").and_then(Value::as_bool).unwrap_or(event == Some("message.sent"));+ let contact = d.get("contact");+ let sender = text(d.get("author")).or_else(|| text(d.get("from"))).unwrap_or_else(|| chat.clone());+ let body = d.get("body").and_then(Value::as_str).unwrap_or("");+ let mut m = Message::new(&id, &chat, &sender, body, epoch_ms(d.get("timestamp")).unwrap_or_else(now_ms));+ m.sender_name = text(contact.and_then(|c| c.get("name")))+ .or_else(|| text(contact.and_then(|c| c.get("pushName"))))+ .unwrap_or_default();+ m.media = openwa_media(kind, text(d.get("media").and_then(|x| x.get("filename"))));+ m.from_me = from_me;+ let group = d.get("isGroup").and_then(Value::as_bool).unwrap_or_else(|| model::is_group(&chat));+ if let (true, Some(mine)) = (group, me) {+ let ids = d.get("mentionedIds").and_then(Value::as_array);+ let named = ids.is_some_and(|ids| ids.iter().filter_map(Value::as_str).any(|x| model::same_user(x, mine)));+ m.mentions_me = named || model::text_mentions(body, Some(mine));+ }+ WebhookEvent::Message(m)+}++/// OpenWA's `type` (text|image|video|audio|voice|document|sticker|location|contact|poll|…).+pub fn openwa_media(kind: &str, filename: Option<String>) -> Media {+ match kind {+ "text" | "" => Media::None,+ "image" => Media::Image,+ "video" => Media::Video,+ "audio" => Media::Audio { seconds: None },+ "voice" => Media::Voice { seconds: None },+ "document" => Media::Document { name: filename },+ "sticker" => Media::Sticker,+ "location" => Media::Location,+ "contact" => Media::Contact,+ _ => Media::Other,+ }+}++// ── REST answers ──────────────────────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Link {+ /// Logged in and online.+ Connected,+ /// Waiting for the QR to be scanned.+ NeedsQr,+ /// Logged in but offline, starting, or anything in between.+ Connecting,+}++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Status {+ pub link: Link,+ /// This account's JID or number, once logged in.+ pub me: Option<String>,+}++pub mod gowa {+ use super::*;++ /// GOWA's envelope: `{code, message, results}`.+ pub fn results(data: &[u8]) -> Option<Value> {+ serde_json::from_slice::<Value>(data).ok()?.get("results").cloned()+ }++ /// `GET /devices` → `results: [{id, phone_number, display_name, state, jid, created_at}]`.+ /// The device Coucou uses: a logged-in one first, else the first one.+ pub fn device(data: &[u8]) -> Option<(String, Status)> {+ let list = results(data)?;+ let list = list.as_array()?;+ let pick = list.iter().find(|d| d.get("state").and_then(Value::as_str) == Some("logged_in")).or(list.first())?;+ let id = text(pick.get("id"))?;+ let jid = text(pick.get("jid"));+ let link = match pick.get("state").and_then(Value::as_str) {+ Some("logged_in") => Link::Connected,+ _ if jid.is_none() => Link::NeedsQr,+ _ => Link::Connecting,+ };+ Some((id, Status { link, me: jid }))+ }++ /// `GET /devices/{id}/login` → `results: {device_id, qr_link, qr_duration}`. The PNG's path,+ /// to fetch from the gateway itself (never from another host the link may name).+ pub fn qr_path(data: &[u8]) -> Option<(String, u64)> {+ let r = results(data)?;+ let link = r.get("qr_link")?.as_str()?;+ let url = reqwest::Url::parse(link).ok()?;+ let path = url.path().to_string();+ if path.is_empty() || path == "/" {+ return None;+ }+ Some((path, r.get("qr_duration").and_then(Value::as_u64).unwrap_or(30)))+ }++ /// `whatsapp rest` for "Start GOWA automatically": on this computer only, on the URL's port,+ /// and media never downloaded (Coucou shows a label), so GOWA keeps no photo or voice note.+ pub fn launch_arguments(port: u16) -> Vec<String> {+ vec![+ "rest".into(),+ "--host=127.0.0.1".into(),+ format!("--port={port}"),+ "--auto-download-media=false".into(),+ ]+ }++ /// The error code of a refused call (`ALREADY_LOGGED_IN`, `DEVICE_ID_REQUIRED`…).+ pub fn error_code(data: &[u8]) -> Option<String> {+ text(serde_json::from_slice::<Value>(data).ok()?.get("code"))+ }++ /// `GET /chats` → `results: {data: [{jid, name, last_message_time, …}], pagination}`.+ pub fn chats(data: &[u8]) -> Vec<(String, String, i64)> {+ let Some(r) = results(data) else { return vec![] };+ let Some(list) = r.get("data").and_then(Value::as_array) else { return vec![] };+ list.iter()+ .filter_map(|c| {+ let jid = text(c.get("jid"))?;+ let name = c.get("name").and_then(Value::as_str).unwrap_or("").to_string();+ Some((jid, name, rfc3339_ms(c.get("last_message_time").and_then(Value::as_str)).unwrap_or(0)))+ })+ .collect()+ }++ /// `GET /chat/{jid}/messages` → `results: {data: [{id, chat_jid, sender_jid, sender_display_name,+ /// content, timestamp, is_from_me, media_type, filename}], chat_info}`. Newest first there.+ pub fn messages(data: &[u8], me: Option<&str>) -> Vec<Message> {+ let Some(r) = results(data) else { return vec![] };+ let chat_name = text(r.get("chat_info").and_then(|c| c.get("name")));+ let Some(list) = r.get("data").and_then(Value::as_array) else { return vec![] };+ list.iter()+ .filter_map(|m| {+ let id = m.get("id")?.as_str()?;+ let chat = m.get("chat_jid")?.as_str()?;+ let content = m.get("content").and_then(Value::as_str).unwrap_or("");+ let sender = m.get("sender_jid").and_then(Value::as_str).unwrap_or(chat);+ let mut msg = Message::new(id, chat, sender, content, rfc3339_ms(m.get("timestamp").and_then(Value::as_str)).unwrap_or(0));+ msg.sender_name = text(m.get("sender_display_name")).unwrap_or_default();+ msg.media = stored_media(m.get("media_type").and_then(Value::as_str), text(m.get("filename")));+ msg.from_me = m.get("is_from_me").and_then(Value::as_bool).unwrap_or(false);+ let group = model::is_group(chat);+ msg.chat_name = if group { chat_name.clone() } else { None };+ msg.mentions_me = group && model::text_mentions(content, me);+ Some(msg)+ })+ .collect()+ }++ /// `media_type` of a stored message: image|video|video_note|audio|document|sticker|call or "".+ pub fn stored_media(kind: Option<&str>, filename: Option<String>) -> Media {+ match kind.unwrap_or("") {+ "" => Media::None,+ "image" => Media::Image,+ "video" | "video_note" => Media::Video,+ "audio" => Media::Voice { seconds: None },+ "document" => Media::Document { name: filename },+ "sticker" => Media::Sticker,+ _ => Media::Other,+ }+ }++ /// `GET /group/info?group_id=…` → `results: {Name, …}`.+ pub fn group_name(data: &[u8]) -> Option<String> {+ text(results(data)?.get("Name"))+ }++ /// `POST /send/message` → `results: {message_id, status}`.+ pub fn sent_id(data: &[u8]) -> Option<String> {+ text(results(data)?.get("message_id"))+ }+}++pub mod openwa {+ use super::*;++ /// A session: `{id (uuid), name, status, phone, pushName, …}`.+ #[derive(Clone, Debug, PartialEq, Eq)]+ pub struct Session {+ pub id: String,+ pub name: String,+ pub status: String,+ pub phone: Option<String>,+ }++ pub fn session(v: &Value) -> Option<Session> {+ Some(Session {+ id: text(v.get("id"))?,+ name: v.get("name").and_then(Value::as_str).unwrap_or("").to_string(),+ status: v.get("status").and_then(Value::as_str).unwrap_or("").to_string(),+ phone: text(v.get("phone")),+ })+ }++ /// `GET /api/sessions` → a bare array of sessions.+ pub fn sessions(data: &[u8]) -> Vec<Session> {+ match serde_json::from_slice::<Value>(data) {+ Ok(Value::Array(list)) => list.iter().filter_map(session).collect(),+ Ok(v) => session(&v).into_iter().collect(),+ Err(_) => vec![],+ }+ }++ pub fn status(s: &Session) -> Status {+ match s.status.as_str() {+ "ready" => Status { link: Link::Connected, me: s.phone.clone() },+ "qr_ready" => Status { link: Link::NeedsQr, me: None },+ _ => Status { link: Link::Connecting, me: s.phone.clone() },+ }+ }++ /// Sessions that must be started before a QR can come: never started, stopped or failed.+ pub fn needs_start(status: &str) -> bool {+ matches!(status, "created" | "disconnected" | "failed")+ }++ /// `GET /api/sessions/{id}/qr` → `{qrCode: "data:image/png;base64,…"}`: the data URL itself,+ /// checked to be a PNG in base64 and nothing else.+ pub fn qr_data_url(data: &[u8]) -> Option<String> {+ let v: Value = serde_json::from_slice(data).ok()?;+ let url = v.get("qrCode")?.as_str()?;+ let b64 = url.strip_prefix("data:image/png;base64,")?;+ (!b64.is_empty() && b64.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'+' || b == b'/' || b == b'='))+ .then(|| url.to_string())+ }++ /// `GET /api/sessions/{id}/messages` → `{messages: [{waMessageId, chatId, from, author, chatName,+ /// body, type, direction, timestamp (s), metadata}], total}`.+ pub fn messages(data: &[u8], me: Option<&str>) -> Vec<Message> {+ let Ok(v) = serde_json::from_slice::<Value>(data) else { return vec![] };+ let Some(list) = v.get("messages").and_then(Value::as_array) else { return vec![] };+ list.iter()+ .filter_map(|m| {+ let id = text(m.get("waMessageId")).or_else(|| text(m.get("id")))?;+ let chat = text(m.get("chatId"))?;+ let kind = m.get("type").and_then(Value::as_str).unwrap_or("text");+ if kind == "revoked" {+ return None;+ }+ let sender = text(m.get("author")).or_else(|| text(m.get("from"))).unwrap_or_else(|| chat.clone());+ let body = m.get("body").and_then(Value::as_str).unwrap_or("");+ let mut msg = Message::new(&id, &chat, &sender, body, epoch_ms(m.get("timestamp")).unwrap_or(0));+ let filename = text(m.get("metadata").and_then(|x| x.get("media")).and_then(|x| x.get("filename")));+ msg.media = openwa_media(kind, filename);+ msg.from_me = m.get("direction").and_then(Value::as_str) == Some("outgoing");+ msg.chat_name = text(m.get("chatName"));+ if model::is_group(&chat) {+ msg.mentions_me = model::text_mentions(body, me);+ }+ Some(msg)+ })+ .collect()+ }++ /// NestJS error: `{statusCode, message (string or [string]), error}`.+ pub fn error_message(data: &[u8]) -> Option<String> {+ let v: Value = serde_json::from_slice(data).ok()?;+ match v.get("message")? {+ Value::String(s) => Some(s.clone()),+ Value::Array(list) => Some(list.iter().filter_map(Value::as_str).collect::<Vec<_>>().join(", ")),+ _ => None,+ }+ }++ /// OpenWA names people `<number>@c.us` (Coucou keeps the @s.whatsapp.net form inside).+ pub fn chat_id(jid: &str) -> String {+ match jid.strip_suffix("@s.whatsapp.net") {+ Some(user) => format!("{user}@c.us"),+ None => jid.to_string(),+ }+ }+}++// ── GOWA's own releases (Install WhatsApp) ─────────────────────────────────────++pub mod release {+ use super::*;++ pub const LATEST_URL: &str = "https://api.github.com/repos/aldinokemal/go-whatsapp-web-multidevice/releases/latest";++ #[derive(Clone, Debug, PartialEq, Eq)]+ pub struct Asset {+ pub name: String,+ pub url: String,+ pub size: u64,+ /// "sha256:<hex>" when GitHub gives it.+ pub digest: Option<String>,+ }++ /// `GET /releases/latest` → `{tag_name, assets: [{name, browser_download_url, size, digest?}]}`.+ pub fn parse(data: &[u8]) -> Option<(String, Vec<Asset>)> {+ let v: Value = serde_json::from_slice(data).ok()?;+ let tag = v.get("tag_name")?.as_str()?;+ let assets = v+ .get("assets")?+ .as_array()?+ .iter()+ .filter_map(|a| {+ Some(Asset {+ name: a.get("name")?.as_str()?.to_string(),+ url: a.get("browser_download_url")?.as_str()?.to_string(),+ size: a.get("size").and_then(Value::as_u64).unwrap_or(0),+ digest: a.get("digest").and_then(Value::as_str).map(str::to_string),+ })+ })+ .collect();+ Some((tag.strip_prefix('v').unwrap_or(tag).to_string(), assets))+ }++ /// GOWA's system names: "windows" or "linux"; "amd64" or "arm64".+ pub fn this_os() -> &'static str {+ if cfg!(windows) { "windows" } else { "linux" }+ }++ pub fn this_arch() -> &'static str {+ if cfg!(target_arch = "aarch64") { "arm64" } else { "amd64" }+ }++ /// The zip for this system (`whatsapp_<version>_<os>_<arch>.zip`, as GOWA's release workflow names+ /// them) and its checksums file (`checksums-<os>.txt`, else a plain `checksums.txt`).+ pub fn pick<'a>(assets: &'a [Asset], os: &str, arch: &str) -> Option<(&'a Asset, Option<&'a Asset>)> {+ let suffix = format!("_{os}_{arch}.zip");+ let zip = assets.iter().find(|a| a.name.starts_with("whatsapp_") && a.name.ends_with(&suffix))?;+ let os_sums = match os {+ "windows" => "checksums-windows.txt",+ "linux" => "checksums-linux.txt",+ _ => "checksums-macos.txt",+ };+ let sums = assets+ .iter()+ .find(|a| a.name == os_sums)+ .or_else(|| assets.iter().find(|a| a.name == "checksums.txt"));+ Some((zip, sums))+ }++ /// The binary inside the zip: `<os>-<arch>` (`.exe` on Windows) as GOWA builds it, else a+ /// `whatsapp` / `whatsapp.exe` at any depth. Never a folder, never anything else.+ pub fn binary_entry<'a>(names: &'a [String], os: &str, arch: &str) -> Option<&'a String> {+ let base = |n: &str| n.rsplit('/').next().unwrap_or(n).to_string();+ let exe = if os == "windows" { ".exe" } else { "" };+ let wanted = [format!("{os}-{arch}{exe}"), format!("{os}-{arch}"), format!("whatsapp{exe}")];+ wanted.iter().find_map(|w| names.iter().find(|n| !n.ends_with('/') && base(n) == *w))+ }++ /// The SHA-256 (lowercase hex) of `asset` in a GoReleaser checksums file ("<hex> <name>" per+ /// line), else GitHub's own "sha256:<hex>" digest.+ pub fn expected_sha256(asset: &Asset, checksums: Option<&str>) -> Option<String> {+ for line in checksums.unwrap_or("").lines() {+ let parts: Vec<&str> = line.split_whitespace().collect();+ if parts.len() == 2 && parts[1] == asset.name && parts[0].len() == 64 && parts[0].bytes().all(|b| b.is_ascii_hexdigit()) {+ return Some(parts[0].to_ascii_lowercase());+ }+ }+ asset.digest.as_deref().and_then(crate::update::parse_digest)+ }+}++// ── Dates ─────────────────────────────────────────────────────────────────────++pub fn now_ms() -> i64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_millis() as i64)+ .unwrap_or(0)+}++/// Days from 1970-01-01 to a civil date (Howard Hinnant's algorithm).+fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {+ let y = if m <= 2 { y - 1 } else { y };+ let era = if y >= 0 { y } else { y - 399 } / 400;+ let yoe = y - era * 400;+ let mp = (m + 9) % 12;+ let doy = (153 * mp + 2) / 5 + d - 1;+ let doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;+ era * 146_097 + doe - 719_468+}++/// "2023-10-15T10:30:00Z", "…T10:30:00.123+02:00" → milliseconds since 1970.+pub fn rfc3339_ms(s: Option<&str>) -> Option<i64> {+ let s = s?.trim();+ let b = s.as_bytes();+ if b.len() < 20 || b[4] != b'-' || b[7] != b'-' || !(b[10] == b'T' || b[10] == b't' || b[10] == b' ') || b[13] != b':' || b[16] != b':' {+ return None;+ }+ let num = |r: std::ops::Range<usize>| s.get(r)?.parse::<i64>().ok();+ let (y, mo, d, h, mi, se) = (num(0..4)?, num(5..7)?, num(8..10)?, num(11..13)?, num(14..16)?, num(17..19)?);+ if !(1..=12).contains(&mo) || !(1..=31).contains(&d) || h > 23 || mi > 59 || se > 60 {+ return None;+ }+ let mut rest = &s[19..];+ let mut millis = 0i64;+ if let Some(frac) = rest.strip_prefix('.') {+ let digits: String = frac.chars().take_while(char::is_ascii_digit).collect();+ if digits.is_empty() {+ return None;+ }+ let ms: String = digits.chars().chain("000".chars()).take(3).collect();+ millis = ms.parse().ok()?;+ rest = &frac[digits.len()..];+ }+ let offset_min = match rest {+ "Z" | "z" => 0,+ o if o.len() == 6 && (o.starts_with('+') || o.starts_with('-')) && &o[3..4] == ":" => {+ let sign = if o.starts_with('-') { -1 } else { 1 };+ sign * (o[1..3].parse::<i64>().ok()? * 60 + o[4..6].parse::<i64>().ok()?)+ }+ _ => return None,+ };+ let days = days_from_civil(y, mo, d);+ Some(((days * 86_400 + h * 3600 + mi * 60 + se - offset_min * 60) * 1000) + millis)+}++/// Epoch seconds, as a number or a numeric string → milliseconds.+pub fn epoch_ms(v: Option<&Value>) -> Option<i64> {+ let secs = match v? {+ Value::Number(n) => n.as_f64()?,+ Value::String(s) => s.trim().parse::<f64>().ok()?,+ _ => return None,+ };+ (secs > 0.0).then(|| (secs * 1000.0) as i64)+}++/// The ISO 8601 form GOWA's `start_time` takes (UTC, seconds).+pub fn iso_utc(ms: i64) -> String {+ let secs = ms.div_euclid(1000);+ let days = secs.div_euclid(86_400);+ let tod = secs.rem_euclid(86_400);+ // civil_from_days (Howard Hinnant).+ let z = days + 719_468;+ let era = if z >= 0 { z } else { z - 146_096 } / 146_097;+ let doe = z - era * 146_097;+ let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;+ let y = yoe + era * 400;+ let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);+ let mp = (5 * doy + 2) / 153;+ let d = doy - (153 * mp + 2) / 5 + 1;+ let m = if mp < 10 { mp + 3 } else { mp - 9 };+ let y = if m <= 2 { y + 1 } else { y };+ format!("{y:04}-{m:02}-{d:02}T{:02}:{:02}:{:02}Z", tod / 3600, tod % 3600 / 60, tod % 60)+}++/// Standard base64 with padding (RFC 4648).+pub fn base64(bytes: &[u8]) -> String {+ const ABC: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";+ let mut out = String::with_capacity(bytes.len().div_ceil(3) * 4);+ for chunk in bytes.chunks(3) {+ let n = (u32::from(chunk[0]) << 16) | (u32::from(*chunk.get(1).unwrap_or(&0)) << 8) | u32::from(*chunk.get(2).unwrap_or(&0));+ out.push(ABC[(n >> 18) as usize & 63] as char);+ out.push(ABC[(n >> 12) as usize & 63] as char);+ out.push(if chunk.len() > 1 { ABC[(n >> 6) as usize & 63] as char } else { '=' });+ out.push(if chunk.len() > 2 { ABC[n as usize & 63] as char } else { '=' });+ }+ out+}++/// PNG bytes → a `data:` URL the webview can show (no file, no other host).+pub fn png_data_url(png: &[u8]) -> String {+ format!("data:image/png;base64,{}", base64(png))+}++#[cfg(test)]+mod tests {+ use super::*;++ // GOWA docs/webhook-payload.md — text message+ const GOWA_TEXT: &str = r#"{"event":"message","device_id":"[email protected]","payload":{"id":"3EB0C127D7BACC83D6A1","chat_id":"[email protected]","from":"[email protected]","from_lid":"251556368777322@lid","sender_display_name":"Saved Contact","from_name":"John Doe","timestamp":"2023-10-15T10:30:00Z","is_from_me":false,"body":"Hello, how are you?"}}"#;+ const GOWA_IMAGE: &str = r#"{"event":"message","device_id":"[email protected]","payload":{"id":"3EB0C127D7BACC83D6A3","chat_id":"[email protected]","from":"[email protected]","from_name":"John Doe","timestamp":"2025-07-13T11:05:51Z","body":"Check this out!","image":{"path":"statics/media/1.jpeg","caption":"Check this out!"}}}"#;+ const GOWA_AUDIO: &str = r#"{"event":"message","device_id":"[email protected]","payload":{"id":"3EB0C127D7BACC83D6A5","chat_id":"[email protected]","from":"[email protected]","from_name":"John Doe","timestamp":"2023-10-15T10:55:00Z","audio":"statics/media/1.ogg"}}"#;+ const GOWA_ACK: &str = r#"{"event":"message.ack","device_id":"[email protected]","timestamp":"2025-07-18T22:44:20Z","payload":{"ids":["3EB00106E8BE0F407E88EC"],"chat_id":"[email protected]","receipt_type":"delivered"}}"#;+ const GOWA_GROUP_MENTION: &str = r#"{"event":"message","device_id":"[email protected]","payload":{"id":"G1","chat_id":"[email protected]","from":"[email protected]","from_name":"John Doe","timestamp":"2025-07-13T11:05:51Z","is_from_me":false,"body":"@628987654321 tu viens ?"}}"#;+ // OpenWA docs/12-troubleshooting-faq.md — 1:1 text message.received+ const OPENWA_TEXT: &str = r#"{"event":"message.received","timestamp":"2026-02-02T10:30:00Z","sessionId":"3f2a","data":{"id":"ABC123_DEF456","from":"[email protected]","to":"[email protected]","chatId":"[email protected]","body":"Hello!","type":"text","timestamp":1706868600,"fromMe":false,"isGroup":false}}"#;+ const OPENWA_MINIMAL: &str = r#"{"event":"message.received","sessionId":"default","data":{"id":"3EB0F5A2B4C...","chatId":"[email protected]","from":"[email protected]","body":"Hello!","type":"text","timestamp":1705312200}}"#;+ const OPENWA_GROUP_VOICE: &str = r#"{"event":"message.received","sessionId":"s1","data":{"id":"3EB0VOICE","from":"[email protected]","to":"[email protected]","chatId":"[email protected]","author":"[email protected]","body":"","type":"voice","timestamp":1706868600,"fromMe":false,"isGroup":true,"mentionedIds":["[email protected]"],"contact":{"pushName":"Budi"}}}"#;++ fn message(kind: Kind, body: &str, me: Option<&str>) -> Message {+ match parse_webhook(kind, body.as_bytes(), me) {+ Some(WebhookEvent::Message(m)) => m,+ other => panic!("{other:?}"),+ }+ }++ #[test]+ fn gowa_webhooks_from_its_docs() {+ let m = message(Kind::Gowa, GOWA_TEXT, None);+ assert_eq!((m.id.as_str(), m.chat.as_str()), ("3EB0C127D7BACC83D6A1", "[email protected]"));+ assert_eq!(m.sender_name, "Saved Contact");+ assert_eq!((m.text.as_str(), &m.media), ("Hello, how are you?", &Media::None));+ assert_eq!(m.date, 1_697_365_800_000);+ assert!(!m.from_me);+ let m = message(Kind::Gowa, GOWA_IMAGE, None);+ assert_eq!((&m.media, m.text.as_str(), m.from_me), (&Media::Image, "Check this out!", false));+ assert_eq!(message(Kind::Gowa, GOWA_AUDIO, None).media, Media::Voice { seconds: None });+ assert_eq!(parse_webhook(Kind::Gowa, GOWA_ACK.as_bytes(), None), Some(WebhookEvent::Ignored));+ assert_eq!(parse_webhook(Kind::Gowa, b"nope", None), None);+ let m = message(Kind::Gowa, GOWA_GROUP_MENTION, None);+ assert!(m.mentions_me);+ assert_eq!(m.sender, "[email protected]");+ let mut inbox = model::Inbox::default();+ assert_eq!(inbox.add(m, &model::Filters::default(), None, false), model::Outcome::Notify);+ }++ #[test]+ fn openwa_webhooks_from_its_docs() {+ let m = message(Kind::Openwa, OPENWA_TEXT, None);+ assert_eq!((m.id.as_str(), m.chat.as_str()), ("ABC123_DEF456", "[email protected]"));+ assert_eq!(m.date, 1_706_868_600_000);+ assert!(!m.from_me);+ let mut inbox = model::Inbox::default();+ inbox.add(m, &model::Filters::default(), None, false);+ assert!(inbox.conversations.contains_key("[email protected]"), "@c.us folded into GOWA's form");+ let m = message(Kind::Openwa, OPENWA_MINIMAL, None);+ assert_eq!(m.id, "3EB0F5A2B4C...");+ let m = message(Kind::Openwa, OPENWA_GROUP_VOICE, Some("6280000000000"));+ assert_eq!((m.sender.as_str(), m.sender_name.as_str()), ("[email protected]", "Budi"));+ assert_eq!(m.media, Media::Voice { seconds: None });+ assert!(m.mentions_me);+ let ping = r#"{"event":"test","data":{"message":"This is a test webhook from OpenWA"}}"#;+ assert_eq!(parse_webhook(Kind::Openwa, ping.as_bytes(), None), Some(WebhookEvent::Ignored));+ let sent = OPENWA_TEXT.replace("message.received", "message.sent").replace(r#""fromMe":false"#, r#""fromMe":true"#);+ assert!(message(Kind::Openwa, &sent, None).from_me);+ }++ #[test]+ fn signatures() {+ // OpenWA sdk/javascript/test/webhook.test.ts.+ let secret = "test-secret-0123456789";+ let body = r#"{"event":"message.received","timestamp":"2026-02-02T10:00:00.000Z","sessionId":"s1","idempotencyKey":"k","deliveryId":"dlv_1","data":{"text":"héllo 👋"}}"#.as_bytes();+ let header = "sha256=d74a41bb687f31ed4c932f76f524116100ca4120d2cabb7a469ee5d928122f70";+ assert_eq!(signature(body, secret), header);+ let h = |v: &str| HashMap::from([("x-openwa-signature".to_string(), v.to_string())]);+ assert!(verify(Kind::Openwa, &h(header), body, secret));+ let mut flipped = body.to_vec();+ flipped[3] ^= 1;+ assert!(!verify(Kind::Openwa, &h(header), &flipped, secret));+ assert!(!verify(Kind::Openwa, &h(header), body, &format!("{secret}x")));+ assert!(!verify(Kind::Openwa, &h(&header[7..]), body, secret));+ assert!(!verify(Kind::Openwa, &h(&format!("SHA256={}", &header[7..])), body, secret));+ assert!(!verify(Kind::Openwa, &h(&header[..header.len() - 1]), body, secret));+ assert!(!verify(Kind::Openwa, &HashMap::new(), body, secret));+ assert!(!verify(Kind::Openwa, &h(header), body, ""));+ assert!(!verify(Kind::Gowa, &h(header), body, secret), "GOWA's header is its own");+ // RFC 4231 test case 2.+ assert_eq!(signature(b"what do ya want for nothing?", "Jefe"),+ "sha256=5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843");+ }++ #[test]+ fn rest_answers() {+ let devices = r#"{"code":"SUCCESS","results":[{"id":"coucou","state":"disconnected"},{"id":"my-device-id","state":"logged_in","jid":"[email protected]"}]}"#;+ assert_eq!(gowa::device(devices.as_bytes()),+ Some(("my-device-id".into(), Status { link: Link::Connected, me: Some("[email protected]".into()) })));+ let fresh = r#"{"code":"SUCCESS","results":[{"id":"coucou","state":"disconnected"}]}"#;+ assert_eq!(gowa::device(fresh.as_bytes()).unwrap().1.link, Link::NeedsQr);+ assert_eq!(gowa::device(br#"{"code":"SUCCESS","results":[]}"#), None);+ let login = r#"{"code":"SUCCESS","results":{"device_id":"coucou","qr_duration":30,"qr_link":"http://localhost:3000/statics/qrcode/scan-qr-b0b7.png"}}"#;+ assert_eq!(gowa::qr_path(login.as_bytes()), Some(("/statics/qrcode/scan-qr-b0b7.png".into(), 30)));+ assert_eq!(gowa::launch_arguments(3001), ["rest", "--host=127.0.0.1", "--port=3001", "--auto-download-media=false"]);+ assert_eq!(gowa::error_code(br#"{"code":"ALREADY_LOGGED_IN","message":"x"}"#).as_deref(), Some("ALREADY_LOGGED_IN"));+ let msgs = r#"{"code":"SUCCESS","results":{"data":[{"id":"M2","chat_jid":"[email protected]","sender_jid":"[email protected]","sender_display_name":"John","content":"","timestamp":"2025-07-13T11:06:00Z","is_from_me":false,"media_type":"document","filename":"devis.pdf"},{"id":"M1","chat_jid":"[email protected]","sender_jid":"[email protected]","content":"salut","timestamp":"2025-07-13T11:05:00Z","is_from_me":true,"media_type":""}],"chat_info":{"name":"Famille"}}}"#;+ let list = gowa::messages(msgs.as_bytes(), None);+ assert_eq!(list.len(), 2);+ assert_eq!(list[0].media, Media::Document { name: Some("devis.pdf".into()) });+ assert!(list[1].from_me);+ assert_eq!(list[0].chat_name.as_deref(), Some("Famille"));+ let chats = r#"{"code":"SUCCESS","results":{"data":[{"jid":"[email protected]","name":"John","last_message_time":"2025-07-13T11:06:00Z"}]}}"#;+ assert_eq!(gowa::chats(chats.as_bytes())[0].1, "John");++ let session = r#"[{"id":"0b5d","name":"coucou","status":"ready","phone":"628123456789"}]"#;+ let s = &openwa::sessions(session.as_bytes())[0];+ assert_eq!(openwa::status(s), Status { link: Link::Connected, me: Some("628123456789".into()) });+ assert!(openwa::needs_start("created") && !openwa::needs_start("qr_ready"));+ assert_eq!(openwa::qr_data_url(br#"{"qrCode":"data:image/png;base64,iVBORw==","status":"qr_ready"}"#).as_deref(),+ Some("data:image/png;base64,iVBORw=="));+ assert_eq!(openwa::qr_data_url(br#"{"qrCode":"data:text/html;base64,PHA+"}"#), None);+ assert_eq!(openwa::qr_data_url(br#"{"qrCode":"data:image/png;base64,\"><script>"}"#), None);+ let stored = r#"{"messages":[{"waMessageId":"3EB0AB","chatId":"[email protected]","from":"[email protected]","chatName":"Alice","author":null,"body":"See you","type":"text","direction":"incoming","timestamp":1719306115}],"total":1}"#;+ let om = openwa::messages(stored.as_bytes(), None);+ assert_eq!((om[0].id.as_str(), om[0].chat_name.as_deref(), om[0].from_me), ("3EB0AB", Some("Alice"), false));+ assert_eq!(openwa::error_message(br#"{"statusCode":400,"message":["a","b"]}"#).as_deref(), Some("a, b"));+ assert_eq!(openwa::chat_id("[email protected]"), "[email protected]");+ }++ #[test]+ fn gowa_release_for_this_system() {+ let json = r#"{"tag_name":"v9.6.0","assets":[+ {"name":"checksums-macos.txt","size":228,"browser_download_url":"https://github.com/a/b/releases/download/v9.6.0/checksums-macos.txt"},+ {"name":"checksums-linux.txt","size":228,"browser_download_url":"https://github.com/a/b/releases/download/v9.6.0/checksums-linux.txt"},+ {"name":"whatsapp_9.6.0_darwin_arm64.zip","size":13100000,"browser_download_url":"https://github.com/x"},+ {"name":"whatsapp_9.6.0_linux_amd64.zip","size":13900000,"browser_download_url":"https://github.com/y"},+ {"name":"whatsapp_9.6.0_linux_arm64.zip","size":1,"browser_download_url":"https://github.com/z"},+ {"name":"whatsapp_9.6.0_windows_amd64.zip","size":14000000,"digest":"sha256:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA","browser_download_url":"https://github.com/w"}]}"#;+ let (version, assets) = release::parse(json.as_bytes()).unwrap();+ assert_eq!(version, "9.6.0");+ let (zip, sums) = release::pick(&assets, "linux", "amd64").unwrap();+ assert_eq!((zip.name.as_str(), sums.map(|s| s.name.as_str())), ("whatsapp_9.6.0_linux_amd64.zip", Some("checksums-linux.txt")));+ let (zip, sums) = release::pick(&assets, "windows", "amd64").unwrap();+ assert_eq!(zip.name, "whatsapp_9.6.0_windows_amd64.zip");+ assert!(sums.is_none(), "no checksums-windows.txt nor checksums.txt here");+ assert!(release::pick(&assets, "windows", "arm64").is_none());+ let text = format!("{} whatsapp_9.6.0_linux_amd64.zip\n{} whatsapp_9.6.0_linux_arm64.zip\n", "1".repeat(64), "2".repeat(64));+ let (zip, _) = release::pick(&assets, "linux", "arm64").unwrap();+ assert_eq!(release::expected_sha256(zip, Some(&text)), Some("2".repeat(64)));+ let (win, _) = release::pick(&assets, "windows", "amd64").unwrap();+ assert_eq!(release::expected_sha256(win, None), Some("a".repeat(64)), "GitHub's digest");+ let (lin, _) = release::pick(&assets, "linux", "amd64").unwrap();+ assert_eq!(release::expected_sha256(lin, Some("nothing here")), None);+ let names: Vec<String> = ["README.md", "bin/", "bin/linux-amd64", "windows-amd64.exe"].map(String::from).to_vec();+ assert_eq!(release::binary_entry(&names, "linux", "amd64").map(String::as_str), Some("bin/linux-amd64"));+ assert_eq!(release::binary_entry(&names, "windows", "amd64").map(String::as_str), Some("windows-amd64.exe"));+ let plain: Vec<String> = ["whatsapp.exe".to_string()].to_vec();+ assert_eq!(release::binary_entry(&plain, "windows", "amd64").map(String::as_str), Some("whatsapp.exe"));+ assert_eq!(release::binary_entry(&plain, "linux", "amd64"), None);+ }++ #[test]+ fn dates_and_data_urls() {+ assert_eq!(rfc3339_ms(Some("1970-01-01T00:00:00Z")), Some(0));+ assert_eq!(rfc3339_ms(Some("2023-10-15T10:30:00Z")), Some(1_697_365_800_000));+ assert_eq!(rfc3339_ms(Some("2023-10-15T12:30:00.5+02:00")), Some(1_697_365_800_500));+ assert_eq!(rfc3339_ms(Some("2023-10-15T10:30:00.123456Z")), Some(1_697_365_800_123));+ assert_eq!(rfc3339_ms(Some("yesterday")), None);+ assert_eq!(rfc3339_ms(Some("2023-13-15T10:30:00Z")), None);+ assert_eq!(rfc3339_ms(None), None);+ assert_eq!(epoch_ms(Some(&serde_json::json!(1706868600))), Some(1_706_868_600_000));+ assert_eq!(epoch_ms(Some(&serde_json::json!("1706868600"))), Some(1_706_868_600_000));+ assert_eq!(epoch_ms(Some(&serde_json::json!(0))), None);+ assert_eq!(iso_utc(1_697_365_800_000), "2023-10-15T10:30:00Z");+ assert_eq!(iso_utc(0), "1970-01-01T00:00:00Z");+ assert_eq!(png_data_url(&[0x89, 0x50, 0x4E, 0x47]), "data:image/png;base64,iVBORw==");+ assert_eq!(png_data_url(b"Man"), "data:image/png;base64,TWFu");+ assert_eq!(png_data_url(b"Ma"), "data:image/png;base64,TWE=");+ assert_eq!(base64(b""), "");+ assert_eq!(base64(b"f"), "Zg==");+ assert_eq!(base64(b"foobar"), "Zm9vYmFy");+ }+}diff --git a/windows/src-tauri/src/whatsapp/install.rs b/windows/src-tauri/src/whatsapp/install.rsnew file mode 100644index 00000000..17eaad8c--- /dev/null+++ b/windows/src-tauri/src/whatsapp/install.rs@@ -0,0 +1,182 @@+// "Install WhatsApp": one click instead of GitHub, a zip and a command line (port of+// WhatsAppGOWAInstaller.swift). Downloads GOWA's own latest build for this system from its GitHub+// releases, checks its SHA-256 against the one GOWA publishes, puts the binary in Coucou's GOWA+// folder (next to the WhatsApp session it keeps) and turns on "Start GOWA automatically".+// The only network call is to GitHub, after the click; no message ever goes there.++use std::io::Write;+use std::time::Duration;++use serde::Serialize;++use super::archive;+use super::gateway::release::{self, Asset};+use super::process;++/// GOWA's zips are about 15 MB; anything far bigger is not one.+const MAX_ZIP: u64 = 150 * 1024 * 1024;++#[derive(Clone, Debug, PartialEq, Eq, Serialize)]+#[serde(tag = "step", rename_all = "camelCase")]+pub enum Step {+ Idle,+ Checking,+ Downloading { megabytes: u64 },+ Verifying,+ Installing,+ Done { version: String },+ /// `reason`: noBuild | noChecksum | downloadFailed | badChecksum | unzipFailed.+ Failed { reason: String },+}++impl Step {+ pub fn busy(&self) -> bool {+ matches!(self, Step::Checking | Step::Downloading { .. } | Step::Verifying | Step::Installing)+ }+}++fn fail(reason: &str) -> String {+ reason.to_string()+}++/// GitHub only: no cookie, a bare user agent, redirects followed only to GitHub over https.+fn github_client(timeout: Duration) -> Result<reqwest::Client, String> {+ let policy = reqwest::redirect::Policy::custom(|attempt| {+ if attempt.previous().len() >= 5 {+ attempt.error("too many redirects")+ } else if attempt.url().scheme() == "https" && crate::update::allowed_host(attempt.url().host_str()) {+ attempt.follow()+ } else {+ attempt.stop()+ }+ });+ reqwest::Client::builder()+ .connect_timeout(Duration::from_secs(15))+ .timeout(timeout)+ .user_agent("Coucou")+ .redirect(policy)+ .build()+ .map_err(|_| fail("downloadFailed"))+}++async fn get(client: &reqwest::Client, url: &str, accept: &str) -> Result<reqwest::Response, String> {+ if !crate::update::allowed_url(url) {+ return Err(fail("downloadFailed"));+ }+ let response = client.get(url).header("Accept", accept).send().await.map_err(|_| fail("downloadFailed"))?;+ if response.status().as_u16() != 200 || response.url().scheme() != "https" || !crate::update::allowed_host(response.url().host_str()) {+ return Err(fail("downloadFailed"));+ }+ Ok(response)+}++/// SHA-256 of `data`, lowercase hex.+pub fn sha256(data: &[u8]) -> String {+ super::gateway::hex(ring::digest::digest(&ring::digest::SHA256, data).as_ref())+}++/// The zip as GOWA published it: exactly its size and its SHA-256, else nothing.+pub fn verified(zip: Vec<u8>, asset: &Asset, expected: &str) -> Result<Vec<u8>, String> {+ if (asset.size != 0 && zip.len() as u64 != asset.size) || sha256(&zip) != expected {+ return Err(fail("badChecksum"));+ }+ Ok(zip)+}++/// The binary out of the zip, for this system.+pub fn binary_from(zip: &[u8], os: &str, arch: &str) -> Result<Vec<u8>, String> {+ let entries = archive::entries(zip).ok_or_else(|| fail("unzipFailed"))?;+ let names: Vec<String> = entries.iter().map(|e| e.name.clone()).collect();+ let name = release::binary_entry(&names, os, arch).ok_or_else(|| fail("noBuild"))?;+ let entry = entries.iter().find(|e| &e.name == name).ok_or_else(|| fail("noBuild"))?;+ archive::read(zip, entry).ok_or_else(|| fail("unzipFailed"))+}++/// Writes the binary beside its final place, then renames it there (GOWA stopped first, so+/// Windows lets go of the old one).+fn put_in_place(binary: &[u8]) -> Result<(), String> {+ let dir = process::working_dir();+ crate::platform::ensure_private_dir(&dir).map_err(|_| fail("unzipFailed"))?;+ let dest = process::installed_binary();+ let temp = dest.with_extension("download");+ let written = (|| -> std::io::Result<()> {+ let mut f = std::fs::File::create(&temp)?;+ f.write_all(binary)?;+ f.flush()?;+ drop(f);+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ std::fs::set_permissions(&temp, std::fs::Permissions::from_mode(0o755))?;+ }+ process::stop_now();+ let _ = std::fs::remove_file(&dest);+ std::fs::rename(&temp, &dest)+ })();+ if written.is_err() {+ let _ = std::fs::remove_file(&temp);+ return Err(fail("unzipFailed"));+ }+ Ok(())+}++/// The whole install; `progress` hears each step. Returns GOWA's version.+pub async fn run(progress: impl Fn(Step)) -> Result<String, String> {+ let (os, arch) = (release::this_os(), release::this_arch());+ let client = github_client(Duration::from_secs(600))?;++ // 1. Which build: GOWA's latest release, the zip for this system.+ let meta = get(&client, release::LATEST_URL, "application/vnd.github+json").await?;+ let meta = crate::net::read_capped(meta, crate::net::MAX_BODY).await.map_err(|_| fail("downloadFailed"))?;+ let (version, assets) = release::parse(&meta).ok_or_else(|| fail("noBuild"))?;+ let (zip, sums) = release::pick(&assets, os, arch).ok_or_else(|| fail("noBuild"))?;+ let checksums = match sums {+ Some(sums) => {+ let r = get(&client, &sums.url, "application/octet-stream").await?;+ let body = crate::net::read_capped(r, 64 * 1024).await.map_err(|_| fail("downloadFailed"))?;+ Some(String::from_utf8_lossy(&body).into_owned())+ }+ None => None,+ };+ let expected = release::expected_sha256(zip, checksums.as_deref()).ok_or_else(|| fail("noChecksum"))?;+ if zip.size > MAX_ZIP {+ return Err(fail("badChecksum"));+ }++ // 2. Download, kept in memory (never a half-written file on disk).+ progress(Step::Downloading { megabytes: (zip.size / 1_000_000).max(1) });+ let response = get(&client, &zip.url, "application/octet-stream").await?;+ let limit = if zip.size > 0 { zip.size as usize } else { MAX_ZIP as usize };+ let data = crate::net::read_capped(response, limit).await.map_err(|_| fail("downloadFailed"))?;++ // 3. Verify: exactly the file GOWA published.+ progress(Step::Verifying);+ let data = verified(data, zip, &expected)?;++ // 4. Unzip, put the binary in place, make it runnable.+ progress(Step::Installing);+ let binary = binary_from(&data, os, arch)?;+ tauri::async_runtime::spawn_blocking(move || put_in_place(&binary)).await.map_err(|_| fail("unzipFailed"))??;+ Ok(version)+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_zip_must_be_the_one_gowa_published() {+ let asset = Asset { name: "whatsapp_9.6.0_linux_amd64.zip".into(), url: "https://github.com/x".into(), size: 3, digest: None };+ let good = sha256(b"abc");+ assert_eq!(good, "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");+ assert_eq!(verified(b"abc".to_vec(), &asset, &good), Ok(b"abc".to_vec()));+ assert_eq!(verified(b"abd".to_vec(), &asset, &good), Err("badChecksum".into()));+ assert_eq!(verified(b"abcd".to_vec(), &asset, &sha256(b"abcd")), Err("badChecksum".into()), "not the published size");+ }++ #[test]+ fn the_binary_comes_out_of_a_real_zip_only() {+ assert_eq!(binary_from(b"not a zip", "linux", "amd64"), Err("unzipFailed".into()));+ assert!(!Step::Idle.busy() && Step::Verifying.busy() && !Step::Done { version: "1".into() }.busy());+ }+}diff --git a/windows/src-tauri/src/whatsapp/mod.rs b/windows/src-tauri/src/whatsapp/mod.rsnew file mode 100644index 00000000..bc01154c--- /dev/null+++ b/windows/src-tauri/src/whatsapp/mod.rs@@ -0,0 +1,1329 @@+// WhatsApp in the island (experimental), the Windows and Linux port of the Mac's WhatsAppController.swift.+//+// Talks to the local gateway the user runs (GOWA, which Coucou can install and start itself, or+// OpenWA), receives new messages on a webhook bound to 127.0.0.1, falls back to polling every 20 s+// when no webhook comes, and keeps the conversations in memory only: nothing of a message is ever+// written to disk or to a log, and everything is forgotten when Coucou quits or the integration is+// turned off. Runs only while the integration is on and its pill is active: otherwise there is no+// timer, no listener and no request at all.+//+// The rules (inbox, filters, signatures, limits) are in model.rs and gateway.rs, the HTTP calls in+// provider.rs, the listener in webhook.rs, GOWA's install and process in install.rs and process.rs.+// The island draws what `IslandView` says (src/views/whatsapp.ts), Settings what `SettingsView`+// says (src/settings/whatsapp.ts); both only ever see status codes, which they translate.++pub mod archive;+pub mod gateway;+pub mod install;+pub mod model;+pub mod prefs;+pub mod process;+pub mod provider;+pub mod webhook;++use std::collections::HashSet;+use std::sync::atomic::Ordering;+use std::sync::{Arc, LazyLock, Mutex, MutexGuard, OnceLock, PoisonError};+use std::time::{Duration, Instant};++use serde::Serialize;+use tauri::{AppHandle, Emitter, WebviewWindow};++use gateway::{Kind, Link, WebhookEvent};+use install::Step;+use model::{Conversation, Filters, Inbox, Message, Outcome, RateLimit, Refusal};+use prefs::Prefs;+use provider::{Provider, WaError};+use webhook::Listener;++pub const PILL_ID: &str = "integration_whatsapp";+const WEBHOOK_PATH: &str = "/whatsapp";+/// Credential store entries, Rust-only (secrets.rs INTERNAL_KEYS): the webview never reads them.+pub const URL_KEY: &str = "whatsapp-url";+pub const CREDENTIAL_KEY: &str = "whatsapp-api-key";+pub const SECRET_KEY: &str = "whatsapp-webhook-secret";++const ISLAND_EVENT: &str = "whatsapp";+const PILL_EVENT: &str = "whatsapp-pill";+const SETTINGS_EVENT: &str = "whatsapp-settings";++#[derive(Clone, Debug, PartialEq, Eq, Serialize)]+#[serde(tag = "state", rename_all = "camelCase")]+pub enum LinkState {+ Off,+ /// The gateway's address can't be used.+ BadUrl,+ Connecting,+ /// The gateway runs, WhatsApp isn't linked: the QR is shown in Settings.+ NeedsQr,+ Connected,+ Unreachable,+ Unauthorized,+ /// The gateway's own error message.+ Failed { detail: String },+}++#[derive(Clone, Debug, PartialEq, Eq, Serialize)]+#[serde(tag = "state", rename_all = "camelCase")]+pub enum WebhookState {+ Off,+ /// Listening on the port, not yet accepted by the gateway.+ Listening,+ /// The gateway accepted the address: messages come on their own.+ Registered,+ /// The gateway refused it (its message): polling instead.+ Refused { detail: String },+ /// The port is taken.+ PortBusy { port: u16 },+}++/// Why the last reply didn't go (shown under the field until the next try).+#[derive(Clone, Debug, PartialEq, Eq, Serialize)]+#[serde(tag = "code", rename_all = "camelCase")]+pub enum SendError {+ TooLong,+ TooFast,+ Unreachable,+ Unauthorized,+ NeedsQr,+ Refused { detail: String },+}++/// What happens to the pill (src/island/whatsapp.ts).+#[derive(Clone, Debug, PartialEq, Eq, Serialize)]+#[serde(tag = "kind", rename_all = "camelCase")]+enum PillEvent {+ /// A new message reaches you: only the conversation's name, never the text.+ Message { name: String },+ /// Nothing unread is left: the badge goes.+ Read,+ /// Turned off: the pill goes back to idle.+ Reset,+}++/// What the island shows.+#[derive(Clone, Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct IslandView {+ pub on: bool,+ pub link: LinkState,+ /// Newest first, filters applied.+ pub conversations: Vec<Conversation>,+ pub unread: u32,+ pub sending: bool,+ pub send_error: Option<SendError>,+ /// The gateway failed twice in a row: a small red dot on the pill.+ pub down: bool,+}++#[derive(Clone, Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct IgnoredChat {+ pub id: String,+ pub name: String,+}++/// What Settings shows.+#[derive(Clone, Debug, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct SettingsView {+ pub prefs: Prefs,+ /// The address typed in Settings, "" for the gateway's default.+ pub url: String,+ pub default_url: String,+ pub has_credential: bool,+ pub link: LinkState,+ pub webhook: WebhookState,+ /// A `data:image/png;base64,…` URL while WhatsApp waits for the scan.+ pub qr: Option<String>,+ /// This account's number once linked.+ pub me: Option<String>,+ pub install: Step,+ /// A GOWA binary Coucou can start (the one it installed, or one the user gave).+ pub installed: bool,+ /// Where GOWA keeps its WhatsApp session (and Coucou the binary it installed).+ pub gowa_dir: String,+ pub pill_active: bool,+ pub ignored: Vec<IgnoredChat>,+}++#[derive(Clone, Debug, PartialEq, Eq, Serialize)]+#[serde(tag = "result", rename_all = "camelCase")]+pub enum TestResult {+ Connected { who: String },+ NeedsQr,+ Connecting,+ BadUrl,+ Unreachable,+ Unauthorized,+ Refused { detail: String },+}++struct Ctl {+ prefs: Prefs,+ url: String,+ has_credential: bool,+ pill_active: bool,+ provider: Option<Arc<Provider>>,+ /// Bumped at each start and stop: an answer from before a restart is dropped.+ generation: u64,+ link: LinkState,+ webhook: WebhookState,+ secret: String,+ qr: Option<String>,+ qr_expiry: Option<Instant>,+ me: Option<String>,+ inbox: Inbox,+ listener: Option<Listener>,+ tick: u64,+ refreshing: bool,+ polling: bool,+ backfilled: bool,+ last_webhook: Option<Instant>,+ last_poll_ms: i64,+ naming: HashSet<String>,+ /// The conversation open in the card: what arrives there is seen, so it isn't unread.+ open_chat: Option<String>,+ rate: RateLimit,+ /// Failed checks in a row (the gateway down, refusing, unreachable).+ failures: u32,+ down: bool,+ sending: bool,+ send_error: Option<SendError>,+ install: Step,+}++static CTL: LazyLock<Mutex<Ctl>> = LazyLock::new(|| {+ Mutex::new(Ctl {+ prefs: Prefs::default(),+ url: String::new(),+ has_credential: false,+ pill_active: false,+ provider: None,+ generation: 0,+ link: LinkState::Off,+ webhook: WebhookState::Off,+ secret: String::new(),+ qr: None,+ qr_expiry: None,+ me: None,+ inbox: Inbox::default(),+ listener: None,+ tick: 0,+ refreshing: false,+ polling: false,+ backfilled: false,+ last_webhook: None,+ last_poll_ms: 0,+ naming: HashSet::new(),+ open_chat: None,+ rate: RateLimit::default(),+ failures: 0,+ down: false,+ sending: false,+ send_error: None,+ install: Step::Idle,+ })+});++static APP: OnceLock<AppHandle> = OnceLock::new();++fn ctl() -> MutexGuard<'static, Ctl> {+ CTL.lock().unwrap_or_else(PoisonError::into_inner)+}++impl Ctl {+ fn kind(&self) -> Kind {+ Kind::from_name(&self.prefs.gateway)+ }++ fn should_run(&self) -> bool {+ self.prefs.enabled && self.pill_active+ }++ fn filters(&self) -> Filters {+ Filters { mute_groups: self.prefs.mute_groups, ignored: self.prefs.ignored.iter().cloned().collect() }+ }++ fn effective_url(&self) -> String {+ if self.url.is_empty() { self.kind().default_url().to_string() } else { self.url.clone() }+ }++ fn webhook_alive(&self) -> bool {+ self.last_webhook.is_some_and(|t| t.elapsed() < Duration::from_secs(300))+ }++ fn island_view(&self) -> IslandView {+ let filters = self.filters();+ IslandView {+ on: self.provider.is_some(),+ link: self.link.clone(),+ conversations: self.inbox.visible(&filters).into_iter().cloned().collect(),+ unread: self.inbox.visible_unread(&filters),+ sending: self.sending,+ send_error: self.send_error.clone(),+ down: self.down,+ }+ }++ fn settings_view(&self) -> SettingsView {+ let path = self.prefs.gowa_path.trim();+ SettingsView {+ prefs: self.prefs.clone(),+ url: self.url.clone(),+ default_url: self.kind().default_url().to_string(),+ has_credential: self.has_credential,+ link: self.link.clone(),+ webhook: self.webhook.clone(),+ qr: self.qr.clone(),+ me: self.me.as_deref().map(model::display_number),+ install: self.install.clone(),+ installed: !path.is_empty() && process::is_runnable(std::path::Path::new(path)),+ gowa_dir: process::working_dir().to_string_lossy().into_owned(),+ pill_active: self.pill_active,+ ignored: self+ .prefs+ .ignored+ .iter()+ .map(|id| IgnoredChat {+ id: id.clone(),+ name: self.inbox.conversations.get(id).map(|c| c.name.clone()).unwrap_or_else(|| model::display_number(id)),+ })+ .collect(),+ }+ }+}++// ── Telling the pages ─────────────────────────────────────────────────────────++/// Both pages redraw from what changed. Never called with the lock held.+fn changed() {+ let Some(app) = APP.get() else { return };+ let (island, settings) = {+ let c = ctl();+ (c.island_view(), c.settings_view())+ };+ let _ = app.emit_to(crate::island::WINDOW_LABEL, ISLAND_EVENT, island);+ let _ = app.emit_to(crate::HUB_LABEL, SETTINGS_EVENT, settings);+}++fn pill(event: PillEvent) {+ if let Some(app) = APP.get() {+ let _ = app.emit_to(crate::island::WINDOW_LABEL, PILL_EVENT, event);+ }+}++fn spawn<F: std::future::Future<Output = ()> + Send + 'static>(f: F) {+ tauri::async_runtime::spawn(f);+}++/// GOWA started or stopped to match Settings, off the async threads (stopping it waits a second).+fn sync_gowa(c: &Ctl) {+ let wanted = c.prefs.auto_start && c.kind() == Kind::Gowa;+ let (binary, url) = (c.prefs.gowa_path.clone(), c.effective_url());+ let credential = if wanted { crate::secrets::get_internal(CREDENTIAL_KEY).unwrap_or_default() } else { String::new() };+ tauri::async_runtime::spawn_blocking(move || {+ process::sync(wanted, &binary, &url, &credential);+ });+}++/// The webhook's signing secret, made once (random, 64 hex characters), kept in the credential store.+fn webhook_secret() -> String {+ if let Some(s) = crate::secrets::get_internal(SECRET_KEY).filter(|s| s.len() >= 16) {+ return s;+ }+ use ring::rand::{SecureRandom, SystemRandom};+ let mut bytes = [0u8; 32];+ if SystemRandom::new().fill(&mut bytes).is_err() {+ return String::new(); // no secret, no webhook: polling only+ }+ let s = gateway::hex(&bytes);+ let _ = crate::secrets::set_internal(SECRET_KEY, &s);+ s+}++// ── Lifecycle ─────────────────────────────────────────────────────────────────++/// Called once at launch.+pub fn start(app: &AppHandle, active_integrations: &[String]) {+ let _ = APP.set(app.clone());+ {+ let mut c = ctl();+ c.prefs = prefs::load();+ c.url = crate::secrets::get_internal(URL_KEY).unwrap_or_default();+ c.has_credential = crate::secrets::get_internal(CREDENTIAL_KEY).is_some();+ c.pill_active = active_integrations.iter().any(|x| x == PILL_ID);+ }+ update();+}++/// Settings were saved: the pill turned on or off from anywhere is followed.+pub fn sync(active_integrations: &[String]) {+ let active = active_integrations.iter().any(|x| x == PILL_ID);+ let moved = {+ let mut c = ctl();+ let moved = c.pill_active != active;+ c.pill_active = active;+ moved+ };+ if moved {+ update();+ }+}++/// Coucou quits: GOWA goes with it, and so does everything in memory.+pub fn shutdown() {+ {+ let mut c = ctl();+ c.generation += 1;+ if let Some(l) = c.listener.take() {+ l.stop();+ }+ c.provider = None;+ c.inbox.clear();+ }+ process::stop_now();+}++fn update() {+ let (run, running) = {+ let c = ctl();+ (c.should_run(), c.provider.is_some())+ };+ if run && !running {+ begin();+ } else if !run && running {+ stop(true);+ changed();+ } else {+ changed();+ }+}++/// Settings changed (on/off, gateway, URL, credentials, port): start over.+fn settings_changed() {+ let forget = !ctl().should_run();+ stop(forget);+ update();+}++fn begin() {+ let secret = webhook_secret();+ let (gen, port, kind) = {+ let mut c = ctl();+ let kind = c.kind();+ let Some(base) = provider::parse_base(&c.effective_url()) else {+ c.link = LinkState::BadUrl;+ drop(c);+ changed();+ return;+ };+ let credential = crate::secrets::get_internal(CREDENTIAL_KEY);+ let Ok(provider) = Provider::new(kind, base, credential) else {+ c.link = LinkState::Unreachable;+ drop(c);+ changed();+ return;+ };+ c.provider = Some(Arc::new(provider));+ c.generation += 1;+ c.link = LinkState::Connecting;+ c.secret = secret.clone();+ c.tick = 0;+ // GOWA started by Coucou when asked to, before the first check.+ sync_gowa(&c);+ (c.generation, c.prefs.port, kind)+ };+ start_listener(gen, port, kind, secret);+ spawn_ticker(gen);+ changed();+ refresh();+}++/// Stops talking to the gateway. `forget`: the conversations go too.+fn stop(forget: bool) {+ let mut c = ctl();+ c.generation += 1;+ c.refreshing = false;+ c.polling = false;+ if let Some(l) = c.listener.take() {+ l.stop();+ }+ c.provider = None;+ c.link = LinkState::Off;+ c.webhook = WebhookState::Off;+ c.qr = None;+ c.qr_expiry = None;+ c.me = None;+ c.backfilled = false;+ c.last_webhook = None;+ c.naming.clear();+ c.failures = 0;+ c.down = false;+ c.sending = false;+ c.send_error = None;+ // Turned off: GOWA goes too. Otherwise begin() keeps it, or restarts it if its settings changed.+ if !c.should_run() {+ tauri::async_runtime::spawn_blocking(process::stop_now);+ }+ if forget {+ c.open_chat = None;+ c.inbox.clear();+ drop(c);+ pill(PillEvent::Reset);+ }+}++fn start_listener(gen: u64, port: u16, kind: Kind, secret: String) {+ let handler: webhook::Handler = Arc::new(move |request| {+ if request.method != "POST" || !request.path.starts_with(WEBHOOK_PATH) {+ return 404;+ }+ // Signed by the gateway with Coucou's secret, over the exact bytes received.+ if !gateway::verify(kind, &request.headers, &request.body, &secret) {+ return 401;+ }+ let body = request.body;+ spawn(async move { received(gen, kind, &body) });+ 200+ });+ let listener = Listener::start(port, handler);+ let mut c = ctl();+ if c.generation != gen {+ if let Ok(l) = listener {+ l.stop();+ }+ return;+ }+ match listener {+ Ok(l) => {+ c.listener = Some(l);+ c.webhook = WebhookState::Listening;+ }+ Err(()) => c.webhook = WebhookState::PortBusy { port },+ }+}++fn spawn_ticker(gen: u64) {+ spawn(async move {+ let mut last = Instant::now();+ loop {+ tokio::time::sleep(Duration::from_secs(5)).await;+ if ctl().generation != gen {+ break;+ }+ // Back from sleep (the 5 s took far longer): nothing is trusted, the gateway may have+ // restarted without Coucou's webhook.+ if last.elapsed() > Duration::from_secs(30) {+ let mut c = ctl();+ if c.webhook == WebhookState::Registered {+ c.webhook = WebhookState::Listening;+ }+ c.last_webhook = None;+ }+ last = Instant::now();+ on_tick();+ }+ });+}++fn on_tick() {+ // Paused from the tray: nothing reaches the network.+ if crate::integrations::PAUSED.load(Ordering::Relaxed) {+ return;+ }+ let (refresh_now, poll_now) = {+ let mut c = ctl();+ c.tick += 1;+ if c.link != LinkState::Connected {+ // Every 5 s while linking (QR, gateway coming up); every 30 s once the gateway has+ // been down for a minute.+ (!(c.failures > 12 && c.tick % 6 != 0), false)+ } else {+ // Every minute: still linked? Every 20 s: new messages, unless the webhook delivers.+ (c.tick % 12 == 0, c.tick % 4 == 0)+ }+ };+ if refresh_now {+ refresh();+ }+ if poll_now {+ poll();+ }+}++// ── Status and QR ─────────────────────────────────────────────────────────────++fn refresh() {+ let (provider, gen) = {+ let mut c = ctl();+ let Some(p) = c.provider.clone() else { return };+ if c.refreshing {+ return;+ }+ c.refreshing = true;+ (p, c.generation)+ };+ spawn(async move {+ let result = provider.status().await;+ let (mut register, mut backfill_now, mut ask_qr) = (false, false, false);+ {+ let mut c = ctl();+ if c.generation != gen {+ return;+ }+ match result {+ Ok(status) => {+ if c.failures > 0 {+ c.failures = 0;+ c.down = false;+ }+ c.me = status.me;+ match status.link {+ Link::Connected => {+ if c.link != LinkState::Connected {+ c.qr = None;+ }+ c.link = LinkState::Connected;+ register = c.webhook == WebhookState::Listening;+ if !c.backfilled {+ c.backfilled = true;+ backfill_now = true;+ }+ }+ Link::NeedsQr => {+ c.link = LinkState::NeedsQr;+ if c.qr.is_none() || c.qr_expiry.is_none_or(|t| Instant::now() > t) {+ // Not asked again for 15 s even when nothing came: each GOWA login+ // call restarts the pairing.+ c.qr_expiry = Some(Instant::now() + Duration::from_secs(15));+ ask_qr = true;+ }+ }+ Link::Connecting => c.link = LinkState::Connecting,+ }+ }+ Err(err) => apply(&mut c, err),+ }+ }+ changed();+ if register {+ register_webhook(&provider, gen).await;+ }+ if backfill_now {+ backfill(&provider, gen).await;+ }+ if ask_qr {+ let qr = provider.qr().await;+ let mut c = ctl();+ if c.generation == gen {+ match qr {+ Ok(Some(qr)) => {+ c.qr = Some(qr.data_url);+ c.qr_expiry = Some(Instant::now() + Duration::from_secs(qr.seconds));+ }+ Ok(None) => {}+ Err(err) => apply(&mut c, err),+ }+ }+ drop(c);+ changed();+ }+ let mut c = ctl();+ if c.generation == gen {+ c.refreshing = false;+ }+ });+}++fn apply(c: &mut Ctl, error: WaError) {+ c.link = match &error {+ WaError::Unreachable => LinkState::Unreachable,+ WaError::Unauthorized => LinkState::Unauthorized,+ WaError::NotLoggedIn => LinkState::NeedsQr,+ WaError::Refused(why) => LinkState::Failed { detail: why.clone() },+ };+ if error == WaError::NotLoggedIn {+ return;+ }+ c.failures += 1;+ // Twice in a row (not a gateway still starting): a small red dot on the pill, nothing more.+ if c.failures == 2 {+ c.down = true;+ }+ // GOWA started by Coucou and gone (crash, killed): started again, once a minute at most.+ if error == WaError::Unreachable {+ sync_gowa(c);+ }+}++/// One check from Settings' "Test connection": what the gateway says.+async fn test_connection() -> TestResult {+ // The running connection when there is one (a second one could race it for OpenWA's session).+ let provider = {+ let c = ctl();+ match c.provider.clone() {+ Some(p) => p,+ None => {+ let Some(base) = provider::parse_base(&c.effective_url()) else { return TestResult::BadUrl };+ match Provider::new(c.kind(), base, crate::secrets::get_internal(CREDENTIAL_KEY)) {+ Ok(p) => Arc::new(p),+ Err(_) => return TestResult::Unreachable,+ }+ }+ }+ };+ let mut attempt = 0;+ let status = loop {+ match provider.status().await {+ // GOWA just started by Coucou: a few seconds to come up.+ Err(WaError::Unreachable) if process::is_running() && attempt < 8 => {+ attempt += 1;+ tokio::time::sleep(Duration::from_secs(1)).await;+ }+ other => break other,+ }+ };+ match status {+ Ok(s) => match s.link {+ Link::Connected => TestResult::Connected { who: s.me.as_deref().map(model::display_number).unwrap_or_default() },+ Link::NeedsQr => TestResult::NeedsQr,+ Link::Connecting => TestResult::Connecting,+ },+ Err(WaError::Unreachable) => TestResult::Unreachable,+ Err(WaError::Unauthorized) => TestResult::Unauthorized,+ Err(WaError::NotLoggedIn) => TestResult::NeedsQr,+ Err(WaError::Refused(detail)) => TestResult::Refused { detail },+ }+}++// ── Webhook ───────────────────────────────────────────────────────────────────++async fn register_webhook(provider: &Provider, gen: u64) {+ let (url, secret) = {+ let c = ctl();+ (format!("http://127.0.0.1:{}{WEBHOOK_PATH}", c.prefs.port), c.secret.clone())+ };+ if secret.is_empty() {+ return;+ }+ let result = provider.register_webhook(&url, &secret).await;+ {+ let mut c = ctl();+ if c.generation != gen {+ return;+ }+ match result {+ Ok(()) => c.webhook = WebhookState::Registered,+ Err(WaError::Refused(why)) => {+ crate::log::line(format!("whatsapp: the gateway refused the webhook: {why}"));+ c.webhook = WebhookState::Refused { detail: why };+ }+ // Tried again on the next minute's check.+ Err(_) => {}+ }+ }+ changed();+}++fn received(gen: u64, kind: Kind, body: &[u8]) {+ let (fresh, groups) = {+ let mut c = ctl();+ if c.generation != gen || c.provider.is_none() {+ return;+ }+ c.last_webhook = Some(Instant::now());+ if c.webhook != WebhookState::Registered {+ c.webhook = WebhookState::Registered;+ }+ let me = c.me.clone();+ let Some(WebhookEvent::Message(message)) = gateway::parse_webhook(kind, body, me.as_deref()) else { return };+ ingest(&mut c, vec![message])+ };+ after_ingest(gen, fresh, groups);+}++// ── Messages ──────────────────────────────────────────────────────────────────++/// The last hours of history, once linked: kept, but nothing counts as new.+async fn backfill(provider: &Arc<Provider>, gen: u64) {+ let me = ctl().me.clone();+ let since = gateway::now_ms() - 12 * 3600 * 1000;+ let Ok(messages) = provider.recent_messages(since, me.as_deref()).await else { return };+ let groups = {+ let mut c = ctl();+ if c.generation != gen {+ return;+ }+ let filters = c.filters();+ // History: kept, never counted as unread, never announced.+ let chats: Vec<String> = messages.iter().map(|m| model::normalized(&m.chat)).collect();+ for message in messages {+ c.inbox.add(message, &filters, None, true);+ }+ let groups = chats.iter().filter_map(|chat| needs_name(&mut c, chat)).collect::<Vec<_>>();+ c.last_poll_ms = gateway::now_ms();+ groups+ };+ name_groups(provider.clone(), gen, groups);+ changed();+}++fn poll() {+ let (provider, gen, since, me) = {+ let mut c = ctl();+ let Some(p) = c.provider.clone() else { return };+ if c.polling || c.webhook_alive() || !c.backfilled {+ return;+ }+ c.polling = true;+ // A little overlap; duplicates are dropped.+ (p, c.generation, c.last_poll_ms - 30_000, c.me.clone())+ };+ spawn(async move {+ let started = gateway::now_ms();+ let result = provider.recent_messages(since, me.as_deref()).await;+ let (fresh, groups) = {+ let mut c = ctl();+ if c.generation != gen {+ return;+ }+ c.polling = false;+ let Ok(messages) = result else { return };+ c.last_poll_ms = started;+ ingest(&mut c, messages)+ };+ after_ingest(gen, fresh, groups);+ });+}++/// Adds what arrived. Returns the conversation to announce (its name), and the groups to name.+fn ingest(c: &mut Ctl, messages: Vec<Message>) -> (Option<String>, Vec<String>) {+ let filters = c.filters();+ let mut fresh: Option<String> = None;+ let mut groups = Vec::new();+ for message in messages {+ let key = model::normalized(&message.chat);+ let from_me = message.from_me;+ let outcome = c.inbox.add(message, &filters, None, false);+ if let Some(g) = needs_name(c, &key) {+ groups.push(g);+ }+ if c.open_chat.as_deref() == Some(key.as_str()) {+ // Read on screen: no unread, no Mochi. The receipt waits for a reply (or the next+ // opening), as Settings says.+ c.inbox.mark_read(&key);+ continue;+ }+ if outcome == Outcome::Notify && !from_me {+ fresh = Some(key);+ }+ }+ let name = fresh.map(|key| c.inbox.conversations.get(&key).map(|conv| conv.name.clone()).unwrap_or_else(|| model::display_number(&key)));+ (name, groups)+}++fn after_ingest(gen: u64, fresh: Option<String>, groups: Vec<String>) {+ if let Some(name) = fresh {+ pill(PillEvent::Message { name });+ }+ if let Some(provider) = ctl().provider.clone() {+ name_groups(provider, gen, groups);+ }+ changed();+}++/// Groups arrive under their id (GOWA's webhook carries no group name): asked once.+fn needs_name(c: &mut Ctl, chat: &str) -> Option<String> {+ if !model::is_group(chat) || c.naming.contains(chat) {+ return None;+ }+ let conv = c.inbox.conversations.get(chat)?;+ if conv.name != model::display_number(chat) {+ return None;+ }+ c.naming.insert(chat.to_string());+ Some(chat.to_string())+}++fn name_groups(provider: Arc<Provider>, gen: u64, groups: Vec<String>) {+ if groups.is_empty() {+ return;+ }+ spawn(async move {+ for chat in groups {+ let Some(name) = provider.group_name(&chat).await else { continue };+ let mut c = ctl();+ if c.generation != gen {+ return;+ }+ c.inbox.rename(&chat, &name);+ drop(c);+ changed();+ }+ });+}++// ── The conversation ──────────────────────────────────────────────────────────++/// Marks the chat read here and, when it had something unread, on WhatsApp too (up to its newest+/// received message). Returns the receipt to send.+fn mark_read(c: &mut Ctl, chat: &str) -> Option<(String, Option<String>)> {+ let key = model::normalized(chat);+ let conv = c.inbox.conversations.get(&key)?;+ let had_unread = conv.unread > 0;+ let last = conv.messages.iter().rev().find(|m| !m.from_me).map(|m| m.id.clone());+ c.inbox.mark_read(&key);+ if c.inbox.visible_unread(&c.filters()) == 0 {+ pill(PillEvent::Read);+ }+ // Nothing new: no receipt to send.+ had_unread.then_some((key, last))+}++/// A conversation opened in the card: its latest messages from the gateway, and the read receipt+/// when Settings says so.+fn open(chat: &str) {+ let (provider, gen, receipt, me) = {+ let mut c = ctl();+ c.send_error = None;+ c.open_chat = Some(model::normalized(chat));+ let Some(p) = c.provider.clone() else { return };+ let receipt = if c.prefs.mark_read_on_open { mark_read(&mut c, chat) } else { None };+ (p, c.generation, receipt, c.me.clone())+ };+ changed();+ let chat = chat.to_string();+ spawn(async move {+ if let Some((key, last)) = receipt {+ let _ = provider.mark_read(&key, last.as_deref()).await;+ }+ let Ok(history) = provider.messages(&chat, 10, me.as_deref()).await else { return };+ {+ let mut c = ctl();+ if c.generation != gen {+ return;+ }+ let filters = c.filters();+ for message in history {+ c.inbox.add(message, &filters, None, true);+ }+ }+ changed();+ });+}++fn close(chat: &str) {+ let mut c = ctl();+ if c.open_chat.as_deref() == Some(model::normalized(chat).as_str()) {+ c.open_chat = None;+ }+}++/// Sends a reply: only to a conversation already in the inbox, one at a time, a few a minute, and+/// only from the user's own Enter or click in the card. True once the gateway took it.+async fn send(chat: &str, text: &str) -> bool {+ let key = model::normalized(chat);+ let (provider, gen, body, me) = {+ let mut c = ctl();+ let Some(p) = c.provider.clone() else { return false };+ if c.sending {+ return false;+ }+ match model::check_reply(text, &key, &c.inbox) {+ Some(Refusal::TooLong) => {+ c.send_error = Some(SendError::TooLong);+ drop(c);+ changed();+ return false;+ }+ Some(_) => return false,+ None => {}+ }+ if !c.rate.allow(Instant::now()) {+ c.send_error = Some(SendError::TooFast);+ drop(c);+ changed();+ return false;+ }+ c.sending = true;+ c.send_error = None;+ (p, c.generation, text.trim().to_string(), c.me.clone())+ };+ changed();+ let result = provider.send(&body, &key).await;+ let receipt = {+ let mut c = ctl();+ // Turned off or restarted meanwhile: the inbox it belonged to is gone.+ if c.generation != gen {+ return result.is_ok();+ }+ c.sending = false;+ match result {+ Ok(id) => {+ let id = id.unwrap_or_else(|| format!("coucou-{}-{}", gateway::now_ms(), c.inbox.conversations.len()));+ let mut mine = Message::new(&id, &key, me.as_deref().unwrap_or(""), &body, gateway::now_ms());+ mine.from_me = true;+ mine.chat_name = c.inbox.conversations.get(&key).map(|conv| conv.name.clone());+ let filters = c.filters();+ c.inbox.add(mine, &filters, None, false);+ // Replying reads the conversation, whatever the setting.+ let last = c.inbox.conversations.get(&key).and_then(|conv| conv.messages.iter().rev().find(|m| !m.from_me)).map(|m| m.id.clone());+ if c.inbox.visible_unread(&filters) == 0 {+ pill(PillEvent::Read);+ }+ Some(last)+ }+ Err(err) => {+ c.send_error = Some(match err {+ WaError::Unreachable => SendError::Unreachable,+ WaError::Unauthorized => SendError::Unauthorized,+ WaError::NotLoggedIn => SendError::NeedsQr,+ WaError::Refused(detail) => SendError::Refused { detail },+ });+ None+ }+ }+ };+ changed();+ match receipt {+ Some(last) => {+ let _ = provider.mark_read(&key, last.as_deref()).await;+ true+ }+ None => false,+ }+}++fn ignore(chat: &str) {+ let key = model::normalized(chat);+ {+ let mut c = ctl();+ c.prefs.ignored.push(key.clone());+ c.prefs = c.prefs.clone().cleaned();+ prefs::save(&c.prefs);+ c.inbox.remove(&key);+ if c.open_chat.as_deref() == Some(key.as_str()) {+ c.open_chat = None;+ }+ }+ changed();+}++/// What Settings' "Add" turns into a chat id: a phone number ("+33 6 12…") or a full id ("…@g.us").+pub fn chat_from_entry(raw: &str) -> Option<String> {+ let raw = raw.trim();+ if raw.contains('@') {+ return (raw.len() > 3 && !raw.chars().any(char::is_whitespace)).then(|| raw.to_string());+ }+ let digits: String = raw.chars().filter(char::is_ascii_digit).collect();+ (!digits.is_empty()).then(|| format!("{digits}@s.whatsapp.net"))+}++// ── GOWA install ──────────────────────────────────────────────────────────────++fn set_install(step: Step) {+ ctl().install = step;+ changed();+}++fn install() {+ {+ let mut c = ctl();+ if c.install.busy() {+ return;+ }+ c.install = Step::Checking;+ }+ changed();+ spawn(async move {+ match install::run(set_install).await {+ Ok(version) => {+ {+ let mut c = ctl();+ c.prefs.gowa_version = Some(version.clone());+ c.prefs.gateway = "gowa".into();+ c.prefs.gowa_path = process::installed_binary().to_string_lossy().into_owned();+ c.prefs.auto_start = true;+ prefs::save(&c.prefs);+ // Back to http://127.0.0.1:3000.+ let _ = crate::secrets::set_internal(URL_KEY, "");+ c.url.clear();+ c.install = Step::Done { version: version.clone() };+ }+ crate::log::line(format!("whatsapp: GOWA {version} installed ({} {})", gateway::release::this_os(), gateway::release::this_arch()));+ // Starts it; the QR follows.+ settings_changed();+ }+ Err(reason) => {+ crate::log::line(format!("whatsapp: GOWA install failed: {reason}"));+ set_install(Step::Failed { reason });+ }+ }+ });+}++// ── Commands ──────────────────────────────────────────────────────────────────++fn only(window: &WebviewWindow, label: &str) -> Result<(), String> {+ if window.label() == label { Ok(()) } else { Err("not from this window".into()) }+}++#[tauri::command]+pub fn whatsapp_island(window: WebviewWindow) -> Result<IslandView, String> {+ only(&window, crate::island::WINDOW_LABEL)?;+ Ok(ctl().island_view())+}++#[tauri::command]+pub fn whatsapp_open(window: WebviewWindow, chat: String) -> Result<(), String> {+ only(&window, crate::island::WINDOW_LABEL)?;+ open(&chat);+ Ok(())+}++#[tauri::command]+pub fn whatsapp_close(window: WebviewWindow, chat: String) -> Result<(), String> {+ only(&window, crate::island::WINDOW_LABEL)?;+ close(&chat);+ Ok(())+}++/// Enter or the send button in the island's card: the only way a message leaves Coucou.+#[tauri::command]+pub async fn whatsapp_send(window: WebviewWindow, chat: String, text: String) -> Result<bool, String> {+ only(&window, crate::island::WINDOW_LABEL)?;+ Ok(send(&chat, &text).await)+}++#[tauri::command]+pub fn whatsapp_ignore(window: WebviewWindow, chat: String) -> Result<(), String> {+ if window.label() != crate::island::WINDOW_LABEL {+ only(&window, crate::HUB_LABEL)?;+ }+ let chat = chat_from_entry(&chat).ok_or("not a chat")?;+ ignore(&chat);+ Ok(())+}++#[tauri::command]+pub fn whatsapp_unignore(window: WebviewWindow, chat: String) -> Result<(), String> {+ only(&window, crate::HUB_LABEL)?;+ {+ let mut c = ctl();+ c.prefs.ignored.retain(|x| x != &chat);+ prefs::save(&c.prefs);+ }+ changed();+ Ok(())+}++#[tauri::command]+pub fn whatsapp_settings(window: WebviewWindow) -> Result<SettingsView, String> {+ only(&window, crate::HUB_LABEL)?;+ Ok(ctl().settings_view())+}++/// The switches: on/off, mute groups, read receipts on opening.+#[tauri::command]+pub fn whatsapp_set_options(window: WebviewWindow, enabled: bool, mute_groups: bool, mark_read_on_open: bool) -> Result<(), String> {+ only(&window, crate::HUB_LABEL)?;+ let restart = {+ let mut c = ctl();+ let restart = c.prefs.enabled != enabled;+ c.prefs.enabled = enabled;+ c.prefs.mute_groups = mute_groups;+ c.prefs.mark_read_on_open = mark_read_on_open;+ prefs::save(&c.prefs);+ restart+ };+ if restart { settings_changed() } else { changed() }+ Ok(())+}++/// Advanced → Save: the gateway, its address and credential (None keeps the stored one, "" removes+/// it), the webhook's port, and GOWA started by Coucou.+#[tauri::command]+pub fn whatsapp_save_gateway(+ window: WebviewWindow,+ gateway: String,+ url: String,+ credential: Option<String>,+ port: u16,+ auto_start: bool,+ gowa_path: String,+) -> Result<(), String> {+ only(&window, crate::HUB_LABEL)?;+ let url = url.trim().to_string();+ if url.len() > 512 || credential.as_ref().is_some_and(|c| c.len() > 1024) {+ return Err("too long".into());+ }+ crate::secrets::set_internal(URL_KEY, &url)?;+ if let Some(credential) = &credential {+ crate::secrets::set_internal(CREDENTIAL_KEY, credential.trim())?;+ }+ {+ let mut c = ctl();+ c.url = url;+ if let Some(credential) = credential {+ c.has_credential = !credential.trim().is_empty();+ }+ let mut next = c.prefs.clone();+ next.gateway = gateway;+ if (1024..=65535).contains(&port) {+ next.port = port;+ }+ next.auto_start = auto_start;+ next.gowa_path = gowa_path;+ c.prefs = next.cleaned();+ prefs::save(&c.prefs);+ }+ settings_changed();+ Ok(())+}++#[tauri::command]+pub async fn whatsapp_test(window: WebviewWindow) -> Result<TestResult, String> {+ only(&window, crate::HUB_LABEL)?;+ Ok(test_connection().await)+}++/// "Install WhatsApp" / "Update": the one network call to GitHub, on this click only.+#[tauri::command]+pub fn whatsapp_install(window: WebviewWindow) -> Result<(), String> {+ only(&window, crate::HUB_LABEL)?;+ install();+ Ok(())+}++#[cfg(test)]+mod tests {+ use super::*;++ fn msg(id: &str, chat: &str, text: &str) -> Message {+ Message::new(id, chat, chat, text, gateway::now_ms())+ }++ fn fresh_ctl() -> Ctl {+ Ctl {+ prefs: Prefs::default(),+ url: String::new(),+ has_credential: false,+ pill_active: true,+ provider: None,+ generation: 0,+ link: LinkState::Off,+ webhook: WebhookState::Off,+ secret: String::new(),+ qr: None,+ qr_expiry: None,+ me: None,+ inbox: Inbox::default(),+ listener: None,+ tick: 0,+ refreshing: false,+ polling: false,+ backfilled: false,+ last_webhook: None,+ last_poll_ms: 0,+ naming: HashSet::new(),+ open_chat: None,+ rate: RateLimit::default(),+ failures: 0,+ down: false,+ sending: false,+ send_error: None,+ install: Step::Idle,+ }+ }++ #[test]+ fn what_arrives_is_announced_by_name_only_and_never_in_the_open_chat() {+ let mut c = fresh_ctl();+ let mut m = msg("1", "[email protected]", "secret text");+ m.sender_name = "Marie".into();+ let (fresh, groups) = ingest(&mut c, vec![m]);+ assert_eq!(fresh.as_deref(), Some("Marie"));+ assert!(groups.is_empty());+ // Open on screen: seen, not unread, not announced.+ c.open_chat = Some("[email protected]".into());+ let (fresh, _) = ingest(&mut c, vec![msg("2", "[email protected]", "again")]);+ assert_eq!(fresh, None);+ assert_eq!(c.inbox.conversations["[email protected]"].unread, 0, "read on screen");+ assert_eq!(c.inbox.conversations["[email protected]"].messages.len(), 2);+ c.open_chat = None;+ let (fresh, _) = ingest(&mut c, vec![msg("2b", "[email protected]", "and again")]);+ assert_eq!(fresh.as_deref(), Some("Marie"), "the person still names the chat");+ // A muted group without a mention stays quiet, but is asked its name once.+ let (fresh, groups) = ingest(&mut c, vec![msg("3", "[email protected]", "hi all")]);+ assert_eq!(fresh, None);+ assert_eq!(groups, ["[email protected]"]);+ let (_, groups) = ingest(&mut c, vec![msg("4", "[email protected]", "hi again")]);+ assert!(groups.is_empty(), "asked once");+ // The island only sees the visible conversations.+ let view = c.island_view();+ assert_eq!(view.conversations.len(), 1);+ assert_eq!(view.unread, 1);+ // Ignored: never shown again.+ c.prefs.ignored = vec!["[email protected]".into()];+ let (fresh, _) = ingest(&mut c, vec![msg("5", "[email protected]", "x")]);+ assert_eq!(fresh, None);+ assert!(c.island_view().conversations.is_empty());+ }++ #[test]+ fn errors_light_the_pill_on_the_second_failure_only() {+ let mut c = fresh_ctl();+ apply(&mut c, WaError::NotLoggedIn);+ assert_eq!((c.link.clone(), c.failures, c.down), (LinkState::NeedsQr, 0, false));+ apply(&mut c, WaError::Unauthorized);+ assert_eq!((c.failures, c.down), (1, false));+ apply(&mut c, WaError::Refused("NOPE".into()));+ assert_eq!((c.link.clone(), c.failures, c.down), (LinkState::Failed { detail: "NOPE".into() }, 2, true));+ }++ #[test]+ fn mark_read_sends_a_receipt_only_for_something_unread() {+ let mut c = fresh_ctl();+ ingest(&mut c, vec![msg("a", "[email protected]", "1"), msg("b", "[email protected]", "2")]);+ assert_eq!(mark_read(&mut c, "[email protected]"), Some(("[email protected]".into(), Some("b".into()))));+ assert_eq!(c.inbox.conversations["[email protected]"].unread, 0);+ assert_eq!(mark_read(&mut c, "[email protected]"), None, "nothing new: no receipt");+ assert_eq!(mark_read(&mut c, "[email protected]"), None);+ }++ #[test]+ fn the_gateways_secrets_never_reach_a_webview() {+ for key in [URL_KEY, CREDENTIAL_KEY, SECRET_KEY] {+ assert!(crate::secrets::is_internal(key), "{key}");+ assert!(!crate::secrets::KNOWN_KEYS.contains(&key), "{key}");+ assert!(crate::secrets::set(key, "x").is_err(), "{key}: secret_set must refuse it");+ assert!(!crate::secrets::present(key), "{key}");+ }+ assert_eq!(crate::secrets::INTERNAL_KEYS.iter().filter(|k| k.starts_with("whatsapp-")).count(), 3);+ }++ #[test]+ fn ignore_entries() {+ assert_eq!(chat_from_entry("+33 6 12 34 56 78").as_deref(), Some("[email protected]"));+ assert_eq!(chat_from_entry(" [email protected] ").as_deref(), Some("[email protected]"));+ assert_eq!(chat_from_entry("abc"), None);+ assert_eq!(chat_from_entry("a [email protected]"), None);+ assert_eq!(chat_from_entry(""), None);+ }++ #[test]+ fn views_say_codes_never_sentences() {+ let c = fresh_ctl();+ let json = serde_json::to_value(c.island_view()).unwrap();+ assert_eq!(json["link"]["state"], "off");+ let json = serde_json::to_value(c.settings_view()).unwrap();+ assert_eq!(json["webhook"]["state"], "off");+ assert_eq!(json["install"]["step"], "idle");+ assert_eq!(json["defaultUrl"], "http://127.0.0.1:3000");+ assert_eq!(serde_json::to_value(SendError::Refused { detail: "x".into() }).unwrap()["code"], "refused");+ assert_eq!(serde_json::to_value(WebhookState::PortBusy { port: 1 }).unwrap()["state"], "portBusy");+ assert_eq!(serde_json::to_value(LinkState::NeedsQr).unwrap()["state"], "needsQr");+ assert_eq!(serde_json::to_value(TestResult::Connected { who: "+1".into() }).unwrap()["result"], "connected");+ }+}diff --git a/windows/src-tauri/src/whatsapp/model.rs b/windows/src-tauri/src/whatsapp/model.rsnew file mode 100644index 00000000..19921676--- /dev/null+++ b/windows/src-tauri/src/whatsapp/model.rs@@ -0,0 +1,559 @@+// WhatsApp in the island: what Coucou keeps of the conversations, in memory only, and the+// rules that decide what reaches the pill. Port of WhatsAppModels.swift (the Mac's spec):+// same rules, same limits. Nothing here is ever written to disk or to a log.++use std::collections::{BTreeSet, HashMap, HashSet, VecDeque};+use std::time::{Duration, Instant};++use serde::Serialize;++/// What a message holds besides text: only a label is shown, the media itself is never fetched.+#[derive(Clone, Debug, PartialEq, Eq, Serialize)]+#[serde(tag = "kind", rename_all = "camelCase")]+pub enum Media {+ None,+ Image,+ Video,+ Audio { seconds: Option<u32> },+ Voice { seconds: Option<u32> },+ Document { name: Option<String> },+ Sticker,+ Location,+ Contact,+ Other,+}++#[derive(Clone, Debug, PartialEq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Message {+ pub id: String,+ /// The conversation: a person (…@s.whatsapp.net, …@lid, …@c.us) or a group (…@g.us).+ pub chat: String,+ /// Who wrote it (in a group, the member; in a private chat, the chat itself).+ pub sender: String,+ pub sender_name: String,+ pub text: String,+ pub media: Media,+ /// Milliseconds since 1970.+ pub date: i64,+ pub from_me: bool,+ /// The message mentions this account (only meaningful in groups).+ pub mentions_me: bool,+ /// Set by the gateway when the chat name came with the message.+ #[serde(skip)]+ pub chat_name: Option<String>,+}++impl Message {+ pub fn new(id: &str, chat: &str, sender: &str, text: &str, date: i64) -> Self {+ Message {+ id: id.into(),+ chat: chat.into(),+ sender: sender.into(),+ sender_name: String::new(),+ text: text.into(),+ media: Media::None,+ date,+ from_me: false,+ mentions_me: false,+ chat_name: None,+ }+ }+}++#[derive(Clone, Debug, PartialEq, Serialize)]+#[serde(rename_all = "camelCase")]+pub struct Conversation {+ /// The chat JID.+ pub id: String,+ pub name: String,+ pub is_group: bool,+ /// Newest last, the last `Inbox::KEEP` only.+ pub messages: Vec<Message>,+ pub unread: u32,+ pub last_activity: i64,+}++/// What the user chose in Settings → WhatsApp.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct Filters {+ /// Groups stay quiet unless the message mentions you.+ pub mute_groups: bool,+ /// Chats never shown (JIDs).+ pub ignored: BTreeSet<String>,+}++impl Default for Filters {+ fn default() -> Self {+ Filters { mute_groups: true, ignored: BTreeSet::new() }+ }+}++// ── JIDs ──────────────────────────────────────────────────────────────────────++pub fn is_group(jid: &str) -> bool {+ jid.ends_with("@g.us")+}++fn user_part(jid: &str) -> &str {+ let user = jid.split('@').next().unwrap_or(jid);+ user.split(':').next().unwrap_or(user)+}++/// "[email protected]" → "+33612345678": the digits with a plus.+pub fn display_number(jid: &str) -> String {+ let digits = user_part(jid);+ if !digits.is_empty() && digits.bytes().all(|b| b.is_ascii_digit()) {+ format!("+{digits}")+ } else {+ digits.to_string()+ }+}++/// The same person under its several forms: "33612345678:[email protected]" and+/// "[email protected]" are one chat.+pub fn normalized(jid: &str) -> String {+ let Some((user, server)) = jid.split_once('@') else { return jid.to_string() };+ let user = user.split(':').next().unwrap_or(user);+ let server = if server == "c.us" { "s.whatsapp.net" } else { server };+ format!("{user}@{server}")+}++/// The user part's digits: "33612345678:[email protected]" → "33612345678".+pub fn digits(jid: &str) -> String {+ user_part(jid).chars().filter(char::is_ascii_digit).collect()+}++/// Two ids of the same person, whatever their server part (@c.us, @s.whatsapp.net, a bare number).+pub fn same_user(a: &str, b: &str) -> bool {+ let (x, y) = (digits(a), digits(b));+ !x.is_empty() && x == y+}++/// "@33612345678" in the text, for this account's number (how GOWA shows a mention of you).+pub fn text_mentions(text: &str, me: Option<&str>) -> bool {+ let Some(me) = me else { return false };+ let d = digits(me);+ d.len() >= 6 && text.contains(&format!("@{d}"))+}++// ── The inbox ─────────────────────────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Outcome {+ Duplicate,+ Ignored,+ Quiet,+ Notify,+}++/// The conversations, grouped by chat: one entry per conversation, never one per message.+#[derive(Default)]+pub struct Inbox {+ pub conversations: HashMap<String, Conversation>,+ seen: HashSet<String>,+ /// The same ids in arrival order, so the oldest are the ones forgotten.+ seen_order: VecDeque<String>,+}++impl Inbox {+ pub const KEEP: usize = 20;++ /// Newest activity first.+ pub fn sorted(&self) -> Vec<&Conversation> {+ let mut list: Vec<&Conversation> = self.conversations.values().collect();+ list.sort_by(|a, b| b.last_activity.cmp(&a.last_activity).then_with(|| a.id.cmp(&b.id)));+ list+ }++ #[cfg(test)]+ pub fn total_unread(&self) -> u32 {+ self.conversations.values().map(|c| c.unread).sum()+ }++ /// Adds a message to its conversation. `Notify` when it should reach you (Mochi reacts),+ /// `Quiet` when it is kept but stays silent (a muted group, your own message).+ /// `history`: an older message loaded on demand: kept, never counted as unread, never announced.+ pub fn add(&mut self, message: Message, filters: &Filters, name: Option<&str>, history: bool) -> Outcome {+ if self.seen.contains(&message.id) {+ return Outcome::Duplicate;+ }+ let chat = normalized(&message.chat);+ if filters.ignored.contains(&chat) {+ return Outcome::Ignored;+ }+ self.seen.insert(message.id.clone());+ self.seen_order.push_back(message.id.clone());+ if self.seen_order.len() > 2_000 {+ for _ in 0..1_000 {+ if let Some(id) = self.seen_order.pop_front() {+ self.seen.remove(&id);+ }+ }+ }++ let group = is_group(&chat);+ let number = display_number(&chat);+ // In a private chat the other person names it: never your own name on your own message.+ let person_name = if group || message.from_me || message.sender_name.is_empty() {+ None+ } else {+ Some(message.sender_name.clone())+ };+ let given = name.map(str::to_string).or_else(|| message.chat_name.clone()).filter(|n| !n.is_empty());+ let mut conversation = self.conversations.remove(&chat).unwrap_or_else(|| Conversation {+ id: chat.clone(),+ name: given.clone().or_else(|| person_name.clone()).unwrap_or_else(|| number.clone()),+ is_group: group,+ messages: Vec::new(),+ unread: 0,+ last_activity: message.date,+ });+ if let Some(n) = given {+ conversation.name = n;+ } else if conversation.name == number {+ if let Some(p) = person_name {+ conversation.name = p;+ }+ }+ let date = message.date;+ let from_me = message.from_me;+ let mentions = message.mentions_me;+ let mut msg = message;+ msg.chat = chat.clone();+ conversation.messages.push(msg);+ conversation.messages.sort_by_key(|m| m.date);+ if conversation.messages.len() > Self::KEEP {+ let extra = conversation.messages.len() - Self::KEEP;+ conversation.messages.drain(0..extra);+ }+ conversation.last_activity = conversation.last_activity.max(date);++ let outcome = if history {+ Outcome::Quiet+ } else if from_me {+ // You answered from the phone: it is read there.+ conversation.unread = 0;+ Outcome::Quiet+ } else {+ conversation.unread += 1;+ if group && filters.mute_groups && !mentions {+ Outcome::Quiet+ } else {+ Outcome::Notify+ }+ };+ self.conversations.insert(chat, conversation);+ outcome+ }++ /// The conversations the pill lists: muted groups without unread mentions stay out of it.+ pub fn visible(&self, filters: &Filters) -> Vec<&Conversation> {+ self.sorted()+ .into_iter()+ .filter(|c| {+ !filters.ignored.contains(&c.id)+ && (!c.is_group || !filters.mute_groups || c.messages.iter().any(|m| m.mentions_me && !m.from_me))+ })+ .collect()+ }++ /// Unread messages in the conversations the pill shows.+ pub fn visible_unread(&self, filters: &Filters) -> u32 {+ self.visible(filters).iter().map(|c| c.unread).sum()+ }++ pub fn remove(&mut self, chat: &str) {+ self.conversations.remove(&normalized(chat));+ }++ pub fn mark_read(&mut self, chat: &str) {+ if let Some(c) = self.conversations.get_mut(&normalized(chat)) {+ c.unread = 0;+ }+ }++ pub fn rename(&mut self, chat: &str, name: &str) {+ if name.is_empty() {+ return;+ }+ if let Some(c) = self.conversations.get_mut(&normalized(chat)) {+ c.name = name.to_string();+ }+ }++ /// Everything goes (Coucou quits, WhatsApp turned off).+ pub fn clear(&mut self) {+ self.conversations.clear();+ self.seen.clear();+ self.seen_order.clear();+ }+}++// ── Replies ───────────────────────────────────────────────────────────────────++#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Refusal {+ Empty,+ TooLong,+ NotAConversation,+}++/// The gateways' own cap (OpenWA's send-text takes 4,096 characters at most).+pub const MAX_REPLY: usize = 4096;++/// What may be sent from the island: a reply, in a conversation already there, one at a time.+pub fn check_reply(text: &str, chat: &str, inbox: &Inbox) -> Option<Refusal> {+ let trimmed = text.trim();+ if trimmed.is_empty() {+ return Some(Refusal::Empty);+ }+ if trimmed.chars().count() > MAX_REPLY {+ return Some(Refusal::TooLong);+ }+ // Never a new chat, never a list of recipients: only a conversation that wrote to you.+ if !inbox.conversations.contains_key(&normalized(chat)) {+ return Some(Refusal::NotAConversation);+ }+ None+}++/// A few sends a minute at most, whatever is clicked: Coucou is no bulk sender.+pub struct RateLimit {+ limit: usize,+ window: Duration,+ sent: VecDeque<Instant>,+}++impl RateLimit {+ pub fn new(limit: usize, window: Duration) -> Self {+ RateLimit { limit, window, sent: VecDeque::new() }+ }++ pub fn allow(&mut self, now: Instant) -> bool {+ while self.sent.front().is_some_and(|t| now.duration_since(*t) > self.window) {+ self.sent.pop_front();+ }+ if self.sent.len() >= self.limit {+ return false;+ }+ self.sent.push_back(now);+ true+ }+}++impl Default for RateLimit {+ fn default() -> Self {+ RateLimit::new(6, Duration::from_secs(60))+ }+}++// ── The webhook's HTTP request ────────────────────────────────────────────────++/// One HTTP request read from the local socket: enough of HTTP/1.1 for a gateway's webhook.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct HttpRequest {+ pub method: String,+ pub path: String,+ /// Lowercased names.+ pub headers: HashMap<String, String>,+ pub body: Vec<u8>,+}++#[derive(Debug, PartialEq, Eq)]+pub enum Parse {+ Incomplete,+ Invalid,+ Done(HttpRequest),+}++pub const MAX_HEAD: usize = 16_384;+pub const MAX_BODY: usize = 1_000_000;++/// Parses what arrived so far; `Incomplete` until the whole body is there.+pub fn parse_request(data: &[u8], max_body: usize) -> Parse {+ let Some(end) = data.windows(4).position(|w| w == b"\r\n\r\n") else {+ return if data.len() > MAX_HEAD { Parse::Invalid } else { Parse::Incomplete };+ };+ let Ok(head) = std::str::from_utf8(&data[..end]) else { return Parse::Invalid };+ let mut lines = head.split("\r\n");+ let first: Vec<&str> = lines.next().unwrap_or("").split(' ').filter(|s| !s.is_empty()).collect();+ if first.len() < 2 {+ return Parse::Invalid;+ }+ let mut headers = HashMap::new();+ for line in lines {+ if let Some((name, value)) = line.split_once(':') {+ headers.insert(name.trim().to_ascii_lowercase(), value.trim().to_string());+ }+ }+ let length = match headers.get("content-length") {+ None => 0usize,+ Some(v) => match v.parse::<usize>() {+ Ok(n) => n,+ Err(_) => return Parse::Invalid,+ },+ };+ if length > max_body {+ return Parse::Invalid;+ }+ let start = end + 4;+ if data.len() - start < length {+ return Parse::Incomplete;+ }+ Parse::Done(HttpRequest {+ method: first[0].to_string(),+ path: first[1].to_string(),+ headers,+ body: data[start..start + length].to_vec(),+ })+}++pub fn response(status: u16, reason: &str) -> Vec<u8> {+ format!("HTTP/1.1 {status} {reason}\r\nContent-Length: 0\r\nConnection: close\r\n\r\n").into_bytes()+}++/// Compares two strings in constant time (signatures).+pub fn constant_time_eq(a: &str, b: &str) -> bool {+ let (x, y) = (a.as_bytes(), b.as_bytes());+ if x.len() != y.len() {+ return false;+ }+ x.iter().zip(y).fold(0u8, |acc, (p, q)| acc | (p ^ q)) == 0+}++#[cfg(test)]+mod tests {+ use super::*;++ fn msg(id: &str, chat: &str, at: i64) -> Message {+ let mut m = Message::new(id, chat, chat, "hi", 1_800_000_000_000 + at * 1000);+ m.sender_name = "Marie".into();+ m+ }++ #[test]+ fn one_conversation_per_chat() {+ let mut inbox = Inbox::default();+ let f = Filters::default();+ assert_eq!(inbox.add(msg("1", "[email protected]", 0), &f, None, false), Outcome::Notify);+ inbox.add(msg("2", "[email protected]", 5), &f, None, false);+ inbox.add(msg("3", "[email protected]", 3), &f, None, false);+ assert_eq!(inbox.conversations.len(), 2);+ assert_eq!(inbox.conversations["[email protected]"].unread, 2);+ assert_eq!(inbox.sorted()[0].id, "[email protected]");+ assert_eq!(inbox.add(msg("2", "[email protected]", 0), &f, None, false), Outcome::Duplicate);+ // The same person under another form.+ assert_eq!(inbox.add(msg("4", "33600000001:[email protected]", 9), &f, None, false), Outcome::Notify);+ assert_eq!(inbox.conversations.len(), 2);+ inbox.mark_read("[email protected]");+ assert_eq!(inbox.conversations["[email protected]"].unread, 0);+ assert_eq!(inbox.total_unread(), 1);+ let mut mine = msg("5", "[email protected]", 10);+ mine.from_me = true;+ assert_eq!(inbox.add(mine, &f, None, false), Outcome::Quiet);+ assert_eq!(inbox.conversations["[email protected]"].unread, 0, "my own message reads the chat");+ }++ #[test]+ fn groups_stay_quiet_unless_they_mention_me_and_ignored_chats_never_come_in() {+ let mut inbox = Inbox::default();+ let mut f = Filters::default();+ let group = "[email protected]";+ let mut g1 = msg("g1", group, 0);+ g1.sender = "[email protected]".into();+ assert_eq!(inbox.add(g1, &f, None, false), Outcome::Quiet);+ assert!(inbox.visible(&f).is_empty());+ let mut g2 = msg("g2", group, 1);+ g2.mentions_me = true;+ assert_eq!(inbox.add(g2, &f, None, false), Outcome::Notify);+ assert_eq!(inbox.visible(&f).len(), 1);+ f.ignored.insert("[email protected]".into());+ assert_eq!(inbox.add(msg("i1", "[email protected]", 0), &f, None, false), Outcome::Ignored);+ f.mute_groups = false;+ assert_eq!(inbox.add(msg("g3", group, 2), &f, None, false), Outcome::Notify);+ }++ #[test]+ fn only_the_last_twenty_messages_are_kept() {+ let mut inbox = Inbox::default();+ for i in 0..30 {+ inbox.add(msg(&format!("m{i}"), "[email protected]", i), &Filters::default(), None, false);+ }+ let c = &inbox.conversations["[email protected]"];+ assert_eq!(c.messages.len(), 20);+ assert_eq!(c.messages.last().unwrap().id, "m29");+ }++ #[test]+ fn the_other_person_names_a_private_chat_and_history_stays_quiet() {+ let mut inbox = Inbox::default();+ let f = Filters::default();+ let chat = "[email protected]";+ let mut mine = Message::new("o1", chat, "me", "yo", 1);+ mine.sender_name = "Louis".into();+ mine.from_me = true;+ inbox.add(mine, &f, None, false);+ assert_eq!(inbox.conversations[chat].name, "+33600000003");+ let mut theirs = Message::new("o2", chat, "x", "yo", 2);+ theirs.sender_name = "Marie".into();+ inbox.add(theirs, &f, None, false);+ assert_eq!(inbox.conversations[chat].name, "Marie");+ let before = inbox.conversations[chat].unread;+ let old = Message::new("h1", chat, "x", "old", 0);+ assert_eq!(inbox.add(old, &f, None, true), Outcome::Quiet);+ assert_eq!(inbox.conversations[chat].unread, before);+ assert_eq!(inbox.conversations[chat].messages[0].id, "h1");+ }++ #[test]+ fn ids_and_mentions() {+ assert!(same_user("[email protected]", "628:[email protected]"));+ assert!(!same_user("[email protected]", "[email protected]"));+ assert!(text_mentions("hey @33612345678!", Some("[email protected]")));+ assert!(!text_mentions("hey @336", Some("[email protected]")));+ assert!(!text_mentions("hey @33612345678", None));+ assert_eq!(display_number("33612345678:[email protected]"), "+33612345678");+ assert_eq!(display_number("abc@lid"), "abc");+ assert_eq!(normalized("33612345678:[email protected]"), "[email protected]");+ assert_eq!(normalized("nojid"), "nojid");+ }++ #[test]+ fn replies_only_to_a_conversation_and_a_few_a_minute() {+ let mut inbox = Inbox::default();+ inbox.add(msg("1", "[email protected]", 0), &Filters::default(), None, false);+ assert_eq!(check_reply(" ", "[email protected]", &inbox), Some(Refusal::Empty));+ assert_eq!(check_reply(&"a".repeat(4097), "[email protected]", &inbox), Some(Refusal::TooLong));+ assert_eq!(check_reply("ok", "[email protected]", &inbox), Some(Refusal::NotAConversation));+ assert_eq!(check_reply("ok", "[email protected]", &inbox), None);+ let mut rate = RateLimit::new(2, Duration::from_secs(60));+ let now = Instant::now();+ assert!(rate.allow(now));+ assert!(rate.allow(now));+ assert!(!rate.allow(now));+ assert!(rate.allow(now + Duration::from_secs(61)));+ }++ #[test]+ fn the_webhook_request_is_read_whole_and_bounded() {+ let req = b"POST /whatsapp HTTP/1.1\r\nHost: 127.0.0.1\r\nX-Hub-Signature-256: sha256=ab\r\nContent-Length: 5\r\n\r\nhello";+ match parse_request(req, MAX_BODY) {+ Parse::Done(r) => {+ assert_eq!(r.method, "POST");+ assert_eq!(r.path, "/whatsapp");+ assert_eq!(r.headers["x-hub-signature-256"], "sha256=ab");+ assert_eq!(r.body, b"hello");+ }+ other => panic!("{other:?}"),+ }+ assert_eq!(parse_request(&req[..req.len() - 2], MAX_BODY), Parse::Incomplete);+ assert_eq!(parse_request(b"POST / HTTP/1.1\r\nContent-Length: 999999999\r\n\r\n", MAX_BODY), Parse::Invalid);+ assert_eq!(parse_request(b"POST / HTTP/1.1\r\nContent-Length: -1\r\n\r\n", MAX_BODY), Parse::Invalid);+ assert_eq!(parse_request(&vec![b'a'; MAX_HEAD + 1], MAX_BODY), Parse::Invalid);+ assert_eq!(parse_request(b"GARBAGE\r\n\r\n", MAX_BODY), Parse::Invalid);+ assert!(constant_time_eq("abc", "abc"));+ assert!(!constant_time_eq("abc", "abd"));+ assert!(!constant_time_eq("abc", "ab"));+ }+}diff --git a/windows/src-tauri/src/whatsapp/prefs.rs b/windows/src-tauri/src/whatsapp/prefs.rsnew file mode 100644index 00000000..ca38c3be--- /dev/null+++ b/windows/src-tauri/src/whatsapp/prefs.rs@@ -0,0 +1,106 @@+// WhatsApp's harmless choices (Settings → Integrations → WhatsApp), in whatsapp.json next to+// settings.json. Owned by Rust: the webview changes them through `whatsapp_set_prefs` only.+// The gateway's address, its credential and the webhook's secret are in the credential store,+// never here; no message, name or number is ever written here either (an ignored chat's id+// is the one exception, as on the Mac: it is what "Ignore" has to remember).++use std::path::PathBuf;++use serde::{Deserialize, Serialize};++pub const DEFAULT_PORT: u16 = 47823;++#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct Prefs {+ pub enabled: bool,+ /// "gowa" or "openwa".+ pub gateway: String,+ /// The webhook's port on 127.0.0.1.+ pub port: u16,+ /// Read receipts when a conversation is opened (on), or only when replying (off).+ pub mark_read_on_open: bool,+ pub mute_groups: bool,+ /// Normalized chat ids.+ pub ignored: Vec<String>,+ /// Coucou starts the GOWA binary at `gowa_path` itself.+ pub auto_start: bool,+ pub gowa_path: String,+ /// GOWA's version once installed by Coucou.+ pub gowa_version: Option<String>,+}++impl Default for Prefs {+ fn default() -> Self {+ Prefs {+ enabled: false,+ gateway: "gowa".into(),+ port: DEFAULT_PORT,+ mark_read_on_open: true,+ mute_groups: true,+ ignored: vec![],+ auto_start: false,+ gowa_path: String::new(),+ gowa_version: None,+ }+ }+}++impl Prefs {+ /// What a file (or the webview) may hold, brought back inside the rules.+ pub fn cleaned(mut self) -> Prefs {+ if self.gateway != "openwa" {+ self.gateway = "gowa".into();+ }+ if self.port < 1024 {+ self.port = DEFAULT_PORT;+ }+ self.ignored.retain(|id| !id.is_empty() && id.len() <= 128);+ self.ignored.sort();+ self.ignored.dedup();+ self.ignored.truncate(500);+ self.gowa_path = self.gowa_path.trim().to_string();+ self+ }+}++fn path() -> PathBuf {+ crate::platform::config_dir().join("whatsapp.json")+}++pub fn load() -> Prefs {+ std::fs::read(path()).ok().and_then(|b| serde_json::from_slice::<Prefs>(&b).ok()).unwrap_or_default().cleaned()+}++pub fn save(prefs: &Prefs) {+ let path = path();+ let Some(dir) = path.parent() else { return };+ let temp = path.with_extension(format!("json.coucou-{}", std::process::id()));+ let written = crate::platform::ensure_private_dir(dir)+ .and_then(|()| serde_json::to_vec_pretty(prefs).map_err(std::io::Error::other))+ .and_then(|json| std::fs::write(&temp, json))+ .and_then(|()| std::fs::rename(&temp, &path));+ if let Err(err) = written {+ let _ = std::fs::remove_file(&temp);+ crate::log::line(format!("whatsapp: could not save whatsapp.json: {err}"));+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn defaults_and_cleaning() {+ let p: Prefs = serde_json::from_str("{}").unwrap();+ assert_eq!(p, Prefs::default());+ assert!(!p.enabled && p.mute_groups && p.mark_read_on_open && p.port == DEFAULT_PORT && p.gateway == "gowa");+ let odd: Prefs = serde_json::from_str(r#"{"gateway":"evil","port":80,"ignored":["b","a","b",""],"gowaPath":" /x/gowa "}"#).unwrap();+ let odd = odd.cleaned();+ assert_eq!((odd.gateway.as_str(), odd.port), ("gowa", DEFAULT_PORT));+ assert_eq!(odd.ignored, ["a", "b"]);+ assert_eq!(odd.gowa_path, "/x/gowa");+ let json = serde_json::to_string(&Prefs::default()).unwrap();+ assert!(json.contains("\"markReadOnOpen\":true") && json.contains("\"muteGroups\":true"));+ }+}diff --git a/windows/src-tauri/src/whatsapp/process.rs b/windows/src-tauri/src/whatsapp/process.rsnew file mode 100644index 00000000..81e2e1b9--- /dev/null+++ b/windows/src-tauri/src/whatsapp/process.rs@@ -0,0 +1,189 @@+// GOWA started by Coucou ("Start GOWA automatically", or after "Install WhatsApp"): a child of+// Coucou, on the address set in Settings, stopped when Coucou quits. Port of WhatsAppGOWAProcess.swift.++use std::path::{Path, PathBuf};+use std::process::{Child, Command, Stdio};+use std::sync::Mutex;+use std::time::{Duration, Instant};++use reqwest::Url;++use super::gateway::gowa;++struct Running {+ child: Option<Child>,+ last_start: Option<Instant>,+ /// What the running GOWA was started with: changed, it is restarted; same, left alone.+ launched_with: Option<String>,+}++static STATE: Mutex<Running> = Mutex::new(Running { child: None, last_start: None, launched_with: None });++/// Where GOWA keeps its own WhatsApp session (its database, not Coucou's), and where Coucou+/// puts the binary it installs: the link survives restarts.+pub fn working_dir() -> PathBuf {+ crate::platform::local_dir().join("GOWA")+}++pub fn installed_binary() -> PathBuf {+ working_dir().join(if cfg!(windows) { "gowa.exe" } else { "gowa" })+}++/// A file Coucou may start: there, a file, and on Linux executable.+pub fn is_runnable(path: &Path) -> bool {+ let Ok(meta) = std::fs::metadata(path) else { return false };+ if !meta.is_file() {+ return false;+ }+ #[cfg(unix)]+ {+ use std::os::unix::fs::PermissionsExt;+ meta.permissions().mode() & 0o111 != 0+ }+ #[cfg(not(unix))]+ {+ path.extension().is_some_and(|e| e.eq_ignore_ascii_case("exe"))+ }+}++/// Only ever on this computer: an address elsewhere is someone else's gateway.+pub fn local_port(url: &Url) -> Option<u16> {+ let host = url.host_str()?.trim_start_matches('[').trim_end_matches(']');+ matches!(host, "127.0.0.1" | "localhost" | "::1").then(|| url.port_or_known_default()).flatten()+}++fn expand(path: &str) -> PathBuf {+ match path.strip_prefix("~/").or_else(|| path.strip_prefix("~\\")) {+ Some(rest) => crate::platform::home_dir().join(rest),+ None => PathBuf::from(path),+ }+}++pub fn is_running() -> bool {+ let mut s = STATE.lock().unwrap();+ match s.child.as_mut() {+ Some(child) => matches!(child.try_wait(), Ok(None)),+ None => false,+ }+}++/// Brings GOWA in line with Settings: started when asked to (and the gateway is GOWA on this+/// computer), restarted only when its binary, address or password changed, stopped otherwise. A+/// GOWA that keeps dying is started again once a minute at most. False when it can't run.+pub fn sync(wanted: bool, binary: &str, url: &str, credential: &str) -> bool {+ if !wanted {+ stop_now();+ return false;+ }+ let path = expand(binary.trim());+ let Some(port) = Url::parse(url.trim()).ok().as_ref().and_then(local_port) else {+ stop_now();+ return false;+ };+ if binary.trim().is_empty() || !is_runnable(&path) {+ crate::log::line("whatsapp: GOWA binary missing or not runnable");+ stop_now();+ return false;+ }+ let signature = [path.to_string_lossy().as_ref(), url.trim(), credential].join("\u{1F}");+ let mut s = STATE.lock().unwrap();+ let alive = s.child.as_mut().is_some_and(|c| matches!(c.try_wait(), Ok(None)));+ if alive {+ if s.launched_with.as_deref() == Some(&signature) {+ return true;+ }+ stop_locked(&mut s); // waits for it to let go of the port and its database+ } else if s.launched_with.as_deref() == Some(&signature) && s.last_start.is_some_and(|t| t.elapsed() < Duration::from_secs(60)) {+ return true;+ }+ let dir = working_dir();+ if let Err(err) = crate::platform::ensure_private_dir(&dir) {+ crate::log::line(format!("whatsapp: GOWA folder: {err}"));+ return false;+ }+ let mut cmd = Command::new(&path);+ cmd.args(gowa::launch_arguments(port))+ .current_dir(&dir)+ // GOWA's own output may name contacts or quote messages: it goes nowhere.+ .stdin(Stdio::null())+ .stdout(Stdio::null())+ .stderr(Stdio::null())+ // Its own web dashboard is not needed (Coucou is the interface).+ .env("APP_UI_ENABLED", "false");+ // The credential goes through the environment, not the command line (any user sees that).+ if credential.contains(':') {+ cmd.env("APP_BASIC_AUTH", credential);+ } else {+ cmd.env_remove("APP_BASIC_AUTH");+ }+ crate::platform::no_console(&mut cmd);+ match cmd.spawn() {+ Ok(child) => {+ crate::log::line(format!("whatsapp: GOWA started (pid {})", child.id()));+ s.child = Some(child);+ s.last_start = Some(Instant::now());+ s.launched_with = Some(signature);+ true+ }+ Err(err) => {+ crate::log::line(format!("whatsapp: GOWA could not start: {err}"));+ s.last_start = Some(Instant::now());+ false+ }+ }+}++fn stop_locked(s: &mut Running) {+ s.launched_with = None;+ let Some(mut child) = s.child.take() else { return };+ if !matches!(child.try_wait(), Ok(None)) {+ return;+ }+ // Asked politely first on Linux, so it closes its database; Windows has no such signal for a+ // console-less child, and GOWA writes its session as it goes.+ #[cfg(target_os = "linux")]+ unsafe {+ libc::kill(child.id() as libc::pid_t, libc::SIGTERM);+ }+ #[cfg(not(target_os = "linux"))]+ let _ = child.kill();+ let deadline = Instant::now() + Duration::from_secs(1);+ while Instant::now() < deadline {+ if !matches!(child.try_wait(), Ok(None)) {+ return;+ }+ std::thread::sleep(Duration::from_millis(50));+ }+ let _ = child.kill();+ let _ = child.wait();+}++/// Stops GOWA if Coucou started it, waiting a second at most (at quit, or before starting it+/// again so two never share its database).+pub fn stop_now() {+ stop_locked(&mut STATE.lock().unwrap());+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn only_on_this_computer() {+ let port = |u: &str| local_port(&Url::parse(u).unwrap());+ assert_eq!(port("http://127.0.0.1:3000"), Some(3000));+ assert_eq!(port("http://localhost:3001/"), Some(3001));+ assert_eq!(port("http://[::1]:3002"), Some(3002));+ assert_eq!(port("http://127.0.0.1"), Some(80));+ assert_eq!(port("http://192.168.1.4:3000"), None);+ assert_eq!(port("http://gowa.example.com:3000"), None);+ }++ #[test]+ fn nothing_runs_without_a_binary() {+ assert!(!sync(true, "", "http://127.0.0.1:3000", ""));+ assert!(!sync(true, "/no/such/gowa", "http://127.0.0.1:3000", ""));+ assert!(!is_running());+ assert!(!is_runnable(&std::env::temp_dir()), "a folder is not a binary");+ }+}diff --git a/windows/src-tauri/src/whatsapp/provider.rs b/windows/src-tauri/src/whatsapp/provider.rsnew file mode 100644index 00000000..39ba255c--- /dev/null+++ b/windows/src-tauri/src/whatsapp/provider.rs@@ -0,0 +1,451 @@+// The two local WhatsApp gateways Coucou can talk to (port of WhatsAppProvider.swift). Each call+// goes to the URL set in Settings (127.0.0.1 by default) and nowhere else: no redirect, no proxy,+// no cookie, every answer read with a ceiling. Nothing of a message is logged.++use std::time::Duration;++use reqwest::{Method, Url};+use serde_json::{json, Value};++use super::gateway::{self, gowa, openwa, Kind, Link, Status};+use super::model::{self, Message};++/// Ceiling for one answer of the gateway (a QR PNG is about 2 KB, a page of messages a few).+const MAX_ANSWER: usize = 2 * 1024 * 1024;++#[derive(Clone, Debug, PartialEq, Eq)]+pub enum WaError {+ /// Nothing answers at that URL.+ Unreachable,+ /// Wrong user:pass (GOWA) or API key (OpenWA).+ Unauthorized,+ /// The gateway answered with an error (its own message, never a message's content).+ Refused(String),+ /// WhatsApp isn't linked yet.+ NotLoggedIn,+}++/// Percent-encodes one path segment (letters, digits and `-._~@` kept).+pub fn path_component(s: &str) -> String {+ let mut out = String::with_capacity(s.len());+ for b in s.bytes() {+ if b.is_ascii_alphanumeric() || b"-._~@".contains(&b) {+ out.push(b as char);+ } else {+ out.push_str(&format!("%{b:02X}"));+ }+ }+ out+}++/// The gateway's address as typed: http(s), a host, no `user:pass@`, nothing after the path.+pub fn parse_base(raw: &str) -> Option<Url> {+ let url = Url::parse(raw.trim()).ok()?;+ if !matches!(url.scheme(), "http" | "https") || url.host_str().is_none_or(str::is_empty) {+ return None;+ }+ if !url.username().is_empty() || url.password().is_some() {+ return None;+ }+ Some(url)+}++/// `base`'s path + `path`, the query added; None when the result left the gateway.+pub fn endpoint(base: &Url, path: &str, query: &[(&str, String)]) -> Option<Url> {+ let mut url = base.clone();+ let prefix = base.path().trim_matches('/');+ let full = if prefix.is_empty() { path.to_string() } else { format!("/{prefix}{path}") };+ url.set_path(&full);+ url.set_query(None);+ url.set_fragment(None);+ if !query.is_empty() {+ let mut pairs = url.query_pairs_mut();+ for (k, v) in query {+ pairs.append_pair(k, v);+ }+ }+ (url.host_str() == base.host_str() && url.port_or_known_default() == base.port_or_known_default()).then_some(url)+}++/// HTTP to the gateway: never a redirect, never a proxy, nothing kept between calls.+pub struct Http {+ base: Url,+ headers: Vec<(&'static str, String)>,+ client: reqwest::Client,+}++impl Http {+ pub fn new(base: Url, headers: Vec<(&'static str, String)>) -> Result<Http, WaError> {+ let client = reqwest::Client::builder()+ .redirect(reqwest::redirect::Policy::none())+ .no_proxy()+ .connect_timeout(Duration::from_secs(5))+ .build()+ .map_err(|_| WaError::Unreachable)?;+ Ok(Http { base, headers, client })+ }++ pub async fn call(&self, method: Method, path: &str, query: &[(&str, String)], body: Option<Value>, timeout: Duration) -> Result<(Vec<u8>, u16), WaError> {+ let url = endpoint(&self.base, path, query).ok_or(WaError::Unreachable)?;+ let mut req = self.client.request(method, url.clone()).timeout(timeout).header("Accept", "application/json");+ for (k, v) in &self.headers {+ req = req.header(*k, v);+ }+ if let Some(body) = body {+ req = req.header("Content-Type", "application/json").body(body.to_string());+ }+ let response = req.send().await.map_err(|_| WaError::Unreachable)?;+ // Second lock: an answer from anywhere but the gateway is not one.+ if response.url().host_str() != url.host_str() || response.url().port_or_known_default() != url.port_or_known_default() {+ return Err(WaError::Unreachable);+ }+ let code = response.status().as_u16();+ let data = crate::net::read_capped(response, MAX_ANSWER).await.map_err(|_| WaError::Unreachable)?;+ Ok((data, code))+ }++ async fn get(&self, path: &str, query: &[(&str, String)]) -> Result<(Vec<u8>, u16), WaError> {+ self.call(Method::GET, path, query, None, Duration::from_secs(10)).await+ }+}++fn basic_auth(credential: &str) -> String {+ format!("Basic {}", gateway::base64(credential.as_bytes()))+}++/// Either gateway, behind one face.+pub enum Provider {+ Gowa { http: Http, device: tokio::sync::Mutex<Option<String>> },+ Openwa { http: Http, session: tokio::sync::Mutex<Option<String>> },+}++/// A QR to show: a `data:image/png;base64,…` URL and how long it stays valid.+pub struct Qr {+ pub data_url: String,+ pub seconds: u64,+}++impl Provider {+ pub fn new(kind: Kind, base: Url, credential: Option<String>) -> Result<Provider, WaError> {+ let credential = credential.filter(|c| !c.is_empty());+ Ok(match kind {+ Kind::Gowa => {+ let headers = credential.filter(|c| c.contains(':')).map(|c| vec![("Authorization", basic_auth(&c))]).unwrap_or_default();+ Provider::Gowa { http: Http::new(base, headers)?, device: Default::default() }+ }+ Kind::Openwa => {+ let headers = credential.map(|c| vec![("X-API-Key", c)]).unwrap_or_default();+ Provider::Openwa { http: Http::new(base, headers)?, session: Default::default() }+ }+ })+ }++ // ── GOWA ──++ fn gowa_check(data: &[u8], code: u16) -> Result<(), WaError> {+ if code == 401 && gowa::error_code(data).as_deref() != Some("AUTHENTICATION_ERROR") {+ return Err(WaError::Unauthorized);+ }+ if code == 401 {+ return Err(WaError::NotLoggedIn);+ }+ if !(200..300).contains(&code) {+ return Err(WaError::Refused(gowa::error_code(data).unwrap_or_else(|| format!("HTTP {code}"))));+ }+ Ok(())+ }++ async fn gowa_device(http: &Http, slot: &tokio::sync::Mutex<Option<String>>) -> Result<(String, Status), WaError> {+ let (data, code) = http.get("/devices", &[]).await?;+ Self::gowa_check(&data, code)?;+ if let Some((id, status)) = gowa::device(&data) {+ *slot.lock().await = Some(id.clone());+ return Ok((id, status));+ }+ let (made, made_code) = http.call(Method::POST, "/devices", &[], Some(json!({"device_id": "coucou"})), Duration::from_secs(10)).await?;+ Self::gowa_check(&made, made_code)?;+ *slot.lock().await = Some("coucou".into());+ Ok(("coucou".into(), Status { link: Link::NeedsQr, me: None }))+ }++ async fn gowa_id(http: &Http, slot: &tokio::sync::Mutex<Option<String>>) -> Result<String, WaError> {+ if let Some(id) = slot.lock().await.clone() {+ return Ok(id);+ }+ Ok(Self::gowa_device(http, slot).await?.0)+ }++ async fn gowa_scoped(http: &Http, slot: &tokio::sync::Mutex<Option<String>>, method: Method, path: &str, query: &[(&str, String)], body: Option<Value>) -> Result<Vec<u8>, WaError> {+ let id = Self::gowa_id(http, slot).await?;+ let mut q: Vec<(&str, String)> = query.to_vec();+ q.push(("device_id", id));+ let (data, code) = http.call(method, path, &q, body, Duration::from_secs(10)).await?;+ Self::gowa_check(&data, code)?;+ Ok(data)+ }++ // ── OpenWA ──++ fn openwa_check(data: &[u8], code: u16) -> Result<(), WaError> {+ if code == 401 || code == 403 {+ return Err(WaError::Unauthorized);+ }+ if !(200..300).contains(&code) {+ return Err(WaError::Refused(openwa::error_message(data).unwrap_or_else(|| format!("HTTP {code}"))));+ }+ Ok(())+ }++ async fn openwa_start(http: &Http, id: &str, fallback: openwa::Session) -> Result<openwa::Session, WaError> {+ let (started, code) = http.call(Method::POST, &format!("/api/sessions/{}/start", path_component(id)), &[], None, Duration::from_secs(10)).await?;+ Self::openwa_check(&started, code)?;+ Ok(serde_json::from_slice::<Value>(&started).ok().as_ref().and_then(openwa::session).unwrap_or(fallback))+ }++ async fn openwa_session(http: &Http, slot: &tokio::sync::Mutex<Option<String>>) -> Result<openwa::Session, WaError> {+ let (data, code) = http.get("/api/sessions", &[]).await?;+ Self::openwa_check(&data, code)?;+ let all = openwa::sessions(&data);+ let known = slot.lock().await.clone();+ let pick = all+ .iter()+ .find(|s| s.status == "ready")+ .or_else(|| all.iter().find(|s| Some(&s.id) == known.as_ref()))+ .or_else(|| all.iter().find(|s| s.name == "coucou"))+ .or(all.first())+ .cloned();+ if let Some(s) = pick {+ *slot.lock().await = Some(s.id.clone());+ if openwa::needs_start(&s.status) {+ return Self::openwa_start(http, &s.id.clone(), s).await;+ }+ return Ok(s);+ }+ let (made, made_code) = http.call(Method::POST, "/api/sessions", &[], Some(json!({"name": "coucou"})), Duration::from_secs(10)).await?;+ Self::openwa_check(&made, made_code)?;+ let s = serde_json::from_slice::<Value>(&made)+ .ok()+ .as_ref()+ .and_then(openwa::session)+ .ok_or_else(|| WaError::Refused("session".into()))?;+ *slot.lock().await = Some(s.id.clone());+ Self::openwa_start(http, &s.id.clone(), s).await+ }++ async fn openwa_id(http: &Http, slot: &tokio::sync::Mutex<Option<String>>) -> Result<String, WaError> {+ if let Some(id) = slot.lock().await.clone() {+ return Ok(id);+ }+ Ok(Self::openwa_session(http, slot).await?.id)+ }++ async fn openwa_scoped(http: &Http, slot: &tokio::sync::Mutex<Option<String>>, method: Method, path: &str, query: &[(&str, String)], body: Option<Value>) -> Result<Vec<u8>, WaError> {+ let id = Self::openwa_id(http, slot).await?;+ let (data, code) = http.call(method, &format!("/api/sessions/{}{path}", path_component(&id)), query, body, Duration::from_secs(10)).await?;+ Self::openwa_check(&data, code)?;+ Ok(data)+ }++ // ── The face ──++ /// The link to WhatsApp (sets up the gateway's device or session the first time).+ pub async fn status(&self) -> Result<Status, WaError> {+ match self {+ Provider::Gowa { http, device } => Ok(Self::gowa_device(http, device).await?.1),+ Provider::Openwa { http, session } => Ok(openwa::status(&Self::openwa_session(http, session).await?)),+ }+ }++ /// The QR to scan; None when there is none to show (already linked, not ready yet).+ pub async fn qr(&self) -> Result<Option<Qr>, WaError> {+ match self {+ Provider::Gowa { http, device } => {+ let id = Self::gowa_id(http, device).await?;+ // GOWA answers once WhatsApp has handed it the first code: a few seconds.+ let (data, code) = http.call(Method::GET, &format!("/devices/{}/login", path_component(&id)), &[], None, Duration::from_secs(45)).await?;+ if gowa::error_code(&data).as_deref() == Some("ALREADY_LOGGED_IN") {+ return Ok(None);+ }+ Self::gowa_check(&data, code)?;+ let Some((path, seconds)) = gowa::qr_path(&data) else { return Ok(None) };+ // The PNG is served by the gateway itself: fetched from the configured URL,+ // whatever host the link names.+ let (png, png_code) = http.get(&path, &[]).await?;+ if png_code != 200 || !png.starts_with(&[0x89, 0x50, 0x4E, 0x47]) {+ return Ok(None);+ }+ // qr_duration is half the code's life: asking again sooner restarts the pairing.+ Ok(Some(Qr { data_url: gateway::png_data_url(&png), seconds: (seconds * 2).saturating_sub(5).max(20) }))+ }+ Provider::Openwa { http, session } => {+ let id = Self::openwa_id(http, session).await?;+ let (data, code) = http.get(&format!("/api/sessions/{}/qr", path_component(&id)), &[]).await?;+ if code == 400 {+ return Ok(None); // not started, already linked, or not ready yet+ }+ Self::openwa_check(&data, code)?;+ Ok(openwa::qr_data_url(&data).map(|data_url| Qr { data_url, seconds: 15 }))+ }+ }+ }++ /// Tells the gateway to post new messages to Coucou's local webhook, signed with `secret`.+ pub async fn register_webhook(&self, url: &str, secret: &str) -> Result<(), WaError> {+ match self {+ Provider::Gowa { http, device } => {+ let id = Self::gowa_id(http, device).await?;+ let body = json!({"webhook_url": url, "webhook_secret": secret, "webhook_events": "message"});+ let (data, code) = http.call(Method::PATCH, &format!("/devices/{}/webhook", path_component(&id)), &[], Some(body), Duration::from_secs(10)).await?;+ Self::gowa_check(&data, code)+ }+ Provider::Openwa { http, session } => {+ let id = path_component(&Self::openwa_id(http, session).await?);+ let body = json!({"url": url, "events": ["message.received", "message.sent"], "secret": secret});+ let (list, list_code) = http.get(&format!("/api/sessions/{id}/webhooks"), &[]).await?;+ Self::openwa_check(&list, list_code)?;+ let hooks: Vec<Value> = serde_json::from_slice(&list).unwrap_or_default();+ let mine = hooks.iter().find(|h| h.get("url").and_then(Value::as_str) == Some(url)).and_then(|h| h.get("id")).and_then(Value::as_str);+ let (data, code) = match mine {+ Some(hook) => http.call(Method::PUT, &format!("/api/sessions/{id}/webhooks/{}", path_component(hook)), &[], Some(body), Duration::from_secs(10)).await?,+ None => http.call(Method::POST, &format!("/api/sessions/{id}/webhooks"), &[], Some(body), Duration::from_secs(10)).await?,+ };+ Self::openwa_check(&data, code)+ }+ }+ }++ /// Messages of every chat since `since_ms` (the polling fallback), oldest first.+ pub async fn recent_messages(&self, since_ms: i64, me: Option<&str>) -> Result<Vec<Message>, WaError> {+ let mut out = match self {+ Provider::Gowa { http, device } => {+ let chats = gowa::chats(&Self::gowa_scoped(http, device, Method::GET, "/chats", &[("limit", "20".into())], None).await?);+ let mut out = Vec::new();+ // Only the chats that moved since then (newest first from the gateway).+ for (jid, name, _) in chats.into_iter().take(8).filter(|c| c.2 > since_ms) {+ let path = format!("/chat/{}/messages", path_component(&jid));+ let data = Self::gowa_scoped(http, device, Method::GET, &path, &[("limit", "10".into()), ("start_time", gateway::iso_utc(since_ms))], None).await?;+ out.extend(gowa::messages(&data, me).into_iter().map(|mut m| {+ if m.chat_name.is_none() && !name.is_empty() && model::is_group(&jid) {+ m.chat_name = Some(name.clone());+ }+ m+ }));+ }+ out+ }+ Provider::Openwa { http, session } => {+ let q = [("since", since_ms.to_string()), ("limit", "50".into()), ("inlineMedia", "false".into())];+ openwa::messages(&Self::openwa_scoped(http, session, Method::GET, "/messages", &q, None).await?, me)+ }+ };+ out.sort_by_key(|m| m.date);+ Ok(out)+ }++ /// The latest `limit` messages of one chat, oldest first.+ pub async fn messages(&self, chat: &str, limit: usize, me: Option<&str>) -> Result<Vec<Message>, WaError> {+ let mut out = match self {+ Provider::Gowa { http, device } => {+ let path = format!("/chat/{}/messages", path_component(chat));+ gowa::messages(&Self::gowa_scoped(http, device, Method::GET, &path, &[("limit", limit.to_string())], None).await?, me)+ }+ Provider::Openwa { http, session } => {+ let q = [("chatId", openwa::chat_id(chat)), ("limit", limit.to_string()), ("inlineMedia", "false".into())];+ openwa::messages(&Self::openwa_scoped(http, session, Method::GET, "/messages", &q, None).await?, me)+ }+ };+ out.sort_by_key(|m| m.date);+ Ok(out)+ }++ /// Sends a text to an existing chat; the new message's id when the gateway gives it.+ pub async fn send(&self, text: &str, chat: &str) -> Result<Option<String>, WaError> {+ match self {+ Provider::Gowa { http, device } => {+ let data = Self::gowa_scoped(http, device, Method::POST, "/send/message", &[], Some(json!({"phone": chat, "message": text}))).await?;+ Ok(gowa::sent_id(&data))+ }+ Provider::Openwa { http, session } => {+ let data = Self::openwa_scoped(http, session, Method::POST, "/messages/send-text", &[], Some(json!({"chatId": openwa::chat_id(chat), "text": text}))).await?;+ Ok(serde_json::from_slice::<Value>(&data).ok().and_then(|v| v.get("messageId").and_then(Value::as_str).map(str::to_string)))+ }+ }+ }++ /// Marks the chat read up to `last_incoming` (the newest message received in it).+ pub async fn mark_read(&self, chat: &str, last_incoming: Option<&str>) -> Result<(), WaError> {+ match self {+ Provider::Gowa { http, device } => {+ let Some(id) = last_incoming else { return Ok(()) };+ let path = format!("/message/{}/read", path_component(id));+ Self::gowa_scoped(http, device, Method::POST, &path, &[], Some(json!({"phone": chat}))).await.map(|_| ())+ }+ Provider::Openwa { http, session } => {+ Self::openwa_scoped(http, session, Method::POST, "/chats/read", &[], Some(json!({"chatId": openwa::chat_id(chat)}))).await.map(|_| ())+ }+ }+ }++ /// A group's name, when the messages don't carry it.+ pub async fn group_name(&self, chat: &str) -> Option<String> {+ if !model::is_group(chat) {+ return None;+ }+ match self {+ Provider::Gowa { http, device } => {+ let data = Self::gowa_scoped(http, device, Method::GET, "/group/info", &[("group_id", chat.to_string())], None).await.ok()?;+ gowa::group_name(&data)+ }+ Provider::Openwa { http, session } => {+ let data = Self::openwa_scoped(http, session, Method::GET, &format!("/groups/{}", path_component(chat)), &[], None).await.ok()?;+ let v: Value = serde_json::from_slice(&data).ok()?;+ v.get("name").and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_string)+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn addresses_stay_on_the_gateway() {+ assert_eq!(path_component("[email protected]"), "[email protected]");+ assert_eq!(path_component("a/b?c#d e"), "a%2Fb%3Fc%23d%20e");+ assert_eq!(path_component("../x"), "..%2Fx");+ let base = parse_base("http://127.0.0.1:3000").unwrap();+ assert_eq!(endpoint(&base, "/devices", &[]).unwrap().as_str(), "http://127.0.0.1:3000/devices");+ let q = endpoint(&base, "/chats", &[("limit", "20".into()), ("device_id", "a&b=c".into())]).unwrap();+ assert_eq!(q.as_str(), "http://127.0.0.1:3000/chats?limit=20&device_id=a%26b%3Dc");+ let prefixed = parse_base("http://127.0.0.1:3000/gowa/").unwrap();+ assert_eq!(endpoint(&prefixed, "/devices", &[]).unwrap().as_str(), "http://127.0.0.1:3000/gowa/devices");+ assert!(parse_base("ftp://127.0.0.1").is_none());+ assert!(parse_base("http://user:[email protected]:3000").is_none());+ assert!(parse_base("not a url").is_none());+ assert_eq!(basic_auth("user:pass"), "Basic dXNlcjpwYXNz");+ }++ #[test]+ fn credentials_go_where_each_gateway_wants_them() {+ let base = parse_base("http://127.0.0.1:3000").unwrap();+ let Provider::Gowa { http, .. } = Provider::new(Kind::Gowa, base.clone(), Some("admin:secret".into())).unwrap() else { panic!() };+ assert_eq!(http.headers, vec![("Authorization", "Basic YWRtaW46c2VjcmV0".to_string())]);+ // A GOWA credential without "user:" is not basic auth: nothing is sent.+ let Provider::Gowa { http, .. } = Provider::new(Kind::Gowa, base.clone(), Some("justakey".into())).unwrap() else { panic!() };+ assert!(http.headers.is_empty());+ let Provider::Openwa { http, .. } = Provider::new(Kind::Openwa, base, Some("k-123".into())).unwrap() else { panic!() };+ assert_eq!(http.headers, vec![("X-API-Key", "k-123".to_string())]);+ }++ #[test]+ fn errors_are_read_like_the_mac() {+ assert_eq!(Provider::gowa_check(br#"{"code":"x"}"#, 401), Err(WaError::Unauthorized));+ assert_eq!(Provider::gowa_check(br#"{"code":"AUTHENTICATION_ERROR"}"#, 401), Err(WaError::NotLoggedIn));+ assert_eq!(Provider::gowa_check(br#"{"code":"INVALID_JID"}"#, 400), Err(WaError::Refused("INVALID_JID".into())));+ assert_eq!(Provider::gowa_check(b"", 500), Err(WaError::Refused("HTTP 500".into())));+ assert_eq!(Provider::gowa_check(b"", 200), Ok(()));+ assert_eq!(Provider::openwa_check(b"", 403), Err(WaError::Unauthorized));+ assert_eq!(Provider::openwa_check(br#"{"message":"Session not found"}"#, 404), Err(WaError::Refused("Session not found".into())));+ }+}diff --git a/windows/src-tauri/src/whatsapp/webhook.rs b/windows/src-tauri/src/whatsapp/webhook.rsnew file mode 100644index 00000000..f1dd5f99--- /dev/null+++ b/windows/src-tauri/src/whatsapp/webhook.rs@@ -0,0 +1,83 @@+// The local door the WhatsApp gateway knocks on with each new message (port of WhatsAppWebhook.swift):+// an HTTP listener bound to 127.0.0.1 only, never reachable from another machine, on the port set in+// Settings. Each request is handed over whole; nothing of it is logged.++use std::net::{Ipv4Addr, SocketAddr, TcpListener as StdListener};+use std::sync::Arc;+use std::time::Duration;++use tokio::io::{AsyncReadExt, AsyncWriteExt};+use tokio::net::TcpStream;++use super::model::{parse_request, response, HttpRequest, Parse, MAX_BODY, MAX_HEAD};++/// Called with each complete request; returns the HTTP status to answer.+pub type Handler = Arc<dyn Fn(HttpRequest) -> u16 + Send + Sync>;++/// A request that never finishes is dropped after this.+const DEADLINE: Duration = Duration::from_secs(10);++pub struct Listener {+ task: tauri::async_runtime::JoinHandle<()>,+}++impl Listener {+ /// Starts listening on 127.0.0.1:`port`; Err when the port is taken or invalid.+ pub fn start(port: u16, handler: Handler) -> Result<Listener, ()> {+ if port == 0 {+ return Err(());+ }+ let std = StdListener::bind(SocketAddr::from((Ipv4Addr::LOCALHOST, port))).map_err(|_| ())?;+ std.set_nonblocking(true).map_err(|_| ())?;+ let task = tauri::async_runtime::spawn(async move {+ let Ok(listener) = tokio::net::TcpListener::from_std(std) else { return };+ loop {+ let Ok((stream, peer)) = listener.accept().await else {+ tokio::time::sleep(Duration::from_millis(200)).await;+ continue;+ };+ // Only the loopback: the listener is bound to it, this is a second lock.+ if !peer.ip().is_loopback() {+ continue;+ }+ let handler = handler.clone();+ tauri::async_runtime::spawn(async move {+ let _ = tokio::time::timeout(DEADLINE, serve(stream, handler)).await;+ });+ }+ });+ Ok(Listener { task })+ }++ pub fn stop(self) {+ self.task.abort();+ }+}++async fn serve(mut stream: TcpStream, handler: Handler) {+ let mut buffer = Vec::new();+ let mut chunk = [0u8; 65_536];+ let answer = loop {+ let n = match stream.read(&mut chunk).await {+ Ok(n) => n,+ Err(_) => return,+ };+ buffer.extend_from_slice(&chunk[..n]);+ match parse_request(&buffer, MAX_BODY) {+ Parse::Incomplete if n > 0 && buffer.len() <= MAX_HEAD + MAX_BODY => continue,+ Parse::Done(request) => {+ let status = handler(request);+ let reason = match status {+ 200 => "OK",+ 401 => "Unauthorized",+ 404 => "Not Found",+ _ => "Error",+ };+ break response(status, reason);+ }+ _ => break response(400, "Bad Request"),+ }+ };+ let _ = stream.write_all(&answer).await;+ let _ = stream.shutdown().await;+}diff --git a/windows/src/core/bridge.ts b/windows/src/core/bridge.tsindex a9cfbfff..ce2f2c4a 100644--- a/windows/src/core/bridge.ts+++ b/windows/src/core/bridge.ts@@ -9,6 +9,7 @@ import type { Settings } from "./state";import type { RecapHistory, RecapPrefs } from "../recap/summary";import type { SpotifyState } from "./spotify";import type { UpdateStatus } from "./update";+import type { WaIslandView, WaSettingsView, WaTestResult } from "./whatsapp";export const IS_TAURI =typeof window !== "undefined" && "__TAURI_INTERNALS__" in window;@@ -443,6 +444,29 @@ export const Bridge = {/** Whether there is a Spotify to launch (Settings). */spotifyInstalled: () => call<boolean>("spotify_installed"),+ // ── WhatsApp (src-tauri/src/whatsapp) ─────────────────────────────────────+ /** The island's copy, asked once at start (then the "whatsapp" event). Island only. */+ whatsappIsland: () => call<WaIslandView>("whatsapp_island"),+ /** A conversation opened in the card: its latest messages, the receipt if Settings says so. */+ whatsappOpen: (chat: string) => call<void>("whatsapp_open", { chat }),+ whatsappClose: (chat: string) => call<void>("whatsapp_close", { chat }),+ /** Enter or the send button only. True once the gateway took it. */+ whatsappSend: (chat: string, text: string) => call<boolean>("whatsapp_send", { chat, text }),+ /** A chat id, or (Settings) a phone number. */+ whatsappIgnore: (chat: string) => call<void>("whatsapp_ignore", { chat }),+ whatsappUnignore: (chat: string) => call<void>("whatsapp_unignore", { chat }),+ /** Settings only, from here down. */+ whatsappSettings: () => call<WaSettingsView>("whatsapp_settings"),+ whatsappSetOptions: (enabled: boolean, muteGroups: boolean, markReadOnOpen: boolean) =>+ callOrThrow<void>("whatsapp_set_options", { enabled, muteGroups, markReadOnOpen }),+ /** `credential`: null keeps the stored one, "" removes it. */+ whatsappSaveGateway: (g: {+ gateway: "gowa" | "openwa"; url: string; credential: string | null; port: number; autoStart: boolean; gowaPath: string;+ }) => callOrThrow<void>("whatsapp_save_gateway", g),+ whatsappTest: () => call<WaTestResult>("whatsapp_test"),+ /** "Install WhatsApp" / "Update": GOWA from its GitHub releases, on this click only. */+ whatsappInstall: () => call<void>("whatsapp_install"),+// ── New versions (src-tauri/src/update.rs) ────────────────────────────────updateStatus: () => call<UpdateStatus>("update_status"),/** The island's question or Settings' toggle: may Coucou look at GitHub on its own? */diff --git a/windows/src/core/pills.ts b/windows/src/core/pills.tsindex c00a608c..fa222fef 100644--- a/windows/src/core/pills.ts+++ b/windows/src/core/pills.ts@@ -138,6 +138,10 @@ export const PILL_CATALOG: readonly PillDefinition[] = [// (src-tauri/src/spotify.rs).{ id: "integration_spotify", name: "Spotify", color: "#1DB954", category: "service",subtitle: N_("Integration"), source: "n8n", support: "yes", connect: none },+ // WhatsApp (experimental) through a gateway on this computer (src-tauri/src/whatsapp): set up,+ // linked and turned on in Settings → Integrations → WhatsApp, off until then.+ { id: "integration_whatsapp", name: "WhatsApp", color: "#25D366", category: "service",+ subtitle: N_("Integration"), source: "n8n", support: "yes", connect: none },];/** The always-on pill unless the user picks another workspace tool. */diff --git a/windows/src/core/whatsapp.ts b/windows/src/core/whatsapp.tsnew file mode 100644index 00000000..970c4192--- /dev/null+++ b/windows/src/core/whatsapp.ts@@ -0,0 +1,295 @@+// WhatsApp (experimental) on the page: what src-tauri/src/whatsapp reports, and the pure rules the+// card and Settings follow — ports of WhatsAppModels.swift (initials, previews) and+// WhatsAppViews.swift (status labels, the time since). Rust only ever sends codes; the words are+// chosen here, in the user's language. Nothing of a message is stored by the page either.++import { N_, t } from "../i18n/i18n";++export const WHATSAPP_ID = "integration_whatsapp";+/** WhatsApp's own green: the pill keeps it whatever, like the brand. */+export const WHATSAPP_GREEN = "#25D366";++export type WaMedia =+ | { kind: "none" | "image" | "video" | "sticker" | "location" | "contact" | "other" }+ | { kind: "audio" | "voice"; seconds: number | null }+ | { kind: "document"; name: string | null };++export interface WaMessage {+ id: string;+ chat: string;+ sender: string;+ senderName: string;+ text: string;+ media: WaMedia;+ /** Unix ms. */+ date: number;+ fromMe: boolean;+ mentionsMe: boolean;+}++export interface WaConversation {+ id: string;+ name: string;+ isGroup: boolean;+ /** Oldest first. */+ messages: WaMessage[];+ unread: number;+ lastActivity: number;+}++export type WaLink =+ | { state: "off" | "badUrl" | "connecting" | "needsQr" | "connected" | "unreachable" | "unauthorized" }+ | { state: "failed"; detail: string };++export type WaSendError =+ | { code: "tooLong" | "tooFast" | "unreachable" | "unauthorized" | "needsQr" }+ | { code: "refused"; detail: string };++/** IslandView in src-tauri/src/whatsapp/mod.rs. */+export interface WaIslandView {+ on: boolean;+ link: WaLink;+ /** Newest first, filters applied. */+ conversations: WaConversation[];+ unread: number;+ sending: boolean;+ sendError: WaSendError | null;+ /** The gateway failed twice in a row: the pill's red dot. */+ down: boolean;+}++export const IDLE_WHATSAPP: WaIslandView = {+ on: false, link: { state: "off" }, conversations: [], unread: 0, sending: false, sendError: null, down: false,+};++/** The page's copy of what Rust keeps. */+export const WhatsApp = {+ view: { ...IDLE_WHATSAPP } as WaIslandView,+};++export type WaWebhook =+ | { state: "off" | "listening" | "registered" }+ | { state: "refused"; detail: string }+ | { state: "portBusy"; port: number };++export type WaInstallStep =+ | { step: "idle" | "checking" | "verifying" | "installing" }+ | { step: "downloading"; megabytes: number }+ | { step: "done"; version: string }+ | { step: "failed"; reason: string };++export interface WaPrefs {+ enabled: boolean;+ gateway: "gowa" | "openwa";+ port: number;+ markReadOnOpen: boolean;+ muteGroups: boolean;+ ignored: string[];+ autoStart: boolean;+ gowaPath: string;+ gowaVersion: string | null;+}++/** SettingsView in src-tauri/src/whatsapp/mod.rs. */+export interface WaSettingsView {+ prefs: WaPrefs;+ url: string;+ defaultUrl: string;+ hasCredential: boolean;+ link: WaLink;+ webhook: WaWebhook;+ qr: string | null;+ me: string | null;+ install: WaInstallStep;+ installed: boolean;+ gowaDir: string;+ pillActive: boolean;+ ignored: { id: string; name: string }[];+}++export type WaTestResult =+ | { result: "needsQr" | "connecting" | "badUrl" | "unreachable" | "unauthorized" }+ | { result: "connected"; who: string }+ | { result: "refused"; detail: string };++export const DEFAULT_URLS = { gowa: "http://127.0.0.1:3000", openwa: "http://127.0.0.1:2785" } as const;+export const DEFAULT_PORT = 47823;++// ── Pure rules ────────────────────────────────────────────────────────────────++/** WAJID.initials: the first letters of the first two words, "#" when there are none. */+export function initials(name: string): string {+ const words = name.split(/[ -]/).filter((w) => /^\p{L}/u.test(w));+ const letters = words.slice(0, 2).map((w) => [...w][0].toUpperCase());+ return letters.length ? letters.join("") : "#";+}++/** WAJID.duration: 12 → "0:12", 75 → "1:15". */+export function duration(seconds: number): string {+ const s = Math.max(0, Math.floor(seconds));+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;+}++/** The label a media gets (English keys, shown with `t()`). */+export const MEDIA_LABELS = {+ image: N_("Photo"),+ video: N_("Video"),+ voice: N_("Voice message"),+ document: N_("Document"),+ sticker: N_("Sticker"),+ location: N_("Location"),+ contact: N_("Contact"),+ other: N_("Message"),+} as const;++/** WAMessage.previewKey: the media's label (if any) and the text that goes with it. */+export function previewParts(m: WaMessage): { label: string | null; value: string } {+ const media = m.media;+ switch (media.kind) {+ case "none": return { label: null, value: m.text };+ case "image": return { label: MEDIA_LABELS.image, value: m.text };+ case "video": return { label: MEDIA_LABELS.video, value: m.text };+ case "audio":+ case "voice": return { label: MEDIA_LABELS.voice, value: media.seconds != null ? duration(media.seconds) : "" };+ case "document": return { label: MEDIA_LABELS.document, value: media.name ?? m.text };+ case "sticker": return { label: MEDIA_LABELS.sticker, value: "" };+ case "location": return { label: MEDIA_LABELS.location, value: "" };+ case "contact": return { label: MEDIA_LABELS.contact, value: "" };+ default: return { label: MEDIA_LABELS.other, value: m.text };+ }+}++/** waPreview: "Marie: see you", "You: ok", "Photo · look", "Voice message": one line. */+export function preview(m: WaMessage, isGroup: boolean): string {+ const { label, value } = previewParts(m);+ let line = label == null ? value : value ? `${t(label)} · ${value}` : t(label);+ line = line.replace(/\n/g, " ");+ if (m.fromMe) return `${t("You")}: ${line}`;+ if (isGroup && m.senderName) return `${m.senderName}: ${line}`;+ return line;+}++/** waTimeAgo: now, 5m, 3h, 2d. */+export function timeAgo(ms: number, now = Date.now()): string {+ const diff = (now - ms) / 1000;+ if (diff < 60) return t("now");+ if (diff < 3600) return `${Math.floor(diff / 60)}m`;+ if (diff < 86400) return `${Math.floor(diff / 3600)}h`;+ return `${Math.floor(diff / 86400)}d`;+}++/** WhatsAppStatus.label. */+export function linkLabel(link: WaLink): string {+ switch (link.state) {+ case "off": return t("Turned off in Settings");+ case "badUrl": return t("The gateway URL isn’t valid (http://…)");+ case "connecting": return t("Connecting to the gateway…");+ case "needsQr": return t("Scan the QR code in Settings");+ case "connected": return t("Connected");+ case "unreachable": return t("The gateway doesn’t answer: is it running?");+ case "unauthorized": return t("The gateway refuses the credentials");+ case "failed": return link.detail;+ }+}++/** WhatsAppStatus.dot. */+export function linkColor(link: WaLink): string {+ switch (link.state) {+ case "connected": return "#22C55E";+ case "connecting":+ case "needsQr": return "#F5B83D";+ case "off": return "#6B7079";+ default: return "#F4505E";+ }+}++export function sendErrorLabel(e: WaSendError): string {+ switch (e.code) {+ case "tooLong": return t("Too long for one message (4,096 characters at most).");+ case "tooFast": return t("A few replies a minute at most: wait a moment.");+ case "unreachable": return t("The gateway doesn’t answer: is it running?");+ case "unauthorized": return t("The gateway refuses the credentials");+ case "needsQr": return t("Scan the QR code in Settings");+ case "refused": return e.detail;+ }+}++/** The last ten messages of a conversation, oldest first: what the open card shows. */+export function lastMessages(c: WaConversation, count = 10): WaMessage[] {+ return c.messages.slice(-count);+}++/** Enter sends, Shift+Enter is a new line; IME composition never sends. */+export function keyAction(e: { key: string; shiftKey: boolean; isComposing?: boolean }): "send" | "newline" | "back" | null {+ if (e.key === "Escape") return "back";+ if (e.key !== "Enter" || e.isComposing) return null;+ return e.shiftKey ? "newline" : "send";+}++/** Something worth sending: not only spaces and new lines. */+export function canSend(draft: string, sending: boolean): boolean {+ return !sending && draft.trim().length > 0;+}++// ── Settings' words ───────────────────────────────────────────────────────────++/** What a running install says (Settings). */+export function installStepLabel(s: WaInstallStep): string {+ switch (s.step) {+ case "checking": return t("Looking for the latest GOWA…");+ case "downloading": return t("Downloading ({megabytes} MB)…", { megabytes: s.megabytes });+ case "verifying": return t("Checking the download…");+ case "installing": return t("Installing and starting…");+ default: return "";+ }+}++/** Why an install stopped (install.rs's reasons). */+export function installFailure(reason: string): string {+ switch (reason) {+ case "noBuild": return t("No GOWA build for this computer was found on GitHub. Try again later, or set your own gateway under Advanced.");+ case "noChecksum": return t("GOWA's release has no checksum to check the download against: nothing was installed.");+ case "badChecksum": return t("The download doesn't match the file GOWA published: it was deleted, nothing was installed.");+ case "unzipFailed": return t("The download couldn't be unzipped. Try again.");+ default: return t("The download didn't go through. Check your connection and try again.");+ }+}++/** Why the last install stopped, in words; null when it didn't. */+export function installError(s: WaInstallStep): string | null {+ return s.step === "failed" ? installFailure(s.reason) : null;+}++export function isInstalling(s: WaInstallStep): boolean {+ return s.step === "checking" || s.step === "downloading" || s.step === "verifying" || s.step === "installing";+}++/** Whether messages come at once or every 20 s, and why. */+export function webhookLine(w: WaWebhook): string {+ switch (w.state) {+ case "registered": return t("Live: new messages arrive at once.");+ case "portBusy": return t("Port {port} is taken: pick another one. Checking every 20 s meanwhile.", { port: w.port });+ case "refused": return t("The gateway refused Coucou’s address ({detail}). Checking every 20 s instead.", { detail: w.detail });+ default: return t("Checking for new messages every 20 s.");+ }+}++/** "Test connection"'s answer. */+export function testResultLabel(r: WaTestResult): string {+ switch (r.result) {+ case "connected": return t("Connected as {number}.", { number: r.who });+ case "needsQr": return t("The gateway answers. Scan the QR code below with your phone.");+ case "connecting": return t("The gateway answers and is connecting to WhatsApp…");+ case "badUrl": return linkLabel({ state: "badUrl" });+ case "unreachable": return linkLabel({ state: "unreachable" });+ case "unauthorized": return linkLabel({ state: "unauthorized" });+ case "refused": return r.detail;+ }+}++/** The status and QR once there is a gateway to talk to: before the install, "the gateway doesn't+ * answer" would only confuse. */+export function showsLinkState(v: WaSettingsView): boolean {+ if (v.prefs.gateway !== "gowa" || v.installed || v.url !== "") return true;+ return v.link.state === "connected" || v.link.state === "needsQr";+}diff --git a/windows/src/i18n/extra.json b/windows/src/i18n/extra.jsonindex 572d5045..06e3c499 100644--- a/windows/src/i18n/extra.json+++ b/windows/src/i18n/extra.json@@ -5285,6 +5285,812 @@"id": "panggilan ditranskrip","de": "transkribierte Anrufe","tr": "çağrı yazıya döküldü"+ },+ "Photo": {+ "zh-Hans": "照片",+ "hi": "फ़ोटो",+ "es": "Foto",+ "ar": "صورة",+ "fr": "Photo",+ "bn": "ছবি",+ "pt-BR": "Foto",+ "ru": "Фото",+ "id": "Foto",+ "de": "Foto",+ "tr": "Fotoğraf"+ },+ "Video": {+ "zh-Hans": "视频",+ "hi": "वीडियो",+ "es": "Vídeo",+ "ar": "فيديو",+ "fr": "Vidéo",+ "bn": "ভিডিও",+ "pt-BR": "Vídeo",+ "ru": "Видео",+ "id": "Video",+ "de": "Video",+ "tr": "Video"+ },+ "Voice message": {+ "zh-Hans": "语音消息",+ "hi": "वॉइस संदेश",+ "es": "Audio",+ "ar": "رسالة صوتية",+ "fr": "Vocal",+ "bn": "ভয়েস বার্তা",+ "pt-BR": "Áudio",+ "ru": "Голосовое",+ "id": "Pesan suara",+ "de": "Sprachnachricht",+ "tr": "Sesli mesaj"+ },+ "Document": {+ "zh-Hans": "文档",+ "hi": "दस्तावेज़",+ "es": "Documento",+ "ar": "مستند",+ "fr": "Document",+ "bn": "ডকুমেন্ট",+ "pt-BR": "Documento",+ "ru": "Документ",+ "id": "Dokumen",+ "de": "Dokument",+ "tr": "Belge"+ },+ "Sticker": {+ "zh-Hans": "贴纸",+ "hi": "स्टिकर",+ "es": "Sticker",+ "ar": "ملصق",+ "fr": "Sticker",+ "bn": "স্টিকার",+ "pt-BR": "Figurinha",+ "ru": "Стикер",+ "id": "Stiker",+ "de": "Sticker",+ "tr": "Çıkartma"+ },+ "Location": {+ "zh-Hans": "位置",+ "hi": "लोकेशन",+ "es": "Ubicación",+ "ar": "موقع",+ "fr": "Position",+ "bn": "লোকেশন",+ "pt-BR": "Localização",+ "ru": "Местоположение",+ "id": "Lokasi",+ "de": "Standort",+ "tr": "Konum"+ },+ "Contact": {+ "zh-Hans": "联系人",+ "hi": "संपर्क",+ "es": "Contacto",+ "ar": "جهة اتصال",+ "fr": "Contact",+ "bn": "পরিচিতি",+ "pt-BR": "Contato",+ "ru": "Контакт",+ "id": "Kontak",+ "de": "Kontakt",+ "tr": "Kişi"+ },+ "Message": {+ "zh-Hans": "消息",+ "hi": "संदेश",+ "es": "Mensaje",+ "ar": "رسالة",+ "fr": "Message",+ "bn": "বার্তা",+ "pt-BR": "Mensagem",+ "ru": "Сообщение",+ "id": "Pesan",+ "de": "Nachricht",+ "tr": "Mesaj"+ },+ "You": {+ "zh-Hans": "你",+ "hi": "आप",+ "es": "Tú",+ "ar": "أنت",+ "fr": "Toi",+ "bn": "আপনি",+ "pt-BR": "Você",+ "ru": "Вы",+ "id": "Kamu",+ "de": "Du",+ "tr": "Sen"+ },+ "Turned off in Settings": {+ "zh-Hans": "已在设置中关闭",+ "hi": "सेटिंग्स में बंद है",+ "es": "Desactivado en Ajustes",+ "ar": "متوقف في الإعدادات",+ "fr": "Désactivé dans les réglages",+ "bn": "সেটিংসে বন্ধ",+ "pt-BR": "Desativado nos Ajustes",+ "ru": "Выключено в настройках",+ "id": "Dimatikan di Pengaturan",+ "de": "In den Einstellungen ausgeschaltet",+ "tr": "Ayarlar’da kapalı"+ },+ "The gateway URL isn’t valid (http://…)": {+ "zh-Hans": "网关地址无效(http://…)",+ "hi": "गेटवे URL मान्य नहीं है (http://…)",+ "es": "La URL de la pasarela no es válida (http://…)",+ "ar": "عنوان البوابة غير صالح (http://…)",+ "fr": "L’URL de la passerelle n’est pas valide (http://…)",+ "bn": "গেটওয়ের URL সঠিক নয় (http://…)",+ "pt-BR": "A URL do gateway não é válida (http://…)",+ "ru": "Неверный адрес шлюза (http://…)",+ "id": "URL gateway tidak valid (http://…)",+ "de": "Die Adresse des Gateways ist ungültig (http://…)",+ "tr": "Ağ geçidi adresi geçerli değil (http://…)"+ },+ "Connecting to the gateway…": {+ "zh-Hans": "正在连接网关…",+ "hi": "गेटवे से जुड़ रहा है…",+ "es": "Conectando con la pasarela…",+ "ar": "جارٍ الاتصال بالبوابة…",+ "fr": "Connexion à la passerelle…",+ "bn": "গেটওয়েতে সংযুক্ত হচ্ছে…",+ "pt-BR": "Conectando ao gateway…",+ "ru": "Подключение к шлюзу…",+ "id": "Menghubungkan ke gateway…",+ "de": "Verbindung zum Gateway…",+ "tr": "Ağ geçidine bağlanılıyor…"+ },+ "Scan the QR code in Settings": {+ "zh-Hans": "请在设置中扫描二维码",+ "hi": "सेटिंग्स में QR कोड स्कैन करें",+ "es": "Escanea el código QR en Ajustes",+ "ar": "امسح رمز QR في الإعدادات",+ "fr": "Scanne le QR code dans les réglages",+ "bn": "সেটিংসে QR কোড স্ক্যান করুন",+ "pt-BR": "Escaneie o QR code nos Ajustes",+ "ru": "Отсканируйте QR-код в настройках",+ "id": "Pindai kode QR di Pengaturan",+ "de": "Scanne den QR-Code in den Einstellungen",+ "tr": "Ayarlar’daki QR kodunu tara"+ },+ "The gateway doesn’t answer: is it running?": {+ "zh-Hans": "网关没有响应:它在运行吗?",+ "hi": "गेटवे जवाब नहीं दे रहा: क्या वह चल रहा है?",+ "es": "La pasarela no responde: ¿está en marcha?",+ "ar": "البوابة لا تستجيب: هل هي قيد التشغيل؟",+ "fr": "La passerelle ne répond pas : est-elle lancée ?",+ "bn": "গেটওয়ে সাড়া দিচ্ছে না: এটি চালু আছে?",+ "pt-BR": "O gateway não responde: ele está rodando?",+ "ru": "Шлюз не отвечает: он запущен?",+ "id": "Gateway tidak merespons: apakah sedang berjalan?",+ "de": "Das Gateway antwortet nicht: Läuft es?",+ "tr": "Ağ geçidi yanıt vermiyor: çalışıyor mu?"+ },+ "The gateway refuses the credentials": {+ "zh-Hans": "网关拒绝了凭据",+ "hi": "गेटवे ने क्रेडेंशियल अस्वीकार किए",+ "es": "La pasarela rechaza las credenciales",+ "ar": "البوابة ترفض بيانات الاعتماد",+ "fr": "La passerelle refuse les identifiants",+ "bn": "গেটওয়ে পরিচয়পত্র প্রত্যাখ্যান করছে",+ "pt-BR": "O gateway recusa as credenciais",+ "ru": "Шлюз отклоняет учётные данные",+ "id": "Gateway menolak kredensial",+ "de": "Das Gateway lehnt die Zugangsdaten ab",+ "tr": "Ağ geçidi kimlik bilgilerini reddediyor"+ },+ "Too long for one message (4,096 characters at most).": {+ "zh-Hans": "单条消息过长(最多 4096 个字符)。",+ "hi": "एक संदेश के लिए बहुत लंबा (अधिकतम 4,096 अक्षर)।",+ "es": "Demasiado largo para un mensaje (4096 caracteres como máximo).",+ "ar": "طويل جدًا لرسالة واحدة (4096 حرفًا كحد أقصى).",+ "fr": "Trop long pour un seul message (4 096 caractères au maximum).",+ "bn": "একটি বার্তার জন্য খুব লম্বা (সর্বোচ্চ ৪০৯৬ অক্ষর)।",+ "pt-BR": "Longo demais para uma mensagem (no máximo 4.096 caracteres).",+ "ru": "Слишком длинно для одного сообщения (не больше 4096 символов).",+ "id": "Terlalu panjang untuk satu pesan (maksimal 4.096 karakter).",+ "de": "Zu lang für eine Nachricht (höchstens 4.096 Zeichen).",+ "tr": "Tek bir mesaj için çok uzun (en fazla 4.096 karakter)."+ },+ "A few replies a minute at most: wait a moment.": {+ "zh-Hans": "每分钟最多回复几条:请稍等。",+ "hi": "एक मिनट में कुछ ही जवाब: थोड़ा रुकें।",+ "es": "Unas pocas respuestas por minuto como máximo: espera un momento.",+ "ar": "بضعة ردود في الدقيقة كحد أقصى: انتظر قليلًا.",+ "fr": "Quelques réponses par minute au maximum : attends un instant.",+ "bn": "মিনিটে সর্বোচ্চ কয়েকটি উত্তর: একটু অপেক্ষা করুন।",+ "pt-BR": "No máximo algumas respostas por minuto: espere um pouco.",+ "ru": "Не больше нескольких ответов в минуту: подождите немного.",+ "id": "Paling banyak beberapa balasan per menit: tunggu sebentar.",+ "de": "Höchstens ein paar Antworten pro Minute: Warte einen Moment.",+ "tr": "Dakikada en fazla birkaç yanıt: biraz bekle."+ },+ "Looking for the latest GOWA…": {+ "zh-Hans": "正在查找最新版 GOWA…",+ "hi": "GOWA का नया वर्शन ढूँढ रहा है…",+ "es": "Buscando la última versión de GOWA…",+ "ar": "البحث عن أحدث إصدار من GOWA…",+ "fr": "Recherche de la dernière version de GOWA…",+ "bn": "GOWA-র সর্বশেষ সংস্করণ খোঁজা হচ্ছে…",+ "pt-BR": "Procurando a versão mais recente do GOWA…",+ "ru": "Поиск последней версии GOWA…",+ "id": "Mencari versi GOWA terbaru…",+ "de": "Suche nach der neuesten GOWA-Version…",+ "tr": "En yeni GOWA aranıyor…"+ },+ "Downloading ({megabytes} MB)…": {+ "zh-Hans": "正在下载({megabytes} MB)…",+ "hi": "डाउनलोड हो रहा है ({megabytes} MB)…",+ "es": "Descargando ({megabytes} MB)…",+ "ar": "جارٍ التنزيل ({megabytes} ميغابايت)…",+ "fr": "Téléchargement ({megabytes} Mo)…",+ "bn": "ডাউনলোড হচ্ছে ({megabytes} MB)…",+ "pt-BR": "Baixando ({megabytes} MB)…",+ "ru": "Загрузка ({megabytes} МБ)…",+ "id": "Mengunduh ({megabytes} MB)…",+ "de": "Wird geladen ({megabytes} MB)…",+ "tr": "İndiriliyor ({megabytes} MB)…"+ },+ "Installing and starting…": {+ "zh-Hans": "正在安装并启动…",+ "hi": "इंस्टॉल और चालू हो रहा है…",+ "es": "Instalando e iniciando…",+ "ar": "جارٍ التثبيت والتشغيل…",+ "fr": "Installation et démarrage…",+ "bn": "ইনস্টল ও চালু হচ্ছে…",+ "pt-BR": "Instalando e iniciando…",+ "ru": "Установка и запуск…",+ "id": "Memasang dan menjalankan…",+ "de": "Wird installiert und gestartet…",+ "tr": "Kuruluyor ve başlatılıyor…"+ },+ "GOWA's release has no checksum to check the download against: nothing was installed.": {+ "zh-Hans": "GOWA 版本没有可用于校验的校验和:未安装任何内容。",+ "hi": "GOWA रिलीज़ में डाउनलोड जाँचने के लिए चेकसम नहीं है: कुछ इंस्टॉल नहीं हुआ।",+ "es": "La versión de GOWA no tiene suma de comprobación para verificar la descarga: no se instaló nada.",+ "ar": "لا يحتوي إصدار GOWA على بصمة للتحقق من التنزيل: لم يُثبَّت شيء.",+ "fr": "La version de GOWA n'a pas d'empreinte pour vérifier le téléchargement : rien n'a été installé.",+ "bn": "GOWA রিলিজে ডাউনলোড যাচাইয়ের চেকসাম নেই: কিছু ইনস্টল হয়নি।",+ "pt-BR": "A versão do GOWA não tem checksum para verificar o download: nada foi instalado.",+ "ru": "У выпуска GOWA нет контрольной суммы для проверки: ничего не установлено.",+ "id": "Rilis GOWA tidak punya checksum untuk memeriksa unduhan: tidak ada yang dipasang.",+ "de": "Die GOWA-Version hat keine Prüfsumme, mit der sich der Download prüfen lässt: Es wurde nichts installiert.",+ "tr": "GOWA sürümünde indirmeyi doğrulayacak bir sağlama toplamı yok: hiçbir şey kurulmadı."+ },+ "The download doesn't match the file GOWA published: it was deleted, nothing was installed.": {+ "zh-Hans": "下载内容与 GOWA 发布的文件不符:已删除,未安装任何内容。",+ "hi": "डाउनलोड GOWA की फ़ाइल से मेल नहीं खाता: हटा दिया गया, कुछ इंस्टॉल नहीं हुआ।",+ "es": "La descarga no coincide con el archivo publicado por GOWA: se eliminó y no se instaló nada.",+ "ar": "التنزيل لا يطابق الملف الذي نشره GOWA: حُذف ولم يُثبَّت شيء.",+ "fr": "Le téléchargement ne correspond pas au fichier publié par GOWA : il a été supprimé, rien n'a été installé.",+ "bn": "ডাউনলোড GOWA-র প্রকাশিত ফাইলের সঙ্গে মেলে না: মুছে ফেলা হয়েছে, কিছু ইনস্টল হয়নি।",+ "pt-BR": "O download não corresponde ao arquivo publicado pelo GOWA: foi apagado, nada foi instalado.",+ "ru": "Загрузка не совпадает с файлом, опубликованным GOWA: она удалена, ничего не установлено.",+ "id": "Unduhan tidak cocok dengan file dari GOWA: sudah dihapus, tidak ada yang dipasang.",+ "de": "Der Download stimmt nicht mit der von GOWA veröffentlichten Datei überein: Er wurde gelöscht, es wurde nichts installiert.",+ "tr": "İndirilen dosya GOWA’nın yayımladığı dosyayla eşleşmiyor: silindi, hiçbir şey kurulmadı."+ },+ "The download couldn't be unzipped. Try again.": {+ "zh-Hans": "无法解压下载内容。请重试。",+ "hi": "डाउनलोड अनज़िप नहीं हो सका। फिर कोशिश करें।",+ "es": "No se pudo descomprimir la descarga. Inténtalo de nuevo.",+ "ar": "تعذّر فك ضغط التنزيل. أعد المحاولة.",+ "fr": "Le téléchargement n'a pas pu être décompressé. Réessaie.",+ "bn": "ডাউনলোড আনজিপ করা যায়নি। আবার চেষ্টা করুন।",+ "pt-BR": "Não foi possível descompactar o download. Tente de novo.",+ "ru": "Не удалось распаковать загрузку. Попробуйте снова.",+ "id": "Unduhan tidak bisa diekstrak. Coba lagi.",+ "de": "Der Download ließ sich nicht entpacken. Versuche es noch einmal.",+ "tr": "İndirilen dosya açılamadı. Tekrar dene."+ },+ "The download didn't go through. Check your connection and try again.": {+ "zh-Hans": "下载未完成。请检查网络后重试。",+ "hi": "डाउनलोड पूरा नहीं हुआ। कनेक्शन जाँचकर फिर कोशिश करें।",+ "es": "La descarga no se completó. Revisa tu conexión e inténtalo de nuevo.",+ "ar": "لم يكتمل التنزيل. تحقق من اتصالك وأعد المحاولة.",+ "fr": "Le téléchargement n'a pas abouti. Vérifie ta connexion et réessaie.",+ "bn": "ডাউনলোড সম্পূর্ণ হয়নি। সংযোগ দেখে আবার চেষ্টা করুন।",+ "pt-BR": "O download não foi concluído. Verifique sua conexão e tente de novo.",+ "ru": "Загрузка не удалась. Проверьте подключение и попробуйте снова.",+ "id": "Unduhan gagal. Periksa koneksimu lalu coba lagi.",+ "de": "Der Download hat nicht geklappt. Prüfe deine Verbindung und versuche es noch einmal.",+ "tr": "İndirme tamamlanamadı. Bağlantını kontrol edip tekrar dene."+ },+ "Live: new messages arrive at once.": {+ "zh-Hans": "实时:新消息会立即送达。",+ "hi": "लाइव: नए संदेश तुरंत आते हैं।",+ "es": "En directo: los mensajes nuevos llegan al instante.",+ "ar": "مباشر: تصل الرسائل الجديدة فورًا.",+ "fr": "En direct : les nouveaux messages arrivent tout de suite.",+ "bn": "লাইভ: নতুন বার্তা সঙ্গে সঙ্গে আসে।",+ "pt-BR": "Ao vivo: as novas mensagens chegam na hora.",+ "ru": "В реальном времени: новые сообщения приходят сразу.",+ "id": "Langsung: pesan baru datang seketika.",+ "de": "Live: Neue Nachrichten kommen sofort an.",+ "tr": "Canlı: yeni mesajlar anında gelir."+ },+ "Port {port} is taken: pick another one. Checking every 20 s meanwhile.": {+ "zh-Hans": "端口 {port} 已被占用:请换一个。在此期间每 20 秒检查一次。",+ "hi": "पोर्ट {port} पहले से इस्तेमाल में है: कोई और चुनें। तब तक हर 20 सेकंड में जाँच।",+ "es": "El puerto {port} está ocupado: elige otro. Mientras tanto, se comprueba cada 20 s.",+ "ar": "المنفذ {port} مستخدم: اختر منفذًا آخر. في الأثناء يتم التحقق كل 20 ث.",+ "fr": "Le port {port} est déjà pris : choisis-en un autre. Vérification toutes les 20 s en attendant.",+ "bn": "পোর্ট {port} ব্যস্ত: অন্যটি বেছে নিন। ততক্ষণ প্রতি ২০ সেকেন্ডে দেখা হচ্ছে।",+ "pt-BR": "A porta {port} está ocupada: escolha outra. Enquanto isso, verificando a cada 20 s.",+ "ru": "Порт {port} занят: выберите другой. Пока проверка каждые 20 с.",+ "id": "Port {port} sudah dipakai: pilih yang lain. Sementara itu diperiksa setiap 20 dtk.",+ "de": "Port {port} ist belegt: Wähle einen anderen. Bis dahin wird alle 20 s nachgesehen.",+ "tr": "{port} numaralı bağlantı noktası kullanımda: başka birini seç. Bu arada her 20 sn’de bir kontrol ediliyor."+ },+ "The gateway refused Coucou’s address ({detail}). Checking every 20 s instead.": {+ "zh-Hans": "网关拒绝了 Coucou 的地址({detail})。改为每 20 秒检查一次。",+ "hi": "गेटवे ने Coucou का पता अस्वीकार किया ({detail})। इसके बजाय हर 20 सेकंड में जाँच।",+ "es": "La pasarela rechazó la dirección de Coucou ({detail}). Se comprueba cada 20 s en su lugar.",+ "ar": "رفضت البوابة عنوان Coucou ({detail}). يتم التحقق كل 20 ث بدلًا من ذلك.",+ "fr": "La passerelle a refusé l’adresse de Coucou ({detail}). Vérification toutes les 20 s à la place.",+ "bn": "গেটওয়ে Coucou-র ঠিকানা প্রত্যাখ্যান করেছে ({detail})। এর বদলে প্রতি ২০ সেকেন্ডে দেখা হচ্ছে।",+ "pt-BR": "O gateway recusou o endereço do Coucou ({detail}). Verificando a cada 20 s no lugar.",+ "ru": "Шлюз отклонил адрес Coucou ({detail}). Вместо этого проверка каждые 20 с.",+ "id": "Gateway menolak alamat Coucou ({detail}). Sebagai gantinya diperiksa setiap 20 dtk.",+ "de": "Das Gateway hat die Adresse von Coucou abgelehnt ({detail}). Stattdessen wird alle 20 s nachgesehen.",+ "tr": "Ağ geçidi Coucou’nun adresini reddetti ({detail}). Bunun yerine her 20 sn’de bir kontrol ediliyor."+ },+ "Checking for new messages every 20 s.": {+ "zh-Hans": "每 20 秒检查一次新消息。",+ "hi": "हर 20 सेकंड में नए संदेश जाँचे जा रहे हैं।",+ "es": "Comprobando mensajes nuevos cada 20 s.",+ "ar": "التحقق من الرسائل الجديدة كل 20 ث.",+ "fr": "Vérification des nouveaux messages toutes les 20 s.",+ "bn": "প্রতি ২০ সেকেন্ডে নতুন বার্তা দেখা হচ্ছে।",+ "pt-BR": "Verificando novas mensagens a cada 20 s.",+ "ru": "Проверка новых сообщений каждые 20 с.",+ "id": "Memeriksa pesan baru setiap 20 dtk.",+ "de": "Alle 20 s wird nach neuen Nachrichten gesehen.",+ "tr": "Yeni mesajlar her 20 sn’de bir kontrol ediliyor."+ },+ "Connected as {number}.": {+ "zh-Hans": "已连接:{number}。",+ "hi": "{number} के रूप में कनेक्टेड।",+ "es": "Conectado como {number}.",+ "ar": "متصل باسم {number}.",+ "fr": "Connecté en tant que {number}.",+ "bn": "{number} হিসেবে সংযুক্ত।",+ "pt-BR": "Conectado como {number}.",+ "ru": "Подключено как {number}.",+ "id": "Terhubung sebagai {number}.",+ "de": "Verbunden als {number}.",+ "tr": "{number} olarak bağlı."+ },+ "The gateway answers. Scan the QR code below with your phone.": {+ "zh-Hans": "网关有响应。请用手机扫描下面的二维码。",+ "hi": "गेटवे जवाब दे रहा है। नीचे दिया QR कोड फ़ोन से स्कैन करें।",+ "es": "La pasarela responde. Escanea el código QR de abajo con tu teléfono.",+ "ar": "البوابة تستجيب. امسح رمز QR أدناه بهاتفك.",+ "fr": "La passerelle répond. Scanne le QR code ci-dessous avec ton téléphone.",+ "bn": "গেটওয়ে সাড়া দিচ্ছে। নিচের QR কোডটি ফোনে স্ক্যান করুন।",+ "pt-BR": "O gateway responde. Escaneie o QR code abaixo com o celular.",+ "ru": "Шлюз отвечает. Отсканируйте QR-код ниже телефоном.",+ "id": "Gateway merespons. Pindai kode QR di bawah dengan ponselmu.",+ "de": "Das Gateway antwortet. Scanne den QR-Code unten mit deinem Handy.",+ "tr": "Ağ geçidi yanıt veriyor. Aşağıdaki QR kodunu telefonunla tara."+ },+ "The gateway answers and is connecting to WhatsApp…": {+ "zh-Hans": "网关有响应,正在连接 WhatsApp…",+ "hi": "गेटवे जवाब दे रहा है और WhatsApp से जुड़ रहा है…",+ "es": "La pasarela responde y se está conectando a WhatsApp…",+ "ar": "البوابة تستجيب وتتصل بواتساب…",+ "fr": "La passerelle répond et se connecte à WhatsApp…",+ "bn": "গেটওয়ে সাড়া দিচ্ছে এবং WhatsApp-এ সংযুক্ত হচ্ছে…",+ "pt-BR": "O gateway responde e está se conectando ao WhatsApp…",+ "ru": "Шлюз отвечает и подключается к WhatsApp…",+ "id": "Gateway merespons dan sedang terhubung ke WhatsApp…",+ "de": "Das Gateway antwortet und verbindet sich mit WhatsApp…",+ "tr": "Ağ geçidi yanıt veriyor ve WhatsApp’a bağlanıyor…"+ },+ "Phone number or chat id to ignore": {+ "zh-Hans": "要忽略的号码或聊天 ID",+ "hi": "अनदेखा करने के लिए नंबर या चैट id",+ "es": "Número o id de chat que ignorar",+ "ar": "رقم أو معرّف دردشة لتجاهله",+ "fr": "Numéro ou identifiant de chat à ignorer",+ "bn": "উপেক্ষা করার নম্বর বা চ্যাট id",+ "pt-BR": "Número ou id da conversa a ignorar",+ "ru": "Номер или id чата для игнорирования",+ "id": "Nomor atau id chat yang diabaikan",+ "de": "Telefonnummer oder Chat-ID zum Ignorieren",+ "tr": "Yok sayılacak telefon numarası veya sohbet kimliği"+ },+ "Advanced: your own gateway": {+ "zh-Hans": "高级:你自己的网关",+ "hi": "एडवांस्ड: अपना गेटवे",+ "es": "Avanzado: tu propia pasarela",+ "ar": "متقدم: بوابتك الخاصة",+ "fr": "Avancé : ta propre passerelle",+ "bn": "অ্যাডভান্সড: নিজের গেটওয়ে",+ "pt-BR": "Avançado: seu próprio gateway",+ "ru": "Дополнительно: свой шлюз",+ "id": "Lanjutan: gateway sendiri",+ "de": "Erweitert: dein eigenes Gateway",+ "tr": "Gelişmiş: kendi ağ geçidin"+ },+ "Path to the GOWA binary (whatsapp)": {+ "zh-Hans": "GOWA 程序路径(whatsapp)",+ "hi": "GOWA बाइनरी का पाथ (whatsapp)",+ "es": "Ruta del binario de GOWA (whatsapp)",+ "ar": "مسار ملف GOWA التنفيذي (whatsapp)",+ "fr": "Chemin du binaire GOWA (whatsapp)",+ "bn": "GOWA বাইনারির পাথ (whatsapp)",+ "pt-BR": "Caminho do binário do GOWA (whatsapp)",+ "ru": "Путь к бинарнику GOWA (whatsapp)",+ "id": "Jalur biner GOWA (whatsapp)",+ "de": "Pfad zur GOWA-Programmdatei (whatsapp)",+ "tr": "GOWA programının yolu (whatsapp)"+ },+ "Save WhatsApp": {+ "zh-Hans": "保存 WhatsApp",+ "hi": "WhatsApp सेव करें",+ "es": "Guardar WhatsApp",+ "ar": "حفظ واتساب",+ "fr": "Enregistrer WhatsApp",+ "bn": "WhatsApp সেভ করো",+ "pt-BR": "Salvar WhatsApp",+ "ru": "Сохранить WhatsApp",+ "id": "Simpan WhatsApp",+ "de": "WhatsApp speichern",+ "tr": "WhatsApp’ı kaydet"+ },+ "Test connection": {+ "zh-Hans": "测试连接",+ "hi": "कनेक्शन जाँचें",+ "es": "Probar la conexión",+ "ar": "اختبار الاتصال",+ "fr": "Tester la connexion",+ "bn": "সংযোগ পরীক্ষা",+ "pt-BR": "Testar a conexão",+ "ru": "Проверить подключение",+ "id": "Uji koneksi",+ "de": "Verbindung testen",+ "tr": "Bağlantıyı test et"+ },+ "Basic auth (user:password, if set)": {+ "zh-Hans": "基本认证(用户:密码,如已设置)",+ "hi": "बेसिक ऑथ (user:password, अगर सेट हो)",+ "es": "Auth básica (usuario:contraseña, si la hay)",+ "ar": "مصادقة أساسية (مستخدم:كلمة مرور، إن وُجدت)",+ "fr": "Auth basique (utilisateur:mot de passe, si activée)",+ "bn": "বেসিক অথ (user:password, থাকলে)",+ "pt-BR": "Auth básica (usuário:senha, se houver)",+ "ru": "Basic auth (пользователь:пароль, если задан)",+ "id": "Basic auth (pengguna:sandi, jika ada)",+ "de": "Basic Auth (Benutzer:Passwort, falls gesetzt)",+ "tr": "Temel kimlik doğrulama (kullanıcı:parola, ayarlıysa)"+ },+ "API key (owa_k1_…)": {+ "zh-Hans": "API 密钥(owa_k1_…)",+ "hi": "API कुंजी (owa_k1_…)",+ "es": "Clave API (owa_k1_…)",+ "ar": "مفتاح API (owa_k1_…)",+ "fr": "Clé API (owa_k1_…)",+ "bn": "API কী (owa_k1_…)",+ "pt-BR": "Chave de API (owa_k1_…)",+ "ru": "API-ключ (owa_k1_…)",+ "id": "Kunci API (owa_k1_…)",+ "de": "API-Schlüssel (owa_k1_…)",+ "tr": "API anahtarı (owa_k1_…)"+ },+ "Start GOWA automatically": {+ "zh-Hans": "自动启动 GOWA",+ "hi": "GOWA अपने-आप शुरू करें",+ "es": "Iniciar GOWA automáticamente",+ "ar": "تشغيل GOWA تلقائيًا",+ "fr": "Lancer GOWA automatiquement",+ "bn": "GOWA স্বয়ংক্রিয়ভাবে চালু করো",+ "pt-BR": "Iniciar o GOWA automaticamente",+ "ru": "Запускать GOWA автоматически",+ "id": "Jalankan GOWA otomatis",+ "de": "GOWA automatisch starten",+ "tr": "GOWA’yı otomatik başlat"+ },+ "Update": {+ "zh-Hans": "更新",+ "hi": "अपडेट करें",+ "es": "Actualizar",+ "ar": "تحديث",+ "fr": "Mettre à jour",+ "bn": "আপডেট করো",+ "pt-BR": "Atualizar",+ "ru": "Обновить",+ "id": "Perbarui",+ "de": "Aktualisieren",+ "tr": "Güncelle"+ },+ "Gateway GOWA {version} installed, started by Coucou": {+ "zh-Hans": "GOWA {version} 网关已安装,由 Coucou 启动",+ "hi": "GOWA {version} गेटवे इंस्टॉल है, Coucou इसे चलाता है",+ "es": "Pasarela GOWA {version} instalada, iniciada por Coucou",+ "ar": "بوابة GOWA {version} مثبّتة ويشغّلها Coucou",+ "fr": "Passerelle GOWA {version} installée, lancée par Coucou",+ "bn": "GOWA {version} গেটওয়ে ইনস্টল, Coucou চালায়",+ "pt-BR": "Gateway GOWA {version} instalado, iniciado pelo Coucou",+ "ru": "Шлюз GOWA {version} установлен, запускается Coucou",+ "id": "Gateway GOWA {version} terpasang, dijalankan oleh Coucou",+ "de": "Gateway GOWA {version} installiert, von Coucou gestartet",+ "tr": "GOWA {version} ağ geçidi kuruldu, Coucou tarafından başlatıldı"+ },+ "Your GOWA gateway is set up": {+ "zh-Hans": "你的 GOWA 网关已设置",+ "hi": "आपका GOWA गेटवे सेट है",+ "es": "Tu pasarela GOWA está configurada",+ "ar": "بوابة GOWA الخاصة بك مُعدّة",+ "fr": "Ta passerelle GOWA est configurée",+ "bn": "আপনার GOWA গেটওয়ে সেট করা আছে",+ "pt-BR": "Seu gateway GOWA está configurado",+ "ru": "Ваш шлюз GOWA настроен",+ "id": "Gateway GOWA-mu sudah diatur",+ "de": "Dein GOWA-Gateway ist eingerichtet",+ "tr": "GOWA ağ geçidin ayarlandı"+ },+ "Install WhatsApp": {+ "zh-Hans": "安装 WhatsApp",+ "hi": "WhatsApp इंस्टॉल करें",+ "es": "Instalar WhatsApp",+ "ar": "تثبيت واتساب",+ "fr": "Installer WhatsApp",+ "bn": "WhatsApp ইনস্টল করো",+ "pt-BR": "Instalar o WhatsApp",+ "ru": "Установить WhatsApp",+ "id": "Pasang WhatsApp",+ "de": "WhatsApp installieren",+ "tr": "WhatsApp’ı kur"+ },+ "Connected as {number}": {+ "zh-Hans": "已连接:{number}",+ "hi": "{number} के रूप में कनेक्टेड",+ "es": "Conectado como {number}",+ "ar": "متصل باسم {number}",+ "fr": "Connecté en tant que {number}",+ "bn": "{number} হিসেবে সংযুক্ত",+ "pt-BR": "Conectado como {number}",+ "ru": "Подключено как {number}",+ "id": "Terhubung sebagai {number}",+ "de": "Verbunden als {number}",+ "tr": "{number} olarak bağlı"+ },+ "On your phone: WhatsApp › Settings › Linked devices › Link a device, then scan this code.": {+ "zh-Hans": "在手机上:WhatsApp › 设置 › 已关联的设备 › 关联新设备,然后扫描此二维码。",+ "hi": "फ़ोन पर: WhatsApp › सेटिंग्स › लिंक किए गए डिवाइस › डिवाइस लिंक करें, फिर यह कोड स्कैन करें।",+ "es": "En tu teléfono: WhatsApp › Ajustes › Dispositivos vinculados › Vincular un dispositivo, y escanea este código.",+ "ar": "على هاتفك: واتساب › الإعدادات › الأجهزة المرتبطة › ربط جهاز، ثم امسح هذا الرمز.",+ "fr": "Sur ton téléphone : WhatsApp › Réglages › Appareils connectés › Connecter un appareil, puis scanne ce code.",+ "bn": "ফোনে: WhatsApp › সেটিংস › লিঙ্ক করা ডিভাইস › ডিভাইস লিঙ্ক করুন, তারপর এই কোডটি স্ক্যান করুন।",+ "pt-BR": "No celular: WhatsApp › Configurações › Dispositivos conectados › Conectar dispositivo, e escaneie este código.",+ "ru": "На телефоне: WhatsApp › Настройки › Связанные устройства › Привязка устройства, затем отсканируйте этот код.",+ "id": "Di ponsel: WhatsApp › Setelan › Perangkat tertaut › Tautkan perangkat, lalu pindai kode ini.",+ "de": "Auf deinem Handy: WhatsApp › Einstellungen › Verknüpfte Geräte › Gerät hinzufügen, dann diesen Code scannen.",+ "tr": "Telefonunda: WhatsApp › Ayarlar › Bağlı cihazlar › Cihaz bağla, sonra bu kodu tara."+ },+ "Gateway": {+ "zh-Hans": "网关",+ "hi": "गेटवे",+ "es": "Pasarela",+ "ar": "البوابة",+ "fr": "Passerelle",+ "bn": "গেটওয়ে",+ "pt-BR": "Gateway",+ "ru": "Шлюз",+ "id": "Gateway",+ "de": "Gateway",+ "tr": "Ağ geçidi"+ },+ "Coucou’s webhook port": {+ "zh-Hans": "Coucou 的 Webhook 端口",+ "hi": "Coucou का वेबहुक पोर्ट",+ "es": "Puerto del webhook de Coucou",+ "ar": "منفذ webhook في Coucou",+ "fr": "Port du webhook de Coucou",+ "bn": "Coucou-র ওয়েবহুক পোর্ট",+ "pt-BR": "Porta do webhook do Coucou",+ "ru": "Порт вебхука Coucou",+ "id": "Port webhook Coucou",+ "de": "Webhook-Port von Coucou",+ "tr": "Coucou’nun webhook bağlantı noktası"+ },+ "Mute groups (unless I’m mentioned)": {+ "zh-Hans": "群组静音(除非提到我)",+ "hi": "ग्रुप म्यूट करें (जब तक मेरा ज़िक्र न हो)",+ "es": "Silenciar grupos (salvo si me mencionan)",+ "ar": "كتم المجموعات (إلا إذا أُشير إليّ)",+ "fr": "Groupes muets (sauf si on me mentionne)",+ "bn": "গ্রুপ মিউট (আমাকে উল্লেখ না করলে)",+ "pt-BR": "Silenciar grupos (exceto quando me mencionam)",+ "ru": "Без звука в группах (если меня не упомянули)",+ "id": "Bisukan grup (kecuali saya disebut)",+ "de": "Gruppen stummschalten (außer ich werde erwähnt)",+ "tr": "Grupları sessize al (benden bahsedilmedikçe)"+ },+ "Mark as read when I open a conversation": {+ "zh-Hans": "打开对话时标记为已读",+ "hi": "बातचीत खोलने पर पढ़ा हुआ मार्क करें",+ "es": "Marcar como leído al abrir una conversación",+ "ar": "تعليم كمقروء عند فتح محادثة",+ "fr": "Marquer comme lu quand j’ouvre une conversation",+ "bn": "কথোপকথন খুললে পড়া হিসেবে চিহ্নিত করো",+ "pt-BR": "Marcar como lida ao abrir uma conversa",+ "ru": "Отмечать прочитанным при открытии беседы",+ "id": "Tandai dibaca saat saya membuka percakapan",+ "de": "Als gelesen markieren, wenn ich eine Unterhaltung öffne",+ "tr": "Bir sohbeti açtığımda okundu olarak işaretle"+ },+ "Off: marked read only when you reply. Never when a message just arrives.": {+ "zh-Hans": "关闭时:仅在你回复时标记为已读。收到消息时从不标记。",+ "hi": "बंद: सिर्फ़ जवाब देने पर पढ़ा हुआ। संदेश आने भर से कभी नहीं।",+ "es": "Desactivado: se marca como leído solo al responder. Nunca solo por recibirlo.",+ "ar": "عند الإيقاف: تُعلَّم كمقروءة فقط عند الرد. لا تُعلَّم أبدًا لمجرد الوصول.",+ "fr": "Désactivé : marqué comme lu seulement quand tu réponds. Jamais à la simple réception.",+ "bn": "বন্ধ: শুধু উত্তর দিলে পড়া হিসেবে চিহ্নিত। বার্তা এলেই কখনও নয়।",+ "pt-BR": "Desativado: marcada como lida só quando você responde. Nunca só por chegar.",+ "ru": "Выключено: прочитанным отмечается только при ответе. Никогда при простом получении.",+ "id": "Mati: ditandai dibaca hanya saat kamu membalas. Tidak pernah hanya karena pesan masuk.",+ "de": "Aus: nur als gelesen markiert, wenn du antwortest. Nie, wenn eine Nachricht nur ankommt.",+ "tr": "Kapalı: yalnızca yanıt verdiğinde okundu olarak işaretlenir. Bir mesaj yalnızca geldiğinde asla."+ },+ "Ignored chats": {+ "zh-Hans": "已忽略的聊天",+ "hi": "अनदेखी चैट",+ "es": "Chats ignorados",+ "ar": "الدردشات المتجاهَلة",+ "fr": "Chats ignorés",+ "bn": "উপেক্ষিত চ্যাট",+ "pt-BR": "Conversas ignoradas",+ "ru": "Игнорируемые чаты",+ "id": "Chat yang diabaikan",+ "de": "Ignorierte Chats",+ "tr": "Yok sayılan sohbetler"+ },+ "WhatsApp (experimental)": {+ "zh-Hans": "WhatsApp(实验性)",+ "hi": "WhatsApp (प्रायोगिक)",+ "es": "WhatsApp (experimental)",+ "ar": "واتساب (تجريبي)",+ "fr": "WhatsApp (expérimental)",+ "bn": "WhatsApp (পরীক্ষামূলক)",+ "pt-BR": "WhatsApp (experimental)",+ "ru": "WhatsApp (экспериментально)",+ "id": "WhatsApp (eksperimental)",+ "de": "WhatsApp (experimentell)",+ "tr": "WhatsApp (deneysel)"+ },+ "Show my WhatsApp messages": {+ "zh-Hans": "显示我的 WhatsApp 消息",+ "hi": "मेरे WhatsApp संदेश दिखाएँ",+ "es": "Mostrar mis mensajes de WhatsApp",+ "ar": "عرض رسائل واتساب",+ "fr": "Afficher mes messages WhatsApp",+ "bn": "আমার WhatsApp বার্তা দেখাও",+ "pt-BR": "Mostrar minhas mensagens do WhatsApp",+ "ru": "Показывать мои сообщения WhatsApp",+ "id": "Tampilkan pesan WhatsApp saya",+ "de": "Meine WhatsApp-Nachrichten anzeigen",+ "tr": "WhatsApp mesajlarımı göster"+ },+ "Ignore this chat": {+ "zh-Hans": "忽略此聊天",+ "hi": "इस चैट को अनदेखा करें",+ "es": "Ignorar este chat",+ "ar": "تجاهل هذه الدردشة",+ "fr": "Ignorer ce chat",+ "bn": "এই চ্যাট উপেক্ষা করো",+ "pt-BR": "Ignorar esta conversa",+ "ru": "Игнорировать этот чат",+ "id": "Abaikan chat ini",+ "de": "Diesen Chat ignorieren",+ "tr": "Bu sohbeti yok say"+ },+ "No new messages": {+ "zh-Hans": "没有新消息",+ "hi": "कोई नया संदेश नहीं",+ "es": "No hay mensajes nuevos",+ "ar": "لا رسائل جديدة",+ "fr": "Aucun nouveau message",+ "bn": "নতুন বার্তা নেই",+ "pt-BR": "Nenhuma mensagem nova",+ "ru": "Нет новых сообщений",+ "id": "Tidak ada pesan baru",+ "de": "Keine neuen Nachrichten",+ "tr": "Yeni mesaj yok"+ },+ "No GOWA build for this computer was found on GitHub. Try again later, or set your own gateway under Advanced.": {+ "zh-Hans": "GitHub 上没有适用于此电脑的 GOWA 版本。请稍后重试,或在“高级”中设置你自己的网关。",+ "hi": "GitHub पर इस कंप्यूटर के लिए GOWA नहीं मिला। बाद में फिर कोशिश करें, या एडवांस्ड में अपना गेटवे सेट करें।",+ "es": "No hay ninguna versión de GOWA para este ordenador en GitHub. Inténtalo más tarde o configura tu propia pasarela en Avanzado.",+ "ar": "لا يوجد إصدار من GOWA لهذا الحاسوب على GitHub. أعد المحاولة لاحقًا أو اضبط بوابتك في «متقدم».",+ "fr": "Aucune version de GOWA pour cet ordinateur sur GitHub. Réessaie plus tard, ou configure ta propre passerelle dans Avancé.",+ "bn": "GitHub-এ এই কম্পিউটারের জন্য GOWA পাওয়া যায়নি। পরে আবার চেষ্টা করুন, বা অ্যাডভান্সডে নিজের গেটওয়ে সেট করুন।",+ "pt-BR": "Nenhuma versão do GOWA para este computador no GitHub. Tente mais tarde ou configure seu próprio gateway em Avançado.",+ "ru": "На GitHub нет сборки GOWA для этого компьютера. Попробуйте позже или укажите свой шлюз в разделе «Дополнительно».",+ "id": "Tidak ada versi GOWA untuk komputer ini di GitHub. Coba lagi nanti, atau atur gateway sendiri di Lanjutan.",+ "de": "Auf GitHub gibt es keine GOWA-Version für diesen Computer. Versuche es später noch einmal oder richte unter „Erweitert“ dein eigenes Gateway ein.",+ "tr": "GitHub’da bu bilgisayar için GOWA sürümü bulunamadı. Daha sonra tekrar dene ya da Gelişmiş bölümünden kendi ağ geçidini ayarla."+ },+ "Coucou runs it on this computer only (127.0.0.1, the URL’s port), without downloading media, and stops it when Coucou quits. Its WhatsApp session stays in {path}.": {+ "zh-Hans": "Coucou 仅在这台电脑上运行它(127.0.0.1,使用地址中的端口),不下载媒体,并在 Coucou 退出时停止它。其 WhatsApp 会话保存在 {path}。",+ "hi": "Coucou इसे सिर्फ़ इस कंप्यूटर पर चलाता है (127.0.0.1, URL का पोर्ट), मीडिया डाउनलोड किए बिना, और Coucou बंद होने पर रोक देता है। इसका WhatsApp सेशन {path} में रहता है।",+ "es": "Coucou lo ejecuta solo en este ordenador (127.0.0.1, el puerto de la URL), sin descargar archivos, y lo detiene al cerrar Coucou. Su sesión de WhatsApp queda en {path}.",+ "ar": "يشغّله Coucou على هذا الحاسوب فقط (127.0.0.1، منفذ العنوان)، دون تنزيل الوسائط، ويوقفه عند إغلاق Coucou. تبقى جلسة واتساب في {path}.",+ "fr": "Coucou le lance sur cet ordinateur uniquement (127.0.0.1, le port de l’URL), sans télécharger les médias, et l’arrête quand Coucou quitte. Sa session WhatsApp reste dans {path}.",+ "bn": "Coucou এটি শুধু এই কম্পিউটারে চালায় (127.0.0.1, URL-এর পোর্ট), মিডিয়া ডাউনলোড ছাড়াই, এবং Coucou বন্ধ হলে থামিয়ে দেয়। এর WhatsApp সেশন থাকে {path}-তে।",+ "pt-BR": "O Coucou o executa só neste computador (127.0.0.1, a porta da URL), sem baixar mídias, e o encerra quando o Coucou fecha. A sessão do WhatsApp fica em {path}.",+ "ru": "Coucou запускает его только на этом компьютере (127.0.0.1, порт из адреса), без загрузки медиа, и останавливает при выходе. Сессия WhatsApp хранится в {path}.",+ "id": "Coucou menjalankannya hanya di komputer ini (127.0.0.1, port dari URL), tanpa mengunduh media, dan menghentikannya saat Coucou ditutup. Sesi WhatsApp-nya ada di {path}.",+ "de": "Coucou startet es nur auf diesem Computer (127.0.0.1, der Port der Adresse), ohne Medien zu laden, und beendet es, wenn Coucou beendet wird. Seine WhatsApp-Sitzung bleibt in {path}.",+ "tr": "Coucou onu yalnızca bu bilgisayarda (127.0.0.1, adresteki bağlantı noktası), medya indirmeden çalıştırır ve Coucou kapanınca durdurur. WhatsApp oturumu {path} içinde kalır."+ },+ "Coucou downloads GOWA, the open-source gateway, from its GitHub page (about 15 MB, once), checks it and starts it. Then scan the QR code with your phone. No command line needed.": {+ "zh-Hans": "Coucou 会从 GitHub 页面下载开源网关 GOWA(约 15 MB,仅一次),校验后启动。然后用手机扫描二维码即可。无需命令行。",+ "hi": "Coucou ओपन-सोर्स गेटवे GOWA को उसके GitHub पेज से डाउनलोड करता है (लगभग 15 MB, सिर्फ़ एक बार), जाँचता है और चालू करता है। फिर फ़ोन से QR कोड स्कैन करें। कमांड लाइन की ज़रूरत नहीं।",+ "es": "Coucou descarga GOWA, la pasarela de código abierto, desde su página de GitHub (unos 15 MB, una sola vez), la comprueba y la inicia. Luego escanea el código QR con tu teléfono. Sin línea de comandos.",+ "ar": "يُنزّل Coucou بوابة GOWA مفتوحة المصدر من صفحتها على GitHub (نحو 15 ميغابايت، مرة واحدة)، ويتحقق منها ويشغّلها. ثم امسح رمز QR بهاتفك. لا حاجة إلى سطر الأوامر.",+ "fr": "Coucou télécharge GOWA, la passerelle open source, depuis sa page GitHub (environ 15 Mo, une seule fois), la vérifie et la lance. Ensuite, scanne le QR code avec ton téléphone. Pas besoin de ligne de commande.",+ "bn": "Coucou ওপেন-সোর্স গেটওয়ে GOWA তার GitHub পেজ থেকে ডাউনলোড করে (প্রায় ১৫ MB, একবারই), যাচাই করে চালু করে। তারপর ফোন দিয়ে QR কোড স্ক্যান করুন। কমান্ড লাইন লাগবে না।",+ "pt-BR": "O Coucou baixa o GOWA, o gateway de código aberto, da página dele no GitHub (cerca de 15 MB, uma única vez), verifica e inicia. Depois, escaneie o QR code com o celular. Sem linha de comando.",+ "ru": "Coucou скачивает GOWA, шлюз с открытым кодом, с его страницы на GitHub (около 15 МБ, один раз), проверяет и запускает. Затем отсканируйте QR-код телефоном. Командная строка не нужна.",+ "id": "Coucou mengunduh GOWA, gateway open source, dari halaman GitHub-nya (sekitar 15 MB, sekali saja), memeriksanya lalu menjalankannya. Lalu pindai kode QR dengan ponselmu. Tanpa baris perintah.",+ "de": "Coucou lädt GOWA, das Open-Source-Gateway, von seiner GitHub-Seite (etwa 15 MB, einmalig), prüft es und startet es. Danach scannst du den QR-Code mit deinem Handy. Keine Kommandozeile nötig.",+ "tr": "Coucou, açık kaynaklı ağ geçidi GOWA’yı GitHub sayfasından indirir (yaklaşık 15 MB, bir kez), doğrular ve başlatır. Ardından QR kodunu telefonunla tara. Komut satırına gerek yok."+ },+ "Coucou only talks to the gateway on this computer. Messages stay in memory, are never logged or saved, and are forgotten when Coucou quits. No photo or media is ever downloaded.": {+ "zh-Hans": "Coucou 只与这台电脑上的网关通信。消息只保存在内存中,从不记录或保存,退出 Coucou 时即被清除。从不下载任何照片或媒体。",+ "hi": "Coucou सिर्फ़ इस कंप्यूटर पर चल रहे गेटवे से बात करता है। संदेश मेमोरी में रहते हैं, कभी लॉग या सेव नहीं होते, और Coucou बंद होने पर भुला दिए जाते हैं। कोई फ़ोटो या मीडिया डाउनलोड नहीं होता।",+ "es": "Coucou solo habla con la pasarela de este ordenador. Los mensajes se quedan en memoria, nunca se registran ni se guardan, y se olvidan al cerrar Coucou. Nunca se descarga ninguna foto ni archivo.",+ "ar": "يتواصل Coucou فقط مع البوابة على هذا الحاسوب. تبقى الرسائل في الذاكرة، ولا تُسجَّل ولا تُحفَظ أبدًا، وتُنسى عند إغلاق Coucou. لا تُنزَّل أي صورة أو وسائط.",+ "fr": "Coucou ne parle qu’à la passerelle sur cet ordinateur. Les messages restent en mémoire, ne sont jamais journalisés ni enregistrés, et sont oubliés quand Coucou quitte. Aucune photo ni aucun média n’est téléchargé.",+ "bn": "Coucou শুধু এই কম্পিউটারের গেটওয়ের সঙ্গে কথা বলে। বার্তা মেমরিতে থাকে, কখনও লগ বা সেভ হয় না, এবং Coucou বন্ধ হলে মুছে যায়। কোনো ছবি বা মিডিয়া ডাউনলোড হয় না।",+ "pt-BR": "O Coucou só fala com o gateway neste computador. As mensagens ficam na memória, nunca são registradas nem salvas e são esquecidas quando o Coucou fecha. Nenhuma foto ou mídia é baixada.",+ "ru": "Coucou общается только со шлюзом на этом компьютере. Сообщения хранятся в памяти, никогда не пишутся в журнал и не сохраняются, и забываются при выходе из Coucou. Фото и медиа не загружаются.",+ "id": "Coucou hanya berbicara dengan gateway di komputer ini. Pesan tetap di memori, tidak pernah dicatat atau disimpan, dan dilupakan saat Coucou ditutup. Tidak ada foto atau media yang diunduh.",+ "de": "Coucou spricht nur mit dem Gateway auf diesem Computer. Nachrichten bleiben im Arbeitsspeicher, werden nie protokolliert oder gespeichert und beim Beenden von Coucou vergessen. Es werden nie Fotos oder Medien geladen.",+ "tr": "Coucou yalnızca bu bilgisayardaki ağ geçidiyle konuşur. Mesajlar bellekte kalır, asla günlüğe yazılmaz veya kaydedilmez ve Coucou kapanınca unutulur. Hiçbir fotoğraf veya medya indirilmez."+ },+ "Unofficial integration: it goes through a gateway you run on this computer. Use it on your own account only. WhatsApp may restrict accounts that abuse it.": {+ "zh-Hans": "非官方集成:通过你在这台电脑上运行的网关工作。仅限用于你自己的账号。滥用时 WhatsApp 可能会限制账号。",+ "hi": "अनौपचारिक इंटीग्रेशन: यह इस कंप्यूटर पर चल रहे गेटवे से होकर काम करता है। सिर्फ़ अपने अकाउंट पर इस्तेमाल करें। दुरुपयोग पर WhatsApp अकाउंट सीमित कर सकता है।",+ "es": "Integración no oficial: pasa por una pasarela que ejecutas en este ordenador. Úsala solo con tu propia cuenta. WhatsApp puede restringir las cuentas que abusen.",+ "ar": "تكامل غير رسمي: يمرّ عبر بوابة تشغّلها على هذا الحاسوب. استخدمه على حسابك فقط. قد يقيّد واتساب الحسابات عند إساءة الاستخدام.",+ "fr": "Intégration non officielle : elle passe par une passerelle que tu lances sur cet ordinateur. À utiliser sur ton propre compte uniquement. WhatsApp peut restreindre un compte en cas d’abus.",+ "bn": "অনানুষ্ঠানিক ইন্টিগ্রেশন: এটি এই কম্পিউটারে চালানো একটি গেটওয়ে দিয়ে কাজ করে। শুধু নিজের অ্যাকাউন্টে ব্যবহার করুন। অপব্যবহারে WhatsApp অ্যাকাউন্ট সীমিত করতে পারে।",+ "pt-BR": "Integração não oficial: passa por um gateway que você executa neste computador. Use só na sua própria conta. O WhatsApp pode restringir contas em caso de abuso.",+ "ru": "Неофициальная интеграция: работает через шлюз, запущенный на этом компьютере. Используйте только со своим аккаунтом. WhatsApp может ограничить аккаунт при злоупотреблении.",+ "id": "Integrasi tidak resmi: berjalan lewat gateway yang kamu jalankan di komputer ini. Gunakan hanya di akunmu sendiri. WhatsApp bisa membatasi akun yang menyalahgunakannya.",+ "de": "Inoffizielle Integration: Sie läuft über ein Gateway, das du auf diesem Computer betreibst. Nutze sie nur mit deinem eigenen Konto. WhatsApp kann Konten einschränken, die sie missbrauchen.",+ "tr": "Resmî olmayan entegrasyon: bu bilgisayarda çalıştırdığın bir ağ geçidi üzerinden çalışır. Yalnızca kendi hesabında kullan. WhatsApp kötüye kullanan hesapları kısıtlayabilir."+ },+ "Reply… (Shift+Enter: new line)": {+ "zh-Hans": "回复…(Shift+Enter:换行)",+ "hi": "जवाब दें… (Shift+Enter: नई लाइन)",+ "es": "Responder… (Mayús+Intro: nueva línea)",+ "ar": "رد… (Shift+Enter: سطر جديد)",+ "fr": "Répondre… (Maj+Entrée : nouvelle ligne)",+ "bn": "উত্তর দিন… (Shift+Enter: নতুন লাইন)",+ "pt-BR": "Responder… (Shift+Enter: nova linha)",+ "ru": "Ответить… (Shift+Enter — новая строка)",+ "id": "Balas… (Shift+Enter: baris baru)",+ "de": "Antworten… (Umschalt+Eingabe: neue Zeile)",+ "tr": "Yanıtla… (Shift+Enter: yeni satır)"+ },+ "Turn off another pill to make room for WhatsApp ({max} at most).": {+ "zh-Hans": "请关闭另一个胶囊,为 WhatsApp 腾出位置(最多 {max} 个)。",+ "hi": "WhatsApp के लिए जगह बनाने हेतु कोई दूसरी पिल बंद करें (अधिकतम {max})।",+ "es": "Desactiva otra píldora para hacer sitio a WhatsApp ({max} como máximo).",+ "ar": "أوقف حبة أخرى لإفساح مكان لواتساب ({max} كحد أقصى).",+ "fr": "Désactive une autre pill pour faire de la place à WhatsApp ({max} au maximum).",+ "bn": "WhatsApp-এর জন্য জায়গা করতে অন্য একটি পিল বন্ধ করুন (সর্বোচ্চ {max}টি)।",+ "pt-BR": "Desative outra pílula para abrir espaço para o WhatsApp (no máximo {max}).",+ "ru": "Отключите другую пилюлю, чтобы освободить место для WhatsApp (не больше {max}).",+ "id": "Matikan pil lain untuk memberi tempat bagi WhatsApp (maksimal {max}).",+ "de": "Schalte eine andere Pill aus, um Platz für WhatsApp zu schaffen (höchstens {max}).",+ "tr": "WhatsApp’a yer açmak için başka bir hapı kapat (en fazla {max})."}}}diff --git a/windows/src/island/island.ts b/windows/src/island/island.tsindex be20bdd8..13158dca 100644--- a/windows/src/island/island.ts+++ b/windows/src/island/island.ts@@ -90,6 +90,8 @@ export class Island {private collapsed = false;private collapseTimer: number | null = null;private wasInIsland = false;+ /** A reply is being typed in a card (WhatsApp): the island stays open. */+ private holdingOpen = false;/** Last shape handed to Rust for the click-through test. */private pushedRect = { x: -1, y: -1, w: -1, h: -1 };@@ -191,6 +193,8 @@ export class Island {integration_stripe: "https://dashboard.stripe.com/payments",integration_notion: "https://notion.so",integration_calcom: "https://app.cal.com/bookings",+ // No WhatsApp app to bring forward here as on the Mac: WhatsApp Web, in the browser.+ integration_whatsapp: "https://web.whatsapp.com",};if (task.id === CLAUDE_DESKTOP_ID) void Bridge.openClaudeDesktop();else if (task.id === "integration_claude" || task.sessionId) {@@ -257,6 +261,22 @@ export class Island {State.wardrobePreview = outfit;State.notify();},+ keyboard: (on) => {+ // The chat view manages the keyboard on its own.+ if (on) void Bridge.focusWindow(true);+ else if (State.view !== "prompt" && State.mode === "expanded") void Bridge.focusWindow(false);+ },+ holdOpen: (on) => {+ if (this.holdingOpen === on) return;+ this.holdingOpen = on;+ if (on) {+ this.fsm.pinned = true;+ this.fsm.cancelTimers();+ } else {+ this.fsm.pinned = State.isPinned || State.pendingApproval != null;+ if (!this.fsm.pinned && !this.wasInIsland && this.fsm.state === "home") this.fsm.mouseLeft();+ }+ },};this.wakeStrip = h("div", { id: "wake-strip" });diff --git a/windows/src/island/whatsapp.ts b/windows/src/island/whatsapp.tsnew file mode 100644index 00000000..9edc4820--- /dev/null+++ b/windows/src/island/whatsapp.ts@@ -0,0 +1,93 @@+// WhatsApp's reports → the page (src-tauri/src/whatsapp). The parts of WhatsAppController.swift that+// touch the island: a new message lights the pill with the conversation's name (never the text),+// Mochi smiles and the "pop" sound plays — once for a burst, not ten times — and the pill goes back+// to idle a minute later; the pill gets its small red dot while the gateway is down.++import { Bridge, onEvent } from "../core/bridge";+import { Sound } from "../core/sound";+import { State } from "../core/state";+import { WHATSAPP_ID, WhatsApp, type WaIslandView } from "../core/whatsapp";+import type { BotEmoteName } from "../core/layout";++export interface WhatsAppHost {+ /** The compact island, so the badge is seen. */+ reveal(): void;+ emote(name: BotEmoteName): void;+}++export type WaPillEvent = { kind: "message"; name: string } | { kind: "read" } | { kind: "reset" };++/** A burst of messages is one reaction. */+const ANNOUNCE_GAP_MS = 4_000;+const RESET_AFTER_MS = 60_000;++let lastAnnounce = -Infinity;+let resetTimer: number | null = null;++export function registerWhatsAppHandlers(island: WhatsAppHost) {+ void onEvent<WaIslandView>("whatsapp", applyWhatsApp);+ void onEvent<WaPillEvent>("whatsapp-pill", (e) => handlePillEvent(island, e));+ void Bridge.whatsappIsland().then((view) => {+ if (view) applyWhatsApp(view);+ });+}++function task() {+ return State.tasks.find((x) => x.id === WHATSAPP_ID);+}++/** A report from Rust: the card redraws, the pill's red dot follows the gateway. */+export function applyWhatsApp(view: WaIslandView) {+ const wasDown = WhatsApp.view.down;+ WhatsApp.view = view;+ const t = task();+ if (t && view.down !== wasDown) {+ if (view.down) t.pillBadge = "error";+ else if (t.pillBadge === "error") t.pillBadge = null;+ }+ State.notify();+}++export function handlePillEvent(island: WhatsAppHost, e: WaPillEvent, now = performance.now()) {+ const t = task();+ if (!t) return;+ switch (e.kind) {+ case "message": {+ if (State.paused) return;+ t.state = "finished";+ t.steps = [e.name];+ t.stepIndex = 0;+ if (State.focusId !== WHATSAPP_ID) t.pillBadge = "finished";+ if (now - lastAnnounce > ANNOUNCE_GAP_MS) {+ lastAnnounce = now;+ island.emote("happy");+ Sound.play("pop");+ }+ island.reveal();+ if (resetTimer != null) window.clearTimeout(resetTimer);+ resetTimer = window.setTimeout(() => {+ resetTimer = null;+ const x = task();+ if (!x || x.state !== "finished") return;+ x.state = "idle";+ x.steps = [];+ x.stepIndex = 0;+ if (x.pillBadge === "finished") x.pillBadge = null;+ State.notify();+ }, RESET_AFTER_MS);+ break;+ }+ case "read":+ if (t.pillBadge === "finished") t.pillBadge = null;+ break;+ case "reset":+ if (resetTimer != null) window.clearTimeout(resetTimer);+ resetTimer = null;+ t.state = "idle";+ t.steps = [];+ t.stepIndex = 0;+ t.pillBadge = null;+ break;+ }+ State.notify();+}diff --git a/windows/src/main.ts b/windows/src/main.tsindex 7723e00a..b199a83c 100644--- a/windows/src/main.ts+++ b/windows/src/main.ts@@ -11,6 +11,7 @@ import { registerIntegrationHandlers, refreshConfigured } from "./island/integraimport { registerShortcutHandlers } from "./island/shortcuts";import { registerVoiceHandlers } from "./island/voice";import { applySpotify, registerSpotifyHandlers } from "./island/spotify";+import { registerWhatsAppHandlers } from "./island/whatsapp";import { SPOTIFY_ID } from "./core/spotify";import { Recap } from "./recap/recap";import { Updates } from "./island/update";@@ -148,6 +149,7 @@ async function main() {registerShortcutHandlers(island, () => setPaused(false));registerVoiceHandlers();registerSpotifyHandlers(island);+ registerWhatsAppHandlers(island);// New versions: Rust offers the card, the island opens it when nothing else waits.await Updates.register(island);// Rust may have read Spotify before this page listened: ask once.diff --git a/windows/src/settings/main.ts b/windows/src/settings/main.tsindex 19434f34..7d086b82 100644--- a/windows/src/settings/main.ts+++ b/windows/src/settings/main.ts@@ -22,6 +22,8 @@ import { startHub, type PageId } from "../hub/shell";import { FLOW_PAGE_RENDERERS } from "../hub/pages";import { agentsSection } from "./agents";import { phoneSection } from "./phone";+import { whatsappSection } from "./whatsapp";+import { WHATSAPP_ID } from "../core/whatsapp";import { updateRows, updatesListener } from "./updates";import { colorDot } from "./colors";import { renderDiff, statusDot } from "./parts";@@ -892,6 +894,27 @@ function integrationsSection(present: Record<string, boolean>): HTMLElement {return h("section", {}, h("h2", {}, h("span", { text: t("Integrations") })), note, list);}+/** WhatsApp (experimental), under the other integrations: its pill is turned on from its own switch. */+function whatsappSections(): HTMLElement[] {+ if (!availablePills().some((p) => p.id === WHATSAPP_ID)) return [];+ return [whatsappSection({+ toggle,+ maxPills: MAX_ACTIVE,+ pillActive: () => settings.activeIntegrations.includes(WHATSAPP_ID),+ setPill: (on) => {+ const has = settings.activeIntegrations.includes(WHATSAPP_ID);+ if (on && !has && settings.activeIntegrations.length < MAX_ACTIVE) {+ settings.activeIntegrations = [...settings.activeIntegrations, WHATSAPP_ID];+ } else if (!on && has) {+ settings.activeIntegrations = settings.activeIntegrations.filter((x) => x !== WHATSAPP_ID);+ } else {+ return;+ }+ declaredChanged();+ },+ })];+}+// ── General section ───────────────────────────────────────────────────────────function generalSection(): HTMLElement {@@ -1379,7 +1402,7 @@ async function render() {pills: () => [activePillsSection(connected)],agents: () => [claudeSection(status), agentsSection(agents), planSection(status)],chat: () => [apiSection(hasKey), chatProvidersSection(chatKeys, keyChanged), localSection(customKey)],- integrations: () => [integrationsSection(present)],+ integrations: () => [integrationsSection(present), ...whatsappSections()],phone: () => [phoneSection(settings.phoneLink ?? false, toggle, settings)],shortcuts: () => [shortcutsSection(shortcutReport)],};diff --git a/windows/src/settings/whatsapp.ts b/windows/src/settings/whatsapp.tsnew file mode 100644index 00000000..3b68c64c--- /dev/null+++ b/windows/src/settings/whatsapp.ts@@ -0,0 +1,328 @@+// Settings → Integrations → WhatsApp (experimental) — a port of WhatsAppSettingsSection+// (WhatsAppViews.swift). Off until turned on. "Install WhatsApp" downloads GOWA from its GitHub+// releases on that click only; the QR to link WhatsApp shows right here. The gateway's address and+// credential go to the credential store through Rust, which never hands the credential back.++import { Bridge, onEvent } from "../core/bridge";+import {+ DEFAULT_PORT, DEFAULT_URLS, WHATSAPP_GREEN, installError, installStepLabel, isInstalling, linkColor, linkLabel,+ showsLinkState, testResultLabel, webhookLine, type WaSettingsView,+} from "../core/whatsapp";+import { h } from "../views/dom";+import { t } from "../i18n/i18n";++type Toggle = (on: boolean, onChange: (v: boolean) => void) => HTMLElement;++export interface WhatsAppSettingsHost {+ toggle: Toggle;+ /** Whether the WhatsApp pill is among the active ones. */+ pillActive(): boolean;+ /** Turns the pill on (when a slot is free) or off, and saves. */+ setPill(on: boolean): void;+ /** How many pills may be active. */+ maxPills: number;+}++const hintStyle = (color: string) => `color:${color}`;++export function whatsappSection(host: WhatsAppSettingsHost): HTMLElement {+ let view: WaSettingsView | null = null;+ let showAdvanced = false;+ /** The advanced fields are filled from Rust once, then left to the user while they type. */+ let fieldsFilled = false;+ let testing = false;+ let testResult = "";+ let lastInstall = "";++ // ── Built once ──+ const enableSwitch = host.toggle(false, (on) => void setEnabled(on));+ const muteSwitch = host.toggle(true, (on) => void setOptions({ muteGroups: on }));+ const readSwitch = host.toggle(true, (on) => void setOptions({ markReadOnOpen: on }));+ const body = h("div", { style: "display:flex;flex-direction:column;gap:10px" });+ const dynamic = h("div", { style: "display:flex;flex-direction:column;gap:10px" });+ const ignoredList = h("div", { style: "display:flex;flex-direction:column;gap:4px" });+ const ignoreInput = h("input", {+ type: "text", placeholder: t("Phone number or chat id to ignore"), autocomplete: "off", spellcheck: "false",+ style: "flex:1 1 auto;min-width:0",+ }) as HTMLInputElement;+ const addBtn = h("button", { text: t("Add") });++ // Advanced+ const advancedBtn = h("button", { text: t("Advanced: your own gateway") });+ const advanced = h("div", { style: "display:flex;flex-direction:column;gap:10px" });+ const gatewaySelect = h("select", {},+ h("option", { value: "gowa", text: "GOWA" }),+ h("option", { value: "openwa", text: "OpenWA" }),+ ) as HTMLSelectElement;+ const urlInput = h("input", { type: "text", autocomplete: "off", spellcheck: "false", style: "flex:1 1 auto;min-width:0" }) as HTMLInputElement;+ const credentialInput = h("input", { type: "password", autocomplete: "off", spellcheck: "false", style: "flex:1 1 auto;min-width:0" }) as HTMLInputElement;+ const credentialRemove = h("button", { class: "danger", text: t("Remove") });+ let autoStart = false;+ const autoStartSwitch = host.toggle(false, (on) => {+ autoStart = on;+ drawAdvanced();+ });+ const pathInput = h("input", {+ type: "text", placeholder: t("Path to the GOWA binary (whatsapp)"), autocomplete: "off", spellcheck: "false",+ style: "flex:1 1 auto;min-width:0",+ }) as HTMLInputElement;+ const autoStartHint = h("div", { class: "hint" });+ const autoStartBlock = h("div", { style: "display:flex;flex-direction:column;gap:8px" });+ const portInput = h("input", { type: "number", min: "1024", max: "65535", style: "width:90px" }) as HTMLInputElement;+ const saveBtn = h("button", { class: "primary", text: t("Save WhatsApp") });+ const testBtn = h("button", { text: t("Test connection") });+ const testNote = h("div", { class: "hint" });+ const saveNote = h("div", {});++ const switchState = (el: HTMLElement, on: boolean) => {+ el.classList.toggle("on", on);+ el.setAttribute("aria-pressed", String(on));+ };++ async function setOptions(change: Partial<{ enabled: boolean; muteGroups: boolean; markReadOnOpen: boolean }>) {+ const p = view?.prefs;+ if (!p) return;+ const next = { enabled: p.enabled, muteGroups: p.muteGroups, markReadOnOpen: p.markReadOnOpen, ...change };+ try {+ await Bridge.whatsappSetOptions(next.enabled, next.muteGroups, next.markReadOnOpen);+ } catch {+ // The next report puts the switches back as they are.+ }+ }++ /** WhatsAppController.setEnabled: on also makes room for its pill when a slot is free. */+ async function setEnabled(on: boolean) {+ await setOptions({ enabled: on });+ host.setPill(on);+ draw();+ }++ function addIgnored() {+ const raw = ignoreInput.value.trim();+ if (!raw) return;+ ignoreInput.value = "";+ void Bridge.whatsappIgnore(raw);+ }+ addBtn.addEventListener("click", addIgnored);+ ignoreInput.addEventListener("keydown", (e) => {+ if (e.key === "Enter") addIgnored();+ });++ advancedBtn.addEventListener("click", () => {+ showAdvanced = !showAdvanced;+ drawAdvanced();+ });++ gatewaySelect.addEventListener("change", () => {+ const kind = gatewaySelect.value as "gowa" | "openwa";+ const other = kind === "gowa" ? DEFAULT_URLS.openwa : DEFAULT_URLS.gowa;+ // Still on the other gateway's default address: follow the switch.+ if (urlInput.value.trim() === other) urlInput.value = "";+ drawAdvanced();+ });++ async function saveGateway(credential: string | null) {+ const port = Number(portInput.value);+ saveNote.replaceChildren();+ try {+ await Bridge.whatsappSaveGateway({+ gateway: gatewaySelect.value === "openwa" ? "openwa" : "gowa",+ url: urlInput.value.trim(),+ credential,+ port: Number.isInteger(port) && port >= 1024 && port <= 65535 ? port : (view?.prefs.port ?? DEFAULT_PORT),+ autoStart,+ gowaPath: pathInput.value.trim(),+ });+ credentialInput.value = "";+ return true;+ } catch (err) {+ saveNote.append(h("div", { class: "notice err", text: t("Could not save: {error}", { error: String(err) }) }));+ return false;+ }+ }++ saveBtn.addEventListener("click", () => {+ const typed = credentialInput.value.trim();+ void saveGateway(typed ? typed : null);+ });+ credentialRemove.addEventListener("click", () => void saveGateway(""));+ testBtn.addEventListener("click", async () => {+ const typed = credentialInput.value.trim();+ if (!(await saveGateway(typed ? typed : null))) return;+ testing = true;+ testResult = "";+ drawAdvanced();+ const result = await Bridge.whatsappTest();+ testing = false;+ testResult = result ? testResultLabel(result) : "";+ drawAdvanced();+ });++ // ── Drawn from each report ──++ function drawAdvanced() {+ const v = view;+ advanced.style.display = showAdvanced ? "" : "none";+ if (!v) return;+ const kind = gatewaySelect.value === "openwa" ? "openwa" : "gowa";+ urlInput.placeholder = DEFAULT_URLS[kind];+ credentialInput.placeholder = v.hasCredential+ ? `•••••••• ${t("(stored)")}`+ : kind === "gowa" ? t("Basic auth (user:password, if set)") : t("API key (owa_k1_…)");+ credentialRemove.style.display = v.hasCredential ? "" : "none";+ switchState(autoStartSwitch, autoStart);+ autoStartBlock.replaceChildren();+ if (kind === "gowa") {+ autoStartBlock.append(h("div", { class: "row" }, h("label", { text: t("Start GOWA automatically") }), autoStartSwitch));+ if (autoStart) {+ autoStartHint.textContent = t("Coucou runs it on this computer only (127.0.0.1, the URL’s port), without downloading media, and stops it when Coucou quits. Its WhatsApp session stays in {path}.", { path: v.gowaDir });+ autoStartBlock.append(h("div", { class: "row" }, h("label", { text: "" }), pathInput), autoStartHint);+ }+ }+ testBtn.disabled = testing;+ testNote.textContent = testing ? "…" : testResult;+ }++ function fillFields(v: WaSettingsView) {+ gatewaySelect.value = v.prefs.gateway;+ urlInput.value = v.url;+ portInput.value = String(v.prefs.port);+ autoStart = v.prefs.autoStart;+ pathInput.value = v.prefs.gowaPath;+ fieldsFilled = true;+ }++ function installBlock(v: WaSettingsView): HTMLElement[] {+ const out: HTMLElement[] = [];+ if (isInstalling(v.install)) {+ out.push(h("div", { class: "hint", text: installStepLabel(v.install) }));+ return out;+ }+ if (v.installed) {+ const update = h("button", { text: t("Update"), onclick: () => void Bridge.whatsappInstall() });+ const text = v.prefs.gowaVersion+ ? t("Gateway GOWA {version} installed, started by Coucou", { version: v.prefs.gowaVersion })+ : t("Your GOWA gateway is set up");+ out.push(h("div", { class: "row" },+ h("span", { style: `color:${WHATSAPP_GREEN}`, text: "✓" }),+ h("span", { style: "font-size:12.5px", text }),+ h("span", { class: "spacer" }),+ update,+ ));+ } else {+ out.push(+ h("div", { class: "row" }, h("button", {+ class: "primary", text: t("Install WhatsApp"), onclick: () => void Bridge.whatsappInstall(),+ })),+ h("div", { class: "hint", text: t("Coucou downloads GOWA, the open-source gateway, from its GitHub page (about 15 MB, once), checks it and starts it. Then scan the QR code with your phone. No command line needed.") }),+ );+ }+ const failed = installError(v.install);+ if (failed) out.push(h("div", { class: "notice err", text: failed }));+ return out;+ }++ function linkState(v: WaSettingsView): HTMLElement[] {+ const out: HTMLElement[] = [];+ const text = v.link.state === "connected" && v.me ? t("Connected as {number}", { number: v.me }) : linkLabel(v.link);+ out.push(h("div", { class: "row", style: "gap:8px" },+ h("i", { class: "dot", style: `background:${linkColor(v.link)}` }),+ h("span", { style: "font-size:12.5px", text }),+ ));+ if (v.link.state === "connected") out.push(h("div", { class: "hint", text: webhookLine(v.webhook) }));+ if (v.link.state === "needsQr") {+ if (v.qr) {+ out.push(h("div", { class: "row", style: "align-items:flex-start" },+ h("img", { class: "qr", src: v.qr, width: "168", height: "168", alt: "", style: "width:168px;height:168px;image-rendering:pixelated" }),+ h("div", { class: "hint", style: "flex:1 1 160px", text: t("On your phone: WhatsApp › Settings › Linked devices › Link a device, then scan this code.") }),+ ));+ } else {+ out.push(h("div", { class: "hint", text: "…" }));+ }+ }+ return out;+ }++ function draw() {+ const v = view;+ if (!v) return;+ // Installed by Coucou just now: the fields follow what it set.+ const install = JSON.stringify(v.install);+ if (!fieldsFilled || (install !== lastInstall && v.install.step === "done")) fillFields(v);+ lastInstall = install;+ switchState(enableSwitch, v.prefs.enabled);+ switchState(muteSwitch, v.prefs.muteGroups);+ switchState(readSwitch, v.prefs.markReadOnOpen);+ body.style.display = v.prefs.enabled ? "" : "none";++ const parts: HTMLElement[] = [];+ if (v.prefs.enabled && !host.pillActive()) {+ parts.push(h("div", { class: "hint", style: hintStyle("#F4505E"), text: t("Turn off another pill to make room for WhatsApp ({max} at most).", { max: host.maxPills }) }));+ }+ // One click: Coucou downloads GOWA, checks it and starts it. No command line.+ if (v.prefs.gateway === "gowa") parts.push(...installBlock(v));+ if (showsLinkState(v)) parts.push(...linkState(v));+ dynamic.replaceChildren(...parts);++ ignoredList.replaceChildren(...v.ignored.map((chat) => h("div", { class: "row", style: "gap:8px" },+ h("span", { style: "font-size:12.5px", text: chat.name }),+ h("span", { class: "spacer" }),+ h("button", { text: t("Remove"), onclick: () => void Bridge.whatsappUnignore(chat.id) }),+ )));+ drawAdvanced();+ }++ advanced.append(+ h("div", { class: "row" }, h("label", { text: t("Gateway") }), gatewaySelect),+ h("div", { class: "row" }, h("label", { text: "" }), urlInput),+ h("div", { class: "row" }, h("label", { text: "" }), credentialInput, credentialRemove),+ autoStartBlock,+ h("div", { class: "row" }, h("label", { text: t("Coucou’s webhook port") }), portInput),+ h("div", { class: "row" }, saveBtn, testBtn),+ testNote,+ saveNote,+ );++ body.append(+ dynamic,+ h("div", { class: "row" }, h("label", { text: t("Mute groups (unless I’m mentioned)") }), muteSwitch),+ h("div", { class: "row" }, h("label", { text: t("Mark as read when I open a conversation") }), readSwitch),+ h("div", { class: "hint", text: t("Off: marked read only when you reply. Never when a message just arrives.") }),+ h("div", { class: "subhead", text: t("Ignored chats") }),+ ignoredList,+ h("div", { class: "row" }, ignoreInput, addBtn),+ h("div", { class: "hint", text: t("Coucou only talks to the gateway on this computer. Messages stay in memory, are never logged or saved, and are forgotten when Coucou quits. No photo or media is ever downloaded.") }),+ h("div", { class: "row" }, advancedBtn),+ advanced,+ );++ const section = h(+ "section",+ {},+ h("h2", {}, h("i", { class: "dot", style: `background:${WHATSAPP_GREEN}` }), h("span", { text: t("WhatsApp (experimental)") })),+ h("div", { class: "hint", style: hintStyle("#F5B83D"), text: t("Unofficial integration: it goes through a gateway you run on this computer. Use it on your own account only. WhatsApp may restrict accounts that abuse it.") }),+ h("div", { class: "row" }, h("label", { text: t("Show my WhatsApp messages") }), enableSwitch),+ body,+ );+ body.style.display = "none";+ advanced.style.display = "none";++ const apply = (v: WaSettingsView | null) => {+ if (!v) return;+ view = v;+ draw();+ };+ void Bridge.whatsappSettings().then(apply);+ let off: (() => void) | null = null;+ void onEvent<WaSettingsView>("whatsapp-settings", (v) => {+ // A section drawn again (another page, a language change) leaves this one behind.+ if (!section.isConnected && view) {+ off?.();+ return;+ }+ apply(v);+ }).then((unlisten) => {+ off = unlisten;+ });+ return section;+}diff --git a/windows/src/style.css b/windows/src/style.cssindex d60a99ec..ebc40932 100644--- a/windows/src/style.css+++ b/windows/src/style.css@@ -2735,6 +2735,274 @@ input[type="range"]::-webkit-slider-thumb {width: 44px;}+/* ── WhatsApp (views/whatsapp.ts) — WhatsAppCardView on macOS ────────────────+ Nothing here applies to a view that already ships: every class is the card's own. */++.wa-card {+ height: 100%;+ box-sizing: border-box;+ padding-top: 10px;+}++.wa-list,+.wa-convo {+ display: flex;+ flex-direction: column;+ min-height: 0;+ height: 100%;+}++.wa-unread {+ font: 600 10px var(--font);+ color: #25d366;+ font-variant-numeric: tabular-nums;+ padding: 1px 6px;+ border-radius: 999px;+ background: rgba(37, 211, 102, 0.14);+}++.wa-empty {+ font: 400 11px var(--font);+ color: var(--dim-3);+ padding: 8px 0 0 8px;+}++.wa-status-text {+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ min-width: 0;+}++.wa-settings {+ color: var(--dim-2);+ padding: 0;+}++.wa-rows {+ overflow-y: auto;+ min-height: 0;+ padding-right: 12px;+ scrollbar-width: none;+}++.wa-row {+ border: 0;+ background: transparent;+ text-align: start;+ width: 100%;+ gap: 6px;+ padding: 3px 6px;+ cursor: default;+ flex: 0 0 auto;+}++.wa-row:hover {+ background: rgba(255, 255, 255, 0.05);+}++.wa-row.unread {+ background: rgba(37, 211, 102, 0.08);+}++.wa-row.unread:hover {+ background: rgba(37, 211, 102, 0.14);+}++.wa-row-name {+ max-width: 92px;+ flex: 0 1 auto;+}++.wa-row.unread .wa-row-name {+ font-weight: 600;+ color: #e8e9ec;+}++.wa-row.unread .wa-preview {+ color: var(--dim-2);+}++.wa-spacer {+ flex: 1 1 0;+}++.wa-count {+ font: 700 9px var(--font);+ color: #0b0c0e;+ background: #25d366;+ border-radius: 999px;+ padding: 1px 5px;+ font-variant-numeric: tabular-nums;+ flex: 0 0 auto;+}++.wa-ignore {+ color: #f4505e;+ padding: 0;+ flex: 0 0 auto;+}++.wa-avatar {+ flex: 0 0 auto;+ display: inline-grid;+ place-items: center;+ border-radius: 50%;+ background: rgba(37, 211, 102, 0.22);+ color: #25d366;+ font-family: var(--font);+ font-weight: 700;+ line-height: 1;+}++.wa-head {+ display: flex;+ align-items: center;+ gap: 6px;+ min-width: 0;+ padding-right: 36px;+ margin-left: -6px;+}++.wa-back {+ width: 20px;+ height: 20px;+}++.wa-name {+ font: 600 11px var(--font);+ color: var(--ink);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+ min-width: 0;+}++.wa-messages {+ flex: 1 1 auto;+ min-height: 0;+ overflow-y: auto;+ display: flex;+ flex-direction: column;+ gap: 3px;+ padding: 4px 12px 4px 0;+ scrollbar-width: none;+}++.wa-line {+ display: flex;+ padding-right: 40px;+}++.wa-line.mine {+ justify-content: flex-end;+ padding-right: 0;+ padding-left: 40px;+}++.wa-bubble {+ padding: 3px 7px;+ border-radius: 6px;+ background: rgba(255, 255, 255, 0.06);+ min-width: 0;+ user-select: text;+}++.wa-bubble.mine {+ background: rgba(37, 211, 102, 0.16);+}++.wa-sender {+ font: 600 9px var(--font);+ color: rgba(37, 211, 102, 0.8);+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.wa-media {+ font: 500 10px var(--font);+ color: #9398a1;+}++.wa-text {+ font: 400 10.5px/1.35 var(--font);+ color: #c5c8cd;+ white-space: pre-wrap;+ overflow-wrap: anywhere;+}++.wa-bubble.mine .wa-text {+ color: #e8e9ec;+}++.wa-reply {+ display: flex;+ align-items: flex-end;+ gap: 6px;+ padding: 4px 8px;+ margin-right: 12px;+ border-radius: 7px;+ background: rgba(255, 255, 255, 0.06);+ flex: 0 0 auto;+}++.wa-field {+ flex: 1 1 auto;+ min-width: 0;+ resize: none;+ border: 0;+ outline: none;+ background: transparent;+ color: var(--ink);+ font: 400 11px/1.35 var(--font);+ max-height: 44px;+ padding: 1px 0;+ field-sizing: content;+}++.wa-field::placeholder {+ color: var(--dim-3);+}++.wa-send {+ width: 16px;+ height: 16px;+ border: 0;+ border-radius: 50%;+ background: rgba(37, 211, 102, 0.3);+ display: grid;+ place-items: center;+ cursor: default;+ flex: 0 0 auto;+}++.wa-send.ready {+ background: #25d366;+}++.wa-note {+ font: 400 9.5px var(--font);+ min-height: 0;+ padding: 2px 0 4px;+ white-space: nowrap;+ overflow: hidden;+ text-overflow: ellipsis;+}++.wa-note.warn {+ color: #f5b83d;+}++.wa-note.err {+ color: #f4505e;+}++html[data-dir="rtl"] #views :is(.wa-text, .wa-field, .wa-preview) {+ unicode-bidi: plaintext;+ text-align: start;+}+/* ── Arabic: right to left ─────────────────────────────────────────────────────i18n.ts sets <html data-dir="rtl">. The text of the cards reads and alignsright to left; Mochi, the pills, the header and the cards themselves keepdiff --git a/windows/src/views/views.ts b/windows/src/views/views.tsindex 81638b9e..491bc9b2 100644--- a/windows/src/views/views.ts+++ b/windows/src/views/views.ts@@ -25,6 +25,8 @@ import { buildUpdate } from "./update";import { buildWhatsNew } from "./whatsnew";import { buildSpotifyCard, buildSpotifyPill, type SpotifyPillHost } from "./spotify";import { SPOTIFY_ID } from "../core/spotify";+import { buildWhatsAppCard } from "./whatsapp";+import { WHATSAPP_ID } from "../core/whatsapp";import type { Outfit, OutfitSelection } from "../mochi/wardrobe";import { language, t, tl, type Msg } from "../i18n/i18n";import type { ViewCommand } from "../island/shortcuts";@@ -55,6 +57,10 @@ export interface ViewActions {chooseOutfit(selection: OutfitSelection): void;/** Wardrobe hover: shows an outfit on Mochi without keeping it; null ends it. */previewOutfit(outfit: Outfit | null): void;+ /** The island takes the keyboard (a text field in a card) or gives it back. */+ keyboard(on: boolean): void;+ /** Something is being typed in a card: the island stays open until it is sent or cleared. */+ holdOpen(on: boolean): void;}export interface ViewHost {@@ -201,6 +207,12 @@ function buildOverview(actions: ViewActions): ViewHost {// runs on, and a slider being dragged must not be rebuilt under the pointer.const spotifyCard = buildSpotifyCard();let spotifyPill: SpotifyPillHost | null = null;+ // WhatsApp's card too: its reply field keeps the draft and the keyboard while messages arrive.+ const whatsappCard = buildWhatsAppCard({+ openSettings: () => actions.openSettingsWindow(),+ keyboard: (on) => actions.keyboard(on),+ holdOpen: (on) => actions.holdOpen(on),+ });const el = h("div", { class: "view overview" },h("div", { class: "left" }, left),@@ -210,7 +222,7 @@ function buildOverview(actions: ViewActions): ViewHost {let pillIds = "";let detailOpen = false;let lastFocus: string | null = null;- let mode: "ticker" | "card" | "plan" | "diff" | "spotify" | null = null;+ let mode: "ticker" | "card" | "plan" | "diff" | "spotify" | "whatsapp" | null = null;let cardKey = "";/** The list row highlighted at the last sync, to scroll only when it moves. */let shownSelection: number | null = null;@@ -367,6 +379,15 @@ function buildOverview(actions: ViewActions): ViewHost {cardKey = "";}spotifyCard.sync();+ } else if (task && task.id === WHATSAPP_ID) {+ // Its own card in every state: not linked, no message, conversations, one open.+ if (mode !== "whatsapp") {+ clear(leftBody);+ leftBody.append(whatsappCard.el);+ mode = "whatsapp";+ cardKey = "";+ }+ whatsappCard.sync();} else if (task) {const info = State.integrations[task.id];const key = [diff --git a/windows/src/views/whatsapp.ts b/windows/src/views/whatsapp.tsnew file mode 100644index 00000000..b72e7e8a--- /dev/null+++ b/windows/src/views/whatsapp.ts@@ -0,0 +1,258 @@+// The WhatsApp card — a DOM port of WhatsAppCardView, WhatsAppRow, WhatsAppConversationView,+// WhatsAppBubble and WhatsAppAvatar (WhatsAppViews.swift). Sizes, colours and wording are the Mac's.+//+// The list: one row per conversation (never one per message) with initials, name, age, the last+// message cut short and the unread count; when the gateway isn't linked, why, and a way to Settings.+// A click on a row opens the conversation: its last ten messages and a reply field. Enter sends,+// Shift+Enter starts a new line, Escape goes back to the list. Nothing is sent without the user's+// own Enter or click, and while a reply is being typed the island stays open.+//+// Built once and synced in place: the field keeps its draft and the keyboard while messages arrive.++import { h, svg, clear, dot } from "./dom";+import { ICONS } from "./icons";+import { Bridge } from "../core/bridge";+import { State } from "../core/state";+import {+ WHATSAPP_GREEN, WHATSAPP_ID, WhatsApp, canSend, initials, keyAction, lastMessages, linkColor, linkLabel,+ preview, previewParts, sendErrorLabel, timeAgo, type WaConversation, type WaMessage,+} from "../core/whatsapp";+import { language, t, tl } from "../i18n/i18n";++export interface WhatsAppCardHost {+ openSettings(): void;+ /** The island takes the keyboard for the reply field, and gives it back. */+ keyboard(on: boolean): void;+ /** A reply is being typed: the island stays open until it is sent or cleared. */+ holdOpen(on: boolean): void;+}++export interface WhatsAppCard {+ el: HTMLElement;+ sync(): void;+}++/** Initials on WhatsApp green: no photo is ever fetched (they live on WhatsApp's servers). */+function avatar(name: string, isGroup: boolean, size = 16): HTMLElement {+ const letters = initials(name);+ const el = h("span", { class: "wa-avatar", style: `width:${size}px;height:${size}px;font-size:${size * 0.42}px` });+ if (isGroup && letters === "#") el.append(svg(ICONS.stack, size * 0.6, { fill: WHATSAPP_GREEN }));+ else el.textContent = letters;+ return el;+}++function bubble(m: WaMessage, isGroup: boolean): HTMLElement {+ const { label, value } = previewParts(m);+ const box = h("div", { class: m.fromMe ? "wa-bubble mine" : "wa-bubble" });+ if (isGroup && !m.fromMe && m.senderName) box.append(h("div", { class: "wa-sender", text: m.senderName }));+ if (label) box.append(h("div", { class: "wa-media", text: t(label) }));+ if (value) box.append(h("div", { class: "wa-text", text: value }));+ return h("div", { class: m.fromMe ? "wa-line mine" : "wa-line" }, box);+}++export function buildWhatsAppCard(host: WhatsAppCardHost): WhatsAppCard {+ // ── The list ──+ const unreadTag = h("span", { class: "wa-unread" });+ const head = h("div", { class: "int-head" }, dot(WHATSAPP_GREEN, 7), h("b", { text: "WhatsApp" }), unreadTag);+ const listBody = h("div", {});+ const listView = h("div", { class: "wa-list" }, head, listBody);++ // ── The conversation ──+ const back = h("button", { class: "int-back wa-back", title: tl("Back") }, svg(ICONS.chevronLeft, 10, { stroke: 2.4 }));+ const convoAvatar = h("span", {});+ const convoName = h("b", { class: "wa-name" });+ const convoHead = h("div", { class: "wa-head" }, back, convoAvatar, convoName);+ const messages = h("div", { class: "wa-messages" });+ const field = h("textarea", { class: "wa-field", rows: "1", spellcheck: "true" }) as HTMLTextAreaElement;+ const sendBtn = h("button", { class: "wa-send", title: tl("Send") }, svg(ICONS.arrowUp, 12, { fill: "#0B0C0E" }));+ const reply = h("div", { class: "wa-reply" }, field, sendBtn);+ const note = h("div", { class: "wa-note" });+ const convoView = h("div", { class: "wa-convo" }, convoHead, messages, reply, note);++ const el = h("div", { class: "int-card wa-card" }, listView, convoView);++ let openChat: string | null = null;+ /** The row whose "Ignore this chat" is showing (a right-click on it). */+ let ignoring: string | null = null;+ let listKey = "";+ let convoKey = "";++ const current = (): WaConversation | undefined =>+ openChat ? WhatsApp.view.conversations.find((c) => c.id === openChat) : undefined;++ function open(id: string) {+ openChat = id;+ ignoring = null;+ field.value = "";+ convoKey = "";+ void Bridge.whatsappOpen(id);+ host.keyboard(true);+ window.setTimeout(() => field.focus(), 120);+ sync();+ }++ function close() {+ if (openChat == null) return;+ void Bridge.whatsappClose(openChat);+ openChat = null;+ field.value = "";+ host.holdOpen(false);+ host.keyboard(false);+ listKey = "";+ sync();+ }++ async function send() {+ const chat = openChat;+ const text = field.value;+ if (!chat || !canSend(text, WhatsApp.view.sending)) return;+ const sent = await Bridge.whatsappSend(chat, text);+ if (sent && openChat === chat && field.value === text) {+ field.value = "";+ host.holdOpen(false);+ syncSendButton();+ }+ field.focus();+ }++ back.addEventListener("click", close);+ sendBtn.addEventListener("click", () => void send());+ field.addEventListener("input", () => {+ host.holdOpen(field.value.trim().length > 0);+ syncSendButton();+ });+ field.addEventListener("keydown", (e) => {+ const action = keyAction(e);+ if (action === "send") {+ e.preventDefault();+ void send();+ } else if (action === "back") {+ // Back to the list, not the island folding away.+ e.preventDefault();+ e.stopPropagation();+ close();+ }+ });++ // Leaving the card (another pill, another view, the island folded) closes the conversation.+ State.subscribe(() => {+ if (openChat == null) return;+ if (State.mode !== "expanded" || State.view !== "overview" || State.focusTask?.id !== WHATSAPP_ID || !WhatsApp.view.on) {+ close();+ }+ });++ function syncSendButton() {+ const ok = canSend(field.value, WhatsApp.view.sending);+ sendBtn.classList.toggle("ready", ok);+ sendBtn.disabled = !ok;+ field.disabled = WhatsApp.view.sending;+ }++ function row(c: WaConversation): HTMLElement {+ const unread = c.unread > 0;+ const r = h("button", { class: unread ? "int-row wa-row unread" : "int-row wa-row" },+ avatar(c.name, c.isGroup),+ h("span", { class: "int-name wa-row-name", text: c.name }),+ h("span", { class: "int-ago", text: timeAgo(c.lastActivity) }),+ );+ const last = c.messages[c.messages.length - 1];+ if (ignoring === c.id) {+ r.append(h("span", { class: "wa-spacer" }), h("span", {+ class: "link-btn wa-ignore",+ text: t("Ignore this chat"),+ onclick: (e: Event) => {+ e.stopPropagation();+ ignoring = null;+ void Bridge.whatsappIgnore(c.id);+ },+ }));+ } else {+ if (last) r.append(h("span", { class: "int-sub wa-preview", text: preview(last, c.isGroup) }));+ r.append(h("span", { class: "wa-spacer" }));+ if (unread) r.append(h("span", { class: "wa-count", text: c.unread > 99 ? "99+" : String(c.unread) }));+ }+ r.addEventListener("click", () => open(c.id));+ r.addEventListener("contextmenu", (e) => {+ e.preventDefault();+ ignoring = ignoring === c.id ? null : c.id;+ listKey = "";+ sync();+ });+ return r;+ }++ function syncList() {+ const v = WhatsApp.view;+ const key = [+ language(), v.link.state, "detail" in v.link ? v.link.detail : "", v.unread, ignoring,+ // The ages move on a minute at a time.+ Math.floor(Date.now() / 60_000),+ ...v.conversations.map((c) => `${c.id}|${c.name}|${c.unread}|${c.lastActivity}|${c.messages[c.messages.length - 1]?.id ?? ""}`),+ ].join("~");+ if (key === listKey) return;+ listKey = key;+ unreadTag.textContent = v.unread > 0 ? t("{0} unread", { 0: v.unread }) : "";+ unreadTag.style.display = v.unread > 0 ? "" : "none";+ clear(listBody);+ if (v.link.state !== "connected") {+ listBody.append(+ h("div", { class: "int-status" }, dot(linkColor(v.link), 5), h("span", { class: "wa-status-text", text: linkLabel(v.link) })),+ h("div", { class: "int-actions" }, h("button", {+ class: "link-btn wa-settings", text: t("Settings…"), onclick: () => host.openSettings(),+ })),+ );+ } else if (v.conversations.length === 0) {+ listBody.append(h("div", { class: "wa-empty", text: t("No new messages") }));+ } else {+ listBody.append(h("div", { class: "int-rows wa-rows" }, ...v.conversations.map(row)));+ }+ }++ function syncConversation(c: WaConversation) {+ const v = WhatsApp.view;+ const shown = lastMessages(c);+ const key = [language(), c.id, c.name, ...shown.map((m) => m.id)].join("~");+ if (key !== convoKey) {+ const wasAtBottom = messages.scrollHeight - messages.scrollTop - messages.clientHeight < 24;+ const first = convoKey === "";+ convoKey = key;+ clear(convoAvatar);+ convoAvatar.append(avatar(c.name, c.isGroup));+ convoName.textContent = c.name;+ convoName.title = c.id.split("@")[0];+ clear(messages);+ for (const m of shown) messages.append(bubble(m, c.isGroup));+ // The newest at the bottom, in view.+ if (first || wasAtBottom) messages.scrollTop = messages.scrollHeight;+ }+ field.placeholder = t("Reply… (Shift+Enter: new line)");+ note.className = "wa-note";+ if (v.link.state !== "connected") {+ note.textContent = linkLabel(v.link);+ note.classList.add("warn");+ } else if (v.sendError) {+ note.textContent = sendErrorLabel(v.sendError);+ note.classList.add("err");+ } else {+ note.textContent = "";+ }+ syncSendButton();+ }++ function sync() {+ const c = current();+ // Kept open through a missed check (the draft too): only gone when WhatsApp is off or the+ // conversation left the list (ignored).+ if (openChat != null && (!c || !WhatsApp.view.on)) {+ close();+ return;+ }+ listView.style.display = c ? "none" : "";+ convoView.style.display = c ? "" : "none";+ if (c) syncConversation(c);+ else syncList();+ }++ return { el, sync };+}diff --git a/windows/tests/pills.test.mjs b/windows/tests/pills.test.mjsindex 232556ab..aab49072 100644--- a/windows/tests/pills.test.mjs+++ b/windows/tests/pills.test.mjs@@ -45,6 +45,7 @@ test("the catalog holds the Mac's pills with the Claude Code label for Windows a["integration_stripe", "Stripe", "#0570DE", "service", "Integration"],["integration_music", "Apple Music", "#FA2D48", "service", "Integration"],["integration_spotify", "Spotify", "#1DB954", "service", "Integration"],+ ["integration_whatsapp", "WhatsApp", "#25D366", "service", "Integration"],];assert.deepEqual(PILL_CATALOG.filter((p) => !["integration_gitlab", "integration_gitea"].includes(p.id))diff --git a/windows/tests/whatsapp.test.mjs b/windows/tests/whatsapp.test.mjsnew file mode 100644index 00000000..968e5b54--- /dev/null+++ b/windows/tests/whatsapp.test.mjs@@ -0,0 +1,323 @@+// WhatsApp (experimental): the page's rules in src/core/whatsapp.ts, the pill's reactions in+// src/island/whatsapp.ts, the card in src/views/whatsapp.ts. The gateway side — payloads,+// signatures, filters, the inbox, the installer — is tested in src-tauri/src/whatsapp/.++import { beforeEach, test } from "node:test";+import assert from "node:assert/strict";+import { emit, sent } from "./tauri.mjs";+import { installFakeDom } from "./fakedom.mjs";+import {+ IDLE_WHATSAPP, WHATSAPP_ID, WhatsApp, canSend, duration, initials, installError, installFailure, installStepLabel,+ keyAction, lastMessages, linkColor, linkLabel, preview, sendErrorLabel, showsLinkState, testResultLabel, timeAgo,+ webhookLine,+} from "../src/core/whatsapp.ts";+import { handlePillEvent, registerWhatsAppHandlers } from "../src/island/whatsapp.ts";+import { buildWhatsAppCard } from "../src/views/whatsapp.ts";+import { pillDefinition } from "../src/core/pills.ts";+import { DEFAULT_SETTINGS, State } from "../src/core/state.ts";+import { lookup, setLanguage } from "../src/i18n/i18n.ts";++installFakeDom();++const NOW = 1_800_000_000_000;++const msg = (over = {}) => ({+ id: "m1", chat: "[email protected]", sender: "[email protected]", senderName: "",+ text: "Hello", media: { kind: "none" }, date: NOW - 30_000, fromMe: false, mentionsMe: false, ...over,+});++const conversation = (over = {}) => ({+ id: "[email protected]", name: "Marie", isGroup: false, messages: [msg()], unread: 1,+ lastActivity: NOW - 30_000, ...over,+});++const connected = (over = {}) => ({ ...IDLE_WHATSAPP, on: true, link: { state: "connected" }, ...over });++// ── The pure rules (WhatsAppModels.swift, WhatsAppViews.swift) ─────────────────++test("initials: the first letters of two words, # when there are none", () => {+ assert.equal(initials("Marie Curie"), "MC");+ assert.equal(initials("jean-luc picard"), "JL");+ assert.equal(initials("Élodie"), "É");+ assert.equal(initials("+33612345678"), "#");+ assert.equal(initials(""), "#");+ assert.equal(duration(12), "0:12");+ assert.equal(duration(75), "1:15");+});++test("previews: one line, media as a label only, who wrote it in a group", () => {+ assert.equal(preview(msg({ text: "see\nyou" }), false), "see you");+ assert.equal(preview(msg({ fromMe: true, text: "ok" }), false), "You: ok");+ assert.equal(preview(msg({ senderName: "Paul", text: "hi" }), true), "Paul: hi");+ assert.equal(preview(msg({ senderName: "Paul", text: "hi" }), false), "hi", "a private chat needs no name");+ assert.equal(preview(msg({ media: { kind: "image" }, text: "look" }), false), "Photo · look");+ assert.equal(preview(msg({ media: { kind: "voice", seconds: null }, text: "" }), false), "Voice message");+ assert.equal(preview(msg({ media: { kind: "voice", seconds: 75 }, text: "" }), false), "Voice message · 1:15");+ assert.equal(preview(msg({ media: { kind: "document", name: "devis.pdf" }, text: "" }), false), "Document · devis.pdf");+ assert.equal(preview(msg({ media: { kind: "sticker" }, text: "" }), false), "Sticker");+ assert.equal(preview(msg({ media: { kind: "other" }, text: "" }), false), "Message");+});++test("the time since reads like the Mac's", () => {+ assert.equal(timeAgo(NOW - 10_000, NOW), "now");+ assert.equal(timeAgo(NOW - 5 * 60_000, NOW), "5m");+ assert.equal(timeAgo(NOW - 3 * 3_600_000, NOW), "3h");+ assert.equal(timeAgo(NOW - 2 * 86_400_000, NOW), "2d");+});++test("Rust's codes become words, a gateway's own message is shown as it is", () => {+ assert.equal(linkLabel({ state: "off" }), "Turned off in Settings");+ assert.equal(linkLabel({ state: "needsQr" }), "Scan the QR code in Settings");+ assert.equal(linkLabel({ state: "unreachable" }), "The gateway doesn’t answer: is it running?");+ assert.equal(linkLabel({ state: "failed", detail: "DEVICE_ID_REQUIRED" }), "DEVICE_ID_REQUIRED");+ assert.equal(linkColor({ state: "connected" }), "#22C55E");+ assert.equal(linkColor({ state: "needsQr" }), "#F5B83D");+ assert.equal(linkColor({ state: "unauthorized" }), "#F4505E");+ assert.equal(sendErrorLabel({ code: "tooFast" }), "A few replies a minute at most: wait a moment.");+ assert.equal(sendErrorLabel({ code: "refused", detail: "INVALID_JID" }), "INVALID_JID");+ assert.equal(webhookLine({ state: "registered" }), "Live: new messages arrive at once.");+ assert.equal(webhookLine({ state: "portBusy", port: 47823 }),+ "Port 47823 is taken: pick another one. Checking every 20 s meanwhile.");+ assert.equal(webhookLine({ state: "listening" }), "Checking for new messages every 20 s.");+ assert.equal(testResultLabel({ result: "connected", who: "+33612345678" }), "Connected as +33612345678.");+ assert.equal(testResultLabel({ result: "unreachable" }), "The gateway doesn’t answer: is it running?");+ assert.equal(installStepLabel({ step: "downloading", megabytes: 15 }), "Downloading (15 MB)…");+ assert.equal(installStepLabel({ step: "idle" }), "");+ assert.match(installFailure("badChecksum"), /doesn't match the file GOWA published/);+ assert.match(installFailure("anything else"), /didn't go through/);+ assert.equal(installError({ step: "done", version: "9.6.0" }), null);+ assert.match(installError({ step: "failed", reason: "noBuild" }), /No GOWA build for this computer/);+});++test("the status and QR show once there is a gateway to talk to", () => {+ const base = {+ prefs: { gateway: "gowa" }, url: "", installed: false, link: { state: "unreachable" },+ };+ assert.equal(showsLinkState(base), false, "before the install, 'it doesn't answer' would only confuse");+ assert.equal(showsLinkState({ ...base, installed: true }), true);+ assert.equal(showsLinkState({ ...base, url: "http://127.0.0.1:3001" }), true);+ assert.equal(showsLinkState({ ...base, prefs: { gateway: "openwa" } }), true);+ assert.equal(showsLinkState({ ...base, link: { state: "needsQr" } }), true);+});++test("Enter sends, Shift+Enter is a new line, Escape goes back, a composition never sends", () => {+ assert.equal(keyAction({ key: "Enter", shiftKey: false }), "send");+ assert.equal(keyAction({ key: "Enter", shiftKey: true }), "newline");+ assert.equal(keyAction({ key: "Enter", shiftKey: false, isComposing: true }), null);+ assert.equal(keyAction({ key: "Escape", shiftKey: false }), "back");+ assert.equal(keyAction({ key: "a", shiftKey: false }), null);+ assert.equal(canSend(" \n ", false), false);+ assert.equal(canSend("hi", true), false, "one reply at a time");+ assert.equal(canSend("hi", false), true);+ const many = conversation({ messages: Array.from({ length: 20 }, (_, i) => msg({ id: `m${i}` })) });+ assert.deepEqual(lastMessages(many).map((m) => m.id), ["m10", "m11", "m12", "m13", "m14", "m15", "m16", "m17", "m18", "m19"]);+});++test("the words are translated", () => {+ setLanguage("fr");+ try {+ assert.equal(linkLabel({ state: "connected" }), lookup("Connected", "fr"));+ assert.equal(preview(msg({ media: { kind: "image" }, text: "" }), false), lookup("Photo", "fr"));+ assert.ok(!webhookLine({ state: "registered" }).startsWith("Live"));+ } finally {+ setLanguage("en");+ }+});++// ── The pill (WhatsAppController.announce) ────────────────────────────────────++const host = { reveals: 0, emotes: [], reveal() { this.reveals++; }, emote(name) { this.emotes.push(name); } };+registerWhatsAppHandlers(host);++beforeEach(() => {+ State.settings = { ...DEFAULT_SETTINGS, activeIntegrations: [WHATSAPP_ID] };+ State.os = "windows";+ State.tasks = [];+ State.focusId = null;+ State.mode = "hidden";+ State.view = "overview";+ State.paused = false;+ State.loadIntegrationTasks();+ WhatsApp.view = { ...IDLE_WHATSAPP };+ host.reveals = 0;+ host.emotes = [];+});++const pill = () => State.tasks.find((t) => t.id === WHATSAPP_ID);++test("the pill is the Mac's, connected with nothing to enter", () => {+ const def = pillDefinition(WHATSAPP_ID);+ assert.equal(def.color, "#25D366");+ assert.equal(def.support, "yes");+ assert.deepEqual(def.connect, { kind: "none" });+ assert.ok(pill(), "declared, it is on the island");+});++test("a new message lights the pill with the chat's name only, and Mochi smiles once per burst", () => {+ handlePillEvent(host, { kind: "message", name: "Marie" }, 10_000);+ assert.equal(pill().state, "finished");+ assert.deepEqual(pill().steps, ["Marie"]);+ assert.equal(pill().pillBadge, "finished");+ assert.deepEqual(host.emotes, ["happy"]);+ assert.equal(host.reveals, 1);+ handlePillEvent(host, { kind: "message", name: "Paul" }, 12_000);+ assert.deepEqual(pill().steps, ["Paul"]);+ assert.deepEqual(host.emotes, ["happy"], "a burst is one reaction");+ handlePillEvent(host, { kind: "message", name: "Paul" }, 20_000);+ assert.deepEqual(host.emotes, ["happy", "happy"]);+ // Read: the badge goes.+ emit("whatsapp-pill", { kind: "read" });+ assert.equal(pill().pillBadge, null);+ // Turned off: back to idle.+ emit("whatsapp-pill", { kind: "reset" });+ assert.equal(pill().state, "idle");+ assert.deepEqual(pill().steps, []);+});++test("paused, or the pill on screen: no badge", () => {+ State.paused = true;+ handlePillEvent(host, { kind: "message", name: "Marie" }, 100_000);+ assert.equal(pill().state, "idle");+ State.paused = false;+ State.focusId = WHATSAPP_ID;+ handlePillEvent(host, { kind: "message", name: "Marie" }, 200_000);+ assert.equal(pill().state, "finished");+ assert.equal(pill().pillBadge ?? null, null);+});++test("the gateway down twice: the small red dot, gone when it answers", () => {+ emit("whatsapp", connected({ down: true }));+ assert.equal(pill().pillBadge, "error");+ emit("whatsapp", connected({ down: false }));+ assert.equal(pill().pillBadge, null);+});++// ── The card (WhatsAppCardView, WhatsAppConversationView) ─────────────────────++function card() {+ const calls = { settings: 0, keyboard: [], hold: [] };+ const built = buildWhatsAppCard({+ openSettings: () => calls.settings++,+ keyboard: (on) => calls.keyboard.push(on),+ holdOpen: (on) => calls.hold.push(on),+ });+ return { ...built, calls };+}++const key = (el, k, shiftKey = false) => {+ const event = { key: k, shiftKey, defaultPrevented: false, propagationStopped: false,+ preventDefault() { this.defaultPrevented = true; }, stopPropagation() { this.propagationStopped = true; } };+ for (const fn of el.listeners.get("keydown") ?? []) fn(event);+ return event;+};++test("not linked: why, and the way to Settings", () => {+ const c = card();+ WhatsApp.view = { ...IDLE_WHATSAPP, on: true, link: { state: "unreachable" } };+ c.sync();+ assert.match(c.el.textContent, /WhatsApp.*The gateway doesn’t answer: is it running\?.*Settings…/);+ c.el.find(".wa-settings")[0].fire("click");+ assert.equal(c.calls.settings, 1);+});++test("linked: one row per conversation, the unread count, or nothing new", () => {+ const c = card();+ WhatsApp.view = connected();+ c.sync();+ assert.match(c.el.textContent, /No new messages/);+ WhatsApp.view = connected({+ unread: 3,+ conversations: [+ conversation({ unread: 2 }),+ conversation({ id: "[email protected]", name: "Famille", isGroup: true, unread: 1,+ messages: [msg({ chat: "[email protected]", senderName: "Paul", text: "<b>@33612345678</b> tu viens ?" })] }),+ ],+ });+ c.sync();+ const rows = c.el.find(".wa-row");+ assert.equal(rows.length, 2);+ assert.match(c.el.textContent, /3 unread/);+ assert.match(rows[0].textContent, /Marie.*Hello.*2/);+ // Text is text, never markup (the fake DOM throws on innerHTML).+ assert.match(rows[1].textContent, /Paul: <b>@33612345678<\/b> tu viens \?/);+});++test("a right-click offers to ignore the chat, and only a click does it", () => {+ const c = card();+ WhatsApp.view = connected({ unread: 1, conversations: [conversation()] });+ c.sync();+ c.el.find(".wa-row")[0].fire("contextmenu");+ assert.equal(sent("whatsapp_ignore").length, 0);+ c.el.find(".wa-ignore")[0].fire("click");+ assert.deepEqual(sent("whatsapp_ignore").at(-1), { chat: "[email protected]" });+});++test("a conversation: its messages, a reply sent on Enter only, Escape back to the list", async () => {+ const c = card();+ WhatsApp.view = connected({+ unread: 1,+ conversations: [conversation({ messages: [msg(), msg({ id: "m2", fromMe: true, text: "Salut !" })] })],+ });+ State.mode = "expanded";+ State.focusId = WHATSAPP_ID;+ c.sync();+ const before = sent("whatsapp_open").length;+ c.el.find(".wa-row")[0].fire("click");+ assert.deepEqual(sent("whatsapp_open").slice(before), [{ chat: "[email protected]" }]);+ assert.deepEqual(c.calls.keyboard, [true], "the island takes the keyboard for the field");+ const bubbles = c.el.find(".wa-bubble");+ assert.equal(bubbles.length, 2);+ assert.ok(bubbles[1].classList.contains("mine"));++ const field = c.el.find("TEXTAREA")[0];+ const sends = () => sent("whatsapp_send").length;+ const start = sends();+ // Nothing to send: nothing goes.+ field.value = " ";+ key(field, "Enter");+ assert.equal(sends(), start);+ // Typing holds the island open; Shift+Enter is a new line, not a send.+ field.value = "On arrive";+ for (const fn of field.listeners.get("input")) fn({});+ assert.deepEqual(c.calls.hold, [true]);+ const shifted = key(field, "Enter", true);+ assert.equal(shifted.defaultPrevented, false);+ assert.equal(sends(), start);+ const enter = key(field, "Enter");+ assert.equal(enter.defaultPrevented, true);+ await Promise.resolve();+ assert.deepEqual(sent("whatsapp_send").slice(start), [{ chat: "[email protected]", text: "On arrive" }]);++ // A send refused: the reason shows under the field, the draft stays.+ WhatsApp.view = { ...WhatsApp.view, sendError: { code: "tooLong" } };+ c.sync();+ assert.match(c.el.find(".wa-note")[0].textContent, /Too long for one message/);++ // Escape: back to the list, not the island folding away.+ const esc = key(field, "Escape");+ assert.equal(esc.propagationStopped, true);+ assert.deepEqual(sent("whatsapp_close").at(-1), { chat: "[email protected]" });+ assert.deepEqual(c.calls.keyboard, [true, false]);+ assert.equal(c.calls.hold.at(-1), false);+ assert.equal(c.el.find(".wa-row").length, 1);+});++test("the conversation closes when WhatsApp is turned off or the island folds", () => {+ const c = card();+ WhatsApp.view = connected({ unread: 1, conversations: [conversation()] });+ State.mode = "expanded";+ State.focusId = WHATSAPP_ID;+ c.sync();+ c.el.find(".wa-row")[0].fire("click");+ const closes = sent("whatsapp_close").length;+ State.mode = "compact";+ State.notify();+ assert.equal(sent("whatsapp_close").length, closes + 1);+ // Opened again, then the integration turned off.+ State.mode = "expanded";+ c.sync();+ c.el.find(".wa-row")[0].fire("click");+ WhatsApp.view = { ...IDLE_WHATSAPP };+ c.sync();+ assert.equal(sent("whatsapp_close").length, closes + 2);+});