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
use super::{
APIConnector,
ClientBuilder,
Context,
EventHandlerFunc,
RawEventHandlerFunc,
UpdatesStream,
Webhook,
WebhookOptions,
};
use crate::{
api::{
types::{SetWebhook, UpdateType},
APIClient,
},
framework::Framework,
model::Update,
Result,
};
use futures::StreamExt;
use parking_lot::RwLock;
use std::sync::Arc;
use typemap::ShareMap;
#[derive(Clone)]
pub struct Client {
pub api_client: Arc<Box<APIConnector>>,
pub data: Arc<RwLock<ShareMap>>,
pub(super) event_handlers: Vec<EventHandlerFunc>,
pub(super) raw_event_handlers: Vec<RawEventHandlerFunc>,
pub(super) framework: Option<Arc<Framework>>,
pub(super) webhook_opts: Option<WebhookOptions>,
pub allowed_updates: Vec<UpdateType>,
}
impl Client {
pub fn new<T: ToString>(token: T) -> Self {
Self {
api_client: Arc::new(Box::new(APIClient::new(None, token))),
event_handlers: Vec::new(),
raw_event_handlers: Vec::new(),
data: Arc::new(RwLock::new(ShareMap::custom())),
framework: None,
webhook_opts: None,
allowed_updates: Vec::new(),
}
}
pub fn with_framework<T: ToString>(fr: Arc<Framework>, token: T) -> Self {
Self {
api_client: Arc::new(Box::new(APIClient::new(None, token))),
event_handlers: Vec::new(),
raw_event_handlers: Vec::new(),
data: Arc::new(RwLock::new(ShareMap::custom())),
webhook_opts: None,
framework: Some(fr),
allowed_updates: Vec::new(),
}
}
pub fn builder() -> ClientBuilder {
ClientBuilder::new()
}
pub async fn start(&self) -> Result<()> {
if let Some(opts) = &self.webhook_opts {
self.start_with_webhook(opts).await
} else {
let mut stream = UpdatesStream::new(self.api_client.clone());
stream.set_allowed_updates(self.allowed_updates.clone());
self.start_with_stream(&mut stream).await
}
}
pub async fn start_with_stream(&self, stream: &mut UpdatesStream) -> Result<()> {
if let Some(fr) = self.framework.clone() {
self.api_client
.set_my_commands(fr.get_commands().into())
.await?;
}
log::info!("starting long polling to listen for updates from telegram api");
while let Some(poll) = stream.next().await {
match poll {
Ok(update) => {
self.fire_handlers(update);
},
Err(err) => return Err(err),
}
}
Ok(())
}
pub async fn start_with_webhook(&self, opts: &WebhookOptions) -> Result<()> {
if let Some(fr) = self.framework.clone() {
self.api_client
.set_my_commands(fr.get_commands().into())
.await?;
}
if let Some(webhook_url) = &opts.url {
self.api_client
.set_webhook(SetWebhook {
url: webhook_url.to_string(),
certificate: None,
max_connections: None,
allowed_updates: Some(self.allowed_updates.clone()),
drop_pending_updates: None,
ip_address: None,
})
.await?;
}
log::info!("starting to listen on the webhook");
let mut receiver = Webhook::new(opts).start();
while let Some(u) = receiver.recv().await {
match u {
Ok(update) => {
self.fire_handlers(update);
},
Err(err) => return Err(err),
}
}
Ok(())
}
pub fn subscribe_handler_func(&mut self, handler: EventHandlerFunc) {
self.event_handlers.push(handler);
}
pub fn subscribe_raw_handler(&mut self, handler: RawEventHandlerFunc) {
self.raw_event_handlers.push(handler);
}
#[doc(hidden)]
pub fn fire_handlers(&self, update: Update) {
for h in self.raw_event_handlers.clone() {
let ctx = Context::new(self.api_client.clone(), self.data.clone());
let u = update.clone();
tokio::spawn(async move { h(ctx, u.into()).await });
}
for h in self.event_handlers.clone() {
let ctx = Context::new(self.api_client.clone(), self.data.clone());
let u = update.clone();
tokio::spawn(async move { h(ctx, u).await });
}
if self.framework.is_some() {
let ctx = Context::new(self.api_client.clone(), self.data.clone());
let fr = self.framework.clone();
fr.as_ref()
.expect("Framework needs to be set before trying to fire commands")
.fire_commands(ctx, update);
}
}
}
impl From<Box<APIConnector>> for Client {
fn from(api: Box<APIConnector>) -> Self {
Self {
api_client: Arc::new(api),
event_handlers: Vec::new(),
raw_event_handlers: Vec::new(),
data: Arc::new(RwLock::new(ShareMap::custom())),
framework: None,
webhook_opts: None,
allowed_updates: Vec::new(),
}
}
}