use anyhow::{anyhow, Result};
use base64::{engine::general_purpose::STANDARD as B64, Engine as _};
use libhardcopy::{HardCopy, HardCopySectionContent};
use std::collections::HashMap;
const DEFAULT_TEMPLATE: &str = include_str!("../../templates/default.html");
fn substitute(text: &str, vars: &[(&str, &str)]) -> String {
let mut out = String::with_capacity(text.len());
let mut rest = text;
while let Some(open) = rest.find("{{") {
out.push_str(&rest[..open]);
rest = &rest[open + 2..];
if let Some(close) = rest.find("}}") {
let key = rest[..close].trim();
if let Some((_, val)) = vars.iter().find(|(k, _)| *k == key) {
out.push_str(val);
} else {
out.push_str("{{");
out.push_str(&rest[..close]);
out.push_str("}}");
}
rest = &rest[close + 2..];
} else {
out.push_str("{{");
}
}
out.push_str(rest);
out
}
fn has_placeholder(text: &str, name: &str) -> bool {
let mut rest = text;
while let Some(open) = rest.find("{{") {
rest = &rest[open + 2..];
if let Some(close) = rest.find("}}") {
if rest[..close].trim() == name {
return true;
}
rest = &rest[close + 2..];
}
}
false
}
fn extract_all_hardcopy_templates(html: &str) -> (HashMap<String, String>, String) {
let mut templates: HashMap<String, String> = HashMap::new();
let mut remaining = html.to_string();
const PREFIX: &str = "<template id=\"hardcopy-";
const CLOSE: &str = "</template>";
loop {
let Some(start) = remaining.find(PREFIX) else {
break;
};
let id_start = start + "<template id=\"".len();
let Some(id_len) = remaining[id_start..].find('"') else {
break;
};
let id = remaining[id_start..id_start + id_len].to_string();
let open_tag = format!("<template id=\"{}\">", id);
let inner_start = start + open_tag.len();
let Some(rel_close) = remaining[inner_start..].find(CLOSE) else {
break;
};
let inner_end = inner_start + rel_close;
let inner = remaining[inner_start..inner_end].to_string();
remaining = format!(
"{}{}",
&remaining[..start],
&remaining[inner_end + CLOSE.len()..]
);
templates.insert(id, inner);
}
(templates, remaining)
}
pub(crate) fn normalize_section_id(name: &str) -> String {
name.chars()
.map(|c| {
if c.is_ascii_alphanumeric() {
c.to_ascii_lowercase()
} else {
'-'
}
})
.collect::<String>()
.split('-')
.filter(|s| !s.is_empty())
.collect::<Vec<_>>()
.join("-")
}
fn html_escape(s: &str) -> String {
s.replace('&', "&")
.replace('<', "<")
.replace('>', ">")
.replace('"', """)
}
pub fn render(hardcopy: &HardCopy, checksum: &str, template: Option<&str>) -> Result<String> {
render_template(hardcopy, checksum, template.unwrap_or(DEFAULT_TEMPLATE))
}
fn render_template(hardcopy: &HardCopy, checksum: &str, src: &str) -> Result<String> {
let version = env!("CARGO_PKG_VERSION");
let date = chrono::Local::now().format("%Y-%m-%d").to_string();
let (templates, src) = extract_all_hardcopy_templates(src);
if !has_placeholder(&src, "sections") {
return Err(anyhow!(
"Template is missing the {{{{ sections }}}} placeholder. \
See doc/html-templates.md for the template reference."
));
}
let mut sections_html = String::new();
for section in &hardcopy.sections {
let id = format!("hardcopy-section-{}", normalize_section_id(§ion.name));
match §ion.content {
HardCopySectionContent::Words(lines) => {
if let Some(tmpl) = templates.get(&id) {
let content: String = lines
.iter()
.map(|l| html_escape(l))
.collect::<Vec<_>>()
.join("\n");
let lines_html: String = lines
.iter()
.map(|l| format!("<div class=\"word-line\">{}</div>\n", html_escape(l)))
.collect();
sections_html.push_str(&substitute(
tmpl,
&[
("name", &html_escape(§ion.name)),
("content", &content),
("lines", &lines_html),
],
));
}
}
HardCopySectionContent::Bytes(png) => {
let tmpl = templates
.get(&id)
.or_else(|| templates.get("hardcopy-section-qr-code"));
if let Some(tmpl) = tmpl {
let data_url = format!("data:image/png;base64,{}", B64.encode(png));
sections_html.push_str(&substitute(
tmpl,
&[
("name", &html_escape(§ion.name)),
("data_url", &data_url),
("content", &data_url),
],
));
}
}
}
}
let result = substitute(
&src,
&[
("version", &html_escape(version)),
("date", &html_escape(&date)),
("checksum", &html_escape(checksum)),
("sections", §ions_html),
],
);
Ok(result)
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn substitute_replaces_with_spaces() {
assert_eq!(
substitute("hello {{ name }}!", &[("name", "world")]),
"hello world!"
);
}
#[test]
fn substitute_replaces_no_spaces() {
assert_eq!(
substitute("hello {{name}}!", &[("name", "world")]),
"hello world!"
);
}
#[test]
fn substitute_unknown_passthrough() {
assert_eq!(substitute("{{ unknown }}", &[]), "{{ unknown }}");
}
#[test]
fn has_placeholder_finds_spaced() {
assert!(has_placeholder("foo {{ sections }} bar", "sections"));
}
#[test]
fn has_placeholder_finds_tight() {
assert!(has_placeholder("foo {{sections}} bar", "sections"));
}
#[test]
fn has_placeholder_absent() {
assert!(!has_placeholder("foo bar", "sections"));
}
#[test]
fn extract_removes_single_block() {
let html = r#"<head><template id="hardcopy-foo">inner</template></head>"#;
let (t, rest) = extract_all_hardcopy_templates(html);
assert_eq!(t.get("hardcopy-foo").map(String::as_str), Some("inner"));
assert_eq!(rest, "<head></head>");
}
#[test]
fn extract_removes_multiple_blocks() {
let html = concat!(
r#"<template id="hardcopy-words-section">W</template>"#,
r#"<template id="hardcopy-qr-section">Q</template>"#,
);
let (t, rest) = extract_all_hardcopy_templates(html);
assert_eq!(
t.get("hardcopy-words-section").map(String::as_str),
Some("W")
);
assert_eq!(t.get("hardcopy-qr-section").map(String::as_str), Some("Q"));
assert_eq!(rest, "");
}
#[test]
fn extract_non_hardcopy_template_left_alone() {
let html = r#"<template id="other">X</template>"#;
let (t, rest) = extract_all_hardcopy_templates(html);
assert!(t.is_empty());
assert_eq!(rest, html);
}
#[test]
fn extract_missing_returns_empty_map() {
let html = "<head></head>";
let (t, rest) = extract_all_hardcopy_templates(html);
assert!(t.is_empty());
assert_eq!(rest, html);
}
#[test]
fn normalize_section_id_examples() {
assert_eq!(normalize_section_id("BIP-39"), "bip-39");
assert_eq!(normalize_section_id("S/KEY OTP"), "s-key-otp");
assert_eq!(normalize_section_id("PGPfone"), "pgpfone");
assert_eq!(
normalize_section_id("EFF Large Diceware"),
"eff-large-diceware"
);
assert_eq!(normalize_section_id("QR Code 1/2"), "qr-code-1-2");
assert_eq!(normalize_section_id("QR Code"), "qr-code");
}
#[test]
fn render_template_requires_sections_placeholder() {
let src = "";
let hc = libhardcopy::HardCopy::new();
assert!(render_template(&hc, "abc", src).is_err());
}
#[test]
fn render_default_template_succeeds() {
let hc = libhardcopy::HardCopy::new();
let html = render_template(&hc, "abc123", DEFAULT_TEMPLATE).unwrap();
assert!(html.contains("abc123"));
assert!(html.contains("<!DOCTYPE html>"));
}
#[test]
fn section_with_template_renders() {
let src = concat!(
r#"<template id="hardcopy-section-pgpfone">RENDERED:{{ name }}</template>"#,
"{{ sections }}",
);
let mut hc = libhardcopy::HardCopy::new();
hc.push(libhardcopy::HardCopySection {
name: "PGPfone".to_string(),
content: libhardcopy::HardCopySectionContent::Words(vec!["0001: test".to_string()]),
});
let html = render_template(&hc, "abc", src).unwrap();
assert!(html.contains("RENDERED:PGPfone"));
}
#[test]
fn section_without_template_omitted() {
let src = "{{ sections }}";
let mut hc = libhardcopy::HardCopy::new();
hc.push(libhardcopy::HardCopySection {
name: "BIP-39".to_string(),
content: libhardcopy::HardCopySectionContent::Words(vec!["0001: test".to_string()]),
});
let html = render_template(&hc, "abc", src).unwrap();
assert!(!html.contains("BIP-39"));
}
}