ctb_formats_syndication/rss/
rss_091.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.91 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    RSS_09_091_MAX_ITEMS, ensure_http_or_ftp_uri, write_text_element,
32};
33use ctb_formats_utf8::ellipsize_to_max_bytes;
34use ctb_utilities::string::remove_line;
35use xml::writer::{EmitterConfig, XmlEvent};
36
37const RSS_091_IMAGE_MAX_WIDTH: u32 = 144;
38const RSS_091_IMAGE_MAX_HEIGHT: u32 = 400;
39
40// ============================================================================
41// RSS 0.91
42// ============================================================================
43
44/// RSS 0.91 rendering flavor.
45#[derive(Debug, Clone, Copy)]
46enum Rss091Flavor {
47    /// Netscape RSS 0.91: requires a DOCTYPE declaration.
48    Netscape,
49    /// `UserLand` RSS 0.91: typically published without a DOCTYPE.
50    UserLand,
51}
52
53/// Render a [`Feed`] into RSS 0.91 (Netscape) format.
54///
55/// This variant includes the required `<!DOCTYPE rss ...>` declaration and
56/// enforces the RSS 0.91 URL constraints (`http://` or `ftp://`).
57///
58/// Constraints enforced:
59/// - Maximum 15 items per channel
60/// - Title: max 100 chars, Description: max 500 chars, Link: max 500 chars
61/// - Item title: max 100 chars, Item link: max 500 chars
62/// - Item description: max 500 chars
63///
64/// Specifications:
65/// - <https://www.rssboard.org/rss-0-9-1> (UserLand variant)
66/// - <https://www.rssboard.org/rss-0-9-1-netscape> (Netscape variant)
67pub fn render_rss_091_netscape(feed: &Feed) -> Result<String> {
68    render_rss_091(feed, Rss091Flavor::Netscape)
69}
70
71/// Render a [`Feed`] into RSS 0.91 (`UserLand`) format.
72///
73/// This variant omits the DOCTYPE declaration and enforces the RSS 0.91 URL
74/// constraints (`http://` or `ftp://`).
75///
76/// Constraints enforced:
77/// - Maximum 15 items per channel
78/// - Title: max 100 chars, Description: max 500 chars, Link: max 500 chars
79/// - Item title: max 100 chars, Item link: max 500 chars
80/// - Item description: max 500 chars
81pub fn render_rss_091_userland(feed: &Feed) -> Result<String> {
82    render_rss_091(feed, Rss091Flavor::UserLand)
83}
84
85fn write_rss_091_userland_channel_image<W: std::io::Write>(
86    writer: &mut xml::writer::EventWriter<W>,
87    feed: &Feed,
88    channel_link: &str,
89) -> Result<()> {
90    let Some(image) = feed.image() else {
91        warn!(
92            "RSS 0.91 (UserLand) requires channel <image>, but none provided"
93        );
94        return Ok(());
95    };
96
97    /*let Some(url) = image.url() else {
98        warn!(
99            "RSS 0.91 (UserLand) channel <image> missing required <url>; skipping <image>"
100        );
101        return Ok(());
102    };*/
103    let url = image.url();
104
105    if url.len() > 500 {
106        warn_fmt!(
107            "RSS 0.91 (UserLand) channel URL is too long; skipping <image>"
108        );
109        return Ok(());
110    }
111
112    if let Err(err) = ensure_http_or_ftp_uri(url) {
113        warn_fmt!(
114            "RSS 0.91 (UserLand) channel <image><url> violates URL constraints (http/ftp only): {err}; skipping <image>"
115        );
116        return Ok(());
117    }
118
119    writer
120        .write(XmlEvent::start_element("image"))
121        .context("writing image start")?;
122
123    let title = match image.alt() {
124        Some(alt) if !alt.is_empty() => alt.to_string(),
125        _ => format!("{} Channel Image", feed.title()),
126    };
127    write_text_element(writer, "title", &ellipsize_to_max_bytes(&title, 100))?;
128
129    write_text_element(writer, "url", &ellipsize_to_max_bytes(url, 500))?;
130
131    // RSS 0.91 requires <link> inside <image>. Spec says that in practice it
132    // should match the channel link.
133    write_text_element(
134        writer,
135        "link",
136        &ellipsize_to_max_bytes(channel_link, 500),
137    )?;
138
139    if let Some(width) = image.width() {
140        let width_clamped = if width > RSS_091_IMAGE_MAX_WIDTH {
141            warn!(
142                "RSS 0.91 (UserLand) channel <image><width> exceeds max {}; clamping",
143                RSS_091_IMAGE_MAX_WIDTH
144            );
145            RSS_091_IMAGE_MAX_WIDTH
146        } else {
147            width
148        };
149        write_text_element(writer, "width", &width_clamped.to_string())?;
150    }
151
152    if let Some(height) = image.height() {
153        let height_clamped = if height > RSS_091_IMAGE_MAX_HEIGHT {
154            warn!(
155                "RSS 0.91 (UserLand) channel <image><height> exceeds max {}; clamping",
156                RSS_091_IMAGE_MAX_HEIGHT
157            );
158            RSS_091_IMAGE_MAX_HEIGHT
159        } else {
160            height
161        };
162        write_text_element(writer, "height", &height_clamped.to_string())?;
163    }
164
165    if let Some(description) = image.description() {
166        if !description.is_empty() {
167            write_text_element(
168                writer,
169                "description",
170                &ellipsize_to_max_bytes(description, 500),
171            )?;
172        }
173    }
174
175    writer
176        .write(XmlEvent::end_element())
177        .context("closing image element")?;
178
179    Ok(())
180}
181
182fn render_rss_091(feed: &Feed, flavor: Rss091Flavor) -> Result<String> {
183    let mut output = Vec::new();
184
185    // Write the XML declaration explicitly so we can inject a DOCTYPE for
186    // the Netscape variant before the root element.
187    output.extend_from_slice(b"\n");
188
189    if matches!(flavor, Rss091Flavor::Netscape) {
190        output.extend_from_slice(br#"<?xml version="1.0"?>"#);
191        output.extend_from_slice(
192            br#"<!DOCTYPE rss SYSTEM "http://my.netscape.com/publish/formats/rss-0.91.dtd">"#,
193        );
194    } else {
195        output.extend_from_slice(br#"<?xml version="1.0" encoding="UTF-8"?>"#);
196    }
197    output.extend_from_slice(b"\n");
198
199    let config = EmitterConfig::new()
200        .perform_indent(true)
201        .indent_string("\t");
202    let mut writer = config.create_writer(&mut output);
203
204    // Start rss element with version.
205    writer
206        .write(XmlEvent::start_element("rss").attr("version", "0.91"))
207        .context("writing rss start element")?;
208
209    // Channel element.
210    writer
211        .write(XmlEvent::start_element("channel"))
212        .context("writing channel start")?;
213
214    write_text_element(
215        &mut writer,
216        "title",
217        &ellipsize_to_max_bytes(feed.title(), 100),
218    )?;
219
220    let Some(link) = feed.home_page_url() else {
221        bail!("RSS 0.91 requires a channel <link> URL");
222    };
223    ensure_http_or_ftp_uri(link)?;
224    write_text_element(
225        &mut writer,
226        "link",
227        &ellipsize_to_max_bytes(link, 500),
228    )?;
229
230    write_text_element(
231        &mut writer,
232        "description",
233        &ellipsize_to_max_bytes(feed.title(), 500),
234    )?;
235
236    // Language is required for 0.91. FIXME: This shouldn't be hardcoded. It's
237    // not totally trivial to implement non-hardcoded since the list of valid
238    // language codes would need to be taken into consideration.
239    write_text_element(&mut writer, "language", "en-us")?;
240
241    if matches!(flavor, Rss091Flavor::UserLand) {
242        write_rss_091_userland_channel_image(&mut writer, feed, link)?;
243    }
244
245    // Items (max 15).
246    let items = feed.entries().iter().take(RSS_09_091_MAX_ITEMS);
247    for entry in items {
248        writer
249            .write(XmlEvent::start_element("item"))
250            .context("writing item start")?;
251
252        write_text_element(
253            &mut writer,
254            "title",
255            &ellipsize_to_max_bytes(entry.title(), 100),
256        )?;
257
258        // Reason for fallback: per RSS 0.91 specification, feed item link falls back to item ID if explicit URL is absent.
259        let item_link = entry.url().unwrap_or(entry.id());
260        ensure_http_or_ftp_uri(item_link)?;
261        write_text_element(
262            &mut writer,
263            "link",
264            &ellipsize_to_max_bytes(item_link, 500),
265        )?;
266
267        // Description (XML escapes markup; RSS 0.91 consumers may impose
268        // additional restrictions beyond well-formed XML).
269        if !entry.body().is_empty() {
270            write_text_element(
271                &mut writer,
272                "description",
273                &ellipsize_to_max_bytes(entry.body(), 500),
274            )?;
275        }
276
277        writer
278            .write(XmlEvent::end_element())
279            .context("closing item element")?;
280    }
281
282    // Close channel.
283    writer
284        .write(XmlEvent::end_element())
285        .context("closing channel element")?;
286
287    // Close rss.
288    writer
289        .write(XmlEvent::end_element())
290        .context("closing rss element")?;
291
292    // Prevent duplicate XML declaration: remove 2nd line for UserLand variant,
293    // and 3rd line for Netscape variant.
294    let result = String::from_utf8(output)
295        .context("RSS 0.91 output is not valid UTF-8")?;
296    Ok(if matches!(flavor, Rss091Flavor::Netscape) {
297        remove_line(&result, 2) // remove 3rd line
298    } else {
299        remove_line(&result, 1) // remove 2nd line
300    })
301}
302
303#[cfg(test)]
304#[allow(
305    clippy::panic,
306    clippy::expect_used,
307    clippy::unwrap_used,
308    clippy::unwrap_in_result,
309    clippy::panic_in_result_fn,
310    clippy::indexing_slicing,
311    clippy::arithmetic_side_effects,
312    reason = "Standard repository test boilerplate"
313)]
314mod tests {
315    use super::*;
316    use crate::Entry;
317    use crate::Image;
318
319    // -------------------------------------------------------------------------
320    // RSS 0.91 tests
321    // -------------------------------------------------------------------------
322
323    #[crate::ctb_test]
324    fn test_rss_091_netscape_basic() -> Result<()> {
325        let entry = Entry::new(
326            "http://example.org/item1",
327            "Test Item",
328            "<p>Description</p>",
329            "2024-01-15",
330        )
331        .with_url_opt(Some("http://example.org/item1".into()));
332
333        let feed = Feed::new("Test Feed", vec![entry])
334            .with_home_page_url_opt(Some("http://example.org/".into()));
335
336        let result = render_rss_091_netscape(&feed)?;
337
338        assert!(
339            result.contains(r#"<?xml version="1.0"?>"#),
340            "Got: '{result}'"
341        );
342        assert!(result.contains(r#"<!DOCTYPE rss SYSTEM "http://my.netscape.com/publish/formats/rss-0.91.dtd">"#), "Got: '{result}'");
343        assert!(
344            result.contains(r#"<rss version="0.91">"#),
345            "Got: '{result}'"
346        );
347        assert!(result.contains("<channel>"), "Got: '{result}'");
348        assert!(
349            result.contains("<language>en-us</language>"),
350            "Got: '{result}'"
351        );
352        assert!(
353            result.contains("<title>Test Item</title>"),
354            "Got: '{result}'"
355        );
356        assert!(result.contains("</rss>"), "Got: '{result}'");
357
358        Ok(())
359    }
360
361    #[crate::ctb_test]
362    fn test_rss_091_userland_basic() -> Result<()> {
363        let entry = Entry::new("http://example.org/item1", "Test Item", "", "")
364            .with_url_opt(Some("http://example.org/item1".into()));
365
366        let feed = Feed::new("Test Feed", vec![entry])
367            .with_home_page_url_opt(Some("http://example.org/".into()));
368
369        let result = render_rss_091_userland(&feed)?;
370
371        assert!(result.contains(r#"<?xml version="1.0" encoding="UTF-8"?>"#));
372        assert!(!result.contains("<!DOCTYPE rss"));
373        assert!(result.contains(r#"<rss version="0.91">"#));
374
375        Ok(())
376    }
377
378    #[crate::ctb_test]
379    fn test_rss_091_userland_with_content() {
380        let entry = Entry::new(
381            "http://example.org/item1",
382            "Test Item",
383            "<p>Description</p>",
384            "2024-01-15",
385        )
386        .with_url_opt(Some("http://example.org/item1".into()));
387
388        let feed = Feed::new("Test Feed", vec![entry])
389            .with_home_page_url_opt(Some("http://example.org/".into()));
390
391        let result = render_rss_091_userland(&feed).unwrap();
392
393        assert!(
394            result.contains("<?xml version=\"1.0\" encoding=\"UTF-8\"?>"),
395            "Got: '{result}'"
396        );
397        assert!(result.contains("<rss version=\"0.91\">"), "Got: '{result}'");
398        assert!(result.contains("<channel>"), "Got: '{result}'");
399        assert!(
400            result.contains("<language>en-us</language>"),
401            "Got: '{result}'"
402        );
403        assert!(
404            result.contains("<title>Test Item</title>"),
405            "Got: '{result}'"
406        );
407        assert!(result.contains("<description>"), "Got: '{result}'");
408        assert!(result.contains("</rss>"), "Got: '{result}'");
409    }
410
411    #[crate::ctb_test]
412    fn test_rss_091_max_15_items() -> Result<()> {
413        let entries: Vec<_> = (0..20)
414            .map(|i| {
415                Entry::new(
416                    format!("http://example.org/item{i}"),
417                    format!("Item {i}"),
418                    "",
419                    "",
420                )
421                .with_url_opt(Some(format!("http://example.org/item{i}")))
422            })
423            .collect();
424
425        let feed = Feed::new("Many Items", entries)
426            .with_home_page_url_opt(Some("http://example.org/".into()));
427
428        let result = render_rss_091_userland(&feed)?;
429
430        assert!(result.contains("Item 14"));
431        assert!(!result.contains("Item 15"));
432
433        Ok(())
434    }
435
436    #[crate::ctb_test]
437    fn test_rss_091_url_constraints_reject_https() -> Result<()> {
438        let entry =
439            Entry::new("https://example.org/item1", "Test Item", "", "")
440                .with_url_opt(Some("https://example.org/item1".into()));
441
442        let feed = Feed::new("Test Feed", vec![entry])
443            .with_home_page_url_opt(Some("https://example.org/".into()));
444
445        match render_rss_091_userland(&feed) {
446            Ok(_) => bail!("expected URL constraint error for https://"),
447            Err(_) => Ok(()),
448        }
449    }
450
451    #[crate::ctb_test]
452    fn test_rss_091_requires_channel_link() -> Result<()> {
453        let entry = Entry::new("http://example.org/item1", "Test Item", "", "")
454            .with_url_opt(Some("http://example.org/item1".into()));
455
456        let feed = Feed::new("Test Feed", vec![entry]);
457
458        match render_rss_091_netscape(&feed) {
459            Ok(_) => bail!("expected missing channel <link> error"),
460            Err(_) => Ok(()),
461        }
462    }
463
464    #[crate::ctb_test]
465    fn test_rss_091_utf8() -> Result<()> {
466        let entry = Entry::new(
467            "http://example.org/item1",
468            "日本語タイトル",
469            "日本語の説明",
470            "",
471        )
472        .with_url_opt(Some("http://example.org/item1".into()));
473
474        let feed = Feed::new("日本語フィード", vec![entry])
475            .with_home_page_url_opt(Some("http://example.org/".into()));
476
477        let result = render_rss_091_userland(&feed)?;
478
479        assert!(result.contains("日本語タイトル"));
480        assert!(result.contains("日本語フィード"));
481
482        Ok(())
483    }
484
485    #[crate::ctb_test]
486    fn test_rss_091_userland_channel_image_best_effort() -> Result<()> {
487        let entry = Entry::new("http://example.org/item1", "Test Item", "", "")
488            .with_url_opt(Some("http://example.org/item1".into()));
489
490        let feed = Feed::new("Test Feed", vec![entry])
491            .with_home_page_url_opt(Some("http://example.org/".into()))
492            // Omit alt/title on purpose; renderer should derive it from
493            // feed.title() + " Channel Image".
494            .with_image(
495                Image::new()
496                    .with_url("http://example.org/image.png".into())
497                    .with_width_opt(Some(200))
498                    .with_height_opt(Some(600))
499                    .with_description_opt(Some("Image description".into())),
500            );
501
502        let result = render_rss_091_userland(&feed)?;
503
504        assert!(result.contains("<image>"), "Got: '{result}'");
505        assert!(
506            result.contains("<title>Test Feed Channel Image</title>"),
507            "Got: '{result}'"
508        );
509        assert!(
510            result.contains("<url>http://example.org/image.png</url>"),
511            "Got: '{result}'"
512        );
513        assert!(
514            result.contains("<link>http://example.org/</link>"),
515            "Got: '{result}'"
516        );
517        // Width/height should be clamped to the RSS 0.91 limits.
518        assert!(result.contains("<width>144</width>"), "Got: '{result}'");
519        assert!(result.contains("<height>400</height>"), "Got: '{result}'");
520        assert!(
521            result.contains("<description>Image description</description>"),
522            "Got: '{result}'"
523        );
524
525        Ok(())
526    }
527}