1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
use std::{error::Error, sync::Arc};

use crate::gen_types::ResponseParameters;
use anyhow::Result;

use reqwest::multipart::Form;
use serde::{Deserialize, Serialize};

pub use reqwest::multipart::Part;
static TELEGRAM_API: &str = "https://api.telegram.org";

/// Hardcoded serde_json "Response" from telegram bot api. We can't genearate this so declare it
/// here
#[derive(Serialize, Deserialize, Debug)]
pub struct Response {
    pub ok: bool,
    pub result: Option<serde_json::Value>,
    pub error_code: Option<i64>,
    pub description: Option<String>,
    pub parameters: Option<ResponseParameters>,
}

/// Default result type retruned by API calls.
pub type BotResult<T> = Result<T, ApiError>;

/// Nifty telegram bot api wrapper autogenerated from online documentation
struct BotState {
    client: reqwest::Client,
    token: String,
}

#[derive(Debug)]
enum ErrResponse {
    Response(Response),
    Err(anyhow::Error),
}

/// Error type containing either a Response type from telegram api or a generic error
#[derive(Debug)]
pub struct ApiError(ErrResponse);

impl ApiError {
    pub(crate) fn from_response(resp: Response) -> Self {
        Self(ErrResponse::Response(resp))
    }

    /// Get the telegram api response if it exists, None if this error is a
    /// non-telegram error
    pub fn get_response<'a>(&'a self) -> Option<&'a Response> {
        if let ErrResponse::Response(ref response) = self.0 {
            Some(response)
        } else {
            None
        }
    }
}

impl From<anyhow::Error> for ApiError {
    fn from(value: anyhow::Error) -> Self {
        Self(ErrResponse::Err(value))
    }
}

impl From<reqwest::Error> for ApiError {
    fn from(value: reqwest::Error) -> Self {
        Self(ErrResponse::Err(anyhow::anyhow!(value)))
    }
}

impl From<serde_json::Error> for ApiError {
    fn from(value: serde_json::Error) -> Self {
        Self(ErrResponse::Err(anyhow::anyhow!(value)))
    }
}

impl From<serde_path_to_error::Error<serde_json::Error>> for ApiError {
    fn from(value: serde_path_to_error::Error<serde_json::Error>) -> Self {
        Self(ErrResponse::Err(anyhow::anyhow!(value)))
    }
}

impl Error for ApiError {}

impl std::fmt::Display for ApiError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.0 {
            ErrResponse::Response(Response {
                description: Some(ref d),
                ..
            }) => f.write_str(&d)?,
            ErrResponse::Response(Response { error_code, .. }) => {
                f.write_str(&error_code.unwrap_or(-1).to_string())?
            }
            ErrResponse::Err(ref err) => f.write_str(&err.to_string())?,
        };
        Ok(())
    }
}

/// Type holding an active connection to telegram API
pub struct Bot(Arc<BotState>);

impl Default for Response {
    fn default() -> Self {
        Response {
            ok: true,
            result: None,
            error_code: None,
            description: None,
            parameters: None,
        }
    }
}

impl Bot {
    /// Instantiate bot using token
    pub fn new<T>(token: T) -> Result<Self>
    where
        T: Into<String>,
    {
        let client = reqwest::ClientBuilder::new().https_only(true).build()?;
        Ok(Self(Arc::new(BotState {
            client,
            token: token.into(),
        })))
    }

    /// generate an api endpoint from bot token
    fn get_endpoint(&self, endpoint: &str) -> String {
        format!("{}/bot{}/{}", TELEGRAM_API, self.0.token, endpoint)
    }

    /// HTTP post helper with x-www-form-urlencoded body
    pub async fn post<T>(&self, endpoint: &str, body: T) -> BotResult<Response>
    where
        T: Serialize,
    {
        let endpoint = self.get_endpoint(endpoint);
        let resp = self
            .0
            .client
            .post(endpoint)
            .query(&body)
            .send()
            .await
            .map_err(|e| e.without_url())?;
        let bytes = resp.bytes().await?;
        let mut deser = serde_json::Deserializer::from_slice(&bytes);
        let resp: Response = serde_path_to_error::deserialize(&mut deser)?;
        Ok(resp)
    }

    /// HTTP post helper with empty body
    pub async fn post_empty(&self, endpoint: &str) -> BotResult<Response> {
        let endpoint = self.get_endpoint(endpoint);
        let resp = self
            .0
            .client
            .post(endpoint)
            .send()
            .await
            .map_err(|e| e.without_url())?;
        let bytes = resp.bytes().await?;
        let mut deser = serde_json::Deserializer::from_slice(&bytes);
        let resp: Response = serde_path_to_error::deserialize(&mut deser)?;
        Ok(resp)
    }

    /// HTTP post helper with x-www-form-urlencode body and multipart/form-data
    pub async fn post_data<T>(&self, endpoint: &str, body: T, data: Form) -> BotResult<Response>
    where
        T: Serialize,
    {
        let endpoint = self.get_endpoint(endpoint);
        let resp = self
            .0
            .client
            .post(endpoint)
            .query(&body)
            .multipart(data)
            .send()
            .await
            .map_err(|e| e.without_url())?;
        let bytes = resp.bytes().await?;
        let mut deser = serde_json::Deserializer::from_slice(&bytes);
        let resp: Response = serde_path_to_error::deserialize(&mut deser)?;
        Ok(resp)
    }
}

impl Clone for Bot {
    fn clone(&self) -> Self {
        Self(Arc::clone(&self.0))
    }
}