1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- use chrono::{DateTime, Utc};
- use htmlescape::encode_minimal;
-
- use config::Config;
- use entry::{Entry, EntryKind};
-
- pub fn generate_post_rss(config: &Config, post: &Entry) -> String {
- let raw_date = post.date.unwrap().and_hms_opt(0, 0, 0).unwrap();
- let date: DateTime<Utc> = DateTime::from_utc(raw_date, Utc);
- let date_string = date.format("%a, %d %b %Y %H:%M:%S %z").to_string();
- let url = format!("{}/posts/{}/", config.url, post.slug);
- format!(
- "<item><title>{}</title><description>{}</description><guid>{}</guid><link>{}</link><pubDate>{}</pubDate></item>",
- post.title, encode_minimal(&post.render("<article>{{ body }}</article>", config)), url, url, date_string
- )
- }
-
- pub fn generate_rss(config: &Config, posts: Vec<Entry>) -> String {
- let items = posts
- .iter()
- .filter(|post| post.kind == EntryKind::Post)
- .map(|post| generate_post_rss(config, post))
- .collect::<Vec<String>>()
- .join("");
-
- format!(
- "<rss version=\"2.0\" xmlns:atom=\"http://www.w3.org/2005/Atom\"><channel><atom:link href=\"{}/rss.xml\" rel=\"self\" /><title>{}</title><description>{}</description><link>{}</link>{}</channel></rss>",
- config.url, config.site_name, config.description, config.url, items
- )
- }
-
- #[cfg(test)]
- mod tests {
- use chrono::NaiveDate;
-
- use super::generate_rss;
- use config::Config;
- use entry::{Entry, EntryKind};
-
- #[test]
- fn generates_rss_feed() {
- let config = Config {
- site_name: String::from("Lorem Ipsum"),
- url: String::from("https://www.loremipsum.com"),
- description: String::from("recent posts from loremipsum.com"),
- };
- let posts: Vec<Entry> = vec![Entry {
- title: String::from("Hello World"),
- body: String::from("lorem ipsum dolor sit amet"),
- slug: String::from("hello-world"),
- date: Some(NaiveDate::from_ymd(2019, 1, 1)),
- kind: EntryKind::Post,
- }];
- assert_eq!(
- generate_rss(&config, posts),
- "<rss version=\"2.0\" xmlns:atom=\"http://www.w3.org/2005/Atom\"><channel><atom:link href=\"https://www.loremipsum.com/rss.xml\" rel=\"self\" /><title>Lorem Ipsum</title><description>recent posts from loremipsum.com</description><link>https://www.loremipsum.com</link><item><title>Hello World</title><description><article><p>lorem ipsum dolor sit amet</p>\n</article></description><guid>https://www.loremipsum.com/posts/hello-world/</guid><link>https://www.loremipsum.com/posts/hello-world/</link><pubDate>Tue, 01 Jan 2019 00:00:00 +0000</pubDate></item></channel></rss>"
- );
- }
- }
|