use std::collections::{HashMap, HashSet};
use std::sync::LazyLock;
use regex::Regex;
use serde::{Serialize, Serializer};
use serde_json::{Map, Value};
use crate::Error;
pub const DEFAULT_TITLE: &str = "Screenshots";
pub const SEE_ALL_TEXT: &str = "See all screenshots";
const SIZES: [&str; 2] = ["desktop", "phone"];
const THEMES: [&str; 2] = ["light", "dark"];
static EXTENSION: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"\.(?:[pP][nN][gG]|[jJ][pP][eE]?[gG]|[wW][eE][bB][pP])\z").unwrap());
static WIDTH_THEME: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\A([0-9]+)-(light|dark)(-2x)?\z").unwrap());
static SCREEN_THEME: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"\A((?s:.)+?)-(light|dark)(?:-([0-9]+))?(-2x)?\z").unwrap());
static ABSOLUTE: LazyLock<Regex> =
LazyLock::new(|| Regex::new(r"\A[hH][tT][tT][pP][sS]?://[^\x00-\x20\x7f]+\z").unwrap());
static CONTROL: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[\x00-\x20\x7f]").unwrap());
static SCHEME: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\A[A-Za-z][A-Za-z0-9+.-]*:").unwrap());
static ID: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\A[A-Za-z][A-Za-z0-9_-]*\z").unwrap());
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Variant {
pub size: String,
pub theme: String,
pub url: String,
pub url2x: Option<String>,
pub width: u64,
pub height: u64,
pub bytes: Option<u64>,
pub bytes2x: Option<u64>,
pub thumb: Option<Thumb>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Thumb {
pub url: String,
pub width: u64,
pub height: u64,
pub bytes: Option<u64>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
pub struct PreloadCaps {
pub fold: u64,
pub count: u64,
pub bytes: u64,
pub parallel: u64,
}
impl Default for PreloadCaps {
fn default() -> Self {
PreloadCaps { fold: 250, count: 500, bytes: 50_000_000, parallel: 4 }
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Preload {
Off,
Caps(PreloadCaps),
}
impl Serialize for Preload {
fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
match self {
Preload::Off => serializer.serialize_str("off"),
Preload::Caps(caps) => caps.serialize(serializer),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Screen {
pub key: String,
pub title: String,
pub caption: Option<String>,
pub variants: Vec<Variant>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct Group {
pub name: String,
pub title: String,
pub slug: String,
pub fit: String,
pub sizes: Vec<String>,
pub screens: Vec<Screen>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SeeAll {
pub href: String,
pub text: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Model {
pub layout: String,
pub theme_switch: bool,
pub see_all: Option<SeeAll>,
pub title: Option<String>,
pub label: String,
pub heading_level: u8,
pub id: String,
pub credit: bool,
pub preload: Option<Preload>,
pub groups: Vec<Group>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Shot {
pub key: String,
pub theme: Option<String>,
pub size: String,
pub x2: bool,
pub css_width: Option<u64>,
}
pub fn parse_shot(name: &str, width: u64, height: u64, size: Option<&str>) -> Shot {
let stripped = EXTENSION.replace(name, "");
let mut parts: Vec<&str> = stripped.split('/').collect();
let last = parts.pop().unwrap_or("");
let folder = parts.join("/");
let sized = |w: Option<&str>| -> String {
match w {
Some(w) => if w.parse::<u64>().is_ok_and(|n| n < 768) { "phone" } else { "desktop" }.to_string(),
None => {
size.map(str::to_string).unwrap_or_else(|| if height > width { "phone" } else { "desktop" }.to_string())
}
}
};
let css = |w: Option<&str>| w.and_then(|w| w.parse::<u64>().ok());
if !folder.is_empty() {
if let Some(m) = WIDTH_THEME.captures(last) {
let w = m.get(1).map(|x| x.as_str());
return Shot {
key: folder,
theme: Some(m[2].to_string()),
size: sized(w),
x2: m.get(3).is_some(),
css_width: css(w),
};
}
}
if let Some(m) = SCREEN_THEME.captures(last) {
let key = if folder.is_empty() { m[1].to_string() } else { format!("{folder}/{}", &m[1]) };
let w = m.get(3).map(|x| x.as_str());
return Shot { key, theme: Some(m[2].to_string()), size: sized(w), x2: m.get(4).is_some(), css_width: css(w) };
}
let key = if folder.is_empty() { last.to_string() } else { format!("{folder}/{last}") };
Shot { key, theme: None, size: sized(None), x2: false, css_width: None }
}
pub fn humanize(segments: &[&str]) -> String {
static RUNS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[-_]+").unwrap());
let text =
segments.iter().map(|s| RUNS.replace_all(s, " ").trim_matches(' ').to_string()).collect::<Vec<_>>().join(", ");
let mut chars = text.chars();
match chars.next() {
Some(first) => first.to_uppercase().chain(chars).collect(),
None => text,
}
}
pub fn slugify(name: &str) -> String {
let mut out = String::new();
let mut dash = false;
for c in name.chars() {
let c = c.to_ascii_lowercase();
if c.is_ascii_lowercase() || c.is_ascii_digit() {
if dash && !out.is_empty() {
out.push('-');
}
dash = false;
out.push(c);
} else {
dash = true;
}
}
if out.is_empty() { "group".to_string() } else { out }
}
fn common_folder(keys: &[&str]) -> usize {
let folders: Vec<Vec<&str>> = keys
.iter()
.map(|k| {
let mut p: Vec<&str> = k.split('/').collect();
p.pop();
p
})
.collect();
let Some(first) = folders.first() else { return 0 };
let mut common = first.len();
for f in &folders[1..] {
let mut i = 0;
while i < common && i < f.len() && first[i] == f[i] {
i += 1;
}
common = i;
}
common
}
fn rank(order: &Option<Vec<String>>, key: &str) -> usize {
let list = order.as_deref().unwrap_or(&[]);
list.iter().position(|k| k == key).unwrap_or(list.len())
}
fn safe_href(value: &str) -> bool {
ABSOLUTE.is_match(value) || (!value.is_empty() && !CONTROL.is_match(value) && !SCHEME.is_match(value))
}
fn fail<T>(message: impl Into<String>) -> Result<T, Error> {
Err(Error::Invalid(message.into()))
}
fn integral(v: &Value) -> Option<f64> {
let n = v.as_f64()?;
(n.is_finite() && n.fract() == 0.0).then_some(n)
}
pub const MAX_SIZE: u64 = 1_000_000;
fn size_of(v: Option<&Value>) -> Option<u64> {
let n = integral(v?)?;
(n > 0.0 && n <= MAX_SIZE as f64).then_some(n as u64)
}
const MAX_CAP: u64 = 1_000_000_000_000;
fn whole_in(v: &Value, min: u64, max: u64) -> Option<u64> {
let n = integral(v)?;
(n >= min as f64 && n <= max as f64).then_some(n as u64)
}
fn bytes_of(v: Option<&Value>) -> Result<Option<u64>, ()> {
match v {
None | Some(Value::Null) => Ok(None),
Some(v) => whole_in(v, 0, MAX_CAP).map(Some).ok_or(()),
}
}
fn thumb_of(v: Option<&Value>) -> Result<Option<Thumb>, ()> {
let t = match v {
None | Some(Value::Null) => return Ok(None),
Some(t) => t,
};
let url = t.get("url").and_then(Value::as_str).filter(|u| t.is_object() && ABSOLUTE.is_match(u)).ok_or(())?;
let (width, height) = (size_of(t.get("width")).ok_or(())?, size_of(t.get("height")).ok_or(())?);
Ok(Some(Thumb { url: url.into(), width, height, bytes: bytes_of(t.get("bytes"))? }))
}
fn preload_valid(v: &Value) -> bool {
v.is_boolean()
|| v.as_object().is_some_and(|m| {
m.iter().all(|(k, x)| match k.as_str() {
"fold" | "count" | "bytes" => x.is_null() || whole_in(x, 0, MAX_CAP).is_some(),
"parallel" => x.is_null() || whole_in(x, 1, 8).is_some(),
_ => false,
})
})
}
fn preload_model(v: Option<&Value>) -> Option<Preload> {
match v? {
Value::Bool(true) => None,
Value::Bool(false) => Some(Preload::Off),
v => {
let d = PreloadCaps::default();
let cap = |k: &str, d: u64| v.get(k).and_then(integral).map_or(d, |n| n as u64);
Some(Preload::Caps(PreloadCaps {
fold: cap("fold", d.fold),
count: cap("count", d.count),
bytes: cap("bytes", d.bytes),
parallel: cap("parallel", d.parallel),
}))
}
}
}
fn check_manifest(manifest: &Value) -> Result<(), Error> {
let Some(groups) = manifest.get("groups").filter(|_| manifest.is_object()).and_then(Value::as_array) else {
return fail("not a gallery manifest: it has no groups");
};
for (i, g) in groups.iter().enumerate() {
let name = match g.get("name").and_then(Value::as_str) {
Some(n) if g.is_object() && !n.is_empty() => n,
_ => return fail(format!("gallery manifest group {i} has no name")),
};
if !matches!(g.get("title"), None | Some(Value::Null) | Some(Value::String(_))) {
return fail(format!("gallery manifest group {name}: its title isn't a string"));
}
let Some(items) = g.get("items").and_then(Value::as_array) else {
return fail(format!("gallery manifest group {name} has no items"));
};
for (j, item) in items.iter().enumerate() {
let place = format!("gallery manifest group {name}, item {j}");
let iname = match item.get("name").and_then(Value::as_str) {
Some(n) if item.is_object() && !n.is_empty() => n,
_ => return fail(format!("{place} has no name")),
};
if !item.get("url").and_then(Value::as_str).is_some_and(|u| ABSOLUTE.is_match(u)) {
return fail(format!("{place} ({iname}): its url isn't an http(s) URL"));
}
if size_of(item.get("width")).is_none() || size_of(item.get("height")).is_none() {
return fail(format!(
"{place} ({iname}): its width and height aren't whole numbers from 1 to {MAX_SIZE}"
));
}
if bytes_of(item.get("bytes")).is_err() {
return fail(format!("{place} ({iname}): its bytes isn't a whole number"));
}
if thumb_of(item.get("thumb")).is_err() {
return fail(format!("{place} ({iname}): its thumb needs an http(s) url, a width and a height"));
}
}
}
Ok(())
}
#[derive(Debug, Clone, Default)]
pub struct Options {
raw: Map<String, Value>,
}
impl Options {
pub fn from_json(value: &Value) -> Result<Self, Error> {
match value {
Value::Object(m) => Ok(Options { raw: m.clone() }),
_ => fail("gallery options must be an object"),
}
}
fn set(mut self, key: &str, value: Value) -> Self {
self.raw.insert(key.to_string(), value);
self
}
pub fn title(self, title: Option<&str>) -> Self {
self.set("title", title.map_or(Value::Null, |t| Value::String(t.into())))
}
pub fn heading_level(self, level: u8) -> Self {
self.set("headingLevel", level.into())
}
pub fn id(self, id: &str) -> Self {
self.set("id", id.into())
}
pub fn screen(mut self, key: &str, title: Option<&str>, caption: Option<&str>) -> Self {
let screens = self.raw.entry("screens").or_insert_with(|| Value::Object(Map::new()));
if let Value::Object(m) = screens {
m.insert(key.into(), serde_json::json!({ "title": title, "caption": caption }));
}
self
}
pub fn order<S: AsRef<str>>(self, keys: &[S]) -> Self {
self.set("order", keys.iter().map(|k| Value::String(k.as_ref().into())).collect())
}
pub fn group(mut self, name: &str, title: Option<&str>, size: Option<&str>, fit: Option<&str>) -> Self {
let groups = self.raw.entry("groups").or_insert_with(|| Value::Object(Map::new()));
if let Value::Object(m) = groups {
m.insert(name.into(), serde_json::json!({ "title": title, "size": size, "fit": fit }));
}
self
}
pub fn group_order<S: AsRef<str>>(self, names: &[S]) -> Self {
self.set("groupOrder", names.iter().map(|k| Value::String(k.as_ref().into())).collect())
}
pub fn credit(self, on: bool) -> Self {
self.set("credit", on.into())
}
pub fn layout(self, layout: &str) -> Self {
self.set("layout", layout.into())
}
pub fn theme_switch(self, on: bool) -> Self {
self.set("themeSwitch", on.into())
}
pub fn see_all(self, href: &str, text: Option<&str>) -> Self {
self.set("seeAll", serde_json::json!({ "href": href, "text": text }))
}
pub fn preload(self, on: bool) -> Self {
self.set("preload", on.into())
}
pub fn preload_caps(
self,
fold: Option<u64>,
count: Option<u64>,
bytes: Option<u64>,
parallel: Option<u64>,
) -> Self {
self.set("preload", serde_json::json!({ "fold": fold, "count": count, "bytes": bytes, "parallel": parallel }))
}
fn get(&self, key: &str, check: impl Fn(&Value) -> bool) -> Result<Option<&Value>, Error> {
match self.raw.get(key) {
None | Some(Value::Null) => Ok(None),
Some(v) if check(v) => Ok(Some(v)),
Some(_) => fail(format!("gallery option {key} is invalid")),
}
}
}
fn texts(keys: &'static [&'static str]) -> impl Fn(&Value) -> bool {
move |v| {
v.as_object().is_some_and(|m| {
m.values().all(|entry| {
entry.as_object().is_some_and(|e| {
e.iter().all(|(k, x)| keys.contains(&k.as_str()) && (x.is_null() || x.is_string()))
})
})
})
}
}
fn group_options(v: &Value) -> bool {
v.as_object().is_some_and(|m| {
m.values().all(|entry| {
entry.as_object().is_some_and(|e| {
e.iter().all(|(k, x)| match (k.as_str(), x) {
("title" | "size" | "fit", Value::Null) => true,
("title", Value::String(_)) => true,
("size", Value::String(s)) => SIZES.contains(&s.as_str()),
("fit", Value::String(f)) => f == "cover" || f == "contain",
_ => false,
})
})
})
})
}
fn strings(v: &Value) -> bool {
v.as_array().is_some_and(|a| a.iter().all(Value::is_string))
}
fn string_list(v: Option<&Value>) -> Option<Vec<String>> {
v.map(|v| v.as_array().unwrap().iter().map(|s| s.as_str().unwrap().to_string()).collect())
}
fn text_of<'a>(map: Option<&'a Value>, outer: &str, inner: &str) -> Option<&'a str> {
map?.get(outer)?.get(inner)?.as_str()
}
pub fn build_model(manifest: &Value, options: &Options) -> Result<Model, Error> {
check_manifest(manifest)?;
let level = options.get("headingLevel", |v| integral(v).is_some())?.and_then(integral).unwrap_or(2.0);
let heading_level = level.clamp(1.0, 4.0) as u8;
let title = if options.raw.contains_key("title") {
options.get("title", Value::is_string)?.and_then(Value::as_str).map(str::to_string)
} else {
Some(DEFAULT_TITLE.to_string())
};
let id = options
.get("id", |v| v.as_str().is_some_and(|s| ID.is_match(s)))?
.and_then(Value::as_str)
.unwrap_or("vg")
.to_string();
let screens_opt = options.get("screens", texts(&["title", "caption"]))?;
let groups_opt = options.get("groups", group_options)?;
let order = string_list(options.get("order", strings)?);
let group_order = string_list(options.get("groupOrder", strings)?);
let credit = options.get("credit", Value::is_boolean)?.and_then(Value::as_bool).unwrap_or(true);
let switch = options.get("themeSwitch", Value::is_boolean)?.and_then(Value::as_bool).unwrap_or(true);
let layout = options
.get("layout", |v| matches!(v.as_str(), Some("grid" | "strip")))?
.and_then(Value::as_str)
.unwrap_or("grid")
.to_string();
let see_all = options.get("seeAll", |v| {
v.is_object()
&& v.get("href").and_then(Value::as_str).is_some_and(safe_href)
&& matches!(v.get("text"), None | Some(Value::Null) | Some(Value::String(_)))
})?;
let preload = preload_model(options.get("preload", preload_valid)?);
let mut slugs = HashSet::new();
let mut groups: Vec<Group> = Vec::new();
for g in manifest["groups"].as_array().unwrap() {
let gname = g["name"].as_str().unwrap();
let size_opt = text_of(groups_opt, gname, "size");
let mut keys: Vec<String> = Vec::new();
let mut found: HashMap<String, Vec<Variant>> = HashMap::new();
for item in g["items"].as_array().unwrap() {
let (w, h) = (size_of(item.get("width")).unwrap(), size_of(item.get("height")).unwrap());
let url = item["url"].as_str().unwrap();
let shot = parse_shot(item["name"].as_str().unwrap(), w, h, size_opt);
let variants = found.entry(shot.key.clone()).or_insert_with(|| {
keys.push(shot.key.clone());
Vec::new()
});
let themes: Vec<&str> = match &shot.theme {
Some(t) => vec![t.as_str()],
None => THEMES.to_vec(),
};
for theme in themes {
let at = match variants.iter().position(|v| v.size == shot.size && v.theme == theme) {
Some(i) => i,
None => {
variants.push(Variant {
size: shot.size.clone(),
theme: theme.into(),
url: String::new(),
url2x: None,
width: 0,
height: 0,
bytes: None,
bytes2x: None,
thumb: None,
});
variants.len() - 1
}
};
let v = &mut variants[at];
if shot.x2 {
if v.url2x.is_none() {
v.url2x = Some(url.into());
v.bytes2x = bytes_of(item.get("bytes")).unwrap();
}
} else if v.url.is_empty() {
match shot.css_width {
Some(cw) if w > cw => {
let height = (2 * h as u128 * cw as u128 + w as u128) / (2 * w as u128);
(v.url, v.width, v.height) = (url.into(), cw, height as u64);
}
_ => (v.url, v.width, v.height) = (url.into(), w, h),
}
v.bytes = bytes_of(item.get("bytes")).unwrap();
v.thumb = thumb_of(item.get("thumb")).unwrap();
}
}
}
let mut kept: Vec<(String, Vec<Variant>)> = Vec::new();
for key in keys {
let mut variants: Vec<Variant> =
found.remove(&key).unwrap().into_iter().filter(|v| !v.url.is_empty()).collect();
variants
.sort_by_key(|v| (SIZES.iter().position(|s| *s == v.size), THEMES.iter().position(|t| *t == v.theme)));
if !variants.is_empty() {
kept.push((key, variants));
}
}
for (key, variants) in &kept {
for v in variants {
if !variants.iter().any(|o| o.size == v.size && o.theme != v.theme) {
let other = if v.theme == "light" { "dark" } else { "light" };
return fail(format!(
"gallery screen {key} in group {gname} has a {} {} screenshot but no {other} one",
v.theme, v.size
));
}
}
}
if kept.is_empty() {
continue;
}
let prefix = common_folder(&kept.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>());
let mut list: Vec<Screen> = kept
.into_iter()
.map(|(key, variants)| {
let set = screens_opt.and_then(|m| m.get(&key));
let title =
set.and_then(|s| s.get("title")).and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| {
let parts: Vec<&str> = key.split('/').skip(prefix).collect();
humanize(&parts)
});
let caption = set.and_then(|s| s.get("caption")).and_then(Value::as_str).map(str::to_string);
Screen { key, title, caption, variants }
})
.collect();
list.sort_by(|a, b| rank(&order, &a.key).cmp(&rank(&order, &b.key)).then_with(|| a.key.cmp(&b.key)));
let base = slugify(gname);
let mut slug = base.clone();
let mut n = 2;
while slugs.contains(&slug) {
slug = format!("{base}-{n}");
n += 1;
}
slugs.insert(slug.clone());
let title = text_of(groups_opt, gname, "title")
.or_else(|| g.get("title").and_then(Value::as_str))
.unwrap_or(gname)
.to_string();
let sizes = SIZES
.iter()
.filter(|s| list.iter().any(|sc| sc.variants.iter().any(|v| v.size == **s)))
.map(|s| s.to_string())
.collect();
let fit = text_of(groups_opt, gname, "fit").unwrap_or("cover").to_string();
groups.push(Group { name: gname.into(), title, slug, fit, sizes, screens: list });
}
if groups.is_empty() {
return fail("the gallery manifest has no screenshots to show");
}
groups.sort_by_key(|g| rank(&group_order, &g.name));
Ok(Model {
theme_switch: layout == "grid" && switch,
layout,
see_all: see_all.map(|v| SeeAll {
href: v["href"].as_str().unwrap().into(),
text: v.get("text").and_then(Value::as_str).unwrap_or(SEE_ALL_TEXT).into(),
}),
label: title.clone().unwrap_or_else(|| DEFAULT_TITLE.into()),
title,
heading_level,
id,
credit,
preload,
groups,
})
}