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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
#[macro_use]
extern crate serde_derive;

use std::{io, error, fmt};
use std::io::Read;
use std::fs::File;

use futures::{Future, SinkExt};
use futures::channel::mpsc::Receiver;
use reqwest::{Client, Response};
use reqwest::multipart::{self, Form};

use serde::Deserialize;
use serde_json::Value;

use std::path::PathBuf;
use tokio::time::Duration;

use types::*;

pub mod types;
pub mod methods;


#[derive(Debug)]
pub enum BotError {
    Http(reqwest::Error),
    Json(serde_json::error::Error),
    Api {
        error_code: i64,
        description: String,
        parameters: Option<ResponseParameters>,
    },
}

impl From<serde_json::error::Error> for BotError {
    fn from(err: serde_json::error::Error) -> BotError {
        BotError::Json(err)
    }
}

impl From<reqwest::Error> for BotError {
    fn from(err: reqwest::Error) -> BotError {
        BotError::Http(err)
    }
}

impl fmt::Display for BotError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            BotError::Http(ref e) => write!(f, "{}", e),
            BotError::Json(ref e) => write!(f, "{}", e),
            BotError::Api {
                error_code,
                ref description,
                ..
            } => write!(f, "Error {0}: {1}", error_code, description),
        }
    }
}

impl error::Error for BotError {
    fn description(&self) -> &str {
        "Something unexpected occurred while talking to the telegram bot api." // meh
    }
}

pub trait TgMethod {
    type ResponseType;
    const PATH: &'static str;
    const USE_MULTIPART: bool;
}

pub trait Captures<'a> {}

impl<'a, T> Captures<'a> for T {}


#[derive(Debug, Clone)]
pub struct Bot {
    token: String,
    client: Client,
}

impl Bot {
    pub fn new(bot_token: impl Into<String>) -> Bot {
        let client = Client::builder()
            .timeout(Duration::from_secs(5 * 60 + 30))
            .connect_timeout(Duration::from_secs(60))
            .build()
            .unwrap();

        Bot {
            token: bot_token.into(),
            client: client,
        }
    }

    pub fn send<'a: 'c, 'b: 'c, 'c, R: for<'de> Deserialize<'de>, M: TgMethod<ResponseType=R> + serde::Serialize>(
        &'a self, m: &'b M,
    ) -> impl Future<Output=Result<R, BotError>> + Captures<'a> + Captures<'b> + 'c {
        async move {
            let url = format!("https://api.telegram.org/bot{}/{}", self.token, M::PATH);

            let resp: Response = if !M::USE_MULTIPART {
                self.client
                    .post(&url)
                    .json(m)
                    .send()
                    .await
                    .unwrap()
            } else {
                let json_value: Value = serde_json::to_value(m).unwrap();
                let form = value_to_form(&json_value);

                self.client
                    .post(&url)
                    .multipart(form)
                    .send()
                    .await
                    .unwrap()
            };

            let res: ApiResult<R> = resp.json().await?;
            res.into()
        }
    }

    pub fn start_polling(&self) -> Receiver<Update> {
        let (mut tx, rx) = futures::channel::mpsc::channel(100);

        let bot = self.clone();

        tokio::spawn(async move {
            let mut req = methods::GetUpdates {
                offset: Some(0),
                limit: None,
                timeout: Some(5 * 60),
                allowed_updates: None,
            };

            loop {
                let updates = bot.send(&req).await;

                for update in updates.unwrap() {
                    req.offset = Some(update.update_id + 1);
                    tx.send(update).await.unwrap();
                }
            }
        });

        rx
    }
}

pub fn value_to_form(json: &Value) -> Form {
    let mut form = Form::new();

    for (key, value) in json.as_object().unwrap() {
        form = add_value_to_form(form, key.to_string(), value);
    }

    form
}

fn add_value_to_form(mut form: Form, key: String, json_val: &Value) -> Form {
    match json_val {
        Value::Null => {
            form.text(key, "null")
        }

        Value::Bool(b) => {
            form.text(key, b.to_string())
        }

        Value::Number(n) => {
            form.text(key, n.to_string())
        }

        Value::String(s) => {
            form.text(key, s.to_string())
        }

        Value::Array(a) => {
            for (i, elem) in a.iter().enumerate() {
                let arr_key = if elem.is_object() || elem.is_array() {
                    format!("{}[{}]", key, i)
                } else {
                    format!("{}[]", key)
                };

                form = add_value_to_form(form, arr_key, elem);
            }

            form
        }

        Value::Object(o) => {
            if let Some(file_path) = o.get("_path") {
                form = add_file_to_form(form, key, file_path.as_str().unwrap()).unwrap();
            } else {
                for (k, v) in o {
                    let val_key = format!("{}[{}]", key, k);

                    if key.ends_with("_path") {
                        let file_path = v.as_str().unwrap().trim_end_matches("_path");
                        form = add_file_to_form(form, val_key, file_path).unwrap();
                    } else {
                        form = add_value_to_form(form, val_key, v);
                    }
                }
            }

            form
        }
    }
}

fn add_file_to_form(form: Form, key: String, file_path: &str) -> io::Result<Form> {
    let path = PathBuf::from(file_path);

    let mut file = File::open(file_path)?;
    let mut bytes = Vec::new();
    file.read_to_end(&mut bytes).unwrap();

    let mut part = multipart::Part::bytes(bytes);
    let filename: String = path.file_name().unwrap().to_str().unwrap().to_string();
    part = part.file_name(filename);

    Ok(form.part(key, part))
}