a3s-search 0.5.0

Embeddable meta search engine library with CLI and proxy pool support
Documentation
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
//! A3S Search CLI - Meta search engine command line interface.

use std::time::Duration;

use anyhow::Result;
use clap::{Parser, Subcommand, ValueEnum};
use tracing::Level;
use tracing_subscriber::FmtSubscriber;

use a3s_search::{
    engines::{Brave, DuckDuckGo, So360, Sogou, Wikipedia},
    proxy::{ProxyConfig, ProxyPool, ProxyProtocol},
    Search, SearchQuery,
};

#[cfg(feature = "headless")]
use a3s_search::{
    browser::{BrowserFetcher, BrowserPool, BrowserPoolConfig},
    engines::{Baidu, BingChina, Google},
    PageFetcher, WaitStrategy,
};

/// A3S Search - Embeddable meta search engine CLI
#[derive(Parser)]
#[command(name = "a3s-search")]
#[command(author, version, about, long_about = None)]
struct Cli {
    /// Search query (if no subcommand is provided)
    query: Option<String>,

    /// Search engines to use (comma-separated)
    /// Available: ddg, brave, wiki, sogou, 360
    #[arg(short, long, value_delimiter = ',')]
    engines: Option<Vec<String>>,

    /// Maximum number of results to display
    #[arg(short, long, default_value = "10")]
    limit: usize,

    /// Search timeout in seconds
    #[arg(short, long, default_value = "10")]
    timeout: u64,

    /// Output format
    #[arg(short, long, default_value = "text")]
    format: OutputFormat,

    /// Proxy URL (e.g., http://127.0.0.1:8080 or socks5://127.0.0.1:1080)
    #[arg(short, long)]
    proxy: Option<String>,

    /// Use headless browser for JS-rendered engines (e.g., Google)
    #[arg(long)]
    headless: bool,

    /// Enable verbose output
    #[arg(short, long)]
    verbose: bool,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// List available search engines
    Engines,
    /// Update a3s-search to the latest version
    Update,
}

#[derive(Clone, Copy, ValueEnum, Debug)]
enum OutputFormat {
    /// Human-readable text output
    Text,
    /// JSON output
    Json,
    /// Compact single-line output
    Compact,
}

#[tokio::main]
async fn main() -> Result<()> {
    let cli = Cli::parse();

    // Setup logging
    if cli.verbose {
        let subscriber = FmtSubscriber::builder()
            .with_max_level(Level::DEBUG)
            .finish();
        tracing::subscriber::set_global_default(subscriber)?;
    }

    match cli.command {
        Some(Commands::Engines) => list_engines(),
        Some(Commands::Update) => {
            a3s_updater::run_update(&a3s_updater::UpdateConfig {
                binary_name: "a3s-search",
                crate_name: "a3s-search",
                current_version: env!("CARGO_PKG_VERSION"),
                github_owner: "A3S-Lab",
                github_repo: "Search",
            })
            .await
        }
        None => {
            if let Some(query) = cli.query {
                run_search(SearchArgs {
                    query,
                    engines: cli.engines,
                    limit: cli.limit,
                    timeout: cli.timeout,
                    format: cli.format,
                    proxy: cli.proxy,
                    headless: cli.headless,
                })
                .await
            } else {
                // No query provided, show help
                println!("A3S Search - Meta search engine CLI\n");
                println!("Usage: a3s-search <QUERY> [OPTIONS]");
                println!("       a3s-search engines\n");
                println!("Examples:");
                println!("  a3s-search \"Rust programming\"");
                println!("  a3s-search \"Rust\" -e ddg,wiki -l 5");
                println!("  a3s-search \"Rust\" -f json");
                println!("  a3s-search \"Rust\" -p http://127.0.0.1:8080\n");
                println!("Options:");
                println!("  -e, --engines <ENGINES>  Engines: ddg,brave,wiki,sogou,360,g,baidu,bing_cn");
                println!("  -l, --limit <N>          Max results (default: 10)");
                println!("  -t, --timeout <SECS>     Timeout in seconds (default: 10)");
                println!("  -f, --format <FORMAT>    Output: text, json, compact");
                println!("  -p, --proxy <URL>        Proxy URL (http/https/socks5)");
                println!("  --headless               Use headless browser for JS engines");
                println!("  -v, --verbose            Enable debug logging");
                println!("  -h, --help               Show help");
                println!("  -V, --version            Show version\n");
                println!("Run 'a3s-search engines' to list all available engines.");
                Ok(())
            }
        }
    }
}

struct SearchArgs {
    query: String,
    engines: Option<Vec<String>>,
    limit: usize,
    timeout: u64,
    format: OutputFormat,
    proxy: Option<String>,
    headless: bool,
}

fn list_engines() -> Result<()> {
    println!("Available search engines:\n");
    println!("  International:");
    println!("    ddg      - DuckDuckGo (privacy-focused search)");
    println!("    brave    - Brave Search");
    println!("    wiki     - Wikipedia");
    println!();
    println!("  Chinese:");
    println!("    sogou    - Sogou (搜狗)");
    println!("    360      - 360 Search (360搜索)");

    #[cfg(feature = "headless")]
    {
        println!();
        println!("  Headless (requires --headless flag):");
        println!("    g        - Google (requires Chrome/Chromium)");
        println!("    baidu    - Baidu (百度, requires Chrome/Chromium)");
        println!("    bing_cn  - Bing China (必应中国, requires Chrome/Chromium)");
    }

    println!();
    println!("Usage: a3s-search \"query\" -e ddg,wiki,sogou");
    Ok(())
}

async fn run_search(args: SearchArgs) -> Result<()> {
    let mut search = Search::new();
    search.set_timeout(Duration::from_secs(args.timeout));

    // Setup proxy if provided
    if let Some(proxy_url) = &args.proxy {
        let proxy_config = parse_proxy_url(proxy_url)?;
        let proxy_pool = ProxyPool::with_proxies(vec![proxy_config]);
        search.set_proxy_pool(proxy_pool);
        if matches!(args.format, OutputFormat::Text) {
            eprintln!("Using proxy: {}", proxy_url);
        }
    }

    // Warn if --headless is passed without the feature
    #[cfg(not(feature = "headless"))]
    if args.headless {
        eprintln!(
            "Warning: --headless flag requires the 'headless' feature. \
             Rebuild with: cargo build --features headless"
        );
    }

    // Setup headless browser fetcher if requested
    #[cfg(feature = "headless")]
    let browser_fetcher: Option<std::sync::Arc<dyn PageFetcher>> = if args.headless {
        let pool_config = BrowserPoolConfig {
            proxy_url: args.proxy.clone(),
            ..Default::default()
        };
        let pool = std::sync::Arc::new(BrowserPool::new(pool_config));
        Some(std::sync::Arc::new(
            BrowserFetcher::new(pool).with_wait(WaitStrategy::Selector {
                css: "div.g".to_string(),
                timeout_ms: 5000,
            }),
        ))
    } else {
        None
    };

    // Add engines based on selection
    let engine_shortcuts: Vec<String> = args
        .engines
        .unwrap_or_else(|| vec!["ddg".to_string(), "wiki".to_string()]);

    for shortcut in &engine_shortcuts {
        match shortcut.as_str() {
            "ddg" | "duckduckgo" => search.add_engine(DuckDuckGo::new()),
            "brave" => search.add_engine(Brave::new()),
            "wiki" | "wikipedia" => search.add_engine(Wikipedia::new()),
            "sogou" => search.add_engine(Sogou::new()),
            "360" | "so360" => search.add_engine(So360::new()),
            #[cfg(feature = "headless")]
            "g" | "google" => {
                if let Some(ref fetcher) = browser_fetcher {
                    search.add_engine(Google::new(std::sync::Arc::clone(fetcher)));
                } else {
                    eprintln!(
                        "Warning: Google engine requires --headless flag, skipping"
                    );
                }
            }
            #[cfg(feature = "headless")]
            "baidu" => {
                if let Some(ref fetcher) = browser_fetcher {
                    search.add_engine(Baidu::new(std::sync::Arc::clone(fetcher)));
                } else {
                    eprintln!(
                        "Warning: Baidu engine requires --headless flag, skipping"
                    );
                }
            }
            #[cfg(feature = "headless")]
            "bing_cn" | "bing" => {
                if let Some(ref fetcher) = browser_fetcher {
                    search.add_engine(BingChina::new(std::sync::Arc::clone(fetcher)));
                } else {
                    eprintln!(
                        "Warning: Bing China engine requires --headless flag, skipping"
                    );
                }
            }
            #[cfg(not(feature = "headless"))]
            "g" | "google" | "baidu" | "bing_cn" | "bing" => {
                eprintln!(
                    "Warning: '{}' engine requires the 'headless' feature. \
                     Rebuild with: cargo build --features headless",
                    shortcut
                );
            }
            _ => {
                eprintln!("Warning: Unknown engine '{}', skipping", shortcut);
            }
        }
    }

    if search.engine_count() == 0 {
        anyhow::bail!("No valid engines specified");
    }

    // Perform search
    let query = SearchQuery::new(&args.query);
    let results = search.search(query).await?;

    // Output results
    match args.format {
        OutputFormat::Text => {
            println!(
                "\nSearch results for \"{}\" ({} results in {}ms):\n",
                args.query, results.count, results.duration_ms
            );

            for (i, result) in results.items().iter().take(args.limit).enumerate() {
                println!("{}. {}", i + 1, result.title);
                println!("   URL: {}", result.url);
                if !result.content.is_empty() {
                    let content = if result.content.len() > 150 {
                        format!("{}...", &result.content[..150])
                    } else {
                        result.content.clone()
                    };
                    println!("   {}", content);
                }
                println!(
                    "   Engines: {:?} | Score: {:.2}",
                    result.engines, result.score
                );
                println!();
            }
        }
        OutputFormat::Json => {
            let output: Vec<_> = results.items().iter().take(args.limit).collect();
            println!("{}", serde_json::to_string_pretty(&output)?);
        }
        OutputFormat::Compact => {
            for result in results.items().iter().take(args.limit) {
                println!("{}\t{}", result.title, result.url);
            }
        }
    }

    Ok(())
}

fn parse_proxy_url(url: &str) -> Result<ProxyConfig> {
    let url = url::Url::parse(url)?;

    let protocol = match url.scheme() {
        "http" => ProxyProtocol::Http,
        "https" => ProxyProtocol::Https,
        "socks5" => ProxyProtocol::Socks5,
        scheme => anyhow::bail!("Unsupported proxy protocol: {}", scheme),
    };

    let host = url
        .host_str()
        .ok_or_else(|| anyhow::anyhow!("Missing proxy host"))?;
    let port = url.port().unwrap_or(match protocol {
        ProxyProtocol::Http => 8080,
        ProxyProtocol::Https => 443,
        ProxyProtocol::Socks5 => 1080,
    });

    let mut config = ProxyConfig::new(host, port).with_protocol(protocol);

    if let Some(password) = url.password() {
        config = config.with_auth(url.username(), password);
    }

    Ok(config)
}

#[cfg(test)]
mod tests {
    use super::*;
    use clap::CommandFactory;

    #[test]
    fn test_cli_parse_help() {
        // Verify CLI structure is valid
        Cli::command().debug_assert();
    }

    #[test]
    fn test_parse_proxy_url_http() {
        let config = parse_proxy_url("http://127.0.0.1:8080").unwrap();
        assert_eq!(config.host, "127.0.0.1");
        assert_eq!(config.port, 8080);
        assert_eq!(config.protocol, ProxyProtocol::Http);
        assert!(config.username.is_none());
        assert!(config.password.is_none());
    }

    #[test]
    fn test_parse_proxy_url_https() {
        let config = parse_proxy_url("https://proxy.example.com:443").unwrap();
        assert_eq!(config.host, "proxy.example.com");
        assert_eq!(config.port, 443);
        assert_eq!(config.protocol, ProxyProtocol::Https);
    }

    #[test]
    fn test_parse_proxy_url_socks5() {
        let config = parse_proxy_url("socks5://localhost:1080").unwrap();
        assert_eq!(config.host, "localhost");
        assert_eq!(config.port, 1080);
        assert_eq!(config.protocol, ProxyProtocol::Socks5);
    }

    #[test]
    fn test_parse_proxy_url_with_auth() {
        let config = parse_proxy_url("http://user:pass@127.0.0.1:8080").unwrap();
        assert_eq!(config.host, "127.0.0.1");
        assert_eq!(config.port, 8080);
        assert_eq!(config.username, Some("user".to_string()));
        assert_eq!(config.password, Some("pass".to_string()));
    }

    #[test]
    fn test_parse_proxy_url_default_http_port() {
        let config = parse_proxy_url("http://127.0.0.1").unwrap();
        assert_eq!(config.port, 8080);
    }

    #[test]
    fn test_parse_proxy_url_default_socks5_port() {
        let config = parse_proxy_url("socks5://127.0.0.1").unwrap();
        assert_eq!(config.port, 1080);
    }

    #[test]
    fn test_parse_proxy_url_unsupported_protocol() {
        let result = parse_proxy_url("ftp://127.0.0.1:21");
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(err.contains("Unsupported proxy protocol"));
    }

    #[test]
    fn test_parse_proxy_url_invalid_url() {
        let result = parse_proxy_url("not-a-valid-url");
        assert!(result.is_err());
    }

    #[test]
    fn test_output_format_values() {
        // Test that all output formats can be created
        let _text = OutputFormat::Text;
        let _json = OutputFormat::Json;
        let _compact = OutputFormat::Compact;
    }

    #[test]
    fn test_cli_with_query() {
        let cli = Cli::parse_from(["a3s-search", "test query"]);
        assert_eq!(cli.query, Some("test query".to_string()));
        assert!(cli.engines.is_none());
        assert_eq!(cli.limit, 10);
        assert_eq!(cli.timeout, 10);
        assert!(cli.proxy.is_none());
        assert!(!cli.verbose);
    }

    #[test]
    fn test_cli_with_engines() {
        let cli = Cli::parse_from(["a3s-search", "query", "-e", "ddg,wiki"]);
        assert_eq!(
            cli.engines,
            Some(vec!["ddg".to_string(), "wiki".to_string()])
        );
    }

    #[test]
    fn test_cli_with_limit() {
        let cli = Cli::parse_from(["a3s-search", "query", "-l", "5"]);
        assert_eq!(cli.limit, 5);
    }

    #[test]
    fn test_cli_with_timeout() {
        let cli = Cli::parse_from(["a3s-search", "query", "-t", "30"]);
        assert_eq!(cli.timeout, 30);
    }

    #[test]
    fn test_cli_with_format_json() {
        let cli = Cli::parse_from(["a3s-search", "query", "-f", "json"]);
        assert!(matches!(cli.format, OutputFormat::Json));
    }

    #[test]
    fn test_cli_with_format_compact() {
        let cli = Cli::parse_from(["a3s-search", "query", "-f", "compact"]);
        assert!(matches!(cli.format, OutputFormat::Compact));
    }

    #[test]
    fn test_cli_with_proxy() {
        let cli = Cli::parse_from(["a3s-search", "query", "-p", "http://127.0.0.1:8080"]);
        assert_eq!(cli.proxy, Some("http://127.0.0.1:8080".to_string()));
    }

    #[test]
    fn test_cli_with_verbose() {
        let cli = Cli::parse_from(["a3s-search", "query", "-v"]);
        assert!(cli.verbose);
    }

    #[test]
    fn test_cli_all_options() {
        let cli = Cli::parse_from([
            "a3s-search",
            "rust programming",
            "-e",
            "ddg,wiki,sogou",
            "-l",
            "20",
            "-t",
            "15",
            "-f",
            "json",
            "-p",
            "socks5://localhost:1080",
            "-v",
        ]);
        assert_eq!(cli.query, Some("rust programming".to_string()));
        assert_eq!(
            cli.engines,
            Some(vec![
                "ddg".to_string(),
                "wiki".to_string(),
                "sogou".to_string()
            ])
        );
        assert_eq!(cli.limit, 20);
        assert_eq!(cli.timeout, 15);
        assert!(matches!(cli.format, OutputFormat::Json));
        assert_eq!(cli.proxy, Some("socks5://localhost:1080".to_string()));
        assert!(cli.verbose);
    }

    #[test]
    fn test_cli_engines_subcommand() {
        let cli = Cli::parse_from(["a3s-search", "engines"]);
        assert!(matches!(cli.command, Some(Commands::Engines)));
    }

    #[test]
    fn test_cli_no_args() {
        let cli = Cli::parse_from(["a3s-search"]);
        assert!(cli.query.is_none());
        assert!(cli.command.is_none());
    }

    #[test]
    fn test_cli_with_headless() {
        let cli = Cli::parse_from(["a3s-search", "query", "--headless"]);
        assert!(cli.headless);
    }

    #[test]
    fn test_cli_headless_default_false() {
        let cli = Cli::parse_from(["a3s-search", "query"]);
        assert!(!cli.headless);
    }

    #[test]
    fn test_cli_headless_with_google_engine() {
        let cli = Cli::parse_from(["a3s-search", "query", "-e", "g,ddg", "--headless"]);
        assert!(cli.headless);
        assert_eq!(
            cli.engines,
            Some(vec!["g".to_string(), "ddg".to_string()])
        );
    }
}