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
use serde::{Deserialize, Serialize};

use crate::types::{ChatId, ChatLocation, ChatPermissions, ChatPhoto, Message, True, User};

/// This object represents a chat.
///
/// [The official docs](https://core.telegram.org/bots/api#chat).
#[serde_with_macros::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct Chat {
    /// A unique identifier for this chat.
    pub id: ChatId,

    #[serde(flatten)]
    pub kind: ChatKind,

    /// A chat photo. Returned only in [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    pub photo: Option<ChatPhoto>,

    /// The most recent pinned message (by sending date). Returned only in
    /// [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    pub pinned_message: Option<Box<Message>>,

    /// The time after which all messages sent to the chat will be automatically
    /// deleted; in seconds. Returned only in [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    pub message_auto_delete_time: Option<u32>,

    /// `true`, if non-administrators can only get the list of bots and
    /// administrators in the chat. Returned only in [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub has_hidden_members: bool,

    /// `true`, if aggressive anti-spam checks are enabled in the supergroup.
    /// The field is only available to chat administrators. Returned only in
    /// [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub has_aggressive_anti_spam_enabled: bool,
}

#[serde_with_macros::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ChatKind {
    Public(ChatPublic),
    Private(ChatPrivate),
}

#[serde_with_macros::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct ChatPublic {
    /// A title, for supergroups, channels and group chats.
    pub title: Option<String>,

    #[serde(flatten)]
    pub kind: PublicChatKind,

    /// A description, for groups, supergroups and channel chats. Returned
    /// only in [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    pub description: Option<String>,

    /// A chat invite link, for groups, supergroups and channel chats. Each
    /// administrator in a chat generates their own invite links, so the
    /// bot must first generate the link using
    /// [`ExportChatInviteLink`]. Returned only in
    /// [`GetChat`].
    ///
    /// [`ExportChatInviteLink`]:
    /// crate::payloads::ExportChatInviteLink
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    pub invite_link: Option<String>,

    /// `True`, if messages from the chat can't be forwarded to other chats.
    /// Returned only in [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    pub has_protected_content: Option<True>,
}

#[serde_with_macros::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(from = "serde_helper::ChatPrivate", into = "serde_helper::ChatPrivate")]
pub struct ChatPrivate {
    /// A username, for private chats, supergroups and channels if
    /// available.
    pub username: Option<String>,

    /// A first name of the other party in a private chat.
    pub first_name: Option<String>,

    /// A last name of the other party in a private chat.
    pub last_name: Option<String>,

    /// Custom emoji identifier of emoji status of the other party in a private
    /// chat. Returned only in [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    // FIXME: CustomEmojiId
    pub emoji_status_custom_emoji_id: Option<String>,

    /// Bio of the other party in a private chat. Returned only in [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    pub bio: Option<String>,

    /// `True`, if privacy settings of the other party in the private chat
    /// allows to use `tg://user?id=<user_id>` links only in chats with the
    /// user. Returned only in [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    pub has_private_forwards: Option<True>,

    /// `True`, if the privacy settings of the other party restrict sending
    /// voice and video note messages in the private chat. Returned only in
    /// [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    pub has_restricted_voice_and_video_messages: Option<True>,
}

#[serde_with_macros::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "type")]
pub enum PublicChatKind {
    Channel(PublicChatChannel),
    Group(PublicChatGroup),
    Supergroup(PublicChatSupergroup),
}

#[serde_with_macros::skip_serializing_none]
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct PublicChatChannel {
    /// A username, for private chats, supergroups and channels if available.
    pub username: Option<String>,

    /// Unique identifier for the linked chat, i.e. the discussion group
    /// identifier for a channel and vice versa. Returned only in [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    pub linked_chat_id: Option<i64>,
}

#[serde_with_macros::skip_serializing_none]
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct PublicChatGroup {
    /// A default chat member permissions, for groups and supergroups. Returned
    /// only from [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    pub permissions: Option<ChatPermissions>,
}

#[serde_with_macros::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct PublicChatSupergroup {
    /// A username, for private chats, supergroups and channels if
    /// available.
    pub username: Option<String>,

    /// If non-empty, the list of all active chat usernames; for private chats,
    /// supergroups and channels. Returned only from [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    pub active_usernames: Option<Vec<String>>,

    /// `true`, if the supergroup chat is a forum (has topics enabled).
    #[serde(default)]
    pub is_forum: bool,

    /// For supergroups, name of group sticker set. Returned only from
    /// [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    pub sticker_set_name: Option<String>,

    /// `true`, if the bot can change the group sticker set. Returned only
    /// from [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    pub can_set_sticker_set: Option<bool>,

    /// A default chat member permissions, for groups and supergroups.
    /// Returned only from [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    pub permissions: Option<ChatPermissions>,

    /// The minimum allowed delay between consecutive messages sent by each
    /// unpriviledged user. Returned only from [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    pub slow_mode_delay: Option<u32>,

    /// Unique identifier for the linked chat, i.e. the discussion group
    /// identifier for a channel and vice versa. Returned only in [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    pub linked_chat_id: Option<i64>,

    /// The location to which the supergroup is connected. Returned only in
    /// [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    pub location: Option<ChatLocation>,

    /// True, if users need to join the supergroup before they can send
    /// messages. Returned only in [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    pub join_to_send_messages: Option<True>,

    /// True, if all users directly joining the supergroup need to be approved
    /// by supergroup administrators. Returned only in [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    pub join_by_request: Option<True>,
}

impl Chat {
    #[must_use]
    pub fn is_private(&self) -> bool {
        matches!(self.kind, ChatKind::Private(_))
    }

    #[must_use]
    pub fn is_group(&self) -> bool {
        matches!(
            self.kind,
            ChatKind::Public(ChatPublic {
                kind: PublicChatKind::Group(_),
                ..
            })
        )
    }

    #[must_use]
    pub fn is_supergroup(&self) -> bool {
        matches!(
            self.kind,
            ChatKind::Public(ChatPublic {
                kind: PublicChatKind::Supergroup(_),
                ..
            })
        )
    }

    #[must_use]
    pub fn is_channel(&self) -> bool {
        matches!(
            self.kind,
            ChatKind::Public(ChatPublic {
                kind: PublicChatKind::Channel(_),
                ..
            })
        )
    }

    #[must_use]
    pub fn is_chat(&self) -> bool {
        self.is_private() || self.is_group() || self.is_supergroup()
    }
}

/// Getters
impl Chat {
    /// A title, for supergroups, channels and group chats.
    #[must_use]
    pub fn title(&self) -> Option<&str> {
        match &self.kind {
            ChatKind::Public(this) => this.title.as_deref(),
            _ => None,
        }
    }

    /// A username, for private chats, supergroups and channels if available.
    #[must_use]
    pub fn username(&self) -> Option<&str> {
        match &self.kind {
            ChatKind::Public(this) => match &this.kind {
                PublicChatKind::Channel(PublicChatChannel { username, .. })
                | PublicChatKind::Supergroup(PublicChatSupergroup { username, .. }) => {
                    username.as_deref()
                }
                PublicChatKind::Group(_) => None,
            },
            ChatKind::Private(this) => this.username.as_deref(),
        }
    }

    /// Unique identifier for the linked chat, i.e. the discussion group
    /// identifier for a channel and vice versa. Returned only in [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    #[must_use]
    pub fn linked_chat_id(&self) -> Option<i64> {
        match &self.kind {
            ChatKind::Public(this) => match &this.kind {
                PublicChatKind::Channel(PublicChatChannel { linked_chat_id, .. })
                | PublicChatKind::Supergroup(PublicChatSupergroup { linked_chat_id, .. }) => {
                    *linked_chat_id
                }
                PublicChatKind::Group(_) => None,
            },
            _ => None,
        }
    }

    /// A default chat member permissions, for groups and supergroups. Returned
    /// only from [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    #[must_use]
    pub fn permissions(&self) -> Option<ChatPermissions> {
        if let ChatKind::Public(this) = &self.kind {
            if let PublicChatKind::Group(PublicChatGroup { permissions })
            | PublicChatKind::Supergroup(PublicChatSupergroup { permissions, .. }) = &this.kind
            {
                return *permissions;
            }
        }

        None
    }

    /// For supergroups, name of group sticker set. Returned only from
    /// [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    #[must_use]
    pub fn sticker_set_name(&self) -> Option<&str> {
        if let ChatKind::Public(this) = &self.kind {
            if let PublicChatKind::Supergroup(this) = &this.kind {
                return this.sticker_set_name.as_deref();
            }
        }

        None
    }

    /// `true`, if the bot can change the group sticker set. Returned only
    /// from [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    #[must_use]
    pub fn can_set_sticker_set(&self) -> Option<bool> {
        if let ChatKind::Public(this) = &self.kind {
            if let PublicChatKind::Supergroup(this) = &this.kind {
                return this.can_set_sticker_set;
            }
        }

        None
    }

    /// The minimum allowed delay between consecutive messages sent by each
    /// unpriviledged user. Returned only from [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    #[must_use]
    pub fn slow_mode_delay(&self) -> Option<u32> {
        if let ChatKind::Public(this) = &self.kind {
            if let PublicChatKind::Supergroup(this) = &this.kind {
                return this.slow_mode_delay;
            }
        }

        None
    }

    /// The location to which the supergroup is connected. Returned only in
    /// [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    #[must_use]
    pub fn location(&self) -> Option<&ChatLocation> {
        if let ChatKind::Public(this) = &self.kind {
            if let PublicChatKind::Supergroup(this) = &this.kind {
                return this.location.as_ref();
            }
        }

        None
    }

    /// True, if users need to join the supergroup before they can send
    /// messages. Returned only in [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    #[must_use]
    pub fn join_to_send_messages(&self) -> Option<True> {
        if let ChatKind::Public(this) = &self.kind {
            if let PublicChatKind::Supergroup(this) = &this.kind {
                return this.join_to_send_messages;
            }
        }

        None
    }

    /// True, if all users directly joining the supergroup need to be approved
    /// by supergroup administrators. Returned only in [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    #[must_use]
    pub fn join_by_request(&self) -> Option<True> {
        if let ChatKind::Public(this) = &self.kind {
            if let PublicChatKind::Supergroup(this) = &this.kind {
                return this.join_by_request;
            }
        }

        None
    }

    /// A description, for groups, supergroups and channel chats. Returned
    /// only in [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    #[must_use]
    pub fn description(&self) -> Option<&str> {
        match &self.kind {
            ChatKind::Public(this) => this.description.as_deref(),
            _ => None,
        }
    }

    /// A chat invite link, for groups, supergroups and channel chats. Each
    /// administrator in a chat generates their own invite links, so the
    /// bot must first generate the link using
    /// [`ExportChatInviteLink`]. Returned only in
    /// [`GetChat`].
    ///
    /// [`ExportChatInviteLink`]:
    /// crate::payloads::ExportChatInviteLink
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    #[must_use]
    pub fn invite_link(&self) -> Option<&str> {
        match &self.kind {
            ChatKind::Public(this) => this.invite_link.as_deref(),
            _ => None,
        }
    }

    /// `True`, if messages from the chat can't be forwarded to other chats.
    /// Returned only in [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    #[must_use]
    pub fn has_protected_content(&self) -> Option<True> {
        match &self.kind {
            ChatKind::Public(this) => this.has_protected_content,
            _ => None,
        }
    }

    /// A first name of the other party in a private chat.
    #[must_use]
    pub fn first_name(&self) -> Option<&str> {
        match &self.kind {
            ChatKind::Private(this) => this.first_name.as_deref(),
            _ => None,
        }
    }

    /// A last name of the other party in a private chat.
    #[must_use]
    pub fn last_name(&self) -> Option<&str> {
        match &self.kind {
            ChatKind::Private(this) => this.last_name.as_deref(),
            _ => None,
        }
    }

    /// Bio of the other party in a private chat. Returned only in [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    #[must_use]
    pub fn bio(&self) -> Option<&str> {
        match &self.kind {
            ChatKind::Private(this) => this.bio.as_deref(),
            _ => None,
        }
    }

    /// `True`, if privacy settings of the other party in the private chat
    /// allows to use tg://user?id=<user_id> links only in chats with the
    /// user. Returned only in [`GetChat`].
    ///
    /// [`GetChat`]: crate::payloads::GetChat
    #[must_use]
    pub fn has_private_forwards(&self) -> Option<True> {
        match &self.kind {
            ChatKind::Private(this) => this.has_private_forwards,
            _ => None,
        }
    }

    /// Returns all users that are "contained" in this `Chat`
    /// structure.
    ///
    /// This might be useful to track information about users.
    ///
    /// Note that this function can return duplicate users.
    pub fn mentioned_users(&self) -> impl Iterator<Item = &User> {
        crate::util::flatten(self.pinned_message.as_ref().map(|m| m.mentioned_users()))
    }

    /// `{Message, Chat}::mentioned_users` are mutually recursive, as such we
    /// can't use `->impl Iterator` everywhere, as it would make an infinite
    /// type. So we need to box somewhere.
    pub(crate) fn mentioned_users_rec(&self) -> impl Iterator<Item = &User> {
        crate::util::flatten(
            self.pinned_message
                .as_ref()
                .map(|m| m.mentioned_users_rec()),
        )
    }
}

mod serde_helper {
    use crate::types::True;
    use serde::{Deserialize, Serialize};

    #[derive(Serialize, Deserialize)]
    enum Type {
        #[allow(non_camel_case_types)]
        private,
    }

    #[derive(Serialize, Deserialize)]
    pub(super) struct ChatPrivate {
        /// A dummy field. Used to ensure that the `type` field is equal to
        /// `private`.
        r#type: Type,

        username: Option<String>,
        first_name: Option<String>,
        last_name: Option<String>,
        bio: Option<String>,
        has_private_forwards: Option<True>,
        has_restricted_voice_and_video_messages: Option<True>,
        emoji_status_custom_emoji_id: Option<String>,
    }

    impl From<ChatPrivate> for super::ChatPrivate {
        fn from(
            ChatPrivate {
                r#type: _,
                username,
                first_name,
                last_name,
                bio,
                has_private_forwards,
                has_restricted_voice_and_video_messages,
                emoji_status_custom_emoji_id,
            }: ChatPrivate,
        ) -> Self {
            Self {
                username,
                first_name,
                last_name,
                bio,
                has_private_forwards,
                has_restricted_voice_and_video_messages,
                emoji_status_custom_emoji_id,
            }
        }
    }

    impl From<super::ChatPrivate> for ChatPrivate {
        fn from(
            super::ChatPrivate {
                username,
                first_name,
                last_name,
                bio,
                has_private_forwards,
                has_restricted_voice_and_video_messages,
                emoji_status_custom_emoji_id,
            }: super::ChatPrivate,
        ) -> Self {
            Self {
                r#type: Type::private,
                username,
                first_name,
                last_name,
                bio,
                has_private_forwards,
                has_restricted_voice_and_video_messages,
                emoji_status_custom_emoji_id,
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use serde_json::{from_str, to_string};

    use crate::types::*;

    #[test]
    fn channel_de() {
        let expected = Chat {
            id: ChatId(-1),
            kind: ChatKind::Public(ChatPublic {
                title: None,
                kind: PublicChatKind::Channel(PublicChatChannel {
                    username: Some("channel_name".into()),
                    linked_chat_id: None,
                }),
                description: None,
                invite_link: None,
                has_protected_content: None,
            }),
            photo: None,
            pinned_message: None,
            message_auto_delete_time: None,
            has_hidden_members: false,
            has_aggressive_anti_spam_enabled: false,
        };
        let actual = from_str(r#"{"id":-1,"type":"channel","username":"channel_name"}"#).unwrap();
        assert_eq!(expected, actual);
    }

    #[test]
    fn private_chat_de() {
        assert_eq!(
            Chat {
                id: ChatId(0),
                kind: ChatKind::Private(ChatPrivate {
                    username: Some("username".into()),
                    first_name: Some("Anon".into()),
                    last_name: None,
                    bio: None,
                    has_private_forwards: None,
                    has_restricted_voice_and_video_messages: None,
                    emoji_status_custom_emoji_id: None
                }),
                photo: None,
                pinned_message: None,
                message_auto_delete_time: None,
                has_hidden_members: false,
                has_aggressive_anti_spam_enabled: false,
            },
            from_str(r#"{"id":0,"type":"private","username":"username","first_name":"Anon"}"#)
                .unwrap()
        );
    }

    #[test]
    fn private_roundtrip() {
        let chat = Chat {
            id: ChatId(0),
            kind: ChatKind::Private(ChatPrivate {
                username: Some("username".into()),
                first_name: Some("Anon".into()),
                last_name: None,
                bio: None,
                has_private_forwards: None,
                has_restricted_voice_and_video_messages: None,
                emoji_status_custom_emoji_id: None,
            }),
            photo: None,
            pinned_message: None,
            message_auto_delete_time: None,
            has_hidden_members: false,
            has_aggressive_anti_spam_enabled: false,
        };

        let json = to_string(&chat).unwrap();
        let chat2 = from_str::<Chat>(&json).unwrap();

        assert_eq!(chat, chat2);
    }

    #[test]
    fn private_chat_de_wrong_type_field() {
        assert!(from_str::<Chat>(r#"{"id":0,"type":"WRONG"}"#).is_err());
    }
}