repositories

percival

Follow the trail a handle leaves across the web: username search across 5,700+ sites, in Rust

clonegit clone https://git.daemon-sec.xyz/percival.git
update.rsRust101 lines3.2 KiBraw download
//! Refresh the built-in databases from their upstream repositories.

use std::path::Path;

use anyhow::{Context, Result, bail};
use reqwest::Client;
use serde::Serialize;

use crate::db::{Source, cache_path, parse_any};

pub fn upstream_url(source: Source) -> Option<&'static str> {
    match source {
        Source::Wmn => {
            Some("https://raw.githubusercontent.com/WebBreacher/WhatsMyName/main/wmn-data.json")
        }
        Source::Sherlock => Some(
            "https://raw.githubusercontent.com/sherlock-project/sherlock/master/sherlock_project/resources/data.json",
        ),
        Source::Maigret => {
            Some("https://raw.githubusercontent.com/soxoj/maigret/main/maigret/resources/data.json")
        }
        Source::Percival | Source::Custom => None,
    }
}

#[derive(Clone, Debug, Serialize)]
pub struct UpdateOutcome {
    pub source: Source,
    pub url: String,
    pub path: String,
    pub sites: usize,
    pub bytes: usize,
    pub changed: bool,
}

/// Download one database, validate it and store it in the data directory.
pub async fn update_source(
    client: &Client,
    data_dir: &Path,
    source: Source,
) -> Result<UpdateOutcome> {
    let url = upstream_url(source).with_context(|| format!("{source} has no upstream"))?;
    let resp = client
        .get(url)
        .send()
        .await
        .with_context(|| format!("fetching {url}"))?;
    if !resp.status().is_success() {
        bail!("{url} returned HTTP {}", resp.status());
    }
    let text = resp.text().await.context("reading body")?;
    let (format, sites, _) =
        parse_any(&text).with_context(|| format!("validating downloaded {source} data"))?;
    if sites.is_empty() {
        bail!("downloaded {source} data ({format:?}) contains no sites");
    }
    let path = cache_path(data_dir, source);
    let changed = std::fs::read_to_string(&path)
        .map(|old| old != text)
        .unwrap_or(true);
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)
            .with_context(|| format!("creating {}", parent.display()))?;
    }
    std::fs::write(&path, &text).with_context(|| format!("writing {}", path.display()))?;
    Ok(UpdateOutcome {
        source,
        url: url.to_string(),
        path: path.display().to_string(),
        sites: sites.len(),
        bytes: text.len(),
        changed,
    })
}

/// Status of the cached copy of each built-in database.
/// (path, size in bytes, modified timestamp) of a cached database.
pub type CacheInfo = (String, u64, String);

pub fn cache_status(data_dir: &Path) -> Vec<(Source, Option<CacheInfo>)> {
    Source::BUILTIN
        .iter()
        .filter(|s| upstream_url(**s).is_some())
        .map(|s| {
            let p = cache_path(data_dir, *s);
            let info = std::fs::metadata(&p).ok().map(|m| {
                let modified = m
                    .modified()
                    .ok()
                    .map(|t| {
                        chrono::DateTime::<chrono::Local>::from(t)
                            .format("%Y-%m-%d %H:%M")
                            .to_string()
                    })
                    .unwrap_or_default();
                (p.display().to_string(), m.len(), modified)
            });
            (*s, info)
        })
        .collect()
}