"""自动代理:一个任务最多向 proxy.scdn.io 领取 8 批中国代理。 每批先要 8 个 SOCKS5,再要 8 个 HTTP,最后要 8 个 HTTPS。按这个顺序检查,第一个能打开学习平台的就用。 学习过程中这个代理失效,再领下一批。8 批都用完任务还没结束,就改走本机网络。 接口的 https 表示这个代理能访问 HTTPS 网站,连接方式仍是 HTTP 转发。 SOCKS4 常因 ident 校验被拒绝,不用。 """ from __future__ import annotations import logging import threading import time import httpx from euniv.client import EUNIV, USER_AGENT from euniv.proxy import ProxyError, assert_public_host, build_proxy_url, shared_tls, sync_httpx_client log = logging.getLogger(__name__) MAX_FETCHES = 8 MAX_SWITCHES = MAX_FETCHES BATCH_SIZE = 8 LATENCY_LIMIT = 3.0 LATENCY_LIMIT_MS = 3000 PROBE_URL = EUNIV + "/" SOURCE_URL = "https://proxy.scdn.io/api/get_proxy.php" # 先试 SOCKS5,再试 HTTP。接口里的 https 仍是 HTTP 代理,用 HTTP CONNECT 打开学习平台。 SOURCE_PROTOCOLS = (("socks5", "socks5"), ("http", "http"), ("https", "http")) _lock = threading.Lock() _holds: dict[str, str] = {} _fetches: dict[str, int] = {} def _elapsed_ms(started: float) -> int: return max(0, int((time.perf_counter() - started) * 1000)) def probe(scheme: str, host: str, port: int) -> tuple[bool, int, str]: url = build_proxy_url(scheme, host, port) samples: list[int] = [] reasons: list[str] = [] try: with sync_httpx_client( url, timeout=LATENCY_LIMIT, follow_redirects=True, headers={"User-Agent": USER_AGENT}, ) as client: started = time.perf_counter() try: response = client.get(PROBE_URL) latency = _elapsed_ms(started) if response.status_code >= 500: samples.append(latency) reasons.append(f"HTTP {response.status_code}") else: samples.append(latency) except Exception as exc: samples.append(_elapsed_ms(started)) reasons.append(_short_reason(exc)) except Exception as exc: return False, 0, _short_reason(exc) average = int(round(sum(samples) / len(samples))) if reasons: return False, average, reasons[0] if average > LATENCY_LIMIT_MS: return False, average, "超时" return True, average, "" def _clip_reason(reason: str, fallback: str = "失效") -> str: text = (reason or "").strip() or fallback if len(text) <= 200: return text log.warning("代理失败原因:%s", text) return text[:200] def _short_reason(exc: BaseException) -> str: from python_socks import ProxyConnectionError, ProxyTimeoutError text = str(exc).strip() or type(exc).__name__ if isinstance(exc, (httpx.ConnectTimeout, httpx.TimeoutException, ProxyTimeoutError)): stored = "超时" elif isinstance(exc, (httpx.ProxyError, httpx.ConnectError, ProxyConnectionError)): stored = "无法连接" else: stored = text if stored != text: log.warning("代理失败原因:%s", text) return stored return _clip_reason(stored) def _parse_endpoint(value: object) -> tuple[str, int] | None: text = str(value or "").strip() if not text or "://" in text or text.count(":") != 1: return None host, raw_port = text.rsplit(":", 1) host = host.strip() try: port = int(raw_port) except ValueError: return None if not host or not 1 <= port <= 65535: return None try: assert_public_host(host) except ProxyError: return None return host, port def _read_proxies(payload: object) -> list[tuple[str, int]]: if not isinstance(payload, dict) or payload.get("code") != 200: return [] data = payload.get("data") proxies = data.get("proxies") if isinstance(data, dict) else None if not isinstance(proxies, list): return [] found: list[tuple[str, int]] = [] for item in proxies: parsed = _parse_endpoint(item) if parsed is None: continue found.append(parsed) if len(found) >= BATCH_SIZE: break return found def _fetch_batch() -> list[tuple[str, str, int]]: """向接口要一批中国代理。顺序是 SOCKS5、HTTP、HTTPS。接口失败时这一批仍然算一次领取。""" found: list[tuple[str, str, int]] = [] seen: set[tuple[str, int]] = set() try: with httpx.Client(timeout=10, trust_env=False, verify=shared_tls()) as client: for protocol, scheme in SOURCE_PROTOCOLS: try: response = client.get( SOURCE_URL, params={"protocol": protocol, "count": BATCH_SIZE, "country_code": "CN"}, ) rows = _read_proxies(response.json()) except Exception: log.warning("代理接口没有获取到 %s", protocol, exc_info=True) continue for host, port in rows: if (host, port) in seen: continue seen.add((host, port)) found.append((scheme, host, port)) except Exception: log.warning("代理接口没有获取到", exc_info=True) return found def force_direct(employee_id: str) -> None: """这个任务不再领代理,之后的访问走本机网络。""" key = (employee_id or "").strip() if not key: return with _lock: _holds.pop(key, None) _fetches[key] = MAX_FETCHES def reset_budget(employee_id: str) -> None: """新的学习任务重新计算 8 次领取。""" key = (employee_id or "").strip() if not key: return with _lock: _holds.pop(key, None) _fetches.pop(key, None) def acquire(employee_id: str) -> str | None: """给这个账号一个已经能打开学习平台的代理。8 批都没有就返回空,调用方改走直连。""" key = (employee_id or "").strip() if not key: return None with _lock: held = _holds.get(key) if held: return held while True: with _lock: used = _fetches.get(key, 0) if used >= MAX_FETCHES: log.info("账号 %s 已领取 %s 批代理,改为直连", key, MAX_FETCHES) return None _fetches[key] = used + 1 # 同批按顺序测,第一个能打开学习平台的立即使用,不再测后面的。 for scheme, host, port in _fetch_batch(): ok, _latency, reason = probe(scheme, host, port) if not ok: log.info("代理 %s:%s 不能访问学习平台:%s", host, port, reason or "失效") continue url = build_proxy_url(scheme, host, port) with _lock: current = _holds.get(key) if current: return current _holds[key] = url return url def release(employee_id: str) -> None: reset_budget(employee_id) def mark_failed(employee_id: str, proxy_url: str | None = None, reason: str = "") -> None: """这个账号正在用的代理已经失败。领取次数保留,下次再领一批。""" del proxy_url, reason key = (employee_id or "").strip() with _lock: _holds.pop(key, None) def retire_if_dead(employee_id: str, proxy_url: str | None, reason: str = "") -> bool: """请求已经失败。放掉当前代理,让下一次重新领取。""" mark_failed(employee_id, proxy_url, reason) return True