feedparser-rs 0.5.3

High-performance RSS/Atom/JSON Feed parser
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
/// Media RSS Specification
///
/// Namespace: <http://search.yahoo.com/mrss/>
/// Prefix: media
///
/// This module provides parsing support for Media RSS elements commonly
/// used in video/audio feeds and podcasts.
///
/// Common elements:
/// - `media:content` → enclosures
/// - `media:thumbnail` → (could add thumbnails field)
/// - `media:title` → title (fallback)
/// - `media:description` → summary (fallback)
/// - `media:keywords` → tags (comma-separated)
/// - `media:category` → tags
/// - `media:credit` → contributors
///
/// # Type Design Note
///
/// The [`MediaContent`] and [`MediaThumbnail`] types in this module use raw `String`
/// fields instead of the `Url`/`MimeType` newtypes from `types::common`. This is
/// intentional:
///
/// 1. These are internal parsing types with extended attributes (medium, bitrate,
///    framerate, expression, `is_default`) not present in the public API types.
/// 2. The `media_content_to_enclosure` function handles conversion to public types.
/// 3. The public API types in `types::common::MediaContent` use proper newtypes.
use crate::types::{Enclosure, Entry, FeedMeta, MediaRating, Tag};

/// Media RSS namespace URI
pub const MEDIA_NAMESPACE: &str = "http://search.yahoo.com/mrss/";

/// Media RSS content element with full attribute support
///
/// Represents a media object embedded in the feed with detailed metadata.
/// Commonly used in video/audio feeds and podcasts.
///
/// # Security Warning
///
/// The `url` field comes from untrusted feed input and has NOT been validated for SSRF.
/// Applications MUST validate URLs before fetching to prevent SSRF attacks.
///
/// # Examples
///
/// ```
/// use feedparser_rs::namespace::media_rss::MediaContent;
///
/// let content = MediaContent {
///     url: "https://example.com/video.mp4".to_string(),
///     type_: Some("video/mp4".to_string()),
///     medium: Some("video".to_string()),
///     width: Some(1920),
///     height: Some(1080),
///     ..Default::default()
/// };
///
/// assert_eq!(content.url, "https://example.com/video.mp4");
/// ```
#[derive(Debug, Clone, Default, PartialEq)]
#[allow(clippy::derive_partial_eq_without_eq)]
pub struct MediaContent {
    /// URL of the media object (url attribute)
    ///
    /// # Security Warning
    ///
    /// This URL comes from untrusted feed input and has NOT been validated for SSRF.
    /// Applications MUST validate URLs before fetching to prevent SSRF attacks.
    pub url: String,
    /// MIME type (type attribute): "video/mp4", "audio/mpeg", etc.
    pub type_: Option<String>,
    /// Medium type (medium attribute): "image", "video", "audio", "document", "executable"
    pub medium: Option<String>,
    /// File size in bytes (fileSize attribute)
    pub file_size: Option<u64>,
    /// Bitrate in kilobits per second (bitrate attribute)
    pub bitrate: Option<u32>,
    /// Frame rate in frames per second (framerate attribute)
    pub framerate: Option<f32>,
    /// Width in pixels (width attribute)
    pub width: Option<u32>,
    /// Height in pixels (height attribute)
    pub height: Option<u32>,
    /// Duration in seconds (duration attribute)
    pub duration: Option<u32>,
    /// Expression (expression attribute): "full", "sample", "nonstop"
    ///
    /// - "full": complete media object
    /// - "sample": preview/sample of media
    /// - "nonstop": continuous/streaming media
    pub expression: Option<String>,
    /// Whether this is the default media object (isDefault attribute)
    pub is_default: Option<bool>,
}

/// Media RSS thumbnail element
///
/// Represents a thumbnail image for a media object.
///
/// # Security Warning
///
/// The `url` field comes from untrusted feed input and has NOT been validated for SSRF.
/// Applications MUST validate URLs before fetching to prevent SSRF attacks.
///
/// # Examples
///
/// ```
/// use feedparser_rs::namespace::media_rss::MediaThumbnail;
///
/// let thumbnail = MediaThumbnail {
///     url: "https://example.com/thumb.jpg".to_string(),
///     width: Some(640),
///     height: Some(480),
///     time: None,
/// };
///
/// assert_eq!(thumbnail.url, "https://example.com/thumb.jpg");
/// ```
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct MediaThumbnail {
    /// URL of the thumbnail image (url attribute)
    ///
    /// # Security Warning
    ///
    /// This URL comes from untrusted feed input and has NOT been validated for SSRF.
    /// Applications MUST validate URLs before fetching to prevent SSRF attacks.
    pub url: String,
    /// Width in pixels (width attribute)
    pub width: Option<u32>,
    /// Height in pixels (height attribute)
    pub height: Option<u32>,
    /// Time offset in NTP format (time attribute)
    ///
    /// Indicates which frame of the media this thumbnail represents.
    pub time: Option<String>,
}

/// Parse `media:rating` text and optional `scheme` attribute into a `MediaRating`.
fn parse_rating(scheme: Option<&str>, text: &str) -> Option<MediaRating> {
    let content = text.trim().to_string();
    if content.is_empty() {
        return None;
    }
    Some(MediaRating {
        scheme: scheme.map(str::to_owned),
        content,
    })
}

/// Handle Media RSS element at feed level (`media:rating`, `media:keywords`).
///
/// # Arguments
///
/// * `element` - Local name of the element (without namespace prefix)
/// * `scheme` - Optional `scheme` attribute value (for `media:rating`)
/// * `text` - Text content of the element
/// * `feed` - Feed metadata to update
pub fn handle_feed_element(element: &str, scheme: Option<&str>, text: &str, feed: &mut FeedMeta) {
    match element {
        "rating" if feed.media_rating.is_none() => {
            feed.media_rating = parse_rating(scheme, text);
        }
        "keywords" if feed.media_keywords.is_none() && !text.trim().is_empty() => {
            feed.media_keywords = Some(text.trim().to_string());
        }
        _ => {}
    }
}

/// Handle Media RSS element at entry level
///
/// Note: This is a simplified implementation. Full Media RSS support
/// would require parsing element attributes (url, type, width, height, etc.)
///
/// # Arguments
///
/// * `element` - Local name of the element (without namespace prefix)
/// * `text` - Text content of the element
/// * `entry` - Entry to update
pub fn handle_entry_element(element: &str, text: &str, entry: &mut Entry) {
    match element {
        "title" if entry.title.is_none() => {
            entry.title = Some(text.to_string());
        }
        "description" if entry.summary.is_none() => {
            entry.summary = Some(text.to_string());
        }
        "keywords" => {
            // Store raw comma-separated string
            if entry.media_keywords.is_none() && !text.is_empty() {
                entry.media_keywords = Some(text.to_string());
            }
            // Split into tags
            for keyword in text.split(',') {
                let keyword = keyword.trim();
                if !keyword.is_empty() {
                    entry.tags.push(Tag::new(keyword));
                }
            }
        }
        "category" if !text.is_empty() => {
            entry.tags.push(Tag::new(text));
        }
        _ => {
            // Other elements like media:content, media:thumbnail, media:credit
            // would require attribute parsing which needs integration with
            // the XML parser. For now, we skip these.
        }
    }
}

/// Handle `media:rating` at entry level with `scheme` attribute.
///
/// Called from the full XML parser where attribute access is available.
pub fn handle_entry_rating(scheme: Option<&str>, text: &str, entry: &mut Entry) {
    if entry.media_rating.is_none() {
        entry.media_rating = parse_rating(scheme, text);
    }
}

/// Convert `MediaContent` to `Enclosure` for backward compatibility
///
/// Extracts URL, type, and `file_size` to create a basic enclosure.
/// Used when adding `media:content` to `entry.enclosures`.
///
/// # Examples
///
/// ```
/// use feedparser_rs::namespace::media_rss::{MediaContent, media_content_to_enclosure};
///
/// let content = MediaContent {
///     url: "https://example.com/video.mp4".to_string(),
///     type_: Some("video/mp4".to_string()),
///     file_size: Some(1_024_000),
///     ..Default::default()
/// };
///
/// let enclosure = media_content_to_enclosure(&content);
/// assert_eq!(enclosure.url, "https://example.com/video.mp4");
/// assert_eq!(enclosure.enclosure_type.as_deref(), Some("video/mp4"));
/// assert_eq!(enclosure.length.as_deref(), Some("1024000"));
/// ```
pub fn media_content_to_enclosure(content: &MediaContent) -> Enclosure {
    Enclosure {
        url: content.url.clone().into(),
        enclosure_type: content.type_.as_ref().map(|t| t.clone().into()),
        length: content.file_size.map(|v| v.to_string()),
        title: None,
        duration: None,
    }
}

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

    #[test]
    fn test_media_title() {
        let mut entry = Entry::default();
        handle_entry_element("title", "Video Title", &mut entry);

        assert_eq!(entry.title.as_deref(), Some("Video Title"));
    }

    #[test]
    fn test_media_description() {
        let mut entry = Entry::default();
        handle_entry_element("description", "Video description", &mut entry);

        assert_eq!(entry.summary.as_deref(), Some("Video description"));
    }

    #[test]
    fn test_media_keywords() {
        let mut entry = Entry::default();
        handle_entry_element("keywords", "tech, programming, rust", &mut entry);

        assert_eq!(entry.tags.len(), 3);
        assert_eq!(entry.tags[0].term, "tech");
        assert_eq!(entry.tags[1].term, "programming");
        assert_eq!(entry.tags[2].term, "rust");
    }

    #[test]
    fn test_media_keywords_with_spaces() {
        let mut entry = Entry::default();
        handle_entry_element("keywords", "  tech  ,  programming  ", &mut entry);

        assert_eq!(entry.tags.len(), 2);
        assert_eq!(entry.tags[0].term, "tech");
        assert_eq!(entry.tags[1].term, "programming");
    }

    #[test]
    fn test_media_category() {
        let mut entry = Entry::default();
        handle_entry_element("category", "Technology", &mut entry);

        assert_eq!(entry.tags.len(), 1);
        assert_eq!(entry.tags[0].term, "Technology");
    }

    #[test]
    fn test_media_content_default() {
        let content = MediaContent::default();
        assert!(content.url.is_empty());
        assert!(content.type_.is_none());
        assert!(content.medium.is_none());
        assert!(content.file_size.is_none());
        assert!(content.bitrate.is_none());
        assert!(content.framerate.is_none());
        assert!(content.width.is_none());
        assert!(content.height.is_none());
        assert!(content.duration.is_none());
        assert!(content.expression.is_none());
        assert!(content.is_default.is_none());
    }

    #[test]
    fn test_media_content_full_attributes() {
        let content = MediaContent {
            url: "https://example.com/video.mp4".to_string(),
            type_: Some("video/mp4".to_string()),
            medium: Some("video".to_string()),
            file_size: Some(10_485_760), // 10 MB
            bitrate: Some(1500),         // 1500 kbps
            framerate: Some(30.0),
            width: Some(1920),
            height: Some(1080),
            duration: Some(600), // 10 minutes
            expression: Some("full".to_string()),
            is_default: Some(true),
        };

        assert_eq!(content.url, "https://example.com/video.mp4");
        assert_eq!(content.type_.as_deref(), Some("video/mp4"));
        assert_eq!(content.medium.as_deref(), Some("video"));
        assert_eq!(content.file_size, Some(10_485_760));
        assert_eq!(content.bitrate, Some(1500));
        assert_eq!(content.framerate, Some(30.0));
        assert_eq!(content.width, Some(1920));
        assert_eq!(content.height, Some(1080));
        assert_eq!(content.duration, Some(600));
        assert_eq!(content.expression.as_deref(), Some("full"));
        assert_eq!(content.is_default, Some(true));
    }

    #[test]
    fn test_media_content_audio() {
        let content = MediaContent {
            url: "https://example.com/audio.mp3".to_string(),
            type_: Some("audio/mpeg".to_string()),
            medium: Some("audio".to_string()),
            file_size: Some(5_242_880), // 5 MB
            bitrate: Some(128),         // 128 kbps
            duration: Some(180),        // 3 minutes
            ..Default::default()
        };

        assert_eq!(content.medium.as_deref(), Some("audio"));
        assert_eq!(content.bitrate, Some(128));
        assert!(content.width.is_none());
        assert!(content.height.is_none());
        assert!(content.framerate.is_none());
    }

    #[test]
    fn test_media_content_image() {
        let content = MediaContent {
            url: "https://example.com/image.jpg".to_string(),
            type_: Some("image/jpeg".to_string()),
            medium: Some("image".to_string()),
            width: Some(800),
            height: Some(600),
            ..Default::default()
        };

        assert_eq!(content.medium.as_deref(), Some("image"));
        assert_eq!(content.width, Some(800));
        assert_eq!(content.height, Some(600));
        assert!(content.duration.is_none());
    }

    #[test]
    fn test_media_content_expression_variants() {
        let full = MediaContent {
            expression: Some("full".to_string()),
            ..Default::default()
        };
        let sample = MediaContent {
            expression: Some("sample".to_string()),
            ..Default::default()
        };
        let nonstop = MediaContent {
            expression: Some("nonstop".to_string()),
            ..Default::default()
        };

        assert_eq!(full.expression.as_deref(), Some("full"));
        assert_eq!(sample.expression.as_deref(), Some("sample"));
        assert_eq!(nonstop.expression.as_deref(), Some("nonstop"));
    }

    #[test]
    fn test_media_thumbnail_default() {
        let thumbnail = MediaThumbnail::default();
        assert!(thumbnail.url.is_empty());
        assert!(thumbnail.width.is_none());
        assert!(thumbnail.height.is_none());
        assert!(thumbnail.time.is_none());
    }

    #[test]
    fn test_media_thumbnail_full_attributes() {
        let thumbnail = MediaThumbnail {
            url: "https://example.com/thumb.jpg".to_string(),
            width: Some(640),
            height: Some(480),
            time: Some("12:05:01.123".to_string()),
        };

        assert_eq!(thumbnail.url, "https://example.com/thumb.jpg");
        assert_eq!(thumbnail.width, Some(640));
        assert_eq!(thumbnail.height, Some(480));
        assert_eq!(thumbnail.time.as_deref(), Some("12:05:01.123"));
    }

    #[test]
    fn test_media_thumbnail_without_time() {
        let thumbnail = MediaThumbnail {
            url: "https://example.com/poster.jpg".to_string(),
            width: Some(1920),
            height: Some(1080),
            time: None,
        };

        assert_eq!(thumbnail.width, Some(1920));
        assert_eq!(thumbnail.height, Some(1080));
        assert!(thumbnail.time.is_none());
    }

    #[test]
    fn test_media_content_to_enclosure() {
        let content = MediaContent {
            url: "https://example.com/video.mp4".to_string(),
            type_: Some("video/mp4".to_string()),
            file_size: Some(1_024_000),
            width: Some(1920), // These fields are not in Enclosure
            height: Some(1080),
            ..Default::default()
        };

        let enclosure = media_content_to_enclosure(&content);

        assert_eq!(enclosure.url, "https://example.com/video.mp4");
        assert_eq!(enclosure.enclosure_type.as_deref(), Some("video/mp4"));
        assert_eq!(enclosure.length.as_deref(), Some("1024000"));
    }

    #[test]
    fn test_media_content_to_enclosure_minimal() {
        let content = MediaContent {
            url: "https://example.com/file.bin".to_string(),
            ..Default::default()
        };

        let enclosure = media_content_to_enclosure(&content);

        assert_eq!(enclosure.url, "https://example.com/file.bin");
        assert!(enclosure.enclosure_type.is_none());
        assert!(enclosure.length.is_none());
    }

    #[test]
    fn test_empty_keywords() {
        let mut entry = Entry::default();
        handle_entry_element("keywords", "", &mut entry);

        assert!(entry.tags.is_empty());
    }

    #[test]
    fn test_keywords_with_empty_values() {
        let mut entry = Entry::default();
        handle_entry_element("keywords", "tech, , programming", &mut entry);

        assert_eq!(entry.tags.len(), 2);
        assert_eq!(entry.tags[0].term, "tech");
        assert_eq!(entry.tags[1].term, "programming");
    }
}