feedparser-rs 0.8.0

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
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
//! iTunes namespace handling shared by the RSS 2.0 and Atom parsers.
//!
//! Feed-level elements, item/entry-level elements and the post-parse promotions into
//! the standard fields live here once, so RSS and Atom cannot drift apart.

use std::collections::HashMap;

use quick_xml::events::Event;

use super::{
    common::{
        LimitedCollectionExt, check_depth, collect_attributes, find_attribute, is_itunes_tag,
        itunes_entry_meta, itunes_feed_meta, read_item_prose, read_item_text, read_prose_str,
        read_text_str, skip_element,
    },
    context::{EntryCtx, XmlCtx, XmlReader},
};
use crate::{
    ParserLimits,
    error::Result,
    types::{
        Email, Entry, FeedMeta, Image, ItunesCategory, ItunesFeedMeta, ItunesOwner, Person, Tag,
        TextConstruct, Url, parse_explicit,
    },
    util::text::truncate_to_length,
};

const ITUNES_SCHEME: &str = "http://www.itunes.com/";

type Attrs<'a> = &'a [(Vec<u8>, String)];

/// The `href` of an `itunes:image`; a blank one must not replace an earlier image.
fn non_blank_href(attrs: Attrs<'_>) -> Option<&str> {
    find_attribute(attrs, b"href").filter(|href| !href.trim().is_empty())
}

/// Parses one iTunes element at feed (channel) level.
///
/// Returns `Ok(true)` when `tag` is a recognised iTunes element and was consumed.
pub(super) fn parse_feed_itunes(
    xml: &mut XmlCtx,
    tag: &[u8],
    attrs: Attrs,
    namespaces: &HashMap<String, String>,
    feed: &mut FeedMeta,
    depth: &mut usize,
    is_empty: bool,
) -> Result<bool> {
    if is_itunes_tag(tag, b"owner", namespaces) {
        if !is_empty && let Ok(owner) = parse_itunes_owner(xml.reader, xml.buf, xml.limits, depth) {
            itunes_feed_meta(feed).owner = Some(owner);
        }
        Ok(true)
    } else if is_itunes_tag(tag, b"category", namespaces) {
        parse_itunes_category(xml, attrs, namespaces, feed, *depth, is_empty)?;
        Ok(true)
    } else if is_itunes_tag(tag, b"image", namespaces) {
        if let Some(href) = non_blank_href(attrs) {
            let url = truncate_to_length(href, xml.limits.max_attribute_length);
            itunes_feed_meta(feed).image = Some(url.into());
        }
        if !is_empty {
            skip_element(xml.reader, xml.buf, xml.limits, *depth)?;
        }
        Ok(true)
    } else {
        parse_feed_itunes_text(xml, tag, namespaces, feed, is_empty)
    }
}

/// Parses the text-valued feed-level iTunes elements.
///
/// An empty element changes nothing: it neither replaces an earlier value nor
/// creates the iTunes block.
fn parse_feed_itunes_text(
    xml: &mut XmlCtx,
    tag: &[u8],
    namespaces: &HashMap<String, String>,
    feed: &mut FeedMeta,
    is_empty: bool,
) -> Result<bool> {
    let is = |name: &[u8]| is_itunes_tag(tag, name, namespaces);
    let prose = is(b"subtitle") || is(b"summary");
    let known = prose
        || [
            &b"author"[..],
            b"explicit",
            b"keywords",
            b"type",
            b"complete",
            b"new-feed-url",
            b"block",
        ]
        .into_iter()
        .any(is);
    if !known {
        return Ok(false);
    }
    if is_empty {
        return Ok(true);
    }
    let text = if prose {
        read_prose_str(xml.reader, xml.buf, xml.limits)?
    } else {
        read_text_str(xml.reader, xml.buf, xml.limits)?
    };
    if !text.is_empty() {
        store_feed_itunes_text(&is, text, xml.limits, itunes_feed_meta(feed));
    }
    Ok(true)
}

/// Stores `text` in the iTunes field named by the matcher `is`.
fn store_feed_itunes_text(
    is: &impl Fn(&[u8]) -> bool,
    text: String,
    limits: &ParserLimits,
    meta: &mut ItunesFeedMeta,
) {
    if is(b"author") {
        meta.author = Some(text);
    } else if is(b"subtitle") {
        meta.subtitle = Some(text);
    } else if is(b"summary") {
        meta.summary = Some(text);
    } else if is(b"explicit") {
        meta.explicit = parse_explicit(&text);
    } else if is(b"keywords") {
        meta.keywords = text
            .split(',')
            .map(|s| s.trim().to_string())
            .filter(|s| !s.is_empty())
            .take(limits.max_tags)
            .collect();
    } else if is(b"type") {
        meta.podcast_type = Some(text);
    } else if is(b"complete") {
        meta.complete = Some(text.trim().to_string());
    } else if is(b"new-feed-url") {
        meta.new_feed_url = Some(text.trim().to_string().into());
    } else if is(b"block") {
        meta.block = Some(u8::from(text.trim().eq_ignore_ascii_case("yes")));
    }
}

/// Parses `<itunes:owner>` (name and email children).
fn parse_itunes_owner(
    reader: &mut XmlReader<'_>,
    buf: &mut Vec<u8>,
    limits: &ParserLimits,
    depth: &mut usize,
) -> Result<ItunesOwner> {
    let mut owner = ItunesOwner::default();

    loop {
        match reader.read_event_into(buf) {
            Ok(Event::Start(e)) => {
                *depth += 1;
                check_depth(*depth, limits.max_nesting_depth)?;

                let tag_name = e.local_name();
                if tag_name.as_ref() == "name" {
                    owner.name = Some(read_text_str(reader, buf, limits)?);
                } else if tag_name.as_ref() == "email" {
                    owner.email = Some(read_text_str(reader, buf, limits)?);
                } else {
                    skip_element(reader, buf, limits, *depth)?;
                }
                *depth = depth.saturating_sub(1);
            }
            Ok(Event::End(_) | Event::Eof) => break,
            Err(e) => return Err(crate::FeedError::xml(e)),
            _ => {}
        }
        buf.clear();
    }

    Ok(owner)
}

/// Reads every nested `<itunes:category>` text of an open category, in document order.
///
/// The count is bounded by `max_tags`; categories without `text` are skipped.
fn read_subcategories(xml: &mut XmlCtx, namespaces: &HashMap<String, String>) -> Vec<String> {
    let max = xml.limits.max_attribute_length;
    let max_tags = xml.limits.max_tags;
    let mut subcategories: Vec<String> = Vec::new();
    let mut nesting = 0usize;
    loop {
        let full = subcategories.len() >= max_tags;
        let found = match xml.reader.read_event_into(xml.buf) {
            Ok(Event::Start(e))
                if is_itunes_tag(e.name().as_ref().as_bytes(), b"category", namespaces) =>
            {
                nesting += 1;
                (!full).then(|| e.into_owned())
            }
            Ok(Event::Empty(e))
                if is_itunes_tag(e.name().as_ref().as_bytes(), b"category", namespaces) =>
            {
                (!full).then(|| e.into_owned())
            }
            Ok(Event::End(e))
                if is_itunes_tag(e.name().as_ref().as_bytes(), b"category", namespaces) =>
            {
                if nesting == 0 {
                    break;
                }
                nesting -= 1;
                None
            }
            Ok(Event::Eof) | Err(_) => break,
            _ => None,
        };
        if let Some(e) = found {
            let (attrs, _) = collect_attributes(&e);
            if let Some(text) = find_attribute(&attrs, b"text") {
                subcategories.push(truncate_to_length(text, max));
            }
        }
        xml.buf.clear();
    }
    subcategories
}

/// The `text` of a category element, truncated to `max_attribute_length`.
fn category_text(xml: &XmlCtx, attrs: Attrs) -> String {
    find_attribute(attrs, b"text")
        .map_or_default(|v| truncate_to_length(v, xml.limits.max_attribute_length))
}

/// Processes the children of a textless `<itunes:category>` as top-level categories.
///
/// Textless descendants are walked with an explicit counter, not recursion, so the stack
/// stays flat however deep `max_nesting_depth` allows the chain to go.
fn parse_orphan_subcategories(
    xml: &mut XmlCtx,
    namespaces: &HashMap<String, String>,
    feed: &mut FeedMeta,
    depth: usize,
) -> Result<()> {
    let max_depth = xml.limits.max_nesting_depth;
    let mut open = 1usize;
    while open > 0 {
        let (attrs, is_empty) = match xml.reader.read_event_into(xml.buf) {
            Ok(Event::Start(e))
                if is_itunes_tag(e.name().as_ref().as_bytes(), b"category", namespaces) =>
            {
                (collect_attributes(&e).0, false)
            }
            Ok(Event::Empty(e))
                if is_itunes_tag(e.name().as_ref().as_bytes(), b"category", namespaces) =>
            {
                (collect_attributes(&e).0, true)
            }
            Ok(Event::End(e))
                if is_itunes_tag(e.name().as_ref().as_bytes(), b"category", namespaces) =>
            {
                open -= 1;
                xml.buf.clear();
                continue;
            }
            Ok(Event::Eof) | Err(_) => break,
            _ => {
                xml.buf.clear();
                continue;
            }
        };
        xml.buf.clear();
        let text = category_text(xml, &attrs);
        if !text.is_empty() {
            push_category(xml, namespaces, feed, text, is_empty);
        } else if !is_empty {
            open += 1;
            check_depth(depth + open, max_depth)?;
        }
    }
    Ok(())
}

/// Parses `<itunes:category>` with its nested subcategories into tags and categories.
///
/// Every nested subcategory becomes a tag; `ItunesCategory::subcategory` keeps the first.
/// A category without a `text` attribute adds nothing itself, but its children are
/// processed as top-level categories.
fn parse_itunes_category(
    xml: &mut XmlCtx,
    attrs: Attrs,
    namespaces: &HashMap<String, String>,
    feed: &mut FeedMeta,
    depth: usize,
    is_empty: bool,
) -> Result<()> {
    let text = category_text(xml, attrs);
    if !text.is_empty() {
        push_category(xml, namespaces, feed, text, is_empty);
    } else if !is_empty {
        parse_orphan_subcategories(xml, namespaces, feed, depth)?;
    }
    Ok(())
}

/// Reads the nested subcategories of a category with `text` and stores its tags and entry.
fn push_category(
    xml: &mut XmlCtx,
    namespaces: &HashMap<String, String>,
    feed: &mut FeedMeta,
    text: String,
    is_empty: bool,
) {
    let subcategories = if is_empty {
        Vec::new()
    } else {
        read_subcategories(xml, namespaces)
    };

    let max_tags = xml.limits.max_tags;
    let subcategory = subcategories.first().cloned();
    for term in std::iter::once(&text).chain(&subcategories) {
        feed.tags.try_push_limited(
            Tag {
                term: term.as_str().into(),
                scheme: Some(ITUNES_SCHEME.into()),
                label: None,
            },
            max_tags,
        );
    }
    itunes_feed_meta(feed)
        .categories
        .try_push_limited(ItunesCategory { text, subcategory }, max_tags);
}

/// Parses one iTunes element at item (RSS) or entry (Atom) level.
///
/// Returns `Ok(true)` when `tag` is a recognised iTunes element and was consumed.
pub(super) fn parse_item_itunes(
    ctx: &mut EntryCtx,
    tag: &[u8],
    attrs: Attrs,
    entry: &mut Entry,
    depth: usize,
    is_empty: bool,
) -> Result<bool> {
    if is_itunes_tag(tag, b"title", ctx.namespaces) {
        let (text, had_bozo) = read_item_prose(&mut ctx.xml, is_empty)?;
        ctx.bozo |= had_bozo;
        if !text.is_empty() {
            itunes_entry_meta(entry).title = Some(text);
        }
        Ok(true)
    } else if is_itunes_tag(tag, b"author", ctx.namespaces) {
        let (text, had_bozo) = read_item_text(&mut ctx.xml, is_empty)?;
        ctx.bozo |= had_bozo;
        if !text.is_empty() {
            // Promote to entry.author unless an earlier element named a person
            if entry.author.as_deref().is_none_or(str::is_empty) {
                entry.set_author(Person::from_name(&text));
                entry
                    .authors
                    .try_push_limited(Person::from_name(&text), ctx.xml.limits.max_authors);
            }
            itunes_entry_meta(entry).author = Some(text);
        }
        Ok(true)
    } else if is_itunes_tag(tag, b"subtitle", ctx.namespaces) {
        let (text, had_bozo) = read_item_prose(&mut ctx.xml, is_empty)?;
        ctx.bozo |= had_bozo;
        if !text.is_empty() {
            itunes_entry_meta(entry).subtitle = Some(text);
        }
        Ok(true)
    } else if is_itunes_tag(tag, b"summary", ctx.namespaces) {
        let (text, had_bozo) = read_item_prose(&mut ctx.xml, is_empty)?;
        ctx.bozo |= had_bozo;
        if !text.is_empty() {
            itunes_entry_meta(entry).summary = Some(text);
        }
        Ok(true)
    } else if is_itunes_tag(tag, b"explicit", ctx.namespaces) {
        let (text, had_bozo) = read_item_text(&mut ctx.xml, is_empty)?;
        ctx.bozo |= had_bozo;
        if !text.is_empty() {
            itunes_entry_meta(entry).explicit = parse_explicit(&text);
        }
        Ok(true)
    } else if is_itunes_tag(tag, b"image", ctx.namespaces) {
        if let Some(value) = non_blank_href(attrs) {
            itunes_entry_meta(entry).image =
                Some(truncate_to_length(value, ctx.xml.limits.max_attribute_length).into());
        }
        if !is_empty {
            skip_element(ctx.xml.reader, ctx.xml.buf, ctx.xml.limits, depth)?;
        }
        Ok(true)
    } else {
        parse_item_itunes_value(ctx, tag, entry, is_empty)
    }
}

/// Parses the item-level iTunes tags stored as written: duration, episode, season,
/// episodeType.
fn parse_item_itunes_value(
    ctx: &mut EntryCtx,
    tag: &[u8],
    entry: &mut Entry,
    is_empty: bool,
) -> Result<bool> {
    let field: fn(&mut crate::types::ItunesEntryMeta) -> &mut Option<String> =
        if is_itunes_tag(tag, b"duration", ctx.namespaces) {
            |meta| &mut meta.duration
        } else if is_itunes_tag(tag, b"episode", ctx.namespaces) {
            |meta| &mut meta.episode
        } else if is_itunes_tag(tag, b"season", ctx.namespaces) {
            |meta| &mut meta.season
        } else if is_itunes_tag(tag, b"episodeType", ctx.namespaces) {
            |meta| &mut meta.episode_type
        } else {
            return Ok(false);
        };
    let (text, had_bozo) = read_item_text(&mut ctx.xml, is_empty)?;
    ctx.bozo |= had_bozo;
    // An empty element must not create the iTunes block either.
    if !text.is_empty() {
        *field(itunes_entry_meta(entry)) = Some(text);
    }
    Ok(true)
}

/// `Some` of `value` unless it is missing or blank.
fn non_blank(value: Option<&str>) -> Option<String> {
    value.filter(|v| !v.trim().is_empty()).map(str::to_owned)
}

/// The subtitle, summary and image URL of an iTunes block that carry data.
struct Promotable {
    subtitle: Option<String>,
    summary: Option<String>,
    image: Option<String>,
}

impl Promotable {
    fn of(subtitle: Option<&str>, summary: Option<&str>, image: Option<&Url>) -> Self {
        Self {
            subtitle: non_blank(subtitle),
            summary: non_blank(summary),
            image: non_blank(image.map(Url::as_str)),
        }
    }
}

/// Applies the iTunes promotion rules to feed-level fields.
///
/// Called once after the whole channel/feed was parsed, so the result does not depend
/// on where iTunes elements appear in the document. Blank iTunes values never override
/// valid data.
pub(super) fn apply_itunes_feed_promotions(feed: &mut FeedMeta) {
    let Some(itunes) = feed.itunes.as_deref() else {
        return;
    };
    let Promotable {
        subtitle,
        summary,
        image,
    } = Promotable::of(
        itunes.subtitle.as_deref(),
        itunes.summary.as_deref(),
        itunes.image.as_ref(),
    );
    let itunes_author = non_blank(itunes.author.as_deref());
    let owner = itunes.owner.clone();

    if let Some(s) = subtitle {
        feed.set_subtitle(TextConstruct::html(s));
    }
    if let Some(s) = summary {
        feed.set_summary(TextConstruct::html(s));
    }
    // itunes:image href always wins over RSS <image> (#287).
    if let Some(url) = image {
        feed.image = Some(Image::new(url.into()));
    }
    promote_owner(feed, owner.as_ref(), itunes_author.as_deref());
}

/// Fills `publisher_detail` and, when no native author exists, `author` from the owner.
///
/// Author priority (#297, #631): native author > `itunes:owner` name > `itunes:author`.
fn promote_owner(feed: &mut FeedMeta, owner: Option<&ItunesOwner>, itunes_author: Option<&str>) {
    let owner_name = owner
        .and_then(|o| o.name.as_deref())
        .filter(|n| !n.trim().is_empty());
    if feed.publisher_detail.is_none()
        && let Some(owner) = owner
    {
        feed.set_publisher(Person {
            name: owner.name.as_deref().map(Into::into),
            email: owner.email.as_deref().map(Email::new),
            uri: None,
            avatar: None,
            ..Person::default()
        });
    }
    if feed.author.is_some() {
        return;
    }
    let person = if let Some(name) = owner_name {
        // #317: `author` is name-only; `author_detail` keeps the email.
        let person = Person {
            name: Some(name.into()),
            email: owner.and_then(|o| o.email.as_deref()).map(Email::new),
            uri: None,
            avatar: None,
            ..Person::default()
        };
        feed.author.clone_from(&person.name);
        feed.author_detail = Some(person.clone());
        person
    } else if let Some(name) = itunes_author {
        let person = Person::from_name(name);
        feed.set_author(person.clone());
        person
    } else {
        return;
    };
    feed.authors.try_push_limited(person, usize::MAX);
}

/// Applies the iTunes promotion rules to entry-level fields.
///
/// Called once after the whole item/entry was parsed. `entry.subtitle` is iTunes-only
/// in RSS; `entry.summary` may already hold the native description.
pub(super) fn apply_itunes_entry_promotions(entry: &mut Entry) {
    let Some(itunes) = entry.itunes.as_deref() else {
        return;
    };
    let Promotable {
        subtitle,
        summary,
        image,
    } = Promotable::of(
        itunes.subtitle.as_deref(),
        itunes.summary.as_deref(),
        itunes.image.as_ref(),
    );

    if let Some(s) = subtitle {
        entry.set_subtitle(TextConstruct::html(s));
    }
    if let Some(s) = summary {
        entry.set_summary(TextConstruct::html(s));
    }
    if let Some(url) = image {
        entry.image = Some(Image::new(url.trim().into()));
    }
}