Skip to main content

rss_gen/
parser.rs

1// Copyright © 2024 RSS Gen. All rights reserved.
2// SPDX-License-Identifier: Apache-2.0 OR MIT
3
4//! A robust and flexible RSS feed parser.
5//!
6//! This module provides functionality to parse RSS feeds of various versions
7//! (0.90, 0.91, 0.92, 1.0, and 2.0) and Atom 1.0 feeds into a structured
8//! format. It offers
9//! comprehensive error handling, extensive customization options, and follows
10//! best practices in Rust development.
11//!
12//! # Features
13//!
14//! - Supports RSS versions 0.90, 0.91, 0.92, 1.0, and 2.0
15//! - Parses Atom 1.0 (RFC 4287) feeds into the same [`RssData`] model
16//! - Robust error handling with custom error types
17//! - Extensible parsing with custom element handlers
18//! - Comprehensive test suite
19//! - Thread-safe and memory-efficient implementation
20//!
21//! # Examples
22//!
23//! ```rust
24//! use rss_gen::parse_rss;
25//!
26//! let xml_content = r#"
27//!     <?xml version="1.0" encoding="UTF-8"?>
28//!     <rss version="2.0">
29//!         <channel>
30//!             <title>My Blog</title>
31//!             <link>https://example.com</link>
32//!             <description>A sample blog</description>
33//!             <item>
34//!                 <title>First Post</title>
35//!                 <link>https://example.com/first-post</link>
36//!                 <description>This is my first post</description>
37//!             </item>
38//!         </channel>
39//!     </rss>
40//! "#;
41//!
42//! let parsed_data = parse_rss(xml_content, None).unwrap();
43//! assert_eq!(parsed_data.title, "My Blog");
44//! assert_eq!(parsed_data.items.len(), 1);
45//! ```
46
47use oxml::stream::{Event, Reader};
48use std::borrow::Cow;
49
50use crate::atom::{detect_feed_format, FeedFormat};
51use std::sync::Arc;
52
53pub use crate::data::{RssData, RssItem, RssVersion};
54pub use crate::error::{Result, RssError};
55
56/// A trait for custom element handlers, supporting RSS extensions.
57///
58/// Implement this trait to provide custom parsing logic for specific RSS elements.
59pub trait ElementHandler: Send + Sync {
60    /// Handle a specific RSS element.
61    ///
62    /// This function processes a single RSS element and performs necessary
63    /// operations based on the element's name, text content, and attributes.
64    ///
65    /// # Arguments
66    ///
67    /// * `name` - The name of the RSS element.
68    /// * `text` - The text content of the RSS element.
69    /// * `attributes` - A slice containing the attributes of the RSS element.
70    ///
71    /// # Returns
72    ///
73    /// This function returns a `Result<()>` indicating the success or failure of
74    /// the handling operation.
75    ///
76    /// # Errors
77    ///
78    /// This function will return an `Err` in the following situations:
79    ///
80    /// - If there is an issue with processing the element, such as invalid
81    ///   attributes, unexpected element names, or a failure in custom parsing
82    ///   logic.
83    fn handle_element(
84        &self,
85        name: &str,
86        text: &str,
87        attributes: &[(String, String)],
88    ) -> Result<()>;
89}
90
91/// Configuration options for the RSS parser.
92///
93/// The `ParserConfig` struct allows for customization of the RSS parser by
94/// including custom handlers for specific elements.
95#[derive(Default)]
96pub struct ParserConfig {
97    /// A vector of custom handlers that will process specific RSS elements.
98    ///
99    /// Each handler implements the `ElementHandler` trait and is wrapped in
100    /// an `Arc` to allow shared ownership across threads.
101    pub custom_handlers: Vec<Arc<dyn ElementHandler>>,
102}
103
104/// Parses a channel element and sets the corresponding field in `RssData`.
105///
106/// This function processes elements found within the `channel` tag of an RSS feed
107/// and assigns the appropriate values to the `RssData` struct.
108///
109/// # Arguments
110///
111/// * `rss_data` - A mutable reference to the `RssData` struct.
112/// * `element` - The name of the channel element.
113/// * `text` - The text content of the channel element.
114/// * `is_rss_1_0` - A boolean indicating if the feed is RSS 1.0.
115fn parse_channel_element(
116    rss_data: &mut RssData,
117    element: &str,
118    text: &str,
119    is_rss_1_0: bool,
120) -> Result<()> {
121    match element {
122        "title" => {
123            rss_data.title = text.to_string();
124            Ok(())
125        }
126        "link" => {
127            rss_data.link = text.to_string();
128            Ok(())
129        }
130        "description" => {
131            rss_data.description = text.to_string();
132            Ok(())
133        }
134        "language" => {
135            rss_data.language = text.to_string();
136            Ok(())
137        }
138        "copyright" => {
139            rss_data.copyright = text.to_string();
140            Ok(())
141        }
142        "managingEditor" => {
143            rss_data.managing_editor = text.to_string();
144            Ok(())
145        }
146        "webMaster" => {
147            rss_data.webmaster = text.to_string();
148            Ok(())
149        }
150        "pubDate" => {
151            rss_data.pub_date = text.to_string();
152            Ok(())
153        }
154        "lastBuildDate" => {
155            rss_data.last_build_date = text.to_string();
156            Ok(())
157        }
158        "category" => {
159            rss_data.category = text.to_string();
160            Ok(())
161        }
162        "generator" => {
163            rss_data.generator = text.to_string();
164            Ok(())
165        }
166        "docs" => {
167            rss_data.docs = text.to_string();
168            Ok(())
169        }
170        "ttl" => {
171            rss_data.ttl = text.to_string();
172            Ok(())
173        }
174        // Handle RSS 1.0 specific elements
175        "items" => {
176            if is_rss_1_0 {
177                Ok(())
178            } else {
179                Err(RssError::UnknownElement("items".into()))
180            }
181        }
182        "rdf:Seq" => {
183            if is_rss_1_0 {
184                Ok(())
185            } else {
186                Err(RssError::UnknownElement("rdf:Seq".into()))
187            }
188        }
189        "rdf:li" => {
190            if is_rss_1_0 {
191                Ok(())
192            } else {
193                Err(RssError::UnknownElement("rdf:li".into()))
194            }
195        }
196        _ => Err(RssError::UnknownElement(format!(
197            "Unknown channel element: {element}"
198        ))),
199    }
200}
201
202/// Parses an item element and sets the corresponding field in `RssItem`.
203///
204/// This function processes elements found within the `item` tag of an RSS feed
205/// and assigns the appropriate values to the `RssItem` struct.
206///
207/// # Arguments
208///
209/// * `item` - A mutable reference to the `RssItem` struct.
210/// * `element` - The name of the item element.
211/// * `text` - The text content of the item element.
212/// * `attributes` - A slice containing the element's attributes as key-value pairs.
213fn parse_item_element(
214    item: &mut RssItem,
215    element: &str,
216    text: &str,
217    attributes: &[(String, String)],
218) {
219    match element {
220        "title" => {
221            item.title = text.to_string();
222        }
223        "link" => {
224            item.link = text.to_string();
225        }
226        "description" => {
227            item.description = text.to_string();
228        }
229        "author" => {
230            item.author = text.to_string();
231        }
232        "guid" => {
233            item.guid = text.to_string();
234        }
235        "pubDate" => {
236            item.pub_date = text.to_string();
237        }
238        "category" => {
239            item.category = Some(text.to_string());
240        }
241        "comments" => {
242            item.comments = Some(text.to_string());
243        }
244        "enclosure" => {
245            if attributes.is_empty() {
246                item.enclosure = None;
247            } else {
248                let enclosure_str = attributes
249                    .iter()
250                    .map(|(k, v)| format!("{k}=\"{v}\""))
251                    .collect::<Vec<String>>()
252                    .join(" ");
253                item.enclosure = Some(enclosure_str);
254            }
255        }
256        "source" => {
257            item.source = Some(text.to_string());
258        }
259        _ => (), // Ignore unknown elements
260    }
261}
262
263/// Represents the current parsing state (whether inside a channel, item, or image).
264#[derive(Clone)]
265enum ParsingState {
266    Channel,
267    Item,
268    Image,
269    None, // When not in any of these states
270}
271
272/// Represents the context of the current element being parsed in the RSS feed.
273struct ParsingContext<'a> {
274    is_rss_1_0: bool,
275    state: ParsingState,
276    current_element: &'a str,
277    text: &'a str,
278    current_attributes: &'a [(String, String)],
279}
280
281impl ParsingContext<'_> {
282    /// Helper function to check if the current state is in a channel.
283    pub(crate) fn in_channel(&self) -> bool {
284        matches!(self.state, ParsingState::Channel)
285    }
286
287    /// Helper function to check if the current state is in an item.
288    pub(crate) fn in_item(&self) -> bool {
289        matches!(self.state, ParsingState::Item)
290    }
291
292    /// Helper function to check if the current state is in an image.
293    pub(crate) fn in_image(&self) -> bool {
294        matches!(self.state, ParsingState::Image)
295    }
296}
297
298/// Represents the image data in an RSS feed.
299struct ImageData {
300    title: String,
301    url: String,
302    link: String,
303}
304
305/// Handles text events for both regular text and CDATA in RSS feeds.
306///
307/// This function processes both text and CDATA events, parsing the content
308/// and assigning values to either channel, item, or image elements in the feed.
309///
310/// # Arguments
311///
312/// * `rss_data` - A mutable reference to the `RssData` struct representing the RSS feed being processed.
313/// * `context` - A `ParsingContext` struct containing details about the current state of the parser (e.g., whether it's within a channel, item, or image, and the element being processed).
314/// * `current_item` - A mutable reference to the `RssItem` struct, representing the current item being parsed in the RSS feed.
315/// * `image_data` - A mutable reference to an `ImageData` struct for storing the parsed `title`, `url`, and `link` of the image element if applicable.
316///
317/// # Returns
318///
319/// A `Result` indicating the success or failure of handling the text event.
320fn handle_text_event(
321    rss_data: &mut RssData,
322    context: &ParsingContext,
323    current_item: &mut RssItem,
324    image_data: &mut ImageData,
325) -> Result<()> {
326    if context.in_channel() && !context.in_item() && !context.in_image()
327    {
328        if !context.current_element.is_empty() {
329            parse_channel_element(
330                rss_data,
331                context.current_element,
332                &Cow::Owned(context.text.to_string()),
333                context.is_rss_1_0,
334            )?;
335        }
336    } else if context.in_item() && !context.current_element.is_empty() {
337        parse_item_element(
338            current_item,
339            context.current_element,
340            context.text,
341            context.current_attributes,
342        );
343    } else if context.in_image() && !context.current_element.is_empty()
344    {
345        match context.current_element {
346            "title" => image_data.title = context.text.to_string(),
347            "url" => image_data.url = context.text.to_string(),
348            "link" => image_data.link = context.text.to_string(),
349            _ => (),
350        }
351    }
352    Ok(())
353}
354
355/// Parses an RSS feed from XML content.
356///
357/// This function takes XML content as input and parses it into an `RssData` struct.
358/// It supports parsing RSS versions 0.90, 0.91, 0.92, 1.0, and 2.0, and
359/// Atom 1.0 feeds (a `<feed>` root in the Atom namespace). Atom elements
360/// are mapped onto the RSS fields: `subtitle` to `description`, `id` to
361/// `guid`, the feed's `updated` to `last_build_date`, an entry's
362/// `published` (or `updated`) to `pub_date`, its `summary` (or
363/// `content`) to `description`, and `author/name` to `author`.
364///
365/// # Arguments
366///
367/// * `xml_content` - A string slice containing the XML content of the RSS feed.
368/// * `config` - Optional configuration for custom parsing behavior.
369///
370/// # Returns
371///
372/// * `Ok(RssData)` - The parsed RSS data if successful.
373/// * `Err(RssError)` - An error if parsing fails.
374///
375/// # Errors
376///
377/// This function returns an `Err(RssError)` in the following cases:
378///
379/// - If the XML content is invalid or malformed, a `RssError::XmlParseError` is returned.
380/// - If an unsupported or invalid RSS version is encountered, a `RssError::InvalidInput` is returned.
381/// - If an unknown or unsupported element is encountered during parsing, a `RssError::UnknownElement` is returned.
382pub fn parse_rss(
383    xml_content: &str,
384    config: Option<&ParserConfig>,
385) -> Result<RssData> {
386    if detect_feed_format(xml_content) == FeedFormat::Atom {
387        return crate::atom_parser::parse_atom(xml_content, config);
388    }
389    parse_rss_events(xml_content, config)
390}
391
392/// Runs the RSS event loop over `xml_content`.
393fn parse_rss_events(
394    xml_content: &str,
395    config: Option<&ParserConfig>,
396) -> Result<RssData> {
397    let mut reader = Reader::new(xml_content.trim_start())?;
398    let mut rss_data = RssData::new(None);
399    let mut context = ParserContext::new();
400
401    while let Some(event) = reader.next_event()? {
402        handle_rss_event(event, &mut context, &mut rss_data, config)?;
403    }
404    Ok(rss_data)
405}
406
407/// Joins an optional prefix and a local name into a qualified name
408/// (`prefix:local`), as the element handlers expect.
409fn qualified_name(prefix: Option<&str>, local: String) -> String {
410    match prefix {
411        Some(p) if !p.is_empty() => format!("{p}:{local}"),
412        _ => local,
413    }
414}
415
416/// Dispatches one stream event to the start, end or text handler.
417fn handle_rss_event(
418    event: Event,
419    context: &mut ParserContext,
420    rss_data: &mut RssData,
421    config: Option<&ParserConfig>,
422) -> Result<()> {
423    match event {
424        Event::StartElement {
425            name,
426            prefix,
427            attributes,
428            ..
429        } => {
430            let qname = qualified_name(prefix.as_deref(), name.local);
431            let attrs: Vec<(String, String)> = attributes
432                .into_iter()
433                .map(|(n, v)| (n.local, v))
434                .collect();
435            process_start_event(&qname, attrs, context, rss_data)
436        }
437        Event::EndElement { name, prefix, .. } => {
438            let qname = qualified_name(prefix.as_deref(), name.local);
439            process_end_event(&qname, context, rss_data);
440            Ok(())
441        }
442        Event::Text(text) if !text.trim().is_empty() => {
443            process_text_event(&text, context, rss_data, config)
444        }
445        _ => Ok(()),
446    }
447}
448
449/// Processes the start event of an XML element during RSS feed parsing.
450///
451/// This function handles the start of an XML element in an RSS feed, determining the RSS version,
452/// handling different element types (e.g., "channel", "item", "image"), and extracting attributes
453/// from the element.
454///
455/// # Arguments
456///
457/// * `name_str` - The qualified name of the XML element.
458/// * `attributes` - Key-value attribute pairs on the element.
459/// * `context` - A mutable reference to the `ParserContext` struct, which maintains the current parsing state.
460/// * `rss_data` - A mutable reference to the `RssData` struct, which stores the parsed RSS data.
461fn process_start_event(
462    name_str: &str,
463    attributes: Vec<(String, String)>,
464    context: &mut ParserContext,
465    _rss_data: &mut RssData,
466) -> Result<()> {
467    if name_str.is_empty() {
468        return Ok(());
469    }
470
471    // Detect RSS version or RDF for RSS 1.0
472    match name_str {
473        "rss" => {
474            return Ok(());
475        }
476        "rdf:RDF" => {
477            context.rss_version = RssVersionState::Rss1_0;
478            return Ok(());
479        }
480        "channel" => {
481            // Correctly handle the `channel` element inside the RSS root
482            context.parsing_state = ParsingState::Channel;
483            return Ok(());
484        }
485        "item" => {
486            context.parsing_state = ParsingState::Item;
487            context.current_item = RssItem::new();
488        }
489        "image" => {
490            context.parsing_state = ParsingState::Image;
491        }
492        _ => {
493            // Only return an error for truly unknown elements, ignoring root elements
494            if !matches!(
495                context.parsing_state,
496                ParsingState::Item
497                    | ParsingState::Channel
498                    | ParsingState::Image
499            ) {
500                return Err(RssError::UnknownElement(format!(
501                    "Unknown element: {name_str}"
502                )));
503            }
504        }
505    }
506
507    // Store current element and attributes
508    context.current_element = name_str.to_string();
509    context.current_attributes = attributes;
510
511    if matches!(context.parsing_state, ParsingState::Item)
512        && name_str == "enclosure"
513    {
514        parse_item_element(
515            &mut context.current_item,
516            "enclosure",
517            "",
518            &context.current_attributes,
519        );
520    }
521
522    Ok(())
523}
524
525/// Processes the end event of an XML element during RSS feed parsing.
526///
527/// This function handles the end of an XML element in an RSS feed, updating the parsing state
528/// based on the element type (e.g., "channel", "item", "image").
529///
530/// # Arguments
531///
532/// * `name` - The qualified name of the closing XML element.
533/// * `context` - A mutable reference to the `ParserContext` struct, which maintains the current parsing state.
534/// * `rss_data` - A mutable reference to the `RssData` struct, which stores the parsed RSS data.
535fn process_end_event(
536    name: &str,
537    context: &mut ParserContext,
538    rss_data: &mut RssData,
539) {
540    if name == "channel" {
541        if matches!(context.parsing_state, ParsingState::Channel) {
542            context.parsing_state = ParsingState::None;
543        }
544    } else if name == "item" {
545        if matches!(context.parsing_state, ParsingState::Item) {
546            context.parsing_state = ParsingState::None;
547            rss_data.add_item(context.current_item.clone());
548        }
549    } else if name == "image"
550        && matches!(context.parsing_state, ParsingState::Image)
551    {
552        context.parsing_state = ParsingState::None;
553        rss_data.set_image(
554            &context.image_title.clone(),
555            &context.image_url.clone(),
556            &context.image_link.clone(),
557        );
558    }
559    context.current_element.clear();
560    context.current_attributes.clear();
561}
562
563fn process_text_event(
564    text: &str,
565    context: &mut ParserContext,
566    rss_data: &mut RssData,
567    config: Option<&ParserConfig>,
568) -> Result<()> {
569    let parse_context = ParsingContext {
570        is_rss_1_0: matches!(
571            context.rss_version,
572            RssVersionState::Rss1_0
573        ),
574        state: context.parsing_state.clone(),
575        current_element: &context.current_element,
576        text,
577        current_attributes: &context.current_attributes,
578    };
579
580    let mut image_data = ImageData {
581        title: context.image_title.clone(),
582        url: context.image_url.clone(),
583        link: context.image_link.clone(),
584    };
585
586    handle_text_event(
587        rss_data,
588        &parse_context,
589        &mut context.current_item,
590        &mut image_data,
591    )?;
592
593    context.image_title = image_data.title;
594    context.image_url = image_data.url;
595    context.image_link = image_data.link;
596
597    // Custom handlers can be applied if necessary
598    apply_custom_handlers(
599        &context.current_element,
600        text,
601        &context.current_attributes,
602        config,
603    )?;
604
605    Ok(())
606}
607
608/// Processes a CDATA event for the current XML element.
609#[cfg(test)]
610fn process_cdata_event(
611    text: &str,
612    context: &mut ParserContext,
613    rss_data: &mut RssData,
614    config: Option<&ParserConfig>,
615) -> Result<()> {
616    process_text_event(text, context, rss_data, config)
617}
618
619/// Applies custom handlers for RSS elements.
620///
621/// This function checks if any custom handlers are provided in the configuration and applies them to the current element.
622///
623/// # Arguments
624///
625/// * `element` - The current XML element being processed.
626/// * `text` - The text content of the element.
627/// * `attributes` - The attributes of the element.
628/// * `config` - Optional parser configuration containing custom handlers.
629fn apply_custom_handlers(
630    element: &str,
631    text: &str,
632    attributes: &[(String, String)],
633    config: Option<&ParserConfig>,
634) -> Result<()> {
635    if let Some(cfg) = config {
636        for handler in &cfg.custom_handlers {
637            handler.handle_element(element, text, attributes)?;
638        }
639    }
640    Ok(())
641}
642
643/// Enum to represent the RSS version being parsed.
644#[allow(dead_code)]
645enum RssVersionState {
646    Rss1_0,
647    Other,
648}
649
650/// Represents the context of the current XML element being parsed.
651struct ParserContext {
652    rss_version: RssVersionState,
653    parsing_state: ParsingState,
654    current_element: String,
655    current_attributes: Vec<(String, String)>,
656    current_item: RssItem,
657    image_title: String,
658    image_url: String,
659    image_link: String,
660}
661
662impl ParserContext {
663    /// Initialize a new `ParserContext` with default values.
664    pub(crate) fn new() -> Self {
665        ParserContext {
666            rss_version: RssVersionState::Other,
667            parsing_state: ParsingState::None,
668            current_element: String::new(),
669            current_attributes: Vec::new(),
670            current_item: RssItem::new(),
671            image_title: String::new(),
672            image_url: String::new(),
673            image_link: String::new(),
674        }
675    }
676}
677
678impl std::fmt::Debug for ParserConfig {
679    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
680        f.debug_struct("ParserConfig")
681            .field(
682                "custom_handlers",
683                &format!("[{} handlers]", self.custom_handlers.len()),
684            )
685            .finish()
686    }
687}
688
689#[cfg(test)]
690mod tests {
691    use super::*;
692    use std::sync::Arc;
693
694    struct MockElementHandler;
695
696    impl ElementHandler for MockElementHandler {
697        fn handle_element(
698            &self,
699            name: &str,
700            text: &str,
701            _attributes: &[(String, String)],
702        ) -> Result<()> {
703            if name == "customElement" && text == "Custom content" {
704                Ok(())
705            } else {
706                Err(RssError::UnknownElement(name.into()))
707            }
708        }
709    }
710
711    #[test]
712    fn test_parser_config_with_custom_handler() {
713        let handler = Arc::new(MockElementHandler);
714        let config = ParserConfig {
715            custom_handlers: vec![handler],
716        };
717
718        assert_eq!(config.custom_handlers.len(), 1);
719        assert!(config.custom_handlers[0]
720            .handle_element("customElement", "Custom content", &[])
721            .is_ok());
722    }
723
724    #[test]
725    fn test_parser_config_no_custom_handlers() {
726        let config = ParserConfig::default();
727        assert!(config.custom_handlers.is_empty());
728    }
729
730    #[test]
731    fn test_process_start_event_empty_name() {
732        let mut context = ParserContext::new();
733        let mut rss_data = RssData::default();
734
735        let result = process_start_event(
736            "",
737            Vec::new(),
738            &mut context,
739            &mut rss_data,
740        );
741        assert!(result.is_ok());
742    }
743
744    #[test]
745    fn test_process_start_event_non_empty_name() {
746        let mut context = ParserContext::new();
747        let mut rss_data = RssData::default();
748
749        let result = process_start_event(
750            "item",
751            Vec::new(),
752            &mut context,
753            &mut rss_data,
754        );
755        assert!(result.is_ok());
756        assert_eq!(context.current_element, "item");
757    }
758
759    #[test]
760    fn test_process_text_event() {
761        let mut context = ParserContext::new();
762        let mut rss_data = RssData::default();
763
764        let result = process_text_event(
765            "Sample Text",
766            &mut context,
767            &mut rss_data,
768            None,
769        );
770        assert!(result.is_ok());
771    }
772
773    #[test]
774    fn test_process_cdata_event() {
775        let mut context = ParserContext::new();
776        let mut rss_data = RssData::default();
777
778        let result = process_cdata_event(
779            "Sample CDATA",
780            &mut context,
781            &mut rss_data,
782            None,
783        );
784        assert!(result.is_ok());
785    }
786
787    #[test]
788    fn test_parse_channel_rdf_li_rss_1_0() {
789        let mut rss_data = RssData::default();
790        let result =
791            parse_channel_element(&mut rss_data, "rdf:li", "", true);
792        assert!(result.is_ok());
793    }
794
795    #[test]
796    fn test_parse_channel_rdf_li_non_rss_1_0() {
797        let mut rss_data = RssData::default();
798        let result =
799            parse_channel_element(&mut rss_data, "rdf:li", "", false);
800        assert!(result.is_err());
801    }
802
803    #[test]
804    fn test_parse_channel_unknown_element() {
805        let mut rss_data = RssData::default();
806        let result = parse_channel_element(
807            &mut rss_data,
808            "unknownElement",
809            "",
810            false,
811        );
812        assert!(result.is_err());
813    }
814
815    #[test]
816    fn test_parse_rss_with_image() {
817        let rss_xml = r#"
818        <?xml version="1.0" encoding="UTF-8"?>
819        <rss version="2.0">
820          <channel>
821            <title>Sample Feed</title>
822            <link>https://example.com</link>
823            <description>A sample RSS feed</description>
824            <image>
825              <title>Sample Image</title>
826              <url>https://example.com/image.jpg</url>
827              <link>https://example.com</link>
828            </image>
829          </channel>
830        </rss>
831        "#;
832
833        let result = parse_rss(rss_xml, None);
834
835        match result {
836            Ok(parsed_data) => {
837                assert_eq!(parsed_data.title, "Sample Feed");
838                assert_eq!(parsed_data.image_title, "Sample Image");
839            }
840            Err(RssError::UnknownElement(element)) => {
841                panic!("Failed due to unknown element: {element:?}");
842            }
843            Err(e) => panic!("Failed to parse RSS with image: {e:?}"),
844        }
845    }
846
847    #[test]
848    fn test_parse_rss_1_0() {
849        let rss_xml = r#"
850        <?xml version="1.0" encoding="UTF-8"?>
851        <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
852                 xmlns="http://purl.org/rss/1.0/">
853          <channel rdf:about="https://example.com">
854            <title>Sample Feed</title>
855            <link>https://example.com</link>
856            <description>A sample RSS feed</description>
857          </channel>
858        </rdf:RDF>
859        "#;
860
861        let result = parse_rss(rss_xml, None);
862
863        match result {
864            Ok(parsed_data) => {
865                assert_eq!(parsed_data.title, "Sample Feed");
866            }
867            Err(RssError::UnknownElement(element)) => {
868                panic!("Failed due to unknown element: {element:?}");
869            }
870            Err(e) => panic!("Failed to parse RSS 1.0: {e:?}"),
871        }
872    }
873
874    #[test]
875    fn test_parse_rss_2_0() {
876        let rss_xml = r#"
877        <?xml version="1.0" encoding="UTF-8"?>
878        <rss version="2.0">
879          <channel>
880            <title>Sample Feed</title>
881            <link>https://example.com</link>
882            <description>A sample RSS feed</description>
883          </channel>
884        </rss>
885        "#;
886
887        let result = parse_rss(rss_xml, None);
888
889        match result {
890            Ok(parsed_data) => {
891                assert_eq!(parsed_data.title, "Sample Feed");
892            }
893            Err(RssError::UnknownElement(element)) => {
894                panic!("Failed due to unknown element: {element:?}");
895            }
896            Err(e) => panic!("Failed to parse RSS 2.0: {e:?}"),
897        }
898    }
899
900    #[test]
901    fn test_parse_channel_language() {
902        let mut rss_data = RssData::default();
903        let result = parse_channel_element(
904            &mut rss_data,
905            "language",
906            "en-US",
907            false,
908        );
909        assert!(result.is_ok());
910        assert_eq!(rss_data.language, "en-US");
911    }
912
913    #[test]
914    fn test_parse_channel_copyright() {
915        let mut rss_data = RssData::default();
916        let result = parse_channel_element(
917            &mut rss_data,
918            "copyright",
919            "© 2024",
920            false,
921        );
922        assert!(result.is_ok());
923        assert_eq!(rss_data.copyright, "© 2024");
924    }
925
926    #[test]
927    fn test_parse_channel_managing_editor() {
928        let mut rss_data = RssData::default();
929        let result = parse_channel_element(
930            &mut rss_data,
931            "managingEditor",
932            "editor@example.com",
933            false,
934        );
935        assert!(result.is_ok());
936        assert_eq!(rss_data.managing_editor, "editor@example.com");
937    }
938
939    #[test]
940    fn test_parse_channel_webmaster() {
941        let mut rss_data = RssData::default();
942        let result = parse_channel_element(
943            &mut rss_data,
944            "webMaster",
945            "webmaster@example.com",
946            false,
947        );
948        assert!(result.is_ok());
949        assert_eq!(rss_data.webmaster, "webmaster@example.com");
950    }
951
952    #[test]
953    fn test_parse_channel_pub_date() {
954        let mut rss_data = RssData::default();
955        let result = parse_channel_element(
956            &mut rss_data,
957            "pubDate",
958            "Mon, 10 Oct 2024 04:00:00 GMT",
959            false,
960        );
961        assert!(result.is_ok());
962        assert_eq!(rss_data.pub_date, "Mon, 10 Oct 2024 04:00:00 GMT");
963    }
964
965    #[test]
966    fn test_parse_channel_last_build_date() {
967        let mut rss_data = RssData::default();
968        let result = parse_channel_element(
969            &mut rss_data,
970            "lastBuildDate",
971            "Mon, 10 Oct 2024 05:00:00 GMT",
972            false,
973        );
974        assert!(result.is_ok());
975        assert_eq!(
976            rss_data.last_build_date,
977            "Mon, 10 Oct 2024 05:00:00 GMT"
978        );
979    }
980
981    #[test]
982    fn test_parse_channel_category() {
983        let mut rss_data = RssData::default();
984        let result = parse_channel_element(
985            &mut rss_data,
986            "category",
987            "Technology",
988            false,
989        );
990        assert!(result.is_ok());
991        assert_eq!(rss_data.category, "Technology");
992    }
993
994    #[test]
995    fn test_parse_channel_generator() {
996        let mut rss_data = RssData::default();
997        let result = parse_channel_element(
998            &mut rss_data,
999            "generator",
1000            "RSS Generator v1.0",
1001            false,
1002        );
1003        assert!(result.is_ok());
1004        assert_eq!(rss_data.generator, "RSS Generator v1.0");
1005    }
1006
1007    #[test]
1008    fn test_parse_channel_docs() {
1009        let mut rss_data = RssData::default();
1010        let result = parse_channel_element(
1011            &mut rss_data,
1012            "docs",
1013            "https://example.com/rss/docs",
1014            false,
1015        );
1016        assert!(result.is_ok());
1017        assert_eq!(rss_data.docs, "https://example.com/rss/docs");
1018    }
1019
1020    #[test]
1021    fn test_parse_channel_ttl() {
1022        let mut rss_data = RssData::default();
1023        let result =
1024            parse_channel_element(&mut rss_data, "ttl", "60", false);
1025        assert!(result.is_ok());
1026        assert_eq!(rss_data.ttl, "60");
1027    }
1028
1029    #[test]
1030    fn test_parse_channel_items_rss_1_0() {
1031        let mut rss_data = RssData::default();
1032        let result =
1033            parse_channel_element(&mut rss_data, "items", "", true);
1034        assert!(result.is_ok());
1035    }
1036
1037    #[test]
1038    fn test_parse_channel_items_non_rss_1_0() {
1039        let mut rss_data = RssData::default();
1040        let result =
1041            parse_channel_element(&mut rss_data, "items", "", false);
1042        assert!(result.is_err());
1043    }
1044
1045    #[test]
1046    fn test_parse_channel_rdf_seq_rss_1_0() {
1047        let mut rss_data = RssData::default();
1048        let result =
1049            parse_channel_element(&mut rss_data, "rdf:Seq", "", true);
1050        assert!(result.is_ok());
1051    }
1052
1053    #[test]
1054    fn test_parse_channel_rdf_seq_non_rss_1_0() {
1055        let mut rss_data = RssData::default();
1056        let result =
1057            parse_channel_element(&mut rss_data, "rdf:Seq", "", false);
1058        assert!(result.is_err());
1059    }
1060
1061    #[test]
1062    fn test_parse_item_author() {
1063        let mut item = RssItem::default();
1064        parse_item_element(
1065            &mut item,
1066            "author",
1067            "author@example.com",
1068            &[],
1069        );
1070        assert_eq!(item.author, "author@example.com");
1071    }
1072
1073    #[test]
1074    fn test_parse_item_guid() {
1075        let mut item = RssItem::default();
1076        parse_item_element(&mut item, "guid", "1234-5678", &[]);
1077        assert_eq!(item.guid, "1234-5678");
1078    }
1079
1080    #[test]
1081    fn test_parse_item_pub_date() {
1082        let mut item = RssItem::default();
1083        parse_item_element(
1084            &mut item,
1085            "pubDate",
1086            "Mon, 10 Oct 2024 04:00:00 GMT",
1087            &[],
1088        );
1089        assert_eq!(item.pub_date, "Mon, 10 Oct 2024 04:00:00 GMT");
1090    }
1091
1092    #[test]
1093    fn test_parse_item_category() {
1094        let mut item = RssItem::default();
1095        parse_item_element(&mut item, "category", "Technology", &[]);
1096        assert_eq!(item.category, Some("Technology".to_string()));
1097    }
1098
1099    #[test]
1100    fn test_parse_item_comments() {
1101        let mut item = RssItem::default();
1102        parse_item_element(
1103            &mut item,
1104            "comments",
1105            "https://example.com/comments",
1106            &[],
1107        );
1108        assert_eq!(
1109            item.comments,
1110            Some("https://example.com/comments".to_string())
1111        );
1112    }
1113
1114    #[test]
1115    fn test_parse_item_enclosure_with_attributes() {
1116        let mut item = RssItem::default();
1117        let attributes = vec![
1118            (
1119                "url".to_string(),
1120                "https://example.com/audio.mp3".to_string(),
1121            ),
1122            ("length".to_string(), "123456".to_string()),
1123            ("type".to_string(), "audio/mpeg".to_string()),
1124        ];
1125        parse_item_element(&mut item, "enclosure", "", &attributes);
1126        assert_eq!(
1127            item.enclosure,
1128            Some("url=\"https://example.com/audio.mp3\" length=\"123456\" type=\"audio/mpeg\"".to_string())
1129        );
1130    }
1131
1132    #[test]
1133    fn test_parse_item_enclosure_without_attributes() {
1134        let mut item = RssItem::default();
1135        parse_item_element(&mut item, "enclosure", "", &[]);
1136        assert_eq!(item.enclosure, None);
1137    }
1138
1139    #[test]
1140    fn test_parse_item_source() {
1141        let mut item = RssItem::default();
1142        parse_item_element(
1143            &mut item,
1144            "source",
1145            "https://example.com",
1146            &[],
1147        );
1148        assert_eq!(
1149            item.source,
1150            Some("https://example.com".to_string())
1151        );
1152    }
1153
1154    #[test]
1155    fn test_process_text_event_in_channel() {
1156        let mut context = ParserContext::new();
1157        context.parsing_state = ParsingState::Channel;
1158        context.current_element = "title".to_string();
1159        let mut rss_data = RssData::default();
1160
1161        let result = process_text_event(
1162            "Channel Title",
1163            &mut context,
1164            &mut rss_data,
1165            None,
1166        );
1167        assert!(result.is_ok());
1168        assert_eq!(rss_data.title, "Channel Title");
1169    }
1170
1171    #[test]
1172    fn test_process_text_event_in_item() {
1173        let mut context = ParserContext::new();
1174        context.parsing_state = ParsingState::Item;
1175        context.current_element = "title".to_string();
1176        let mut rss_data = RssData::default();
1177
1178        let result = process_text_event(
1179            "Item Title",
1180            &mut context,
1181            &mut rss_data,
1182            None,
1183        );
1184        assert!(result.is_ok());
1185        assert_eq!(context.current_item.title, "Item Title");
1186    }
1187
1188    #[test]
1189    fn test_process_cdata_event_in_channel() {
1190        let mut context = ParserContext::new();
1191        context.parsing_state = ParsingState::Channel;
1192        context.current_element = "description".to_string();
1193        let mut rss_data = RssData::default();
1194
1195        let result = process_cdata_event(
1196            "CDATA Description",
1197            &mut context,
1198            &mut rss_data,
1199            None,
1200        );
1201        assert!(result.is_ok());
1202        assert_eq!(rss_data.description, "CDATA Description");
1203    }
1204
1205    #[test]
1206    fn test_process_cdata_event_in_item() {
1207        let mut context = ParserContext::new();
1208        context.parsing_state = ParsingState::Item;
1209        context.current_element = "description".to_string();
1210        let mut rss_data = RssData::default();
1211
1212        let result = process_cdata_event(
1213            "CDATA Item Desc",
1214            &mut context,
1215            &mut rss_data,
1216            None,
1217        );
1218        assert!(result.is_ok());
1219        assert_eq!(context.current_item.description, "CDATA Item Desc");
1220    }
1221
1222    #[test]
1223    fn test_process_text_event_with_custom_handler() {
1224        let handler = Arc::new(MockElementHandler);
1225        let config = ParserConfig {
1226            custom_handlers: vec![handler],
1227        };
1228
1229        let mut context = ParserContext::new();
1230        // Use None state so handle_text_event skips channel/item/image parsing
1231        // and apply_custom_handlers is invoked with the element and text
1232        context.current_element = "customElement".to_string();
1233        let mut rss_data = RssData::default();
1234
1235        let result = process_text_event(
1236            "Custom content",
1237            &mut context,
1238            &mut rss_data,
1239            Some(&config),
1240        );
1241        assert!(result.is_ok());
1242    }
1243
1244    #[test]
1245    fn test_parse_rss_with_cdata() {
1246        let rss_xml = r#"
1247        <?xml version="1.0" encoding="UTF-8"?>
1248        <rss version="2.0">
1249          <channel>
1250            <title>CDATA Feed</title>
1251            <link>https://example.com</link>
1252            <description><![CDATA[A feed with <b>CDATA</b> content]]></description>
1253            <item>
1254              <title><![CDATA[CDATA Item]]></title>
1255              <link>https://example.com/item1</link>
1256              <description><![CDATA[Item with <em>HTML</em>]]></description>
1257            </item>
1258          </channel>
1259        </rss>
1260        "#;
1261
1262        let result = parse_rss(rss_xml, None);
1263        assert!(result.is_ok());
1264        let data = result.unwrap();
1265        assert_eq!(data.title, "CDATA Feed");
1266        assert!(data.description.contains("CDATA"));
1267        assert_eq!(data.items.len(), 1);
1268        assert_eq!(data.items[0].title, "CDATA Item");
1269    }
1270
1271    #[test]
1272    fn test_process_text_event_with_escaped_entities() {
1273        let rss_xml = r#"<?xml version="1.0" encoding="UTF-8"?>
1274        <rss version="2.0">
1275          <channel>
1276            <title>&amp; &lt; &gt;</title>
1277            <link>https://example.com</link>
1278            <description>Desc</description>
1279          </channel>
1280        </rss>"#;
1281
1282        let data = parse_rss(rss_xml, None).unwrap();
1283        assert_eq!(data.title, "& < >");
1284    }
1285
1286    #[test]
1287    fn test_process_start_event_unknown_element_outside_context() {
1288        let mut context = ParserContext::new();
1289        // State is None, so unknown element triggers error
1290        context.parsing_state = ParsingState::None;
1291        let mut rss_data = RssData::default();
1292
1293        let result = process_start_event(
1294            "unknownRoot",
1295            Vec::new(),
1296            &mut context,
1297            &mut rss_data,
1298        );
1299        assert!(result.is_err());
1300    }
1301
1302    #[test]
1303    fn test_parse_rss_with_all_channel_fields() {
1304        let rss_xml = r#"
1305        <?xml version="1.0" encoding="UTF-8"?>
1306        <rss version="2.0">
1307          <channel>
1308            <title>Full Channel</title>
1309            <link>https://example.com</link>
1310            <description>A complete channel</description>
1311            <language>en-US</language>
1312            <copyright>2024</copyright>
1313            <managingEditor>editor@example.com</managingEditor>
1314            <webMaster>webmaster@example.com</webMaster>
1315            <pubDate>Mon, 01 Jan 2024 00:00:00 GMT</pubDate>
1316            <lastBuildDate>Mon, 01 Jan 2024 00:00:00 GMT</lastBuildDate>
1317            <category>Technology</category>
1318            <generator>Test Generator</generator>
1319            <docs>https://example.com/docs</docs>
1320            <ttl>60</ttl>
1321            <item>
1322              <title>Item 1</title>
1323              <link>https://example.com/item1</link>
1324              <description>First item</description>
1325              <author>author@example.com</author>
1326              <category>Cat1</category>
1327              <comments>https://example.com/item1/comments</comments>
1328              <source>https://example.com</source>
1329            </item>
1330          </channel>
1331        </rss>
1332        "#;
1333
1334        let result = parse_rss(rss_xml, None);
1335        assert!(result.is_ok());
1336        let data = result.unwrap();
1337        assert_eq!(data.title, "Full Channel");
1338        assert_eq!(data.language, "en-US");
1339        assert_eq!(data.copyright, "2024");
1340        assert_eq!(data.managing_editor, "editor@example.com");
1341        assert_eq!(data.webmaster, "webmaster@example.com");
1342        assert_eq!(data.category, "Technology");
1343        assert_eq!(data.generator, "Test Generator");
1344        assert_eq!(data.docs, "https://example.com/docs");
1345        assert_eq!(data.ttl, "60");
1346        assert_eq!(data.items.len(), 1);
1347        assert_eq!(data.items[0].author, "author@example.com");
1348        assert_eq!(data.items[0].category, Some("Cat1".to_string()));
1349        assert_eq!(
1350            data.items[0].comments,
1351            Some("https://example.com/item1/comments".to_string())
1352        );
1353        assert_eq!(
1354            data.items[0].source,
1355            Some("https://example.com".to_string())
1356        );
1357    }
1358
1359    #[test]
1360    fn test_parse_rss_malformed_xml() {
1361        let xml = "<rss><channel><title>Test</unclosed";
1362        let result = parse_rss(xml, None);
1363        assert!(result.is_err());
1364    }
1365
1366    #[test]
1367    fn test_parse_rss_with_cdata_in_image() {
1368        let rss_xml = r#"<?xml version="1.0" encoding="UTF-8"?>
1369        <rss version="2.0">
1370          <channel>
1371            <title>Test Feed</title>
1372            <link>https://example.com</link>
1373            <description>Test</description>
1374            <image>
1375              <title><![CDATA[Image Title]]></title>
1376              <url><![CDATA[https://example.com/image.png]]></url>
1377              <link><![CDATA[https://example.com]]></link>
1378            </image>
1379            <item>
1380              <title>Item 1</title>
1381              <link>https://example.com/1</link>
1382              <description>Desc</description>
1383            </item>
1384          </channel>
1385        </rss>
1386        "#;
1387
1388        let result = parse_rss(rss_xml, None);
1389        assert!(result.is_ok());
1390        let data = result.unwrap();
1391        assert_eq!(data.image_title, "Image Title");
1392        assert_eq!(data.image_url, "https://example.com/image.png");
1393        assert_eq!(data.image_link, "https://example.com");
1394    }
1395
1396    #[test]
1397    fn test_parse_rss_with_cdata_in_item() {
1398        let rss_xml = r#"<?xml version="1.0" encoding="UTF-8"?>
1399        <rss version="2.0">
1400          <channel>
1401            <title>Test Feed</title>
1402            <link>https://example.com</link>
1403            <description>Test</description>
1404            <item>
1405              <title><![CDATA[CDATA Item Title]]></title>
1406              <link>https://example.com/1</link>
1407              <description><![CDATA[<p>HTML content</p>]]></description>
1408            </item>
1409          </channel>
1410        </rss>
1411        "#;
1412
1413        let result = parse_rss(rss_xml, None);
1414        assert!(result.is_ok());
1415        let data = result.unwrap();
1416        assert_eq!(data.items[0].title, "CDATA Item Title");
1417        assert!(data.items[0].description.contains("HTML content"));
1418    }
1419
1420    #[test]
1421    fn test_process_text_event_with_failing_custom_handler() {
1422        let rss_xml = r#"<?xml version="1.0" encoding="UTF-8"?>
1423        <rss version="2.0">
1424          <channel>
1425            <title>Test Feed</title>
1426            <link>https://example.com</link>
1427            <description>Test</description>
1428            <item>
1429              <title>Item</title>
1430              <link>https://example.com/1</link>
1431              <description>Desc</description>
1432              <unknownField>value</unknownField>
1433            </item>
1434          </channel>
1435        </rss>
1436        "#;
1437
1438        let handler = Arc::new(MockElementHandler);
1439        let config = ParserConfig {
1440            custom_handlers: vec![handler],
1441        };
1442
1443        let result = parse_rss(rss_xml, Some(&config));
1444        // The handler returns Err for unknown elements
1445        assert!(result.is_err());
1446    }
1447
1448    #[test]
1449    fn test_parse_element_with_attributes() {
1450        let rss_xml = r#"<?xml version="1.0" encoding="UTF-8"?>
1451        <rss version="2.0">
1452          <channel>
1453            <title>Test Feed</title>
1454            <link>https://example.com</link>
1455            <description>Test</description>
1456            <item>
1457              <title>Item</title>
1458              <link href="https://example.com/1">https://example.com/1</link>
1459              <description>Desc</description>
1460              <enclosure url="https://example.com/audio.mp3" length="12345" type="audio/mpeg"/>
1461            </item>
1462          </channel>
1463        </rss>
1464        "#;
1465
1466        let result = parse_rss(rss_xml, None);
1467        assert!(result.is_ok());
1468    }
1469
1470    #[test]
1471    fn test_cdata_event_channel_elements() {
1472        let rss_xml = r#"<?xml version="1.0" encoding="UTF-8"?>
1473        <rss version="2.0">
1474          <channel>
1475            <title><![CDATA[CDATA Channel Title]]></title>
1476            <link>https://example.com</link>
1477            <description><![CDATA[CDATA Description]]></description>
1478            <item>
1479              <title>Item</title>
1480              <link>https://example.com/1</link>
1481              <description>Desc</description>
1482            </item>
1483          </channel>
1484        </rss>
1485        "#;
1486
1487        let result = parse_rss(rss_xml, None);
1488        assert!(result.is_ok());
1489        let data = result.unwrap();
1490        assert_eq!(data.title, "CDATA Channel Title");
1491        assert_eq!(data.description, "CDATA Description");
1492    }
1493}