Added trivial web ui.
This commit is contained in:
1 parent
f99513a8c8
commit
894f969d0f
11 files changed
+1382
-19
No files matched your search
@@ -0,0 +1,129 @@
|
||||
mod views;
|
||||
|
||||
use actix_utils::future::{ready, Ready};
|
||||
use minijinja;
|
||||
use minijinja_autoreload::AutoReloader;
|
||||
use std::{collections::HashMap, env, fs, io, path::PathBuf};
|
||||
use std::io::{Error, ErrorKind};
|
||||
use std::path::Path;
|
||||
|
||||
use actix_web::{
|
||||
dev::{ServiceResponse},
|
||||
error,
|
||||
http::{header::ContentType, StatusCode},
|
||||
middleware::{ErrorHandlerResponse, ErrorHandlers, Logger},
|
||||
web, App, FromRequest, HttpRequest, HttpResponse, HttpServer, Responder, Result,
|
||||
};
|
||||
use actix_web_lab::respond::Html;
|
||||
|
||||
struct MiniJinjaRenderer {
|
||||
tmpl_env: web::Data<minijinja_autoreload::AutoReloader>,
|
||||
}
|
||||
|
||||
impl MiniJinjaRenderer {
|
||||
fn render(
|
||||
&self,
|
||||
tmpl: &str,
|
||||
ctx: impl Into<minijinja::value::Value>,
|
||||
) -> actix_web::Result<Html> {
|
||||
log::info!("Rendering template {:?}", tmpl);
|
||||
self.tmpl_env
|
||||
.acquire_env()
|
||||
.map_err(|_| error::ErrorInternalServerError("could not acquire template env"))?
|
||||
.get_template(tmpl)
|
||||
.map_err(|e| error::ErrorInternalServerError(format!("{:?}", e)))?
|
||||
.render(ctx.into())
|
||||
.map(Html)
|
||||
.map_err(|err| {
|
||||
log::error!("{err}");
|
||||
error::ErrorInternalServerError("template error")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl FromRequest for MiniJinjaRenderer {
|
||||
type Error = actix_web::Error;
|
||||
type Future = actix_utils::future::Ready<Result<Self, Self::Error>>;
|
||||
|
||||
fn from_request(req: &HttpRequest, _pl: &mut actix_web::dev::Payload) -> Self::Future {
|
||||
let tmpl_env = <web::Data<minijinja_autoreload::AutoReloader>>::extract(req)
|
||||
.into_inner()
|
||||
.unwrap();
|
||||
|
||||
actix_utils::future::ready(Ok(Self { tmpl_env }))
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[tokio::main]
|
||||
pub async fn web_ui_main(port: u16, enable_template_autoreload: bool) -> std::io::Result<()> {
|
||||
// The closure is invoked every time the environment is outdated to recreate it.
|
||||
let tmpl_reloader = AutoReloader::new(move |notifier| {
|
||||
let mut env: minijinja::Environment<'static> = minijinja::Environment::new();
|
||||
|
||||
let tmpl_path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("templates");
|
||||
log::info!("Using template dir {:?}", tmpl_path);
|
||||
|
||||
// if watch_path is never called, no fs watcher is created
|
||||
if enable_template_autoreload {
|
||||
notifier.watch_path(&tmpl_path, true);
|
||||
}
|
||||
env.set_source(minijinja::Source::from_path(tmpl_path));
|
||||
|
||||
Ok(env)
|
||||
});
|
||||
|
||||
let tmpl_reloader = web::Data::new(tmpl_reloader);
|
||||
|
||||
HttpServer::new(move || {
|
||||
App::new()
|
||||
.app_data(tmpl_reloader.clone())
|
||||
.service(views::index)
|
||||
.wrap(ErrorHandlers::new().handler(StatusCode::NOT_FOUND, not_found))
|
||||
.wrap(Logger::default())
|
||||
})
|
||||
.workers(2)
|
||||
.bind(("0.0.0.0", port))?
|
||||
.run()
|
||||
.await
|
||||
}
|
||||
|
||||
/// Error handler for a 404 Page not found error.
|
||||
fn not_found<B>(svc_res: ServiceResponse<B>) -> Result<ErrorHandlerResponse<B>> {
|
||||
let res = get_error_response(&svc_res, "Page not found");
|
||||
|
||||
Ok(ErrorHandlerResponse::Response(ServiceResponse::new(
|
||||
svc_res.into_parts().0,
|
||||
res.map_into_right_body(),
|
||||
)))
|
||||
}
|
||||
|
||||
/// Generic error handler.
|
||||
fn get_error_response<B>(res: &ServiceResponse<B>, error: &str) -> HttpResponse {
|
||||
let req = res.request();
|
||||
|
||||
let tmpl_env = MiniJinjaRenderer::extract(req).into_inner().unwrap();
|
||||
|
||||
// Provide a fallback to a simple plain text response in case an error occurs during the
|
||||
// rendering of the error page.
|
||||
let fallback = |err: &str| {
|
||||
HttpResponse::build(res.status())
|
||||
.content_type(ContentType::plaintext())
|
||||
.body(err.to_string())
|
||||
};
|
||||
|
||||
let ctx = minijinja::context! {
|
||||
error => error,
|
||||
status_code => res.status().as_str(),
|
||||
};
|
||||
|
||||
match tmpl_env.render("error.html", ctx) {
|
||||
Ok(body) => body
|
||||
.customize()
|
||||
.with_status(res.status())
|
||||
.respond_to(req)
|
||||
.map_into_boxed_body(),
|
||||
|
||||
Err(_) => fallback(error),
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user