Skip to main content

visualci_gallery/
lib.rs

1//! A screenshots page from a VisualCI [public gallery](https://visualci.com/docs/gallery/) manifest, rendered in Rust
2//! as the gallery contract's markup: byte for byte what the `visualci-gallery` JS library renders, so its script
3//! hydrates it (tabs, light and dark, desktop and phone, the full-size view).
4//!
5//! ```no_run
6//! # fn main() -> Result<(), visualci_gallery::Error> {
7//! use visualci_gallery::{Gallery, Options};
8//!
9//! // The manifest a build step wrote (a copy of https://app.visualci.com/g/<org>/<project>.json).
10//! let manifest = std::fs::read_to_string("screenshots.json").expect("the build writes it");
11//! let gallery = Gallery::from_json(&manifest, &Options::default().title(None))?;
12//! let html = gallery.to_string();
13//! # Ok(()) }
14//! ```
15//!
16//! There is no fallback: rendering fails when the manifest has nothing to show or the options are invalid, and
17//! [`fetch`] (feature `fetch`) fails when the manifest can't be read. Read it when the site builds, fail the build if
18//! it can't be, and render from that copy.
19//!
20//! With the `askama` feature, [`Gallery`] is safe HTML to Askama: a template writes `{{ gallery }}`.
21
22mod 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/// Why a gallery can't be shown.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum Error {
36    /// The manifest or the options are invalid, or nothing in the manifest can be shown. The message is the
37    /// contract's, word for word (contract/errors/*.message).
38    Invalid(String),
39    /// The manifest couldn't be read: "The screenshots gallery couldn't read <url>: <why>".
40    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/// A rendered gallery. Displays as its HTML; with the `askama` feature, Askama doesn't escape it.
54#[derive(Debug, Clone, PartialEq, Eq)]
55pub struct Gallery {
56    html: String,
57}
58
59impl Gallery {
60    /// The gallery for a parsed manifest.
61    pub fn new(manifest: &serde_json::Value, options: &Options) -> Result<Self, Error> {
62        Ok(Gallery { html: render(manifest, options)? })
63    }
64
65    /// The gallery for a manifest's JSON text (a file the build wrote, or `include_str!`).
66    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
86/// The gallery's HTML for a parsed manifest.
87pub fn render(manifest: &serde_json::Value, options: &Options) -> Result<String, Error> {
88    Ok(render_model(&build_model(manifest, options)?))
89}
90
91/// The manifest at `url`, parsed: tried `attempts` times, each within `timeout`. Fails, naming the URL, when it can't
92/// be read (a network error, a timeout, a status other than 200, JSON that doesn't parse).
93#[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}