File size: 2,175 Bytes
0ca462b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
pub mod arxiv;
pub mod bing;
pub mod bing_news;
pub mod brave;
pub mod ddg_news;
pub mod duckduckgo;
pub mod gdelt;
pub mod github;
pub mod google;
pub mod google_news;
pub mod invidious;
pub mod librex;
pub mod medium;
pub mod mojeek;
pub mod reddit;
pub mod searx;
pub mod startpage;
pub mod whoogle;

use crate::meta_search::models::SearchResult;
use crate::meta_search::proxy_manager::ProxyManager;
use crate::meta_search::tor::TorManager;
use anyhow::Result;
use async_trait::async_trait;
use reqwest::Client;
use std::sync::Arc;
use std::time::Duration;

#[allow(dead_code)]
pub struct SearchContext {
    pub proxy_manager: Arc<ProxyManager>,
    pub tor_manager: Option<Arc<TorManager>>,
}

/// Build an HTTP client with the best available transport.
/// Priority: Tor > Public Proxy > Direct
pub async fn build_client_with_transport(ctx: &SearchContext, timeout_secs: u64) -> Result<Client> {
    let ua = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36 IntentForge/0.1";

    // Try Tor first
    if let Some(tor_mgr) = &ctx.tor_manager {
        if let Some(tor_client) = tor_mgr.get_client() {
            tracing::debug!("Using Tor transport for HTTP client");
            return Ok(tor_client.clone());
        }
    }

    // Try public proxy second
    if let Some(proxy) = ctx.proxy_manager.get_random_proxy().await {
        tracing::debug!("Using public proxy {} for HTTP client", proxy.to_url());
        let client = Client::builder()
            .user_agent(ua)
            .proxy(reqwest::Proxy::all(proxy.to_url())?)
            .timeout(Duration::from_secs(timeout_secs))
            .build()?;
        return Ok(client);
    }

    // Fall back to direct
    tracing::debug!("No Tor or proxy available, using direct transport");
    Ok(Client::builder()
        .user_agent(ua)
        .timeout(Duration::from_secs(timeout_secs))
        .build()?)
}

#[async_trait]
pub trait SearchProvider: Send + Sync {
    fn name(&self) -> &'static str;
    async fn search(&self, query: &str, ctx: Arc<SearchContext>) -> Result<Vec<SearchResult>>;
    fn as_any(&self) -> &dyn std::any::Any;
}