|
| 1 | +include!(concat!(env!("OUT_DIR"), "/generated.rs")); |
| 2 | + |
| 3 | +use anyhow::{anyhow, bail, Context}; |
| 4 | +use base64::prelude::BASE64_STANDARD; |
| 5 | +use base64::Engine; |
| 6 | +use serde::Serialize; |
| 7 | +use static_files::resource::new_resource; |
| 8 | +use static_files::Resource; |
| 9 | +use std::collections::HashMap; |
| 10 | +use std::str::from_utf8; |
| 11 | +use std::sync::OnceLock; |
| 12 | + |
| 13 | +#[derive(Serialize, Clone, Default)] |
| 14 | +pub struct UI { |
| 15 | + #[serde(rename(serialize = "VERSION"))] |
| 16 | + pub version: String, |
| 17 | +} |
| 18 | + |
| 19 | +pub fn openubl_ui_resources() -> HashMap<&'static str, Resource> { |
| 20 | + let mut resources = generate(); |
| 21 | + if let Some(index) = resources.get("index.html.ejs") { |
| 22 | + resources.insert( |
| 23 | + "index.html", |
| 24 | + new_resource(index.data, index.modified, "text/html"), |
| 25 | + ); |
| 26 | + } |
| 27 | + |
| 28 | + resources |
| 29 | +} |
| 30 | + |
| 31 | +pub fn generate_index_html(ui: &UI, template_file: String) -> tera::Result<String> { |
| 32 | + let template = template_file.replace("<%=", "{{").replace("%>", "}}"); |
| 33 | + |
| 34 | + let env_json = serde_json::to_string(&ui)?; |
| 35 | + let env_base64 = BASE64_STANDARD.encode(env_json.as_bytes()); |
| 36 | + |
| 37 | + let mut context = tera::Context::new(); |
| 38 | + context.insert("_env", &env_base64); |
| 39 | + |
| 40 | + tera::Tera::one_off(&template, &context, true) |
| 41 | +} |
| 42 | + |
| 43 | +pub fn openubl_ui(ui: &UI) -> anyhow::Result<HashMap<&'static str, Resource>> { |
| 44 | + let mut resources = generate(); |
| 45 | + |
| 46 | + let template_file = resources.get("index.html.ejs"); |
| 47 | + |
| 48 | + let result = INDEX_HTML.get_or_init(|| { |
| 49 | + if let Some(template_file) = template_file { |
| 50 | + let modified = template_file.modified; |
| 51 | + let template_file = |
| 52 | + from_utf8(template_file.data).context("cannot interpret template as UTF-8")?; |
| 53 | + Ok(( |
| 54 | + generate_index_html(ui, template_file.to_string()) |
| 55 | + .expect("cannot generate index.html"), |
| 56 | + modified, |
| 57 | + )) |
| 58 | + } else { |
| 59 | + bail!("Missing template"); |
| 60 | + } |
| 61 | + }); |
| 62 | + |
| 63 | + let (index_html, modified) = match result { |
| 64 | + Ok((index_html, modified)) => (index_html.as_bytes(), *modified), |
| 65 | + Err(err) => return Err(anyhow!(err)), |
| 66 | + }; |
| 67 | + |
| 68 | + resources.insert("", new_resource(index_html, modified, "text/html")); |
| 69 | + |
| 70 | + Ok(resources) |
| 71 | +} |
| 72 | + |
| 73 | +static INDEX_HTML: OnceLock<anyhow::Result<(String, u64)>> = OnceLock::new(); |
0 commit comments