1use telbot_types::update::{GetUpdates, Update};
2
3use crate::{Api, Result};
4
5pub struct Polling<'a> {
6 api: &'a Api,
7 offset: u32,
8 timeout: u32,
9 queue: Vec<Update>,
10}
11
12impl<'a> Polling<'a> {
13 pub fn new(api: &'a Api) -> Self {
15 const DEFAULT_TIMEOUT: u32 = 1;
16
17 Self {
18 api,
19 offset: 0,
20 timeout: DEFAULT_TIMEOUT,
21 queue: vec![],
22 }
23 }
24}
25
26impl Iterator for Polling<'_> {
27 type Item = Result<Update>;
28
29 fn next(&mut self) -> Option<Self::Item> {
30 while self.queue.is_empty() {
31 let updates = self.api.send_json(
32 &GetUpdates::new()
33 .with_offset(self.offset as i32)
34 .with_timeout(self.timeout),
35 );
36 match updates {
37 Ok(update) => {
38 self.queue = update;
39 self.offset = self
40 .queue
41 .iter()
42 .map(|update| update.update_id + 1)
43 .fold(self.offset, std::cmp::max);
44 }
45 Err(e) => return Some(Result::Err(e)),
46 }
47 }
48 self.queue.pop().map(Result::Ok)
49 }
50}