1use super::access::Access;
6use super::{Channel, IncomingMessage, OutgoingMessage, html_escape};
7use anyhow::Context;
8use async_trait::async_trait;
9use chrono::{DateTime, Utc};
10use reqwest::Client;
11use serde::Deserialize;
12use sha2::{Digest, Sha256};
13use std::fmt;
14use std::fmt::Debug;
15use std::fmt::Formatter;
16use std::fmt::Write as _;
17use std::mem;
18use std::sync::Arc;
19use std::time::Duration;
20use tokio::sync::Mutex;
21use tokio::sync::mpsc;
22use tokio::sync::mpsc::Receiver;
23use tokio::time;
24
25const TELEGRAM_LONG_POLL_TIMEOUT_SECS: u64 = 30;
26const TELEGRAM_HTTP_TIMEOUT_SECS: u64 = TELEGRAM_LONG_POLL_TIMEOUT_SECS + 15;
27const TELEGRAM_MAX_RETRIES: u32 = 3;
28const _: () = assert!(
29 TELEGRAM_HTTP_TIMEOUT_SECS > TELEGRAM_LONG_POLL_TIMEOUT_SECS,
30 "the HTTP timeout must outlast the long poll"
31);
32
33const MAX_MESSAGE_CHARS: usize = 4000;
39
40fn split_for_telegram(text: &str, max: usize) -> Vec<String> {
44 let size = |s: &str| html_escape(s).chars().count();
45 let mut parts = Vec::new();
46 let mut current = String::new();
47 for line in text.split_inclusive('\n') {
48 if !current.is_empty() && size(¤t) + size(line) > max {
49 parts.push(mem::take(&mut current));
50 }
51 if size(line) <= max {
52 current.push_str(line);
53 continue;
54 }
55
56 for c in line.chars() {
57 let mut buf = [0u8; 4];
58 let c = c.encode_utf8(&mut buf);
59 if size(¤t) + size(c) > max {
60 parts.push(mem::take(&mut current));
61 }
62 current.push_str(c);
63 }
64 }
65 if !current.is_empty() || parts.is_empty() {
66 parts.push(current);
67 }
68 parts
69}
70
71fn is_preformatted_html(msg: &OutgoingMessage) -> bool {
72 msg.metadata
73 .get("preformatted_html")
74 .and_then(serde_json::Value::as_bool)
75 .unwrap_or(false)
76}
77
78pub struct TelegramChannel {
79 pub token: String,
80 pub client: Client,
81 pub chat_id: Option<String>,
82 pub allowed_user_ids: Vec<String>,
83 pub offset: Arc<Mutex<i64>>,
84}
85
86impl Debug for TelegramChannel {
87 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
88 f.debug_struct("TelegramChannel")
89 .field("chat_id", &self.chat_id)
90 .finish_non_exhaustive()
91 }
92}
93
94#[derive(Deserialize)]
95struct TelegramUser {
96 id: i64,
97 first_name: String,
98 #[serde(default)]
99 username: Option<String>,
100}
101
102#[derive(Deserialize)]
103struct TelegramMessage {
104 message_id: i64,
105 from: Option<TelegramUser>,
106 chat: TelegramChat,
107 text: Option<String>,
108 date: i64,
109 #[serde(default)]
110 message_thread_id: Option<i64>,
111}
112
113#[derive(Deserialize)]
114struct TelegramChat {
115 id: i64,
116}
117
118#[derive(Deserialize)]
119struct CallbackQuery {
120 id: String,
121 from: TelegramUser,
122 message: Option<TelegramMessage>,
123 data: Option<String>,
124}
125
126#[derive(Deserialize)]
127struct Update {
128 #[serde(rename = "update_id")]
129 id: i64,
130 message: Option<TelegramMessage>,
131 callback_query: Option<CallbackQuery>,
132}
133
134#[derive(Deserialize)]
135struct GetUpdatesResponse {
136 ok: bool,
137 result: Vec<Update>,
138}
139
140impl TelegramChannel {
141 pub fn new(token: String, chat_id: Option<String>) -> anyhow::Result<Self> {
142 let client = Client::builder()
143 .timeout(Duration::from_secs(TELEGRAM_HTTP_TIMEOUT_SECS))
144 .build()
145 .context("failed to build HTTP client")?;
146
147 Ok(Self {
148 token,
149 client,
150 chat_id,
151 allowed_user_ids: Vec::new(),
152 offset: Arc::new(Mutex::new(0)),
153 })
154 }
155
156 #[must_use]
158 pub fn with_allowed_users(mut self, user_ids: Vec<String>) -> Self {
159 self.allowed_user_ids = user_ids;
160 self
161 }
162
163 fn api_url(&self, method: &str) -> String {
164 format!("https://api.telegram.org/bot{}/{}", self.token, method)
165 }
166
167 async fn get_updates(&self, offset: i64) -> anyhow::Result<Vec<Update>> {
168 let url = self.api_url("getUpdates");
169
170 let params = serde_json::json!({
171 "offset": offset,
172 "timeout": TELEGRAM_LONG_POLL_TIMEOUT_SECS,
173 "allowed_updates": ["message", "callback_query"]
174 });
175
176 for attempt in 0..TELEGRAM_MAX_RETRIES {
177 let response = match self
178 .client
179 .post(&url)
180 .json(¶ms)
181 .send()
182 .await
183 .map_err(reqwest::Error::without_url)
184 {
185 Ok(r) => r,
186 Err(e) => {
187 if attempt + 1 < TELEGRAM_MAX_RETRIES {
188 time::sleep(Duration::from_secs(2)).await;
189 continue;
190 }
191 anyhow::bail!(
192 "telegram getUpdates failed after {TELEGRAM_MAX_RETRIES} attempts: {e}",
193 );
194 }
195 };
196
197 if !response.status().is_success() {
198 let body = response.text().await.unwrap_or_default();
199 anyhow::bail!("telegram API error: {body}");
200 }
201
202 let updates: GetUpdatesResponse =
203 response.json().await.map_err(reqwest::Error::without_url)?;
204
205 if !updates.ok {
206 anyhow::bail!("telegram API returned ok=false");
207 }
208
209 return Ok(updates.result);
210 }
211
212 anyhow::bail!("telegram getUpdates failed after {TELEGRAM_MAX_RETRIES} attempts");
213 }
214
215 async fn send_message(
216 &self,
217 chat_id: i64,
218 text: &str,
219 topic_id: Option<i64>,
220 ) -> anyhow::Result<()> {
221 for part in split_for_telegram(text, MAX_MESSAGE_CHARS) {
222 self.send_formatted_message(chat_id, &html_escape(&part), topic_id)
223 .await?;
224 }
225 Ok(())
226 }
227
228 async fn send_formatted_message(
229 &self,
230 chat_id: i64,
231 text: &str,
232 topic_id: Option<i64>,
233 ) -> anyhow::Result<()> {
234 let url = self.api_url("sendMessage");
235
236 let mut params = serde_json::json!({
240 "chat_id": chat_id,
241 "text": text,
242 "parse_mode": "HTML"
243 });
244 if let Some(tid) = topic_id {
245 params["message_thread_id"] = serde_json::json!(tid);
246 }
247
248 let response = self
249 .client
250 .post(&url)
251 .json(¶ms)
252 .send()
253 .await
254 .map_err(reqwest::Error::without_url)?;
255
256 if !response.status().is_success() {
257 let body = response.text().await.unwrap_or_default();
258 anyhow::bail!("telegram API error: {body}");
259 }
260
261 Ok(())
262 }
263
264 pub async fn send_inline_keyboard(
265 &self,
266 chat_id: i64,
267 topic_id: Option<i64>,
268 text: &str,
269 buttons: &[(String, String)], ) -> anyhow::Result<i64> {
271 let keyboard: Vec<Vec<serde_json::Value>> = buttons
272 .iter()
273 .map(|(label, data)| {
274 vec![serde_json::json!({
275 "text": label,
276 "callback_data": data
277 })]
278 })
279 .collect();
280
281 let mut params = serde_json::json!({
282 "chat_id": chat_id,
283 "text": text,
284 "reply_markup": { "inline_keyboard": keyboard }
285 });
286 if let Some(tid) = topic_id {
287 params["message_thread_id"] = serde_json::json!(tid);
288 }
289
290 let url = self.api_url("sendMessage");
291 let response = self
292 .client
293 .post(&url)
294 .json(¶ms)
295 .send()
296 .await
297 .map_err(reqwest::Error::without_url)?;
298 if !response.status().is_success() {
299 let body = response.text().await.unwrap_or_default();
300 anyhow::bail!("telegram API error: {body}");
301 }
302 let result: serde_json::Value =
303 response.json().await.map_err(reqwest::Error::without_url)?;
304 let message_id = result["result"]["message_id"].as_i64().unwrap_or(0);
305 Ok(message_id)
306 }
307
308 pub async fn answer_callback_query(
309 &self,
310 callback_query_id: &str,
311 text: &str,
312 ) -> anyhow::Result<()> {
313 let url = self.api_url("answerCallbackQuery");
314 let params = serde_json::json!({
315 "callback_query_id": callback_query_id,
316 "text": text
317 });
318 let response = self
319 .client
320 .post(&url)
321 .json(¶ms)
322 .send()
323 .await
324 .map_err(reqwest::Error::without_url)?;
325 if !response.status().is_success() {
326 let body = response.text().await.unwrap_or_default();
327 anyhow::bail!("telegram API error: {body}");
328 }
329 Ok(())
330 }
331}
332
333#[async_trait]
334impl Channel for TelegramChannel {
335 fn name(&self) -> &'static str {
336 "telegram"
337 }
338
339 async fn start(&self) -> anyhow::Result<Receiver<IncomingMessage>> {
340 let (tx, rx) = mpsc::channel(64);
341 let token = self.token.clone();
342 let client = self.client.clone();
343 let chat_id = self.chat_id.clone();
344 let access = Access::new(chat_id.clone(), self.allowed_user_ids.clone());
345 access.warn_if_closed("telegram");
346 let allowed_user_ids = self.allowed_user_ids.clone();
347 let offset = Arc::clone(&self.offset);
348
349 let token_fingerprint = {
350 let mut hasher = Sha256::new();
351 hasher.update(token.as_bytes());
352 let hash = hasher.finalize();
353 let hex = hash[..8].iter().fold(String::new(), |mut hex, b| {
354 let _ = write!(hex, "{b:02x}");
355 hex
356 });
357 format!("sha256:{hex}")
358 };
359
360 tracing::info!(token_fingerprint = %token_fingerprint, "telegram channel started");
361
362 let channel = TelegramChannel {
364 token,
365 client,
366 chat_id,
367 allowed_user_ids,
368 offset: Arc::clone(&offset),
369 };
370
371 tokio::spawn(async move {
372 const POLL_BACKOFF_BASE: Duration = Duration::from_secs(5);
373 const POLL_BACKOFF_CAP: Duration = Duration::from_secs(60);
374 let mut backoff = POLL_BACKOFF_BASE;
375
376 loop {
377 let current_offset = {
378 let off = offset.lock().await;
379 *off
380 };
381
382 let updates = match channel.get_updates(current_offset).await {
383 Ok(u) => u,
384 Err(e) => {
385 tracing::warn!(
386 ?e,
387 backoff_secs = backoff.as_secs(),
388 "failed to get telegram updates"
389 );
390 time::sleep(backoff).await;
391 backoff = (backoff * 2).min(POLL_BACKOFF_CAP);
392 continue;
393 }
394 };
395 backoff = POLL_BACKOFF_BASE;
396
397 let has_updates = !updates.is_empty();
398
399 for update in updates {
400 {
402 let mut off = offset.lock().await;
403 if update.id + 1 > *off {
404 *off = update.id + 1;
405 }
406 }
407
408 if let Some(cb) = update.callback_query {
410 let cb_chat = cb.message.as_ref().map(|m| m.chat.id.to_string());
411 if !cb_chat
412 .as_deref()
413 .is_some_and(|c| access.allows(c, &cb.from.id.to_string()))
414 {
415 tracing::warn!(chat = ?cb_chat, user = cb.from.id, "dropping telegram callback from unauthorized sender");
416 continue;
417 }
418 let chat_id_val = cb
419 .message
420 .as_ref()
421 .map(|m| m.chat.id.to_string())
422 .unwrap_or_default();
423 let topic_id = cb
424 .message
425 .as_ref()
426 .and_then(|m| m.message_thread_id)
427 .map(|id| id.to_string());
428 let author = cb
429 .from
430 .username
431 .clone()
432 .unwrap_or(cb.from.first_name.clone());
433 let body = cb.data.clone().unwrap_or_default();
434 let msg_id = cb
435 .message
436 .as_ref()
437 .map(|m| m.message_id.to_string())
438 .unwrap_or_default();
439 let msg_date = cb.message.as_ref().map_or(0, |m| m.date);
440
441 let incoming = IncomingMessage {
442 channel: "telegram".to_string(),
443 id: msg_id,
444 thread_id: chat_id_val,
445 author,
446 body,
447 timestamp: DateTime::from_timestamp(msg_date, 0)
448 .unwrap_or_else(Utc::now),
449 metadata: serde_json::json!({
450 "callback_query_id": cb.id,
451 "callback_data": cb.data
452 }),
453 topic_id,
454 };
455
456 if tx.send(incoming).await.is_err() {
457 tracing::debug!("telegram channel receiver dropped");
458 return;
459 }
460 continue;
461 }
462
463 let Some(msg) = update.message else { continue };
465
466 if !msg
467 .from
468 .as_ref()
469 .is_some_and(|u| access.allows(&msg.chat.id.to_string(), &u.id.to_string()))
470 {
471 tracing::warn!(
472 chat = msg.chat.id,
473 user = msg.from.as_ref().map(|u| u.id),
474 "dropping telegram message from unauthorized sender"
475 );
476 continue;
477 }
478
479 let author = msg.from.as_ref().map_or_else(
480 || "unknown".to_string(),
481 |u| u.username.clone().unwrap_or(u.first_name.clone()),
482 );
483
484 let body = msg.text.unwrap_or_default();
485
486 if body.is_empty() {
488 continue;
489 }
490
491 let topic_id = msg.message_thread_id.map(|id| id.to_string());
492
493 let incoming = IncomingMessage {
494 channel: "telegram".to_string(),
495 id: msg.message_id.to_string(),
496 thread_id: msg.chat.id.to_string(),
497 author,
498 body,
499 timestamp: DateTime::from_timestamp(msg.date, 0).unwrap_or_else(Utc::now),
500 metadata: serde_json::json!({ "chat_id": msg.chat.id }),
501 topic_id,
502 };
503
504 if tx.send(incoming).await.is_err() {
505 tracing::debug!("telegram channel receiver dropped");
506 return;
507 }
508 }
509
510 if !has_updates {
512 time::sleep(Duration::from_secs(1)).await;
513 }
514 }
515 });
516
517 Ok(rx)
518 }
519
520 async fn send(&self, msg: &OutgoingMessage) -> anyhow::Result<()> {
521 let chat_id = if let Some(override_val) = msg.metadata.get("chat_id_override") {
523 override_val
524 .as_str()
525 .ok_or_else(|| anyhow::anyhow!("chat_id_override is not a string"))?
526 .parse::<i64>()
527 .map_err(|_| anyhow::anyhow!("invalid chat_id_override"))?
528 } else {
529 self.chat_id
530 .as_ref()
531 .ok_or_else(|| anyhow::anyhow!("telegram chat_id not configured"))?
532 .parse::<i64>()
533 .map_err(|_| anyhow::anyhow!("invalid chat_id"))?
534 };
535
536 let topic_id = msg.topic_id.as_ref().and_then(|t| t.parse::<i64>().ok());
537
538 if let Some(buttons_val) = msg.metadata.get("buttons")
540 && let Some(buttons_arr) = buttons_val.as_array()
541 {
542 let buttons: Vec<(String, String)> = buttons_arr
543 .iter()
544 .filter_map(|b| {
545 let text = b["text"].as_str()?.to_string();
546 let callback_data = b["callback_data"].as_str()?.to_string();
547 Some((text, callback_data))
548 })
549 .collect();
550 if !buttons.is_empty() {
551 self.send_inline_keyboard(chat_id, topic_id, &msg.body, &buttons)
552 .await?;
553 return Ok(());
554 }
555 }
556
557 let preformatted = is_preformatted_html(msg);
560
561 if preformatted {
562 self.send_formatted_message(chat_id, &msg.body, topic_id)
563 .await
564 } else {
565 self.send_message(chat_id, &msg.body, topic_id).await
566 }
567 }
568
569 async fn ack_interaction(&self, callback_query_id: &str) -> anyhow::Result<()> {
570 self.answer_callback_query(callback_query_id, "").await
571 }
572
573 async fn health_check(&self) -> anyhow::Result<()> {
574 let url = self.api_url("getMe");
575
576 let response = self
577 .client
578 .get(&url)
579 .send()
580 .await
581 .map_err(reqwest::Error::without_url)?;
582
583 if !response.status().is_success() {
584 let body = response.text().await.unwrap_or_default();
585 anyhow::bail!("telegram health check failed: {body}");
586 }
587
588 tracing::info!("telegram bot health check passed");
589 Ok(())
590 }
591}
592
593#[cfg(test)]
594mod tests {
595
596 use super::*;
597 use serde_json::json;
598
599 #[tokio::test]
600 async fn request_errors_do_not_contain_the_token_url() {
601 let token = "123456:FAKE-TOKEN";
602 let url = format!("http://127.0.0.1:1/bot{token}/getUpdates");
603 let err = Client::new()
604 .post(&url)
605 .send()
606 .await
607 .expect_err("port 1 refuses connections");
608 assert!(err.to_string().contains(token));
609
610 let err = reqwest::Error::without_url(err);
611 assert!(!err.to_string().contains(token));
612 assert!(!format!("{err:?}").contains(token));
613 }
614
615 #[test]
616 fn a_short_message_is_one_part() {
617 assert_eq!(split_for_telegram("hello\nworld", 4000), ["hello\nworld"]);
618 assert_eq!(split_for_telegram("", 4000), [""]);
619 }
620
621 #[test]
622 fn a_long_message_splits_at_line_ends_and_loses_nothing() {
623 let text = (0..400).fold(String::new(), |mut text, i| {
624 let _ = writeln!(text, "line {i} with some text");
625 text
626 });
627 let parts = split_for_telegram(&text, 4000);
628 assert!(parts.len() > 1);
629 assert_eq!(parts.concat(), text);
630 for part in &parts {
631 assert!(html_escape(part).chars().count() <= 4000);
632 assert!(part.ends_with('\n'), "a part ended mid line");
633 }
634 }
635
636 #[test]
637 fn escaping_counts_toward_the_limit_and_an_entity_is_never_cut() {
638 let text = "&".repeat(3000);
639 let parts = split_for_telegram(&text, 4000);
640 assert_eq!(parts.concat(), text);
641 for part in &parts {
642 let escaped = html_escape(part);
643 assert!(escaped.chars().count() <= 4000);
644 assert_eq!(escaped.matches("&").count(), part.len());
645 }
646 }
647
648 #[test]
649 fn a_line_longer_than_the_limit_is_hard_split_on_char_boundaries() {
650 let text = "é".repeat(9000);
651 let parts = split_for_telegram(&text, 4000);
652 assert_eq!(parts.len(), 3);
653 assert_eq!(parts.concat(), text);
654 }
655
656 #[test]
657 fn html_escape_escapes_telegram_html_entities() {
658 assert_eq!(
659 html_escape("a < b && c > d"),
660 "a < b && c > d"
661 );
662 }
663
664 #[test]
665 fn preformatted_html_defaults_to_false() {
666 let msg = OutgoingMessage {
667 thread_id: "thread".to_string(),
668 body: "raw <text>".to_string(),
669 reply_to: None,
670 metadata: serde_json::Value::Null,
671 topic_id: None,
672 };
673
674 assert!(!is_preformatted_html(&msg));
675 }
676
677 #[test]
678 fn preformatted_html_honors_metadata_flag() {
679 let msg = OutgoingMessage {
680 thread_id: "thread".to_string(),
681 body: "<b>formatted</b>".to_string(),
682 reply_to: None,
683 metadata: json!({ "preformatted_html": true }),
684 topic_id: None,
685 };
686
687 assert!(is_preformatted_html(&msg));
688 }
689}