//! Unified site schema. Every upstream format (WhatsMyName, Sherlock, Maigret,
//! Percival's own) is translated into this model at load time.
use std::fmt;
use std::str::FromStr;
use regex::Regex;
use serde::{Deserialize, Serialize};
use crate::util;
/// Where a site definition came from.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Source {
Percival,
Wmn,
Sherlock,
Maigret,
Custom,
}
impl Source {
/// Built-in databases that ship inside the binary, in load order.
pub const BUILTIN: [Source; 4] = [
Source::Wmn,
Source::Sherlock,
Source::Maigret,
Source::Percival,
];
pub fn as_str(self) -> &'static str {
match self {
Source::Percival => "percival",
Source::Wmn => "wmn",
Source::Sherlock => "sherlock",
Source::Maigret => "maigret",
Source::Custom => "custom",
}
}
/// Lower wins when two sources describe the same site.
pub fn priority(self) -> u8 {
match self {
Source::Custom => 0,
Source::Percival => 1,
Source::Wmn => 2,
Source::Sherlock => 3,
Source::Maigret => 4,
}
}
pub fn upstream_name(self) -> &'static str {
match self {
Source::Percival => "Percival",
Source::Wmn => "WhatsMyName",
Source::Sherlock => "Sherlock",
Source::Maigret => "Maigret",
Source::Custom => "custom file",
}
}
}
impl fmt::Display for Source {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
impl FromStr for Source {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.trim().to_ascii_lowercase().as_str() {
"wmn" | "whatsmyname" => Ok(Source::Wmn),
"sherlock" => Ok(Source::Sherlock),
"maigret" => Ok(Source::Maigret),
"percival" => Ok(Source::Percival),
"custom" => Ok(Source::Custom),
other => Err(format!(
"unknown source '{other}' (expected wmn, sherlock, maigret, percival, custom)"
)),
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum HttpMethod {
#[default]
Get,
Post,
Head,
Put,
}
impl HttpMethod {
pub fn as_str(self) -> &'static str {
match self {
HttpMethod::Get => "GET",
HttpMethod::Post => "POST",
HttpMethod::Head => "HEAD",
HttpMethod::Put => "PUT",
}
}
pub fn parse_loose(s: &str) -> Option<Self> {
match s.trim().to_ascii_uppercase().as_str() {
"GET" => Some(HttpMethod::Get),
"POST" => Some(HttpMethod::Post),
"HEAD" => Some(HttpMethod::Head),
"PUT" => Some(HttpMethod::Put),
_ => None,
}
}
}
/// How a response is interpreted. Each variant mirrors the semantics of the
/// database it was born in, so upstream data behaves exactly as upstream
/// tools expect it to.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum Detector {
/// WhatsMyName: exact status + substring for both the "exists" and the
/// "missing" branch.
CodeAndString {
e_code: u16,
#[serde(default)]
e_string: String,
m_code: u16,
#[serde(default)]
m_string: String,
},
/// Sherlock / Maigret "message": any absence marker → missing, all
/// presence markers → found. Without presence markers a 2xx response
/// that lacks the absence marker counts as found.
Message {
#[serde(default)]
absence: Vec<String>,
#[serde(default)]
presence: Vec<String>,
},
/// Sherlock "status_code": 2xx → found, configured codes / 404 → missing.
/// Redirects are not followed.
StatusCode {
#[serde(default)]
error_codes: Vec<u16>,
},
/// Sherlock "response_url": a redirect means missing.
ResponseUrl {
#[serde(default)]
error_url: Option<String>,
},
}
impl Default for Detector {
fn default() -> Self {
Detector::StatusCode {
error_codes: Vec::new(),
}
}
}
impl Detector {
pub fn kind(&self) -> &'static str {
match self {
Detector::CodeAndString { .. } => "code+string",
Detector::Message { .. } => "message",
Detector::StatusCode { .. } => "status",
Detector::ResponseUrl { .. } => "redirect",
}
}
/// One-line human description, used by `percival sites --show`.
pub fn describe(&self) -> String {
match self {
Detector::CodeAndString {
e_code,
e_string,
m_code,
m_string,
} => format!(
"found: HTTP {e_code} + {:?}; missing: HTTP {m_code} + {:?}",
util::truncate(e_string, 40),
util::truncate(m_string, 40)
),
Detector::Message { absence, presence } => format!(
"missing if any of {:?}; found if all of {:?}",
absence
.iter()
.map(|s| util::truncate(s, 30))
.collect::<Vec<_>>(),
presence
.iter()
.map(|s| util::truncate(s, 30))
.collect::<Vec<_>>()
),
Detector::StatusCode { error_codes } => {
if error_codes.is_empty() {
"found on 2xx, missing on 404/3xx".to_string()
} else {
format!("found on 2xx, missing on {error_codes:?}")
}
}
Detector::ResponseUrl { error_url } => match error_url {
Some(u) => format!("missing when redirected to {u}"),
None => "missing when redirected".to_string(),
},
}
}
}
/// A single site check definition.
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct Site {
pub name: String,
pub source: Source,
pub category: String,
pub tags: Vec<String>,
/// URL template that is actually requested. Placeholder: `{account}`.
pub url: String,
/// Human-facing profile URL template, if different from `url`.
pub pretty_url: Option<String>,
/// Site home page.
pub home: Option<String>,
pub method: HttpMethod,
/// Request body template (POST/PUT).
pub body: Option<String>,
pub headers: Vec<(String, String)>,
/// Characters removed from the account before substitution.
pub strip_chars: Option<String>,
/// Regex a username must satisfy to be valid on this site.
pub username_regex: Option<String>,
pub follow_redirects: bool,
pub detector: Detector,
/// Body markers that indicate a site-specific error (marker → reason).
pub errors: Vec<(String, String)>,
/// Usernames known to exist (used by self-check).
pub known: Vec<String>,
/// A username known not to exist.
pub unclaimed: Option<String>,
pub nsfw: bool,
/// Bot-protection hints from upstream (cloudflare, tls_fingerprint, …).
pub protection: Vec<String>,
pub disabled: bool,
pub disabled_reason: Option<String>,
/// Popularity rank (lower is more popular).
pub rank: Option<u32>,
/// Identifier type the site accepts: `username`, `email`, `steam_id`, …
pub id_type: String,
pub ignore_403: bool,
/// Charset override for response decoding.
pub encoding: Option<String>,
/// Other databases' definitions of the same site, used as fallback probes.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub alternates: Vec<Site>,
#[serde(skip)]
pub compiled_regex: Option<Regex>,
}
impl Default for Site {
fn default() -> Self {
Site {
name: String::new(),
source: Source::Custom,
category: "misc".to_string(),
tags: Vec::new(),
url: String::new(),
pretty_url: None,
home: None,
method: HttpMethod::Get,
body: None,
headers: Vec::new(),
strip_chars: None,
username_regex: None,
follow_redirects: true,
detector: Detector::default(),
errors: Vec::new(),
known: Vec::new(),
unclaimed: None,
nsfw: false,
protection: Vec::new(),
disabled: false,
disabled_reason: None,
rank: None,
id_type: "username".to_string(),
ignore_403: false,
encoding: None,
alternates: Vec::new(),
compiled_regex: None,
}
}
}
impl Site {
/// Normalise fields and compile the username regex. Called once after load.
pub fn finalize(&mut self) {
self.category = self.category.trim().to_ascii_lowercase();
if self.category.is_empty() {
self.category = "misc".to_string();
}
if self.id_type.trim().is_empty() {
self.id_type = "username".to_string();
}
self.url = normalize_placeholders(&self.url);
self.pretty_url = self.pretty_url.as_deref().map(normalize_placeholders);
self.body = self.body.as_deref().map(normalize_placeholders);
let mut tags: Vec<String> = self
.tags
.iter()
.map(|t| t.trim().to_ascii_lowercase())
.filter(|t| !t.is_empty())
.collect();
if !tags.contains(&self.category) {
tags.push(self.category.clone());
}
if self.nsfw && !tags.iter().any(|t| t == "nsfw") {
tags.push("nsfw".to_string());
}
tags.sort();
tags.dedup();
self.tags = tags;
self.compiled_regex = self
.username_regex
.as_deref()
.filter(|r| !r.trim().is_empty())
.and_then(|r| Regex::new(r).ok());
}
/// Apply `strip_chars` to the raw account.
pub fn prepare_account(&self, raw: &str) -> String {
match &self.strip_chars {
Some(chars) if !chars.is_empty() => {
raw.chars().filter(|c| !chars.contains(*c)).collect()
}
_ => raw.to_string(),
}
}
/// Whether the account satisfies the site's username rules.
pub fn accepts(&self, account: &str) -> bool {
match &self.compiled_regex {
Some(re) => re.is_match(account),
None => true,
}
}
pub fn probe_url(&self, account: &str) -> String {
render_url(&self.url, account)
}
pub fn display_template(&self) -> &str {
self.pretty_url.as_deref().unwrap_or(&self.url)
}
pub fn display_url(&self, account: &str) -> String {
render_url(self.display_template(), account)
}
/// Bare host of the human-facing URL (no `www.`, no account subdomain).
pub fn host(&self) -> String {
util::bare_host(self.display_template()).unwrap_or_default()
}
/// Bare host of the probe URL.
pub fn probe_host(&self) -> String {
util::bare_host(&self.url).unwrap_or_default()
}
/// Host used for per-host concurrency limiting (template form).
pub fn limiter_key(&self) -> String {
util::host_of(&self.url).unwrap_or_default()
}
pub fn is_email(&self) -> bool {
self.id_type == "email"
}
/// Value of the Content-Type request header, if any.
pub fn content_type(&self) -> Option<&str> {
self.headers
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case("content-type"))
.map(|(_, v)| v.as_str())
}
/// Key used to detect the same site described by several databases.
pub fn dedupe_key(&self) -> String {
normalize_key(self.display_template())
}
pub fn probe_key(&self) -> String {
normalize_key(&self.url)
}
}
fn normalize_key(template: &str) -> String {
let t = normalize_placeholders(template).to_ascii_lowercase();
let t = t.split("://").nth(1).unwrap_or(&t).to_string();
let t = t.strip_prefix("www.").map(str::to_string).unwrap_or(t);
t.trim_end_matches('/').to_string()
}
/// Map every upstream placeholder spelling onto `{account}`.
pub fn normalize_placeholders(t: &str) -> String {
t.replace("{}", "{account}")
.replace("{username}", "{account}")
.replace("{email}", "{account}")
}
fn replace_placeholders(template: &str, encoded: &str, raw: &str) -> String {
let mut out = template.replace("{account}", encoded);
if out.contains("{account_lower}") {
out = out.replace("{account_lower}", &encoded.to_ascii_lowercase());
}
if out.contains("{email_md5}") {
out = out.replace("{email_md5}", &util::md5_hex_normalized(raw));
}
out
}
/// Substitute the account into a URL template (percent-encoded).
pub fn render_url(template: &str, account: &str) -> String {
replace_placeholders(template, &util::percent_encode_account(account), account)
}
/// Substitute the account into a request body, escaping for the body type.
pub fn render_body(template: &str, account: &str, content_type: Option<&str>) -> String {
let ct = content_type.unwrap_or("").to_ascii_lowercase();
let looks_json =
template.trim_start().starts_with('{') || template.trim_start().starts_with('[');
let encoded = if ct.contains("json") || (looks_json && !ct.contains("form")) {
util::json_escape(account)
} else if ct.contains("x-www-form-urlencoded") || (!looks_json && template.contains('=')) {
util::form_encode(account)
} else {
account.to_string()
};
replace_placeholders(template, &encoded, account)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn renders_templates() {
assert_eq!(
render_url("https://x.com/{account}", "a b"),
"https://x.com/a%20b"
);
assert_eq!(render_url("https://x.com/{}", "ab"), "https://x.com/{}"); // not normalized here
assert_eq!(
render_body("{\"u\":\"{account}\"}", "a\"b", Some("application/json")),
"{\"u\":\"a\\\"b\"}"
);
assert_eq!(
render_body(
"user={account}",
"a&b",
Some("application/x-www-form-urlencoded")
),
"user=a%26b"
);
assert_eq!(
render_url("https://g.com/{email_md5}.json", "X@Y.com"),
format!("https://g.com/{}.json", util::md5_hex_normalized("x@y.com"))
);
}
#[test]
fn site_helpers() {
let mut s = Site {
name: "T".into(),
url: "https://api.example.com/users/{username}".into(),
pretty_url: Some("https://www.Example.com/{}/".into()),
strip_chars: Some(".".into()),
username_regex: Some("^[a-z]+$".into()),
category: "Social".into(),
nsfw: true,
..Default::default()
};
s.finalize();
assert_eq!(s.url, "https://api.example.com/users/{account}");
assert_eq!(s.dedupe_key(), "example.com/{account}");
assert_eq!(s.probe_key(), "api.example.com/users/{account}");
assert_eq!(s.host(), "example.com");
assert_eq!(s.prepare_account("a.b.c"), "abc");
assert!(s.accepts("abc"));
assert!(!s.accepts("abc1"));
assert_eq!(s.category, "social");
assert!(s.tags.contains(&"nsfw".to_string()));
assert!(s.tags.contains(&"social".to_string()));
}
}