ctb_formats_syndication/rss/
scripting_news.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//! `ScriptingNews` format renderer for the syndication data model.
21//!
22//! `ScriptingNews` is an XML syndication format predating RSS, first published
23//! in December 1997.
24//!
25//! I'm not sure about the encoding or specific entities used, so I made a best
26//! guess.
27//!
28//! This module implements:
29//! - **`ScriptingNews` 1.0** (version string `1.0a2`): ASCII-only output using
30//!   HTML 3.2 entities.
31//! - **`ScriptingNews` 2.0** (version string `2.0b1`): ASCII-only output using
32//!   Netscape 1999 entities, with additional header elements for parity with
33//!   RSS 0.9.
34//!
35//! Specification for 2.0b1: <https://web.archive.org/web/19990902194349/http://my.userland.com/stories/storyReader$11>
36//! DTD: <https://web.archive.org/web/19980131193200if_/http://www.scripting.com:80/dtd/scriptingNews.dtd>
37
38#[allow(
39    unused_imports,
40    clippy::wildcard_imports,
41    reason = "Standard workspace module prelude"
42)]
43use crate::utilities::*;
44
45use super::Feed;
46use ctb_formats_html::entities::{
47    to_entities_html32, to_entities_netscape_1999,
48};
49use ctb_formats_utf8::to_ascii_translit;
50use jiff::Timestamp;
51
52const TIME_FMT: &str = "%a, %d %b %Y %H:%M:%S GMT";
53
54fn write_feed_dates_to_strings(feed: &Feed) -> (String, String) {
55    // Use current date for pubDate and lastBuildDate if not available.
56    // Format: "Fri, 26 Dec 1997 08:00:00 GMT"
57
58    let now_date = Timestamp::now().strftime(TIME_FMT).to_string();
59
60    let pub_date = if let Some(entry) = feed.entries().first() {
61        entry.try_updated_try_format(TIME_FMT)
62    } else {
63        now_date.clone()
64    };
65
66    (pub_date, now_date)
67}
68
69fn push_open(out: &mut String, indent: usize, name: &str) {
70    out.push_str(&"\t".repeat(indent));
71    out.push('<');
72    out.push_str(name);
73    out.push_str(">\n");
74}
75
76fn push_close(out: &mut String, indent: usize, name: &str) {
77    out.push_str(&"\t".repeat(indent));
78    out.push_str("</");
79    out.push_str(name);
80    out.push_str(">\n");
81}
82
83fn push_text_element_raw(
84    out: &mut String,
85    indent: usize,
86    name: &str,
87    value: &str,
88) {
89    out.push_str(&"\t".repeat(indent));
90    out.push('<');
91    out.push_str(name);
92    out.push('>');
93    out.push_str(value);
94    out.push_str("</");
95    out.push_str(name);
96    out.push_str(">\n");
97}
98
99// ============================================================================
100// `ScriptingNews` 1.0 (version 1.0a2)
101// ============================================================================
102
103/// Prepare a string for `ScriptingNews` 1.0 (ASCII-only, HTML 3.2 entities).
104fn prep_string_10(input: &str) -> Result<String> {
105    let input = to_entities_html32(input.to_string())?;
106    Ok(to_ascii_translit(&input))
107}
108
109/// Render a [`Feed`] into `ScriptingNews` 1.0 (version 1.0a2) format.
110///
111/// `ScriptingNews` 1.0 is an early XML syndication format with:
112/// - A header containing copyright, version, dates, and docs URL
113/// - Multiple items, each with text and a single link (url + linetext)
114/// - ASCII-only output (non-ASCII replaced with `?`)
115/// TODO: Make sure it is *not* escaping HTML syntax in item text, unlike 2.0.
116pub fn render_scripting_news_10(feed: &Feed) -> Result<String> {
117    let mut out = String::new();
118
119    // Original format: uppercase XML declaration + external DTD.
120    out.push_str(r#"<?XML VERSION="1.0"?>"#);
121    out.push('\n');
122    out.push_str(
123        r#"<!DOCTYPE scriptingNews SYSTEM "http://www.scripting.com/dtd/scriptingNews.dtd">"#,
124    );
125    out.push('\n');
126
127    push_open(&mut out, 0, "scriptingNews");
128    push_open(&mut out, 1, "header");
129
130    /* write_text_element(
131        &mut writer,
132        "copyright",
133        &prep_string_10(&format!("Copyright {}", feed.title()))?,
134    )?; */
135    push_text_element_raw(&mut out, 2, "scriptingNewsVersion", "1.0a2");
136
137    let (pub_date, last_build_date) = write_feed_dates_to_strings(feed);
138    push_text_element_raw(&mut out, 2, "pubDate", &pub_date);
139    push_text_element_raw(&mut out, 2, "lastBuildDate", &last_build_date);
140
141    // Reason for fallback: docs element defaults to empty string if home_page_url is absent.
142    let docs_url = feed.home_page_url().unwrap_or("");
143    push_text_element_raw(&mut out, 2, "docs", &prep_string_10(docs_url)?);
144
145    push_close(&mut out, 1, "header");
146
147    for entry in feed.entries() {
148        push_open(&mut out, 1, "item");
149
150        // 1.0a2: do not escape embedded HTML markup inside `<text>`.
151        // FIXME? This doesn't try to convert modern HTML to HTML 3.2 (guessing
152        // that is the appropriate version to use).
153        let text = to_ascii_translit(entry.body());
154        push_text_element_raw(&mut out, 2, "text", &text);
155
156        push_open(&mut out, 2, "link");
157
158        // Reason for fallback: item URL falls back to item ID per scripting news specification.
159        let url = entry.url().unwrap_or(entry.id());
160        push_text_element_raw(&mut out, 3, "url", &prep_string_10(url)?);
161        push_text_element_raw(
162            &mut out,
163            3,
164            "linetext",
165            &prep_string_10(entry.title())?,
166        );
167
168        push_close(&mut out, 2, "link");
169        push_close(&mut out, 1, "item");
170    }
171
172    push_close(&mut out, 0, "scriptingNews");
173
174    if !out.bytes().all(|b| b.is_ascii()) {
175        bail!("ScriptingNews 1.0 output contains non-ASCII characters");
176    }
177
178    Ok(out)
179}
180
181// ============================================================================
182// `ScriptingNews` 2.0 (version 2.0b1)
183// ============================================================================
184
185/// Prepare a string for `ScriptingNews` 2.0 (ASCII-only, Netscape 1999
186/// entities).
187fn prep_string_20(input: &str) -> Result<String> {
188    let input = to_entities_netscape_1999(input.to_string())?;
189    Ok(to_ascii_translit(&input))
190}
191
192/// Render a [`Feed`] into `ScriptingNews` 2.0 (version 2.0b1) format.
193///
194/// `ScriptingNews` 2.0 extends 1.0 with additional header elements for parity
195/// with RSS 0.9:
196/// - channelTitle, channelLink, channelDescription
197/// - imageTitle, imageUrl, imageLink
198/// - managingEditor, webmaster, language
199/// - imageHeight, imageWidth, imageCaption
200/// - skipHours, skipDays (not implemented here)
201///
202/// ASCII-only output (non-ASCII replaced with `?`).
203pub fn render_scripting_news_20(feed: &Feed) -> Result<String> {
204    let mut out = String::new();
205
206    // Sample output uses no `encoding="..."` attribute.
207    out.push_str(r#"<?xml version="1.0"?>"#);
208    out.push('\n');
209
210    push_open(&mut out, 0, "scriptingNews");
211    push_open(&mut out, 1, "header");
212
213    /* write_text_element(
214        &mut writer,
215        "copyright",
216        &prep_string_20(&format!("Copyright {}", feed.title()))?,
217    )?; */
218    push_text_element_raw(&mut out, 2, "scriptingNewsVersion", "2.0b1");
219
220    let (pub_date, last_build_date) = write_feed_dates_to_strings(feed);
221    push_text_element_raw(&mut out, 2, "pubDate", &pub_date);
222    push_text_element_raw(&mut out, 2, "lastBuildDate", &last_build_date);
223
224    // Reason for fallback: docs element defaults to empty string if home_page_url is absent.
225    let docs_url = feed.home_page_url().unwrap_or("");
226    push_text_element_raw(&mut out, 2, "docs", &prep_string_20(docs_url)?);
227
228    push_text_element_raw(
229        &mut out,
230        2,
231        "channelDescription",
232        &prep_string_20(feed.title())?,
233    );
234
235    // Reason for fallback: channelLink defaults to empty string if home_page_url is absent.
236    let channel_link = feed.home_page_url().unwrap_or("");
237    push_text_element_raw(
238        &mut out,
239        2,
240        "channelLink",
241        &prep_string_20(channel_link)?,
242    );
243    push_text_element_raw(
244        &mut out,
245        2,
246        "channelTitle",
247        &prep_string_20(feed.title())?,
248    );
249
250    push_text_element_raw(&mut out, 2, "language", "en-US");
251
252    push_close(&mut out, 1, "header");
253
254    for entry in feed.entries() {
255        push_open(&mut out, 1, "item");
256
257        // 2.0b1: `<text>` should be escaped (e.g. `<i>` -> `&lt;i&gt;`).
258        push_text_element_raw(
259            &mut out,
260            2,
261            "text",
262            &prep_string_20(entry.body())?,
263        );
264
265        push_open(&mut out, 2, "link");
266
267        // Reason for fallback: item URL falls back to item ID per scripting news specification.
268        let url = entry.url().unwrap_or(entry.id());
269        push_text_element_raw(&mut out, 3, "url", &prep_string_20(url)?);
270        push_text_element_raw(
271            &mut out,
272            3,
273            "linetext",
274            &prep_string_20(entry.title())?,
275        );
276
277        push_close(&mut out, 2, "link");
278        push_close(&mut out, 1, "item");
279    }
280
281    push_close(&mut out, 0, "scriptingNews");
282
283    if !out.bytes().all(|b| b.is_ascii()) {
284        bail!("ScriptingNews 2.0 output contains non-ASCII characters");
285    }
286
287    Ok(out)
288}
289
290// ============================================================================
291// Tests
292// ============================================================================
293
294#[cfg(test)]
295#[allow(
296    clippy::panic,
297    clippy::expect_used,
298    clippy::unwrap_used,
299    clippy::unwrap_in_result,
300    clippy::panic_in_result_fn,
301    clippy::indexing_slicing,
302    clippy::arithmetic_side_effects,
303    reason = "Standard repository test boilerplate"
304)]
305mod tests {
306    use super::*;
307    use crate::Entry;
308
309    // -------------------------------------------------------------------------
310    // ScriptingNews 1.0 tests
311    // -------------------------------------------------------------------------
312
313    #[crate::ctb_test]
314    fn test_scripting_news_10_basic() {
315        let entry = Entry::new(
316            "http://example.org/item1",
317            "Test Item",
318            "The example content. Lorem ipsum dolor sit amet.",
319            "2024-01-15T10:00:00Z",
320        )
321        .with_url_opt(Some("http://example.org/item1".into()));
322
323        let feed = Feed::new("Test Feed", vec![entry])
324            .with_home_page_url_opt(Some("http://example.org/".into()));
325
326        let result = render_scripting_news_10(&feed).unwrap();
327
328        // Check XML declaration (uppercase VERSION per original format).
329        assert!(result.contains(r#"<?XML VERSION="1.0"?>"#));
330        // Check DOCTYPE.
331        assert!(result.contains(
332            r#"<!DOCTYPE scriptingNews SYSTEM "http://www.scripting.com/dtd/scriptingNews.dtd">"#
333        ));
334        // Check structure.
335        assert!(result.contains("<scriptingNews>"));
336        assert!(result.contains("<header>"));
337        assert!(
338            result
339                .contains("<scriptingNewsVersion>1.0a2</scriptingNewsVersion>")
340        );
341        assert!(result.contains("<item>"));
342        assert!(result.contains(
343            "<text>The example content. Lorem ipsum dolor sit amet.</text>"
344        ));
345        assert!(result.contains("<link>"));
346        assert!(result.contains("<url>http://example.org/item1</url>"));
347        assert!(result.contains("<linetext>Test Item</linetext>"));
348        assert!(result.contains("</scriptingNews>"));
349    }
350
351    #[crate::ctb_test]
352    fn test_scripting_news_10_ascii_only() {
353        let entry = Entry::new(
354            "http://example.org/item1",
355            "Tëst with ümlauts",
356            "Cöntent with spëcial chärs",
357            "2024-01-15",
358        )
359        .with_url_opt(Some("http://example.org/item1".into()));
360
361        let feed = Feed::new("Fëed with spëcial chars", vec![entry])
362            .with_home_page_url_opt(Some("http://example.org/".into()));
363
364        let result = render_scripting_news_10(&feed).unwrap();
365
366        // Non-ASCII should be replaced with `?` or transliterated.
367        assert!(result.bytes().all(|b| b.is_ascii()));
368        // Should contain transliterated or entity-replaced versions.
369        assert!(!result.contains("ë"));
370        assert!(!result.contains("ü"));
371        assert!(!result.contains("ö"));
372        assert!(!result.contains("ä"));
373    }
374
375    #[crate::ctb_test]
376    fn test_scripting_news_10_html_in_text() {
377        let entry = Entry::new(
378            "http://example.org/item1",
379            "Item with HTML",
380            "Content with <i>italic</i> and <b>bold</b>",
381            "2024-01-15",
382        )
383        .with_url_opt(Some("http://example.org/item1".into()));
384
385        let feed = Feed::new("Test Feed", vec![entry])
386            .with_home_page_url_opt(Some("http://example.org/".into()));
387
388        let result = render_scripting_news_10(&feed).unwrap();
389
390        // HTML tags should probably be escaped in XML. However, in practice, it
391        // doesn't seem to be in ScriptingNews 1.0a2 based on a sample file.
392        // ScriptingNews 2.0b1 does escape them.
393        assert!(result.contains("<i>italic</i>"), "Got: '{result}'");
394        assert!(result.contains("<b>bold</b>"), "Got: '{result}'");
395    }
396
397    #[crate::ctb_test]
398    fn test_scripting_news_10_multiple_items() {
399        let entries: Vec<_> = (0..5)
400            .map(|i| {
401                Entry::new(
402                    format!("http://example.org/item{i}"),
403                    format!("Item {i}"),
404                    format!("Content for item {i}"),
405                    "",
406                )
407                .with_url_opt(Some(format!("http://example.org/item{i}")))
408            })
409            .collect();
410
411        let feed = Feed::new("Multi-Item Feed", entries)
412            .with_home_page_url_opt(Some("http://example.org/".into()));
413
414        let result = render_scripting_news_10(&feed).unwrap();
415
416        assert!(result.contains("Item 0"));
417        assert!(result.contains("Item 4"));
418        assert!(result.contains("Content for item 2"));
419    }
420
421    // -------------------------------------------------------------------------
422    // ScriptingNews 2.0 tests
423    // -------------------------------------------------------------------------
424
425    #[crate::ctb_test]
426    fn test_scripting_news_20_basic() {
427        let entry = Entry::new(
428            "http://example.org/item1",
429            "Test Item",
430            "The example content. Lorem ipsum dolor sit amet.",
431            "2024-01-15T10:00:00Z",
432        )
433        .with_url_opt(Some("http://example.org/item1".into()));
434
435        let feed = Feed::new("Test Feed", vec![entry])
436            .with_home_page_url_opt(Some("http://example.org/".into()));
437
438        let result = render_scripting_news_20(&feed).unwrap();
439
440        // Check XML declaration (lowercase, standard).
441        assert!(
442            result.contains(r#"<?xml version="1.0"?>"#),
443            "Got: '{result}'"
444        );
445        // Check structure.
446        assert!(result.contains("<scriptingNews>"), "Got: '{result}'");
447        assert!(result.contains("<header>"), "Got: '{result}'");
448        assert!(
449            result
450                .contains("<scriptingNewsVersion>2.0b1</scriptingNewsVersion>"),
451            "Got: '{result}'"
452        );
453
454        // Check 2.0-specific header elements.
455        assert!(
456            result.contains("<channelTitle>Test Feed</channelTitle>"),
457            "Got: '{result}'"
458        );
459        assert!(
460            result.contains("<channelLink>http://example.org/</channelLink>"),
461            "Got: '{result}'"
462        );
463        assert!(
464            result
465                .contains("<channelDescription>Test Feed</channelDescription>"),
466            "Got: '{result}'"
467        );
468        assert!(
469            result.contains("<language>en-US</language>"),
470            "Got: '{result}'"
471        );
472
473        // Check item structure.
474        assert!(result.contains("<item>"), "Got: '{result}'");
475        assert!(
476            result.contains(
477                "<text>The example content. Lorem ipsum dolor sit amet.</text>"
478            ),
479            "Got: '{result}'"
480        );
481        assert!(result.contains("<link>"), "Got: '{result}'");
482        assert!(
483            result.contains("<url>http://example.org/item1</url>"),
484            "Got: '{result}'"
485        );
486        assert!(
487            result.contains("<linetext>Test Item</linetext>"),
488            "Got: '{result}'"
489        );
490        assert!(result.contains("</scriptingNews>"), "Got: '{result}'");
491    }
492
493    #[crate::ctb_test]
494    fn test_scripting_news_20_ascii_only() {
495        let entry = Entry::new(
496            "http://example.org/item1",
497            "Tëst with ümlauts",
498            "Cöntent with spëcial chärs",
499            "2024-01-15",
500        )
501        .with_url_opt(Some("http://example.org/item1".into()));
502
503        let feed = Feed::new("Fëed with spëcial chars", vec![entry])
504            .with_home_page_url_opt(Some("http://example.org/".into()));
505
506        let result = render_scripting_news_20(&feed).unwrap();
507
508        // Non-ASCII should be replaced with `?` or transliterated.
509        assert!(result.bytes().all(|b| b.is_ascii()));
510        // Should not contain raw non-ASCII characters.
511        assert!(!result.contains("ë"));
512        assert!(!result.contains("ü"));
513        assert!(!result.contains("ö"));
514        assert!(!result.contains("ä"));
515    }
516
517    #[crate::ctb_test]
518    fn test_scripting_news_20_no_doctype() {
519        let feed = Feed::empty("Test Feed")
520            .with_home_page_url_opt(Some("http://example.org/".into()));
521
522        let result = render_scripting_news_20(&feed).unwrap();
523
524        // Version 2.0 should NOT have a DOCTYPE declaration (per the sample).
525        assert!(!result.contains("<!DOCTYPE"), "Got: '{result}'");
526    }
527
528    #[crate::ctb_test]
529    fn test_scripting_news_20_html_in_text() {
530        let entry = Entry::new(
531            "http://example.org/item1",
532            "Item with HTML",
533            "Content with <i>italic</i> text",
534            "2024-01-15",
535        )
536        .with_url_opt(Some("http://example.org/item1".into()));
537
538        let feed = Feed::new("Test Feed", vec![entry])
539            .with_home_page_url_opt(Some("http://example.org/".into()));
540
541        let result = render_scripting_news_20(&feed).unwrap();
542
543        // HTML tags should be escaped in XML.
544        assert!(
545            result.contains("&lt;i&gt;italic&lt;/i&gt;"),
546            "Got: '{result}'"
547        );
548    }
549
550    #[crate::ctb_test]
551    fn test_scripting_news_20_multiple_items() {
552        let entries: Vec<_> = (0..3)
553            .map(|i| {
554                Entry::new(
555                    format!("http://example.org/item{i}"),
556                    format!("Item {i}"),
557                    format!("Content for item {i}"),
558                    "",
559                )
560                .with_url_opt(Some(format!("http://example.org/item{i}")))
561            })
562            .collect();
563
564        let feed = Feed::new("Multi-Item Feed", entries)
565            .with_home_page_url_opt(Some("http://example.org/".into()));
566
567        let result = render_scripting_news_20(&feed).unwrap();
568
569        assert!(result.contains("Item 0"));
570        assert!(result.contains("Item 2"));
571        assert!(result.contains("Content for item 1"));
572    }
573
574    #[crate::ctb_test]
575    fn test_scripting_news_10_vs_20_version_strings() {
576        let feed = Feed::empty("Test")
577            .with_home_page_url_opt(Some("http://example.org/".into()));
578
579        let result_10 = render_scripting_news_10(&feed).unwrap();
580        let result_20 = render_scripting_news_20(&feed).unwrap();
581
582        assert!(
583            result_10
584                .contains("<scriptingNewsVersion>1.0a2</scriptingNewsVersion>"),
585            "Got: '{result_10}'"
586        );
587        assert!(
588            result_20
589                .contains("<scriptingNewsVersion>2.0b1</scriptingNewsVersion>"),
590            "Got: '{result_20}'"
591        );
592    }
593
594    #[crate::ctb_test]
595    fn test_scripting_news_20_has_channel_elements() {
596        let feed = Feed::new("My Channel", vec![])
597            .with_home_page_url_opt(Some("http://example.org/".into()));
598
599        let result_10 = render_scripting_news_10(&feed).unwrap();
600        let result_20 = render_scripting_news_20(&feed).unwrap();
601
602        // Version 1.0 should NOT have channel* elements.
603        assert!(!result_10.contains("<channelTitle>"), "Got: '{result_10}'");
604        assert!(!result_10.contains("<channelLink>"), "Got: '{result_10}'");
605        assert!(
606            !result_10.contains("<channelDescription>"),
607            "Got: '{result_10}'"
608        );
609
610        // Version 2.0 SHOULD have channel* elements.
611        assert!(
612            result_20.contains("<channelTitle>My Channel</channelTitle>"),
613            "Got: '{result_20}'"
614        );
615        assert!(
616            result_20
617                .contains("<channelLink>http://example.org/</channelLink>"),
618            "Got: '{result_20}'"
619        );
620        assert!(
621            result_20.contains(
622                "<channelDescription>My Channel</channelDescription>"
623            ),
624            "Got: '{result_20}'"
625        );
626    }
627}