Use shared get_posts() function for rss and post list

Checkout v4

3.6.0 checkout

Try remote builder
This commit is contained in:
Gabriel Simmer 2023-09-22 13:35:53 +01:00
parent 8d51d01c8b
commit b18534f384
Signed by: arch
SSH key fingerprint: SHA256:m3OEcdtrnBpMX+2BDGh/byv3hrCekCLzDYMdvGEKPPQ
2 changed files with 31 additions and 63 deletions

View file

@ -6,9 +6,9 @@ on:
jobs: jobs:
deploy: deploy:
name: Deploy app name: Deploy app
runs-on: debian-latest runs-on: debian-latest-arm
steps: steps:
- uses: actions/checkout@v3.5.3 - uses: actions/checkout@v3.6.0
with: with:
ref: trunk ref: trunk
- uses: https://github.com/superfly/flyctl-actions/setup-flyctl@master - uses: https://github.com/superfly/flyctl-actions/setup-flyctl@master

View file

@ -20,7 +20,6 @@ use orgize::Org;
use serde::Deserialize; use serde::Deserialize;
use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions}; use sqlx::sqlite::{SqliteConnectOptions, SqliteJournalMode, SqlitePoolOptions};
use sqlx::{FromRow, Pool, Sqlite}; use sqlx::{FromRow, Pool, Sqlite};
use time::format_description::well_known::Rfc2822;
use std::collections::HashMap; use std::collections::HashMap;
use std::fs::{self, File}; use std::fs::{self, File};
use std::io::prelude::*; use std::io::prelude::*;
@ -29,8 +28,7 @@ use std::time::{SystemTime, UNIX_EPOCH};
use tokio::sync::Mutex; use tokio::sync::Mutex;
use tower_http::services::ServeDir; use tower_http::services::ServeDir;
use rss::ChannelBuilder; use rss::ChannelBuilder;
use time::{self, Date, format_description}; use time::{self, format_description, format_description::well_known::Rfc2822};
use time::macros::time as t;
lazy_static! { lazy_static! {
static ref CACHE: Mutex<HashMap<String, CachedPage>> = Mutex::new(HashMap::new()); static ref CACHE: Mutex<HashMap<String, CachedPage>> = Mutex::new(HashMap::new());
@ -128,8 +126,8 @@ async fn main() -> Result<(), sqlx::Error> {
Ok(()) Ok(())
} }
async fn rss() -> Result<impl IntoResponse, StatusCode> { fn get_posts() -> Vec<Post> {
let mut posts: Vec<rss::Item> = Vec::new(); let mut posts: Vec<Post> = Vec::new();
for entry in fs::read_dir("./posts").unwrap() { for entry in fs::read_dir("./posts").unwrap() {
let entry = entry.unwrap(); let entry = entry.unwrap();
let path = entry.path(); let path = entry.path();
@ -160,27 +158,39 @@ async fn rss() -> Result<impl IntoResponse, StatusCode> {
.unwrap_or(&"") .unwrap_or(&"")
.split(":") .split(":")
.collect::<Vec<&str>>()[1].trim(); .collect::<Vec<&str>>()[1].trim();
let date = format!("{} 00:00:00 +00:00:00", date.trim()); let date = date.trim();
posts.push(Post {
name: title.to_owned(),
route: fname,
date: date.to_owned(),
});
}
}
posts.sort_by(|a, b| b.date.cmp(&a.date));
posts
}
async fn rss() -> Result<impl IntoResponse, StatusCode> {
let posts = get_posts();
let rss_posts: Vec<rss::Item> = posts.into_iter().map(|p| {
let date = format!("{} 00:00:00 +00:00:00", p.date);
let format = format_description::parse("[year]-[month]-[day] [hour]:[minute]:[second] [offset_hour sign:mandatory]:[offset_minute]:[offset_second]").unwrap(); let format = format_description::parse("[year]-[month]-[day] [hour]:[minute]:[second] [offset_hour sign:mandatory]:[offset_minute]:[offset_second]").unwrap();
let pub_date = match time::OffsetDateTime::parse(&date, &format).unwrap().format(&Rfc2822) { let pub_date = match time::OffsetDateTime::parse(&date, &format).unwrap().format(&Rfc2822) {
Ok(r) => r, Ok(r) => r,
Err(e) => { dbg!(e.to_string()); "".to_owned() }, Err(e) => { dbg!(e.to_string()); "".to_owned() },
}; };
let item = rss::ItemBuilder::default() rss::ItemBuilder::default()
.title(Some(title.to_owned())) .title(Some(p.name))
.link(Some(format!("https://gabrielsimmer.com/blog/{}", fname))) .link(Some(format!("https://gabrielsimmer.com/blog/{}", p.route)))
.pub_date(Some(pub_date)) .pub_date(Some(pub_date))
.build(); .build()
}).collect();
posts.push(item);
}
}
let channel = ChannelBuilder::default() let channel = ChannelBuilder::default()
.title("Gabriel Simmer's Blog".to_owned()) .title("Gabriel Simmer's Blog".to_owned())
.link("https://gabrielsimmer.com/blog".to_owned()) .link("https://gabrielsimmer.com/blog".to_owned())
.description("Gabriel Simmer's Blog Posts.".to_owned()) .description("Gabriel Simmer's Blog Posts.".to_owned())
.items(posts) .items(rss_posts)
.build(); .build();
return Ok(Response::builder() return Ok(Response::builder()
@ -227,50 +237,8 @@ async fn homepage() -> Markup {
} }
async fn list_blog_posts() -> Markup { async fn list_blog_posts() -> Markup {
let mut posts: Vec<Post> = Vec::new(); let posts = get_posts();
for entry in fs::read_dir("./posts").unwrap() {
let entry = entry.unwrap();
let path = entry.path();
let filename = path.file_name().unwrap().to_str().unwrap();
let ext = path.extension().unwrap().to_str().unwrap();
// strip extension
let fname = filename.replace(&format!(".{}", ext), "");
if ext == "md" || ext == "org" {
// We'll have the date at the beginning of the file
let mut content = File::open(&path).unwrap();
let mut buffer = [0; 100];
content.read(&mut buffer).unwrap();
// Match date data of `date: YYYY-MM-DD` in the first 100 bytes
let metadata = String::from_utf8_lossy(&buffer);
let metadata_lines = metadata.split("\n").collect::<Vec<&str>>();
// dbg!(&metadata);
// Split by --- and get the second element
let date = metadata_lines
.iter()
.find(|&x| x.contains("date:"))
.unwrap_or(&"")
.split(":")
.collect::<Vec<&str>>()[1];
let title = metadata_lines
.iter()
.find(|&x| x.contains("title:"))
.unwrap_or(&"")
.split(":")
.collect::<Vec<&str>>()[1];
let date = date.trim();
dbg!(&date);
posts.push(Post {
name: title.to_owned(),
route: fname,
date: date.to_owned(),
});
}
}
// Sort posts by date // Sort posts by date
posts.sort_by(|a, b| b.date.cmp(&a.date));
html! { html! {
(header("/blog")) (header("/blog"))