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
use crate::types::TelegramResponse; use actix::{Actor, Context}; use actix_web::{client, HttpMessage}; use futures::Future; use multipart_rfc7578::{Form, SetBody}; use serde::{de::DeserializeOwned, Serialize}; use std::fmt::Debug; use std::time::Duration; pub struct TelegramApi { pub(crate) token: String, pub(crate) timeout: Duration, } impl TelegramApi { pub fn new(token: String, timeout: u16) -> Self { let timeout = Duration::from_secs(u64::from(timeout)); Self { token, timeout } } pub fn send_request<T, R>( token: &str, method: &str, timeout: Duration, item: &T, ) -> Box<Future<Item = R, Error = ()>> where R: DeserializeOwned + Debug + 'static, T: Serialize, { let url = format!("https://api.telegram.org/bot{}/{}", token, method); let future = client::post(url) .timeout(timeout) .json(item) .unwrap() .send() .map_err(|e| error!("request error {:?}", e)) .and_then(|response| { response .json() .then(|response: Result<TelegramResponse<R>, _>| match response { Ok(response) => { debug!("response {:?}", response); if response.ok { Ok(response.result.unwrap()) } else { error!("telegram error {:?}", response.description); Err(()) } } Err(e) => { error!("parsing json error {:?}", e); Err(()) } }) }); Box::new(future) } pub fn send_multipart_request<R>( token: &str, method: &str, timeout: Duration, item: Form, ) -> Box<Future<Item = R, Error = ()>> where R: DeserializeOwned + Debug + 'static, { let url = format!("https://api.telegram.org/bot{}/{}", token, method); let mut request = client::post(url); let future = item .set_body(request.timeout(timeout)) .unwrap() .send() .map_err(|e| error!("request error {:?}", e)) .and_then(|response| { response .json() .then(|response: Result<TelegramResponse<R>, _>| match response { Ok(response) => { debug!("response {:?}", response); if response.ok { Ok(response.result.unwrap()) } else { error!("telegram error {:?}", response.description); Err(()) } } Err(e) => { error!("parsing json error {:?}", e); Err(()) } }) }); Box::new(future) } } impl Actor for TelegramApi { type Context = Context<Self>; fn started(&mut self, _ctx: &mut Context<Self>) { debug!("TelegramApi is alive"); } fn stopped(&mut self, _ctx: &mut Context<Self>) { debug!("TelegramApi is stopped"); } }