ferogram-parsers 0.6.3

Telegram HTML and Markdown entity parsers for ferogram
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
// Copyright (c) Ankit Chaubey <ankitchaubey.dev@gmail.com>
//
// ferogram: async Telegram MTProto client in Rust
// https://github.com/ankit-chaubey/ferogram
//
// Licensed under either the MIT License or the Apache License 2.0.
// See the LICENSE-MIT or LICENSE-APACHE file in this repository:
// https://github.com/ankit-chaubey/ferogram
//
// Feel free to use, modify, and share this code.
// Please keep this notice when redistributing.

use ferogram_tl_types as tl;

use crate::rich_common::*;

pub fn parse_rich_html(html: &str) -> Vec<tl::enums::PageBlock> {
    RichHtmlParser::new(html).parse()
}

struct RichHtmlParser {
    html: String,
    pos: usize,
}

impl RichHtmlParser {
    fn new(html: &str) -> Self {
        Self {
            html: html.to_string(),
            pos: 0,
        }
    }

    fn remaining(&self) -> &str {
        &self.html[self.pos..]
    }

    fn skip_whitespace(&mut self) {
        while self.pos < self.html.len() {
            let c = self.html.as_bytes()[self.pos];
            if c.is_ascii_whitespace() {
                self.pos += 1;
            } else {
                break;
            }
        }
    }

    fn parse(mut self) -> Vec<tl::enums::PageBlock> {
        let mut blocks = Vec::new();
        loop {
            self.skip_whitespace();
            if self.pos >= self.html.len() {
                break;
            }
            if self.remaining().starts_with('<')
                && let Some(block) = self.try_parse_block_tag()
            {
                blocks.extend(block);
                continue;
            }
            // Text content at top level → paragraph
            if let Some(para) = self.parse_text_paragraph() {
                blocks.push(para);
            }
        }
        blocks
    }

    fn try_parse_block_tag(&mut self) -> Option<Vec<tl::enums::PageBlock>> {
        let rem = self.remaining();
        let lower = rem.to_ascii_lowercase();

        macro_rules! heading {
            ($tag:literal, $level:expr) => {
                if lower.starts_with(concat!("<", $tag, ">"))
                    || lower.starts_with(concat!("<", $tag, " "))
                {
                    let body = self.consume_tag($tag)?;
                    return Some(vec![heading_block($level, parse_rich_html_inline(&body))]);
                }
            };
        }

        heading!("h1", 1);
        heading!("h2", 2);
        heading!("h3", 3);
        heading!("h4", 4);
        heading!("h5", 5);
        heading!("h6", 6);

        if lower.starts_with("<p>") || lower.starts_with("<p ") {
            let body = self.consume_tag("p")?;
            return Some(vec![tl::enums::PageBlock::Paragraph(
                tl::types::PageBlockParagraph {
                    text: parse_rich_html_inline(&body),
                },
            )]);
        }

        if lower.starts_with("<pre>") || lower.starts_with("<pre>") || lower.starts_with("<pre ") {
            let body = self.consume_tag("pre")?;
            let (lang, code) = extract_pre_content_from_body(&body);
            return Some(vec![tl::enums::PageBlock::Preformatted(
                tl::types::PageBlockPreformatted {
                    text: rt_plain(code),
                    language: lang,
                },
            )]);
        }

        if lower.starts_with("<footer>") || lower.starts_with("<footer ") {
            let body = self.consume_tag("footer")?;
            return Some(vec![tl::enums::PageBlock::Footer(
                tl::types::PageBlockFooter {
                    text: parse_rich_html_inline(&body),
                },
            )]);
        }

        if lower.starts_with("<hr") {
            self.consume_until('>');
            self.pos += 1;
            return Some(vec![tl::enums::PageBlock::Divider]);
        }

        if lower.starts_with("<blockquote") {
            let body = self.consume_tag("blockquote")?;
            let (text, credit) = split_cite(&body);
            return Some(vec![tl::enums::PageBlock::Blockquote(
                tl::types::PageBlockBlockquote {
                    text: parse_rich_html_inline(&text),
                    caption: parse_rich_html_inline(&credit),
                },
            )]);
        }

        if lower.starts_with("<aside") {
            let body = self.consume_tag("aside")?;
            let (text, credit) = split_cite(&body);
            return Some(vec![tl::enums::PageBlock::Pullquote(
                tl::types::PageBlockPullquote {
                    text: parse_rich_html_inline(&text),
                    caption: parse_rich_html_inline(&credit),
                },
            )]);
        }

        if lower.starts_with("<ul") {
            let body = self.consume_tag("ul")?;
            let items = parse_html_list_items(&body, false);
            return Some(vec![tl::enums::PageBlock::List(tl::types::PageBlockList {
                items,
            })]);
        }

        if lower.starts_with("<ol") {
            let tag_open = rem.split('>').next().unwrap_or("").to_string();
            let (_, attrs) = parse_tag(tag_open.trim_start_matches('<'));
            let start: Option<i32> = attrs
                .iter()
                .find(|(k, _)| k == "start")
                .and_then(|(_, v)| v.parse().ok());
            let reversed = attrs.iter().any(|(k, _)| k == "reversed");
            let ol_type: Option<String> = attrs
                .iter()
                .find(|(k, _)| k == "type")
                .map(|(_, v)| v.clone());
            let body = self.consume_tag("ol")?;
            let items = parse_html_ordered_list_items(&body, ol_type.as_deref());
            return Some(vec![tl::enums::PageBlock::OrderedList(
                tl::types::PageBlockOrderedList {
                    reversed,
                    items,
                    start,
                    r#type: ol_type,
                },
            )]);
        }

        if lower.starts_with("<table") {
            let tag_open = rem.split('>').next().unwrap_or("").to_string();
            let (_, attrs) = parse_tag(tag_open.trim_start_matches('<'));
            let bordered = attrs.iter().any(|(k, _)| k == "bordered");
            let striped = attrs.iter().any(|(k, _)| k == "striped");
            let body = self.consume_tag("table")?;
            let (title, rows) = parse_html_table(&body);
            return Some(vec![tl::enums::PageBlock::Table(
                tl::types::PageBlockTable {
                    bordered,
                    striped,
                    title,
                    rows,
                },
            )]);
        }

        if lower.starts_with("<details") {
            let is_open_hint = rem.to_ascii_lowercase().starts_with("<details open");
            let full = self.consume_tag("details")?;
            let is_open = is_open_hint || full.starts_with("open");
            let summary = extract_between(&full, "<summary>", "</summary>").unwrap_or_default();
            let body_start = full
                .find("</summary>")
                .map(|i| i + "</summary>".len())
                .unwrap_or(full.len());
            let inner = parse_rich_html(full[body_start..].trim());
            return Some(vec![tl::enums::PageBlock::Details(
                tl::types::PageBlockDetails {
                    open: is_open,
                    blocks: inner,
                    title: parse_rich_html_inline(&summary),
                },
            )]);
        }

        if lower.starts_with("<img ") {
            let tag_raw = self.consume_self_closing_tag();
            let (_, attrs) = parse_tag(&tag_raw);
            let src = attrs
                .iter()
                .find(|(k, _)| k == "src")
                .map(|(_, v)| v.clone())
                .unwrap_or_default();
            let spoiler = attrs.iter().any(|(k, _)| k == "tg-spoiler");
            if !src.is_empty() {
                return Some(vec![media_block(&src, empty_caption(), spoiler)]);
            }
            return Some(vec![]);
        }

        if lower.starts_with("<video ") {
            let tag_raw = self.consume_self_closing_or_pair("video");
            let (_, attrs) = parse_tag(&tag_raw);
            let src = attrs
                .iter()
                .find(|(k, _)| k == "src")
                .map(|(_, v)| v.clone())
                .unwrap_or_default();
            let spoiler = attrs.iter().any(|(k, _)| k == "tg-spoiler");
            if !src.is_empty() {
                return Some(vec![media_block(&src, empty_caption(), spoiler)]);
            }
            return Some(vec![]);
        }

        if lower.starts_with("<audio ") {
            let tag_raw = self.consume_self_closing_or_pair("audio");
            let (_, attrs) = parse_tag(&tag_raw);
            let src = attrs
                .iter()
                .find(|(k, _)| k == "src")
                .map(|(_, v)| v.clone())
                .unwrap_or_default();
            if !src.is_empty() {
                return Some(vec![media_block(&src, empty_caption(), false)]);
            }
            return Some(vec![]);
        }

        if lower.starts_with("<figure") {
            let body = self.consume_tag("figure")?;
            let caption_raw =
                extract_between(&body, "<figcaption>", "</figcaption>").unwrap_or_default();
            let (cap_t, cap_cr) = split_cite(&caption_raw);
            let cap = if cap_t.is_empty() {
                empty_caption()
            } else {
                caption_text_credit(
                    parse_rich_html_inline(&cap_t),
                    parse_rich_html_inline(&cap_cr),
                )
            };
            let spoiler = body.contains("tg-spoiler");

            if body.to_ascii_lowercase().contains("<tg-map") {
                let map_inner = extract_between(&body, "<tg-map", "/>").unwrap_or_default();
                let (_, attrs) = parse_tag(&format!("tg-map {map_inner}"));
                let lat: f64 = attrs
                    .iter()
                    .find(|(k, _)| k == "lat")
                    .and_then(|(_, v)| v.parse().ok())
                    .unwrap_or(0.0);
                let long: f64 = attrs
                    .iter()
                    .find(|(k, _)| k == "long")
                    .and_then(|(_, v)| v.parse().ok())
                    .unwrap_or(0.0);
                let zoom: i32 = attrs
                    .iter()
                    .find(|(k, _)| k == "zoom")
                    .and_then(|(_, v)| v.parse().ok())
                    .unwrap_or(15);
                return Some(vec![tl::enums::PageBlock::Map(tl::types::PageBlockMap {
                    geo: tl::enums::GeoPoint::GeoPoint(tl::types::GeoPoint {
                        lat,
                        long,
                        access_hash: 0,
                        accuracy_radius: None,
                    }),
                    zoom,
                    w: 400,
                    h: 300,
                    caption: cap,
                })]);
            }

            let src = extract_src_from_figure(&body);
            if let Some(url) = src {
                return Some(vec![media_block(&url, cap, spoiler)]);
            }
            return Some(vec![]);
        }

        if lower.starts_with("<tg-collage") {
            let body = self.consume_tag("tg-collage")?;
            let (items, cap) = extract_collage_items(&body);
            return Some(vec![tl::enums::PageBlock::Collage(
                tl::types::PageBlockCollage {
                    items,
                    caption: cap.unwrap_or_else(empty_caption),
                },
            )]);
        }

        if lower.starts_with("<tg-slideshow") {
            let body = self.consume_tag("tg-slideshow")?;
            let (items, cap) = extract_collage_items(&body);
            return Some(vec![tl::enums::PageBlock::Slideshow(
                tl::types::PageBlockSlideshow {
                    items,
                    caption: cap.unwrap_or_else(empty_caption),
                },
            )]);
        }

        if lower.starts_with("<tg-map") {
            let tag_raw = self.consume_self_closing_tag();
            let (_, attrs) = parse_tag(&tag_raw);
            let lat: f64 = attrs
                .iter()
                .find(|(k, _)| k == "lat")
                .and_then(|(_, v)| v.parse().ok())
                .unwrap_or(0.0);
            let long: f64 = attrs
                .iter()
                .find(|(k, _)| k == "long")
                .and_then(|(_, v)| v.parse().ok())
                .unwrap_or(0.0);
            let zoom: i32 = attrs
                .iter()
                .find(|(k, _)| k == "zoom")
                .and_then(|(_, v)| v.parse().ok())
                .unwrap_or(15);
            return Some(vec![tl::enums::PageBlock::Map(tl::types::PageBlockMap {
                geo: tl::enums::GeoPoint::GeoPoint(tl::types::GeoPoint {
                    lat,
                    long,
                    access_hash: 0,
                    accuracy_radius: None,
                }),
                zoom,
                w: 400,
                h: 300,
                caption: empty_caption(),
            })]);
        }

        if lower.starts_with("<tg-math-block") {
            let body = self.consume_tag("tg-math-block")?;
            return Some(vec![tl::enums::PageBlock::Math(tl::types::PageBlockMath {
                source: body,
            })]);
        }

        if lower.starts_with("<a ") && lower.contains("name=") {
            // Standalone anchor: <a name="id"></a>
            let tag_raw = self.consume_self_closing_or_pair("a");
            let (_, attrs) = parse_tag(&tag_raw);
            let name = attrs
                .iter()
                .find(|(k, _)| k == "name")
                .map(|(_, v)| v.clone())
                .unwrap_or_default();
            if !name.is_empty() {
                return Some(vec![tl::enums::PageBlock::Anchor(
                    tl::types::PageBlockAnchor { name },
                )]);
            }
            return Some(vec![]);
        }

        // Skip unknown/comment/doctype tags
        if lower.starts_with("<!--") || lower.starts_with("<!") {
            self.consume_until('>');
            self.pos = (self.pos + 1).min(self.html.len());
            return Some(vec![]);
        }

        None
    }

    fn consume_tag(&mut self, tag: &str) -> Option<String> {
        // Move past the opening tag
        let open_end = self.remaining().find('>')?;
        self.pos += open_end + 1;
        let close_tag = format!("</{tag}>");
        let close_pos = self.remaining().to_ascii_lowercase().find(&close_tag)?;
        let body = self.remaining()[..close_pos].to_string();
        self.pos += close_pos + close_tag.len();
        Some(body)
    }

    fn consume_self_closing_tag(&mut self) -> String {
        let end = self.remaining().find('>').unwrap_or(self.remaining().len());
        let tag_raw = self.remaining()[1..end]
            .trim_end_matches('/')
            .trim()
            .to_string();
        self.pos += end + 1;
        tag_raw
    }

    fn consume_self_closing_or_pair(&mut self, tag: &str) -> String {
        let rem = self.remaining();
        // Check if it's self-closing or has a close tag in the same stretch
        let open_end = rem.find('>').unwrap_or(rem.len());
        let is_self = rem[..open_end].ends_with('/');
        let tag_raw = rem[1..open_end].trim_end_matches('/').trim().to_string();
        self.pos += open_end + 1;
        if !is_self {
            let close_tag = format!("</{tag}>");
            if let Some(end) = self.remaining().to_ascii_lowercase().find(&close_tag) {
                self.pos += end + close_tag.len();
            }
        }
        tag_raw
    }

    fn consume_until(&mut self, ch: char) {
        while self.pos < self.html.len() {
            if self.html.as_bytes()[self.pos] == ch as u8 {
                break;
            }
            self.pos += 1;
        }
    }

    fn parse_text_paragraph(&mut self) -> Option<tl::enums::PageBlock> {
        let start = self.pos;
        while self.pos < self.html.len() {
            let rem = self.remaining();
            if rem.starts_with('<') {
                // Peek at the tag: if it's a block tag, stop
                let lower = rem.to_ascii_lowercase();
                let is_block = is_block_html_tag(&lower);
                if is_block {
                    break;
                }
                // Inline tag: include it as-is and continue
                let end = rem.find('>').unwrap_or(rem.len());
                self.pos += end + 1;
            } else {
                self.pos += 1;
            }
        }
        if self.pos == start {
            return None;
        }
        let text_raw = &self.html[start..self.pos];
        let decoded = decode_html_entities(text_raw);
        if decoded.trim().is_empty() {
            return None;
        }
        Some(tl::enums::PageBlock::Paragraph(
            tl::types::PageBlockParagraph {
                text: parse_rich_html_inline(&decoded),
            },
        ))
    }
}

/// Parse an HTML inline string into a `RichText` tree.
/// Handles all inline tags: b, strong, i, em, u, ins, s, del, strike,
/// code, mark, tg-spoiler, sub, sup, a, tg-emoji, tg-time, tg-math, tg-reference.
pub fn parse_rich_html_inline(html: &str) -> tl::enums::RichText {
    let chars: Vec<char> = html.chars().collect();
    let mut parts = Vec::new();
    let mut buf = String::new();
    let mut i = 0;
    let n = chars.len();

    macro_rules! flush {
        () => {
            if !buf.is_empty() {
                parts.push(rt_plain(decode_html_entities(&std::mem::take(&mut buf))));
            }
        };
    }

    while i < n {
        if chars[i] == '&' {
            // HTML entity: collect until `;`
            let mut j = i + 1;
            while j < n && chars[j] != ';' && chars[j] != ' ' {
                j += 1;
            }
            if j < n && chars[j] == ';' {
                let entity: String = chars[i..=j].iter().collect();
                buf.push_str(&decode_html_entities(&entity));
                i = j + 1;
                continue;
            }
        }

        if chars[i] != '<' {
            buf.push(chars[i]);
            i += 1;
            continue;
        }

        // Try to parse as inline HTML tag
        let remaining: String = chars[i..].iter().collect();
        if let Some((consumed, rt)) = try_parse_html_inline_tag(&chars, i, n) {
            flush!();
            parts.push(rt);
            i = consumed;
            continue;
        }

        // Not recognised - emit as text
        buf.push(chars[i]);
        i += 1;
        let _ = remaining;
    }
    flush!();
    rt_concat(parts)
}

fn extract_pre_content_from_body(body: &str) -> (String, String) {
    // <code class="language-X">…</code>
    let lo = body.to_ascii_lowercase();
    if lo.contains("<code") {
        let lang = extract_between(body, "class=\"language-", "\"").unwrap_or_default();
        let code_start = lo.find('>').map(|i| i + 1).unwrap_or(0);
        let code = extract_between(body, ">", "</code>")
            .or_else(|| {
                extract_between(body, "<code", "</code>").map(|c| {
                    let ci = c.find('>').map(|i| i + 1).unwrap_or(0);
                    c[ci..].to_string()
                })
            })
            .unwrap_or_else(|| body[code_start..].to_string());
        return (lang, decode_html_entities(&code));
    }
    (String::new(), decode_html_entities(body))
}