ctb_formats_syndication/rss/
rss_20.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//! RSS 2.0 syndication feed serializer and validator.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use super::Feed;
30use crate::rss::{
31    ATOM_NAMESPACE, ensure_permanent_or_historic_iana_uri, write_text_element,
32};
33use xml::writer::{EmitterConfig, XmlEvent};
34
35// ============================================================================
36// RSS 2.0
37// ============================================================================
38
39/// Render a [`Feed`] into RSS 2.0 format.
40///
41/// RSS 2.0 is the most common modern RSS format. Includes optional atom:link
42/// for self-reference.
43///
44/// Specification: <https://www.rssboard.org/rss-specification>
45pub fn render_rss_20(feed: &Feed) -> Result<String> {
46    let mut output = Vec::new();
47
48    let config = EmitterConfig::new()
49        .perform_indent(true)
50        .indent_string("  ");
51    let mut writer = config.create_writer(&mut output);
52
53    writer
54        .write(XmlEvent::StartDocument {
55            version: xml::common::XmlVersion::Version10,
56            encoding: Some("utf-8"),
57            standalone: None,
58        })
59        .context("writing XML declaration")?;
60
61    // Start rss element with version and optional atom namespace.
62    writer
63        .write(
64            XmlEvent::start_element("rss")
65                .ns("atom", ATOM_NAMESPACE)
66                .attr("version", "2.0"),
67        )
68        .context("writing rss start element")?;
69
70    writer
71        .write(XmlEvent::start_element("channel"))
72        .context("writing channel start")?;
73
74    write_text_element(&mut writer, "title", feed.title())?;
75
76    if let Some(home_page_url) = feed.home_page_url() {
77        // The spec says "The data in these elements must begin with an
78        // IANA-registered URI scheme". It's not clear to me if provisional or
79        // historic schemes are allowed; I made a guess here.
80        ensure_permanent_or_historic_iana_uri(home_page_url)?;
81
82        write_text_element(&mut writer, "link", home_page_url)?;
83    } else {
84        // RSS 2.0 requires a channel link.
85        bail!("RSS 2.0 requires a channel <link> URL");
86    }
87
88    write_text_element(&mut writer, "description", feed.title())?;
89
90    // Optional atom:link for self.
91    if let Some(feed_url) = feed.feed_url() {
92        writer
93            .write(
94                XmlEvent::start_element("atom:link")
95                    .attr("href", feed_url)
96                    .attr("rel", "self")
97                    .attr("type", "application/rss+xml"),
98            )
99            .context("writing atom:link")?;
100        writer
101            .write(XmlEvent::end_element())
102            .context("closing atom:link")?;
103    }
104
105    // Items.
106    for entry in feed.entries() {
107        writer
108            .write(XmlEvent::start_element("item"))
109            .context("writing item start")?;
110
111        if !entry.title().is_empty() {
112            write_text_element(&mut writer, "title", entry.title())?;
113        }
114
115        if let Some(url) = entry.url() {
116            ensure_permanent_or_historic_iana_uri(url)?;
117
118            write_text_element(&mut writer, "link", url)?;
119        }
120
121        if !entry.body().is_empty() {
122            write_text_element(&mut writer, "description", entry.body())?;
123        }
124
125        // pubDate
126        if !entry.date().is_empty() {
127            write_text_element(&mut writer, "pubDate", entry.date())?;
128        }
129
130        // Reason for fallback: per RSS 2.0 specification, item guid falls back to item ID if explicit URL is absent.
131        let guid = entry.url().unwrap_or(entry.id());
132        if !guid.is_empty() {
133            write_text_element(&mut writer, "guid", guid)?;
134        }
135
136        writer
137            .write(XmlEvent::end_element())
138            .context("closing item")?;
139    }
140
141    writer
142        .write(XmlEvent::end_element())
143        .context("closing channel")?;
144
145    writer
146        .write(XmlEvent::end_element())
147        .context("closing rss")?;
148
149    Ok(String::from_utf8(output)
150        .context("RSS 2.0 output is not valid UTF-8")?
151        .replace(
152            "<rss xmlns:atom=\"http://www.w3.org/2005/Atom\" version=\"2.0\">",
153            "<rss version=\"2.0\" xmlns:atom=\"http://www.w3.org/2005/Atom\">",
154        ))
155}
156
157#[cfg(test)]
158#[allow(
159    clippy::panic,
160    clippy::expect_used,
161    clippy::unwrap_used,
162    clippy::unwrap_in_result,
163    clippy::panic_in_result_fn,
164    clippy::indexing_slicing,
165    clippy::arithmetic_side_effects,
166    reason = "Standard repository test boilerplate"
167)]
168mod tests {
169    use super::*;
170
171    use crate::Entry;
172
173    // -------------------------------------------------------------------------
174    // RSS 2.0 tests
175    // -------------------------------------------------------------------------
176
177    #[crate::ctb_test]
178    fn test_rss_20_basic() {
179        let entry = Entry::new(
180            "http://example.org/item1",
181            "Test Item",
182            "<p>Description</p>",
183            "2024-01-15T10:00:00Z",
184        )
185        .with_url_opt(Some("http://example.org/item1".into()));
186
187        let feed = Feed::new("Test Feed", vec![entry])
188            .with_home_page_url_opt(Some("http://example.org/".into()))
189            .with_feed_url_opt(Some("http://example.org/feed.rss".into()));
190
191        let result = render_rss_20(&feed).unwrap();
192
193        assert!(result.contains("<rss version=\"2.0\" xmlns:atom=\"http://www.w3.org/2005/Atom\">"), "Got: '{result}'");
194        assert!(
195            result.contains("xmlns:atom=\"http://www.w3.org/2005/Atom\""),
196            "Got: '{result}'"
197        );
198        assert!(
199            result.contains("<atom:link href=\"http://example.org/feed.rss\""),
200            "Got: '{result}'"
201        );
202        assert!(
203            result.contains("<pubDate>2024-01-15T10:00:00Z</pubDate>"),
204            "Got: '{result}'"
205        );
206        assert!(
207            result.contains("<guid>http://example.org/item1</guid>"),
208            "Got: '{result}'"
209        );
210    }
211
212    #[crate::ctb_test]
213    fn test_rss_20_no_atom_link_without_feed_url() {
214        let feed = Feed::new("Test Feed", vec![])
215            .with_home_page_url_opt(Some("http://example.org/".into()));
216
217        let result = render_rss_20(&feed).unwrap();
218
219        assert!(!result.contains("<atom:link"));
220    }
221
222    #[crate::ctb_test]
223    fn test_rss_20_item_without_title() {
224        let entry = Entry::new(
225            "http://example.org/item1",
226            "",
227            "Just a description",
228            "",
229        )
230        .with_url_opt(Some("http://example.org/item1".into()));
231
232        let feed = Feed::new("Test Feed", vec![entry])
233            .with_home_page_url_opt(Some("http://example.org/".into()));
234
235        let result = render_rss_20(&feed).unwrap();
236
237        assert!(
238            result.contains("<description>Just a description</description>")
239        );
240        assert!(!result.contains("<title></title>"));
241    }
242}