ctb_formats_syndication/
syndication.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Syndication data model.
21//!
22//! This module defines in-memory structures (`Feed`, `Entry`) that can later be
23//! rendered into various syndication formats (e.g., JSON Feed, Atom, RSS).
24//!
25//! Note that some formats have special limitations:
26//!
27//! - RSS 0.90 only allows HTTP, HTTPS, FTP, and mailto URLs
28//! - RSS 0.92 and both RSS 0.91 variants only allow HTTP or FTP URLs
29//! - RSS 2.0 only allows IANA-registered URI schemes
30
31#[allow(
32    unused_imports,
33    clippy::wildcard_imports,
34    reason = "Standard workspace crate prelude"
35)]
36pub(crate) use ctb_utilities::*;
37
38use dateparser::parse;
39use jiff::Timestamp;
40
41fn parse_timestamp(input: &str) -> Result<Timestamp> {
42    let dt = parse(input)?;
43    let nanos = i32::try_from(dt.timestamp_subsec_nanos())
44        .context("Parsed timestamp nanoseconds out of range")?;
45    Timestamp::new(dt.timestamp(), nanos)
46        .context("Parsed timestamp out of range")
47}
48
49pub mod atom;
50pub mod hatom;
51pub mod json_feed;
52pub mod rss;
53
54/// Output formats supported by [`Feed::to`].
55#[derive(Clone, Copy, Debug, Eq, PartialEq)]
56pub enum FeedFormat {
57    /// JSON Feed 1.1.
58    JsonFeed,
59    /// Atom
60    Atom,
61    HAtom,
62    /// RSS
63    Rss,
64    Rss1,
65    Rss092,
66    Rss091Netscape,
67    Rss091UserLand,
68    Rss09,
69    ScriptingNews10,
70    ScriptingNews20,
71}
72
73/// A single item in a syndication feed.
74#[derive(Clone, Debug, Eq, PartialEq)]
75pub struct Entry {
76    id: String,
77    title: String,
78    body_html: String,
79    author: Option<String>,
80    date_published: String,
81    date_updated: Option<String>,
82    url: Option<String>,
83}
84
85/// Optional channel image metadata.
86///
87/// Some output formats (e.g. RSS 0.91 UserLand) expect a channel `<image>`.
88/// Since the syndication data model is shared across multiple formats, all
89/// fields are optional and individual renderers can enforce/derive defaults.
90#[derive(Clone, Debug, Default, Eq, PartialEq)]
91pub struct Image {
92    url: String,
93    alt: Option<String>,
94    width: Option<u32>,
95    height: Option<u32>,
96    description: Option<String>,
97}
98
99impl Image {
100    /// Create an empty image descriptor.
101    #[must_use]
102    pub fn new() -> Self {
103        Self::default()
104    }
105
106    /// Set or clear the image URL.
107    #[must_use]
108    pub fn with_url(mut self, url: String) -> Self {
109        self.url = url;
110        self
111    }
112
113    /// Set or clear the image alt text.
114    #[must_use]
115    pub fn with_alt_opt(mut self, alt: Option<String>) -> Self {
116        self.alt = alt;
117        self
118    }
119
120    /// Set or clear the image width.
121    #[must_use]
122    pub fn with_width_opt(mut self, width: Option<u32>) -> Self {
123        self.width = width;
124        self
125    }
126
127    /// Set or clear the image height.
128    #[must_use]
129    pub fn with_height_opt(mut self, height: Option<u32>) -> Self {
130        self.height = height;
131        self
132    }
133
134    /// Set or clear the image description.
135    #[must_use]
136    pub fn with_description_opt(mut self, description: Option<String>) -> Self {
137        self.description = description;
138        self
139    }
140
141    /// Borrow the image URL, if present.
142    pub fn url(&self) -> &str {
143        &self.url
144    }
145
146    /// Borrow the image alt text, if present.
147    pub fn alt(&self) -> Option<&str> {
148        self.alt.as_deref()
149    }
150
151    /// Borrow the image width, if present.
152    pub fn width(&self) -> Option<u32> {
153        self.width
154    }
155
156    /// Borrow the image height, if present.
157    pub fn height(&self) -> Option<u32> {
158        self.height
159    }
160
161    /// Borrow the image description, if present.
162    pub fn description(&self) -> Option<&str> {
163        self.description.as_deref()
164    }
165}
166
167impl Entry {
168    /// Create a new entry.
169    ///
170    /// The `date_published` is intentionally stored as a string for now; format
171    /// and parsing will be decided when output formats are implemented.
172    pub fn new(
173        id: impl Into<String>,
174        title: impl Into<String>,
175        body_html: impl Into<String>,
176        date_published: impl Into<String>,
177    ) -> Self {
178        Self {
179            id: id.into(),
180            title: title.into(),
181            body_html: body_html.into(),
182            author: None,
183            date_published: date_published.into(),
184            date_updated: None,
185            url: None,
186        }
187    }
188
189    /// Set the author for this entry.
190    #[must_use]
191    pub fn with_author(mut self, author: impl Into<String>) -> Self {
192        self.author = Some(author.into());
193        self
194    }
195
196    /// Set or clear the author for this entry.
197    #[must_use]
198    pub fn with_author_opt(mut self, author: Option<String>) -> Self {
199        self.author = author;
200        self
201    }
202
203    /// Set or clear the canonical URL for this entry.
204    #[must_use]
205    pub fn with_url_opt(mut self, url: Option<String>) -> Self {
206        self.url = url;
207        self
208    }
209
210    /// Set or clear the canonical URL for this entry.
211    #[must_use]
212    pub fn with_updated_opt(mut self, updated: Option<String>) -> Self {
213        self.date_updated = updated;
214        self
215    }
216
217    /// Borrow the entry id.
218    pub fn id(&self) -> &str {
219        &self.id
220    }
221
222    /// Borrow the entry title.
223    pub fn title(&self) -> &str {
224        &self.title
225    }
226
227    /// Borrow the entry body.
228    pub fn body(&self) -> &str {
229        &self.body_html
230    }
231
232    /// Borrow the entry author, if present.
233    pub fn author(&self) -> Option<&str> {
234        self.author.as_deref()
235    }
236
237    /// Borrow the entry published date string.
238    pub fn date(&self) -> &str {
239        &self.date_published
240    }
241
242    pub fn date_parsed(&self) -> Result<Timestamp> {
243        // FIXME: This uses the dateparser crate to parse various date formats.
244        // It doesn't look very maintained and has some bugs/what appear to be
245        // limitations particularly around timezone. Look for something better
246        // later.
247        parse_timestamp(&self.date_published)
248    }
249
250    pub fn date_try_format(&self, fmt: &str) -> String {
251        if let Ok(dt) = self.date_parsed()
252            && let Ok(formatted) = jiff::fmt::strtime::format(fmt, dt)
253        {
254            formatted
255        } else {
256            self.date_published.clone()
257        }
258    }
259
260    /// Borrow the entry updated date string, if present.
261    pub fn updated(&self) -> Option<&str> {
262        self.date_updated.as_deref()
263    }
264
265    pub fn updated_parsed(&self) -> Result<Timestamp> {
266        parse_timestamp(bail_if_none!(self.date_updated.as_ref()))
267    }
268
269    pub fn updated_try_format(&self, fmt: &str) -> Option<String> {
270        if let Ok(dt) = self.updated_parsed()
271            && let Ok(formatted) = jiff::fmt::strtime::format(fmt, dt)
272        {
273            Some(formatted)
274        } else {
275            Some(self.date().to_string())
276        }
277    }
278
279    pub fn try_updated(&self) -> String {
280        match &self.updated() {
281            Some(dt) => (*dt).to_string(),
282            None => self.date().to_string(),
283        }
284    }
285
286    pub fn try_updated_parsed(&self) -> Result<Timestamp> {
287        parse_timestamp(&self.try_updated())
288    }
289
290    pub fn try_updated_try_format(&self, fmt: &str) -> String {
291        if let Ok(dt) = self.try_updated_parsed()
292            && let Ok(formatted) = jiff::fmt::strtime::format(fmt, dt)
293        {
294            formatted
295        } else {
296            self.try_updated()
297        }
298    }
299
300    /// Borrow the entry URL, if present.
301    pub fn url(&self) -> Option<&str> {
302        self.url.as_deref()
303    }
304}
305
306/// A collection of entries intended to be rendered into different formats.
307#[derive(Clone, Debug, Default, Eq, PartialEq)]
308pub struct Feed {
309    title: String,
310    home_page_url: Option<String>,
311    #[expect(
312        clippy::struct_field_names,
313        reason = "feed_url is standard RSS/Atom nomenclature"
314    )]
315    feed_url: Option<String>,
316    image: Option<Image>,
317    entries: Vec<Entry>,
318}
319
320impl Feed {
321    /// Create a new feed from an iterator of entries.
322    pub fn new(
323        title: impl Into<String>,
324        entries: impl IntoIterator<Item = Entry>,
325    ) -> Self {
326        Self {
327            title: title.into(),
328            home_page_url: None,
329            feed_url: None,
330            image: None,
331            entries: entries.into_iter().collect(),
332        }
333    }
334
335    /// Create an empty feed.
336    pub fn empty(title: impl Into<String>) -> Self {
337        Self {
338            title: title.into(),
339            home_page_url: None,
340            feed_url: None,
341            image: None,
342            entries: Vec::new(),
343        }
344    }
345
346    /// Set or clear the home page URL for this feed.
347    #[must_use]
348    pub fn with_home_page_url_opt(
349        mut self,
350        home_page_url: Option<String>,
351    ) -> Self {
352        self.home_page_url = home_page_url;
353        self
354    }
355
356    /// Set or clear the feed URL for this feed.
357    #[must_use]
358    pub fn with_feed_url_opt(mut self, feed_url: Option<String>) -> Self {
359        self.feed_url = feed_url;
360        self
361    }
362
363    /// Provide an image for formats that support channel images.
364    #[must_use]
365    pub fn with_image(mut self, image: Image) -> Self {
366        self.image = Some(image);
367        self
368    }
369
370    /// Borrow the feed title.
371    pub fn title(&self) -> &str {
372        &self.title
373    }
374
375    /// Borrow the feed home page URL, if present.
376    pub fn home_page_url(&self) -> Option<&str> {
377        self.home_page_url.as_deref()
378    }
379
380    /// Borrow the feed URL, if present.
381    pub fn feed_url(&self) -> Option<&str> {
382        self.feed_url.as_deref()
383    }
384
385    /// Borrow the feed channel image, if present.
386    pub fn image(&self) -> Option<&Image> {
387        self.image.as_ref()
388    }
389
390    /// Add an entry to the end of the feed.
391    pub fn add_entry(&mut self, entry: Entry) {
392        self.entries.push(entry);
393    }
394
395    /// Add an entry to the end of the feed, returning `self` for chaining.
396    #[must_use]
397    pub fn with_entry(mut self, entry: Entry) -> Self {
398        self.entries.push(entry);
399        self
400    }
401
402    /// Borrow all entries in order.
403    pub fn entries(&self) -> &[Entry] {
404        &self.entries
405    }
406
407    /// Consume the feed and return its entries.
408    pub fn into_entries(self) -> Vec<Entry> {
409        self.entries
410    }
411
412    /// Render the feed in the requested format.
413    pub fn to(&self, format: FeedFormat) -> Result<String> {
414        match format {
415            FeedFormat::JsonFeed => json_feed::render(self),
416            FeedFormat::Atom => atom::render(self),
417            FeedFormat::Rss => rss::render(self),
418            FeedFormat::HAtom => hatom::render(self),
419            FeedFormat::Rss1 => rss::rss_10::render_rss_10(self),
420            FeedFormat::Rss092 => rss::rss_092::render_rss_092(self),
421            FeedFormat::Rss091Netscape => {
422                rss::rss_091::render_rss_091_netscape(self)
423            }
424            FeedFormat::Rss091UserLand => {
425                rss::rss_091::render_rss_091_userland(self)
426            }
427            FeedFormat::Rss09 => rss::rss_09::render_rss_09(self),
428            FeedFormat::ScriptingNews10 => {
429                rss::scripting_news::render_scripting_news_10(self)
430            }
431            FeedFormat::ScriptingNews20 => {
432                rss::scripting_news::render_scripting_news_20(self)
433            }
434        }
435    }
436
437    /// Render as JSON Feed.
438    pub fn to_json_feed(&self) -> Result<String> {
439        self.to(FeedFormat::JsonFeed)
440    }
441
442    /// Render as Atom.
443    pub fn to_atom(&self) -> Result<String> {
444        self.to(FeedFormat::Atom)
445    }
446
447    /// Render as RSS.
448    pub fn to_rss(&self) -> Result<String> {
449        self.to(FeedFormat::Rss)
450    }
451
452    /// Render as hAtom (HTML with microformat markup).
453    pub fn to_hatom(&self) -> Result<String> {
454        self.to(FeedFormat::HAtom)
455    }
456}