added rss generator

This commit is contained in:
2024-12-10 14:06:22 -05:00
parent ae86f86339
commit 637f0b47dd
6 changed files with 190 additions and 3 deletions

View File

@ -16,6 +16,7 @@ use tracing_subscriber::{filter, layer::SubscriberExt, prelude::*, util::Subscri
mod config;
mod datasources;
mod routes;
mod utils;
pub struct AppState {
db: PgPool,

View File

@ -1,7 +1,11 @@
use std::collections::HashMap;
use crate::utils::rss;
use crate::{datasources::posts::PostsDatasource, AppState};
use axum::http::{HeaderMap, HeaderValue};
use axum::{
extract::{Path, State},
http::StatusCode,
http::{header, StatusCode},
response::IntoResponse,
routing::get,
Json, Router,
@ -10,7 +14,7 @@ use chrono::Utc;
use serde::{Deserialize, Serialize, Serializer};
use sqlx::{Pool, Postgres};
#[derive(sqlx::FromRow, Serialize, Debug)]
#[derive(sqlx::FromRow, Serialize, Debug, Clone)]
pub struct Post {
pub post_id: i32,
pub author_id: Option<i32>,
@ -51,6 +55,7 @@ impl PostsRoute {
.route("/popular", get(PostsRoute::get_popular_posts))
.route("/hot", get(PostsRoute::get_hot_posts))
.route("/featured", get(PostsRoute::get_featured_posts))
.route("/rss", get(PostsRoute::get_rss_posts))
.with_state(app_state.db.clone())
}
@ -104,6 +109,40 @@ impl PostsRoute {
Err(e) => Err((StatusCode::INTERNAL_SERVER_ERROR, e.to_string())),
}
}
// get rss posts
async fn get_rss_posts(State(pool): State<Pool<Postgres>>) -> impl IntoResponse {
match PostsDatasource::get_all(&pool).await {
Ok(posts) => {
let web_url = std::env::var("BASE_URI_WEB").expect("No environment variable found");
let mapped_posts: HashMap<String, Post> = posts
.into_iter()
.map(|post| (post.post_id.to_string(), post))
.collect();
let xml: String = rss::generate_rss(
"Wyatt's blog",
"Wyatt and friends",
web_url.as_str(),
&mapped_posts,
);
let mut headers = HeaderMap::new();
headers.insert(
header::CONTENT_DISPOSITION,
HeaderValue::from_str(r#"attachment; filename="posts.xml""#).unwrap(),
);
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/xml"),
);
(headers, xml)
}
Err(e) => {
let mut headers = HeaderMap::new();
headers.insert("Content-Type", HeaderValue::from_static("text/plain"));
(headers, e.to_string())
}
}
}
}
pub fn serialize_datetime<S>(

View File

@ -0,0 +1 @@
pub mod rss;

View File

@ -0,0 +1,90 @@
use crate::routes::posts;
use std::collections::HashMap;
use xml::escape::escape_str_pcdata;
pub struct RssEntry {
pub title: String,
pub link: String,
pub description: Option<String>,
pub created_at: String,
pub author: String,
pub guid: String,
}
impl From<posts::Post> for RssEntry {
fn from(post: posts::Post) -> Self {
let web_url = std::env::var("BASE_URI_WEB").expect("Environment variable not found");
let post_url = format!("{}{}{}", web_url, "/posts/", post.post_id.to_string());
let author_full_name = format!("{} {}", post.first_name.unwrap(), post.last_name.unwrap());
Self {
title: post.title.clone(),
link: post_url.clone(),
description: Some(post.body.clone()),
created_at: post
.created_at
.expect("No timestamp was available")
.to_rfc2822(),
author: author_full_name,
guid: post_url.clone(),
}
}
}
impl RssEntry {
pub fn to_item(&self) -> String {
format!(
r#"
<item>
<title><![CDATA[{}]]></title>
<description><![CDATA[{}]]></description>
<pubDate>{}</pubDate>
<link>{}</link>
<guid isPermaLink="true">{}</guid>
</item>
"#,
self.title,
self.description.clone().unwrap_or_default(),
self.created_at,
self.guid,
self.guid
)
}
}
pub fn generate_rss(
title: &str,
description: &str,
link: &str,
posts: &HashMap<String, posts::Post>,
) -> String {
println!("{:?}", posts);
let values = posts.clone().into_values();
println!("{:?}", values);
let rss_entries = values
.map(|p| p.into())
.map(|r: RssEntry| r.to_item())
.collect::<String>();
let safe_title = escape_str_pcdata(title);
let safe_description = escape_str_pcdata(description);
println!("{:?}", rss_entries);
format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">
<channel>
<title>{safe_title}</title>
<description>{safe_description}</description>
<link>{link}</link>
<language>en-us</language>
<ttl>60</ttl>
<generator>Kyouma 1.0.0-SE</generator>
<atom:link href="https://wyattjmiller.com/posts.xml" rel="self" type="application/rss+xml" />
{}
</channel>
</rss>"#,
rss_entries
)
}