grammers-client 0.9.0

A high level client to interact with Telegram's API.
Documentation
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
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
// Copyright 2020 - developers of the `grammers` project.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

use std::fmt::Debug;

use chrono::{DateTime, Utc};
use grammers_tl_types as tl;

use super::{Downloadable, PhotoSize};

/// Photo media contained within a message.
#[derive(Clone, Debug, PartialEq)]
pub struct Photo {
    pub raw: tl::types::MessageMediaPhoto,
}

/// File documents unlike the alternative of compressed photos.
///
/// This includes uncompressed photos, videos, stickers, and files of any type.
#[derive(Clone, Debug, PartialEq)]
pub struct Document {
    pub raw: tl::types::MessageMediaDocument,
}

/// A sticker [`Document`].
#[derive(Clone, Debug, PartialEq)]
pub struct Sticker {
    pub document: Document,
    pub raw_attrs: tl::types::DocumentAttributeSticker,
    animated: bool,
}

/// Data uploaded by the client to be used as either a [`Photo`] or [`Document`].
#[derive(Clone, Debug, PartialEq)]
pub struct Uploaded {
    pub raw: tl::enums::InputFile,
}

/// Contact media containing a phone number.
#[derive(Clone, Debug, PartialEq)]
pub struct Contact {
    pub raw: tl::types::MessageMediaContact,
}

/// Poll or quiz which may be voted on while open.
#[derive(Clone, Debug, PartialEq)]
pub struct Poll {
    pub raw: tl::types::Poll,
    pub raw_results: tl::types::PollResults,
}

/// Geo point with latitude and longitude coordinates on the globe.
#[derive(Clone, Debug, PartialEq)]
pub struct Geo {
    pub raw: tl::types::GeoPoint,
}

/// Animated built-in sticker with a set of possible outcomes.
///
/// Originally used to roll dice (🎲), but other emoji such as darts (🎯),
/// basket-balls (🏀) and slot-machines (🎰) can also be used.
#[derive(Clone, Debug, PartialEq)]
pub struct Dice {
    pub raw: tl::types::MessageMediaDice,
}

/// A place with optional coordinates.
#[derive(Clone, Debug, PartialEq)]
pub struct Venue {
    pub geo: Option<Geo>,
    pub raw_venue: tl::types::MessageMediaVenue,
}

/// Like [`Geo`], but periodcally edits itself with updated information.
#[derive(Clone, Debug, PartialEq)]
pub struct GeoLive {
    pub geo: Option<Geo>,
    pub raw_geolive: tl::types::MessageMediaGeoLive,
}

/// Instant View web-page previews.
#[derive(Clone, Debug, PartialEq)]
pub struct WebPage {
    pub raw: tl::types::MessageMediaWebPage,
}

/// Profile picture of a group.
#[derive(Clone, Debug, PartialEq)]
pub struct ChatPhoto {
    pub raw: tl::enums::InputFileLocation,
}

/// Message media (e.g. photos, polls, videos).
#[derive(Clone, Debug, PartialEq)]
#[non_exhaustive]
pub enum Media {
    /// Compressed JPEG photo.
    Photo(Photo),
    /// File which may or not be rendered directly by clients.
    Document(Document),
    /// Document that has the attributes of a sticker.
    Sticker(Sticker),
    /// Contact information.
    Contact(Contact),
    /// Poll which can be voted on while open.
    Poll(Poll),
    /// Coordinates of a place.
    Geo(Geo),
    /// Dice-like built-in sticker media.
    Dice(Dice),
    /// Information about a place with optional coordinates.
    Venue(Venue),
    /// Self-updating coordinates of a place or person.
    GeoLive(GeoLive),
    /// Web-page instant view.
    WebPage(WebPage),
}

impl Photo {
    pub fn from_raw(photo: tl::enums::Photo) -> Self {
        Self {
            raw: tl::types::MessageMediaPhoto {
                spoiler: false,
                photo: Some(photo),
                ttl_seconds: None,
            },
        }
    }

    pub fn from_raw_media(photo: tl::types::MessageMediaPhoto) -> Self {
        Self { raw: photo }
    }

    pub fn to_raw_input_media(&self) -> tl::types::InputMediaPhoto {
        use tl::{
            enums::{InputPhoto as eInputPhoto, Photo},
            types::InputPhoto,
        };

        tl::types::InputMediaPhoto {
            spoiler: false,
            id: match self.raw.photo {
                Some(Photo::Photo(ref photo)) => InputPhoto {
                    id: photo.id,
                    access_hash: photo.access_hash,
                    file_reference: photo.file_reference.clone(),
                }
                .into(),
                _ => eInputPhoto::Empty,
            },
            ttl_seconds: self.raw.ttl_seconds,
        }
    }

    /// The globally unique identifier for this media, as seen by any account.
    pub fn id(&self) -> i64 {
        use tl::enums::Photo as P;

        match self.raw.photo.as_ref().unwrap() {
            P::Empty(photo) => photo.id,
            P::Photo(photo) => photo.id,
        }
    }

    /// The size of the photo, if not empty.
    pub fn size(&self) -> Option<usize> {
        self.thumbs()
            .iter()
            .max_by_key(|x| x.size())
            .map(|thumb| thumb.size())
    }

    /// Get photo thumbs.
    ///
    /// Since Telegram doesn't store the original photo, it can be presented in different sizes
    /// and quality, a.k.a. thumbnails. Each photo preview has a specific type, indicating
    /// the resolution and image transform that was applied server-side. Some low-resolution
    /// thumbnails already contain all necessary information that can be shown to the user, but
    /// for other types an additional request to the Telegram should be performed.
    /// Check the description of [`PhotoSize``] to get an information about each particular thumbnail.
    ///
    /// <https://core.telegram.org/api/files#image-thumbnail-types>
    pub fn thumbs(&self) -> Vec<PhotoSize> {
        use tl::enums::Photo as P;

        let photo = match self.raw.photo.as_ref() {
            Some(photo) => photo,
            None => return vec![],
        };

        match photo {
            P::Empty(_) => vec![],
            P::Photo(photo) => photo
                .sizes
                .iter()
                .map(|x| PhotoSize::make_from(x, photo))
                .collect(),
        }
    }

    /// Returns true if the photo is a spoiler.
    pub fn is_spoiler(&self) -> bool {
        self.raw.spoiler
    }

    /// Returns TTL seconds if the photo is self-destructive, None otherwise
    pub fn ttl_seconds(&self) -> Option<i32> {
        self.raw.ttl_seconds
    }
}

impl Downloadable for Photo {
    fn to_raw_input_location(&self) -> Option<tl::enums::InputFileLocation> {
        use tl::enums::Photo as P;

        self.raw.photo.as_ref().and_then(|p| match p {
            P::Empty(_) => None,
            P::Photo(photo) => Some(
                tl::types::InputPhotoFileLocation {
                    id: photo.id,
                    access_hash: photo.access_hash,
                    file_reference: photo.file_reference.clone(),
                    thumb_size: self
                        .thumbs()
                        .iter()
                        .max_by_key(|x| x.size())
                        .map(|ps| ps.photo_type())
                        .unwrap_or(String::from("w")),
                }
                .into(),
            ),
        })
    }
}

impl Document {
    pub fn from_raw_media(document: tl::types::MessageMediaDocument) -> Self {
        Self { raw: document }
    }

    pub fn to_raw_input_media(&self) -> tl::types::InputMediaDocument {
        use tl::{
            enums::{Document, InputDocument as eInputDocument},
            types::InputDocument,
        };

        tl::types::InputMediaDocument {
            spoiler: false,
            id: match self.raw.document {
                Some(Document::Document(ref document)) => InputDocument {
                    id: document.id,
                    access_hash: document.access_hash,
                    file_reference: document.file_reference.clone(),
                }
                .into(),
                _ => eInputDocument::Empty,
            },
            ttl_seconds: self.raw.ttl_seconds,
            query: None,
            video_cover: None,
            video_timestamp: None,
        }
    }

    /// The globally unique identifier for this media, as seen by any account.
    pub fn id(&self) -> i64 {
        use tl::enums::Document as D;

        match self.raw.document.as_ref().unwrap() {
            D::Empty(document) => document.id,
            D::Document(document) => document.id,
        }
    }

    /// Return the file's name.
    ///
    /// If the file was uploaded with no file name, the returned string will be empty.
    ///
    /// Note that the file name is not necessarily valid as seen by the OS,
    /// and using it directly as the download location is subject to causing
    /// path trasversal attacks.
    pub fn name(&self) -> Option<&str> {
        use tl::enums::Document as D;

        match self.raw.document.as_ref().unwrap() {
            D::Empty(_) => None,
            D::Document(document) => document.attributes.iter().find_map(|attr| match attr {
                tl::enums::DocumentAttribute::Filename(attr) => Some(attr.file_name.as_ref()),
                _ => None,
            }),
        }
    }

    /// Get the file's MIME type, if any.
    pub fn mime_type(&self) -> Option<&str> {
        match self.raw.document.as_ref() {
            Some(tl::enums::Document::Document(d)) => Some(d.mime_type.as_str()),
            _ => None,
        }
    }

    /// The date on which the file was created, if any.
    pub fn creation_date(&self) -> Option<DateTime<Utc>> {
        match self.raw.document.as_ref() {
            Some(tl::enums::Document::Document(d)) => {
                Some(DateTime::<Utc>::from_timestamp(d.date as i64, 0).expect("date out of range"))
            }
            _ => None,
        }
    }

    /// The size of the file.
    pub fn size(&self) -> Option<usize> {
        match self.raw.document.as_ref() {
            Some(tl::enums::Document::Document(d)) => Some(d.size as usize),
            _ => None,
        }
    }

    /// Get document thumbs.
    /// See <https://core.telegram.org/api/files#image-thumbnail-types>.
    pub fn thumbs(&self) -> Vec<PhotoSize> {
        use tl::enums::Document as D;

        let document = match self.raw.document.as_ref() {
            Some(document) => document,
            None => return vec![],
        };

        match document {
            D::Empty(_) => vec![],
            D::Document(document) => match &document.thumbs {
                Some(thumbs) => thumbs
                    .iter()
                    .map(|x| PhotoSize::make_from_document(x, document))
                    .collect(),
                None => vec![],
            },
        }
    }

    /// Duration of video/audio, in seconds.
    pub fn duration(&self) -> Option<f64> {
        match self.raw.document.as_ref() {
            Some(tl::enums::Document::Document(d)) => {
                for attr in &d.attributes {
                    match attr {
                        tl::enums::DocumentAttribute::Video(v) => return Some(v.duration),
                        tl::enums::DocumentAttribute::Audio(a) => return Some(a.duration as _),
                        _ => {}
                    }
                }
                None
            }
            _ => None,
        }
    }

    /// Width & height of video/image, in pixels.
    pub fn resolution(&self) -> Option<(i32, i32)> {
        match self.raw.document.as_ref() {
            Some(tl::enums::Document::Document(d)) => {
                for attr in &d.attributes {
                    match attr {
                        tl::enums::DocumentAttribute::Video(v) => return Some((v.w, v.h)),
                        tl::enums::DocumentAttribute::ImageSize(i) => return Some((i.w, i.h)),
                        _ => {}
                    }
                }
                None
            }
            _ => None,
        }
    }

    /// Title of audio.
    pub fn audio_title(&self) -> Option<&str> {
        match self.raw.document.as_ref() {
            Some(tl::enums::Document::Document(d)) => {
                for attr in &d.attributes {
                    #[allow(clippy::single_match)]
                    match attr {
                        tl::enums::DocumentAttribute::Audio(a) => return a.title.as_deref(),
                        _ => {}
                    }
                }
                None
            }
            _ => None,
        }
    }

    /// Performer (artist) of audio.
    pub fn performer(&self) -> Option<&str> {
        match self.raw.document.as_ref() {
            Some(tl::enums::Document::Document(d)) => {
                for attr in &d.attributes {
                    #[allow(clippy::single_match)]
                    match attr {
                        tl::enums::DocumentAttribute::Audio(a) => return a.performer.as_deref(),
                        _ => {}
                    }
                }
                None
            }
            _ => None,
        }
    }

    /// Returns `true` if the document is an animated sticker.
    pub fn is_animated(&self) -> bool {
        match self.raw.document.as_ref() {
            Some(tl::enums::Document::Document(d)) => {
                for attr in &d.attributes {
                    #[allow(clippy::single_match)]
                    match attr {
                        tl::enums::DocumentAttribute::Animated => return true,
                        _ => {}
                    }
                }
                false
            }
            _ => false,
        }
    }

    /// Returns `true` if the document is a spoiler.
    pub fn is_spoiler(&self) -> bool {
        self.raw.spoiler
    }
}

impl Downloadable for Document {
    fn to_raw_input_location(&self) -> Option<tl::enums::InputFileLocation> {
        use tl::enums::Document as D;

        self.raw.document.as_ref().and_then(|p| match p {
            D::Empty(_) => None,
            D::Document(document) => Some(
                tl::types::InputDocumentFileLocation {
                    id: document.id,
                    access_hash: document.access_hash,
                    file_reference: document.file_reference.clone(),
                    thumb_size: String::new(),
                }
                .into(),
            ),
        })
    }

    fn size(&self) -> Option<usize> {
        self.size()
    }
}

impl Sticker {
    pub fn from_document(document: &Document) -> Option<Self> {
        match document.raw.document {
            Some(tl::enums::Document::Document(ref doc)) => {
                let mut animated = false;
                let mut sticker_attrs: Option<tl::types::DocumentAttributeSticker> = None;
                for attr in &doc.attributes {
                    match attr {
                        tl::enums::DocumentAttribute::Sticker(s) => sticker_attrs = Some(s.clone()),
                        tl::enums::DocumentAttribute::Animated => animated = true,
                        _ => (),
                    }
                }
                Some(Self {
                    document: document.clone(),
                    raw_attrs: sticker_attrs?,
                    animated,
                })
            }
            _ => None,
        }
    }

    /// Get the emoji associated with the sticker.
    pub fn emoji(&self) -> &str {
        self.raw_attrs.alt.as_str()
    }

    /// Is this sticker an animated sticker?
    pub fn is_animated(&self) -> bool {
        self.animated
    }
}

impl Contact {
    pub fn from_raw_media(contact: tl::types::MessageMediaContact) -> Self {
        Self { raw: contact }
    }

    pub fn to_raw_input_media(&self) -> tl::types::InputMediaContact {
        tl::types::InputMediaContact {
            phone_number: self.raw.phone_number.clone(),
            first_name: self.raw.first_name.clone(),
            last_name: self.raw.last_name.clone(),
            vcard: self.raw.vcard.clone(),
        }
    }

    /// The contact's phone number, in international format. This field will always be a non-empty
    /// string of digits, although there's no guarantee that the number actually exists.
    pub fn phone_number(&self) -> &str {
        self.raw.phone_number.as_str()
    }

    /// The contact's first name. Although official clients will always send a non-empty string,
    /// it is possible for this field to be empty when sent via different means.
    pub fn first_name(&self) -> &str {
        self.raw.first_name.as_str()
    }

    /// The contact's last name. May be empty if it's not set by sender.
    pub fn last_name(&self) -> &str {
        self.raw.last_name.as_str()
    }

    /// Contact information in [vCard format]. Applications such as Telegram Desktop leave this
    /// field empty. The vCard version used in this field could be any. The field may also contain
    /// arbitrary text when sent by non-official clients.
    ///
    /// [vCard format]: https://en.wikipedia.org/wiki/VCard
    pub fn vcard(&self) -> &str {
        self.raw.vcard.as_str()
    }
}

impl Poll {
    pub fn from_raw_media(poll: tl::types::MessageMediaPoll) -> Self {
        Self {
            raw: match poll.poll {
                tl::enums::Poll::Poll(poll) => poll,
            },
            raw_results: match poll.results {
                tl::enums::PollResults::Results(results) => results,
            },
        }
    }

    pub fn to_raw_input_media(&self) -> tl::types::InputMediaPoll {
        tl::types::InputMediaPoll {
            poll: grammers_tl_types::enums::Poll::Poll(self.raw.clone()),
            correct_answers: None,
            solution: None,
            solution_entities: None,
        }
    }

    /// Returns the question asked by the poll.
    pub fn question(&self) -> &grammers_tl_types::enums::TextWithEntities {
        &self.raw.question
    }

    /// Return `true` if the poll is a quiz with a set of correct answers.
    pub fn is_quiz(&self) -> bool {
        self.raw.quiz
    }

    /// Returns `true` if the poll is closed.
    pub fn closed(&self) -> bool {
        self.raw.closed
    }

    /// Returns an iterator over the poll answer options.
    pub fn iter_answers(&self) -> impl Iterator<Item = &tl::types::PollAnswer> {
        self.raw.answers.iter().map(|answer| match answer {
            tl::enums::PollAnswer::Answer(answer) => answer,
        })
    }

    /// Total voters that took part in the vote.
    ///
    /// May be `None` if poll hasn't started.
    pub fn total_voters(&self) -> Option<i32> {
        self.raw_results.total_voters
    }

    /// Returns details of the voters choices,
    /// such as amount of voters per answer and whether the answer
    /// is currently selected by the logged-in account.
    pub fn iter_voters_summary(
        &self,
    ) -> Option<impl Iterator<Item = &tl::types::PollAnswerVoters>> {
        self.raw_results.results.as_ref().map(|results| {
            results.iter().map(|result| match result {
                tl::enums::PollAnswerVoters::Voters(voters) => voters,
            })
        })
    }
}

impl Geo {
    pub fn from_raw_media(geo: tl::types::MessageMediaGeo) -> Option<Self> {
        use tl::enums::GeoPoint as eGeoPoint;

        match &geo.geo {
            eGeoPoint::Empty => None,
            eGeoPoint::Point(point) => Some(Self { raw: point.clone() }),
        }
    }

    pub fn to_raw_input_media(&self) -> tl::types::InputMediaGeoPoint {
        use tl::types::InputGeoPoint;

        tl::types::InputMediaGeoPoint {
            geo_point: InputGeoPoint {
                lat: self.raw.lat,
                long: self.raw.long,
                accuracy_radius: self.raw.accuracy_radius,
            }
            .into(),
        }
    }

    pub fn to_raw_input_geo_point(&self) -> tl::enums::InputGeoPoint {
        use tl::{enums::InputGeoPoint as eInputGeoPoint, types::InputGeoPoint};

        eInputGeoPoint::Point(InputGeoPoint {
            lat: self.raw.lat,
            long: self.raw.long,
            accuracy_radius: self.raw.accuracy_radius,
        })
    }

    /// Get the latitude of the location.
    pub fn latitue(&self) -> f64 {
        self.raw.lat
    }

    /// Get the latitude of the location.
    pub fn longitude(&self) -> f64 {
        self.raw.long
    }

    /// Get the accuracy of the geo location, in meters.
    pub fn accuracy_radius(&self) -> Option<i32> {
        self.raw.accuracy_radius
    }
}

impl Dice {
    pub fn from_raw_media(dice: tl::types::MessageMediaDice) -> Self {
        Self { raw: dice }
    }

    pub fn to_raw_input_media(&self) -> tl::types::InputMediaDice {
        tl::types::InputMediaDice {
            emoticon: self.raw.emoticon.clone(),
        }
    }

    /// Get the emoji of the dice.
    pub fn emoji(&self) -> &str {
        &self.raw.emoticon
    }

    /// Get the value of the dice.
    pub fn value(&self) -> i32 {
        self.raw.value
    }
}

impl Venue {
    pub fn from_raw_media(venue: tl::types::MessageMediaVenue) -> Self {
        use tl::types::MessageMediaGeo;
        Self {
            geo: Geo::from_raw_media(MessageMediaGeo {
                geo: venue.geo.clone(),
            }),
            raw_venue: venue,
        }
    }

    pub fn to_raw_input_media(&self) -> tl::types::InputMediaVenue {
        tl::types::InputMediaVenue {
            geo_point: match self.geo {
                Some(ref geo) => geo.to_raw_input_geo_point(),
                None => tl::enums::InputGeoPoint::Empty,
            },
            title: self.raw_venue.title.clone(),
            address: self.raw_venue.address.clone(),
            provider: self.raw_venue.provider.clone(),
            venue_id: self.raw_venue.venue_id.clone(),
            venue_type: self.raw_venue.venue_type.clone(),
        }
    }

    /// Returns the title of the venue.
    pub fn title(&self) -> &str {
        &self.raw_venue.title
    }

    /// Returns the address of the venue.
    pub fn address(&self) -> &str {
        &self.raw_venue.address
    }

    /// Returns the provider of the venue location.
    pub fn provider(&self) -> &str {
        &self.raw_venue.provider
    }

    /// Returns the id of the venue.
    pub fn venue_id(&self) -> &str {
        &self.raw_venue.venue_id
    }

    /// Returns the type of the venue.
    pub fn venue_type(&self) -> &str {
        &self.raw_venue.venue_type
    }
}

impl GeoLive {
    pub fn from_raw_media(geolive: tl::types::MessageMediaGeoLive) -> Self {
        use tl::types::MessageMediaGeo;
        Self {
            geo: Geo::from_raw_media(MessageMediaGeo {
                geo: geolive.geo.clone(),
            }),
            raw_geolive: geolive,
        }
    }

    pub fn to_raw_input_media(&self) -> tl::types::InputMediaGeoLive {
        tl::types::InputMediaGeoLive {
            geo_point: match self.geo {
                Some(ref geo) => geo.to_raw_input_geo_point(),
                None => tl::enums::InputGeoPoint::Empty,
            },
            heading: self.raw_geolive.heading,
            period: Some(self.raw_geolive.period),
            proximity_notification_radius: self.raw_geolive.proximity_notification_radius,
            stopped: false,
        }
    }

    /// Returns the heading of the live location in degress (1-360).
    pub fn heading(&self) -> Option<i32> {
        self.raw_geolive.heading
    }

    /// Returns the validity period of the live location.
    pub fn period(&self) -> i32 {
        self.raw_geolive.period
    }

    /// Returns the radius of the proximity alert.
    pub fn proximity_notification_radius(&self) -> Option<i32> {
        self.raw_geolive.proximity_notification_radius
    }
}

impl WebPage {
    pub fn from_raw_media(webpage: tl::types::MessageMediaWebPage) -> Self {
        Self { raw: webpage }
    }
}

impl Uploaded {
    pub fn from_raw(input_file: tl::enums::InputFile) -> Self {
        Self { raw: input_file }
    }

    pub(crate) fn name(&self) -> &str {
        match &self.raw {
            tl::enums::InputFile::File(f) => f.name.as_ref(),
            tl::enums::InputFile::Big(f) => f.name.as_ref(),
            tl::enums::InputFile::StoryDocument(_) => "",
        }
    }
}

impl Media {
    pub fn from_raw(media: tl::enums::MessageMedia) -> Option<Self> {
        use tl::enums::MessageMedia as M;

        // TODO implement the rest
        match media {
            M::Empty => None,
            M::Photo(photo) => Some(Self::Photo(Photo::from_raw_media(photo))),
            M::Geo(geo) => Geo::from_raw_media(geo).map(Self::Geo),
            M::Contact(contact) => Some(Self::Contact(Contact::from_raw_media(contact))),
            M::Unsupported => None,
            M::Document(document) => {
                let document = Document::from_raw_media(document);
                Some(if let Some(sticker) = Sticker::from_document(&document) {
                    Self::Sticker(sticker)
                } else {
                    Self::Document(document)
                })
            }
            M::WebPage(webpage) => Some(Self::WebPage(WebPage::from_raw_media(webpage))),
            M::Venue(venue) => Some(Self::Venue(Venue::from_raw_media(venue))),
            M::Game(_) => None,
            M::Invoice(_) => None,
            M::GeoLive(geolive) => Some(Self::GeoLive(GeoLive::from_raw_media(geolive))),
            M::Poll(poll) => Some(Self::Poll(Poll::from_raw_media(poll))),
            M::Dice(dice) => Some(Self::Dice(Dice::from_raw_media(dice))),
            M::Story(_) => None,
            M::Giveaway(_) => None,
            M::GiveawayResults(_) => None,
            M::PaidMedia(_) => None,
            M::ToDo(_) => None,
            M::VideoStream(_) => None,
        }
    }

    pub fn to_raw_input_media(&self) -> Option<tl::enums::InputMedia> {
        match self {
            Media::Photo(photo) => Some(photo.to_raw_input_media().into()),
            Media::Document(document) => Some(document.to_raw_input_media().into()),
            Media::Sticker(sticker) => Some(sticker.document.to_raw_input_media().into()),
            Media::Contact(contact) => Some(contact.to_raw_input_media().into()),
            Media::Poll(poll) => Some(poll.to_raw_input_media().into()),
            Media::Geo(geo) => Some(geo.to_raw_input_media().into()),
            Media::Dice(dice) => Some(dice.to_raw_input_media().into()),
            Media::Venue(venue) => Some(venue.to_raw_input_media().into()),
            Media::GeoLive(geolive) => Some(geolive.to_raw_input_media().into()),
            Media::WebPage(_) => None,
        }
    }
}

impl Downloadable for Media {
    fn to_raw_input_location(&self) -> Option<tl::enums::InputFileLocation> {
        match self {
            Media::Photo(photo) => photo.to_raw_input_location(),
            Media::Document(document) => document.to_raw_input_location(),
            Media::Sticker(sticker) => sticker.document.to_raw_input_location(),
            Media::Contact(_) => None,
            Media::Poll(_) => None,
            Media::Geo(_) => None,
            Media::Dice(_) => None,
            Media::Venue(_) => None,
            Media::GeoLive(_) => None,
            Media::WebPage(_) => None,
        }
    }
}

impl From<Photo> for Media {
    fn from(photo: Photo) -> Self {
        Self::Photo(photo)
    }
}

impl Downloadable for ChatPhoto {
    fn to_raw_input_location(&self) -> Option<tl::enums::InputFileLocation> {
        Some(self.raw.clone())
    }
}