feedparser_rs/types/feed.rs
1use super::{
2 common::{Cloud, Generator, Image, Link, MediaRating, Person, Tag, TextConstruct, TextInput},
3 entry::Entry,
4 generics::LimitedCollectionExt,
5 podcast::{ItunesFeedMeta, PodcastMeta},
6 version::FeedVersion,
7};
8use crate::ParserLimits;
9use crate::namespace::syndication::SyndicationMeta;
10use jiff::Timestamp;
11use std::collections::HashMap;
12
13/// Feed metadata
14#[derive(Debug, Clone, Default)]
15#[non_exhaustive]
16pub struct FeedMeta {
17 /// Feed title
18 pub title: Option<String>,
19 /// Detailed title with metadata
20 pub title_detail: Option<TextConstruct>,
21 /// Primary feed link
22 pub link: Option<String>,
23 /// All links associated with this feed
24 pub links: Vec<Link>,
25 /// Feed subtitle/description
26 pub subtitle: Option<String>,
27 /// Detailed subtitle with metadata
28 pub subtitle_detail: Option<TextConstruct>,
29 /// Feed summary (populated from itunes:summary when present)
30 pub summary: Option<String>,
31 /// Detailed summary with metadata
32 pub summary_detail: Option<TextConstruct>,
33 /// Last update date
34 pub updated: Option<Timestamp>,
35 /// Original update date string as found in the feed (timezone preserved)
36 pub updated_str: Option<String>,
37 /// Initial publication date (RSS pubDate, Atom published)
38 pub published: Option<Timestamp>,
39 /// Original publication date string as found in the feed (timezone preserved)
40 pub published_str: Option<String>,
41 /// Primary author name (stored inline for names ≤24 bytes)
42 pub author: Option<super::common::SmallString>,
43 /// Detailed author information
44 pub author_detail: Option<Person>,
45 /// All authors
46 pub authors: Vec<Person>,
47 /// Contributors
48 pub contributors: Vec<Person>,
49 /// Publisher name (stored inline for names ≤24 bytes)
50 pub publisher: Option<super::common::SmallString>,
51 /// Detailed publisher information
52 pub publisher_detail: Option<Person>,
53 /// Feed language (e.g., "en-us") - stored inline as lang codes are ≤24 bytes
54 pub language: Option<super::common::SmallString>,
55 /// Copyright/rights statement
56 pub rights: Option<String>,
57 /// Detailed rights with metadata
58 pub rights_detail: Option<TextConstruct>,
59 /// Generator name
60 pub generator: Option<String>,
61 /// Detailed generator information
62 pub generator_detail: Option<Generator>,
63 /// Feed image
64 pub image: Option<Image>,
65 /// Icon URL (small image)
66 pub icon: Option<String>,
67 /// Logo URL (larger image)
68 pub logo: Option<String>,
69 /// Feed-level tags/categories
70 pub tags: Vec<Tag>,
71 /// Unique feed identifier
72 pub id: Option<String>,
73 /// Time-to-live (update frequency hint) in minutes (kept as string for API compatibility)
74 pub ttl: Option<String>,
75 /// URL of documentation for the RSS format used
76 pub docs: Option<String>,
77 /// iTunes podcast metadata (if present)
78 pub itunes: Option<Box<ItunesFeedMeta>>,
79 /// Podcast 2.0 namespace metadata (if present)
80 pub podcast: Option<Box<PodcastMeta>>,
81 /// Dublin Core creator (author fallback) - stored inline for names ≤24 bytes
82 pub dc_creator: Option<super::common::SmallString>,
83 /// Dublin Core publisher (stored inline for names ≤24 bytes)
84 pub dc_publisher: Option<super::common::SmallString>,
85 /// Dublin Core rights (copyright)
86 pub dc_rights: Option<String>,
87 /// License URL (Creative Commons, etc.)
88 pub license: Option<String>,
89 /// Syndication module metadata (RSS 1.0)
90 pub syndication: Option<Box<SyndicationMeta>>,
91 /// Geographic location from `GeoRSS` namespace (feed level, exposed as `where` per Python feedparser API)
92 pub r#where: Option<Box<crate::namespace::georss::GeoLocation>>,
93 /// W3C Basic Geo latitude (`geo:lat`)
94 pub geo_lat: Option<String>,
95 /// W3C Basic Geo longitude (`geo:long`)
96 pub geo_long: Option<String>,
97 /// Pagination URL for the next page of results (JSON Feed `next_url`, RFC 5005 `<link rel="next">`)
98 pub next_url: Option<String>,
99 /// Media RSS thumbnails at feed/channel level
100 pub media_thumbnail: Vec<super::common::MediaThumbnail>,
101 /// Media RSS content items at feed/channel level
102 pub media_content: Vec<super::common::MediaContent>,
103 /// Media RSS rating (`media:rating`) at feed level
104 pub media_rating: Option<MediaRating>,
105 /// Media RSS keywords (`media:keywords`) at feed level, comma-separated string
106 pub media_keywords: Option<String>,
107 /// RSS 2.0 `<cloud>` element — subscription endpoint for notifications
108 pub cloud: Option<Cloud>,
109 /// RSS 2.0 `<textInput>` element — text input form associated with the channel
110 pub textinput: Option<TextInput>,
111 /// RSS 2.0 `<skipHours>` — hours of the day when the channel may be skipped (0–23)
112 pub skiphours: Vec<u32>,
113 /// RSS 2.0 `<skipDays>` — days of the week when the channel may be skipped
114 pub skipdays: Vec<String>,
115 /// Custom JSON Feed extension objects captured from the feed's top level.
116 ///
117 /// JSON Feed 1.1 permits custom object keys anywhere in a feed, provided the
118 /// key starts with `_` followed by a letter (e.g. `_cast`). Only the
119 /// feed-root scope is captured here — nested custom objects under array
120 /// scopes such as `authors[]`, `attachments[]`, or `hubs[]` are not (MVP
121 /// limitation). A value over the size or node bound of
122 /// [`crate::ParserLimits::max_text_length`], or one that does not fit in what is
123 /// left of [`crate::ParserLimits::max_json_extension_memory_bytes`] for the
124 /// document, is dropped. Kept values are captured verbatim and never interpreted.
125 /// Only the JSON Feed parser populates this field; RSS and Atom feeds always
126 /// leave it empty.
127 ///
128 /// # Examples
129 ///
130 /// ```
131 /// use feedparser_rs::parse;
132 ///
133 /// let json = br#"{
134 /// "version": "https://jsonfeed.org/version/1.1",
135 /// "title": "Podcast Feed",
136 /// "_cast": {"subcategory": "Tech News"},
137 /// "items": []
138 /// }"#;
139 /// let feed = parse(json).unwrap();
140 /// assert_eq!(
141 /// feed.feed.json_extensions["_cast"]["subcategory"],
142 /// "Tech News"
143 /// );
144 /// ```
145 pub json_extensions: HashMap<String, serde_json::Value>,
146}
147
148/// Parsed feed result
149///
150/// This is the main result type returned by the parser, analogous to
151/// Python feedparser's `FeedParserDict`.
152#[derive(Debug, Clone, Default)]
153#[non_exhaustive]
154pub struct ParsedFeed {
155 /// Feed metadata
156 pub feed: FeedMeta,
157 /// Feed entries/items
158 pub entries: Vec<Entry>,
159 /// True if parsing encountered errors
160 pub bozo: bool,
161 /// Description of parsing error (if bozo is true)
162 pub bozo_exception: Option<String>,
163 /// Detected or declared encoding
164 pub encoding: String,
165 /// Detected feed format version
166 pub version: FeedVersion,
167 /// XML namespaces (prefix -> URI)
168 pub namespaces: HashMap<String, String>,
169 /// HTTP status code (if fetched from URL)
170 pub status: Option<u16>,
171 /// Final URL after redirects (if fetched from URL)
172 pub href: Option<String>,
173 /// `ETag` header from HTTP response
174 pub etag: Option<String>,
175 /// Last-Modified header from HTTP response
176 pub modified: Option<String>,
177 /// HTTP response headers (if fetched from URL)
178 #[cfg(feature = "http")]
179 pub headers: Option<HashMap<String, String>>,
180}
181
182impl ParsedFeed {
183 /// Creates a new `ParsedFeed` with default UTF-8 encoding
184 #[must_use]
185 pub fn new() -> Self {
186 Self {
187 encoding: String::from("utf-8"),
188 ..Default::default()
189 }
190 }
191
192 /// Creates a `ParsedFeed` with pre-allocated capacity for entries
193 ///
194 /// This method pre-allocates space for the expected number of entries,
195 /// reducing memory allocations during parsing.
196 ///
197 /// # Arguments
198 ///
199 /// * `entry_count` - Expected number of entries in the feed
200 ///
201 /// # Examples
202 ///
203 /// ```
204 /// use feedparser_rs::ParsedFeed;
205 ///
206 /// let feed = ParsedFeed::with_capacity(50);
207 /// assert_eq!(feed.encoding, "utf-8");
208 /// ```
209 #[must_use]
210 pub fn with_capacity(entry_count: usize) -> Self {
211 Self {
212 entries: Vec::with_capacity(entry_count),
213 namespaces: HashMap::with_capacity(8), // Typical feeds have 3-8 namespaces
214 encoding: String::from("utf-8"),
215 ..Default::default()
216 }
217 }
218
219 /// Whether one more entry fits; sets bozo if not. Skips nothing, so it also
220 /// serves a self-closing `<item/>` or `<entry/>`.
221 pub(crate) fn admits_entry(&mut self, limits: &ParserLimits) -> bool {
222 let fits = !self.entries.is_at_limit(limits.max_entries);
223 if !fits {
224 self.bozo = true;
225 self.bozo_exception = Some(format!("Entry limit exceeded: {}", limits.max_entries));
226 }
227 fits
228 }
229}
230
231impl FeedMeta {
232 /// Creates `FeedMeta` with capacity hints for typical RSS 2.0 feeds
233 ///
234 /// Pre-allocates collections based on common RSS 2.0 field usage:
235 /// - 1-2 links (channel link, self link)
236 /// - 1 author (managingEditor)
237 /// - 0-3 tags (categories)
238 ///
239 /// # Examples
240 ///
241 /// ```
242 /// use feedparser_rs::FeedMeta;
243 ///
244 /// let meta = FeedMeta::with_rss_capacity();
245 /// ```
246 #[must_use]
247 pub fn with_rss_capacity() -> Self {
248 Self {
249 links: Vec::with_capacity(2),
250 authors: Vec::with_capacity(1),
251 contributors: Vec::new(),
252 tags: Vec::with_capacity(3),
253 ..Default::default()
254 }
255 }
256
257 /// Creates `FeedMeta` with capacity hints for typical Atom 1.0 feeds
258 ///
259 /// Pre-allocates collections based on common Atom 1.0 field usage:
260 /// - 3-5 links (alternate, self, related, etc.)
261 /// - 1-2 authors
262 /// - 1 contributor
263 /// - 3-5 tags (categories)
264 ///
265 /// # Examples
266 ///
267 /// ```
268 /// use feedparser_rs::FeedMeta;
269 ///
270 /// let meta = FeedMeta::with_atom_capacity();
271 /// ```
272 #[must_use]
273 pub fn with_atom_capacity() -> Self {
274 Self {
275 links: Vec::with_capacity(4),
276 authors: Vec::with_capacity(2),
277 contributors: Vec::with_capacity(1),
278 tags: Vec::with_capacity(5),
279 ..Default::default()
280 }
281 }
282
283 /// Sets title field with `TextConstruct`, storing both simple and detailed versions
284 ///
285 /// # Examples
286 ///
287 /// ```
288 /// use feedparser_rs::{FeedMeta, TextConstruct};
289 ///
290 /// let mut meta = FeedMeta::default();
291 /// meta.set_title(TextConstruct::text("Example Feed"));
292 /// assert_eq!(meta.title.as_deref(), Some("Example Feed"));
293 /// ```
294 #[inline]
295 pub fn set_title(&mut self, text: TextConstruct) {
296 self.title = Some(text.value.clone());
297 self.title_detail = Some(text);
298 }
299
300 /// Sets subtitle field with `TextConstruct`, storing both simple and detailed versions
301 ///
302 /// # Examples
303 ///
304 /// ```
305 /// use feedparser_rs::{FeedMeta, TextConstruct};
306 ///
307 /// let mut meta = FeedMeta::default();
308 /// meta.set_subtitle(TextConstruct::text("A great feed"));
309 /// assert_eq!(meta.subtitle.as_deref(), Some("A great feed"));
310 /// ```
311 #[inline]
312 pub fn set_subtitle(&mut self, text: TextConstruct) {
313 self.subtitle = Some(text.value.clone());
314 self.subtitle_detail = Some(text);
315 }
316
317 /// Sets summary field with `TextConstruct`, storing both simple and detailed versions
318 ///
319 /// # Examples
320 ///
321 /// ```
322 /// use feedparser_rs::{FeedMeta, TextConstruct};
323 ///
324 /// let mut meta = FeedMeta::default();
325 /// meta.set_summary(TextConstruct::text("A detailed description"));
326 /// assert_eq!(meta.summary.as_deref(), Some("A detailed description"));
327 /// ```
328 #[inline]
329 pub fn set_summary(&mut self, text: TextConstruct) {
330 self.summary = Some(text.value.clone());
331 self.summary_detail = Some(text);
332 }
333
334 /// Sets rights field with `TextConstruct`, storing both simple and detailed versions
335 ///
336 /// # Examples
337 ///
338 /// ```
339 /// use feedparser_rs::{FeedMeta, TextConstruct};
340 ///
341 /// let mut meta = FeedMeta::default();
342 /// meta.set_rights(TextConstruct::text("© 2025 Example"));
343 /// assert_eq!(meta.rights.as_deref(), Some("© 2025 Example"));
344 /// ```
345 #[inline]
346 pub fn set_rights(&mut self, text: TextConstruct) {
347 self.rights = Some(text.value.clone());
348 self.rights_detail = Some(text);
349 }
350
351 /// Sets generator field with `Generator`, storing both simple and detailed versions
352 ///
353 /// # Examples
354 ///
355 /// ```
356 /// use feedparser_rs::{FeedMeta, Generator};
357 ///
358 /// # fn main() {
359 /// let mut meta = FeedMeta::default();
360 /// let generator = Generator::new("Example Generator");
361 /// meta.set_generator(generator);
362 /// assert_eq!(meta.generator.as_deref(), Some("Example Generator"));
363 /// # }
364 /// ```
365 #[inline]
366 pub fn set_generator(&mut self, generator: Generator) {
367 // Clone the name for the flat `generator` field; the detail struct keeps its own copy.
368 self.generator = Some(generator.name.clone());
369 self.generator_detail = Some(generator);
370 }
371
372 /// Sets author field with `Person`, storing both simple and detailed versions
373 ///
374 /// # Examples
375 ///
376 /// ```
377 /// use feedparser_rs::{FeedMeta, Person};
378 ///
379 /// let mut meta = FeedMeta::default();
380 /// meta.set_author(Person::from_name("John Doe"));
381 /// assert_eq!(meta.author.as_deref(), Some("John Doe"));
382 /// ```
383 #[inline]
384 pub fn set_author(&mut self, person: Person) {
385 self.author = person.flat_string();
386 self.author_detail = Some(person);
387 }
388
389 /// Sets publisher field with `Person`, storing both simple and detailed versions
390 ///
391 /// # Examples
392 ///
393 /// ```
394 /// use feedparser_rs::{FeedMeta, Person};
395 ///
396 /// let mut meta = FeedMeta::default();
397 /// meta.set_publisher(Person::from_name("ACME Corp"));
398 /// assert_eq!(meta.publisher.as_deref(), Some("ACME Corp"));
399 /// ```
400 #[inline]
401 pub fn set_publisher(&mut self, person: Person) {
402 self.publisher.clone_from(&person.name);
403 self.publisher_detail = Some(person);
404 }
405
406 /// Sets the primary link and adds it to the links collection
407 ///
408 /// This is a convenience method that:
409 /// 1. Sets the `link` field (if not already set)
410 /// 2. Adds an "alternate" link to the `links` collection
411 ///
412 /// # Examples
413 ///
414 /// ```
415 /// use feedparser_rs::FeedMeta;
416 ///
417 /// let mut meta = FeedMeta::default();
418 /// meta.set_alternate_link("https://example.com".to_string(), 10);
419 /// assert_eq!(meta.link.as_deref(), Some("https://example.com"));
420 /// assert_eq!(meta.links.len(), 1);
421 /// assert_eq!(meta.links[0].rel.as_deref(), Some("alternate"));
422 /// ```
423 #[inline]
424 pub fn set_alternate_link(&mut self, href: String, max_links: usize) {
425 if self.link.is_none() {
426 self.link = Some(href.clone());
427 }
428 self.links.try_push_limited(
429 Link {
430 href: href.into(),
431 rel: Some("alternate".into()),
432 ..Default::default()
433 },
434 max_links,
435 );
436 }
437}
438
439#[cfg(test)]
440mod tests {
441 use super::*;
442
443 #[test]
444 fn test_feed_meta_default() {
445 let meta = FeedMeta::default();
446 assert!(meta.title.is_none());
447 assert!(meta.links.is_empty());
448 assert!(meta.authors.is_empty());
449 }
450
451 #[test]
452 fn test_parsed_feed_default() {
453 let feed = ParsedFeed::default();
454 assert!(!feed.bozo);
455 assert!(feed.bozo_exception.is_none());
456 assert_eq!(feed.version, FeedVersion::Unknown);
457 assert!(feed.entries.is_empty());
458 }
459
460 #[test]
461 fn test_parsed_feed_new() {
462 let feed = ParsedFeed::new();
463 assert_eq!(feed.encoding, "utf-8");
464 assert!(!feed.bozo);
465 }
466
467 #[test]
468 fn test_parsed_feed_clone() {
469 let feed = ParsedFeed {
470 version: FeedVersion::Rss20,
471 bozo: true,
472 ..ParsedFeed::new()
473 };
474
475 assert_eq!(feed.version, FeedVersion::Rss20);
476 assert!(feed.bozo);
477 }
478}