beta 1.0
This commit is contained in:
commit
366a84fa89
24 files changed
+5303
No files matched your search
@@ -0,0 +1,16 @@
|
||||
"""WhereAmI 核心模块"""
|
||||
from .models import ProxyInfo, ProxyProtocol, ProxyStatus
|
||||
from .data_source import DataSource
|
||||
from .health_checker import HealthChecker
|
||||
from .proxy_manager import ProxyManager
|
||||
from .simple_proxy_forwarder import SimpleProxyForwarder
|
||||
|
||||
__all__ = [
|
||||
'ProxyInfo',
|
||||
'ProxyProtocol',
|
||||
'ProxyStatus',
|
||||
'DataSource',
|
||||
'HealthChecker',
|
||||
'ProxyManager',
|
||||
'SimpleProxyForwarder'
|
||||
]
|
||||
@@ -0,0 +1,219 @@
|
||||
"""代理数据源获取模块"""
|
||||
import requests
|
||||
from bs4 import BeautifulSoup
|
||||
import json
|
||||
import os
|
||||
from typing import List, Optional
|
||||
from datetime import datetime
|
||||
from loguru import logger
|
||||
from .models import ProxyInfo, ProxyProtocol
|
||||
|
||||
|
||||
class DataSource:
|
||||
"""代理数据源管理器"""
|
||||
|
||||
def __init__(self, config: dict):
|
||||
self.config = config
|
||||
self.logger = logger
|
||||
|
||||
def fetch_from_web(self, url: str, output_file: str = "proxy.json", pages: int = 1) -> List[ProxyInfo]:
|
||||
"""从网页获取代理列表并保存到文件
|
||||
|
||||
Args:
|
||||
url: 基础URL(不含页码参数)
|
||||
output_file: 输出文件路径
|
||||
pages: 抓取的页数,默认1页
|
||||
"""
|
||||
self.logger.info(f"开始从网页获取代理: {url} (共{pages}页)")
|
||||
all_proxies = []
|
||||
|
||||
try:
|
||||
headers = {
|
||||
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
|
||||
}
|
||||
|
||||
# 抓取多页
|
||||
for page in range(1, pages + 1):
|
||||
# 构建带页码的URL
|
||||
if '?' in url:
|
||||
page_url = f"{url}&page={page}"
|
||||
else:
|
||||
page_url = f"{url}?page={page}"
|
||||
|
||||
self.logger.info(f"正在获取第 {page}/{pages} 页: {page_url}")
|
||||
|
||||
try:
|
||||
response = requests.get(page_url, headers=headers, timeout=30)
|
||||
response.encoding = 'utf-8'
|
||||
|
||||
if response.status_code != 200:
|
||||
self.logger.warning(f"第{page}页获取失败,状态码: {response.status_code}")
|
||||
continue
|
||||
|
||||
proxies = self._parse_html(response.text)
|
||||
self.logger.info(f"第{page}页成功获取 {len(proxies)} 个代理")
|
||||
all_proxies.extend(proxies)
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"第{page}页获取失败: {str(e)}")
|
||||
continue
|
||||
|
||||
# 去重(基于IP+端口)
|
||||
seen = set()
|
||||
unique_proxies = []
|
||||
for proxy in all_proxies:
|
||||
key = f"{proxy.ip_address}:{proxy.port}"
|
||||
if key not in seen:
|
||||
seen.add(key)
|
||||
unique_proxies.append(proxy)
|
||||
|
||||
self.logger.info(f"成功获取 {len(unique_proxies)} 个唯一代理(共{len(all_proxies)}个,去重后)")
|
||||
|
||||
# 保存到文件
|
||||
if unique_proxies:
|
||||
self.save_to_file(unique_proxies, output_file)
|
||||
self.logger.info(f"代理已保存到: {output_file}")
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"获取网页代理失败: {str(e)}")
|
||||
|
||||
return unique_proxies
|
||||
|
||||
def _parse_html(self, html: str) -> List[ProxyInfo]:
|
||||
"""解析HTML提取代理信息(基于page.html结构)"""
|
||||
proxies = []
|
||||
soup = BeautifulSoup(html, 'html.parser')
|
||||
|
||||
# 查找表格
|
||||
table = soup.find('table', class_='table')
|
||||
if not table:
|
||||
self.logger.warning("未找到代理表格")
|
||||
return proxies
|
||||
|
||||
# 解析表格行
|
||||
tbody = table.find('tbody')
|
||||
if not tbody:
|
||||
return proxies
|
||||
|
||||
rows = tbody.find_all('tr')
|
||||
for row in rows:
|
||||
try:
|
||||
cells = row.find_all('td')
|
||||
if len(cells) < 12:
|
||||
continue
|
||||
|
||||
# 提取字段(根据page.html结构)
|
||||
ip_address = cells[0].text.strip()
|
||||
port_text = cells[1].text.strip()
|
||||
|
||||
# 用户名和密码隐藏在img的data-text属性中
|
||||
username_img = cells[2].find('img')
|
||||
username = username_img.get('data-text', 'no need') if username_img else 'no need'
|
||||
|
||||
password_img = cells[3].find('img')
|
||||
password = password_img.get('data-text', 'no need') if password_img else 'no need'
|
||||
|
||||
# 国家
|
||||
country_link = cells[4].find('a')
|
||||
country = country_link.get('title', '') if country_link else ''
|
||||
|
||||
# 协议
|
||||
protocol_text = cells[5].text.strip().lower()
|
||||
|
||||
# 匿名级别
|
||||
anonymity = cells[6].text.strip()
|
||||
|
||||
# 速度
|
||||
speed = cells[7].text.strip()
|
||||
|
||||
# 运行时间百分比
|
||||
uptime = cells[8].text.strip()
|
||||
|
||||
# 响应时间
|
||||
response_time = cells[9].text.strip()
|
||||
|
||||
# 延迟
|
||||
latency = cells[10].text.strip()
|
||||
|
||||
# 更新时间
|
||||
last_updated = cells[11].text.strip()
|
||||
|
||||
# 验证必要字段
|
||||
if not ip_address or not port_text:
|
||||
continue
|
||||
|
||||
# 转换端口为整数
|
||||
try:
|
||||
port = int(port_text)
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
# 映射协议
|
||||
protocol_map = {
|
||||
'http': ProxyProtocol.HTTP,
|
||||
'https': ProxyProtocol.HTTPS,
|
||||
'socks4': ProxyProtocol.SOCKS4,
|
||||
'socks5': ProxyProtocol.SOCKS5
|
||||
}
|
||||
protocol = protocol_map.get(protocol_text, ProxyProtocol.SOCKS5)
|
||||
|
||||
proxy = ProxyInfo(
|
||||
ip_address=ip_address,
|
||||
port=port,
|
||||
username=username,
|
||||
password=password,
|
||||
protocol=protocol,
|
||||
country=country,
|
||||
anonymity=anonymity,
|
||||
speed=speed,
|
||||
uptime_percentage=uptime,
|
||||
response_time=response_time,
|
||||
latency=latency,
|
||||
last_updated=last_updated
|
||||
)
|
||||
proxies.append(proxy)
|
||||
|
||||
except Exception as e:
|
||||
self.logger.debug(f"解析代理行失败: {str(e)}")
|
||||
continue
|
||||
|
||||
return proxies
|
||||
|
||||
def load_from_file(self, filepath: str) -> List[ProxyInfo]:
|
||||
"""从本地文件加载代理列表"""
|
||||
self.logger.info(f"从本地文件加载代理: {filepath}")
|
||||
proxies = []
|
||||
|
||||
if not os.path.exists(filepath):
|
||||
self.logger.warning(f"文件不存在: {filepath}")
|
||||
return proxies
|
||||
|
||||
try:
|
||||
with open(filepath, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
|
||||
if isinstance(data, list):
|
||||
for item in data:
|
||||
try:
|
||||
proxy = ProxyInfo.from_dict(item)
|
||||
proxies.append(proxy)
|
||||
except Exception as e:
|
||||
self.logger.debug(f"解析代理项失败: {str(e)}")
|
||||
continue
|
||||
|
||||
self.logger.info(f"成功加载 {len(proxies)} 个代理")
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"加载本地文件失败: {str(e)}")
|
||||
|
||||
return proxies
|
||||
|
||||
def save_to_file(self, proxies: List[ProxyInfo], filepath: str):
|
||||
"""保存代理列表到文件"""
|
||||
try:
|
||||
data = [proxy.to_dict() for proxy in proxies]
|
||||
with open(filepath, 'w', encoding='utf-8') as f:
|
||||
json.dump(data, f, indent=2, ensure_ascii=False)
|
||||
self.logger.info(f"保存 {len(proxies)} 个代理到文件: {filepath}")
|
||||
except Exception as e:
|
||||
self.logger.error(f"保存文件失败: {str(e)}")
|
||||
@@ -0,0 +1,192 @@
|
||||
"""代理健康检测模块"""
|
||||
import socket
|
||||
import requests
|
||||
import threading
|
||||
import time
|
||||
from typing import List, Callable, Optional
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from datetime import datetime, timedelta
|
||||
from loguru import logger
|
||||
from .models import ProxyInfo, ProxyStatus
|
||||
|
||||
|
||||
class HealthChecker:
|
||||
"""代理健康检测器"""
|
||||
|
||||
def __init__(self, config: dict):
|
||||
self.config = config
|
||||
self.logger = logger
|
||||
self.health_config = config.get('health_check', {})
|
||||
|
||||
self.timeout = self.health_config.get('timeout', 5)
|
||||
self.connectivity_url = self.health_config.get('connectivity_test_url', 'https://www.google.com/')
|
||||
self.connectivity_timeout = self.health_config.get('connectivity_timeout', 10)
|
||||
self.max_failures = self.health_config.get('max_failures', 3)
|
||||
self.retry_delay = self.health_config.get('retry_delay', 600)
|
||||
|
||||
self._check_lock = threading.Lock()
|
||||
self._executor = ThreadPoolExecutor(max_workers=10)
|
||||
|
||||
def check_proxy(self, proxy: ProxyInfo) -> ProxyStatus:
|
||||
"""检测单个代理的健康状态"""
|
||||
with self._check_lock:
|
||||
proxy.status = ProxyStatus.CHECKING
|
||||
proxy.last_check = datetime.now()
|
||||
|
||||
try:
|
||||
# 步骤1: TCP连接测试(快速检查)
|
||||
start_time = time.time()
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.settimeout(self.timeout)
|
||||
|
||||
result = sock.connect_ex((proxy.ip_address, proxy.port))
|
||||
tcp_elapsed = (time.time() - start_time) * 1000 # 转换为毫秒
|
||||
|
||||
sock.close()
|
||||
|
||||
if result != 0:
|
||||
raise ConnectionError(f"无法连接到 {proxy.get_address()}")
|
||||
|
||||
proxy.latency_ms = tcp_elapsed
|
||||
|
||||
# 步骤2: 测试Google连通性
|
||||
if not self._test_connectivity(proxy):
|
||||
raise ConnectionError("Google连通性测试失败")
|
||||
|
||||
# 步骤3: 连通性成功后,再次测试真实延迟
|
||||
start_time = time.time()
|
||||
sock2 = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock2.settimeout(self.timeout)
|
||||
|
||||
result2 = sock2.connect_ex((proxy.ip_address, proxy.port))
|
||||
real_elapsed = (time.time() - start_time) * 1000 # 转换为毫秒
|
||||
|
||||
sock2.close()
|
||||
|
||||
if result2 == 0:
|
||||
# 使用第二次测试的真实延迟
|
||||
proxy.latency_ms = real_elapsed
|
||||
|
||||
# 判断等级(基于真实延迟)
|
||||
if real_elapsed < 200:
|
||||
proxy.status = ProxyStatus.EXCELLENT
|
||||
else:
|
||||
proxy.status = ProxyStatus.AVAILABLE
|
||||
proxy.consecutive_failures = 0
|
||||
|
||||
except Exception as e:
|
||||
proxy.consecutive_failures += 1
|
||||
proxy.latency_ms = 9999
|
||||
proxy.status = ProxyStatus.UNAVAILABLE
|
||||
|
||||
self.logger.debug(f"代理 {proxy.get_address()} 检测失败: {str(e)}")
|
||||
|
||||
return proxy.status
|
||||
|
||||
def _test_connectivity(self, proxy: ProxyInfo) -> bool:
|
||||
"""测试代理的Google连通性
|
||||
|
||||
使用多种方法测试,提高准确性:
|
||||
1. 首先尝试 HEAD 请求(类似 curl -I)
|
||||
2. 如果失败,尝试 GET 请求
|
||||
3. 支持多个测试URL
|
||||
"""
|
||||
test_urls = [
|
||||
'https://www.google.com/',
|
||||
'https://www.google.com/generate_204', # 专门用于连通性测试
|
||||
'http://www.google.com/',
|
||||
]
|
||||
|
||||
for test_url in test_urls:
|
||||
try:
|
||||
proxies_dict = {}
|
||||
protocol = proxy.protocol.value
|
||||
|
||||
# 构建代理配置
|
||||
if protocol in ['http', 'https']:
|
||||
auth = proxy.get_auth_string()
|
||||
if auth:
|
||||
proxies_dict['http'] = f"http://{auth}@{proxy.get_address()}"
|
||||
proxies_dict['https'] = f"http://{auth}@{proxy.get_address()}"
|
||||
else:
|
||||
proxies_dict['http'] = f"http://{proxy.get_address()}"
|
||||
proxies_dict['https'] = f"http://{proxy.get_address()}"
|
||||
elif protocol in ['socks4', 'socks5']:
|
||||
auth = proxy.get_auth_string()
|
||||
proxy_url = f"socks5://{auth}@{proxy.get_address()}" if auth else f"socks5://{proxy.get_address()}"
|
||||
proxies_dict['http'] = proxy_url
|
||||
proxies_dict['https'] = proxy_url
|
||||
|
||||
# 方法1: 尝试 HEAD 请求(轻量,类似 curl -I)
|
||||
try:
|
||||
response = requests.head(
|
||||
test_url,
|
||||
proxies=proxies_dict,
|
||||
timeout=self.connectivity_timeout,
|
||||
verify=False,
|
||||
allow_redirects=True
|
||||
)
|
||||
# HEAD 请求成功即可
|
||||
if response.status_code < 400:
|
||||
self.logger.debug(f"代理 {proxy.get_address()} HEAD测试成功: {test_url} ({response.status_code})")
|
||||
return True
|
||||
except Exception as e:
|
||||
self.logger.debug(f"HEAD测试失败: {str(e)}")
|
||||
|
||||
# 方法2: 如果 HEAD 失败,尝试 GET 请求
|
||||
try:
|
||||
response = requests.get(
|
||||
test_url,
|
||||
proxies=proxies_dict,
|
||||
timeout=self.connectivity_timeout,
|
||||
verify=False,
|
||||
allow_redirects=True
|
||||
)
|
||||
# GET 请求成功
|
||||
if response.status_code < 400:
|
||||
self.logger.debug(f"代理 {proxy.get_address()} GET测试成功: {test_url} ({response.status_code})")
|
||||
return True
|
||||
except Exception as e:
|
||||
self.logger.debug(f"GET测试失败: {str(e)}")
|
||||
continue
|
||||
|
||||
except Exception as e:
|
||||
self.logger.debug(f"测试URL {test_url} 失败: {str(e)}")
|
||||
continue
|
||||
|
||||
# 所有测试都失败
|
||||
self.logger.debug(f"代理 {proxy.get_address()} 所有连通性测试均失败")
|
||||
return False
|
||||
|
||||
def batch_check(self, proxies: List[ProxyInfo], callback: Callable = None) -> List[ProxyInfo]:
|
||||
"""批量检测代理"""
|
||||
self.logger.info(f"开始批量检测 {len(proxies)} 个代理")
|
||||
|
||||
futures = {}
|
||||
for proxy in proxies:
|
||||
# 跳过最近检测过的代理(缓存60秒)
|
||||
if proxy.last_check and (datetime.now() - proxy.last_check) < timedelta(seconds=60):
|
||||
continue
|
||||
|
||||
future = self._executor.submit(self.check_proxy, proxy)
|
||||
futures[future] = proxy
|
||||
|
||||
checked_proxies = []
|
||||
for future in as_completed(futures):
|
||||
proxy = futures[future]
|
||||
try:
|
||||
future.result()
|
||||
checked_proxies.append(proxy)
|
||||
|
||||
if callback:
|
||||
callback(proxy)
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"检测代理 {proxy.get_address()} 时出错: {str(e)}")
|
||||
|
||||
self.logger.info(f"完成检测,共检测 {len(checked_proxies)} 个代理")
|
||||
return checked_proxies
|
||||
|
||||
def shutdown(self):
|
||||
"""关闭检测器"""
|
||||
self._executor.shutdown(wait=False)
|
||||
@@ -0,0 +1,98 @@
|
||||
"""数据模型定义"""
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Optional
|
||||
from enum import Enum
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class ProxyProtocol(Enum):
|
||||
"""代理协议枚举"""
|
||||
HTTP = "http"
|
||||
HTTPS = "https"
|
||||
SOCKS4 = "socks4"
|
||||
SOCKS5 = "socks5"
|
||||
|
||||
|
||||
class ProxyStatus(Enum):
|
||||
"""代理状态枚举"""
|
||||
UNKNOWN = "unknown"
|
||||
CHECKING = "checking"
|
||||
AVAILABLE = "available"
|
||||
EXCELLENT = "excellent"
|
||||
UNAVAILABLE = "unavailable"
|
||||
|
||||
|
||||
@dataclass
|
||||
class ProxyInfo:
|
||||
"""代理信息数据类"""
|
||||
ip_address: str
|
||||
port: int
|
||||
username: str = "no need"
|
||||
password: str = "no need"
|
||||
protocol: ProxyProtocol = ProxyProtocol.SOCKS5
|
||||
country: str = ""
|
||||
anonymity: str = ""
|
||||
speed: str = ""
|
||||
uptime_percentage: str = ""
|
||||
response_time: str = ""
|
||||
latency: str = ""
|
||||
last_updated: str = ""
|
||||
|
||||
# 运行时状态
|
||||
status: ProxyStatus = ProxyStatus.UNKNOWN
|
||||
latency_ms: float = 0.0
|
||||
last_check: Optional[datetime] = None
|
||||
consecutive_failures: int = 0
|
||||
is_active: bool = False
|
||||
|
||||
def to_dict(self) -> dict:
|
||||
"""转换为字典"""
|
||||
return {
|
||||
'ip_address': self.ip_address,
|
||||
'port': self.port,
|
||||
'username': self.username,
|
||||
'password': self.password,
|
||||
'protocol': self.protocol.value,
|
||||
'country': self.country,
|
||||
'anonymity': self.anonymity,
|
||||
'speed': self.speed,
|
||||
'uptime_percentage': self.uptime_percentage,
|
||||
'response_time': self.response_time,
|
||||
'latency': self.latency,
|
||||
'last_updated': self.last_updated
|
||||
}
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, data: dict) -> 'ProxyInfo':
|
||||
"""从字典创建"""
|
||||
protocol_map = {
|
||||
'http': ProxyProtocol.HTTP,
|
||||
'https': ProxyProtocol.HTTPS,
|
||||
'socks4': ProxyProtocol.SOCKS4,
|
||||
'socks5': ProxyProtocol.SOCKS5
|
||||
}
|
||||
|
||||
return cls(
|
||||
ip_address=data['ip_address'],
|
||||
port=int(data['port']),
|
||||
username=data.get('username', 'no need'),
|
||||
password=data.get('password', 'no need'),
|
||||
protocol=protocol_map.get(data.get('protocol', 'socks5'), ProxyProtocol.SOCKS5),
|
||||
country=data.get('country', ''),
|
||||
anonymity=data.get('anonymity', ''),
|
||||
speed=data.get('speed', ''),
|
||||
uptime_percentage=data.get('uptime_percentage', ''),
|
||||
response_time=data.get('response_time', ''),
|
||||
latency=data.get('latency', ''),
|
||||
last_updated=data.get('last_updated', '')
|
||||
)
|
||||
|
||||
def get_address(self) -> str:
|
||||
"""获取代理地址字符串"""
|
||||
return f"{self.ip_address}:{self.port}"
|
||||
|
||||
def get_auth_string(self) -> Optional[str]:
|
||||
"""获取认证字符串"""
|
||||
if self.username and self.username != "no need":
|
||||
return f"{self.username}:{self.password}"
|
||||
return None
|
||||
@@ -0,0 +1,266 @@
|
||||
"""代理管理器 - 协调数据源、检测器和转发器"""
|
||||
import threading
|
||||
import time
|
||||
import json
|
||||
import os
|
||||
from typing import List, Optional
|
||||
from datetime import datetime
|
||||
from loguru import logger
|
||||
from .models import ProxyInfo, ProxyStatus
|
||||
from .data_source import DataSource
|
||||
from .health_checker import HealthChecker
|
||||
from .simple_proxy_forwarder import SimpleProxyForwarder
|
||||
|
||||
|
||||
class ProxyManager:
|
||||
"""代理管理器"""
|
||||
|
||||
def __init__(self, config: dict, connection_log_callback=None):
|
||||
self.config = config
|
||||
self.logger = logger
|
||||
|
||||
self.data_source = DataSource(config)
|
||||
self.health_checker = HealthChecker(config)
|
||||
self.forwarder = SimpleProxyForwarder(config, connection_log_callback)
|
||||
|
||||
self.proxies: List[ProxyInfo] = []
|
||||
self.active_proxy: Optional[ProxyInfo] = None
|
||||
self.available_proxies: List[ProxyInfo] = []
|
||||
|
||||
self._lock = threading.RLock()
|
||||
self._running = False
|
||||
self._refresh_thread = None
|
||||
|
||||
def load_proxies(self) -> int:
|
||||
"""加载代理列表"""
|
||||
with self._lock:
|
||||
all_proxies = []
|
||||
|
||||
# 从网页获取(保存到 proxy.json)
|
||||
if self.config.get('proxy_sources', {}).get('auto_fetch', {}).get('enabled', True):
|
||||
url = self.config['proxy_sources']['auto_fetch'].get('url')
|
||||
output_file = self.config['proxy_sources']['auto_fetch'].get('output_file', 'proxy.json')
|
||||
pages = self.config['proxy_sources']['auto_fetch'].get('pages', 1) # 获取页数配置
|
||||
if url:
|
||||
web_proxies = self.data_source.fetch_from_web(url, output_file, pages)
|
||||
all_proxies.extend(web_proxies)
|
||||
|
||||
# 从本地文件加载(用户手动添加的 local.json)
|
||||
if self.config.get('proxy_sources', {}).get('local_file', {}).get('enabled', True):
|
||||
filepath = self.config['proxy_sources']['local_file'].get('path', 'local.json')
|
||||
file_proxies = self.data_source.load_from_file(filepath)
|
||||
all_proxies.extend(file_proxies)
|
||||
|
||||
# 去重(基于IP+端口)
|
||||
seen = set()
|
||||
unique_proxies = []
|
||||
for proxy in all_proxies:
|
||||
key = f"{proxy.ip_address}:{proxy.port}"
|
||||
if key not in seen:
|
||||
seen.add(key)
|
||||
unique_proxies.append(proxy)
|
||||
|
||||
self.proxies = unique_proxies
|
||||
self.logger.info(f"加载了 {len(self.proxies)} 个唯一代理")
|
||||
|
||||
return len(self.proxies)
|
||||
|
||||
def set_proxies(self, proxies: List[ProxyInfo]):
|
||||
"""设置代理列表(用于GUI选择单个代理)"""
|
||||
with self._lock:
|
||||
self.proxies = proxies
|
||||
self.logger.info(f"设置代理列表: {len(proxies)} 个代理")
|
||||
|
||||
def check_all_proxies(self) -> int:
|
||||
"""检测所有代理"""
|
||||
with self._lock:
|
||||
available_count = 0
|
||||
|
||||
def on_check_complete(proxy: ProxyInfo):
|
||||
nonlocal available_count
|
||||
if proxy.status in [ProxyStatus.AVAILABLE, ProxyStatus.EXCELLENT]:
|
||||
available_count += 1
|
||||
|
||||
self.health_checker.batch_check(self.proxies, callback=on_check_complete)
|
||||
|
||||
# 更新可用代理列表
|
||||
self.available_proxies = [
|
||||
p for p in self.proxies
|
||||
if p.status in [ProxyStatus.AVAILABLE, ProxyStatus.EXCELLENT]
|
||||
]
|
||||
|
||||
# 同步延迟到本地文件
|
||||
self._sync_latency_to_file()
|
||||
|
||||
self.logger.info(f"检测到 {available_count} 个可用代理")
|
||||
return available_count
|
||||
|
||||
def _sync_latency_to_file(self):
|
||||
"""将检测结果(延迟)同步到本地文件
|
||||
|
||||
同时同步到:
|
||||
1. proxy.json(网页抓取的代理)
|
||||
2. local.json(用户手动添加的代理)
|
||||
"""
|
||||
try:
|
||||
# 同步到 proxy.json
|
||||
self._sync_to_single_file(
|
||||
self.config.get('proxy_sources', {}).get('auto_fetch', {}).get('output_file', 'proxy.json')
|
||||
)
|
||||
|
||||
# 同步到 local.json
|
||||
local_file_path = self.config.get('proxy_sources', {}).get('local_file', {}).get('path', 'local.json')
|
||||
if local_file_path and local_file_path != 'proxy.json':
|
||||
self._sync_to_single_file(local_file_path)
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"同步延迟到文件失败: {str(e)}")
|
||||
|
||||
def _sync_to_single_file(self, filepath: str):
|
||||
"""同步延迟到单个文件"""
|
||||
try:
|
||||
if not os.path.exists(filepath):
|
||||
return
|
||||
|
||||
# 读取现有文件
|
||||
with open(filepath, 'r', encoding='utf-8') as f:
|
||||
data = json.load(f)
|
||||
|
||||
if not isinstance(data, list):
|
||||
return
|
||||
|
||||
# 创建索引
|
||||
existing_proxies = {}
|
||||
for item in data:
|
||||
key = f"{item['ip_address']}:{item['port']}"
|
||||
existing_proxies[key] = item
|
||||
|
||||
# 更新延迟信息
|
||||
updated_count = 0
|
||||
for proxy in self.proxies:
|
||||
key = proxy.get_address()
|
||||
if key in existing_proxies:
|
||||
# 更新延迟和状态
|
||||
existing_proxies[key]['latency'] = f"{proxy.latency_ms:.0f}ms" if proxy.latency_ms < 9999 else "timeout"
|
||||
existing_proxies[key]['status'] = proxy.status.value
|
||||
existing_proxies[key]['last_checked'] = datetime.now().isoformat()
|
||||
updated_count += 1
|
||||
|
||||
# 保存更新后的数据
|
||||
if updated_count > 0:
|
||||
updated_data = list(existing_proxies.values())
|
||||
with open(filepath, 'w', encoding='utf-8') as f:
|
||||
json.dump(updated_data, f, indent=2, ensure_ascii=False)
|
||||
self.logger.info(f"已同步 {updated_count} 个代理的延迟信息到 {filepath}")
|
||||
|
||||
except Exception as e:
|
||||
self.logger.debug(f"同步到 {filepath} 失败: {str(e)}")
|
||||
|
||||
def start_service(self) -> bool:
|
||||
"""启动代理服务"""
|
||||
if self._running:
|
||||
self.logger.warning("服务已在运行")
|
||||
return True
|
||||
|
||||
try:
|
||||
# 加载代理
|
||||
self.load_proxies()
|
||||
|
||||
# 检测代理
|
||||
self.check_all_proxies()
|
||||
|
||||
if not self.available_proxies:
|
||||
self.logger.error("没有可用的代理,无法启动服务")
|
||||
return False
|
||||
|
||||
# 启动转发器
|
||||
self.forwarder.start(self.available_proxies)
|
||||
|
||||
self._running = True
|
||||
self.active_proxy = self.forwarder.current_proxy
|
||||
|
||||
self.logger.info("代理服务已启动")
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"启动服务失败: {str(e)}")
|
||||
return False
|
||||
|
||||
def stop_service(self):
|
||||
"""停止代理服务"""
|
||||
if not self._running:
|
||||
return
|
||||
|
||||
self._running = False
|
||||
self.forwarder.stop()
|
||||
self.health_checker.shutdown()
|
||||
|
||||
self.logger.info("代理服务已停止")
|
||||
|
||||
def switch_to_next_proxy(self) -> bool:
|
||||
"""切换到下一个代理"""
|
||||
if not self._running:
|
||||
self.logger.warning("服务未运行")
|
||||
return False
|
||||
|
||||
if not self.available_proxies:
|
||||
self.logger.warning("没有可用代理")
|
||||
return False
|
||||
|
||||
# 找到当前代理的索引
|
||||
current_index = -1
|
||||
if self.active_proxy and self.active_proxy in self.available_proxies:
|
||||
current_index = self.available_proxies.index(self.active_proxy)
|
||||
|
||||
# 选择下一个代理
|
||||
next_index = (current_index + 1) % len(self.available_proxies)
|
||||
next_proxy = self.available_proxies[next_index]
|
||||
|
||||
# 切换代理
|
||||
success = self.forwarder.switch_proxy(next_proxy)
|
||||
if success:
|
||||
self.active_proxy = next_proxy
|
||||
self.logger.info(f"成功切换到下一个代理: {next_proxy.get_address()}")
|
||||
|
||||
return success
|
||||
|
||||
def get_active_proxy(self) -> Optional[ProxyInfo]:
|
||||
"""获取当前活跃代理"""
|
||||
with self._lock:
|
||||
return self.active_proxy
|
||||
|
||||
def get_statistics(self) -> dict:
|
||||
"""获取统计信息"""
|
||||
with self._lock:
|
||||
stats = {
|
||||
'total': len(self.proxies),
|
||||
'available': len([p for p in self.proxies if p.status == ProxyStatus.AVAILABLE]),
|
||||
'excellent': len([p for p in self.proxies if p.status == ProxyStatus.EXCELLENT]),
|
||||
'unavailable': len([p for p in self.proxies if p.status == ProxyStatus.UNAVAILABLE]),
|
||||
'active': self.active_proxy.get_address() if self.active_proxy else None
|
||||
}
|
||||
return stats
|
||||
|
||||
def start_auto_refresh(self, interval_minutes: int = 10):
|
||||
"""启动自动刷新"""
|
||||
if self._running:
|
||||
return
|
||||
|
||||
self._running = True
|
||||
|
||||
def refresh_loop():
|
||||
while self._running:
|
||||
time.sleep(interval_minutes * 60)
|
||||
if self._running:
|
||||
self.logger.info("执行自动刷新...")
|
||||
self.load_proxies()
|
||||
self.check_all_proxies()
|
||||
|
||||
self._refresh_thread = threading.Thread(target=refresh_loop, daemon=True)
|
||||
self._refresh_thread.start()
|
||||
|
||||
def stop_auto_refresh(self):
|
||||
"""停止自动刷新"""
|
||||
self._running = False
|
||||
if self._refresh_thread:
|
||||
self._refresh_thread.join(timeout=5)
|
||||
@@ -0,0 +1,385 @@
|
||||
"""简化代理转发器 - 三步工作流程"""
|
||||
import socket
|
||||
import threading
|
||||
import socks
|
||||
import time
|
||||
from typing import List, Optional
|
||||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||||
from loguru import logger
|
||||
from .models import ProxyInfo, ProxyStatus
|
||||
|
||||
|
||||
class SimpleProxyForwarder:
|
||||
"""简化代理转发器
|
||||
|
||||
工作流程:
|
||||
1. 验证代理 (_validate_proxies)
|
||||
2. 获取可用代理 (_test_proxy)
|
||||
3. 转发到8745端口 (_run_forwarder)
|
||||
"""
|
||||
|
||||
def __init__(self, config: dict, connection_log_callback=None):
|
||||
self.config = config
|
||||
self.logger = logger
|
||||
|
||||
output_config = config.get('output', {})
|
||||
self.host = output_config.get('host', '127.0.0.1')
|
||||
self.port = output_config.get('port', 8745)
|
||||
|
||||
self.validated_proxies: List[ProxyInfo] = []
|
||||
self.current_proxy: Optional[ProxyInfo] = None
|
||||
self.server_socket: Optional[socket.socket] = None
|
||||
self._running = False
|
||||
self._server_thread: Optional[threading.Thread] = None
|
||||
self._connections = []
|
||||
self._lock = threading.Lock()
|
||||
self._executor = ThreadPoolExecutor(max_workers=10)
|
||||
|
||||
# 连接日志回调函数
|
||||
self.connection_log_callback = connection_log_callback
|
||||
|
||||
def validate_proxies(self, proxies: List[ProxyInfo]) -> List[ProxyInfo]:
|
||||
"""步骤1: 验证所有代理的连通性"""
|
||||
self.logger.info(f"开始验证 {len(proxies)} 个代理")
|
||||
self.validated_proxies = []
|
||||
|
||||
futures = {}
|
||||
for proxy in proxies:
|
||||
future = self._executor.submit(self._validate_single_proxy, proxy)
|
||||
futures[future] = proxy
|
||||
|
||||
for future in as_completed(futures):
|
||||
proxy = futures[future]
|
||||
try:
|
||||
is_valid = future.result()
|
||||
if is_valid:
|
||||
self.validated_proxies.append(proxy)
|
||||
proxy.status = ProxyStatus.AVAILABLE
|
||||
except Exception as e:
|
||||
self.logger.debug(f"验证代理 {proxy.get_address()} 失败: {str(e)}")
|
||||
|
||||
self.logger.info(f"验证完成,{len(self.validated_proxies)} 个代理可用")
|
||||
return self.validated_proxies
|
||||
|
||||
def _validate_single_proxy(self, proxy: ProxyInfo) -> bool:
|
||||
"""验证单个代理"""
|
||||
try:
|
||||
# TCP连接测试
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
sock.settimeout(5)
|
||||
|
||||
result = sock.connect_ex((proxy.ip_address, proxy.port))
|
||||
sock.close()
|
||||
|
||||
if result != 0:
|
||||
return False
|
||||
|
||||
# SOCKS握手验证(针对SOCKS代理)
|
||||
if proxy.protocol.value in ['socks4', 'socks5']:
|
||||
return self._test_socks_handshake(proxy)
|
||||
|
||||
return True
|
||||
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def _test_socks_handshake(self, proxy: ProxyInfo) -> bool:
|
||||
"""测试SOCKS握手"""
|
||||
try:
|
||||
proxy_type = socks.SOCKS5 if proxy.protocol.value == 'socks5' else socks.SOCKS4
|
||||
|
||||
test_sock = socks.socksocket()
|
||||
test_sock.set_proxy(
|
||||
proxy_type,
|
||||
proxy.ip_address,
|
||||
proxy.port,
|
||||
username=proxy.username if proxy.username != "no need" else None,
|
||||
password=proxy.password if proxy.password != "no need" else None
|
||||
)
|
||||
test_sock.settimeout(5)
|
||||
|
||||
# 尝试连接到测试服务器
|
||||
test_sock.connect(('www.google.com', 80))
|
||||
test_sock.close()
|
||||
|
||||
return True
|
||||
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
def get_available_proxy(self) -> Optional[ProxyInfo]:
|
||||
"""步骤2: 获取可用的代理"""
|
||||
if not self.validated_proxies:
|
||||
return None
|
||||
|
||||
# 选择第一个可用代理(可以扩展为负载均衡策略)
|
||||
return self.validated_proxies[0]
|
||||
|
||||
def start(self, proxies: List[ProxyInfo]):
|
||||
"""启动转发器"""
|
||||
if self._running:
|
||||
self.logger.warning("转发器已在运行")
|
||||
return
|
||||
|
||||
# 步骤1: 验证代理
|
||||
self.validate_proxies(proxies)
|
||||
|
||||
if not self.validated_proxies:
|
||||
self.logger.error("没有可用的代理")
|
||||
return
|
||||
|
||||
# 步骤2: 获取代理
|
||||
self.current_proxy = self.get_available_proxy()
|
||||
if not self.current_proxy:
|
||||
self.logger.error("无法获取可用代理")
|
||||
return
|
||||
|
||||
self.logger.info(f"使用代理: {self.current_proxy.get_address()} ({self.current_proxy.protocol.value})")
|
||||
|
||||
# 步骤3: 启动转发器
|
||||
self._run_forwarder()
|
||||
|
||||
def _run_forwarder(self):
|
||||
"""步骤3: 运行SOCKS5转发服务器"""
|
||||
try:
|
||||
self.server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
self.server_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
self.server_socket.bind((self.host, self.port))
|
||||
self.server_socket.listen(100)
|
||||
self.server_socket.settimeout(1.0)
|
||||
|
||||
self._running = True
|
||||
self._server_thread = threading.Thread(target=self._accept_loop, daemon=True)
|
||||
self._server_thread.start()
|
||||
|
||||
self.logger.info(f"SOCKS5转发器已启动: {self.host}:{self.port}")
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"启动转发器失败: {str(e)}")
|
||||
raise
|
||||
|
||||
def _accept_loop(self):
|
||||
"""接受客户端连接循环"""
|
||||
while self._running:
|
||||
try:
|
||||
client_socket, client_address = self.server_socket.accept()
|
||||
|
||||
# 为新连接创建处理线程
|
||||
handler = ForwarderConnectionHandler(
|
||||
client_socket,
|
||||
client_address,
|
||||
self.current_proxy,
|
||||
self.logger,
|
||||
self.connection_log_callback # 传递日志回调
|
||||
)
|
||||
handler.start()
|
||||
|
||||
with self._lock:
|
||||
self._connections.append(handler)
|
||||
|
||||
except socket.timeout:
|
||||
continue
|
||||
except Exception as e:
|
||||
if self._running:
|
||||
self.logger.error(f"接受连接失败: {str(e)}")
|
||||
break
|
||||
|
||||
def stop(self):
|
||||
"""停止转发器"""
|
||||
self._running = False
|
||||
|
||||
# 关闭所有连接
|
||||
with self._lock:
|
||||
for conn in self._connections:
|
||||
try:
|
||||
conn.running = False
|
||||
conn.join(timeout=2)
|
||||
except:
|
||||
pass
|
||||
self._connections.clear()
|
||||
|
||||
if self.server_socket:
|
||||
try:
|
||||
self.server_socket.close()
|
||||
except:
|
||||
pass
|
||||
|
||||
if self._server_thread:
|
||||
self._server_thread.join(timeout=5)
|
||||
|
||||
self._executor.shutdown(wait=False)
|
||||
|
||||
self.logger.info("转发器已停止")
|
||||
|
||||
def switch_proxy(self, proxy: ProxyInfo) -> bool:
|
||||
"""切换到新代理"""
|
||||
if proxy not in self.validated_proxies:
|
||||
self.logger.warning(f"代理 {proxy.get_address()} 未通过验证")
|
||||
return False
|
||||
|
||||
with self._lock:
|
||||
self.current_proxy = proxy
|
||||
self.logger.info(f"切换到代理: {proxy.get_address()}")
|
||||
return True
|
||||
|
||||
|
||||
class ForwarderConnectionHandler(threading.Thread):
|
||||
"""转发器连接处理器"""
|
||||
|
||||
def __init__(self, client_socket: socket.socket, client_address, upstream_proxy: ProxyInfo, logger, connection_log_callback=None):
|
||||
super().__init__(daemon=True)
|
||||
self.client_socket = client_socket
|
||||
self.client_address = client_address
|
||||
self.upstream_proxy = upstream_proxy
|
||||
self.logger = logger
|
||||
self.running = True
|
||||
self.connection_log_callback = connection_log_callback
|
||||
|
||||
def run(self):
|
||||
"""处理客户端连接"""
|
||||
try:
|
||||
# SOCKS5握手
|
||||
if not self._socks5_handshake():
|
||||
self.logger.debug(f"SOCKS5握手失败: {self.client_address}")
|
||||
return
|
||||
|
||||
# 建立到目标服务器的连接
|
||||
target_socket = self._connect_to_target()
|
||||
if not target_socket:
|
||||
return
|
||||
|
||||
# 记录连接日志
|
||||
if self.connection_log_callback:
|
||||
local_addr = f"{self.client_address[0]}:{self.client_address[1]}"
|
||||
remote_addr = f"{self.upstream_proxy.ip_address}:{self.upstream_proxy.port}"
|
||||
log_message = f"{local_addr} -> {remote_addr}"
|
||||
self.connection_log_callback(log_message)
|
||||
|
||||
# 双向转发数据
|
||||
self._forward_data(target_socket)
|
||||
|
||||
except Exception as e:
|
||||
self.logger.debug(f"处理连接时出错: {str(e)}")
|
||||
finally:
|
||||
try:
|
||||
self.client_socket.close()
|
||||
except:
|
||||
pass
|
||||
self.running = False
|
||||
|
||||
def _socks5_handshake(self) -> bool:
|
||||
"""执行SOCKS5握手"""
|
||||
try:
|
||||
version = self.client_socket.recv(1)
|
||||
if version != b'\x05':
|
||||
return False
|
||||
|
||||
nmethods = ord(self.client_socket.recv(1))
|
||||
methods = self.client_socket.recv(nmethods)
|
||||
|
||||
self.client_socket.send(b'\x05\x00')
|
||||
|
||||
version = self.client_socket.recv(1)
|
||||
if version != b'\x05':
|
||||
return False
|
||||
|
||||
cmd = self.client_socket.recv(1)
|
||||
if cmd != b'\x01':
|
||||
self.client_socket.send(b'\x05\x07\x00\x01\x00\x00\x00\x00\x00\x00')
|
||||
return False
|
||||
|
||||
self.client_socket.recv(1)
|
||||
atype = self.client_socket.recv(1)
|
||||
|
||||
if atype == b'\x01':
|
||||
dest_addr = self.client_socket.recv(4)
|
||||
dest_port = self.client_socket.recv(2)
|
||||
elif atype == b'\x03':
|
||||
addr_len_byte = self.client_socket.recv(1)
|
||||
addr_len = addr_len_byte[0] if isinstance(addr_len_byte, bytes) else ord(addr_len_byte)
|
||||
dest_addr = self.client_socket.recv(addr_len)
|
||||
dest_port = self.client_socket.recv(2)
|
||||
elif atype == b'\x04':
|
||||
dest_addr = self.client_socket.recv(16)
|
||||
dest_port = self.client_socket.recv(2)
|
||||
else:
|
||||
return False
|
||||
|
||||
self.client_socket.send(b'\x05\x00\x00\x01\x00\x00\x00\x00\x00\x00')
|
||||
|
||||
self.dest_addr = dest_addr
|
||||
self.dest_port = dest_port
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
self.logger.debug(f"SOCKS5握手异常: {str(e)}")
|
||||
return False
|
||||
|
||||
def _connect_to_target(self):
|
||||
"""连接到目标服务器"""
|
||||
try:
|
||||
if len(self.dest_addr) == 4:
|
||||
dest_ip = '.'.join(str(b) for b in self.dest_addr)
|
||||
else:
|
||||
dest_ip = self.dest_addr.decode('utf-8', errors='ignore')
|
||||
|
||||
# Python 3中bytes索引直接返回int,不需要ord()
|
||||
if isinstance(self.dest_port, bytes):
|
||||
dest_port = (self.dest_port[0] << 8) + self.dest_port[1]
|
||||
else:
|
||||
dest_port = (ord(self.dest_port[0]) << 8) + ord(self.dest_port[1])
|
||||
|
||||
proxy_type_map = {
|
||||
'socks4': socks.SOCKS4,
|
||||
'socks5': socks.SOCKS5,
|
||||
'http': socks.HTTP,
|
||||
'https': socks.HTTP
|
||||
}
|
||||
|
||||
proxy_type = proxy_type_map.get(self.upstream_proxy.protocol.value, socks.SOCKS5)
|
||||
|
||||
target_socket = socks.socksocket()
|
||||
target_socket.set_proxy(
|
||||
proxy_type,
|
||||
self.upstream_proxy.ip_address,
|
||||
self.upstream_proxy.port,
|
||||
username=self.upstream_proxy.username if self.upstream_proxy.username != "no need" else None,
|
||||
password=self.upstream_proxy.password if self.upstream_proxy.password != "no need" else None
|
||||
)
|
||||
|
||||
target_socket.settimeout(10)
|
||||
target_socket.connect((dest_ip, dest_port))
|
||||
target_socket.settimeout(None)
|
||||
|
||||
return target_socket
|
||||
|
||||
except Exception as e:
|
||||
self.logger.error(f"连接目标失败: {str(e)}")
|
||||
return None
|
||||
|
||||
def _forward_data(self, target_socket):
|
||||
"""双向转发数据"""
|
||||
import select
|
||||
|
||||
sockets = [self.client_socket, target_socket]
|
||||
|
||||
while self.running:
|
||||
try:
|
||||
readable, _, _ = select.select(sockets, [], [], 1.0)
|
||||
|
||||
for sock in readable:
|
||||
if sock == self.client_socket:
|
||||
data = self.client_socket.recv(4096)
|
||||
if not data:
|
||||
return
|
||||
target_socket.sendall(data)
|
||||
elif sock == target_socket:
|
||||
data = target_socket.recv(4096)
|
||||
if not data:
|
||||
return
|
||||
self.client_socket.sendall(data)
|
||||
|
||||
except Exception as e:
|
||||
self.logger.debug(f"转发数据时出错: {str(e)}")
|
||||
break
|
||||
Reference in new issue
Block a user