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
use std::{cmp, ops::Range};
use serde::{Deserialize, Serialize};
use crate::types::{User, UserId};
/// This object represents one special entity in a text message.
///
/// For example, hashtags, usernames, URLs, etc.
///
/// [The official docs](https://core.telegram.org/bots/api#messageentity).
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
pub struct MessageEntity {
#[serde(flatten)]
pub kind: MessageEntityKind,
/// Offset in UTF-16 code units to the start of the entity.
pub offset: usize,
/// Length of the entity in UTF-16 code units.
pub length: usize,
}
/// A "parsed" [`MessageEntity`].
///
/// [`MessageEntity`] has offsets in UTF-**16** code units, but in Rust we
/// mostly work with UTF-**8**. In order to use an entity we need to convert
/// UTF-16 offsets to UTF-8 ones. This type represents a message entity with
/// converted offsets and a reference to the text.
///
/// You can get [`MessageEntityRef`]s by calling [`parse_entities`] and
/// [`parse_caption_entities`] methods of [`Message`] or by calling
/// [`MessageEntityRef::parse`].
///
/// [`parse_entities`]: crate::types::Message::parse_entities
/// [`parse_caption_entities`]: crate::types::Message::parse_caption_entities
/// [`Message`]: crate::types::Message
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
pub struct MessageEntityRef<'a> {
message: &'a str,
range: Range<usize>,
kind: &'a MessageEntityKind,
}
impl MessageEntity {
#[must_use]
pub const fn new(kind: MessageEntityKind, offset: usize, length: usize) -> Self {
Self { kind, offset, length }
}
/// Create a message entity representing a bold text.
#[must_use]
pub const fn bold(offset: usize, length: usize) -> Self {
Self { kind: MessageEntityKind::Bold, offset, length }
}
/// Create a message entity representing an italic text.
#[must_use]
pub const fn italic(offset: usize, length: usize) -> Self {
Self { kind: MessageEntityKind::Italic, offset, length }
}
/// Create a message entity representing an underline text.
#[must_use]
pub const fn underline(offset: usize, length: usize) -> Self {
Self { kind: MessageEntityKind::Underline, offset, length }
}
/// Create a message entity representing a strikethrough text.
#[must_use]
pub const fn strikethrough(offset: usize, length: usize) -> Self {
Self { kind: MessageEntityKind::Strikethrough, offset, length }
}
/// Create a message entity representing a spoiler text.
#[must_use]
pub const fn spoiler(offset: usize, length: usize) -> Self {
Self { kind: MessageEntityKind::Spoiler, offset, length }
}
/// Create a message entity representing a monowidth text.
#[must_use]
pub const fn code(offset: usize, length: usize) -> Self {
Self { kind: MessageEntityKind::Code, offset, length }
}
/// Create a message entity representing a monowidth block.
#[must_use]
pub const fn pre(language: Option<String>, offset: usize, length: usize) -> Self {
Self { kind: MessageEntityKind::Pre { language }, offset, length }
}
/// Create a message entity representing a clickable text URL.
#[must_use]
pub const fn text_link(url: reqwest::Url, offset: usize, length: usize) -> Self {
Self { kind: MessageEntityKind::TextLink { url }, offset, length }
}
/// Create a message entity representing a text mention.
///
/// # Note
///
/// If you don't have a complete [`User`] value, please use
/// [`MessageEntity::text_mention_id`] instead.
#[must_use]
pub const fn text_mention(user: User, offset: usize, length: usize) -> Self {
Self { kind: MessageEntityKind::TextMention { user }, offset, length }
}
/// Create a message entity representing a text link in the form of
/// `tg://user/?id=...` that mentions user with `user_id`.
#[must_use]
pub fn text_mention_id(user_id: UserId, offset: usize, length: usize) -> Self {
Self { kind: MessageEntityKind::TextLink { url: user_id.url() }, offset, length }
}
/// Create a message entity representing a custom emoji.
#[must_use]
pub const fn custom_emoji(custom_emoji_id: String, offset: usize, length: usize) -> Self {
Self { kind: MessageEntityKind::CustomEmoji { custom_emoji_id }, offset, length }
}
#[must_use]
pub fn kind(mut self, val: MessageEntityKind) -> Self {
self.kind = val;
self
}
#[must_use]
pub const fn offset(mut self, val: usize) -> Self {
self.offset = val;
self
}
#[must_use]
pub const fn length(mut self, val: usize) -> Self {
self.length = val;
self
}
}
impl<'a> MessageEntityRef<'a> {
/// Returns kind of this entity.
#[must_use]
pub fn kind(&self) -> &'a MessageEntityKind {
self.kind
}
/// Returns the text that this entity is related to.
#[must_use]
pub fn text(&self) -> &'a str {
&self.message[self.range.clone()]
}
/// Returns range that this entity is related to.
///
/// The range is in bytes for UTF-8 encoding i.e. you can use it with common
/// Rust strings.
#[must_use]
pub fn range(&self) -> Range<usize> {
self.range.clone()
}
/// Returns the offset (in bytes, for UTF-8) to the start of this entity in
/// the original message.
#[must_use]
pub fn start(&self) -> usize {
self.range.start
}
/// Returns the offset (in bytes, for UTF-8) to the end of this entity in
/// the original message.
#[must_use]
pub fn end(&self) -> usize {
self.range.end
}
/// Returns the length of this entity in bytes for UTF-8 encoding.
#[allow(clippy::len_without_is_empty)]
#[must_use]
pub fn len(&self) -> usize {
self.range.len()
}
/// Returns the full text of the original message.
#[must_use]
pub fn message_text(&self) -> &'a str {
self.message
}
/// Parses telegram [`MessageEntity`]s converting offsets to UTF-8.
#[must_use]
pub fn parse(text: &'a str, entities: &'a [MessageEntity]) -> Vec<Self> {
// This creates entities with **wrong** offsets (UTF-16) that we later patch.
let mut entities: Vec<_> = entities
.iter()
.map(|e| Self { message: text, range: e.offset..e.offset + e.length, kind: &e.kind })
.collect();
// Convert offsets
// References to all offsets that need patching
let mut offsets: Vec<&mut usize> = entities
.iter_mut()
.flat_map(|Self { range: Range { start, end }, .. }| [start, end])
.collect();
// Sort in decreasing order, so the smallest elements are at the end and can be
// removed more easily
offsets.sort_unstable_by_key(|&&mut offset| cmp::Reverse(offset));
let _ = text
.chars()
.chain(['\0']) // this is needed to process offset pointing at the end of the string
.try_fold((0, 0), |(len_utf8, len_utf16), c| {
// Stop if there are no more offsets to patch
if offsets.is_empty() {
return None;
}
// Patch all offsets that can be patched
while offsets.last().map(|&&mut offset| offset <= len_utf16).unwrap_or(false) {
let offset = offsets.pop().unwrap();
assert_eq!(*offset, len_utf16, "Invalid utf-16 offset");
// Patch the offset to be UTF-8
*offset = len_utf8;
}
// Update "running" length
Some((len_utf8 + c.len_utf8(), len_utf16 + c.len_utf16()))
});
entities
}
}
#[serde_with_macros::skip_serializing_none]
#[derive(Clone, Debug, Eq, Hash, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
#[serde(tag = "type")]
pub enum MessageEntityKind {
Mention,
Hashtag,
Cashtag,
BotCommand,
Url,
Email,
PhoneNumber,
Bold,
Italic,
Underline,
Strikethrough,
Spoiler,
Code,
Pre { language: Option<String> },
TextLink { url: reqwest::Url },
TextMention { user: User },
CustomEmoji { custom_emoji_id: String }, // FIXME(waffle): newtype this
}
#[cfg(test)]
mod tests {
use super::*;
use cool_asserts::assert_matches;
use MessageEntity;
use MessageEntityKind::*;
#[test]
fn recursive_kind() {
use serde_json::from_str;
assert_eq!(
MessageEntity {
kind: MessageEntityKind::TextLink {
url: reqwest::Url::parse("https://example.com").unwrap(),
},
offset: 1,
length: 2,
},
from_str::<MessageEntity>(
r#"{"type":"text_link","url":"https://example.com","offset":1,"length":2}"#
)
.unwrap()
);
}
#[test]
fn pre() {
use serde_json::from_str;
assert_eq!(
MessageEntity {
kind: MessageEntityKind::Pre { language: Some("rust".to_string()) },
offset: 1,
length: 2,
},
from_str::<MessageEntity>(r#"{"type":"pre","offset":1,"length":2,"language":"rust"}"#)
.unwrap()
);
}
// https://github.com/teloxide/teloxide-core/pull/145
#[test]
fn pre_with_none_language() {
use serde_json::to_string;
assert_eq!(
to_string(&MessageEntity {
kind: MessageEntityKind::Pre { language: None },
offset: 1,
length: 2,
})
.unwrap()
.find("language"),
None
);
}
#[test]
fn parse_быба() {
let parsed = MessageEntityRef::parse(
"быба",
&[
MessageEntity { kind: Strikethrough, offset: 0, length: 1 },
MessageEntity { kind: Bold, offset: 1, length: 1 },
MessageEntity { kind: Italic, offset: 2, length: 1 },
MessageEntity { kind: Code, offset: 3, length: 1 },
],
);
assert_matches!(
parsed,
[
entity if entity.text() == "б" && entity.kind() == &Strikethrough,
entity if entity.text() == "ы" && entity.kind() == &Bold,
entity if entity.text() == "б" && entity.kind() == &Italic,
entity if entity.text() == "а" && entity.kind() == &Code,
]
);
}
#[test]
fn parse_symbol_24bit() {
let parsed = MessageEntityRef::parse(
"xx আ #tt",
&[MessageEntity { kind: Hashtag, offset: 5, length: 3 }],
);
assert_matches!(
parsed,
[entity if entity.text() == "#tt" && entity.kind() == &Hashtag]
);
}
#[test]
fn parse_enclosed() {
let parsed = MessageEntityRef::parse(
"b i b",
// For some reason this is how telegram encodes <b>b <i>i<i/> b<b/>
&[
MessageEntity { kind: Bold, offset: 0, length: 2 },
MessageEntity { kind: Bold, offset: 2, length: 3 },
MessageEntity { kind: Italic, offset: 2, length: 1 },
],
);
assert_matches!(
parsed,
[
entity if entity.text() == "b " && entity.kind() == &Bold,
entity if entity.text() == "i b" && entity.kind() == &Bold,
entity if entity.text() == "i" && entity.kind() == &Italic,
]
);
}
#[test]
fn parse_nothing() {
let parsed = MessageEntityRef::parse("a", &[]);
assert_eq!(parsed, []);
}
#[test]
fn parse_empty() {
// It should be impossible for this to be returned from telegram, but just to be
// sure
let parsed = MessageEntityRef::parse(
"",
&[
MessageEntity { kind: Bold, offset: 0, length: 0 },
MessageEntity { kind: Italic, offset: 0, length: 0 },
],
);
assert_matches!(
parsed,
[
entity if entity.text() == "" && entity.kind() == &Bold,
entity if entity.text() == "" && entity.kind() == &Italic,
]
);
}
}