use std::borrow::Cow;
use std::path::Path;
use rocket::fairing::Fairing;
use rocket::figment::{error::Error, value::Value};
use rocket::http::{ContentType, Status};
use rocket::request::Request;
use rocket::response::{self, Responder};
use rocket::serde::Serialize;
use rocket::{Ignite, Orbit, Rocket, Sentinel};
use tera::Tera;
use crate::context::{Context, ContextManager};
use crate::engine;
use crate::fairing::TemplateFairing;
pub(crate) const DEFAULT_TEMPLATE_DIR: &str = "templates";
pub(crate) fn log_missing_fairing() {
error!("Uninitialized template context: missing fairing.");
info_!("To use templates, you must attach `Template::fairing()`.");
info_!("See the `Template` documentation for more information.");
}
#[derive(Debug)]
pub struct Template {
name: Cow<'static, str>,
value: Result<Value, Error>,
}
impl Template {
pub fn fairing() -> impl Fairing {
Template::custom(|_| {})
}
pub fn custom<F>(f: F) -> impl Fairing
where
F: Fn(&mut Tera) + Send + Sync + 'static,
{
Self::try_custom(move |tera| {
f(tera);
Ok(())
})
}
pub fn try_custom<F>(f: F) -> impl Fairing
where
F: Fn(&mut Tera) -> Result<(), Box<dyn std::error::Error>> + Send + Sync + 'static,
{
TemplateFairing {
callback: Box::new(f),
}
}
#[inline]
pub fn render<S, C>(name: S, context: C) -> Template
where
S: Into<Cow<'static, str>>,
C: Serialize,
{
Template {
name: name.into(),
value: Value::serialize(context),
}
}
#[inline]
pub fn show<S, C>(rocket: &Rocket<Orbit>, name: S, context: C) -> Option<String>
where
S: Into<Cow<'static, str>>,
C: Serialize,
{
let ctxt = rocket
.state::<ContextManager>()
.map(ContextManager::context)
.or_else(|| {
log_missing_fairing();
None
})?;
Template::render(name, context)
.finalize(&ctxt)
.ok()
.map(|v| v.1)
}
#[inline(always)]
pub(crate) fn finalize(self, ctxt: &Context) -> Result<(ContentType, String), Status> {
let template = &*self.name;
if !ctxt.tera.contains_template(template) {
let ts: Vec<_> = ctxt.tera.get_template_names().collect();
error_!("Template '{}' does not exist.", template);
info_!("Known templates: {}.", ts.join(", "));
info_!("Searched in {:?}.", ctxt.root);
return Err(Status::InternalServerError);
}
let value = self.value.map_err(|e| {
error_!("Template context failed to serialize: {}.", e);
Status::InternalServerError
})?;
let string = engine::render(&ctxt.tera, template, value).ok_or_else(|| {
error_!("Template '{}' failed to render.", template);
Status::InternalServerError
})?;
let data_type = Path::new(template)
.extension()
.and_then(|ext| ext.to_str())
.and_then(ContentType::from_extension)
.unwrap_or(ContentType::Text);
Ok((data_type, string))
}
}
impl<'r> Responder<'r, 'static> for Template {
fn respond_to(self, req: &'r Request<'_>) -> response::Result<'static> {
let ctxt = req.rocket().state::<ContextManager>().ok_or_else(|| {
log_missing_fairing();
Status::InternalServerError
})?;
self.finalize(&ctxt.context())?.respond_to(req)
}
}
impl Sentinel for Template {
fn abort(rocket: &Rocket<Ignite>) -> bool {
if rocket.state::<ContextManager>().is_none() {
log_missing_fairing();
return true;
}
false
}
}
#[macro_export]
macro_rules! context {
($($key:ident $(: $value:expr)?),*$(,)?) => {{
use $crate::serde::ser::{Serialize, Serializer, SerializeMap};
use ::std::fmt::{Debug, Formatter};
use ::std::result::Result;
#[allow(non_camel_case_types)]
struct ContextMacroCtxObject<$($key: Serialize),*> {
$($key: $key),*
}
#[allow(non_camel_case_types)]
impl<$($key: Serialize),*> Serialize for ContextMacroCtxObject<$($key),*> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer,
{
let mut map = serializer.serialize_map(None)?;
$(map.serialize_entry(stringify!($key), &self.$key)?;)*
map.end()
}
}
#[allow(non_camel_case_types)]
impl<$($key: Debug + Serialize),*> Debug for ContextMacroCtxObject<$($key),*> {
fn fmt(&self, f: &mut Formatter<'_>) -> ::std::fmt::Result {
f.debug_struct("context!")
$(.field(stringify!($key), &self.$key))*
.finish()
}
}
ContextMacroCtxObject {
$($key $(: $value)?),*
}
}};
}