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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
//! This is the actual Bot module. For ergonomic reasons there is a RcBot which uses the real bot
//! as an underlying field. You should always use RcBot.

use crate::objects;
//use functions::FunctionGetMe;
use crate::error::{ErrorKind, TelegramError};
use crate::file::File;

use std::{str, time::{Duration, Instant}, collections::HashMap, sync::Arc};
use std::sync::atomic::{AtomicUsize, Ordering};

use tokio::timer::Interval;
use hyper::{Body as Body2, Client, Request, Uri, header::CONTENT_TYPE, client::{HttpConnector, ResponseFuture}, rt::Stream};
use hyper_tls::HttpsConnector;
use hyper_multipart::client::multipart;
use serde_json::{self, value::Value};
use futures::{stream, Future, future::IntoFuture, sync::mpsc::{self, UnboundedSender}};
use failure::{Error, Fail, ResultExt};
use hyper_multipart_rfc7578::client::multipart::Body;

#[derive(Clone)]
pub struct RequestHandle {
    key: String,
    pub inner: Arc<hyper::Client<HttpsConnector<HttpConnector>, Body2>>
}

impl RequestHandle {
    /// Creates a new request and adds a JSON message to it. The returned Future contains a the
    /// reply as a string.  This method should be used if no file is added becontext a JSON msg is
    /// always compacter than a formdata one.
    pub fn fetch_json(
        &self,
        func: &'static str,
        msg: &str,
    ) -> impl Future<Item = String, Error = Error> {
        debug!("Send JSON {}: {}", func, msg);

        let request = self.build_json(func, String::from(msg)).unwrap();

        _fetch(self.inner.request(request))
    }

    /// Builds the HTTP header for a JSON request. The JSON is already converted to a str and is
    /// appended to the POST header.
    fn build_json(
        &self,
        func: &'static str,
        msg: String,
    ) -> Result<Request<Body2>, Error> {
        let url: Result<Uri, _> =
            format!("https://api.telegram.org/bot{}/{}", self.key, func).parse();

        /*let client = Client::builder()
            .build(HttpsConnector::new(2).context(ErrorKind::HttpsInitializeError)?);*/

        let req = Request::post(url.context(ErrorKind::Uri)?)
            .header(CONTENT_TYPE, "application/json")
            .body(msg.into())
            .context(ErrorKind::Hyper)?;

        Ok(req)
    }
    ///
    /// Creates a new request with some byte content (e.g. a file). The method properties have to be
    /// in the formdata setup and cannot be sent as JSON.
    pub fn fetch_formdata(
        &self,
        func: &'static str,
        msg: &Value,
        files: Vec<File>,
        kind: &str,
    ) -> impl Future<Item = String, Error = Error> {
        debug!("Send formdata {}: {}", func, msg.to_string());

        let request = self.build_formdata(func, msg, files, kind).unwrap();

        _fetch(self.inner.request(request))
    }

    /// Builds the HTTP header for a formdata request. The file content is read and then append to
    /// the formdata. Each key-value pair has a own line.
    fn build_formdata(
        &self,
        func: &'static str,
        msg: &Value,
        files: Vec<File>,
        _kind: &str,
    ) -> Result<Request<Body2>,Error> {
        /*let client: Client<HttpsConnector<_>, multipart::Body> = Client::builder()
            .keep_alive(true)
            .build(HttpsConnector::new(4).context(ErrorKind::HttpsInitializeError)?);*/

        let url: Result<Uri, _> =
            format!("https://api.telegram.org/bot{}/{}", self.key, func).parse();

        let mut req_builder = Request::post(url.context(ErrorKind::Uri)?);
        let mut form = multipart::Form::default();

        let msg = msg.as_object().ok_or(ErrorKind::JsonNotMap)?;

        // add properties
        for (key, val) in msg.iter() {
            let val = match val {
                &Value::String(ref val) => format!("{}", val),
                etc => format!("{}", etc),
            };

            form.add_text(key, val);
        }

        for file in files {
            match file {
                File::Memory { name, source } => {
                    form.add_reader_file(name.clone(), source, name);
                }
                File::Disk { path } => {
                    form.add_file(path.clone().file_name().unwrap().to_str().unwrap(), path).context(ErrorKind::NoFile)?;
                },
                _ => {}
            }
        }

        let req = form.set_body_convert::<Body2, Body>(&mut req_builder).context(ErrorKind::Hyper)?;

        Ok(req)
    }
}
/// Calls the Telegram API for the function and awaits the result. The result is then converted
/// to a String and returned in a Future.
pub fn _fetch(fut_res: ResponseFuture) -> impl Future<Item = String, Error = Error> {
    fut_res
        .and_then(move |res| res.into_body().concat2())
        .map_err(|e| Error::from(e.context(ErrorKind::Hyper)))
        .and_then(move |response_chunks| {
            let s = str::from_utf8(&response_chunks)?;

            debug!("Got a result from telegram: {}", s);
            // try to parse the result as a JSON and find the OK field.
            // If the ok field is true, then the string in "result" will be returned
            let req = serde_json::from_str::<Value>(&s).context(ErrorKind::JsonParse)?;

            let ok = req.get("ok")
                .and_then(Value::as_bool)
                .ok_or(ErrorKind::Json)?;

            if ok {
                if let Some(result) = req.get("result") {
                    return Ok(serde_json::to_string(result).context(ErrorKind::JsonSerialize)?);
                }
            }

            let e = match req.get("description").and_then(Value::as_str) {
                Some(err) => {
                    Error::from(TelegramError::new(err.into()).context(ErrorKind::Telegram))
                }
                None => Error::from(ErrorKind::Telegram),
            };

            Err(Error::from(e.context(ErrorKind::Telegram)))
        })
}

#[derive(Clone)]
pub struct Bot {
    pub request: RequestHandle,
    key: String,
    name: Option<String>,
    update_interval: u64,
    timeout: u64,
    pub handlers: HashMap<String, UnboundedSender<(RequestHandle, objects::Message)>>,
    pub unknown_handler: Option<UnboundedSender<(RequestHandle, objects::Message)>>,
    pub callback_handler: Option<UnboundedSender<(RequestHandle, objects::CallbackQuery)>>,
    pub inline_handler: Option<UnboundedSender<(RequestHandle, objects::InlineQuery)>>
}

impl Bot {
    pub fn new(key: &str) -> Bot {
        let client = Client::builder()
                .keep_alive(true)
                .keep_alive_timeout(None)
                .build(HttpsConnector::new(4).unwrap());

        Bot {
            request: RequestHandle { inner: Arc::new(client), key: key.into() },
            key: key.into(),
            name: None,
            update_interval: 2000,
            timeout: 100,
            handlers: HashMap::new(),
            unknown_handler: None,
            callback_handler: None,
            inline_handler: None
        }
    }

    /// Sets the update interval to an integer in milliseconds
    pub fn update_interval(mut self, interval: u64) -> Bot {
        self.update_interval = interval;

        self
    }

    /// Sets the timeout interval for long polling
    pub fn timeout(mut self, timeout: u64) -> Bot {
        self.timeout = timeout;

        self
    }

    /// Creates a new command and returns a stream which will yield a message when the command is send
    pub fn new_cmd(
        &mut self,
        cmd: &str,
    ) -> impl Stream<Item = (RequestHandle, objects::Message), Error = Error> {
        let (sender, receiver) = mpsc::unbounded();

        let cmd = if cmd.starts_with("/") {
            cmd.into()
        } else {
            format!("/{}", cmd)
        };

        self.handlers.insert(cmd.into(), sender);

        receiver.map_err(|_| Error::from(ErrorKind::Channel))
    }

    /// Returns a stream which will yield a message when none of previously registered commands matches
    pub fn unknown_cmd(&mut self) -> impl Stream<Item = (RequestHandle, objects::Message), Error = Error> {
        let (sender, receiver) = mpsc::unbounded();

        self.unknown_handler = Some(sender);

        receiver.then(|x| x.map_err(|_| Error::from(ErrorKind::Channel)))
    }

    /// Returns a stream which will yield a received CallbackQuery
    pub fn callback(&mut self) -> impl Stream<Item = (RequestHandle, objects::CallbackQuery), Error = Error> {
        let (sender, receiver) = mpsc::unbounded();

        self.callback_handler = Some(sender);

        receiver.then(|x| x.map_err(|_| Error::from(ErrorKind::Channel)))
    }

    /// Returns a stream which will yield a received CallbackQuery
    pub fn inline(&mut self) -> impl Stream<Item = (RequestHandle, objects::InlineQuery), Error = Error> {
        let (sender, receiver) = mpsc::unbounded();

        self.inline_handler = Some(sender);

        receiver.then(|x| x.map_err(|_| Error::from(ErrorKind::Channel)))
    }

    pub fn resolve_name(&self) -> impl Future<Item = Option<String>, Error = Error> {
        use crate::functions::FunctionGetMe;

        // create a new task which resolves the bot name and then set it in the struct
        let resolve_name = self.request.get_me().send()
            .map(move |user| {
                if let Some(name) = user.1.username {
                    return Some(format!("@{}", name));
                } else {
                    return None;
                }
            });

        resolve_name
    }

    pub fn process_updates(self, last_id: Arc<AtomicUsize>) -> impl Stream<Item = (RequestHandle, objects::Update), Error = Error> {
        use crate::functions::FunctionGetUpdates;

        self.request.get_updates()
            .offset(last_id.load(Ordering::Relaxed) as i64)
            .timeout(self.timeout as i64)
            .send()
            .into_stream()
            .map(|(_, x)| {
                stream::iter_result(
                    x.0
                        .into_iter()
                        .map(|x| Ok(x))
                        .collect::<Vec<Result<objects::Update, Error>>>(),
                )
            })
            .flatten()
            .and_then(move |x| {
                if last_id.load(Ordering::Relaxed) < x.update_id as usize + 1 {
                    last_id.store(x.update_id as usize + 1, Ordering::Relaxed);
                }

                Ok(x)
            })
        .filter_map(move |mut val| {
            debug!("Got an update from Telegram: {:?}", val);
    
            if let Some(_) = val.callback_query {
                if let Some(sender) = self.callback_handler.clone() {
                    sender
                        .unbounded_send((self.request.clone(), val.callback_query.unwrap()))
                        .unwrap_or_else(|e| error!("Error: {}", e));
                    return None;
                }
            }
    
            if let Some(_) = val.inline_query {
                if let Some(sender) = self.inline_handler.clone() {
                    sender
                        .unbounded_send((self.request.clone(), val.inline_query.unwrap()))
                        .unwrap_or_else(|e| error!("Error: {}", e));
                    return None;
                }
            }

            let mut sndr: Option<UnboundedSender<(RequestHandle, objects::Message)>> = None;
    
            if let Some(ref mut message) = val.message {
                if let Some(text) = message.text.clone() {
                    let mut content = text.split_whitespace();
                    if let Some(mut cmd) = content.next() {
                        if cmd.starts_with("/") {
                            if let Some(name) = self.name.as_ref() {
                                if cmd.ends_with(name.as_str()) {
                                    cmd = cmd.rsplitn(2, '@').skip(1).next().unwrap();
                                }
                            }
                            if let Some(sender) = self.handlers.get(cmd)
                            {
                                sndr = Some(sender.clone());
                                message.text = Some(content.collect::<Vec<&str>>().join(" "));
                            } else if let Some(ref sender) =
                                self.unknown_handler
                            {
                                sndr = Some(sender.clone());
                            }
                        }
                    }
                }
            }
    
            if let Some(sender) = sndr {
                sender
                    .unbounded_send((self.request.clone(), val.message.unwrap()))
                    .unwrap_or_else(|e| error!("Error: {}", e));
                return None;
            } else {
                return Some((self.request.clone(), val));
            }
        })
    }

    ///
    /// The main update loop, the update function is called every update_interval milliseconds
    /// When an update is available the last_id will be updated and the message is filtered
    /// for commands
    /// The message is forwarded to the returned stream if no command was found
    pub fn get_stream(
        mut self,
        name: Option<String>
    ) -> impl Stream<Item = (RequestHandle, objects::Update), Error = Error> { 
        self.name = name;
        let last_id = Arc::new(AtomicUsize::new(0));

        let duration = Duration::from_millis(self.update_interval);
        Interval::new(Instant::now(), duration)
            .map_err(|x| Error::from(x.context(ErrorKind::IntervalTimer)))
            .map(move |_| self.clone().process_updates(last_id.clone()))
            .flatten()
    }

    pub fn into_future(&self) -> impl Future<Item = (), Error = Error> {
        let bot = self.clone();

        self.resolve_name()
            .and_then(|name| bot.get_stream(name).for_each(|_| Ok(())))
            .map(|_| ())
    }

    pub fn run_with<I>(self, other: I) 
    where
        I: IntoFuture<Error = Error>,
        <I as IntoFuture>::Future: Send + 'static,
        <I as IntoFuture>::Item: Send
    {
        tokio::run(
            self.into_future().join(other)
            .map(|_| ())
            .map_err(|e| {
                eprintln!("Error: could not resolve the bot name!");

                for (i, cause) in e.iter_causes().enumerate() {
                    println!(" => {}: {}", i, cause);
                }
            })
        );
    }

    pub fn run(self) {
        self.run_with(Ok(()));
    }
}