mod model;
mod render;
mod screenshot;
use std::fmt;
pub use model::{
Dimension, DimensionValue, Group, Missing, Model, Options, Preload, PreloadCaps, SEE_ALL_TEXT, Screen, SeeAll,
Shape, Shot, TEXT_DEFAULTS, Text, Thumb, Values, Variant, build_model, default_dimensions, humanize, parse_shot,
slugify,
};
pub use render::{escape, render_model};
pub use screenshot::{ScreenshotOptions, screenshot, screenshot_markdown};
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Error {
Invalid(String),
Fetch(String),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Invalid(m) | Error::Fetch(m) => f.write_str(m),
}
}
}
impl std::error::Error for Error {}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Gallery {
html: String,
}
impl Gallery {
pub fn new(manifest: &serde_json::Value, options: &Options) -> Result<Self, Error> {
Ok(Gallery { html: render(manifest, options)? })
}
pub fn from_json(manifest: &str, options: &Options) -> Result<Self, Error> {
let value = serde_json::from_str(manifest)
.map_err(|e| Error::Invalid(format!("not a gallery manifest: it isn't JSON ({e})")))?;
Self::new(&value, options)
}
pub fn as_str(&self) -> &str {
&self.html
}
}
impl fmt::Display for Gallery {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.html)
}
}
#[cfg(feature = "askama")]
impl askama::filters::HtmlSafe for Gallery {}
pub fn render(manifest: &serde_json::Value, options: &Options) -> Result<String, Error> {
Ok(render_model(&build_model(manifest, options)?))
}
#[cfg(feature = "fetch")]
pub fn fetch(url: &str, timeout: std::time::Duration, attempts: u32) -> Result<serde_json::Value, Error> {
let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(timeout)).build().into();
let attempts = attempts.max(1);
let mut last = String::new();
for i in 0..attempts {
let result = agent.get(url).call().map_err(|e| match e {
ureq::Error::StatusCode(code) => format!("HTTP {code}"),
e => e.to_string(),
});
match result.and_then(|mut res| {
if res.status() != 200 {
return Err(format!("HTTP {}", res.status().as_u16()));
}
let text = res.body_mut().read_to_string().map_err(|e| e.to_string())?;
serde_json::from_str(&text).map_err(|e| e.to_string())
}) {
Ok(v) => return Ok(v),
Err(e) => last = e,
}
if i + 1 < attempts {
std::thread::sleep(std::time::Duration::from_secs(u64::from(i) + 1));
}
}
Err(Error::Fetch(format!("The screenshots gallery couldn't read {url}: {last}")))
}