1use std::collections::{HashMap, HashSet};
5use std::sync::LazyLock;
6
7use regex::Regex;
8use serde::{Serialize, Serializer};
9use serde_json::{Map, Value};
10
11use crate::Error;
12
13pub const DEFAULT_TITLE: &str = "Screenshots";
14pub const SEE_ALL_TEXT: &str = "See all screenshots";
15const SIZES: [&str; 2] = ["desktop", "phone"];
16const THEMES: [&str; 2] = ["light", "dark"];
17
18static EXTENSION: LazyLock<Regex> =
21 LazyLock::new(|| Regex::new(r"\.(?:[pP][nN][gG]|[jJ][pP][eE]?[gG]|[wW][eE][bB][pP])\z").unwrap());
22static WIDTH_THEME: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\A([0-9]+)-(light|dark)(-2x)?\z").unwrap());
23static SCREEN_THEME: LazyLock<Regex> =
24 LazyLock::new(|| Regex::new(r"\A((?s:.)+?)-(light|dark)(?:-([0-9]+))?(-2x)?\z").unwrap());
25static ABSOLUTE: LazyLock<Regex> =
26 LazyLock::new(|| Regex::new(r"\A[hH][tT][tT][pP][sS]?://[^\x00-\x20\x7f]+\z").unwrap());
27static CONTROL: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[\x00-\x20\x7f]").unwrap());
28static SCHEME: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\A[A-Za-z][A-Za-z0-9+.-]*:").unwrap());
29static ID: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\A[A-Za-z][A-Za-z0-9_-]*\z").unwrap());
30
31#[derive(Debug, Clone, PartialEq, Serialize)]
32pub struct Variant {
33 pub size: String,
34 pub theme: String,
35 pub url: String,
36 pub url2x: Option<String>,
37 pub width: u64,
38 pub height: u64,
39 pub bytes: Option<u64>,
41 pub bytes2x: Option<u64>,
42 pub thumb: Option<Thumb>,
44}
45
46#[derive(Debug, Clone, PartialEq, Serialize)]
47pub struct Thumb {
48 pub url: String,
49 pub width: u64,
50 pub height: u64,
51 pub bytes: Option<u64>,
52}
53
54#[derive(Debug, Clone, PartialEq, Eq, Serialize)]
57pub struct PreloadCaps {
58 pub fold: u64,
59 pub count: u64,
60 pub bytes: u64,
61 pub parallel: u64,
62}
63
64impl Default for PreloadCaps {
65 fn default() -> Self {
67 PreloadCaps { fold: 250, count: 500, bytes: 50_000_000, parallel: 4 }
68 }
69}
70
71#[derive(Debug, Clone, PartialEq, Eq)]
73pub enum Preload {
74 Off,
75 Caps(PreloadCaps),
76}
77
78impl Serialize for Preload {
79 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
80 match self {
81 Preload::Off => serializer.serialize_str("off"),
82 Preload::Caps(caps) => caps.serialize(serializer),
83 }
84 }
85}
86
87#[derive(Debug, Clone, PartialEq, Serialize)]
88pub struct Screen {
89 pub key: String,
90 pub title: String,
91 pub caption: Option<String>,
92 pub variants: Vec<Variant>,
93}
94
95#[derive(Debug, Clone, PartialEq, Serialize)]
96pub struct Group {
97 pub name: String,
98 pub title: String,
99 pub slug: String,
100 pub fit: String,
101 pub sizes: Vec<String>,
102 pub screens: Vec<Screen>,
103}
104
105#[derive(Debug, Clone, PartialEq, Serialize)]
106pub struct SeeAll {
107 pub href: String,
108 pub text: String,
109}
110
111#[derive(Debug, Clone, PartialEq, Serialize)]
113#[serde(rename_all = "camelCase")]
114pub struct Model {
115 pub layout: String,
116 pub theme_switch: bool,
117 pub see_all: Option<SeeAll>,
118 pub title: Option<String>,
119 pub label: String,
120 pub heading_level: u8,
121 pub id: String,
122 pub credit: bool,
123 pub preload: Option<Preload>,
125 pub groups: Vec<Group>,
126}
127
128#[derive(Debug, Clone, PartialEq)]
130pub struct Shot {
131 pub key: String,
133 pub theme: Option<String>,
135 pub size: String,
136 pub x2: bool,
137 pub css_width: Option<u64>,
139}
140
141pub fn parse_shot(name: &str, width: u64, height: u64, size: Option<&str>) -> Shot {
145 let stripped = EXTENSION.replace(name, "");
146 let mut parts: Vec<&str> = stripped.split('/').collect();
147 let last = parts.pop().unwrap_or("");
148 let folder = parts.join("/");
149 let sized = |w: Option<&str>| -> String {
151 match w {
152 Some(w) => if w.parse::<u64>().is_ok_and(|n| n < 768) { "phone" } else { "desktop" }.to_string(),
153 None => {
154 size.map(str::to_string).unwrap_or_else(|| if height > width { "phone" } else { "desktop" }.to_string())
155 }
156 }
157 };
158 let css = |w: Option<&str>| w.and_then(|w| w.parse::<u64>().ok());
159
160 if !folder.is_empty() {
161 if let Some(m) = WIDTH_THEME.captures(last) {
162 let w = m.get(1).map(|x| x.as_str());
163 return Shot {
164 key: folder,
165 theme: Some(m[2].to_string()),
166 size: sized(w),
167 x2: m.get(3).is_some(),
168 css_width: css(w),
169 };
170 }
171 }
172 if let Some(m) = SCREEN_THEME.captures(last) {
173 let key = if folder.is_empty() { m[1].to_string() } else { format!("{folder}/{}", &m[1]) };
174 let w = m.get(3).map(|x| x.as_str());
175 return Shot { key, theme: Some(m[2].to_string()), size: sized(w), x2: m.get(4).is_some(), css_width: css(w) };
176 }
177 let key = if folder.is_empty() { last.to_string() } else { format!("{folder}/{last}") };
178 Shot { key, theme: None, size: sized(None), x2: false, css_width: None }
179}
180
181pub fn humanize(segments: &[&str]) -> String {
183 static RUNS: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"[-_]+").unwrap());
184 let text =
185 segments.iter().map(|s| RUNS.replace_all(s, " ").trim_matches(' ').to_string()).collect::<Vec<_>>().join(", ");
186 let mut chars = text.chars();
187 match chars.next() {
188 Some(first) => first.to_uppercase().chain(chars).collect(),
189 None => text,
190 }
191}
192
193pub fn slugify(name: &str) -> String {
195 let mut out = String::new();
196 let mut dash = false;
197 for c in name.chars() {
198 let c = c.to_ascii_lowercase();
199 if c.is_ascii_lowercase() || c.is_ascii_digit() {
200 if dash && !out.is_empty() {
201 out.push('-');
202 }
203 dash = false;
204 out.push(c);
205 } else {
206 dash = true;
207 }
208 }
209 if out.is_empty() { "group".to_string() } else { out }
210}
211
212fn common_folder(keys: &[&str]) -> usize {
213 let folders: Vec<Vec<&str>> = keys
214 .iter()
215 .map(|k| {
216 let mut p: Vec<&str> = k.split('/').collect();
217 p.pop();
218 p
219 })
220 .collect();
221 let Some(first) = folders.first() else { return 0 };
222 let mut common = first.len();
223 for f in &folders[1..] {
224 let mut i = 0;
225 while i < common && i < f.len() && first[i] == f[i] {
226 i += 1;
227 }
228 common = i;
229 }
230 common
231}
232
233fn rank(order: &Option<Vec<String>>, key: &str) -> usize {
234 let list = order.as_deref().unwrap_or(&[]);
235 list.iter().position(|k| k == key).unwrap_or(list.len())
236}
237
238fn safe_href(value: &str) -> bool {
239 ABSOLUTE.is_match(value) || (!value.is_empty() && !CONTROL.is_match(value) && !SCHEME.is_match(value))
240}
241
242fn fail<T>(message: impl Into<String>) -> Result<T, Error> {
243 Err(Error::Invalid(message.into()))
244}
245
246fn integral(v: &Value) -> Option<f64> {
248 let n = v.as_f64()?;
249 (n.is_finite() && n.fract() == 0.0).then_some(n)
250}
251
252pub const MAX_SIZE: u64 = 1_000_000;
254
255fn size_of(v: Option<&Value>) -> Option<u64> {
256 let n = integral(v?)?;
257 (n > 0.0 && n <= MAX_SIZE as f64).then_some(n as u64)
258}
259
260const MAX_CAP: u64 = 1_000_000_000_000;
262
263fn whole_in(v: &Value, min: u64, max: u64) -> Option<u64> {
265 let n = integral(v)?;
266 (n >= min as f64 && n <= max as f64).then_some(n as u64)
267}
268
269fn bytes_of(v: Option<&Value>) -> Result<Option<u64>, ()> {
271 match v {
272 None | Some(Value::Null) => Ok(None),
273 Some(v) => whole_in(v, 0, MAX_CAP).map(Some).ok_or(()),
274 }
275}
276
277fn thumb_of(v: Option<&Value>) -> Result<Option<Thumb>, ()> {
279 let t = match v {
280 None | Some(Value::Null) => return Ok(None),
281 Some(t) => t,
282 };
283 let url = t.get("url").and_then(Value::as_str).filter(|u| t.is_object() && ABSOLUTE.is_match(u)).ok_or(())?;
284 let (width, height) = (size_of(t.get("width")).ok_or(())?, size_of(t.get("height")).ok_or(())?);
285 Ok(Some(Thumb { url: url.into(), width, height, bytes: bytes_of(t.get("bytes"))? }))
286}
287
288fn preload_valid(v: &Value) -> bool {
291 v.is_boolean()
292 || v.as_object().is_some_and(|m| {
293 m.iter().all(|(k, x)| match k.as_str() {
294 "fold" | "count" | "bytes" => x.is_null() || whole_in(x, 0, MAX_CAP).is_some(),
295 "parallel" => x.is_null() || whole_in(x, 1, 8).is_some(),
296 _ => false,
297 })
298 })
299}
300
301fn preload_model(v: Option<&Value>) -> Option<Preload> {
302 match v? {
303 Value::Bool(true) => None,
304 Value::Bool(false) => Some(Preload::Off),
305 v => {
306 let d = PreloadCaps::default();
307 let cap = |k: &str, d: u64| v.get(k).and_then(integral).map_or(d, |n| n as u64);
308 Some(Preload::Caps(PreloadCaps {
309 fold: cap("fold", d.fold),
310 count: cap("count", d.count),
311 bytes: cap("bytes", d.bytes),
312 parallel: cap("parallel", d.parallel),
313 }))
314 }
315 }
316}
317
318fn check_manifest(manifest: &Value) -> Result<(), Error> {
320 let Some(groups) = manifest.get("groups").filter(|_| manifest.is_object()).and_then(Value::as_array) else {
321 return fail("not a gallery manifest: it has no groups");
322 };
323 for (i, g) in groups.iter().enumerate() {
324 let name = match g.get("name").and_then(Value::as_str) {
325 Some(n) if g.is_object() && !n.is_empty() => n,
326 _ => return fail(format!("gallery manifest group {i} has no name")),
327 };
328 if !matches!(g.get("title"), None | Some(Value::Null) | Some(Value::String(_))) {
329 return fail(format!("gallery manifest group {name}: its title isn't a string"));
330 }
331 let Some(items) = g.get("items").and_then(Value::as_array) else {
332 return fail(format!("gallery manifest group {name} has no items"));
333 };
334 for (j, item) in items.iter().enumerate() {
335 let place = format!("gallery manifest group {name}, item {j}");
336 let iname = match item.get("name").and_then(Value::as_str) {
337 Some(n) if item.is_object() && !n.is_empty() => n,
338 _ => return fail(format!("{place} has no name")),
339 };
340 if !item.get("url").and_then(Value::as_str).is_some_and(|u| ABSOLUTE.is_match(u)) {
341 return fail(format!("{place} ({iname}): its url isn't an http(s) URL"));
342 }
343 if size_of(item.get("width")).is_none() || size_of(item.get("height")).is_none() {
344 return fail(format!(
345 "{place} ({iname}): its width and height aren't whole numbers from 1 to {MAX_SIZE}"
346 ));
347 }
348 if bytes_of(item.get("bytes")).is_err() {
349 return fail(format!("{place} ({iname}): its bytes isn't a whole number"));
350 }
351 if thumb_of(item.get("thumb")).is_err() {
352 return fail(format!("{place} ({iname}): its thumb needs an http(s) url, a width and a height"));
353 }
354 }
355 }
356 Ok(())
357}
358
359#[derive(Debug, Clone, Default)]
362pub struct Options {
363 raw: Map<String, Value>,
364}
365
366impl Options {
367 pub fn from_json(value: &Value) -> Result<Self, Error> {
369 match value {
370 Value::Object(m) => Ok(Options { raw: m.clone() }),
371 _ => fail("gallery options must be an object"),
372 }
373 }
374 fn set(mut self, key: &str, value: Value) -> Self {
375 self.raw.insert(key.to_string(), value);
376 self
377 }
378 pub fn title(self, title: Option<&str>) -> Self {
380 self.set("title", title.map_or(Value::Null, |t| Value::String(t.into())))
381 }
382 pub fn heading_level(self, level: u8) -> Self {
383 self.set("headingLevel", level.into())
384 }
385 pub fn id(self, id: &str) -> Self {
386 self.set("id", id.into())
387 }
388 pub fn screen(mut self, key: &str, title: Option<&str>, caption: Option<&str>) -> Self {
390 let screens = self.raw.entry("screens").or_insert_with(|| Value::Object(Map::new()));
391 if let Value::Object(m) = screens {
392 m.insert(key.into(), serde_json::json!({ "title": title, "caption": caption }));
393 }
394 self
395 }
396 pub fn order<S: AsRef<str>>(self, keys: &[S]) -> Self {
397 self.set("order", keys.iter().map(|k| Value::String(k.as_ref().into())).collect())
398 }
399 pub fn group(mut self, name: &str, title: Option<&str>, size: Option<&str>, fit: Option<&str>) -> Self {
402 let groups = self.raw.entry("groups").or_insert_with(|| Value::Object(Map::new()));
403 if let Value::Object(m) = groups {
404 m.insert(name.into(), serde_json::json!({ "title": title, "size": size, "fit": fit }));
405 }
406 self
407 }
408 pub fn group_order<S: AsRef<str>>(self, names: &[S]) -> Self {
409 self.set("groupOrder", names.iter().map(|k| Value::String(k.as_ref().into())).collect())
410 }
411 pub fn credit(self, on: bool) -> Self {
412 self.set("credit", on.into())
413 }
414 pub fn layout(self, layout: &str) -> Self {
416 self.set("layout", layout.into())
417 }
418 pub fn theme_switch(self, on: bool) -> Self {
419 self.set("themeSwitch", on.into())
420 }
421 pub fn see_all(self, href: &str, text: Option<&str>) -> Self {
422 self.set("seeAll", serde_json::json!({ "href": href, "text": text }))
423 }
424 pub fn preload(self, on: bool) -> Self {
426 self.set("preload", on.into())
427 }
428 pub fn preload_caps(
432 self,
433 fold: Option<u64>,
434 count: Option<u64>,
435 bytes: Option<u64>,
436 parallel: Option<u64>,
437 ) -> Self {
438 self.set("preload", serde_json::json!({ "fold": fold, "count": count, "bytes": bytes, "parallel": parallel }))
439 }
440
441 fn get(&self, key: &str, check: impl Fn(&Value) -> bool) -> Result<Option<&Value>, Error> {
443 match self.raw.get(key) {
444 None | Some(Value::Null) => Ok(None),
445 Some(v) if check(v) => Ok(Some(v)),
446 Some(_) => fail(format!("gallery option {key} is invalid")),
447 }
448 }
449}
450
451fn texts(keys: &'static [&'static str]) -> impl Fn(&Value) -> bool {
452 move |v| {
453 v.as_object().is_some_and(|m| {
454 m.values().all(|entry| {
455 entry.as_object().is_some_and(|e| {
456 e.iter().all(|(k, x)| keys.contains(&k.as_str()) && (x.is_null() || x.is_string()))
457 })
458 })
459 })
460 }
461}
462
463fn group_options(v: &Value) -> bool {
464 v.as_object().is_some_and(|m| {
465 m.values().all(|entry| {
466 entry.as_object().is_some_and(|e| {
467 e.iter().all(|(k, x)| match (k.as_str(), x) {
468 ("title" | "size" | "fit", Value::Null) => true,
469 ("title", Value::String(_)) => true,
470 ("size", Value::String(s)) => SIZES.contains(&s.as_str()),
471 ("fit", Value::String(f)) => f == "cover" || f == "contain",
472 _ => false,
473 })
474 })
475 })
476 })
477}
478
479fn strings(v: &Value) -> bool {
480 v.as_array().is_some_and(|a| a.iter().all(Value::is_string))
481}
482
483fn string_list(v: Option<&Value>) -> Option<Vec<String>> {
484 v.map(|v| v.as_array().unwrap().iter().map(|s| s.as_str().unwrap().to_string()).collect())
485}
486
487fn text_of<'a>(map: Option<&'a Value>, outer: &str, inner: &str) -> Option<&'a str> {
488 map?.get(outer)?.get(inner)?.as_str()
489}
490
491pub fn build_model(manifest: &Value, options: &Options) -> Result<Model, Error> {
494 check_manifest(manifest)?;
495 let level = options.get("headingLevel", |v| integral(v).is_some())?.and_then(integral).unwrap_or(2.0);
496 let heading_level = level.clamp(1.0, 4.0) as u8;
497 let title = if options.raw.contains_key("title") {
498 options.get("title", Value::is_string)?.and_then(Value::as_str).map(str::to_string)
499 } else {
500 Some(DEFAULT_TITLE.to_string())
501 };
502 let id = options
503 .get("id", |v| v.as_str().is_some_and(|s| ID.is_match(s)))?
504 .and_then(Value::as_str)
505 .unwrap_or("vg")
506 .to_string();
507 let screens_opt = options.get("screens", texts(&["title", "caption"]))?;
508 let groups_opt = options.get("groups", group_options)?;
509 let order = string_list(options.get("order", strings)?);
510 let group_order = string_list(options.get("groupOrder", strings)?);
511 let credit = options.get("credit", Value::is_boolean)?.and_then(Value::as_bool).unwrap_or(true);
512 let switch = options.get("themeSwitch", Value::is_boolean)?.and_then(Value::as_bool).unwrap_or(true);
513 let layout = options
514 .get("layout", |v| matches!(v.as_str(), Some("grid" | "strip")))?
515 .and_then(Value::as_str)
516 .unwrap_or("grid")
517 .to_string();
518 let see_all = options.get("seeAll", |v| {
519 v.is_object()
520 && v.get("href").and_then(Value::as_str).is_some_and(safe_href)
521 && matches!(v.get("text"), None | Some(Value::Null) | Some(Value::String(_)))
522 })?;
523 let preload = preload_model(options.get("preload", preload_valid)?);
524
525 let mut slugs = HashSet::new();
526 let mut groups: Vec<Group> = Vec::new();
527 for g in manifest["groups"].as_array().unwrap() {
528 let gname = g["name"].as_str().unwrap();
529 let size_opt = text_of(groups_opt, gname, "size");
530 let mut keys: Vec<String> = Vec::new();
532 let mut found: HashMap<String, Vec<Variant>> = HashMap::new();
533 for item in g["items"].as_array().unwrap() {
534 let (w, h) = (size_of(item.get("width")).unwrap(), size_of(item.get("height")).unwrap());
535 let url = item["url"].as_str().unwrap();
536 let shot = parse_shot(item["name"].as_str().unwrap(), w, h, size_opt);
537 let variants = found.entry(shot.key.clone()).or_insert_with(|| {
538 keys.push(shot.key.clone());
539 Vec::new()
540 });
541 let themes: Vec<&str> = match &shot.theme {
542 Some(t) => vec![t.as_str()],
543 None => THEMES.to_vec(),
544 };
545 for theme in themes {
546 let at = match variants.iter().position(|v| v.size == shot.size && v.theme == theme) {
547 Some(i) => i,
548 None => {
549 variants.push(Variant {
550 size: shot.size.clone(),
551 theme: theme.into(),
552 url: String::new(),
553 url2x: None,
554 width: 0,
555 height: 0,
556 bytes: None,
557 bytes2x: None,
558 thumb: None,
559 });
560 variants.len() - 1
561 }
562 };
563 let v = &mut variants[at];
564 if shot.x2 {
565 if v.url2x.is_none() {
566 v.url2x = Some(url.into());
567 v.bytes2x = bytes_of(item.get("bytes")).unwrap();
568 }
569 } else if v.url.is_empty() {
570 match shot.css_width {
573 Some(cw) if w > cw => {
574 let height = (2 * h as u128 * cw as u128 + w as u128) / (2 * w as u128);
575 (v.url, v.width, v.height) = (url.into(), cw, height as u64);
576 }
577 _ => (v.url, v.width, v.height) = (url.into(), w, h),
578 }
579 v.bytes = bytes_of(item.get("bytes")).unwrap();
580 v.thumb = thumb_of(item.get("thumb")).unwrap();
581 }
582 }
583 }
584 let mut kept: Vec<(String, Vec<Variant>)> = Vec::new();
586 for key in keys {
587 let mut variants: Vec<Variant> =
588 found.remove(&key).unwrap().into_iter().filter(|v| !v.url.is_empty()).collect();
589 variants
590 .sort_by_key(|v| (SIZES.iter().position(|s| *s == v.size), THEMES.iter().position(|t| *t == v.theme)));
591 if !variants.is_empty() {
592 kept.push((key, variants));
593 }
594 }
595 for (key, variants) in &kept {
597 for v in variants {
598 if !variants.iter().any(|o| o.size == v.size && o.theme != v.theme) {
599 let other = if v.theme == "light" { "dark" } else { "light" };
600 return fail(format!(
601 "gallery screen {key} in group {gname} has a {} {} screenshot but no {other} one",
602 v.theme, v.size
603 ));
604 }
605 }
606 }
607 if kept.is_empty() {
608 continue;
609 }
610 let prefix = common_folder(&kept.iter().map(|(k, _)| k.as_str()).collect::<Vec<_>>());
611 let mut list: Vec<Screen> = kept
612 .into_iter()
613 .map(|(key, variants)| {
614 let set = screens_opt.and_then(|m| m.get(&key));
615 let title =
616 set.and_then(|s| s.get("title")).and_then(Value::as_str).map(str::to_string).unwrap_or_else(|| {
617 let parts: Vec<&str> = key.split('/').skip(prefix).collect();
618 humanize(&parts)
619 });
620 let caption = set.and_then(|s| s.get("caption")).and_then(Value::as_str).map(str::to_string);
621 Screen { key, title, caption, variants }
622 })
623 .collect();
624 list.sort_by(|a, b| rank(&order, &a.key).cmp(&rank(&order, &b.key)).then_with(|| a.key.cmp(&b.key)));
626
627 let base = slugify(gname);
628 let mut slug = base.clone();
629 let mut n = 2;
630 while slugs.contains(&slug) {
631 slug = format!("{base}-{n}");
632 n += 1;
633 }
634 slugs.insert(slug.clone());
635 let title = text_of(groups_opt, gname, "title")
636 .or_else(|| g.get("title").and_then(Value::as_str))
637 .unwrap_or(gname)
638 .to_string();
639 let sizes = SIZES
640 .iter()
641 .filter(|s| list.iter().any(|sc| sc.variants.iter().any(|v| v.size == **s)))
642 .map(|s| s.to_string())
643 .collect();
644 let fit = text_of(groups_opt, gname, "fit").unwrap_or("cover").to_string();
645 groups.push(Group { name: gname.into(), title, slug, fit, sizes, screens: list });
646 }
647 if groups.is_empty() {
648 return fail("the gallery manifest has no screenshots to show");
649 }
650 groups.sort_by_key(|g| rank(&group_order, &g.name));
652
653 Ok(Model {
654 theme_switch: layout == "grid" && switch,
655 layout,
656 see_all: see_all.map(|v| SeeAll {
657 href: v["href"].as_str().unwrap().into(),
658 text: v.get("text").and_then(Value::as_str).unwrap_or(SEE_ALL_TEXT).into(),
659 }),
660 label: title.clone().unwrap_or_else(|| DEFAULT_TITLE.into()),
661 title,
662 heading_level,
663 id,
664 credit,
665 preload,
666 groups,
667 })
668}