Spaces:
Build error
Build error
File size: 5,124 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 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 | use crate::meta_search::proxy::{Proxy, ProxyProtocol};
use anyhow::Result;
use futures::future::join_all;
use rand::seq::SliceRandom;
use reqwest::Client;
use std::sync::Arc;
use std::time::Duration;
use tokio::sync::RwLock;
use tracing::{info, warn};
pub struct ProxyManager {
proxies: Arc<RwLock<Vec<Proxy>>>,
client: Client,
}
impl ProxyManager {
pub fn new() -> Self {
Self {
proxies: Arc::new(RwLock::new(Vec::new())),
client: Client::builder()
.timeout(Duration::from_secs(5))
.build()
.unwrap(),
}
}
/// Scrape proxies from public lists and validate them.
pub async fn scrape_proxies(&self) -> Result<()> {
info!("Scraping for new proxies...");
let sources = vec![
"https://raw.githubusercontent.com/TheSpeedX/SOCKS-List/master/socks5.txt",
"https://raw.githubusercontent.com/TheSpeedX/SOCKS-List/master/http.txt",
"https://raw.githubusercontent.com/ShiftyTR/Proxy-List/master/socks5.txt",
"https://raw.githubusercontent.com/ShiftyTR/Proxy-List/master/http.txt",
"https://raw.githubusercontent.com/monosans/proxy-list/main/proxies/socks5.txt",
"https://raw.githubusercontent.com/monosans/proxy-list/main/proxies/http.txt",
"https://raw.githubusercontent.com/hookzof/socks5_list/master/proxy.txt",
"https://raw.githubusercontent.com/roosterkid/openproxylist/main/SOCKS5_RAW.txt",
"https://raw.githubusercontent.com/roosterkid/openproxylist/main/HTTPS_RAW.txt",
"https://api.proxyscrape.com/v2/?request=displayproxies&protocol=socks5&timeout=10000&country=all&ssl=all&anonymity=all",
"https://api.proxyscrape.com/v2/?request=displayproxies&protocol=http&timeout=10000&country=all&ssl=all&anonymity=all",
];
let mut new_proxies = Vec::new();
for source in sources {
match self.client.get(source).send().await {
Ok(resp) => {
if let Ok(text) = resp.text().await {
let proto = if source.contains("socks5") {
ProxyProtocol::Socks5
} else {
ProxyProtocol::Http
};
for line in text.lines() {
let parts: Vec<&str> = line.split(':').collect();
if parts.len() == 2 {
if let Ok(port) = parts[1].parse::<u16>() {
new_proxies.push(Proxy::new(
parts[0].to_string(),
port,
proto.clone(),
));
}
}
}
}
}
Err(e) => warn!("Failed to fetch proxies from {}: {}", source, e),
}
}
info!(
"Scraped {} potential proxies. Starting validation...",
new_proxies.len()
);
self.validate_and_add(new_proxies).await;
Ok(())
}
async fn validate_and_add(&self, proxies: Vec<Proxy>) {
let to_check = proxies.into_iter().take(100).collect::<Vec<_>>();
let futures: Vec<_> = to_check
.into_iter()
.map(|mut proxy| async move {
let start = std::time::Instant::now();
let test_url = "http://www.google.com/generate_204";
let proxy_url = proxy.to_url();
match Client::builder()
.proxy(reqwest::Proxy::all(&proxy_url).ok()?)
.timeout(Duration::from_secs(8))
.build()
.ok()?
.get(test_url)
.send()
.await
{
Ok(resp) if resp.status().is_success() => {
proxy.is_working = true;
proxy.latency = Some(start.elapsed());
proxy.last_checked = Some(std::time::Instant::now());
Some(proxy)
}
_ => None,
}
})
.collect();
let results = join_all(futures).await;
let mut valid_proxies: Vec<Proxy> = results.into_iter().flatten().collect();
info!("Found {} working proxies", valid_proxies.len());
let mut current = self.proxies.write().await;
current.append(&mut valid_proxies);
}
/// Get a random working proxy for use in requests.
pub async fn get_random_proxy(&self) -> Option<Proxy> {
let proxies = self.proxies.read().await;
if proxies.is_empty() {
return None;
}
proxies.as_slice().choose(&mut rand::thread_rng()).cloned()
}
}
impl Default for ProxyManager {
fn default() -> Self {
Self::new()
}
}
|