feedparser-rs 0.8.0

High-performance RSS/Atom/JSON Feed parser
Documentation
//! Media RSS namespace handling shared by the RSS 2.0 and Atom parsers.
//!
//! Item/entry-level objects, metadata and text, `media:group` and `media:content`
//! children, and the channel/feed-level elements live here once.

use std::collections::HashMap;

use quick_xml::events::{BytesStart, Event};

use super::{
    common::{
        LimitedCollectionExt, build_media_content, build_media_thumbnail, check_depth,
        collect_attributes, find_attribute, is_media_tag, read_item_text, read_prose_str,
        read_text_str, skip_element,
    },
    context::{EntryCtx, XmlCtx},
};
use crate::{
    ParserLimits,
    error::Result,
    namespace::media_rss,
    types::{Entry, FeedMeta, MediaCopyright, MediaCredit},
};

/// Parse one `media:*` element at item (RSS) or entry (Atom) level.
pub(super) fn parse_item_media(
    ctx: &mut EntryCtx,
    media_element: &str,
    attrs: &[(Vec<u8>, String)],
    entry: &mut Entry,
    depth: usize,
    is_empty: bool,
) -> Result<()> {
    if parse_item_media_object(ctx, media_element, attrs, entry, depth, is_empty)? {
        return Ok(());
    }
    if parse_item_media_meta(ctx, media_element, attrs, entry, is_empty)? {
        return Ok(());
    }
    parse_item_media_text(ctx, media_element, attrs, entry, is_empty)
}

/// Parse structured `media:*` elements that contain their own child content:
/// thumbnail, content, group.
///
/// Every arm returns `Ok(true)` unconditionally; `is_empty` is only tested inside
/// arm bodies, so a self-closing structured element never falls through to the
/// text handlers.
fn parse_item_media_object(
    ctx: &mut EntryCtx,
    media_element: &str,
    attrs: &[(Vec<u8>, String)],
    entry: &mut Entry,
    depth: usize,
    is_empty: bool,
) -> Result<bool> {
    match media_element {
        "thumbnail" => {
            if let Some(thumb) = build_media_thumbnail(attrs, ctx.xml.limits) {
                entry
                    .media_thumbnail
                    .try_push_limited(thumb, ctx.xml.limits.max_enclosures);
            }
            if !is_empty {
                skip_element(ctx.xml.reader, ctx.xml.buf, ctx.xml.limits, depth)?;
            }
            Ok(true)
        }
        "content" => {
            if let Some(content) = build_media_content(attrs, ctx.xml.limits) {
                entry
                    .media_content
                    .try_push_limited(content, ctx.xml.limits.max_enclosures);
            }
            if !is_empty {
                parse_media_content_children(ctx, entry, depth)?;
            }
            Ok(true)
        }
        "group" => {
            // media:group is a transparent container; parse its children as if they
            // were direct siblings of the enclosing item.
            if !is_empty {
                parse_media_group(ctx, entry, depth)?;
            }
            Ok(true)
        }
        _ => Ok(false),
    }
}

/// Parse `media:*` metadata elements: rating, credit, copyright.
///
/// Every arm returns `Ok(true)` unconditionally; `is_empty` is only tested inside
/// arm bodies (see [`parse_item_media_object`]).
fn parse_item_media_meta(
    ctx: &mut EntryCtx,
    media_element: &str,
    attrs: &[(Vec<u8>, String)],
    entry: &mut Entry,
    is_empty: bool,
) -> Result<bool> {
    match media_element {
        "rating" => {
            if !is_empty {
                let scheme = find_attribute(attrs, b"scheme").map(str::to_owned);
                let text = read_text_str(ctx.xml.reader, ctx.xml.buf, ctx.xml.limits)?;
                media_rss::handle_entry_rating(scheme.as_deref(), &text, entry);
            }
            Ok(true)
        }
        "credit" => {
            let role = find_attribute(attrs, b"role").map(str::to_owned);
            let scheme = find_attribute(attrs, b"scheme").map(str::to_owned);
            let text = if is_empty {
                String::new()
            } else {
                read_text_str(ctx.xml.reader, ctx.xml.buf, ctx.xml.limits)?
            };
            if !text.is_empty() {
                entry.media_credit.try_push_limited(
                    MediaCredit {
                        role,
                        scheme,
                        content: text,
                    },
                    ctx.xml.limits.max_links_per_entry,
                );
            }
            Ok(true)
        }
        "copyright" => {
            let url = find_attribute(attrs, b"url").map(str::to_owned);
            if !is_empty {
                read_text_str(ctx.xml.reader, ctx.xml.buf, ctx.xml.limits)?;
            }
            entry.media_copyright = Some(MediaCopyright { url });
            Ok(true)
        }
        _ => Ok(false),
    }
}

/// Parse `media:*` text elements: description, title; falls back to the generic
/// Media RSS element handler for anything else.
fn parse_item_media_text(
    ctx: &mut EntryCtx,
    media_element: &str,
    attrs: &[(Vec<u8>, String)],
    entry: &mut Entry,
    is_empty: bool,
) -> Result<()> {
    match media_element {
        "description" => {
            let (text, is_plain) = read_media_text(ctx, attrs, is_empty)?;
            store_media_text(
                text,
                is_plain,
                &mut entry.media_description,
                &mut entry.summary,
            );
        }
        "title" => {
            let (text, is_plain) = read_media_text(ctx, attrs, is_empty)?;
            store_media_text(text, is_plain, &mut entry.media_title, &mut entry.title);
        }
        _ => {
            let media_elem = media_element.to_string();
            let (text, had_bozo) = read_item_text(&mut ctx.xml, is_empty)?;
            ctx.bozo |= had_bozo;
            media_rss::handle_entry_element(&media_elem, &text, entry, ctx.xml.limits);
        }
    }
    Ok(())
}

/// Reads a `media:title` or `media:description` and whether its `type` is plain text.
fn read_media_text(
    ctx: &mut EntryCtx,
    attrs: &[(Vec<u8>, String)],
    is_empty: bool,
) -> Result<(String, bool)> {
    let is_plain = find_attribute(attrs, b"type").is_none_or(|t| t == "plain");
    let text = if is_empty {
        String::new()
    } else {
        read_prose_str(ctx.xml.reader, ctx.xml.buf, ctx.xml.limits)?
    };
    Ok((text, is_plain))
}

/// Stores non-empty media text in its own field when plain, and in the native `fallback`
/// field when that is still blank.
fn store_media_text(
    text: String,
    is_plain: bool,
    own: &mut Option<String>,
    fallback: &mut Option<String>,
) {
    if text.is_empty() {
        return;
    }
    if fallback.as_deref().is_none_or(str::is_empty) {
        *fallback = Some(text.clone());
    }
    if is_plain {
        *own = Some(text);
    }
}

/// Parse children of `<media:group>`, treating the group as a transparent container.
///
/// Per the Media RSS spec, `<media:group>` groups related media objects but has no
/// semantic meaning of its own; its children are promoted to the parent item level.
fn parse_media_group(ctx: &mut EntryCtx, entry: &mut Entry, depth: usize) -> Result<()> {
    let mut inner_depth = depth;
    loop {
        ctx.xml.buf.clear();
        match ctx.xml.reader.read_event_into(ctx.xml.buf) {
            Ok(Event::Start(e)) => {
                inner_depth += 1;
                check_depth(inner_depth, ctx.xml.limits.max_nesting_depth)?;
                let tag = e.name().as_ref().as_bytes().to_vec();
                let (attrs, _) = collect_attributes(&e);
                if let Some(media_element) = is_media_tag(&tag, ctx.namespaces) {
                    parse_item_media(ctx, media_element, &attrs, entry, inner_depth, false)?;
                } else {
                    skip_element(ctx.xml.reader, ctx.xml.buf, ctx.xml.limits, inner_depth)?;
                }
                inner_depth = inner_depth.saturating_sub(1);
            }
            Ok(Event::Empty(e)) => {
                let tag = e.name().as_ref().as_bytes().to_vec();
                let (attrs, _) = collect_attributes(&e);
                if let Some(media_element) = is_media_tag(&tag, ctx.namespaces) {
                    parse_item_media(ctx, media_element, &attrs, entry, inner_depth, true)?;
                }
            }
            Ok(Event::End(_) | Event::Eof) | Err(_) => break,
            _ => {}
        }
    }
    Ok(())
}

/// Parse children of `<media:content>`, collecting nested `media:thumbnail` elements.
///
/// Python feedparser collects all `media:thumbnail` elements into `entry.media_thumbnail`
/// regardless of whether they are top-level or nested inside `media:content`.
fn parse_media_content_children(ctx: &mut EntryCtx, entry: &mut Entry, depth: usize) -> Result<()> {
    let mut inner_depth = depth;
    loop {
        ctx.xml.buf.clear();
        match ctx.xml.reader.read_event_into(ctx.xml.buf) {
            Ok(Event::Start(e)) => {
                inner_depth += 1;
                check_depth(inner_depth, ctx.xml.limits.max_nesting_depth)?;
                push_nested_thumbnail(&e, ctx.namespaces, ctx.xml.limits, entry);
                skip_element(ctx.xml.reader, ctx.xml.buf, ctx.xml.limits, inner_depth)?;
                inner_depth = inner_depth.saturating_sub(1);
            }
            Ok(Event::Empty(e)) => {
                push_nested_thumbnail(&e, ctx.namespaces, ctx.xml.limits, entry);
            }
            Ok(Event::End(_) | Event::Eof) => break,
            Err(_) => {
                ctx.bozo = true;
                break;
            }
            _ => {}
        }
    }
    Ok(())
}

/// Adds `element` to `entry.media_thumbnail` when it is a `media:thumbnail` with a URL.
fn push_nested_thumbnail(
    element: &BytesStart<'_>,
    namespaces: &HashMap<String, String>,
    limits: &ParserLimits,
    entry: &mut Entry,
) {
    if is_media_tag(element.name().as_ref().as_bytes(), namespaces) != Some("thumbnail") {
        return;
    }
    let (attrs, _) = collect_attributes(element);
    if let Some(thumb) = build_media_thumbnail(&attrs, limits) {
        entry
            .media_thumbnail
            .try_push_limited(thumb, limits.max_enclosures);
    }
}

/// Parse one `media:*` element at feed (channel) level.
pub(super) fn parse_feed_media(
    xml: &mut XmlCtx,
    media_element: &str,
    attrs: &[(Vec<u8>, String)],
    feed: &mut FeedMeta,
    depth: usize,
    is_empty: bool,
) -> Result<()> {
    match media_element {
        "thumbnail" => {
            if let Some(thumb) = build_media_thumbnail(attrs, xml.limits) {
                feed.media_thumbnail
                    .try_push_limited(thumb, xml.limits.max_enclosures);
            }
            if !is_empty {
                skip_element(xml.reader, xml.buf, xml.limits, depth)?;
            }
        }
        "content" => {
            if let Some(content) = build_media_content(attrs, xml.limits) {
                feed.media_content
                    .try_push_limited(content, xml.limits.max_enclosures);
            }
            if !is_empty {
                skip_element(xml.reader, xml.buf, xml.limits, depth)?;
            }
        }
        "rating" | "keywords" => {
            if !is_empty {
                let scheme = find_attribute(attrs, b"scheme").map(str::to_owned);
                let text = read_text_str(xml.reader, xml.buf, xml.limits)?;
                media_rss::handle_feed_element(media_element, scheme.as_deref(), &text, feed);
            }
        }
        _ => {
            if !is_empty {
                skip_element(xml.reader, xml.buf, xml.limits, depth)?;
            }
        }
    }
    Ok(())
}