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
//! Types representing a chat member.

use crate::types::User;
use is_macro::Is;
use serde::{
    de::{Deserializer, Error, IgnoredAny, MapAccess, Visitor},
    Deserialize,
};

use super::{Chat, InviteLink};

/// Represents the status of a member.
#[derive(Debug, PartialEq, Eq, Clone, Hash, Is)]
#[non_exhaustive]
pub enum Status {
    /// The user is the creator of the chat.
    #[non_exhaustive]
    Creator {
        /// Custom title of the creator.
        custom_title: Option<String>,
        /// `true` if the creator is anonymous.
        is_anonymous: bool,
    },
    /// The user is an administrator of the chat.
    #[non_exhaustive]
    Administrator {
        /// Custom title of the admin.
        custom_title: Option<String>,
        /// `true` if the admin can perform any administrative actions.
        can_manage_chat: bool,
        /// `true` if the bot can edit this admin's rights.
        can_be_edited: bool,
        /// `true` if the admin can change the group's info.
        can_change_info: bool,
        /// `true` if the admin can post messages (channels only).
        can_post_messages: Option<bool>,
        /// `true` if the admin can edit messages (channels only).
        can_edit_messages: Option<bool>,
        /// `true` if the admin can delete messages.
        can_delete_messages: bool,
        /// `true` if the admin can invite users.
        can_invite_users: bool,
        /// `true` if the admin can restruct users.
        can_restrict_members: bool,
        /// `true` if the admin can pin messages.
        can_pin_messages: Option<bool>,
        /// `true` if the admin can promote members.
        can_promote_members: bool,
        /// `true` if the admin can manage voice chats.
        can_manage_voice_chats: bool,
        /// `true` if the admin is anonymous.
        is_anonymous: bool,
    },
    /// The user is a member of the chat.
    Member,
    /// The user is restricted in the chat.
    #[non_exhaustive]
    Restricted {
        /// Time when the restriction will be lifted.
        until_date: Option<i64>,
        /// `true` if the user is a member of the chat.
        is_member: bool,
        /// `true` if the user can send messages.
        can_send_mesages: bool,
        /// `true` if the user can send media messages.
        can_send_media_messages: bool,
        /// `true` if the user can send other messages, such as games.
        can_send_other_messages: bool,
        /// `true` if the user can send messages with link previews.
        can_add_web_page_previews: bool,
        /// `true` if the user can send polls.
        can_send_polls: bool,
        /// `true` if the user can change the group's info.
        can_change_info: bool,
        /// `true` if the user can invite users.
        can_invite_users: bool,
        /// `true` if the user can pin messages.
        can_pin_messages: bool,
    },
    /// The user left the chat.
    Left,
    /// The user was kicked out of the chat.
    #[non_exhaustive]
    Kicked {
        /// Time when the restriction will be lifted.
        until_date: Option<i64>,
    },
}

/// Represents a [`ChatMember`].
///
/// [`ChatMember`]: https://core.telegram.org/bots/api#chatmember
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
#[non_exhaustive]
pub struct Member {
    /// Information about the member.
    pub user: User,
    /// Status of the member.
    pub status: Status,
}

/// Represents changes about a chat member's status.
///
/// See [`ChatMemberUpdated`] from Bot API docs.
///
/// [`ChatMemberUpdated`]: https://core.telegram.org/bots/api#chatmemberupdated
#[derive(Debug, PartialEq, Clone, Deserialize)]
pub struct Updated {
    /// The chat in which the change occured.
    pub chat: Chat,
    /// The user who caused the change.
    pub from: User,
    /// Timestamp when this change occured.
    pub date: i64,
    /// Previous information about the member.
    #[serde(rename = "old_chat_member")]
    pub before: Member,
    /// New information about the member.
    #[serde(rename = "new_chat_member")]
    pub after: Member,
    /// The invite link which the user used to join the chat.
    pub invite_link: Option<InviteLink>,
}

const USER: &str = "user";
const STATUS: &str = "status";
const CUSTOM_TITLE: &str = "custom_title";
const UNTIL_DATE: &str = "until_date";
const CAN_MANAGE_CHAT: &str = "can_manage_chat";
const CAN_BE_EDITED: &str = "can_be_edited";
const CAN_CHANGE_INFO: &str = "can_change_info";
const CAN_POST_MESSAGES: &str = "can_post_messages";
const CAN_EDIT_MESSAGES: &str = "can_edit_messages";
const CAN_DELETE_MESSAGES: &str = "can_delete_messages";
const CAN_INVITE_USERS: &str = "can_invite_users";
const CAN_RESTRICT_MEMBERS: &str = "can_restrict_members";
const CAN_PIN_MESSAGES: &str = "can_pin_messages";
const CAN_PROMOTE_MEMBERS: &str = "can_promote_members";
const IS_MEMBER: &str = "is_member";
const CAN_SEND_MESSAGES: &str = "can_send_messages";
const CAN_SEND_MEDIA_MESSAGES: &str = "can_send_media_messages";
const CAN_SEND_OTHER_MESSAGES: &str = "can_send_other_messages";
const CAN_SEND_POLLS: &str = "can_send_polls";
const CAN_ADD_WEB_PAGE_PREVIEWS: &str = "can_add_web_page_previews";
const CAN_MANAGE_VOICE_CHATS: &str = "can_manage_voice_chats";
const IS_ANONYMOUS: &str = "is_anonymous";

const CREATOR: &str = "creator";
const ADMINISTRATOR: &str = "administrator";
const MEMBER: &str = "member";
const RESTRICTED: &str = "restricted";
const LEFT: &str = "left";
const KICKED: &str = "kicked";

struct MemberVisitor;

impl<'v> Visitor<'v> for MemberVisitor {
    type Value = Member;

    fn expecting(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(fmt, "struct Member")
    }

    #[allow(clippy::too_many_lines)] // nothing to split
    fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
    where
        V: MapAccess<'v>,
    {
        let mut user = None;
        let mut status = None;
        let mut custom_title = None;
        let mut until_date = None;
        let mut can_manage_chat = None;
        let mut can_be_edited = None;
        let mut can_change_info = None;
        let mut can_post_messages = None;
        let mut can_edit_messages = None;
        let mut can_delete_messages = None;
        let mut can_invite_users = None;
        let mut can_restrict_members = None;
        let mut can_pin_messages = None;
        let mut can_promote_members = None;
        let mut is_member = None;
        let mut can_send_messages = None;
        let mut can_send_media_messages = None;
        let mut can_send_other_messages = None;
        let mut can_send_polls = None;
        let mut can_add_web_page_previews = None;
        let mut can_manage_voice_chats = None;
        let mut is_anonymous = None;

        while let Some(key) = map.next_key()? {
            match key {
                USER => user = Some(map.next_value()?),
                STATUS => status = Some(map.next_value()?),
                CUSTOM_TITLE => custom_title = Some(map.next_value()?),
                UNTIL_DATE => until_date = Some(map.next_value()?),
                CAN_MANAGE_CHAT => can_manage_chat = Some(map.next_value()?),
                CAN_BE_EDITED => can_be_edited = Some(map.next_value()?),
                CAN_CHANGE_INFO => can_change_info = Some(map.next_value()?),
                CAN_POST_MESSAGES => {
                    can_post_messages = Some(map.next_value()?);
                }
                CAN_EDIT_MESSAGES => {
                    can_edit_messages = Some(map.next_value()?);
                }
                CAN_DELETE_MESSAGES => {
                    can_delete_messages = Some(map.next_value()?);
                }
                CAN_INVITE_USERS => can_invite_users = Some(map.next_value()?),
                CAN_RESTRICT_MEMBERS => {
                    can_restrict_members = Some(map.next_value()?);
                }
                CAN_PIN_MESSAGES => can_pin_messages = Some(map.next_value()?),
                CAN_PROMOTE_MEMBERS => {
                    can_promote_members = Some(map.next_value()?);
                }
                IS_MEMBER => is_member = Some(map.next_value()?),
                CAN_SEND_MESSAGES => {
                    can_send_messages = Some(map.next_value()?);
                }
                CAN_SEND_MEDIA_MESSAGES => {
                    can_send_media_messages = Some(map.next_value()?);
                }
                CAN_SEND_OTHER_MESSAGES => {
                    can_send_other_messages = Some(map.next_value()?);
                }
                CAN_SEND_POLLS => can_send_polls = Some(map.next_value()?),
                CAN_ADD_WEB_PAGE_PREVIEWS => {
                    can_add_web_page_previews = Some(map.next_value()?);
                }
                CAN_MANAGE_VOICE_CHATS => {
                    can_manage_voice_chats = Some(map.next_value()?);
                }
                IS_ANONYMOUS => is_anonymous = Some(map.next_value()?),
                _ => {
                    let _ = map.next_value::<IgnoredAny>()?;
                }
            }
        }

        let status = match &status {
            Some(CREATOR) => Status::Creator {
                custom_title,
                is_anonymous: is_anonymous
                    .ok_or_else(|| Error::missing_field(IS_ANONYMOUS))?,
            },
            Some(ADMINISTRATOR) => Status::Administrator {
                custom_title,
                can_manage_chat: can_manage_chat
                    .ok_or_else(|| Error::missing_field(CAN_MANAGE_CHAT))?,
                can_be_edited: can_be_edited
                    .ok_or_else(|| Error::missing_field(CAN_BE_EDITED))?,
                can_change_info: can_change_info
                    .ok_or_else(|| Error::missing_field(CAN_CHANGE_INFO))?,
                can_post_messages,
                can_edit_messages,
                can_delete_messages: can_delete_messages
                    .ok_or_else(|| Error::missing_field(CAN_DELETE_MESSAGES))?,
                can_invite_users: can_invite_users
                    .ok_or_else(|| Error::missing_field(CAN_INVITE_USERS))?,
                can_restrict_members: can_restrict_members.ok_or_else(
                    || Error::missing_field(CAN_RESTRICT_MEMBERS),
                )?,
                can_pin_messages,
                can_promote_members: can_promote_members
                    .ok_or_else(|| Error::missing_field(CAN_PROMOTE_MEMBERS))?,
                can_manage_voice_chats: can_manage_voice_chats.ok_or_else(
                    || Error::missing_field(CAN_MANAGE_VOICE_CHATS),
                )?,
                is_anonymous: is_anonymous
                    .ok_or_else(|| Error::missing_field(IS_ANONYMOUS))?,
            },
            Some(MEMBER) => Status::Member,
            Some(RESTRICTED) => Status::Restricted {
                until_date: until_date.filter(|&date| date > 0),
                is_member: is_member
                    .ok_or_else(|| Error::missing_field(IS_MEMBER))?,
                can_send_mesages: can_send_messages
                    .ok_or_else(|| Error::missing_field(CAN_SEND_MESSAGES))?,
                can_send_media_messages: can_send_media_messages.ok_or_else(
                    || Error::missing_field(CAN_SEND_MEDIA_MESSAGES),
                )?,
                can_send_other_messages: can_send_other_messages.ok_or_else(
                    || Error::missing_field(CAN_SEND_OTHER_MESSAGES),
                )?,
                can_send_polls: can_send_polls
                    .ok_or_else(|| Error::missing_field(CAN_SEND_POLLS))?,
                can_add_web_page_previews: can_add_web_page_previews
                    .ok_or_else(|| {
                        Error::missing_field(CAN_ADD_WEB_PAGE_PREVIEWS)
                    })?,
                can_change_info: can_change_info
                    .ok_or_else(|| Error::missing_field(CAN_CHANGE_INFO))?,
                can_invite_users: can_invite_users
                    .ok_or_else(|| Error::missing_field(CAN_INVITE_USERS))?,
                can_pin_messages: can_pin_messages
                    .ok_or_else(|| Error::missing_field(CAN_PIN_MESSAGES))?,
            },
            Some(LEFT) => Status::Left,
            Some(KICKED) => Status::Kicked {
                until_date: until_date.filter(|&date| date > 0),
            },
            Some(unknown_status) => {
                return Err(Error::unknown_variant(
                    unknown_status,
                    &[CREATOR, ADMINISTRATOR, MEMBER, RESTRICTED, LEFT, KICKED],
                ))
            }
            None => return Err(Error::missing_field(STATUS)),
        };

        Ok(Member {
            user: user.ok_or_else(|| Error::missing_field(USER))?,
            status,
        })
    }
}

impl<'de> Deserialize<'de> for Member {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_struct(
            "Member",
            &[
                USER,
                STATUS,
                CUSTOM_TITLE,
                UNTIL_DATE,
                CAN_BE_EDITED,
                CAN_CHANGE_INFO,
                CAN_POST_MESSAGES,
                CAN_EDIT_MESSAGES,
                CAN_DELETE_MESSAGES,
                CAN_INVITE_USERS,
                CAN_RESTRICT_MEMBERS,
                CAN_PIN_MESSAGES,
                CAN_PROMOTE_MEMBERS,
                IS_MEMBER,
                CAN_SEND_MESSAGES,
                CAN_SEND_MEDIA_MESSAGES,
                CAN_SEND_OTHER_MESSAGES,
                CAN_ADD_WEB_PAGE_PREVIEWS,
                IS_ANONYMOUS,
            ],
            MemberVisitor,
        )
    }
}