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
use crate::{
    methods::Method,
    request::RequestBuilder,
    types::{AllowedUpdate, Integer, Update, WebhookInfo},
};
use failure::Error;
use serde::Serialize;
use std::{collections::HashSet, time::Duration};

/// Receive incoming updates using long polling
///
/// An Array of Update objects is returned
#[derive(Clone, Debug, Default, Serialize)]
pub struct GetUpdates {
    #[serde(skip_serializing_if = "Option::is_none")]
    offset: Option<Integer>,
    #[serde(skip_serializing_if = "Option::is_none")]
    limit: Option<Integer>,
    #[serde(skip_serializing_if = "Option::is_none")]
    timeout: Option<Integer>,
    #[serde(skip_serializing_if = "Option::is_none")]
    allowed_updates: Option<HashSet<AllowedUpdate>>,
}

impl Method for GetUpdates {
    type Response = Vec<Update>;

    fn into_request(self) -> Result<RequestBuilder, Error> {
        RequestBuilder::json("getUpdates", &self)
    }
}

impl GetUpdates {
    /// Identifier of the first update to be returned
    ///
    /// Must be greater by one than the highest among the identifiers of previously received updates
    /// By default, updates starting with the earliest unconfirmed update are returned
    /// An update is considered confirmed as soon as getUpdates is called with an offset higher than its update_id
    /// The negative offset can be specified to retrieve updates starting from -offset update from the end of the updates queue
    /// All previous updates will forgotten
    pub fn offset(mut self, offset: Integer) -> Self {
        self.offset = Some(offset);
        self
    }

    /// Limits the number of updates to be retrieved
    ///
    /// Values between 1—100 are accepted
    /// Defaults to 100
    pub fn limit(mut self, limit: Integer) -> Self {
        self.limit = Some(limit);
        self
    }

    /// Timeout for long polling
    ///
    /// Defaults to 0, i.e. usual short polling
    /// Should be positive, short polling should be used for testing purposes only
    pub fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout.as_secs() as i64);
        self
    }

    /// List the types of updates you want your bot to receive
    ///
    /// For example, specify [“message”, “edited_channel_post”, “callback_query”] to only receive updates of these types
    /// Specify an empty list to receive all updates regardless of type (default)
    /// If not specified, the previous setting will be used
    /// Please note that this parameter doesn't affect updates created before the call to the getUpdates,
    /// so unwanted updates may be received for a short period of time
    pub fn allowed_updates(mut self, allowed_updates: HashSet<AllowedUpdate>) -> Self {
        self.allowed_updates = Some(allowed_updates);
        self
    }

    /// Adds a type of updates you want your bot to receive
    pub fn add_allowed_update(mut self, allowed_update: AllowedUpdate) -> Self {
        match self.allowed_updates {
            Some(ref mut updates) => {
                updates.insert(allowed_update);
            }
            None => {
                let mut updates = HashSet::new();
                updates.insert(allowed_update);
                self.allowed_updates = Some(updates);
            }
        };
        self
    }
}

/// Specify a url and receive incoming updates via an outgoing webhook
///
/// Whenever there is an update for the bot, we will send an HTTPS POST request
/// to the specified url, containing a JSON-serialized Update
/// In case of an unsuccessful request, we will give up after a reasonable amount of attempts
///
/// If you'd like to make sure that the Webhook request comes from Telegram,
/// we recommend using a secret path in the URL, e.g. https://www.example.com/<token>
/// Since nobody else knows your bot‘s token, you can be pretty sure it’s us
#[derive(Clone, Debug, Serialize)]
pub struct SetWebhook {
    url: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    certificate: Option<String>,
    #[serde(skip_serializing_if = "Option::is_none")]
    max_connections: Option<Integer>,
    #[serde(skip_serializing_if = "Option::is_none")]
    allowed_updates: Option<HashSet<AllowedUpdate>>,
}

impl SetWebhook {
    /// Creates a new SetWebhook with given url
    ///
    /// # Arguments
    ///
    /// * url - HTTPS url to send updates to
    ///         Use an empty string to remove webhook integration
    pub fn new<S: Into<String>>(url: S) -> Self {
        SetWebhook {
            url: url.into(),
            certificate: None,
            max_connections: None,
            allowed_updates: None,
        }
    }

    /// Upload your public key certificate so that the root certificate in use can be checked
    pub fn certificate<C: Into<String>>(mut self, certificate: C) -> Self {
        self.certificate = Some(certificate.into());
        self
    }

    /// Maximum allowed number of simultaneous HTTPS connections to the webhook for update delivery, 1-100
    ///
    /// Defaults to 40
    /// Use lower values to limit the load on your bot‘s server, and higher values to increase your bot’s throughput
    pub fn max_connections(mut self, max_connections: Integer) -> Self {
        self.max_connections = Some(max_connections);
        self
    }

    /// List the types of updates you want your bot to receive
    ///
    /// For example, specify [“message”, “edited_channel_post”, “callback_query”]
    /// to only receive updates of these types
    /// See Update for a complete list of available update types
    /// Specify an empty list to receive all updates regardless of type (default)
    /// If not specified, the previous setting will be used
    /// Please note that this parameter doesn't affect updates created before the call to the setWebhook,
    /// so unwanted updates may be received for a short period of time
    pub fn allowed_updates(mut self, allowed_updates: HashSet<AllowedUpdate>) -> Self {
        self.allowed_updates = Some(allowed_updates);
        self
    }

    /// Adds a type of updates you want your bot to receive
    pub fn add_allowed_update(mut self, allowed_update: AllowedUpdate) -> Self {
        match self.allowed_updates {
            Some(ref mut updates) => {
                updates.insert(allowed_update);
            }
            None => {
                let mut updates = HashSet::new();
                updates.insert(allowed_update);
                self.allowed_updates = Some(updates);
            }
        };
        self
    }
}

impl Method for SetWebhook {
    type Response = bool;

    fn into_request(self) -> Result<RequestBuilder, Error> {
        RequestBuilder::json("setWebhook", &self)
    }
}

/// Remove webhook integration if you decide to switch back to getUpdates
///
/// Returns True on success
#[derive(Clone, Copy, Debug)]
pub struct DeleteWebhook;

impl Method for DeleteWebhook {
    type Response = bool;

    fn into_request(self) -> Result<RequestBuilder, Error> {
        RequestBuilder::empty("deleteWebhook")
    }
}

/// Get current webhook status
#[derive(Clone, Copy, Debug)]
pub struct GetWebhookInfo;

impl Method for GetWebhookInfo {
    type Response = WebhookInfo;

    fn into_request(self) -> Result<RequestBuilder, Error> {
        RequestBuilder::empty("getWebhookInfo")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::request::{RequestBody, RequestMethod};
    use serde_json::Value;

    #[test]
    fn get_updates() {
        let req = GetUpdates::default().into_request().unwrap().build("host", "token");
        assert_eq!(req.method, RequestMethod::Post);
        assert_eq!(req.url, "host/bottoken/getUpdates");
        match req.body {
            RequestBody::Json(data) => {
                assert_eq!(String::from_utf8(data).unwrap(), String::from(r#"{}"#));
            }
            data => panic!("Unexpected request data: {:?}", data),
        }

        let mut updates = HashSet::new();
        updates.insert(AllowedUpdate::Message);
        updates.insert(AllowedUpdate::Message);
        updates.insert(AllowedUpdate::EditedMessage);
        updates.insert(AllowedUpdate::ChannelPost);
        updates.insert(AllowedUpdate::EditedChannelPost);
        updates.insert(AllowedUpdate::ChosenInlineResult);
        let req = GetUpdates::default()
            .offset(0)
            .limit(10)
            .timeout(Duration::from_secs(10))
            .allowed_updates(updates)
            .add_allowed_update(AllowedUpdate::InlineQuery)
            .add_allowed_update(AllowedUpdate::CallbackQuery)
            .add_allowed_update(AllowedUpdate::PreCheckoutQuery)
            .add_allowed_update(AllowedUpdate::ShippingQuery)
            .into_request()
            .unwrap()
            .build("host", "token");
        match req.body {
            RequestBody::Json(data) => {
                let data: Value = serde_json::from_slice(&data).unwrap();;
                assert_eq!(data["offset"], 0);
                assert_eq!(data["limit"], 10);
                assert_eq!(data["timeout"], 10);
                let mut updates: Vec<&str> = data["allowed_updates"]
                    .as_array()
                    .unwrap()
                    .iter()
                    .map(|x| x.as_str().unwrap())
                    .collect();
                updates.sort();
                assert_eq!(
                    updates,
                    vec![
                        "callback_query",
                        "channel_post",
                        "chosen_inline_result",
                        "edited_channel_post",
                        "edited_message",
                        "inline_query",
                        "message",
                        "pre_checkout_query",
                        "shipping_query",
                    ]
                );
            }
            data => panic!("Unexpected request data: {:?}", data),
        }

        let method = GetUpdates::default().add_allowed_update(AllowedUpdate::Message);
        assert_eq!(method.allowed_updates.unwrap().len(), 1);
    }

    #[test]
    fn set_webhook() {
        let req = SetWebhook::new("url").into_request().unwrap().build("host", "token");
        assert_eq!(req.method, RequestMethod::Post);
        assert_eq!(req.url, "host/bottoken/setWebhook");
        match req.body {
            RequestBody::Json(data) => {
                assert_eq!(String::from_utf8(data).unwrap(), r#"{"url":"url"}"#);
            }
            data => panic!("Unexpected request data: {:?}", data),
        }

        let mut updates = HashSet::new();
        updates.insert(AllowedUpdate::Message);
        updates.insert(AllowedUpdate::Message);
        updates.insert(AllowedUpdate::EditedMessage);
        updates.insert(AllowedUpdate::ChannelPost);
        updates.insert(AllowedUpdate::EditedChannelPost);
        updates.insert(AllowedUpdate::ChosenInlineResult);
        let req = SetWebhook::new("url")
            .certificate("cert")
            .max_connections(10)
            .allowed_updates(updates)
            .add_allowed_update(AllowedUpdate::InlineQuery)
            .add_allowed_update(AllowedUpdate::CallbackQuery)
            .add_allowed_update(AllowedUpdate::PreCheckoutQuery)
            .add_allowed_update(AllowedUpdate::ShippingQuery)
            .into_request()
            .unwrap()
            .build("host", "token");
        assert_eq!(req.method, RequestMethod::Post);
        assert_eq!(req.url, "host/bottoken/setWebhook");
        match req.body {
            RequestBody::Json(data) => {
                let data: Value = serde_json::from_slice(&data).unwrap();
                assert_eq!(data["certificate"], "cert");
                assert_eq!(data["max_connections"], 10);
                let mut updates: Vec<&str> = data["allowed_updates"]
                    .as_array()
                    .unwrap()
                    .iter()
                    .map(|x| x.as_str().unwrap())
                    .collect();
                updates.sort();
                assert_eq!(
                    updates,
                    vec![
                        "callback_query",
                        "channel_post",
                        "chosen_inline_result",
                        "edited_channel_post",
                        "edited_message",
                        "inline_query",
                        "message",
                        "pre_checkout_query",
                        "shipping_query",
                    ]
                );
            }
            data => panic!("Unexpected request data: {:?}", data),
        }

        let method = SetWebhook::new("url").add_allowed_update(AllowedUpdate::Message);
        assert_eq!(method.allowed_updates.unwrap().len(), 1);
    }

    #[test]
    fn delete_webhook() {
        let req = DeleteWebhook.into_request().unwrap().build("host", "token");
        assert_eq!(req.method, RequestMethod::Get);
        assert_eq!(req.url, "host/bottoken/deleteWebhook");
        match req.body {
            RequestBody::Empty => {}
            data => panic!("Unexpected request data: {:?}", data),
        }
    }

    #[test]
    fn get_webhook_info() {
        let req = GetWebhookInfo.into_request().unwrap().build("host", "token");
        assert_eq!(req.method, RequestMethod::Get);
        assert_eq!(req.url, "host/bottoken/getWebhookInfo");
        match req.body {
            RequestBody::Empty => {}
            data => panic!("Unexpected request data: {:?}", data),
        }
    }
}