mbr-markdown-browser 0.5.1

A fast, featureful markdown viewer, browser, and (optional) static site generator
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
//! Media embedding detection and HTML generation for image syntax extensions.
//!
//! This module handles the `![caption](url)` markdown syntax when the URL points to
//! media files (video, audio, PDF) or embeddable content (YouTube).

use crate::audio::Audio;
use crate::vid::Vid;
use regex::Regex;
use std::borrow::Cow;
use std::sync::LazyLock;

const PDF_EMBED_HEIGHT: &str = "600px";

static EXTENSION_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(r"\.([0-9a-zA-Z]+)([?#].*)?$").expect("Invalid EXTENSION_RE regex pattern")
});

static YOUTUBE_RE: LazyLock<Regex> = LazyLock::new(|| {
    Regex::new(
        r"(?:youtube(?:-nocookie)?\.com/watch\?.*v=|youtu\.be/|youtube(?:-nocookie)?\.com/embed/|youtube(?:-nocookie)?\.com/v/)([a-zA-Z0-9_-]{11})",
    )
    .expect("Invalid YOUTUBE_RE regex pattern")
});

/// Represents different types of media that can be embedded via image syntax
#[derive(Debug, PartialEq)]
pub enum MediaEmbed {
    /// Video files (mp4, webm, etc.) - uses HTML5 video
    Video(Vid),
    /// Audio files (mp3, wav, etc.) - uses HTML5 audio
    Audio(Audio),
    /// YouTube videos - uses iframe embed
    YouTube {
        video_id: String,
        caption: Option<String>,
    },
    /// PDF documents - uses object tag with fallback link
    Pdf {
        url: String,
        caption: Option<String>,
    },
}

impl MediaEmbed {
    /// Create a MediaEmbed for bare URLs (no caption)
    ///
    /// This is used by the oembed system to detect media files from bare URLs
    /// in markdown text before attempting OpenGraph fetching.
    pub fn from_bare_url(url: &str) -> Option<Self> {
        Self::from_url_and_title(url, "")
    }

    /// Try to detect media type from URL and create appropriate embed
    ///
    /// Priority order:
    /// 1. YouTube URLs (checked first since they might not have extensions)
    /// 2. Video files by extension
    /// 3. Audio files by extension
    /// 4. PDF files by extension
    ///
    /// Returns None if the URL doesn't match any known media type
    pub fn from_url_and_title(url: &str, title: &str) -> Option<Self> {
        // Check YouTube first (doesn't rely on extension)
        if let Some(video_id) = Self::extract_youtube_id(url) {
            return Some(MediaEmbed::YouTube {
                video_id,
                caption: if title.is_empty() {
                    None
                } else {
                    Some(title.to_string())
                },
            });
        }

        // Check by extension
        if let Some(ext) = Self::extension_from_url(url) {
            let ext_lower = ext.to_lowercase();

            // Video extensions (handled by Vid)
            if let Some(vid) = Vid::from_url_and_title(url, title) {
                return Some(MediaEmbed::Video(vid));
            }

            // Audio extensions
            if let Some(audio) = Audio::from_url_and_title(url, title) {
                return Some(MediaEmbed::Audio(audio));
            }

            // PDF
            if ext_lower == "pdf" {
                return Some(MediaEmbed::Pdf {
                    url: url.to_string(),
                    caption: if title.is_empty() {
                        None
                    } else {
                        Some(title.to_string())
                    },
                });
            }
        }

        None
    }

    /// Generate opening HTML for the media embed
    ///
    /// - `open_only`: When true, leaves figcaption open for markdown parser to fill
    /// - `server_mode`: True in server/GUI mode, false in build/CLI mode
    /// - `transcode_enabled`: True when dynamic transcoding is enabled
    pub fn to_html(&self, open_only: bool, server_mode: bool, transcode_enabled: bool) -> String {
        match self {
            MediaEmbed::Video(vid) => vid.to_html(open_only, server_mode, transcode_enabled),
            MediaEmbed::Audio(audio) => audio.to_html(open_only),
            MediaEmbed::YouTube { video_id, caption } => {
                Self::youtube_to_html(video_id, caption.as_deref(), open_only)
            }
            MediaEmbed::Pdf { url, caption } => {
                Self::pdf_to_html(url, caption.as_deref(), open_only)
            }
        }
    }

    /// Generate closing HTML tags
    pub fn html_close(&self) -> String {
        match self {
            MediaEmbed::Video(_) => Vid::html_close(),
            MediaEmbed::Audio(_) => Audio::html_close().to_string(),
            MediaEmbed::YouTube { .. } | MediaEmbed::Pdf { .. } => {
                "</figcaption></figure>".to_string()
            }
        }
    }

    fn extract_youtube_id(url: &str) -> Option<String> {
        YOUTUBE_RE
            .captures(url)
            .and_then(|caps| caps.get(1))
            .map(|id| id.as_str().to_string())
    }

    fn extension_from_url(url: &str) -> Option<String> {
        EXTENSION_RE.captures(url).map(|cap| cap[1].to_string())
    }

    /// Escape a caption for HTML element-text context (`<figcaption>`).
    ///
    /// Captions come from the markdown link title, which pulldown-cmark hands
    /// over unescaped.
    fn escaped_caption(caption: Option<&str>) -> Cow<'_, str> {
        caption.map(html_escape::encode_text).unwrap_or_default()
    }

    fn youtube_to_html(video_id: &str, caption: Option<&str>, open_only: bool) -> String {
        format!(
            r#"
            <figure class="video-embed youtube-embed">
                <iframe
                    width="{yt_width}"
                    height="{yt_height}"
                    src="https://www.youtube-nocookie.com/embed/{video_id}"
                    title="YouTube video player"
                    frameborder="0"
                    allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share"
                    referrerpolicy="strict-origin-when-cross-origin"
                    allowfullscreen>
                </iframe>
                <figcaption>{caption}{close}"#,
            yt_width = crate::constants::YOUTUBE_EMBED_WIDTH,
            yt_height = crate::constants::YOUTUBE_EMBED_HEIGHT,
            video_id = html_escape::encode_double_quoted_attribute(video_id),
            caption = Self::escaped_caption(caption),
            close = if open_only {
                ""
            } else {
                "</figcaption></figure>"
            }
        )
    }

    fn pdf_to_html(url: &str, caption: Option<&str>, open_only: bool) -> String {
        // Graceful degradation: object tag with fallback download link
        // The data-pdf-url attribute allows JavaScript enhancement (e.g., PDF.js)
        //
        // The URL is the raw markdown link destination (pulldown-cmark does not
        // escape it, and neither does link_transform), so it must be escaped for
        // double-quoted attribute context or an `&` corrupts the output and a
        // `"` breaks out of the attribute entirely.
        let escaped_url = html_escape::encode_double_quoted_attribute(url);
        format!(
            r#"
            <figure class="pdf-embed" data-pdf-url="{url}">
                <object data="{url}" type="application/pdf" width="100%" height="{pdf_height}">
                    <p class="pdf-fallback">
                        PDF cannot be displayed inline.
                        <a href="{url}" download data-pdf-fallback>Download PDF</a>
                    </p>
                </object>
                <figcaption>{caption}{close}"#,
            url = escaped_url,
            pdf_height = PDF_EMBED_HEIGHT,
            caption = Self::escaped_caption(caption),
            close = if open_only {
                ""
            } else {
                "</figcaption></figure>"
            }
        )
    }
}

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

    // YouTube detection tests
    #[test]
    fn test_youtube_watch_url() {
        let embed =
            MediaEmbed::from_url_and_title("https://www.youtube.com/watch?v=dQw4w9WgXcQ", "Title");
        assert!(matches!(
            embed,
            Some(MediaEmbed::YouTube { video_id, .. }) if video_id == "dQw4w9WgXcQ"
        ));
    }

    #[test]
    fn test_youtube_short_url() {
        let embed = MediaEmbed::from_url_and_title("https://youtu.be/dQw4w9WgXcQ", "");
        assert!(matches!(
            embed,
            Some(MediaEmbed::YouTube { video_id, caption }) if video_id == "dQw4w9WgXcQ" && caption.is_none()
        ));
    }

    #[test]
    fn test_youtube_embed_url() {
        let embed =
            MediaEmbed::from_url_and_title("https://www.youtube.com/embed/dQw4w9WgXcQ", "Caption");
        assert!(matches!(
            embed,
            Some(MediaEmbed::YouTube { video_id, caption }) if video_id == "dQw4w9WgXcQ" && caption == Some("Caption".to_string())
        ));
    }

    #[test]
    fn test_youtube_with_extra_params() {
        let embed = MediaEmbed::from_url_and_title(
            "https://www.youtube-nocookie.com/watch?v=dQw4w9WgXcQ&t=30s",
            "",
        );
        assert!(matches!(
            embed,
            Some(MediaEmbed::YouTube { video_id, .. }) if video_id == "dQw4w9WgXcQ"
        ));
    }

    // Video detection tests
    #[test]
    fn test_video_mp4() {
        let embed = MediaEmbed::from_url_and_title("video.mp4", "My Video");
        assert!(matches!(embed, Some(MediaEmbed::Video(_))));
    }

    #[test]
    fn test_video_webm_not_detected_by_vid() {
        // webm is not in Vid's list, so it won't be detected as video
        // This is existing behavior - webm goes through as audio since Audio supports it
        let embed = MediaEmbed::from_url_and_title("video.webm", "");
        assert!(matches!(embed, Some(MediaEmbed::Audio(_))));
    }

    // Audio detection tests
    #[test]
    fn test_audio_mp3() {
        let embed = MediaEmbed::from_url_and_title("podcast.mp3", "Episode 1");
        assert!(matches!(embed, Some(MediaEmbed::Audio(_))));
    }

    #[test]
    fn test_audio_wav() {
        let embed = MediaEmbed::from_url_and_title("sound.wav", "");
        assert!(matches!(embed, Some(MediaEmbed::Audio(_))));
    }

    // PDF detection tests
    #[test]
    fn test_pdf() {
        let embed = MediaEmbed::from_url_and_title("document.pdf", "Important Doc");
        assert!(matches!(
            embed,
            Some(MediaEmbed::Pdf { url, caption }) if url == "document.pdf" && caption == Some("Important Doc".to_string())
        ));
    }

    #[test]
    fn test_pdf_with_path() {
        let embed = MediaEmbed::from_url_and_title("/docs/report.pdf", "");
        assert!(matches!(
            embed,
            Some(MediaEmbed::Pdf { url, caption }) if url == "/docs/report.pdf" && caption.is_none()
        ));
    }

    #[test]
    fn test_pdf_case_insensitive() {
        let embed = MediaEmbed::from_url_and_title("document.PDF", "");
        assert!(matches!(embed, Some(MediaEmbed::Pdf { .. })));
    }

    // Non-media files
    #[test]
    fn test_image_not_detected() {
        assert!(MediaEmbed::from_url_and_title("photo.jpg", "").is_none());
        assert!(MediaEmbed::from_url_and_title("image.png", "").is_none());
        assert!(MediaEmbed::from_url_and_title("graphic.gif", "").is_none());
    }

    #[test]
    fn test_unknown_extension() {
        assert!(MediaEmbed::from_url_and_title("file.xyz", "").is_none());
    }

    #[test]
    fn test_no_extension() {
        assert!(MediaEmbed::from_url_and_title("https://example.com/page", "").is_none());
    }

    // HTML generation tests
    #[test]
    fn test_youtube_html() {
        let embed = MediaEmbed::YouTube {
            video_id: "abc123xyz".to_string(),
            caption: Some("Test Video".to_string()),
        };
        let html = embed.to_html(false, false, false);
        assert!(html.contains("youtube-embed"));
        assert!(html.contains("https://www.youtube-nocookie.com/embed/abc123xyz"));
        assert!(html.contains("<figcaption>Test Video</figcaption>"));
    }

    #[test]
    fn test_pdf_html() {
        let embed = MediaEmbed::Pdf {
            url: "/docs/test.pdf".to_string(),
            caption: Some("My PDF".to_string()),
        };
        let html = embed.to_html(false, false, false);
        assert!(html.contains("pdf-embed"));
        assert!(html.contains(r#"data="/docs/test.pdf""#));
        assert!(html.contains(r#"type="application/pdf""#));
        assert!(html.contains("data-pdf-fallback"));
        assert!(html.contains("<figcaption>My PDF</figcaption>"));
    }

    #[test]
    fn test_pdf_html_open_only() {
        let embed = MediaEmbed::Pdf {
            url: "doc.pdf".to_string(),
            caption: None,
        };
        let html = embed.to_html(true, false, false);
        assert!(html.contains("<object"));
        assert!(!html.contains("</figcaption></figure>"));
    }

    #[test]
    fn test_youtube_v_url() {
        let embed = MediaEmbed::from_url_and_title("https://www.youtube.com/v/dQw4w9WgXcQ", "");
        assert!(matches!(
            embed,
            Some(MediaEmbed::YouTube { video_id, .. }) if video_id == "dQw4w9WgXcQ"
        ));
    }

    #[test]
    fn test_youtube_without_www() {
        let embed = MediaEmbed::from_url_and_title("https://youtube.com/watch?v=dQw4w9WgXcQ", "");
        assert!(matches!(
            embed,
            Some(MediaEmbed::YouTube { video_id, .. }) if video_id == "dQw4w9WgXcQ"
        ));
    }

    #[test]
    fn test_youtube_invalid_id_length() {
        let embed = MediaEmbed::from_url_and_title("https://www.youtube.com/watch?v=short", "");
        assert!(embed.is_none());
    }

    #[test]
    fn test_youtube_not_youtube() {
        let embed = MediaEmbed::from_url_and_title("https://example.com/watch?v=dQw4w9WgXcQ", "");
        assert!(embed.is_none());
    }

    #[test]
    fn test_youtube_nocookie_embed_url() {
        let embed = MediaEmbed::from_url_and_title(
            "https://www.youtube-nocookie.com/embed/dQw4w9WgXcQ",
            "Caption",
        );
        assert!(matches!(
            embed,
            Some(MediaEmbed::YouTube { video_id, caption }) if video_id == "dQw4w9WgXcQ" && caption == Some("Caption".to_string())
        ));
    }

    #[test]
    fn test_youtube_nocookie_v_url() {
        let embed =
            MediaEmbed::from_url_and_title("https://www.youtube-nocookie.com/v/dQw4w9WgXcQ", "");
        assert!(matches!(
            embed,
            Some(MediaEmbed::YouTube { video_id, .. }) if video_id == "dQw4w9WgXcQ"
        ));
    }

    /// Regression: a PDF link destination containing a double quote must not be
    /// able to close `data-pdf-url`/`data`/`href` and inject new attributes.
    #[test]
    fn test_pdf_html_escapes_hostile_url() {
        let embed =
            MediaEmbed::from_url_and_title(r#"a"onerror="alert(1)"b.pdf"#, "").expect("pdf embed");
        let html = embed.to_html(false, false, false);
        assert!(
            html.contains("&quot;"),
            "double quotes must be escaped: {html}"
        );
        // The hostile destination must stay inside each attribute value; the
        // injected text may appear only as escaped data, never as an attribute.
        assert_eq!(
            html.matches(r#"a&quot;onerror=&quot;alert(1)&quot;b.pdf"#)
                .count(),
            3,
            "data-pdf-url, object data, and href must all be escaped: {html}"
        );
        assert!(
            !html.contains(r#""onerror=""#),
            "must not emit an injected attribute: {html}"
        );
    }

    /// Regression: a bare `&` in a filename is invalid in an attribute value
    /// and must be encoded in all three places the URL is interpolated.
    #[test]
    fn test_pdf_html_escapes_ampersand_in_url() {
        let embed = MediaEmbed::from_url_and_title("/docs/Q&A-report.pdf", "").expect("pdf embed");
        let html = embed.to_html(false, false, false);
        assert!(
            !html.contains("Q&A-report"),
            "bare ampersand emitted: {html}"
        );
        assert_eq!(
            html.matches("/docs/Q&amp;A-report.pdf").count(),
            3,
            "data-pdf-url, object data, and href must all be encoded: {html}"
        );
    }

    /// Regression: captions land in element-text context and must be escaped.
    #[test]
    fn test_pdf_html_escapes_caption() {
        let embed = MediaEmbed::from_url_and_title("doc.pdf", "<script>alert(1)</script> & more")
            .expect("pdf embed");
        let html = embed.to_html(false, false, false);
        assert!(
            html.contains("&lt;script&gt;alert(1)&lt;/script&gt; &amp; more"),
            "caption must be escaped: {html}"
        );
        assert!(
            !html.contains("<script>"),
            "must not emit a raw script tag: {html}"
        );
    }

    /// Escaping must not double-encode ordinary destinations or captions.
    #[test]
    fn test_pdf_html_ordinary_values_round_trip_unchanged() {
        let embed =
            MediaEmbed::from_url_and_title("/docs/my_report-v2.pdf", "My PDF").expect("pdf embed");
        let html = embed.to_html(false, false, false);
        assert!(html.contains(r#"data-pdf-url="/docs/my_report-v2.pdf""#));
        assert!(html.contains(r#"data="/docs/my_report-v2.pdf""#));
        assert!(html.contains(r#"href="/docs/my_report-v2.pdf""#));
        assert!(html.contains("<figcaption>My PDF</figcaption>"));
        assert!(!html.contains("&amp;"), "nothing to escape here: {html}");
    }

    /// Regression: the YouTube video id and caption are interpolated too.
    #[test]
    fn test_youtube_html_escapes_video_id_and_caption() {
        let embed = MediaEmbed::YouTube {
            video_id: r#"x"onload="alert(1)"#.to_string(),
            caption: Some("<b>hi</b> & bye".to_string()),
        };
        let html = embed.to_html(false, false, false);
        assert!(
            html.contains("&quot;"),
            "double quotes must be escaped: {html}"
        );
        assert!(
            html.contains(
                r#"src="https://www.youtube-nocookie.com/embed/x&quot;onload=&quot;alert(1)""#
            ),
            "iframe src must be fully escaped: {html}"
        );
        assert!(
            !html.contains(r#""onload=""#),
            "must not emit an injected attribute: {html}"
        );
        assert!(html.contains("&lt;b&gt;hi&lt;/b&gt; &amp; bye"));
    }

    #[test]
    fn test_html_close() {
        let youtube = MediaEmbed::YouTube {
            video_id: "x".to_string(),
            caption: None,
        };
        let pdf = MediaEmbed::Pdf {
            url: "x.pdf".to_string(),
            caption: None,
        };
        assert_eq!(youtube.html_close(), "</figcaption></figure>");
        assert_eq!(pdf.html_close(), "</figcaption></figure>");
    }
}