1mod model;
23mod render;
24mod screenshot;
25
26use std::fmt;
27
28pub use model::{
29 Dimension, DimensionValue, Group, Missing, Model, NEW_DAYS, Options, Preload, PreloadCaps, SEARCH_FROM,
30 SEE_ALL_TEXT, Screen, SeeAll, Shape, Shot, TEXT_DEFAULTS, Text, Thumb, Values, Variant, Version, Versions,
31 build_model, default_dimensions, humanize, options_json, parse_shot, slugify,
32};
33pub use render::{escape, render_model};
34pub use screenshot::{ScreenshotOptions, screenshot, screenshot_markdown};
35
36#[derive(Debug, Clone, PartialEq, Eq)]
38pub enum Error {
39 Invalid(String),
42 Fetch(String),
44}
45
46impl fmt::Display for Error {
47 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
48 match self {
49 Error::Invalid(m) | Error::Fetch(m) => f.write_str(m),
50 }
51 }
52}
53
54impl std::error::Error for Error {}
55
56#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct Gallery {
59 html: String,
60}
61
62impl Gallery {
63 pub fn new(manifest: &serde_json::Value, options: &Options) -> Result<Self, Error> {
65 Ok(Gallery { html: render(manifest, options)? })
66 }
67
68 pub fn from_json(manifest: &str, options: &Options) -> Result<Self, Error> {
70 let value = serde_json::from_str(manifest)
71 .map_err(|e| Error::Invalid(format!("not a gallery manifest: it isn't JSON ({e})")))?;
72 Self::new(&value, options)
73 }
74
75 pub fn as_str(&self) -> &str {
76 &self.html
77 }
78}
79
80impl fmt::Display for Gallery {
81 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82 f.write_str(&self.html)
83 }
84}
85
86#[cfg(feature = "askama")]
87impl askama::filters::HtmlSafe for Gallery {}
88
89pub fn render(manifest: &serde_json::Value, options: &Options) -> Result<String, Error> {
91 Ok(render_model(&build_model(manifest, options)?))
92}
93
94pub fn manifest_url(url: &str, reference: Option<&str>) -> Result<String, Error> {
99 let Some(reference) = reference else { return Ok(url.to_string()) };
100 let mut key = String::new();
101 let mut dash = false;
102 for c in reference.chars() {
103 let c = c.to_ascii_lowercase();
104 if c.is_ascii_lowercase() || c.is_ascii_digit() {
105 if dash && !key.is_empty() {
106 key.push('-');
107 }
108 dash = false;
109 key.push(c);
110 } else {
111 dash = true;
112 }
113 }
114 match url.strip_suffix(".json") {
115 Some(base) if !key.is_empty() && key != "latest" => Ok(format!("{base}@{key}.json")),
116 _ => Err(Error::Invalid("gallery option ref is invalid".into())),
117 }
118}
119
120#[cfg(feature = "fetch")]
123pub fn fetch(url: &str, timeout: std::time::Duration, attempts: u32) -> Result<serde_json::Value, Error> {
124 let agent: ureq::Agent = ureq::Agent::config_builder().timeout_global(Some(timeout)).build().into();
125 let attempts = attempts.max(1);
126 let mut last = String::new();
127 for i in 0..attempts {
128 let result = agent.get(url).call().map_err(|e| match e {
129 ureq::Error::StatusCode(code) => format!("HTTP {code}"),
130 e => e.to_string(),
131 });
132 match result.and_then(|mut res| {
133 if res.status() != 200 {
134 return Err(format!("HTTP {}", res.status().as_u16()));
135 }
136 let text = res.body_mut().read_to_string().map_err(|e| e.to_string())?;
137 serde_json::from_str(&text).map_err(|e| e.to_string())
138 }) {
139 Ok(v) => return Ok(v),
140 Err(e) => last = e,
141 }
142 if i + 1 < attempts {
143 std::thread::sleep(std::time::Duration::from_secs(u64::from(i) + 1));
144 }
145 }
146 Err(Error::Fetch(format!("The screenshots gallery couldn't read {url}: {last}")))
147}