Files
telefind-rs/crates/telefind-app/src/telegram/client.rs
T

100 lines
2.9 KiB
Rust

use serde::{de::DeserializeOwned, Deserialize};
use serde_json::Value;
use std::{fmt, time::Duration};
use ureq::Agent;
#[derive(Debug)]
pub struct Failure {
pub code: u16,
pub retry_after: Option<Duration>,
}
impl Failure {
pub fn transient(&self) -> bool {
self.code == 0 || self.code == 429 || self.code >= 500
}
}
impl fmt::Display for Failure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self.code {
0 => f.write_str("Telegram connection failed"),
200..=299 => f.write_str("invalid Telegram API response"),
code => write!(f, "Telegram API failure (code {code})"),
}
}
}
impl std::error::Error for Failure {}
#[derive(Deserialize)]
struct Response<T> {
ok: bool,
result: Option<T>,
error_code: Option<u16>,
parameters: Option<Parameters>,
}
#[derive(Deserialize)]
struct Parameters {
retry_after: Option<u64>,
}
pub struct Client {
agent: Agent,
endpoint: String,
}
impl Client {
pub fn new(token: &str) -> Result<Self, &'static str> {
let Some((id, secret)) = token.split_once(':') else {
return Err("invalid TELEGRAM_BOT_TOKEN");
};
if id.is_empty()
|| secret.is_empty()
|| !id.bytes().all(|b| b.is_ascii_digit())
|| !secret
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'_' || b == b'-')
{
return Err("invalid TELEGRAM_BOT_TOKEN");
}
Ok(Self::at(format!("https://api.telegram.org/bot{token}")))
}
pub(super) fn at(endpoint: String) -> Self {
let config = Agent::config_builder()
.timeout_global(Some(Duration::from_secs(50)))
.max_redirects(0)
.http_status_as_error(false)
.build();
Self {
agent: config.into(),
endpoint,
}
}
pub fn call<T: DeserializeOwned>(&self, method: &str, payload: &Value) -> Result<T, Failure> {
// Transport errors may include the request URL, which contains the token.
let mut response = self
.agent
.post(format!("{}/{method}", self.endpoint))
.send_json(payload)
.map_err(|_| Failure {
code: 0,
retry_after: None,
})?;
let status = response.status().as_u16();
let envelope: Response<T> = response.body_mut().read_json().map_err(|_| Failure {
code: status,
retry_after: None,
})?;
if envelope.ok {
return envelope.result.ok_or(Failure {
code: status,
retry_after: None,
});
}
Err(Failure {
code: envelope.error_code.unwrap_or(status),
retry_after: envelope
.parameters
.and_then(|p| p.retry_after)
.map(Duration::from_secs),
})
}
}