mbr-markdown-browser 0.4.7

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
//! 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::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())
    }

    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 = video_id,
            caption = caption.unwrap_or(""),
            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)
        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 = url,
            pdf_height = PDF_EMBED_HEIGHT,
            caption = caption.unwrap_or(""),
            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"
        ));
    }

    #[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>");
    }
}