ctb_formats_syndication/rss/
rss_09.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 0.90 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    RDF_NAMESPACE, RSS_09_091_MAX_ITEMS, RSS_09_MAX_SIZE, RSS_09_NAMESPACE,
32    ensure_http_https_ftp_or_mailto_uri, write_text_element,
33};
34use ctb_formats_html::entities::to_entities_netscape_1999;
35use ctb_formats_utf8::{ellipsize_to_max_bytes, to_ascii_translit};
36use ctb_utilities::anyhow::ensure;
37use xml::writer::{EmitterConfig, XmlEvent};
38
39// ============================================================================
40// RSS 0.9 (RDF Site Summary)
41// ============================================================================
42
43fn prep_string(input: &str, max_bytes: usize) -> Result<String> {
44    let input =
45        to_ascii_translit(&to_entities_netscape_1999(input.to_string())?);
46    let input = ellipsize_to_max_bytes(&input, max_bytes);
47    Ok(to_ascii_translit(&input))
48}
49
50/// Render a [`Feed`] into RSS 0.9 (RDF Site Summary) format.
51///
52/// Constraints enforced:
53/// - ASCII characters only (non-ASCII replaced with `?`)
54/// - Maximum 15 items per channel
55/// - Maximum 8KB total file size
56/// - Lowercase tags only
57/// - Title: max 40 chars, Description: max 500 chars, Link: max 500 chars
58/// - Item title: max 100 chars, Item link: max 500 chars
59///
60/// Specification: <https://www.rssboard.org/rss-0-9-0>
61pub fn render_rss_09(feed: &Feed) -> Result<String> {
62    let mut output = Vec::new();
63
64    // Use a custom config with no escaping because `prep_string()` already
65    // returns entity-escaped ASCII.
66    let mut config = EmitterConfig::new().perform_indent(false);
67    config.perform_escaping = false;
68    let mut writer = config.create_writer(&mut output);
69
70    // XML declaration
71    writer
72        .write(XmlEvent::StartDocument {
73            version: xml::common::XmlVersion::Version10,
74            encoding: None,
75            standalone: None,
76        })
77        .context("writing XML declaration")?;
78
79    // Start rdf:RDF element with namespaces.
80    writer
81        .write(
82            XmlEvent::start_element("rdf:RDF")
83                .ns("rdf", RDF_NAMESPACE)
84                .default_ns(RSS_09_NAMESPACE),
85        )
86        .context("writing rdf:RDF start element")?;
87
88    // Channel element.
89    writer
90        .write(XmlEvent::start_element("channel"))
91        .context("writing channel start")?;
92
93    write_text_element(&mut writer, "title", &prep_string(feed.title(), 40)?)?;
94
95    if let Some(home_page_url) = feed.home_page_url() {
96        ensure_http_https_ftp_or_mailto_uri(home_page_url)?;
97
98        write_text_element(
99            &mut writer,
100            "link",
101            &prep_string(home_page_url, 500)?,
102        )?;
103    }
104
105    // Use title as description fallback since Feed doesn't have description.
106    write_text_element(
107        &mut writer,
108        "description",
109        &prep_string(feed.title(), 500)?,
110    )?;
111
112    writer
113        .write(XmlEvent::end_element())
114        .context("closing channel element")?;
115
116    // Items (max 15).
117    let items = feed.entries().iter().take(RSS_09_091_MAX_ITEMS);
118    for entry in items {
119        writer
120            .write(XmlEvent::start_element("item"))
121            .context("writing item start")?;
122
123        write_text_element(
124            &mut writer,
125            "title",
126            &prep_string(entry.title(), 100)?,
127        )?;
128
129        if let Some(item_link) = entry.url() {
130            ensure_http_https_ftp_or_mailto_uri(item_link)?;
131
132            write_text_element(
133                &mut writer,
134                "link",
135                &prep_string(item_link, 500)?,
136            )?;
137        } else {
138            warn!("RSS 0.9 item is missing link URL: '{}'", entry.title());
139        }
140
141        writer
142            .write(XmlEvent::end_element())
143            .context("closing item element")?;
144    }
145
146    // Close rdf:RDF
147    writer
148        .write(XmlEvent::end_element())
149        .context("closing rdf:RDF element")?;
150
151    let result = String::from_utf8(output)
152        .context("RSS 0.9 output is not valid UTF-8")?
153        .replace(
154            "<?xml version=\"1.0\" encoding=\"UTF-8\"?>",
155            "<?xml version=\"1.0\"?>",
156        );
157
158    ensure!(
159        result.bytes().all(|b| b.is_ascii()),
160        "RSS 0.9 output contains non-ASCII bytes"
161    );
162
163    // Enforce 8KB limit.
164    if result.len() > RSS_09_MAX_SIZE {
165        bail!("RSS 0.9 output exceeds 8KB limit ({} bytes)", result.len());
166    }
167
168    Ok(result)
169}
170
171#[cfg(test)]
172#[allow(
173    clippy::panic,
174    clippy::expect_used,
175    clippy::unwrap_used,
176    clippy::unwrap_in_result,
177    clippy::panic_in_result_fn,
178    clippy::indexing_slicing,
179    clippy::arithmetic_side_effects,
180    reason = "Standard repository test boilerplate"
181)]
182mod tests {
183    use super::*;
184    use crate::Entry;
185    use crate::rss::rss_09::render_rss_09;
186
187    // -------------------------------------------------------------------------
188    // RSS 0.9 tests
189    // -------------------------------------------------------------------------
190
191    #[crate::ctb_test]
192    fn test_rss_09_basic() {
193        let entry = Entry::new(
194            "http://example.org/item1",
195            "Test Item",
196            "<p>Content</p>",
197            "2024-01-15T10:00:00Z",
198        )
199        .with_url_opt(Some("http://example.org/item1".into()));
200
201        let feed = Feed::new("Test Feed", vec![entry])
202            .with_home_page_url_opt(Some("http://example.org/".into()));
203
204        let result = render_rss_09(&feed).unwrap();
205
206        assert!(
207            result.contains("<?xml version=\"1.0\"?>"),
208            "Got: '{result}'"
209        );
210        assert!(result.contains("xmlns:rdf="), "Got: '{result}'");
211        assert!(result.contains("<channel>"), "Got: '{result}'");
212        assert!(
213            result.contains("<title>Test Feed</title>"),
214            "Got: '{result}'"
215        );
216        assert!(
217            result.contains("<link>http://example.org/</link>"),
218            "Got: '{result}'"
219        );
220        assert!(result.contains("<item>"), "Got: '{result}'");
221        assert!(
222            result.contains("<title>Test Item</title>"),
223            "Got: '{result}'"
224        );
225        assert!(result.contains("</rdf:RDF>"), "Got: '{result}'");
226    }
227
228    #[crate::ctb_test]
229    fn test_rss_09_ascii_only() {
230        let entry = Entry::new(
231            "http://example.org/item1",
232            "Tëst with語 ümlauts",
233            "<p>Cönt語ent</p>",
234            "2024-01-15",
235        )
236        .with_url_opt(Some("http://example.org/item1".into()));
237
238        let feed = Feed::new("Fëed with spë語cial chars", vec![entry])
239            .with_home_page_url_opt(Some("http://example.org/".into()));
240
241        let result = render_rss_09(&feed).unwrap();
242
243        // Non-ASCII should be replaced with `?`.
244        assert!(
245            result.contains("<title>T&euml;st withYu &uuml;mlauts</title"),
246            "Got: '{result}'"
247        );
248        assert!(
249            result.contains("<description>F&euml;ed with sp&euml;Yu cial chars</description>"),
250            "Got: '{result}'"
251        );
252        // Should be valid ASCII.
253        assert!(result.bytes().all(|b| b.is_ascii()));
254    }
255
256    #[crate::ctb_test]
257    fn test_rss_09_max_15_items() {
258        let entries: Vec<_> = (0..20)
259            .map(|i| {
260                Entry::new(
261                    format!("http://example.org/item{i}"),
262                    format!("Item {i}"),
263                    "",
264                    "",
265                )
266                .with_url_opt(Some(format!("http://example.org/item{i}")))
267            })
268            .collect();
269
270        let feed = Feed::new("Many Items", entries)
271            .with_home_page_url_opt(Some("http://example.org/".into()));
272
273        let result = render_rss_09(&feed).unwrap();
274
275        // Should contain items 0-14, but not 15-19.
276        assert!(result.contains("Item 0"));
277        assert!(result.contains("Item 14"));
278        assert!(!result.contains("Item 15"));
279        assert!(!result.contains("Item 19"));
280    }
281
282    #[crate::ctb_test]
283    fn test_rss_09_truncation() {
284        let long_title = "A".repeat(50);
285        let entry = Entry::new("http://example.org/item1", long_title, "", "")
286            .with_url_opt(Some("http://example.org/item1".into()));
287
288        let feed = Feed::new("Test", vec![entry])
289            .with_home_page_url_opt(Some("http://example.org/".into()));
290
291        let result = render_rss_09(&feed).unwrap();
292
293        // Channel title max is 40, but item title max is 100.
294        // The feed title "Test" is short, so it's fine.
295        // The item title of 50 chars is under 100, so it's fine.
296        assert!(result.contains(&"A".repeat(50)));
297    }
298}