Skip to main content

telegram_client/api/
inner.rs

1use std::borrow::Borrow;
2use std::sync::{Arc, LazyLock, OnceLock};
3
4use log::{debug, info};
5use rtdlib::errors::RTDResult;
6use rtdlib::types::RFunction;
7use rtdlib::Tdlib;
8
9use crate::api::aasync::AsyncApi;
10use crate::api::aevent::EventApi;
11
12static API_ID_RE: LazyLock<regex::Regex> =
13  LazyLock::new(|| regex::Regex::new(r#""api_id"\s*:\s*"?[0-9]+"?"#).expect("api_id regex"));
14
15static API_HASH_RE: LazyLock<regex::Regex> = LazyLock::new(|| {
16  regex::Regex::new(r#""api_hash"\s*:\s*"[0-9A-Fa-f]*""#).expect("api_hash regex")
17});
18
19/// Hide Telegram application credentials before they reach the log.
20pub(crate) fn redact_secrets(text: &str) -> String {
21  let hide_api_id = API_ID_RE.replace_all(text, r#""api_id":"****""#);
22  API_HASH_RE
23    .replace_all(&hide_api_id, r#""api_hash":"**********""#)
24    .into_owned()
25}
26
27#[derive(Debug, Clone)]
28pub struct ApiBuilder {
29  // Shared so `build` can fill it through `&self`, and so a cloned builder
30  // still returns the same client. `Api::new` stores the caller's client
31  // before the first `build`.
32  tdlib: Arc<OnceLock<Arc<Tdlib>>>,
33  log: bool,
34  unsafe_log: bool,
35}
36
37impl Default for ApiBuilder {
38  fn default() -> Self {
39    Self::new()
40  }
41}
42
43impl ApiBuilder {
44  /// Does not call `Tdlib::new`. The client is created on [`Self::build`],
45  /// or taken from [`Api::new`] when the caller already has one.
46  ///
47  /// Creating it here opened a client that `Api::event` and `Api::rasync`
48  /// immediately replaced. TDLib then destroyed that extra client and logged
49  /// `authorizationStateClosing` / `authorizationStateClosed` for it.
50  pub fn new() -> Self {
51    Self {
52      tdlib: Arc::new(OnceLock::new()),
53      log: true,
54      unsafe_log: false,
55    }
56  }
57
58  pub fn build(&self) -> Api {
59    let tdlib = Arc::clone(self.tdlib.get_or_init(|| Arc::new(Tdlib::new())));
60    Api {
61      tdlib,
62      log: self.log,
63      unsafe_log: self.unsafe_log,
64    }
65  }
66
67  fn tdlib(&mut self, tdlib: Tdlib) -> &mut Self {
68    self
69      .tdlib
70      .set(Arc::new(tdlib))
71      .expect("TDLib client is already set on this builder");
72    self
73  }
74
75  pub fn log(&mut self, open: bool) -> &mut Self {
76    self.log = open;
77    self
78  }
79
80  pub fn unsafe_log(&mut self, unsafe_log: bool) -> &mut Self {
81    self.unsafe_log = unsafe_log;
82    self
83  }
84}
85
86#[derive(Debug, Clone)]
87pub struct Api {
88  tdlib: Arc<Tdlib>,
89  log: bool,
90  unsafe_log: bool,
91}
92
93impl Default for Api {
94  fn default() -> Self {
95    ApiBuilder::new().build()
96  }
97}
98
99impl Api {
100  pub fn builder() -> ApiBuilder {
101    ApiBuilder::new()
102  }
103
104  pub fn new(tdlib: Tdlib) -> Self {
105    ApiBuilder::new().tdlib(tdlib).build()
106  }
107
108  pub fn event() -> EventApi {
109    Api::event_with_api(Api::default())
110  }
111
112  pub fn event_with_tdlib(tdlib: Tdlib) -> EventApi {
113    Api::event_with_api(Api::new(tdlib))
114  }
115
116  pub fn event_with_api(api: Api) -> EventApi {
117    EventApi::new(api)
118  }
119
120  pub fn rasync() -> AsyncApi {
121    Api::rasync_with_api(Api::default())
122  }
123
124  pub fn rasync_with_tdlib(tdlib: Tdlib) -> AsyncApi {
125    Api::rasync_with_api(Api::new(tdlib))
126  }
127
128  pub fn rasync_with_api(api: Api) -> AsyncApi {
129    AsyncApi::new(api)
130  }
131
132  pub fn event_api(&self) -> EventApi {
133    Api::event_with_api(self.clone())
134  }
135
136  pub fn rasync_api(&self) -> AsyncApi {
137    Api::rasync_with_api(self.clone())
138  }
139
140  #[doc(hidden)]
141  pub fn tdlib(&self) -> &Tdlib {
142    self.tdlib.borrow()
143  }
144
145  fn safe_log(&self, text: &str) -> String {
146    if self.unsafe_log || (!text.contains("api_id") && !text.contains("api_hash")) {
147      text.to_string()
148    } else {
149      redact_secrets(text)
150    }
151  }
152
153  pub fn send<Fnc: RFunction>(&self, fnc: Fnc) -> RTDResult<()> {
154    let json = fnc.to_json()?;
155    if self.log {
156      debug!("===> {}", self.safe_log(&json));
157    }
158    self.tdlib.send(&json[..]);
159    Ok(())
160  }
161
162  pub fn receive(&self, timeout: f64) -> Option<String> {
163    let receive = self.tdlib.receive(timeout);
164    if self.log {
165      if let Some(value) = receive.as_ref() {
166        debug!("<=== {}", self.safe_log(value));
167      }
168    }
169    receive
170  }
171
172  pub fn execute<Fnc: RFunction>(&self, fnc: Fnc) -> RTDResult<Option<String>> {
173    let json = fnc.to_json()?;
174    if self.log {
175      info!("===>>> {}", self.safe_log(&json));
176    }
177    Ok(self.tdlib.execute(&json[..]))
178  }
179}
180
181#[cfg(test)]
182mod tests {
183  use super::*;
184
185  #[test]
186  fn safe_log_redacts_tdlib_credentials() {
187    let api = Api::default();
188    let raw = r#"{"@type":"setTdlibParameters","api_id":12345,"api_hash":"0123abcdef"}"#;
189    let out = api.safe_log(raw);
190    assert!(!out.contains("12345"));
191    assert!(!out.contains("0123abcdef"));
192    assert!(out.contains(r#""api_id":"****""#));
193    assert!(out.contains(r#""api_hash":"**********""#));
194  }
195
196  #[test]
197  fn unsafe_log_keeps_credentials() {
198    let api = Api::builder().unsafe_log(true).build();
199    let raw = r#"{"api_id":12345,"api_hash":"abcdef"}"#;
200    assert_eq!(api.safe_log(raw), raw);
201  }
202
203  #[test]
204  fn safe_log_leaves_unrelated_payloads_unchanged() {
205    let api = Api::default();
206    let raw = r#"{"@type":"getMe"}"#;
207    assert_eq!(api.safe_log(raw), raw);
208  }
209}