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
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
use super::{api::API, endpoints::APIEndpoint, response::Response};
use crate::utils::{
    encode_multipart_form_data,
    result::Result,
    AsFormData,
    FormDataFile,
    BOUNDARY,
};
use async_trait::async_trait;
use hyper::{body::HttpBody, client::HttpConnector, Body, Client, Request};
use std::io::Write;

static TELEGRAM_API: &str = "https://api.telegram.org/bot";

#[cfg(feature = "native-tls")]
pub type TlsClient = Client<hyper_tls::HttpsConnector<HttpConnector>>;
#[cfg(all(feature = "rustls", not(feature = "native-tls")))]
pub type TlsClient = Client<hyper_rustls::HttpsConnector<HttpConnector>>;

/// A default implementation of the [`API`] trait.
///
/// It requires your bot token in order to interact with the telegram API and
/// also allows you to configure your own [`hyper::Client`] for it to use.
///
/// Using the default `APIClient` is as easy as:
/// ```no_run
/// use telexide::api::{APIClient, API, types::SendMessage};
///
/// # #[tokio::main]
/// # async fn main() {
///     # let token = "test token";
///     # let chat_id = telexide::model::IntegerOrString::Integer(3);
///     let message = SendMessage::new(chat_id, "hi!");
///
///     let client = APIClient::new_default(token);
///     client.send_message(message).await;
/// # }
/// ```
///
/// In most cases you would want to get updates though and the [`Client`] is
/// best suited for that, as it allows for easier handling of those updates
///
/// [`Client`]: ../client/struct.Client.html
pub struct APIClient {
    hyper_client: TlsClient,
    token: String,
}

impl APIClient {
    /// Creates a new `APIClient` with the provided token and hyper client (if
    /// it is Some).
    #[allow(clippy::needless_pass_by_value)]
    pub fn new(hyper_client: Option<TlsClient>, token: impl ToString) -> Self {
        hyper_client.map_or_else(
            || Self {
                hyper_client: Self::make_default_client(),
                token: token.to_string(),
            },
            |c| Self {
                hyper_client: c,
                token: token.to_string(),
            },
        )
    }

    #[cfg(feature = "native-tls")]
    fn make_default_client() -> TlsClient {
        hyper::Client::builder().build(hyper_tls::HttpsConnector::new())
    }

    #[cfg(all(feature = "rustls", not(feature = "native-tls")))]
    fn make_default_client() -> TlsClient {
        hyper::Client::builder().build(
            hyper_rustls::HttpsConnectorBuilder::new()
                .with_native_roots()
                .https_or_http()
                .enable_http1()
                .build(),
        )
    }

    /// Creates a new `APIClient` with the provided token and the default hyper
    /// client.
    #[allow(clippy::needless_pass_by_value)]
    pub fn new_default(token: impl ToString) -> Self {
        Self::new(None, token)
    }

    fn parse_endpoint(&self, endpoint: &APIEndpoint) -> String {
        format!("{}{}/{}", TELEGRAM_API, self.token, endpoint)
    }

    /// Sends a request to the provided `APIEndpoint` with the data provided
    /// (does not support files)
    pub async fn request<D>(&self, endpoint: APIEndpoint, data: Option<&D>) -> Result<Response>
    where
        D: ?Sized + serde::Serialize,
    {
        let data: Option<serde_json::Value> = if let Some(d) = data {
            Some(serde_json::to_value(d)?)
        } else {
            None
        };

        match endpoint {
            e if e.as_str().starts_with("get") => self.get(e, data).await,
            e => self.post(e, data).await,
        }
    }

    /// gets a reference to the underlying hyper client, for example so you can
    /// make custom api requests
    pub fn get_hyper(&self) -> &TlsClient {
        &self.hyper_client
    }
}

#[async_trait]
impl API for APIClient {
    async fn get(
        &self,
        endpoint: APIEndpoint,
        data: Option<serde_json::Value>,
    ) -> Result<Response> {
        let req_builder = Request::get(self.parse_endpoint(&endpoint))
            .header("content-type", "application/json")
            .header("accept", "application/json");

        let request = if let Some(d) = data {
            req_builder.body(Body::from(serde_json::to_string(&d)?))?
        } else {
            req_builder.body(Body::empty())?
        };

        log::debug!("GET request to {}", &endpoint);
        let mut response = self.hyper_client.request(request).await?;

        let mut res: Vec<u8> = Vec::new();
        while let Some(chunk) = response.body_mut().data().await {
            res.write_all(&chunk?)?;
        }

        Ok(serde_json::from_slice(&res)?)
    }

    async fn post(
        &self,
        endpoint: APIEndpoint,
        data: Option<serde_json::Value>,
    ) -> Result<Response> {
        let req_builder = Request::post(self.parse_endpoint(&endpoint))
            .header("content-type", "application/json")
            .header("accept", "application/json");

        let request = if let Some(d) = data {
            req_builder.body(Body::from(serde_json::to_string(&d)?))?
        } else {
            req_builder.body(Body::empty())?
        };

        log::debug!("POST request to {}", &endpoint);
        let mut response = self.hyper_client.request(request).await?;

        let mut res: Vec<u8> = Vec::new();
        while let Some(chunk) = response.body_mut().data().await {
            res.write_all(&chunk?)?;
        }

        Ok(serde_json::from_slice(&res)?)
    }

    async fn post_file(
        &self,
        endpoint: APIEndpoint,
        data: Option<serde_json::Value>,
        files: Option<Vec<FormDataFile>>,
    ) -> Result<Response> {
        if files.is_none() {
            return self.post(endpoint, data).await;
        }

        let mut files = files.expect("no files");
        if files.is_empty() {
            return self.post(endpoint, data).await;
        }

        let req_builder = Request::post(self.parse_endpoint(&endpoint))
            .header(
                "content-type",
                format!("multipart/form-data; boundary={BOUNDARY}"),
            )
            .header("accept", "application/json");

        if data.is_some() {
            files.append(&mut data.expect("no data").as_form_data()?);
        }

        let bytes = encode_multipart_form_data(&files)?;
        let request = req_builder.body(Body::from(bytes))?;

        log::debug!("POST request with files to {}", &endpoint);
        let mut response = self.hyper_client.request(request).await?;

        let mut res: Vec<u8> = Vec::new();
        while let Some(chunk) = response.body_mut().data().await {
            res.write_all(&chunk?)?;
        }

        Ok(serde_json::from_slice(&res)?)
    }
}