Cotton code
117 lines · 6.0 KB · RustRaw
//! A fake WhatsApp helper on its Unix socket, speaking the Go link's//! protocol (apps/cotton-whatsapp-link): hello, events, ack, media and send.//! A text it sends it keeps as the owner's message, as the real one does.use std::io::{BufRead, BufReader, Write};use std::os::unix::net::UnixListener;use std::path::Path;use std::sync::{Arc, Mutex};use cotton_client::ingest::sources::whatsapp_link::{PROTOCOL_VERSION, SOCKET_NAME};use serde_json::{json, Value};#[derive(Default)]pub struct Helper {    pub outbox: Vec<Value>,    pub acks: Vec<i64>,    pub media_asks: usize,    /// The numbers `hello` names as linked.    pub accounts: Vec<String>,    /// Every `send` asked.    pub sends: Vec<Value>,    /// The bytes of each file a send named (`path`), by its message id, read when it was asked.    pub files: Vec<(String, Vec<u8>)>,}/// What the real helper keeps of a send it made (send.go sentEvent, send_kinds.go sentKindEvent), for the reader.fn echo(request: &Value, seq: i64, ts: i64) -> Value {    let chat = request["chat"].clone();    let is_group = chat.as_str().is_some_and(|c| c.ends_with("@g.us"));    let mut message = json!({ "id": request["message_id"], "chat": chat, "from_me": true, "is_group": is_group, "ts": ts, "kind": "text", "text": request["text"], "origin": "live" });    let kind = request["kind"].as_str().unwrap_or("text");    let mut event = "message";    match kind {        "picture" | "video" | "voice" | "audio" | "document" => {            message["kind"] = json!(match kind { "picture" => "image", other => other });            message["landed"] = request["landed"].clone();        }        "poll" => {            message["kind"] = json!("poll");            message["poll"] = json!({ "options": request["options"], "selectable": request["selectable"].as_u64().unwrap_or(0) });        }        "reaction" => {            message["kind"] = json!("reaction");            message["reaction_to"] = request["target"].clone();            message["text"] = request["emoji"].clone();        }        "edit" => message["edit_of"] = request["target"].clone(),        "delete" => event = "revoke",        "poll_vote" => event = "skip",        _ => {}    }    if let Some(quoted) = request["quoted_id"].as_str() {        message["quoted_id"] = json!(quoted);    }    // As the real helper writes it (omitempty): no field that holds nothing.    let strip = |value: Value| match value {        Value::Object(map) => Value::Object(map.into_iter().filter(|(_, v)| !v.is_null()).collect()),        other => other,    };    strip(json!({ "seq": seq, "event": event, "account": request["account"], "chat": request["chat"], "target": request["target"], "message": strip(message) }))}/// A helper holding `outbox`, answering every `media` request as the real/// one answers a pointer with no direct path.pub fn fake_helper(dir: &Path, state: Arc<Mutex<Helper>>) {    let listener = UnixListener::bind(dir.join(SOCKET_NAME)).unwrap();    std::thread::spawn(move || {        for stream in listener.incoming() {            let Ok(stream) = stream else { return };            let state = Arc::clone(&state);            std::thread::spawn(move || {                let mut writer = stream.try_clone().unwrap();                for line in BufReader::new(stream).lines() {                    let Ok(line) = line else { return };                    let request: Value = serde_json::from_str(&line).unwrap();                    let id = request["id"].clone();                    let mut helper = state.lock().unwrap();                    let reply = match request["op"].as_str().unwrap() {                        "hello" => json!({ "reply": id, "ok": true, "result": { "version": PROTOCOL_VERSION, "accounts": helper.accounts.iter().map(|a| json!({ "account": a, "state": "connected" })).collect::<Vec<_>>(), "pending": helper.outbox.len() } }),                        "events" => {                            let after = request["after"].as_i64().unwrap_or(0);                            let page: Vec<Value> = helper.outbox.iter().filter(|e| e["seq"].as_i64().unwrap() > after).cloned().collect();                            json!({ "reply": id, "ok": true, "result": { "events": page } })                        }                        "ack" => {                            let seq = request["seq"].as_i64().unwrap();                            helper.acks.push(seq);                            helper.outbox.retain(|e| e["seq"].as_i64().unwrap() > seq);                            json!({ "reply": id, "ok": true, "result": null })                        }                        "media" => {                            helper.media_asks += 1;                            json!({ "reply": id, "ok": false, "error": "unfetchable: media pointer incomplete: no direct path" })                        }                        "send" => {                            helper.sends.push(request.clone());                            if let Some(path) = request["path"].as_str() {                                let bytes = std::fs::read(path).unwrap_or_default();                                helper.files.push((request["message_id"].as_str().unwrap_or_default().to_string(), bytes));                            }                            let seq = helper.outbox.iter().filter_map(|e| e["seq"].as_i64()).max().unwrap_or(0).max(helper.acks.last().copied().unwrap_or(0)) + 1;                            let ts = 1_763_100_000 + seq;                            let kept = echo(&request, seq, ts);                            if kept["event"] != "skip" {                                helper.outbox.push(kept);                            }                            json!({ "reply": id, "ok": true, "result": { "id": request["message_id"], "ts": ts } })                        }                        other => panic!("the reader must not ask the helper for {other}"),                    };                    writer.write_all(format!("{reply}\n").as_bytes()).unwrap();                }            });        }    });}