Files
EnuivTools/backend/euniv/collectors.py
T

215 lines
6.3 KiB
Python

"""代理上游采集。新增平台时实现 Collector 并 register。"""
from __future__ import annotations
import json
import logging
from concurrent.futures import ThreadPoolExecutor, as_completed
from dataclasses import dataclass
import httpx
from euniv.proxy import SCHEMES
log = logging.getLogger(__name__)
CHINA = {"cn", "chn", "china", "中国"}
_SOURCE_TITLES = {"proxyhub": "ProxyHub"}
@dataclass(frozen=True)
class ProxyCandidate:
scheme: str
host: str
port: int
country: str = ""
anonymity: str = ""
source: str = ""
class Collector:
name = ""
def collect(self) -> list[ProxyCandidate]:
raise NotImplementedError
_REGISTRY: list[Collector] = []
def register(collector: Collector) -> None:
if collector not in _REGISTRY:
_REGISTRY.append(collector)
def collectors() -> list[Collector]:
return list(_REGISTRY)
def source_title(name: str) -> str:
key = (name or "").strip()
return _SOURCE_TITLES.get(key, key or "未知")
def is_china(country: str | None) -> bool:
text = (country or "").strip()
if not text:
return False
lower = text.lower()
return lower in CHINA or "中国" in text
def collect_all() -> list[ProxyCandidate]:
items: list[ProxyCandidate] = []
seen: set[tuple[str, str, int]] = set()
for collector in collectors():
try:
batch = collector.collect()
except Exception:
log.warning("上游 %s 没有获取到", collector.name, exc_info=True)
continue
for item in batch:
if not is_china(item.country):
continue
key = (item.scheme, item.host, item.port)
if key in seen:
continue
seen.add(key)
items.append(item)
return items
def _normalize_scheme(value: object) -> str:
kind = str(value or "").strip().lower()
if kind == "socks":
kind = "socks5"
return kind if kind in SCHEMES else ""
def _normalize_host(value: object) -> str:
host = str(value or "").strip()
if not host or "://" in host or any(ch.isspace() for ch in host):
return ""
return host[:255]
def _normalize_port(value: object) -> int | None:
try:
port = int(value) # type: ignore[arg-type]
except (TypeError, ValueError):
return None
if not 1 <= port <= 65535:
return None
return port
def parse_proxy_rows(rows: object, source: str) -> list[ProxyCandidate]:
if not isinstance(rows, list):
return []
items: list[ProxyCandidate] = []
for row in rows:
if not isinstance(row, dict):
continue
scheme = _normalize_scheme(row.get("type") or row.get("scheme"))
host = _normalize_host(row.get("ip") or row.get("host"))
port = _normalize_port(row.get("port"))
if not scheme or not host or port is None:
continue
items.append(
ProxyCandidate(
scheme=scheme,
host=host,
port=port,
country=str(row.get("country") or "").strip(),
anonymity=str(row.get("anonymity") or "").strip().lower(),
source=source,
)
)
return items
def parse_proxyhub_result(payload: object) -> list[ProxyCandidate]:
if not isinstance(payload, dict):
return []
result = payload.get("result")
if not isinstance(result, dict) or result.get("isError") is True:
return []
data = result.get("structuredContent")
rows = data.get("proxies") if isinstance(data, dict) else None
if isinstance(rows, list):
return parse_proxy_rows(rows, "proxyhub")
content = result.get("content")
if not isinstance(content, list):
return []
for block in content:
if not isinstance(block, dict):
continue
text = block.get("text")
if not isinstance(text, str) or not text.strip():
continue
try:
nested = json.loads(text)
except json.JSONDecodeError:
continue
if isinstance(nested, dict):
return parse_proxy_rows(nested.get("proxies"), "proxyhub")
return []
def _read_mcp(response: httpx.Response) -> dict:
ctype = (response.headers.get("content-type") or "").lower()
if "json" in ctype:
payload = response.json()
return payload if isinstance(payload, dict) else {}
for line in response.text.splitlines():
if line.startswith("data:"):
payload = json.loads(line[5:].strip() or "{}")
return payload if isinstance(payload, dict) else {}
payload = json.loads(response.text or "{}")
return payload if isinstance(payload, dict) else {}
class ProxyHubCollector(Collector):
name = "proxyhub"
url = "https://proxyhub.me/api/mcp"
types = ("http", "https", "socks4", "socks5")
limit = 100
def collect(self) -> list[ProxyCandidate]:
items: list[ProxyCandidate] = []
with ThreadPoolExecutor(max_workers=len(self.types)) as pool:
futures = [pool.submit(self._list, kind) for kind in self.types]
for future in as_completed(futures):
items.extend(future.result())
return items
def _list(self, kind: str) -> list[ProxyCandidate]:
body = {
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "list_proxies",
"arguments": {"country": "cn", "type": kind, "limit": self.limit},
"_meta": {
"io.modelcontextprotocol/protocolVersion": "2026-07-28",
"io.modelcontextprotocol/clientCapabilities": {},
"io.modelcontextprotocol/clientInfo": {"name": "eunivtools", "version": "1.0.0"},
},
},
}
headers = {
"Accept": "application/json, text/event-stream",
"Content-Type": "application/json",
"MCP-Protocol-Version": "2026-07-28",
"Mcp-Method": "tools/call",
"Mcp-Name": "list_proxies",
}
with httpx.Client(timeout=20, follow_redirects=True) as client:
response = client.post(self.url, headers=headers, json=body)
response.raise_for_status()
return parse_proxyhub_result(_read_mcp(response))
register(ProxyHubCollector())