use crate::{Blog, support};
pub struct Feed;
impl Feed {
pub fn for_blog(blog: &Blog, locale: &str) -> String {
let settings = blog.settings();
let app_name = laravel::config().app.name.clone();
let title = settings
.feed
.title
.as_ref()
.and_then(|title| title.for_locale(locale))
.map_or(app_name, str::to_owned);
let description = settings
.feed
.description
.as_ref()
.and_then(|description| description.for_locale(locale))
.map_or_else(|| title.clone(), str::to_owned);
let mut xml = String::from("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
xml.push_str("<rss version=\"2.0\" xmlns:atom=\"http://www.w3.org/2005/Atom\">\n <channel>\n");
xml.push_str(&format!(" <title>{}</title>\n", text(&title)));
xml.push_str(&format!(
" <link>{}</link>\n",
text(&blog.url("index", Some(locale), &[], true))
));
xml.push_str(&format!(" <description>{}</description>\n", text(&description)));
xml.push_str(&format!(" <language>{}</language>\n", text(locale)));
xml.push_str(&format!(
" <atom:link href=\"{}\" rel=\"self\" type=\"application/rss+xml\"/>\n",
attribute(&blog.url("feed", Some(locale), &[], true))
));
for post in blog.posts(Some(locale)).into_iter().take(settings.feed.limit) {
let url = post.url();
xml.push_str(" <item>\n");
xml.push_str(&format!(" <title>{}</title>\n", text(&post.title)));
xml.push_str(&format!(" <link>{}</link>\n", text(&url)));
xml.push_str(&format!(" <guid isPermaLink=\"true\">{}</guid>\n", text(&url)));
xml.push_str(&format!(" <pubDate>{}</pubDate>\n", support::rss(post.date)));
if let Some(description) = post
.description
.as_deref()
.filter(|description| !description.is_empty())
{
xml.push_str(&format!(" <description>{}</description>\n", text(description)));
}
if let Some(category) = post.category() {
xml.push_str(&format!(" <category>{}</category>\n", text(&category.name)));
}
xml.push_str(" </item>\n");
}
xml.push_str(" </channel>\n</rss>\n");
xml
}
}
fn text(value: &str) -> String {
value.replace('&', "&").replace('<', "<").replace('>', ">")
}
fn attribute(value: &str) -> String {
text(value).replace('"', """)
}