templates

This commit is contained in:
Pascal Engélibert 2026-03-03 15:15:18 +01:00
commit 2c1793a128
12 changed files with 496 additions and 26 deletions

View file

@ -1,4 +1,8 @@
use crate::{cache, config::Config, repo::ReadRepoMetadataError};
use askama::Template;
use log::error;
use std::{collections::HashMap, io::ErrorKind, path::PathBuf, sync::{Arc, Mutex}};
use trillium::{Conn, Handler};
use trillium_router::{Router, RouterConnExt};
@ -6,7 +10,13 @@ pub async fn hello_world(conn: Conn) -> Conn {
conn.ok("hello world!")
}
pub fn make_router() -> impl Handler {
pub fn make_router(config: Arc<Config>) -> impl Handler {
let mut hl_registry = giallo::Registry::builtin().unwrap();
hl_registry.link_grammars();
let hl_registry = Arc::new(hl_registry);
let mut metadata_cache = Arc::new(Mutex::new(cache::Cache::<String, HashMap<String, String>>::default()));
(
trillium_caching_headers::CachingHeaders::new(),
//trillium_static_compiled::static_compiled!("./static").with_index_file("index.html"),
@ -29,8 +39,70 @@ pub fn make_router() -> impl Handler {
//let planet = conn.param("planet").unwrap();
conn.ok(crate::templates::Home {}.render().unwrap())
})
.get("/r/:hash", |conn: Conn| async move {
conn.ok(crate::templates::Home {}.render().unwrap())
.get("/r/:hash/*", move |conn: Conn| {
let hl_registry = hl_registry.clone();
let config = config.clone();
let metadata_cache = metadata_cache.clone();
async move {
let Some(repo_hash_str) = conn.param("hash") else {
return conn.with_status(401);
};
let cache_fetch = |key| {
let mut repo_hash = [0; 32];
if base64_turbo::URL_SAFE.decode_into(repo_hash_str, &mut repo_hash) != Ok(32) {
return None;
}
let repo_dir = PathBuf::from(&config.data_dir).join(crate::SUBDIR_REPOS).join(repo_hash_str);
let repo_metadata =
match crate::repo::RepoMetadata::read_from_file(&config, &repo_dir) {
Ok(v) => v,
Err(e) => {
if let ReadRepoMetadataError::CannotOpenFile(e) = &e {
if e.kind() == ErrorKind::NotFound {
return None;
}
}
error!("Reading repo metadata: {e:?}");
return None;
}
};
let mut files = HashMap::new();
for file in repo_metadata.iter_files() {
match file {
Ok(file) => {
files.insert(file.file_path.to_string(), file.hash.to_string());
}
Err(e) => {
error!("Reading repo metadata file index: {e:?}")
}
}
}
Some(files)
};
// TODO replace mutex with better thing (less contention or async mutex)
metadata_cache.lock().unwrap().fetch(repo_hash_str.to_string(), cache_fetch);
let hl_options = giallo::HighlightOptions::new(
"py",
giallo::ThemeVariant::Single("catppuccin-frappe"),
);
let highlighted = hl_registry
.highlight("def foo():\n\tpass", &hl_options)
.unwrap();
let html = giallo::HtmlRenderer::default().render(
&highlighted,
&giallo::RenderOptions {
show_line_numbers: true,
..Default::default()
},
);
conn.ok(crate::templates::Repo {
content: html.clone(),
}
.render()
.unwrap())
}
})
.get("/e/:secret", |conn: Conn| async move {
conn.ok(crate::templates::Home {}.render().unwrap())