//! Loader for Maigret's `data.json` format (sites + engines + tags). use anyhow::{Context, Result}; use serde_json::{Map, Value}; use super::categories; use super::schema::{Detector, HttpMethod, Site, Source, normalize_placeholders}; pub fn looks_like(v: &Value) -> bool { v.get("engines").is_some() && v.get("sites").map(Value::is_object).unwrap_or(false) } pub fn parse(json: &str) -> Result> { let v: Value = serde_json::from_str(json).context("parsing Maigret data")?; let sites = v .get("sites") .and_then(Value::as_object) .context("Maigret data has no 'sites' object")?; let engines = v .get("engines") .and_then(Value::as_object) .cloned() .unwrap_or_default(); Ok(sites .iter() .filter_map(|(name, raw)| raw.as_object().and_then(|r| convert(name, r, &engines))) .collect()) } fn str_of(m: &Map, key: &str) -> Option { m.get(key) .and_then(Value::as_str) .map(|s| s.trim().to_string()) .filter(|s| !s.is_empty()) } fn list_of(m: &Map, key: &str) -> Vec { m.get(key) .and_then(Value::as_array) .map(|a| { a.iter() .filter_map(Value::as_str) .map(String::from) .collect() }) .unwrap_or_default() } fn convert(name: &str, raw: &Map, engines: &Map) -> Option { // Engine template first, then the site's own fields on top. let mut merged = Map::new(); if let Some(engine) = raw.get("engine").and_then(Value::as_str) { if let Some(tpl) = engines .get(engine) .and_then(|e| e.get("site")) .and_then(Value::as_object) { for (k, v) in tpl { merged.insert(k.clone(), v.clone()); } } } for (k, v) in raw { merged.insert(k.clone(), v.clone()); } let m = &merged; let url_main = str_of(m, "urlMain") .map(|u| u.trim_end_matches('/').to_string()) .unwrap_or_default(); let subpath = str_of(m, "urlSubpath").unwrap_or_default(); let resolve = |t: String| { t.replace("{urlMain}", &url_main) .replace("{urlSubpath}", &subpath) }; let url = str_of(m, "url").map(resolve); let probe = str_of(m, "urlProbe").map(resolve); let (check_url, pretty) = match (probe, url) { (Some(p), Some(u)) => (p, Some(u)), (Some(p), None) => (p, None), (None, Some(u)) => (u, None), (None, None) => return None, }; if !check_url.contains("{username}") && !check_url.contains("{account}") && !check_url.contains("{}") { // Cannot substitute an account → useless. return None; } let absence = list_of(m, "absenceStrs"); let mut presence = list_of(m, "presenseStrs"); presence.extend(list_of(m, "presenceStrs")); let check_type = str_of(m, "checkType").unwrap_or_else(|| { if !absence.is_empty() || !presence.is_empty() { "message".into() } else { "status_code".into() } }); let (detector, follow) = match check_type.as_str() { "message" => (Detector::Message { absence, presence }, true), "response_url" => ( Detector::ResponseUrl { error_url: str_of(m, "errorUrl"), }, true, ), _ => ( Detector::StatusCode { error_codes: Vec::new(), }, true, ), }; let head_only = m .get("requestHeadOnly") .and_then(Value::as_bool) .unwrap_or(false); let payload = m.get("requestPayload"); let body = payload.map(|p| normalize_placeholders(&serde_json::to_string(p).unwrap_or_default())); let mut headers: Vec<(String, String)> = m .get("headers") .and_then(Value::as_object) .map(|h| { h.iter() .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string()))) .collect() }) .unwrap_or_default(); if body.is_some() && !headers .iter() .any(|(k, _)| k.eq_ignore_ascii_case("content-type")) { headers.push(("Content-Type".to_string(), "application/json".to_string())); } let method = if head_only { HttpMethod::Head } else { str_of(m, "requestMethod") .and_then(|s| HttpMethod::parse_loose(&s)) .unwrap_or(if body.is_some() { HttpMethod::Post } else { HttpMethod::Get }) }; let mut tags: Vec = list_of(m, "tags") .into_iter() .map(|t| t.to_ascii_lowercase()) .collect(); if let Some(engine) = str_of(raw, "engine") { tags.push(format!("engine:{}", engine.to_ascii_lowercase())); } let category = categories::from_tags(&tags); let nsfw = category == "nsfw"; let mut disabled = m.get("disabled").and_then(Value::as_bool).unwrap_or(false); let mut disabled_reason = if disabled { Some("disabled upstream".to_string()) } else { None }; if m.get("activation").is_some() && !disabled { disabled = true; disabled_reason = Some("requires token activation upstream".to_string()); } let errors: Vec<(String, String)> = m .get("errors") .and_then(Value::as_object) .map(|e| { e.iter() .filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string()))) .collect() }) .unwrap_or_default(); Some(Site { name: name.trim().to_string(), source: Source::Maigret, category, tags, url: check_url, pretty_url: pretty, home: if url_main.is_empty() { None } else { Some(url_main.clone()) }, method, body, headers, username_regex: str_of(m, "regexCheck"), follow_redirects: follow, detector, errors, known: str_of(m, "usernameClaimed") .map(|u| vec![u]) .unwrap_or_default(), unclaimed: str_of(m, "usernameUnclaimed"), nsfw, protection: list_of(m, "protection"), disabled, disabled_reason, rank: m.get("alexaRank").and_then(Value::as_u64).map(|r| r as u32), id_type: str_of(m, "type").unwrap_or_else(|| "username".to_string()), ignore_403: m.get("ignore403").and_then(Value::as_bool).unwrap_or(false), encoding: str_of(m, "encoding"), ..Default::default() }) } #[cfg(test)] mod tests { use super::*; #[test] fn resolves_engine_templates() { let json = r#"{"engines":{"Discourse":{"name":"Discourse","site":{"checkType":"message","url":"{urlMain}/u/{username}/summary","absenceStrs":["Oops"]}}}, "sites":{"Forum":{"engine":"Discourse","urlMain":"https://forum.example.org/","usernameClaimed":"alice","tags":["forum","tech","us"],"alexaRank":123}, "Dead":{"checkType":"status_code","url":"https://dead.example/{username}","disabled":true,"usernameClaimed":"bob"}, "Tok":{"checkType":"status_code","url":"https://tok.example/{username}","activation":{"method":"x"}}, "NoUrl":{"engine":"engine404","urlMain":"https://x.y"}},"tags":["forum"]}"#; let v: Value = serde_json::from_str(json).unwrap(); assert!(looks_like(&v)); let sites = parse(json).unwrap(); assert_eq!(sites.len(), 3); let f = sites.iter().find(|s| s.name == "Forum").unwrap(); assert_eq!(f.url, "https://forum.example.org/u/{username}/summary"); assert_eq!(f.category, "forum"); assert_eq!(f.rank, Some(123)); assert!(f.tags.contains(&"engine:discourse".to_string())); assert!( matches!(&f.detector, Detector::Message { absence, .. } if absence == &vec!["Oops".to_string()]) ); assert!(sites.iter().find(|s| s.name == "Dead").unwrap().disabled); assert!(sites.iter().find(|s| s.name == "Tok").unwrap().disabled); } }