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
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
//! This module contains functionality for extracting data to the handler arguments.
//!
//! [`Extractor`] is the main trait which need to be implemented for extracting data.
//! If you want to use your own types as handler arguments, you need to implement this trait for them.
//! By default, this trait is implemented for the most common middlewares, types and filters, so you can use them without any additional actions.
//! The trait also is implemented for `Option<T>`, `Result<T, E>` where `T: Extractor`,
//! so you can don't implement it for your types if you want to use them as optional or result arguments.
//!
//! # Using extensions
//!
//! You can use [`Extension`] to extract data from [`Extensions`] that can be easily filled in,
//! for example in middlewares:
//! ```rust
//! use telers::{
//! errors::EventErrorKind,
//! event::{telegram::HandlerResult, EventReturn},
//! middlewares::outer::{Middleware, MiddlewareResponse},
//! Extension, Request,
//! };
//!
//! #[derive(Clone)]
//! struct ToExtensionsMiddleware<T> {
//! data: T,
//! }
//!
//! impl<T> Middleware for ToExtensionsMiddleware<T>
//! where
//! T: Send + Sync + Clone + 'static,
//! {
//! async fn call(
//! &mut self,
//! mut request: Request,
//! ) -> Result<MiddlewareResponse, EventErrorKind> {
//! request.extensions.insert(self.data.clone());
//!
//! Ok((request, EventReturn::default()))
//! }
//! }
//!
//! async fn send_data_handler<T>(Extension(data2): Extension<T>) -> HandlerResult {
//! todo!();
//! }
//! ```
//!
//! You can check examples of usage extensions in the [`examples`] directory.
//!
//! # Implementing trait
//!
//! Ways to implement [`Extractor`] for your own types:
//! * Implement it directly (much boilerplate code, but it's needed for complex types)
//! * Use the [`FromContext`] macro (simple way to implement this for types in a [`Context`] by its key)
//! * Use the [`FromEvent`] macro (simple way to implement this for types in an event, for example, [`crate::types::Update`])
//!
//! ## Implementing directly
//!
//! Simple example with extracting id from [`crate::types::Update`]:
//!
//! ```rust
//! use std::convert::Infallible;
//! use telers::{Extractor, Request};
//!
//! struct UpdateId(i64);
//!
//! impl Extractor for UpdateId {
//! type Error = Infallible;
//!
//! async fn extract(request: &Request) -> Result<Self, Self::Error> {
//! Ok(UpdateId(request.update.update_id()))
//! }
//! }
//! ```
//!
//! This example will extract the [`crate::types::Update`] id to the handler argument.
//! After that, you can use this argument in the handler:
//!
//! ```ignore
//! async fn handler(update_id: UpdateId) {
//! println!("Update id: {}", id.0);
//! }
//! ```
//!
//! Another example with extracting id of the user who sent the message from [`crate::types::Update`]:
//!
//! ```rust
//! use telers::{errors::ConvertToTypeError, Extractor, Request};
//!
//! struct UpdateFromId(i64);
//!
//! impl Extractor for UpdateFromId {
//! type Error = ConvertToTypeError;
//!
//! // you can use your own error type, this is just an example
//!
//! async fn extract(request: &Request) -> Result<Self, Self::Error> {
//! match request.update.from() {
//! Some(from) => Ok(UpdateFromId(from.id)),
//! None => Err(ConvertToTypeError::new("Update", "UpdateFromId")),
//! }
//! }
//! }
//! ```
//!
//! In some cases we sure that some data is not none, so in one handler we can use `Option` and in another handler we can use the type directly.
//! After we implemented [`Extractor`] for our type, we can use it in both cases,
//! because the trait is implemented for `Option<T>` and `Result<T, E>` where `T: Extractor`:
//!
//! ```rust
//! use telers::{errors::ConvertToTypeError, Extractor, Request};
//!
//! struct UpdateFromId(i64);
//!
//! impl Extractor for UpdateFromId {
//! type Error = ConvertToTypeError;
//!
//! // you can use your own error type, this is just an example
//!
//! async fn extract(request: &Request) -> Result<Self, Self::Error> {
//! match request.update.from() {
//! Some(from) => Ok(UpdateFromId(from.id)),
//! None => Err(ConvertToTypeError::new("Update", "UpdateFromId")),
//! }
//! }
//! }
//! ```
//!
//! After that, you can use this argument in the handlers:
//!
//! ```ignore
//! // Here `from_id` can't be `None` (for example we use filter which checks that `from_id` is not `None`)
//! async fn handler_first(from_id: UpdateFromId) {
//! println!("Update from id: {}", from_id.0);
//! }
//!
//! // Here `from_id` can be `None`
//! async fn handler_second(from_id: Option<UpdateFromId>) {
//! if let Some(from_id) = from_id {
//! println!("Update from id: {}", from_id.0);
//! }
//! }
//! ```
//!
//! ## Implementing with [`FromEvent`] macro
//!
//! Simple example with extracting id from [`crate::types::Update`]:
//!
//! ```rust
//! use telers::{types::Update, FromEvent};
//!
//! #[derive(FromEvent)]
//! #[event(from = Update)]
//! struct UpdateId(i64);
//!
//! // We need to implement `From<Update>` for `UpdateId` by ourselves (this is required by `FromEvent` macro)
//! impl From<Update> for UpdateId {
//! fn from(update: Update) -> Self {
//! Self(update.update_id())
//! }
//! }
//! ```
//!
//! Here we used `#[event(from = Update)]` attribute to specify the type from which the type will be converted.
//!
//! We also can use `#[event(try_from = "...")]`, but in this case we need to implement [`TryFrom`] for our type instead of [`From`]:
//!
//! ```rust
//! use telers::{types::Update, FromEvent, errors::ConvertToTypeError};
//!
//! #[derive(FromEvent)]
//! #[event(try_from = Update)] // you can specify [`ConvertToTypeError`] as error type, but it's not necessary, because it's default
//! struct UpdateFromId(i64);
//!
//! impl TryFrom<Update> for UpdateFromId {
//! type Error = ConvertToTypeError;
//!
//! fn try_from(update: Update) -> Result<Self, Self::Error> {
//! match update.from() {
//! Some(from) => Ok(Self(from.id)),
//! None => Err(ConvertToTypeError::new("Update", "UpdateFromId")),
//! }
//! }
//! }
//! ```
//!
//! By default, the error type is [`ConvertToTypeError`](telers::errors::ConvertToTypeError),
//! but you can specify your own error type with `#[event(error = "...")]` attribute:
//!
//! ```rust
//! use std::convert::Infallible;
//! use telers::{types::Update, FromEvent};
//!
//! #[derive(FromEvent)]
//! #[event(try_from = Update, error = Infallible)]
//! struct UpdateId(i64);
//!
//! impl TryFrom<Update> for UpdateId {
//! // we use `TryFrom` here just for example, you need to use `From` if error is impossible
//! type Error = Infallible;
//!
//! fn try_from(update: Update) -> Result<Self, Self::Error> {
//! Ok(Self(update.update_id()))
//! }
//! }
//! ```
//!
//! ## Implementing with [`FromContext`] macro
//!
//! Simple example with extracting struct by key from [`Context`]:
//!
//! ```rust
//! use telers_macros::FromContext;
//!
//! #[derive(Clone, FromContext)]
//! #[context(key = "my_struct")]
//! struct MyStruct {
//! field: i32,
//! }
//! ```
//!
//! Now we can use `MyStruct` as handler argument if we put it in the context with key `my_struct`.
//! There is a serious problem here: we don't know where struct by key `my_struct` is set to the context
//! and if context doesn't contain type by key `my_struct` we need to know where the source of the problem is.
//! We can use `#[content(description = "...")]` to describe where the structure is installed, or cases where it is not installed, for example:
//!
//! ```rust
//! use telers_macros::FromContext;
//!
//! #[derive(Clone, FromContext)]
//! #[context(
//! key = "my_struct",
//! description = "This struct is set in the `MyMiddleware` middleware. If it is not set, \
//! then the `MyMiddleware` middleware is not used."
//! )]
//! struct MyStruct {
//! field: i32,
//! }
//! ```
//!
//! In some cases, you may want to use a one type in context, but extract it as another type.
//! For this case, you can use `#[context(into = "...")]` attribute:
//!
//! ```rust
//! use telers_macros::FromContext;
//!
//! #[derive(Clone, FromContext)]
//! #[context(key = "my_struct", into = MyStructWrapper)]
//! struct MyStruct {
//! field: i32,
//! }
//!
//! struct MyStructWrapper(MyStruct);
//!
//! impl From<MyStruct> for MyStructWrapper {
//! fn from(my_struct: MyStruct) -> Self {
//! Self(my_struct)
//! }
//! }
//! ```
//!
//! This code will extract `MyStruct` from context and convert it to `MyStructWrapper`,
//! but we need to implement `From<MyStruct>` for `MyStructWrapper` by ourselves (this is required by [`FromContext`] macro).
//! In this case, the trait is implements for `MyStructWrapper`, not for `MyStruct`,
//! so we can't use `MyStruct` as handler argument without implementing `Extractor` for it.
//!
//! We also can use `#[context(from = "...")]` attribute to specify the type from which the type will be converted:
//!
//! ```rust
//! use telers_macros::FromContext;
//!
//! #[derive(Clone)]
//! struct MyStruct {
//! field: i32,
//! }
//!
//! #[derive(FromContext)]
//! #[context(key = "my_struct", from = MyStruct)]
//! struct MyStructWrapper(MyStruct);
//!
//! impl From<MyStruct> for MyStructWrapper {
//! fn from(my_struct: MyStruct) -> Self {
//! Self(my_struct)
//! }
//! }
//! ```
//!
//! This code similar to the previous one, but more useful in cases when `from` type is a foreign type.
//!
//! [`FromEvent`]: telers::FromEvent
//! [`FromContext`]: telers::FromContext
//! [`Extensions`]: telers::extensions::Extensions
//! [`examples`]: https://github.com/Desiders/telers/tree/dev-1.x/examples
use crate::;
use ;
/// Trait for extracting data from [`crate::types::Update`] and [`Context`] to handlers arguments
/// To be able to use [`Option`] as handler argument
/// This implementation will return `None` if extraction was unsuccessful, and `Some(value)` otherwise
/// To be able to use [`Result`] as handler argument
/// This implementation will return `Ok(value)` if extraction was successful, and `Err(error)` otherwise,
/// where `error` is `T::Error` converted to `E`
/// To be able to use handler without arguments
/// Handler without arguments will be called with `()` argument (unit type)