proxy_pilot/notify/
bale.rs1use std::time::Duration;
2
3use async_trait::async_trait;
4use reqwest::Client;
5use serde::Serialize;
6
7use crate::error::{PilotError, Result};
8use crate::notify::{AlertEvent, AlertSeverity, Notifier};
9
10const DEFAULT_BALE_API_BASE: &str = "https://tapi.bale.ai";
11
12pub struct BaleNotifier {
13 base_url: String,
14 bot_token: String,
15 chat_id: String,
16 client: Client,
17}
18
19#[derive(Serialize)]
20struct SendMessagePayload<'a> {
21 chat_id: &'a str,
22 text: String,
23}
24
25impl BaleNotifier {
26 pub fn new(bot_token: String, chat_id: String) -> Result<Self> {
27 Self::with_base_url(DEFAULT_BALE_API_BASE.to_string(), bot_token, chat_id)
28 }
29
30 pub fn with_base_url(base_url: String, bot_token: String, chat_id: String) -> Result<Self> {
31 if bot_token.trim().is_empty() || chat_id.trim().is_empty() {
32 return Err(PilotError::Notify(
33 "bale bot_token and chat_id must not be empty".into(),
34 ));
35 }
36 let client = Client::builder()
37 .no_proxy()
38 .connect_timeout(Duration::from_secs(5))
39 .timeout(Duration::from_secs(10))
40 .build()
41 .map_err(|err| PilotError::Notify(format!("failed to build bale client: {err}")))?;
42 Ok(Self {
43 base_url: base_url.trim_end_matches('/').to_string(),
44 bot_token,
45 chat_id,
46 client,
47 })
48 }
49
50 pub fn format_message(event: &AlertEvent) -> String {
51 let icon = match event.severity {
52 AlertSeverity::Info => "ℹ️",
53 AlertSeverity::Warning => "⚠️",
54 AlertSeverity::Critical => "🚨",
55 };
56 format!("{icon} {}\n\n{}", event.title, event.message)
57 }
58}
59
60#[async_trait]
61impl Notifier for BaleNotifier {
62 fn channel_name(&self) -> &'static str {
63 "bale"
64 }
65
66 async fn send(&self, event: &AlertEvent) -> Result<()> {
67 let url = format!("{}/bot{}/sendMessage", self.base_url, self.bot_token);
68 let payload = SendMessagePayload {
69 chat_id: &self.chat_id,
70 text: Self::format_message(event),
71 };
72 let resp = self
73 .client
74 .post(&url)
75 .json(&payload)
76 .send()
77 .await
78 .map_err(|err| {
79 PilotError::Notify(format!("bale request failed: {}", err.without_url()))
80 })?;
81
82 if !resp.status().is_success() {
83 let status = resp.status().as_u16();
84 return Err(PilotError::Notify(format!(
85 "bale api returned HTTP {status}"
86 )));
87 }
88 Ok(())
89 }
90}
91
92#[cfg(test)]
93mod tests {
94 use super::*;
95
96 #[test]
97 fn rejects_empty_credentials() {
98 assert!(BaleNotifier::new("".into(), "123".into()).is_err());
99 assert!(BaleNotifier::new("tok".into(), " ".into()).is_err());
100 }
101
102 #[test]
103 fn formats_alert_with_severity_prefix() {
104 let event = AlertEvent {
105 severity: AlertSeverity::Critical,
106 title: "قطع کامل کانفیگها".into(),
107 message: "هیچ کانفیگ سالمی در دسترس نیست.".into(),
108 };
109 let text = BaleNotifier::format_message(&event);
110 assert!(text.starts_with("🚨 قطع کامل کانفیگها"));
111 assert!(text.contains("هیچ کانفیگ سالمی"));
112 }
113}