ctb_formats_syndication/
json_feed.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//! JSON Feed (version 1.1) serialization and feed conversion utilities.
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29use super::{Entry, Feed};
30use serde::Serialize;
31
32const JSON_FEED_VERSION: &str = "https://jsonfeed.org/version/1.1";
33
34/// Render a [`Feed`] into JSON Feed 1.1.
35///
36/// This intentionally produces a minimal valid JSON Feed with a stable shape,
37/// while leaving room to extend the data model later (attachments, tags, etc.).
38///
39/// Specification: <https://www.jsonfeed.org/version/1.1/>
40pub(crate) fn render(feed: &Feed) -> Result<String> {
41    let out = JsonFeed::from_feed(feed);
42    serde_json::to_string_pretty(&out).context("serializing JSON Feed")
43}
44
45#[derive(Debug, Serialize)]
46struct JsonFeed<'a> {
47    version: &'static str,
48    title: &'a str,
49
50    #[serde(skip_serializing_if = "Option::is_none")]
51    home_page_url: Option<&'a str>,
52
53    #[serde(skip_serializing_if = "Option::is_none")]
54    feed_url: Option<&'a str>,
55
56    items: Vec<JsonFeedItem<'a>>,
57}
58
59impl<'a> JsonFeed<'a> {
60    fn from_feed(feed: &'a Feed) -> Self {
61        Self {
62            version: JSON_FEED_VERSION,
63            title: feed.title(),
64            home_page_url: feed.home_page_url(),
65            feed_url: feed.feed_url(),
66            items: feed
67                .entries()
68                .iter()
69                .map(JsonFeedItem::from_entry)
70                .collect(),
71        }
72    }
73}
74
75#[derive(Debug, Serialize)]
76struct JsonFeedItem<'a> {
77    id: &'a str,
78
79    #[serde(skip_serializing_if = "Option::is_none")]
80    url: Option<&'a str>,
81
82    #[serde(skip_serializing_if = "Option::is_none")]
83    title: Option<&'a str>,
84
85    #[serde(skip_serializing_if = "Option::is_none")]
86    content_html: Option<&'a str>,
87
88    #[serde(skip_serializing_if = "Option::is_none")]
89    date_published: Option<&'a str>,
90
91    #[serde(skip_serializing_if = "Option::is_none")]
92    author: Option<JsonFeedAuthor<'a>>,
93}
94
95impl<'a> JsonFeedItem<'a> {
96    fn from_entry(entry: &'a Entry) -> Self {
97        let title = entry.title();
98        let title = (!title.is_empty()).then_some(title);
99
100        let body_html = entry.body();
101        let body_html = (!body_html.is_empty()).then_some(body_html);
102
103        let date_published = entry.date();
104        let date_published =
105            (!date_published.is_empty()).then_some(date_published);
106
107        Self {
108            id: entry.id(),
109            url: entry.url(),
110            title,
111            content_html: body_html,
112            date_published,
113            author: entry.author().map(|name| JsonFeedAuthor { name }),
114        }
115    }
116}
117
118#[derive(Debug, Serialize)]
119struct JsonFeedAuthor<'a> {
120    name: &'a str,
121}
122
123#[cfg(test)]
124#[allow(
125    clippy::panic,
126    clippy::expect_used,
127    clippy::unwrap_used,
128    clippy::unwrap_in_result,
129    clippy::panic_in_result_fn,
130    clippy::indexing_slicing,
131    clippy::arithmetic_side_effects,
132    reason = "Standard repository test boilerplate"
133)]
134mod tests {
135    use super::*;
136
137    #[crate::ctb_test]
138    fn test_render_empty_feed() {
139        let feed = Feed::empty("Empty Test Feed");
140        let result = render(&feed).unwrap();
141
142        assert!(
143            result.contains(r#""version": "https://jsonfeed.org/version/1.1""#)
144        );
145        assert!(result.contains(r#""title": "Empty Test Feed""#), "{result}");
146        assert!(result.contains(r#""items": []"#));
147    }
148
149    #[crate::ctb_test]
150    fn test_render_feed_with_urls() {
151        let feed = Feed::empty("Test Feed")
152            .with_home_page_url_opt(Some("https://example.org/".into()))
153            .with_feed_url_opt(Some("https://example.org/feed.json".into()));
154        let result = render(&feed).unwrap();
155
156        assert!(result.contains(r#""home_page_url": "https://example.org/""#));
157        assert!(
158            result.contains(r#""feed_url": "https://example.org/feed.json""#)
159        );
160    }
161
162    #[crate::ctb_test]
163    fn test_render_feed_without_optional_urls() {
164        let feed = Feed::empty("Test Feed");
165        let result = render(&feed).unwrap();
166
167        // Optional fields should not appear when not set
168        assert!(!result.contains("home_page_url"));
169        assert!(!result.contains("feed_url"));
170    }
171
172    #[crate::ctb_test]
173    fn test_render_feed_with_entry() {
174        let entry = Entry::new(
175            "entry-1",
176            "Test Entry",
177            "<p>Test content</p>",
178            "2024-01-15T10:30:00Z",
179        )
180        .with_author("Test Author")
181        .with_url_opt(Some("https://example.org/entry-1".into()));
182
183        let feed = Feed::new("Test Feed", vec![entry]);
184        let result = render(&feed).unwrap();
185
186        assert!(result.contains(r#""id": "entry-1""#));
187        assert!(result.contains(r#""title": "Test Entry""#));
188        assert!(result.contains(r#""content_html": "<p>Test content</p>""#));
189        assert!(result.contains(r#""date_published": "2024-01-15T10:30:00Z""#));
190        assert!(result.contains(r#""url": "https://example.org/entry-1""#));
191        assert!(result.contains(r#""author""#));
192        assert!(result.contains(r#""name": "Test Author""#));
193    }
194
195    #[crate::ctb_test]
196    fn test_render_entry_minimal() {
197        // Entry with only required fields (id is required, others optional)
198        let entry = Entry::new("minimal-id", "", "", "");
199        let feed = Feed::new("Minimal Feed", vec![entry]);
200        let result = render(&feed).unwrap();
201
202        assert!(result.contains(r#""id": "minimal-id""#));
203        // Empty strings should not produce fields
204        assert!(!result.contains(r#""title": """#), "{result}");
205        assert!(!result.contains(r#""content_html""#));
206        assert!(!result.contains(r#""date_published""#));
207        assert!(!result.contains(r#""author""#));
208    }
209
210    #[crate::ctb_test]
211    fn test_render_multiple_entries() {
212        let entry1 =
213            Entry::new("id-1", "First", "<p>First</p>", "2024-01-10T00:00:00Z");
214        let entry2 = Entry::new(
215            "id-2",
216            "Second",
217            "<p>Second</p>",
218            "2024-01-15T00:00:00Z",
219        );
220        let feed = Feed::new("Multi Entry Feed", vec![entry1, entry2]);
221        let result = render(&feed).unwrap();
222
223        assert!(result.contains(r#""id": "id-1""#));
224        assert!(result.contains(r#""id": "id-2""#));
225        assert!(result.contains(r#""title": "First""#));
226        assert!(result.contains(r#""title": "Second""#));
227    }
228
229    #[crate::ctb_test]
230    fn test_render_json_structure() {
231        let feed = Feed::empty("Structure Test");
232        let result = render(&feed).unwrap();
233
234        // Should be valid JSON that can be parsed
235        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
236        assert_eq!(
237            parsed.get("version").unwrap(),
238            "https://jsonfeed.org/version/1.1"
239        );
240        assert_eq!(parsed.get("title").unwrap(), "Structure Test");
241        assert!(parsed.get("items").unwrap().is_array());
242    }
243
244    #[crate::ctb_test]
245    fn test_render_special_characters() {
246        let entry = Entry::new(
247            "special-chars",
248            "Title with \"quotes\" and <angle>",
249            "<p>Content with special chars: &amp; \"quotes\"</p>",
250            "2024-01-01T00:00:00Z",
251        );
252        let feed = Feed::new("Special Chars Test", vec![entry]);
253        let result = render(&feed).unwrap();
254
255        // Should produce valid JSON even with special characters
256        let parsed: serde_json::Value = serde_json::from_str(&result).unwrap();
257        let items = parsed.get("items").unwrap().as_array().unwrap();
258        let first_item = items.first().unwrap();
259        assert_eq!(
260            first_item.get("title").unwrap(),
261            "Title with \"quotes\" and <angle>"
262        );
263    }
264}