1use anyhow::Error;
2use reqwest::{Client as ReqwestClient, StatusCode};
3use reqwest::ClientBuilder;
4use reqwest::header::{AUTHORIZATION, CONTENT_TYPE, HeaderMap, HeaderValue, USER_AGENT as USER_AGENT_PARAM};
5
6use crate::error::HttpError;
7use crate::USER_AGENT;
8
9pub struct Client {
10 headers: HeaderMap<HeaderValue>,
11 builder: ClientBuilder,
12}
13
14impl Client {
15 pub fn new() -> Result<Client, Error> {
16 let client = Client { headers: get_headers()?,
18 builder: reqwest::Client::builder()
19 .user_agent(USER_AGENT)
20 .referer(true),
21 };
22 Ok(client)
23 }
24
25 pub fn with_auth(mut self, token: &str) -> Result<Client, Error> {
26 self.headers
27 .insert(AUTHORIZATION, format!("Bearer {}", token).parse()?);
28 Ok(self)
29 }
30
31 pub fn build(self) -> Result<ReqwestClient, Error> {
32 Ok(self.builder.default_headers(self.headers).build()?)
33 }
34}
35
36pub fn get_headers() -> Result<HeaderMap<HeaderValue>, Error> {
37 let mut header_map = HeaderMap::new();
38 header_map.insert(USER_AGENT_PARAM, USER_AGENT.parse()?);
39 header_map.insert("Origin", "https://mail.tm".parse()?); header_map.insert("TE", "Trailers".parse()?); header_map.insert(CONTENT_TYPE, "application/json;charset=utf-8".parse()?); Ok(header_map)
43}
44
45pub async fn check_response_status(status: &StatusCode, res: &str) -> Result<(), Error> {
46 if !status.is_success() {
47 return Err(HttpError::Status(status.as_u16(), res.to_string()).into());
48 }
49 Ok(())
50}