mod html;
mod pdf;
mod txt;
use crate::*;
#[cfg(feature = "out-bip39")]
use libhardcopy::plugins::bip39::Bip39Plugin;
#[cfg(feature = "out-diceware")]
use libhardcopy::plugins::diceware::DicewarePlugin;
use libhardcopy::plugins::pgpfone::PGPfonePlugin;
use libhardcopy::plugins::skeyotp::SKeyOtpPlugin;
use libhardcopy::plugins::HardCopyGenerator;
use libhardcopy::SoftCopyInput;
use sha2::{Digest, Sha256};
use std::fs;
enum RenderedOutput {
Text(String),
Pdf(Vec<u8>),
Html(String),
}
pub struct HardCopyOutput {
content: RenderedOutput,
path: String,
}
impl HardCopyOutput {
pub fn build(input: HardCopyInput, config: &HardCopyConfig) -> Result<HardCopyOutput> {
let raw = input.as_bytes();
let checksum = hex::encode(Sha256::digest(raw));
let softinput = SoftCopyInput::from_bytes(raw.to_vec());
let mut hardcopy = libhardcopy::HardCopy::new();
if config.pgpfone_enabled {
let pgp = PGPfonePlugin
.generate_hard_copy(&softinput)
.map_err(|_| anyhow::anyhow!("PGPfone encoding failed"))?;
for section in pgp.sections {
hardcopy.push(section);
}
}
if config.skeyotp_enabled {
let skey = SKeyOtpPlugin
.generate_hard_copy(&softinput)
.map_err(|_| anyhow::anyhow!("S/KEY OTP encoding failed"))?;
for section in skey.sections {
hardcopy.push(section);
}
}
#[cfg(feature = "out-bip39")]
if config.bip39_enabled {
let bip39 = Bip39Plugin
.generate_hard_copy(&softinput)
.map_err(|_| anyhow::anyhow!("BIP-39 encoding failed"))?;
for section in bip39.sections {
hardcopy.push(section);
}
}
#[cfg(feature = "out-diceware")]
if config.diceware_enabled {
let diceware = DicewarePlugin
.generate_hard_copy(&softinput)
.map_err(|_| anyhow::anyhow!("Diceware encoding failed"))?;
for section in diceware.sections {
hardcopy.push(section);
}
}
if config.qrcode_enabled {
for section in libhardcopy::plugins::qrcode::bytes_to_qr_sections(raw) {
hardcopy.push(section);
}
}
let font_dir = config.font_dir.as_deref();
let font_name = config.font_name.as_deref();
let content = if config.out_file.ends_with(".pdf") {
RenderedOutput::Pdf(pdf::render(&hardcopy, &checksum, font_dir, font_name)?)
} else if config.out_file.ends_with(".html") || config.out_file.ends_with(".htm") {
let tmpl_src = config
.html_template
.as_deref()
.map(|path| {
fs::read_to_string(path)
.map_err(|e| anyhow::anyhow!("Failed to read template '{}': {}", path, e))
})
.transpose()?;
RenderedOutput::Html(html::render(&hardcopy, &checksum, tmpl_src.as_deref())?)
} else {
RenderedOutput::Text(txt::render(&hardcopy, &checksum))
};
Ok(HardCopyOutput {
content,
path: config.out_file.clone(),
})
}
pub fn save(self) -> Result<()> {
match self.content {
RenderedOutput::Text(s) => fs::write(&self.path, s)?,
RenderedOutput::Html(s) => fs::write(&self.path, s)?,
RenderedOutput::Pdf(b) => fs::write(&self.path, b)?,
}
Ok(())
}
}