"""代理上游采集。新增平台时实现 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"} MAX_RESPONSE_BYTES = 1_048_576 @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() return text == "中国" or text.lower() in {"cn", "chn", "china"} 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" if kind == "socks5h": kind = "socks5" if kind == "https": kind = "http" 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 "" from euniv.proxy import ProxyError, assert_public_host try: assert_public_host(host) except ProxyError: 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 _json_dict(text: str) -> dict: try: payload = json.loads(text or "{}") except json.JSONDecodeError: return {} return payload if isinstance(payload, dict) else {} def _limited_body(response: httpx.Response) -> bytes: declared = response.headers.get("content-length") if declared and declared.isdigit() and int(declared) > MAX_RESPONSE_BYTES: raise ValueError("上游响应过大") chunks: list[bytes] = [] total = 0 for chunk in response.iter_bytes(): total += len(chunk) if total > MAX_RESPONSE_BYTES: raise ValueError("上游响应过大") chunks.append(chunk) return b"".join(chunks) def _read_mcp(response: httpx.Response) -> dict: text = _limited_body(response).decode("utf-8", errors="replace") ctype = (response.headers.get("content-type") or "").lower() if "json" in ctype and "event-stream" not in ctype: parsed = _json_dict(text) if parsed or text.strip() in {"", "{}"}: return parsed chosen: dict | None = None saw_data = False for line in text.splitlines(): if not line.startswith("data:"): continue saw_data = True raw = line[5:].strip() if not raw: continue try: payload = json.loads(raw) except json.JSONDecodeError: continue if not isinstance(payload, dict): continue if chosen is None or "result" in payload or "error" in payload: chosen = payload if saw_data: return chosen or {} return _json_dict(text) 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): kind for kind in self.types} for future in as_completed(futures): kind = futures[future] try: items.extend(future.result()) except Exception: log.warning("上游 %s 的 %s 没有获取到", self.name, kind, exc_info=True) 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, trust_env=False) as client: with client.stream("POST", self.url, headers=headers, json=body) as response: response.raise_for_status() return parse_proxyhub_result(_read_mcp(response)) register(ProxyHubCollector())