mylloon.fr/src/routes/blog.rs
Mylloon a293ef4332
Some checks are pending
ci/woodpecker/push/publish Pipeline is pending
better metadata
2023-04-19 21:16:39 +02:00

108 lines
2.9 KiB
Rust

use actix_web::{get, web, HttpResponse, Responder};
use cached::proc_macro::once;
use glob::glob;
use ramhorns::Content;
use crate::{
config::Config,
template::{get_md_asm, get_md_metadata, read_md_file, File, Infos},
};
#[get("/blog")]
pub async fn index(config: web::Data<Config>) -> impl Responder {
HttpResponse::Ok().body(get_index(config.get_ref().clone()))
}
#[derive(Content)]
struct BlogIndexTemplate {
posts: Option<Vec<Post>>,
}
#[derive(Content, Debug)]
struct Post {
title: String,
url: String,
}
#[once(time = 60)]
pub fn get_index(config: Config) -> String {
let location = "data/blog";
let paths = glob(&format!("{location}/*.md"))
.unwrap()
.map(|f| {
let filename = f
.unwrap()
.file_name()
.unwrap()
.to_string_lossy()
.to_string();
let file_without_ext = filename.split_at(filename.len() - 3).0;
let file_metadata = match std::fs::read_to_string(format!("{location}/{filename}")) {
Ok(text) => {
let md_tree = get_md_asm(&text);
let md_nodes = md_tree.children().unwrap();
get_md_metadata(md_nodes).title
}
_ => None,
};
Post {
url: file_without_ext.to_string(),
title: file_metadata.unwrap_or(file_without_ext.to_string()),
}
})
.collect::<Vec<Post>>();
config.tmpl.render(
"blog/index.html",
BlogIndexTemplate {
posts: if paths.is_empty() { None } else { Some(paths) },
},
Infos {
page_title: Some("Blog".to_string()),
page_desc: Some("Liste des posts d'Anri".to_string()),
page_kw: Some(["blog", "blogging"].join(", ")),
},
)
}
#[derive(Content)]
struct BlogPostTemplate {
post: Option<File>,
}
#[get("/blog/{id}")]
pub async fn page(path: web::Path<(String,)>, config: web::Data<Config>) -> impl Responder {
HttpResponse::Ok().body(get_post(path.into_inner().0, config.get_ref().clone()))
}
pub fn get_post(file: String, config: Config) -> String {
let mut post = None;
let infos = _get_post(&mut post, file);
config
.tmpl
.render("blog/post.html", BlogPostTemplate { post }, infos)
}
fn _get_post(post: &mut Option<File>, filename: String) -> Infos {
let blog_dir = "data/blog";
let ext = ".md";
*post = read_md_file(&format!("{blog_dir}/{filename}{ext}"));
let title = match post {
Some(data) => match &data.metadata.info.title {
Some(text) => text,
None => &filename,
},
None => &filename,
};
Infos {
page_title: Some(format!("Post: {}", title)),
page_desc: Some("Blog d'Anri".to_string()),
page_kw: Some(["blog", "blogging", "write", "writing"].join(", ")),
}
}