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
//! Utils for working with the [HTML message style][spec].
//!
//! [spec]: https://core.telegram.org/bots/api#html-style
use crate::types::User;
use std::string::String;

/// Applies the bold font style to the string.
///
/// Passed string will not be automatically escaped because it can contain
/// nested markup.
pub fn bold(s: &str) -> String {
    format!("<b>{}</b>", s)
}

/// Applies the italic font style to the string.
///
/// Passed string will not be automatically escaped because it can contain
/// nested markup.
pub fn italic(s: &str) -> String {
    format!("<i>{}</i>", s)
}

/// Applies the underline font style to the string.
///
/// Passed string will not be automatically escaped because it can contain
/// nested markup.
pub fn underline(s: &str) -> String {
    format!("<u>{}</u>", s)
}

/// Applies the strikethrough font style to the string.
///
/// Passed string will not be automatically escaped because it can contain
/// nested markup.
pub fn strike(s: &str) -> String {
    format!("<s>{}</s>", s)
}

/// Builds an inline link with an anchor.
///
/// Escapes the passed URL and the link text.
pub fn link(url: &str, text: &str) -> String {
    format!("<a href=\"{}\">{}</a>", escape(url), escape(text))
}

/// Builds an inline user mention link with an anchor.
pub fn user_mention(user_id: i32, text: &str) -> String {
    link(format!("tg://user?id={}", user_id).as_str(), text)
}

/// Formats the code block.
///
/// Escapes HTML characters inside the block.
pub fn code_block(code: &str) -> String {
    format!("<pre>{}</pre>", escape(code))
}

/// Formats the code block with a specific language syntax.
///
/// Escapes HTML characters inside the block.
pub fn code_block_with_lang(code: &str, lang: &str) -> String {
    format!(
        "<pre><code class=\"language-{}\">{}</code></pre>",
        escape(lang).replace("\"", "&quot;"),
        escape(code)
    )
}

/// Formats the string as an inline code.
///
/// Escapes HTML characters inside the block.
pub fn code_inline(s: &str) -> String {
    format!("<code>{}</code>", escape(s))
}

/// Escapes the string to be shown "as is" within the Telegram HTML message
/// style.
///
/// Does not escape ' and " characters (as should be for usual HTML), because
/// they shoudn't be escaped by the [spec].
///
/// [spec]: https://core.telegram.org/bots/api#html-style
pub fn escape(s: &str) -> String {
    s.replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;")
}

pub fn user_mention_or_link(user: &User) -> String {
    match user.mention() {
        Some(mention) => mention,
        None => link(user.url().as_str(), &user.full_name()),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_bold() {
        assert_eq!(bold(" foobar "), "<b> foobar </b>");
        assert_eq!(bold(" <i>foobar</i> "), "<b> <i>foobar</i> </b>");
        assert_eq!(bold("<s>(`foobar`)</s>"), "<b><s>(`foobar`)</s></b>");
    }

    #[test]
    fn test_italic() {
        assert_eq!(italic(" foobar "), "<i> foobar </i>");
        assert_eq!(italic(" <b>foobar</b> "), "<i> <b>foobar</b> </i>");
        assert_eq!(italic("<s>(`foobar`)</s>"), "<i><s>(`foobar`)</s></i>");
    }

    #[test]
    fn test_underline() {
        assert_eq!(underline(" foobar "), "<u> foobar </u>");
        assert_eq!(underline(" <b>foobar</b> "), "<u> <b>foobar</b> </u>");
        assert_eq!(underline("<s>(`foobar`)</s>"), "<u><s>(`foobar`)</s></u>");
    }

    #[test]
    fn test_strike() {
        assert_eq!(strike(" foobar "), "<s> foobar </s>");
        assert_eq!(strike(" <b>foobar</b> "), "<s> <b>foobar</b> </s>");
        assert_eq!(strike("<b>(`foobar`)</b>"), "<s><b>(`foobar`)</b></s>");
    }

    #[test]
    fn test_link() {
        assert_eq!(
            link("https://www.google.com/?q=foo&l=ru", "<google>"),
            "<a href=\"https://www.google.com/?q=foo&amp;l=ru\">&lt;google&gt;\
             </a>",
        );
    }

    #[test]
    fn test_user_mention() {
        assert_eq!(
            user_mention(123_456_789, "<pwner666>"),
            "<a href=\"tg://user?id=123456789\">&lt;pwner666&gt;</a>",
        );
    }

    #[test]
    fn test_code_block() {
        assert_eq!(
            code_block("<p>pre-'formatted'\n & fixed-width \\code `block`</p>"),
            "<pre>&lt;p&gt;pre-'formatted'\n &amp; fixed-width \\code \
             `block`&lt;/p&gt;</pre>"
        );
    }

    #[test]
    fn test_code_block_with_lang() {
        assert_eq!(
            code_block_with_lang(
                "<p>pre-'formatted'\n & fixed-width \\code `block`</p>",
                "<html>\""
            ),
            concat!(
                "<pre><code class=\"language-&lt;html&gt;&quot;\">",
                "&lt;p&gt;pre-'formatted'\n &amp; fixed-width \\code \
                 `block`&lt;/p&gt;",
                "</code></pre>",
            )
        );
    }

    #[test]
    fn test_code_inline() {
        assert_eq!(
            code_inline("<span class=\"foo\">foo & bar</span>"),
            "<code>&lt;span class=\"foo\"&gt;foo &amp; bar&lt;/span&gt;</code>",
        );
    }

    #[test]
    fn test_escape() {
        assert_eq!(
            escape("  <title>Foo & Bar</title>   "),
            "  &lt;title&gt;Foo &amp; Bar&lt;/title&gt;   "
        );
        assert_eq!(
            escape("<p>你好 & 再見</p>"),
            "&lt;p&gt;你好 &amp; 再見&lt;/p&gt;"
        );
        assert_eq!(escape("'foo\""), "'foo\"");
    }

    #[test]
    fn user_mention_link() {
        let user_with_username = User {
            id: 0,
            is_bot: false,
            first_name: "".to_string(),
            last_name: None,
            username: Some("abcd".to_string()),
            language_code: None,
        };
        assert_eq!(user_mention_or_link(&user_with_username), "@abcd");
        let user_without_username = User {
            id: 123_456_789,
            is_bot: false,
            first_name: "Name".to_string(),
            last_name: None,
            username: None,
            language_code: None,
        };
        assert_eq!(
            user_mention_or_link(&user_without_username),
            r#"<a href="tg://user/?id=123456789">Name</a>"#
        )
    }
}