1mod model;
23mod render;
24
25use std::fmt;
26
27pub use model::{
28 DEFAULT_TITLE, Group, Model, Options, Preload, PreloadCaps, SEE_ALL_TEXT, Screen, SeeAll, Shot, Thumb, Variant,
29 build_model, humanize, parse_shot, slugify,
30};
31pub use render::{escape, render_model};
32
33#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum Error {
36 Invalid(String),
39 Fetch(String),
41}
42
43impl fmt::Display for Error {
44 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
45 match self {
46 Error::Invalid(m) | Error::Fetch(m) => f.write_str(m),
47 }
48 }
49}
50
51impl std::error::Error for Error {}
52
53#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct Gallery {
56 html: String,
57}
58
59impl Gallery {
60 pub fn new(manifest: &serde_json::Value, options: &Options) -> Result<Self, Error> {
62 Ok(Gallery { html: render(manifest, options)? })
63 }
64
65 pub fn from_json(manifest: &str, options: &Options) -> Result<Self, Error> {
67 let value = serde_json::from_str(manifest)
68 .map_err(|e| Error::Invalid(format!("not a gallery manifest: it isn't JSON ({e})")))?;
69 Self::new(&value, options)
70 }
71
72 pub fn as_str(&self) -> &str {
73 &self.html
74 }
75}
76
77impl fmt::Display for Gallery {
78 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
79 f.write_str(&self.html)
80 }
81}
82
83#[cfg(feature = "askama")]
84impl askama::filters::HtmlSafe for Gallery {}
85
86pub fn render(manifest: &serde_json::Value, options: &Options) -> Result<String, Error> {
88 Ok(render_model(&build_model(manifest, options)?))
89}
90
91#[cfg(feature = "fetch")]
94pub fn fetch(url: &str, timeout: std::time::Duration, attempts: u32) -> Result<serde_json::Value, Error> {
95 let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(timeout)).build().into();
96 let attempts = attempts.max(1);
97 let mut last = String::new();
98 for i in 0..attempts {
99 let result = agent.get(url).call().map_err(|e| match e {
100 ureq::Error::StatusCode(code) => format!("HTTP {code}"),
101 e => e.to_string(),
102 });
103 match result.and_then(|mut res| {
104 if res.status() != 200 {
105 return Err(format!("HTTP {}", res.status().as_u16()));
106 }
107 let text = res.body_mut().read_to_string().map_err(|e| e.to_string())?;
108 serde_json::from_str(&text).map_err(|e| e.to_string())
109 }) {
110 Ok(v) => return Ok(v),
111 Err(e) => last = e,
112 }
113 if i + 1 < attempts {
114 std::thread::sleep(std::time::Duration::from_secs(u64::from(i) + 1));
115 }
116 }
117 Err(Error::Fetch(format!("The screenshots gallery couldn't read {url}: {last}")))
118}