use crate::{config::Config, queries::*}; use handlebars::Handlebars; use serde::Serialize; use serde_json::value::Value as Json; use std::{path::Path, sync::Arc}; const TEMPLATES_DIR: &str = "templates"; static TEMPLATE_FILES: &[(&str, &str)] = &[ ("admin.html", include_str!("../templates/admin.html")), ( "admin_group.html", include_str!("../templates/admin_group.html"), ), ( "admin_login.html", include_str!("../templates/admin_login.html"), ), ("group.html", include_str!("../templates/group.html")), ("index.html", include_str!("../templates/index.html")), ]; pub struct Templates<'reg> { pub hb: Handlebars<'reg>, } pub fn load_templates<'reg>(dir: &Path) -> Templates<'reg> { let dir = dir.join(TEMPLATES_DIR); std::fs::create_dir_all(&dir).expect("Cannot create templates dir"); for &(file, default) in TEMPLATE_FILES { let file_path = dir.join(file); if !file_path.is_file() { std::fs::write(file_path, default) .unwrap_or_else(|_| panic!("Cannot write template file {}", file)); } } let mut hb = Handlebars::new(); for &(file, _) in TEMPLATE_FILES { hb.register_template_string( file, std::str::from_utf8( &std::fs::read(dir.join(file)) .unwrap_or_else(|_| panic!("Cannot read template file`{}`", file)), ) .unwrap_or_else(|_| panic!("Bad encoding in template file `{}`", file)), ) .unwrap(); } Templates { hb } } #[derive(Serialize)] pub struct CommonTemplate<'a> { pub lang: &'a str, pub root_url: &'a str, pub title: &'a str, pub errors: &'a [ErrorTemplate<'a>], pub bg_id: usize, pub bg_about: &'a str, } impl<'a> CommonTemplate<'a> { pub fn new(config: &'a Arc, errors: &'a [ErrorTemplate<'a>]) -> Self { let bg_id = crate::static_files::get_background(); Self { lang: "fr", root_url: &config.as_ref().root_url, title: &config.as_ref().title, errors, bg_id, bg_about: crate::static_files::BACKGROUND_ABOUT[bg_id], } } } #[derive(Serialize)] pub struct IndexTemplate<'a> { #[serde(flatten)] pub common: CommonTemplate<'a>, pub ads: &'a Json, pub groups: &'a Json, pub new_ad_form_refill: Option, } #[derive(Serialize)] pub struct AdminLoginTemplate<'a> { #[serde(flatten)] pub common: CommonTemplate<'a>, } #[derive(Serialize)] pub struct AdminTemplate<'a> { #[serde(flatten)] pub common: CommonTemplate<'a>, pub ads: &'a Json, pub groups: &'a Json, } #[derive(Serialize)] pub struct GroupTemplate<'a> { #[serde(flatten)] pub common: CommonTemplate<'a>, pub ads: &'a Json, pub group: &'a Json, pub groups: &'a Json, pub parent_group_name: &'a str, pub new_ad_form_refill: Option, } #[derive(Serialize)] pub struct AdminGroupTemplate<'a> { #[serde(flatten)] pub common: CommonTemplate<'a>, pub ads: &'a Json, pub group: &'a Json, pub groups: &'a Json, pub parent_group_name: &'a str, pub new_group_form_refill: Option, } #[derive(Serialize)] pub struct ErrorTemplate<'a> { pub text: &'a str, }