conogram 0.2.19

An async wrapper for Telegram Bot API
Documentation
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
use std::{
    fmt::Display,
    ops::{Range, RangeBounds},
};

use crate::{
    entities::{
        chat::TgChat,
        message_entity::{MessageEntity, MessageEntityType},
        user::User,
    },
    impl_trait,
};

pub trait FormatMention {
    fn mention<'a>(&self, ft: &'a mut FormattedText) -> &'a mut FormattedText;
}

impl_trait!(
    FormatMention for User {
        fn mention<'a>(&self, ft: &'a mut FormattedText) -> &'a mut FormattedText {
            ft.url(self.full_name(), self.get_url())
        }
    }
);

impl<T: TgChat> FormatMention for T {
    fn mention<'a>(&self, ft: &'a mut FormattedText) -> &'a mut FormattedText {
        ft.url(self.full_name(), self.get_url())
    }
}

fn ranges_intersect<T1, T2>(one: Range<T1>, two: Range<T2>) -> bool
where
    T2: PartialOrd<T1>,
    T1: PartialOrd<T2>,
{
    two.contains(&one.start) || two.contains(&one.end)
}

pub trait Utf16Len {
    /// Returns a count of utf16 code units in the string
    ///
    /// <https://core.telegram.org/api/entities#computing-entity-length>
    fn utf16_codeunits(&self) -> usize;
}

impl<T: AsRef<str>> Utf16Len for T {
    fn utf16_codeunits(&self) -> usize {
        // self.as_ref().chars().map(|c| c.len_utf16()).sum::<usize>() as i64
        let mut len = 0;

        for byte in self.as_ref().bytes() {
            // if byte does not start with 0b10
            if (byte & 0xc0) != 0x80 {
                // if byte starts with 0b11110 (i.e. marks the beginning of a 32-bit UTF-8 code unit)
                if byte >= 0xf0 {
                    len += 2;
                } else {
                    len += 1;
                }
            }
        }

        len
    }
}

#[derive(Debug, Clone)]
pub struct FormattedText {
    text: String,
    /// Length in utf-16 codeunits
    len_utf16: i64,
    entities: Vec<MessageEntity>,

    /// Ignore trailing and preceding whitespace chars when calculating entities' length
    pub trim_spaces: bool,

    /// Uses offsets from last pushed text for all new ones and ignores new text content while the flag is set.
    ///
    /// This is needed for stacking entities for the text chunk that was last added
    pub use_last_offsets: bool,
    /// Last entity offset, used for ulo-mode
    last_ent_offset: i64,
    /// Last entity offset, used for ulo-mode
    last_ent_len: i64,
}

impl FormattedText {
    pub const fn empty() -> Self {
        Self {
            text: String::new(),
            len_utf16: 0,
            entities: Vec::new(),
            trim_spaces: true,
            use_last_offsets: false,
            last_ent_offset: 0,
            last_ent_len: 0,
        }
    }

    pub const fn new() -> Self {
        Self::empty()
    }

    pub fn with_text(text: impl Into<String>, entities: impl Into<Vec<MessageEntity>>) -> Self {
        let text = text.into();
        let len = text.utf16_codeunits() as i64;

        Self {
            text,
            len_utf16: len,
            entities: entities.into(),
            trim_spaces: true,
            use_last_offsets: false,
            last_ent_offset: 0,
            last_ent_len: len,
        }
    }

    pub fn clear(&mut self) -> &mut Self {
        self.text.clear();
        self.entities.clear();

        self.len_utf16 = 0;
        self.last_ent_len = 0;
        self.last_ent_offset = 0;

        self
    }

    #[must_use]
    pub fn slice(&self, range: impl Into<Range<usize>>) -> Self {
        let mut range: Range<usize> = range.into();
        range.end = std::cmp::min(range.end, self.len_utf16 as usize);
        range.start = std::cmp::max(range.start, 0);

        let new_text = self.text[range.clone()].to_string();

        let mut new_entities = self
            .entities
            .iter()
            .filter(|ent| {
                ranges_intersect(
                    ent.offset..ent.offset + ent.length,
                    range.start as i64..range.end as i64,
                )
                // TODO: убедиться что похуй на бот команды и всякие хештеги
                // && ent.type_ != MessageEntityType::BotCommand
            })
            .cloned()
            .collect::<Vec<_>>();

        for ent in &mut new_entities {
            let offset = std::cmp::max(ent.offset, range.start as i64);
            let end = std::cmp::min(ent.offset + ent.length, range.end as i64);

            ent.offset = offset - range.start as i64;
            ent.length = end - offset;
        }

        Self::with_text(new_text, new_entities)
    }

    /// Concats `other` to this instance
    pub fn concat(&mut self, other: impl Into<Self>) -> &mut Self {
        let other: Self = other.into();

        let added_entities = other.entities.into_iter().map(|mut ent| {
            ent.offset += self.len_utf16;
            ent
        });

        self.last_ent_offset = self.len_utf16;
        self.last_ent_len = other.len_utf16;

        self.entities.extend(added_entities);
        self.text.push_str(&other.text);
        self.len_utf16 += other.len_utf16;

        self
    }

    pub const fn is_empty(&self) -> bool {
        self.len_utf16 == 0
    }

    pub fn len(&self) -> usize {
        self.text.len()
    }

    /// Length in utf-16 codeunits
    pub const fn len_utf16(&self) -> usize {
        self.len_utf16 as usize
    }

    pub const fn get_entities(&self) -> &Vec<MessageEntity> {
        &self.entities
    }

    pub const fn get_text(&self) -> &String {
        &self.text
    }

    /// Ignore trailing and preceding whitespace chars when calculating entities' length
    pub fn trim_spaces(&mut self, trim: bool) -> &mut Self {
        self.trim_spaces = trim;
        self
    }

    /// Uses offsets from last pushed text for all new ones and ignores new text content while the flag is set.
    pub fn ulo(&mut self, use_last_offsets: bool) -> &mut Self {
        self.use_last_offsets = use_last_offsets;
        self
    }

    pub const fn is_ulo(&self) -> bool {
        self.use_last_offsets
    }

    /// Calculates text length, entity lenght and offset in utf-16 codeunits needed to wrap provided text
    fn calc_entity_len_offset(&self, text: &str) -> (i64, i64, i64) {
        let text_len = text.utf16_codeunits() as i64;

        let entity_offset;
        let entity_len = if self.trim_spaces {
            let l_trim = text.trim_start();
            let l_trim_len = l_trim.utf16_codeunits() as i64;

            entity_offset = self.len_utf16 + (text_len - l_trim_len);
            l_trim.trim_end().utf16_codeunits() as i64
        } else {
            entity_offset = self.len_utf16;
            text_len
        };

        (text_len, entity_offset, entity_len)
    }

    fn push_entity_extended(
        &mut self,
        text: impl AsRef<str>,
        entity_type: MessageEntityType,
        url: impl Into<Option<String>>,
        user: impl Into<Option<User>>,
        pre_lang: impl Into<Option<String>>,
        custom_emoji_id: impl Into<Option<String>>,
    ) -> &mut Self {
        if self.use_last_offsets {
            let entity = MessageEntity {
                type_: entity_type,
                offset: self.last_ent_offset,
                length: self.last_ent_len,
                url: url.into(),
                user: user.into(),
                language: pre_lang.into(),
                custom_emoji_id: custom_emoji_id.into(),
            };

            self.entities.push(entity);
        } else {
            let text = text.as_ref();
            let (text_len, entity_offset, entity_len) = self.calc_entity_len_offset(text);

            let entity = MessageEntity {
                type_: entity_type,
                offset: entity_offset,
                length: entity_len,
                url: url.into(),
                user: user.into(),
                language: pre_lang.into(),
                custom_emoji_id: custom_emoji_id.into(),
            };

            self.last_ent_offset = entity_offset;
            self.last_ent_len = entity_len;

            self.entities.push(entity);
            self.text.push_str(text);
            self.len_utf16 += text_len;
        }

        self
    }

    fn push_entity_simple(
        &mut self,
        text: impl AsRef<str>,
        entity_type: MessageEntityType,
    ) -> &mut Self {
        if self.use_last_offsets {
            let entity = MessageEntity {
                type_: entity_type,
                offset: self.last_ent_offset,
                length: self.last_ent_len,
                ..Default::default()
            };

            self.entities.push(entity);
        } else {
            let text = text.as_ref();
            let (text_len, entity_offset, entity_len) = self.calc_entity_len_offset(text);

            let entity = MessageEntity {
                type_: entity_type,
                offset: entity_offset,
                length: entity_len,
                ..Default::default()
            };

            self.last_ent_offset = entity_offset;
            self.last_ent_len = entity_len;

            self.entities.push(entity);
            self.text.push_str(text);
            self.len_utf16 += text_len;
        }

        self
    }

    pub fn add_entity_uncheked(&mut self, entity: MessageEntity) -> &mut Self {
        self.entities.push(entity);
        self
    }

    pub fn entities(
        &mut self,
        text: impl AsRef<str>,
        entity_types: impl IntoIterator<Item = MessageEntityType>,
    ) -> &mut Self {
        if self.use_last_offsets {
            let entities = entity_types.into_iter().map(|t| MessageEntity {
                type_: t,
                offset: self.last_ent_offset,
                length: self.last_ent_len,
                ..Default::default()
            });
            self.entities.extend(entities);
            self
        } else {
            let text = text.as_ref();
            let (text_len, entity_offset, entity_len) = self.calc_entity_len_offset(text);

            let entities = entity_types.into_iter().map(|t| MessageEntity {
                type_: t,
                offset: entity_offset,
                length: entity_len,
                ..Default::default()
            });

            self.last_ent_offset = entity_offset;
            self.last_ent_len = entity_len;

            self.entities.extend(entities);
            self.text.push_str(text);
            self.len_utf16 += text_len;
            self
        }
    }

    pub fn text(&mut self, text: impl Display) -> &mut Self {
        let text_ref = text.to_string();

        let (text_len, entity_offset, entity_len) = self.calc_entity_len_offset(&text_ref);

        if !self.use_last_offsets {
            self.last_ent_offset = entity_offset;
            self.last_ent_len = entity_len;
        }

        self.text.push_str(&text_ref);
        self.len_utf16 += text_len;
        self
    }

    pub fn nl(&mut self) -> &mut Self {
        // newlines don't count in entity borders, so no special handling for
        // self.use_last_entities_offset

        self.text.push('\n');
        self.len_utf16 += 1;
        self
    }

    pub fn bold(&mut self, text: impl AsRef<str>) -> &mut Self {
        self.push_entity_simple(text, MessageEntityType::Bold)
    }

    pub fn italic(&mut self, text: impl AsRef<str>) -> &mut Self {
        self.push_entity_simple(text, MessageEntityType::Italic)
    }

    pub fn strikethrough(&mut self, text: impl AsRef<str>) -> &mut Self {
        self.push_entity_simple(text, MessageEntityType::Strikethrough)
    }

    pub fn underline(&mut self, text: impl AsRef<str>) -> &mut Self {
        self.push_entity_simple(text, MessageEntityType::Underline)
    }

    pub fn spoiler(&mut self, text: impl AsRef<str>) -> &mut Self {
        self.push_entity_simple(text, MessageEntityType::Spoiler)
    }

    pub fn blockquote(&mut self, text: impl AsRef<str>) -> &mut Self {
        self.push_entity_simple(text, MessageEntityType::Blockquote)
    }

    pub fn expandable_blockquote(&mut self, text: impl AsRef<str>) -> &mut Self {
        self.push_entity_simple(text, MessageEntityType::ExpandableBlockquote)
    }

    pub fn monowidth(&mut self, text: impl AsRef<str>) -> &mut Self {
        self.code(text)
    }

    pub fn code(&mut self, text: impl AsRef<str>) -> &mut Self {
        self.push_entity_simple(text, MessageEntityType::Code)
    }

    pub fn pre(&mut self, text: impl AsRef<str>) -> &mut Self {
        self.code_block(text)
    }

    pub fn url(&mut self, text: impl AsRef<str>, url: impl Into<String>) -> &mut Self {
        self.push_entity_extended(
            text,
            MessageEntityType::TextLink,
            Some(url.into()),
            None,
            None,
            None,
        )
    }

    pub fn mention_user(&mut self, text: impl AsRef<str>, user_id: impl Into<i64>) -> &mut Self {
        let user_id = user_id.into();

        if user_id > 0 {
            self.push_entity_extended(
                text,
                MessageEntityType::TextMention,
                None,
                Some(User {
                    id: user_id,
                    ..Default::default()
                }),
                None,
                None,
            )
        // Attempt to handle user error...
        } else if user_id < -1000000000000 {
            self.url(text, format!("https://t.me/c/{}", -user_id - 1000000000000))
        } else {
            self
        }
    }

    pub fn mention(&mut self, mention: &impl FormatMention) -> &mut Self {
        mention.mention(self)
    }

    pub fn code_block(&mut self, text: impl AsRef<str>) -> &mut Self {
        self.push_entity_simple(text, MessageEntityType::Pre)
    }

    pub fn code_block_in(
        &mut self,
        text: impl Into<String>,
        language: impl Into<String>,
    ) -> &mut Self {
        self.push_entity_extended(
            text.into(),
            MessageEntityType::Pre,
            None,
            None,
            Some(language.into().to_lowercase()),
            None,
        )
    }

    pub fn custom_emoji(
        &mut self,
        text: impl Into<String>,
        custom_emoji_id: impl Into<String>,
    ) -> &mut Self {
        self.push_entity_extended(
            text.into(),
            MessageEntityType::CustomEmoji,
            None,
            None,
            None,
            Some(custom_emoji_id.into()),
        )
    }

    pub fn build(self) -> (String, Vec<MessageEntity>) {
        (self.text, self.entities)
    }
}

impl Default for FormattedText {
    fn default() -> Self {
        Self::empty()
    }
}

impl PartialEq for FormattedText {
    fn eq(&self, other: &Self) -> bool {
        self.text == other.text
            && self.len_utf16 == other.len_utf16
            && self.entities == other.entities
    }
}

impl Display for FormattedText {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.text)
    }
}

impl From<String> for FormattedText {
    fn from(value: String) -> Self {
        let len = value.utf16_codeunits() as i64;
        Self {
            text: value,
            len_utf16: len,

            trim_spaces: true,
            ..Default::default()
        }
    }
}

impl From<&str> for FormattedText {
    fn from(value: &str) -> Self {
        let len = value.utf16_codeunits() as i64;
        Self {
            text: value.to_owned(),
            len_utf16: len,

            trim_spaces: true,
            ..Default::default()
        }
    }
}

impl<Item: Into<Self>> FromIterator<Item> for FormattedText {
    fn from_iter<T: IntoIterator<Item = Item>>(iter: T) -> Self {
        let mut first = Self::empty();

        for ft in iter {
            first.concat(ft);
        }

        first
    }
}

pub trait JoinFormatted {
    fn join_formatted<Separator: Into<FormattedText> + Clone>(
        self,
        sep: Separator,
    ) -> FormattedText;
}

impl<Iter: IntoIterator<Item = impl Into<FormattedText>>> JoinFormatted for Iter {
    fn join_formatted<Separator: Into<FormattedText> + Clone>(
        self,
        sep: Separator,
    ) -> FormattedText {
        let mut iter = self.into_iter();

        let mut first = if let Some(v) = iter.next() {
            v.into()
        } else {
            return FormattedText::empty();
        };

        let sep = if let Some(second) = iter.next() {
            let sep = sep;
            first.concat(sep.clone());
            first.concat(second);
            sep
        } else {
            return first;
        };

        for next in iter {
            first.concat(sep.clone());
            first.concat(next);
        }

        first
    }
}