Skip to main content

feedparser_rs/types/
entry.rs

1use super::{
2    common::{
3        Content, Enclosure, Image, Link, MediaContent, MediaCopyright, MediaCredit, MediaRating,
4        MediaThumbnail, Person, Source, Tag, TextConstruct,
5    },
6    generics::LimitedCollectionExt,
7    podcast::{ItunesEntryMeta, PodcastEntryMeta, PodcastPerson, PodcastTranscript},
8    thread::InReplyTo,
9};
10use jiff::Timestamp;
11use std::collections::HashMap;
12
13/// Feed entry/item
14#[derive(Debug, Clone, Default)]
15#[non_exhaustive]
16pub struct Entry {
17    /// Unique entry identifier (stored inline for IDs ≤24 bytes)
18    pub id: Option<super::common::SmallString>,
19    /// Entry title
20    pub title: Option<String>,
21    /// Detailed title with metadata
22    pub title_detail: Option<TextConstruct>,
23    /// Primary link
24    pub link: Option<String>,
25    /// All links associated with this entry
26    pub links: Vec<Link>,
27    /// Entry subtitle (Atom §4.2.12 at entry level)
28    pub subtitle: Option<String>,
29    /// Detailed subtitle with metadata
30    pub subtitle_detail: Option<TextConstruct>,
31    /// Rights/copyright statement
32    pub rights: Option<String>,
33    /// Detailed rights with metadata
34    pub rights_detail: Option<TextConstruct>,
35    /// Short description/summary
36    pub summary: Option<String>,
37    /// Detailed summary with metadata
38    pub summary_detail: Option<TextConstruct>,
39    /// Full content blocks
40    pub content: Vec<Content>,
41    /// Publication date
42    pub published: Option<Timestamp>,
43    /// Original publication date string as found in the feed (timezone preserved)
44    pub published_str: Option<String>,
45    /// Last update date
46    pub updated: Option<Timestamp>,
47    /// Original update date string as found in the feed (timezone preserved)
48    pub updated_str: Option<String>,
49    /// Creation date
50    pub created: Option<Timestamp>,
51    /// Original creation date string as found in the feed (timezone preserved)
52    pub created_str: Option<String>,
53    /// Expiration date
54    pub expired: Option<Timestamp>,
55    /// Primary author name (stored inline for names ≤24 bytes)
56    pub author: Option<super::common::SmallString>,
57    /// Detailed author information
58    pub author_detail: Option<Person>,
59    /// All authors
60    pub authors: Vec<Person>,
61    /// Contributors
62    pub contributors: Vec<Person>,
63    /// Publisher name (stored inline for names ≤24 bytes)
64    pub publisher: Option<super::common::SmallString>,
65    /// Detailed publisher information
66    pub publisher_detail: Option<Person>,
67    /// Tags/categories
68    pub tags: Vec<Tag>,
69    /// Media enclosures (audio, video, etc.)
70    pub enclosures: Vec<Enclosure>,
71    /// Comments URL or text
72    pub comments: Option<String>,
73    /// Source feed reference
74    pub source: Option<Source>,
75    /// Entry-level image: item or entry `itunes:image` href, or a JSON Feed item `image`
76    pub image: Option<Image>,
77    /// iTunes episode metadata (if present)
78    pub itunes: Option<Box<ItunesEntryMeta>>,
79    /// Dublin Core creator (author fallback) - stored inline for names ≤24 bytes
80    pub dc_creator: Option<super::common::SmallString>,
81    /// Dublin Core date (publication date fallback)
82    pub dc_date: Option<Timestamp>,
83    /// Dublin Core subjects (tags)
84    pub dc_subject: Vec<String>,
85    /// Dublin Core rights (copyright)
86    pub dc_rights: Option<String>,
87    /// Media RSS thumbnails
88    pub media_thumbnail: Vec<MediaThumbnail>,
89    /// Media RSS content items
90    pub media_content: Vec<MediaContent>,
91    /// Media RSS credits (media:credit elements)
92    pub media_credit: Vec<MediaCredit>,
93    /// Media RSS copyright (media:copyright element)
94    pub media_copyright: Option<MediaCopyright>,
95    /// Media RSS rating (media:rating element)
96    pub media_rating: Option<MediaRating>,
97    /// Media RSS keywords (raw comma-separated string from media:keywords)
98    pub media_keywords: Option<String>,
99    /// Media RSS description (plain text only; None if type != "plain")
100    pub media_description: Option<String>,
101    /// Media RSS title (`media:title` element, plain text only; `None` if `type != "plain"`)
102    pub media_title: Option<String>,
103    /// Podcast 2.0 transcripts for this episode
104    pub podcast_transcripts: Vec<PodcastTranscript>,
105    /// Podcast 2.0 persons for this episode (hosts, guests, etc.)
106    pub podcast_persons: Vec<PodcastPerson>,
107    /// Podcast 2.0 episode metadata
108    pub podcast: Option<Box<PodcastEntryMeta>>,
109    /// `GeoRSS` location data (exposed as `where` per Python feedparser API)
110    pub r#where: Option<Box<crate::namespace::georss::GeoLocation>>,
111    /// W3C Basic Geo latitude (`geo:lat`)
112    pub geo_lat: Option<String>,
113    /// W3C Basic Geo longitude (`geo:long`)
114    pub geo_long: Option<String>,
115    /// License URL (Creative Commons, etc.)
116    pub license: Option<String>,
117    /// Atom Threading Extensions: entries this is a reply to (thr:in-reply-to)
118    pub in_reply_to: Vec<InReplyTo>,
119    /// Atom Threading Extensions: total response count (thr:total)
120    ///
121    /// Stored as u32 in Rust for type safety. Python binding converts
122    /// to string to match Python feedparser's API.
123    pub thr_total: Option<u32>,
124    /// Slash namespace: comment count (`slash:comments`)
125    pub slash_comments: Option<u32>,
126    /// Slash namespace: hit parade (`slash:hit_parade`)
127    pub slash_hit_parade: Option<String>,
128    /// WFW namespace: comment RSS feed URL (`wfw:commentRss`)
129    pub wfw_comment_rss: Option<String>,
130    /// Whether the RSS `<guid>` is a permalink (`isPermaLink` attribute).
131    ///
132    /// `true` when `isPermaLink="true"` or the attribute is absent (RSS 2.0 default).
133    /// `false` when `isPermaLink="false"`. `None` when no `<guid>` element is present.
134    pub guidislink: Option<bool>,
135    /// Entry language (JSON Feed `language` field)
136    pub language: Option<super::common::SmallString>,
137    /// External URL where the full content lives (JSON Feed `external_url`)
138    pub external_url: Option<String>,
139    /// Custom JSON Feed extension objects captured from this item.
140    ///
141    /// Same capture mechanism as [`super::feed::FeedMeta::json_extensions`],
142    /// scoped to this entry independently — a key present at both feed and
143    /// item level is captured separately in each map, with no merging. All scopes
144    /// share one [`crate::ParserLimits::max_json_extension_memory_bytes`] budget.
145    ///
146    /// # Examples
147    ///
148    /// ```
149    /// use feedparser_rs::parse;
150    ///
151    /// let json = br#"{
152    ///     "version": "https://jsonfeed.org/version/1.1",
153    ///     "title": "Feed",
154    ///     "items": [{"id": "1", "_explicit": true}]
155    /// }"#;
156    /// let feed = parse(json).unwrap();
157    /// assert_eq!(feed.entries[0].json_extensions["_explicit"], true);
158    /// ```
159    pub json_extensions: HashMap<String, serde_json::Value>,
160}
161
162impl Entry {
163    /// Creates `Entry` with pre-allocated capacity for collections
164    ///
165    /// Pre-allocates space for typical entry fields:
166    /// - 1-2 links (alternate, related)
167    /// - 1 content block
168    /// - 1 author
169    /// - 2-3 tags
170    /// - 0-1 enclosures
171    /// - 2 podcast transcripts (typical for podcasts with multiple languages)
172    /// - 4 podcast persons (host, co-hosts, guests)
173    ///
174    /// # Examples
175    ///
176    /// ```
177    /// use feedparser_rs::Entry;
178    ///
179    /// let entry = Entry::with_capacity();
180    /// ```
181    #[must_use]
182    pub fn with_capacity() -> Self {
183        Self {
184            links: Vec::with_capacity(2),
185            content: Vec::with_capacity(1),
186            authors: Vec::with_capacity(1),
187            contributors: Vec::new(),
188            tags: Vec::with_capacity(3),
189            enclosures: Vec::with_capacity(1),
190            dc_subject: Vec::with_capacity(2),
191            media_thumbnail: Vec::with_capacity(1),
192            media_content: Vec::with_capacity(1),
193            media_credit: Vec::with_capacity(1),
194            podcast_transcripts: Vec::with_capacity(2),
195            podcast_persons: Vec::with_capacity(4),
196            // Most entries reply to at most one parent
197            in_reply_to: Vec::with_capacity(1),
198            ..Default::default()
199        }
200    }
201
202    /// Sets title field with `TextConstruct`, storing both simple and detailed versions
203    ///
204    /// # Examples
205    ///
206    /// ```
207    /// use feedparser_rs::{Entry, TextConstruct};
208    ///
209    /// let mut entry = Entry::default();
210    /// entry.set_title(TextConstruct::text("Great Article"));
211    /// assert_eq!(entry.title.as_deref(), Some("Great Article"));
212    /// ```
213    #[inline]
214    pub fn set_title(&mut self, text: TextConstruct) {
215        self.title = Some(text.value.clone());
216        self.title_detail = Some(text);
217    }
218
219    /// Sets subtitle field with `TextConstruct`, storing both simple and detailed versions
220    ///
221    /// # Examples
222    ///
223    /// ```
224    /// use feedparser_rs::{Entry, TextConstruct};
225    ///
226    /// let mut entry = Entry::default();
227    /// entry.set_subtitle(TextConstruct::text("A teaser"));
228    /// assert_eq!(entry.subtitle.as_deref(), Some("A teaser"));
229    /// ```
230    #[inline]
231    pub fn set_subtitle(&mut self, text: TextConstruct) {
232        self.subtitle = Some(text.value.clone());
233        self.subtitle_detail = Some(text);
234    }
235
236    /// Sets rights field with `TextConstruct`, storing both simple and detailed versions
237    #[inline]
238    pub fn set_rights(&mut self, text: TextConstruct) {
239        self.rights = Some(text.value.clone());
240        self.rights_detail = Some(text);
241    }
242
243    /// Sets summary field with `TextConstruct`, storing both simple and detailed versions
244    ///
245    /// # Examples
246    ///
247    /// ```
248    /// use feedparser_rs::{Entry, TextConstruct};
249    ///
250    /// let mut entry = Entry::default();
251    /// entry.set_summary(TextConstruct::text("A summary"));
252    /// assert_eq!(entry.summary.as_deref(), Some("A summary"));
253    /// ```
254    #[inline]
255    pub fn set_summary(&mut self, text: TextConstruct) {
256        self.summary = Some(text.value.clone());
257        self.summary_detail = Some(text);
258    }
259
260    /// Sets author field with `Person`, storing both simple and detailed versions
261    ///
262    /// # Examples
263    ///
264    /// ```
265    /// use feedparser_rs::{Entry, Person};
266    ///
267    /// let mut entry = Entry::default();
268    /// entry.set_author(Person::from_name("Jane Doe"));
269    /// assert_eq!(entry.author.as_deref(), Some("Jane Doe"));
270    /// ```
271    #[inline]
272    pub fn set_author(&mut self, person: Person) {
273        self.author = person.flat_string();
274        self.author_detail = Some(person);
275    }
276
277    /// Sets publisher field with `Person`, storing both simple and detailed versions
278    ///
279    /// # Examples
280    ///
281    /// ```
282    /// use feedparser_rs::{Entry, Person};
283    ///
284    /// let mut entry = Entry::default();
285    /// entry.set_publisher(Person::from_name("ACME Corp"));
286    /// assert_eq!(entry.publisher.as_deref(), Some("ACME Corp"));
287    /// ```
288    #[inline]
289    pub fn set_publisher(&mut self, person: Person) {
290        self.publisher.clone_from(&person.name);
291        self.publisher_detail = Some(person);
292    }
293
294    /// Sets the primary link and adds it to the links collection
295    ///
296    /// This is a convenience method that:
297    /// 1. Sets the `link` field (if not already set)
298    /// 2. Adds an "alternate" link to the `links` collection
299    ///
300    /// # Examples
301    ///
302    /// ```
303    /// use feedparser_rs::Entry;
304    ///
305    /// let mut entry = Entry::default();
306    /// entry.set_alternate_link("https://example.com/post/1".to_string(), 10);
307    /// assert_eq!(entry.link.as_deref(), Some("https://example.com/post/1"));
308    /// assert_eq!(entry.links.len(), 1);
309    /// assert_eq!(entry.links[0].rel.as_deref(), Some("alternate"));
310    /// ```
311    #[inline]
312    pub fn set_alternate_link(&mut self, href: String, max_links: usize) {
313        if self.link.is_none() {
314            self.link = Some(href.clone());
315        }
316        self.links.try_push_limited(
317            Link {
318                href: href.into(),
319                rel: Some("alternate".into()),
320                ..Default::default()
321            },
322            max_links,
323        );
324    }
325}
326
327#[cfg(test)]
328mod tests {
329    use super::*;
330
331    #[test]
332    fn test_entry_default() {
333        let entry = Entry::default();
334        assert!(entry.id.is_none());
335        assert!(entry.title.is_none());
336        assert!(entry.links.is_empty());
337        assert!(entry.content.is_empty());
338        assert!(entry.authors.is_empty());
339    }
340
341    #[test]
342    #[expect(
343        clippy::redundant_clone,
344        reason = "the test checks that the clone equals the original"
345    )]
346    fn test_entry_clone() {
347        fn create_entry() -> Entry {
348            Entry {
349                title: Some("Test".to_string()),
350                links: vec![Link::default()],
351                ..Default::default()
352            }
353        }
354        let entry = create_entry();
355        let cloned = entry.clone();
356        assert_eq!(cloned.title.as_deref(), Some("Test"));
357        assert_eq!(cloned.links.len(), 1);
358    }
359}