chat-system 0.1.3

A multi-protocol async chat crate — single interface for IRC, Matrix, Discord, Telegram, Slack, Signal, WhatsApp, and more
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
//! Markdown-to-platform conversion utilities.
//!
//! Functions for converting standard Markdown to platform-specific formats.

/// Telegram message character limit.
pub const TELEGRAM_MAX_LEN: usize = 4096;
/// Slack message character limit.
pub const SLACK_MAX_LEN: usize = 40_000;

fn escape_html(s: impl AsRef<str>) -> String {
    let s = s.as_ref();
    let mut out = String::with_capacity(s.len());
    for ch in s.chars() {
        match ch {
            '&' => out.push_str("&amp;"),
            '<' => out.push_str("&lt;"),
            '>' => out.push_str("&gt;"),
            c => out.push(c),
        }
    }
    out
}

/// Convert Markdown to Telegram HTML.
///
/// Telegram supports `<b>`, `<i>`, `<s>`, `<code>`, `<pre>`, `<a href="">`.
pub fn markdown_to_telegram_html(md: impl AsRef<str>) -> String {
    let escaped = escape_html(md);
    let mut out = String::with_capacity(escaped.len() + 64);
    let mut i = 0;

    while i < escaped.len() {
        // Fenced code block: ```
        if escaped.get(i..i + 3) == Some("```") {
            i += 3;
            let start = i;
            let mut code_end = None;
            let mut j = i;
            while j <= escaped.len().saturating_sub(3) {
                if escaped.get(j..j + 3) == Some("```") {
                    code_end = Some(j);
                    break;
                }
                // advance by one char
                let ch_len = escaped[j..].chars().next().map_or(1, |c| c.len_utf8());
                j += ch_len;
            }
            if let Some(end) = code_end {
                let content = &escaped[start..end];
                let (lang, code) = if let Some(nl) = content.find('\n') {
                    let maybe_lang = content[..nl].trim();
                    if !maybe_lang.is_empty() && !maybe_lang.contains(' ') {
                        (maybe_lang, &content[nl + 1..])
                    } else {
                        ("", content)
                    }
                } else {
                    ("", content)
                };
                if lang.is_empty() {
                    out.push_str("<pre>");
                    out.push_str(code);
                    out.push_str("</pre>");
                } else {
                    out.push_str("<pre><code class=\"language-");
                    out.push_str(lang);
                    out.push_str("\">");
                    out.push_str(code);
                    out.push_str("</code></pre>");
                }
                i = end + 3;
            } else {
                out.push_str("```");
            }
            continue;
        }

        // Inline code: `
        if escaped.get(i..i + 1) == Some("`") {
            i += 1;
            let start = i;
            while i < escaped.len() && escaped.get(i..i + 1) != Some("`") {
                let ch_len = escaped[i..].chars().next().map_or(1, |c| c.len_utf8());
                i += ch_len;
            }
            out.push_str("<code>");
            out.push_str(&escaped[start..i]);
            out.push_str("</code>");
            if i < escaped.len() {
                i += 1; // skip closing `
            }
            continue;
        }

        // Bold: **
        if escaped.get(i..i + 2) == Some("**") {
            i += 2;
            let start = i;
            if let Some(rel) = escaped[i..].find("**") {
                let end = i + rel;
                out.push_str("<b>");
                out.push_str(&escaped[start..end]);
                out.push_str("</b>");
                i = end + 2;
            } else {
                out.push_str("**");
            }
            continue;
        }

        // Strikethrough: ~~
        if escaped.get(i..i + 2) == Some("~~") {
            i += 2;
            let start = i;
            if let Some(rel) = escaped[i..].find("~~") {
                let end = i + rel;
                out.push_str("<s>");
                out.push_str(&escaped[start..end]);
                out.push_str("</s>");
                i = end + 2;
            } else {
                out.push_str("~~");
            }
            continue;
        }

        // Italic: * (single)
        if escaped.get(i..i + 1) == Some("*") {
            i += 1;
            let start = i;
            if let Some(rel) = escaped[i..].find('*') {
                let end = i + rel;
                out.push_str("<i>");
                out.push_str(&escaped[start..end]);
                out.push_str("</i>");
                i = end + 1;
            } else {
                out.push('*');
            }
            continue;
        }

        // Italic: _text_
        if escaped.get(i..i + 1) == Some("_") {
            i += 1;
            let start = i;
            if let Some(rel) = escaped[i..].find('_') {
                let end = i + rel;
                out.push_str("<i>");
                out.push_str(&escaped[start..end]);
                out.push_str("</i>");
                i = end + 1;
            } else {
                out.push('_');
            }
            continue;
        }

        // Link: [text](url)
        if escaped.get(i..i + 1) == Some("[") {
            if let Some(close_bracket_rel) = escaped[i..].find("](") {
                let text_end = i + close_bracket_rel;
                let url_start = text_end + 2;
                if let Some(close_paren_rel) = escaped[url_start..].find(')') {
                    let url_end = url_start + close_paren_rel;
                    let link_text = &escaped[i + 1..text_end];
                    let url = &escaped[url_start..url_end];
                    out.push_str("<a href=\"");
                    out.push_str(url);
                    out.push_str("\">");
                    out.push_str(link_text);
                    out.push_str("</a>");
                    i = url_end + 1;
                    continue;
                }
            }
        }

        // Regular char
        let ch = escaped[i..].chars().next().unwrap_or(' ');
        out.push(ch);
        i += ch.len_utf8();
    }

    out
}

/// Convert Markdown to Slack mrkdwn format.
pub fn markdown_to_slack(text: impl AsRef<str>) -> String {
    let text = text.as_ref();
    let mut out = String::with_capacity(text.len());
    let mut i = 0;
    let bytes = text.as_bytes();
    let len = text.len();

    while i < len {
        // Bold: **text** → *text*
        if text.get(i..i + 2) == Some("**") {
            i += 2;
            let start = i;
            if let Some(rel) = text[i..].find("**") {
                let end = i + rel;
                out.push('*');
                out.push_str(&text[start..end]);
                out.push('*');
                i = end + 2;
            } else {
                out.push_str("**");
            }
            continue;
        }

        // Strikethrough: ~~text~~ → ~text~
        if text.get(i..i + 2) == Some("~~") {
            i += 2;
            let start = i;
            if let Some(rel) = text[i..].find("~~") {
                let end = i + rel;
                out.push('~');
                out.push_str(&text[start..end]);
                out.push('~');
                i = end + 2;
            } else {
                out.push_str("~~");
            }
            continue;
        }

        // Link: [text](url) → <url|text>
        if text.get(i..i + 1) == Some("[") {
            if let Some(close_bracket_rel) = text[i..].find("](") {
                let text_end = i + close_bracket_rel;
                let url_start = text_end + 2;
                if let Some(close_paren_rel) = text[url_start..].find(')') {
                    let url_end = url_start + close_paren_rel;
                    let link_text = &text[i + 1..text_end];
                    let url = &text[url_start..url_end];
                    out.push('<');
                    out.push_str(url);
                    out.push('|');
                    out.push_str(link_text);
                    out.push('>');
                    i = url_end + 1;
                    continue;
                }
            }
        }

        // Header: # at line start → *Header*
        if (i == 0 || bytes.get(i.saturating_sub(1)) == Some(&b'\n'))
            && text.get(i..i + 1) == Some("#")
        {
            // Count heading level (we just flatten to bold)
            let mut hashes = 0;
            let mut j = i;
            while text.get(j..j + 1) == Some("#") {
                hashes += 1;
                j += 1;
            }
            if hashes > 0 && text.get(j..j + 1) == Some(" ") {
                j += 1; // skip space
                let line_end = text[j..].find('\n').map_or(text.len(), |p| j + p);
                out.push('*');
                out.push_str(&text[j..line_end]);
                out.push('*');
                i = line_end;
                continue;
            }
        }

        // Regular char
        let ch = text[i..].chars().next().unwrap_or(' ');
        out.push(ch);
        i += ch.len_utf8();
    }

    out
}

/// Find the largest char boundary at or before `pos` in `s`.
fn floor_char_boundary(s: &str, pos: usize) -> usize {
    let mut e = pos.min(s.len());
    while e > 0 && !s.is_char_boundary(e) {
        e -= 1;
    }
    e
}

/// Convert markdown to Telegram HTML then split into chunks of at most `max_len` bytes.
pub fn chunk_markdown_html(md: impl AsRef<str>, max_len: usize) -> Vec<String> {
    let html = markdown_to_telegram_html(md);
    if html.len() <= max_len {
        return vec![html];
    }

    let mut chunks = Vec::new();
    let mut current = String::new();

    for line in html.split('\n') {
        let with_newline = if current.is_empty() {
            line.to_string()
        } else {
            format!("\n{}", line)
        };

        if current.len() + with_newline.len() > max_len {
            if !current.is_empty() {
                chunks.push(current.clone());
                current = line.to_string();
            } else {
                // Single line exceeds max_len, force split
                let mut pos = 0;
                while pos < line.len() {
                    let end = floor_char_boundary(line, pos + max_len);
                    let end = if end <= pos { pos + 1 } else { end };
                    let end = end.min(line.len());
                    chunks.push(line[pos..end].to_string());
                    pos = end;
                }
            }
        } else {
            current.push_str(&with_newline);
        }
    }

    if !current.is_empty() {
        chunks.push(current);
    }

    chunks
}

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

    #[test]
    fn test_escape_html() {
        assert_eq!(escape_html("a & b"), "a &amp; b");
        assert_eq!(escape_html("<tag>"), "&lt;tag&gt;");
    }

    #[test]
    fn test_telegram_bold() {
        let result = markdown_to_telegram_html("**hello**");
        assert_eq!(result, "<b>hello</b>");
    }

    #[test]
    fn test_telegram_italic_star() {
        let result = markdown_to_telegram_html("*hello*");
        assert_eq!(result, "<i>hello</i>");
    }

    #[test]
    fn test_telegram_strike() {
        let result = markdown_to_telegram_html("~~hello~~");
        assert_eq!(result, "<s>hello</s>");
    }

    #[test]
    fn test_telegram_inline_code() {
        let result = markdown_to_telegram_html("`code`");
        assert_eq!(result, "<code>code</code>");
    }

    #[test]
    fn test_telegram_link() {
        let result = markdown_to_telegram_html("[click](https://example.com)");
        assert_eq!(result, "<a href=\"https://example.com\">click</a>");
    }

    #[test]
    fn test_telegram_html_escape() {
        let result = markdown_to_telegram_html("a & b");
        assert!(result.contains("&amp;"));
    }

    #[test]
    fn test_slack_bold() {
        assert_eq!(markdown_to_slack("**hello**"), "*hello*");
    }

    #[test]
    fn test_slack_strike() {
        assert_eq!(markdown_to_slack("~~hello~~"), "~hello~");
    }

    #[test]
    fn test_slack_link() {
        assert_eq!(
            markdown_to_slack("[click](https://example.com)"),
            "<https://example.com|click>"
        );
    }

    #[test]
    fn test_slack_header() {
        assert_eq!(markdown_to_slack("# Hello"), "*Hello*");
    }

    #[test]
    fn test_chunk_small() {
        let chunks = chunk_markdown_html("hello", 100);
        assert_eq!(chunks.len(), 1);
        assert_eq!(chunks[0], "hello");
    }

    #[test]
    fn test_chunk_split() {
        let long_md = "line1\nline2\nline3";
        let chunks = chunk_markdown_html(long_md, 8);
        assert!(chunks.len() > 1);
        for chunk in &chunks {
            assert!(chunk.len() <= 8);
        }
    }
}