use crate::config::TelegramConfig; use anyhow::{anyhow, bail, Context, Result}; use serde::{Deserialize, Serialize}; use serde_json::{json, Value}; use std::future::Future; use std::io::Read; use std::pin::Pin; use std::sync::atomic::{AtomicI64, Ordering}; use std::time::{Duration, Instant}; /// Approval prompts with Approve/Deny buttons. A bot has one getUpdates /// consumer, so exactly one process may own it: a host's broker in direct /// mode, or the gateway (gateway.rs) for every host. pub struct Telegram { http: reqwest::Client, /// Contains the token: never print it, and strip it from reqwest errors. base: String, chat_id: i64, offset: AtomicI64, } #[derive(Clone, Copy, PartialEq, Debug, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub enum Verdict { Approved, Denied, Expired, Cancelled, } impl Verdict { fn outcome(self) -> &'static str { match self { Verdict::Approved => "✅ approved", Verdict::Denied => "❌ denied", Verdict::Expired => "⌛ expired", Verdict::Cancelled => "🚫 cancelled: the requester went away", } } } /// An owner's tap on a live prompt's button. pub struct Tap { pub nonce: String, pub verdict: Verdict, } impl Telegram { pub fn new(cfg: &TelegramConfig) -> Result { let token = std::fs::read_to_string(&cfg.token_file) .with_context(|| format!("reading {}", cfg.token_file.display()))?; let chat_id = std::fs::read_to_string(&cfg.chat_id_file) .with_context(|| format!("reading {}", cfg.chat_id_file.display()))? .trim() .parse() .context("telegram chat id is not a number")?; Ok(Self { http: reqwest::Client::builder().timeout(Duration::from_secs(40)).build()?, base: format!("{}/bot{}", cfg.api_base.trim_end_matches('/'), token.trim()), chat_id, offset: AtomicI64::new(0), }) } async fn call(&self, method: &str, body: Value) -> Result { let resp = self .http .post(format!("{}/{method}", self.base)) .json(&body) .send() .await .map_err(|e| anyhow!("telegram {method}: {}", e.without_url()))?; let v: Value = resp .json() .await .map_err(|e| anyhow!("telegram {method}: {}", e.without_url()))?; if v["ok"] != json!(true) { bail!("telegram {method}: {}", v["description"]); } Ok(v["result"].clone()) } /// Sends the prompt; returns its message id. pub async fn prompt(&self, text: &str, nonce: &str) -> Result { let msg = self .call( "sendMessage", json!({ "chat_id": self.chat_id, "text": text, "reply_markup": { "inline_keyboard": [[ { "text": "Approve", "callback_data": format!("ok:{nonce}") }, { "text": "Deny", "callback_data": format!("no:{nonce}") }, ]]}, }), ) .await?; msg["message_id"].as_i64().ok_or_else(|| anyhow!("sendMessage returned no message_id")) } /// One long poll. Every tap is answered; the owner's taps on prompts /// `live` still knows are returned. pub async fn taps(&self, timeout_secs: u64, live: impl Fn(&str) -> bool) -> Result> { let updates = self .call( "getUpdates", json!({ "offset": self.offset.load(Ordering::SeqCst), "timeout": timeout_secs, "allowed_updates": ["callback_query"], }), ) .await?; let mut taps = vec![]; for u in updates.as_array().into_iter().flatten() { if let Some(id) = u["update_id"].as_i64() { self.offset.fetch_max(id + 1, Ordering::SeqCst); } let cq = &u["callback_query"]; let Some(cq_id) = cq["id"].as_str() else { continue }; let data = cq["data"].as_str().unwrap_or(""); let tap = match data.split_once(':') { Some(("ok", n)) => Some((n, Verdict::Approved)), Some(("no", n)) => Some((n, Verdict::Denied)), _ => None, } .filter(|(n, _)| live(n)); // The button lives in our chat, but the bot can be added // elsewhere and a forwarded message keeps its buttons. let from_owner = cq["from"]["id"].as_i64() == Some(self.chat_id); let note = match (&tap, from_owner) { (_, false) => "Not yours.", (None, true) => "Expired.", (Some(_), true) => "", }; let _ = self .call("answerCallbackQuery", json!({ "callback_query_id": cq_id, "text": note })) .await; if let (Some((n, verdict)), true) = (tap, from_owner) { taps.push(Tap { nonce: n.to_string(), verdict }); } } Ok(taps) } /// Appends the outcome; without reply_markup this also drops the buttons. pub async fn conclude(&self, message_id: i64, text: &str, verdict: Verdict) { let _ = self .call( "editMessageText", json!({ "chat_id": self.chat_id, "message_id": message_id, "text": format!("{text}\n\n{}", verdict.outcome()), }), ) .await; } /// Direct mode: prompt and poll in one call. Callers must not ask /// concurrently. `gone` resolving (the client hung up) withdraws it. pub async fn ask( &self, text: &str, timeout: Duration, mut gone: Pin<&mut impl Future>, ) -> Result { let nonce = nonce()?; let message_id = self.prompt(text, &nonce).await?; let deadline = Instant::now() + timeout; let verdict = 'poll: loop { let left = deadline.saturating_duration_since(Instant::now()); if left.is_zero() { break Verdict::Expired; } let polled = tokio::select! { biased; _ = gone.as_mut() => break 'poll Verdict::Cancelled, r = self.taps(left.as_secs().min(25), |n| n == nonce) => r, }; match polled { Ok(taps) => { if let Some(t) = taps.first() { break t.verdict; } } Err(e) => { eprintln!("{e:#}"); tokio::time::sleep(Duration::from_secs(2)).await; } } }; self.conclude(message_id, text, verdict).await; Ok(verdict) } } pub fn nonce() -> Result { let mut buf = [0u8; 16]; std::fs::File::open("/dev/urandom")?.read_exact(&mut buf)?; Ok(buf.iter().map(|b| format!("{b:02x}")).collect()) }