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
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";
pub struct APIClient {
hyper_client: Client<hyper_tls::HttpsConnector<HttpConnector>>,
token: String,
}
impl APIClient {
pub fn new<T: ToString>(
hyper_client: Option<Client<hyper_tls::HttpsConnector<HttpConnector>>>,
token: &T,
) -> Self {
hyper_client.map_or_else(
|| Self {
hyper_client: hyper::Client::builder().build(hyper_tls::HttpsConnector::new()),
token: token.to_string(),
},
|c| Self {
hyper_client: c,
token: token.to_string(),
},
)
}
pub fn new_default<T: ToString>(token: &T) -> Self {
Self {
hyper_client: hyper::Client::builder().build(hyper_tls::HttpsConnector::new()),
token: token.to_string(),
}
}
fn parse_endpoint(&self, endpoint: &APIEndpoint) -> String {
format!("{}{}/{}", TELEGRAM_API, self.token, endpoint)
}
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,
}
}
pub fn get_hyper(&self) -> &Client<hyper_tls::HttpsConnector<HttpConnector>> {
&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)?)
}
}