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
//! Types representing text.

use crate::types::User;
use is_macro::Is;
use serde::de::{Deserialize, Deserializer, Error, IgnoredAny, Visitor};
use std::fmt::{self, Formatter};

/// Represents either a text message or a caption.
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
#[non_exhaustive]
pub struct Text {
    /// The text/caption. If there's no text, will be empty.
    pub value: String,
    /// The entities in the text/caption. If there are none, will be empty.
    pub entities: Vec<Entity>,
}

/// Represents an entity's kind.
#[derive(Debug, PartialEq, Eq, Clone, Hash, Is)]
#[non_exhaustive]
pub enum EntityKind {
    /// A mention.
    Mention,
    /// A hashtag.
    Hashtag,
    /// A cashtag (e.g. `$TBOT`).
    Cashtag,
    /// A bot command.
    BotCommand,
    /// An url.
    Url,
    /// An email.
    Email,
    /// A phone number.
    PhoneNumber,
    /// Text in bold.
    Bold,
    /// Text in italic.
    Italic,
    /// Underlined text.
    Underline,
    /// Strikethrough text.
    Strikethrough,
    /// String of monowidth text.
    Code,
    /// Block of monowidth text.
    Pre(Option<String>),
    /// A clickable text url.
    TextLink(String),
    /// A mention for users without username.
    TextMention(User),
}

/// Represents an entity of a message.
#[derive(Debug, PartialEq, Eq, Clone, Hash)]
#[non_exhaustive]
pub struct Entity {
    /// The kind of the entity.
    pub kind: EntityKind,
    /// The offset at which the entity starts.
    pub offset: usize,
    /// The length of the entity.
    pub length: usize,
}

const OFFSET: &str = "offset";
const LENGTH: &str = "length";
const URL: &str = "url";
const USER: &str = "user";
const LANGUAGE: &str = "language";
const TYPE: &str = "type";

const MENTION: &str = "mention";
const HASHTAG: &str = "hashtag";
const CASHTAG: &str = "cashtag";
const BOT_COMMAND: &str = "bot_command";
// URL already defined
const EMAIL: &str = "email";
const PHONE_NUMBER: &str = "phone_number";
const BOLD: &str = "bold";
const ITALIC: &str = "italic";
const UNDERLINE: &str = "underline";
const STRIKETHROUGH: &str = "strikethrough";
const CODE: &str = "code";
const PRE: &str = "pre";
const TEXT_LINK: &str = "text_link";
const TEXT_MENTION: &str = "text_mention";

struct EntityVisitor;

impl<'v> Visitor<'v> for EntityVisitor {
    type Value = Entity;

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

    fn visit_map<V>(self, mut map: V) -> Result<Self::Value, V::Error>
    where
        V: serde::de::MapAccess<'v>,
    {
        let mut kind: Option<String> = None;
        let mut offset = None;
        let mut length = None;
        let mut url = None;
        let mut user = None;
        let mut language = None;

        while let Some(key) = map.next_key()? {
            match key {
                OFFSET => offset = Some(map.next_value()?),
                LENGTH => length = Some(map.next_value()?),
                URL => url = Some(map.next_value()?),
                USER => user = Some(map.next_value()?),
                LANGUAGE => language = Some(map.next_value()?),
                TYPE => kind = Some(map.next_value()?),
                _ => drop(map.next_value::<IgnoredAny>()),
            }
        }

        let kind = kind.ok_or_else(|| serde::de::Error::missing_field(TYPE))?;

        let kind = match kind.as_str() {
            TEXT_MENTION => EntityKind::TextMention(
                user.ok_or_else(|| serde::de::Error::missing_field(USER))?,
            ),
            TEXT_LINK => EntityKind::TextLink(
                url.ok_or_else(|| serde::de::Error::missing_field(URL))?,
            ),
            MENTION => EntityKind::Mention,
            HASHTAG => EntityKind::Hashtag,
            CASHTAG => EntityKind::Cashtag,
            BOT_COMMAND => EntityKind::BotCommand,
            URL => EntityKind::Url,
            EMAIL => EntityKind::Email,
            PHONE_NUMBER => EntityKind::PhoneNumber,
            BOLD => EntityKind::Bold,
            ITALIC => EntityKind::Italic,
            UNDERLINE => EntityKind::Underline,
            STRIKETHROUGH => EntityKind::Strikethrough,
            CODE => EntityKind::Code,
            PRE => EntityKind::Pre(language),
            _ => {
                return Err(Error::unknown_variant(
                    &kind,
                    &[
                        MENTION,
                        HASHTAG,
                        CASHTAG,
                        BOT_COMMAND,
                        URL,
                        EMAIL,
                        PHONE_NUMBER,
                        BOLD,
                        ITALIC,
                        UNDERLINE,
                        STRIKETHROUGH,
                        CODE,
                        PRE,
                        TEXT_LINK,
                        TEXT_MENTION,
                    ],
                ))
            }
        };

        Ok(Entity {
            kind,
            offset: offset.ok_or_else(|| Error::missing_field(OFFSET))?,
            length: length.ok_or_else(|| Error::missing_field(LENGTH))?,
        })
    }
}

impl<'de> Deserialize<'de> for Entity {
    fn deserialize<D>(d: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        d.deserialize_struct(
            "Entity",
            &[TYPE, OFFSET, LENGTH, URL, USER, LANGUAGE],
            EntityVisitor,
        )
    }
}