mylloon.fr/src/routes/blog.rs

378 lines
11 KiB
Rust
Raw Normal View History

2023-04-26 14:19:02 +02:00
use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
2023-04-26 16:51:19 +02:00
use ::rss::{
extension::atom::{AtomExtension, Link},
Category, Channel, Guid, Image, Item,
};
2023-04-26 12:50:08 +02:00
use actix_web::{dev::ConnectionInfo, get, web, HttpRequest, HttpResponse, Responder};
2023-04-14 11:30:58 +02:00
use cached::proc_macro::once;
2023-04-26 13:49:05 +02:00
use chrono::{DateTime, Datelike, Local, NaiveDateTime, Utc};
use chrono_tz::Europe;
2023-04-21 16:48:31 +02:00
use comrak::{parse_document, Arena};
2023-04-14 11:30:58 +02:00
use ramhorns::Content;
use crate::{
config::Config,
misc::{
date::Date,
2023-04-21 16:48:31 +02:00
markdown::{get_metadata, get_options, read_file, File, FileMetadata},
utils::get_url,
},
template::{Infos, NavBar},
};
2023-04-14 11:30:58 +02:00
2023-04-26 16:57:37 +02:00
const MIME_TYPE_RSS: &str = "application/rss+xml";
2023-04-26 16:51:19 +02:00
2023-04-14 11:30:58 +02:00
#[get("/blog")]
async fn index(req: HttpRequest, config: web::Data<Config>) -> impl Responder {
HttpResponse::Ok().body(build_index(
config.get_ref().to_owned(),
get_url(req.connection_info()),
))
2023-04-14 11:30:58 +02:00
}
2023-05-02 13:34:43 +02:00
#[derive(Content, Debug)]
2023-04-19 18:55:03 +02:00
struct BlogIndexTemplate {
navbar: NavBar,
2023-04-24 18:01:38 +02:00
posts: Vec<Post>,
no_posts: bool,
2023-04-19 20:27:40 +02:00
}
2023-04-24 19:15:28 +02:00
#[once(time = 120)]
fn build_index(config: Config, url: String) -> String {
let mut posts = get_posts("data/blog");
// Sort from newest to oldest
posts.sort_by_cached_key(|p| (p.date.year, p.date.month, p.date.day));
posts.reverse();
config.tmpl.render(
"blog/index.html",
BlogIndexTemplate {
navbar: NavBar {
blog: true,
..NavBar::default()
},
2023-04-24 18:01:38 +02:00
no_posts: posts.is_empty(),
posts,
},
Infos {
page_title: Some("Blog".into()),
2023-04-28 12:49:48 +02:00
page_desc: Some(format!(
"Liste des posts d'{}",
config.fc.name.unwrap_or_default()
)),
page_kw: Some(["blog", "blogging"].join(", ")),
url,
},
)
}
2023-05-02 13:34:43 +02:00
#[derive(Content, Debug)]
2023-04-19 20:27:40 +02:00
struct Post {
title: String,
2023-04-20 14:41:36 +02:00
date: Date,
2023-04-19 20:27:40 +02:00
url: String,
2023-04-24 18:41:40 +02:00
desc: Option<String>,
2023-04-26 17:17:48 +02:00
content: Option<String>,
2023-05-02 16:02:50 +02:00
tags: Vec<String>,
2023-04-19 18:55:03 +02:00
}
2023-04-14 11:30:58 +02:00
2023-04-26 17:17:48 +02:00
impl Post {
// Fetch the file content
fn fetch_content(&mut self) {
2023-04-26 14:19:02 +02:00
let blog_dir = "data/blog";
let ext = ".md";
if let Some(file) = read_file(&format!("{blog_dir}/{}{ext}", self.url)) {
2023-04-26 17:17:48 +02:00
self.content = Some(file.content);
}
}
}
impl Hash for Post {
fn hash<H: Hasher>(&self, state: &mut H) {
if let Some(content) = &self.content {
content.hash(state)
2023-04-26 14:19:02 +02:00
}
}
}
fn get_posts(location: &str) -> Vec<Post> {
let entries = match std::fs::read_dir(location) {
Ok(res) => res
.flatten()
2023-05-02 13:07:04 +02:00
.filter(|f| match f.path().extension() {
Some(ext) => ext == "md",
None => false,
})
.collect::<Vec<std::fs::DirEntry>>(),
Err(_) => vec![],
};
2023-04-20 11:57:06 +02:00
entries
2023-04-20 11:57:06 +02:00
.iter()
2023-05-02 13:05:42 +02:00
.filter_map(|f| {
2023-04-20 11:57:06 +02:00
let _filename = f.file_name();
let filename = _filename.to_string_lossy();
2023-04-19 20:54:05 +02:00
let file_without_ext = filename.split_at(filename.len() - 3).0;
2023-04-19 21:16:39 +02:00
let file_metadata = match std::fs::read_to_string(format!("{location}/{filename}")) {
2023-04-21 16:48:31 +02:00
Ok(text) => {
let arena = Arena::new();
let options = get_options();
let root = parse_document(&arena, &text, &options);
let mut metadata = get_metadata(root);
2023-04-20 11:57:06 +02:00
2023-05-02 14:37:32 +02:00
// Always have a title
2023-04-20 11:57:06 +02:00
metadata.title = match metadata.title {
2023-04-21 16:48:31 +02:00
Some(title) => Some(title),
None => Some(file_without_ext.into()),
2023-04-20 11:57:06 +02:00
};
2023-04-21 16:48:31 +02:00
metadata
2023-04-19 21:16:39 +02:00
}
2023-04-20 11:57:06 +02:00
Err(_) => FileMetadata {
title: Some(file_without_ext.into()),
2023-04-24 18:41:40 +02:00
..FileMetadata::default()
2023-04-20 11:57:06 +02:00
},
2023-04-19 21:16:39 +02:00
};
2023-05-02 13:05:42 +02:00
if let Some(true) = file_metadata.publish {
Some(Post {
url: file_without_ext.into(),
title: file_metadata.title.unwrap(),
date: file_metadata.date.unwrap_or({
let m = f.metadata().unwrap();
let date = std::convert::Into::<DateTime<Utc>>::into(
m.modified().unwrap_or(m.created().unwrap()),
)
.date_naive();
Date {
day: date.day(),
month: date.month(),
year: date.year(),
}
}),
desc: file_metadata.description,
content: None,
2023-05-02 16:02:50 +02:00
tags: file_metadata
.tags
.unwrap_or_default()
.iter()
.map(|t| t.name.to_owned())
.collect(),
2023-05-02 13:05:42 +02:00
})
} else {
None
2023-04-19 20:54:05 +02:00
}
})
.collect::<Vec<Post>>()
}
2023-05-02 13:34:43 +02:00
#[derive(Content, Debug)]
struct BlogPostTemplate {
navbar: NavBar,
post: Option<File>,
2023-05-02 23:10:36 +02:00
toc: String,
2023-04-14 11:30:58 +02:00
}
2023-04-26 10:41:49 +02:00
#[get("/blog/p/{id}")]
async fn page(
req: HttpRequest,
path: web::Path<(String,)>,
config: web::Data<Config>,
) -> impl Responder {
HttpResponse::Ok().body(build_post(
path.into_inner().0,
config.get_ref().to_owned(),
get_url(req.connection_info()),
))
2023-04-14 11:30:58 +02:00
}
fn build_post(file: String, config: Config, url: String) -> String {
2023-04-19 20:08:15 +02:00
let mut post = None;
2023-05-02 23:10:36 +02:00
let (infos, toc) = get_post(&mut post, file, config.fc.name.unwrap_or_default(), url);
2023-04-19 18:55:03 +02:00
config.tmpl.render(
"blog/post.html",
BlogPostTemplate {
navbar: NavBar {
blog: true,
..NavBar::default()
},
post,
toc,
},
infos,
)
}
2023-05-02 23:10:36 +02:00
fn get_post(
post: &mut Option<File>,
filename: String,
name: String,
url: String,
) -> (Infos, String) {
let blog_dir = "data/blog";
let ext = ".md";
*post = read_file(&format!("{blog_dir}/{filename}{ext}"));
2023-05-02 23:10:36 +02:00
let default = (&filename, Vec::new(), String::new());
let (title, tags, toc) = match post {
2023-05-02 14:37:32 +02:00
Some(data) => (
match &data.metadata.info.title {
Some(text) => text,
2023-05-02 23:10:36 +02:00
None => default.0,
2023-05-02 14:37:32 +02:00
},
match &data.metadata.info.tags {
Some(tags) => tags.clone(),
2023-05-02 23:10:36 +02:00
None => default.1,
},
match &data.metadata.info.toc {
// TODO: Generate TOC
Some(true) => String::new(),
_ => default.2,
2023-05-02 14:37:32 +02:00
},
),
2023-05-02 23:10:36 +02:00
None => default,
};
2023-05-02 23:10:36 +02:00
(
Infos {
page_title: Some(format!("Post: {}", title)),
page_desc: Some(format!("Blog d'{name}")),
page_kw: Some(
["blog", "blogging", "write", "writing"]
2023-05-02 23:10:36 +02:00
.iter()
.map(|&tag| tag.to_owned())
.chain(tags.into_iter().map(|t| t.name))
.collect::<Vec<String>>()
.join(", "),
),
url,
},
toc,
)
2023-04-14 11:30:58 +02:00
}
2023-04-26 12:50:08 +02:00
#[get("/blog/rss")]
async fn rss(req: HttpRequest, config: web::Data<Config>) -> impl Responder {
2023-04-26 15:16:57 +02:00
HttpResponse::Ok()
2023-04-26 16:57:37 +02:00
.append_header(("content-type", MIME_TYPE_RSS))
2023-04-26 15:16:57 +02:00
.body(build_rss(
config.get_ref().to_owned(),
req.connection_info().to_owned(),
))
2023-04-26 12:50:08 +02:00
}
2023-04-26 16:22:54 +02:00
#[once(time = 10800)] // 3h
2023-04-26 12:50:08 +02:00
fn build_rss(config: Config, info: ConnectionInfo) -> String {
let mut posts = get_posts("data/blog");
// Sort from newest to oldest
posts.sort_by_cached_key(|p| (p.date.year, p.date.month, p.date.day));
posts.reverse();
// Only the 20 newest
let max = 20;
if posts.len() > max {
posts.drain(max..);
}
let link_to_site = format!("{}://{}", info.scheme(), info.host());
2023-04-28 12:49:48 +02:00
let author = if let (Some(mail), Some(name)) = (config.fc.mail, config.fc.fullname.to_owned()) {
2023-04-26 16:21:57 +02:00
Some(format!("{mail} ({name})"))
} else {
None
};
2023-04-28 12:49:48 +02:00
let title = format!("Blog d'{}", config.fc.name.unwrap_or_default());
2023-04-26 16:51:19 +02:00
let lang = "fr";
2023-04-26 12:50:08 +02:00
let channel = Channel {
2023-04-26 16:32:57 +02:00
title: title.to_owned(),
2023-04-26 12:50:08 +02:00
link: link_to_site.to_owned(),
2023-04-26 13:49:05 +02:00
description: "Un fil qui parle d'informatique notamment".into(),
2023-04-26 16:51:19 +02:00
language: Some(lang.into()),
2023-04-26 16:21:57 +02:00
managing_editor: author.to_owned(),
webmaster: author,
2023-04-26 13:49:05 +02:00
pub_date: Some(Local::now().to_rfc2822()),
2023-04-26 12:50:08 +02:00
categories: ["blog", "blogging", "write", "writing"]
.iter()
.map(|&c| Category {
name: c.into(),
..Category::default()
})
.collect(),
generator: Some("ewp with rss crate".into()),
docs: Some("https://www.rssboard.org/rss-specification".into()),
image: Some(Image {
2023-04-26 13:49:05 +02:00
url: format!("{}/icons/favicon-32x32.png", link_to_site),
2023-04-26 16:32:57 +02:00
title: title.to_owned(),
2023-04-26 13:49:05 +02:00
link: link_to_site.to_owned(),
2023-04-26 12:50:08 +02:00
..Image::default()
}),
2023-04-26 13:49:05 +02:00
items: posts
2023-04-26 17:17:48 +02:00
.iter_mut()
.map(|p| {
// Get post data
p.fetch_content();
// Build item
Item {
title: Some(p.title.to_owned()),
link: Some(format!("{}/blog/p/{}", link_to_site, p.url)),
description: p.content.to_owned(),
2023-05-02 16:02:50 +02:00
categories: p
.tags
.iter()
.map(|c| Category {
name: c.to_owned(),
..Category::default()
})
.collect(),
2023-04-26 17:17:48 +02:00
guid: Some(Guid {
value: format!("urn:hash:{}", {
let mut hasher = DefaultHasher::new();
p.hash(&mut hasher);
hasher.finish()
}),
permalink: false,
2023-04-26 14:19:02 +02:00
}),
2023-04-26 17:17:48 +02:00
pub_date: Some(
NaiveDateTime::parse_from_str(
&format!("{}-{}-{} 13:12:00", p.date.day, p.date.month, p.date.year),
"%d-%m-%Y %H:%M:%S",
)
.unwrap()
.and_local_timezone(Europe::Paris)
.unwrap()
.to_rfc2822(),
),
..Item::default()
}
2023-04-26 13:49:05 +02:00
})
.collect(),
2023-04-26 16:51:19 +02:00
atom_ext: Some(AtomExtension {
links: vec![Link {
href: format!("{}/blog/rss", link_to_site),
rel: "self".into(),
hreflang: Some(lang.into()),
2023-04-26 16:59:00 +02:00
mime_type: Some(MIME_TYPE_RSS.into()),
2023-04-28 12:49:48 +02:00
title: Some(title),
2023-04-26 16:51:19 +02:00
length: None,
}],
}),
2023-04-26 12:50:08 +02:00
..Channel::default()
};
std::str::from_utf8(&channel.write_to(Vec::new()).unwrap())
.unwrap()
.into()
}