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
misc.rsRust178 lines5.6 KiBraw download
//! `permute`, `parse`, `config`, `completions`.

use anyhow::Result;
use clap::CommandFactory;

use crate::cli::{Cli, ConfigArgs, ParseArgs, PermuteArgs};
use crate::config;
use crate::db::{HttpMethod, Site};
use crate::engine::http::{Prepared, build_client, fetch};
use crate::extract;
use crate::permute;
use crate::settings::Settings;
use crate::ui::kv_block;

pub fn run_permute(settings: &Settings, args: &PermuteArgs) -> Result<i32> {
    let t = settings.theme;
    for name in &args.names {
        let list = permute::permute(name, args.all, args.max.unwrap_or(64));
        if args.names.len() > 1 {
            eprintln!("{}", t.heading(format!("# {name}")));
        }
        for p in list {
            println!("{p}");
        }
    }
    Ok(0)
}

pub async fn run_parse(settings: &Settings, args: &ParseArgs) -> Result<i32> {
    let t = settings.theme;
    let client = if args.fetch {
        Some(build_client(&settings.client_options(&args.net)?)?)
    } else {
        None
    };
    let mut any = false;
    let mut out_json = Vec::new();
    for url in &args.urls {
        let pivot = extract::links::handle_from_url(url);
        let mut profile = None;
        if let Some(client) = &client {
            let req = Prepared {
                method: HttpMethod::Get,
                url: url.clone(),
                headers: Vec::new(),
                body: None,
                follow_redirects: true,
                encoding: None,
            };
            match fetch(client, &req, 3 * 1024 * 1024, None).await {
                Ok(ex) => {
                    let host = crate::util::bare_host(url).unwrap_or_default();
                    let site = Site {
                        name: host.clone(),
                        url: url.clone(),
                        ..Default::default()
                    };
                    profile = extract::extract(
                        &site,
                        &ex,
                        pivot.as_ref().map(|p| p.handle.as_str()).unwrap_or(""),
                    );
                }
                Err(e) => eprintln!("{} {url}: {e}", t.error("✖")),
            }
        }
        any |= pivot.is_some() || profile.is_some();
        if args.json {
            out_json.push(serde_json::json!({"url": url, "host": pivot.as_ref().map(|p| p.host.clone()), "handle": pivot.as_ref().map(|p| p.handle.clone()), "numeric": pivot.as_ref().map(|p| p.numeric), "profile": profile}));
            continue;
        }
        println!("{}", t.link(url));
        match &pivot {
            Some(p) => println!(
                "  {} {} {}",
                t.subtle("handle"),
                t.bold(t.accent(&p.handle)),
                t.dim(format!(
                    "on {}{}",
                    p.host,
                    if p.numeric { " (numeric id)" } else { "" }
                ))
            ),
            None => println!("  {}", t.dim("no handle pattern recognised for this host")),
        }
        if let Some(p) = &profile {
            let pairs: Vec<(&str, String)> = p.fields();
            if !pairs.is_empty() {
                println!("{}", kv_block(&t, &pairs));
            }
            if !p.links.is_empty() {
                println!(
                    "  {} {}",
                    t.subtle("links"),
                    p.links
                        .iter()
                        .map(|l| t.link(l))
                        .collect::<Vec<_>>()
                        .join(" ")
                );
            }
            if !p.handles.is_empty() {
                println!(
                    "  {} {}",
                    t.subtle("handles"),
                    p.handles
                        .iter()
                        .map(|h| t.accent(h))
                        .collect::<Vec<_>>()
                        .join(" ")
                );
            }
        }
    }
    if args.json {
        println!("{}", serde_json::to_string_pretty(&out_json)?);
    }
    Ok(if any { 0 } else { 1 })
}

pub fn run_config(
    settings: &Settings,
    args: &ConfigArgs,
    explicit: Option<&std::path::PathBuf>,
) -> Result<i32> {
    let t = settings.theme;
    let path = explicit.cloned().unwrap_or_else(config::config_path);
    if args.path {
        println!("{}", path.display());
        return Ok(0);
    }
    if args.init {
        if config::write_template(&path)? {
            println!("{} wrote {}", t.found("✔"), path.display());
        } else {
            println!("{} {} already exists", t.warn("!"), path.display());
        }
        return Ok(0);
    }
    println!(
        "{} {}",
        t.subtle("config file:"),
        if path.is_file() {
            t.link(path.display())
        } else {
            t.dim(format!(
                "{} (missing — run `percival config --init`)",
                path.display()
            ))
        }
    );
    println!(
        "{} {}",
        t.subtle("data dir:   "),
        t.link(settings.data_dir.display())
    );
    println!(
        "{} {} ({})",
        t.subtle("theme:      "),
        settings.theme.variant.name(),
        match settings.theme.mode {
            crate::ui::ColorMode::None => "no colour",
            crate::ui::ColorMode::Ansi256 => "256 colours",
            crate::ui::ColorMode::Truecolor => "truecolor",
        }
    );
    if path.is_file() {
        println!("{}", t.rule(40));
        print!("{}", std::fs::read_to_string(&path)?);
    }
    Ok(0)
}

pub fn run_completions(shell: clap_complete::Shell) -> Result<i32> {
    let mut cmd = Cli::command();
    clap_complete::generate(shell, &mut cmd, crate::NAME, &mut std::io::stdout());
    Ok(0)
}