//! Loader for Sherlock's `data.json` format.
use anyhow::{Context, Result};
use serde_json::{Map, Value};
use super::schema::{Detector, HttpMethod, Site, Source, normalize_placeholders};
pub fn looks_like(v: &Value) -> bool {
let Some(obj) = v.as_object() else {
return false;
};
if obj.contains_key("sites") || obj.contains_key("engines") {
return false;
}
obj.values().filter_map(Value::as_object).take(5).any(|e| {
e.contains_key("url") && (e.contains_key("errorType") || e.contains_key("urlMain"))
})
}
pub fn parse(json: &str) -> Result<Vec<Site>> {
let v: Value = serde_json::from_str(json).context("parsing Sherlock data")?;
let obj = v
.as_object()
.context("Sherlock data must be a JSON object")?;
Ok(obj
.iter()
.filter_map(|(name, entry)| entry.as_object().and_then(|e| convert(name, e)))
.collect())
}
fn str_field(e: &Map<String, Value>, key: &str) -> Option<String> {
e.get(key)
.and_then(Value::as_str)
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty())
}
fn str_list(v: Option<&Value>) -> Vec<String> {
match v {
Some(Value::String(s)) => vec![s.clone()],
Some(Value::Array(a)) => a
.iter()
.filter_map(Value::as_str)
.map(String::from)
.collect(),
_ => Vec::new(),
}
}
fn code_list(v: Option<&Value>) -> Vec<u16> {
match v {
Some(Value::Number(n)) => n.as_u64().map(|c| vec![c as u16]).unwrap_or_default(),
Some(Value::Array(a)) => a
.iter()
.filter_map(Value::as_u64)
.map(|c| c as u16)
.collect(),
_ => Vec::new(),
}
}
fn convert(name: &str, e: &Map<String, Value>) -> Option<Site> {
let url = str_field(e, "url")?;
let probe = str_field(e, "urlProbe");
let error_type = str_field(e, "errorType").unwrap_or_else(|| "status_code".to_string());
let (detector, follow) = match error_type.as_str() {
"message" => (
Detector::Message {
absence: str_list(e.get("errorMsg")),
presence: Vec::new(),
},
true,
),
"response_url" => (
Detector::ResponseUrl {
error_url: str_field(e, "errorUrl"),
},
true,
),
_ => (
Detector::StatusCode {
error_codes: code_list(e.get("errorCode")),
},
true,
),
};
let mut headers: Vec<(String, String)> = e
.get("headers")
.and_then(Value::as_object)
.map(|m| {
m.iter()
.filter_map(|(k, v)| v.as_str().map(|s| (k.clone(), s.to_string())))
.collect()
})
.unwrap_or_default();
let payload = e.get("request_payload");
let body =
payload.map(|p| normalize_placeholders(&serde_json::to_string(p).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 = str_field(e, "request_method")
.and_then(|m| HttpMethod::parse_loose(&m))
.unwrap_or(if body.is_some() {
HttpMethod::Post
} else {
HttpMethod::Get
});
let nsfw = e.get("isNSFW").and_then(Value::as_bool).unwrap_or(false);
let known = str_field(e, "username_claimed")
.map(|u| vec![u])
.unwrap_or_default();
Some(Site {
name: name.trim().to_string(),
source: Source::Sherlock,
category: if nsfw {
"nsfw".to_string()
} else {
"misc".to_string()
},
url: probe.clone().unwrap_or_else(|| url.clone()),
pretty_url: if probe.is_some() { Some(url) } else { None },
home: str_field(e, "urlMain"),
method,
body,
headers,
username_regex: str_field(e, "regexCheck"),
follow_redirects: follow,
detector,
known,
unclaimed: str_field(e, "username_unclaimed"),
nsfw,
..Default::default()
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_entries() {
let json = r#"{"$schema":"x","GitHub":{"errorType":"status_code","url":"https://github.com/{}","urlMain":"https://github.com/","username_claimed":"blue","regexCheck":"^[a-z]+$"},
"Msg":{"errorMsg":["a","b"],"errorType":"message","url":"https://m.com/{}","urlProbe":"https://api.m.com/{}","isNSFW":true},
"Post":{"errorType":"status_code","request_method":"POST","request_payload":{"q":"{}"},"url":"https://p.com/{}","urlProbe":"https://p.com/api"}}"#;
let v: Value = serde_json::from_str(json).unwrap();
assert!(looks_like(&v));
let sites = parse(json).unwrap();
assert_eq!(sites.len(), 3);
let gh = sites.iter().find(|s| s.name == "GitHub").unwrap();
assert!(gh.follow_redirects);
assert_eq!(gh.known, vec!["blue".to_string()]);
let msg = sites.iter().find(|s| s.name == "Msg").unwrap();
assert!(msg.nsfw);
assert_eq!(msg.url, "https://api.m.com/{}");
assert_eq!(msg.pretty_url.as_deref(), Some("https://m.com/{}"));
assert!(matches!(&msg.detector, Detector::Message { absence, .. } if absence.len() == 2));
let post = sites.iter().find(|s| s.name == "Post").unwrap();
assert_eq!(post.method, HttpMethod::Post);
assert_eq!(post.body.as_deref(), Some("{\"q\":\"{account}\"}"));
assert_eq!(post.content_type(), Some("application/json"));
}
}